@reinsjs/eval 0.1.0

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/dist/index.js ADDED
@@ -0,0 +1,888 @@
1
+ // src/arms.ts
2
+ import {
3
+ foldCompactions,
4
+ reinjectPins,
5
+ visibilityFilter
6
+ } from "@reinsjs/core";
7
+ function noneArm(name = "none") {
8
+ return {
9
+ name,
10
+ sockets: [],
11
+ // 与 defaultProjectionChain 相同,只少最后一步 budgetTruncate
12
+ projection: { strategies: [visibilityFilter(), foldCompactions(), reinjectPins()] }
13
+ };
14
+ }
15
+ function thresholdArm(name = "threshold") {
16
+ return { name, sockets: [] };
17
+ }
18
+ function withCapabilities(lowering, override) {
19
+ return {
20
+ capabilities(model) {
21
+ const caps = lowering.capabilities(model);
22
+ const patch = typeof override === "function" ? override(caps, model) : override;
23
+ return { ...caps, ...patch };
24
+ },
25
+ toRequest(input) {
26
+ const req = lowering.toRequest(input);
27
+ return { ...req, capabilities: this.capabilities(input.model) };
28
+ },
29
+ stream(req, ctx) {
30
+ return lowering.stream(req, ctx);
31
+ }
32
+ };
33
+ }
34
+ function withContextWindow(lowering, contextWindow) {
35
+ if (!Number.isFinite(contextWindow) || contextWindow <= 0) {
36
+ throw new RangeError(`contextWindow \u5FC5\u987B\u662F\u6B63\u7684\u6709\u9650\u6570\uFF0C\u6536\u5230 ${contextWindow}`);
37
+ }
38
+ return withCapabilities(lowering, { contextWindow });
39
+ }
40
+
41
+ // src/gate.ts
42
+ function checkGate(report, opts) {
43
+ const reference = report.summary[opts.reference];
44
+ const candidate = report.summary[opts.candidate];
45
+ if (!reference) throw new Error(`\u62A5\u544A\u91CC\u6CA1\u6709\u57FA\u7EBF\u81C2 "${opts.reference}"`);
46
+ if (!candidate) throw new Error(`\u62A5\u544A\u91CC\u6CA1\u6709\u5019\u9009\u81C2 "${opts.candidate}"`);
47
+ const ratio = opts.tokenRatioMax ?? 1;
48
+ const checks = [];
49
+ checks.push({
50
+ name: "tokens",
51
+ rule: `\u5019\u9009\u603B token \u2264 \u57FA\u7EBF \xD7 ${ratio}`,
52
+ reference: reference.tokens.total,
53
+ candidate: candidate.tokens.total,
54
+ pass: candidate.tokens.total <= reference.tokens.total * ratio
55
+ });
56
+ checks.push({
57
+ name: "completion",
58
+ rule: "\u5019\u9009\u5B8C\u6210\u5EA6 \u2265 \u57FA\u7EBF",
59
+ reference: reference.completion,
60
+ candidate: candidate.completion,
61
+ pass: candidate.completion >= reference.completion
62
+ });
63
+ if (reference.recall === void 0 && candidate.recall === void 0) {
64
+ checks.push({ name: "recall", rule: "\u5019\u9009\u53EC\u56DE \u2265 \u57FA\u7EBF", pass: true, note: "\u6CA1\u6709\u9884\u57CB\u4E8B\u5B9E\uFF0C\u89C6\u4E3A\u901A\u8FC7" });
65
+ } else {
66
+ checks.push({
67
+ name: "recall",
68
+ rule: "\u5019\u9009\u53EC\u56DE \u2265 \u57FA\u7EBF",
69
+ ...reference.recall !== void 0 ? { reference: reference.recall } : {},
70
+ ...candidate.recall !== void 0 ? { candidate: candidate.recall } : {},
71
+ pass: (candidate.recall ?? 0) >= (reference.recall ?? 0)
72
+ });
73
+ }
74
+ checks.push({
75
+ name: "governance",
76
+ rule: "\u5019\u9009\u6574\u7406\u540E\u8FDD\u89C4\u7387 \u2264 \u6574\u7406\u524D",
77
+ reference: candidate.violations.before,
78
+ candidate: candidate.violations.after,
79
+ pass: candidate.violations.after <= candidate.violations.before
80
+ });
81
+ return { pass: checks.every((c) => c.pass), checks, reference, candidate };
82
+ }
83
+
84
+ // src/jsonl.ts
85
+ import { createCoreRegistry } from "@reinsjs/core";
86
+ var JsonlParseError = class extends Error {
87
+ constructor(line, message, options) {
88
+ super(`\u7B2C ${line} \u884C\uFF1A${message}`, options);
89
+ this.line = line;
90
+ this.name = "JsonlParseError";
91
+ }
92
+ line;
93
+ };
94
+ function parseEventsJsonl(text, opts = {}) {
95
+ const registry = opts.registry ?? createCoreRegistry();
96
+ const out = [];
97
+ const lines = text.split("\n");
98
+ for (let i = 0; i < lines.length; i++) {
99
+ const line = lines[i].trim();
100
+ if (line === "") continue;
101
+ let raw;
102
+ try {
103
+ raw = JSON.parse(line);
104
+ } catch (err) {
105
+ throw new JsonlParseError(i + 1, "\u4E0D\u662F\u5408\u6CD5 JSON", { cause: err });
106
+ }
107
+ try {
108
+ out.push(registry.read(raw));
109
+ } catch (err) {
110
+ throw new JsonlParseError(i + 1, err instanceof Error ? err.message : String(err), { cause: err });
111
+ }
112
+ }
113
+ return out;
114
+ }
115
+ function toEventsJsonl(events) {
116
+ return events.length === 0 ? "" : `${events.map((e) => JSON.stringify(e)).join("\n")}
117
+ `;
118
+ }
119
+
120
+ // src/metrics.ts
121
+ import { isModelOutput } from "@reinsjs/core";
122
+
123
+ // src/recorded-tools.ts
124
+ function canonicalArgs(args) {
125
+ return JSON.stringify(sortKeys(args));
126
+ }
127
+ function sortKeys(v) {
128
+ if (Array.isArray(v)) return v.map(sortKeys);
129
+ if (v !== null && typeof v === "object") {
130
+ const out = {};
131
+ for (const k of Object.keys(v).sort()) {
132
+ out[k] = sortKeys(v[k]);
133
+ }
134
+ return out;
135
+ }
136
+ return v;
137
+ }
138
+ function recordedTools(recording, opts = {}) {
139
+ const results = /* @__PURE__ */ new Map();
140
+ for (const e of recording) {
141
+ if (e.type === "core.tool_result") {
142
+ const r = e;
143
+ results.set(r.payload.toolCallId, r);
144
+ }
145
+ }
146
+ const byName = /* @__PURE__ */ new Map();
147
+ const stats = { pairs: 0, byName: {}, spilled: 0, unanswered: 0 };
148
+ for (const e of recording) {
149
+ if (e.type !== "core.tool_call") continue;
150
+ const call = e;
151
+ const { name, toolCallId, args } = call.payload;
152
+ if (opts.only && !opts.only.includes(name)) continue;
153
+ const r = results.get(toolCallId);
154
+ if (!r) {
155
+ stats.unanswered++;
156
+ continue;
157
+ }
158
+ if (r.payload.spilled) stats.spilled++;
159
+ stats.pairs++;
160
+ stats.byName[name] = (stats.byName[name] ?? 0) + 1;
161
+ const list = byName.get(name) ?? [];
162
+ list.push({
163
+ key: canonicalArgs(args),
164
+ result: { content: r.payload.content, isError: r.payload.isError }
165
+ });
166
+ byName.set(name, list);
167
+ }
168
+ const tools = [];
169
+ for (const [name, calls] of byName) {
170
+ const spec = opts.specs?.[name] ?? {};
171
+ const cursor = /* @__PURE__ */ new Map();
172
+ const used = /* @__PURE__ */ new Set();
173
+ const tool = {
174
+ name,
175
+ description: spec.description ?? `Replays recorded results of "${name}" from a previous real session.`,
176
+ inputSchema: spec.inputSchema ?? { type: "object", additionalProperties: true },
177
+ ...spec.risk !== void 0 ? { risk: spec.risk } : {},
178
+ ...spec.needsApproval !== void 0 ? { needsApproval: spec.needsApproval } : {},
179
+ ...spec.resultPolicy !== void 0 ? { resultPolicy: spec.resultPolicy } : {},
180
+ async execute(input, ctx) {
181
+ const key = canonicalArgs(input);
182
+ const matches = calls.map((c, i) => c.key === key ? i : -1).filter((i) => i >= 0);
183
+ if (matches.length > 0) {
184
+ const n = cursor.get(key) ?? 0;
185
+ const idx = matches[n % matches.length];
186
+ cursor.set(key, n + 1);
187
+ used.add(idx);
188
+ return calls[idx].result;
189
+ }
190
+ const fb = await opts.fallback?.(name, input, ctx);
191
+ if (fb) return fb;
192
+ if (opts.sequence) {
193
+ const next = calls.findIndex((_, i) => !used.has(i));
194
+ if (next >= 0) {
195
+ used.add(next);
196
+ return calls[next].result;
197
+ }
198
+ }
199
+ return noRecording(name, input);
200
+ }
201
+ };
202
+ tools.push(tool);
203
+ }
204
+ return { tools, stats };
205
+ }
206
+ function noRecording(name, input) {
207
+ const content = [
208
+ {
209
+ type: "text",
210
+ text: `No recorded response for ${name} with these arguments: ${JSON.stringify(input)}. This is a replayed environment; only previously observed calls have data. Try the arguments you used before, or proceed with what you already have.`
211
+ }
212
+ ];
213
+ return { content, isError: true };
214
+ }
215
+
216
+ // src/metrics.ts
217
+ var ZERO_TOKENS = {
218
+ input: 0,
219
+ output: 0,
220
+ cacheRead: 0,
221
+ cacheWrite: 0,
222
+ total: 0
223
+ };
224
+ function sumTokens(timeline) {
225
+ const t = { ...ZERO_TOKENS };
226
+ for (const e of timeline) {
227
+ if (e.type !== "core.budget_usage") continue;
228
+ const u = e.payload.tokens;
229
+ t.input += u.input;
230
+ t.output += u.output;
231
+ t.cacheRead += u.cacheRead ?? 0;
232
+ t.cacheWrite += u.cacheWrite ?? 0;
233
+ }
234
+ t.total = t.input + t.output + t.cacheRead + t.cacheWrite;
235
+ return t;
236
+ }
237
+ function addTokens(a, b) {
238
+ return {
239
+ input: a.input + b.input,
240
+ output: a.output + b.output,
241
+ cacheRead: a.cacheRead + b.cacheRead,
242
+ cacheWrite: a.cacheWrite + b.cacheWrite,
243
+ total: a.total + b.total
244
+ };
245
+ }
246
+ function billableTokens(t) {
247
+ return t.input + t.output + 0.1 * t.cacheRead + t.cacheWrite;
248
+ }
249
+ function cacheHitRateOf(t) {
250
+ const context = t.input + t.cacheRead + t.cacheWrite;
251
+ return context === 0 ? void 0 : t.cacheRead / context;
252
+ }
253
+ function splitModelTurns(timeline) {
254
+ const turns = [];
255
+ const preamble = [];
256
+ let i = 0;
257
+ while (i < timeline.length && !isModelOutput(timeline[i])) preamble.push(timeline[i++]);
258
+ while (i < timeline.length) {
259
+ const output = [];
260
+ while (i < timeline.length && isModelOutput(timeline[i])) output.push(timeline[i++]);
261
+ const aftermath = [];
262
+ while (i < timeline.length && !isModelOutput(timeline[i])) aftermath.push(timeline[i++]);
263
+ turns.push({ output, aftermath });
264
+ }
265
+ if (turns[0]) turns[0].aftermath = [...preamble, ...turns[0].aftermath];
266
+ return turns;
267
+ }
268
+ function countCompactions(timeline) {
269
+ const counts = { model: 0, threshold: 0, maxConsecutive: 0 };
270
+ for (const e of timeline) {
271
+ if (e.type !== "core.compaction") continue;
272
+ const by = e.payload.decidedBy;
273
+ if (by === "model") counts.model++;
274
+ else counts.threshold++;
275
+ }
276
+ let run = 0;
277
+ for (const turn of splitModelTurns(timeline)) {
278
+ const n = turn.aftermath.filter((e) => e.type === "core.compaction").length;
279
+ run = n > 0 ? run + n : 0;
280
+ counts.maxConsecutive = Math.max(counts.maxConsecutive, run);
281
+ }
282
+ return counts;
283
+ }
284
+ function countRepeatedToolCalls(timeline) {
285
+ const seen = /* @__PURE__ */ new Set();
286
+ let repeated = 0;
287
+ for (const e of timeline) {
288
+ if (e.type !== "core.tool_call") continue;
289
+ const { name, args } = e.payload;
290
+ const key = `${name}\0${canonicalArgs(args)}`;
291
+ if (seen.has(key)) repeated++;
292
+ else seen.add(key);
293
+ }
294
+ return repeated;
295
+ }
296
+ function isModelAction(e) {
297
+ return e.type === "core.tool_call" || e.type === "core.model_text";
298
+ }
299
+ function measureViolations(timeline, constraints) {
300
+ const firstCompaction = timeline.findIndex((e) => e.type === "core.compaction");
301
+ const before = { actions: 0, violations: 0, rate: 0 };
302
+ const after = { actions: 0, violations: 0, rate: 0 };
303
+ const ctx = { timeline };
304
+ timeline.forEach((e, i) => {
305
+ if (!isModelAction(e)) return;
306
+ const window = firstCompaction >= 0 && i > firstCompaction ? after : before;
307
+ window.actions++;
308
+ if (constraints.some((c) => c.violates(e, ctx))) window.violations++;
309
+ });
310
+ before.rate = before.actions === 0 ? 0 : before.violations / before.actions;
311
+ after.rate = after.actions === 0 ? 0 : after.violations / after.actions;
312
+ return { before, after };
313
+ }
314
+ function measureTimeline(timeline, constraints = []) {
315
+ const tokens = sumTokens(timeline);
316
+ const cacheHitRate = cacheHitRateOf(tokens);
317
+ let toolCalls = 0;
318
+ let toolErrors = 0;
319
+ for (const e of timeline) {
320
+ if (e.type === "core.tool_call") toolCalls++;
321
+ else if (e.type === "core.tool_result" && e.payload.isError)
322
+ toolErrors++;
323
+ }
324
+ return {
325
+ tokens,
326
+ ...cacheHitRate !== void 0 ? { cacheHitRate } : {},
327
+ turns: splitModelTurns(timeline).length,
328
+ toolCalls,
329
+ toolErrors,
330
+ repeatedToolCalls: countRepeatedToolCalls(timeline),
331
+ compactions: countCompactions(timeline),
332
+ violations: measureViolations(timeline, constraints)
333
+ };
334
+ }
335
+ function finalTextOf(timeline) {
336
+ const turns = splitModelTurns(timeline);
337
+ for (let i = turns.length - 1; i >= 0; i--) {
338
+ const texts = turns[i].output.filter((e) => e.type === "core.model_text").map((e) => e.payload.text);
339
+ if (texts.length > 0) return texts.join("\n");
340
+ }
341
+ return "";
342
+ }
343
+ function mean(values) {
344
+ return values.length === 0 ? 0 : values.reduce((a, b) => a + b, 0) / values.length;
345
+ }
346
+
347
+ // src/recording.ts
348
+ var FETCH_HEADER = /^\[blob "([^"]+)": characters ([\d,]+)–([\d,]+) of ([\d,]+) \([\d,]+ lines total\)[^\]]*\]\n?/;
349
+ var num = (s) => Number(s.replace(/,/g, ""));
350
+ function parseFetchChunk(text) {
351
+ const m = FETCH_HEADER.exec(text);
352
+ if (!m) return void 0;
353
+ const [header, id, start, end, total] = m;
354
+ return { id, start: num(start), end: num(end), total: num(total), text: text.slice(header.length) };
355
+ }
356
+ function assembleChunks(chunks) {
357
+ if (chunks.length === 0) return void 0;
358
+ const total = chunks[0].total;
359
+ const sorted = [...chunks].sort((a, b) => a.start - b.start);
360
+ let cursor = 0;
361
+ let out = "";
362
+ for (const c of sorted) {
363
+ if (c.total !== total) return void 0;
364
+ if (c.start > cursor) return void 0;
365
+ if (c.text.length !== c.end - c.start) return void 0;
366
+ if (c.end > cursor) {
367
+ out += c.text.slice(cursor - c.start);
368
+ cursor = c.end;
369
+ }
370
+ }
371
+ return cursor === total ? out : void 0;
372
+ }
373
+ var textOf = (content) => content.map((p) => p.type === "text" ? p.text : "").join("");
374
+ function unspillRecording(recording, opts = {}) {
375
+ const fetchName = opts.fetchToolName ?? "fetch_blob";
376
+ const dropFetch = opts.dropFetchBlob ?? true;
377
+ const chunks = /* @__PURE__ */ new Map();
378
+ const fetchCallIds = /* @__PURE__ */ new Set();
379
+ for (const e of recording) {
380
+ if (e.type === "core.tool_call" && e.payload.name === fetchName) {
381
+ fetchCallIds.add(e.payload.toolCallId);
382
+ continue;
383
+ }
384
+ if (e.type !== "core.tool_result") continue;
385
+ const r = e;
386
+ if (r.payload.name !== fetchName || r.payload.isError) continue;
387
+ const chunk = parseFetchChunk(textOf(r.payload.content));
388
+ if (!chunk) continue;
389
+ const list = chunks.get(chunk.id) ?? [];
390
+ list.push(chunk);
391
+ chunks.set(chunk.id, list);
392
+ }
393
+ const restored = [];
394
+ const incomplete = [];
395
+ const events = [];
396
+ let droppedFetches = 0;
397
+ for (const e of recording) {
398
+ if (dropFetch) {
399
+ if (e.type === "core.tool_call" && fetchCallIds.has(e.payload.toolCallId)) {
400
+ droppedFetches++;
401
+ continue;
402
+ }
403
+ if (e.type === "core.tool_result" && fetchCallIds.has(e.payload.toolCallId))
404
+ continue;
405
+ }
406
+ if (e.type !== "core.tool_result") {
407
+ events.push(e);
408
+ continue;
409
+ }
410
+ const r = e;
411
+ const spilled = r.payload.spilled;
412
+ if (!spilled) {
413
+ events.push(e);
414
+ continue;
415
+ }
416
+ const full = assembleChunks(chunks.get(spilled.blobId) ?? []);
417
+ if (full === void 0) {
418
+ incomplete.push(spilled.blobId);
419
+ events.push(e);
420
+ continue;
421
+ }
422
+ restored.push(spilled.blobId);
423
+ const { spilled: _drop, ...payload } = r.payload;
424
+ events.push({ ...r, payload: { ...payload, content: [{ type: "text", text: full }] } });
425
+ }
426
+ return { events, restored, incomplete, droppedFetches };
427
+ }
428
+ var jsonForm = (s) => JSON.stringify(s).slice(1, -1);
429
+ function scrubEvents(events, replacements) {
430
+ const ordered = replacements.map((r, i) => ({ from: jsonForm(r[0]), to: jsonForm(r[1]), i })).filter((r) => r.from.length > 0).sort((a, b) => b.from.length - a.from.length);
431
+ const hits = replacements.map(() => 0);
432
+ const out = [];
433
+ for (const e of events) {
434
+ let text = JSON.stringify(e);
435
+ for (const r of ordered) {
436
+ const parts = text.split(r.from);
437
+ if (parts.length === 1) continue;
438
+ hits[r.i] = (hits[r.i] ?? 0) + parts.length - 1;
439
+ text = parts.join(r.to);
440
+ }
441
+ out.push(JSON.parse(text));
442
+ }
443
+ return { events: out, hits };
444
+ }
445
+ function aliasTable(values, alias) {
446
+ const seen = /* @__PURE__ */ new Set();
447
+ const out = [];
448
+ for (const v of values) {
449
+ if (v === "" || seen.has(v)) continue;
450
+ seen.add(v);
451
+ out.push([v, alias(out.length + 1, v)]);
452
+ }
453
+ return out;
454
+ }
455
+ function matchStrings(events, pattern) {
456
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
457
+ const re = new RegExp(pattern.source, flags);
458
+ const seen = /* @__PURE__ */ new Set();
459
+ const out = [];
460
+ for (const e of events) {
461
+ const text = JSON.stringify(e);
462
+ for (const m of text.matchAll(re)) {
463
+ const v = m[0];
464
+ if (!seen.has(v)) {
465
+ seen.add(v);
466
+ out.push(v);
467
+ }
468
+ }
469
+ }
470
+ return out;
471
+ }
472
+ function jsonValuesAt(events, keys) {
473
+ const want = new Set(keys);
474
+ const seen = /* @__PURE__ */ new Set();
475
+ const out = [];
476
+ const visit = (v) => {
477
+ if (Array.isArray(v)) {
478
+ for (const x of v) visit(x);
479
+ return;
480
+ }
481
+ if (v === null || typeof v !== "object") return;
482
+ for (const [k, x] of Object.entries(v)) {
483
+ if (want.has(k) && typeof x === "string" && x !== "" && !seen.has(x)) {
484
+ seen.add(x);
485
+ out.push(x);
486
+ }
487
+ if (k === "text" && typeof x === "string") {
488
+ const parsed = tryParseJson(x);
489
+ if (parsed !== void 0) visit(parsed);
490
+ }
491
+ visit(x);
492
+ }
493
+ };
494
+ for (const e of events) visit(e.payload);
495
+ return out;
496
+ }
497
+ function tryParseJson(text) {
498
+ const t = text.trimStart();
499
+ if (!t.startsWith("{") && !t.startsWith("[")) return void 0;
500
+ try {
501
+ return JSON.parse(t);
502
+ } catch {
503
+ return void 0;
504
+ }
505
+ }
506
+
507
+ // src/report.ts
508
+ var pct = (v, digits = 0) => v === void 0 ? "\u2014" : `${(v * 100).toFixed(digits)}%`;
509
+ var num2 = (v) => Math.round(v).toLocaleString("en-US");
510
+ var secs = (ms) => `${(ms / 1e3).toFixed(1)}s`;
511
+ function renderReport(report, opts = {}) {
512
+ const arms = Object.values(report.summary);
513
+ const lines = [];
514
+ const fixtures = new Set(report.outcomes.map((o) => o.fixtureId)).size;
515
+ lines.push(`# eval \u62A5\u544A`);
516
+ lines.push("");
517
+ lines.push(
518
+ `\u6A21\u578B \`${report.model.provider}/${report.model.id}\`\uFF0C${fixtures} \u4E2A fixture \xD7 ${arms.length} \u81C2\uFF0C\u5171 ${report.outcomes.length} \u6B21\u8FD0\u884C\uFF0C\u8017\u65F6 ${secs(report.finishedAt - report.startedAt)}\u3002`
519
+ );
520
+ lines.push("");
521
+ lines.push(
522
+ "| \u81C2 | \u8DD1\u5B8C | \u5B8C\u6210\u5EA6 | \u603B token | \u8BA1\u8D39\u7B49\u4EF7 | \u7F13\u5B58\u547D\u4E2D | \u53EC\u56DE | \u8FDD\u89C4\u7387 \u524D\u2192\u540E | \u6574\u7406 \u6A21\u578B/\u9608\u503C/\u8FDE\u7EED | \u8F6E | \u5DE5\u5177 | \u91CD\u590D\u8C03\u7528 | \u5899\u949F |"
523
+ );
524
+ lines.push("| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |");
525
+ for (const a of arms) {
526
+ lines.push(
527
+ `| ${a.arm} | ${pct(a.finishedRate)} | ${pct(a.completion)} | ${num2(a.tokens.total)} | ${num2(billableTokens(a.tokens))} | ${pct(a.cacheHitRate, 1)} | ${pct(a.recall)} | ${pct(a.violations.before, 1)} \u2192 ${pct(a.violations.after, 1)} | ${a.compactions.model.toFixed(1)} / ${a.compactions.threshold.toFixed(1)} / ${a.compactions.maxConsecutive.toFixed(1)} | ${a.turns.toFixed(1)} | ${a.toolCalls.toFixed(1)} | ${a.repeatedToolCalls.toFixed(1)} | ${secs(a.wallMs)} |`
528
+ );
529
+ }
530
+ lines.push("");
531
+ lines.push(
532
+ "\u5747\u503C\u6309 fixture \xD7 \u91CD\u590D\u53D6\uFF1B\u6574\u7406\u4E09\u5217\u662F\u6BCF\u6B21\u8FD0\u884C\u7684\u6B21\u6570\u5747\u503C\u3002\u603B token \u628A\u7F13\u5B58\u8BFB\u6309 1\xD7 \u8BA1\uFF08\u6A21\u578B\u6BCF\u8F6E\u8BFB\u4E86\u591A\u5C11\uFF09\uFF0C\u8BA1\u8D39\u7B49\u4EF7\u6309\u7F13\u5B58\u8BFB 0.1\xD7 \u6298\u7B97\uFF08\u8D26\u5355\uFF09\u3002"
533
+ );
534
+ if (opts.gate) {
535
+ lines.push("");
536
+ lines.push(
537
+ `## \u95E8\u7981\uFF1A${opts.gate.pass ? "\u901A\u8FC7 \u2705" : "\u672A\u901A\u8FC7 \u274C"}\uFF08\u5019\u9009 \`${opts.gate.candidate.arm}\` \u5BF9\u7167 \`${opts.gate.reference.arm}\`\uFF09`
538
+ );
539
+ lines.push("");
540
+ lines.push("| \u89C4\u5219 | \u57FA\u7EBF | \u5019\u9009 | \u7ED3\u679C |");
541
+ lines.push("| --- | ---: | ---: | --- |");
542
+ for (const c of opts.gate.checks) {
543
+ const fmt = (v) => v === void 0 ? "\u2014" : c.name === "tokens" ? num2(v) : pct(v, 1);
544
+ lines.push(
545
+ `| ${c.rule} | ${fmt(c.reference)} | ${fmt(c.candidate)} | ${c.pass ? "\u2705" : "\u274C"}${c.note ? ` ${c.note}` : ""} |`
546
+ );
547
+ }
548
+ }
549
+ if (opts.detail) {
550
+ lines.push("");
551
+ lines.push("## \u660E\u7EC6");
552
+ lines.push("");
553
+ lines.push(
554
+ "| fixture | \u81C2 | # | \u72B6\u6001 | \u5B8C\u6210\u5EA6 | \u603B token | \u8BA1\u8D39\u7B49\u4EF7 | \u7F13\u5B58\u547D\u4E2D | \u53EC\u56DE | \u8FDD\u89C4 \u524D/\u540E | \u6574\u7406 \u6A21\u578B/\u9608\u503C/\u8FDE\u7EED | \u8F6E | \u5DE5\u5177 | \u5899\u949F |"
555
+ );
556
+ lines.push(
557
+ "| --- | --- | ---: | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |"
558
+ );
559
+ for (const o of report.outcomes) lines.push(detailRow(o));
560
+ }
561
+ return `${lines.join("\n")}
562
+ `;
563
+ }
564
+ function detailRow(o) {
565
+ const m = o.metrics;
566
+ return `| ${o.fixtureId} | ${o.arm} | ${o.repeat} | ${m.status} | ${pct(m.completed)} | ${num2(m.tokens.total)} | ${num2(billableTokens(m.tokens))} | ${pct(m.cacheHitRate, 1)} | ${pct(m.recall)} | ${m.violations.before.violations}/${m.violations.before.actions} \u2192 ${m.violations.after.violations}/${m.violations.after.actions} | ${m.compactions.model} / ${m.compactions.threshold} / ${m.compactions.maxConsecutive} | ${m.turns} | ${m.toolCalls} | ${secs(m.wallMs)} |`;
567
+ }
568
+
569
+ // src/runner.ts
570
+ import {
571
+ createCoreRegistry as createCoreRegistry2,
572
+ memoryStore,
573
+ readTimeline,
574
+ runLoop,
575
+ uuidv7
576
+ } from "@reinsjs/core";
577
+ var PROBE_NOTE = "Answer the following question using only what you already know from this conversation. Do not call tools except to bring back a previously spilled or folded tool result. Answer concisely.";
578
+ async function runEval(opts) {
579
+ assertFixtures(opts);
580
+ const now = opts.now ?? Date.now;
581
+ const startedAt = now();
582
+ const repeats = opts.repeats ?? 1;
583
+ const outcomes = [];
584
+ for (const fixture of opts.fixtures) {
585
+ for (const arm of opts.arms) {
586
+ const start = opts.repeatStart ?? 1;
587
+ for (let repeat = start; repeat < start + repeats; repeat++) {
588
+ opts.signal?.throwIfAborted();
589
+ const outcome = await runCell(opts, fixture, arm, repeat);
590
+ outcomes.push(outcome);
591
+ opts.onOutcome?.(outcome);
592
+ }
593
+ }
594
+ }
595
+ const finishedAt = now();
596
+ return { model: opts.model, startedAt, finishedAt, outcomes, summary: summarize(outcomes) };
597
+ }
598
+ function assertFixtures(opts) {
599
+ if (opts.fixtures.length === 0) throw new Error("\u6CA1\u6709 fixture");
600
+ if (opts.arms.length === 0) throw new Error("\u6CA1\u6709\u81C2");
601
+ const names = /* @__PURE__ */ new Set();
602
+ for (const arm of opts.arms) {
603
+ if (names.has(arm.name)) throw new Error(`\u81C2\u540D\u91CD\u590D\uFF1A${arm.name}`);
604
+ names.add(arm.name);
605
+ }
606
+ for (const f of opts.fixtures) {
607
+ for (const fact of f.facts ?? []) {
608
+ if (fact.expect === void 0 && !opts.judge) {
609
+ throw new Error(`fixture ${f.id} \u7684\u4E8B\u5B9E ${fact.id} \u6CA1\u6709 expect\uFF0C\u4E5F\u6CA1\u6709\u914D judge`);
610
+ }
611
+ }
612
+ if (f.task.seed) {
613
+ f.task.seed.forEach((e, i) => {
614
+ if (e.seq !== i + 1)
615
+ throw new Error(`fixture ${f.id} \u7684\u79CD\u5B50\u5386\u53F2 seq \u5FC5\u987B\u4ECE 1 \u8D77\u8FDE\u7EED\uFF0C\u7B2C ${i + 1} \u6761 seq \u4E3A ${e.seq}`);
616
+ });
617
+ }
618
+ }
619
+ }
620
+ async function runCell(opts, fixture, arm, repeat) {
621
+ const now = opts.now ?? Date.now;
622
+ const env = {
623
+ stores: (opts.stores ?? memoryStore)(),
624
+ lowering: fixture.contextWindow ? withContextWindow(opts.lowering, fixture.contextWindow) : opts.lowering,
625
+ model: opts.model,
626
+ registry: opts.registry ?? createCoreRegistry2(),
627
+ systemPrompt: joinPrompts(fixture.task.systemPrompt, arm.systemPrompt),
628
+ now,
629
+ newId: opts.newId ?? uuidv7
630
+ };
631
+ const cell = { fixtureId: fixture.id, arm: arm.name, repeat };
632
+ const emit = (probe) => (e) => opts.onEvent?.(e, probe ? { ...cell, probe } : cell);
633
+ let sessionId = env.newId(now());
634
+ if (fixture.task.seed?.length) {
635
+ await env.stores.log.append(fixture.task.seed.map((e) => ({ ...e, sessionId })));
636
+ }
637
+ const sessionIds = [sessionId];
638
+ const wallStart = now();
639
+ let result = await drain(
640
+ runLoop(loopConfig(env, fixture, arm, sessionId, { input: fixture.task.input })),
641
+ emit()
642
+ );
643
+ let resumes = 0;
644
+ let steps = 0;
645
+ const maxSteps = opts.maxSteps ?? 200;
646
+ const draft = () => ({
647
+ ...cell,
648
+ sessionIds,
649
+ timelines: [],
650
+ timeline: [],
651
+ fresh: [],
652
+ result,
653
+ finalText: ""
654
+ });
655
+ while (steps++ < maxSteps) {
656
+ opts.signal?.throwIfAborted();
657
+ if (result.status === "handoff") {
658
+ sessionId = result.toSessionId;
659
+ sessionIds.push(sessionId);
660
+ result = await drain(runLoop(loopConfig(env, fixture, arm, sessionId, {})), emit());
661
+ continue;
662
+ }
663
+ if (result.status !== "paused") break;
664
+ if (result.reason === "approval") {
665
+ const decisions = [];
666
+ let blocked = false;
667
+ for (const i of result.interruptions) {
668
+ if (i.kind === "approval") {
669
+ const approved = fixture.approve ? fixture.approve(i, draft()) : true;
670
+ decisions.push({ toolCallId: i.toolCallId, approved, by: "eval" });
671
+ } else blocked = true;
672
+ }
673
+ if (blocked) break;
674
+ result = await drain(
675
+ runLoop(loopConfig(env, fixture, arm, sessionId, { resume: result.state, decisions })),
676
+ emit()
677
+ );
678
+ continue;
679
+ }
680
+ if (result.reason === "budget" && resumes < (fixture.maxResumes ?? 0)) {
681
+ resumes++;
682
+ result = await drain(
683
+ runLoop(loopConfig(env, fixture, arm, sessionId, { resume: result.state })),
684
+ emit()
685
+ );
686
+ continue;
687
+ }
688
+ break;
689
+ }
690
+ const wallMs = now() - wallStart;
691
+ const timelines = [];
692
+ for (const id of sessionIds)
693
+ timelines.push(await readTimeline(env.stores.log, id, { registry: env.registry }));
694
+ const timeline = timelines.flat();
695
+ const seedLen = fixture.task.seed?.length ?? 0;
696
+ const fresh = seedLen > 0 ? [...(timelines[0] ?? []).slice(seedLen), ...timelines.slice(1).flat()] : timeline;
697
+ const outcomeDraft = {
698
+ ...cell,
699
+ sessionIds,
700
+ timelines,
701
+ timeline,
702
+ fresh,
703
+ result,
704
+ finalText: finalTextOf(fresh)
705
+ };
706
+ const completed = clamp01(await fixture.completion(outcomeDraft));
707
+ const facts = [];
708
+ let probeTokens = { ...ZERO_TOKENS };
709
+ const last = timelines[timelines.length - 1];
710
+ const lastSeq = last[last.length - 1]?.seq ?? 0;
711
+ for (const fact of fixture.facts ?? []) {
712
+ opts.signal?.throwIfAborted();
713
+ const probe = await runProbe(opts, env, fixture, arm, sessionId, lastSeq, fact, emit(fact.id));
714
+ probeTokens = addTokens(probeTokens, probe.tokens);
715
+ facts.push(probe.fact);
716
+ }
717
+ const base = measureTimeline(fresh, fixture.constraints ?? []);
718
+ const metrics = {
719
+ status: result.status,
720
+ completed,
721
+ ...base,
722
+ ...facts.length > 0 ? { recall: mean(facts.map((f) => f.score)) } : {},
723
+ wallMs,
724
+ probeTokens
725
+ };
726
+ return { ...outcomeDraft, metrics, facts };
727
+ }
728
+ function loopConfig(env, fixture, arm, sessionId, extra) {
729
+ const tools = extra.tools ?? fixture.tools;
730
+ const systemPrompt = extra.systemPrompt ?? env.systemPrompt;
731
+ return {
732
+ sessionId,
733
+ log: env.stores.log,
734
+ ...env.stores.blobs ? { blobs: env.stores.blobs } : {},
735
+ ...env.stores.memory ? { memory: env.stores.memory } : {},
736
+ lowering: env.lowering,
737
+ model: env.model,
738
+ tools,
739
+ sockets: arm.sockets ?? [],
740
+ ...systemPrompt !== void 0 ? { systemPrompt } : {},
741
+ ...arm.projection ? { projection: arm.projection } : {},
742
+ registry: env.registry,
743
+ maxTurns: extra.maxTurns ?? fixture.maxTurns ?? 100,
744
+ now: env.now,
745
+ newId: env.newId,
746
+ ...extra.input !== void 0 ? { input: extra.input } : {},
747
+ ...extra.resume ? { resume: extra.resume } : {},
748
+ ...extra.decisions ? { decisions: extra.decisions } : {}
749
+ };
750
+ }
751
+ async function runProbe(opts, env, fixture, arm, fromSessionId, atSeq, fact, onEvent) {
752
+ const probeSessionId = env.newId(env.now());
753
+ await env.stores.log.fork(fromSessionId, atSeq, probeSessionId);
754
+ const probeEvents = [];
755
+ await drain(
756
+ runLoop(
757
+ loopConfig(env, fixture, arm, probeSessionId, {
758
+ input: fact.question,
759
+ tools: [],
760
+ systemPrompt: joinPrompts(env.systemPrompt, PROBE_NOTE),
761
+ maxTurns: opts.probeMaxTurns ?? 4
762
+ })
763
+ ),
764
+ (e) => {
765
+ probeEvents.push(e);
766
+ onEvent(e);
767
+ }
768
+ );
769
+ const { answer, answerFrom } = probeAnswerOf(probeEvents);
770
+ const graded = await grade(opts, fixture, fact, answer);
771
+ return {
772
+ fact: { id: fact.id, question: fact.question, answer, answerFrom, ...graded },
773
+ tokens: sumTokens(probeEvents)
774
+ };
775
+ }
776
+ function probeAnswerOf(events) {
777
+ const text = finalTextOf(events);
778
+ if (text !== "") return { answer: text, answerFrom: "text" };
779
+ const thinking = [...events].reverse().filter((e) => e.type === "core.model_thinking").find((e) => e.payload.text !== "");
780
+ return thinking ? { answer: thinking.payload.text, answerFrom: "thinking" } : { answer: "", answerFrom: "none" };
781
+ }
782
+ async function grade(opts, fixture, fact, answer) {
783
+ const expect = fact.expect;
784
+ if (expect === void 0) {
785
+ if (!opts.judge) throw new Error(`\u4E8B\u5B9E ${fact.id} \u6CA1\u6709 expect \u4E5F\u6CA1\u6709 judge`);
786
+ return { score: clamp01(await opts.judge({ fixtureId: fixture.id, fact, answer })), gradedBy: "judge" };
787
+ }
788
+ return { score: gradeExpect(expect, answer), gradedBy: "expect" };
789
+ }
790
+ function gradeExpect(expect, answer) {
791
+ if (typeof expect === "string") return answer.toLowerCase().includes(expect.toLowerCase()) ? 1 : 0;
792
+ if (expect instanceof RegExp) return expect.test(answer) ? 1 : 0;
793
+ return clamp01(expect(answer));
794
+ }
795
+ async function drain(gen, onEvent) {
796
+ while (true) {
797
+ const step = await gen.next();
798
+ if (step.done) return step.value;
799
+ onEvent(step.value);
800
+ }
801
+ }
802
+ function joinPrompts(...parts) {
803
+ const kept = parts.filter((p) => p !== void 0 && p !== "");
804
+ return kept.length === 0 ? void 0 : kept.join("\n\n");
805
+ }
806
+ function clamp01(v) {
807
+ if (typeof v === "boolean") return v ? 1 : 0;
808
+ if (!Number.isFinite(v)) return 0;
809
+ return Math.min(1, Math.max(0, v));
810
+ }
811
+ function summarize(outcomes) {
812
+ const byArm = /* @__PURE__ */ new Map();
813
+ for (const o of outcomes) byArm.set(o.arm, [...byArm.get(o.arm) ?? [], o]);
814
+ const summary = {};
815
+ for (const [arm, list] of byArm) {
816
+ const ms = list.map((o) => o.metrics);
817
+ const tokens = {
818
+ input: mean(ms.map((m) => m.tokens.input)),
819
+ output: mean(ms.map((m) => m.tokens.output)),
820
+ cacheRead: mean(ms.map((m) => m.tokens.cacheRead)),
821
+ cacheWrite: mean(ms.map((m) => m.tokens.cacheWrite)),
822
+ total: mean(ms.map((m) => m.tokens.total))
823
+ };
824
+ const recalls = ms.map((m) => m.recall).filter((r) => r !== void 0);
825
+ const cacheHitRate = cacheHitRateOf(tokens);
826
+ summary[arm] = {
827
+ arm,
828
+ runs: list.length,
829
+ finishedRate: mean(ms.map((m) => m.status === "done" ? 1 : 0)),
830
+ completion: mean(ms.map((m) => m.completed)),
831
+ tokens,
832
+ ...cacheHitRate !== void 0 ? { cacheHitRate } : {},
833
+ ...recalls.length > 0 ? { recall: mean(recalls) } : {},
834
+ violations: {
835
+ before: mean(ms.map((m) => m.violations.before.rate)),
836
+ after: mean(ms.map((m) => m.violations.after.rate))
837
+ },
838
+ compactions: {
839
+ model: mean(ms.map((m) => m.compactions.model)),
840
+ threshold: mean(ms.map((m) => m.compactions.threshold)),
841
+ maxConsecutive: mean(ms.map((m) => m.compactions.maxConsecutive))
842
+ },
843
+ turns: mean(ms.map((m) => m.turns)),
844
+ toolCalls: mean(ms.map((m) => m.toolCalls)),
845
+ repeatedToolCalls: mean(ms.map((m) => m.repeatedToolCalls)),
846
+ wallMs: mean(ms.map((m) => m.wallMs))
847
+ };
848
+ }
849
+ return summary;
850
+ }
851
+ export {
852
+ JsonlParseError,
853
+ ZERO_TOKENS,
854
+ addTokens,
855
+ aliasTable,
856
+ assembleChunks,
857
+ billableTokens,
858
+ cacheHitRateOf,
859
+ canonicalArgs,
860
+ checkGate,
861
+ countCompactions,
862
+ countRepeatedToolCalls,
863
+ finalTextOf,
864
+ gradeExpect,
865
+ isModelAction,
866
+ jsonValuesAt,
867
+ matchStrings,
868
+ mean,
869
+ measureTimeline,
870
+ measureViolations,
871
+ noneArm,
872
+ parseEventsJsonl,
873
+ parseFetchChunk,
874
+ probeAnswerOf,
875
+ recordedTools,
876
+ renderReport,
877
+ runEval,
878
+ scrubEvents,
879
+ splitModelTurns,
880
+ sumTokens,
881
+ summarize,
882
+ thresholdArm,
883
+ toEventsJsonl,
884
+ unspillRecording,
885
+ withCapabilities,
886
+ withContextWindow
887
+ };
888
+ //# sourceMappingURL=index.js.map