@agentguard-run/burn 0.3.17 → 0.3.19

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.
@@ -16,11 +16,13 @@
16
16
  * as little as possible.
17
17
  */
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.loadPolicy = void 0;
19
+ exports.AGENT_OVERRIDE_REASON = exports.loadPolicy = void 0;
20
20
  exports.inflateHookSession = inflateHookSession;
21
21
  exports.findingSignature = findingSignature;
22
22
  exports.refreshSession = refreshSession;
23
23
  exports.handlePreToolUse = handlePreToolUse;
24
+ exports.asksPerson = asksPerson;
25
+ exports.agentOverrideAttempt = agentOverrideAttempt;
24
26
  exports.settingsSnippet = settingsSnippet;
25
27
  const node_crypto_1 = require("node:crypto");
26
28
  const events_1 = require("../events");
@@ -36,6 +38,8 @@ const policy_1 = require("../policy");
36
38
  const override_1 = require("../override");
37
39
  const recording_1 = require("../recording");
38
40
  const render_1 = require("../replay/render");
41
+ const stop_text_1 = require("../stop-text");
42
+ const node_os_1 = require("node:os");
39
43
  const live_1 = require("../insights/live");
40
44
  const hook_1 = require("../idle/hook");
41
45
  const SPAWN_TOOLS = new Set(['Agent', 'Task']);
@@ -165,6 +169,15 @@ function handlePreToolUse(input, home, now = Date.now()) {
165
169
  const warning = (0, hook_1.sessionStartWarning)(home, (0, policy_1.loadPolicy)(home), now);
166
170
  return warning ? { continue: true, suppressOutput: false, systemMessage: warning } : { continue: true, suppressOutput: true };
167
171
  }
172
+ const attempt = agentOverrideAttempt(input, home);
173
+ if (attempt) {
174
+ const policy = (0, policy_1.loadPolicy)(home);
175
+ if (policy.mode === 'enforce') {
176
+ recordDecision(home, { host: 'claude-code', action: 'override_attempt', at: now, sessionId: input.session_id ?? null,
177
+ toolUseId: input.tool_use_id ?? null, tool: input.tool_name ?? null, target: attempt, verdict: 'STOP', enforced: true });
178
+ return deny(exports.AGENT_OVERRIDE_REASON);
179
+ }
180
+ }
168
181
  const observation = (0, live_1.observeTool)(home, input, 'claude', (0, policy_1.loadPolicy)(home), now);
169
182
  const output = handleSpawnPreToolUse(input, home, now);
170
183
  if (!observation.messages.length)
@@ -195,6 +208,8 @@ function handleSpawnPreToolUse(input, home, now) {
195
208
  // The audited override: only consulted when a block is about to happen.
196
209
  const override = shouldDeny && policy.mode === 'enforce' ? (0, override_1.consumeOverride)(home, now) : null;
197
210
  const blocked = policy.mode === 'enforce' && shouldDeny && !override;
211
+ // Held behind Claude Code's own prompt, which only the person can answer.
212
+ const asked = blocked && asksPerson(input, policy);
198
213
  const verdict = shouldDeny ? 'STOP' : report.verdict;
199
214
  const raw = JSON.parse((0, node_fs_1.readFileSync)(sessionFile(home, input.session_id), 'utf8'));
200
215
  const receipt = signer.sign({
@@ -204,7 +219,7 @@ function handleSpawnPreToolUse(input, home, now) {
204
219
  measured: { sessionTokens: state.totalTokens, sessionSpawns: reservation.effectiveSpawns,
205
220
  proposedDepth, inFlight: 0, occupiedMs: 0 },
206
221
  coverage: events_1.CAPABILITIES['claude-code'], verdict, blocked,
207
- reasons: [...report.findings.map((f) => `${f.detector}:${f.verdict}`), ...(!reservation.allowed ? ['fanout:STOP'] : [])],
222
+ reasons: [...report.findings.map((f) => `${f.detector}:${f.verdict}`), ...(!reservation.allowed ? ['fanout:STOP'] : []), ...(asked ? ['decision:ask'] : [])],
208
223
  previous: raw.lastReceipt ?? null,
209
224
  });
210
225
  store.assertHeld();
@@ -218,6 +233,8 @@ function handleSpawnPreToolUse(input, home, now) {
218
233
  verdict,
219
234
  wouldDeny: shouldDeny,
220
235
  enforced: policy.mode === 'enforce' && shouldDeny && !override,
236
+ asked: asked || undefined,
237
+ permissionMode: input.permission_mode ?? null,
221
238
  overridden: override ? { once: override.once, reason: override.reason } : undefined,
222
239
  mode: policy.mode,
223
240
  findings: report.findings.map((f) => ({ detector: f.detector, verdict: f.verdict, observed: f.observed, threshold: f.threshold })),
@@ -227,14 +244,15 @@ function handleSpawnPreToolUse(input, home, now) {
227
244
  });
228
245
  if (shouldDeny && policy.mode === 'enforce') {
229
246
  if (!override) {
230
- (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'blocked' });
247
+ if (asked) {
248
+ (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'asked', host: 'claude-code' });
249
+ return ask((0, stop_text_1.askReason)(report));
250
+ }
251
+ (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'blocked', host: 'claude-code' });
231
252
  return deny(reason);
232
253
  }
233
- (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'overridden' });
234
- return {
235
- continue: true,
236
- systemMessage: `AgentGuard STOP overridden${override.once ? ' once' : ''} ("${override.reason}"): ${report.findings[0]?.summary ?? ''}`,
237
- };
254
+ (0, recording_1.recordFrame)({ kind: 'report', report, outcome: 'overridden', host: 'claude-code' });
255
+ return { continue: true, systemMessage: (0, stop_text_1.overriddenLine)(report, override) };
238
256
  }
239
257
  if (report.verdict !== 'OK') {
240
258
  const signature = findingSignature(report);
@@ -242,10 +260,7 @@ function handleSpawnPreToolUse(input, home, now) {
242
260
  return { continue: true, suppressOutput: true };
243
261
  rememberNotified(home, input.session_id, signature);
244
262
  (0, recording_1.recordFrame)({ kind: 'report', report, outcome: policy.mode === 'shadow' && shouldDeny ? 'shadow' : 'allowed' });
245
- return {
246
- continue: true,
247
- systemMessage: `AgentGuard ${report.verdict}${policy.mode === 'shadow' && shouldDeny ? ' (shadow: would have blocked)' : ''}: ${report.findings[0]?.summary ?? ''}`,
248
- };
263
+ return { continue: true, systemMessage: warnLine(report, policy, input, shouldDeny) };
249
264
  }
250
265
  if (notified)
251
266
  rememberNotified(home, input.session_id, '');
@@ -264,7 +279,63 @@ function buildDenyReason(report, _reservation) {
264
279
  // sentence reads as a log line. Colour is off: the host decides rendering.
265
280
  // Claude trims leading whitespace before adding Error:. A zero-width word
266
281
  // joiner preserves the blank first line, keeping that prefix off the frame.
267
- return '\u2060\n' + (0, render_1.renderStop)(report, { colour: false });
282
+ return '\u2060\n' + (0, render_1.renderStop)(report, { colour: false, host: 'claude-code' });
283
+ }
284
+ const ASK_MODES = new Set(['default', 'acceptEdits', 'auto', 'plan']);
285
+ /**
286
+ * Claude Code turns a hook's "ask" into a real permission prompt in these
287
+ * modes, and since v2.1.211 auto mode's classifier cannot approve it
288
+ * silently. bypassPermissions skips prompts, dontAsk denies them and print
289
+ * mode has nobody to ask, so those keep the hard refusal.
290
+ */
291
+ function asksPerson(input, policy) {
292
+ return (policy.stopStyle ?? 'ask') === 'ask' && typeof input.permission_mode === 'string' && ASK_MODES.has(input.permission_mode);
293
+ }
294
+ const WARN_CONSEQUENCE = new Set(['spawn_rate', 'fanout', 'sustained_burn']);
295
+ function warnLine(report, policy, input, shouldDeny) {
296
+ const shadow = policy.mode === 'shadow' && shouldDeny ? ' (shadow: would have refused)' : '';
297
+ const warn = report.verdict === 'WARN' ? report.findings.find((f) => f.verdict === 'WARN') : undefined;
298
+ const consequence = policy.mode === 'enforce' && warn && WARN_CONSEQUENCE.has(warn.detector)
299
+ ? (asksPerson(input, policy) ? ' Past the limit, the next launch waits for your yes.' : ' Past the limit, the next launch is refused.')
300
+ : '';
301
+ return `AgentGuard ${report.verdict}${shadow}: ${(0, stop_text_1.primarySummary)(report)}${consequence}`;
302
+ }
303
+ /** What Claude is told when it tries to override AgentGuard itself. */
304
+ exports.AGENT_OVERRIDE_REASON = `AgentGuard: overrides come from the person, not the agent. Ask them to type it themselves in Claude Code, with ! in front:\n! ${stop_text_1.OVERRIDE_COMMAND}`;
305
+ const OVERRIDE_VERB = /(?:@agentguard-run\/burn|agentguard-burn)\S*\s+(?:resume|shadow|calibrate)\b/;
306
+ const STATE_FILE = /\.agentguard[\\/](?:override|burn-policy)\.json\b/;
307
+ /**
308
+ * An agent's own attempt to lift a STOP: running `resume`, `shadow` or
309
+ * `calibrate` (which writes a shadow policy), or writing the override or
310
+ * policy file. A person's `!` command in Claude Code never reaches a hook, so
311
+ * refusing these here never blocks the person. Returns what was targeted.
312
+ */
313
+ function agentOverrideAttempt(input, home) {
314
+ const tool = input.tool_name ?? '';
315
+ const args = input.tool_input ?? {};
316
+ const own = (path) => {
317
+ const full = (0, node_path_1.resolve)(path.replace(/^~(?=$|[\\/])/, (0, node_os_1.homedir)()));
318
+ return full === (0, node_path_1.resolve)(home, 'override.json') || full === (0, node_path_1.resolve)(home, 'burn-policy.json');
319
+ };
320
+ if (tool === 'Bash' || tool === 'PowerShell') {
321
+ const command = typeof args.command === 'string' ? args.command : '';
322
+ if (OVERRIDE_VERB.test(command) || STATE_FILE.test(command)
323
+ || command.includes((0, node_path_1.resolve)(home, 'override.json')) || command.includes((0, node_path_1.resolve)(home, 'burn-policy.json')))
324
+ return 'command';
325
+ return null;
326
+ }
327
+ if (tool === 'Write' || tool === 'Edit' || tool === 'MultiEdit' || tool === 'NotebookEdit') {
328
+ const path = typeof args.file_path === 'string' ? args.file_path : typeof args.notebook_path === 'string' ? args.notebook_path : '';
329
+ if (path && (own(path) || STATE_FILE.test(path)))
330
+ return 'file';
331
+ }
332
+ return null;
333
+ }
334
+ function ask(reason) {
335
+ return {
336
+ continue: true,
337
+ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: reason },
338
+ };
268
339
  }
269
340
  function deny(reason) {
270
341
  return {
@@ -7,8 +7,9 @@ export { applyEvent, applyCorrection, newSessionState, windowSum, medianComplete
7
7
  export { ReservationStore, Transaction, RESERVATION_TTL_MS, type Reservation, type CallReservation, type ComputeSnapshot } from './state/reservations';
8
8
  export { replayAll, replaySession, replayEvents, discoverTranscripts, type ReplaySummary, type SessionReplay } from './replay/simulate';
9
9
  export { renderReplay, renderStop } from './replay/render';
10
+ export { askReason, continueLines, overriddenLine, primarySummary, sessionSoFar, stopSummary, OVERRIDE_COMMAND, type StopHost } from './stop-text';
10
11
  export { calibrate, type CalibrationResult } from './calibrate';
11
- export { handlePreToolUse, refreshSession, loadPolicy, settingsSnippet, type HookInput, type HookOutput } from './hook/pre-tool-use';
12
+ export { handlePreToolUse, refreshSession, loadPolicy, settingsSnippet, asksPerson, agentOverrideAttempt, AGENT_OVERRIDE_REASON, type HookInput, type HookOutput } from './hook/pre-tool-use';
12
13
  export * from './events';
13
14
  export { Gateway, mergeCapabilities, type Decision, type GatewaySessionView, type UsageCoverage, type GatewayOptions } from './gateway';
14
15
  export { ReceiptSigner, verifyReceipt, receiptDigest, canonical, sha256, type ReceiptPayload, type SignedReceipt } from './receipt';
package/dist/src/index.js CHANGED
@@ -14,8 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.UsageObserver = exports.profileFor = exports.startProxy = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.settingsSnippet = exports.loadPolicy = exports.refreshSession = exports.handlePreToolUse = exports.calibrate = exports.renderStop = exports.renderReplay = exports.discoverTranscripts = exports.replayEvents = exports.replaySession = exports.replayAll = exports.RESERVATION_TTL_MS = exports.Transaction = exports.ReservationStore = exports.cacheReadRatio = exports.medianCompletedMinute = exports.windowSum = exports.newSessionState = exports.applyCorrection = exports.applyEvent = exports.normaliseLine = exports.newCursor = exports.readAll = exports.readIncremental = exports.evaluateLocalCompute = exports.fmt = exports.evaluate = exports.CALL_RESERVATION_TTL_MS = exports.DEFAULT_LOCAL_COMPUTE = exports.DEFAULT_THRESHOLDS = exports.DEFAULT_POLICY = void 0;
18
- exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = void 0;
17
+ exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = exports.agentOverrideAttempt = exports.asksPerson = exports.settingsSnippet = exports.loadPolicy = exports.refreshSession = exports.handlePreToolUse = exports.calibrate = exports.OVERRIDE_COMMAND = exports.stopSummary = exports.sessionSoFar = exports.primarySummary = exports.overriddenLine = exports.continueLines = exports.askReason = exports.renderStop = exports.renderReplay = exports.discoverTranscripts = exports.replayEvents = exports.replaySession = exports.replayAll = exports.RESERVATION_TTL_MS = exports.Transaction = exports.ReservationStore = exports.cacheReadRatio = exports.medianCompletedMinute = exports.windowSum = exports.newSessionState = exports.applyCorrection = exports.applyEvent = exports.normaliseLine = exports.newCursor = exports.readAll = exports.readIncremental = exports.evaluateLocalCompute = exports.fmt = exports.evaluate = exports.CALL_RESERVATION_TTL_MS = exports.DEFAULT_LOCAL_COMPUTE = exports.DEFAULT_THRESHOLDS = exports.DEFAULT_POLICY = void 0;
18
+ exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = exports.UsageObserver = exports.profileFor = exports.startProxy = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = void 0;
19
19
  __exportStar(require("./types"), exports);
20
20
  var defaults_1 = require("./defaults");
21
21
  Object.defineProperty(exports, "DEFAULT_POLICY", { enumerable: true, get: function () { return defaults_1.DEFAULT_POLICY; } });
@@ -51,6 +51,14 @@ Object.defineProperty(exports, "discoverTranscripts", { enumerable: true, get: f
51
51
  var render_1 = require("./replay/render");
52
52
  Object.defineProperty(exports, "renderReplay", { enumerable: true, get: function () { return render_1.renderReplay; } });
53
53
  Object.defineProperty(exports, "renderStop", { enumerable: true, get: function () { return render_1.renderStop; } });
54
+ var stop_text_1 = require("./stop-text");
55
+ Object.defineProperty(exports, "askReason", { enumerable: true, get: function () { return stop_text_1.askReason; } });
56
+ Object.defineProperty(exports, "continueLines", { enumerable: true, get: function () { return stop_text_1.continueLines; } });
57
+ Object.defineProperty(exports, "overriddenLine", { enumerable: true, get: function () { return stop_text_1.overriddenLine; } });
58
+ Object.defineProperty(exports, "primarySummary", { enumerable: true, get: function () { return stop_text_1.primarySummary; } });
59
+ Object.defineProperty(exports, "sessionSoFar", { enumerable: true, get: function () { return stop_text_1.sessionSoFar; } });
60
+ Object.defineProperty(exports, "stopSummary", { enumerable: true, get: function () { return stop_text_1.stopSummary; } });
61
+ Object.defineProperty(exports, "OVERRIDE_COMMAND", { enumerable: true, get: function () { return stop_text_1.OVERRIDE_COMMAND; } });
54
62
  var calibrate_1 = require("./calibrate");
55
63
  Object.defineProperty(exports, "calibrate", { enumerable: true, get: function () { return calibrate_1.calibrate; } });
56
64
  var pre_tool_use_1 = require("./hook/pre-tool-use");
@@ -58,6 +66,9 @@ Object.defineProperty(exports, "handlePreToolUse", { enumerable: true, get: func
58
66
  Object.defineProperty(exports, "refreshSession", { enumerable: true, get: function () { return pre_tool_use_1.refreshSession; } });
59
67
  Object.defineProperty(exports, "loadPolicy", { enumerable: true, get: function () { return pre_tool_use_1.loadPolicy; } });
60
68
  Object.defineProperty(exports, "settingsSnippet", { enumerable: true, get: function () { return pre_tool_use_1.settingsSnippet; } });
69
+ Object.defineProperty(exports, "asksPerson", { enumerable: true, get: function () { return pre_tool_use_1.asksPerson; } });
70
+ Object.defineProperty(exports, "agentOverrideAttempt", { enumerable: true, get: function () { return pre_tool_use_1.agentOverrideAttempt; } });
71
+ Object.defineProperty(exports, "AGENT_OVERRIDE_REASON", { enumerable: true, get: function () { return pre_tool_use_1.AGENT_OVERRIDE_REASON; } });
61
72
  // Cross-tool layer (0.2.0)
62
73
  __exportStar(require("./events"), exports);
63
74
  var gateway_1 = require("./gateway");
@@ -0,0 +1,104 @@
1
+ import type { DollarRange, PricingTable } from './pricing';
2
+ import { type TranscriptLocation, type TranscriptOrigin } from './sessions';
3
+ import { type CompareMetric, type InsightHost, type InsightTranscript } from './types';
4
+ import { type WhyLang } from './i18n';
5
+ export interface CompareMetrics {
6
+ assistantResponses: number | null;
7
+ /** Cache reads plus cache writes plus fresh input. */
8
+ inputTokens: number | null;
9
+ cacheReadTokens: number | null;
10
+ cacheWriteTokens: number | null;
11
+ freshInputTokens: number | null;
12
+ /** Cache reads divided by all input, 0 to 1; 0 without input, as `why` prints a share of nothing. */
13
+ cacheShare: number | null;
14
+ outputTokens: number | null;
15
+ /** Agent, Task and spawn_agent calls in the session and its children: the spawns `why` counts. */
16
+ subagentsLaunched: number | null;
17
+ fullPrefixRewrites: number | null;
18
+ /** The API list equivalent `why` prints; null when a model is unpriced or usage is unavailable. */
19
+ usd: DollarRange | null;
20
+ }
21
+ export interface CompareModel {
22
+ /** Null when responses carry no model id. */
23
+ model: string | null;
24
+ responses: number;
25
+ outputTokens: number;
26
+ /** Share of the session's output tokens, 0 to 1; null when the session has no output tokens. */
27
+ share: number | null;
28
+ }
29
+ export interface CompareSession {
30
+ sessionId: string;
31
+ /** The last dash-separated part of the id: short, and accepted back as an id suffix. */
32
+ shortId: string;
33
+ host: InsightHost;
34
+ /** The transcript file. */
35
+ path: string;
36
+ /** The working directory the transcript recorded, else Claude Code's project directory; null when neither is known. */
37
+ project: string | null;
38
+ /** The earliest recorded response of the session itself (its children when it has none), ISO 8601 UTC. */
39
+ startedAt: string | null;
40
+ /** The model with the most output tokens; null without responses or when they carry no model id. */
41
+ dominantModel: string | null;
42
+ /** Every model, most output tokens first, children included. */
43
+ models: CompareModel[];
44
+ /** False when inherited Codex history has no verifiable boundary; every metric is then null, as `why` prints nothing. */
45
+ usageAvailable: boolean;
46
+ /** Models without a verified rate for at least one token category; null is a missing model id. */
47
+ unpricedModels: Array<string | null>;
48
+ metrics: CompareMetrics;
49
+ }
50
+ export interface CompareReport {
51
+ a: CompareSession;
52
+ b: CompareSession;
53
+ /** (B minus A) divided by A, unrounded; null unless both are numbers and A is not zero as printed. A dollar range compares midpoints. */
54
+ change: Record<CompareMetric, number | null>;
55
+ subagentsIncluded: true;
56
+ basis: 'estimated_api_list_price';
57
+ }
58
+ /** The last dash-separated part of a session id, which `why` and `compare` accept back as an id suffix. */
59
+ export declare const shortId: (sessionId: string) => string;
60
+ /** One session's figures. `origin` supplies the recorded working directory; without it a Claude session shows its project directory. */
61
+ export declare function compareSession(location: Pick<TranscriptLocation, 'path' | 'host'>, transcript: InsightTranscript, rates?: PricingTable, origin?: TranscriptOrigin | null): CompareSession;
62
+ export declare function compareReport(a: CompareSession, b: CompareSession): CompareReport;
63
+ export type ComparePick = {
64
+ ok: true;
65
+ a: TranscriptLocation;
66
+ b: TranscriptLocation;
67
+ explicit: boolean;
68
+ } | {
69
+ ok: false;
70
+ found: 0 | 1;
71
+ project: string | null;
72
+ };
73
+ export interface ComparePickOptions {
74
+ locations?: TranscriptLocation[];
75
+ roots?: {
76
+ claude: string;
77
+ codex: string;
78
+ };
79
+ origin?: (location: TranscriptLocation) => TranscriptOrigin;
80
+ }
81
+ /**
82
+ * Two selectors: those two sessions, in that order. One: that session and the
83
+ * newest other top-level session of its project. None: the two newest top-level
84
+ * sessions of the newest one's project. Selectors resolve exactly as `why`
85
+ * resolves one (id, id suffix or JSONL path). A top-level Claude Code session is
86
+ * a transcript directly inside its project directory, never a sub-agent file or
87
+ * any other file a session keeps beside it; a Codex rollout is top-level unless
88
+ * its first records mark a spawned sub-agent, and its project is the working
89
+ * directory it recorded. The session variables `why` falls back on are not read:
90
+ * with nothing given, recency decides.
91
+ */
92
+ export declare function pickCompareSessions(selectors: string[], options?: ComparePickOptions): ComparePick;
93
+ /** Reads each picked session the way `why` reads one. Unless the order was given, A is the session that started first. */
94
+ export declare function comparePicked(pick: {
95
+ a: TranscriptLocation;
96
+ b: TranscriptLocation;
97
+ explicit: boolean;
98
+ }, rates?: PricingTable, origin?: (location: TranscriptLocation) => TranscriptOrigin): CompareReport;
99
+ /** A signed percentage with one decimal, as `why` prints shares; a change that rounds to zero has no sign. */
100
+ export declare function signedChange(change: number | null): string;
101
+ /** A difference in share, in percentage points: "+2.6 pp" reads the same in English, Spanish and Portuguese. */
102
+ export declare function signedPoints(change: number | null): string;
103
+ /** `lang` changes words only; every figure, id, model id, path and command prints as it does in English. */
104
+ export declare function renderCompare(report: CompareReport, lang?: WhyLang): string;
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.shortId = void 0;
4
+ exports.compareSession = compareSession;
5
+ exports.compareReport = compareReport;
6
+ exports.pickCompareSessions = pickCompareSessions;
7
+ exports.comparePicked = comparePicked;
8
+ exports.signedChange = signedChange;
9
+ exports.signedPoints = signedPoints;
10
+ exports.renderCompare = renderCompare;
11
+ /**
12
+ * `compare`: two sessions side by side from local transcripts, for the advice to
13
+ * run the same task on each model and compare what /usage reports, which shows
14
+ * one session at a time. Every figure is the one `why` prints for that session
15
+ * (sessionFigures), child transcripts included the way `why` includes them.
16
+ * Measurement only: the report never judges which session or model did better.
17
+ */
18
+ const node_fs_1 = require("node:fs");
19
+ const node_path_1 = require("node:path");
20
+ const live_1 = require("./live");
21
+ const render_1 = require("./render");
22
+ const sessions_1 = require("./sessions");
23
+ const transcript_1 = require("./transcript");
24
+ const types_1 = require("./types");
25
+ const i18n_1 = require("./i18n");
26
+ /** The last dash-separated part of a session id, which `why` and `compare` accept back as an id suffix. */
27
+ const shortId = (sessionId) => sessionId.slice(sessionId.lastIndexOf('-') + 1) || sessionId;
28
+ exports.shortId = shortId;
29
+ const byName = (a, b) => a === b ? 0 : a === null ? 1 : b === null ? -1 : a < b ? -1 : 1;
30
+ const earliest = (times) => times.length ? times.reduce((low, value) => Math.min(low, value)) : undefined;
31
+ /** One session's figures. `origin` supplies the recorded working directory; without it a Claude session shows its project directory. */
32
+ function compareSession(location, transcript, rates = {}, origin = null) {
33
+ const figures = (0, render_1.sessionFigures)(transcript, rates), totals = figures.totals;
34
+ const available = !transcript.state.forkHistoryBoundaryUnknown;
35
+ const byModel = new Map();
36
+ for (const turn of figures.turns) {
37
+ const model = turn.model ?? null, row = byModel.get(model) ?? { model, responses: 0, outputTokens: 0, share: null };
38
+ row.responses++;
39
+ row.outputTokens += turn.outputTokens;
40
+ byModel.set(model, row);
41
+ }
42
+ const models = [...byModel.values()].map(row => ({ ...row, share: totals.output ? row.outputTokens / totals.output : null }))
43
+ .sort((a, b) => b.outputTokens - a.outputTokens || b.responses - a.responses || byName(a.model, b.model));
44
+ const timed = figures.turns.filter(turn => turn.at !== undefined && Number.isFinite(turn.at));
45
+ const started = earliest(timed.filter(turn => !turn.subagent).map(turn => turn.at)) ?? earliest(timed.map(turn => turn.at));
46
+ const input = totals.input + totals.write + totals.read;
47
+ const metrics = available
48
+ ? { assistantResponses: figures.turns.length, inputTokens: input, cacheReadTokens: totals.read, cacheWriteTokens: totals.write, freshInputTokens: totals.input,
49
+ cacheShare: input ? totals.read / input : 0, outputTokens: totals.output, subagentsLaunched: transcript.observations.spawnCalls,
50
+ fullPrefixRewrites: figures.attribution.rewrites.length, usd: figures.totalUsd }
51
+ : { assistantResponses: null, inputTokens: null, cacheReadTokens: null, cacheWriteTokens: null, freshInputTokens: null,
52
+ cacheShare: null, outputTokens: null, subagentsLaunched: null, fullPrefixRewrites: null, usd: null };
53
+ return {
54
+ sessionId: transcript.sessionId, shortId: (0, exports.shortId)(transcript.sessionId), host: location.host, path: location.path,
55
+ project: origin?.workingDirectory ?? (location.host === 'claude' ? (0, node_path_1.dirname)(location.path) : null),
56
+ startedAt: started === undefined ? null : new Date(started).toISOString(),
57
+ dominantModel: models[0]?.model ?? null, models, usageAvailable: available,
58
+ unpricedModels: available ? [...new Set(figures.prices.filter(price => price.usd === null).map(price => price.model))] : [],
59
+ metrics,
60
+ };
61
+ }
62
+ const midpoint = (value) => (value.min + value.max) / 2;
63
+ /** "A is not zero" as the table prints it: against $0.00 or 0.0% no change is computed. */
64
+ function printsAsZero(key, value) {
65
+ if (key === 'usd')
66
+ return Math.abs(value).toFixed(2) === '0.00';
67
+ if (key === 'cacheShare')
68
+ return (value * 100).toFixed(1) === '0.0';
69
+ return value === 0;
70
+ }
71
+ /**
72
+ * B against A. Counts and dollars change relatively (-65.3%); the cache share
73
+ * is already a percentage, so it changes by its difference in points (+2.6 pp),
74
+ * never by a percentage of a percentage.
75
+ */
76
+ function metricChange(key, before, after) {
77
+ const figure = (value) => value === null ? null : typeof value === 'number' ? value : midpoint(value);
78
+ const from = figure(before), to = figure(after);
79
+ if (from === null || to === null || printsAsZero(key, from))
80
+ return null;
81
+ return key === 'cacheShare' ? to - from : (to - from) / from;
82
+ }
83
+ function compareReport(a, b) {
84
+ const change = Object.fromEntries(types_1.COMPARE_METRICS.map(key => [key, metricChange(key, a.metrics[key], b.metrics[key])]));
85
+ return { a, b, change, subagentsIncluded: true, basis: 'estimated_api_list_price' };
86
+ }
87
+ /**
88
+ * A path given on the command line can name a discovered transcript through
89
+ * other text: a symlinked ~/.claude or ~/.codex, or a relative path resolved
90
+ * from the physical working directory. The discovered location is the one that
91
+ * groups with its siblings, and the one the newest-other search must skip.
92
+ */
93
+ function asDiscovered(location, locations) {
94
+ if (locations.some(item => item.path === location.path))
95
+ return location;
96
+ const real = (path) => { try {
97
+ return (0, node_fs_1.realpathSync)(path);
98
+ }
99
+ catch {
100
+ return null;
101
+ } };
102
+ const target = real(location.path);
103
+ return (target !== null && locations.find(item => (0, node_path_1.basename)(item.path) === (0, node_path_1.basename)(location.path) && real(item.path) === target)) || location;
104
+ }
105
+ /**
106
+ * Two selectors: those two sessions, in that order. One: that session and the
107
+ * newest other top-level session of its project. None: the two newest top-level
108
+ * sessions of the newest one's project. Selectors resolve exactly as `why`
109
+ * resolves one (id, id suffix or JSONL path). A top-level Claude Code session is
110
+ * a transcript directly inside its project directory, never a sub-agent file or
111
+ * any other file a session keeps beside it; a Codex rollout is top-level unless
112
+ * its first records mark a spawned sub-agent, and its project is the working
113
+ * directory it recorded. The session variables `why` falls back on are not read:
114
+ * with nothing given, recency decides.
115
+ */
116
+ function pickCompareSessions(selectors, options = {}) {
117
+ const roots = options.roots ?? (0, sessions_1.transcriptRoots)();
118
+ let discovered = options.locations;
119
+ const locations = () => discovered ??= (0, sessions_1.discoverInsightTranscripts)(roots);
120
+ if (selectors.length === 2)
121
+ return { ok: true, a: (0, sessions_1.selectInsightTranscript)(selectors[0], locations()), b: (0, sessions_1.selectInsightTranscript)(selectors[1], locations()), explicit: true };
122
+ const origins = new Map(), read = options.origin ?? sessions_1.transcriptOrigin;
123
+ const origin = (location) => {
124
+ let value = origins.get(location.path);
125
+ if (!value) {
126
+ value = read(location);
127
+ origins.set(location.path, value);
128
+ }
129
+ return value;
130
+ };
131
+ const topLevel = (location) => !(0, sessions_1.isSubagentTranscript)(location)
132
+ && (location.host === 'claude' ? (0, node_path_1.dirname)((0, node_path_1.dirname)(location.path)) === roots.claude : !origin(location).spawned);
133
+ const project = (location) => location.host === 'claude' ? (0, node_path_1.dirname)(location.path) : origin(location).workingDirectory;
134
+ const anchor = selectors.length ? asDiscovered((0, sessions_1.selectInsightTranscript)(selectors[0], locations()), locations()) : locations().find(topLevel);
135
+ if (!anchor)
136
+ return { ok: false, found: 0, project: null };
137
+ const key = project(anchor);
138
+ const other = key === null ? undefined
139
+ : locations().find(location => location.path !== anchor.path && location.host === anchor.host && project(location) === key && topLevel(location));
140
+ if (!other)
141
+ return { ok: false, found: 1, project: origin(anchor).workingDirectory ?? key };
142
+ return other.modifiedAt <= anchor.modifiedAt ? { ok: true, a: other, b: anchor, explicit: false } : { ok: true, a: anchor, b: other, explicit: false };
143
+ }
144
+ /** Reads each picked session the way `why` reads one. Unless the order was given, A is the session that started first. */
145
+ function comparePicked(pick, rates = {}, origin = sessions_1.transcriptOrigin) {
146
+ const read = (location) => compareSession(location, (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId }), rates, origin(location));
147
+ let a = read(pick.a), b = read(pick.b);
148
+ if (!pick.explicit && a.startedAt !== null && b.startedAt !== null && b.startedAt < a.startedAt)
149
+ [a, b] = [b, a];
150
+ return compareReport(a, b);
151
+ }
152
+ const INDENTED = new Set(['cacheReadTokens', 'cacheWriteTokens', 'freshInputTokens']);
153
+ const stamp = (iso) => `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`;
154
+ const isRange = (value) => value !== null && Math.abs(value.max - value.min) >= 0.000001;
155
+ /** A signed percentage with one decimal, as `why` prints shares; a change that rounds to zero has no sign. */
156
+ function signedChange(change) {
157
+ if (change === null)
158
+ return '';
159
+ const digits = Math.abs(change * 100).toFixed(1);
160
+ return digits === '0.0' ? '0.0%' : `${change < 0 ? '-' : '+'}${digits}%`;
161
+ }
162
+ /** A difference in share, in percentage points: "+2.6 pp" reads the same in English, Spanish and Portuguese. */
163
+ function signedPoints(change) {
164
+ if (change === null)
165
+ return '';
166
+ const digits = Math.abs(change * 100).toFixed(1);
167
+ return digits === '0.0' ? '0.0 pp' : `${change < 0 ? '-' : '+'}${digits} pp`;
168
+ }
169
+ /** `lang` changes words only; every figure, id, model id, path and command prints as it does in English. */
170
+ function renderCompare(report, lang = 'en') {
171
+ const text = i18n_1.COMPARE_TEXT[lang], words = i18n_1.WHY_TEXT[lang];
172
+ const name = (model) => model ?? words.missingModel;
173
+ const modelLine = (session) => {
174
+ if (!session.models.length)
175
+ return text.noModel;
176
+ const output = session.models.reduce((sum, row) => sum + row.outputTokens, 0);
177
+ const listed = session.models.filter(row => row.share !== null && row.share >= 0.05);
178
+ return listed.length > 1 ? text.models(listed.map(row => `${name(row.model)} ${(0, render_1.share)(row.outputTokens, output)}`).join(', ')) : text.model(name(session.models[0].model));
179
+ };
180
+ const heading = (label, session) => [
181
+ `${label} ${session.shortId} ${session.startedAt === null ? text.startUnknown : text.started(stamp(session.startedAt))}`,
182
+ ` ${modelLine(session)}`,
183
+ ` ${text.project(session.project)}`,
184
+ ];
185
+ const cell = (session, key) => {
186
+ const metrics = session.metrics;
187
+ if (!session.usageAvailable)
188
+ return text.unavailable;
189
+ if (key === 'usd')
190
+ return (0, live_1.dollars)(metrics.usd, words);
191
+ if (key === 'cacheShare')
192
+ return (0, render_1.share)(metrics.cacheReadTokens, metrics.inputTokens);
193
+ return (0, render_1.count)(metrics[key]);
194
+ };
195
+ const rows = types_1.COMPARE_METRICS.map(key => [`${INDENTED.has(key) ? ' ' : ''}${text.labels[key]}`, cell(report.a, key), cell(report.b, key), key === 'cacheShare' ? signedPoints(report.change[key]) : signedChange(report.change[key])]);
196
+ const sessions = [['A', report.a], ['B', report.b]];
197
+ const unpriced = [...new Set(sessions.flatMap(([, session]) => session.unpricedModels.map(name)))];
198
+ const ranged = sessions.some(([, session]) => isRange(session.metrics.usd));
199
+ return [
200
+ text.title,
201
+ ...heading('A', report.a), ...heading('B', report.b),
202
+ '', (0, render_1.table)([...text.headers], rows), text.subagents,
203
+ '',
204
+ ...sessions.filter(([, session]) => !session.usageAvailable).map(([label]) => text.forkUnavailable(label)),
205
+ ...(unpriced.length ? [words.unpricedModels(unpriced.join(', '))] : []),
206
+ ...(ranged ? [words.missingTtl, ...(report.change.usd !== null ? [text.rangeMidpoint] : [])] : []),
207
+ text.listPrice,
208
+ text.sameTask,
209
+ ].join('\n');
210
+ }
@@ -1,14 +1,14 @@
1
1
  /**
2
- * Languages of the plain `why` report: English, Latin American Spanish and
3
- * Brazilian Portuguese. Only words change. Numbers keep their en-US formatting
4
- * (1,234,567, $1335.37, 12.3%) so figures match screenshots and the site, and
5
- * session ids, model ids, commands, URLs and product names print as they are.
6
- * `why json` is a machine format and is never translated.
2
+ * Languages of the plain `why` and `compare` reports: English, Latin American
3
+ * Spanish and Brazilian Portuguese. Only words change. Numbers keep their en-US
4
+ * formatting (1,234,567, $1335.37, 12.3%) so figures match screenshots and the
5
+ * site, and session ids, model ids, commands, URLs and product names print as
6
+ * they are. `why json` and `compare json` are machine formats, never translated.
7
7
  *
8
8
  * Detection is pure: the CLI passes in the flag, the environment and the Intl
9
- * locale, and renderWhy receives the chosen language through its options.
9
+ * locale, and each renderer receives the chosen language as an argument.
10
10
  */
11
- import type { InsightBucket, InsightObservations } from './types';
11
+ import type { CompareMetric, InsightBucket, InsightObservations } from './types';
12
12
  export type WhyLang = 'en' | 'es' | 'pt';
13
13
  /**
14
14
  * The language of a flag value or locale: the part before '_', '-', '.' or '@',
@@ -63,3 +63,34 @@ export interface WhyText {
63
63
  hide: string;
64
64
  }
65
65
  export declare const WHY_TEXT: Readonly<Record<WhyLang, WhyText>>;
66
+ /**
67
+ * Every line of the plain `compare` report, in the same three languages and under
68
+ * the same rules as `why`: words change, figures, ids, model ids, paths and
69
+ * commands do not. The rewrite label, the List USD header and the unpriced and
70
+ * missing-model wording are `why`'s own, so both reports use one vocabulary.
71
+ */
72
+ export interface CompareText {
73
+ title: string;
74
+ /** The session line after the short id; `stamp` is `YYYY-MM-DD HH:MM UTC`. */
75
+ started: (stamp: string) => string;
76
+ startUnknown: string;
77
+ /** The one model with at least 5% of output tokens, or the dominant one. */
78
+ model: (model: string) => string;
79
+ /** Two or more models with at least 5% of output tokens each, each with its share of the output tokens. */
80
+ models: (list: string) => string;
81
+ noModel: string;
82
+ project: (path: string | null) => string;
83
+ headers: [metric: string, a: string, b: string, change: string];
84
+ /** Table labels; the three input rows print indented under the input total. */
85
+ labels: Record<CompareMetric, string>;
86
+ /** Every cell of a session whose usage is unavailable. */
87
+ unavailable: string;
88
+ subagents: string;
89
+ forkUnavailable: (session: string) => string;
90
+ rangeMidpoint: string;
91
+ listPrice: string;
92
+ sameTask: string;
93
+ /** Stderr when fewer than two sessions are found; `project` is null when none is known. */
94
+ fewerThanTwo: (found: number, project: string | null) => string;
95
+ }
96
+ export declare const COMPARE_TEXT: Readonly<Record<WhyLang, CompareText>>;