@agentguard-run/burn 0.3.19 → 0.3.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +61 -2
- package/dist/src/canvas.d.ts +7 -1
- package/dist/src/canvas.js +10 -1
- package/dist/src/cli.js +64 -4
- package/dist/src/frames.d.ts +10 -0
- package/dist/src/frames.js +5 -0
- package/dist/src/history/claude-transcript.d.ts +26 -1
- package/dist/src/history/claude-transcript.js +58 -2
- package/dist/src/hook/pre-tool-use.d.ts +5 -1
- package/dist/src/hook/pre-tool-use.js +35 -8
- package/dist/src/insights/calendar-render.d.ts +48 -0
- package/dist/src/insights/calendar-render.js +196 -0
- package/dist/src/insights/calendar.d.ts +138 -0
- package/dist/src/insights/calendar.js +431 -0
- package/dist/src/insights/i18n.d.ts +101 -6
- package/dist/src/insights/i18n.js +120 -7
- package/dist/src/insights/render.d.ts +70 -12
- package/dist/src/insights/render.js +190 -15
- package/dist/src/insights/transcript.d.ts +13 -2
- package/dist/src/insights/transcript.js +61 -6
- package/dist/src/insights/types.d.ts +14 -0
- package/dist/src/recording.js +5 -1
- package/dist/src/replay/render.d.ts +2 -0
- package/dist/src/replay/render.js +4 -0
- package/dist/src/stop-text.d.ts +11 -2
- package/dist/src/stop-text.js +23 -3
- package/dist/src/subagent-cost.d.ts +38 -0
- package/dist/src/subagent-cost.js +65 -0
- package/package.json +1 -1
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.weeksThatFit = exports.cachePath = exports.rollupPath = exports.calendarDirectory = exports.weekdayOf = exports.addDays = exports.dayNumber = exports.CALENDAR_GRID_PREFIX = exports.CALENDAR_MAX_WEEKS = void 0;
|
|
4
|
+
exports.localDay = localDay;
|
|
5
|
+
exports.collectCalendar = collectCalendar;
|
|
6
|
+
exports.calendarLevels = calendarLevels;
|
|
7
|
+
exports.calendarReport = calendarReport;
|
|
8
|
+
/**
|
|
9
|
+
* `calendar`: every local Claude Code and Codex session on one heatmap of
|
|
10
|
+
* measured tokens per local calendar day, sub-agents included. Each response is
|
|
11
|
+
* read with the parser and pricing `why` uses (sessionFigures): its tokens, its
|
|
12
|
+
* API list price and whether a sub-agent recorded it, binned by the local day
|
|
13
|
+
* the response was recorded. Measurement only: nothing here compares with anyone.
|
|
14
|
+
*
|
|
15
|
+
* Retention: Claude Code deletes transcripts after 30 days by default, so Burn
|
|
16
|
+
* keeps a content-free daily count per transcript file in the Burn home
|
|
17
|
+
* (calendar/daily.json: token, sub-agent token and dollar totals per file per
|
|
18
|
+
* day; no paths, no content). A file still on disk is recomputed from its
|
|
19
|
+
* transcript; a file that is gone comes from the daily count; no file-day is
|
|
20
|
+
* taken from both. A per-transcript cache (calendar/cache.json, keyed by path
|
|
21
|
+
* digest, size and modification time) keeps each response's counts, so a second
|
|
22
|
+
* run re-reads only the transcripts that changed.
|
|
23
|
+
*/
|
|
24
|
+
const node_crypto_1 = require("node:crypto");
|
|
25
|
+
const node_fs_1 = require("node:fs");
|
|
26
|
+
const node_path_1 = require("node:path");
|
|
27
|
+
const history_1 = require("./history");
|
|
28
|
+
const pricing_1 = require("./pricing");
|
|
29
|
+
const render_1 = require("./render");
|
|
30
|
+
const sessions_1 = require("./sessions");
|
|
31
|
+
const transcript_1 = require("./transcript");
|
|
32
|
+
const i18n_1 = require("./i18n");
|
|
33
|
+
/** A span of at most 53 weeks: a year of Sundays plus the week in progress. */
|
|
34
|
+
exports.CALENDAR_MAX_WEEKS = 53;
|
|
35
|
+
/**
|
|
36
|
+
* Weekday labels plus one space, in the widest language, so the span a width
|
|
37
|
+
* allows, and so `calendar json`, is the same in every language.
|
|
38
|
+
*/
|
|
39
|
+
exports.CALENDAR_GRID_PREFIX = Math.max(...Object.values(i18n_1.CALENDAR_TEXT).flatMap(text => text.weekdays.map(label => label.length))) + 1;
|
|
40
|
+
/** Transcripts larger than this are parsed in pieces (see InsightReadOptions), which bounds memory on a machine of 400 MB sessions. */
|
|
41
|
+
const CHUNK_BYTES = 16 * 1024 * 1024;
|
|
42
|
+
const CACHE_SCHEMA = 3, ROLLUP_SCHEMA = 1;
|
|
43
|
+
const sha256 = (text) => (0, node_crypto_1.createHash)('sha256').update(text).digest('hex');
|
|
44
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
45
|
+
/** The local calendar day of an instant, YYYY-MM-DD, in this process's time zone. */
|
|
46
|
+
function localDay(at) {
|
|
47
|
+
const date = new Date(at);
|
|
48
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
|
49
|
+
}
|
|
50
|
+
/** Days since the epoch for a YYYY-MM-DD date: date arithmetic without clock time or daylight saving. */
|
|
51
|
+
const dayNumber = (day) => Date.UTC(Number(day.slice(0, 4)), Number(day.slice(5, 7)) - 1, Number(day.slice(8, 10))) / 86_400_000;
|
|
52
|
+
exports.dayNumber = dayNumber;
|
|
53
|
+
const dayText = (n) => new Date(n * 86_400_000).toISOString().slice(0, 10);
|
|
54
|
+
const addDays = (day, days) => dayText((0, exports.dayNumber)(day) + days);
|
|
55
|
+
exports.addDays = addDays;
|
|
56
|
+
/** 0 is Sunday. */
|
|
57
|
+
const weekdayOf = (day) => new Date((0, exports.dayNumber)(day) * 86_400_000).getUTCDay();
|
|
58
|
+
exports.weekdayOf = weekdayOf;
|
|
59
|
+
function transcriptUnits(locations) {
|
|
60
|
+
const units = [];
|
|
61
|
+
for (const location of locations) {
|
|
62
|
+
const child = location.host === 'claude' && (0, node_path_1.basename)((0, node_path_1.dirname)(location.path)) === 'subagents';
|
|
63
|
+
if (location.host === 'claude' && !child && (0, sessions_1.isSessionSidecar)(location))
|
|
64
|
+
continue;
|
|
65
|
+
let info;
|
|
66
|
+
try {
|
|
67
|
+
info = (0, node_fs_1.statSync)(location.path);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (!info.isFile())
|
|
73
|
+
continue;
|
|
74
|
+
units.push({ host: location.host, path: location.path, size: info.size, mtimeMs: info.mtimeMs,
|
|
75
|
+
key: child ? `${(0, node_path_1.basename)((0, node_path_1.dirname)((0, node_path_1.dirname)(location.path)))}/${location.sessionId}` : location.sessionId });
|
|
76
|
+
}
|
|
77
|
+
return units.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
78
|
+
}
|
|
79
|
+
/** Parser ids are SHA-256 digests; 64 bits of one tell a machine's responses apart. */
|
|
80
|
+
const turnKey = (id) => /^[0-9a-f]{64}$/.test(id) ? id.slice(0, 16) : sha256(id).slice(0, 16);
|
|
81
|
+
const rowTokens = (row) => row[5] + row[6] + row[7] + row[8];
|
|
82
|
+
/** One file's responses, read with the parser and pricing `why` uses. */
|
|
83
|
+
function readUnit(unit, rates) {
|
|
84
|
+
// A stored child is a spawned session by its path, as readInsightSession reads it.
|
|
85
|
+
const transcript = (0, transcript_1.readInsightTranscript)(unit.path, { host: unit.host }, { chunkBytes: CHUNK_BYTES });
|
|
86
|
+
if (transcript.state.forkHistoryBoundaryUnknown)
|
|
87
|
+
return { host: unit.host, key: unit.key, models: [], rows: [], forkUnknown: true };
|
|
88
|
+
const figures = (0, render_1.sessionFigures)(transcript, rates);
|
|
89
|
+
const models = [], modelIndex = new Map();
|
|
90
|
+
const rows = figures.turns.map((turn, i) => {
|
|
91
|
+
const usd = figures.prices[i].usd, model = turn.model ?? null;
|
|
92
|
+
if (!modelIndex.has(model)) {
|
|
93
|
+
modelIndex.set(model, models.length);
|
|
94
|
+
models.push(model);
|
|
95
|
+
}
|
|
96
|
+
const split = turn.cacheWrite5mTokens !== undefined && turn.cacheWrite1hTokens !== undefined;
|
|
97
|
+
return [turnKey(turn.id), turn.at !== undefined && Number.isFinite(turn.at) ? turn.at : null, usd?.min ?? null, usd?.max ?? null, modelIndex.get(model),
|
|
98
|
+
turn.inputTokens, turn.cacheWriteTokens, turn.cacheReadTokens, turn.outputTokens,
|
|
99
|
+
split ? turn.cacheWrite5mTokens : null, split ? turn.cacheWrite1hTokens : null, turn.cacheTtlSeconds ?? null, turn.subagent ? 1 : 0];
|
|
100
|
+
});
|
|
101
|
+
return { host: unit.host, key: unit.key, models, rows, forkUnknown: false };
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* A cached response as a turn again, for the rare response recorded in more
|
|
105
|
+
* than one file. Its session id is its file's key, so the merged turn names the
|
|
106
|
+
* file that owns it. Only what de-duplication and pricing read is restored.
|
|
107
|
+
*/
|
|
108
|
+
function turnOf(copy) {
|
|
109
|
+
const [id, at, , , , input, write, read, output, write5m, write1h, ttl, subagent] = copy.row;
|
|
110
|
+
return {
|
|
111
|
+
id, sessionId: copy.key, host: copy.host, ...(at !== null ? { at } : {}), ...(subagent ? { subagent: true } : {}), ...(copy.model !== null ? { model: copy.model } : {}),
|
|
112
|
+
inputTokens: input, cacheWriteTokens: write, cacheReadTokens: read, outputTokens: output,
|
|
113
|
+
...(write5m !== null && write1h !== null ? { cacheWrite5mTokens: write5m, cacheWrite1hTokens: write1h } : {}), ...(ttl !== null ? { cacheTtlSeconds: ttl } : {}),
|
|
114
|
+
contextTokens: input + write + read, signals: { afterCompaction: false, firstSpawnedTurn: false }, explicitAttribution: [], uncertainties: [],
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
const calendarDirectory = (home) => (0, node_path_1.join)(home, 'calendar');
|
|
118
|
+
exports.calendarDirectory = calendarDirectory;
|
|
119
|
+
const rollupPath = (home) => (0, node_path_1.join)((0, exports.calendarDirectory)(home), 'daily.json');
|
|
120
|
+
exports.rollupPath = rollupPath;
|
|
121
|
+
const cachePath = (home) => (0, node_path_1.join)((0, exports.calendarDirectory)(home), 'cache.json');
|
|
122
|
+
exports.cachePath = cachePath;
|
|
123
|
+
/** Owner-only file written beside its target and renamed over it, so a reader never sees half of it. */
|
|
124
|
+
function writeAtomic(file, text) {
|
|
125
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(file), { recursive: true, mode: 0o700 });
|
|
126
|
+
const temporary = `${file}.${process.pid}.${(0, node_crypto_1.randomUUID)()}.tmp`;
|
|
127
|
+
try {
|
|
128
|
+
(0, node_fs_1.writeFileSync)(temporary, text, { mode: 0o600, flag: 'wx' });
|
|
129
|
+
(0, node_fs_1.renameSync)(temporary, file);
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
try {
|
|
133
|
+
(0, node_fs_1.unlinkSync)(temporary);
|
|
134
|
+
}
|
|
135
|
+
catch { /* never created */ }
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const record = (value) => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
140
|
+
const count = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0;
|
|
141
|
+
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
142
|
+
function figuresOf(value) {
|
|
143
|
+
const raw = record(value), usd = record(raw.usd);
|
|
144
|
+
const models = Array.isArray(raw.unpricedModels) ? raw.unpricedModels.filter((model) => model === null || typeof model === 'string') : [];
|
|
145
|
+
return { tokens: count(raw.tokens), subagentTokens: count(raw.subagentTokens), usd: { min: count(usd.min), max: count(usd.max) },
|
|
146
|
+
unpricedTokens: count(raw.unpricedTokens), unpricedModels: models };
|
|
147
|
+
}
|
|
148
|
+
/** The daily count on disk. An unreadable file is moved aside, never overwritten, so it can still be recovered. */
|
|
149
|
+
function readRollup(home) {
|
|
150
|
+
const file = (0, exports.rollupPath)(home);
|
|
151
|
+
const empty = () => ({ schema: ROLLUP_SCHEMA, files: {}, shared: {} });
|
|
152
|
+
let text;
|
|
153
|
+
try {
|
|
154
|
+
text = (0, node_fs_1.readFileSync)(file, 'utf8');
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return empty();
|
|
158
|
+
}
|
|
159
|
+
let raw;
|
|
160
|
+
try {
|
|
161
|
+
raw = record(JSON.parse(text));
|
|
162
|
+
if (raw.schema !== ROLLUP_SCHEMA)
|
|
163
|
+
throw new Error('schema');
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
try {
|
|
167
|
+
(0, node_fs_1.renameSync)(file, `${file}.unreadable-${Date.now()}`);
|
|
168
|
+
}
|
|
169
|
+
catch { /* left in place */ }
|
|
170
|
+
return empty();
|
|
171
|
+
}
|
|
172
|
+
const rollup = empty();
|
|
173
|
+
for (const [key, value] of Object.entries(record(raw.files))) {
|
|
174
|
+
const entry = record(value);
|
|
175
|
+
if (entry.host !== 'claude' && entry.host !== 'codex')
|
|
176
|
+
continue;
|
|
177
|
+
const days = {};
|
|
178
|
+
for (const [day, figures] of Object.entries(record(entry.days)))
|
|
179
|
+
if (DAY.test(day))
|
|
180
|
+
days[day] = figuresOf(figures);
|
|
181
|
+
rollup.files[key] = { host: entry.host, days };
|
|
182
|
+
}
|
|
183
|
+
for (const [id, owner] of Object.entries(record(raw.shared)))
|
|
184
|
+
if (typeof owner === 'string')
|
|
185
|
+
rollup.shared[id] = owner;
|
|
186
|
+
return rollup;
|
|
187
|
+
}
|
|
188
|
+
function readCache(home, signature) {
|
|
189
|
+
try {
|
|
190
|
+
const raw = record(JSON.parse((0, node_fs_1.readFileSync)((0, exports.cachePath)(home), 'utf8')));
|
|
191
|
+
if (raw.schema === CACHE_SCHEMA && raw.signature === signature)
|
|
192
|
+
return { schema: CACHE_SCHEMA, signature, units: record(raw.units) };
|
|
193
|
+
}
|
|
194
|
+
catch { /* first run, or unreadable: rebuilt below */ }
|
|
195
|
+
return { schema: CACHE_SCHEMA, signature, units: {} };
|
|
196
|
+
}
|
|
197
|
+
/** Parser, pricing and cache format: a new Burn release or a pricing override change recomputes every transcript once. */
|
|
198
|
+
function cacheSignature(rates) {
|
|
199
|
+
const table = { ...pricing_1.MODEL_PRICING, ...rates };
|
|
200
|
+
const version = require('../../../package.json').version;
|
|
201
|
+
return `${CACHE_SCHEMA}:${version}:${sha256(JSON.stringify(Object.keys(table).sort().map(model => [model, table[model]])))}`;
|
|
202
|
+
}
|
|
203
|
+
function cachedUnit(value, file) {
|
|
204
|
+
const unit = record(value);
|
|
205
|
+
const same = Array.isArray(unit.file) && unit.file.length === 3 && unit.file.every((part, i) => part === file[i]);
|
|
206
|
+
return same && typeof unit.key === 'string' && Array.isArray(unit.models) && Array.isArray(unit.rows)
|
|
207
|
+
&& (unit.host === 'claude' || unit.host === 'codex') && typeof unit.forkUnknown === 'boolean' ? unit : undefined;
|
|
208
|
+
}
|
|
209
|
+
/* ----------------------------------------------------------------- ledger */
|
|
210
|
+
/**
|
|
211
|
+
* Sub-agent launches AgentGuard held, per local day, from the decisions ledger:
|
|
212
|
+
* a spawn refused by an enforced STOP, or held by the ask prompt (`asked: true`).
|
|
213
|
+
* A decision id, or a session and tool call, counts once. Shadow and overridden
|
|
214
|
+
* decisions were not held, and a refused model call or override attempt is not
|
|
215
|
+
* a launch.
|
|
216
|
+
*/
|
|
217
|
+
function ledgerDays(home) {
|
|
218
|
+
const held = new Map(), seen = new Set();
|
|
219
|
+
let row = 0;
|
|
220
|
+
try {
|
|
221
|
+
for (const raw of (0, history_1.jsonRows)((0, node_path_1.join)(home, 'decisions.ndjson'))) {
|
|
222
|
+
row++;
|
|
223
|
+
const action = typeof raw.action === 'string' ? raw.action : 'spawn';
|
|
224
|
+
if (action !== 'spawn' || raw.verdict !== 'STOP' || !(raw.enforced === true || raw.blocked === true || raw.asked === true))
|
|
225
|
+
continue;
|
|
226
|
+
const at = (0, history_1.timestamp)(raw.at ?? raw.timestamp);
|
|
227
|
+
if (at === null)
|
|
228
|
+
continue;
|
|
229
|
+
const id = typeof raw.decisionId === 'string' ? `decision:${raw.decisionId}`
|
|
230
|
+
: typeof raw.sessionId === 'string' && typeof raw.toolUseId === 'string' ? `call:${raw.sessionId}:${raw.toolUseId}` : `row:${row}`;
|
|
231
|
+
if (seen.has(id))
|
|
232
|
+
continue;
|
|
233
|
+
seen.add(id);
|
|
234
|
+
const day = localDay(at);
|
|
235
|
+
held.set(day, (held.get(day) ?? 0) + 1);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
catch { /* No ledger yet, or unreadable: no marks. */ }
|
|
239
|
+
return held;
|
|
240
|
+
}
|
|
241
|
+
const emptyFigures = () => ({ tokens: 0, subagentTokens: 0, usd: { min: 0, max: 0 }, unpricedTokens: 0, unpricedModels: [] });
|
|
242
|
+
/**
|
|
243
|
+
* Reads every local transcript (from the cache when unchanged), merges the daily
|
|
244
|
+
* count of files that are gone, writes both back, and reads the ledger.
|
|
245
|
+
*/
|
|
246
|
+
function collectCalendar(options) {
|
|
247
|
+
const { home } = options, rates = options.rates ?? {};
|
|
248
|
+
const units = transcriptUnits((0, sessions_1.discoverInsightTranscripts)(options.roots ?? (0, sessions_1.transcriptRoots)()));
|
|
249
|
+
const signature = cacheSignature(rates), cache = readCache(home, signature);
|
|
250
|
+
const nextCache = {}, loaded = [];
|
|
251
|
+
let cacheChanged = false, unreadable = 0;
|
|
252
|
+
for (const unit of units) {
|
|
253
|
+
const id = sha256(unit.path), file = [id.slice(0, 16), unit.size, unit.mtimeMs];
|
|
254
|
+
let entry = cachedUnit(cache.units[id], file);
|
|
255
|
+
if (!entry) {
|
|
256
|
+
try {
|
|
257
|
+
entry = { file, ...readUnit(unit, rates) };
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
unreadable++;
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
cacheChanged = true;
|
|
264
|
+
}
|
|
265
|
+
nextCache[id] = entry;
|
|
266
|
+
loaded.push(entry);
|
|
267
|
+
}
|
|
268
|
+
if (Object.keys(cache.units).some(id => !(id in nextCache)))
|
|
269
|
+
cacheChanged = true;
|
|
270
|
+
const rollup = readRollup(home);
|
|
271
|
+
const present = new Map();
|
|
272
|
+
for (const entry of loaded)
|
|
273
|
+
present.set(entry.key, entry.host);
|
|
274
|
+
const first = new Map(), groups = new Map();
|
|
275
|
+
for (const entry of loaded)
|
|
276
|
+
for (const row of entry.rows) {
|
|
277
|
+
const copy = { key: entry.key, host: entry.host, row, model: entry.models[row[4]] ?? null }, seen = first.get(row[0]);
|
|
278
|
+
if (!seen)
|
|
279
|
+
first.set(row[0], copy);
|
|
280
|
+
else
|
|
281
|
+
groups.set(row[0], [...groups.get(row[0]) ?? [seen], copy]);
|
|
282
|
+
}
|
|
283
|
+
const shared = {};
|
|
284
|
+
for (const [id, owner] of Object.entries(rollup.shared))
|
|
285
|
+
if (!present.has(owner))
|
|
286
|
+
shared[id] = owner;
|
|
287
|
+
const fresh = new Map();
|
|
288
|
+
for (const key of present.keys())
|
|
289
|
+
fresh.set(key, {});
|
|
290
|
+
let undatedTokens = 0;
|
|
291
|
+
const add = (key, at, tokens, subagent, usd, model) => {
|
|
292
|
+
if (at === null) {
|
|
293
|
+
undatedTokens += tokens;
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
const target = fresh.get(key)[localDay(at)] ??= emptyFigures();
|
|
297
|
+
target.tokens += tokens;
|
|
298
|
+
if (subagent)
|
|
299
|
+
target.subagentTokens += tokens;
|
|
300
|
+
if (usd === null) {
|
|
301
|
+
target.unpricedTokens += tokens;
|
|
302
|
+
if (tokens > 0 && !target.unpricedModels.includes(model))
|
|
303
|
+
target.unpricedModels.push(model);
|
|
304
|
+
}
|
|
305
|
+
else
|
|
306
|
+
target.usd = { min: target.usd.min + usd.min, max: target.usd.max + usd.max };
|
|
307
|
+
};
|
|
308
|
+
for (const [id, copy] of first) {
|
|
309
|
+
if (id in shared)
|
|
310
|
+
continue;
|
|
311
|
+
const group = groups.get(id), row = copy.row;
|
|
312
|
+
if (!group) {
|
|
313
|
+
add(copy.key, row[1], rowTokens(row), row[12] === 1, row[2] === null || row[3] === null ? null : { min: row[2], max: row[3] }, copy.model);
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
const merged = (0, transcript_1.deduplicateTurns)(group.map(turnOf))[0];
|
|
317
|
+
shared[id] = merged.sessionId;
|
|
318
|
+
add(merged.sessionId, merged.at ?? null, merged.inputTokens + merged.cacheWriteTokens + merged.cacheReadTokens + merged.outputTokens, merged.subagent === true, (0, pricing_1.priceTurn)(merged, rates).usd, merged.model ?? null);
|
|
319
|
+
}
|
|
320
|
+
// Files on disk replace their own days; files that are gone keep theirs.
|
|
321
|
+
const files = {};
|
|
322
|
+
let rollupFiles = 0;
|
|
323
|
+
for (const [key, entry] of Object.entries(rollup.files))
|
|
324
|
+
if (!present.has(key) && Object.keys(entry.days).length) {
|
|
325
|
+
files[key] = entry;
|
|
326
|
+
rollupFiles++;
|
|
327
|
+
}
|
|
328
|
+
for (const [key, host] of present)
|
|
329
|
+
if (Object.keys(fresh.get(key)).length)
|
|
330
|
+
files[key] = { host, days: fresh.get(key) };
|
|
331
|
+
const sorted = (value) => Object.fromEntries(Object.keys(value).sort().map(key => [key, value[key]]));
|
|
332
|
+
const nextRollup = { schema: ROLLUP_SCHEMA, files: sorted(files), shared: sorted(shared) };
|
|
333
|
+
let saved = true;
|
|
334
|
+
try {
|
|
335
|
+
const text = JSON.stringify(nextRollup);
|
|
336
|
+
let previous = '';
|
|
337
|
+
try {
|
|
338
|
+
previous = (0, node_fs_1.readFileSync)((0, exports.rollupPath)(home), 'utf8');
|
|
339
|
+
}
|
|
340
|
+
catch { /* none yet */ }
|
|
341
|
+
if (text !== previous)
|
|
342
|
+
writeAtomic((0, exports.rollupPath)(home), text);
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
saved = false;
|
|
346
|
+
}
|
|
347
|
+
if (cacheChanged) {
|
|
348
|
+
try {
|
|
349
|
+
writeAtomic((0, exports.cachePath)(home), JSON.stringify({ schema: CACHE_SCHEMA, signature, units: nextCache }));
|
|
350
|
+
}
|
|
351
|
+
catch { /* A cache that cannot be written (a full disk) only costs the next run time. */ }
|
|
352
|
+
}
|
|
353
|
+
const days = new Map();
|
|
354
|
+
let claudeSeen = [...present.values()].includes('claude');
|
|
355
|
+
for (const entry of Object.values(nextRollup.files)) {
|
|
356
|
+
if (entry.host === 'claude')
|
|
357
|
+
claudeSeen = true;
|
|
358
|
+
for (const [day, figures] of Object.entries(entry.days)) {
|
|
359
|
+
const total = days.get(day) ?? { ...emptyFigures(), claudeTokens: 0, codexTokens: 0 };
|
|
360
|
+
total.tokens += figures.tokens;
|
|
361
|
+
total.subagentTokens += figures.subagentTokens;
|
|
362
|
+
total.usd = { min: total.usd.min + figures.usd.min, max: total.usd.max + figures.usd.max };
|
|
363
|
+
total.unpricedTokens += figures.unpricedTokens;
|
|
364
|
+
for (const model of figures.unpricedModels)
|
|
365
|
+
if (!total.unpricedModels.includes(model))
|
|
366
|
+
total.unpricedModels.push(model);
|
|
367
|
+
if (entry.host === 'claude')
|
|
368
|
+
total.claudeTokens += figures.tokens;
|
|
369
|
+
else
|
|
370
|
+
total.codexTokens += figures.tokens;
|
|
371
|
+
days.set(day, total);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const recorded = [...days].filter(([, figures]) => figures.tokens > 0).map(([day]) => day).sort();
|
|
375
|
+
return {
|
|
376
|
+
days, heldLaunches: ledgerDays(home), firstDay: recorded[0] ?? null, claudeSeen, saved,
|
|
377
|
+
sources: { transcripts: loaded.length, rollupFiles, forkBoundaryUnknown: loaded.filter(entry => entry.forkUnknown).length, unreadable, undatedTokens },
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
/** Weeks of two columns each that fit beside the weekday labels in `columns`, 1 to 53. */
|
|
381
|
+
const weeksThatFit = (columns) => Math.min(exports.CALENDAR_MAX_WEEKS, Math.max(1, Math.floor((columns - exports.CALENDAR_GRID_PREFIX + 1) / 2)));
|
|
382
|
+
exports.weeksThatFit = weeksThatFit;
|
|
383
|
+
/** A day's shade: the quarter of the shown days with tokens that it reaches, so the busiest shown day is always level 4. */
|
|
384
|
+
function calendarLevels(values) {
|
|
385
|
+
const sorted = values.filter(value => value > 0).sort((a, b) => a - b);
|
|
386
|
+
return tokens => {
|
|
387
|
+
if (!(tokens > 0) || !sorted.length)
|
|
388
|
+
return 0;
|
|
389
|
+
let low = 0, high = sorted.length;
|
|
390
|
+
while (low < high) {
|
|
391
|
+
const middle = (low + high) >> 1;
|
|
392
|
+
if (sorted[middle] <= tokens)
|
|
393
|
+
low = middle + 1;
|
|
394
|
+
else
|
|
395
|
+
high = middle;
|
|
396
|
+
}
|
|
397
|
+
return Math.max(1, Math.min(4, Math.ceil(4 * low / sorted.length)));
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
function calendarReport(data, options = {}) {
|
|
401
|
+
const today = localDay(options.now ?? Date.now()), lastSunday = (0, exports.addDays)(today, -(0, exports.weekdayOf)(today));
|
|
402
|
+
const oldest = data.firstDay;
|
|
403
|
+
const span = options.weeks ?? (0, exports.weeksThatFit)(options.columns ?? 80);
|
|
404
|
+
const history = oldest === null ? 0 : Math.max(1, ((0, exports.dayNumber)(lastSunday) - (0, exports.dayNumber)((0, exports.addDays)(oldest, -(0, exports.weekdayOf)(oldest)))) / 7 + 1);
|
|
405
|
+
const weeks = options.weeks ?? Math.max(1, Math.min(span, history));
|
|
406
|
+
const from = (0, exports.addDays)(lastSunday, -7 * (weeks - 1));
|
|
407
|
+
const days = [];
|
|
408
|
+
for (let n = (0, exports.dayNumber)(from); n <= (0, exports.dayNumber)(today); n++) {
|
|
409
|
+
const date = dayText(n), figures = data.days.get(date), tokens = figures?.tokens ?? 0, subagentTokens = figures?.subagentTokens ?? 0;
|
|
410
|
+
days.push({ date, recorded: oldest !== null && date >= oldest, tokens, subagentTokens, usd: { ...figures?.usd ?? { min: 0, max: 0 } },
|
|
411
|
+
unpricedTokens: figures?.unpricedTokens ?? 0, claudeTokens: figures?.claudeTokens ?? 0, codexTokens: figures?.codexTokens ?? 0,
|
|
412
|
+
level: null, subagentsOverHalf: tokens > 0 && subagentTokens * 2 > tokens, heldLaunches: data.heldLaunches.get(date) ?? 0 });
|
|
413
|
+
}
|
|
414
|
+
const level = calendarLevels(days.filter(day => day.recorded).map(day => day.tokens));
|
|
415
|
+
for (const day of days)
|
|
416
|
+
day.level = day.recorded ? level(day.tokens) : null;
|
|
417
|
+
const sum = (field) => days.reduce((total, day) => total + day[field], 0);
|
|
418
|
+
const tokens = sum('tokens'), subagentTokens = sum('subagentTokens'), unpricedTokens = sum('unpricedTokens');
|
|
419
|
+
const unpricedModels = [...new Set(days.flatMap(day => data.days.get(day.date)?.unpricedModels ?? []))]
|
|
420
|
+
.sort((a, b) => a === b ? 0 : a === null ? 1 : b === null ? -1 : a < b ? -1 : 1);
|
|
421
|
+
const usd = tokens > 0 && unpricedTokens === tokens ? null : days.reduce((total, day) => ({ min: total.min + day.usd.min, max: total.max + day.usd.max }), { min: 0, max: 0 });
|
|
422
|
+
const busiest = days.reduce((best, day) => day.tokens > (best?.tokens ?? 0) ? day : best, null);
|
|
423
|
+
return {
|
|
424
|
+
from, to: today, weeks, firstRecordedDay: oldest, days,
|
|
425
|
+
totals: { tokens, subagentTokens, subagentShare: tokens ? subagentTokens / tokens : null, usd, unpricedTokens, unpricedModels,
|
|
426
|
+
heldLaunches: sum('heldLaunches'), claudeTokens: sum('claudeTokens'), codexTokens: sum('codexTokens') },
|
|
427
|
+
busiest: busiest ? { date: busiest.date, tokens: busiest.tokens } : null,
|
|
428
|
+
historyShort: data.claudeSeen && oldest !== null && history < span,
|
|
429
|
+
sources: data.sources, subagentsIncluded: true, basis: 'estimated_api_list_price',
|
|
430
|
+
};
|
|
431
|
+
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Languages of the plain `why` and `
|
|
3
|
-
* Spanish and Brazilian Portuguese. Only words change. Numbers keep their
|
|
4
|
-
* formatting (1,234,567, $1335.37, 12.3%) so figures match screenshots and
|
|
5
|
-
* site, and session ids, model ids, commands, URLs and product names print as
|
|
6
|
-
* they are. `why json` and `
|
|
2
|
+
* Languages of the plain `why`, `compare` and `calendar` reports: English, Latin
|
|
3
|
+
* American Spanish and Brazilian Portuguese. Only words change. Numbers keep their
|
|
4
|
+
* en-US formatting (1,234,567, $1335.37, 12.3%) so figures match screenshots and
|
|
5
|
+
* the site, and session ids, model ids, commands, URLs and product names print as
|
|
6
|
+
* they are. `why json`, `compare json` and `calendar json` are machine formats,
|
|
7
|
+
* never translated.
|
|
7
8
|
*
|
|
8
9
|
* Detection is pure: the CLI passes in the flag, the environment and the Intl
|
|
9
10
|
* locale, and each renderer receives the chosen language as an argument.
|
|
@@ -57,12 +58,50 @@ export interface WhyText {
|
|
|
57
58
|
missingTtl: string;
|
|
58
59
|
mixedRanges: string;
|
|
59
60
|
diagnostics: (duplicates: number, malformed: number) => string;
|
|
61
|
+
/** The sub-agent share, with AgentGuard's plugin that asks before the next sub-agent past a limit starts; and the 0.3.16 reload dollars, with the `rewrites` command. */
|
|
60
62
|
tipFanout: (share: string) => string;
|
|
61
63
|
tipRewrites: (rewrites: string, total: string) => string;
|
|
62
|
-
|
|
64
|
+
/** Sub-agents that ran on the main conversation's model, by its display name (Opus 5.5). */
|
|
65
|
+
tipSubagentModel: (count: number, model: string) => string;
|
|
66
|
+
/** Reloads after a pause outlasted the cache; `longest` is the longest such pause as `rewrites` prints it (47m, 2h 5m). */
|
|
67
|
+
tipIdleReloads: (count: number, longest: string) => string;
|
|
68
|
+
/** Reloads that a model switch caused. */
|
|
69
|
+
tipModelSwitch: (count: number) => string;
|
|
70
|
+
/** The conversation Claude re-read per message, a median. */
|
|
71
|
+
tipConversation: (tokens: string) => string;
|
|
72
|
+
/** The setup Claude read per message, a median. */
|
|
73
|
+
tipSetup: (tokens: string) => string;
|
|
74
|
+
/**
|
|
75
|
+
* One measured change around a compaction, /clear or model switch: the median
|
|
76
|
+
* tokens per message in the `messages` after it and in as many before it. The
|
|
77
|
+
* date and time are UTC. Measurement only, never a saving or a cause.
|
|
78
|
+
*/
|
|
79
|
+
proof: (event: ProofEvent, when: {
|
|
80
|
+
date: string;
|
|
81
|
+
time: string;
|
|
82
|
+
}, after: string, before: string, messages: number, direction: 'down' | 'up' | 'same') => string;
|
|
63
83
|
hide: string;
|
|
64
84
|
}
|
|
85
|
+
/** What `why` measures a change around. `model` is a display name (Sonnet 5). */
|
|
86
|
+
export type ProofEvent = {
|
|
87
|
+
kind: 'compact' | 'auto' | 'compaction' | 'clear';
|
|
88
|
+
} | {
|
|
89
|
+
kind: 'model';
|
|
90
|
+
model: string;
|
|
91
|
+
};
|
|
65
92
|
export declare const WHY_TEXT: Readonly<Record<WhyLang, WhyText>>;
|
|
93
|
+
/**
|
|
94
|
+
* The cost of one more sub-agent, for the STOP prompt and box: what this
|
|
95
|
+
* session's finished sub-agents averaged, a measurement of what already ran and
|
|
96
|
+
* never a forecast. `count` is at least three; `usd` is null when any of them ran
|
|
97
|
+
* on an unpriced model. Every other line of the STOP text is English on every
|
|
98
|
+
* host, so the hook asks for English; the Spanish and Portuguese lines are here
|
|
99
|
+
* for when the STOP text is translated.
|
|
100
|
+
*/
|
|
101
|
+
export interface DecisionText {
|
|
102
|
+
finished: (count: number, tokens: string, usd: string | null) => string;
|
|
103
|
+
}
|
|
104
|
+
export declare const DECISION_TEXT: Readonly<Record<WhyLang, DecisionText>>;
|
|
66
105
|
/**
|
|
67
106
|
* Every line of the plain `compare` report, in the same three languages and under
|
|
68
107
|
* the same rules as `why`: words change, figures, ids, model ids, paths and
|
|
@@ -94,3 +133,59 @@ export interface CompareText {
|
|
|
94
133
|
fewerThanTwo: (found: number, project: string | null) => string;
|
|
95
134
|
}
|
|
96
135
|
export declare const COMPARE_TEXT: Readonly<Record<WhyLang, CompareText>>;
|
|
136
|
+
/** A calendar date as the report names it: the month's short name, the day of the month and the year. */
|
|
137
|
+
export interface CalendarDate {
|
|
138
|
+
month: string;
|
|
139
|
+
day: number;
|
|
140
|
+
year: number;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Every line of the plain `calendar` report, in the same three languages and
|
|
144
|
+
* under the same rules as `why` and `compare`: words, weekday and month names
|
|
145
|
+
* change; figures, the shade characters, the plain-text day letters, AgentGuard,
|
|
146
|
+
* Burn, Claude Code and Codex do not. The command name in the title stays as
|
|
147
|
+
* typed, as `why` and `compare` keep theirs. Every line is written for a
|
|
148
|
+
* developer who has never heard of AgentGuard, in everyday words: "sub-agents" is
|
|
149
|
+
* Claude Code's own word, and a dollar figure is "at API prices, not a bill".
|
|
150
|
+
*/
|
|
151
|
+
export interface CalendarText {
|
|
152
|
+
/** Row labels, Sunday first. */
|
|
153
|
+
weekdays: readonly [string, string, string, string, string, string, string];
|
|
154
|
+
/** January first, three letters each, so a label fits above two week columns. */
|
|
155
|
+
months: readonly [string, string, string, string, string, string, string, string, string, string, string, string];
|
|
156
|
+
/** A day in the summary, with its year only when the calendar spans two years. */
|
|
157
|
+
date: (date: CalendarDate, withYear: boolean) => string;
|
|
158
|
+
/** The span in the title, first day to last. */
|
|
159
|
+
span: (from: CalendarDate, to: CalendarDate) => string;
|
|
160
|
+
title: (span: string) => string;
|
|
161
|
+
tokens: (count: string) => string;
|
|
162
|
+
/** `usd` is null when no token shown has a known API price. */
|
|
163
|
+
dollars: (usd: string | null) => string;
|
|
164
|
+
busiest: (date: string, count: string) => string;
|
|
165
|
+
subagents: (share: string) => string;
|
|
166
|
+
/** Sub-agent launches AgentGuard held (refused, or held for the person's yes); printed only above zero. */
|
|
167
|
+
held: (launches: number) => string;
|
|
168
|
+
less: string;
|
|
169
|
+
more: string;
|
|
170
|
+
/** What an amber day means: `colour` beside an amber cell, `plain` names the day letter. */
|
|
171
|
+
subagentDays: {
|
|
172
|
+
colour: string;
|
|
173
|
+
plain: (letter: string) => string;
|
|
174
|
+
};
|
|
175
|
+
/** What a red mark means, the same way. */
|
|
176
|
+
heldDays: {
|
|
177
|
+
colour: string;
|
|
178
|
+
plain: (letter: string) => string;
|
|
179
|
+
};
|
|
180
|
+
/** Which hosts the shown days came from. */
|
|
181
|
+
sources: (claude: boolean, codex: boolean) => string;
|
|
182
|
+
unpriced: (tokens: string, models: string) => string;
|
|
183
|
+
forkUnknown: (forks: number) => string;
|
|
184
|
+
unreadable: (files: number) => string;
|
|
185
|
+
noData: string;
|
|
186
|
+
/** Printed while the recorded history is shorter than the calendar could show. */
|
|
187
|
+
shortHistory: readonly [string, string];
|
|
188
|
+
/** Stderr when the daily counts cannot be written. */
|
|
189
|
+
saveFailed: string;
|
|
190
|
+
}
|
|
191
|
+
export declare const CALENDAR_TEXT: Readonly<Record<WhyLang, CalendarText>>;
|