dsh-lean-router 2.0.0 → 2.1.1

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.
@@ -0,0 +1,11 @@
1
+ ---
2
+ status: accepted
3
+ ---
4
+
5
+ # Token 账本以 durable session/event 为真相源
6
+
7
+ cost-meter 的 `ledger.json` 是按天、会话和模型聚合的快照,没有逐 request 记录;lean-router 又需要把真实 Usage 与 RequestSnapshot、任务结果关联起来做回放。因此第一版不修改宿主:以 `session/event` 的 durable `assistant/message` 作为 Usage 主账本,`llm/stream` 只提供实时辅助,costMeter Remote 用于对账;Usage 保留宿主原始字段并显式计算 `prompt = input + cacheRead + cacheWrite`。
8
+
9
+ 第一版只做 durable Usage 回放,不重跑模型。RequestSnapshot 用于归因,不产出 token 真值;live shadow A/B 被推迟到账本可信之后。这样能先验证字段、去重、对账和任务结果关联,但暂不能证明新压缩策略的 token 节省。
10
+
11
+ 当前实现增量先落地为独立库与 fixture adapter,用来验证 Usage 归一化、快照隐私边界、显式断言与报表契约;实时 `session/event`/`llm/stream`/costMeter adapter 与真机 E2E 不属于本增量,待库契约稳定后接入。
@@ -1,6 +1,35 @@
1
1
  # Changelog
2
2
 
3
- > English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.0.0).
3
+ > English version of [changelog.md](./changelog.md). Versions follow package.json (currently 2.1.1).
4
+
5
+ ## 2.1.1 (2026-11-29)
6
+
7
+ ### Improved
8
+
9
+ - **Static tool surface slimmed**: the `code_run` description drops from 459 to 298 characters and the SDK explanation from 2340 to 1738, for 3346 to 2526 in total (-24.5%). Required fields, enums, property names and the conditional `timeoutMs` semantics are all locked by new structural contract assertions, cutting roughly 820 characters of per-turn resident injection.
10
+ - **Conservative tool-output compaction**: new `lib/lean/output-slim.js`, wired into `lib/toolface/executor.js` by wrapping each visible definition's `finalizeContent` in place. Compaction only engages above 2000 characters: adjacent duplicate lines collapse, and adjacent duplicate elements of a string array collapse to the first element plus one marker element. Error, exception, failure, exit-code, path and conclusion lines are never folded. JSON output stays parseable with unchanged keys and types, only the model-visible content changes, the program-visible value never does, and any pre-existing `finalizeContent` is chained rather than replaced.
11
+
12
+ ### Notes
13
+
14
+ - Both changes are static or output-side; real gains need a restart to be observed inside the host, and no device verification has been done yet.
15
+ - Compaction pays off on repetitive log output (example: 3788 to 172 characters) and is a no-op for output without repetition.
16
+
17
+ ## 2.1.0 (2026-11-29)
18
+
19
+ ### Added
20
+
21
+ - **Standalone token ledger** under `lib/token-ledger/`: `createMemoryUsageAdapter` (dedupe and sort by session/turn/step/seq, range reads and subscriptions), `captureRequestSnapshot` (metadata and hashes only; raw prompts and tool output are rejected) and `createTokenReport` (real Usage kept apart from attribution, explicit assertions produce `pass`/`successRate`/`reasons`).
22
+ - **Live Usage adapter** in `lib/token-ledger/live.js`: subscribes to the host's `session/event` and keeps only `assistant/message` events that carry `usage`; `hydrate` backfills through the half-open `snapshotEvents` range; missing services, logger failures and subscription errors all degrade to skip, and `dispose` is idempotent.
23
+ - **Package exports** `./token-ledger` and `./token-ledger/live`.
24
+
25
+ ### Changed
26
+
27
+ - **Band-specific reasoning opener**: the spec `guideText` now asks reasoning and the first reply to start with "We need …" and name the gap before acting; react asks to start with "I'm doing …" and name the action; weak adds no forced opener. `personaText`, `ROUTER_PROMPT` and the preset shards are untouched.
28
+
29
+ ### Notes
30
+
31
+ - The ledger only replays durable Usage and never re-runs a model; the live adapter is not mounted in the preset yet, so nothing is captured at runtime.
32
+ - Host 0.2.2-rc.5 has no costMeter service, so per-request Usage must come from `session/event`, never from cost-meter aggregates.
4
33
 
5
34
  ## 2.0.0 (2026-11-29)
6
35
 
package/docs/changelog.md CHANGED
@@ -1,6 +1,35 @@
1
1
  # 变更记录(changelog)
2
2
 
3
- > 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.0.0)。
3
+ > 中文为主,英文版:[changelog.en.md](./changelog.en.md)。版本号遵循 package.json(当前 2.1.1)。
4
+
5
+ ## 2.1.1 (2026-11-29)
6
+
7
+ ### 优化
8
+
9
+ - **静态工具面瘦身**:`code_run` 的 description 459→298 字符、SDK 说明 2340→1738,合计 3346→2526(-24.5%);required/enum/属性名与 `timeoutMs` 条件语义均由新增的结构契约断言锁定,每轮常驻注入因此减少约 820 字符。
10
+ - **工具输出保守压缩**:新增 `lib/lean/output-slim.js`,并在 `lib/toolface/executor.js` 的 `describe()` 里给每个可见工具就地包装 `finalizeContent`。压缩只在输出超过 2000 字符时启用:折叠相邻重复行,以及字符串数组里相邻重复元素(保留首个 + 一个 marker 元素);错误、异常、失败、退出码、路径与结论行永不折叠。JSON 输出保持可解析、键与类型不变,只改模型可见 content,不改程序内 value;原有 `finalizeContent` 会被串联而不是覆盖。
11
+
12
+ ### 说明
13
+
14
+ - 两项都是静态或输出侧的改动,真实收益需重启后在宿主里观察,尚未做真机验证。
15
+ - 输出压缩对重复日志类输出收益明显(示例 3788→172 字符),对无重复的输出不生效。
16
+
17
+ ## 2.1.0 (2026-11-29)
18
+
19
+ ### 新增
20
+
21
+ - **独立 token 账本库** `lib/token-ledger/`:`createMemoryUsageAdapter`(按 session/turn/step/seq 去重排序、范围读取与订阅)、`captureRequestSnapshot`(只保留元数据与哈希,拒绝原始 prompt 与工具输出)、`createTokenReport`(真实 Usage 与归因分离,显式断言产出 `pass`/`successRate`/`reasons`)。
22
+ - **live Usage adapter** `lib/token-ledger/live.js`:订阅宿主 `session/event`,只收带 `usage` 的 `assistant/message`;`hydrate` 用 `snapshotEvents` 半开区间补录;服务缺失、logger 异常与订阅失败均降级跳过,`dispose` 幂等。
23
+ - **包导出** `./token-ledger` 与 `./token-ledger/live`。
24
+
25
+ ### 变更
26
+
27
+ - **思考句式按 band 分流**:spec 带 `guideText` 末尾要求推理与回复第一句以 "We need …" 开头并先陈述缺口;react 带要求以 "I'm doing …" 开头并直接说明动作;weak 不加强制句式。`personaText`、`ROUTER_PROMPT` 与分片未改动。
28
+
29
+ ### 说明
30
+
31
+ - 账本当前只做 durable Usage 回放,不重跑模型;live adapter 尚未挂载到预设,运行时不会自动采集。
32
+ - 本机宿主 0.2.2-rc.5 无 costMeter 服务,历史记录不得以 cost-meter 聚合数据充当逐请求 Usage。
4
33
 
5
34
  ## 2.0.0 (2026-11-29)
6
35
 
package/lib/bands.js CHANGED
@@ -35,7 +35,8 @@ export const BANDS = {
35
35
  GUIDE_TAIL,
36
36
  guideText:
37
37
  "Near-field guide (inspect-and-plan): you are working a fix/inspection task. Read and locate before changing; state the plan when your information is complete, then apply the smallest safe change and verify it. " +
38
- GUIDE_TAIL,
38
+ GUIDE_TAIL +
39
+ ' Start reasoning and your first reply with "We need …", naming the gap before acting.',
39
40
  },
40
41
  react: {
41
42
  id: "react",
@@ -46,7 +47,8 @@ export const BANDS = {
46
47
  GUIDE_TAIL,
47
48
  guideText:
48
49
  "Near-field guide (hands-on production): you are working a build task. Produce the next working increment now; verify by running it before claiming progress. " +
49
- GUIDE_TAIL,
50
+ GUIDE_TAIL +
51
+ ' Start reasoning and your first reply with "I\'m doing …", naming the action you take.',
50
52
  },
51
53
  weak: {
52
54
  id: "weak",
@@ -0,0 +1,271 @@
1
+ // dsh-lean-router · lib/lean/output-slim.js —— 机制 5:工具输出的保守压缩(同步纯函数)
2
+ //
3
+ // 口径(ticket: context_output_compactor,GT-17「不改 JSON 结构」):
4
+ // - 只在文本超过阈值时启用,小输出一个字都不改;
5
+ // - 普通文本:只折叠「连续 >= 3 行完全相同」的块,保留一行并紧跟一行 marker;
6
+ // - 可 JSON.parse 的文本(code_run 的 content 恒为 JSON 文本):绝不按行折叠顶层。
7
+ // 改为两条保持结构的压缩:
8
+ // a) 字符串值内部做相邻重复行折叠(marker 作为字符串内容);
9
+ // b) 字符串数组折叠相邻相同元素——保留第一个,后面连续相同的 N 个(N >= 2)
10
+ // 替换为一个 marker 字符串,数组长度因此变短(预期行为)。
11
+ // 键与类型不变,再 JSON.stringify 输出;若 stringify 后不比原文短则返回原文;
12
+ // - 错误 / 异常 / 失败 / 退出码 / 文件路径 / 结论行永不折叠、永不删除(两种路径同判据);
13
+ // - 不做结构化摘要、不改值、不重排键。
14
+ //
15
+ // 与 lib/lean/pruner.js 的关系:pruner 按头 / 中 / 尾裁掉中段(宿主 pruner 的纯函数端口),
16
+ // 本模块只做「相邻重复行」的局部折叠,判据更保守,二者互不替代。
17
+ //
18
+ // 零依赖、同步、纯函数:不读会话、不碰 Cordis 上下文,可脱离宿主单测。
19
+ // 注意:本模块只产出「模型可见文本」,值的处理在其调用方(lib/toolface/executor.js)。
20
+
21
+ /** 启用压缩的最小文本长度(严格大于该值才启用,等于阈值不启用)。 */
22
+ export const SLIM_THRESHOLD_CHARS = 2000;
23
+
24
+ /** 连续相同行达到该数量才折叠;2 行重复保持原样。 */
25
+ export const COLLAPSE_MIN_LINES = 3;
26
+
27
+ /** 单次折叠的 marker 原文({collapsed} 为被折叠掉的行数,即 run 长度 - 1)。 */
28
+ export const COLLAPSE_MARKER = '[... {collapsed} identical lines collapsed]';
29
+
30
+ /** 压缩收益 marker 原文({saved} 为折叠本身节省的字符数,不含本 marker)。 */
31
+ export const SAVED_MARKER = '[... output compacted: {saved} chars saved ...]';
32
+
33
+ /**
34
+ * 受保护行的判据。任何命中一项的行都不折叠——宁可少折叠,也不把结论行吃掉。
35
+ * 覆盖:错误 / 异常 / 失败 / 退出码(含中文口径)、结论行、文件路径。
36
+ */
37
+ const PROTECTED_PATTERNS = [
38
+ // 错误 / 异常 / 失败 / 致命(含 stderr、非零退出等常见措辞)
39
+ /\b(?:error|errors|exception|exceptions|failed|failure|failures|fatal|panic|traceback|throw|throws|threw|stderr|denied|refused)\b/i,
40
+ // 退出码 / 退出状态
41
+ /\b(?:exit\s*(?:code|status))\b/i,
42
+ /\b(?:exited\s+with|non-?zero)\b/i,
43
+ // 中文口径的错误与结论
44
+ /(?:错误|异常|失败|退出码|结论|总结|原因|无法|抛出)/,
45
+ // 结论行:整行以结论词开头(大小写不敏感)
46
+ /^\s*(?:summary|conclusion|result|verdict|totals?)\b/i,
47
+ // 文件路径:盘符、UNC、POSIX 绝对路径、./ ../ 相对路径
48
+ /(?:^|[\s"'(<[=:])(?:[A-Za-z]:[\\/]|\\\\|\/|\.{1,2}\/)/,
49
+ // 文件路径:带已知扩展名的文件名
50
+ /(?:^|[\s"'(<[=:])[\w.@~+-]+\.(?:[cm]?[jt]sx?|jsonc?|py|rb|go|rs|java|kt|c|h|cc|cpp|hpp|cs|php|sh|bash|zsh|ps1|cmd|bat|md|markdown|txt|log|ya?ml|toml|ini|cfg|conf|xml|html?|css|scss|sql|db|lock|env|patch|diff)\b/i,
51
+ ];
52
+
53
+ /**
54
+ * 裸大整数 token(16 位以上):`JSON.parse` 会丢精度,遇到这类文档完全不碰,
55
+ * 宁可放弃这次压缩也不改写用户数据。
56
+ */
57
+ const BIG_INTEGER_TOKEN = /(?:^|[\s:,[{])-?\d{16,}(?=[\s,\]}]|$)/;
58
+
59
+ /** 解析阈值:非正数 / 非数字回落到默认值。 */
60
+ function resolveThreshold(options) {
61
+ const value = options?.thresholdChars;
62
+ return Number.isFinite(value) && value > 0 ? Math.floor(value) : SLIM_THRESHOLD_CHARS;
63
+ }
64
+
65
+ /** 该行是否必须原样保留。 */
66
+ export function isProtectedLine(line) {
67
+ return typeof line === 'string' && PROTECTED_PATTERNS.some((pattern) => pattern.test(line));
68
+ }
69
+
70
+ /** 折叠结果的可读 marker。 */
71
+ function collapseMarker(collapsed) {
72
+ return COLLAPSE_MARKER.replace('{collapsed}', String(collapsed));
73
+ }
74
+
75
+ /** 收益 marker。 */
76
+ function savedMarker(saved) {
77
+ return SAVED_MARKER.replace('{saved}', String(saved));
78
+ }
79
+
80
+ /**
81
+ * 按行折叠相邻重复块(不设阈值门、不加收益 marker):普通文本与 JSON 字符串值共用。
82
+ *
83
+ * @param text - 待折叠文本。
84
+ * @returns `{ eol, body, collapsedLines }`:换行风格、折叠正文、被折叠掉的总行数。
85
+ */
86
+ function foldLines(text) {
87
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
88
+ const lines = text.split(/\r?\n/);
89
+ const kept = [];
90
+ let collapsedLines = 0;
91
+
92
+ for (let index = 0; index < lines.length;) {
93
+ const line = lines[index];
94
+ let end = index + 1;
95
+ while (end < lines.length && lines[end] === line) end += 1;
96
+ const runLength = end - index;
97
+ // 受保护的行整段保留:连续相同的错误行也是每条都有信息。
98
+ if (runLength >= COLLAPSE_MIN_LINES && !isProtectedLine(line)) {
99
+ const collapsed = runLength - 1;
100
+ kept.push(line);
101
+ kept.push(collapseMarker(collapsed));
102
+ collapsedLines += collapsed;
103
+ } else {
104
+ for (let offset = index; offset < end; offset += 1) kept.push(line);
105
+ }
106
+ index = end;
107
+ }
108
+
109
+ return { eol, body: kept.join(eol), collapsedLines };
110
+ }
111
+
112
+ /**
113
+ * 折叠一段普通文本并在末尾补收益 marker;不值得改时返回原值。
114
+ * @param text - 已确认超过阈值的文本。
115
+ * @returns 折叠后的文本,或原值。
116
+ */
117
+ function slimPlainText(text) {
118
+ const folded = foldLines(text);
119
+ if (folded.collapsedLines === 0) return text;
120
+ const savedChars = text.length - folded.body.length;
121
+ // 负收益(折叠 marker 比省下的内容还长)就不动原文。
122
+ if (savedChars <= 0) return text;
123
+ return folded.body + folded.eol + savedMarker(savedChars);
124
+ }
125
+
126
+ /**
127
+ * 压缩 JSON 文档里的一个字符串值:只在字符串内部折叠相邻重复行。
128
+ * 未超过阈值的字符串(短值)不碰。
129
+ */
130
+ function slimJsonString(value, threshold) {
131
+ if (value.length <= threshold) return value;
132
+ const folded = foldLines(value);
133
+ if (folded.collapsedLines === 0) return value;
134
+ const savedChars = value.length - folded.body.length;
135
+ if (savedChars <= 0) return value;
136
+ return folded.body + folded.eol + savedMarker(savedChars);
137
+ }
138
+
139
+ /**
140
+ * 折叠字符串数组里相邻相同的元素:保留第一个,后面连续相同的 N 个(N >= 2)
141
+ * 替换成一个 marker 字符串。错误 / 路径 / 结论行元素永不折叠。
142
+ * 非字符串元素不参与折叠(类型与顺序都保持)。
143
+ *
144
+ * @param items - 已递归处理过的数组元素。
145
+ * @returns `{ items, collapsed }`:折叠后的数组与被折叠掉的元素总数。
146
+ */
147
+ function foldStringRuns(items) {
148
+ const kept = [];
149
+ let collapsed = 0;
150
+ for (let index = 0; index < items.length;) {
151
+ const item = items[index];
152
+ let end = index + 1;
153
+ if (typeof item === 'string') {
154
+ while (end < items.length && items[end] === item) end += 1;
155
+ }
156
+ const runLength = end - index;
157
+ // 保留首个,其余至少 2 个才折叠(单个 marker 才比被折叠的元素更短)。
158
+ if (typeof item === 'string' && runLength >= COLLAPSE_MIN_LINES && !isProtectedLine(item)) {
159
+ kept.push(item);
160
+ kept.push(collapseMarker(runLength - 1));
161
+ collapsed += runLength - 1;
162
+ } else {
163
+ for (let offset = index; offset < end; offset += 1) kept.push(items[offset]);
164
+ }
165
+ index = end;
166
+ }
167
+ return { items: kept, collapsed };
168
+ }
169
+
170
+ /**
171
+ * 递归压缩 JSON 值:字符串值内部折叠,字符串数组折叠相邻相同元素;键与类型不变。
172
+ * 数组长度可能变短(只在字符串数组的重复段上),这是预期行为。
173
+ * @returns `{ value, changed }`;`changed` 为 false 时 `value` 与入参结构等价。
174
+ */
175
+ function compactJsonStrings(node, threshold) {
176
+ let changed = false;
177
+ const walk = (current) => {
178
+ if (typeof current === 'string') {
179
+ const slimmed = slimJsonString(current, threshold);
180
+ if (slimmed === current) return current;
181
+ changed = true;
182
+ return slimmed;
183
+ }
184
+ if (Array.isArray(current)) {
185
+ const mapped = current.map(walk);
186
+ const folded = foldStringRuns(mapped);
187
+ if (folded.collapsed > 0) changed = true;
188
+ return folded.collapsed > 0 ? folded.items : mapped;
189
+ }
190
+ if (current !== null && typeof current === 'object') {
191
+ // Object.fromEntries 走 CreateDataProperty,`__proto__` 这类键不会被改写。
192
+ return Object.fromEntries(Object.entries(current).map(([key, child]) => [key, walk(child)]));
193
+ }
194
+ return current;
195
+ };
196
+ const value = walk(node);
197
+ return { value, changed };
198
+ }
199
+
200
+ /**
201
+ * JSON 文档路径:只压缩字符串值内部,结构不动。
202
+ *
203
+ * @param text - 已确认超过阈值的文本。
204
+ * @param threshold - 单字符串值启用折叠的长度阈值。
205
+ * @returns 压缩后的 JSON 文本;不是 JSON、无可压缩字符串、或 stringify 后不更短时返回原文。
206
+ */
207
+ function slimJsonDocument(text, threshold) {
208
+ const trimmed = text.trim();
209
+ if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return undefined;
210
+ if (BIG_INTEGER_TOKEN.test(text)) return text;
211
+ let parsed;
212
+ try {
213
+ parsed = JSON.parse(text);
214
+ } catch {
215
+ return undefined;
216
+ }
217
+ if (parsed === null || typeof parsed !== 'object') return undefined;
218
+ const { value, changed } = compactJsonStrings(parsed, threshold);
219
+ if (!changed) return text;
220
+ // 与 code_run 的 renderJson 同形(2 空格缩进),保证模型读到的排版一致。
221
+ const rendered = JSON.stringify(value, null, 2);
222
+ return rendered.length < text.length ? rendered : text;
223
+ }
224
+
225
+ /**
226
+ * 保守压缩一段模型可见文本。
227
+ *
228
+ * - 非字符串或空串:原样返回;
229
+ * - 未超过阈值:原样返回;
230
+ * - JSON 文本:递归压缩字符串值内部,并折叠字符串数组里相邻相同的元素(数组长度可变短),
231
+ * 键与类型不变;不短则原样返回;
232
+ * - 普通文本:行级折叠相邻重复块,受保护行不折叠。
233
+ *
234
+ * @param text - 待压缩文本。
235
+ * @param options - `thresholdChars` 覆盖阈值(仅供测试 / 预检)。
236
+ * @returns 压缩后的文本;任何情况下都不比原文长(JSON 路径保证),不需要压缩时返回原值。
237
+ */
238
+ export function slimToolOutput(text, options) {
239
+ if (typeof text !== 'string' || text.length === 0) return text;
240
+ const threshold = resolveThreshold(options);
241
+ if (text.length <= threshold) return text;
242
+
243
+ const json = slimJsonDocument(text, threshold);
244
+ if (json !== undefined) return json;
245
+
246
+ return slimPlainText(text);
247
+ }
248
+
249
+ /**
250
+ * 压缩一条 content 数组里的文本块。
251
+ *
252
+ * 只改 `type === 'text'` 且 `text` 是字符串的块,块上的其他字段原样保留;
253
+ * 非 text 块(图片等)与整段无变化时返回**原数组引用**,让调用方可以据此判断是否改动。
254
+ *
255
+ * @param blocks - 工具结果的内容块;非数组原样返回。
256
+ * @param options - 透传给 {@link slimToolOutput}。
257
+ * @returns 压缩后的数组,或未发生变化时的原数组。
258
+ */
259
+ export function slimContentBlocks(blocks, options) {
260
+ if (!Array.isArray(blocks)) return blocks;
261
+ let changed = false;
262
+ const next = blocks.map((block) => {
263
+ if (block === null || typeof block !== 'object') return block;
264
+ if (block.type !== 'text' || typeof block.text !== 'string') return block;
265
+ const slimmed = slimToolOutput(block.text, options);
266
+ if (slimmed === block.text) return block;
267
+ changed = true;
268
+ return { ...block, text: slimmed };
269
+ });
270
+ return changed ? next : blocks;
271
+ }
@@ -0,0 +1,147 @@
1
+ function definedFields(source, keys) {
2
+ const result = {};
3
+ for (const key of keys) {
4
+ if (source[key] !== undefined) result[key] = source[key];
5
+ }
6
+ return result;
7
+ }
8
+
9
+ export function captureRequestSnapshot(input) {
10
+ for (const field of ['prompt', 'body', 'toolOutput']) {
11
+ if (Object.hasOwn(input, field)) {
12
+ throw new Error('RequestSnapshot: raw field "' + field + '" is not allowed');
13
+ }
14
+ }
15
+ const snapshot = definedFields(input, ['sessionId', 'turn', 'step', 'seq', 'headerHash']);
16
+ if (input.tools !== undefined) {
17
+ snapshot.tools = input.tools.map((tool) => definedFields(tool, ['name', 'schemaHash']));
18
+ }
19
+ if (input.partitionChars !== undefined) {
20
+ snapshot.partitionChars = { ...input.partitionChars };
21
+ }
22
+ if (input.taskResult !== undefined) {
23
+ snapshot.taskResult = definedFields(input.taskResult, ['terminal', 'artifacts', 'errors']);
24
+ }
25
+ return snapshot;
26
+ }
27
+
28
+ function compareUsageRecords(left, right) {
29
+ return left.turn - right.turn
30
+ || left.step - right.step
31
+ || left.seq - right.seq;
32
+ }
33
+
34
+ const USAGE_FIELDS = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'reasoningTokens'];
35
+
36
+ function normalizeUsage(usage) {
37
+ const normalized = {};
38
+ for (const field of USAGE_FIELDS) normalized[field] = usage[field] ?? 0;
39
+ normalized.prompt = normalized.inputTokens + normalized.cacheReadTokens + normalized.cacheWriteTokens;
40
+ return normalized;
41
+ }
42
+
43
+ function snapshotKey(snapshot) {
44
+ return JSON.stringify([snapshot.sessionId, snapshot.turn, snapshot.step, snapshot.seq]);
45
+ }
46
+
47
+ export function createTokenReport({
48
+ records = [],
49
+ snapshots = [],
50
+ taskResult = {},
51
+ assertions = {},
52
+ } = {}) {
53
+ const attributionByKey = new Map(snapshots.map((snapshot) => [snapshotKey(snapshot), snapshot]));
54
+ const entries = [...records].sort(compareUsageRecords).map((record) => ({
55
+ ...definedFields(record, ['sessionId', 'turn', 'step', 'seq', 'provider', 'model', 'atMs']),
56
+ usage: normalizeUsage(record.usage),
57
+ snapshot: attributionByKey.get(snapshotKey(record)) ?? null,
58
+ }));
59
+ const usage = normalizeUsage({});
60
+ for (const entry of entries) {
61
+ for (const field of USAGE_FIELDS) usage[field] += entry.usage[field];
62
+ }
63
+ usage.prompt = usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
64
+
65
+ const toolNames = new Set((taskResult.toolCalls ?? []).map((call) => typeof call === 'string' ? call : call.name));
66
+ const artifacts = new Set(taskResult.artifacts ?? []);
67
+ const errors = new Set(taskResult.errors ?? []);
68
+ const reasons = [];
69
+ if (assertions.expectedTerminal !== undefined && taskResult.terminal !== assertions.expectedTerminal) {
70
+ reasons.push('expected terminal "' + assertions.expectedTerminal + '", got "' + taskResult.terminal + '"');
71
+ }
72
+ for (const tool of assertions.requiredTools ?? []) {
73
+ if (!toolNames.has(tool)) reasons.push('missing required tool "' + tool + '"');
74
+ }
75
+ for (const artifact of assertions.requiredArtifacts ?? []) {
76
+ if (!artifacts.has(artifact)) reasons.push('missing required artifact "' + artifact + '"');
77
+ }
78
+ for (const error of assertions.forbiddenErrors ?? []) {
79
+ if (errors.has(error)) reasons.push('forbidden error "' + error + '"');
80
+ }
81
+
82
+ const pass = reasons.length === 0;
83
+ return {
84
+ entries,
85
+ requestSnapshots: snapshots,
86
+ usage,
87
+ taskResult,
88
+ assertions,
89
+ pass,
90
+ successRate: pass ? 1 : 0,
91
+ reasons,
92
+ };
93
+ }
94
+
95
+ function usageKey(record) {
96
+ return JSON.stringify([record.sessionId, record.turn, record.step, record.seq]);
97
+ }
98
+
99
+ export function createMemoryUsageAdapter(initialRecords = []) {
100
+ const records = new Map();
101
+ const watchers = new Set();
102
+ for (const record of initialRecords) {
103
+ const key = usageKey(record);
104
+ if (!records.has(key)) records.set(key, record);
105
+ }
106
+
107
+ function selectRecords(candidates, sessionId, afterSeq, toSeq) {
108
+ return [...candidates]
109
+ .filter((record) => record.sessionId === sessionId
110
+ && record.seq > afterSeq
111
+ && (toSeq === undefined || record.seq <= toSeq))
112
+ .sort(compareUsageRecords);
113
+ }
114
+
115
+ function read(sessionId, afterSeq = 0, toSeq) {
116
+ return selectRecords(records.values(), sessionId, afterSeq, toSeq);
117
+ }
118
+
119
+ return {
120
+ read,
121
+
122
+ append(...newRecords) {
123
+ const addedKeys = new Set();
124
+ for (const record of newRecords) {
125
+ const key = usageKey(record);
126
+ if (records.has(key)) continue;
127
+ records.set(key, record);
128
+ addedKeys.add(key);
129
+ }
130
+ for (const watcher of watchers) {
131
+ const pending = selectRecords(
132
+ [...addedKeys].map((key) => records.get(key)),
133
+ watcher.sessionId,
134
+ watcher.afterSeq,
135
+ );
136
+ for (const record of pending) watcher.callback(record);
137
+ }
138
+ },
139
+
140
+ watch(sessionId, afterSeq, callback) {
141
+ const watcher = { sessionId, afterSeq, callback };
142
+ watchers.add(watcher);
143
+ for (const record of read(sessionId, afterSeq)) callback(record);
144
+ return () => watchers.delete(watcher);
145
+ },
146
+ };
147
+ }