evalvcr 0.0.0-stage → 0.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.
- package/LICENSE +21 -0
- package/README.md +221 -2
- package/dist/cassette.d.ts +75 -0
- package/dist/cassette.d.ts.map +1 -0
- package/dist/cassette.js +390 -0
- package/dist/cassette.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +422 -0
- package/dist/cli.js.map +1 -0
- package/dist/evalite-compat.d.ts +23 -0
- package/dist/evalite-compat.d.ts.map +1 -0
- package/dist/evalite-compat.js +19 -0
- package/dist/evalite-compat.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/interceptors/ai-sdk.d.ts +14 -0
- package/dist/interceptors/ai-sdk.d.ts.map +1 -0
- package/dist/interceptors/ai-sdk.js +216 -0
- package/dist/interceptors/ai-sdk.js.map +1 -0
- package/dist/interceptors/anthropic.d.ts +15 -0
- package/dist/interceptors/anthropic.d.ts.map +1 -0
- package/dist/interceptors/anthropic.js +180 -0
- package/dist/interceptors/anthropic.js.map +1 -0
- package/dist/interceptors/fetch.d.ts +3 -0
- package/dist/interceptors/fetch.d.ts.map +1 -0
- package/dist/interceptors/fetch.js +121 -0
- package/dist/interceptors/fetch.js.map +1 -0
- package/dist/interceptors/index.d.ts +6 -0
- package/dist/interceptors/index.d.ts.map +1 -0
- package/dist/interceptors/index.js +8 -0
- package/dist/interceptors/index.js.map +1 -0
- package/dist/interceptors/mcp.d.ts +70 -0
- package/dist/interceptors/mcp.d.ts.map +1 -0
- package/dist/interceptors/mcp.js +294 -0
- package/dist/interceptors/mcp.js.map +1 -0
- package/dist/interceptors/openai.d.ts +17 -0
- package/dist/interceptors/openai.d.ts.map +1 -0
- package/dist/interceptors/openai.js +210 -0
- package/dist/interceptors/openai.js.map +1 -0
- package/dist/migrate-evalite.d.ts +25 -0
- package/dist/migrate-evalite.d.ts.map +1 -0
- package/dist/migrate-evalite.js +138 -0
- package/dist/migrate-evalite.js.map +1 -0
- package/dist/report.d.ts +2 -0
- package/dist/report.d.ts.map +1 -0
- package/dist/report.js +4 -0
- package/dist/report.js.map +1 -0
- package/dist/reporters/index.d.ts +9 -0
- package/dist/reporters/index.d.ts.map +1 -0
- package/dist/reporters/index.js +23 -0
- package/dist/reporters/index.js.map +1 -0
- package/dist/reporters/json.d.ts +3 -0
- package/dist/reporters/json.d.ts.map +1 -0
- package/dist/reporters/json.js +6 -0
- package/dist/reporters/json.js.map +1 -0
- package/dist/reporters/markdown.d.ts +3 -0
- package/dist/reporters/markdown.d.ts.map +1 -0
- package/dist/reporters/markdown.js +41 -0
- package/dist/reporters/markdown.js.map +1 -0
- package/dist/reporters/pretty.d.ts +6 -0
- package/dist/reporters/pretty.d.ts.map +1 -0
- package/dist/reporters/pretty.js +59 -0
- package/dist/reporters/pretty.js.map +1 -0
- package/dist/reporters/sarif.d.ts +43 -0
- package/dist/reporters/sarif.d.ts.map +1 -0
- package/dist/reporters/sarif.js +74 -0
- package/dist/reporters/sarif.js.map +1 -0
- package/dist/runner.d.ts +49 -0
- package/dist/runner.d.ts.map +1 -0
- package/dist/runner.js +689 -0
- package/dist/runner.js.map +1 -0
- package/dist/schemas.d.ts +15 -0
- package/dist/schemas.d.ts.map +1 -0
- package/dist/schemas.js +275 -0
- package/dist/schemas.js.map +1 -0
- package/dist/scorer-utils.d.ts +6 -0
- package/dist/scorer-utils.d.ts.map +1 -0
- package/dist/scorer-utils.js +59 -0
- package/dist/scorer-utils.js.map +1 -0
- package/dist/scrub.d.ts +25 -0
- package/dist/scrub.d.ts.map +1 -0
- package/dist/scrub.js +285 -0
- package/dist/scrub.js.map +1 -0
- package/dist/server.d.ts +16 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +493 -0
- package/dist/server.js.map +1 -0
- package/dist/storage/index.d.ts +5 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +19 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/json-file.d.ts +17 -0
- package/dist/storage/json-file.d.ts.map +1 -0
- package/dist/storage/json-file.js +89 -0
- package/dist/storage/json-file.js.map +1 -0
- package/dist/storage/sqlite.d.ts +16 -0
- package/dist/storage/sqlite.d.ts.map +1 -0
- package/dist/storage/sqlite.js +125 -0
- package/dist/storage/sqlite.js.map +1 -0
- package/dist/types.d.ts +336 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +4 -0
- package/dist/types.js.map +1 -0
- package/package.json +95 -3
package/dist/runner.js
ADDED
|
@@ -0,0 +1,689 @@
|
|
|
1
|
+
// packages/core/src/runner.ts
|
|
2
|
+
// language: TypeScript | runtime: Node >= 20 (ESM) | eval suite registry, runner, traces & watch mode
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { existsSync, readdirSync, statSync, watch } from "node:fs";
|
|
6
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import { CassetteDriftError, CassetteMissError, sanitizeCassetteName, VCREngine, } from "./cassette.js";
|
|
9
|
+
import { scrubText } from "./scrub.js";
|
|
10
|
+
import { createLocalStorage } from "./storage/index.js";
|
|
11
|
+
export class EvalVCRInputError extends Error {
|
|
12
|
+
exitCode = 2;
|
|
13
|
+
constructor(message) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.name = "EvalVCRInputError";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const REGISTRY_KEY = Symbol.for("evalvcr.registryState");
|
|
19
|
+
const g = globalThis;
|
|
20
|
+
if (!g[REGISTRY_KEY]) {
|
|
21
|
+
g[REGISTRY_KEY] = {
|
|
22
|
+
suites: [],
|
|
23
|
+
watchRunSeq: 0,
|
|
24
|
+
traceStorage: new AsyncLocalStorage(),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
const registryState = g[REGISTRY_KEY];
|
|
28
|
+
const traceStorage = registryState.traceStorage;
|
|
29
|
+
function round4(n) {
|
|
30
|
+
if (!Number.isFinite(n)) {
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
return Math.round(n * 10000) / 10000;
|
|
34
|
+
}
|
|
35
|
+
export function clearRegisteredSuites() {
|
|
36
|
+
registryState.suites.length = 0;
|
|
37
|
+
}
|
|
38
|
+
export function getRegisteredSuites() {
|
|
39
|
+
return [...registryState.suites];
|
|
40
|
+
}
|
|
41
|
+
export function reportTrace(span) {
|
|
42
|
+
const ctx = traceStorage.getStore();
|
|
43
|
+
if (!ctx) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
ctx.spans.push({
|
|
47
|
+
...span,
|
|
48
|
+
spanId: span.spanId ?? randomUUID(),
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function registerSuite(name, options) {
|
|
52
|
+
const suite = {
|
|
53
|
+
id: sanitizeCassetteName(`${name}-${registryState.suites.length + 1}`),
|
|
54
|
+
name,
|
|
55
|
+
...(registryState.currentLoadingFile !== undefined
|
|
56
|
+
? { file: registryState.currentLoadingFile }
|
|
57
|
+
: {}),
|
|
58
|
+
options: options,
|
|
59
|
+
};
|
|
60
|
+
registryState.suites.push(suite);
|
|
61
|
+
return suite;
|
|
62
|
+
}
|
|
63
|
+
function normalizeEachRows(rows) {
|
|
64
|
+
return rows.map((row, idx) => {
|
|
65
|
+
if (typeof row === "object" &&
|
|
66
|
+
row !== null &&
|
|
67
|
+
"input" in row) {
|
|
68
|
+
const rec = row;
|
|
69
|
+
return {
|
|
70
|
+
...rec,
|
|
71
|
+
...(rec.name !== undefined ? { name: rec.name } : { name: `case-${idx + 1}` }),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return {
|
|
75
|
+
name: `case-${idx + 1}`,
|
|
76
|
+
input: row,
|
|
77
|
+
};
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
const defineEvalImpl = ((name, options) => {
|
|
81
|
+
return registerSuite(name, options);
|
|
82
|
+
});
|
|
83
|
+
defineEvalImpl.only = (name, options) => {
|
|
84
|
+
return registerSuite(name, { ...options, only: true });
|
|
85
|
+
};
|
|
86
|
+
defineEvalImpl.skip = (name, options) => {
|
|
87
|
+
return registerSuite(name, { ...options, skip: true });
|
|
88
|
+
};
|
|
89
|
+
defineEvalImpl.each = (rows) => {
|
|
90
|
+
return (name, options) => {
|
|
91
|
+
const fallbackData = normalizeEachRows(rows);
|
|
92
|
+
return registerSuite(name, {
|
|
93
|
+
...options,
|
|
94
|
+
data: options.data ?? fallbackData,
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
};
|
|
98
|
+
export const defineEval = defineEvalImpl;
|
|
99
|
+
const EVAL_FILE_RE = /\.evals?\.(?:ts|mts|js|mjs)$/i;
|
|
100
|
+
const IGNORED_DIRS = new Set(["node_modules", "dist", ".git", ".evalvcr"]);
|
|
101
|
+
function discoverEvalFilesInDir(dirPath) {
|
|
102
|
+
const results = [];
|
|
103
|
+
const entries = readdirSync(dirPath, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
104
|
+
for (const entry of entries) {
|
|
105
|
+
if (IGNORED_DIRS.has(entry.name)) {
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const full = join(dirPath, entry.name);
|
|
109
|
+
if (entry.isDirectory()) {
|
|
110
|
+
results.push(...discoverEvalFilesInDir(full));
|
|
111
|
+
}
|
|
112
|
+
else if (entry.isFile() && EVAL_FILE_RE.test(entry.name)) {
|
|
113
|
+
results.push(full);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return results;
|
|
117
|
+
}
|
|
118
|
+
export function resolveEvalFiles(paths) {
|
|
119
|
+
const files = [];
|
|
120
|
+
for (const rawPath of paths) {
|
|
121
|
+
const abs = resolve(rawPath);
|
|
122
|
+
if (!existsSync(abs)) {
|
|
123
|
+
throw new EvalVCRInputError(`Path not found: ${rawPath}`);
|
|
124
|
+
}
|
|
125
|
+
const st = statSync(abs);
|
|
126
|
+
if (st.isDirectory()) {
|
|
127
|
+
files.push(...discoverEvalFilesInDir(abs));
|
|
128
|
+
}
|
|
129
|
+
else if (st.isFile()) {
|
|
130
|
+
files.push(abs);
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
throw new EvalVCRInputError(`Unsupported path type: ${rawPath}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return Array.from(new Set(files));
|
|
137
|
+
}
|
|
138
|
+
async function importEvalFile(absPath, seq) {
|
|
139
|
+
const ext = extname(absPath).toLowerCase();
|
|
140
|
+
if (![".ts", ".mts", ".js", ".mjs"].includes(ext)) {
|
|
141
|
+
throw new EvalVCRInputError(`Unsupported eval file extension "${ext}" for "${absPath}". Expected .ts, .mts, .js, or .mjs.`);
|
|
142
|
+
}
|
|
143
|
+
const url = `${pathToFileURL(absPath).href}?t=${seq}_${Date.now()}`;
|
|
144
|
+
registryState.currentLoadingFile = absPath;
|
|
145
|
+
try {
|
|
146
|
+
await import(url);
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
const code = typeof err === "object" && err !== null && "code" in err
|
|
150
|
+
? String(err.code)
|
|
151
|
+
: "";
|
|
152
|
+
if ((ext === ".ts" || ext === ".mts") &&
|
|
153
|
+
(code === "ERR_UNKNOWN_FILE_EXTENSION" ||
|
|
154
|
+
(err instanceof Error &&
|
|
155
|
+
err.message.includes("Unknown file extension")))) {
|
|
156
|
+
// Attempt tsx fallback on Node 20 if available
|
|
157
|
+
try {
|
|
158
|
+
const tsxName = "tsx/esm/api";
|
|
159
|
+
const tsxMod = (await import(tsxName));
|
|
160
|
+
if (typeof tsxMod.tsImport === "function") {
|
|
161
|
+
await tsxMod.tsImport(url, import.meta.url);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
// Fall through to clean diagnostic
|
|
167
|
+
}
|
|
168
|
+
throw new EvalVCRInputError(`Cannot load TypeScript eval file "${absPath}" on Node ${process.version}. Use Node >= 22.6 (native type stripping), install "tsx", or run compiled .js/.mjs files.`);
|
|
169
|
+
}
|
|
170
|
+
throw err;
|
|
171
|
+
}
|
|
172
|
+
finally {
|
|
173
|
+
registryState.currentLoadingFile = undefined;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function wrapVcrWithUsage(vcr, totals) {
|
|
177
|
+
return {
|
|
178
|
+
get name() {
|
|
179
|
+
return vcr.name;
|
|
180
|
+
},
|
|
181
|
+
get mode() {
|
|
182
|
+
return vcr.mode;
|
|
183
|
+
},
|
|
184
|
+
get cassettePath() {
|
|
185
|
+
return vcr.cassettePath;
|
|
186
|
+
},
|
|
187
|
+
async interact(input) {
|
|
188
|
+
const interaction = await vcr.interact(input);
|
|
189
|
+
const u = interaction.usage;
|
|
190
|
+
if (u) {
|
|
191
|
+
totals.hasUsage = true;
|
|
192
|
+
totals.inputTokens += u.inputTokens ?? 0;
|
|
193
|
+
totals.outputTokens += u.outputTokens ?? 0;
|
|
194
|
+
totals.totalTokens +=
|
|
195
|
+
u.totalTokens ?? (u.inputTokens ?? 0) + (u.outputTokens ?? 0);
|
|
196
|
+
totals.costUsd += u.costUsd ?? 0;
|
|
197
|
+
}
|
|
198
|
+
return interaction;
|
|
199
|
+
},
|
|
200
|
+
verifyComplete() {
|
|
201
|
+
vcr.verifyComplete();
|
|
202
|
+
},
|
|
203
|
+
save() {
|
|
204
|
+
return vcr.save();
|
|
205
|
+
},
|
|
206
|
+
close() {
|
|
207
|
+
return vcr.close();
|
|
208
|
+
},
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
function isFindingBreach(findings, failOn) {
|
|
212
|
+
if (failOn === "off") {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
if (failOn === "error") {
|
|
216
|
+
return findings.some((f) => f.severity === "error");
|
|
217
|
+
}
|
|
218
|
+
return findings.some((f) => f.severity === "error" || f.severity === "warning");
|
|
219
|
+
}
|
|
220
|
+
export async function runEvals(options = {}) {
|
|
221
|
+
const mode = options.mode ?? "replay";
|
|
222
|
+
const defaultThreshold = options.threshold ?? 0.7;
|
|
223
|
+
const failOn = options.failOn ?? "error";
|
|
224
|
+
const cassetteDir = options.cassetteDir ?? ".evalvcr/cassettes";
|
|
225
|
+
let suitesToRun;
|
|
226
|
+
if (options.suites) {
|
|
227
|
+
suitesToRun = [...options.suites];
|
|
228
|
+
}
|
|
229
|
+
else if (options.paths && options.paths.length > 0) {
|
|
230
|
+
const resolvedFiles = resolveEvalFiles(options.paths);
|
|
231
|
+
if (resolvedFiles.length === 0) {
|
|
232
|
+
throw new EvalVCRInputError(`No *.eval.{ts,mts,js,mjs} files found in: ${options.paths.join(", ")}`);
|
|
233
|
+
}
|
|
234
|
+
clearRegisteredSuites();
|
|
235
|
+
registryState.watchRunSeq += 1;
|
|
236
|
+
for (const file of resolvedFiles) {
|
|
237
|
+
await importEvalFile(file, registryState.watchRunSeq);
|
|
238
|
+
}
|
|
239
|
+
suitesToRun = getRegisteredSuites();
|
|
240
|
+
}
|
|
241
|
+
else {
|
|
242
|
+
const alreadyRegistered = getRegisteredSuites();
|
|
243
|
+
if (alreadyRegistered.length > 0) {
|
|
244
|
+
suitesToRun = alreadyRegistered;
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
const discovered = resolveEvalFiles(["."]);
|
|
248
|
+
if (discovered.length === 0) {
|
|
249
|
+
throw new EvalVCRInputError("No *.eval.{ts,mts,js,mjs} files found in current directory.");
|
|
250
|
+
}
|
|
251
|
+
clearRegisteredSuites();
|
|
252
|
+
registryState.watchRunSeq += 1;
|
|
253
|
+
for (const file of discovered) {
|
|
254
|
+
await importEvalFile(file, registryState.watchRunSeq);
|
|
255
|
+
}
|
|
256
|
+
suitesToRun = getRegisteredSuites();
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const runStart = performance.now();
|
|
260
|
+
const nonSkippedSuites = suitesToRun.filter((s) => !s.options.skip);
|
|
261
|
+
const hasOnlySuite = nonSkippedSuites.some((s) => s.options.only === true);
|
|
262
|
+
const selectedSuites = hasOnlySuite
|
|
263
|
+
? nonSkippedSuites.filter((s) => s.options.only === true)
|
|
264
|
+
: nonSkippedSuites;
|
|
265
|
+
const reportSuites = [];
|
|
266
|
+
const allFindings = [];
|
|
267
|
+
let hasUnhandledException = false;
|
|
268
|
+
let hasCassetteFailure = false;
|
|
269
|
+
let totalTokens = 0;
|
|
270
|
+
let totalCostUsd = 0;
|
|
271
|
+
let trialsTotal = 0;
|
|
272
|
+
for (const suite of selectedSuites) {
|
|
273
|
+
const suiteStart = performance.now();
|
|
274
|
+
const suiteThreshold = options.threshold ?? suite.options.scoreThreshold ?? defaultThreshold;
|
|
275
|
+
const suiteMode = suite.options.mode ?? mode;
|
|
276
|
+
const suiteCassetteDir = suite.options.cassetteDir ?? cassetteDir;
|
|
277
|
+
const trialCount = Math.max(1, Math.floor(suite.options.trialCount ?? 1));
|
|
278
|
+
const suiteFile = suite.file ?? "inline";
|
|
279
|
+
const rawCases = typeof suite.options.data === "function"
|
|
280
|
+
? await suite.options.data()
|
|
281
|
+
: suite.options.data;
|
|
282
|
+
const nonSkippedCases = rawCases.filter((c) => !c.skip);
|
|
283
|
+
const hasOnlyCase = nonSkippedCases.some((c) => c.only === true);
|
|
284
|
+
const selectedCases = hasOnlyCase
|
|
285
|
+
? nonSkippedCases.filter((c) => c.only === true)
|
|
286
|
+
: nonSkippedCases;
|
|
287
|
+
const reportCases = [];
|
|
288
|
+
for (let caseIdx = 0; caseIdx < selectedCases.length; caseIdx += 1) {
|
|
289
|
+
const tc = selectedCases[caseIdx];
|
|
290
|
+
const caseName = tc.name ?? `case-${caseIdx + 1}`;
|
|
291
|
+
const caseId = sanitizeCassetteName(`${suite.id}-${caseName}-${caseIdx + 1}`);
|
|
292
|
+
const caseStart = performance.now();
|
|
293
|
+
const trials = [];
|
|
294
|
+
let caseCassettePath;
|
|
295
|
+
for (let trialIndex = 0; trialIndex < trialCount; trialIndex += 1) {
|
|
296
|
+
trialsTotal += 1;
|
|
297
|
+
const trialStart = performance.now();
|
|
298
|
+
const cassetteName = tc.cassette ?? suite.options.cassette ?? `${suite.name}--${caseName}`;
|
|
299
|
+
const vcr = new VCREngine({
|
|
300
|
+
name: cassetteName,
|
|
301
|
+
cassetteDir: suiteCassetteDir,
|
|
302
|
+
mode: suiteMode,
|
|
303
|
+
});
|
|
304
|
+
caseCassettePath = vcr.cassettePath;
|
|
305
|
+
const usageTracker = {
|
|
306
|
+
inputTokens: 0,
|
|
307
|
+
outputTokens: 0,
|
|
308
|
+
totalTokens: 0,
|
|
309
|
+
costUsd: 0,
|
|
310
|
+
hasUsage: false,
|
|
311
|
+
};
|
|
312
|
+
const wrappedVcr = wrapVcrWithUsage(vcr, usageTracker);
|
|
313
|
+
const spans = [];
|
|
314
|
+
const activeTrace = {
|
|
315
|
+
spans,
|
|
316
|
+
startMs: performance.now(),
|
|
317
|
+
};
|
|
318
|
+
let output = undefined;
|
|
319
|
+
let trialError;
|
|
320
|
+
let isCassetteErr = false;
|
|
321
|
+
const scorerResults = [];
|
|
322
|
+
try {
|
|
323
|
+
output = await traceStorage.run(activeTrace, async () => {
|
|
324
|
+
const evalCtx = {
|
|
325
|
+
vcr: wrappedVcr,
|
|
326
|
+
reportTrace: (span) => {
|
|
327
|
+
spans.push({
|
|
328
|
+
...span,
|
|
329
|
+
spanId: span.spanId ?? randomUUID(),
|
|
330
|
+
});
|
|
331
|
+
},
|
|
332
|
+
trialIndex,
|
|
333
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
334
|
+
};
|
|
335
|
+
const result = await suite.options.task(tc.input, evalCtx);
|
|
336
|
+
await vcr.saveIfDirty();
|
|
337
|
+
vcr.verifyComplete();
|
|
338
|
+
return result;
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
catch (err) {
|
|
342
|
+
await vcr.saveIfDirty().catch(() => undefined);
|
|
343
|
+
if (err instanceof CassetteMissError ||
|
|
344
|
+
err instanceof CassetteDriftError) {
|
|
345
|
+
isCassetteErr = true;
|
|
346
|
+
hasCassetteFailure = true;
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
hasUnhandledException = true;
|
|
350
|
+
}
|
|
351
|
+
trialError = err instanceof Error ? err.message : String(err);
|
|
352
|
+
}
|
|
353
|
+
const trialDurationMs = round4(Math.max(0, performance.now() - trialStart));
|
|
354
|
+
if (usageTracker.hasUsage) {
|
|
355
|
+
totalTokens += usageTracker.totalTokens;
|
|
356
|
+
totalCostUsd += usageTracker.costUsd;
|
|
357
|
+
}
|
|
358
|
+
let trialScore = 0;
|
|
359
|
+
if (trialError === undefined) {
|
|
360
|
+
const scorers = suite.options.scorers ?? [];
|
|
361
|
+
if (scorers.length === 0) {
|
|
362
|
+
trialScore = 1.0;
|
|
363
|
+
}
|
|
364
|
+
else {
|
|
365
|
+
try {
|
|
366
|
+
for (const scorer of scorers) {
|
|
367
|
+
const res = await scorer.score({
|
|
368
|
+
input: tc.input,
|
|
369
|
+
output,
|
|
370
|
+
...(tc.expected !== undefined ? { expected: tc.expected } : {}),
|
|
371
|
+
traces: spans,
|
|
372
|
+
...(usageTracker.hasUsage
|
|
373
|
+
? {
|
|
374
|
+
usage: {
|
|
375
|
+
inputTokens: usageTracker.inputTokens,
|
|
376
|
+
outputTokens: usageTracker.outputTokens,
|
|
377
|
+
totalTokens: usageTracker.totalTokens,
|
|
378
|
+
costUsd: usageTracker.costUsd,
|
|
379
|
+
},
|
|
380
|
+
}
|
|
381
|
+
: {}),
|
|
382
|
+
durationMs: trialDurationMs,
|
|
383
|
+
...(tc.metadata ? { metadata: tc.metadata } : {}),
|
|
384
|
+
file: suiteFile,
|
|
385
|
+
suite: suite.name,
|
|
386
|
+
caseName,
|
|
387
|
+
});
|
|
388
|
+
const enrichedFindings = res.findings?.map((f) => ({
|
|
389
|
+
...f,
|
|
390
|
+
file: f.file ?? suiteFile,
|
|
391
|
+
suite: f.suite ?? suite.name,
|
|
392
|
+
caseName: f.caseName ?? caseName,
|
|
393
|
+
...(f.evidence !== undefined
|
|
394
|
+
? { evidence: scrubText(f.evidence) }
|
|
395
|
+
: {}),
|
|
396
|
+
}));
|
|
397
|
+
const normalizedRes = {
|
|
398
|
+
...res,
|
|
399
|
+
...(enrichedFindings !== undefined
|
|
400
|
+
? { findings: enrichedFindings }
|
|
401
|
+
: {}),
|
|
402
|
+
};
|
|
403
|
+
scorerResults.push(normalizedRes);
|
|
404
|
+
if (enrichedFindings) {
|
|
405
|
+
allFindings.push(...enrichedFindings);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
const sum = scorerResults.reduce((acc, s) => acc + s.score, 0);
|
|
409
|
+
trialScore = round4(sum / scorerResults.length);
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
hasUnhandledException = true;
|
|
413
|
+
trialError = err instanceof Error ? err.message : String(err);
|
|
414
|
+
trialScore = 0;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
else if (isCassetteErr) {
|
|
419
|
+
trialScore = 0;
|
|
420
|
+
}
|
|
421
|
+
const trialPassed = trialError === undefined && trialScore >= suiteThreshold;
|
|
422
|
+
trials.push({
|
|
423
|
+
trialIndex,
|
|
424
|
+
score: trialScore,
|
|
425
|
+
passed: trialPassed,
|
|
426
|
+
durationMs: trialDurationMs,
|
|
427
|
+
output,
|
|
428
|
+
...(trialError !== undefined ? { error: trialError } : {}),
|
|
429
|
+
scores: scorerResults,
|
|
430
|
+
traces: spans,
|
|
431
|
+
...(usageTracker.hasUsage
|
|
432
|
+
? {
|
|
433
|
+
usage: {
|
|
434
|
+
inputTokens: usageTracker.inputTokens,
|
|
435
|
+
outputTokens: usageTracker.outputTokens,
|
|
436
|
+
totalTokens: usageTracker.totalTokens,
|
|
437
|
+
costUsd: round4(usageTracker.costUsd),
|
|
438
|
+
},
|
|
439
|
+
}
|
|
440
|
+
: {}),
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
const caseDurationMs = round4(Math.max(0, performance.now() - caseStart));
|
|
444
|
+
const caseAverageScore = trials.length > 0
|
|
445
|
+
? round4(trials.reduce((acc, t) => acc + t.score, 0) / trials.length)
|
|
446
|
+
: 1.0;
|
|
447
|
+
const casePassed = trials.every((t) => t.passed) && caseAverageScore >= suiteThreshold;
|
|
448
|
+
const lastTrial = trials[trials.length - 1];
|
|
449
|
+
let columns;
|
|
450
|
+
if (suite.options.columns && lastTrial) {
|
|
451
|
+
try {
|
|
452
|
+
columns = suite.options.columns({
|
|
453
|
+
input: tc.input,
|
|
454
|
+
output: lastTrial.output,
|
|
455
|
+
...(tc.expected !== undefined ? { expected: tc.expected } : {}),
|
|
456
|
+
scores: lastTrial.scores,
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
catch {
|
|
460
|
+
columns = undefined;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
reportCases.push({
|
|
464
|
+
id: caseId,
|
|
465
|
+
name: caseName,
|
|
466
|
+
input: tc.input,
|
|
467
|
+
...(tc.expected !== undefined ? { expected: tc.expected } : {}),
|
|
468
|
+
...(lastTrial !== undefined ? { output: lastTrial.output } : {}),
|
|
469
|
+
averageScore: caseAverageScore,
|
|
470
|
+
passed: casePassed,
|
|
471
|
+
durationMs: caseDurationMs,
|
|
472
|
+
...(caseCassettePath !== undefined
|
|
473
|
+
? { cassettePath: caseCassettePath }
|
|
474
|
+
: {}),
|
|
475
|
+
...(columns !== undefined ? { columns } : {}),
|
|
476
|
+
trials,
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
const suiteDurationMs = round4(Math.max(0, performance.now() - suiteStart));
|
|
480
|
+
const suiteAverageScore = reportCases.length > 0
|
|
481
|
+
? round4(reportCases.reduce((acc, c) => acc + c.averageScore, 0) /
|
|
482
|
+
reportCases.length)
|
|
483
|
+
: 1.0;
|
|
484
|
+
const suitePassed = reportCases.every((c) => c.passed) && suiteAverageScore >= suiteThreshold;
|
|
485
|
+
reportSuites.push({
|
|
486
|
+
id: suite.id,
|
|
487
|
+
name: suite.name,
|
|
488
|
+
file: suiteFile,
|
|
489
|
+
threshold: suiteThreshold,
|
|
490
|
+
averageScore: suiteAverageScore,
|
|
491
|
+
passed: suitePassed,
|
|
492
|
+
durationMs: suiteDurationMs,
|
|
493
|
+
cases: reportCases,
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
const durationMs = round4(Math.max(0, performance.now() - runStart));
|
|
497
|
+
const suitesTotal = reportSuites.length;
|
|
498
|
+
const suitesPassed = reportSuites.filter((s) => s.passed).length;
|
|
499
|
+
const casesTotal = reportSuites.reduce((acc, s) => acc + s.cases.length, 0);
|
|
500
|
+
const casesPassed = reportSuites.reduce((acc, s) => acc + s.cases.filter((c) => c.passed).length, 0);
|
|
501
|
+
const casesFailed = casesTotal - casesPassed;
|
|
502
|
+
const averageScore = casesTotal > 0
|
|
503
|
+
? round4(reportSuites.reduce((acc, s) => acc + s.cases.reduce((a, c) => a + c.averageScore, 0), 0) / casesTotal)
|
|
504
|
+
: 1.0;
|
|
505
|
+
const passRate = casesTotal > 0 ? round4(casesPassed / casesTotal) : 1.0;
|
|
506
|
+
const findingsBySeverity = {
|
|
507
|
+
error: allFindings.filter((f) => f.severity === "error").length,
|
|
508
|
+
warning: allFindings.filter((f) => f.severity === "warning").length,
|
|
509
|
+
info: allFindings.filter((f) => f.severity === "info").length,
|
|
510
|
+
};
|
|
511
|
+
const findingBreached = isFindingBreach(allFindings, failOn);
|
|
512
|
+
let status;
|
|
513
|
+
let exitCode;
|
|
514
|
+
if (hasUnhandledException) {
|
|
515
|
+
status = "error";
|
|
516
|
+
exitCode = 1;
|
|
517
|
+
}
|
|
518
|
+
else if (hasCassetteFailure ||
|
|
519
|
+
casesFailed > 0 ||
|
|
520
|
+
suitesPassed < suitesTotal ||
|
|
521
|
+
findingBreached) {
|
|
522
|
+
status = "failed";
|
|
523
|
+
exitCode = 1;
|
|
524
|
+
}
|
|
525
|
+
else {
|
|
526
|
+
status = "passed";
|
|
527
|
+
exitCode = 0;
|
|
528
|
+
}
|
|
529
|
+
const report = {
|
|
530
|
+
schemaVersion: "evalvcr.report.v1",
|
|
531
|
+
runId: randomUUID(),
|
|
532
|
+
createdAt: new Date().toISOString(),
|
|
533
|
+
durationMs,
|
|
534
|
+
mode,
|
|
535
|
+
runtime: {
|
|
536
|
+
language: "typescript",
|
|
537
|
+
version: process.version,
|
|
538
|
+
},
|
|
539
|
+
threshold: defaultThreshold,
|
|
540
|
+
status,
|
|
541
|
+
exitCode,
|
|
542
|
+
summary: {
|
|
543
|
+
suitesTotal,
|
|
544
|
+
suitesPassed,
|
|
545
|
+
casesTotal,
|
|
546
|
+
casesPassed,
|
|
547
|
+
casesFailed,
|
|
548
|
+
trialsTotal,
|
|
549
|
+
averageScore,
|
|
550
|
+
passRate,
|
|
551
|
+
totalDurationMs: durationMs,
|
|
552
|
+
totalTokens,
|
|
553
|
+
totalCostUsd: round4(totalCostUsd),
|
|
554
|
+
findingsCount: allFindings.length,
|
|
555
|
+
findingsBySeverity,
|
|
556
|
+
},
|
|
557
|
+
suites: reportSuites,
|
|
558
|
+
findings: allFindings,
|
|
559
|
+
};
|
|
560
|
+
if (options.persist) {
|
|
561
|
+
const storage = await createLocalStorage(options.storageDir ?? ".evalvcr");
|
|
562
|
+
try {
|
|
563
|
+
await storage.saveRun(report);
|
|
564
|
+
}
|
|
565
|
+
finally {
|
|
566
|
+
await storage.close();
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return report;
|
|
570
|
+
}
|
|
571
|
+
export function startEvalWatch(options) {
|
|
572
|
+
const targetPaths = options.paths && options.paths.length > 0 ? options.paths : ["."];
|
|
573
|
+
const watchTargets = Array.from(new Set(targetPaths.map((p) => {
|
|
574
|
+
const abs = resolve(p);
|
|
575
|
+
if (!existsSync(abs)) {
|
|
576
|
+
throw new EvalVCRInputError(`Path not found: ${p}`);
|
|
577
|
+
}
|
|
578
|
+
return statSync(abs).isDirectory() ? abs : dirname(abs);
|
|
579
|
+
})));
|
|
580
|
+
const debounceMs = options.debounceMs ?? 150;
|
|
581
|
+
const watchers = [];
|
|
582
|
+
let timer = null;
|
|
583
|
+
let running = false;
|
|
584
|
+
let pending = false;
|
|
585
|
+
let closed = false;
|
|
586
|
+
let resolveDone;
|
|
587
|
+
const done = new Promise((r) => {
|
|
588
|
+
resolveDone = r;
|
|
589
|
+
});
|
|
590
|
+
const triggerRun = async () => {
|
|
591
|
+
if (closed) {
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
if (running) {
|
|
595
|
+
pending = true;
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
running = true;
|
|
599
|
+
try {
|
|
600
|
+
const report = await runEvals(options);
|
|
601
|
+
await options.onReport(report);
|
|
602
|
+
}
|
|
603
|
+
catch (err) {
|
|
604
|
+
options.onError?.(err);
|
|
605
|
+
}
|
|
606
|
+
finally {
|
|
607
|
+
running = false;
|
|
608
|
+
if (pending && !closed) {
|
|
609
|
+
pending = false;
|
|
610
|
+
void triggerRun();
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
const scheduleRun = () => {
|
|
615
|
+
if (closed) {
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (timer) {
|
|
619
|
+
clearTimeout(timer);
|
|
620
|
+
}
|
|
621
|
+
timer = setTimeout(() => {
|
|
622
|
+
timer = null;
|
|
623
|
+
void triggerRun();
|
|
624
|
+
}, debounceMs);
|
|
625
|
+
};
|
|
626
|
+
const close = () => {
|
|
627
|
+
if (closed) {
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
closed = true;
|
|
631
|
+
if (timer) {
|
|
632
|
+
clearTimeout(timer);
|
|
633
|
+
timer = null;
|
|
634
|
+
}
|
|
635
|
+
for (const w of watchers) {
|
|
636
|
+
try {
|
|
637
|
+
w.close();
|
|
638
|
+
}
|
|
639
|
+
catch {
|
|
640
|
+
// Ignore close errors
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
process.off("SIGINT", onSig);
|
|
644
|
+
process.off("SIGTERM", onSig);
|
|
645
|
+
options.signal?.removeEventListener("abort", close);
|
|
646
|
+
resolveDone();
|
|
647
|
+
};
|
|
648
|
+
const onSig = () => {
|
|
649
|
+
close();
|
|
650
|
+
};
|
|
651
|
+
for (const dir of watchTargets) {
|
|
652
|
+
try {
|
|
653
|
+
const w = watch(dir, { recursive: true }, (_event, filename) => {
|
|
654
|
+
if (!filename) {
|
|
655
|
+
scheduleRun();
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
const normalized = String(filename).replace(/\\/g, "/");
|
|
659
|
+
if (normalized.includes(".evalvcr/") ||
|
|
660
|
+
normalized.includes("node_modules/") ||
|
|
661
|
+
normalized.includes("dist/") ||
|
|
662
|
+
normalized.includes(".git/")) {
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
scheduleRun();
|
|
666
|
+
});
|
|
667
|
+
watchers.push(w);
|
|
668
|
+
}
|
|
669
|
+
catch {
|
|
670
|
+
// Fallback non-recursive watch if platform rejects recursive option
|
|
671
|
+
const w = watch(dir, () => scheduleRun());
|
|
672
|
+
watchers.push(w);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
process.on("SIGINT", onSig);
|
|
676
|
+
process.on("SIGTERM", onSig);
|
|
677
|
+
if (options.signal) {
|
|
678
|
+
if (options.signal.aborted) {
|
|
679
|
+
close();
|
|
680
|
+
}
|
|
681
|
+
else {
|
|
682
|
+
options.signal.addEventListener("abort", close, { once: true });
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
// Initial run
|
|
686
|
+
void triggerRun();
|
|
687
|
+
return { close, done };
|
|
688
|
+
}
|
|
689
|
+
//# sourceMappingURL=runner.js.map
|