@botpress/evals 1.19.0-beta.7 → 2.0.0-alpha.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.
Files changed (90) hide show
  1. package/dist/client.d.ts +25 -11
  2. package/dist/client.d.ts.map +1 -1
  3. package/dist/client.js +143 -55
  4. package/dist/client.js.map +4 -4
  5. package/dist/definition.d.ts +9 -2
  6. package/dist/definition.d.ts.map +1 -1
  7. package/dist/definition.js.map +2 -2
  8. package/dist/errors.d.ts +15 -0
  9. package/dist/errors.d.ts.map +1 -0
  10. package/dist/graders/index.js +31 -74
  11. package/dist/graders/index.js.map +3 -3
  12. package/dist/graders/llm.d.ts +14 -12
  13. package/dist/graders/llm.d.ts.map +1 -1
  14. package/dist/graders/llm.js +46 -74
  15. package/dist/graders/llm.js.map +3 -3
  16. package/dist/graders/response.js +24 -64
  17. package/dist/graders/response.js.map +3 -3
  18. package/dist/index.d.ts +3 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +10 -0
  21. package/dist/index.js.map +3 -3
  22. package/dist/loader.d.ts.map +1 -1
  23. package/dist/loader.js +22 -8
  24. package/dist/loader.js.map +3 -3
  25. package/dist/manifest.d.ts +13 -0
  26. package/dist/manifest.d.ts.map +1 -0
  27. package/dist/runner.d.ts +7 -1
  28. package/dist/runner.d.ts.map +1 -1
  29. package/dist/runner.js +445 -246
  30. package/dist/runner.js.map +4 -4
  31. package/dist/spans/index.d.ts +5 -0
  32. package/dist/spans/index.d.ts.map +1 -0
  33. package/dist/spans/index.js +687 -0
  34. package/dist/spans/index.js.map +7 -0
  35. package/dist/spans/local-span-source.d.ts +19 -0
  36. package/dist/spans/local-span-source.d.ts.map +1 -0
  37. package/dist/spans/local-span-source.js +505 -0
  38. package/dist/spans/local-span-source.js.map +7 -0
  39. package/dist/spans/span-source.d.ts +40 -0
  40. package/dist/spans/span-source.d.ts.map +1 -0
  41. package/dist/spans/span-source.js +1 -0
  42. package/dist/{sse-collector.d.ts → spans/sse-collector.d.ts} +44 -5
  43. package/dist/spans/sse-collector.d.ts.map +1 -0
  44. package/dist/{sse-collector.js → spans/sse-collector.js} +109 -22
  45. package/dist/spans/sse-collector.js.map +7 -0
  46. package/dist/spans/trace.d.ts.map +1 -0
  47. package/dist/spans/trace.js.map +7 -0
  48. package/dist/spans/vortex-span-source.d.ts +42 -0
  49. package/dist/spans/vortex-span-source.d.ts.map +1 -0
  50. package/dist/spans/vortex-span-source.js +184 -0
  51. package/dist/spans/vortex-span-source.js.map +7 -0
  52. package/dist/stores/eval-definition-loader.d.ts +4 -0
  53. package/dist/stores/eval-definition-loader.d.ts.map +1 -0
  54. package/dist/stores/eval-definition-loader.js +104 -0
  55. package/dist/stores/eval-definition-loader.js.map +7 -0
  56. package/dist/stores/eval-store.d.ts +61 -0
  57. package/dist/stores/eval-store.d.ts.map +1 -0
  58. package/dist/stores/eval-store.js +1 -0
  59. package/dist/stores/eval-store.js.map +7 -0
  60. package/dist/stores/index.d.ts +8 -0
  61. package/dist/stores/index.d.ts.map +1 -0
  62. package/dist/stores/index.js +1118 -0
  63. package/dist/stores/index.js.map +7 -0
  64. package/dist/stores/local-eval-store.d.ts +66 -0
  65. package/dist/stores/local-eval-store.d.ts.map +1 -0
  66. package/dist/stores/local-eval-store.js +557 -0
  67. package/dist/stores/local-eval-store.js.map +7 -0
  68. package/dist/stores/vortex-eval-store-entry.d.ts +6 -0
  69. package/dist/stores/vortex-eval-store-entry.d.ts.map +1 -0
  70. package/dist/stores/vortex-eval-store-entry.js +664 -0
  71. package/dist/stores/vortex-eval-store-entry.js.map +7 -0
  72. package/dist/stores/vortex-eval-store.d.ts +78 -0
  73. package/dist/stores/vortex-eval-store.d.ts.map +1 -0
  74. package/dist/stores/vortex-eval-store.js +562 -0
  75. package/dist/stores/vortex-eval-store.js.map +7 -0
  76. package/dist/transformer.d.ts +2 -2
  77. package/dist/transformer.d.ts.map +1 -1
  78. package/dist/transformer.js +1 -1
  79. package/dist/transformer.js.map +2 -2
  80. package/dist/types.d.ts +55 -33
  81. package/dist/types.d.ts.map +1 -1
  82. package/dist/types.js +5 -1
  83. package/dist/types.js.map +3 -3
  84. package/package.json +66 -6
  85. package/dist/sse-collector.d.ts.map +0 -1
  86. package/dist/sse-collector.js.map +0 -7
  87. package/dist/trace.d.ts.map +0 -1
  88. /package/dist/{trace.js.map → spans/span-source.js.map} +0 -0
  89. /package/dist/{trace.d.ts → spans/trace.d.ts} +0 -0
  90. /package/dist/{trace.js → spans/trace.js} +0 -0
@@ -0,0 +1,1118 @@
1
+ // src/stores/local-eval-store.ts
2
+ import { Database } from "bun:sqlite";
3
+ import { existsSync as existsSync2, mkdirSync, readdirSync as readdirSync2, readFileSync, renameSync } from "fs";
4
+ import { join } from "path";
5
+
6
+ // src/loader.ts
7
+ import { readdirSync, existsSync } from "fs";
8
+ import { resolve } from "path";
9
+
10
+ // src/definition.ts
11
+ var Eval = class {
12
+ name;
13
+ description;
14
+ tags;
15
+ type;
16
+ setup;
17
+ conversation;
18
+ outcome;
19
+ options;
20
+ constructor(def) {
21
+ this.name = def.name;
22
+ this.conversation = def.conversation;
23
+ if (def.description !== void 0) this.description = def.description;
24
+ if (def.tags !== void 0) this.tags = def.tags;
25
+ if (def.type !== void 0) this.type = def.type;
26
+ if (def.setup !== void 0) this.setup = def.setup;
27
+ if (def.outcome !== void 0) this.outcome = def.outcome;
28
+ if (def.options !== void 0) this.options = def.options;
29
+ }
30
+ };
31
+
32
+ // src/errors.ts
33
+ import { AdkError } from "@botpress/analytics";
34
+ var EvalRunnerError = class extends AdkError {
35
+ };
36
+
37
+ // src/loader.ts
38
+ function isEvalDefinition(value) {
39
+ return value !== null && typeof value === "object" && typeof value.name === "string" && value.name !== "" && Array.isArray(value.conversation);
40
+ }
41
+ async function loadEvalFile(filePath) {
42
+ const absPath = resolve(filePath);
43
+ let mod;
44
+ try {
45
+ mod = await import(absPath);
46
+ } catch (err) {
47
+ const msg = err instanceof Error ? err.message : String(err);
48
+ throw new EvalRunnerError({
49
+ code: "EVAL_LOAD_FAILED",
50
+ message: `Failed to load eval file ${filePath}: ${msg}
51
+
52
+ Make sure your eval file:
53
+ - Has no syntax or type errors
54
+ - Exports one or more \`new Eval({...})\` instances
55
+ - Has all dependencies installed (\`bun install\`)`,
56
+ expected: true,
57
+ cause: err
58
+ });
59
+ }
60
+ const results = [];
61
+ for (const [key, value] of Object.entries(mod)) {
62
+ if (key === "__esModule") continue;
63
+ if (value instanceof Eval || isEvalDefinition(value)) {
64
+ results.push(value);
65
+ }
66
+ }
67
+ if (results.length === 0) {
68
+ throw new EvalRunnerError({
69
+ code: "EVAL_FILE_EMPTY",
70
+ message: `Invalid eval file ${filePath}: no valid evals found. Export one or more \`new Eval({...})\` instances (as default or named exports).`,
71
+ expected: true
72
+ });
73
+ }
74
+ return results;
75
+ }
76
+ async function loadEvalsFromDir(dirPath) {
77
+ const absDir = resolve(dirPath);
78
+ if (!existsSync(absDir)) {
79
+ return [];
80
+ }
81
+ const files = readdirSync(absDir).filter((f) => f.endsWith(".eval.ts"));
82
+ const evals = [];
83
+ for (const f of files) {
84
+ const defs = await loadEvalFile(`${absDir}/${f}`);
85
+ evals.push(...defs);
86
+ }
87
+ const seen = /* @__PURE__ */ new Set();
88
+ for (const e of evals) {
89
+ if (seen.has(e.name)) {
90
+ throw new EvalRunnerError({
91
+ code: "EVAL_DUPLICATE_NAME",
92
+ message: `Duplicate eval name "${e.name}" found in ${dirPath} \u2014 names must be unique across the evals directory.`,
93
+ expected: true,
94
+ details: { name: e.name }
95
+ });
96
+ }
97
+ seen.add(e.name);
98
+ }
99
+ return evals;
100
+ }
101
+ function filterEvals(evals, filter) {
102
+ if (!filter) return evals;
103
+ return evals.filter((e) => {
104
+ if (filter.names && filter.names.length > 0) {
105
+ if (!filter.names.includes(e.name)) return false;
106
+ }
107
+ if (filter.tags && filter.tags.length > 0) {
108
+ if (!e.tags || !filter.tags.some((t) => e.tags.includes(t))) return false;
109
+ }
110
+ if (filter.type) {
111
+ if (e.type !== filter.type) return false;
112
+ }
113
+ return true;
114
+ });
115
+ }
116
+
117
+ // src/stores/eval-definition-loader.ts
118
+ function createDiskEvalLoader(evalsDir) {
119
+ return () => loadEvalsFromDir(evalsDir);
120
+ }
121
+
122
+ // src/stores/local-eval-store.ts
123
+ var errText = (err) => err instanceof Error ? err.message : String(err);
124
+ var SCHEMA_VERSION = "2";
125
+ var SCHEMA = `
126
+ CREATE TABLE IF NOT EXISTS eval_runs (
127
+ id TEXT PRIMARY KEY,
128
+ timestamp TEXT NOT NULL,
129
+ started_at INTEGER NOT NULL,
130
+ passed INTEGER NOT NULL,
131
+ failed INTEGER NOT NULL,
132
+ total INTEGER NOT NULL,
133
+ duration REAL NOT NULL,
134
+ bot_duration REAL NOT NULL DEFAULT 0,
135
+ eval_duration REAL NOT NULL DEFAULT 0,
136
+ aborted INTEGER NOT NULL DEFAULT 0,
137
+ filter_json TEXT,
138
+ eval_names TEXT NOT NULL DEFAULT '[]'
139
+ );
140
+ CREATE INDEX IF NOT EXISTS idx_eval_runs_started ON eval_runs(started_at DESC);
141
+
142
+ CREATE TABLE IF NOT EXISTS eval_reports (
143
+ run_id TEXT NOT NULL REFERENCES eval_runs(id) ON DELETE CASCADE,
144
+ seq INTEGER NOT NULL,
145
+ name TEXT NOT NULL,
146
+ started_at INTEGER NOT NULL,
147
+ pass INTEGER NOT NULL,
148
+ duration REAL NOT NULL,
149
+ type TEXT,
150
+ error TEXT,
151
+ report_json TEXT NOT NULL,
152
+ PRIMARY KEY (run_id, seq)
153
+ );
154
+ CREATE INDEX IF NOT EXISTS idx_eval_reports_name_time ON eval_reports(name, started_at DESC);
155
+
156
+ CREATE TABLE IF NOT EXISTS schema_meta (
157
+ key TEXT PRIMARY KEY,
158
+ value TEXT NOT NULL
159
+ );
160
+ `;
161
+ function aggregateTurnTimings(report) {
162
+ let botDuration = 0;
163
+ let evalDuration = 0;
164
+ for (const e of report.evals) {
165
+ for (const t of e.turns) {
166
+ botDuration += t.botDuration;
167
+ evalDuration += t.evalDuration;
168
+ }
169
+ }
170
+ return { botDuration, evalDuration };
171
+ }
172
+ function toEvalSummary(e) {
173
+ return {
174
+ name: e.name,
175
+ description: e.description,
176
+ tags: e.tags || [],
177
+ type: e.type || "capability",
178
+ turnCount: e.conversation.length,
179
+ hasOutcome: !!e.outcome
180
+ };
181
+ }
182
+ var LocalEvalStore = class {
183
+ db = null;
184
+ dbPath;
185
+ evalsDir;
186
+ insertRunStmt = null;
187
+ insertReportStmt = null;
188
+ _getActiveRunId;
189
+ _loadEvalDefinitions;
190
+ constructor(config) {
191
+ this.evalsDir = join(config.agentPath, ".adk", "evals");
192
+ this.dbPath = join(this.evalsDir, "evals.db");
193
+ this._getActiveRunId = config.getActiveRunId ?? (() => null);
194
+ this._loadEvalDefinitions = config.loadEvalDefinitions ?? createDiskEvalLoader(join(config.agentPath, "evals"));
195
+ }
196
+ // ── Eval definitions (from disk) ───────────────────────────────────
197
+ async listEvals(filter) {
198
+ const allEvals = await this._loadEvalDefinitions();
199
+ const evals = filter ? filterEvals(allEvals, filter) : allEvals;
200
+ return evals.map(toEvalSummary);
201
+ }
202
+ async getEval(name) {
203
+ const allEvals = await this._loadEvalDefinitions();
204
+ return allEvals.find((e) => e.name === name) ?? null;
205
+ }
206
+ // ── Run lifecycle — write ───────────────────────────────────────────
207
+ async createRun(_runType, _metadata) {
208
+ return crypto.randomUUID().replace(/-/g, "").slice(0, 26);
209
+ }
210
+ async addRunResults(_runId, _evalReport) {
211
+ }
212
+ async completeRun(_runId, report) {
213
+ const db = this.getDb();
214
+ if (!db) return;
215
+ db.run("BEGIN");
216
+ try {
217
+ this.insertRunReport(report);
218
+ db.run("COMMIT");
219
+ } catch (err) {
220
+ db.run("ROLLBACK");
221
+ console.error(`[local-eval-store] completeRun transaction failed (run ${report.id}): ${errText(err)}`);
222
+ throw err;
223
+ }
224
+ }
225
+ // ── Run results — read ─────────────────────────────────────────────
226
+ async loadRunResult(runId) {
227
+ const db = this.getDb();
228
+ if (!db) return null;
229
+ const runRow = db.prepare("SELECT * FROM eval_runs WHERE id = ?").get(runId);
230
+ if (!runRow) return null;
231
+ const reportRows = db.prepare("SELECT * FROM eval_reports WHERE run_id = ? ORDER BY seq").all(runRow.id);
232
+ return this.assembleRun(runRow, reportRows);
233
+ }
234
+ async getLatestRun() {
235
+ const db = this.getDb();
236
+ if (!db) return null;
237
+ const runRow = db.prepare("SELECT * FROM eval_runs ORDER BY started_at DESC LIMIT 1").get();
238
+ if (!runRow) return null;
239
+ const reportRows = db.prepare("SELECT * FROM eval_reports WHERE run_id = ? ORDER BY seq").all(runRow.id);
240
+ return this.assembleRun(runRow, reportRows);
241
+ }
242
+ async listRunSummaries(opts) {
243
+ const db = this.getDb();
244
+ if (!db) return [];
245
+ const limit = opts?.limit ?? 50;
246
+ const sinceTs = opts?.since;
247
+ const rows = sinceTs !== void 0 ? db.prepare(
248
+ "SELECT * FROM eval_runs WHERE started_at >= ? ORDER BY started_at DESC LIMIT ?"
249
+ ).all(sinceTs, limit) : db.prepare("SELECT * FROM eval_runs ORDER BY started_at DESC LIMIT ?").all(limit);
250
+ return rows.map((r) => ({
251
+ id: r.id,
252
+ timestamp: r.timestamp,
253
+ passed: r.passed,
254
+ failed: r.failed,
255
+ total: r.total,
256
+ duration: r.duration,
257
+ botDuration: r.bot_duration,
258
+ evalDuration: r.eval_duration,
259
+ filter: r.filter_json ? JSON.parse(r.filter_json) : void 0,
260
+ evalNames: JSON.parse(r.eval_names),
261
+ aborted: r.aborted === 1
262
+ }));
263
+ }
264
+ async listEvalReportsByName(evalName, opts) {
265
+ const db = this.getDb();
266
+ if (!db) return [];
267
+ const limit = opts?.limit ?? 20;
268
+ const sinceTs = opts?.since;
269
+ const baseSql = `
270
+ SELECT er.*,
271
+ r.timestamp AS run_timestamp,
272
+ r.total AS run_total,
273
+ r.filter_json AS run_filter_json
274
+ FROM eval_reports er
275
+ JOIN eval_runs r ON r.id = er.run_id
276
+ WHERE er.name = ?
277
+ `;
278
+ const rows = sinceTs !== void 0 ? db.prepare(
279
+ `${baseSql} AND er.started_at >= ? ORDER BY er.started_at DESC LIMIT ?`
280
+ ).all(evalName, sinceTs, limit) : db.prepare(`${baseSql} ORDER BY er.started_at DESC LIMIT ?`).all(evalName, limit);
281
+ return rows.map((row) => ({
282
+ runId: row.run_id,
283
+ timestamp: row.run_timestamp,
284
+ report: JSON.parse(row.report_json),
285
+ totalEvalsInRun: row.run_total,
286
+ filter: row.run_filter_json ? JSON.parse(row.run_filter_json) : void 0
287
+ }));
288
+ }
289
+ async listEvalReportsBulk(opts) {
290
+ const db = this.getDb();
291
+ if (!db) return {};
292
+ const perEval = opts?.perEval ?? 20;
293
+ const sinceTs = opts?.since;
294
+ const sinceClause = sinceTs !== void 0 ? "WHERE er.started_at >= ?" : "";
295
+ const sql = `
296
+ WITH ranked AS (
297
+ SELECT er.*, ROW_NUMBER() OVER (PARTITION BY name ORDER BY started_at DESC) AS rn
298
+ FROM eval_reports er
299
+ ${sinceClause}
300
+ )
301
+ SELECT ranked.run_id, ranked.name, ranked.started_at, ranked.pass,
302
+ ranked.duration, ranked.type, ranked.error, ranked.report_json,
303
+ r.timestamp AS run_timestamp,
304
+ r.total AS run_total,
305
+ r.filter_json AS run_filter_json
306
+ FROM ranked
307
+ JOIN eval_runs r ON r.id = ranked.run_id
308
+ WHERE ranked.rn <= ?
309
+ ORDER BY ranked.name, ranked.started_at DESC
310
+ `;
311
+ const rows = sinceTs !== void 0 ? db.prepare(sql).all(sinceTs, perEval) : db.prepare(sql).all(perEval);
312
+ const out = {};
313
+ for (const row of rows) {
314
+ const entry = {
315
+ runId: row.run_id,
316
+ timestamp: row.run_timestamp,
317
+ report: JSON.parse(row.report_json),
318
+ totalEvalsInRun: row.run_total,
319
+ filter: row.run_filter_json ? JSON.parse(row.run_filter_json) : void 0
320
+ };
321
+ const arr = out[row.name];
322
+ if (arr) arr.push(entry);
323
+ else out[row.name] = [entry];
324
+ }
325
+ return out;
326
+ }
327
+ // ── Live run tracking ──────────────────────────────────────────────
328
+ async *watchRun(_signal, _options) {
329
+ }
330
+ // ── Runner state ───────────────────────────────────────────────────
331
+ async getRunnerState() {
332
+ const runId = this._getActiveRunId();
333
+ return { running: runId !== null, runId };
334
+ }
335
+ // ── Extra (not on EvalStore interface) ──────────────────────────────
336
+ async listRunResults(limit = 50, sinceTs) {
337
+ const db = this.getDb();
338
+ if (!db) return [];
339
+ let runRows;
340
+ if (sinceTs !== void 0) {
341
+ runRows = db.prepare(
342
+ "SELECT * FROM eval_runs WHERE started_at >= ? ORDER BY started_at DESC LIMIT ?"
343
+ ).all(sinceTs, limit);
344
+ } else {
345
+ runRows = db.prepare("SELECT * FROM eval_runs ORDER BY started_at DESC LIMIT ?").all(limit);
346
+ }
347
+ if (runRows.length === 0) return [];
348
+ const ids = runRows.map((r) => r.id);
349
+ const placeholders = ids.map(() => "?").join(",");
350
+ const reportRows = db.prepare(`SELECT * FROM eval_reports WHERE run_id IN (${placeholders}) ORDER BY seq`).all(...ids);
351
+ const byRun = /* @__PURE__ */ new Map();
352
+ for (const row of reportRows) {
353
+ const arr = byRun.get(row.run_id);
354
+ if (arr) arr.push(row);
355
+ else byRun.set(row.run_id, [row]);
356
+ }
357
+ return runRows.map((row) => this.assembleRun(row, byRun.get(row.id) ?? []));
358
+ }
359
+ // ── Lifecycle ──────────────────────────────────────────────────────
360
+ close() {
361
+ try {
362
+ this.db?.close();
363
+ } catch {
364
+ }
365
+ this.db = null;
366
+ this.insertRunStmt = null;
367
+ this.insertReportStmt = null;
368
+ }
369
+ getDbPath() {
370
+ return this.dbPath;
371
+ }
372
+ // ── SQLite internals ───────────────────────────────────────────────
373
+ getDb() {
374
+ if (this.db) return this.db;
375
+ mkdirSync(this.evalsDir, { recursive: true });
376
+ try {
377
+ this.db = new Database(this.dbPath);
378
+ this.db.run("PRAGMA journal_mode=WAL");
379
+ this.db.run("PRAGMA synchronous=NORMAL");
380
+ this.db.run("PRAGMA busy_timeout=5000");
381
+ this.db.run("PRAGMA foreign_keys=ON");
382
+ this.db.run(SCHEMA);
383
+ this.setMeta("schema_version", SCHEMA_VERSION);
384
+ this.insertRunStmt = this.db.prepare(`
385
+ INSERT OR REPLACE INTO eval_runs (
386
+ id, timestamp, started_at, passed, failed, total, duration,
387
+ bot_duration, eval_duration, aborted, filter_json, eval_names
388
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
389
+ `);
390
+ this.insertReportStmt = this.db.prepare(`
391
+ INSERT OR REPLACE INTO eval_reports (
392
+ run_id, seq, name, started_at, pass, duration, type, error, report_json
393
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
394
+ `);
395
+ this.importLegacyJsonRunsIfNeeded();
396
+ return this.db;
397
+ } catch (err) {
398
+ console.warn("[local-eval-store] Failed to initialize database:", err);
399
+ try {
400
+ this.db?.close();
401
+ } catch {
402
+ }
403
+ try {
404
+ if (existsSync2(this.dbPath)) {
405
+ renameSync(this.dbPath, `${this.dbPath}.corrupt-${Date.now()}`);
406
+ }
407
+ } catch {
408
+ }
409
+ this.db = null;
410
+ this.insertRunStmt = null;
411
+ this.insertReportStmt = null;
412
+ return null;
413
+ }
414
+ }
415
+ getMeta(key) {
416
+ const db = this.db;
417
+ if (!db) return null;
418
+ const row = db.prepare("SELECT value FROM schema_meta WHERE key = ?").get(key);
419
+ return row?.value ?? null;
420
+ }
421
+ setMeta(key, value) {
422
+ const db = this.db;
423
+ if (!db) return;
424
+ db.prepare("INSERT OR REPLACE INTO schema_meta (key, value) VALUES (?, ?)").run(key, value);
425
+ }
426
+ importLegacyJsonRunsIfNeeded() {
427
+ const db = this.db;
428
+ if (!db) return;
429
+ if (this.getMeta("imported_legacy") === "1") return;
430
+ const legacyDir = join(this.evalsDir, "runs");
431
+ if (!existsSync2(legacyDir)) {
432
+ this.setMeta("imported_legacy", "1");
433
+ return;
434
+ }
435
+ let files = [];
436
+ try {
437
+ files = readdirSync2(legacyDir).filter((f) => f.endsWith(".json"));
438
+ } catch (err) {
439
+ console.warn("[local-eval-store] Could not read legacy runs dir:", err);
440
+ return;
441
+ }
442
+ if (files.length === 0) {
443
+ this.setMeta("imported_legacy", "1");
444
+ return;
445
+ }
446
+ let imported = 0;
447
+ let skipped = 0;
448
+ db.run("BEGIN");
449
+ try {
450
+ for (const file of files) {
451
+ db.run("SAVEPOINT import_file");
452
+ try {
453
+ const raw = readFileSync(join(legacyDir, file), "utf-8");
454
+ const report = JSON.parse(raw);
455
+ this.insertRunReport(report);
456
+ db.run("RELEASE import_file");
457
+ imported++;
458
+ } catch (err) {
459
+ db.run("ROLLBACK TO import_file");
460
+ db.run("RELEASE import_file");
461
+ skipped++;
462
+ console.warn(`[local-eval-store] Skipping unreadable legacy run ${file}:`, err);
463
+ }
464
+ }
465
+ this.setMeta("imported_legacy", "1");
466
+ db.run("COMMIT");
467
+ } catch (err) {
468
+ db.run("ROLLBACK");
469
+ console.warn("[local-eval-store] Legacy import failed, will retry on next start:", err);
470
+ return;
471
+ }
472
+ try {
473
+ renameSync(legacyDir, join(this.evalsDir, "runs.json-migrated"));
474
+ } catch (err) {
475
+ console.warn("[local-eval-store] Could not rename legacy runs dir:", err);
476
+ }
477
+ console.log(
478
+ `[local-eval-store] Imported ${imported} legacy eval run${imported === 1 ? "" : "s"}` + (skipped > 0 ? ` (${skipped} skipped)` : "")
479
+ );
480
+ }
481
+ insertRunReport(report) {
482
+ if (!this.insertRunStmt || !this.insertReportStmt) return;
483
+ const startedAt = Date.parse(report.timestamp);
484
+ const { botDuration, evalDuration } = aggregateTurnTimings(report);
485
+ this.insertRunStmt.run(
486
+ report.id,
487
+ report.timestamp,
488
+ Number.isNaN(startedAt) ? 0 : startedAt,
489
+ report.passed,
490
+ report.failed,
491
+ report.total,
492
+ report.duration,
493
+ botDuration,
494
+ evalDuration,
495
+ report.aborted ? 1 : 0,
496
+ report.filter ? JSON.stringify(report.filter) : null,
497
+ JSON.stringify(report.evals.map((e) => e.name))
498
+ );
499
+ for (let i = 0; i < report.evals.length; i++) {
500
+ const evalReport = report.evals[i];
501
+ this.insertReportStmt.run(
502
+ report.id,
503
+ i,
504
+ evalReport.name,
505
+ Number.isNaN(startedAt) ? 0 : startedAt,
506
+ evalReport.pass ? 1 : 0,
507
+ evalReport.duration,
508
+ evalReport.type ?? null,
509
+ evalReport.error ?? null,
510
+ JSON.stringify(evalReport)
511
+ );
512
+ }
513
+ }
514
+ assembleRun(runRow, reportRows) {
515
+ const evals = reportRows.map((r) => JSON.parse(r.report_json));
516
+ const report = {
517
+ id: runRow.id,
518
+ timestamp: runRow.timestamp,
519
+ evals,
520
+ passed: runRow.passed,
521
+ failed: runRow.failed,
522
+ total: runRow.total,
523
+ duration: runRow.duration
524
+ };
525
+ if (runRow.filter_json) {
526
+ report.filter = JSON.parse(runRow.filter_json);
527
+ }
528
+ if (runRow.aborted === 1) {
529
+ report.aborted = true;
530
+ }
531
+ return report;
532
+ }
533
+ };
534
+ var stores = /* @__PURE__ */ new Map();
535
+ function getLocalEvalStore(agentPath, getActiveRunId) {
536
+ let store = stores.get(agentPath);
537
+ if (!store) {
538
+ store = new LocalEvalStore({ agentPath, getActiveRunId });
539
+ stores.set(agentPath, store);
540
+ }
541
+ return store;
542
+ }
543
+ function closeLocalEvalStores(agentPath) {
544
+ if (agentPath) {
545
+ stores.get(agentPath)?.close();
546
+ stores.delete(agentPath);
547
+ return;
548
+ }
549
+ for (const store of stores.values()) store.close();
550
+ stores.clear();
551
+ }
552
+
553
+ // src/stores/vortex-eval-store.ts
554
+ var OUTCOME_TURN_INDEX = -1;
555
+ function vortexEntryToEvalReport(entry) {
556
+ const outcomeAssertions = entry.results.filter((r) => r.turnIndex === OUTCOME_TURN_INDEX).map((r) => ({
557
+ assertion: r.graderName,
558
+ pass: r.passed,
559
+ expected: r.evidence?.expected ?? "",
560
+ actual: r.evidence?.actual ?? ""
561
+ }));
562
+ const resultsByTurn = /* @__PURE__ */ new Map();
563
+ for (const r of entry.results) {
564
+ if (r.turnIndex === OUTCOME_TURN_INDEX) continue;
565
+ const existing = resultsByTurn.get(r.turnIndex) ?? [];
566
+ existing.push(r);
567
+ resultsByTurn.set(r.turnIndex, existing);
568
+ }
569
+ const turns = [...resultsByTurn.entries()].sort(([a], [b]) => a - b).map(([turnIndex, results]) => {
570
+ const assertions = results.map((r) => ({
571
+ assertion: r.graderName,
572
+ pass: r.passed,
573
+ expected: r.evidence?.expected ?? "",
574
+ actual: r.evidence?.actual ?? ""
575
+ }));
576
+ const first = results[0];
577
+ return {
578
+ turnIndex,
579
+ userMessage: first.userMessage,
580
+ botResponse: first.botResponse,
581
+ assertions,
582
+ pass: assertions.every((a) => a.pass),
583
+ botDuration: first.botDurationMs ?? 0,
584
+ evalDuration: first.graderDurationMs ?? 0
585
+ };
586
+ });
587
+ return {
588
+ name: entry.evalName,
589
+ description: entry.description || void 0,
590
+ type: entry.evalType,
591
+ tags: entry.tags,
592
+ turns,
593
+ outcomeAssertions,
594
+ pass: entry.passed ?? false,
595
+ duration: entry.durationMs ?? 0,
596
+ error: entry.error ?? void 0
597
+ };
598
+ }
599
+ async function mapWithConcurrency(items, concurrency, fn) {
600
+ const results = new Array(items.length);
601
+ let next = 0;
602
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
603
+ while (next < items.length) {
604
+ const i = next++;
605
+ results[i] = await fn(items[i]);
606
+ }
607
+ });
608
+ await Promise.all(workers);
609
+ return results;
610
+ }
611
+ function turnToResultRows(turn) {
612
+ return graderResultsToRows(turn.assertions, {
613
+ turnIndex: turn.turnIndex,
614
+ userMessage: turn.userMessage,
615
+ botResponse: turn.botResponse,
616
+ botDurationMs: turn.botDuration,
617
+ graderDurationMs: turn.evalDuration
618
+ });
619
+ }
620
+ function outcomeToResultRows(assertions) {
621
+ return graderResultsToRows(assertions, {
622
+ turnIndex: OUTCOME_TURN_INDEX,
623
+ userMessage: "",
624
+ botResponse: "",
625
+ botDurationMs: 0,
626
+ graderDurationMs: 0
627
+ });
628
+ }
629
+ function graderResultsToRows(assertions, context) {
630
+ return assertions.map((assertion) => ({
631
+ ...context,
632
+ graderName: assertion.assertion,
633
+ passed: assertion.pass,
634
+ evidence: { expected: assertion.expected, actual: assertion.actual }
635
+ }));
636
+ }
637
+ function runMatchesWatchOptions(run, options) {
638
+ if (options.runId && run.id !== options.runId) return false;
639
+ if (options.workflowId && run.metadata?.workflowId !== options.workflowId) return false;
640
+ return true;
641
+ }
642
+ function vortexRunToReport(run) {
643
+ const evals = run.entries.map(vortexEntryToEvalReport);
644
+ return {
645
+ id: run.id,
646
+ timestamp: run.createdAt,
647
+ evals,
648
+ passed: evals.filter((e) => e.pass).length,
649
+ failed: evals.filter((e) => !e.pass).length,
650
+ total: evals.length,
651
+ duration: evals.reduce((s, e) => s + e.duration, 0)
652
+ };
653
+ }
654
+ function vortexRunToSummary(run) {
655
+ const startMs = run.startedAt ? new Date(run.startedAt).getTime() : 0;
656
+ const endMs = run.completedAt ? new Date(run.completedAt).getTime() : 0;
657
+ if (run.entries) {
658
+ const evals = run.entries.map(vortexEntryToEvalReport);
659
+ return {
660
+ id: run.id,
661
+ timestamp: run.createdAt,
662
+ passed: evals.filter((e) => e.pass).length,
663
+ failed: evals.filter((e) => !e.pass).length,
664
+ total: evals.length,
665
+ duration: evals.reduce((s, e) => s + e.duration, 0),
666
+ botDuration: evals.reduce((s, e) => e.turns.reduce((ts, t) => ts + t.botDuration, s), 0),
667
+ evalDuration: evals.reduce((s, e) => e.turns.reduce((ts, t) => ts + t.evalDuration, s), 0),
668
+ evalNames: evals.map((e) => e.name),
669
+ aborted: false
670
+ };
671
+ }
672
+ return {
673
+ id: run.id,
674
+ timestamp: run.createdAt,
675
+ passed: 0,
676
+ failed: 0,
677
+ total: 0,
678
+ duration: startMs && endMs ? endMs - startMs : 0,
679
+ botDuration: 0,
680
+ evalDuration: 0,
681
+ evalNames: [],
682
+ aborted: false
683
+ };
684
+ }
685
+ var VortexEvalStore = class {
686
+ url;
687
+ botId;
688
+ workspaceId;
689
+ token;
690
+ _evalManifestId;
691
+ _loadEvalDefinitions;
692
+ constructor(config) {
693
+ this.url = config.url.replace(/\/$/, "");
694
+ this.botId = config.botId;
695
+ if (config.workspaceId) this.workspaceId = config.workspaceId;
696
+ if (config.token) this.token = config.token;
697
+ this._evalManifestId = config.evalManifestId;
698
+ this._loadEvalDefinitions = config.loadEvalDefinitions;
699
+ }
700
+ // ── Eval definitions (from Files API manifest) ───────────────────────
701
+ async listEvals(filter) {
702
+ const defs = await this.getEvalDefinitions();
703
+ const filtered = defs.filter((e) => {
704
+ if (filter?.names && !filter.names.includes(e.name)) return false;
705
+ if (filter?.type && e.type !== filter.type) return false;
706
+ if (filter?.tags && !filter.tags.every((tag) => e.tags?.includes(tag))) return false;
707
+ return true;
708
+ });
709
+ return filtered.map((e) => ({
710
+ name: e.name,
711
+ description: e.description,
712
+ tags: e.tags || [],
713
+ type: e.type || "capability",
714
+ turnCount: e.conversation.length,
715
+ hasOutcome: !!e.outcome
716
+ }));
717
+ }
718
+ async getEval(name) {
719
+ const defs = await this.getEvalDefinitions();
720
+ return defs.find((e) => e.name === name) ?? null;
721
+ }
722
+ // ── Run lifecycle — write ───────────────────────────────────────────
723
+ async createRun(runType = "scheduled", metadata) {
724
+ if (!this.workspaceId) {
725
+ throw new Error("workspaceId is required to create Vortex eval runs");
726
+ }
727
+ const triggerType = runType === "manual" ? "manual" : "scheduled";
728
+ const res = await this.fetch(`/v1/evals/bot/${this.botId}/runs`, {
729
+ method: "POST",
730
+ headers: { "Content-Type": "application/json" },
731
+ body: JSON.stringify({
732
+ evalManifestId: (typeof this._evalManifestId === "function" ? this._evalManifestId() : this._evalManifestId) ?? "",
733
+ workspaceId: this.workspaceId,
734
+ triggerType,
735
+ ...metadata ? { metadata } : {}
736
+ })
737
+ });
738
+ if (!res.ok) {
739
+ const text = await res.text().catch(() => "");
740
+ throw new Error(`Vortex create run failed: ${res.status} ${text}`);
741
+ }
742
+ const { id } = await res.json();
743
+ return id;
744
+ }
745
+ async addRunResults(runId, evalReport) {
746
+ const entry = {
747
+ evalName: evalReport.name,
748
+ evalType: evalReport.type ?? "capability",
749
+ description: evalReport.description ?? "",
750
+ tags: evalReport.tags ?? [],
751
+ passed: evalReport.pass,
752
+ durationMs: evalReport.duration,
753
+ error: evalReport.error,
754
+ results: [...evalReport.turns.flatMap(turnToResultRows), ...outcomeToResultRows(evalReport.outcomeAssertions)]
755
+ };
756
+ const res = await this.fetch(`/v1/evals/runs/${runId}/entries`, {
757
+ method: "POST",
758
+ headers: { "Content-Type": "application/json" },
759
+ body: JSON.stringify({ entries: [entry] })
760
+ });
761
+ if (!res.ok) {
762
+ const text = await res.text().catch(() => "");
763
+ throw new Error(`Vortex ingest entries failed: ${res.status} ${text}`);
764
+ }
765
+ }
766
+ async completeRun(runId, report) {
767
+ const hasRunError = report.aborted === true || report.evals.some((e) => e.error !== void 0);
768
+ const res = await this.fetch(`/v1/evals/runs/${runId}/entries`, {
769
+ method: "POST",
770
+ headers: { "Content-Type": "application/json" },
771
+ body: JSON.stringify({
772
+ entries: [],
773
+ completed: !hasRunError,
774
+ failed: hasRunError
775
+ })
776
+ });
777
+ if (!res.ok) {
778
+ const text = await res.text().catch(() => "");
779
+ throw new Error(`Vortex complete run failed: ${res.status} ${text}`);
780
+ }
781
+ }
782
+ // ── Per-turn incremental lifecycle (Option B) ──
783
+ //
784
+ // The eval-runner workflow builds each entry up as the eval runs (rather than
785
+ // writing it whole at the end), so the dev console can stream turn-by-turn
786
+ // progress. This is the prod ingestion path and requires Vortex to provide:
787
+ // startEntry POST /runs/{runId}/entries → { entries:[{ id }] } (passed:null, in-progress)
788
+ // appendTurnResults POST /runs/{runId}/entries/{entryId}/results (idempotent upsert by turnIndex+graderName)
789
+ // finalizeEntry PATCH /runs/{runId}/entries/{entryId} (sets the verdict)
790
+ // markRunComplete POST /runs/{runId}/complete (status → completed|failed)
791
+ /** Create an in-progress entry (metadata only, no results) and return its server id. */
792
+ async startEntry(runId, meta) {
793
+ const res = await this.fetch(`/v1/evals/runs/${runId}/entries`, {
794
+ method: "POST",
795
+ headers: { "Content-Type": "application/json" },
796
+ body: JSON.stringify({
797
+ entries: [
798
+ {
799
+ evalName: meta.evalName,
800
+ evalType: meta.evalType ?? "capability",
801
+ description: meta.description ?? "",
802
+ tags: meta.tags ?? []
803
+ }
804
+ ]
805
+ })
806
+ });
807
+ if (!res.ok) {
808
+ const text = await res.text().catch(() => "");
809
+ throw new Error(`Vortex start entry failed: ${res.status} ${text}`);
810
+ }
811
+ const data = await res.json();
812
+ const entryId = data.entries?.[0]?.id ?? data.id;
813
+ if (!entryId) {
814
+ throw new Error("Vortex start entry returned no entry id");
815
+ }
816
+ return entryId;
817
+ }
818
+ /** Append one turn's grader results to an existing entry. */
819
+ async appendTurnResults(runId, entryId, turn) {
820
+ const res = await this.fetch(`/v1/evals/runs/${runId}/entries/${entryId}/results`, {
821
+ method: "POST",
822
+ headers: { "Content-Type": "application/json" },
823
+ body: JSON.stringify({ results: turnToResultRows(turn) })
824
+ });
825
+ if (!res.ok) {
826
+ const text = await res.text().catch(() => "");
827
+ throw new Error(`Vortex append results failed: ${res.status} ${text}`);
828
+ }
829
+ }
830
+ /** Append outcome-level grader results to an existing entry. */
831
+ async appendOutcomeResults(runId, entryId, assertions) {
832
+ if (assertions.length === 0) return;
833
+ const res = await this.fetch(`/v1/evals/runs/${runId}/entries/${entryId}/results`, {
834
+ method: "POST",
835
+ headers: { "Content-Type": "application/json" },
836
+ body: JSON.stringify({ results: outcomeToResultRows(assertions) })
837
+ });
838
+ if (!res.ok) {
839
+ const text = await res.text().catch(() => "");
840
+ throw new Error(`Vortex append results failed: ${res.status} ${text}`);
841
+ }
842
+ }
843
+ /** Set the verdict on an entry once its eval finishes. */
844
+ async finalizeEntry(runId, entryId, verdict) {
845
+ const res = await this.fetch(`/v1/evals/runs/${runId}/entries/${entryId}`, {
846
+ method: "PATCH",
847
+ headers: { "Content-Type": "application/json" },
848
+ body: JSON.stringify({
849
+ passed: verdict.passed,
850
+ ...verdict.durationMs !== void 0 ? { durationMs: verdict.durationMs } : {},
851
+ ...verdict.error !== void 0 ? { error: verdict.error } : {}
852
+ })
853
+ });
854
+ if (!res.ok) {
855
+ const text = await res.text().catch(() => "");
856
+ throw new Error(`Vortex finalize entry failed: ${res.status} ${text}`);
857
+ }
858
+ }
859
+ /** Flip the run to its terminal status (replaces completeRun's empty-entries hack). */
860
+ async markRunComplete(runId, opts = {}) {
861
+ const res = await this.fetch(`/v1/evals/runs/${runId}/complete`, {
862
+ method: "POST",
863
+ headers: { "Content-Type": "application/json" },
864
+ body: JSON.stringify({ ...opts.failed !== void 0 ? { failed: opts.failed } : {} })
865
+ });
866
+ if (!res.ok) {
867
+ const text = await res.text().catch(() => "");
868
+ throw new Error(`Vortex complete run failed: ${res.status} ${text}`);
869
+ }
870
+ }
871
+ // ── Run results — read ─────────────────────────────────────────────
872
+ async loadRunResult(runId) {
873
+ const data = await this.fetchJson(`/v1/evals/runs/${runId}`);
874
+ return vortexRunToReport(data);
875
+ }
876
+ async getLatestRun() {
877
+ const data = await this.fetchJson(`/v1/evals/bot/${this.botId}/runs`, { limit: "1" });
878
+ if (!data.runs.length) return null;
879
+ const latest = data.runs[0];
880
+ return this.loadRunResult(latest.id);
881
+ }
882
+ async listRunSummaries(opts) {
883
+ const runs = await this.fetchRunsWithEntries(opts?.limit ?? 50, opts?.since);
884
+ return runs.map(vortexRunToSummary);
885
+ }
886
+ async listEvalReportsByName(evalName, opts) {
887
+ const limit = opts?.limit ?? 20;
888
+ const runs = await this.fetchRunsWithEntries(50, opts?.since);
889
+ const entries = [];
890
+ for (const run of runs) {
891
+ if (entries.length >= limit) break;
892
+ const entry = run.entries.find((e) => e.evalName === evalName);
893
+ if (entry) {
894
+ entries.push({
895
+ runId: run.id,
896
+ timestamp: run.createdAt,
897
+ report: vortexEntryToEvalReport(entry),
898
+ totalEvalsInRun: run.entries.length
899
+ });
900
+ }
901
+ }
902
+ return entries;
903
+ }
904
+ async listEvalReportsBulk(opts) {
905
+ const per = opts?.perEval ?? 20;
906
+ const runs = await this.fetchRunsWithEntries(50, opts?.since);
907
+ const grouped = {};
908
+ for (const run of runs) {
909
+ for (const entry of run.entries) {
910
+ if (!grouped[entry.evalName]) grouped[entry.evalName] = [];
911
+ if (grouped[entry.evalName].length < per) {
912
+ grouped[entry.evalName].push({
913
+ runId: run.id,
914
+ timestamp: run.createdAt,
915
+ report: vortexEntryToEvalReport(entry),
916
+ totalEvalsInRun: run.entries.length
917
+ });
918
+ }
919
+ }
920
+ }
921
+ return grouped;
922
+ }
923
+ // ── Live run tracking ──────────────────────────────────────────────
924
+ async *watchRun(signal, options = {}) {
925
+ const POLL_INTERVAL = 1500;
926
+ const POLL_TIMEOUT = 60 * 60 * 1e3;
927
+ const start = Date.now();
928
+ const hasExpectedRun = !!options.runId || !!options.workflowId;
929
+ let baselineRunId = null;
930
+ if (!hasExpectedRun) {
931
+ try {
932
+ const initial = await this.fetchJson(`/v1/evals/bot/${this.botId}/runs`, {
933
+ limit: "1"
934
+ });
935
+ baselineRunId = initial.runs[0]?.id ?? null;
936
+ } catch {
937
+ }
938
+ }
939
+ const evalMeta = await this.loadEvalMeta();
940
+ const startedEvals = /* @__PURE__ */ new Set();
941
+ const seenTurns = /* @__PURE__ */ new Set();
942
+ const startedTurns = /* @__PURE__ */ new Set();
943
+ const finalizedEvals = /* @__PURE__ */ new Set();
944
+ while (!signal?.aborted && Date.now() - start < POLL_TIMEOUT) {
945
+ try {
946
+ const data = await this.fetchJson(`/v1/evals/bot/${this.botId}/runs`, {
947
+ limit: hasExpectedRun ? "20" : "1"
948
+ });
949
+ let latest = null;
950
+ let raw = null;
951
+ for (const candidate of data.runs) {
952
+ if (options.runId && candidate.id !== options.runId) continue;
953
+ if (options.workflowId && candidate.metadata?.workflowId !== options.workflowId) {
954
+ const candidateRaw = await this.fetchJson(`/v1/evals/runs/${candidate.id}`);
955
+ if (!runMatchesWatchOptions(candidateRaw, options)) continue;
956
+ raw = candidateRaw;
957
+ }
958
+ latest = candidate;
959
+ break;
960
+ }
961
+ if (!latest || !hasExpectedRun && latest.id === baselineRunId) {
962
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL));
963
+ continue;
964
+ }
965
+ raw ??= await this.fetchJson(`/v1/evals/runs/${latest.id}`);
966
+ const terminal = raw.status === "completed" || raw.status === "failed";
967
+ for (let i = 0; i < raw.entries.length; i++) {
968
+ const entry = raw.entries[i];
969
+ const evalReport = vortexEntryToEvalReport(entry);
970
+ const meta = evalMeta.get(entry.evalName);
971
+ const totalTurns = meta?.totalTurns ?? evalReport.turns.length;
972
+ if (!startedEvals.has(entry.evalName)) {
973
+ startedEvals.add(entry.evalName);
974
+ yield { type: "eval_start", evalName: entry.evalName, index: i, totalTurns };
975
+ }
976
+ for (const turn of evalReport.turns) {
977
+ const turnKey = `${entry.evalName}::${turn.turnIndex}`;
978
+ if (seenTurns.has(turnKey)) continue;
979
+ seenTurns.add(turnKey);
980
+ yield {
981
+ type: "turn_complete",
982
+ evalName: entry.evalName,
983
+ evalIndex: i,
984
+ turnIndex: turn.turnIndex,
985
+ totalTurns,
986
+ turnReport: turn
987
+ };
988
+ }
989
+ if (entry.passed != null && !finalizedEvals.has(entry.evalName)) {
990
+ finalizedEvals.add(entry.evalName);
991
+ yield { type: "eval_complete", evalName: entry.evalName, index: i, report: evalReport };
992
+ } else if (entry.passed == null && !terminal) {
993
+ const nextTurnIndex = evalReport.turns.length;
994
+ const startKey = `${entry.evalName}::${nextTurnIndex}`;
995
+ if (nextTurnIndex < totalTurns && !startedTurns.has(startKey)) {
996
+ startedTurns.add(startKey);
997
+ yield {
998
+ type: "turn_start",
999
+ evalName: entry.evalName,
1000
+ evalIndex: i,
1001
+ turnIndex: nextTurnIndex,
1002
+ totalTurns,
1003
+ userMessage: meta?.userMessages[nextTurnIndex] ?? ""
1004
+ };
1005
+ }
1006
+ }
1007
+ }
1008
+ if (terminal) {
1009
+ const finalReport = vortexRunToReport(raw);
1010
+ for (let i = 0; i < finalReport.evals.length; i++) {
1011
+ const evalReport = finalReport.evals[i];
1012
+ if (finalizedEvals.has(evalReport.name)) continue;
1013
+ finalizedEvals.add(evalReport.name);
1014
+ yield { type: "eval_complete", evalName: evalReport.name, index: i, report: evalReport };
1015
+ }
1016
+ yield {
1017
+ type: "suite_complete",
1018
+ report: finalReport,
1019
+ error: raw.status === "failed" ? "Eval run failed" : void 0
1020
+ };
1021
+ return;
1022
+ }
1023
+ } catch {
1024
+ }
1025
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL));
1026
+ }
1027
+ if (!signal?.aborted) {
1028
+ yield {
1029
+ type: "suite_complete",
1030
+ report: {
1031
+ id: "timeout",
1032
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1033
+ evals: [],
1034
+ passed: 0,
1035
+ failed: 0,
1036
+ total: 0,
1037
+ duration: 0
1038
+ },
1039
+ error: "Eval run timed out"
1040
+ };
1041
+ }
1042
+ }
1043
+ // ── Runner state ───────────────────────────────────────────────────
1044
+ async getRunnerState() {
1045
+ try {
1046
+ const data = await this.fetchJson(`/v1/evals/bot/${this.botId}/runs`, {
1047
+ status: "running",
1048
+ limit: "1"
1049
+ });
1050
+ const active = data.runs[0] ?? null;
1051
+ return { running: !!active, runId: active?.id ?? null };
1052
+ } catch {
1053
+ return { running: false, runId: null };
1054
+ }
1055
+ }
1056
+ // ── Internal helpers ───────────────────────────────────────────────
1057
+ async getEvalDefinitions() {
1058
+ if (!this._loadEvalDefinitions) return [];
1059
+ return this._loadEvalDefinitions();
1060
+ }
1061
+ /**
1062
+ * evalName → { totalTurns, userMessages } from the eval definitions, so
1063
+ * watchRun can report `totalTurns` and synthesize `turn_start` events (with
1064
+ * the turn's user message) for the in-flight turn — matching the dev SSE
1065
+ * experience where the pending turn is visible before its results land.
1066
+ */
1067
+ async loadEvalMeta() {
1068
+ try {
1069
+ const defs = await this.getEvalDefinitions();
1070
+ return new Map(
1071
+ defs.map((d) => [
1072
+ d.name,
1073
+ { totalTurns: d.conversation.length, userMessages: d.conversation.map((t) => t.user ?? "") }
1074
+ ])
1075
+ );
1076
+ } catch {
1077
+ return /* @__PURE__ */ new Map();
1078
+ }
1079
+ }
1080
+ async fetchRunsWithEntries(limit, since) {
1081
+ const data = await this.fetchJson(`/v1/evals/bot/${this.botId}/runs`, {
1082
+ limit: String(limit)
1083
+ });
1084
+ let runs = data.runs;
1085
+ if (since) {
1086
+ runs = runs.filter((r) => new Date(r.createdAt).getTime() >= since);
1087
+ }
1088
+ return mapWithConcurrency(runs, 8, (r) => this.fetchJson(`/v1/evals/runs/${r.id}`));
1089
+ }
1090
+ async fetch(path, init) {
1091
+ const target = new URL(`${this.url}${path}`);
1092
+ const headers = new Headers(init?.headers);
1093
+ if (this.token) headers.set("Authorization", `Bearer ${this.token}`);
1094
+ return globalThis.fetch(target, { ...init, headers });
1095
+ }
1096
+ async fetchJson(path, params) {
1097
+ const target = new URL(`${this.url}${path}`);
1098
+ if (params) {
1099
+ for (const [k, v] of Object.entries(params)) target.searchParams.set(k, v);
1100
+ }
1101
+ const headers = new Headers();
1102
+ if (this.token) headers.set("Authorization", `Bearer ${this.token}`);
1103
+ const res = await globalThis.fetch(target, { headers });
1104
+ if (!res.ok) {
1105
+ const text = await res.text().catch(() => "");
1106
+ throw new Error(`Vortex ${res.status}: ${text}`);
1107
+ }
1108
+ return res.json();
1109
+ }
1110
+ };
1111
+ export {
1112
+ LocalEvalStore,
1113
+ VortexEvalStore,
1114
+ closeLocalEvalStores,
1115
+ createDiskEvalLoader,
1116
+ getLocalEvalStore
1117
+ };
1118
+ //# sourceMappingURL=index.js.map