@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,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.displayConfigPath = void 0;
|
|
4
|
+
exports.setDisplayMode = setDisplayMode;
|
|
5
|
+
exports.displayArguments = displayArguments;
|
|
6
|
+
exports.displayMode = displayMode;
|
|
7
|
+
exports.simpleViewNotice = simpleViewNotice;
|
|
8
|
+
const node_fs_1 = require("node:fs");
|
|
9
|
+
const node_crypto_1 = require("node:crypto");
|
|
10
|
+
const node_path_1 = require("node:path");
|
|
11
|
+
const i18n_1 = require("./insights/i18n");
|
|
12
|
+
const displayConfigPath = (home) => (0, node_path_1.join)(home, 'burn-config.json');
|
|
13
|
+
exports.displayConfigPath = displayConfigPath;
|
|
14
|
+
const isMode = (value) => value === 'simple' || value === 'detailed';
|
|
15
|
+
function readConfig(home) {
|
|
16
|
+
try {
|
|
17
|
+
const value = JSON.parse((0, node_fs_1.readFileSync)((0, exports.displayConfigPath)(home), 'utf8'));
|
|
18
|
+
if (value && typeof value === 'object' && !Array.isArray(value))
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
if (error.code === 'ENOENT')
|
|
23
|
+
return {};
|
|
24
|
+
}
|
|
25
|
+
throw new Error('Burn display settings could not be read. Keep the existing file and repair its JSON.');
|
|
26
|
+
}
|
|
27
|
+
function saveConfig(home, value) {
|
|
28
|
+
(0, node_fs_1.mkdirSync)(home, { recursive: true, mode: 0o700 });
|
|
29
|
+
const temporary = `${(0, exports.displayConfigPath)(home)}.${(0, node_crypto_1.randomUUID)()}.tmp`;
|
|
30
|
+
(0, node_fs_1.writeFileSync)(temporary, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
|
|
31
|
+
(0, node_fs_1.renameSync)(temporary, (0, exports.displayConfigPath)(home));
|
|
32
|
+
}
|
|
33
|
+
function setDisplayMode(home, mode) {
|
|
34
|
+
saveConfig(home, { ...readConfig(home), displayMode: mode });
|
|
35
|
+
}
|
|
36
|
+
function displayArguments(args) {
|
|
37
|
+
const simple = args.includes('--simple'), detailed = args.includes('--detailed');
|
|
38
|
+
if (simple && detailed)
|
|
39
|
+
throw new Error('Choose either simple or detailed for this command.');
|
|
40
|
+
return { args: args.filter(arg => arg !== '--simple' && arg !== '--detailed'), mode: simple ? 'simple' : detailed ? 'detailed' : undefined };
|
|
41
|
+
}
|
|
42
|
+
/** `fallback` applies only when no flag, environment value or saved preference chooses a mode. */
|
|
43
|
+
function displayMode(home, override, env = process.env, fallback = 'simple') {
|
|
44
|
+
if (override)
|
|
45
|
+
return override;
|
|
46
|
+
if (env.AGENTGUARD_BURN_MODE) {
|
|
47
|
+
if (!isMode(env.AGENTGUARD_BURN_MODE))
|
|
48
|
+
throw new Error('AGENTGUARD_BURN_MODE must be simple or detailed.');
|
|
49
|
+
return env.AGENTGUARD_BURN_MODE;
|
|
50
|
+
}
|
|
51
|
+
const value = readConfig(home).displayMode;
|
|
52
|
+
return isMode(value) ? value : fallback;
|
|
53
|
+
}
|
|
54
|
+
/** Call before observers create state. A migration notice is human output only. */
|
|
55
|
+
function simpleViewNotice(home, lang) {
|
|
56
|
+
try {
|
|
57
|
+
const config = readConfig(home);
|
|
58
|
+
if (config.simpleViewSeen === true)
|
|
59
|
+
return null;
|
|
60
|
+
const existing = config.displayMode === 'detailed' || ['burn-policy.json', 'decisions.ndjson', 'sessions', 'pace', 'calendar'].some(file => (0, node_fs_1.existsSync)((0, node_path_1.join)(home, file)));
|
|
61
|
+
saveConfig(home, { ...config, simpleViewSeen: true });
|
|
62
|
+
return existing ? i18n_1.SIMPLE_TEXT[lang].notice : null;
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return null;
|
|
66
|
+
} // A read-only home never breaks a status display.
|
|
67
|
+
}
|
package/dist/src/index.d.ts
CHANGED
|
@@ -32,3 +32,5 @@ export { readLaunchTree, readLaunchTreeWithReceipts, buildLaunchTree, renderLaun
|
|
|
32
32
|
export { sessionTally, tallyEntries, readLedgerTallies, readLedgerDailyTallies, renderSessionTally, pluginLedgerDirectories, sessionLaunchReceipts, type SessionTally, type TallyCounts } from './insights/tally';
|
|
33
33
|
export { formatStatusFields, parseStatusFields, statusPace, statusColor, type StatusInput, type StatusMetrics } from './insights/status-fields';
|
|
34
34
|
export { readStatusBurn, readStatusMetrics } from './insights/status-data';
|
|
35
|
+
export { collectWeek, saveWeek, weekFigures, weekStartOf, lastCompletedWeekStart, isMonday, WEEK_SCHEMA, SMALLER_MODEL, type WeekFigures, type WeekReport, type WeekAmount, type WeekCause, type WeekTopCause, type BurnWeekFile, type CollectWeekOptions, type SaveWeekResult } from './insights/week';
|
|
36
|
+
export { renderWeek } from './insights/week-render';
|
package/dist/src/index.js
CHANGED
|
@@ -16,7 +16,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
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
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
|
+
exports.renderWeek = exports.SMALLER_MODEL = exports.WEEK_SCHEMA = exports.isMonday = exports.lastCompletedWeekStart = exports.weekStartOf = exports.weekFigures = exports.saveWeek = exports.collectWeek = exports.readStatusMetrics = exports.readStatusBurn = exports.statusColor = exports.statusPace = void 0;
|
|
20
20
|
__exportStar(require("./types"), exports);
|
|
21
21
|
var defaults_1 = require("./defaults");
|
|
22
22
|
Object.defineProperty(exports, "DEFAULT_POLICY", { enumerable: true, get: function () { return defaults_1.DEFAULT_POLICY; } });
|
|
@@ -159,3 +159,14 @@ Object.defineProperty(exports, "statusColor", { enumerable: true, get: function
|
|
|
159
159
|
var status_data_1 = require("./insights/status-data");
|
|
160
160
|
Object.defineProperty(exports, "readStatusBurn", { enumerable: true, get: function () { return status_data_1.readStatusBurn; } });
|
|
161
161
|
Object.defineProperty(exports, "readStatusMetrics", { enumerable: true, get: function () { return status_data_1.readStatusMetrics; } });
|
|
162
|
+
var week_1 = require("./insights/week");
|
|
163
|
+
Object.defineProperty(exports, "collectWeek", { enumerable: true, get: function () { return week_1.collectWeek; } });
|
|
164
|
+
Object.defineProperty(exports, "saveWeek", { enumerable: true, get: function () { return week_1.saveWeek; } });
|
|
165
|
+
Object.defineProperty(exports, "weekFigures", { enumerable: true, get: function () { return week_1.weekFigures; } });
|
|
166
|
+
Object.defineProperty(exports, "weekStartOf", { enumerable: true, get: function () { return week_1.weekStartOf; } });
|
|
167
|
+
Object.defineProperty(exports, "lastCompletedWeekStart", { enumerable: true, get: function () { return week_1.lastCompletedWeekStart; } });
|
|
168
|
+
Object.defineProperty(exports, "isMonday", { enumerable: true, get: function () { return week_1.isMonday; } });
|
|
169
|
+
Object.defineProperty(exports, "WEEK_SCHEMA", { enumerable: true, get: function () { return week_1.WEEK_SCHEMA; } });
|
|
170
|
+
Object.defineProperty(exports, "SMALLER_MODEL", { enumerable: true, get: function () { return week_1.SMALLER_MODEL; } });
|
|
171
|
+
var week_render_1 = require("./insights/week-render");
|
|
172
|
+
Object.defineProperty(exports, "renderWeek", { enumerable: true, get: function () { return week_render_1.renderWeek; } });
|
|
@@ -26,6 +26,7 @@ exports.drawCalendar = drawCalendar;
|
|
|
26
26
|
* bar, while ▇ leaves a thin gap above each day and the grid reads as squares.
|
|
27
27
|
*/
|
|
28
28
|
const canvas_1 = require("../canvas");
|
|
29
|
+
const version_1 = require("../version");
|
|
29
30
|
const calendar_1 = require("./calendar");
|
|
30
31
|
const i18n_1 = require("./i18n");
|
|
31
32
|
const live_1 = require("./live");
|
|
@@ -144,7 +145,7 @@ function calendarLines(report, lang, columns, skin) {
|
|
|
144
145
|
const lines = [];
|
|
145
146
|
const paragraph = (value, color, indent = '') => { for (const line of wrap(value, width, indent))
|
|
146
147
|
lines.push([segment(line, color)]); };
|
|
147
|
-
paragraph(text.title(text.span(dateOf(report.from, text), dateOf(report.to, text)))
|
|
148
|
+
paragraph(`Burn ${version_1.BURN_VERSION} | ${text.title(text.span(dateOf(report.from, text), dateOf(report.to, text)))}`, 'mint');
|
|
148
149
|
if (report.firstRecordedDay === null) {
|
|
149
150
|
paragraph(text.noData, 'white');
|
|
150
151
|
return lines;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { type DollarRange, type PricingTable } from './pricing';
|
|
2
|
+
import type { InsightTurn } from './types';
|
|
3
|
+
import { type CompactSettings, type CompactWindow } from './compact-settings';
|
|
4
|
+
interface Boundary {
|
|
5
|
+
pre: number | null;
|
|
6
|
+
trigger: 'auto' | 'manual' | 'unknown';
|
|
7
|
+
at: number | null;
|
|
8
|
+
}
|
|
9
|
+
export interface CompactReplayTurn {
|
|
10
|
+
usage: InsightTurn;
|
|
11
|
+
boundary?: Boundary;
|
|
12
|
+
clear?: boolean;
|
|
13
|
+
gap?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface CompactReplaySession {
|
|
16
|
+
id: string;
|
|
17
|
+
subagent: boolean;
|
|
18
|
+
turns: CompactReplayTurn[];
|
|
19
|
+
settings: CompactSettings;
|
|
20
|
+
incomplete: number;
|
|
21
|
+
}
|
|
22
|
+
export interface CompactReplayRow {
|
|
23
|
+
window: number | null;
|
|
24
|
+
label: string;
|
|
25
|
+
current: boolean;
|
|
26
|
+
tokens: number | null;
|
|
27
|
+
usd: DollarRange | null;
|
|
28
|
+
compactions: number | null;
|
|
29
|
+
extraCompactions: number | null;
|
|
30
|
+
tokensSaved: number | null;
|
|
31
|
+
usdSaved: DollarRange | null;
|
|
32
|
+
tokenChangePercent: number | null;
|
|
33
|
+
usdChangePercent: number | null;
|
|
34
|
+
unavailable: string[];
|
|
35
|
+
}
|
|
36
|
+
export interface CompactReplayReport {
|
|
37
|
+
version: string;
|
|
38
|
+
days: number;
|
|
39
|
+
from: string;
|
|
40
|
+
to: string;
|
|
41
|
+
basis: 'API list equivalent';
|
|
42
|
+
sessions: number;
|
|
43
|
+
subagentTranscripts: number;
|
|
44
|
+
responses: number;
|
|
45
|
+
measuredCompactions: number;
|
|
46
|
+
recorded: {
|
|
47
|
+
tokens: number;
|
|
48
|
+
usd: DollarRange | null;
|
|
49
|
+
compactions: number;
|
|
50
|
+
};
|
|
51
|
+
settings: Array<CompactWindow & {
|
|
52
|
+
model: string;
|
|
53
|
+
}>;
|
|
54
|
+
windows: CompactReplayRow[];
|
|
55
|
+
backtest: {
|
|
56
|
+
replayTokens: number | null;
|
|
57
|
+
recordedTokens: number;
|
|
58
|
+
errorTokens: number | null;
|
|
59
|
+
errorPercent: number | null;
|
|
60
|
+
unreliable: boolean;
|
|
61
|
+
complete: boolean;
|
|
62
|
+
};
|
|
63
|
+
suggestion: {
|
|
64
|
+
window: number;
|
|
65
|
+
command: string;
|
|
66
|
+
} | null;
|
|
67
|
+
diagnostics: {
|
|
68
|
+
unreadableFiles: number;
|
|
69
|
+
incompleteResponses: number;
|
|
70
|
+
duplicateResponses: number;
|
|
71
|
+
missingTimestamps: number;
|
|
72
|
+
malformedLines: number;
|
|
73
|
+
};
|
|
74
|
+
caveat: string;
|
|
75
|
+
notes: string[];
|
|
76
|
+
settingSource: string;
|
|
77
|
+
}
|
|
78
|
+
export interface CompactReplayOptions {
|
|
79
|
+
days?: number;
|
|
80
|
+
now?: number;
|
|
81
|
+
configDir?: string;
|
|
82
|
+
cwd?: string;
|
|
83
|
+
env?: NodeJS.ProcessEnv;
|
|
84
|
+
/** Explicit settings for fixture callers, with no home or project reads. */
|
|
85
|
+
settings?: CompactSettings;
|
|
86
|
+
rates?: PricingTable;
|
|
87
|
+
}
|
|
88
|
+
/** Pure numerical replay. No observed reset is forced into the automatic backtest. */
|
|
89
|
+
export declare function compactReplay(sessions: CompactReplaySession[], options: {
|
|
90
|
+
days: number;
|
|
91
|
+
now: number;
|
|
92
|
+
rates?: PricingTable;
|
|
93
|
+
diagnostics?: CompactReplayReport['diagnostics'];
|
|
94
|
+
}): CompactReplayReport;
|
|
95
|
+
export declare function collectCompactReplay(options?: CompactReplayOptions): Promise<CompactReplayReport>;
|
|
96
|
+
export declare function renderCompactReplay(report: CompactReplayReport): string;
|
|
97
|
+
export {};
|
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.compactReplay = compactReplay;
|
|
4
|
+
exports.collectCompactReplay = collectCompactReplay;
|
|
5
|
+
exports.renderCompactReplay = renderCompactReplay;
|
|
6
|
+
const node_fs_1 = require("node:fs");
|
|
7
|
+
const node_readline_1 = require("node:readline");
|
|
8
|
+
const node_path_1 = require("node:path");
|
|
9
|
+
const node_os_1 = require("node:os");
|
|
10
|
+
const version_1 = require("../version");
|
|
11
|
+
const live_1 = require("./live");
|
|
12
|
+
const pricing_1 = require("./pricing");
|
|
13
|
+
const transcript_1 = require("./transcript");
|
|
14
|
+
const compact_settings_1 = require("./compact-settings");
|
|
15
|
+
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
16
|
+
const count = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
17
|
+
const DAY = 86_400_000;
|
|
18
|
+
const WINDOWS = [600_000, 400_000, 300_000, 200_000];
|
|
19
|
+
/** Claude JSONL files only, including subagents. Symlinks and sidecars are skipped. */
|
|
20
|
+
function transcriptFiles(root) {
|
|
21
|
+
const files = [];
|
|
22
|
+
const walk = (directory, depth) => {
|
|
23
|
+
if (depth > 8)
|
|
24
|
+
return;
|
|
25
|
+
let entries;
|
|
26
|
+
try {
|
|
27
|
+
entries = (0, node_fs_1.readdirSync)(directory, { withFileTypes: true });
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
for (const entry of entries) {
|
|
33
|
+
const path = (0, node_path_1.join)(directory, entry.name);
|
|
34
|
+
if (entry.isDirectory())
|
|
35
|
+
walk(path, depth + 1);
|
|
36
|
+
else if (entry.isFile() && entry.name.endsWith('.jsonl') && entry.name !== 'skill-injections.jsonl')
|
|
37
|
+
files.push(path);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
walk(root, 0);
|
|
41
|
+
// A parent's provider response owns a copy inherited by its child.
|
|
42
|
+
return files.sort((a, b) => Number((0, node_path_1.dirname)(a).endsWith('subagents')) - Number((0, node_path_1.dirname)(b).endsWith('subagents')) || a.localeCompare(b));
|
|
43
|
+
}
|
|
44
|
+
const timestamp = (value) => {
|
|
45
|
+
const at = typeof value === 'string' ? Date.parse(value) : NaN;
|
|
46
|
+
return Number.isFinite(at) ? at : null;
|
|
47
|
+
};
|
|
48
|
+
/** Retains usage and boundaries only; messages and tool inputs never enter the report. */
|
|
49
|
+
async function readSession(file, from, to, diagnostics, firstObserved) {
|
|
50
|
+
const turns = new Map();
|
|
51
|
+
const invalid = new Set();
|
|
52
|
+
let boundary, clear = false, gap = false, cwd;
|
|
53
|
+
const stream = (0, node_fs_1.createReadStream)(file, { encoding: 'utf8' });
|
|
54
|
+
const lines = (0, node_readline_1.createInterface)({ input: stream, crlfDelay: Infinity });
|
|
55
|
+
let lineNumber = 0;
|
|
56
|
+
try {
|
|
57
|
+
for await (const line of lines) {
|
|
58
|
+
lineNumber++;
|
|
59
|
+
if (!line.trim())
|
|
60
|
+
continue;
|
|
61
|
+
let raw;
|
|
62
|
+
try {
|
|
63
|
+
raw = object(JSON.parse(line));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
diagnostics.malformedLines++;
|
|
67
|
+
gap = true;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
const at = timestamp(raw.timestamp);
|
|
71
|
+
const message = object(raw.message);
|
|
72
|
+
const nativeId = message.id ?? raw.uuid;
|
|
73
|
+
const id = (0, transcript_1.providerResponseIdentity)('claude', nativeId ?? [file, lineNumber]);
|
|
74
|
+
// Fork copies may rewrite timestamps. Remember original response dates
|
|
75
|
+
// before filtering, without keeping any out-of-range message or usage.
|
|
76
|
+
if (raw.type === 'assistant' && nativeId !== undefined && at !== null)
|
|
77
|
+
firstObserved.set(id, Math.min(firstObserved.get(id) ?? at, at));
|
|
78
|
+
if (at !== null && (at < from || at > to))
|
|
79
|
+
continue;
|
|
80
|
+
if (raw.type === 'system' && raw.subtype === 'compact_boundary') {
|
|
81
|
+
const metadata = object(raw.compactMetadata);
|
|
82
|
+
if (boundary)
|
|
83
|
+
gap = true;
|
|
84
|
+
boundary = { pre: count(metadata.preTokens) ? metadata.preTokens : null,
|
|
85
|
+
trigger: metadata.trigger === 'auto' || metadata.trigger === 'manual' ? metadata.trigger : 'unknown', at };
|
|
86
|
+
if (at === null)
|
|
87
|
+
diagnostics.missingTimestamps++;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (raw.type === 'user') {
|
|
91
|
+
const content = message.content;
|
|
92
|
+
const text = typeof content === 'string' ? content : Array.isArray(content) ? content.map(item => object(item).text).filter(item => typeof item === 'string').join('\n') : '';
|
|
93
|
+
if (text.includes('<command-name>/clear</command-name>'))
|
|
94
|
+
clear = true;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (raw.type !== 'assistant' || message.model === '<synthetic>')
|
|
98
|
+
continue;
|
|
99
|
+
if (at === null) {
|
|
100
|
+
diagnostics.missingTimestamps++;
|
|
101
|
+
gap = true;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (!cwd && typeof raw.cwd === 'string')
|
|
105
|
+
cwd = raw.cwd;
|
|
106
|
+
const usage = object(message.usage);
|
|
107
|
+
// A missing category is unknown, not zero. Streaming snapshots are allowed
|
|
108
|
+
// to complete later, but an unresolved response makes its replay incomplete.
|
|
109
|
+
if (!['input_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens', 'output_tokens'].every(key => count(usage[key]))) {
|
|
110
|
+
if (!turns.has(id))
|
|
111
|
+
invalid.add(id);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
invalid.delete(id);
|
|
115
|
+
const input = usage.input_tokens, read = usage.cache_read_input_tokens;
|
|
116
|
+
const write = usage.cache_creation_input_tokens, output = usage.output_tokens;
|
|
117
|
+
if (!Number.isSafeInteger(input + read + write + output)) {
|
|
118
|
+
invalid.add(id);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (input + read + write + output === 0)
|
|
122
|
+
continue;
|
|
123
|
+
const split = object(usage.cache_creation);
|
|
124
|
+
const five = split.ephemeral_5m_input_tokens, hour = split.ephemeral_1h_input_tokens;
|
|
125
|
+
const knownSplit = count(five) && count(hour) && five + hour === write;
|
|
126
|
+
const ttl = usage.cache_ttl_seconds ?? raw.cache_ttl_seconds ?? message.cache_ttl_seconds;
|
|
127
|
+
const turn = {
|
|
128
|
+
id, sessionId: (0, node_path_1.basename)(file, '.jsonl'), host: 'claude', at,
|
|
129
|
+
...(typeof message.model === 'string' && /^[\w.:[\]/-]{1,128}$/.test(message.model) ? { model: message.model } : {}),
|
|
130
|
+
inputTokens: input, cacheReadTokens: read, cacheWriteTokens: write, outputTokens: output, contextTokens: input + read + write,
|
|
131
|
+
...(knownSplit ? { cacheWrite5mTokens: five, cacheWrite1hTokens: hour } : {}),
|
|
132
|
+
...(ttl === 300 || ttl === 3600 ? { cacheTtlSeconds: ttl } : {}),
|
|
133
|
+
signals: { afterCompaction: Boolean(boundary), firstSpawnedTurn: false }, explicitAttribution: [], uncertainties: [],
|
|
134
|
+
};
|
|
135
|
+
const previous = turns.get(id);
|
|
136
|
+
if (previous) {
|
|
137
|
+
diagnostics.duplicateResponses++;
|
|
138
|
+
previous.usage = (0, transcript_1.deduplicateTurns)([previous.usage, turn])[0];
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
turns.set(id, { usage: turn, ...(boundary ? { boundary } : {}), ...(clear ? { clear } : {}), ...(gap ? { gap } : {}) });
|
|
142
|
+
boundary = undefined;
|
|
143
|
+
clear = false;
|
|
144
|
+
gap = false;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
lines.close();
|
|
150
|
+
stream.destroy();
|
|
151
|
+
}
|
|
152
|
+
return { turns: [...turns.values()], cwd, incomplete: invalid.size + (gap ? 1 : 0) + (boundary ? 1 : 0) };
|
|
153
|
+
}
|
|
154
|
+
const totalTokens = (turn) => turn.contextTokens + turn.outputTokens;
|
|
155
|
+
const plus = (a, b) => a && b ? { min: a.min + b.min, max: a.max + b.max } : null;
|
|
156
|
+
const zero = () => ({ min: 0, max: 0 });
|
|
157
|
+
const median = (values) => {
|
|
158
|
+
const sorted = [...values].sort((a, b) => a - b), middle = Math.floor(sorted.length / 2);
|
|
159
|
+
return sorted.length % 2 ? sorted[middle] : Math.round((sorted[middle - 1] + sorted[middle]) / 2);
|
|
160
|
+
};
|
|
161
|
+
const sampleKey = (session, model) => `${session.subagent ? 'child' : 'main'}:${model ?? 'unknown'}`;
|
|
162
|
+
const measuredReset = (frame) => Boolean(frame.boundary && frame.boundary.pre !== null
|
|
163
|
+
&& frame.usage.contextTokens > 0 && frame.usage.contextTokens < frame.boundary.pre);
|
|
164
|
+
/** Keep fresh input, then cache writes, then reads when a shorter context fits.
|
|
165
|
+
* A new reset writes the new cache prefix. TTL uncertainty stays a price range. */
|
|
166
|
+
function resized(turn, context, reset) {
|
|
167
|
+
const inputTokens = Math.min(turn.inputTokens, context);
|
|
168
|
+
const cacheWriteTokens = reset ? context - inputTokens : Math.min(turn.cacheWriteTokens, context - inputTokens);
|
|
169
|
+
const cacheReadTokens = context - inputTokens - cacheWriteTokens;
|
|
170
|
+
const result = { ...turn, contextTokens: context, inputTokens, cacheWriteTokens, cacheReadTokens };
|
|
171
|
+
delete result.cacheWrite5mTokens;
|
|
172
|
+
delete result.cacheWrite1hTokens;
|
|
173
|
+
if (turn.cacheWriteTokens > 0 && turn.cacheWrite5mTokens !== undefined && turn.cacheWrite1hTokens !== undefined) {
|
|
174
|
+
result.cacheWrite5mTokens = Math.round(cacheWriteTokens * turn.cacheWrite5mTokens / turn.cacheWriteTokens);
|
|
175
|
+
result.cacheWrite1hTokens = cacheWriteTokens - result.cacheWrite5mTokens;
|
|
176
|
+
}
|
|
177
|
+
return result;
|
|
178
|
+
}
|
|
179
|
+
function simulate(session, window, pool, rates) {
|
|
180
|
+
const result = { tokens: 0, usd: zero(), compactions: 0, unavailable: [] };
|
|
181
|
+
if (session.incomplete || session.turns.some(turn => turn.gap))
|
|
182
|
+
result.unavailable.push('Missing or malformed usage interrupts a session.');
|
|
183
|
+
const local = new Map();
|
|
184
|
+
for (const frame of session.turns)
|
|
185
|
+
if (measuredReset(frame)) {
|
|
186
|
+
const key = sampleKey(session, frame.usage.model);
|
|
187
|
+
local.set(key, [...local.get(key) ?? [], frame.usage.contextTokens]);
|
|
188
|
+
}
|
|
189
|
+
const recordedCompactions = session.turns.filter(frame => frame.boundary).length;
|
|
190
|
+
const events = [];
|
|
191
|
+
let context = 0, previous;
|
|
192
|
+
const maxima = new Map();
|
|
193
|
+
for (const frame of session.turns)
|
|
194
|
+
maxima.set(frame.usage.model ?? 'unknown', Math.max(maxima.get(frame.usage.model ?? 'unknown') ?? 0, frame.usage.contextTokens, frame.boundary?.pre ?? 0));
|
|
195
|
+
const actualByModel = new Map();
|
|
196
|
+
for (const frame of session.turns) {
|
|
197
|
+
const turn = frame.usage, boundary = frame.boundary;
|
|
198
|
+
let actual = actualByModel.get(turn.model ?? 'unknown');
|
|
199
|
+
if (!actual) {
|
|
200
|
+
actual = (0, compact_settings_1.resolveCompactWindow)(turn.model, session.settings, maxima.get(turn.model ?? 'unknown'));
|
|
201
|
+
actualByModel.set(turn.model ?? 'unknown', actual);
|
|
202
|
+
}
|
|
203
|
+
const threshold = window === null ? actual.tokens : Math.min(window, actual.modelContextTokens);
|
|
204
|
+
let reset = false;
|
|
205
|
+
if (frame.clear || boundary?.trigger === 'manual') {
|
|
206
|
+
// The setting cannot remove the person's explicit reset.
|
|
207
|
+
context = turn.contextTokens;
|
|
208
|
+
if (boundary) {
|
|
209
|
+
result.compactions++;
|
|
210
|
+
reset = true;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
if (boundary && boundary.pre === null)
|
|
215
|
+
result.unavailable.push('A compaction has no recorded preTokens measurement.');
|
|
216
|
+
const observed = boundary?.pre ?? turn.contextTokens;
|
|
217
|
+
context = previous ? Math.max(0, context + observed - previous.contextTokens) : observed;
|
|
218
|
+
if (actual.enabled && context >= threshold) {
|
|
219
|
+
const key = sampleKey(session, turn.model), samples = local.get(key) ?? pool.get(key);
|
|
220
|
+
if (!samples?.length)
|
|
221
|
+
result.unavailable.push('No measured post-compaction size for a window crossing.');
|
|
222
|
+
else {
|
|
223
|
+
const post = median(samples);
|
|
224
|
+
if (post >= threshold)
|
|
225
|
+
result.unavailable.push('Measured post-compaction context does not fit this window.');
|
|
226
|
+
else {
|
|
227
|
+
events.push({ turn, pre: context, post });
|
|
228
|
+
context = post;
|
|
229
|
+
result.compactions++;
|
|
230
|
+
reset = true;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const usage = resized(turn, context, reset);
|
|
236
|
+
result.tokens += totalTokens(usage);
|
|
237
|
+
result.usd = plus(result.usd, (0, pricing_1.priceTurn)(usage, rates).usd);
|
|
238
|
+
previous = turn;
|
|
239
|
+
}
|
|
240
|
+
// Recorded usage does not reliably identify the summary API requests. Credit
|
|
241
|
+
// none when fewer occur. For extra ones, charge a full uncached read plus the
|
|
242
|
+
// measured post-reset context as summary output: a conservative estimate,
|
|
243
|
+
// deliberately not a claim that summary output is recorded in the transcript.
|
|
244
|
+
const extra = Math.max(0, result.compactions - recordedCompactions);
|
|
245
|
+
for (const event of extra ? events.slice(-extra) : []) {
|
|
246
|
+
const summary = { ...event.turn, contextTokens: event.pre, inputTokens: event.pre,
|
|
247
|
+
cacheReadTokens: 0, cacheWriteTokens: 0, cacheWrite5mTokens: 0, cacheWrite1hTokens: 0, outputTokens: event.post };
|
|
248
|
+
result.tokens += totalTokens(summary);
|
|
249
|
+
result.usd = plus(result.usd, (0, pricing_1.priceTurn)(summary, rates).usd);
|
|
250
|
+
}
|
|
251
|
+
return result;
|
|
252
|
+
}
|
|
253
|
+
/** Pure numerical replay. No observed reset is forced into the automatic backtest. */
|
|
254
|
+
function compactReplay(sessions, options) {
|
|
255
|
+
const { days, now } = options, rates = options.rates ?? {};
|
|
256
|
+
const diagnostics = options.diagnostics ?? { unreadableFiles: 0, incompleteResponses: 0, duplicateResponses: 0, missingTimestamps: 0, malformedLines: 0 };
|
|
257
|
+
const pool = new Map(), settings = new Map();
|
|
258
|
+
let recordedTokens = 0, recordedUsd = zero(), recordedCompactions = 0, responses = 0;
|
|
259
|
+
for (const session of sessions) {
|
|
260
|
+
const maxima = new Map();
|
|
261
|
+
for (const frame of session.turns)
|
|
262
|
+
maxima.set(frame.usage.model ?? 'unknown', Math.max(maxima.get(frame.usage.model ?? 'unknown') ?? 0, frame.usage.contextTokens, frame.boundary?.pre ?? 0));
|
|
263
|
+
const models = new Set();
|
|
264
|
+
for (const frame of session.turns) {
|
|
265
|
+
const turn = frame.usage;
|
|
266
|
+
recordedTokens += totalTokens(turn);
|
|
267
|
+
recordedUsd = plus(recordedUsd, (0, pricing_1.priceTurn)(turn, rates).usd);
|
|
268
|
+
responses++;
|
|
269
|
+
if (!models.has(turn.model ?? 'unknown')) {
|
|
270
|
+
const actual = { ...(0, compact_settings_1.resolveCompactWindow)(turn.model, session.settings, maxima.get(turn.model ?? 'unknown')), model: turn.model ?? 'unknown' };
|
|
271
|
+
settings.set(JSON.stringify(actual), actual);
|
|
272
|
+
models.add(turn.model ?? 'unknown');
|
|
273
|
+
}
|
|
274
|
+
if (frame.boundary) {
|
|
275
|
+
recordedCompactions++;
|
|
276
|
+
const key = sampleKey(session, turn.model);
|
|
277
|
+
if (measuredReset(frame))
|
|
278
|
+
pool.set(key, [...pool.get(key) ?? [], turn.contextTokens]);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
const values = [...settings.values()], actualWindows = [...new Set(values.map(value => value.tokens))];
|
|
283
|
+
const baselineWindow = actualWindows.length === 1 ? actualWindows[0] : null;
|
|
284
|
+
const windowLabel = (window) => window === 1_000_000 ? '1M' : `${window / 1000}K`;
|
|
285
|
+
const targets = [null, ...WINDOWS.filter(window => window !== baselineWindow)];
|
|
286
|
+
const windows = targets.map(window => {
|
|
287
|
+
let tokens = 0, usd = zero(), compactions = 0;
|
|
288
|
+
const unavailable = new Set();
|
|
289
|
+
for (const session of sessions) {
|
|
290
|
+
const result = simulate(session, window, pool, rates);
|
|
291
|
+
tokens += result.tokens;
|
|
292
|
+
usd = plus(usd, result.usd);
|
|
293
|
+
compactions += result.compactions;
|
|
294
|
+
result.unavailable.forEach(reason => unavailable.add(reason));
|
|
295
|
+
}
|
|
296
|
+
if (!responses)
|
|
297
|
+
unavailable.add('No complete Claude Code usage in this date range.');
|
|
298
|
+
return { window: window ?? baselineWindow, label: window === null ? `${baselineWindow ? windowLabel(baselineWindow) : 'Mixed'} current` : windowLabel(window), current: window === null,
|
|
299
|
+
tokens: unavailable.size ? null : tokens, usd: unavailable.size ? null : usd, compactions: unavailable.size ? null : compactions,
|
|
300
|
+
extraCompactions: null, tokensSaved: null, usdSaved: null, tokenChangePercent: null, usdChangePercent: null, unavailable: [...unavailable] };
|
|
301
|
+
});
|
|
302
|
+
const baseline = windows[0];
|
|
303
|
+
for (const row of windows) {
|
|
304
|
+
if (row.tokens !== null && baseline.tokens !== null) {
|
|
305
|
+
row.tokensSaved = baseline.tokens - row.tokens;
|
|
306
|
+
row.tokenChangePercent = baseline.tokens ? (row.tokens - baseline.tokens) / baseline.tokens * 100 : 0;
|
|
307
|
+
}
|
|
308
|
+
if (row.compactions !== null && baseline.compactions !== null)
|
|
309
|
+
row.extraCompactions = row.compactions - baseline.compactions;
|
|
310
|
+
if (row.usd && baseline.usd) {
|
|
311
|
+
row.usdSaved = row.current ? zero() : { min: baseline.usd.min - row.usd.max, max: baseline.usd.max - row.usd.min };
|
|
312
|
+
const base = (baseline.usd.min + baseline.usd.max) / 2, next = (row.usd.min + row.usd.max) / 2;
|
|
313
|
+
row.usdChangePercent = base ? (next - base) / base * 100 : null;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
const errorTokens = baseline.tokens === null ? null : baseline.tokens - recordedTokens;
|
|
317
|
+
const errorPercent = errorTokens === null || !recordedTokens ? null : Math.abs(errorTokens) / recordedTokens * 100;
|
|
318
|
+
const complete = !diagnostics.unreadableFiles && !diagnostics.incompleteResponses && !diagnostics.missingTimestamps && !diagnostics.malformedLines && baseline.tokens !== null;
|
|
319
|
+
const unreliable = errorPercent !== null && errorPercent > 10;
|
|
320
|
+
const warnings = [...new Set(sessions.flatMap(session => session.settings.warnings))];
|
|
321
|
+
const candidates = windows.filter(row => !row.current && row.window !== null
|
|
322
|
+
&& row.window >= compact_settings_1.MIN_COMPACT_WINDOW && row.window <= compact_settings_1.MAX_COMPACT_WINDOW
|
|
323
|
+
&& values.every(value => value.commandCanApply && row.window < value.tokens)
|
|
324
|
+
&& row.extraCompactions !== null && row.extraCompactions < 2 * recordedCompactions
|
|
325
|
+
&& (row.tokensSaved ?? 0) > 0 && (row.usdSaved?.min ?? 0) > 0);
|
|
326
|
+
// Choose the smallest qualifying window, with a strict limit on extra resets.
|
|
327
|
+
candidates.sort((a, b) => a.window - b.window);
|
|
328
|
+
const pick = !unreliable && complete && !warnings.length ? candidates[0] : undefined;
|
|
329
|
+
const suggestion = pick ? { window: pick.window, command: `/autocompact ${pick.window / 1000}k` } : null;
|
|
330
|
+
const band = errorPercent === null ? 'unavailable' : `${errorPercent.toFixed(1)}%`;
|
|
331
|
+
const caveat = `Caveat: backtest error band ${band} against recorded tokens at the current window${unreliable ? '; replay is unreliable for this machine' : ''}${!complete ? '; incomplete evidence, no recommendation' : ''}. This is measured replay error, not a statistical confidence interval; task quality and future output can change.`;
|
|
332
|
+
const notes = [
|
|
333
|
+
'Savings compare each simulation with the current-window replay. Tokens include input, cache reads, cache writes and output.',
|
|
334
|
+
`The suggestion is the smallest tested window within 100K to 1M with positive savings and extra compactions strictly below twice the recorded current count (${recordedCompactions}). The full table lets you choose.`,
|
|
335
|
+
'Post-compaction sizes use the median measured next-request context, first in that transcript, otherwise from the same model and main or sub-agent role in this date range.',
|
|
336
|
+
'Extra summaries conservatively cost a full uncached context read plus the measured reset size as output. Fewer summaries receive no credit. New resets rewrite the cache; ordinary output stays fixed.',
|
|
337
|
+
'Current saved settings are applied to this history. Past launch flags, remote managed policy, host safety buffers and changes to settings during a session are not reconstructed. Partial sessions start at their first recorded context in the date range.',
|
|
338
|
+
...(values.some(value => value.assumed) ? ['The tuned default is not recorded as a setting; the model window is assumed for rows without an explicit value.'] : []),
|
|
339
|
+
...(values.some(value => !value.commandCanApply) ? ['Automatic compaction is disabled or an override prevents the saved slash command from applying; no apply command is suggested.'] : []),
|
|
340
|
+
...warnings,
|
|
341
|
+
...[...new Set(windows.flatMap(row => row.unavailable))],
|
|
342
|
+
];
|
|
343
|
+
return { version: version_1.BURN_VERSION, days, from: new Date(now - days * DAY).toISOString(), to: new Date(now).toISOString(), basis: 'API list equivalent',
|
|
344
|
+
sessions: sessions.filter(session => !session.subagent).length, subagentTranscripts: sessions.filter(session => session.subagent).length,
|
|
345
|
+
responses, measuredCompactions: [...pool.values()].reduce((sum, sizes) => sum + sizes.length, 0),
|
|
346
|
+
recorded: { tokens: recordedTokens, usd: recordedUsd, compactions: recordedCompactions }, settings: values, windows,
|
|
347
|
+
backtest: { replayTokens: baseline.tokens, recordedTokens, errorTokens, errorPercent, unreliable, complete }, suggestion, diagnostics, caveat, notes, settingSource: compact_settings_1.COMPACT_SETTING_SOURCE };
|
|
348
|
+
}
|
|
349
|
+
async function collectCompactReplay(options = {}) {
|
|
350
|
+
const days = options.days ?? 7, now = options.now ?? Date.now();
|
|
351
|
+
if (!Number.isSafeInteger(days) || days < 1 || days > 3650)
|
|
352
|
+
throw new Error('Days must be a whole number from 1 to 3650.');
|
|
353
|
+
if (!Number.isFinite(now) || now - days * DAY < 0)
|
|
354
|
+
throw new Error('Invalid replay date range.');
|
|
355
|
+
const env = options.env ?? process.env;
|
|
356
|
+
const configDir = options.configDir ?? (env.CLAUDE_CONFIG_DIR || (0, node_path_1.join)((0, node_os_1.homedir)(), '.claude'));
|
|
357
|
+
const diagnostics = { unreadableFiles: 0, incompleteResponses: 0, duplicateResponses: 0, missingTimestamps: 0, malformedLines: 0 };
|
|
358
|
+
const sessions = [], ownership = new Map();
|
|
359
|
+
const firstObserved = new Map();
|
|
360
|
+
const settingsCache = new Map();
|
|
361
|
+
for (const file of transcriptFiles((0, node_path_1.join)(configDir, 'projects'))) {
|
|
362
|
+
let parsed;
|
|
363
|
+
try {
|
|
364
|
+
parsed = await readSession(file, now - days * DAY, now, diagnostics, firstObserved);
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
diagnostics.unreadableFiles++;
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
diagnostics.incompleteResponses += parsed.incomplete;
|
|
371
|
+
const turns = parsed.turns.filter(frame => {
|
|
372
|
+
const previous = ownership.get(frame.usage.id);
|
|
373
|
+
if (!previous) {
|
|
374
|
+
ownership.set(frame.usage.id, frame);
|
|
375
|
+
return true;
|
|
376
|
+
}
|
|
377
|
+
previous.usage = (0, transcript_1.deduplicateTurns)([previous.usage, frame.usage])[0];
|
|
378
|
+
diagnostics.duplicateResponses++;
|
|
379
|
+
return false;
|
|
380
|
+
});
|
|
381
|
+
if (!turns.length && !parsed.incomplete)
|
|
382
|
+
continue;
|
|
383
|
+
const cwd = parsed.cwd ?? options.cwd ?? process.cwd();
|
|
384
|
+
let settings = options.settings ?? settingsCache.get(cwd);
|
|
385
|
+
if (!settings) {
|
|
386
|
+
settings = (0, compact_settings_1.readCompactSettings)({ configDir, cwd, env });
|
|
387
|
+
settingsCache.set(cwd, settings);
|
|
388
|
+
}
|
|
389
|
+
sessions.push({ id: (0, node_path_1.basename)(file, '.jsonl'), subagent: (0, node_path_1.dirname)(file).endsWith('subagents') || (0, node_path_1.basename)(file).startsWith('agent-'), turns, settings, incomplete: parsed.incomplete });
|
|
390
|
+
}
|
|
391
|
+
for (const session of sessions)
|
|
392
|
+
session.turns = session.turns.filter(frame => (firstObserved.get(frame.usage.id) ?? now) >= now - days * DAY)
|
|
393
|
+
.sort((a, b) => a.usage.at - b.usage.at);
|
|
394
|
+
return compactReplay(sessions.filter(session => session.turns.length || session.incomplete), { days, now, rates: options.rates, diagnostics });
|
|
395
|
+
}
|
|
396
|
+
function renderCompactReplay(report) {
|
|
397
|
+
const n = (value) => value === null ? 'unavailable' : value.toLocaleString('en-US');
|
|
398
|
+
const percent = (value) => value === null ? 'n/a' : `${value > 0 ? '+' : ''}${value.toFixed(1)}%`;
|
|
399
|
+
const rows = report.windows.map(row => [row.label, n(row.tokensSaved), (0, live_1.dollars)(row.usdSaved), n(row.extraCompactions), percent(row.tokenChangePercent)]);
|
|
400
|
+
const header = ['Window', 'Tokens saved', 'USD saved', 'Extra compactions', 'Token change'];
|
|
401
|
+
const widths = header.map((label, index) => Math.max(label.length, ...rows.map(row => row[index].length)));
|
|
402
|
+
const table = [header, ...rows].map(row => row.map((cell, index) => cell.padEnd(widths[index])).join(' ').trimEnd()).join('\n');
|
|
403
|
+
return [
|
|
404
|
+
`Burn ${version_1.BURN_VERSION} | AgentGuard compact-replay: last ${report.days} days`,
|
|
405
|
+
`${report.sessions} session${report.sessions === 1 ? '' : 's'}, ${report.subagentTranscripts} sub-agent transcripts, ${report.responses} responses; ${report.measuredCompactions} measured compactions.`,
|
|
406
|
+
`Recorded: ${n(report.recorded.tokens)} tokens, ${(0, live_1.dollars)(report.recorded.usd)} API list equivalent. All dollars below are API list equivalent, not a bill.`,
|
|
407
|
+
'', table, report.caveat,
|
|
408
|
+
`Backtest: ${n(report.backtest.replayTokens)} replay tokens versus ${n(report.backtest.recordedTokens)} recorded; difference ${n(report.backtest.errorTokens)} tokens.`,
|
|
409
|
+
...report.settings.map(value => `Current ${value.model}: ${n(value.tokens)} tokens (${value.source}${value.assumed ? ', assumed' : ''}).`),
|
|
410
|
+
'', ...report.notes,
|
|
411
|
+
report.suggestion ? `To try the suggested window, type this in Claude Code for each model you want to change: ${report.suggestion.command}`
|
|
412
|
+
: 'No smaller window is supported by this replay. Check your current window in Claude Code: /autocompact',
|
|
413
|
+
].join('\n');
|
|
414
|
+
}
|