@agentguard-run/burn 0.3.12 → 0.3.14
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 +13 -0
- package/README.md +73 -4
- package/dist/src/cli.js +16 -6
- package/dist/src/defaults.js +1 -0
- package/dist/src/detectors/evaluate.js +10 -1
- package/dist/src/insights/attribution.d.ts +6 -0
- package/dist/src/insights/attribution.js +37 -11
- package/dist/src/insights/pricing.d.ts +16 -0
- package/dist/src/insights/pricing.js +17 -1
- package/dist/src/insights/render.d.ts +47 -2
- package/dist/src/insights/render.js +42 -13
- package/dist/src/insights/sessions.d.ts +2 -0
- package/dist/src/insights/sessions.js +12 -1
- package/dist/src/insights/transcript.js +53 -2
- package/dist/src/insights/ttl.d.ts +42 -0
- package/dist/src/insights/ttl.js +105 -0
- package/dist/src/insights/types.d.ts +19 -1
- package/dist/src/insights/types.js +2 -1
- package/dist/src/types.d.ts +8 -0
- package/docs/USAGE_AND_PRICING.md +18 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.14 (2026-09-24)
|
|
4
|
+
|
|
5
|
+
- `rewrites` names the cause of every cache miss, in a fixed precedence: `model_switch` (the model differs from the previous usage turn), `version_upgrade` (Claude Code's recorded `version` differs), `compaction`, `first_spawned_turn`, `idle_ttl_expired`, `image_pruning` (an earlier message re-recorded with fewer image or PDF blocks), then a host-reported `prefix_change`. The remainder is `prefix_change` as a stated residual or `unknown_ttl`. Effort changes, fast mode and tool definition changes are not in any transcript, and Claude Code does not persist image pruning, so the explanation says so instead of guessing. Codex takes the model from `turn_context` and compaction from `compacted`; a Codex rewrite with neither signal is `unknown` with the reason, never prefix change by default.
|
|
6
|
+
- `rewrites` prints one row per rewrite (time, session, host, model, cause, idle gap, cache-write tokens, list USD, explanation), keeps the by-cause summary, and ends with the rewrite total as a share of the same session list total that `why` prints. With no session it follows `why`: the newest top-level session plus its stored child transcripts. `rewrites <session> json` has a stable schema: `{sessions: [{sessionId, host, records: [{at, model, cause, explanation, idleMs, cacheWriteTokens, usd}]}], totals: {count, cacheWriteTokens, usd, shareOfSessionUsd}}`.
|
|
7
|
+
- New `ttl [session|all] [json]`: a list-price counterfactual of a one-hour cache lifetime on your own recorded turns, per bucket (main conversation, subagent transcripts). Rewrites that followed an expired five-minute lifetime with an idle gap of at most one hour count as avoided and are repriced as cache reads; every other five-minute write is repriced at the one-hour write rate; the net at list price decides, and the verdict names the exact setting (`promptCacheTtl`, `subagentPromptCacheTtl`) or says plainly that five minutes wins. Unknown lifetimes stay excluded, with the count shown. Nothing here is a bill; the difference is stated only as a net at list price.
|
|
8
|
+
- `src/insights/pricing.ts` gains the prompt-caching multipliers as named constants (`CACHE_WRITE_5M_MULTIPLIER` 1.25, `CACHE_WRITE_1H_MULTIPLIER` 2, `CACHE_READ_MULTIPLIER` 0.1) with the Anthropic source; a model row's verified rates and local overrides take precedence.
|
|
9
|
+
- Parser: turns carry `hostVersion`, and signals carry `modelChanged`, `versionChanged` and `imagesDropped`. Image and PDF blocks are counted, never stored.
|
|
10
|
+
|
|
11
|
+
## 0.3.13 (2026-09-24)
|
|
12
|
+
|
|
13
|
+
- `why`, `blocks` and the other insight commands: with no session given, the newest top-level transcript is selected. A subagent's own transcript (`<session>/subagents/agent-*.jsonl`) was often the newest file on disk and, read alone, reported 100% fan-out and nothing else. Subagent transcripts stay selectable by id.
|
|
14
|
+
- `account.stopConcurrentSessions` (default `null`): a hard ceiling on live sessions for the machine. Above it, every spawn proposal on the machine is refused with an `account` STOP until a session finishes; other tool calls are untouched and a plain status evaluation only warns. For hosts that start sessions on their own, such as Claude Code Projects running threads locally. `calibrate` and `policy` print the machine line beside the spawn-rate line.
|
|
15
|
+
|
|
3
16
|
## 0.3.12 (2026-09-24)
|
|
4
17
|
|
|
5
18
|
- `render --playback <rate>` (1 to 4) for both the recorded render and the dashboard: a faster cut of the same recording. Recorded renders divide every frame interval by the rate and the header reads "RECORDED · 1.5x"; the dashboard samples recorded time at the rate and draws "PLAYBACK 1.5x" under the counters on every frame. Frame times in provenance stay in recorded time; provenance records `playback` (and `video_seconds` for the dashboard).
|
package/README.md
CHANGED
|
@@ -122,13 +122,76 @@ The line is WARN-only in both shadow and enforce modes. If only browser or works
|
|
|
122
122
|
|
|
123
123
|
macOS uses local process, file-handle and swap metadata. Linux uses `/proc` and available local tools, and says what could not be read. Windows prints `not supported on this platform yet` and exits successfully. See the [docs page draft](docs/burn-idle-audit.md) for the audit boundary and limitations.
|
|
124
124
|
|
|
125
|
+
## Name every cache miss
|
|
126
|
+
|
|
127
|
+
```sh
|
|
128
|
+
agentguard-burn rewrites
|
|
129
|
+
agentguard-burn rewrites SESSION_ID
|
|
130
|
+
agentguard-burn rewrites all
|
|
131
|
+
agentguard-burn rewrites SESSION_ID json
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
A full-prefix rewrite writes more than 150,000 tokens and more than half the actual input context. Every rewrite gets one row: when it happened, the session, the host, the model, the cause, the idle gap before it, the cache-write tokens, the list-price equivalent of that write and a one-line explanation. The by-cause summary follows, and the last line is the rewrite total as a share of the same session list total that `why` prints. Without a session, `rewrites` reads the newest top-level session plus its stored child transcripts, exactly as `why` does.
|
|
135
|
+
|
|
136
|
+
Causes are named in a fixed order, so a rewrite with several signals gets the first one that applies: `model_switch` (the model differs from the previous usage turn), `version_upgrade` (Claude Code's recorded `version` differs), `compaction`, `first_spawned_turn`, `idle_ttl_expired` (the idle gap exceeds the lifetime recorded for the write), `image_pruning` (an earlier message was re-recorded with fewer image or PDF blocks), then a host-reported `prefix_change`. What remains is `prefix_change` as a residual, or `unknown_ttl` when the lifetime is absent or mixed. Codex transcripts carry the model on `turn_context` and mark compaction with `compacted`; a Codex rewrite with neither signal is `unknown`, with the reason stated, never prefix change by default.
|
|
137
|
+
|
|
138
|
+
Three causes in Claude Code's cache-invalidation list are not written to the transcript, so Burn never names them: effort changes, fast mode and tool definition changes (MCP connect or disconnect, plugin toggles, denying a whole tool). Claude Code also does not persist image pruning; the `image_pruning` rule only fires when a message is re-recorded without its images. The explanation column says which of these could not be observed instead of guessing.
|
|
139
|
+
|
|
140
|
+
The synthetic fixture in `tests/fixtures/rewrite-fixtures.ts` renders as follows (rows shortened):
|
|
141
|
+
|
|
142
|
+
```text
|
|
143
|
+
AgentGuard rewrites: 10; 1 followed an idle gap over 60 minutes.
|
|
144
|
+
|
|
145
|
+
When Session Host Model Cause Idle Write tokens List ...
|
|
146
|
+
2026-09-24T09:20:00Z synthetic-claude-fixture claude claude-sonnet-5 idle_ttl_expired 20m 180,000 $0.45 ...
|
|
147
|
+
2026-09-24T09:22:00Z synthetic-claude-fixture claude claude-opus-5-5 model_switch 2m 180,000 $1.44 ...
|
|
148
|
+
2026-09-24T09:24:00Z synthetic-claude-fixture claude claude-opus-5-5 version_upgrade 2m 180,000 $1.44 ...
|
|
149
|
+
2026-09-24T09:26:00Z synthetic-claude-fixture claude claude-opus-5-5 compaction 2m 180,000 $0.90 ...
|
|
150
|
+
2026-09-24T12:26:00Z synthetic-claude-fixture claude claude-opus-5-5 idle_ttl_expired 3h 180,000 $1.44 ...
|
|
151
|
+
...
|
|
152
|
+
Rewrites: $9.47, 95.6% of the combined session list total $9.90 (API list equivalent, not a bill).
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The JSON form is stable: `{sessions: [{sessionId, host, records: [{at, model, cause, explanation, idleMs, cacheWriteTokens, usd}]}], totals: {count, cacheWriteTokens, usd, shareOfSessionUsd}}`. Rewrite tokens are always a subset of the measured cache-creation tokens; nothing is estimated from text.
|
|
156
|
+
|
|
157
|
+
## Cache lifetime from your own gaps
|
|
158
|
+
|
|
159
|
+
```sh
|
|
160
|
+
agentguard-burn ttl
|
|
161
|
+
agentguard-burn ttl SESSION_ID
|
|
162
|
+
agentguard-burn ttl all
|
|
163
|
+
agentguard-burn ttl SESSION_ID json
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
`ttl` answers one question from recorded turns: had the cache lifetime been one hour instead of five minutes, what would the same history have been billed at API list rates? A rewrite counts as avoided when it followed an expired five-minute lifetime with an idle gap of at most one hour; under a one-hour lifetime those tokens would have been billed as cache reads. Against that, every other write recorded with a five-minute lifetime would have been billed at the one-hour write rate. The report keeps the main conversation and subagent transcripts in separate buckets because Claude Code sets their lifetimes separately. Unknown lifetimes stay unknown and are excluded, with the excluded count shown.
|
|
167
|
+
|
|
168
|
+
The same fixture renders as:
|
|
169
|
+
|
|
170
|
+
```text
|
|
171
|
+
AgentGuard ttl: synthetic-claude-fixture, agent-synthetic-child
|
|
172
|
+
List-price counterfactual on recorded turns: the result is the net at list price, not a bill. Subscription users: read the token columns; every dollar column is the API list equivalent.
|
|
173
|
+
|
|
174
|
+
Bucket Rewrites avoided Avoided write tokens Billed at 5m Would have been reads Repriced 5m write tokens Extra at 1h rate Net at list
|
|
175
|
+
main 1 of 8 180,000 $0.45 $0.04 751,000 $2.07 -$1.66 (5m)
|
|
176
|
+
subagent 1 of 2 170,000 $0.42 $0.03 160,900 $0.24 +$0.15 (1h)
|
|
177
|
+
|
|
178
|
+
Rewrites avoided: full-prefix writes that followed an expired five-minute lifetime with an idle gap of at most one hour. Under a one-hour lifetime they would have been billed as cache reads, not writes.
|
|
179
|
+
Extra at 1h rate: every other write recorded with a five-minute lifetime would have been billed at the one-hour write rate instead. Net = billed at 5m minus reads minus extra.
|
|
180
|
+
main: 1 rewrite with an unknown lifetime excluded from the counterfactual
|
|
181
|
+
|
|
182
|
+
Main conversation: net favours 5m. Leave promptCacheTtl unset; the longer lifetime would have been billed more on these turns.
|
|
183
|
+
Subagent transcripts: net favours 1h. Set "subagentPromptCacheTtl": "1h" in settings.json.
|
|
184
|
+
On a Claude subscription within plan usage the main conversation already has a one-hour lifetime; API key and usage-credit sessions start at five minutes. Subagents, forks, compaction and titles stay at five minutes unless subagentPromptCacheTtl is set.
|
|
185
|
+
Multipliers relative to base input: 5m write 1.25x, 1h write 2x, cache read 0.1x; a model row's verified rates take precedence.
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Every dollar column is an API list equivalent; on a subscription, read the token columns. The multipliers come from Anthropic's prompt caching pricing (five-minute writes 1.25x base input, one-hour writes 2x, cache reads 0.1x) and only fill rates a model row leaves empty; the verified rates in the pricing table, and any local override, take precedence. The verdict lines name the exact setting: `"promptCacheTtl": "1h"` for the main conversation (or `CLAUDE_CODE_PROMPT_CACHE_TTL=1h`) and `"subagentPromptCacheTtl": "1h"` for subagents, forks, compaction and titles. On a Claude subscription within plan usage the main conversation already has a one-hour lifetime; API key and usage-credit sessions start at five minutes. When the net favours five minutes, the report says so plainly.
|
|
189
|
+
|
|
125
190
|
## Why this session
|
|
126
191
|
|
|
127
192
|
```sh
|
|
128
193
|
agentguard-burn why
|
|
129
194
|
agentguard-burn why SESSION_ID
|
|
130
|
-
agentguard-burn rewrites SESSION_ID
|
|
131
|
-
agentguard-burn rewrites all
|
|
132
195
|
agentguard-burn pace SESSION_ID
|
|
133
196
|
agentguard-burn pricing
|
|
134
197
|
```
|
|
@@ -141,8 +204,6 @@ Later cache reads up to the baseline go to instruction stack + system. Reads abo
|
|
|
141
204
|
|
|
142
205
|
Rewrite tokens and child transcript usage keep their own buckets. Prior output deducted from an input increment remains in the unattributed residual so every recorded input and output token is counted exactly once. Missing event evidence also remains there. Integer allocation preserves every token, and the Method footer explains each row.
|
|
143
206
|
|
|
144
|
-
A full-prefix rewrite writes more than 150,000 tokens and more than half the actual input context. Burn reports the observed cache lifetime and surrounding evidence: idle beyond that lifetime, immediate compaction, first subagent response, or residual prefix change. An unknown lifetime stays unknown. Each write is priced at its measured lifetime, or a range when that lifetime is unavailable.
|
|
145
|
-
|
|
146
207
|
Every tool hook updates a local pace file under the Burn home. Pace uses ten wall-clock minutes: cached means cache reads; uncached means fresh input, writes and output. The next-hour projection assumes that pace continues. A time-to-limit estimate requires rising, fresh host percentage samples from the same quota pool and reset window. No token-to-limit conversion or cache weighting is assumed. Without sufficient host data, the line says why the limit is unknown.
|
|
147
208
|
|
|
148
209
|
The new warnings are advisory in both modes. Cache rewrites warn once when their last-hour API list equivalent exceeds $5. A context crossing 500,000 tokens warns about processing time and compaction, estimates a cache rewrite, and suggests a fresh session with a handoff note. These warnings do not deny a tool call.
|
|
@@ -462,6 +523,14 @@ Both token limits default to `null`. Closed gateway sessions are excluded;
|
|
|
462
523
|
hook and gateway session files are both read. WARN never blocks. STOP records
|
|
463
524
|
a would-block decision in shadow and blocks new work only in enforce mode.
|
|
464
525
|
|
|
526
|
+
`account.stopConcurrentSessions` (default `null`) is a hard ceiling on live
|
|
527
|
+
sessions for the machine. Above it, every spawn proposal on the machine is
|
|
528
|
+
refused until a session finishes; other tool calls are untouched, and a plain
|
|
529
|
+
status evaluation only warns. It is meant for hosts that start sessions on
|
|
530
|
+
their own, such as Claude Code Projects running threads locally: the project
|
|
531
|
+
can run as many threads as it likes, but none of them may add copies while
|
|
532
|
+
the machine is over your number.
|
|
533
|
+
|
|
465
534
|
## Terminal canvas and local recordings
|
|
466
535
|
|
|
467
536
|
Interactive screens use a fixed 104 by 35 cell canvas, with mint for good, slate for neutral, amber for WARN and red for STOP. Smaller terminals drop side detail and paginate rows without wrapping. Use --no-color for the existing plain-text commands and hook cards. Hook JSON and the one-line statusline remain host protocols, with no canvas control sequences inserted.
|
package/dist/src/cli.js
CHANGED
|
@@ -80,6 +80,7 @@ const attribution_1 = require("./insights/attribution");
|
|
|
80
80
|
const pricing_1 = require("./insights/pricing");
|
|
81
81
|
const transcript_2 = require("./insights/transcript");
|
|
82
82
|
const render_2 = require("./insights/render");
|
|
83
|
+
const ttl_1 = require("./insights/ttl");
|
|
83
84
|
const blocks_1 = require("./insights/blocks");
|
|
84
85
|
const cli_1 = require("./idle/cli");
|
|
85
86
|
const HOME = process.env.AGENTGUARD_HOME ?? (0, node_path_1.join)((0, node_os_1.homedir)(), '.agentguard');
|
|
@@ -197,12 +198,18 @@ async function main(argv) {
|
|
|
197
198
|
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)))) } }, rest.includes('json') ? JSON.stringify(transcript, null, 2) + '\n' : (0, render_2.renderWhy)(transcript, (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME))) + '\n', rest.includes('json'));
|
|
198
199
|
return 0;
|
|
199
200
|
}
|
|
200
|
-
case 'rewrites':
|
|
201
|
+
case 'rewrites':
|
|
202
|
+
case 'ttl': {
|
|
203
|
+
// Like `why`: with no session, the newest top-level transcript plus its stored
|
|
204
|
+
// child transcripts; `all` reads every local transcript file on its own.
|
|
201
205
|
const session = rest.find(value => value !== 'json');
|
|
202
|
-
const
|
|
203
|
-
|
|
206
|
+
const transcripts = session === 'all'
|
|
207
|
+
? (0, sessions_1.discoverInsightTranscripts)().map(location => (0, transcript_1.readInsightTranscript)(location.path, { host: location.host, sessionId: location.sessionId }))
|
|
208
|
+
: [(() => { const location = (0, sessions_1.selectInsightTranscript)(session); return (0, transcript_1.readInsightSession)(location.path, { host: location.host, sessionId: location.sessionId }); })()];
|
|
204
209
|
const rates = (0, live_1.readPricing)(HOME, (0, pre_tool_use_1.loadPolicy)(HOME));
|
|
205
|
-
|
|
210
|
+
const json = rest.includes('json');
|
|
211
|
+
const report = command === 'ttl' ? (0, ttl_1.ttlReport)(transcripts, rates) : (0, render_2.rewriteReportJson)(transcripts, rates);
|
|
212
|
+
show({ kind: 'command', command, values: { ...report } }, json ? JSON.stringify(report, null, 2) + '\n' : (command === 'ttl' ? (0, ttl_1.renderTtl)(report) : (0, render_2.renderRewrites)(transcripts, rates)) + '\n', json);
|
|
206
213
|
return 0;
|
|
207
214
|
}
|
|
208
215
|
case 'pricing': {
|
|
@@ -278,6 +285,7 @@ async function main(argv) {
|
|
|
278
285
|
` sustained WARN ${(t.sustained.warnTokens / 1e9).toFixed(2)}B STOP ${(t.sustained.stopTokens / 1e9).toFixed(2)}B`,
|
|
279
286
|
` fan-out lifetime WARN ${t.fanout.warn}; STOP above ${t.fanout.stop} spawns in ${t.fanout.windowActiveMinutes ?? 120} active minutes; depth above ${t.fanout.maxDepth}`,
|
|
280
287
|
` spawn-rate WARN ${t.spawnRate?.warn ?? 8}; STOP ${t.spawnRate?.stop ?? 16} in ${t.spawnRate?.windowActiveMinutes ?? 15} active minutes; ${t.spawnRate?.enforce === false ? 'shadow only' : 'enforcing in enforce mode'}`,
|
|
288
|
+
` machine WARN above ${t.account?.warnConcurrentSessions ?? 4} live sessions; ${t.account?.stopConcurrentSessions != null ? `no new copies above ${t.account.stopConcurrentSessions}` : 'no concurrency ceiling (account.stopConcurrentSessions is null)'}`,
|
|
281
289
|
` burn-debt ${t.burnDebt.enabled ? `ON, baseline ${Math.round(t.burnDebt.baselinePerActiveMinute / 1e6)}M/active-min` : 'off'}`,
|
|
282
290
|
...result.notes.map((n) => ` note: ${n}`),
|
|
283
291
|
`Policy written to ${(0, node_path_1.join)(HOME, 'burn-policy.json')} in SHADOW mode.`,
|
|
@@ -295,6 +303,7 @@ async function main(argv) {
|
|
|
295
303
|
`mode: ${policy.mode}${policy.mode === 'enforce' ? ' (the next STOP blocks)' : ' (recording only; nothing is blocked)'}`,
|
|
296
304
|
`thresholds: fan-out lifetime WARN ${policy.thresholds.fanout.warn}; STOP above ${policy.thresholds.fanout.stop} spawns in ${policy.thresholds.fanout.windowActiveMinutes ?? 120} active minutes; depth above ${policy.thresholds.fanout.maxDepth}`,
|
|
297
305
|
`spawn-rate: WARN ${policy.thresholds.spawnRate?.warn ?? 8}; STOP ${policy.thresholds.spawnRate?.stop ?? 16} in ${policy.thresholds.spawnRate?.windowActiveMinutes ?? 15} active minutes; ${policy.thresholds.spawnRate?.enforce === false ? 'shadow only' : 'enforcing in enforce mode'}`,
|
|
306
|
+
`machine: WARN above ${policy.thresholds.account?.warnConcurrentSessions ?? 4} live sessions; ${policy.thresholds.account?.stopConcurrentSessions != null ? `no new copies above ${policy.thresholds.account.stopConcurrentSessions}` : 'no concurrency ceiling (account.stopConcurrentSessions is null)'}`,
|
|
298
307
|
`sustained: ${(policy.thresholds.sustained.warnTokens / 1e9).toFixed(1)}B/${(policy.thresholds.sustained.stopTokens / 1e9).toFixed(1)}B local-compute warn at ${lc?.warnConcurrent ?? 4} concurrent${lc?.stopConcurrent ? `, stop at ${lc.stopConcurrent}` : ' (no stop set)'}`,
|
|
299
308
|
policy.calibration ? `calibrated from ${policy.calibration.sessionsSampled} sessions` : 'using shipped defaults (run: agentguard-burn calibrate)',
|
|
300
309
|
`shadow observation: ${e.decisions} decisions over ${e.days.toFixed(1)} days`,
|
|
@@ -438,7 +447,7 @@ async function main(argv) {
|
|
|
438
447
|
return 0;
|
|
439
448
|
}
|
|
440
449
|
default:
|
|
441
|
-
show({ kind: 'command', command: 'help', values: { commands: ['ps', 'reap', 'live', 'record', 'render', 'blocks', 'limits', 'price-shadow', 'why', 'rewrites', 'pace', 'statusline', 'pricing', 'replay', 'calibrate', 'status', 'init', 'enforce', 'shadow', 'resume', 'proxy', 'conformance'] } }, 'agentguard-burn <ps|reap|live|record|render|blocks|limits|price-shadow|why|rewrites|pace|statusline|pricing|replay|calibrate|status|init|enforce|shadow|resume|proxy|conformance>\n' +
|
|
450
|
+
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', '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|proxy|conformance>\n' +
|
|
442
451
|
' ps [--json] local agent processes, held memory and workspace disk\n' +
|
|
443
452
|
' render <run.jsonl> --mp4 <out.mp4> [--gif <out.gif>] [--phone] local recorded-run export\n' +
|
|
444
453
|
' render <run.jsonl> --mp4 <out.mp4> --dashboard [--wide] [--economics <blocks.json>] dashboard export\n' +
|
|
@@ -450,7 +459,8 @@ async function main(argv) {
|
|
|
450
459
|
' limits [session|all] local plan walls and prior Burn decisions\n' +
|
|
451
460
|
' price-shadow [session|all] local child list-price exposure and sensitivity\n' +
|
|
452
461
|
' why [session] token attribution and API list-price equivalents\n' +
|
|
453
|
-
' rewrites [session|all] full-prefix cache
|
|
462
|
+
' rewrites [session|all] every full-prefix cache write with its cause, idle gap and list price\n' +
|
|
463
|
+
' ttl [session|all] one-hour cache lifetime counterfactual from your own idle gaps\n' +
|
|
454
464
|
' pace [session] ten-minute pace and next-hour projection\n' +
|
|
455
465
|
' statusline [session] one-line local status; accepts Claude status JSON\n' +
|
|
456
466
|
' pricing verified model rates and local overrides\n' +
|
package/dist/src/defaults.js
CHANGED
|
@@ -44,6 +44,7 @@ exports.DEFAULT_THRESHOLDS = {
|
|
|
44
44
|
warnTokens: null,
|
|
45
45
|
windowActiveMinutes: 300,
|
|
46
46
|
warnConcurrentSessions: 4,
|
|
47
|
+
stopConcurrentSessions: null,
|
|
47
48
|
},
|
|
48
49
|
// Local model runtimes. Elapsed request time is not GPU utilisation (it
|
|
49
50
|
// includes queueing and transport), so it is called occupied time and it
|
|
@@ -140,7 +140,16 @@ function evaluate(state, thresholds, proposedSpawnDepth = null, account) {
|
|
|
140
140
|
if (account && thresholds.account) {
|
|
141
141
|
const t = thresholds.account;
|
|
142
142
|
const live = account.sessions.filter((s) => account.now - s.lastEventAt <= account_1.ACTIVE_SESSION_WINDOW_MS);
|
|
143
|
-
if (live.length > t.
|
|
143
|
+
if (t.stopConcurrentSessions != null && live.length > t.stopConcurrentSessions) {
|
|
144
|
+
// The machine is over its concurrency ceiling. A spawn proposal is refused;
|
|
145
|
+
// a plain session evaluation only reports it, since nothing is being added.
|
|
146
|
+
const severity = proposedSpawnDepth !== null ? 'STOP' : 'WARN';
|
|
147
|
+
findings.push({ detector: 'account', verdict: severity,
|
|
148
|
+
summary: `${live.length} concurrent active sessions on this machine; ceiling is ${t.stopConcurrentSessions}. ${proposedSpawnDepth !== null ? 'No session may add a copy until one finishes.' : 'New copies are refused until one finishes.'}`,
|
|
149
|
+
observed: live.length, threshold: t.stopConcurrentSessions });
|
|
150
|
+
verdict = worst(verdict, severity);
|
|
151
|
+
}
|
|
152
|
+
else if (live.length > t.warnConcurrentSessions) {
|
|
144
153
|
findings.push({ detector: 'account', verdict: 'WARN',
|
|
145
154
|
summary: `${live.length} concurrent active sessions on this machine; warning threshold is ${t.warnConcurrentSessions}.`,
|
|
146
155
|
observed: live.length, threshold: t.warnConcurrentSessions });
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import { type AttributionSummary, type InsightTurn, type RewriteEvidence } from './types';
|
|
2
|
+
export declare const idleLabel: (idleMs: number) => string;
|
|
3
|
+
/**
|
|
4
|
+
* Names the cause of a full-prefix rewrite in fixed precedence: model switch,
|
|
5
|
+
* version upgrade, compaction, first spawned turn, expired lifetime, image drop,
|
|
6
|
+
* host-reported prefix change. What remains is a residual, stated as such.
|
|
7
|
+
*/
|
|
2
8
|
export declare function classifyRewrite(turn: InsightTurn): RewriteEvidence | null;
|
|
3
9
|
/** Partition measured usage; byte lengths only divide a measured increment among its recorded events. */
|
|
4
10
|
export declare function attributeTurns(turns: InsightTurn[]): AttributionSummary;
|
|
@@ -1,28 +1,54 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.idleLabel = void 0;
|
|
3
4
|
exports.classifyRewrite = classifyRewrite;
|
|
4
5
|
exports.attributeTurns = attributeTurns;
|
|
5
6
|
const types_1 = require("./types");
|
|
6
7
|
const transcript_1 = require("./transcript");
|
|
8
|
+
const idleLabel = (idleMs) => {
|
|
9
|
+
const seconds = Math.round(idleMs / 1000);
|
|
10
|
+
if (seconds < 60)
|
|
11
|
+
return `${seconds}s`;
|
|
12
|
+
const minutes = Math.round(seconds / 60);
|
|
13
|
+
if (minutes < 60)
|
|
14
|
+
return `${minutes}m`;
|
|
15
|
+
return minutes % 60 === 0 ? `${minutes / 60}h` : `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
|
|
16
|
+
};
|
|
17
|
+
exports.idleLabel = idleLabel;
|
|
18
|
+
const NOT_RECORDED = 'Effort changes, fast mode, tool definition changes (MCP connect or disconnect, plugin toggles, denying a whole tool) and image pruning are not recorded in Claude Code transcripts';
|
|
19
|
+
/**
|
|
20
|
+
* Names the cause of a full-prefix rewrite in fixed precedence: model switch,
|
|
21
|
+
* version upgrade, compaction, first spawned turn, expired lifetime, image drop,
|
|
22
|
+
* host-reported prefix change. What remains is a residual, stated as such.
|
|
23
|
+
*/
|
|
7
24
|
function classifyRewrite(turn) {
|
|
8
25
|
if (!(turn.cacheWriteTokens > 150_000 && turn.cacheWriteTokens > turn.contextTokens / 2))
|
|
9
26
|
return null;
|
|
10
|
-
const
|
|
27
|
+
const signals = turn.signals;
|
|
28
|
+
const idleMs = signals.idleMs;
|
|
11
29
|
const ttl = turn.cacheTtlSeconds;
|
|
12
30
|
const evidence = { turnId: turn.id, cacheWriteTokens: turn.cacheWriteTokens, contextTokens: turn.contextTokens,
|
|
13
31
|
...(idleMs !== undefined ? { idleMs } : {}), idleOver60Minutes: idleMs !== undefined && idleMs > 3_600_000,
|
|
14
32
|
...(ttl ? { ttlSeconds: ttl } : {}), ttlUnknown: !ttl };
|
|
33
|
+
if (signals.modelChanged)
|
|
34
|
+
return { ...evidence, cause: 'model_switch', explanation: `Model changed from ${signals.previousModel ?? 'unknown'} to ${turn.model ?? 'unknown'} since the previous usage turn; a model switch invalidates the whole cached prefix.` };
|
|
35
|
+
if (signals.versionChanged)
|
|
36
|
+
return { ...evidence, cause: 'version_upgrade', explanation: `Claude Code changed from ${signals.previousHostVersion ?? 'unknown'} to ${turn.hostVersion ?? 'unknown'} since the previous usage turn; an upgrade changes the system prompt and tool definitions.` };
|
|
37
|
+
if (signals.afterCompaction)
|
|
38
|
+
return { ...evidence, cause: 'compaction', explanation: 'A compaction boundary immediately precedes this usage turn; compaction replaces the conversation prefix.' };
|
|
39
|
+
if (signals.firstSpawnedTurn)
|
|
40
|
+
return { ...evidence, cause: 'first_spawned_turn', explanation: 'This is the first recorded usage turn in an explicitly identified subagent session; a new prefix is written once per spawn.' };
|
|
15
41
|
if (ttl && idleMs !== undefined && idleMs > ttl * 1000)
|
|
16
|
-
return { ...evidence, cause: 'idle_ttl_expired', explanation:
|
|
17
|
-
if (
|
|
18
|
-
return { ...evidence, cause: '
|
|
19
|
-
if (
|
|
20
|
-
return { ...evidence, cause: '
|
|
42
|
+
return { ...evidence, cause: 'idle_ttl_expired', explanation: `An idle gap of ${(0, exports.idleLabel)(idleMs)} exceeds the ${ttl === 300 ? 'five-minute' : 'one-hour'} lifetime recorded for this write; timing is consistent with expiration.` };
|
|
43
|
+
if (signals.imagesDropped)
|
|
44
|
+
return { ...evidence, cause: 'image_pruning', explanation: `${signals.imagesDropped} image or PDF block${signals.imagesDropped === 1 ? '' : 's'} in earlier messages were re-recorded without them before this turn; pruning changes earlier messages and invalidates the prefix from that point.` };
|
|
45
|
+
if (signals.prefixChanged)
|
|
46
|
+
return { ...evidence, cause: 'prefix_change', explanation: 'The host reports a changed prefix identifier without a model switch, version change, compaction, expired lifetime or image drop.' };
|
|
47
|
+
if (turn.host === 'codex')
|
|
48
|
+
return { ...evidence, cause: 'unknown', explanation: `No model switch, compaction or first spawned turn precedes this write, and Codex transcripts record no cache lifetime, prefix identity, effort change or tool definition change; ${idleMs === undefined ? 'no idle gap is recorded' : `the idle gap of ${(0, exports.idleLabel)(idleMs)} cannot be matched to a lifetime`}. Cause unknown.` };
|
|
21
49
|
if (!ttl)
|
|
22
|
-
return { ...evidence, cause: 'unknown_ttl', explanation:
|
|
23
|
-
return { ...evidence, cause: 'prefix_change', explanation: turn.
|
|
24
|
-
? 'The host reports a changed prefix identifier without an expired-TTL or compaction signal.'
|
|
25
|
-
: 'No expiration, compaction, or first-subagent-turn signal explains the rewrite; prefix change is a residual hypothesis, not an observed cause.' };
|
|
50
|
+
return { ...evidence, cause: 'unknown_ttl', explanation: `Cache lifetime is absent or mixed for this write; expiration cannot be distinguished from a prefix change. ${NOT_RECORDED}.` };
|
|
51
|
+
return { ...evidence, cause: 'prefix_change', explanation: `No model switch, version change, compaction, first spawned turn, expired lifetime or image drop is recorded before this turn. ${NOT_RECORDED}, so prefix change is a residual hypothesis, not an observed cause.` };
|
|
26
52
|
}
|
|
27
53
|
const tokenCategories = ['input', 'cacheCreation', 'cacheRead', 'output'];
|
|
28
54
|
const emptyBuckets = () => types_1.INSIGHT_BUCKETS.map(bucket => ({ bucket, tokens: 0,
|
|
@@ -45,7 +71,7 @@ function attributeTurns(turns) {
|
|
|
45
71
|
const buckets = emptyBuckets();
|
|
46
72
|
const byBucket = new Map(buckets.map(bucket => [bucket.bucket, bucket]));
|
|
47
73
|
const result = { buckets, totalTokens: 0, rewrites: [],
|
|
48
|
-
rewriteCounts:
|
|
74
|
+
rewriteCounts: Object.fromEntries(types_1.REWRITE_CAUSES.map(cause => [cause, 0])),
|
|
49
75
|
idleOver60MinuteRewrites: 0, uncertainties: [], turnAttributions: [], sharedTurns: 0,
|
|
50
76
|
prefixRebaselines: 0, previousOutputTokensReserved: 0 };
|
|
51
77
|
const uncertainties = new Set();
|
|
@@ -36,6 +36,22 @@ export interface TurnPrice {
|
|
|
36
36
|
unknownCacheWriteTokens: number;
|
|
37
37
|
reason?: string;
|
|
38
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* Prompt-caching multipliers relative to a model's base input rate, from
|
|
41
|
+
* Anthropic's prompt caching pricing (https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing):
|
|
42
|
+
* five-minute cache writes cost 1.25x base input, one-hour writes 2x, and cache
|
|
43
|
+
* reads 0.1x. They only fill a rate a model row leaves null; a row's verified
|
|
44
|
+
* cacheWrite5m, cacheWrite1h and cacheRead values, bundled or overridden, win.
|
|
45
|
+
*/
|
|
46
|
+
export declare const CACHE_WRITE_5M_MULTIPLIER = 1.25;
|
|
47
|
+
export declare const CACHE_WRITE_1H_MULTIPLIER = 2;
|
|
48
|
+
export declare const CACHE_READ_MULTIPLIER = 0.1;
|
|
49
|
+
/** Cache rates for one model: explicit table values first, multipliers of base input otherwise. */
|
|
50
|
+
export declare function cacheRates(rate: ModelPricing): {
|
|
51
|
+
write5m: number | null;
|
|
52
|
+
write1h: number | null;
|
|
53
|
+
read: number | null;
|
|
54
|
+
};
|
|
39
55
|
/** Exact IDs only. Never price an unknown model by a similar family name. */
|
|
40
56
|
export declare const MODEL_PRICING: PricingTable;
|
|
41
57
|
/** Local JSON only. Errors are generic so neither file contents nor paths leak. */
|
|
@@ -1,10 +1,26 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MODEL_PRICING = void 0;
|
|
3
|
+
exports.MODEL_PRICING = exports.CACHE_READ_MULTIPLIER = exports.CACHE_WRITE_1H_MULTIPLIER = exports.CACHE_WRITE_5M_MULTIPLIER = void 0;
|
|
4
|
+
exports.cacheRates = cacheRates;
|
|
4
5
|
exports.loadPricingOverrides = loadPricingOverrides;
|
|
5
6
|
exports.priceTurn = priceTurn;
|
|
6
7
|
const node_fs_1 = require("node:fs");
|
|
7
8
|
const SOURCE = 'https://platform.claude.com/docs/en/about-claude/pricing';
|
|
9
|
+
/**
|
|
10
|
+
* Prompt-caching multipliers relative to a model's base input rate, from
|
|
11
|
+
* Anthropic's prompt caching pricing (https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing):
|
|
12
|
+
* five-minute cache writes cost 1.25x base input, one-hour writes 2x, and cache
|
|
13
|
+
* reads 0.1x. They only fill a rate a model row leaves null; a row's verified
|
|
14
|
+
* cacheWrite5m, cacheWrite1h and cacheRead values, bundled or overridden, win.
|
|
15
|
+
*/
|
|
16
|
+
exports.CACHE_WRITE_5M_MULTIPLIER = 1.25;
|
|
17
|
+
exports.CACHE_WRITE_1H_MULTIPLIER = 2;
|
|
18
|
+
exports.CACHE_READ_MULTIPLIER = 0.1;
|
|
19
|
+
/** Cache rates for one model: explicit table values first, multipliers of base input otherwise. */
|
|
20
|
+
function cacheRates(rate) {
|
|
21
|
+
const derived = (multiplier) => rate.input === null ? null : rate.input * multiplier;
|
|
22
|
+
return { write5m: rate.cacheWrite5m ?? derived(exports.CACHE_WRITE_5M_MULTIPLIER), write1h: rate.cacheWrite1h ?? derived(exports.CACHE_WRITE_1H_MULTIPLIER), read: rate.cacheRead ?? derived(exports.CACHE_READ_MULTIPLIER) };
|
|
23
|
+
}
|
|
8
24
|
const DATE = '2026-09-17';
|
|
9
25
|
const rates = (input, cacheRead, cacheWrite5m, cacheWrite1h, output) => Object.freeze({ input, cacheRead, cacheWrite5m, cacheWrite1h, output, sourceUrl: SOURCE, verifiedAt: DATE });
|
|
10
26
|
const openaiRates = (input, cacheRead, cacheWrite, output, sourceUrl, longContext = true) => Object.freeze({ input, cacheRead, cacheWrite5m: cacheWrite, cacheWrite1h: cacheWrite, output, sourceUrl, verifiedAt: DATE,
|
|
@@ -1,8 +1,53 @@
|
|
|
1
1
|
import { type DollarRange, type PricingTable } from './pricing';
|
|
2
|
-
import { type InsightTranscript, type InsightTurn } from './types';
|
|
2
|
+
import { type InsightHost, type InsightTranscript, type InsightTurn, type RewriteCause, type RewriteEvidence } from './types';
|
|
3
3
|
export declare function sumPrices(values: Array<DollarRange | null>): DollarRange | null;
|
|
4
4
|
export declare function totalTokens(turn: InsightTurn): number;
|
|
5
5
|
export declare function renderWhy(transcript: InsightTranscript, rates?: PricingTable): string;
|
|
6
|
-
export
|
|
6
|
+
export interface RewriteRow extends RewriteEvidence {
|
|
7
|
+
sessionId: string;
|
|
8
|
+
host: InsightHost;
|
|
9
|
+
at?: number;
|
|
10
|
+
model?: string;
|
|
11
|
+
usd: DollarRange | null;
|
|
12
|
+
}
|
|
13
|
+
export interface RewriteReport {
|
|
14
|
+
sessions: Array<{
|
|
15
|
+
sessionId: string;
|
|
16
|
+
host: InsightHost;
|
|
17
|
+
records: RewriteRow[];
|
|
18
|
+
}>;
|
|
19
|
+
total: number;
|
|
20
|
+
excludedUnknownHistories: number;
|
|
21
|
+
idleOver60Minutes: number;
|
|
22
|
+
/** Sum of every rewrite's cache-write list price; null when any model is unpriced. */
|
|
23
|
+
usd: DollarRange | null;
|
|
24
|
+
/** The same list total `why` prints for these turns: every token category of every response. */
|
|
25
|
+
sessionUsd: DollarRange | null;
|
|
26
|
+
shareOfSessionUsd: number | null;
|
|
27
|
+
}
|
|
28
|
+
export declare function rewriteReport(transcripts: InsightTranscript[], rates?: PricingTable): RewriteReport;
|
|
29
|
+
/** Stable machine-readable form of `rewrites <session> json`. */
|
|
30
|
+
export interface RewriteReportJson {
|
|
31
|
+
sessions: Array<{
|
|
32
|
+
sessionId: string;
|
|
33
|
+
host: InsightHost;
|
|
34
|
+
records: Array<{
|
|
35
|
+
at: string | null;
|
|
36
|
+
model: string | null;
|
|
37
|
+
cause: RewriteCause;
|
|
38
|
+
explanation: string;
|
|
39
|
+
idleMs: number | null;
|
|
40
|
+
cacheWriteTokens: number;
|
|
41
|
+
usd: DollarRange | null;
|
|
42
|
+
}>;
|
|
43
|
+
}>;
|
|
44
|
+
totals: {
|
|
45
|
+
count: number;
|
|
46
|
+
cacheWriteTokens: number;
|
|
47
|
+
usd: DollarRange | null;
|
|
48
|
+
shareOfSessionUsd: number | null;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export declare function rewriteReportJson(transcripts: InsightTranscript[], rates?: PricingTable): RewriteReportJson;
|
|
7
52
|
export declare function renderRewrites(transcripts: InsightTranscript[], rates?: PricingTable): string;
|
|
8
53
|
export declare function renderPricing(overrides?: PricingTable): string;
|
|
@@ -4,6 +4,7 @@ exports.sumPrices = sumPrices;
|
|
|
4
4
|
exports.totalTokens = totalTokens;
|
|
5
5
|
exports.renderWhy = renderWhy;
|
|
6
6
|
exports.rewriteReport = rewriteReport;
|
|
7
|
+
exports.rewriteReportJson = rewriteReportJson;
|
|
7
8
|
exports.renderRewrites = renderRewrites;
|
|
8
9
|
exports.renderPricing = renderPricing;
|
|
9
10
|
const attribution_1 = require("./attribution");
|
|
@@ -84,41 +85,69 @@ function renderWhy(transcript, rates = {}) {
|
|
|
84
85
|
`Usage records de-duplicated: ${transcript.diagnostics.duplicateUsageRecords}. Malformed lines skipped: ${transcript.diagnostics.malformedLines}.`,
|
|
85
86
|
].join('\n');
|
|
86
87
|
}
|
|
88
|
+
const stamp = (at) => at === undefined ? 'unknown time' : new Date(at).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
89
|
+
const idle = (idleMs) => idleMs === undefined ? '-' : (0, attribution_1.idleLabel)(idleMs);
|
|
90
|
+
const midpoint = (value) => (value.min + value.max) / 2;
|
|
87
91
|
function rewriteReport(transcripts, rates = {}) {
|
|
92
|
+
const turns = (0, transcript_1.deduplicateTurns)(transcripts.flatMap(transcript => transcript.turns)).sort((a, b) => (a.at ?? 0) - (b.at ?? 0) || a.id.localeCompare(b.id));
|
|
88
93
|
const grouped = new Map();
|
|
89
|
-
for (const turn of
|
|
94
|
+
for (const turn of turns)
|
|
90
95
|
grouped.set(turn.sessionId, [...grouped.get(turn.sessionId) ?? [], turn]);
|
|
91
|
-
const sessions = [...grouped].map(([sessionId,
|
|
92
|
-
const records =
|
|
96
|
+
const sessions = [...grouped].map(([sessionId, sessionTurns]) => {
|
|
97
|
+
const records = sessionTurns.flatMap(turn => {
|
|
93
98
|
const rewrite = (0, attribution_1.classifyRewrite)(turn);
|
|
94
|
-
return rewrite ? [{ ...rewrite, sessionId, at: turn.at, model: turn.model,
|
|
99
|
+
return rewrite ? [{ ...rewrite, sessionId, host: turn.host, at: turn.at, model: turn.model,
|
|
95
100
|
usd: (0, pricing_1.priceTurn)({ ...turn, inputTokens: 0, cacheReadTokens: 0, outputTokens: 0 }, rates).usd }] : [];
|
|
96
101
|
});
|
|
97
|
-
return { sessionId, records };
|
|
102
|
+
return { sessionId, host: sessionTurns[0].host, records };
|
|
98
103
|
});
|
|
99
|
-
|
|
104
|
+
const records = sessions.flatMap(session => session.records);
|
|
105
|
+
const usd = sumPrices(records.map(record => record.usd));
|
|
106
|
+
const sessionUsd = sumPrices(turns.map(turn => (0, pricing_1.priceTurn)(turn, rates).usd));
|
|
107
|
+
return { sessions, total: records.length,
|
|
100
108
|
excludedUnknownHistories: transcripts.filter(transcript => transcript.state.forkHistoryBoundaryUnknown).length,
|
|
101
|
-
idleOver60Minutes:
|
|
109
|
+
idleOver60Minutes: records.filter(record => record.idleOver60Minutes).length,
|
|
110
|
+
usd, sessionUsd, shareOfSessionUsd: usd && sessionUsd && midpoint(sessionUsd) > 0 ? midpoint(usd) / midpoint(sessionUsd) : null };
|
|
111
|
+
}
|
|
112
|
+
function rewriteReportJson(transcripts, rates = {}) {
|
|
113
|
+
const report = rewriteReport(transcripts, rates);
|
|
114
|
+
return {
|
|
115
|
+
sessions: report.sessions.map(session => ({ sessionId: session.sessionId, host: session.host, records: session.records.map(record => ({
|
|
116
|
+
at: record.at === undefined ? null : new Date(record.at).toISOString(), model: record.model ?? null, cause: record.cause, explanation: record.explanation,
|
|
117
|
+
idleMs: record.idleMs ?? null, cacheWriteTokens: record.cacheWriteTokens, usd: record.usd
|
|
118
|
+
})) })),
|
|
119
|
+
totals: { count: report.total, cacheWriteTokens: report.sessions.flatMap(session => session.records).reduce((sum, record) => sum + record.cacheWriteTokens, 0),
|
|
120
|
+
usd: report.usd, shareOfSessionUsd: report.shareOfSessionUsd },
|
|
121
|
+
};
|
|
102
122
|
}
|
|
103
123
|
function renderRewrites(transcripts, rates = {}) {
|
|
104
124
|
const report = rewriteReport(transcripts, rates);
|
|
105
|
-
const
|
|
125
|
+
const detail = [];
|
|
126
|
+
const summary = [];
|
|
106
127
|
const totals = new Map();
|
|
107
128
|
for (const session of report.sessions) {
|
|
108
129
|
const groups = new Map();
|
|
109
130
|
session.records.forEach(record => {
|
|
131
|
+
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]);
|
|
110
132
|
groups.set(record.cause, [...groups.get(record.cause) ?? [], record]);
|
|
111
133
|
totals.set(record.cause, [...totals.get(record.cause) ?? [], record]);
|
|
112
134
|
});
|
|
113
135
|
for (const [cause, records] of groups)
|
|
114
|
-
|
|
136
|
+
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)))]);
|
|
115
137
|
}
|
|
116
138
|
for (const [cause, records] of totals)
|
|
117
|
-
|
|
139
|
+
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)))]);
|
|
140
|
+
const sessions = report.sessions.length === 1 ? 'session' : 'combined session';
|
|
141
|
+
const share = report.usd && report.sessionUsd && report.shareOfSessionUsd !== null
|
|
142
|
+
? `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).`
|
|
143
|
+
: `Rewrites: unpriced share of the ${sessions} list total; at least one model has no verified rate, so tokens are the comparable figure.`;
|
|
118
144
|
return [`AgentGuard rewrites: ${report.total}; ${report.idleOver60Minutes} followed an idle gap over 60 minutes.`,
|
|
119
|
-
table(['Session', 'Cause', '
|
|
120
|
-
|
|
121
|
-
|
|
145
|
+
...(detail.length ? ['', table(['When', 'Session', 'Host', 'Model', 'Cause', 'Idle', 'Write tokens', 'List USD', 'Explanation'], detail)] : []),
|
|
146
|
+
'', table(['Session', 'Cause', 'Count', 'Write tokens', 'List USD'], summary), '',
|
|
147
|
+
...(transcripts.some(transcript => transcript.state.forkHistoryBoundaryUnknown) ? [`Excluded ${report.excludedUnknownHistories} Codex histories whose inherited usage boundary is unknown. Counts are incomplete.`] : []),
|
|
148
|
+
'Causes in precedence order: model switch, version upgrade, compaction, first spawned turn, expired lifetime (observed idle time against the recorded lifetime), image drop, host-reported prefix change. Prefix change without a host signal is the residual explanation; an absent or mixed lifetime stays unknown.',
|
|
149
|
+
'Not recorded in transcripts, so never named: effort changes, fast mode, tool definition changes (MCP connect or disconnect, plugin toggles, denying a whole tool). Claude Code does not persist image pruning; Codex records no cache lifetime or prefix identity, so an unexplained Codex rewrite is unknown.',
|
|
150
|
+
share].join('\n');
|
|
122
151
|
}
|
|
123
152
|
function renderPricing(overrides = {}) {
|
|
124
153
|
const rows = Object.entries({ ...pricing_1.MODEL_PRICING, ...overrides }).map(([model, rate]) => [model, String(rate.input), String(rate.cacheRead), String(rate.cacheWrite5m), String(rate.cacheWrite1h), String(rate.output), rate.verifiedAt, rate.sourceUrl]);
|
|
@@ -10,3 +10,5 @@ export declare function discoverInsightTranscripts(roots?: {
|
|
|
10
10
|
codex: string;
|
|
11
11
|
}): TranscriptLocation[];
|
|
12
12
|
export declare function selectInsightTranscript(session?: string, locations?: TranscriptLocation[]): TranscriptLocation;
|
|
13
|
+
/** Claude Code stores each subagent's transcript beside its parent under `subagents/`. */
|
|
14
|
+
export declare function isSubagentTranscript(location: Pick<TranscriptLocation, 'path' | 'sessionId'>): boolean;
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.discoverInsightTranscripts = discoverInsightTranscripts;
|
|
4
4
|
exports.selectInsightTranscript = selectInsightTranscript;
|
|
5
|
+
exports.isSubagentTranscript = isSubagentTranscript;
|
|
5
6
|
const node_fs_1 = require("node:fs");
|
|
6
7
|
const node_path_1 = require("node:path");
|
|
7
8
|
const node_os_1 = require("node:os");
|
|
@@ -44,8 +45,18 @@ function selectInsightTranscript(session, locations) {
|
|
|
44
45
|
return { path, host: /(?:rollout-|[\\/]\.codex[\\/])/.test(path) ? 'codex' : 'claude', sessionId: (0, node_path_1.basename)(path, '.jsonl'), modifiedAt: (0, node_fs_1.statSync)(path).mtimeMs };
|
|
45
46
|
}
|
|
46
47
|
const candidates = locations ?? discoverInsightTranscripts();
|
|
47
|
-
|
|
48
|
+
// With nothing requested, the newest top-level session wins. A subagent's own
|
|
49
|
+
// transcript (Claude Code keeps them under <session>/subagents/agent-*.jsonl) is
|
|
50
|
+
// often the newest file on disk, and read alone it reports 100% fan-out and
|
|
51
|
+
// nothing else, which tells the operator nothing. It stays reachable by id.
|
|
52
|
+
const selected = requested
|
|
53
|
+
? candidates.find(item => item.sessionId === requested || item.sessionId.endsWith(`-${requested}`))
|
|
54
|
+
: candidates.find(item => !isSubagentTranscript(item)) ?? candidates[0];
|
|
48
55
|
if (!selected)
|
|
49
56
|
throw new Error(requested ? 'Session transcript not found. Pass its local JSONL path.' : 'No local Claude Code or Codex transcript found.');
|
|
50
57
|
return selected;
|
|
51
58
|
}
|
|
59
|
+
/** Claude Code stores each subagent's transcript beside its parent under `subagents/`. */
|
|
60
|
+
function isSubagentTranscript(location) {
|
|
61
|
+
return (0, node_path_1.basename)((0, node_path_1.dirname)(location.path)) === 'subagents' || location.sessionId.startsWith('agent-');
|
|
62
|
+
}
|
|
@@ -120,6 +120,46 @@ function observeTools(raw, state) {
|
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
|
+
/** Counts image and PDF blocks in one message; nested tool_result content is included. Nothing else is read. */
|
|
124
|
+
function imageBlockCount(content) {
|
|
125
|
+
if (!Array.isArray(content))
|
|
126
|
+
return 0;
|
|
127
|
+
let total = 0;
|
|
128
|
+
for (const value of content) {
|
|
129
|
+
const block = object(value);
|
|
130
|
+
if (block.type === 'image' || block.type === 'document' || block.type === 'input_image' || block.type === 'input_file')
|
|
131
|
+
total++;
|
|
132
|
+
else if (block.type === 'tool_result')
|
|
133
|
+
total += imageBlockCount(block.content);
|
|
134
|
+
}
|
|
135
|
+
return total;
|
|
136
|
+
}
|
|
137
|
+
/** A message re-recorded with fewer image or PDF blocks is the only observable drop in an append-only transcript. */
|
|
138
|
+
function observeImageBlocks(raw, state) {
|
|
139
|
+
const message = object(raw.message), payload = object(raw.payload);
|
|
140
|
+
let content, identity;
|
|
141
|
+
if (raw.type === 'user' || raw.type === 'assistant') {
|
|
142
|
+
content = message.content;
|
|
143
|
+
identity = raw.uuid ?? message.id ?? raw.id;
|
|
144
|
+
}
|
|
145
|
+
else if (raw.type === 'response_item' && payload.type === 'message') {
|
|
146
|
+
content = payload.content;
|
|
147
|
+
identity = payload.id ?? raw.id;
|
|
148
|
+
}
|
|
149
|
+
else
|
|
150
|
+
return;
|
|
151
|
+
if (identity === undefined)
|
|
152
|
+
return;
|
|
153
|
+
const key = digest(['message-images', identity]);
|
|
154
|
+
state.imageBlocksByMessage ??= {};
|
|
155
|
+
const previous = state.imageBlocksByMessage[key];
|
|
156
|
+
const current = imageBlockCount(content);
|
|
157
|
+
if (previous === undefined && current === 0)
|
|
158
|
+
return;
|
|
159
|
+
if (previous !== undefined && current < previous)
|
|
160
|
+
state.imagesDroppedPending = (state.imagesDroppedPending ?? 0) + (previous - current);
|
|
161
|
+
state.imageBlocksByMessage[key] = current;
|
|
162
|
+
}
|
|
123
163
|
function emptyInterval() {
|
|
124
164
|
return { toolOutputBytes: 0, reReadBytes: 0, conversationBytes: 0, toolResults: 0, userMessages: 0, shared: false };
|
|
125
165
|
}
|
|
@@ -313,6 +353,9 @@ function parseInsightTranscript(text, options = {}) {
|
|
|
313
353
|
}
|
|
314
354
|
observeTools(raw, state);
|
|
315
355
|
observeInputEvents(raw, state);
|
|
356
|
+
observeImageBlocks(raw, state);
|
|
357
|
+
if (identifier(raw.version) && /^\d+\.\d+/.test(String(raw.version)))
|
|
358
|
+
state.hostVersion = identifier(raw.version);
|
|
316
359
|
const host = detectHost(raw, usage, state.host);
|
|
317
360
|
if (state.host === 'unknown')
|
|
318
361
|
state.host = host;
|
|
@@ -400,14 +443,19 @@ function parseInsightTranscript(text, options = {}) {
|
|
|
400
443
|
uncertainties.push(knownSplits ? 'cache_ttl_mixed' : 'cache_ttl_unknown');
|
|
401
444
|
if ((hasCount(split5m) || hasCount(split1h)) && !knownSplits)
|
|
402
445
|
uncertainties.push('cache_write_ttl_split_inconsistent');
|
|
446
|
+
const modelChanged = state.lastTurnModel !== undefined && state.model !== undefined && state.model !== state.lastTurnModel;
|
|
447
|
+
const versionChanged = state.lastTurnVersion !== undefined && state.hostVersion !== undefined && state.hostVersion !== state.lastTurnVersion;
|
|
403
448
|
const turn = { id, sessionId: state.sessionId, host, ...(at !== undefined ? { at } : {}),
|
|
404
449
|
...(state.spawnedSession ? { subagent: true } : {}),
|
|
405
|
-
...(state.model ? { model: state.model } : {}), inputTokens, cacheWriteTokens, cacheReadTokens, outputTokens,
|
|
450
|
+
...(state.model ? { model: state.model } : {}), ...(state.hostVersion ? { hostVersion: state.hostVersion } : {}), inputTokens, cacheWriteTokens, cacheReadTokens, outputTokens,
|
|
406
451
|
...(knownSplits ? { cacheWrite5mTokens: count(split5m), cacheWrite1hTokens: count(split1h) } : {}),
|
|
407
452
|
...(cacheTtlSeconds ? { cacheTtlSeconds, cacheTtlSource } : {}), contextTokens: inputTokens + cacheWriteTokens + cacheReadTokens,
|
|
408
453
|
signals: existing?.signals ?? { afterCompaction: state.compactionPending, firstSpawnedTurn: state.spawnedSession && !state.forkHistoryBoundaryUnknown && seenCount === 0,
|
|
409
454
|
...(state.lastAt !== undefined && at !== undefined && at >= state.lastAt ? { idleMs: at - state.lastAt } : {}),
|
|
410
|
-
...(state.prefixChangedPending !== undefined ? { prefixChanged: state.prefixChangedPending } : {})
|
|
455
|
+
...(state.prefixChangedPending !== undefined ? { prefixChanged: state.prefixChangedPending } : {}),
|
|
456
|
+
...(modelChanged ? { modelChanged: true, previousModel: state.lastTurnModel } : {}),
|
|
457
|
+
...(versionChanged ? { versionChanged: true, previousHostVersion: state.lastTurnVersion } : {}),
|
|
458
|
+
...(state.imagesDroppedPending ? { imagesDropped: state.imagesDroppedPending } : {}) },
|
|
411
459
|
explicitAttribution: explicitAttribution(usage), uncertainties,
|
|
412
460
|
interval: existing?.interval ?? { ...state.pendingInterval } };
|
|
413
461
|
if (existing) {
|
|
@@ -435,6 +483,9 @@ function parseInsightTranscript(text, options = {}) {
|
|
|
435
483
|
state.conversationEcho = undefined;
|
|
436
484
|
state.compactionPending = false;
|
|
437
485
|
state.prefixChangedPending = undefined;
|
|
486
|
+
state.imagesDroppedPending = 0;
|
|
487
|
+
state.lastTurnModel = state.model;
|
|
488
|
+
state.lastTurnVersion = state.hostVersion;
|
|
438
489
|
seenCount++;
|
|
439
490
|
if (at !== undefined)
|
|
440
491
|
state.lastAt = at;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type PricingTable } from './pricing';
|
|
2
|
+
import type { InsightTranscript } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Cache-lifetime counterfactual from the operator's own recorded idle gaps.
|
|
5
|
+
* Everything here is an API list-price equivalent on turns that already ran.
|
|
6
|
+
* It never says what a bill was or what a subscription would have charged.
|
|
7
|
+
*/
|
|
8
|
+
export type TtlBucketName = 'main' | 'subagent';
|
|
9
|
+
export type TtlVerdict = '1h' | '5m' | 'even' | 'unknown' | 'unpriced';
|
|
10
|
+
export interface TtlBucket {
|
|
11
|
+
bucket: TtlBucketName;
|
|
12
|
+
turns: number;
|
|
13
|
+
rewrites: number;
|
|
14
|
+
/** Rewrites classified as an expired five-minute lifetime with an idle gap of at most one hour. */
|
|
15
|
+
avoided: number;
|
|
16
|
+
/** Rewrites whose lifetime is absent or mixed; they stay out of the counterfactual. */
|
|
17
|
+
excludedUnknownTtl: number;
|
|
18
|
+
avoidedCacheWriteTokens: number;
|
|
19
|
+
billedAtFiveMinuteUsd: number | null;
|
|
20
|
+
wouldHaveBeenReadsUsd: number | null;
|
|
21
|
+
/** Five-minute write tokens on every other turn, which a one-hour lifetime would have billed at the one-hour write rate. */
|
|
22
|
+
repricedFiveMinuteWriteTokens: number;
|
|
23
|
+
extraOneHourWriteUsd: number | null;
|
|
24
|
+
netAtListUsd: number | null;
|
|
25
|
+
favours: TtlVerdict;
|
|
26
|
+
}
|
|
27
|
+
export interface TtlReport {
|
|
28
|
+
sessions: string[];
|
|
29
|
+
buckets: TtlBucket[];
|
|
30
|
+
settings: {
|
|
31
|
+
promptCacheTtl: '1h' | null;
|
|
32
|
+
subagentPromptCacheTtl: '1h' | null;
|
|
33
|
+
};
|
|
34
|
+
basis: 'list_price_counterfactual_on_recorded_turns';
|
|
35
|
+
multipliers: {
|
|
36
|
+
cacheWrite5m: number;
|
|
37
|
+
cacheWrite1h: number;
|
|
38
|
+
cacheRead: number;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export declare function ttlReport(transcripts: InsightTranscript[], rates?: PricingTable): TtlReport;
|
|
42
|
+
export declare function renderTtl(report: TtlReport): string;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ttlReport = ttlReport;
|
|
4
|
+
exports.renderTtl = renderTtl;
|
|
5
|
+
const attribution_1 = require("./attribution");
|
|
6
|
+
const live_1 = require("./live");
|
|
7
|
+
const pricing_1 = require("./pricing");
|
|
8
|
+
const transcript_1 = require("./transcript");
|
|
9
|
+
const AVOIDABLE_IDLE_MS = 3600 * 1000;
|
|
10
|
+
const add = (total, value) => total === null || value === null ? null : total + value;
|
|
11
|
+
const perMillion = (tokens, rate) => tokens === 0 ? 0 : rate === null ? null : tokens * rate / 1_000_000;
|
|
12
|
+
function bucketFor(turns, bucket, rates) {
|
|
13
|
+
const result = { bucket, turns: turns.length, rewrites: 0, avoided: 0, excludedUnknownTtl: 0, avoidedCacheWriteTokens: 0,
|
|
14
|
+
billedAtFiveMinuteUsd: 0, wouldHaveBeenReadsUsd: 0, repricedFiveMinuteWriteTokens: 0, extraOneHourWriteUsd: 0, netAtListUsd: null, favours: 'unknown' };
|
|
15
|
+
let known = false;
|
|
16
|
+
for (const turn of turns) {
|
|
17
|
+
const model = turn.model;
|
|
18
|
+
const rate = model === undefined ? undefined : Object.hasOwn(rates, model) ? rates[model] : Object.hasOwn(pricing_1.MODEL_PRICING, model) ? pricing_1.MODEL_PRICING[model] : undefined;
|
|
19
|
+
const cache = rate ? (0, pricing_1.cacheRates)(rate) : { write5m: null, write1h: null, read: null };
|
|
20
|
+
const rewrite = (0, attribution_1.classifyRewrite)(turn);
|
|
21
|
+
if (rewrite) {
|
|
22
|
+
result.rewrites++;
|
|
23
|
+
if (rewrite.ttlUnknown)
|
|
24
|
+
result.excludedUnknownTtl++;
|
|
25
|
+
}
|
|
26
|
+
const avoided = rewrite !== null && rewrite.cause === 'idle_ttl_expired' && rewrite.ttlSeconds === 300 && rewrite.idleMs !== undefined && rewrite.idleMs <= AVOIDABLE_IDLE_MS;
|
|
27
|
+
if (avoided) {
|
|
28
|
+
known = true;
|
|
29
|
+
result.avoided++;
|
|
30
|
+
result.avoidedCacheWriteTokens += turn.cacheWriteTokens;
|
|
31
|
+
result.billedAtFiveMinuteUsd = add(result.billedAtFiveMinuteUsd, perMillion(turn.cacheWriteTokens, cache.write5m));
|
|
32
|
+
result.wouldHaveBeenReadsUsd = add(result.wouldHaveBeenReadsUsd, perMillion(turn.cacheWriteTokens, cache.read));
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
// Only writes whose five-minute lifetime is recorded are repriced. Unknown lifetimes stay out.
|
|
36
|
+
const fiveMinuteTokens = turn.cacheWrite5mTokens ?? (turn.cacheTtlSeconds === 300 ? turn.cacheWriteTokens : 0);
|
|
37
|
+
if (fiveMinuteTokens > 0) {
|
|
38
|
+
known = true;
|
|
39
|
+
result.repricedFiveMinuteWriteTokens += fiveMinuteTokens;
|
|
40
|
+
const difference = cache.write5m === null || cache.write1h === null ? null : cache.write1h - cache.write5m;
|
|
41
|
+
result.extraOneHourWriteUsd = add(result.extraOneHourWriteUsd, perMillion(fiveMinuteTokens, difference));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (!known) {
|
|
45
|
+
result.billedAtFiveMinuteUsd = 0;
|
|
46
|
+
result.wouldHaveBeenReadsUsd = 0;
|
|
47
|
+
result.extraOneHourWriteUsd = 0;
|
|
48
|
+
result.netAtListUsd = null;
|
|
49
|
+
result.favours = 'unknown';
|
|
50
|
+
return result;
|
|
51
|
+
}
|
|
52
|
+
const net = result.billedAtFiveMinuteUsd === null || result.wouldHaveBeenReadsUsd === null || result.extraOneHourWriteUsd === null ? null
|
|
53
|
+
: result.billedAtFiveMinuteUsd - result.wouldHaveBeenReadsUsd - result.extraOneHourWriteUsd;
|
|
54
|
+
result.netAtListUsd = net;
|
|
55
|
+
result.favours = net === null ? 'unpriced' : net > 1e-9 ? '1h' : net < -1e-9 ? '5m' : 'even';
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
function ttlReport(transcripts, rates = {}) {
|
|
59
|
+
const turns = (0, transcript_1.deduplicateTurns)(transcripts.flatMap(transcript => transcript.turns)).sort((a, b) => (a.at ?? 0) - (b.at ?? 0) || a.id.localeCompare(b.id));
|
|
60
|
+
// Main conversation first, in order of first appearance; child transcripts after.
|
|
61
|
+
const sessions = [...new Set([...turns.filter(turn => !turn.subagent), ...turns.filter(turn => turn.subagent)].map(turn => turn.sessionId))];
|
|
62
|
+
const buckets = [bucketFor(turns.filter(turn => !turn.subagent), 'main', rates), bucketFor(turns.filter(turn => Boolean(turn.subagent)), 'subagent', rates)];
|
|
63
|
+
return { sessions, buckets,
|
|
64
|
+
settings: { promptCacheTtl: buckets[0].favours === '1h' ? '1h' : null, subagentPromptCacheTtl: buckets[1].favours === '1h' ? '1h' : null },
|
|
65
|
+
basis: 'list_price_counterfactual_on_recorded_turns',
|
|
66
|
+
multipliers: { cacheWrite5m: pricing_1.CACHE_WRITE_5M_MULTIPLIER, cacheWrite1h: pricing_1.CACHE_WRITE_1H_MULTIPLIER, cacheRead: pricing_1.CACHE_READ_MULTIPLIER } };
|
|
67
|
+
}
|
|
68
|
+
const count = (n) => n.toLocaleString('en-US');
|
|
69
|
+
const usd = (value) => value === null ? 'unpriced' : (0, live_1.dollars)({ min: value, max: value });
|
|
70
|
+
const signed = (value) => value === null ? 'unpriced' : `${value < 0 ? '-' : '+'}$${Math.abs(value).toFixed(2)}`;
|
|
71
|
+
function table(headers, rows) {
|
|
72
|
+
const widths = headers.map((header, i) => Math.max(header.length, ...rows.map(row => row[i]?.length ?? 0)));
|
|
73
|
+
return [headers, ...rows].map(row => row.map((cell, i) => cell.padEnd(widths[i])).join(' ').trimEnd()).join('\n');
|
|
74
|
+
}
|
|
75
|
+
const label = { main: 'Main conversation', subagent: 'Subagent transcripts' };
|
|
76
|
+
function verdictLine(bucket) {
|
|
77
|
+
const name = label[bucket.bucket];
|
|
78
|
+
const setting = bucket.bucket === 'main' ? 'promptCacheTtl' : 'subagentPromptCacheTtl';
|
|
79
|
+
switch (bucket.favours) {
|
|
80
|
+
case '1h': return `${name}: net favours 1h. Set "${setting}": "1h" in settings.json${bucket.bucket === 'main' ? ' (or CLAUDE_CODE_PROMPT_CACHE_TTL=1h)' : ''}.`;
|
|
81
|
+
case '5m': return `${name}: net favours 5m. Leave ${setting} unset; the longer lifetime would have been billed more on these turns.`;
|
|
82
|
+
case 'even': return `${name}: net is even at list price on these turns; ${setting} makes no difference here.`;
|
|
83
|
+
case 'unpriced': return `${name}: at least one model has no verified rate, so the net is unpriced; the token columns still hold.`;
|
|
84
|
+
default: return `${name}: no turn with a recorded five-minute lifetime, so there is nothing to compare for ${setting}.`;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function renderTtl(report) {
|
|
88
|
+
const rows = report.buckets.map(bucket => [bucket.bucket, `${bucket.avoided} of ${bucket.rewrites}`, count(bucket.avoidedCacheWriteTokens), usd(bucket.billedAtFiveMinuteUsd),
|
|
89
|
+
usd(bucket.wouldHaveBeenReadsUsd), count(bucket.repricedFiveMinuteWriteTokens), usd(bucket.extraOneHourWriteUsd), bucket.netAtListUsd === null ? bucket.favours : `${signed(bucket.netAtListUsd)} (${bucket.favours})`]);
|
|
90
|
+
const excluded = report.buckets.filter(bucket => bucket.excludedUnknownTtl > 0).map(bucket => `${bucket.bucket}: ${bucket.excludedUnknownTtl} rewrite${bucket.excludedUnknownTtl === 1 ? '' : 's'} with an unknown lifetime excluded from the counterfactual`);
|
|
91
|
+
return [
|
|
92
|
+
`AgentGuard ttl: ${report.sessions.join(', ')}`,
|
|
93
|
+
'List-price counterfactual on recorded turns: the result is the net at list price, not a bill. Subscription users: read the token columns; every dollar column is the API list equivalent.',
|
|
94
|
+
'',
|
|
95
|
+
table(['Bucket', 'Rewrites avoided', 'Avoided write tokens', 'Billed at 5m', 'Would have been reads', 'Repriced 5m write tokens', 'Extra at 1h rate', 'Net at list'], rows),
|
|
96
|
+
'',
|
|
97
|
+
'Rewrites avoided: full-prefix writes that followed an expired five-minute lifetime with an idle gap of at most one hour. Under a one-hour lifetime they would have been billed as cache reads, not writes.',
|
|
98
|
+
'Extra at 1h rate: every other write recorded with a five-minute lifetime would have been billed at the one-hour write rate instead. Net = billed at 5m minus reads minus extra.',
|
|
99
|
+
...excluded,
|
|
100
|
+
'',
|
|
101
|
+
...report.buckets.map(verdictLine),
|
|
102
|
+
'On a Claude subscription within plan usage the main conversation already has a one-hour lifetime; API key and usage-credit sessions start at five minutes. Subagents, forks, compaction and titles stay at five minutes unless subagentPromptCacheTtl is set.',
|
|
103
|
+
`Multipliers relative to base input: 5m write ${report.multipliers.cacheWrite5m}x, 1h write ${report.multipliers.cacheWrite1h}x, cache read ${report.multipliers.cacheRead}x; a model row's verified rates take precedence.`,
|
|
104
|
+
].join('\n');
|
|
105
|
+
}
|
|
@@ -25,6 +25,8 @@ export interface InsightTurn {
|
|
|
25
25
|
subagent?: boolean;
|
|
26
26
|
at?: number;
|
|
27
27
|
model?: string;
|
|
28
|
+
/** Host build recorded on the transcript line (Claude Code writes `version` on every record). */
|
|
29
|
+
hostVersion?: string;
|
|
28
30
|
/** Fresh input only. Codex cached input is subtracted from its inclusive input. */
|
|
29
31
|
inputTokens: number;
|
|
30
32
|
cacheWriteTokens: number;
|
|
@@ -41,6 +43,14 @@ export interface InsightTurn {
|
|
|
41
43
|
afterCompaction: boolean;
|
|
42
44
|
firstSpawnedTurn: boolean;
|
|
43
45
|
prefixChanged?: boolean;
|
|
46
|
+
/** Model differs from the previous usage turn in this transcript. */
|
|
47
|
+
modelChanged?: boolean;
|
|
48
|
+
previousModel?: string;
|
|
49
|
+
/** Host build differs from the previous usage turn in this transcript. */
|
|
50
|
+
versionChanged?: boolean;
|
|
51
|
+
previousHostVersion?: string;
|
|
52
|
+
/** Image or PDF blocks that an earlier message was re-recorded without, since the previous usage turn. */
|
|
53
|
+
imagesDropped?: number;
|
|
44
54
|
};
|
|
45
55
|
explicitAttribution: ExplicitTokenAttribution[];
|
|
46
56
|
uncertainties: string[];
|
|
@@ -102,6 +112,12 @@ export interface InsightParserState {
|
|
|
102
112
|
digest: string;
|
|
103
113
|
source: 'response' | 'event';
|
|
104
114
|
};
|
|
115
|
+
lastTurnModel?: string;
|
|
116
|
+
hostVersion?: string;
|
|
117
|
+
lastTurnVersion?: string;
|
|
118
|
+
/** Image or PDF block counts per message identity digest; only counts, never bytes. */
|
|
119
|
+
imageBlocksByMessage?: Record<string, number>;
|
|
120
|
+
imagesDroppedPending?: number;
|
|
105
121
|
}
|
|
106
122
|
export interface InsightObservations {
|
|
107
123
|
readCalls: number;
|
|
@@ -128,7 +144,9 @@ export interface InsightParseOptions {
|
|
|
128
144
|
state?: InsightParserState;
|
|
129
145
|
spawnedSession?: boolean;
|
|
130
146
|
}
|
|
131
|
-
|
|
147
|
+
/** Precedence order when several signals are present; `unknown` is the Codex residual, never prefix change by default. */
|
|
148
|
+
export type RewriteCause = 'model_switch' | 'version_upgrade' | 'compaction' | 'first_spawned_turn' | 'idle_ttl_expired' | 'image_pruning' | 'prefix_change' | 'unknown_ttl' | 'unknown';
|
|
149
|
+
export declare const REWRITE_CAUSES: RewriteCause[];
|
|
132
150
|
export interface RewriteEvidence {
|
|
133
151
|
turnId: string;
|
|
134
152
|
cause: RewriteCause;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.INSIGHT_BUCKETS = void 0;
|
|
3
|
+
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
|
+
exports.REWRITE_CAUSES = ['model_switch', 'version_upgrade', 'compaction', 'first_spawned_turn', 'idle_ttl_expired', 'image_pruning', 'prefix_change', 'unknown_ttl', 'unknown'];
|
package/dist/src/types.d.ts
CHANGED
|
@@ -118,6 +118,14 @@ export interface Thresholds {
|
|
|
118
118
|
warnTokens: number | null;
|
|
119
119
|
windowActiveMinutes: number;
|
|
120
120
|
warnConcurrentSessions: number;
|
|
121
|
+
/**
|
|
122
|
+
* Hard ceiling on live sessions for this machine. Above it, no session may
|
|
123
|
+
* add a copy until one finishes (a spawn proposal is refused; other tool
|
|
124
|
+
* calls are untouched). `null` keeps the WARN-only default. Meant for
|
|
125
|
+
* hosts that start sessions on their own, such as Claude Code Projects
|
|
126
|
+
* running threads locally.
|
|
127
|
+
*/
|
|
128
|
+
stopConcurrentSessions: number | null;
|
|
121
129
|
};
|
|
122
130
|
/**
|
|
123
131
|
* Local inference plane (Ollama, vLLM, LM Studio). Token dollars are close
|
|
@@ -10,12 +10,13 @@ The observer and reports run locally without network requests. Reports contain u
|
|
|
10
10
|
agentguard-burn why
|
|
11
11
|
agentguard-burn why SESSION_ID json
|
|
12
12
|
agentguard-burn rewrites all
|
|
13
|
+
agentguard-burn ttl SESSION_ID
|
|
13
14
|
agentguard-burn pace SESSION_ID
|
|
14
15
|
agentguard-burn statusline SESSION_ID
|
|
15
16
|
agentguard-burn pricing
|
|
16
17
|
```
|
|
17
18
|
|
|
18
|
-
`why` breaks down a session's recorded usage. `rewrites` lists large prefix
|
|
19
|
+
`why` breaks down a session's recorded usage. `rewrites` lists every large prefix write with its cause, idle gap and list price. `ttl` is the one-hour cache lifetime counterfactual on the same recorded turns. `pace` and `statusline` show a short local summary. The optional final `json` argument on `why`, `rewrites` and `ttl` makes the report suitable for another local program.
|
|
19
20
|
|
|
20
21
|
## Attribution method in 0.2.5
|
|
21
22
|
|
|
@@ -33,10 +34,25 @@ The table's Method footer has one sentence per bucket. Zero now means a computed
|
|
|
33
34
|
|
|
34
35
|
For Claude, `cache_creation_input_tokens` is the total written. When the transcript also includes `cache_creation.ephemeral_5m_input_tokens` and `cache_creation.ephemeral_1h_input_tokens`, Burn uses that split. If the lifetime is unavailable, Burn returns a range between the two published write rates. A long pause alone does not establish the requested cache lifetime. See the [provider's cache usage fields](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#1-hour-cache-duration).
|
|
35
36
|
|
|
36
|
-
A large rewrite
|
|
37
|
+
A large rewrite is named by the first signal that applies, in this order: model switch (the model differs from the previous usage turn), version upgrade (Claude Code's recorded `version` differs), compaction, first spawned turn, expired lifetime (the idle gap exceeds the lifetime recorded for the write), image pruning (an earlier message re-recorded with fewer image or PDF blocks), then a host-reported prefix change. The remainder is prefix change as a residual, or unknown when the lifetime is absent or mixed. These are evidence labels, not proof that one cause was solely responsible. Effort changes, fast mode and tool definition changes are not written to any transcript, and Claude Code does not persist image pruning, so the explanation says these could not be observed rather than guessing. Codex records the model on `turn_context` and compaction as `compacted`; it records no cache lifetime or prefix identity, so an unexplained Codex rewrite stays unknown.
|
|
37
38
|
|
|
38
39
|
For `claude-fable-5-1`, 500,000 cache-read tokens have a $0.125 API equivalent. Writing that many tokens costs $6.25 with a five-minute lifetime or $10 with a one-hour lifetime. At the same verified cache-read rate, 1.69 billion reads cost $422.50. Multiplying all token categories by the fresh-input rate would give the wrong result.
|
|
39
40
|
|
|
41
|
+
## Cache lifetime counterfactual
|
|
42
|
+
|
|
43
|
+
`ttl` reprices recorded turns under a one-hour cache lifetime. It is a list-price counterfactual on turns that already ran: never a bill, never a subscription charge, and the difference is only ever stated as a net at list price. The wording is always "would have been billed" and "net at list price, not a bill". Subscription users read the token columns; every dollar column is labelled as the API list equivalent.
|
|
44
|
+
|
|
45
|
+
For each bucket (main conversation, subagent transcripts):
|
|
46
|
+
|
|
47
|
+
- A rewrite is avoided when it was classified as an expired five-minute lifetime and the idle gap before it was at most 3,600 seconds. Its cache-write tokens would have been billed as cache reads.
|
|
48
|
+
- Every other write recorded with a five-minute lifetime (the `ephemeral_5m_input_tokens` split, or explicit five-minute metadata) would have been billed at the one-hour write rate instead.
|
|
49
|
+
- Net at list = the avoided writes at the five-minute rate, minus the same tokens at the cache-read rate, minus the extra one-hour write cost. A positive net favours one hour; a negative net favours five minutes, and the report says so plainly.
|
|
50
|
+
- Writes with an absent or mixed lifetime are excluded from both sides, and the number of excluded rewrites is shown.
|
|
51
|
+
|
|
52
|
+
The multipliers relative to base input are named constants in `src/insights/pricing.ts`, from [Anthropic's prompt caching pricing](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing): `CACHE_WRITE_5M_MULTIPLIER = 1.25`, `CACHE_WRITE_1H_MULTIPLIER = 2`, `CACHE_READ_MULTIPLIER = 0.1`. They only fill a rate that a model row leaves null. A bundled row's verified `cacheWrite5m`, `cacheWrite1h` and `cacheRead`, or the same fields in a local override file, take precedence, which is how `claude-opus-5-5` keeps its verified 0.05x cache-read rate.
|
|
53
|
+
|
|
54
|
+
The verdict names the exact setting: `"promptCacheTtl": "1h"` in `settings.json` (or `CLAUDE_CODE_PROMPT_CACHE_TTL=1h`) for the main conversation and `"subagentPromptCacheTtl": "1h"` for subagents, forks, compaction and titles. On a Claude subscription within plan usage the main conversation already has a one-hour lifetime; API key and usage-credit sessions start at five minutes.
|
|
55
|
+
|
|
40
56
|
## Pricing sources and overrides
|
|
41
57
|
|
|
42
58
|
Every bundled row includes its exact model identifier, `sourceUrl` and `verifiedAt`. The rates were checked on 2026-09-17, except `claude-opus-5-5`, `gpt-6-sol` and `gpt-6-luna`, which were checked on 2026-09-22. The runtime never downloads pricing. Run `agentguard-burn pricing` to inspect the installed table.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agentguard-run/burn",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.14",
|
|
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",
|