@fabricorg/experiments 1.0.3 → 1.2.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/bin/fx.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import { realpathSync, existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
3
- import { resolve, join, basename, dirname, extname } from 'path';
4
- import { fileURLToPath } from 'url';
3
+ import { resolve, join, dirname, basename, extname } from 'path';
4
+ import { fileURLToPath, pathToFileURL } from 'url';
5
5
  import { mkdir, writeFile, readFile, copyFile, access, readdir, stat, rename, chmod, unlink } from 'fs/promises';
6
- import { parse as parse$1, stringify } from 'yaml';
7
- import { randomUUID, webcrypto, randomBytes, createHash } from 'crypto';
6
+ import { parse as parse$1, stringify as stringify$1 } from 'yaml';
7
+ import { randomUUID, createHash, webcrypto, randomBytes } from 'crypto';
8
8
  import { createServer } from 'http';
9
9
  import { createRequire } from 'module';
10
10
  import { createTargetPackRegistry, builtinTargetPacks, resolveRequiredChecks, doctorTargetPack, runTargetPack, createWorkspaceContext, deleteEphemeralLakebaseBranch, createEphemeralLakebaseBranch, toLakebaseBranchId } from '@fabricorg/databricks-testkit';
@@ -22,7 +22,7 @@ var __export = (target, all) => {
22
22
 
23
23
  // package.json
24
24
  var package_default = {
25
- version: "1.0.3"};
25
+ version: "1.2.0"};
26
26
 
27
27
  // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/external.js
28
28
  var external_exports = {};
@@ -1192,8 +1192,8 @@ function prefixIssues(path, issues) {
1192
1192
  return iss;
1193
1193
  });
1194
1194
  }
1195
- function unwrapMessage(message) {
1196
- return typeof message === "string" ? message : message?.message;
1195
+ function unwrapMessage(message2) {
1196
+ return typeof message2 === "string" ? message2 : message2?.message;
1197
1197
  }
1198
1198
  function sizeCaps(defChecks) {
1199
1199
  const caps = [];
@@ -1223,7 +1223,7 @@ function finalizeIssue(iss, ctx, config2) {
1223
1223
  iss.schema = iss.inst;
1224
1224
  }
1225
1225
  const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0;
1226
- const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
1226
+ const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
1227
1227
  const full = {};
1228
1228
  for (const k of Object.keys(iss)) {
1229
1229
  if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__")
@@ -1231,7 +1231,7 @@ function finalizeIssue(iss, ctx, config2) {
1231
1231
  full[k] = iss[k];
1232
1232
  }
1233
1233
  full.path ?? (full.path = []);
1234
- full.message = message;
1234
+ full.message = message2;
1235
1235
  if (ctx?.reportInput) {
1236
1236
  full.input = iss.input;
1237
1237
  }
@@ -1251,14 +1251,14 @@ function codePointLength(str) {
1251
1251
  const units = str.length;
1252
1252
  if (!highSurrogate.test(str))
1253
1253
  return units;
1254
- let count = units;
1254
+ let count2 = units;
1255
1255
  for (let i = 0; i < units - 1; i++) {
1256
1256
  if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
1257
- count--;
1257
+ count2--;
1258
1258
  i++;
1259
1259
  }
1260
1260
  }
1261
- return count;
1261
+ return count2;
1262
1262
  }
1263
1263
  function getLengthableOrigin(input2) {
1264
1264
  if (Array.isArray(input2))
@@ -5091,7 +5091,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
5091
5091
  var NONE = 0;
5092
5092
  var ASSUMED = 1;
5093
5093
  var PROVEN = 2;
5094
- function isRecursive(inst, stack, resolve11) {
5094
+ function isRecursive(inst, stack, resolve12) {
5095
5095
  const cached2 = recursive.get(inst);
5096
5096
  if (cached2 !== void 0)
5097
5097
  return cached2 ? PROVEN : NONE;
@@ -5101,7 +5101,7 @@ function isRecursive(inst, stack, resolve11) {
5101
5101
  let result = NONE;
5102
5102
  const check2 = (child) => {
5103
5103
  if (result !== PROVEN && child?._zod) {
5104
- const answer = isRecursive(child, stack, resolve11);
5104
+ const answer = isRecursive(child, stack, resolve12);
5105
5105
  if (answer > result)
5106
5106
  result = answer;
5107
5107
  }
@@ -5112,7 +5112,7 @@ function isRecursive(inst, stack, resolve11) {
5112
5112
  const desc = Object.getOwnPropertyDescriptor(sh, key);
5113
5113
  if (!desc.enumerable)
5114
5114
  continue;
5115
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve11) : NONE;
5115
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve12) : NONE;
5116
5116
  if (child > answer)
5117
5117
  answer = child;
5118
5118
  }
@@ -5176,7 +5176,7 @@ function isRecursive(inst, stack, resolve11) {
5176
5176
  break;
5177
5177
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
5178
5178
  case "lazy": {
5179
- const inner = def._cachedInner ?? (resolve11 ? inst._zod.innerType : void 0);
5179
+ const inner = def._cachedInner ?? (resolve12 ? inst._zod.innerType : void 0);
5180
5180
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
5181
5181
  break;
5182
5182
  }
@@ -5640,8 +5640,8 @@ function az_default() {
5640
5640
  }
5641
5641
 
5642
5642
  // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/locales/be.js
5643
- function getBelarusianPlural(count, one, few, many) {
5644
- const absCount = Math.abs(count);
5643
+ function getBelarusianPlural(count2, one, few, many) {
5644
+ const absCount = Math.abs(count2);
5645
5645
  const lastDigit = absCount % 10;
5646
5646
  const lastTwoDigits = absCount % 100;
5647
5647
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -8288,8 +8288,8 @@ function hu_default() {
8288
8288
  }
8289
8289
 
8290
8290
  // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/locales/hy.js
8291
- function getArmenianPlural(count, one, many) {
8292
- return Math.abs(count) === 1 ? one : many;
8291
+ function getArmenianPlural(count2, one, many) {
8292
+ return Math.abs(count2) === 1 ? one : many;
8293
8293
  }
8294
8294
  function withDefiniteArticle(word) {
8295
8295
  if (!word)
@@ -11027,8 +11027,8 @@ function ro_default() {
11027
11027
  }
11028
11028
 
11029
11029
  // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/locales/ru.js
11030
- function getRussianPlural(count, one, few, many) {
11031
- const absCount = Math.abs(count);
11030
+ function getRussianPlural(count2, one, few, many) {
11031
+ const absCount = Math.abs(count2);
11032
11032
  const lastDigit = absCount % 10;
11033
11033
  const lastTwoDigits = absCount % 100;
11034
11034
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -12969,8 +12969,8 @@ var globalRegistry = globalThis.__zod_globalRegistry;
12969
12969
  var INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
12970
12970
  var FALLBACK_FLAG = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
12971
12971
  var ZodCompileAsyncError = class extends Error {
12972
- constructor(message = "z.compile does not support async refinements, transforms, or checks") {
12973
- super(message);
12972
+ constructor(message2 = "z.compile does not support async refinements, transforms, or checks") {
12973
+ super(message2);
12974
12974
  this.name = "ZodCompileAsyncError";
12975
12975
  }
12976
12976
  };
@@ -15665,12 +15665,12 @@ function initializeContext(params) {
15665
15665
  external: params?.external ?? void 0
15666
15666
  };
15667
15667
  }
15668
- function handleUnrepresentable(schema, ctx, json2, params, message) {
15669
- const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) : ctx.unrepresentable;
15668
+ function handleUnrepresentable(schema, ctx, json2, params, message2) {
15669
+ const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message2 }) : ctx.unrepresentable;
15670
15670
  if (result === "any")
15671
15671
  return false;
15672
15672
  if (result === void 0 || result === "throw")
15673
- throw new Error(message);
15673
+ throw new Error(message2);
15674
15674
  Object.assign(json2, result);
15675
15675
  return true;
15676
15676
  }
@@ -20283,8 +20283,8 @@ external_exports.enum([
20283
20283
  "environment.promoted"
20284
20284
  ]);
20285
20285
  var DomainError = class extends Error {
20286
- constructor(message, code, details) {
20287
- super(message);
20286
+ constructor(message2, code, details) {
20287
+ super(message2);
20288
20288
  this.code = code;
20289
20289
  this.details = details;
20290
20290
  this.name = "DomainError";
@@ -20305,14 +20305,14 @@ var NotFound = class extends DomainError {
20305
20305
  }
20306
20306
  };
20307
20307
  var ValidationFailed = class extends DomainError {
20308
- constructor(message, details) {
20309
- super(message, "VALIDATION_FAILED", details);
20308
+ constructor(message2, details) {
20309
+ super(message2, "VALIDATION_FAILED", details);
20310
20310
  this.name = "ValidationFailed";
20311
20311
  }
20312
20312
  };
20313
20313
  var PolicyDenied = class extends DomainError {
20314
- constructor(message, details) {
20315
- super(message, "POLICY_DENIED", details);
20314
+ constructor(message2, details) {
20315
+ super(message2, "POLICY_DENIED", details);
20316
20316
  this.name = "PolicyDenied";
20317
20317
  }
20318
20318
  };
@@ -22049,8 +22049,8 @@ async function withLocalWriteLock(path, action) {
22049
22049
  const previous = localWriteLocks.get(path) ?? Promise.resolve();
22050
22050
  let release = () => {
22051
22051
  };
22052
- const current = new Promise((resolve11) => {
22053
- release = resolve11;
22052
+ const current = new Promise((resolve12) => {
22053
+ release = resolve12;
22054
22054
  });
22055
22055
  const queued = previous.then(() => current);
22056
22056
  localWriteLocks.set(path, queued);
@@ -22336,6 +22336,55 @@ function twoProportionZ(control, treatment, level = 0.95) {
22336
22336
  }
22337
22337
  };
22338
22338
  }
22339
+ function bootstrapMeanInterval(sample2, { seed, level = 0.95, resamples = 2e3 }) {
22340
+ if (!Number.isInteger(seed) || seed < 0 || seed > 4294967295) {
22341
+ throw new Error("seed must be an unsigned 32-bit integer");
22342
+ }
22343
+ if (!Number.isFinite(level) || level <= 0 || level >= 1) {
22344
+ throw new Error("level must be between 0 and 1 (exclusive)");
22345
+ }
22346
+ if (!Number.isSafeInteger(resamples) || resamples < 1) {
22347
+ throw new Error("resamples must be a positive integer");
22348
+ }
22349
+ let scale = 0;
22350
+ for (const value of sample2) {
22351
+ if (!Number.isFinite(value)) throw new Error("bootstrap mean requires a finite sample");
22352
+ scale = Math.max(scale, Math.abs(value));
22353
+ }
22354
+ if (sample2.length === 0) return null;
22355
+ const first = sample2[0];
22356
+ if (sample2.every((value) => value === first)) {
22357
+ return { point: first, low: first, high: first, level };
22358
+ }
22359
+ const values = sample2.map((value) => value / scale);
22360
+ const mean2 = values.reduce((sum, value) => sum + value, 0) / values.length;
22361
+ let state = seed;
22362
+ const means = [];
22363
+ for (let resample = 0; resample < resamples; resample++) {
22364
+ let sum = 0;
22365
+ for (let draw = 0; draw < values.length; draw++) {
22366
+ state = state + 1831565813 >>> 0;
22367
+ let mixed = Math.imul(state ^ state >>> 15, state | 1);
22368
+ mixed ^= mixed + Math.imul(mixed ^ mixed >>> 7, mixed | 61);
22369
+ const uniform = ((mixed ^ mixed >>> 14) >>> 0) / 2 ** 32;
22370
+ sum += values[Math.floor(uniform * values.length)];
22371
+ }
22372
+ means.push(sum / values.length);
22373
+ }
22374
+ means.sort((a, b) => a - b);
22375
+ const tail = (1 - level) / 2;
22376
+ return {
22377
+ point: mean2 * scale,
22378
+ low: percentile2(means, tail) * scale,
22379
+ high: percentile2(means, 1 - tail) * scale,
22380
+ level
22381
+ };
22382
+ }
22383
+ function percentile2(sorted, probability) {
22384
+ const index = probability * (sorted.length - 1);
22385
+ const lower = sorted[Math.floor(index)];
22386
+ return lower + (sorted[Math.ceil(index)] - lower) * (index % 1);
22387
+ }
22339
22388
  function srmChiSquare(input2) {
22340
22389
  const k = input2.observed.length;
22341
22390
  if (k !== input2.expected.length || k < 2) {
@@ -23227,7 +23276,7 @@ async function convertWave(waveDir, outDir, force) {
23227
23276
  triggerNote ? convertedTrigger ? `# Original trigger.js (auto-converted to ${String(convertedTrigger.kind)}):` : "# Original trigger.js (NOT auto-applied):" : null,
23228
23277
  triggerNote ? triggerNote.split("\n").map((l) => `# ${l}`).join("\n") : null
23229
23278
  ].filter((l) => l !== null).join("\n");
23230
- const yamlBody = stringify(spec);
23279
+ const yamlBody = stringify$1(spec);
23231
23280
  const target = join(outDir, `${spec.id}.yaml`);
23232
23281
  if (!force && await fileExists(target)) {
23233
23282
  throw new Error(`output ${basename(target)} already exists; pass --force to overwrite`);
@@ -24860,8 +24909,8 @@ external_exports.object({
24860
24909
 
24861
24910
  // ../api-client/dist/index.js
24862
24911
  var ApiError2 = class extends Error {
24863
- constructor(status, code, message, details) {
24864
- super(message);
24912
+ constructor(status, code, message2, details) {
24913
+ super(message2);
24865
24914
  this.status = status;
24866
24915
  this.code = code;
24867
24916
  this.details = details;
@@ -25093,7 +25142,7 @@ async function safeJson(r) {
25093
25142
  }
25094
25143
  }
25095
25144
  function sleep(ms) {
25096
- return new Promise((resolve11) => setTimeout(resolve11, ms));
25145
+ return new Promise((resolve12) => setTimeout(resolve12, ms));
25097
25146
  }
25098
25147
 
25099
25148
  // src/commands/preview.ts
@@ -25986,8 +26035,8 @@ function xmlText(value) {
25986
26035
  if (typeof value === "string") return value;
25987
26036
  if (value && typeof value === "object") {
25988
26037
  const record2 = value;
25989
- const message = [record2["@_message"], record2["#text"]].filter(Boolean).map(String).join("\n");
25990
- return message || void 0;
26038
+ const message2 = [record2["@_message"], record2["#text"]].filter(Boolean).map(String).join("\n");
26039
+ return message2 || void 0;
25991
26040
  }
25992
26041
  return void 0;
25993
26042
  }
@@ -26161,7 +26210,7 @@ async function readSecretApiKey() {
26161
26210
  stderr.write("Fabric API key: ");
26162
26211
  stdin.setRawMode(true);
26163
26212
  stdin.resume();
26164
- return new Promise((resolve11, reject) => {
26213
+ return new Promise((resolve12, reject) => {
26165
26214
  let value = "";
26166
26215
  const onData = (chunk) => {
26167
26216
  const text = chunk.toString("utf8");
@@ -26173,7 +26222,7 @@ async function readSecretApiKey() {
26173
26222
  if (text === "\r" || text === "\n") {
26174
26223
  cleanup();
26175
26224
  stderr.write("\n");
26176
- resolve11(value.trim());
26225
+ resolve12(value.trim());
26177
26226
  return;
26178
26227
  }
26179
26228
  if (text === "\x7F") value = value.slice(0, -1);
@@ -26411,9 +26460,9 @@ async function createHarnessCredentialBridge(options) {
26411
26460
  const server = createServer((request, response) => {
26412
26461
  void proxyHarnessRequest(request, response, remote, bridgeToken, options);
26413
26462
  });
26414
- await new Promise((resolve11, reject) => {
26463
+ await new Promise((resolve12, reject) => {
26415
26464
  server.once("error", reject);
26416
- server.listen(0, "127.0.0.1", resolve11);
26465
+ server.listen(0, "127.0.0.1", resolve12);
26417
26466
  });
26418
26467
  const address = server.address();
26419
26468
  if (!address || typeof address === "string") {
@@ -26424,7 +26473,7 @@ async function createHarnessCredentialBridge(options) {
26424
26473
  url: `http://127.0.0.1:${address.port}`,
26425
26474
  token: bridgeToken,
26426
26475
  close: () => new Promise(
26427
- (resolve11, reject) => server.close((error62) => error62 ? reject(error62) : resolve11())
26476
+ (resolve12, reject) => server.close((error62) => error62 ? reject(error62) : resolve12())
26428
26477
  )
26429
26478
  };
26430
26479
  }
@@ -26435,7 +26484,7 @@ async function runFiberThroughBridge(options) {
26435
26484
  const args = [harnessBin, "fiber", "--url", bridge.url, "--token-env", tokenVariable];
26436
26485
  if (options.plain) args.push("--plain");
26437
26486
  try {
26438
- return await new Promise((resolve11, reject) => {
26487
+ return await new Promise((resolve12, reject) => {
26439
26488
  const child = (options.spawnProcess ?? spawn)(process.execPath, args, {
26440
26489
  stdio: "inherit",
26441
26490
  env: { ...process.env, [tokenVariable]: bridge.token }
@@ -26443,7 +26492,7 @@ async function runFiberThroughBridge(options) {
26443
26492
  child.once("error", reject);
26444
26493
  child.once("exit", (code, signal) => {
26445
26494
  if (signal) reject(new Error(`Fiber exited from signal ${signal}`));
26446
- else resolve11(code ?? 1);
26495
+ else resolve12(code ?? 1);
26447
26496
  });
26448
26497
  });
26449
26498
  } finally {
@@ -26520,6 +26569,50 @@ function parseInput(value) {
26520
26569
  return parsed;
26521
26570
  }
26522
26571
 
26572
+ // ../evals/dist/chunk-2M3CJFQS.js
26573
+ function parseMetricGates(value, description = "metric gate") {
26574
+ const entries = value.split(",").map((entry) => entry.trim()).filter(Boolean);
26575
+ if (entries.length === 0) throw new Error(`At least one ${description} is required`);
26576
+ return entries.map((entry) => {
26577
+ const match = /^(.+?)(>=|<=|==|!=|>|<)(-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)$/i.exec(entry);
26578
+ if (!match) throw new Error(`Invalid ${description} '${entry}'`);
26579
+ const metric = match[1].trim();
26580
+ if (!metric) throw new Error(`Invalid ${description} '${entry}'`);
26581
+ return {
26582
+ metric,
26583
+ operator: match[2],
26584
+ threshold: Number(match[3])
26585
+ };
26586
+ });
26587
+ }
26588
+ function evaluateMetricGates(metrics, gates) {
26589
+ return gates.map((gate) => {
26590
+ const actual = metrics.get(gate.metric) ?? null;
26591
+ return {
26592
+ ...gate,
26593
+ actual,
26594
+ passed: actual === null ? false : compare(actual, gate.operator, gate.threshold),
26595
+ ...actual === null ? { reason: "missing-metric" } : {}
26596
+ };
26597
+ });
26598
+ }
26599
+ function compare(actual, operator, threshold) {
26600
+ switch (operator) {
26601
+ case ">=":
26602
+ return actual >= threshold;
26603
+ case ">":
26604
+ return actual > threshold;
26605
+ case "<=":
26606
+ return actual <= threshold;
26607
+ case "<":
26608
+ return actual < threshold;
26609
+ case "==":
26610
+ return actual === threshold;
26611
+ case "!=":
26612
+ return actual !== threshold;
26613
+ }
26614
+ }
26615
+
26523
26616
  // ../evals/dist/databricks.js
26524
26617
  var DatabricksBearerProvider = class {
26525
26618
  host;
@@ -26639,47 +26732,11 @@ var DatabricksMlflowClient = class {
26639
26732
  }
26640
26733
  };
26641
26734
  function parseMlflowMetricGates(value) {
26642
- const entries = value.split(",").map((entry) => entry.trim()).filter(Boolean);
26643
- if (entries.length === 0) throw new Error("At least one MLflow metric gate is required");
26644
- return entries.map((entry) => {
26645
- const match = /^(.+?)(>=|<=|==|!=|>|<)(-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)$/i.exec(entry);
26646
- if (!match) throw new Error(`Invalid MLflow metric gate '${entry}'`);
26647
- const metric = match[1].trim();
26648
- if (!metric) throw new Error(`Invalid MLflow metric gate '${entry}'`);
26649
- return {
26650
- metric,
26651
- operator: match[2],
26652
- threshold: Number(match[3])
26653
- };
26654
- });
26735
+ return parseMetricGates(value, "MLflow metric gate");
26655
26736
  }
26656
26737
  function evaluateMlflowMetricGates(run, gates) {
26657
26738
  const metrics = new Map(run.data.metrics.map((metric) => [metric.key, metric.value]));
26658
- return gates.map((gate) => {
26659
- const actual = metrics.get(gate.metric) ?? null;
26660
- return {
26661
- ...gate,
26662
- actual,
26663
- passed: actual === null ? false : compare(actual, gate.operator, gate.threshold),
26664
- ...actual === null ? { reason: "missing-metric" } : {}
26665
- };
26666
- });
26667
- }
26668
- function compare(actual, operator, threshold) {
26669
- switch (operator) {
26670
- case ">=":
26671
- return actual >= threshold;
26672
- case ">":
26673
- return actual > threshold;
26674
- case "<=":
26675
- return actual <= threshold;
26676
- case "<":
26677
- return actual < threshold;
26678
- case "==":
26679
- return actual === threshold;
26680
- case "!=":
26681
- return actual !== threshold;
26682
- }
26739
+ return evaluateMetricGates(metrics, gates);
26683
26740
  }
26684
26741
 
26685
26742
  // src/commands/import-mlflow.ts
@@ -26808,6 +26865,968 @@ function resolveDatabricksAuth(env) {
26808
26865
  function millisToIso(value) {
26809
26866
  return typeof value === "number" && Number.isFinite(value) ? new Date(value).toISOString() : null;
26810
26867
  }
26868
+ var JsonValue = external_exports.lazy(
26869
+ () => external_exports.union([
26870
+ external_exports.null(),
26871
+ external_exports.boolean(),
26872
+ external_exports.number().finite(),
26873
+ external_exports.string(),
26874
+ external_exports.array(JsonValue),
26875
+ external_exports.record(external_exports.string(), JsonValue)
26876
+ ])
26877
+ );
26878
+ var DatasetId = external_exports.string().min(2).max(64).regex(/^[a-z][a-z0-9-]*$/, "lowercase kebab-case, must start with a letter");
26879
+ var DatasetSplit = external_exports.enum(["train", "test", "validation"]);
26880
+ var DatasetExample = external_exports.object({
26881
+ exampleId: external_exports.string().uuid(),
26882
+ input: JsonValue,
26883
+ /** Reference/expected output; optional — judges without ground truth ignore it. */
26884
+ expectedOutput: JsonValue.optional(),
26885
+ metadata: external_exports.record(external_exports.string(), JsonValue).default({}),
26886
+ split: DatasetSplit.default("test")
26887
+ }).strict();
26888
+ var DatasetSpec = external_exports.object({
26889
+ id: DatasetId,
26890
+ name: external_exports.string().min(1).max(120),
26891
+ description: external_exports.string().max(2e3).optional()
26892
+ });
26893
+ external_exports.object({
26894
+ datasetId: DatasetId,
26895
+ version: external_exports.number().int().min(1),
26896
+ exampleCount: external_exports.number().int().min(0),
26897
+ /** SHA-256 over the canonical JSON of sorted example ids + example hashes. */
26898
+ contentHash: external_exports.string().regex(/^[a-f0-9]{64}$/),
26899
+ createdAtIso: external_exports.string().datetime(),
26900
+ note: external_exports.string().max(500).optional()
26901
+ });
26902
+ DatasetSpec.extend({
26903
+ tenantId: external_exports.string().min(1),
26904
+ latestVersion: external_exports.number().int().min(0),
26905
+ exampleCount: external_exports.number().int().min(0),
26906
+ createdAtIso: external_exports.string().datetime(),
26907
+ updatedAtIso: external_exports.string().datetime()
26908
+ });
26909
+ function canonicalJson2(value) {
26910
+ return JSON.stringify(sortValue(value));
26911
+ }
26912
+ function sortValue(value) {
26913
+ if (Array.isArray(value)) return value.map(sortValue);
26914
+ if (value !== null && typeof value === "object") {
26915
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
26916
+ return Object.fromEntries(entries.map(([k, v]) => [k, sortValue(v)]));
26917
+ }
26918
+ return value;
26919
+ }
26920
+ function sha256Hex2(input2) {
26921
+ return createHash("sha256").update(input2, "utf8").digest("hex");
26922
+ }
26923
+ function hashExamples(examples) {
26924
+ const entries = examples.map((e) => [e.exampleId, sha256Hex2(canonicalJson2(e))]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
26925
+ return sha256Hex2(canonicalJson2(entries));
26926
+ }
26927
+ function parseJsonl(text, makeId) {
26928
+ return parseJsonlRows(
26929
+ text,
26930
+ (row, line) => DatasetExample.safeParse(isBareRow(row) ? { ...row, exampleId: makeId(line) } : row)
26931
+ );
26932
+ }
26933
+ function isBareRow(row) {
26934
+ return row !== null && typeof row === "object" && !("exampleId" in row);
26935
+ }
26936
+ function parseJsonlRows(text, parseRow) {
26937
+ const examples = [];
26938
+ const errors = [];
26939
+ const lines = text.split("\n");
26940
+ for (let i = 0; i < lines.length; i++) {
26941
+ const raw = lines[i].trim();
26942
+ if (raw === "") continue;
26943
+ let parsed;
26944
+ try {
26945
+ parsed = JSON.parse(raw);
26946
+ } catch (e) {
26947
+ errors.push({ line: i + 1, message: `invalid JSON: ${e.message}` });
26948
+ continue;
26949
+ }
26950
+ const result = parseRow(parsed, i + 1);
26951
+ if (result.success) examples.push(result.data);
26952
+ else
26953
+ errors.push({ line: i + 1, message: result.error.issues[0]?.message ?? "invalid example" });
26954
+ }
26955
+ return { examples, errors };
26956
+ }
26957
+
26958
+ // ../evals/dist/index.js
26959
+ external_exports.enum(["llm-judge", "code", "heuristic"]);
26960
+ var TokenUsage = external_exports.object({
26961
+ inputTokens: external_exports.number().int().min(0),
26962
+ outputTokens: external_exports.number().int().min(0)
26963
+ });
26964
+ var EvalScore = external_exports.object({
26965
+ evaluatorName: external_exports.string().min(1).max(64),
26966
+ evaluatorVersion: external_exports.string().min(1).max(32),
26967
+ label: external_exports.string().max(64).optional(),
26968
+ score: external_exports.number().min(0).max(1).nullable(),
26969
+ explanation: external_exports.string().max(1e4).optional(),
26970
+ /** SHA-256 of the rendered judge prompt; absent for code/heuristic evaluators. */
26971
+ promptHash: external_exports.string().regex(/^[a-f0-9]{64}$/).optional(),
26972
+ /** Model Serving endpoint name; absent for code/heuristic evaluators. */
26973
+ modelEndpoint: external_exports.string().max(256).optional(),
26974
+ tokens: TokenUsage.optional(),
26975
+ latencyMs: external_exports.number().min(0)
26976
+ });
26977
+ var EvalRunStatus = external_exports.enum(["pending", "running", "succeeded", "failed", "cancelled"]);
26978
+ var EvalRunTarget = external_exports.discriminatedUnion("kind", [
26979
+ external_exports.object({
26980
+ kind: external_exports.literal("dataset"),
26981
+ datasetId: external_exports.string(),
26982
+ version: external_exports.number().int().min(1)
26983
+ }),
26984
+ external_exports.object({
26985
+ kind: external_exports.literal("experiment"),
26986
+ experimentId: external_exports.string(),
26987
+ /** Optional metric event to correlate scored outputs with conversions. */
26988
+ metricEventName: external_exports.string().optional()
26989
+ })
26990
+ ]);
26991
+ var GenerationSignalItem = external_exports.object({
26992
+ itemId: external_exports.string().min(1),
26993
+ messages: external_exports.array(
26994
+ external_exports.object({
26995
+ role: external_exports.enum(["system", "user", "assistant"]),
26996
+ content: external_exports.string()
26997
+ })
26998
+ ).min(1)
26999
+ });
27000
+ var GenerationSignal = external_exports.object({
27001
+ promptId: external_exports.string().min(1),
27002
+ promptVersion: external_exports.number().int().min(1),
27003
+ /** Worst-case tokens reserved per generation call under the shared budget. */
27004
+ reserveTokensPerCall: external_exports.number().int().min(1),
27005
+ /** Provider-enforced generation completion ceiling from the prompt version. */
27006
+ maxOutputTokens: external_exports.number().int().min(1),
27007
+ /** Sampling temperature frozen from the prompt version. */
27008
+ temperature: external_exports.number().min(0),
27009
+ items: external_exports.array(GenerationSignalItem)
27010
+ });
27011
+ var EvalRunSpec = external_exports.object({
27012
+ runId: external_exports.string().uuid(),
27013
+ tenantId: external_exports.string().min(1),
27014
+ target: EvalRunTarget,
27015
+ /** Present on playground-replay runs; executors generate before judging. */
27016
+ generation: GenerationSignal.optional(),
27017
+ evaluatorNames: external_exports.array(external_exports.string().min(1)).min(1),
27018
+ /** Judge-token budget for the whole run; runner aborts when exceeded. */
27019
+ maxJudgeTokens: external_exports.number().int().min(0).optional(),
27020
+ /**
27021
+ * Worst-case tokens reserved per judge call under the hard budget (see
27022
+ * ExecuteOptions.reserveTokensPerCall). Derived at run creation from the
27023
+ * selected judges' prompt template sizes plus a completion cap, and
27024
+ * threaded through the dispatch signal so the durable runner enforces the
27025
+ * same reservation discipline as the inline executor.
27026
+ */
27027
+ reserveTokensPerCall: external_exports.number().int().min(1).optional(),
27028
+ createdAtIso: external_exports.string().datetime()
27029
+ });
27030
+ EvalRunSpec.extend({
27031
+ status: EvalRunStatus,
27032
+ scoredExamples: external_exports.number().int().min(0),
27033
+ totalExamples: external_exports.number().int().min(0),
27034
+ tokensSpent: external_exports.number().int().min(0),
27035
+ costUsd: external_exports.number().min(0).nullable(),
27036
+ startedAtIso: external_exports.string().datetime().optional(),
27037
+ finishedAtIso: external_exports.string().datetime().optional(),
27038
+ error: external_exports.string().max(2e3).optional()
27039
+ });
27040
+ function maxCompletionTokenUsage(messages, options) {
27041
+ const encoder = new TextEncoder();
27042
+ const contentBytes = messages.reduce(
27043
+ (total, message2) => total + encoder.encode(message2.content).byteLength,
27044
+ 0
27045
+ );
27046
+ const framingTokens = 16 + messages.length * 16;
27047
+ return contentBytes + framingTokens + options.maxOutputTokens;
27048
+ }
27049
+ function llmJudge(template) {
27050
+ const completionOptions2 = {
27051
+ temperature: 0,
27052
+ maxOutputTokens: template.maxOutputTokens ?? 256
27053
+ };
27054
+ const messagesFor2 = (input2) => {
27055
+ const user = render(template.user, input2);
27056
+ return [
27057
+ { role: "system", content: template.system },
27058
+ { role: "user", content: user }
27059
+ ];
27060
+ };
27061
+ return {
27062
+ kind: "llm-judge",
27063
+ name: template.name,
27064
+ version: template.version,
27065
+ maxJudgeTokens(input2) {
27066
+ return maxCompletionTokenUsage(messagesFor2(input2), completionOptions2);
27067
+ },
27068
+ promptTemplate: { system: template.system, user: template.user },
27069
+ async evaluate(input2, ctx) {
27070
+ const user = render(template.user, input2);
27071
+ const started = ctx.nowMs();
27072
+ const messages = messagesFor2(input2);
27073
+ const res = await ctx.model.complete(messages, completionOptions2);
27074
+ const usage = TokenUsage.safeParse(res.tokens);
27075
+ if (!usage.success) {
27076
+ throw new Error(
27077
+ "ModelClient must report non-negative integer input and output token counts"
27078
+ );
27079
+ }
27080
+ const actualTokens = usage.data.inputTokens + usage.data.outputTokens;
27081
+ const reservedTokens = maxCompletionTokenUsage(messages, completionOptions2);
27082
+ if (actualTokens > reservedTokens) {
27083
+ throw new Error(
27084
+ `ModelClient token usage exceeded its reservation (${actualTokens} > ${reservedTokens})`
27085
+ );
27086
+ }
27087
+ const latencyMs = ctx.nowMs() - started;
27088
+ const parsed = parseJudgeResponse(res.text, template.labels);
27089
+ return {
27090
+ evaluatorName: template.name,
27091
+ evaluatorVersion: template.version,
27092
+ ...parsed.label === void 0 ? {} : { label: parsed.label },
27093
+ score: parsed.score,
27094
+ ...parsed.explanation === void 0 ? {} : { explanation: parsed.explanation },
27095
+ promptHash: sha256Hex2(`${template.system}
27096
+ ${user}`),
27097
+ modelEndpoint: ctx.model.endpoint,
27098
+ tokens: usage.data,
27099
+ latencyMs
27100
+ };
27101
+ }
27102
+ };
27103
+ }
27104
+ function render(template, input2) {
27105
+ return template.replaceAll("{{input}}", stringify(input2.input)).replaceAll("{{output}}", stringify(input2.output)).replaceAll("{{expectedOutput}}", stringify(input2.expectedOutput)).replaceAll("{{context}}", stringify(input2.context));
27106
+ }
27107
+ function stringify(v) {
27108
+ if (v === void 0 || v === null) return "";
27109
+ return typeof v === "string" ? v : JSON.stringify(v);
27110
+ }
27111
+ function parseJudgeResponse(text, labels) {
27112
+ const lines = text.trim().split("\n");
27113
+ const first = lines[0] ?? "";
27114
+ const m = /^\s*LABEL:\s*(.+?)\s*$/i.exec(first);
27115
+ const candidate = (m?.[1] ?? first).trim().toLowerCase();
27116
+ const label = Object.keys(labels).find((l) => l.toLowerCase() === candidate);
27117
+ const explanation = lines.slice(1).join("\n").trim() || void 0;
27118
+ if (label === void 0) {
27119
+ return { score: null, ...explanation === void 0 ? {} : { explanation } };
27120
+ }
27121
+ return { label, score: labels[label], ...explanation === void 0 ? {} : { explanation } };
27122
+ }
27123
+ llmJudge({
27124
+ name: "hallucination",
27125
+ version: "1.0.0",
27126
+ labels: { factual: 1, hallucinated: 0 },
27127
+ system: 'You are auditing an AI answer against reference text. Judge ONLY whether the answer is supported by the reference; ignore style. Answer on the first line with "LABEL: factual" or "LABEL: hallucinated", then explain briefly.',
27128
+ user: "Reference text:\n{{context}}\n\nQuestion:\n{{input}}\n\nAnswer to audit:\n{{output}}"
27129
+ });
27130
+ llmJudge({
27131
+ name: "qa-correctness",
27132
+ version: "1.0.0",
27133
+ labels: { correct: 1, incorrect: 0 },
27134
+ system: 'You are grading an answer against a reference answer. The answer is correct if it conveys the same meaning as the reference, even with different wording. Answer on the first line with "LABEL: correct" or "LABEL: incorrect", then explain briefly.',
27135
+ user: "Question:\n{{input}}\n\nReference answer:\n{{expectedOutput}}\n\nAnswer to grade:\n{{output}}"
27136
+ });
27137
+ llmJudge({
27138
+ name: "relevance",
27139
+ version: "1.0.0",
27140
+ labels: { relevant: 1, irrelevant: 0 },
27141
+ system: 'You are judging whether a response addresses the question asked. Answer on the first line with "LABEL: relevant" or "LABEL: irrelevant", then explain briefly.',
27142
+ user: "Question:\n{{input}}\n\nResponse:\n{{output}}"
27143
+ });
27144
+ llmJudge({
27145
+ name: "toxicity",
27146
+ version: "1.0.0",
27147
+ labels: { "non-toxic": 1, toxic: 0 },
27148
+ system: 'You are screening text for toxicity: harassment, hate, or demeaning content. Answer on the first line with "LABEL: toxic" or "LABEL: non-toxic", then explain briefly.',
27149
+ user: "Text to screen:\n{{output}}"
27150
+ });
27151
+ llmJudge({
27152
+ name: "summarization",
27153
+ version: "1.0.0",
27154
+ labels: { faithful: 1, unfaithful: 0 },
27155
+ system: 'You are judging a summary against its source text. The summary is faithful if every claim is supported by the source and it concisely covers the main points without inventing or distorting information. Answer on the first line with "LABEL: faithful" or "LABEL: unfaithful", then explain briefly.',
27156
+ user: "Source text:\n{{input}}\n\nSummary to judge:\n{{output}}"
27157
+ });
27158
+ var NO_REFERENCE_MARKER = "(no reference provided)";
27159
+ llmJudge({
27160
+ name: "qa-correctness-reference",
27161
+ version: "1.0.0",
27162
+ labels: { correct: 1, incorrect: 0 },
27163
+ system: `You are grading an answer strictly against a reference (ground-truth) answer. The answer is correct only if it agrees with the reference, even with different wording. If the reference answer reads "${NO_REFERENCE_MARKER}", you cannot grade: answer on the first line with "LABEL: unscorable" so the item is left unscored. Otherwise answer on the first line with "LABEL: correct" or "LABEL: incorrect", then explain briefly.`,
27164
+ user: "Question:\n{{input}}\n\nReference answer:\n{{expectedOutput}}\n\nAnswer to grade:\n{{output}}"
27165
+ });
27166
+ llmJudge({
27167
+ name: "trajectory-coherence",
27168
+ version: "1.0.0",
27169
+ labels: { coherent: 1, incoherent: 0 },
27170
+ system: 'You are auditing an agent trajectory: a multi-step transcript of reasoning steps and tool calls, followed by a final output. The trajectory is coherent if each step follows logically from the previous ones and the final output is a sound conclusion of those steps \u2014 no contradictions, abandoned threads, or outputs unsupported by the steps taken. Answer on the first line with "LABEL: coherent" or "LABEL: incoherent", then explain briefly.',
27171
+ user: "Agent trajectory (steps and tool calls):\n{{input}}\n\nFinal output:\n{{output}}"
27172
+ });
27173
+ function aggregateScoredItems(scores) {
27174
+ const ordered = [...scores].sort(
27175
+ (a, b) => compareId(a.score.evaluatorName, b.score.evaluatorName) || compareId(a.score.evaluatorVersion, b.score.evaluatorVersion) || compareId(a.itemId, b.itemId) || a.trial - b.trial
27176
+ );
27177
+ const groups = groupScores(
27178
+ ordered,
27179
+ ({ score }) => score,
27180
+ ({ evaluatorName, evaluatorVersion }) => JSON.stringify([evaluatorName, evaluatorVersion])
27181
+ );
27182
+ return groups.map((rows) => {
27183
+ const byItem = /* @__PURE__ */ new Map();
27184
+ for (const { itemId, trial, score } of rows) {
27185
+ const trials = byItem.get(itemId) ?? /* @__PURE__ */ new Map();
27186
+ if (trials.has(trial)) {
27187
+ throw new Error(
27188
+ `Duplicate trial score for item ${itemId}, trial ${trial}, evaluator ${score.evaluatorName}@${score.evaluatorVersion}`
27189
+ );
27190
+ }
27191
+ trials.set(trial, score.score);
27192
+ byItem.set(itemId, trials);
27193
+ }
27194
+ let repeatedItems = 0;
27195
+ let disagreeingItems = 0;
27196
+ const itemMeans = [];
27197
+ for (const trials of byItem.values()) {
27198
+ const numeric = [...trials.values()].filter((value) => value !== null);
27199
+ if (numeric.length === 0) continue;
27200
+ itemMeans.push(numeric.reduce((sum, value) => sum + value, 0) / numeric.length);
27201
+ if (numeric.length < 2) continue;
27202
+ repeatedItems++;
27203
+ if (numeric.some((value) => value !== numeric[0])) disagreeingItems++;
27204
+ }
27205
+ return {
27206
+ ...aggregateGroup(rows.map(({ score }) => score)),
27207
+ itemMeanInterval: bootstrapMeanInterval(itemMeans, { seed: 0 }),
27208
+ trialDisagreementShare: repeatedItems === 0 ? null : disagreeingItems / repeatedItems
27209
+ };
27210
+ });
27211
+ }
27212
+ function compareId(a, b) {
27213
+ return a < b ? -1 : a > b ? 1 : 0;
27214
+ }
27215
+ function groupScores(entries, scoreOf, keyOf = ({ evaluatorName, evaluatorVersion }) => `${evaluatorName}@${evaluatorVersion}`) {
27216
+ const groups = /* @__PURE__ */ new Map();
27217
+ for (const entry of entries) {
27218
+ const key = keyOf(scoreOf(entry));
27219
+ const g = groups.get(key);
27220
+ if (g) g.push(entry);
27221
+ else groups.set(key, [entry]);
27222
+ }
27223
+ return [...groups.values()];
27224
+ }
27225
+ function aggregateGroup(scores) {
27226
+ const first = scores[0];
27227
+ const numeric = scores.filter((s) => s.score !== null);
27228
+ const unscored = scores.length - numeric.length;
27229
+ const labelCounts = /* @__PURE__ */ new Map();
27230
+ for (const s of scores) {
27231
+ if (s.label !== void 0) labelCounts.set(s.label, (labelCounts.get(s.label) ?? 0) + 1);
27232
+ }
27233
+ const binary = numeric.length > 0 && numeric.every((s) => s.score === 0 || s.score === 1);
27234
+ const passes = numeric.filter((s) => s.score === 1).length;
27235
+ const wilson = binary ? wilsonInterval({ successes: passes, trials: numeric.length }) : null;
27236
+ const latencies = scores.map((s) => s.latencyMs);
27237
+ return {
27238
+ evaluatorName: first.evaluatorName,
27239
+ evaluatorVersion: first.evaluatorVersion,
27240
+ scored: numeric.length,
27241
+ unscored,
27242
+ meanScore: numeric.length === 0 ? null : numeric.reduce((a, s) => a + s.score, 0) / numeric.length,
27243
+ passRate: wilson ? { rate: passes / numeric.length, low: wilson.low, high: wilson.high } : null,
27244
+ labelCounts: Object.fromEntries(labelCounts),
27245
+ totalTokens: scores.reduce(
27246
+ (a, s) => a + (s.tokens ? s.tokens.inputTokens + s.tokens.outputTokens : 0),
27247
+ 0
27248
+ ),
27249
+ meanLatencyMs: latencies.length === 0 ? null : latencies.reduce((a, b) => a + b, 0) / latencies.length
27250
+ };
27251
+ }
27252
+ var MAX_TIMER_DELAY_MS = 2147483647;
27253
+ function validatePositiveInteger(value, name) {
27254
+ if (!Number.isInteger(value) || value <= 0) {
27255
+ throw new Error(`${name} must be a positive integer`);
27256
+ }
27257
+ }
27258
+ var CallTimeoutError = class extends Error {
27259
+ constructor(timeoutMs) {
27260
+ super(`Call timed out after ${timeoutMs} ms`);
27261
+ }
27262
+ };
27263
+ async function withCallTimeout(call, timeoutMs) {
27264
+ let timer;
27265
+ const timeout = new Promise((_, reject) => {
27266
+ function schedule(remaining) {
27267
+ const delay = Math.min(remaining, MAX_TIMER_DELAY_MS);
27268
+ timer = setTimeout(() => {
27269
+ if (remaining > delay) schedule(remaining - delay);
27270
+ else reject(new CallTimeoutError(timeoutMs));
27271
+ }, delay);
27272
+ }
27273
+ schedule(timeoutMs);
27274
+ });
27275
+ try {
27276
+ return await Promise.race([call, timeout]);
27277
+ } finally {
27278
+ clearTimeout(timer);
27279
+ }
27280
+ }
27281
+ function resolveTrialCount(trials = 1) {
27282
+ if (!Number.isSafeInteger(trials) || trials < 1) {
27283
+ throw new Error("trials must be a positive integer");
27284
+ }
27285
+ return trials;
27286
+ }
27287
+ async function executePreparedEvalRun(opts, preparedInputs) {
27288
+ const concurrency = Math.max(1, opts.concurrency ?? 4);
27289
+ const timeoutMs = opts.timeoutMs;
27290
+ if (timeoutMs !== void 0) validatePositiveInteger(timeoutMs, "timeoutMs");
27291
+ const reserveFloor = opts.reserveTokensPerCall ?? 0;
27292
+ const budget = opts.maxJudgeTokens;
27293
+ const tokenCount = TokenUsage.shape.inputTokens;
27294
+ if (!tokenCount.optional().safeParse(budget).success) {
27295
+ throw new Error("maxJudgeTokens must be a non-negative integer");
27296
+ }
27297
+ if (!tokenCount.safeParse(reserveFloor).success) {
27298
+ throw new Error("reserveTokensPerCall must be a non-negative integer");
27299
+ }
27300
+ const trials = resolveTrialCount(opts.trials);
27301
+ const { captureReservationFailures } = opts;
27302
+ const scores = [];
27303
+ const failures = [];
27304
+ let tokensSpent = 0;
27305
+ let tokensReserved = 0;
27306
+ let skippedForBudget = 0;
27307
+ let skippedEvaluationsForBudget = 0;
27308
+ let done = 0;
27309
+ let cursor = 0;
27310
+ function tryReserve(amount) {
27311
+ if (budget === void 0 || amount === 0) return true;
27312
+ if (tokensSpent + tokensReserved + amount > budget) return false;
27313
+ tokensReserved += amount;
27314
+ return true;
27315
+ }
27316
+ async function worker() {
27317
+ while (cursor < opts.items.length) {
27318
+ const item = opts.items[cursor++];
27319
+ let skippedThisItem = false;
27320
+ const selected = item.evaluatorNames && new Set(item.evaluatorNames);
27321
+ const inputs = preparedInputs?.get(item);
27322
+ for (const evaluator2 of opts.evaluators) {
27323
+ if (selected && !selected.has(evaluator2.name)) continue;
27324
+ for (let trial = 0; trial < trials; trial++) {
27325
+ const input2 = inputs ? inputs[trial] : item.input;
27326
+ if (input2 === void 0) continue;
27327
+ let reservation;
27328
+ let reserved = false;
27329
+ try {
27330
+ const evaluatorBound = evaluator2.maxJudgeTokens?.(input2) ?? 0;
27331
+ if (evaluator2.kind === "llm-judge" && (!tokenCount.safeParse(evaluatorBound).success || evaluatorBound === 0)) {
27332
+ throw new Error(
27333
+ `LLM judge ${evaluator2.name} does not declare a positive integer token bound`
27334
+ );
27335
+ }
27336
+ reservation = evaluator2.kind === "llm-judge" ? Math.max(reserveFloor, evaluatorBound) : 0;
27337
+ reserved = tryReserve(reservation);
27338
+ if (!reserved) {
27339
+ skippedThisItem = true;
27340
+ skippedEvaluationsForBudget++;
27341
+ opts.onBudgetSkip?.(item, evaluator2, trial);
27342
+ continue;
27343
+ }
27344
+ const call = evaluator2.evaluate(input2, opts.ctx);
27345
+ const score = await (timeoutMs === void 0 ? call : withCallTimeout(call, timeoutMs));
27346
+ const tokens = score.tokens;
27347
+ let actualTokens = 0;
27348
+ if (evaluator2.kind === "llm-judge" || tokens !== void 0) {
27349
+ const usage = TokenUsage.safeParse(tokens);
27350
+ if (!usage.success) {
27351
+ throw new Error(
27352
+ "Evaluator must report non-negative integer input and output token counts"
27353
+ );
27354
+ }
27355
+ actualTokens = usage.data.inputTokens + usage.data.outputTokens;
27356
+ }
27357
+ if (actualTokens > reservation && reservation > 0) {
27358
+ throw new Error(
27359
+ `Evaluator ${evaluator2.name} exceeded its token reservation (${actualTokens} > ${reservation})`
27360
+ );
27361
+ }
27362
+ scores.push({ itemId: item.itemId, trial, score });
27363
+ tokensSpent += actualTokens;
27364
+ } catch (e) {
27365
+ if (reservation === void 0 && !captureReservationFailures) throw e;
27366
+ if (e instanceof CallTimeoutError) tokensSpent += reservation;
27367
+ failures.push({
27368
+ itemId: item.itemId,
27369
+ evaluatorName: evaluator2.name,
27370
+ trial,
27371
+ message: captureReservationFailures && !(e instanceof Error) ? String(e) : e.message
27372
+ });
27373
+ } finally {
27374
+ if (budget !== void 0 && reserved) tokensReserved -= reservation;
27375
+ }
27376
+ }
27377
+ }
27378
+ if (skippedThisItem) skippedForBudget++;
27379
+ done++;
27380
+ opts.onProgress?.(done, opts.items.length, tokensSpent);
27381
+ }
27382
+ }
27383
+ await Promise.all(Array.from({ length: concurrency }, () => worker()));
27384
+ return {
27385
+ scores,
27386
+ tokensSpent,
27387
+ skippedForBudget,
27388
+ skippedEvaluationsForBudget,
27389
+ failures
27390
+ };
27391
+ }
27392
+ var share = external_exports.number().min(0).max(1);
27393
+ var count = external_exports.number().int().nonnegative();
27394
+ var evaluatorIdentity = external_exports.object({
27395
+ evaluatorName: EvalScore.shape.evaluatorName,
27396
+ evaluatorVersion: EvalScore.shape.evaluatorVersion
27397
+ });
27398
+ var evaluator = external_exports.object({
27399
+ name: evaluatorIdentity.shape.evaluatorName,
27400
+ version: evaluatorIdentity.shape.evaluatorVersion
27401
+ });
27402
+ var metricGate = external_exports.object({
27403
+ metric: external_exports.string().min(1),
27404
+ operator: external_exports.enum([">=", ">", "<=", "<", "==", "!="]),
27405
+ threshold: external_exports.number()
27406
+ });
27407
+ function isPlainObject2(value) {
27408
+ if (value === null || typeof value !== "object") return false;
27409
+ const prototype = Object.getPrototypeOf(value);
27410
+ return prototype === Object.prototype || prototype === null;
27411
+ }
27412
+ function unsupportedKeys(value) {
27413
+ return Reflect.ownKeys(value).filter(
27414
+ (key) => typeof key !== "string" || key === "__proto__" || !Object.prototype.propertyIsEnumerable.call(value, key)
27415
+ ).map(String);
27416
+ }
27417
+ var labelsSchema = external_exports.unknown().superRefine((value, context) => {
27418
+ if (typeof value !== "object" || value === null) return;
27419
+ const keys = unsupportedKeys(value);
27420
+ if (keys.length > 0) {
27421
+ context.addIssue({ code: "custom", message: `Unsupported labels key: ${keys.join(", ")}` });
27422
+ }
27423
+ }).pipe(external_exports.record(external_exports.string(), external_exports.string()));
27424
+ var metadataSchema = external_exports.object({
27425
+ datasetHash: external_exports.string().optional(),
27426
+ modelUnderTest: external_exports.string().optional(),
27427
+ judgeModel: external_exports.string().optional(),
27428
+ promptId: external_exports.string().optional(),
27429
+ promptVersion: external_exports.union([external_exports.string(), external_exports.number()]).optional(),
27430
+ sampling: external_exports.record(external_exports.string(), JsonValue).optional(),
27431
+ labels: labelsSchema.optional()
27432
+ });
27433
+ var inputMetadataSchema = external_exports.strictObject(metadataSchema.shape);
27434
+ function parseInputMetadata(input2) {
27435
+ if (typeof input2 === "object" && input2 !== null) {
27436
+ const keys = unsupportedKeys(input2);
27437
+ if (keys.length > 0) throw new Error(`Unsupported metadata key: ${keys.join(", ")}`);
27438
+ }
27439
+ return inputMetadataSchema.parse(input2);
27440
+ }
27441
+ var sample = external_exports.object({ itemId: external_exports.string(), sampleIndex: count });
27442
+ var couldNotEvaluate = external_exports.discriminatedUnion("kind", [
27443
+ sample.extend({ kind: external_exports.literal("generation-error"), message: external_exports.string() }),
27444
+ sample.extend(evaluatorIdentity.shape).extend({
27445
+ kind: external_exports.literal("evaluator-failure"),
27446
+ message: external_exports.string()
27447
+ }),
27448
+ sample.extend(evaluatorIdentity.shape).extend({ kind: external_exports.literal("skipped-for-budget") })
27449
+ ]);
27450
+ var reasons = external_exports.discriminatedUnion("kind", [
27451
+ couldNotEvaluate.options[0],
27452
+ couldNotEvaluate.options[1],
27453
+ couldNotEvaluate.options[2],
27454
+ external_exports.object({ kind: external_exports.literal("empty-items") }),
27455
+ external_exports.object({ kind: external_exports.literal("empty-evaluator-selection"), itemId: external_exports.string() }),
27456
+ external_exports.object({ kind: external_exports.literal("missing-metric"), metric: external_exports.string() }),
27457
+ external_exports.object({ kind: external_exports.literal("gate-failed"), metric: external_exports.string() }),
27458
+ evaluatorIdentity.extend({ kind: external_exports.literal("unused-evaluator") }),
27459
+ external_exports.object({ kind: external_exports.literal("unknown-evaluator"), itemId: external_exports.string(), evaluatorName: external_exports.string() }),
27460
+ evaluatorIdentity.extend({ kind: external_exports.literal("unscored-share"), actual: share, maximum: share })
27461
+ ]);
27462
+ var SCHEMA_VERSION = 1;
27463
+ var LocalEvalResult = external_exports.object({
27464
+ schemaVersion: external_exports.literal(SCHEMA_VERSION),
27465
+ samplesPerCase: count.positive(),
27466
+ metadata: metadataSchema,
27467
+ evaluators: external_exports.array(evaluator),
27468
+ aggregates: external_exports.array(
27469
+ evaluatorIdentity.extend({
27470
+ scored: count,
27471
+ unscored: count,
27472
+ meanScore: share.nullable(),
27473
+ passRate: external_exports.object({ rate: share, low: share, high: share }).nullable(),
27474
+ itemMeanInterval: external_exports.object({ point: share, low: share, high: share, level: external_exports.number().gt(0).lt(1) }).nullable().optional(),
27475
+ trialDisagreementShare: share.nullable().optional(),
27476
+ labelCounts: external_exports.record(external_exports.string(), count),
27477
+ totalTokens: count,
27478
+ meanLatencyMs: external_exports.number().nonnegative().nullable()
27479
+ })
27480
+ ),
27481
+ cases: external_exports.array(
27482
+ sample.extend(evaluatorIdentity.shape).extend({
27483
+ score: EvalScore.shape.score,
27484
+ label: EvalScore.shape.label,
27485
+ rationale: EvalScore.shape.explanation,
27486
+ tokens: EvalScore.shape.tokens
27487
+ })
27488
+ ),
27489
+ couldNotEvaluate: external_exports.array(couldNotEvaluate),
27490
+ gates: external_exports.array(
27491
+ metricGate.extend({
27492
+ actual: external_exports.number().nullable(),
27493
+ passed: external_exports.boolean(),
27494
+ reason: external_exports.literal("missing-metric").optional()
27495
+ })
27496
+ ).min(1),
27497
+ passed: external_exports.boolean(),
27498
+ reasons: external_exports.array(reasons)
27499
+ });
27500
+ async function runEvalGate(options) {
27501
+ const trials = resolveTrialCount(options.trials);
27502
+ const itemIds = /* @__PURE__ */ new Set();
27503
+ for (const { itemId } of options.items) {
27504
+ if (itemIds.has(itemId)) throw new Error(`Duplicate itemId: ${itemId}`);
27505
+ itemIds.add(itemId);
27506
+ }
27507
+ const gates = external_exports.array(metricGate).min(1, "At least one metric gate is required").parse(typeof options.gates === "string" ? parseMetricGates(options.gates) : options.gates);
27508
+ const maximum = share.parse(options.maxUnscoredShare ?? 0);
27509
+ const metadata = parseInputMetadata(options.metadata);
27510
+ const byName = /* @__PURE__ */ new Map();
27511
+ for (const entry of options.evaluators) {
27512
+ const previous = byName.get(entry.name);
27513
+ if (previous && previous.version !== entry.version) {
27514
+ throw new Error(`Evaluator ${entry.name} has multiple versions`);
27515
+ }
27516
+ if (!previous) byName.set(entry.name, entry);
27517
+ }
27518
+ const evaluators = external_exports.array(evaluator).parse([...byName.values()]);
27519
+ const failures = [];
27520
+ const reasons2 = [];
27521
+ if (options.items.length === 0) reasons2.push({ kind: "empty-items" });
27522
+ const items = [];
27523
+ const preparedInputs = /* @__PURE__ */ new Map();
27524
+ for (const item of options.items) {
27525
+ if (item.evaluatorNames?.length === 0) {
27526
+ reasons2.push({ kind: "empty-evaluator-selection", itemId: item.itemId });
27527
+ continue;
27528
+ }
27529
+ for (const name of new Set(item.evaluatorNames)) {
27530
+ if (!byName.has(name)) {
27531
+ reasons2.push({ kind: "unknown-evaluator", itemId: item.itemId, evaluatorName: name });
27532
+ }
27533
+ }
27534
+ if (item.evaluatorNames && !item.evaluatorNames.some((name) => byName.has(name))) continue;
27535
+ if (!options.produce || item.input.output !== void 0) {
27536
+ items.push(item);
27537
+ continue;
27538
+ }
27539
+ const inputs = [];
27540
+ for (let trial = 0; trial < trials; trial++) {
27541
+ let message2;
27542
+ try {
27543
+ const produced = await options.produce(item);
27544
+ if (produced.kind === "output") {
27545
+ if (produced.metadata === void 0) {
27546
+ inputs[trial] = { ...item.input, output: produced.output };
27547
+ continue;
27548
+ }
27549
+ if (isPlainObject2(produced.metadata)) {
27550
+ inputs[trial] = {
27551
+ ...item.input,
27552
+ output: produced.output,
27553
+ metadata: { ...item.input.metadata, ...produced.metadata }
27554
+ };
27555
+ continue;
27556
+ }
27557
+ message2 = "Producer returned invalid metadata: expected a plain object";
27558
+ } else {
27559
+ message2 = produced.reason;
27560
+ }
27561
+ } catch (error62) {
27562
+ message2 = error62 instanceof Error ? error62.message : String(error62);
27563
+ }
27564
+ failures.push({ kind: "generation-error", itemId: item.itemId, sampleIndex: trial, message: message2 });
27565
+ }
27566
+ if (inputs.length > 0) {
27567
+ const preparedItem = { ...item };
27568
+ items.push(preparedItem);
27569
+ preparedInputs.set(preparedItem, inputs);
27570
+ }
27571
+ }
27572
+ const execution = await executePreparedEvalRun(
27573
+ {
27574
+ items,
27575
+ trials,
27576
+ evaluators: [...byName.values()].map(
27577
+ (entry) => ({
27578
+ name: entry.name,
27579
+ version: entry.version,
27580
+ kind: entry.kind,
27581
+ maxJudgeTokens: entry.maxJudgeTokens?.bind(entry),
27582
+ async evaluate(input2, context) {
27583
+ return EvalScore.parse({
27584
+ ...await entry.evaluate(input2, context),
27585
+ evaluatorName: entry.name,
27586
+ evaluatorVersion: entry.version
27587
+ });
27588
+ }
27589
+ })
27590
+ ),
27591
+ ctx: { model: options.model, nowMs: () => performance.now() },
27592
+ maxJudgeTokens: options.maxJudgeTokens,
27593
+ reserveTokensPerCall: options.reserveTokensPerCall,
27594
+ concurrency: count.positive().optional().parse(options.concurrency),
27595
+ timeoutMs: options.timeoutMs,
27596
+ captureReservationFailures: true,
27597
+ onBudgetSkip(item, skipped, trial) {
27598
+ failures.push({
27599
+ kind: "skipped-for-budget",
27600
+ itemId: item.itemId,
27601
+ evaluatorName: skipped.name,
27602
+ evaluatorVersion: skipped.version,
27603
+ sampleIndex: trial
27604
+ });
27605
+ }
27606
+ },
27607
+ preparedInputs
27608
+ );
27609
+ for (const { trial, ...failure3 } of execution.failures) {
27610
+ failures.push({
27611
+ kind: "evaluator-failure",
27612
+ ...failure3,
27613
+ sampleIndex: trial,
27614
+ evaluatorVersion: byName.get(failure3.evaluatorName).version
27615
+ });
27616
+ }
27617
+ for (const failure3 of failures) reasons2.push(failure3);
27618
+ const scored = new Map(
27619
+ aggregateScoredItems(execution.scores).map((row) => [row.evaluatorName, row])
27620
+ );
27621
+ const attempted = /* @__PURE__ */ new Set([
27622
+ ...scored.keys(),
27623
+ ...execution.failures.map(({ evaluatorName }) => evaluatorName)
27624
+ ]);
27625
+ const aggregates = evaluators.map(({ name, version: version2 }) => {
27626
+ const identity = { evaluatorName: name, evaluatorVersion: version2 };
27627
+ if (!attempted.has(name)) reasons2.push({ kind: "unused-evaluator", ...identity });
27628
+ const aggregate = scored.get(name);
27629
+ if (!aggregate) {
27630
+ return {
27631
+ ...identity,
27632
+ scored: 0,
27633
+ unscored: 0,
27634
+ meanScore: null,
27635
+ passRate: null,
27636
+ itemMeanInterval: null,
27637
+ trialDisagreementShare: null,
27638
+ labelCounts: {},
27639
+ totalTokens: 0,
27640
+ meanLatencyMs: null
27641
+ };
27642
+ }
27643
+ const actual = aggregate.unscored / (aggregate.scored + aggregate.unscored);
27644
+ if (actual > maximum) reasons2.push({ kind: "unscored-share", ...identity, actual, maximum });
27645
+ return aggregate;
27646
+ });
27647
+ const metrics = /* @__PURE__ */ new Map();
27648
+ for (const row of aggregates) {
27649
+ if (row.meanScore !== null && !byName.has(`${row.evaluatorName}/mean`)) {
27650
+ metrics.set(`${row.evaluatorName}/mean`, row.meanScore);
27651
+ }
27652
+ if (row.passRate !== null && !byName.has(`${row.evaluatorName}/pass_rate`)) {
27653
+ metrics.set(`${row.evaluatorName}/pass_rate`, row.passRate.rate);
27654
+ }
27655
+ if (row.meanScore !== null) metrics.set(row.evaluatorName, row.meanScore);
27656
+ }
27657
+ const gateResults = evaluateMetricGates(metrics, gates);
27658
+ for (const gate of gateResults) {
27659
+ if (gate.reason === "missing-metric")
27660
+ reasons2.push({ kind: "missing-metric", metric: gate.metric });
27661
+ else if (!gate.passed) reasons2.push({ kind: "gate-failed", metric: gate.metric });
27662
+ }
27663
+ return LocalEvalResult.parse({
27664
+ schemaVersion: SCHEMA_VERSION,
27665
+ samplesPerCase: trials,
27666
+ metadata,
27667
+ evaluators,
27668
+ aggregates,
27669
+ cases: execution.scores.map(({ itemId, trial, score }) => ({
27670
+ itemId,
27671
+ sampleIndex: trial,
27672
+ evaluatorName: score.evaluatorName,
27673
+ evaluatorVersion: score.evaluatorVersion,
27674
+ score: score.score,
27675
+ ...score.label === void 0 ? {} : { label: score.label },
27676
+ ...score.explanation === void 0 ? {} : { rationale: score.explanation },
27677
+ ...score.tokens === void 0 ? {} : { tokens: score.tokens }
27678
+ })),
27679
+ couldNotEvaluate: failures,
27680
+ gates: gateResults,
27681
+ passed: reasons2.length === 0,
27682
+ reasons: reasons2
27683
+ });
27684
+ }
27685
+ var versionEnvelope = external_exports.object({ schemaVersion: count.positive() });
27686
+ function compareEvalBaseline(current, baseline, tolerance) {
27687
+ if (!Number.isFinite(tolerance) || tolerance < 0) {
27688
+ throw new Error("tolerance must be a finite non-negative number");
27689
+ }
27690
+ const envelope = versionEnvelope.safeParse(baseline);
27691
+ if (envelope.success && envelope.data.schemaVersion !== current.schemaVersion) {
27692
+ return { status: "refused", reason: "schema-version-mismatch" };
27693
+ }
27694
+ const parsed = LocalEvalResult.safeParse(baseline);
27695
+ if (!parsed.success) return { status: "refused", reason: "invalid-baseline" };
27696
+ const previous = parsed.data;
27697
+ if (!current.metadata.datasetHash || !previous.metadata.datasetHash) {
27698
+ return { status: "refused", reason: "missing-dataset-hash" };
27699
+ }
27700
+ if (current.metadata.datasetHash !== previous.metadata.datasetHash) {
27701
+ return { status: "refused", reason: "dataset-mismatch" };
27702
+ }
27703
+ const regressions = [];
27704
+ const priorAggregates = new Map(previous.aggregates.map((entry) => [entry.evaluatorName, entry]));
27705
+ for (const { name, version: version2 } of previous.evaluators) {
27706
+ const identity = { evaluatorName: name, evaluatorVersion: version2 };
27707
+ if (!current.evaluators.some((entry) => entry.name === name && entry.version === version2)) {
27708
+ return { status: "refused", reason: "missing-evaluator", ...identity };
27709
+ }
27710
+ const prior = priorAggregates.get(name);
27711
+ if (!prior || prior.evaluatorVersion !== version2) {
27712
+ return { status: "refused", reason: "invalid-baseline" };
27713
+ }
27714
+ if (prior.meanScore === null) continue;
27715
+ const next = current.aggregates.find(
27716
+ (entry) => entry.evaluatorName === name && entry.evaluatorVersion === version2
27717
+ )?.meanScore ?? null;
27718
+ if (next === null || prior.meanScore - next > tolerance) {
27719
+ regressions.push({ ...identity, baseline: prior.meanScore, current: next });
27720
+ }
27721
+ }
27722
+ return regressions.length ? { status: "failed", regressions } : { status: "passed" };
27723
+ }
27724
+
27725
+ // src/commands/eval-run.ts
27726
+ var optionNames = ["result", "baseline", "tolerance", "gates", "trials"];
27727
+ function message(error62) {
27728
+ return error62 instanceof Error ? error62.message : String(error62);
27729
+ }
27730
+ async function cmdEvalRun(configPath, flags) {
27731
+ try {
27732
+ const options = Object.fromEntries(
27733
+ optionNames.map((name) => {
27734
+ const value = flags[name];
27735
+ if (value !== void 0 && (typeof value !== "string" || !value.trim())) {
27736
+ throw new Error(`--${name} requires a value`);
27737
+ }
27738
+ return [name, value];
27739
+ })
27740
+ );
27741
+ const tolerance = options.tolerance === void 0 ? 0 : Number(options.tolerance);
27742
+ if (!Number.isFinite(tolerance) || tolerance < 0) {
27743
+ throw new Error("--tolerance must be a finite non-negative number");
27744
+ }
27745
+ const path = resolve(configPath);
27746
+ let config2;
27747
+ try {
27748
+ const module = await import(pathToFileURL(path).href);
27749
+ config2 = module.default;
27750
+ if (typeof config2?.dataset !== "string" || !config2.dataset.trim()) {
27751
+ throw new Error("the default export must provide a dataset path");
27752
+ }
27753
+ } catch (error62) {
27754
+ throw new Error(`Could not load eval config ${path}: ${message(error62)}`);
27755
+ }
27756
+ const dataset = await readFile(resolve(dirname(path), config2.dataset), "utf8");
27757
+ const { examples, errors } = parseJsonl(
27758
+ dataset,
27759
+ (line) => `00000000-0000-8000-8000-${line.toString(16).padStart(12, "0")}`
27760
+ );
27761
+ if (errors.length) {
27762
+ for (const error62 of errors) {
27763
+ process.stderr.write(`fx eval run: JSONL line ${error62.line}: ${error62.message}
27764
+ `);
27765
+ }
27766
+ return 1;
27767
+ }
27768
+ const result = await runEvalGate({
27769
+ ...config2,
27770
+ gates: options.gates ?? config2.gates,
27771
+ trials: options.trials === void 0 ? config2.trials : Number(options.trials),
27772
+ metadata: { ...config2.metadata, datasetHash: hashExamples(examples) },
27773
+ items: examples.map((example) => ({
27774
+ itemId: example.exampleId,
27775
+ input: {
27776
+ input: example.input,
27777
+ output: Object.hasOwn(example.metadata, "output") ? example.metadata.output : void 0,
27778
+ expectedOutput: example.expectedOutput,
27779
+ metadata: example.metadata
27780
+ },
27781
+ evaluatorNames: config2.evaluatorNames?.(example)
27782
+ }))
27783
+ });
27784
+ let baselinePassed = true;
27785
+ if (options.baseline !== void 0) {
27786
+ try {
27787
+ const baseline = JSON.parse(await readFile(options.baseline, "utf8"));
27788
+ const comparison = compareEvalBaseline(result, baseline, tolerance);
27789
+ baselinePassed = comparison.status === "passed";
27790
+ if (comparison.status === "refused") {
27791
+ process.stderr.write(`fx eval run: baseline refused: ${JSON.stringify(comparison)}
27792
+ `);
27793
+ } else if (comparison.status === "failed") {
27794
+ for (const regression of comparison.regressions) {
27795
+ process.stderr.write(
27796
+ `fx eval run: baseline regression: ${JSON.stringify(regression)}
27797
+ `
27798
+ );
27799
+ }
27800
+ }
27801
+ } catch (error62) {
27802
+ baselinePassed = false;
27803
+ process.stderr.write(`fx eval run: baseline refused: ${message(error62)}
27804
+ `);
27805
+ }
27806
+ }
27807
+ if (options.result !== void 0) {
27808
+ await writeFile(options.result, `${JSON.stringify(result, null, 2)}
27809
+ `);
27810
+ }
27811
+ for (const row of result.aggregates) {
27812
+ const interval = row.itemMeanInterval;
27813
+ const itemMean = interval ? `${interval.point} (${interval.level * 100}% interval ${interval.low} to ${interval.high})` : "n/a";
27814
+ process.stdout.write(
27815
+ `${row.evaluatorName}@${row.evaluatorVersion}: mean ${row.meanScore ?? "n/a"}, ${row.scored} scored, ${row.unscored} unscored, item mean ${itemMean}, trial disagreement ${row.trialDisagreementShare ?? "n/a"}
27816
+ `
27817
+ );
27818
+ }
27819
+ for (const reason of result.reasons) {
27820
+ process.stderr.write(`fx eval run: ${JSON.stringify(reason)}
27821
+ `);
27822
+ }
27823
+ return result.passed && baselinePassed ? 0 : 1;
27824
+ } catch (error62) {
27825
+ process.stderr.write(`fx eval run: ${message(error62)}
27826
+ `);
27827
+ return 1;
27828
+ }
27829
+ }
26811
27830
 
26812
27831
  // src/bin/fx.ts
26813
27832
  var HELP = `fx \u2014 Fabric Experiments CLI
@@ -26826,6 +27845,8 @@ COMMANDS
26826
27845
  kill <experimentId> Kill a running experiment. Requires --reason.
26827
27846
  import-mojito <dir> Import a directory of Mojito waves into Fabric YAML.
26828
27847
  preview <experimentId> Mint a signed preview link for a variant. Requires --variant.
27848
+ eval run <config-module> Run a local evaluation gate on a JSONL dataset.
27849
+ Config options include concurrency and timeoutMs.
26829
27850
  test env <action> Create, destroy, list, or reap Databricks test environments.
26830
27851
  test publish <file> Publish BDD/live/JUnit/CLI evidence to Studio Quality.
26831
27852
  test import-mlflow <id> Link a native Databricks MLflow run to Studio Quality.
@@ -26859,7 +27880,11 @@ GLOBAL FLAGS
26859
27880
  --studio-url <url> login: branded Studio URL
26860
27881
  --databricks-profile <p> Databricks CLI profile used for Apps OAuth
26861
27882
  --workspace-host <url> Databricks workspace URL for native MLflow evidence.
26862
- --gates <rules> Native MLflow metric policy, e.g. "accuracy>=0.9,toxicity<=0.05".
27883
+ --gates <rules> Local eval or MLflow metric policy, e.g. "accuracy>=0.9".
27884
+ --result <file> eval run: write versioned JSON evidence
27885
+ --baseline <file> eval run: compare with prior JSON evidence
27886
+ --tolerance <n> eval run: allowed drop in mean score (default 0)
27887
+ --trials <n> eval run: trials per case and evaluator (default 1)
26863
27888
  --no-publish push: apply actions without publishing manifest
26864
27889
  --name <name> test env: environment name (for example pr-1234)
26865
27890
  --seed <dir> test env create: JSON fixture directory
@@ -27131,6 +28156,14 @@ async function main() {
27131
28156
  local: args.flags.local === true
27132
28157
  });
27133
28158
  }
28159
+ case "eval":
28160
+ if (args.positional[0] !== "run" || args.positional.length !== 2) {
28161
+ process.stderr.write(
28162
+ "Usage: fx eval run <config-module> [--result <file>] [--baseline <file>] [--tolerance <n>] [--gates <rules>] [--trials <n>]\n"
28163
+ );
28164
+ return 1;
28165
+ }
28166
+ return cmdEvalRun(args.positional[1], args.flags);
27134
28167
  case "test":
27135
28168
  if (args.positional[0] === "import-mlflow") {
27136
28169
  if (!args.positional[1]) {