@trazum/core 3.0.1 → 3.0.2

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.
Files changed (80) hide show
  1. package/README.md +1 -1
  2. package/dist/claude-model-pricing.d.ts +73 -0
  3. package/dist/claude-model-pricing.d.ts.map +1 -0
  4. package/dist/claude-model-pricing.js +208 -0
  5. package/dist/claude-model-pricing.js.map +1 -0
  6. package/dist/config-schema.d.ts +14 -1
  7. package/dist/config-schema.d.ts.map +1 -1
  8. package/dist/config-schema.js +24 -0
  9. package/dist/config-schema.js.map +1 -1
  10. package/dist/index.d.ts +13 -4
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +10 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/node.d.ts +1 -1
  15. package/dist/node.d.ts.map +1 -1
  16. package/dist/node.js +1 -1
  17. package/dist/node.js.map +1 -1
  18. package/dist/otlp.d.ts +103 -0
  19. package/dist/otlp.d.ts.map +1 -1
  20. package/dist/otlp.js +185 -0
  21. package/dist/otlp.js.map +1 -1
  22. package/dist/partner-model-id.d.ts +26 -0
  23. package/dist/partner-model-id.d.ts.map +1 -0
  24. package/dist/partner-model-id.js +60 -0
  25. package/dist/partner-model-id.js.map +1 -0
  26. package/dist/plan-edit.d.ts +99 -0
  27. package/dist/plan-edit.d.ts.map +1 -0
  28. package/dist/plan-edit.js +142 -0
  29. package/dist/plan-edit.js.map +1 -0
  30. package/dist/plan.d.ts +63 -2
  31. package/dist/plan.d.ts.map +1 -1
  32. package/dist/plan.js +55 -0
  33. package/dist/plan.js.map +1 -1
  34. package/dist/pricing.d.ts +19 -0
  35. package/dist/pricing.d.ts.map +1 -1
  36. package/dist/pricing.js +32 -0
  37. package/dist/pricing.js.map +1 -1
  38. package/dist/prometheus.d.ts +42 -0
  39. package/dist/prometheus.d.ts.map +1 -0
  40. package/dist/prometheus.js +112 -0
  41. package/dist/prometheus.js.map +1 -0
  42. package/dist/receipt.d.ts +2 -1
  43. package/dist/receipt.d.ts.map +1 -1
  44. package/dist/receipt.js +11 -1
  45. package/dist/receipt.js.map +1 -1
  46. package/dist/session-waste.d.ts +145 -0
  47. package/dist/session-waste.d.ts.map +1 -0
  48. package/dist/session-waste.js +489 -0
  49. package/dist/session-waste.js.map +1 -0
  50. package/dist/structure.js +3 -3
  51. package/dist/structure.js.map +1 -1
  52. package/dist/tokenizer.d.ts +9 -0
  53. package/dist/tokenizer.d.ts.map +1 -1
  54. package/dist/tokenizer.js +1 -1
  55. package/dist/tokenizer.js.map +1 -1
  56. package/dist/verify.d.ts +11 -1
  57. package/dist/verify.d.ts.map +1 -1
  58. package/dist/verify.js +54 -0
  59. package/dist/verify.js.map +1 -1
  60. package/dist/walk.d.ts +14 -0
  61. package/dist/walk.d.ts.map +1 -1
  62. package/dist/walk.js +35 -0
  63. package/dist/walk.js.map +1 -1
  64. package/package.json +1 -1
  65. package/src/claude-model-pricing.ts +245 -0
  66. package/src/config-schema.ts +44 -0
  67. package/src/index.ts +46 -4
  68. package/src/node.ts +1 -1
  69. package/src/otlp.ts +281 -0
  70. package/src/partner-model-id.ts +69 -0
  71. package/src/plan-edit.ts +180 -0
  72. package/src/plan.ts +104 -3
  73. package/src/pricing.ts +33 -0
  74. package/src/prometheus.ts +131 -0
  75. package/src/receipt.ts +16 -2
  76. package/src/session-waste.ts +570 -0
  77. package/src/structure.ts +3 -3
  78. package/src/tokenizer.ts +1 -1
  79. package/src/verify.ts +78 -2
  80. package/src/walk.ts +33 -0
@@ -0,0 +1,145 @@
1
+ import type { PricingCatalogue } from './pricing.js';
2
+ /**
3
+ * Waste in a coding-agent session, named and priced, from counts and paths.
4
+ *
5
+ * ## What it looks at, and what it refuses to look at
6
+ *
7
+ * A Claude Code transcript holds the conversation. This module reads **counts
8
+ * and paths out of it and never what was said**: for each assistant call the
9
+ * usage counts the converter already reads; for each tool call its name and,
10
+ * for the file tools, the one `file_path` argument plus a `Read`'s `offset`
11
+ * and `limit` (numbers); for each tool result only whether it was an error;
12
+ * and, from the lines Claude Code writes about what it loaded, server and tool
13
+ * names. No tool input other than those, no tool result body, no message text
14
+ * and no file content is read into a variable. `session-waste.test.js` plants a
15
+ * secret in each of those places and greps the whole report for it.
16
+ *
17
+ * ## Three findings, and what each can be priced from
18
+ *
19
+ * - **The same file read again.** Priced from the session's own counts: the
20
+ * prompt grew by `P(next) - P(this) - output(this)` tokens across the call
21
+ * that read the file, and that growth was carried, as cache reads, on every
22
+ * later call of the same thread until the context shrank. The saving is the
23
+ * difference between the thread's actual cost and its cost with those
24
+ * tokens taken out, both through `profileUsage`, so a long-context band, a
25
+ * cache TTL or a fast-mode multiplier is applied by the one code that
26
+ * already knows them. Measurable only where the call made exactly one tool
27
+ * call: with several, the growth cannot be split among them and the repeat
28
+ * is counted and left unpriced.
29
+ * - **MCP servers loaded and never called.** Named, and **not priced**: what a
30
+ * server's tool definitions cost is not in the transcript, and where tools
31
+ * are deferred the definitions are not even sent until the tool is asked for.
32
+ * The number of tools it brought is a count, and is all that is said.
33
+ * - **A CLAUDE.md carried on every turn.** The transcript does not record its
34
+ * size. The caller supplies the file's size in bytes (a `stat`, never the
35
+ * content), and the tokens are that size over the estimator's divisor,
36
+ * with the published band on both sides. It is the one estimated figure here
37
+ * and says so.
38
+ *
39
+ * ## What it never does
40
+ *
41
+ * It recommends and edits nothing. A saving is computed from this session's
42
+ * counts at the dated bundled catalogue, as API-equivalent cost, and is never
43
+ * a percentage taken from elsewhere. A saving it cannot compute is `null` with
44
+ * the reason beside it, never a number that looks like one.
45
+ */
46
+ export declare const WASTE_LIMITATIONS: readonly ['Every figure is API-equivalent cost: the usage at the dated catalogue rates, not what was charged.', 'A repeated read is only priced where its call made no other tool call, because the prompt growth cannot be split among several. The rest are counted and not priced.', 'A file that Bash rewrote between two reads is not seen as changed, so that second read counts as a repeat.', 'MCP tool-definition tokens are not recorded in a transcript, so a server that was never called is named and not priced.', 'A CLAUDE.md size is a file size in bytes, not a count from the transcript, and its tokens are an estimate within the published band.', 'Savings are a lower bound: they count the context a repeat added and carried, not the extra round trip.'];
47
+ /** `mcp__server__tool` to `server`. A name that is not an MCP name has none. */
48
+ export declare function mcpServerOf(toolName: string): string | undefined;
49
+ export interface RepeatedRead {
50
+ path: string;
51
+ /** Reads of the path that were not an error, in every thread. */
52
+ reads: number;
53
+ /** Reads after the first of the same range with no write to the file between. */
54
+ repeats: number;
55
+ /** Repeats whose call made one tool call, so the growth it caused is known. */
56
+ measured: number;
57
+ /** The prompt growth of the measured repeats, summed. */
58
+ tokens: number;
59
+ /** What carrying that growth cost, or null where nothing could be measured. */
60
+ usd: number | null;
61
+ }
62
+ export interface UnusedMcpServer {
63
+ server: string;
64
+ /** Tools it brought, when the transcript names them. */
65
+ tools: number | null;
66
+ }
67
+ export interface ClaudeMdFinding {
68
+ path: string;
69
+ bytes: number;
70
+ tokens: number;
71
+ /** The same cost at the band's two ends. */
72
+ usdLow: number;
73
+ usd: number;
74
+ usdHigh: number;
75
+ /** Calls of the main thread that carried it. */
76
+ calls: number;
77
+ }
78
+ export type McpSource = 'transcript' | 'flag' | 'none';
79
+ export interface SessionWasteReport {
80
+ schemaVersion: 1;
81
+ kind: 'trazum-waste';
82
+ pricing: {
83
+ source: 'bundled';
84
+ lastReviewed: string;
85
+ basis: 'api-equivalent';
86
+ };
87
+ /** Calls priced, threads they ran in. */
88
+ session: {
89
+ calls: number;
90
+ threads: number;
91
+ files: number;
92
+ };
93
+ /** Set when the transcript could not be paired with its usage, and nothing below was computed. */
94
+ cannotTell: 'unreadable' | null;
95
+ unpricedModels: string[];
96
+ reads: {
97
+ minReads: number;
98
+ findings: RepeatedRead[];
99
+ /** Paths read again that are not listed, because they fall under `minReads` or past the cap. */
100
+ omitted: number;
101
+ /** Repeats of the listed paths, and how many of them were priced. */
102
+ repeats: number;
103
+ measured: number;
104
+ /** All listed repeats taken out together; null when none was measured. */
105
+ usd: number | null;
106
+ };
107
+ mcp: {
108
+ source: McpSource;
109
+ loaded: number;
110
+ called: number;
111
+ /** Loaded and never called. Not priced: see `unpricedReason`. */
112
+ unused: UnusedMcpServer[];
113
+ unpricedReason: 'definitions-not-recorded';
114
+ };
115
+ claudeMd: {
116
+ checked: boolean;
117
+ findings: ClaudeMdFinding[];
118
+ bandPct: number;
119
+ };
120
+ limitations: string[];
121
+ }
122
+ export interface SessionWasteOptions {
123
+ catalogue: PricingCatalogue;
124
+ on: Date;
125
+ /** Paths read fewer times than this are not listed. */
126
+ minReads: number;
127
+ /** Server names the person says are loaded, when the transcript does not say. */
128
+ mcpServers?: readonly string[];
129
+ /** Files to price as carried every turn: a size from `stat`, never the content. */
130
+ claudeMd?: ReadonlyArray<{
131
+ path: string;
132
+ bytes: number;
133
+ }>;
134
+ }
135
+ /** The most paths listed. The rest are counted in `omitted`. */
136
+ export declare const MAX_LISTED_READS = 20;
137
+ /**
138
+ * The directory a session ran in, the first one a main-thread line names.
139
+ *
140
+ * A path and nothing else of the line. It is how a caller finds the project's
141
+ * CLAUDE.md to measure, and it is never copied into the report.
142
+ */
143
+ export declare function sessionCwd(text: string): string | undefined;
144
+ export declare function analyzeSessionWaste(files: readonly string[], options: SessionWasteOptions): SessionWasteReport;
145
+ //# sourceMappingURL=session-waste.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-waste.d.ts","sourceRoot":"","sources":["../src/session-waste.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAIrD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,eAAO,MAAM,iBAAiB,YAC5B,oGAAoG,EACpG,sKAAsK,EACtK,4GAA4G,EAC5G,yHAAyH,EACzH,sIAAsI,EACtI,yGAAyG,CACjG,CAAC;AAqCX,gFAAgF;AAChF,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAIhE;AA+JD,MAAM,WAAW,YAAY;IAC3B,IAAI,E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_ERROR_BAND_PCT } from './tokenizer.js';
3
+ import { profileUsage } from './usage.js';
4
+ /**
5
+ * Waste in a coding-agent session, named and priced, from counts and paths.
6
+ *
7
+ * ## What it looks at, and what it refuses to look at
8
+ *
9
+ * A Claude Code transcript holds the conversation. This module reads **counts
10
+ * and paths out of it and never what was said**: for each assistant call the
11
+ * usage counts the converter already reads; for each tool call its name and,
12
+ * for the file tools, the one `file_path` argument plus a `Read`'s `offset`
13
+ * and `limit` (numbers); for each tool result only whether it was an error;
14
+ * and, from the lines Claude Code writes about what it loaded, server and tool
15
+ * names. No tool input other than those, no tool result body, no message text
16
+ * and no file content is read into a variable. `session-waste.test.js` plants a
17
+ * secret in each of those places and greps the whole report for it.
18
+ *
19
+ * ## Three findings, and what each can be priced from
20
+ *
21
+ * - **The same file read again.** Priced from the session's own counts: the
22
+ * prompt grew by `P(next) - P(this) - output(this)` tokens across the call
23
+ * that read the file, and that growth was carried, as cache reads, on every
24
+ * later call of the same thread until the context shrank. The saving is the
25
+ * difference between the thread's actual cost and its cost with those
26
+ * tokens taken out, both through `profileUsage`, so a long-context band, a
27
+ * cache TTL or a fast-mode multiplier is applied by the one code that
28
+ * already knows them. Measurable only where the call made exactly one tool
29
+ * call: with several, the growth cannot be split among them and the repeat
30
+ * is counted and left unpriced.
31
+ * - **MCP servers loaded and never called.** Named, and **not priced**: what a
32
+ * server's tool definitions cost is not in the transcript, and where tools
33
+ * are deferred the definitions are not even sent until the tool is asked for.
34
+ * The number of tools it brought is a count, and is all that is said.
35
+ * - **A CLAUDE.md carried on every turn.** The transcript does not record its
36
+ * size. The caller supplies the file's size in bytes (a `stat`, never the
37
+ * content), and the tokens are that size over the estimator's divisor,
38
+ * with the published band on both sides. It is the one estimated figure here
39
+ * and says so.
40
+ *
41
+ * ## What it never does
42
+ *
43
+ * It recommends and edits nothing. A saving is computed from this session's
44
+ * counts at the dated bundled catalogue, as API-equivalent cost, and is never
45
+ * a percentage taken from elsewhere. A saving it cannot compute is `null` with
46
+ * the reason beside it, never a number that looks like one.
47
+ */
48
+ export const WASTE_LIMITATIONS = [
49
+ 'Every figure is API-equivalent cost: the usage at the dated catalogue rates, not what was charged.',
50
+ 'A repeated read is only priced where its call made no other tool call, because the prompt growth cannot be split among several. The rest are counted and not priced.',
51
+ 'A file that Bash rewrote between two reads is not seen as changed, so that second read counts as a repeat.',
52
+ 'MCP tool-definition tokens are not recorded in a transcript, so a server that was never called is named and not priced.',
53
+ 'A CLAUDE.md size is a file size in bytes, not a count from the transcript, and its tokens are an estimate within the published band.',
54
+ 'Savings are a lower bound: they count the context a repeat added and carried, not the extra round trip.',
55
+ ];
56
+ /** Tools that change a file, and so make the next read of it a different read. */
57
+ const WRITERS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
58
+ const asObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) ? value : null;
59
+ const asCount = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
60
+ const strings = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === 'string') : [];
61
+ /** `mcp__server__tool` to `server`. A name that is not an MCP name has none. */
62
+ export function mcpServerOf(toolName) {
63
+ if (!toolName.startsWith('mcp__'))
64
+ return undefined;
65
+ const server = toolName.slice(5).split('__')[0];
66
+ return server === undefined || server === '' ? undefined : server;
67
+ }
68
+ /**
69
+ * One transcript, as calls with their tool names, in the converter's order.
70
+ *
71
+ * The converter keys a call by `requestId`, else `message.id`, keeps the last
72
+ * line's usage and drops `<synthetic>`; this applies the same rules to the same
73
+ * lines to know which tool calls belong to which of its records, and `aligned`
74
+ * says whether the two agree on how many calls there were. If they do not, the
75
+ * caller says it cannot tell rather than pair a tool call with the wrong prompt.
76
+ */
77
+ function extract(text, fileIndex) {
78
+ const conversion = claudeCodeRecords(text);
79
+ const out = {
80
+ calls: [],
81
+ failed: new Set(),
82
+ loaded: { servers: new Set(), tools: new Set(), recorded: false },
83
+ aligned: true,
84
+ };
85
+ const byKey = new Map();
86
+ const loaded = out.loaded;
87
+ let next = 0;
88
+ for (const line of text.split('\n')) {
89
+ if (line.trim() === '')
90
+ continue;
91
+ let raw;
92
+ try {
93
+ raw = JSON.parse(line);
94
+ }
95
+ catch {
96
+ continue;
97
+ }
98
+ const entry = asObject(raw);
99
+ if (entry === null)
100
+ continue;
101
+ if (entry.type === 'user') {
102
+ const content = asObject(entry.message)?.content;
103
+ if (Array.isArray(content)) {
104
+ for (const block of content) {
105
+ const b = asObject(block);
106
+ // Only the id and the flag: the body of a result is never read.
107
+ if (b !== null && b.type === 'tool_result' && b.is_error === true && typeof b.tool_use_id === 'string')
108
+ out.failed.add(b.tool_use_id);
109
+ }
110
+ }
111
+ continue;
112
+ }
113
+ if (entry.type === 'attachment') {
114
+ const attachment = asObject(entry.attachment);
115
+ // Names only. `addedLines` carries descriptions and is never read.
116
+ if (attachment !== null && attachment.type === 'deferred_tools_delta') {
117
+ loaded.recorded = true;
118
+ for (const name of strings(attachment.addedNames))
119
+ if (name.startsWith('mcp__'))
120
+ loaded.tools.add(name);
121
+ for (const name of strings(attachment.removedNames))
122
+ loaded.tools.delete(name);
123
+ }
124
+ else if (attachment !== null && attachment.type === 'mcp_instructions_delta') {
125
+ loaded.recorded = true;
126
+ for (const name of strings(attachment.addedNames))
127
+ loaded.servers.add(name);
128
+ for (const name of strings(attachment.removedNames))
129
+ loaded.servers.delete(name);
130
+ }
131
+ continue;
132
+ }
133
+ if (entry.type === 'system' && Array.isArray(entry.mcp_servers)) {
134
+ loaded.recorded = true;
135
+ for (const server of entry.mcp_servers) {
136
+ const name = asObject(server)?.name;
137
+ if (typeof name === 'string' && name !== '')
138
+ loaded.servers.add(name);
139
+ }
140
+ continue;
141
+ }
142
+ if (entry.type !== 'assistant')
143
+ continue;
144
+ const message = asObject(entry.message);
145
+ const usage = message === null ? null : asObject(message.usage);
146
+ const model = message === null ? undefined : message.model;
147
+ if (usage === null || typeof model !== 'string' || asCount(usage.input_tokens) === undefined || asCount(usage.output_tokens) === undefined)
148
+ continue;
149
+ if (model === '<synthetic>')
150
+ continue;
151
+ const key = typeof entry.requestId === 'string' && entry.requestId !== ''
152
+ ? `request:${entry.requestId}`
153
+ : message !== null && typeof message.id === 'string' && message.id !== ''
154
+ ? `message:${message.id}`
155
+ : null;
156
+ let call = key === null ? undefined : byKey.get(key);
157
+ if (call === undefined) {
158
+ const record = conversion.records[next];
159
+ next += 1;
160
+ if (record === undefined) {
161
+ out.aligned = false;
162
+ continue;
163
+ }
164
+ call = { record, thread: `${fileIndex}:${record.thread ?? 'main'}`, tools: [] };
165
+ out.calls.push(call);
166
+ if (key !== null)
167
+ byKey.set(key, call);
168
+ }
169
+ const content = message === null ? undefined : message.content;
170
+ if (!Array.isArray(content))
171
+ continue;
172
+ for (const block of content) {
173
+ const b = asObject(block);
174
+ if (b === null || b.type !== 'tool_use' || typeof b.id !== 'string' || typeof b.name !== 'string')
175
+ continue;
176
+ if (call.tools.some((tool) => tool.id === b.id))
177
+ continue;
178
+ const input = asObject(b.input);
179
+ const tool = { id: b.id, name: b.name };
180
+ if (input !== null) {
181
+ const path = b.name === 'NotebookEdit' ? input.notebook_path : input.file_path;
182
+ if (typeof path === 'string' && path !== '')
183
+ tool.path = path;
184
+ if (b.name === 'Read')
185
+ tool.range = `${asCount(input.offset) ?? ''}:${asCount(input.limit) ?? ''}`;
186
+ }
187
+ call.tools.push(tool);
188
+ }
189
+ }
190
+ if (next !== conversion.records.length)
191
+ out.aligned = false;
192
+ return out;
193
+ }
194
+ /**
195
+ * `n` tokens taken out of a call's usage, from the buckets in the order given.
196
+ *
197
+ * Never below zero: a bucket that holds fewer than asked gives what it has and
198
+ * the rest comes from the next, and what no bucket held is simply not removed,
199
+ * which can only make a saving smaller.
200
+ */
201
+ function without(usage, n, order) {
202
+ const next = { ...usage, ...(usage.cache_creation === undefined ? {} : { cache_creation: { ...usage.cache_creation } }) };
203
+ let left = n;
204
+ for (const bucket of order) {
205
+ if (left <= 0)
206
+ break;
207
+ if (bucket === 'input') {
208
+ const take = Math.min(left, next.input_tokens);
209
+ next.input_tokens -= take;
210
+ left -= take;
211
+ }
212
+ else if (bucket === 'read') {
213
+ const take = Math.min(left, next.cache_read_input_tokens ?? 0);
214
+ if (take > 0)
215
+ next.cache_read_input_tokens = (next.cache_read_input_tokens ?? 0) - take;
216
+ left -= take;
217
+ }
218
+ else {
219
+ const have = next.cache_creation_input_tokens ?? 0;
220
+ const take = Math.min(left, have);
221
+ if (take > 0) {
222
+ next.cache_creation_input_tokens = have - take;
223
+ if (next.cache_creation !== undefined) {
224
+ let rest = take;
225
+ for (const ttl of ['ephemeral_5m_input_tokens', 'ephemeral_1h_input_tokens']) {
226
+ const held = next.cache_creation[ttl] ?? 0;
227
+ const cut = Math.min(rest, held);
228
+ if (cut > 0)
229
+ next.cache_creation[ttl] = held - cut;
230
+ rest -= cut;
231
+ }
232
+ }
233
+ }
234
+ left -= take;
235
+ }
236
+ }
237
+ return next;
238
+ }
239
+ const promptOf = (usage) => usage.input_tokens + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0);
240
+ /** The most paths listed. The rest are counted in `omitted`. */
241
+ export const MAX_LISTED_READS = 20;
242
+ /**
243
+ * The directory a session ran in, the first one a main-thread line names.
244
+ *
245
+ * A path and nothing else of the line. It is how a caller finds the project's
246
+ * CLAUDE.md to measure, and it is never copied into the report.
247
+ */
248
+ export function sessionCwd(text) {
249
+ for (const line of text.split('\n')) {
250
+ if (!line.includes('"cwd"'))
251
+ continue;
252
+ let raw;
253
+ try {
254
+ raw = JSON.parse(line);
255
+ }
256
+ catch {
257
+ continue;
258
+ }
259
+ const entry = asObject(raw);
260
+ if (entry !== null && entry.isSidechain !== true && typeof entry.cwd === 'string' && entry.cwd !== '')
261
+ return entry.cwd;
262
+ }
263
+ return undefined;
264
+ }
265
+ function priced(records, options) {
266
+ const text = records.length === 0 ? '' : `${records.map((record) => JSON.stringify(record)).join('\n')}\n`;
267
+ const report = profileUsage(text, { catalogue: options.catalogue, on: options.on });
268
+ return { usd: report.total.totalUsd, unpriced: report.unpricedModels, skipped: report.skippedLines.length };
269
+ }
270
+ /** Every thread's calls in order, with the usage each would have had without `removed`. */
271
+ function counterfactual(threads, removed) {
272
+ const out = [];
273
+ for (const calls of threads.values()) {
274
+ let carry = 0;
275
+ for (let i = 0; i < calls.length; i += 1) {
276
+ const call = calls[i];
277
+ // A prompt that shrank is a context that was compacted or cleared: what was carried is gone.
278
+ if (i > 0 && promptOf(call.record.usage) < promptOf(calls[i - 1].record.usage))
279
+ carry = 0;
280
+ let usage = call.record.usage;
281
+ if (carry > 0)
282
+ usage = without(usage, carry, ['read', 'write', 'input']);
283
+ const own = removed.get(call);
284
+ if (own !== undefined) {
285
+ usage = without(usage, own.measured, ['write', 'input', 'read']);
286
+ carry += own.measured;
287
+ }
288
+ out.push({ ...call.record, usage });
289
+ }
290
+ }
291
+ return out;
292
+ }
293
+ /** What the repeats in `chosen` cost, as the difference of two pricings of the same thread set. */
294
+ function savedBy(threads, growth, chosen, options, whole) {
295
+ // A repeat's growth lands on the call after it, as new tokens, and rides on every call after that.
296
+ const landing = new Map();
297
+ for (const calls of threads.values()) {
298
+ for (let i = 0; i + 1 < calls.length; i += 1) {
299
+ const call = calls[i];
300
+ const tokens = growth.get(call);
301
+ if (tokens !== undefined && chosen.has(call))
302
+ landing.set(calls[i + 1], { measured: tokens });
303
+ }
304
+ }
305
+ const after = priced(counterfactual(threads, landing), options).usd;
306
+ return Math.max(0, whole - after);
307
+ }
308
+ export function analyzeSessionWaste(files, options) {
309
+ const report = {
310
+ schemaVersion: 1,
311
+ kind: 'trazum-waste',
312
+ pricing: { source: 'bundled', lastReviewed: options.catalogue.lastReviewed, basis: 'api-equivalent' },
313
+ session: { calls: 0, threads: 0, files: files.length },
314
+ cannotTell: null,
315
+ unpricedModels: [],
316
+ reads: { minReads: options.minReads, findings: [], omitted: 0, repeats: 0, measured: 0, usd: null },
317
+ mcp: { source: 'none', loaded: 0, called: 0, unused: [], unpricedReason: 'definitions-not-recorded' },
318
+ claudeMd: { checked: options.claudeMd !== undefined, findings: [], bandPct: ESTIMATE_ERROR_BAND_PCT },
319
+ limitations: [...WASTE_LIMITATIONS],
320
+ };
321
+ const parts = files.map((text, index) => extract(text, index));
322
+ if (parts.some((part) => !part.aligned)) {
323
+ report.cannotTell = 'unreadable';
324
+ return report;
325
+ }
326
+ const threads = new Map();
327
+ for (const part of parts)
328
+ for (const call of part.calls)
329
+ (threads.get(call.thread) ?? threads.set(call.thread, []).get(call.thread)).push(call);
330
+ const failed = new Set();
331
+ for (const part of parts)
332
+ for (const id of part.failed)
333
+ failed.add(id);
334
+ report.session.calls = parts.reduce((sum, part) => sum + part.calls.length, 0);
335
+ report.session.threads = threads.size;
336
+ const whole = priced([...threads.values()].flat().map((call) => call.record), options);
337
+ report.unpricedModels = whole.unpriced;
338
+ // A call that could not be read as usage is not a free call: nothing below is computed from a part of the session.
339
+ if (whole.skipped > 0) {
340
+ report.cannotTell = 'unreadable';
341
+ return report;
342
+ }
343
+ const tallies = new Map();
344
+ const growth = new Map();
345
+ const owner = new Map();
346
+ for (const calls of threads.values()) {
347
+ const seen = new Map();
348
+ for (let i = 0; i < calls.length; i += 1) {
349
+ const call = calls[i];
350
+ let repeated;
351
+ for (const tool of call.tools) {
352
+ if (tool.path === undefined)
353
+ continue;
354
+ if (WRITERS.has(tool.name)) {
355
+ seen.delete(tool.path);
356
+ continue;
357
+ }
358
+ if (tool.name !== 'Read' || failed.has(tool.id))
359
+ continue;
360
+ const tally = tallies.get(tool.path) ?? { reads: 0, repeats: [] };
361
+ tallies.set(tool.path, tally);
362
+ tally.reads += 1;
363
+ const ranges = seen.get(tool.path) ?? new Set();
364
+ seen.set(tool.path, ranges);
365
+ const range = tool.range ?? '';
366
+ if (ranges.has(range)) {
367
+ tally.repeats.push(call);
368
+ repeated = tool.path;
369
+ }
370
+ else
371
+ ranges.add(range);
372
+ }
373
+ // The growth is known only where this call made one tool call and there is a next call to show it.
374
+ const following = calls[i + 1];
375
+ if (repeated !== undefined && call.tools.length === 1 && following !== undefined) {
376
+ const tokens = promptOf(following.record.usage) - promptOf(call.record.usage) - call.record.usage.output_tokens;
377
+ if (tokens > 0) {
378
+ growth.set(call, tokens);
379
+ owner.set(call, repeated);
380
+ }
381
+ }
382
+ }
383
+ }
384
+ const candidates = [...tallies.entries()].filter(([, tally]) => tally.reads >= options.minReads && tally.repeats.length > 0);
385
+ const rows = candidates.map(([path, tally]) => {
386
+ const measuredCalls = tally.repeats.filter((call) => growth.has(call) && owner.get(call) === path);
387
+ return {
388
+ path,
389
+ reads: tally.reads,
390
+ repeats: tally.repeats.length,
391
+ measured: measuredCalls.length,
392
+ tokens: measuredCalls.reduce((sum, call) => sum + (growth.get(call) ?? 0), 0),
393
+ usd: null,
394
+ calls: measuredCalls,
395
+ };
396
+ });
397
+ // The dearest first needs the cost, and the cost needs a run per path: so the order the cap is applied in is the tokens, which the run then prices.
398
+ rows.sort((a, b) => b.tokens - a.tokens || b.repeats - a.repeats || (a.path < b.path ? -1 : 1));
399
+ const listed = rows.slice(0, MAX_LISTED_READS);
400
+ for (const row of listed) {
401
+ if (row.calls.length > 0)
402
+ row.usd = savedBy(threads, growth, new Set(row.calls), options, whole.usd);
403
+ }
404
+ listed.sort((a, b) => (b.usd ?? -1) - (a.usd ?? -1) || b.tokens - a.tokens || (a.path < b.path ? -1 : 1));
405
+ report.reads.omitted = [...tallies.values()].filter((tally) => tally.repeats.length > 0).length - listed.length;
406
+ report.reads.findings = listed.map(({ calls: _calls, ...row }) => row);
407
+ report.reads.repeats = listed.reduce((sum, row) => sum + row.repeats, 0);
408
+ report.reads.measured = listed.reduce((sum, row) => sum + row.measured, 0);
409
+ const allMeasured = new Set(listed.flatMap((row) => row.calls));
410
+ if (allMeasured.size > 0)
411
+ report.reads.usd = savedBy(threads, growth, allMeasured, options, whole.usd);
412
+ // ---- MCP servers loaded and never called ----------------------------------
413
+ const loadedServers = new Map();
414
+ let recorded = false;
415
+ const loadedTools = new Set();
416
+ const loadedNames = new Set();
417
+ for (const part of parts) {
418
+ if (part.loaded.recorded)
419
+ recorded = true;
420
+ for (const tool of part.loaded.tools)
421
+ loadedTools.add(tool);
422
+ for (const server of part.loaded.servers)
423
+ loadedNames.add(server);
424
+ }
425
+ for (const tool of loadedTools) {
426
+ const server = mcpServerOf(tool);
427
+ if (server !== undefined)
428
+ loadedServers.set(server, (loadedServers.get(server) ?? 0) + 1);
429
+ }
430
+ for (const server of loadedNames)
431
+ if (!loadedServers.has(server))
432
+ loadedServers.set(server, null);
433
+ if (recorded && loadedServers.size > 0)
434
+ report.mcp.source = 'transcript';
435
+ else if (options.mcpServers !== undefined && options.mcpServers.length > 0) {
436
+ report.mcp.source = 'flag';
437
+ for (const server of options.mcpServers)
438
+ if (server !== '' && !loadedServers.has(server))
439
+ loadedServers.set(server, null);
440
+ }
441
+ if (report.mcp.source !== 'none') {
442
+ const calledServers = new Set();
443
+ for (const calls of threads.values())
444
+ for (const call of calls)
445
+ for (const tool of call.tools) {
446
+ const server = mcpServerOf(tool.name);
447
+ if (server !== undefined)
448
+ calledServers.add(server);
449
+ }
450
+ report.mcp.loaded = loadedServers.size;
451
+ report.mcp.called = [...loadedServers.keys()].filter((server) => calledServers.has(server)).length;
452
+ report.mcp.unused = [...loadedServers.entries()]
453
+ .filter(([server]) => !calledServers.has(server))
454
+ .map(([server, tools]) => ({ server, tools }))
455
+ .sort((a, b) => (a.server < b.server ? -1 : 1));
456
+ }
457
+ // ---- A CLAUDE.md carried on every turn ------------------------------------
458
+ const main = [...threads.entries()].filter(([key]) => key.endsWith(':main')).flatMap(([, calls]) => calls);
459
+ for (const file of options.claudeMd ?? []) {
460
+ if (!Number.isFinite(file.bytes) || file.bytes <= 0 || main.length === 0)
461
+ continue;
462
+ const at = (tokens) => {
463
+ const records = [];
464
+ for (const [key, calls] of threads) {
465
+ const isMain = key.endsWith(':main');
466
+ calls.forEach((call, index) => {
467
+ if (!isMain)
468
+ records.push(call.record);
469
+ // The first call writes it to the cache, every later one reads it.
470
+ else
471
+ records.push({ ...call.record, usage: without(call.record.usage, tokens, index === 0 ? ['write', 'input', 'read'] : ['read', 'write', 'input']) });
472
+ });
473
+ }
474
+ return Math.max(0, whole.usd - priced(records, options).usd);
475
+ };
476
+ const tokens = Math.ceil(file.bytes / DEFAULT_DIVISOR);
477
+ report.claudeMd.findings.push({
478
+ path: file.path,
479
+ bytes: file.bytes,
480
+ tokens,
481
+ usdLow: at(Math.floor((tokens * (100 - ESTIMATE_ERROR_BAND_PCT)) / 100)),
482
+ usd: at(tokens),
483
+ usdHigh: at(Math.ceil((tokens * (100 + ESTIMATE_ERROR_BAND_PCT)) / 100)),
484
+ calls: main.length,
485
+ });
486
+ }
487
+ return report;
488
+ }
489
+ //# sourceMappingURL=session-waste.js.map