@agentguard-run/burn 0.3.18 → 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.
- package/CHANGELOG.md +11 -0
- package/README.md +44 -3
- package/dist/src/cli.js +38 -4
- package/dist/src/hook/pre-tool-use.d.ts +1 -1
- package/dist/src/insights/compare.d.ts +104 -0
- package/dist/src/insights/compare.js +210 -0
- package/dist/src/insights/i18n.d.ts +38 -7
- package/dist/src/insights/i18n.js +81 -7
- package/dist/src/insights/render.d.ts +24 -2
- package/dist/src/insights/render.js +25 -16
- package/dist/src/insights/sessions.d.ts +25 -0
- package/dist/src/insights/sessions.js +72 -5
- package/dist/src/insights/types.d.ts +3 -0
- package/dist/src/insights/types.js +3 -1
- package/dist/src/stop-text.d.ts +5 -3
- package/dist/src/stop-text.js +5 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.19 (2026-09-27)
|
|
4
|
+
|
|
5
|
+
- Every command Burn prints now uses the short, unscoped name `npx agentguard-burn` (the `agentguard-burn` launcher on npm runs the latest Burn): the override line in the STOP box, the `why` tips in English, Spanish and Portuguese, and the `quiet` messages. The name has no "@", so X no longer turns a quoted command into a link to someone else's account. `why` output is otherwise byte-identical to 0.3.16 in English.
|
|
6
|
+
- `enforce` now says what enforcement does: "In an interactive Claude Code session the next STOP asks you first; where nobody can answer, it refuses the launch."
|
|
7
|
+
- `why` with no session no longer picks a file Claude Code keeps inside a session's own directory, such as `<session>/skill-injections.jsonl`, when that file is the newest on disk.
|
|
8
|
+
- New `compare [sessionA] [sessionB] [json] [--lang en|es|pt]`: two sessions side by side from local transcripts, so the same task run once on each model reads as one table. Rows: assistant responses; input tokens, split into cache reads, cache writes and fresh input; the cache share (cache reads divided by all input); output tokens; sub-agents launched; full-prefix rewrites; the API list-price equivalent. Each is exactly the figure `why` prints for that session, child transcripts included, and the table says "Totals include sub-agents." The Change column is B against A: a signed percentage for counts and dollars, and a difference in percentage points for the cache share (for example "+2.6 pp", never a percentage of a percentage; `change.cacheShare` in json is that difference), only where both values are numbers and A is not zero as printed; a dollar range compares midpoints, and an unpriced model prints `unpriced` with no change. Every report ends with "Dollar figures are API list-price equivalents, not a bill." and "AgentGuard cannot tell whether these sessions did the same task. Compare runs of the same task."
|
|
9
|
+
- Picking: two sessions compare those two in the order given; one pairs it with the newest other top-level session in its project; none takes the two newest top-level sessions in the project of the newest one. Ids, id suffixes and transcript paths resolve as they do for `why`. Sub-agent transcripts and other files Claude Code keeps beside a session (such as `skill-injections.jsonl`) are never picked. A Codex rollout's project is the working directory it recorded, and a spawned sub-agent rollout is skipped. Unless both are named, A is the session that started first. The session variables `why` falls back on are not read. Fewer than two sessions exits 1 with one line on stderr saying so and how to pass two ids.
|
|
10
|
+
- Both sessions are named above the table: the short id (the last part of the session id, accepted back as an id suffix), the time of the first recorded response in UTC, the dominant model by output tokens (every model with at least 5% of output tokens, with its share, when there are several) and the project path (the working directory the transcript recorded, read from its first records only).
|
|
11
|
+
- The table fits 80 columns in English. Spanish and Portuguese follow `why`: every line through `src/insights/i18n.ts`, figures in en-US digits, AgentGuard untranslated, the same language precedence and the same exit-64 usage line for a bad `--lang`. `compare json` is never translated and carries both sessions (ids, paths, project, models, every metric) and each change as an unrounded fraction of A. The report prints its plain table on a terminal, through the same presentation path as the other reports.
|
|
12
|
+
- What changes in output: only the new command, and the help, which lists it in its synopsis and on one new line. `why`, `why json` and every other command are byte-identical to 0.3.17. Internally, `why`'s header figures now come from an exported `sessionFigures`, which `compare` reads as well; `render.ts` exports its `table`, `count` and `share` helpers, and `sessions.ts` gains `transcriptRoots` (the same default roots) and `transcriptOrigin` (the recorded working directory and the parser's sub-agent verdict, from at most the first megabyte of a transcript).
|
|
13
|
+
|
|
3
14
|
## 0.3.18 (2026-09-27)
|
|
4
15
|
|
|
5
16
|
- An enforced STOP in an interactive Claude Code session (Manual, accept edits, auto or plan mode) now holds the launch behind Claude Code's own permission prompt instead of refusing it: three lines naming the one limit that fired, then "Allow this one launch? If you say no, nothing starts." Claude Code shows that text to the person and not to Claude, and since Claude Code 2.1.211 auto mode cannot approve it silently. Print mode, `bypassPermissions`, `dontAsk`, Codex and Cursor still refuse outright. `"stopStyle": "deny"` in `burn-policy.json` keeps the outright refusal everywhere. The decisions ledger records `asked: true` and the permission mode; the signed receipt adds the reason `decision:ask`.
|
package/README.md
CHANGED
|
@@ -225,6 +225,47 @@ Optional settings in your existing `burn-policy.json`:
|
|
|
225
225
|
|
|
226
226
|
Merge these fields into the existing policy. All existing thresholds and modes remain supported. Prices are exact-model API list equivalents, not a subscription bill. Unknown models show tokens only. Every rate has a source and verification date. A local override file and full pricing table are documented in [Usage and pricing](docs/USAGE_AND_PRICING.md).
|
|
227
227
|
|
|
228
|
+
## Compare two sessions
|
|
229
|
+
|
|
230
|
+
```sh
|
|
231
|
+
agentguard-burn compare
|
|
232
|
+
agentguard-burn compare SESSION_ID
|
|
233
|
+
agentguard-burn compare SESSION_A SESSION_B
|
|
234
|
+
agentguard-burn compare SESSION_A SESSION_B json
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Run the same task once on each model, then put the two sessions side by side. With no session, `compare` takes the two most recent top-level sessions in the project of the newest one; with one, that session and the newest other top-level session in its project; with two, those two in the order given. Sessions resolve as they do for `why` (id, id suffix or transcript path). Sub-agent transcripts and other files Claude Code keeps beside a session are never picked. A Codex rollout's project is the working directory it recorded, and a spawned sub-agent rollout is skipped. Unless you name both, A is the session that started first. Fewer than two sessions exits 1 with one line saying how to pass two ids.
|
|
238
|
+
|
|
239
|
+
Both sessions are named first: the short id (the last part of the session id, which `compare` and `why` accept back), the time of the first recorded response in UTC, the model with the most output tokens (every model with at least 5% of output tokens, with its share, when there are several) and the project path. Each figure is the one `why` prints for that session, child transcripts included. Change is B against A, only where both values are numbers and A is not zero as printed; a dollar range compares midpoints, and an unpriced model prints `unpriced` with no change. The fixture in `tests/fixtures/compare-fixtures.ts` renders as:
|
|
240
|
+
|
|
241
|
+
```text
|
|
242
|
+
AgentGuard compare: B against A
|
|
243
|
+
A aaaaaaaaaaaa started 2026-09-25 10:01 UTC
|
|
244
|
+
Output by model: claude-opus-5-5 92.3%, claude-haiku-4-5-20251001 7.7%
|
|
245
|
+
Project: /synthetic/project
|
|
246
|
+
B bbbbbbbbbbbb started 2026-09-25 11:01 UTC
|
|
247
|
+
Model: claude-sonnet-5
|
|
248
|
+
Project: /synthetic/project
|
|
249
|
+
|
|
250
|
+
Metric A B Change
|
|
251
|
+
Assistant responses 4 3 -25.0%
|
|
252
|
+
Input tokens 599,600 543,000 -9.4%
|
|
253
|
+
read from cache 200,000 360,000 +80.0%
|
|
254
|
+
cache writes 396,000 180,500 -54.4%
|
|
255
|
+
fresh input 3,600 2,500 -30.6%
|
|
256
|
+
Cache share 33.4% 66.3% +98.8%
|
|
257
|
+
Output tokens 6,500 4,000 -38.5%
|
|
258
|
+
Sub-agents launched 1 0 -100.0%
|
|
259
|
+
Full-prefix rewrites 2 1 -50.0%
|
|
260
|
+
List USD $2.13 $0.57 -73.3%
|
|
261
|
+
Totals include sub-agents.
|
|
262
|
+
|
|
263
|
+
Dollar figures are API list-price equivalents, not a bill.
|
|
264
|
+
AgentGuard cannot tell whether these sessions did the same task. Compare runs of the same task.
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
`compare` measures and does not rank models. `--lang es|pt` and your locale choose the language exactly as for `why`. `compare json` is never translated: both sessions with ids, paths, project, models and every metric, and each change as an unrounded fraction of A.
|
|
268
|
+
|
|
228
269
|
## Two safety planes
|
|
229
270
|
|
|
230
271
|
Structural limits use active time rather than the age of the session. The
|
|
@@ -368,9 +409,9 @@ ends with the override to run. In Claude Code, type it with `!` in front so it
|
|
|
368
409
|
runs in your own shell:
|
|
369
410
|
|
|
370
411
|
```
|
|
371
|
-
! npx
|
|
372
|
-
! npx
|
|
373
|
-
! npx
|
|
412
|
+
! npx agentguard-burn resume --once --reason "these 60 agents are the plan" # the next STOP passes, once, on any host
|
|
413
|
+
! npx agentguard-burn resume --reason "load test" # every STOP passes for 15 minutes
|
|
414
|
+
! npx agentguard-burn resume --clear
|
|
374
415
|
```
|
|
375
416
|
|
|
376
417
|
Only the person can override. A `!` command never passes through a hook, so
|
package/dist/src/cli.js
CHANGED
|
@@ -230,6 +230,39 @@ async function main(argv) {
|
|
|
230
230
|
show({ kind: 'command', command, values: { session: transcript.sessionId, observations: transcript.observations, diagnostics: transcript.diagnostics, attribution: (0, attribution_1.attributeTurns)((0, transcript_2.deduplicateTurns)(transcript.turns)).buckets, prices: (0, transcript_2.deduplicateTurns)(transcript.turns).map(turn => (0, pricing_1.priceTurn)(turn, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)))) } }, json ? JSON.stringify(transcript, null, 2) + '\n' : (0, render_2.renderWhy)(transcript, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)), { tips: !quietOn(), lang: (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() }) }) + '\n', json);
|
|
231
231
|
return 0;
|
|
232
232
|
}
|
|
233
|
+
case 'compare': {
|
|
234
|
+
// Up to two session selectors, `json`, and `--lang` exactly as `why` takes it.
|
|
235
|
+
const args = [];
|
|
236
|
+
let lang, langGiven = false;
|
|
237
|
+
for (let i = 0; i < rest.length; i++) {
|
|
238
|
+
if (rest[i] === '--lang') {
|
|
239
|
+
langGiven = true;
|
|
240
|
+
lang = rest[++i];
|
|
241
|
+
}
|
|
242
|
+
else if (rest[i].startsWith('--lang=')) {
|
|
243
|
+
langGiven = true;
|
|
244
|
+
lang = rest[i].slice('--lang='.length);
|
|
245
|
+
}
|
|
246
|
+
else
|
|
247
|
+
args.push(rest[i]);
|
|
248
|
+
}
|
|
249
|
+
const json = args.includes('json') || args.includes('--json');
|
|
250
|
+
const selectors = args.filter(value => value !== 'json' && value !== '--json');
|
|
251
|
+
if ((langGiven && (0, i18n_1.whyLangOf)(lang) === null) || selectors.length > 2 || selectors.some(value => !value.trim() || value.startsWith('--'))) {
|
|
252
|
+
process.stderr.write('Usage: agentguard-burn compare [sessionA] [sessionB] [json] [--lang en|es|pt]\n');
|
|
253
|
+
return 64;
|
|
254
|
+
}
|
|
255
|
+
const language = (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() });
|
|
256
|
+
const { comparePicked, pickCompareSessions, renderCompare } = await Promise.resolve().then(() => __importStar(require('./insights/compare')));
|
|
257
|
+
const pick = pickCompareSessions(selectors);
|
|
258
|
+
if (!pick.ok) {
|
|
259
|
+
process.stderr.write(i18n_1.COMPARE_TEXT[language].fewerThanTwo(pick.found, pick.project) + '\n');
|
|
260
|
+
return 1;
|
|
261
|
+
}
|
|
262
|
+
const report = comparePicked(pick, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME)));
|
|
263
|
+
show({ kind: 'command', command, values: { ...report } }, json ? JSON.stringify(report, null, 2) + '\n' : renderCompare(report, language) + '\n', json);
|
|
264
|
+
return 0;
|
|
265
|
+
}
|
|
233
266
|
case 'quiet': {
|
|
234
267
|
const [state, ...extra] = rest;
|
|
235
268
|
if (extra.length || (state !== undefined && state !== 'on' && state !== 'off')) {
|
|
@@ -240,8 +273,8 @@ async function main(argv) {
|
|
|
240
273
|
(0, upgrade_moments_1.setQuiet)(HOME, state === 'on');
|
|
241
274
|
const quiet = quietOn();
|
|
242
275
|
show({ kind: 'command', command, values: { tips: quiet ? 'off' : 'on', quiet: quiet ? 'on' : 'off', file: (0, upgrade_moments_1.quietFile)(HOME) } }, quiet
|
|
243
|
-
? 'Tips are off. Quiet is on: the why tip, the monthly summary in status and the AgentGuard plugin\'s upgrade, version and Score lines stay hidden on this machine.\nTurn them back on: npx
|
|
244
|
-
: 'Tips are on. The why report ends with one tip when a share of the session stands out.\nHide tips: npx
|
|
276
|
+
? 'Tips are off. Quiet is on: the why tip, the monthly summary in status and the AgentGuard plugin\'s upgrade, version and Score lines stay hidden on this machine.\nTurn them back on: npx agentguard-burn quiet off\n'
|
|
277
|
+
: 'Tips are on. The why report ends with one tip when a share of the session stands out.\nHide tips: npx agentguard-burn quiet on\n');
|
|
245
278
|
return 0;
|
|
246
279
|
}
|
|
247
280
|
case 'rewrites':
|
|
@@ -465,7 +498,7 @@ async function main(argv) {
|
|
|
465
498
|
return 2;
|
|
466
499
|
}
|
|
467
500
|
savePolicy({ ...policy, mode: 'enforce' });
|
|
468
|
-
show({ kind: 'command', command, values: { mode: 'enforce' } }, 'Enforcement ON.
|
|
501
|
+
show({ kind: 'command', command, values: { mode: 'enforce' } }, 'Enforcement ON. In an interactive Claude Code session the next STOP asks you first; where nobody can answer, it refuses the launch.\n');
|
|
469
502
|
return 0;
|
|
470
503
|
}
|
|
471
504
|
case 'shadow': {
|
|
@@ -493,7 +526,7 @@ async function main(argv) {
|
|
|
493
526
|
return 0;
|
|
494
527
|
}
|
|
495
528
|
default:
|
|
496
|
-
show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'why', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|why|rewrites|ttl|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|quiet|proxy|conformance>\n' +
|
|
529
|
+
show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'why', 'compare', 'rewrites', 'ttl', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'quiet', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|why|compare|rewrites|ttl|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|quiet|proxy|conformance>\n' +
|
|
497
530
|
' ps [--json] local agent processes, held memory and workspace disk\n' +
|
|
498
531
|
' render <run.jsonl> --mp4 <out.mp4> [--gif <out.gif>] [--phone] local recorded-run export\n' +
|
|
499
532
|
' render <run.jsonl> --mp4 <out.mp4> --dashboard [--wide] [--economics <blocks.json>] dashboard export\n' +
|
|
@@ -506,6 +539,7 @@ async function main(argv) {
|
|
|
506
539
|
' price-shadow [session|all] local child list-price exposure and sensitivity\n' +
|
|
507
540
|
' why [session] token attribution and API list-price equivalents\n' +
|
|
508
541
|
' --lang es|pt the why report in Latin American Spanish or Brazilian Portuguese; your locale picks it by default\n' +
|
|
542
|
+
' compare [sessionA] [sessionB] two sessions side by side: tokens, cache, sub-agents, rewrites, list USD; json and --lang as for why\n' +
|
|
509
543
|
' rewrites [session|all] every full-prefix cache write with its cause, idle gap and list price\n' +
|
|
510
544
|
' ttl [session|all] one-hour cache lifetime counterfactual from your own idle gaps\n' +
|
|
511
545
|
' pace [session] ten-minute pace and next-hour projection\n' +
|
|
@@ -84,7 +84,7 @@ export declare function handlePreToolUse(input: HookInput, home: string, now?: n
|
|
|
84
84
|
*/
|
|
85
85
|
export declare function asksPerson(input: HookInput, policy: Pick<Policy, 'stopStyle'>): boolean;
|
|
86
86
|
/** What Claude is told when it tries to override AgentGuard itself. */
|
|
87
|
-
export declare const 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! npx
|
|
87
|
+
export declare const 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! npx agentguard-burn resume --once --reason \"...\"";
|
|
88
88
|
/**
|
|
89
89
|
* An agent's own attempt to lift a STOP: running `resume`, `shadow` or
|
|
90
90
|
* `calibrate` (which writes a shadow policy), or writing the override or
|
|
@@ -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`
|
|
3
|
-
* Brazilian Portuguese. Only words change. Numbers keep their en-US
|
|
4
|
-
* (1,234,567, $1335.37, 12.3%) so figures match screenshots and the
|
|
5
|
-
* session ids, model ids, commands, URLs and product names print as
|
|
6
|
-
* `why json`
|
|
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
|
|
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>>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WHY_TEXT = void 0;
|
|
3
|
+
exports.COMPARE_TEXT = exports.WHY_TEXT = void 0;
|
|
4
4
|
exports.whyLangOf = whyLangOf;
|
|
5
5
|
exports.detectWhyLang = detectWhyLang;
|
|
6
6
|
/**
|
|
@@ -65,9 +65,9 @@ const en = {
|
|
|
65
65
|
mixedRanges: 'Some bucket cache-write costs are ranges because mixed cache lifetimes are not attributed to individual buckets. Range endpoints are not additive across buckets.',
|
|
66
66
|
diagnostics: (duplicates, malformed) => `Usage records de-duplicated: ${duplicates}. Malformed lines skipped: ${malformed}.`,
|
|
67
67
|
tipFanout: share => `Next: sub-agent fan-out is ${share} of this session's tokens. Spawn limits refuse the next sub-agent launch past your limit, free on one machine: agentguard.run/try`,
|
|
68
|
-
tipRewrites: (rewrites, total) => `Next: full-prefix rewrites are ${rewrites} of ${total} API list equivalent here. See the cause of each one: npx
|
|
68
|
+
tipRewrites: (rewrites, total) => `Next: full-prefix rewrites are ${rewrites} of ${total} API list equivalent here. See the cause of each one: npx agentguard-burn rewrites`,
|
|
69
69
|
tipHistory: share => `Next: history re-sent is ${share} of this session's tokens. A fresh session, or /compact, starts that history over.`,
|
|
70
|
-
hide: 'Hide tips like this: npx
|
|
70
|
+
hide: 'Hide tips like this: npx agentguard-burn quiet on',
|
|
71
71
|
};
|
|
72
72
|
/** Latin American Spanish: tú forms and vocabulary that reads the same from Mexico and Panama to Argentina. */
|
|
73
73
|
const es = {
|
|
@@ -105,9 +105,9 @@ const es = {
|
|
|
105
105
|
mixedRanges: 'Algunos costos de escritura en caché por categoría son rangos, porque las duraciones de caché mixtas no se atribuyen a categorías individuales. Los extremos de los rangos no se suman entre categorías.',
|
|
106
106
|
diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Líneas mal formadas omitidas: ${malformed}.`,
|
|
107
107
|
tipFanout: share => `Próximo paso: el fan-out de subagentes representa el ${share} de los tokens de esta sesión. Los límites de subagentes rechazan nuevos subagentes cuando llegas a tu límite, gratis en una máquina: agentguard.run/try`,
|
|
108
|
-
tipRewrites: (rewrites, total) => `Próximo paso: las reescrituras de prefijo completo suman ${rewrites} de ${total} (equivalente a precio de lista de la API) en esta sesión. Mira la causa de cada una: npx
|
|
108
|
+
tipRewrites: (rewrites, total) => `Próximo paso: las reescrituras de prefijo completo suman ${rewrites} de ${total} (equivalente a precio de lista de la API) en esta sesión. Mira la causa de cada una: npx agentguard-burn rewrites`,
|
|
109
109
|
tipHistory: share => `Próximo paso: el historial reenviado representa el ${share} de los tokens de esta sesión. Una sesión nueva, o /compact, reinicia ese historial.`,
|
|
110
|
-
hide: 'Para ocultar consejos como este: npx
|
|
110
|
+
hide: 'Para ocultar consejos como este: npx agentguard-burn quiet on',
|
|
111
111
|
};
|
|
112
112
|
/** Brazilian Portuguese: você forms. */
|
|
113
113
|
const pt = {
|
|
@@ -145,8 +145,82 @@ const pt = {
|
|
|
145
145
|
mixedRanges: 'Alguns custos de gravação em cache por categoria aparecem como faixas, porque durações de cache mistas não são atribuídas a categorias individuais. Os extremos das faixas não se somam entre categorias.',
|
|
146
146
|
diagnostics: (duplicates, malformed) => `Registros de uso deduplicados: ${duplicates}. Linhas malformadas ignoradas: ${malformed}.`,
|
|
147
147
|
tipFanout: share => `Próximo passo: o fan-out de subagentes representa ${share} dos tokens desta sessão. Os limites de subagentes recusam novos subagentes quando você chega ao seu limite, grátis em uma máquina: agentguard.run/try`,
|
|
148
|
-
tipRewrites: (rewrites, total) => `Próximo passo: as reescritas de prefixo completo somam ${rewrites} de ${total} (equivalente ao preço de tabela da API) nesta sessão. Veja a causa de cada uma: npx
|
|
148
|
+
tipRewrites: (rewrites, total) => `Próximo passo: as reescritas de prefixo completo somam ${rewrites} de ${total} (equivalente ao preço de tabela da API) nesta sessão. Veja a causa de cada uma: npx agentguard-burn rewrites`,
|
|
149
149
|
tipHistory: share => `Próximo passo: o histórico reenviado representa ${share} dos tokens desta sessão. Uma sessão nova, ou /compact, reinicia esse histórico.`,
|
|
150
|
-
hide: 'Para ocultar dicas como esta: npx
|
|
150
|
+
hide: 'Para ocultar dicas como esta: npx agentguard-burn quiet on',
|
|
151
151
|
};
|
|
152
152
|
exports.WHY_TEXT = { en, es, pt };
|
|
153
|
+
const TWO_IDS = 'agentguard-burn compare SESSION_A SESSION_B';
|
|
154
|
+
const compareEn = {
|
|
155
|
+
title: 'AgentGuard compare: B against A',
|
|
156
|
+
started: stamp => `started ${stamp}`,
|
|
157
|
+
startUnknown: 'start time not recorded',
|
|
158
|
+
model: model => `Model: ${model}`,
|
|
159
|
+
models: list => `Output by model: ${list}`,
|
|
160
|
+
noModel: 'Model: no assistant response recorded',
|
|
161
|
+
project: path => `Project: ${path ?? 'not recorded'}`,
|
|
162
|
+
headers: ['Metric', 'A', 'B', 'Change'],
|
|
163
|
+
labels: {
|
|
164
|
+
assistantResponses: 'Assistant responses', inputTokens: 'Input tokens', cacheReadTokens: 'read from cache', cacheWriteTokens: 'cache writes',
|
|
165
|
+
freshInputTokens: 'fresh input', cacheShare: 'Cache share', outputTokens: 'Output tokens', subagentsLaunched: 'Sub-agents launched',
|
|
166
|
+
fullPrefixRewrites: en.labels.full_prefix_rewrites, usd: en.headers[2],
|
|
167
|
+
},
|
|
168
|
+
unavailable: 'unavailable',
|
|
169
|
+
subagents: 'Totals include sub-agents.',
|
|
170
|
+
forkUnavailable: session => `${session}: inherited Codex history has no verifiable boundary, so its usage is unavailable. Copied usage is excluded, not counted as zero.`,
|
|
171
|
+
rangeMidpoint: 'A dollar range is compared at its midpoint.',
|
|
172
|
+
listPrice: 'Dollar figures are API list-price equivalents, not a bill.',
|
|
173
|
+
sameTask: 'AgentGuard cannot tell whether these sessions did the same task. Compare runs of the same task.',
|
|
174
|
+
fewerThanTwo: (found, project) => found === 0
|
|
175
|
+
? `No local top-level session found, and compare needs two. Pass two ids: ${TWO_IDS}`
|
|
176
|
+
: `Only one top-level session found${project ? ` in ${project}` : ''}, and compare needs two. Pass two ids: ${TWO_IDS}`,
|
|
177
|
+
};
|
|
178
|
+
const compareEs = {
|
|
179
|
+
title: 'AgentGuard compare: B frente a A',
|
|
180
|
+
started: stamp => `inicio ${stamp}`,
|
|
181
|
+
startUnknown: 'hora de inicio no registrada',
|
|
182
|
+
model: model => `Modelo: ${model}`,
|
|
183
|
+
models: list => `Salida por modelo: ${list}`,
|
|
184
|
+
noModel: 'Modelo: no hay respuestas del asistente registradas',
|
|
185
|
+
project: path => `Proyecto: ${path ?? 'no registrado'}`,
|
|
186
|
+
headers: ['Métrica', 'A', 'B', 'Cambio'],
|
|
187
|
+
labels: {
|
|
188
|
+
assistantResponses: 'Respuestas del asistente', inputTokens: 'Tokens de entrada', cacheReadTokens: 'lectura de caché', cacheWriteTokens: 'escritura en caché',
|
|
189
|
+
freshInputTokens: 'entrada nueva', cacheShare: 'Proporción de caché', outputTokens: 'Tokens de salida', subagentsLaunched: 'Subagentes lanzados',
|
|
190
|
+
fullPrefixRewrites: es.labels.full_prefix_rewrites, usd: es.headers[2],
|
|
191
|
+
},
|
|
192
|
+
unavailable: 'no disponible',
|
|
193
|
+
subagents: 'Los totales incluyen los subagentes.',
|
|
194
|
+
forkUnavailable: session => `${session}: el historial heredado de Codex no tiene un punto de corte verificable, así que el uso de esta sesión no está disponible. El uso copiado queda excluido, no se cuenta como cero.`,
|
|
195
|
+
rangeMidpoint: 'Un rango en dólares se compara por su punto medio.',
|
|
196
|
+
listPrice: 'Las cifras en dólares son equivalentes a precio de lista de la API, no una factura.',
|
|
197
|
+
sameTask: 'AgentGuard no puede saber si estas sesiones hicieron la misma tarea. Compara ejecuciones de la misma tarea.',
|
|
198
|
+
fewerThanTwo: (found, project) => found === 0
|
|
199
|
+
? `No se encontró ninguna sesión principal local, y compare necesita dos. Pasa dos ids: ${TWO_IDS}`
|
|
200
|
+
: `Solo se encontró una sesión principal${project ? ` en ${project}` : ''}, y compare necesita dos. Pasa dos ids: ${TWO_IDS}`,
|
|
201
|
+
};
|
|
202
|
+
const comparePt = {
|
|
203
|
+
title: 'AgentGuard compare: B em relação a A',
|
|
204
|
+
started: stamp => `início ${stamp}`,
|
|
205
|
+
startUnknown: 'horário de início não registrado',
|
|
206
|
+
model: model => `Modelo: ${model}`,
|
|
207
|
+
models: list => `Saída por modelo: ${list}`,
|
|
208
|
+
noModel: 'Modelo: nenhuma resposta do assistente registrada',
|
|
209
|
+
project: path => `Projeto: ${path ?? 'não registrado'}`,
|
|
210
|
+
headers: ['Métrica', 'A', 'B', 'Variação'],
|
|
211
|
+
labels: {
|
|
212
|
+
assistantResponses: 'Respostas do assistente', inputTokens: 'Tokens de entrada', cacheReadTokens: 'leitura de cache', cacheWriteTokens: 'gravação em cache',
|
|
213
|
+
freshInputTokens: 'entrada nova', cacheShare: 'Proporção de cache', outputTokens: 'Tokens de saída', subagentsLaunched: 'Subagentes iniciados',
|
|
214
|
+
fullPrefixRewrites: pt.labels.full_prefix_rewrites, usd: pt.headers[2],
|
|
215
|
+
},
|
|
216
|
+
unavailable: 'indisponível',
|
|
217
|
+
subagents: 'Os totais incluem os subagentes.',
|
|
218
|
+
forkUnavailable: session => `${session}: o histórico herdado do Codex não tem um ponto de corte verificável, então o uso desta sessão fica indisponível. O uso copiado fica de fora, não é contado como zero.`,
|
|
219
|
+
rangeMidpoint: 'Uma faixa em dólares é comparada pelo ponto médio.',
|
|
220
|
+
listPrice: 'Os valores em dólares são equivalentes ao preço de tabela da API, não uma fatura.',
|
|
221
|
+
sameTask: 'O AgentGuard não consegue saber se estas sessões fizeram a mesma tarefa. Compare execuções da mesma tarefa.',
|
|
222
|
+
fewerThanTwo: (found, project) => found === 0
|
|
223
|
+
? `Nenhuma sessão principal local foi encontrada, e o compare precisa de duas. Passe dois ids: ${TWO_IDS}`
|
|
224
|
+
: `Só uma sessão principal foi encontrada${project ? ` em ${project}` : ''}, e o compare precisa de duas. Passe dois ids: ${TWO_IDS}`,
|
|
225
|
+
};
|
|
226
|
+
exports.COMPARE_TEXT = { en: compareEn, es: compareEs, pt: comparePt };
|
|
@@ -1,8 +1,30 @@
|
|
|
1
|
-
import { type DollarRange, type PricingTable } from './pricing';
|
|
2
|
-
import { type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence } from './types';
|
|
1
|
+
import { type DollarRange, type PricingTable, type TurnPrice } from './pricing';
|
|
2
|
+
import { type AttributionSummary, type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence } from './types';
|
|
3
3
|
import { type WhyLang } from './i18n';
|
|
4
4
|
export declare function sumPrices(values: Array<DollarRange | null>): DollarRange | null;
|
|
5
5
|
export declare function totalTokens(turn: InsightTurn): number;
|
|
6
|
+
/** What the two header lines of `why` are computed from; `compare` reads the same object, so both commands print the same figures. */
|
|
7
|
+
export interface SessionFigures {
|
|
8
|
+
/** Deduplicated responses in time order, child transcripts included when the transcript carries them. */
|
|
9
|
+
turns: InsightTurn[];
|
|
10
|
+
attribution: AttributionSummary;
|
|
11
|
+
prices: TurnPrice[];
|
|
12
|
+
totals: {
|
|
13
|
+
input: number;
|
|
14
|
+
write: number;
|
|
15
|
+
read: number;
|
|
16
|
+
output: number;
|
|
17
|
+
};
|
|
18
|
+
/** The API list equivalent `why` prints; null when any response has no verified rate. */
|
|
19
|
+
totalUsd: DollarRange | null;
|
|
20
|
+
}
|
|
21
|
+
export declare function sessionFigures(transcript: InsightTranscript, rates?: PricingTable): SessionFigures;
|
|
22
|
+
/** Left-aligned columns two spaces apart; widths follow the widest cell, so translated labels widen their column. */
|
|
23
|
+
export declare function table(headers: string[], rows: string[][]): string;
|
|
24
|
+
/** Token counts in en-US digits in every language. */
|
|
25
|
+
export declare const count: (n: number) => string;
|
|
26
|
+
/** The table's share column; the tip prints the same figure. */
|
|
27
|
+
export declare const share: (tokens: number, total: number) => string;
|
|
6
28
|
export declare const WHY_TIP_HIDE_LINE: string;
|
|
7
29
|
/**
|
|
8
30
|
* One next step from the session's own measured shares, first match wins; null
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WHY_TIP_HIDE_LINE = void 0;
|
|
3
|
+
exports.WHY_TIP_HIDE_LINE = exports.share = exports.count = void 0;
|
|
4
4
|
exports.sumPrices = sumPrices;
|
|
5
5
|
exports.totalTokens = totalTokens;
|
|
6
|
+
exports.sessionFigures = sessionFigures;
|
|
7
|
+
exports.table = table;
|
|
6
8
|
exports.whyTip = whyTip;
|
|
7
9
|
exports.renderWhy = renderWhy;
|
|
8
10
|
exports.rewriteReport = rewriteReport;
|
|
@@ -19,6 +21,13 @@ function sumPrices(values) {
|
|
|
19
21
|
return values.some(value => value === null) ? null : values.reduce((sum, value) => ({ min: sum.min + value.min, max: sum.max + value.max }), { min: 0, max: 0 });
|
|
20
22
|
}
|
|
21
23
|
function totalTokens(turn) { return turn.inputTokens + turn.cacheWriteTokens + turn.cacheReadTokens + turn.outputTokens; }
|
|
24
|
+
function sessionFigures(transcript, rates = {}) {
|
|
25
|
+
const turns = (0, transcript_1.deduplicateTurns)(transcript.turns).sort((a, b) => (a.at ?? 0) - (b.at ?? 0));
|
|
26
|
+
const prices = turns.map(turn => (0, pricing_1.priceTurn)(turn, rates));
|
|
27
|
+
const totals = { input: 0, write: 0, read: 0, output: 0 };
|
|
28
|
+
turns.forEach(turn => { totals.input += turn.inputTokens; totals.write += turn.cacheWriteTokens; totals.read += turn.cacheReadTokens; totals.output += turn.outputTokens; });
|
|
29
|
+
return { turns, attribution: (0, attribution_1.attributeTurns)(turns), prices, totals, totalUsd: sumPrices(prices.map(price => price.usd)) };
|
|
30
|
+
}
|
|
22
31
|
function bucketPrice(turn, allocation, rates) {
|
|
23
32
|
const quantities = allocation.categories;
|
|
24
33
|
if (Object.values(quantities).every(value => value === 0))
|
|
@@ -31,13 +40,17 @@ function bucketPrice(turn, allocation, rates) {
|
|
|
31
40
|
cacheWrite5mTokens: completeWrites ? turn.cacheWrite5mTokens : undefined,
|
|
32
41
|
cacheWrite1hTokens: completeWrites ? turn.cacheWrite1hTokens : undefined }, rates).usd;
|
|
33
42
|
}
|
|
43
|
+
/** Left-aligned columns two spaces apart; widths follow the widest cell, so translated labels widen their column. */
|
|
34
44
|
function table(headers, rows) {
|
|
35
45
|
const widths = headers.map((header, i) => Math.max(header.length, ...rows.map(row => row[i]?.length ?? 0)));
|
|
36
46
|
return [headers, ...rows].map(row => row.map((cell, i) => cell.padEnd(widths[i])).join(' ').trimEnd()).join('\n');
|
|
37
47
|
}
|
|
48
|
+
/** Token counts in en-US digits in every language. */
|
|
38
49
|
const count = (n) => n.toLocaleString('en-US');
|
|
50
|
+
exports.count = count;
|
|
39
51
|
/** The table's share column; the tip prints the same figure. */
|
|
40
52
|
const share = (tokens, total) => `${(total ? tokens / total * 100 : 0).toFixed(1)}%`;
|
|
53
|
+
exports.share = share;
|
|
41
54
|
const midpoint = (value) => (value.min + value.max) / 2;
|
|
42
55
|
exports.WHY_TIP_HIDE_LINE = i18n_1.WHY_TEXT.en.hide;
|
|
43
56
|
/**
|
|
@@ -50,11 +63,11 @@ function whyTip(input, lang = 'en') {
|
|
|
50
63
|
const { totalTokens, fanoutTokens, historyTokens, rewriteUsd, totalUsd } = input;
|
|
51
64
|
const text = i18n_1.WHY_TEXT[lang];
|
|
52
65
|
if (totalTokens > 0 && fanoutTokens / totalTokens >= 0.2)
|
|
53
|
-
return text.tipFanout(share(fanoutTokens, totalTokens));
|
|
66
|
+
return text.tipFanout((0, exports.share)(fanoutTokens, totalTokens));
|
|
54
67
|
if (rewriteUsd && totalUsd && midpoint(totalUsd) > 0 && midpoint(rewriteUsd) / midpoint(totalUsd) >= 0.15)
|
|
55
68
|
return text.tipRewrites((0, live_1.dollars)(rewriteUsd, text), (0, live_1.dollars)(totalUsd, text));
|
|
56
69
|
if (totalTokens > 0 && historyTokens / totalTokens >= 0.3)
|
|
57
|
-
return text.tipHistory(share(historyTokens, totalTokens));
|
|
70
|
+
return text.tipHistory((0, exports.share)(historyTokens, totalTokens));
|
|
58
71
|
return null;
|
|
59
72
|
}
|
|
60
73
|
/** `lang` changes words only: every figure, id, command and URL prints as it does in English, and `why json` never passes through here. */
|
|
@@ -67,31 +80,27 @@ function renderWhy(transcript, rates = {}, options = {}) {
|
|
|
67
80
|
text.forkUnavailable,
|
|
68
81
|
table(text.headers, types_1.INSIGHT_BUCKETS.map(bucket => [text.labels[bucket], text.unattributed, text.unattributed, text.unattributed, text.unattributed])),
|
|
69
82
|
].join('\n');
|
|
70
|
-
const turns
|
|
71
|
-
const
|
|
83
|
+
const { turns, attribution, prices, totals, totalUsd } = sessionFigures(transcript, rates);
|
|
84
|
+
const lastAttribution = attribution.turnAttributions.at(-1);
|
|
72
85
|
const byTurn = new Map(attribution.turnAttributions.map(turn => [turn.turnId, turn]));
|
|
73
|
-
const prices = turns.map(turn => (0, pricing_1.priceTurn)(turn, rates));
|
|
74
86
|
const mixedWriteAllocation = turns.some(turn => (turn.cacheWrite5mTokens ?? 0) > 0 && (turn.cacheWrite1hTokens ?? 0) > 0
|
|
75
87
|
&& byTurn.get(turn.id).buckets.some(bucket => bucket.categories.cacheCreation > 0 && bucket.categories.cacheCreation < turn.cacheWriteTokens));
|
|
76
|
-
const totals = { input: 0, write: 0, read: 0, output: 0 };
|
|
77
|
-
turns.forEach(turn => { totals.input += turn.inputTokens; totals.write += turn.cacheWriteTokens; totals.read += turn.cacheReadTokens; totals.output += turn.outputTokens; });
|
|
78
88
|
const bucketTokens = (bucket) => attribution.buckets.find(item => item.bucket === bucket).tokens;
|
|
79
89
|
const bucketUsd = (bucket) => sumPrices(turns.map(turn => bucketPrice(turn, byTurn.get(turn.id).buckets.find(item => item.bucket === bucket), rates)));
|
|
80
|
-
const totalUsd = sumPrices(prices.map(price => price.usd));
|
|
81
90
|
const rows = types_1.INSIGHT_BUCKETS.map(bucket => {
|
|
82
91
|
const tokens = bucketTokens(bucket), lastTokens = lastAttribution?.buckets.find(item => item.bucket === bucket).tokens ?? 0;
|
|
83
|
-
return [text.labels[bucket], count(tokens), money(bucketUsd(bucket)), share(tokens, attribution.totalTokens), share(lastTokens, lastAttribution?.totalTokens ?? 0)];
|
|
92
|
+
return [text.labels[bucket], (0, exports.count)(tokens), money(bucketUsd(bucket)), (0, exports.share)(tokens, attribution.totalTokens), (0, exports.share)(lastTokens, lastAttribution?.totalTokens ?? 0)];
|
|
84
93
|
});
|
|
85
94
|
const unknownModels = [...new Set(prices.filter(price => price.usd === null).map(price => price.model ?? text.missingModel))];
|
|
86
95
|
const tip = options.tips ? whyTip({ totalTokens: attribution.totalTokens, fanoutTokens: bucketTokens('subagent_fanout'),
|
|
87
96
|
historyTokens: bucketTokens('history_resent'), rewriteUsd: bucketUsd('full_prefix_rewrites'), totalUsd }, lang) : null;
|
|
88
97
|
return [
|
|
89
98
|
`AgentGuard why: ${transcript.sessionId}`,
|
|
90
|
-
text.summary(turns.length, count(attribution.totalTokens), totalUsd === null ? null : money(totalUsd)),
|
|
91
|
-
text.usage(count(totals.input), count(totals.write), count(totals.read), count(totals.output)),
|
|
99
|
+
text.summary(turns.length, (0, exports.count)(attribution.totalTokens), totalUsd === null ? null : money(totalUsd)),
|
|
100
|
+
text.usage((0, exports.count)(totals.input), (0, exports.count)(totals.write), (0, exports.count)(totals.read), (0, exports.count)(totals.output)),
|
|
92
101
|
'', table(text.headers, rows), '',
|
|
93
102
|
text.shares,
|
|
94
|
-
text.increments(attribution.sharedTurns, attribution.prefixRebaselines, count(attribution.previousOutputTokensReserved)),
|
|
103
|
+
text.increments(attribution.sharedTurns, attribution.prefixRebaselines, (0, exports.count)(attribution.previousOutputTokensReserved)),
|
|
95
104
|
text.observed(transcript.observations),
|
|
96
105
|
'', text.methodTitle,
|
|
97
106
|
...types_1.INSIGHT_BUCKETS.map(bucket => `${text.labels[bucket]}: ${text.method[bucket]}`),
|
|
@@ -145,15 +154,15 @@ function renderRewrites(transcripts, rates = {}) {
|
|
|
145
154
|
for (const session of report.sessions) {
|
|
146
155
|
const groups = new Map();
|
|
147
156
|
session.records.forEach(record => {
|
|
148
|
-
detail.push([stamp(record.at), session.sessionId, session.host, record.model ?? 'unknown', record.cause, idle(record.idleMs), count(record.cacheWriteTokens), (0, live_1.dollars)(record.usd), record.explanation]);
|
|
157
|
+
detail.push([stamp(record.at), session.sessionId, session.host, record.model ?? 'unknown', record.cause, idle(record.idleMs), (0, exports.count)(record.cacheWriteTokens), (0, live_1.dollars)(record.usd), record.explanation]);
|
|
149
158
|
groups.set(record.cause, [...groups.get(record.cause) ?? [], record]);
|
|
150
159
|
totals.set(record.cause, [...totals.get(record.cause) ?? [], record]);
|
|
151
160
|
});
|
|
152
161
|
for (const [cause, records] of groups)
|
|
153
|
-
summary.push([session.sessionId, cause, String(records.length), count(records.reduce((sum, record) => sum + record.cacheWriteTokens, 0)), (0, live_1.dollars)(sumPrices(records.map(record => record.usd)))]);
|
|
162
|
+
summary.push([session.sessionId, cause, String(records.length), (0, exports.count)(records.reduce((sum, record) => sum + record.cacheWriteTokens, 0)), (0, live_1.dollars)(sumPrices(records.map(record => record.usd)))]);
|
|
154
163
|
}
|
|
155
164
|
for (const [cause, records] of totals)
|
|
156
|
-
summary.push(['ALL', cause, String(records.length), count(records.reduce((sum, record) => sum + record.cacheWriteTokens, 0)), (0, live_1.dollars)(sumPrices(records.map(record => record.usd)))]);
|
|
165
|
+
summary.push(['ALL', cause, String(records.length), (0, exports.count)(records.reduce((sum, record) => sum + record.cacheWriteTokens, 0)), (0, live_1.dollars)(sumPrices(records.map(record => record.usd)))]);
|
|
157
166
|
const sessions = report.sessions.length === 1 ? 'session' : 'combined session';
|
|
158
167
|
const share = report.usd && report.sessionUsd && report.shareOfSessionUsd !== null
|
|
159
168
|
? `Rewrites: ${(0, live_1.dollars)(report.usd)}, ${(report.shareOfSessionUsd * 100).toFixed(1)}% of the ${sessions} list total ${(0, live_1.dollars)(report.sessionUsd)} (API list equivalent, not a bill).`
|
|
@@ -4,11 +4,36 @@ export interface TranscriptLocation {
|
|
|
4
4
|
sessionId: string;
|
|
5
5
|
modifiedAt: number;
|
|
6
6
|
}
|
|
7
|
+
/** Claude Code keeps one directory per project here, each session a JSONL file directly inside it; Codex keeps dated rollouts. */
|
|
8
|
+
export declare function transcriptRoots(): {
|
|
9
|
+
claude: string;
|
|
10
|
+
codex: string;
|
|
11
|
+
};
|
|
7
12
|
/** Local locators only. Never follows directory symlinks or reads message content. */
|
|
8
13
|
export declare function discoverInsightTranscripts(roots?: {
|
|
9
14
|
claude: string;
|
|
10
15
|
codex: string;
|
|
11
16
|
}): TranscriptLocation[];
|
|
12
17
|
export declare function selectInsightTranscript(session?: string, locations?: TranscriptLocation[]): TranscriptLocation;
|
|
18
|
+
/**
|
|
19
|
+
* A file Claude Code keeps inside a session's own directory, such as
|
|
20
|
+
* `<session>/skill-injections.jsonl`. It is not a session, so a no-argument
|
|
21
|
+
* `why` must not pick it even when it is the newest file on disk.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isSessionSidecar(location: Pick<TranscriptLocation, 'path' | 'sessionId'>): boolean;
|
|
13
24
|
/** Claude Code stores each subagent's transcript beside its parent under `subagents/`. */
|
|
14
25
|
export declare function isSubagentTranscript(location: Pick<TranscriptLocation, 'path' | 'sessionId'>): boolean;
|
|
26
|
+
export interface TranscriptOrigin {
|
|
27
|
+
/** The working directory the host recorded as the session began; null when the first megabyte records none. */
|
|
28
|
+
workingDirectory: string | null;
|
|
29
|
+
/** The usage parser's verdict on those same first records: a spawned sub-agent (Codex session_meta, Claude sidechain). */
|
|
30
|
+
spawned: boolean;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Where a transcript ran, from its first complete records only: the working
|
|
34
|
+
* directory the host recorded (Claude Code writes `cwd` on its records, Codex on
|
|
35
|
+
* its session_meta and turn_context payloads) and whether the usage parser marks
|
|
36
|
+
* those records a spawned sub-agent. Reads at most one megabyte, stops at the
|
|
37
|
+
* first recorded directory and keeps no other field.
|
|
38
|
+
*/
|
|
39
|
+
export declare function transcriptOrigin(location: Pick<TranscriptLocation, 'path' | 'host'>): TranscriptOrigin;
|
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.transcriptRoots = transcriptRoots;
|
|
3
4
|
exports.discoverInsightTranscripts = discoverInsightTranscripts;
|
|
4
5
|
exports.selectInsightTranscript = selectInsightTranscript;
|
|
6
|
+
exports.isSessionSidecar = isSessionSidecar;
|
|
5
7
|
exports.isSubagentTranscript = isSubagentTranscript;
|
|
8
|
+
exports.transcriptOrigin = transcriptOrigin;
|
|
6
9
|
const node_fs_1 = require("node:fs");
|
|
7
10
|
const node_path_1 = require("node:path");
|
|
8
11
|
const node_os_1 = require("node:os");
|
|
12
|
+
const transcript_1 = require("./transcript");
|
|
13
|
+
/** Claude Code keeps one directory per project here, each session a JSONL file directly inside it; Codex keeps dated rollouts. */
|
|
14
|
+
function transcriptRoots() {
|
|
15
|
+
return { claude: (0, node_path_1.join)((0, node_os_1.homedir)(), '.claude', 'projects'), codex: (0, node_path_1.join)((0, node_os_1.homedir)(), '.codex', 'sessions') };
|
|
16
|
+
}
|
|
9
17
|
/** Local locators only. Never follows directory symlinks or reads message content. */
|
|
10
|
-
function discoverInsightTranscripts(roots = {
|
|
11
|
-
claude: (0, node_path_1.join)((0, node_os_1.homedir)(), '.claude', 'projects'),
|
|
12
|
-
codex: (0, node_path_1.join)((0, node_os_1.homedir)(), '.codex', 'sessions'),
|
|
13
|
-
}) {
|
|
18
|
+
function discoverInsightTranscripts(roots = transcriptRoots()) {
|
|
14
19
|
const found = [];
|
|
15
20
|
function visit(directory, host, depth) {
|
|
16
21
|
if (depth > 8)
|
|
@@ -51,12 +56,74 @@ function selectInsightTranscript(session, locations) {
|
|
|
51
56
|
// nothing else, which tells the operator nothing. It stays reachable by id.
|
|
52
57
|
const selected = requested
|
|
53
58
|
? candidates.find(item => item.sessionId === requested || item.sessionId.endsWith(`-${requested}`))
|
|
54
|
-
: candidates.find(item => !isSubagentTranscript(item)) ?? candidates[0];
|
|
59
|
+
: candidates.find(item => !isSubagentTranscript(item) && !isSessionSidecar(item)) ?? candidates[0];
|
|
55
60
|
if (!selected)
|
|
56
61
|
throw new Error(requested ? 'Session transcript not found. Pass its local JSONL path.' : 'No local Claude Code or Codex transcript found.');
|
|
57
62
|
return selected;
|
|
58
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* A file Claude Code keeps inside a session's own directory, such as
|
|
66
|
+
* `<session>/skill-injections.jsonl`. It is not a session, so a no-argument
|
|
67
|
+
* `why` must not pick it even when it is the newest file on disk.
|
|
68
|
+
*/
|
|
69
|
+
function isSessionSidecar(location) {
|
|
70
|
+
return location.sessionId === 'skill-injections'
|
|
71
|
+
|| /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test((0, node_path_1.basename)((0, node_path_1.dirname)(location.path)));
|
|
72
|
+
}
|
|
59
73
|
/** Claude Code stores each subagent's transcript beside its parent under `subagents/`. */
|
|
60
74
|
function isSubagentTranscript(location) {
|
|
61
75
|
return (0, node_path_1.basename)((0, node_path_1.dirname)(location.path)) === 'subagents' || location.sessionId.startsWith('agent-');
|
|
62
76
|
}
|
|
77
|
+
const ORIGIN_CHUNK_BYTES = 64 * 1024, ORIGIN_LIMIT_BYTES = 1024 * 1024;
|
|
78
|
+
/**
|
|
79
|
+
* Where a transcript ran, from its first complete records only: the working
|
|
80
|
+
* directory the host recorded (Claude Code writes `cwd` on its records, Codex on
|
|
81
|
+
* its session_meta and turn_context payloads) and whether the usage parser marks
|
|
82
|
+
* those records a spawned sub-agent. Reads at most one megabyte, stops at the
|
|
83
|
+
* first recorded directory and keeps no other field.
|
|
84
|
+
*/
|
|
85
|
+
function transcriptOrigin(location) {
|
|
86
|
+
const lines = [];
|
|
87
|
+
let workingDirectory = null, fd;
|
|
88
|
+
try {
|
|
89
|
+
fd = (0, node_fs_1.openSync)(location.path, 'r');
|
|
90
|
+
let pending = Buffer.alloc(0), offset = 0;
|
|
91
|
+
while (workingDirectory === null && offset < ORIGIN_LIMIT_BYTES) {
|
|
92
|
+
const chunk = Buffer.alloc(Math.min(ORIGIN_CHUNK_BYTES, ORIGIN_LIMIT_BYTES - offset));
|
|
93
|
+
const read = (0, node_fs_1.readSync)(fd, chunk, 0, chunk.length, offset);
|
|
94
|
+
if (!read)
|
|
95
|
+
break;
|
|
96
|
+
offset += read;
|
|
97
|
+
pending = Buffer.concat([pending, chunk.subarray(0, read)]);
|
|
98
|
+
for (let newline = pending.indexOf(10); workingDirectory === null && newline >= 0; newline = pending.indexOf(10)) {
|
|
99
|
+
const line = pending.subarray(0, newline).toString('utf8');
|
|
100
|
+
pending = pending.subarray(newline + 1);
|
|
101
|
+
if (!line.trim())
|
|
102
|
+
continue;
|
|
103
|
+
lines.push(line);
|
|
104
|
+
workingDirectory = recordedDirectory(line);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
catch { /* unreadable or removed: nothing is recorded */ }
|
|
109
|
+
finally {
|
|
110
|
+
if (fd !== undefined)
|
|
111
|
+
(0, node_fs_1.closeSync)(fd);
|
|
112
|
+
}
|
|
113
|
+
return { workingDirectory, spawned: lines.length > 0 && (0, transcript_1.parseInsightTranscript)(`${lines.join('\n')}\n`, { host: location.host }).state.spawnedSession };
|
|
114
|
+
}
|
|
115
|
+
function recordedDirectory(line) {
|
|
116
|
+
let value;
|
|
117
|
+
try {
|
|
118
|
+
value = JSON.parse(line);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
if (!value || typeof value !== 'object')
|
|
124
|
+
return null;
|
|
125
|
+
const record = value;
|
|
126
|
+
const payload = record.payload && typeof record.payload === 'object' ? record.payload : {};
|
|
127
|
+
const cwd = typeof record.cwd === 'string' ? record.cwd : record.type === 'session_meta' || record.type === 'turn_context' ? payload.cwd : undefined;
|
|
128
|
+
return typeof cwd === 'string' && cwd.length > 0 ? cwd : null;
|
|
129
|
+
}
|
|
@@ -158,6 +158,9 @@ export interface RewriteEvidence {
|
|
|
158
158
|
ttlUnknown: boolean;
|
|
159
159
|
explanation: string;
|
|
160
160
|
}
|
|
161
|
+
/** The rows `compare` prints for each session, in table order. */
|
|
162
|
+
export declare const COMPARE_METRICS: readonly ["assistantResponses", "inputTokens", "cacheReadTokens", "cacheWriteTokens", "freshInputTokens", "cacheShare", "outputTokens", "subagentsLaunched", "fullPrefixRewrites", "usd"];
|
|
163
|
+
export type CompareMetric = typeof COMPARE_METRICS[number];
|
|
161
164
|
export interface BucketAttribution {
|
|
162
165
|
bucket: InsightBucket;
|
|
163
166
|
tokens: number;
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.REWRITE_CAUSES = exports.INSIGHT_BUCKETS = void 0;
|
|
3
|
+
exports.COMPARE_METRICS = exports.REWRITE_CAUSES = exports.INSIGHT_BUCKETS = void 0;
|
|
4
4
|
exports.INSIGHT_BUCKETS = ['instruction_stack', 'history_resent', 'reread_files', 'subagent_fanout', 'tool_output', 'conversation', 'full_prefix_rewrites', 'output', 'unattributed'];
|
|
5
5
|
exports.REWRITE_CAUSES = ['model_switch', 'version_upgrade', 'compaction', 'first_spawned_turn', 'idle_ttl_expired', 'image_pruning', 'prefix_change', 'unknown_ttl', 'unknown'];
|
|
6
|
+
/** The rows `compare` prints for each session, in table order. */
|
|
7
|
+
exports.COMPARE_METRICS = ['assistantResponses', 'inputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'freshInputTokens', 'cacheShare', 'outputTokens', 'subagentsLaunched', 'fullPrefixRewrites', 'usd'];
|
package/dist/src/stop-text.d.ts
CHANGED
|
@@ -10,10 +10,12 @@ import type { BurnReport } from './types';
|
|
|
10
10
|
/** Where the person continues from. */
|
|
11
11
|
export type StopHost = 'claude-code' | 'codex' | 'cursor';
|
|
12
12
|
/**
|
|
13
|
-
* The override the person runs. The
|
|
14
|
-
*
|
|
13
|
+
* The override the person runs. The unscoped `agentguard-burn` launcher runs
|
|
14
|
+
* the latest Burn through npx, so it works for everyone, including plugin-only
|
|
15
|
+
* installs that never put a Burn binary on PATH, and it has no "@" for X to
|
|
16
|
+
* turn into a mention link when it is quoted in a post.
|
|
15
17
|
*/
|
|
16
|
-
export declare const OVERRIDE_COMMAND = "npx
|
|
18
|
+
export declare const OVERRIDE_COMMAND = "npx agentguard-burn resume --once --reason \"...\"";
|
|
17
19
|
/** The one limit that stopped this launch, in its own words and numbers. */
|
|
18
20
|
export declare function stopSummary(report: BurnReport): string;
|
|
19
21
|
/** The finding a one-line message should lead with: the STOP, else the first WARN, else the first finding. */
|
package/dist/src/stop-text.js
CHANGED
|
@@ -8,10 +8,12 @@ exports.continueLines = continueLines;
|
|
|
8
8
|
exports.askReason = askReason;
|
|
9
9
|
exports.overriddenLine = overriddenLine;
|
|
10
10
|
/**
|
|
11
|
-
* The override the person runs. The
|
|
12
|
-
*
|
|
11
|
+
* The override the person runs. The unscoped `agentguard-burn` launcher runs
|
|
12
|
+
* the latest Burn through npx, so it works for everyone, including plugin-only
|
|
13
|
+
* installs that never put a Burn binary on PATH, and it has no "@" for X to
|
|
14
|
+
* turn into a mention link when it is quoted in a post.
|
|
13
15
|
*/
|
|
14
|
-
exports.OVERRIDE_COMMAND = 'npx
|
|
16
|
+
exports.OVERRIDE_COMMAND = 'npx agentguard-burn resume --once --reason "..."';
|
|
15
17
|
function fmt(n) {
|
|
16
18
|
if (n >= 1e9)
|
|
17
19
|
return `${(n / 1e9).toFixed(2)}B`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentguard-run/burn",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.19",
|
|
4
4
|
"description": "Local session usage and runaway-agent circuit breaker. Explain tokens, cache rewrites and API list cost, track pace, warn on heavy turns, and gate agent fan-out with signed receipts. Developer command ranking requires explicit --rank.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"type": "commonjs",
|