@plune-ai/cli 0.39.15 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -45,8 +45,8 @@ function machineless(raw, repoRoot, home) {
45
45
  let text = (0, import_node_util.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
46
46
  const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
47
47
  if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
48
- const own2 = pathIn(home);
49
- if (own2 !== void 0) text = text.replace(new RegExp(`${PATH_START}${own2.source}(?![\\w.-])`, own2.flags), "~");
48
+ const own3 = pathIn(home);
49
+ if (own3 !== void 0) text = text.replace(new RegExp(`${PATH_START}${own3.source}(?![\\w.-])`, own3.flags), "~");
50
50
  if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
51
51
  return text;
52
52
  }
@@ -92,12 +92,12 @@ function openJournal(path11, redact) {
92
92
  if (path11 === void 0) return NONE;
93
93
  const fd = (0, import_node_fs2.openSync)(path11, "w", 384);
94
94
  if (process.platform !== "win32") (0, import_node_fs2.fchmodSync)(fd, 384);
95
- const start = import_node_perf_hooks.performance.now();
95
+ const start2 = import_node_perf_hooks.performance.now();
96
96
  let closed = false;
97
97
  return {
98
98
  write(dir, fields) {
99
99
  if (closed) return;
100
- const dtMs = Math.round((import_node_perf_hooks.performance.now() - start) * 1e3) / 1e3;
100
+ const dtMs = Math.round((import_node_perf_hooks.performance.now() - start2) * 1e3) / 1e3;
101
101
  const line = {
102
102
  ts: (/* @__PURE__ */ new Date()).toISOString(),
103
103
  dtMs,
@@ -254,11 +254,11 @@ function maskUrl(raw) {
254
254
  } catch {
255
255
  return raw;
256
256
  }
257
- if (url.username !== "") url.username = MASK;
258
- if (url.password !== "") url.password = MASK;
257
+ if (url.username !== "") url.username = MASK2;
258
+ if (url.password !== "") url.password = MASK2;
259
259
  for (const name of [...url.searchParams.keys()])
260
- if (SECRET_QUERY.has(name.toLowerCase())) url.searchParams.set(name, MASK);
261
- return url.href.replaceAll("%2A%2A%2A", MASK);
260
+ if (SECRET_QUERY.has(name.toLowerCase())) url.searchParams.set(name, MASK2);
261
+ return url.href.replaceAll("%2A%2A%2A", MASK2);
262
262
  }
263
263
  function secretsOf(target) {
264
264
  const secrets = { values: [], named: [], urls: [] };
@@ -309,7 +309,7 @@ function createRedactor(secrets, opts = {}) {
309
309
  const ordered = longestFirst(forms);
310
310
  const urls = longestFirst(opts.url?.raw ?? []).filter((raw) => raw !== "");
311
311
  const text = (input) => ordered.reduce(
312
- (out, secret) => out.replaceAll(secret, MASK),
312
+ (out, secret) => out.replaceAll(secret, MASK2),
313
313
  urls.reduce((out, raw) => out.replaceAll(raw, opts.url.masked), input)
314
314
  );
315
315
  const value = (input, depth = 0) => {
@@ -334,7 +334,7 @@ function describeTarget(target, redact) {
334
334
  const masked = (entries, secret) => Object.fromEntries(
335
335
  Object.entries(entries).map(([name, value]) => [
336
336
  name,
337
- secret(name) ? MASK : redact.text(value)
337
+ secret(name) ? MASK2 : redact.text(value)
338
338
  ])
339
339
  );
340
340
  if (target.kind === "stdio") {
@@ -352,12 +352,12 @@ function describeTarget(target, redact) {
352
352
  headers: masked(target.headers, isSecretHeader)
353
353
  };
354
354
  }
355
- var MASK, MIN_SECRET_LENGTH, MAX_DEPTH, SECRET_HEADERS, SECRET_HEADER_PART, SECRET_ENV_PART, SECRET_QUERY, isSecretHeader, isSecretEnv, decoded, rawQuery;
355
+ var MASK2, MIN_SECRET_LENGTH, MAX_DEPTH, SECRET_HEADERS, SECRET_HEADER_PART, SECRET_ENV_PART, SECRET_QUERY, isSecretHeader, isSecretEnv, decoded, rawQuery;
356
356
  var init_redact = __esm({
357
357
  "src/mcp-testing/connect/redact.ts"() {
358
358
  "use strict";
359
359
  init_cjs_shims();
360
- MASK = "***";
360
+ MASK2 = "***";
361
361
  MIN_SECRET_LENGTH = 8;
362
362
  MAX_DEPTH = 64;
363
363
  SECRET_HEADERS = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie"]);
@@ -443,10 +443,10 @@ function readLines(stream, onLine, stats) {
443
443
  partial = rest.slice(0, STDERR_LINE_LIMIT);
444
444
  };
445
445
  return new Promise((resolve9) => {
446
- let done = false;
446
+ let done2 = false;
447
447
  const finish = () => {
448
- if (done) return;
449
- done = true;
448
+ if (done2) return;
449
+ done2 = true;
450
450
  feed(decoder.end());
451
451
  if (partial !== "") onLine(partial.endsWith("\r") ? partial.slice(0, -1) : partial);
452
452
  resolve9();
@@ -508,9 +508,9 @@ function intercept(transport, name, before) {
508
508
  });
509
509
  }
510
510
  function watchStdout(transport, journal, seen) {
511
- const start = transport.start.bind(transport);
511
+ const start2 = transport.start.bind(transport);
512
512
  transport.start = async () => {
513
- await start();
513
+ await start2();
514
514
  const stdout = transport._process?.stdout;
515
515
  if (stdout === null || stdout === void 0) return;
516
516
  (0, import_node_readline.createInterface)({ input: stdout, crlfDelay: Infinity }).on("line", (line) => {
@@ -720,7 +720,7 @@ async function openSession(config, options = {}) {
720
720
  },
721
721
  fetchForOrigin(origin) {
722
722
  const allowed = new URL(origin).origin;
723
- const own2 = target.kind !== "stdio" && new URL(target.url).origin === allowed;
723
+ const own3 = target.kind !== "stdio" && new URL(target.url).origin === allowed;
724
724
  return async (input, init) => {
725
725
  const url = new URL(input);
726
726
  if (url.origin !== allowed)
@@ -728,7 +728,7 @@ async function openSession(config, options = {}) {
728
728
  `fetchForOrigin(${allowed}) refuses a request to another origin, ${url.origin}.`
729
729
  );
730
730
  const headers = new Headers(init?.headers);
731
- if (own2) {
731
+ if (own3) {
732
732
  for (const [name, value] of Object.entries(target.headers))
733
733
  if (!headers.has(name)) headers.set(name, value);
734
734
  }
@@ -748,23 +748,23 @@ async function openSession(config, options = {}) {
748
748
  if (stdin === null || stdin === void 0 || stdin.writableEnded)
749
749
  throw spawnError !== void 0 ? await toConnectError(spawnError) : new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
750
750
  return new Promise((resolve9, reject) => {
751
- const done = () => {
751
+ const done2 = () => {
752
752
  clearTimeout(timer2);
753
753
  listeners.delete(listener);
754
754
  stopped.delete(stop);
755
755
  };
756
756
  const timer2 = setTimeout(() => {
757
- done();
757
+ done2();
758
758
  reject(noAnswer());
759
759
  }, ms);
760
760
  const listener = (line) => {
761
761
  const frame2 = parsed(line);
762
762
  if (!answers(frame2, id)) return;
763
- done();
763
+ done2();
764
764
  resolve9({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
765
765
  };
766
766
  const stop = () => {
767
- done();
767
+ done2();
768
768
  void toConnectError(spawnError ?? new Error("closed")).then(reject);
769
769
  };
770
770
  listeners.add(listener);
@@ -802,8 +802,8 @@ async function openSession(config, options = {}) {
802
802
  const reader = res.body.getReader();
803
803
  const decoder = new TextDecoder();
804
804
  for (; ; ) {
805
- const { done, value } = await reader.read();
806
- if (done) break;
805
+ const { done: done2, value } = await reader.read();
806
+ if (done2) break;
807
807
  text += decoder.decode(value, { stream: true });
808
808
  if (sse && (frame = fromEventStream(text, id)) !== void 0) break;
809
809
  if (text.length > STDIO_MESSAGE_LIMIT) break;
@@ -1065,7 +1065,7 @@ init_cjs_shims();
1065
1065
 
1066
1066
  // src/cli/commands/run.ts
1067
1067
  init_cjs_shims();
1068
- var fs5 = __toESM(require("fs"), 1);
1068
+ var fs6 = __toESM(require("fs"), 1);
1069
1069
  var path5 = __toESM(require("path"), 1);
1070
1070
 
1071
1071
  // src/config/loader.ts
@@ -1106,6 +1106,628 @@ var ConfigValidationError = class extends Error {
1106
1106
  init_cjs_shims();
1107
1107
  var import_zod = require("zod");
1108
1108
 
1109
+ // src/json-verify/compare.ts
1110
+ init_cjs_shims();
1111
+
1112
+ // src/json-verify/functions.ts
1113
+ init_cjs_shims();
1114
+
1115
+ // src/json-verify/regex.ts
1116
+ init_cjs_shims();
1117
+ var MAX_REGEX_NODES = 2e3;
1118
+ var SHORTHAND = { d: /\d/, w: /\w/, s: /\s/ };
1119
+ var CONTROL = { n: 10, r: 13, t: 9, f: 12, v: 11, "0": 0 };
1120
+ var SIMPLE_REPEAT = { "*": [0, Infinity], "+": [1, Infinity], "?": [0, 1] };
1121
+ var LINE_ENDS = /* @__PURE__ */ new Set([10, 13, 8232, 8233]);
1122
+ var QUANTIFIER = /[*+?]|\{(\d+)(?:(,)(\d*))?\}/y;
1123
+ function caseClass(code) {
1124
+ const upper = String.fromCharCode(code).toUpperCase();
1125
+ if (upper.length !== 1) return code;
1126
+ const folded = upper.charCodeAt(0);
1127
+ return code >= 128 && folded < 128 ? code : folded;
1128
+ }
1129
+ var caseClasses;
1130
+ function sameCase(code) {
1131
+ if (caseClasses === void 0) {
1132
+ const all = /* @__PURE__ */ new Map();
1133
+ for (let c = 0; c < 65536; c++) {
1134
+ const key = caseClass(c);
1135
+ const members = all.get(key);
1136
+ if (members === void 0) all.set(key, [c]);
1137
+ else members.push(c);
1138
+ }
1139
+ caseClasses = new Map([...all].filter(([, members]) => members.length > 1));
1140
+ }
1141
+ return caseClasses.get(caseClass(code)) ?? [code];
1142
+ }
1143
+ function parse(pattern, flags) {
1144
+ let i = 0;
1145
+ const fail2 = (what) => new Error(`${what} (character ${i} of the pattern)`);
1146
+ const ignoreCase = flags.includes("i");
1147
+ const fold = (test) => ignoreCase ? (code) => sameCase(code).some(test) : test;
1148
+ const literal = (code) => fold((c) => c === code);
1149
+ const shorthand = (e) => {
1150
+ const re = SHORTHAND[e.toLowerCase()];
1151
+ if (re === void 0) return void 0;
1152
+ const negated = e !== e.toLowerCase();
1153
+ return (code) => re.test(String.fromCharCode(code)) !== negated;
1154
+ };
1155
+ const escaped = (e) => {
1156
+ if (e === void 0) throw fail2("a backslash ends the pattern");
1157
+ if (e === "0" && /\d/.test(pattern[i] ?? "")) throw fail2("\\0 before a digit is not supported");
1158
+ const control = CONTROL[e];
1159
+ if (control !== void 0) return control;
1160
+ if (/[A-Za-z0-9]/.test(e)) throw fail2(`\\${e} is not supported`);
1161
+ return e.charCodeAt(0);
1162
+ };
1163
+ const classAtom = () => {
1164
+ const ch = pattern[i++];
1165
+ if (ch === void 0) throw fail2("a character class is not closed");
1166
+ if (ch !== "\\") return ch.charCodeAt(0);
1167
+ const e = pattern[i++];
1168
+ if (e === "b") return 8;
1169
+ return (e === void 0 ? void 0 : shorthand(e)) ?? escaped(e);
1170
+ };
1171
+ const parseClass = () => {
1172
+ const negated = pattern[i] === "^";
1173
+ if (negated) i++;
1174
+ const tests = [];
1175
+ while (pattern[i] !== "]") {
1176
+ const low = classAtom();
1177
+ if (typeof low !== "number") tests.push(low);
1178
+ else if (pattern[i] === "-" && pattern[i + 1] !== "]") {
1179
+ i++;
1180
+ const high = classAtom();
1181
+ if (typeof high !== "number" || high < low) throw fail2("a range in a character class is out of order");
1182
+ tests.push(fold((c) => c >= low && c <= high));
1183
+ } else tests.push(literal(low));
1184
+ }
1185
+ i++;
1186
+ return (code) => tests.some((test) => test(code)) !== negated;
1187
+ };
1188
+ const parseAtom = () => {
1189
+ const ch = pattern[i++];
1190
+ if (ch === "(") {
1191
+ if (pattern[i] === "?") {
1192
+ if (pattern[i + 1] !== ":") throw fail2("lookahead, lookbehind and named groups are not supported");
1193
+ i += 2;
1194
+ }
1195
+ const options2 = parseOptions();
1196
+ if (pattern[i] !== ")") throw fail2("a group is not closed");
1197
+ i++;
1198
+ return { t: "group", options: options2 };
1199
+ }
1200
+ if (ch === "[") return { t: "char", test: parseClass() };
1201
+ if (ch === ".") return { t: "char", test: flags.includes("s") ? () => true : (c) => !LINE_ENDS.has(c) };
1202
+ if (ch === "^" || ch === "$") return { t: "anchor", kind: ch };
1203
+ QUANTIFIER.lastIndex = i - 1;
1204
+ if (QUANTIFIER.test(pattern)) throw fail2("nothing to repeat");
1205
+ if (ch !== "\\") return { t: "char", test: literal(ch.charCodeAt(0)) };
1206
+ const e = pattern[i++];
1207
+ if (e === "b" || e === "B") return { t: "anchor", kind: e };
1208
+ const set = e === void 0 ? void 0 : shorthand(e);
1209
+ return { t: "char", test: set ?? literal(escaped(e)) };
1210
+ };
1211
+ const parseRepeat = (atom) => {
1212
+ QUANTIFIER.lastIndex = i;
1213
+ const m = QUANTIFIER.exec(pattern);
1214
+ if (m === null) return atom;
1215
+ i += m[0].length;
1216
+ if (atom.t === "anchor") throw fail2("an anchor cannot be repeated");
1217
+ const least = Number(m[1]);
1218
+ const counted = [least, m[2] === void 0 ? least : m[3] === "" ? Infinity : Number(m[3])];
1219
+ const [min, max] = SIMPLE_REPEAT[m[0]] ?? counted;
1220
+ if (max < min) throw fail2("a repeat has its numbers out of order");
1221
+ if (pattern[i] === "?") i++;
1222
+ return { t: "repeat", node: atom, min, max };
1223
+ };
1224
+ function parseOptions() {
1225
+ const options2 = [[]];
1226
+ while (i < pattern.length && pattern[i] !== ")") {
1227
+ if (pattern[i] === "|") {
1228
+ i++;
1229
+ options2.push([]);
1230
+ } else options2[options2.length - 1].push(parseRepeat(parseAtom()));
1231
+ }
1232
+ return options2;
1233
+ }
1234
+ const options = parseOptions();
1235
+ if (i < pattern.length) throw fail2('a ")" has no group to close');
1236
+ return options;
1237
+ }
1238
+ var CHAR = 0;
1239
+ var SPLIT = 1;
1240
+ var ANCHOR = 2;
1241
+ var MATCH = 3;
1242
+ var isWord = (text, at) => at >= 0 && at < text.length && /\w/.test(text[at]);
1243
+ function compileRegex(pattern, flags = "") {
1244
+ const options = parse(pattern, flags);
1245
+ const multiline = flags.includes("m");
1246
+ const states = [{ kind: MATCH, next: 0, other: 0 }];
1247
+ const tooLarge = () => new Error(`the pattern is too large once its repeats are written out (over ${MAX_REGEX_NODES} parts)`);
1248
+ const add = (state) => {
1249
+ if (states.length > MAX_REGEX_NODES) throw tooLarge();
1250
+ return states.push(state) - 1;
1251
+ };
1252
+ let built = 0;
1253
+ const build = (node, next) => {
1254
+ if (++built > MAX_REGEX_NODES) throw tooLarge();
1255
+ if (node.t === "char") return add({ kind: CHAR, next, other: 0, test: node.test });
1256
+ if (node.t === "anchor") return add({ kind: ANCHOR, next, other: 0, anchor: node.kind });
1257
+ if (node.t === "group") return buildOptions(node.options, next);
1258
+ let enter = next;
1259
+ if (node.max === Infinity) {
1260
+ enter = add({ kind: SPLIT, next: 0, other: next });
1261
+ states[enter].next = build(node.node, enter);
1262
+ } else
1263
+ for (let k = node.min; k < node.max; k++)
1264
+ enter = add({ kind: SPLIT, next: build(node.node, enter), other: enter });
1265
+ for (let k = 0; k < node.min; k++) enter = build(node.node, enter);
1266
+ return enter;
1267
+ };
1268
+ const buildOptions = (list2, next) => list2.map((sequence) => sequence.reduceRight((after, node) => build(node, after), next)).reduceRight((rest, entry) => add({ kind: SPLIT, next: entry, other: rest }));
1269
+ const start2 = buildOptions(options, 0);
1270
+ const holds = (anchor, text, at) => {
1271
+ if (anchor === "b" || anchor === "B") return isWord(text, at - 1) !== isWord(text, at) === (anchor === "b");
1272
+ const edge = anchor === "^" ? at === 0 : at === text.length;
1273
+ return edge || multiline && LINE_ENDS.has(text.charCodeAt(anchor === "^" ? at - 1 : at));
1274
+ };
1275
+ return (text) => {
1276
+ const seen = new Int32Array(states.length).fill(-1);
1277
+ let matched = false;
1278
+ const enter = (list2, from, at2) => {
1279
+ const stack = [from];
1280
+ while (stack.length > 0) {
1281
+ const s = stack.pop();
1282
+ if (seen[s] === at2) continue;
1283
+ seen[s] = at2;
1284
+ const state = states[s];
1285
+ if (state.kind === SPLIT) stack.push(state.next, state.other);
1286
+ else if (state.kind === ANCHOR) {
1287
+ if (holds(state.anchor, text, at2)) stack.push(state.next);
1288
+ } else if (state.kind === MATCH) matched = true;
1289
+ else list2.push(s);
1290
+ }
1291
+ };
1292
+ let current = [];
1293
+ let at = 0;
1294
+ enter(current, start2, 0);
1295
+ while (!matched && at < text.length) {
1296
+ const code = text.charCodeAt(at++);
1297
+ const following = [];
1298
+ for (const s of current) if (states[s].test(code)) enter(following, states[s].next, at);
1299
+ enter(following, start2, at);
1300
+ current = following;
1301
+ }
1302
+ return matched;
1303
+ };
1304
+ }
1305
+
1306
+ // src/json-verify/functions.ts
1307
+ var MAX_REGEX_INPUT = 1e4;
1308
+ var MAX_REGEX_PATTERN = 500;
1309
+ var none = (args) => args.length === 0 ? void 0 : "takes no arguments";
1310
+ var oneNumber = (args) => args.length === 1 && typeof args[0] === "number" ? void 0 : "takes one number";
1311
+ var oneLength = (args) => args.length === 1 && Number.isInteger(args[0]) && args[0] >= 0 ? void 0 : "takes one whole number, 0 or more";
1312
+ var lengthOf = (v) => typeof v === "string" || Array.isArray(v) ? v.length : void 0;
1313
+ var is = (test) => ({ args: none, test });
1314
+ var matchers = /* @__PURE__ */ new Map();
1315
+ function matcher(pattern, flags) {
1316
+ const key = `${flags}/${pattern}`;
1317
+ let compiled = matchers.get(key);
1318
+ if (compiled === void 0) {
1319
+ compiled = compileRegex(pattern, flags);
1320
+ if (matchers.size >= 100) matchers.clear();
1321
+ matchers.set(key, compiled);
1322
+ }
1323
+ return compiled;
1324
+ }
1325
+ function regexArgs(args) {
1326
+ const [pattern, flags = ""] = args;
1327
+ if (args.length < 1 || args.length > 2 || typeof pattern !== "string" || typeof flags !== "string")
1328
+ return "takes a pattern in quotes and, optionally, flags in quotes";
1329
+ if (!/^(?!.*(.).*\1)[ims]*$/.test(flags)) return `takes the flags i, m and s, each at most once; got "${flags}"`;
1330
+ if (pattern.length > MAX_REGEX_PATTERN)
1331
+ return `takes a pattern of at most ${MAX_REGEX_PATTERN} characters; got ${pattern.length}`;
1332
+ try {
1333
+ matcher(pattern, flags);
1334
+ } catch (err) {
1335
+ return `has a pattern it cannot run: ${err.message}`;
1336
+ }
1337
+ return void 0;
1338
+ }
1339
+ var CHECK_FUNCTIONS = {
1340
+ isNotNull: is((v) => v !== null),
1341
+ isString: is((v) => typeof v === "string"),
1342
+ isNumber: is((v) => typeof v === "number"),
1343
+ isBoolean: is((v) => typeof v === "boolean"),
1344
+ isArray: is((v) => Array.isArray(v)),
1345
+ isObject: is((v) => typeof v === "object" && v !== null && !Array.isArray(v)),
1346
+ matchesRegex: {
1347
+ args: regexArgs,
1348
+ test(v, [pattern, flags]) {
1349
+ if (typeof v !== "string") return false;
1350
+ if (v.length > MAX_REGEX_INPUT)
1351
+ return `the value is ${v.length} characters long and a pattern is not run on more than ${MAX_REGEX_INPUT}`;
1352
+ return matcher(pattern, flags ?? "")(v);
1353
+ }
1354
+ },
1355
+ minLength: { args: oneLength, test: (v, [n]) => (lengthOf(v) ?? -1) >= n },
1356
+ maxLength: { args: oneLength, test: (v, [n]) => (lengthOf(v) ?? Infinity) <= n },
1357
+ gt: { args: oneNumber, test: (v, [n]) => typeof v === "number" && v > n },
1358
+ lt: { args: oneNumber, test: (v, [n]) => typeof v === "number" && v < n },
1359
+ oneOf: {
1360
+ args: (args) => args.length > 0 ? void 0 : "takes at least one value",
1361
+ test: (v, args) => args.includes(v)
1362
+ }
1363
+ };
1364
+ var known = (name) => Object.prototype.hasOwnProperty.call(CHECK_FUNCTIONS, name);
1365
+ var CheckSyntaxError = class extends Error {
1366
+ constructor(message) {
1367
+ super(message);
1368
+ this.name = "CheckSyntaxError";
1369
+ }
1370
+ };
1371
+ var CALL_START = /^@([A-Za-z_]\w*)(\()?/;
1372
+ var BARE_ARG = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)$/;
1373
+ function parseArgs(s, from, name) {
1374
+ const args = [];
1375
+ const bad = (what, at) => new CheckSyntaxError(`@${name}: ${what} at character ${at + 1} of ${JSON.stringify(s)}`);
1376
+ let i = from;
1377
+ const skipSpaces = () => {
1378
+ while (s[i] === " ") i++;
1379
+ };
1380
+ skipSpaces();
1381
+ if (s[i] === ")") return [args, i + 1];
1382
+ for (; ; ) {
1383
+ const quote = s[i];
1384
+ if (quote === '"' || quote === "'") {
1385
+ let text = "";
1386
+ for (i++; s[i] !== quote; i++) {
1387
+ if (i >= s.length) throw bad("a string is not closed", from);
1388
+ if (s[i] === "\\" && s[i + 1] === quote) i++;
1389
+ text += s[i];
1390
+ }
1391
+ i++;
1392
+ args.push(text);
1393
+ } else {
1394
+ const start2 = i;
1395
+ while (i < s.length && !" ,)".includes(s[i])) i++;
1396
+ const token = s.slice(start2, i);
1397
+ if (!BARE_ARG.test(token))
1398
+ throw bad(
1399
+ `argument ${args.length + 1} must be a number, true, false, null or a string in quotes, got ${JSON.stringify(token)}`,
1400
+ start2
1401
+ );
1402
+ const value = JSON.parse(token);
1403
+ if (typeof value === "number" && !Number.isFinite(value))
1404
+ throw bad(`argument ${args.length + 1} is not a finite number, got ${JSON.stringify(token)}`, start2);
1405
+ args.push(value);
1406
+ }
1407
+ skipSpaces();
1408
+ if (s[i] === ")") return [args, i + 1];
1409
+ if (s[i] !== ",") throw bad('expected "," or ")"', i);
1410
+ i++;
1411
+ skipSpaces();
1412
+ }
1413
+ }
1414
+ function parseExpectedString(s) {
1415
+ if (s.startsWith("@@")) return { literal: s.slice(1) };
1416
+ const first2 = CALL_START.exec(s);
1417
+ if (first2 === null) return { literal: s };
1418
+ if (first2[2] === void 0) {
1419
+ const after = s[first2[0].length];
1420
+ if (known(first2[1]) && (after === void 0 || after === " "))
1421
+ throw new CheckSyntaxError(
1422
+ `@${first2[1]} needs parentheses to be a check: @${first2[1]}(); for the text itself write @${s}`
1423
+ );
1424
+ return { literal: s };
1425
+ }
1426
+ const checks = [];
1427
+ let i = 0;
1428
+ while (i < s.length) {
1429
+ const call = CALL_START.exec(s.slice(i));
1430
+ if (call === null || call[2] === void 0)
1431
+ throw new CheckSyntaxError(
1432
+ `expected a check such as @isString() at character ${i + 1} of ${JSON.stringify(s)}; for the text itself write @${s}`
1433
+ );
1434
+ const name = call[1];
1435
+ if (!known(name))
1436
+ throw new CheckSyntaxError(
1437
+ `@${name} is not a check function (known: ${Object.keys(CHECK_FUNCTIONS).join(", ")}); for the text itself write @${s}`
1438
+ );
1439
+ const [args, end] = parseArgs(s, i + call[0].length, name);
1440
+ const text = s.slice(i, end);
1441
+ const wrong = CHECK_FUNCTIONS[name].args(args);
1442
+ if (wrong !== void 0) throw new CheckSyntaxError(`@${name} ${wrong}; got ${text}`);
1443
+ checks.push({ name, args, text });
1444
+ i = end;
1445
+ if (i < s.length && s[i] !== " ")
1446
+ throw new CheckSyntaxError(`checks are separated by a space: character ${i + 1} of ${JSON.stringify(s)}`);
1447
+ while (s[i] === " ") i++;
1448
+ }
1449
+ return { checks };
1450
+ }
1451
+ function firstFailedCheck(checks, actual) {
1452
+ for (const check3 of checks) {
1453
+ const result = CHECK_FUNCTIONS[check3.name].test(actual, check3.args);
1454
+ if (result === true) continue;
1455
+ return typeof result === "string" ? { check: check3, note: result } : { check: check3 };
1456
+ }
1457
+ return void 0;
1458
+ }
1459
+
1460
+ // src/json-verify/compare.ts
1461
+ var COMPARE_MODES = ["exact", "unordered", "contains"];
1462
+ var ExpectedJsonError = class extends Error {
1463
+ constructor(path11, message) {
1464
+ super(`${path11}: ${message}`);
1465
+ this.path = path11;
1466
+ this.name = "ExpectedJsonError";
1467
+ }
1468
+ path;
1469
+ };
1470
+ var MAX_MATCH_STEPS = 2e6;
1471
+ var MAX_INDEXED_KEYS = 50;
1472
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1473
+ var own = (o, key) => Object.prototype.hasOwnProperty.call(o, key);
1474
+ var typeOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
1475
+ var PLAIN_KEY = /^[A-Za-z_$][\w$]*$/;
1476
+ var keyPath = (path11, key) => PLAIN_KEY.test(key) ? `${path11}.${key}` : `${path11}[${JSON.stringify(key)}]`;
1477
+ function readMarker(exp) {
1478
+ const keys = Object.keys(exp);
1479
+ if (own(exp, "$literal")) {
1480
+ if (keys.length !== 1)
1481
+ return 'an object with $literal must have no other key; data with a key $literal goes inside {"$literal": ...}';
1482
+ return { value: exp.$literal, literal: true };
1483
+ }
1484
+ if (!own(exp, "$mode")) return void 0;
1485
+ if (keys.length !== 2 || !own(exp, "$value"))
1486
+ return 'an object with $mode must have exactly the keys $mode and $value; data with a key $mode goes inside {"$literal": ...}';
1487
+ const mode = exp.$mode;
1488
+ if (!COMPARE_MODES.includes(mode))
1489
+ return `$mode must be one of ${COMPARE_MODES.join(", ")}; got ${JSON.stringify(exp.$mode)}`;
1490
+ return { value: exp.$value, mode, literal: false };
1491
+ }
1492
+ var MAX_EXPECTED_DEPTH = 100;
1493
+ var JSON_LEAF = /* @__PURE__ */ new Set(["string", "number", "boolean", "object"]);
1494
+ function validateExpected(expected) {
1495
+ const issues = [];
1496
+ const visit = (exp, path11, depth, literal) => {
1497
+ if (depth > MAX_EXPECTED_DEPTH) {
1498
+ issues.push({ path: path11, message: `expected is nested deeper than ${MAX_EXPECTED_DEPTH} levels` });
1499
+ } else if (Array.isArray(exp)) {
1500
+ exp.forEach((item, i) => visit(item, `${path11}[${i}]`, depth + 1, literal));
1501
+ } else if (isObject(exp)) {
1502
+ const proto = Object.getPrototypeOf(exp);
1503
+ const marker = literal ? void 0 : readMarker(exp);
1504
+ if (proto !== Object.prototype && proto !== null)
1505
+ issues.push({ path: path11, message: "an object that is not plain JSON data" });
1506
+ else if (own(exp, "__proto__"))
1507
+ issues.push({ path: keyPath(path11, "__proto__"), message: "the key __proto__ is not supported in expected" });
1508
+ else if (typeof marker === "string") issues.push({ path: path11, message: marker });
1509
+ else if (marker === void 0)
1510
+ for (const key of Object.keys(exp)) visit(exp[key], keyPath(path11, key), depth + 1, literal);
1511
+ else visit(marker.value, path11, depth + 1, marker.literal);
1512
+ } else if (!literal && typeof exp === "string") {
1513
+ try {
1514
+ parseExpectedString(exp);
1515
+ } catch (err) {
1516
+ issues.push({ path: path11, message: err.message });
1517
+ }
1518
+ } else if (!JSON_LEAF.has(typeof exp) || typeof exp === "number" && !Number.isFinite(exp)) {
1519
+ const what = typeof exp === "number" || exp === void 0 ? String(exp) : `a ${typeof exp}`;
1520
+ issues.push({ path: path11, message: `${what} is not a JSON value` });
1521
+ }
1522
+ };
1523
+ visit(expected, "$", 0, false);
1524
+ return issues;
1525
+ }
1526
+ var done = (sink) => sink.list.length >= sink.limit || sink.budget.spent !== void 0;
1527
+ function walk(exp, act, mode, path11, sink, literal) {
1528
+ if (!literal && isObject(exp)) {
1529
+ const marker = readMarker(exp);
1530
+ if (marker !== void 0) {
1531
+ walk(marker.value, act, marker.mode ?? mode, path11, sink, marker.literal);
1532
+ return;
1533
+ }
1534
+ }
1535
+ if (!literal && typeof exp === "string") {
1536
+ const parsed2 = parseExpectedString(exp);
1537
+ if ("checks" in parsed2) {
1538
+ const failed = firstFailedCheck(parsed2.checks, act);
1539
+ if (failed !== void 0)
1540
+ sink.list.push({
1541
+ path: path11,
1542
+ reason: "function",
1543
+ expected: exp,
1544
+ actual: act,
1545
+ detail: failed.note === void 0 ? failed.check.text : `${failed.check.text}: ${failed.note}`
1546
+ });
1547
+ return;
1548
+ }
1549
+ exp = parsed2.literal;
1550
+ }
1551
+ if (typeOf(exp) !== typeOf(act)) {
1552
+ sink.list.push({ path: path11, reason: "type", expected: exp, actual: act });
1553
+ } else if (Array.isArray(exp)) {
1554
+ (mode === "exact" ? walkInOrder : walkAnyOrder)(exp, act, mode, path11, sink, literal);
1555
+ } else if (isObject(exp)) {
1556
+ walkObject(exp, act, mode, path11, sink, literal);
1557
+ } else if (exp !== act) {
1558
+ sink.list.push({ path: path11, reason: "value", expected: exp, actual: act });
1559
+ }
1560
+ }
1561
+ function walkObject(exp, act, mode, path11, sink, literal) {
1562
+ const keys = Object.keys(exp);
1563
+ if (sink.limit === 1) keys.sort((a, b) => Number(!isScalar(exp[a])) - Number(!isScalar(exp[b])));
1564
+ for (const key of keys) {
1565
+ if (done(sink)) return;
1566
+ const at = keyPath(path11, key);
1567
+ if (own(act, key)) walk(exp[key], act[key], mode, at, sink, literal);
1568
+ else sink.list.push({ path: at, reason: "missing-key", expected: exp[key] });
1569
+ }
1570
+ if (mode === "contains") return;
1571
+ for (const key of Object.keys(act))
1572
+ if (!own(exp, key)) sink.list.push({ path: keyPath(path11, key), reason: "extra-key", actual: act[key] });
1573
+ }
1574
+ function walkInOrder(exp, act, mode, path11, sink, literal) {
1575
+ const shared = Math.min(exp.length, act.length);
1576
+ for (let i = 0; i < shared && !done(sink); i++) walk(exp[i], act[i], mode, `${path11}[${i}]`, sink, literal);
1577
+ for (let i = shared; i < exp.length; i++)
1578
+ sink.list.push({ path: `${path11}[${i}]`, reason: "missing-element", expected: exp[i] });
1579
+ for (let i = shared; i < act.length; i++)
1580
+ sink.list.push({ path: `${path11}[${i}]`, reason: "extra-element", actual: act[i] });
1581
+ }
1582
+ var isScalar = (v) => typeof v !== "object" || v === null;
1583
+ function plainScalar(e, literal) {
1584
+ if (!isScalar(e)) return void 0;
1585
+ if (literal || typeof e !== "string") return { value: e };
1586
+ const parsed2 = parseExpectedString(e);
1587
+ return "literal" in parsed2 ? { value: parsed2.literal } : void 0;
1588
+ }
1589
+ var scalarKey = (v) => `${typeOf(v)}:${String(v)}`;
1590
+ function walkAnyOrder(exp, act, mode, path11, sink, literal) {
1591
+ const probing = sink.limit === 1;
1592
+ if (probing && (mode === "unordered" ? exp.length !== act.length : exp.length > act.length)) {
1593
+ sink.list.push({ path: path11, reason: "no-match" });
1594
+ return;
1595
+ }
1596
+ const { budget } = sink;
1597
+ const taken = new Uint8Array(act.length);
1598
+ const unmatched = [];
1599
+ const rest = [];
1600
+ const scalars = /* @__PURE__ */ new Map();
1601
+ for (let j = act.length - 1; j >= 0; j--) {
1602
+ if (!isScalar(act[j])) continue;
1603
+ const key = scalarKey(act[j]);
1604
+ const at = scalars.get(key);
1605
+ if (at === void 0) scalars.set(key, [j]);
1606
+ else at.push(j);
1607
+ }
1608
+ exp.forEach((e, i) => {
1609
+ const plain = plainScalar(e, literal);
1610
+ if (plain === void 0) return rest.push(i);
1611
+ const j = scalars.get(scalarKey(plain.value))?.pop();
1612
+ if (j === void 0) return unmatched.push(i);
1613
+ taken[j] = 1;
1614
+ });
1615
+ if (rest.length > 0 && !(probing && unmatched.length > 0)) {
1616
+ const open2 = [];
1617
+ for (let j = 0; j < act.length; j++) if (taken[j] === 0) open2.push(j);
1618
+ const fits = /* @__PURE__ */ new Map();
1619
+ const fit = (e, c) => {
1620
+ const at = e * open2.length + c;
1621
+ let known2 = fits.get(at);
1622
+ if (known2 === void 0) {
1623
+ if (--budget.steps < 0) {
1624
+ budget.spent = {
1625
+ path: path11,
1626
+ reason: "too-large",
1627
+ detail: `matching arrays in any order took more than ${MAX_MATCH_STEPS} comparisons of elements`
1628
+ };
1629
+ return false;
1630
+ }
1631
+ const probe = { list: [], limit: 1, budget };
1632
+ walk(exp[rest[e]], act[open2[c]], mode, path11, probe, literal);
1633
+ known2 = probe.list.length === 0;
1634
+ fits.set(at, known2);
1635
+ }
1636
+ return known2;
1637
+ };
1638
+ const all = open2.map((_, c) => c);
1639
+ const index = /* @__PURE__ */ new Map();
1640
+ const withValue = (key, value) => {
1641
+ let byValue = index.get(key);
1642
+ if (byValue === void 0) {
1643
+ if (index.size === MAX_INDEXED_KEYS) return void 0;
1644
+ byValue = /* @__PURE__ */ new Map();
1645
+ for (let c = 0; c < open2.length; c++) {
1646
+ const a = act[open2[c]];
1647
+ if (!isObject(a) || !own(a, key) || !isScalar(a[key])) continue;
1648
+ const list2 = byValue.get(scalarKey(a[key]));
1649
+ if (list2 === void 0) byValue.set(scalarKey(a[key]), [c]);
1650
+ else list2.push(c);
1651
+ }
1652
+ index.set(key, byValue);
1653
+ }
1654
+ return byValue.get(value) ?? [];
1655
+ };
1656
+ const lists = /* @__PURE__ */ new Map();
1657
+ const candidates = (e) => {
1658
+ let best = lists.get(e);
1659
+ if (best !== void 0) return best;
1660
+ best = all;
1661
+ const x = exp[rest[e]];
1662
+ if (isObject(x) && (literal || readMarker(x) === void 0))
1663
+ for (const key of Object.keys(x)) {
1664
+ const plain = plainScalar(x[key], literal);
1665
+ const list2 = plain === void 0 ? void 0 : withValue(key, scalarKey(plain.value));
1666
+ if (list2 !== void 0 && list2.length < best.length) best = list2;
1667
+ }
1668
+ lists.set(e, best);
1669
+ return best;
1670
+ };
1671
+ const holder = new Int32Array(open2.length).fill(-1);
1672
+ const seen = new Int32Array(open2.length).fill(-1);
1673
+ const place = (root) => {
1674
+ const elements = [root];
1675
+ const tried = [0];
1676
+ const reached = [];
1677
+ while (elements.length > 0) {
1678
+ const top = elements.length - 1;
1679
+ const e = elements[top];
1680
+ const list2 = candidates(e);
1681
+ let deeper = false;
1682
+ while (!deeper && tried[top] < list2.length) {
1683
+ const c = list2[(e + tried[top]++) % list2.length];
1684
+ if (seen[c] === root) continue;
1685
+ if (!fit(e, c)) {
1686
+ if (budget.spent !== void 0) return false;
1687
+ continue;
1688
+ }
1689
+ seen[c] = root;
1690
+ reached[top] = c;
1691
+ if (holder[c] === -1) {
1692
+ for (let k = top; k >= 0; k--) holder[reached[k]] = elements[k];
1693
+ return true;
1694
+ }
1695
+ elements.push(holder[c]);
1696
+ tried.push(0);
1697
+ deeper = true;
1698
+ }
1699
+ if (!deeper) {
1700
+ elements.pop();
1701
+ tried.pop();
1702
+ }
1703
+ }
1704
+ return false;
1705
+ };
1706
+ for (let e = 0; e < rest.length; e++) {
1707
+ const placed = place(e);
1708
+ if (budget.spent !== void 0) return;
1709
+ if (placed) continue;
1710
+ unmatched.push(rest[e]);
1711
+ if (probing) break;
1712
+ }
1713
+ holder.forEach((e, c) => {
1714
+ if (e !== -1) taken[open2[c]] = 1;
1715
+ });
1716
+ }
1717
+ for (const i of unmatched.sort((a, b) => a - b))
1718
+ sink.list.push({ path: `${path11}[${i}]`, reason: "no-match", expected: exp[i] });
1719
+ if (mode === "contains") return;
1720
+ for (let j = 0; j < act.length; j++)
1721
+ if (taken[j] === 0) sink.list.push({ path: `${path11}[${j}]`, reason: "extra-element", actual: act[j] });
1722
+ }
1723
+ function compareJson(expected, actual, options = {}) {
1724
+ const issue = validateExpected(expected)[0];
1725
+ if (issue !== void 0) throw new ExpectedJsonError(issue.path, issue.message);
1726
+ const sink = { list: [], limit: Infinity, budget: { steps: MAX_MATCH_STEPS } };
1727
+ walk(expected, actual, options.mode ?? "exact", "$", sink, false);
1728
+ return sink.budget.spent === void 0 ? sink.list : [sink.budget.spent];
1729
+ }
1730
+
1109
1731
  // src/util/duration.ts
1110
1732
  init_cjs_shims();
1111
1733
  var MAX_TIMER_MS = 2147483647;
@@ -1172,9 +1794,23 @@ var jsonSchemaAssertionSchema = import_zod.z.object({
1172
1794
  schema: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()),
1173
1795
  extract: import_zod.z.enum(["auto", "strict"]).optional()
1174
1796
  });
1797
+ var jsonVerifyAssertionSchema = import_zod.z.strictObject({
1798
+ type: import_zod.z.literal("json-verify"),
1799
+ // Optional to the parser so that a missing one gets the message below, not "Invalid input".
1800
+ expected: import_zod.z.any().optional(),
1801
+ mode: import_zod.z.enum(COMPARE_MODES).optional(),
1802
+ extract: import_zod.z.enum(["auto", "strict"]).optional()
1803
+ }).superRefine((a, ctx) => {
1804
+ if (a.expected === void 0)
1805
+ ctx.addIssue({ code: "custom", path: ["expected"], message: "expected is required (null is written as null)" });
1806
+ else
1807
+ for (const issue of validateExpected(a.expected))
1808
+ ctx.addIssue({ code: "custom", path: ["expected"], message: `${issue.path}: ${issue.message}` });
1809
+ });
1175
1810
  var jevJudgeSchema = import_zod.z.strictObject({
1176
1811
  type: import_zod.z.literal("jev"),
1177
- model: import_zod.z.string().min(1),
1812
+ // A full version, never an alias: `jev-latest` would change the judge under a run without a word.
1813
+ model: import_zod.z.string().regex(/^jev-\d+\.\d+\.\d+$/, "must be a full Jev version such as jev-1.14.0; an alias such as jev-latest is not taken"),
1178
1814
  timeout: providerTimeoutSchema.optional()
1179
1815
  });
1180
1816
  var partialProviderSchema = providerConfigSchema.partial();
@@ -1269,6 +1905,7 @@ var assertionConfigSchema = import_zod.z.discriminatedUnion("type", [
1269
1905
  containsAnyAssertionSchema,
1270
1906
  containsAllAssertionSchema,
1271
1907
  jsonSchemaAssertionSchema,
1908
+ jsonVerifyAssertionSchema,
1272
1909
  llmJudgeAssertionSchema,
1273
1910
  semanticSimilarityAssertionSchema,
1274
1911
  faithfulnessAssertionSchema,
@@ -1302,14 +1939,14 @@ var mcpServersSchema = import_zod.z.record(import_zod.z.string().min(1), mcpServ
1302
1939
  for (const [name, server] of Object.entries(servers)) {
1303
1940
  const issue = (message) => ctx.addIssue({ code: "custom", path: [name], message });
1304
1941
  const stdio = server.command !== void 0;
1305
- const http = server.url !== void 0;
1306
- if (stdio && http)
1942
+ const http2 = server.url !== void 0;
1943
+ if (stdio && http2)
1307
1944
  issue(`server "${name}" has both command and url; give command (stdio) or url (HTTP), not both`);
1308
- else if (!stdio && !http)
1945
+ else if (!stdio && !http2)
1309
1946
  issue(`server "${name}" needs command (a stdio server) or url (an HTTP server)`);
1310
1947
  else if (stdio && server.headers !== void 0)
1311
1948
  issue(`server "${name}": headers are for a server at url, not one started with command`);
1312
- else if (http && (server.args ?? server.env ?? server.cwd) !== void 0)
1949
+ else if (http2 && (server.args ?? server.env ?? server.cwd) !== void 0)
1313
1950
  issue(`server "${name}": args, env and cwd are for a server started with command, not one at url`);
1314
1951
  }
1315
1952
  });
@@ -1329,7 +1966,9 @@ var evalConfigSchema = import_zod.z.object({
1329
1966
  dataset: datasetRefSchema,
1330
1967
  assertions: import_zod.z.array(assertionConfigSchema),
1331
1968
  ...evalRepeatsShape,
1332
- mcp: evalMcpSchema.optional()
1969
+ mcp: evalMcpSchema.optional(),
1970
+ // The path of a stub file; the file itself is read and checked when the run starts.
1971
+ stubs: import_zod.z.string().min(1).optional()
1333
1972
  }).refine(
1334
1973
  (data) => !(data.prompt !== void 0 && data.prompt_file !== void 0),
1335
1974
  { message: "prompt and prompt_file are mutually exclusive" }
@@ -1374,6 +2013,12 @@ var pluneConfigSchema = import_zod.z.object({
1374
2013
  });
1375
2014
  }
1376
2015
  config.evals.forEach((evalConfig, i) => {
2016
+ if (evalConfig.stubs !== void 0 && evalConfig.mcp !== void 0)
2017
+ ctx.addIssue({
2018
+ code: "custom",
2019
+ path: ["evals", i, "stubs"],
2020
+ message: `eval "${evalConfig.id}" has both stubs and mcp: stubs answer the model call of an eval without mcp`
2021
+ });
1377
2022
  const server = evalConfig.mcp?.server;
1378
2023
  if (server === void 0) {
1379
2024
  const misplaced = (assertions, path11) => assertions.forEach((a, j) => {
@@ -1397,8 +2042,8 @@ var pluneConfigSchema = import_zod.z.object({
1397
2042
  });
1398
2043
  }).transform(({ provider, ...rest }) => {
1399
2044
  if (!Array.isArray(provider)) return { provider, ...rest };
1400
- const [first, ...others] = provider;
1401
- return others.length === 0 ? { provider: first, ...rest } : { provider: first, providers: provider, ...rest };
2045
+ const [first2, ...others] = provider;
2046
+ return others.length === 0 ? { provider: first2, ...rest } : { provider: first2, providers: provider, ...rest };
1402
2047
  });
1403
2048
 
1404
2049
  // src/config/env-overrides.ts
@@ -1767,6 +2412,9 @@ init_cjs_shims();
1767
2412
  // src/providers/prices.ts
1768
2413
  init_cjs_shims();
1769
2414
  var PRICE_TABLE = {
2415
+ // TypeSafe Jev, the experimental judge of `llm-judge`: input tokens only, its output is not billed.
2416
+ // Source: docs.typesafe.ai, read on 2026-11-24 (USD 0.042 per million input tokens).
2417
+ "jev-1.14.0": { input_per_1k_usd: 42e-6, output_per_1k_usd: 0 },
1770
2418
  // Anthropic, current models. Source: platform.claude.com/docs/en/about-claude/pricing — base
1771
2419
  // input and output tokens per million, read on 2026-09-29, kept here per thousand.
1772
2420
  "claude-fable-5-1": { input_per_1k_usd: 0.01, output_per_1k_usd: 0.05 },
@@ -1890,7 +2538,7 @@ function warnReasoningEffortNotSent(model, effort) {
1890
2538
  `
1891
2539
  );
1892
2540
  }
1893
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2541
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1894
2542
  function toAnthropicMessages(messages) {
1895
2543
  return messages.map((m) => {
1896
2544
  if (m.role === "user") return { role: "user", content: m.content };
@@ -1912,13 +2560,13 @@ function toAnthropicMessages(messages) {
1912
2560
  type: "tool_use",
1913
2561
  id: c.id,
1914
2562
  name: c.name,
1915
- input: isObject(c.args) ? c.args : {}
2563
+ input: isObject2(c.args) ? c.args : {}
1916
2564
  }))
1917
2565
  ]
1918
2566
  };
1919
2567
  });
1920
2568
  }
1921
- function makeAnthropicProvider(config, env, pricing) {
2569
+ function makeAnthropicProvider(config, env, pricing, stubOrigin) {
1922
2570
  const apiKey = env[ENV_VAR];
1923
2571
  if (apiKey === void 0 || apiKey.trim() === "") {
1924
2572
  throw new AuthError(
@@ -1929,6 +2577,8 @@ function makeAnthropicProvider(config, env, pricing) {
1929
2577
  const client = new import_sdk.default({
1930
2578
  apiKey,
1931
2579
  maxRetries: 0,
2580
+ // The client adds `/v1/messages` itself.
2581
+ ...stubOrigin !== void 0 ? { baseURL: stubOrigin } : {},
1932
2582
  ...config.timeout !== void 0 ? { timeout: config.timeout } : {}
1933
2583
  });
1934
2584
  const maxRetries = config.max_retries ?? DEFAULT_MAX_RETRIES;
@@ -2122,12 +2772,13 @@ function makeOpenAiCompatibleProvider(opts) {
2122
2772
  }
2123
2773
  };
2124
2774
  }
2125
- function makeOpenAiProvider(config, env, pricing) {
2775
+ function makeOpenAiProvider(config, env, pricing, stubOrigin) {
2126
2776
  return makeOpenAiCompatibleProvider({
2127
2777
  config,
2128
2778
  env,
2129
2779
  pricing,
2130
2780
  apiKeyEnv: "OPENAI_API_KEY",
2781
+ ...stubOrigin !== void 0 ? { baseURL: `${stubOrigin}/v1` } : {},
2131
2782
  maxCompletionTokens: true,
2132
2783
  sendsReasoningEffort: true
2133
2784
  });
@@ -2136,13 +2787,13 @@ function makeOpenAiProvider(config, env, pricing) {
2136
2787
  // src/providers/openrouter.ts
2137
2788
  init_cjs_shims();
2138
2789
  var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
2139
- function makeOpenRouterProvider(config, env, pricing) {
2790
+ function makeOpenRouterProvider(config, env, pricing, stubOrigin) {
2140
2791
  return makeOpenAiCompatibleProvider({
2141
2792
  config,
2142
2793
  env,
2143
2794
  pricing,
2144
2795
  apiKeyEnv: "OPENROUTER_API_KEY",
2145
- baseURL: OPENROUTER_BASE_URL,
2796
+ baseURL: stubOrigin !== void 0 ? `${stubOrigin}/api/v1` : OPENROUTER_BASE_URL,
2146
2797
  reportsCost: true
2147
2798
  // OpenRouter reports the call's actual cost via usage.cost (ADR-PRC02)
2148
2799
  });
@@ -2158,13 +2809,13 @@ function createProviderRegistry() {
2158
2809
  }
2159
2810
  factories.set(name, factory);
2160
2811
  },
2161
- resolve(name, config, env, pricing) {
2812
+ resolve(name, config, env, pricing, stubOrigin) {
2162
2813
  const factory = factories.get(name);
2163
2814
  if (factory === void 0) {
2164
- const known = [...factories.keys()].join(", ") || "(none)";
2165
- throw new Error(`Unknown provider type "${name}". Registered providers: ${known}.`);
2815
+ const known2 = [...factories.keys()].join(", ") || "(none)";
2816
+ throw new Error(`Unknown provider type "${name}". Registered providers: ${known2}.`);
2166
2817
  }
2167
- return factory(config, env, pricing);
2818
+ return factory(config, env, pricing, stubOrigin);
2168
2819
  },
2169
2820
  has(name) {
2170
2821
  return factories.has(name);
@@ -2178,8 +2829,8 @@ function createDefaultRegistry() {
2178
2829
  registry.register("openrouter", makeOpenRouterProvider);
2179
2830
  return registry;
2180
2831
  }
2181
- function getProvider(config, env, pricing) {
2182
- return createDefaultRegistry().resolve(config.type, config, env, pricing);
2832
+ function getProvider(config, env, pricing, stubOrigin) {
2833
+ return createDefaultRegistry().resolve(config.type, config, env, pricing, stubOrigin);
2183
2834
  }
2184
2835
 
2185
2836
  // src/providers/estimate.ts
@@ -2519,7 +3170,7 @@ init_cjs_shims();
2519
3170
 
2520
3171
  // src/orchestrator/run.ts
2521
3172
  init_cjs_shims();
2522
- var fs3 = __toESM(require("fs"), 1);
3173
+ var fs4 = __toESM(require("fs"), 1);
2523
3174
  var path3 = __toESM(require("path"), 1);
2524
3175
 
2525
3176
  // src/assertions/json-extract.ts
@@ -2555,23 +3206,23 @@ function* balancedRuns(s) {
2555
3206
  while (i < s.length) {
2556
3207
  const rel = s.slice(i).search(/[{[]/);
2557
3208
  if (rel === -1) return;
2558
- const start = i + rel;
2559
- const run = balancedFrom(s, start);
3209
+ const start2 = i + rel;
3210
+ const run = balancedFrom(s, start2);
2560
3211
  if (run === null) {
2561
- i = start + 1;
3212
+ i = start2 + 1;
2562
3213
  } else {
2563
3214
  yield run;
2564
- i = start + run.length;
3215
+ i = start2 + run.length;
2565
3216
  }
2566
3217
  }
2567
3218
  }
2568
- function balancedFrom(s, start) {
2569
- const open2 = s[start];
3219
+ function balancedFrom(s, start2) {
3220
+ const open2 = s[start2];
2570
3221
  const close = open2 === "{" ? "}" : "]";
2571
3222
  let depth = 0;
2572
3223
  let inString = false;
2573
3224
  let escaped = false;
2574
- for (let i = start; i < s.length; i++) {
3225
+ for (let i = start2; i < s.length; i++) {
2575
3226
  const ch = s[i];
2576
3227
  if (inString) {
2577
3228
  if (escaped) escaped = false;
@@ -2585,7 +3236,7 @@ function balancedFrom(s, start) {
2585
3236
  depth++;
2586
3237
  } else if (ch === close) {
2587
3238
  depth--;
2588
- if (depth === 0) return s.slice(start, i + 1);
3239
+ if (depth === 0) return s.slice(start2, i + 1);
2589
3240
  }
2590
3241
  }
2591
3242
  return null;
@@ -2714,6 +3365,93 @@ var jsonSchema = {
2714
3365
  }
2715
3366
  };
2716
3367
 
3368
+ // src/assertions/json-verify.ts
3369
+ init_cjs_shims();
3370
+
3371
+ // src/json-verify/format.ts
3372
+ init_cjs_shims();
3373
+ var MAX_FRAGMENT = 120;
3374
+ var MAX_FRAGMENT_DEPTH = 6;
3375
+ var MAX_LISTED = 10;
3376
+ var typeOf2 = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
3377
+ function fragment(value) {
3378
+ let out = "";
3379
+ const write = (v, depth) => {
3380
+ if (typeof v !== "object" || v === null) {
3381
+ out += JSON.stringify(typeof v === "string" ? v.slice(0, MAX_FRAGMENT) : v);
3382
+ } else if (depth === MAX_FRAGMENT_DEPTH) {
3383
+ out += "...";
3384
+ } else {
3385
+ const list2 = Array.isArray(v);
3386
+ out += list2 ? "[" : "{";
3387
+ let n = 0;
3388
+ for (const [key, item] of list2 ? v.entries() : Object.entries(v)) {
3389
+ if (out.length > MAX_FRAGMENT) return;
3390
+ if (n++ > 0) out += ",";
3391
+ if (!list2) out += `${JSON.stringify(key)}:`;
3392
+ write(item, depth + 1);
3393
+ }
3394
+ out += list2 ? "]" : "}";
3395
+ }
3396
+ };
3397
+ write(value, 0);
3398
+ if (out.length <= MAX_FRAGMENT) return out;
3399
+ const last = out.charCodeAt(MAX_FRAGMENT - 1);
3400
+ const end = last >= 55296 && last <= 56319 ? MAX_FRAGMENT - 1 : MAX_FRAGMENT;
3401
+ return `${out.slice(0, end)}...`;
3402
+ }
3403
+ function reasonText(m) {
3404
+ switch (m.reason) {
3405
+ case "missing-key":
3406
+ return "missing key";
3407
+ case "extra-key":
3408
+ return "extra key";
3409
+ case "type":
3410
+ return `type differs: expected ${typeOf2(m.expected)}, got ${typeOf2(m.actual)}`;
3411
+ case "value":
3412
+ return "value differs";
3413
+ case "function":
3414
+ return `function not satisfied: ${m.detail}`;
3415
+ case "missing-element":
3416
+ return "missing element";
3417
+ case "extra-element":
3418
+ return "extra element";
3419
+ case "no-match":
3420
+ return "no match for an array element";
3421
+ case "too-large":
3422
+ return `too large: ${m.detail}`;
3423
+ }
3424
+ }
3425
+ function formatMismatches(list2) {
3426
+ if (list2.length === 0) return "";
3427
+ const lines = [`${list2.length} ${list2.length === 1 ? "mismatch" : "mismatches"}`];
3428
+ for (const m of list2.slice(0, MAX_LISTED)) {
3429
+ lines.push(` ${m.path}: ${reasonText(m)}`);
3430
+ if (m.expected !== void 0) lines.push(` expected: ${fragment(m.expected)}`);
3431
+ if (m.actual !== void 0) lines.push(` actual: ${fragment(m.actual)}`);
3432
+ }
3433
+ if (list2.length > MAX_LISTED) lines.push(` and ${list2.length - MAX_LISTED} more`);
3434
+ return lines.join("\n");
3435
+ }
3436
+
3437
+ // src/assertions/json-verify.ts
3438
+ var jsonVerify = {
3439
+ run(ctx) {
3440
+ const extract = ctx.params.extract ?? "auto";
3441
+ const extracted = extractJson(ctx.output, extract);
3442
+ if (!extracted.ok) {
3443
+ return Promise.resolve({
3444
+ passed: false,
3445
+ reason: `output is not valid JSON (extract mode: ${extract})`
3446
+ });
3447
+ }
3448
+ const mismatches = compareJson(ctx.params.expected, extracted.value, { mode: ctx.params.mode ?? "exact" });
3449
+ return Promise.resolve(
3450
+ mismatches.length === 0 ? { passed: true } : { passed: false, reason: formatMismatches(mismatches) }
3451
+ );
3452
+ }
3453
+ };
3454
+
2717
3455
  // src/assertions/semantic-similarity.ts
2718
3456
  init_cjs_shims();
2719
3457
  var DEFAULT_THRESHOLD = 0.8;
@@ -2806,7 +3544,7 @@ var llmJudge = {
2806
3544
  const criteria = interpolate(ctx.params.criteria, ctx);
2807
3545
  const threshold = ctx.params.pass_threshold ?? DEFAULT_PASS_THRESHOLD;
2808
3546
  if (ctx.judge.decide !== void 0) {
2809
- const p = await ctx.judge.decide({
3547
+ const { probability: p } = await ctx.judge.decide({
2810
3548
  criteria,
2811
3549
  output: ctx.output,
2812
3550
  ...ctx.input !== void 0 ? { input: ctx.input } : {}
@@ -3124,9 +3862,9 @@ var firstTool = check((ctx) => {
3124
3862
  const { tool } = ctx.params;
3125
3863
  const t = transcriptOf("first-tool", ctx);
3126
3864
  checkNames("first-tool", t, [tool]);
3127
- const first = callsOf(t)[0];
3128
- if (first?.call.name === tool) return pass;
3129
- const got = first === void 0 ? "no tool call at all: the model answered without one" : describeCall(first);
3865
+ const first2 = callsOf(t)[0];
3866
+ if (first2?.call.name === tool) return pass;
3867
+ const got = first2 === void 0 ? "no tool call at all: the model answered without one" : describeCall(first2);
3130
3868
  return fail(
3131
3869
  `expected the first call to be "${tool}"; got ${got}; check that the prompt and the tool's description point the model to it first`
3132
3870
  );
@@ -3317,8 +4055,8 @@ function createAssertionRegistry() {
3317
4055
  resolve(type) {
3318
4056
  const impl = impls.get(type);
3319
4057
  if (impl === void 0) {
3320
- const known = [...impls.keys()].join(", ") || "(none)";
3321
- throw new Error(`Unknown assertion type "${type}". Registered: ${known}.`);
4058
+ const known2 = [...impls.keys()].join(", ") || "(none)";
4059
+ throw new Error(`Unknown assertion type "${type}". Registered: ${known2}.`);
3322
4060
  }
3323
4061
  return impl;
3324
4062
  },
@@ -3337,6 +4075,7 @@ function createDefaultRegistry2() {
3337
4075
  registry.register("contains-any", containsAny);
3338
4076
  registry.register("contains-all", containsAll);
3339
4077
  registry.register("json-schema", jsonSchema);
4078
+ registry.register("json-verify", jsonVerify);
3340
4079
  registry.register("semantic-similarity", semanticSimilarity);
3341
4080
  registry.register("llm-judge", llmJudge);
3342
4081
  registry.register("faithfulness", faithfulness);
@@ -3372,6 +4111,7 @@ var ASSERTION_CLASSES = {
3372
4111
  "contains-any": "deterministic",
3373
4112
  "contains-all": "deterministic",
3374
4113
  "json-schema": "deterministic",
4114
+ "json-verify": "deterministic",
3375
4115
  // A score against the author's threshold. They decide the row as they always have.
3376
4116
  "semantic-similarity": "measure",
3377
4117
  "llm-judge": "measure",
@@ -3495,6 +4235,13 @@ function rowStatus(row) {
3495
4235
  if (row.error !== void 0) return "errored";
3496
4236
  return row.assertions.every((a) => a.passed) ? "passed" : "failed";
3497
4237
  }
4238
+ function stubbedEvals(run) {
4239
+ return run.evals.filter((ev) => ev.stubs !== void 0 || ev.rows.some((row) => row.stubbed === true)).map((ev) => ev.id);
4240
+ }
4241
+ function baseEvalId(ev) {
4242
+ const suffix = ev.provider === void 0 ? "" : `@${ev.provider.model}`;
4243
+ return suffix !== "" && ev.id.endsWith(suffix) ? ev.id.slice(0, -suffix.length) : ev.id;
4244
+ }
3498
4245
 
3499
4246
  // src/orchestrator/agent.ts
3500
4247
  init_cjs_shims();
@@ -3536,7 +4283,7 @@ var CAMEL = /[a-z0-9](?:Id|Ids|Uuid|Key|Slug|Number|Ref|Identifier)$/;
3536
4283
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3537
4284
  var isIdKey = (key) => WHOLE.test(key) || SNAKE.test(key) || CAMEL.test(key);
3538
4285
  var isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3539
- var isScalar = (v) => typeof v === "string" && v !== "" || typeof v === "number" && Number.isFinite(v);
4286
+ var isScalar2 = (v) => typeof v === "string" && v !== "" || typeof v === "number" && Number.isFinite(v);
3540
4287
  var EMAIL = /@/;
3541
4288
  function segment(key) {
3542
4289
  const plain = /^[A-Za-z_][\w-]*$/.test(key) && key.length <= 40 && !UUID.test(key) && !EMAIL.test(key);
@@ -3551,7 +4298,7 @@ function noteValue(out, v, at) {
3551
4298
  where.add(at);
3552
4299
  out.values.set(h, where);
3553
4300
  }
3554
- function walk(value, path11, depth, out) {
4301
+ function walk2(value, path11, depth, out) {
3555
4302
  if (depth > SCAN_DEPTH) return;
3556
4303
  if (typeof value === "string" && UUID.test(value)) {
3557
4304
  const at = cap(path11 === "" ? "(root)" : path11);
@@ -3559,17 +4306,17 @@ function walk(value, path11, depth, out) {
3559
4306
  noteValue(out, value, at);
3560
4307
  }
3561
4308
  if (Array.isArray(value)) {
3562
- for (const item of value.slice(0, SCAN_ITEMS)) walk(item, `${path11}[]`, depth + 1, out);
4309
+ for (const item of value.slice(0, SCAN_ITEMS)) walk2(item, `${path11}[]`, depth + 1, out);
3563
4310
  return;
3564
4311
  }
3565
4312
  if (!isRecord3(value)) return;
3566
4313
  for (const [key, v] of Object.entries(value)) {
3567
4314
  const at = cap(path11 === "" ? segment(key) : `${path11}.${segment(key)}`);
3568
- if (isIdKey(key) && (isScalar(v) || Array.isArray(v) && v.length > 0 && v.every(isScalar))) {
4315
+ if (isIdKey(key) && (isScalar2(v) || Array.isArray(v) && v.length > 0 && v.every(isScalar2))) {
3569
4316
  out.paths.add(at);
3570
4317
  for (const x of Array.isArray(v) ? v : [v]) noteValue(out, x, at);
3571
4318
  }
3572
- walk(v, at, depth + 1, out);
4319
+ walk2(v, at, depth + 1, out);
3573
4320
  }
3574
4321
  }
3575
4322
  function scanIds(result) {
@@ -3578,13 +4325,13 @@ function scanIds(result) {
3578
4325
  if (isRecord3(result)) {
3579
4326
  if (result.structuredContent !== void 0) {
3580
4327
  readable = true;
3581
- walk(result.structuredContent, "", 0, found);
4328
+ walk2(result.structuredContent, "", 0, found);
3582
4329
  }
3583
4330
  if (Array.isArray(result.content))
3584
4331
  for (const block of result.content) {
3585
4332
  if (!isRecord3(block) || block.type !== "text" || typeof block.text !== "string") continue;
3586
4333
  try {
3587
- walk(JSON.parse(block.text), "", 0, found);
4334
+ walk2(JSON.parse(block.text), "", 0, found);
3588
4335
  readable = true;
3589
4336
  } catch {
3590
4337
  }
@@ -3627,7 +4374,7 @@ function strip(value, depth, st) {
3627
4374
  for (const [key, v] of Object.entries(value)) {
3628
4375
  let name = redactUuids(key);
3629
4376
  for (let n = 2; name !== key && Object.hasOwn(out, name); n++) name = `${ID_MARK}#${n}`;
3630
- out[name] = isIdKey(key) && (isScalar(v) || Array.isArray(v) && v.length > 0 && v.every(isScalar)) ? Array.isArray(v) ? v.map(() => ID_MARK) : ID_MARK : strip(v, depth + 1, st);
4377
+ out[name] = isIdKey(key) && (isScalar2(v) || Array.isArray(v) && v.length > 0 && v.every(isScalar2)) ? Array.isArray(v) ? v.map(() => ID_MARK) : ID_MARK : strip(v, depth + 1, st);
3631
4378
  }
3632
4379
  return out;
3633
4380
  }
@@ -3865,8 +4612,8 @@ async function runAgentRow(p) {
3865
4612
  );
3866
4613
  for (const t of listed) {
3867
4614
  const isOffered = offered.includes(t);
3868
- const known = transcript.tools.find((k) => k.name === t.name);
3869
- if (known !== void 0) known.offered ||= isOffered;
4615
+ const known2 = transcript.tools.find((k) => k.name === t.name);
4616
+ if (known2 !== void 0) known2.offered ||= isOffered;
3870
4617
  else
3871
4618
  transcript.tools.push({
3872
4619
  name: t.name,
@@ -4111,6 +4858,200 @@ async function runAgentRow(p) {
4111
4858
  };
4112
4859
  }
4113
4860
 
4861
+ // src/mock/schema.ts
4862
+ init_cjs_shims();
4863
+ var fs3 = __toESM(require("fs/promises"), 1);
4864
+ var import_node_http = require("http");
4865
+ var import_yaml2 = require("yaml");
4866
+ var import_zod3 = require("zod");
4867
+ var STUB_FILE_VERSION = 1;
4868
+ var sseChunkSchema = import_zod3.z.union([
4869
+ import_zod3.z.string(),
4870
+ import_zod3.z.strictObject({ event: import_zod3.z.string().min(1).optional(), data: import_zod3.z.unknown() })
4871
+ ]);
4872
+ var responseSchema = import_zod3.z.strictObject({
4873
+ status: import_zod3.z.number().int().min(200).max(599).default(200),
4874
+ // Checked with the checks Node runs when it sends them, so a bad one fails here and not at a request.
4875
+ headers: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.string()).superRefine((headers, ctx) => {
4876
+ for (const [name, value] of Object.entries(headers)) {
4877
+ const check3 = (what, validate) => {
4878
+ try {
4879
+ validate();
4880
+ } catch {
4881
+ ctx.addIssue({ code: "custom", message: `not a valid header ${what}`, path: [name] });
4882
+ }
4883
+ };
4884
+ check3("name", () => (0, import_node_http.validateHeaderName)(name));
4885
+ check3("value", () => (0, import_node_http.validateHeaderValue)(name, value));
4886
+ }
4887
+ }).default({}),
4888
+ json: import_zod3.z.unknown().optional(),
4889
+ text: import_zod3.z.string().optional(),
4890
+ sse: import_zod3.z.array(sseChunkSchema).optional()
4891
+ }).superRefine((r, ctx) => {
4892
+ const bodies = ["json", "text", "sse"].filter((k) => r[k] !== void 0);
4893
+ if (bodies.length > 1)
4894
+ ctx.addIssue({
4895
+ code: "custom",
4896
+ message: `give one body, not ${bodies.join(" and ")}`,
4897
+ path: [bodies[1]]
4898
+ });
4899
+ });
4900
+ var first = import_zod3.z.number().int().positive().optional();
4901
+ var failureSchema = import_zod3.z.discriminatedUnion("type", [
4902
+ // The request is read and never answered, until the client gives up or the scope closes.
4903
+ import_zod3.z.strictObject({ type: import_zod3.z.literal("timeout"), first }),
4904
+ // The connection is reset once the request is read; no response at all.
4905
+ import_zod3.z.strictObject({ type: import_zod3.z.literal("reset"), first }),
4906
+ import_zod3.z.strictObject({
4907
+ type: import_zod3.z.literal("http_429"),
4908
+ first,
4909
+ retry_after_seconds: import_zod3.z.number().int().min(0).default(1)
4910
+ }),
4911
+ import_zod3.z.strictObject({ type: import_zod3.z.literal("http_500"), first }),
4912
+ // The stub's `response`, complete and correct, at this many bytes per second: a whole number, 1 or more.
4913
+ import_zod3.z.strictObject({ type: import_zod3.z.literal("slow_stream"), first, bytes_per_sec: import_zod3.z.number().int().min(1) }),
4914
+ // The first half of the bytes of `response.json`. `full` declares the length of the whole body and closes
4915
+ // the connection after the half, as when a provider's connection drops: the client's read of the body
4916
+ // fails. `cut` declares the length of the half, as when something in between cut the body and re-framed
4917
+ // it: the response arrives whole and only parsing it fails.
4918
+ import_zod3.z.strictObject({
4919
+ type: import_zod3.z.literal("truncated_json"),
4920
+ first,
4921
+ content_length: import_zod3.z.enum(["full", "cut"]).default("full")
4922
+ })
4923
+ ]);
4924
+ var stubSchema = import_zod3.z.strictObject({
4925
+ method: import_zod3.z.string().min(1).default("POST").transform((m) => m.toUpperCase()),
4926
+ // Exact, or with wildcards: `*` stands for any characters inside one path segment, `**` for anything,
4927
+ // slashes included. The query string takes no part in the match, so a path holds none.
4928
+ path: import_zod3.z.string().regex(/^\/[^?#\s]*$/, 'must start with "/" and hold no "?", "#" or whitespace'),
4929
+ // A JSON subset of the request body: every key given here must be in the request with a matching value,
4930
+ // other keys of the request are ignored. Arrays match whole: same length, each item by the same rule.
4931
+ body: import_zod3.z.unknown().optional(),
4932
+ // How `path` and `body` are compared. Left out, or `subset`: as said above. `exact`: the path is compared
4933
+ // as written, so `*` is a character, and `body` is the whole JSON body of the request, with the same
4934
+ // keys and values and nothing more; a stub without `body` then matches a request with no JSON body.
4935
+ // In an exact stub `[masked]` inside the path or a string of the body stands for any text, and a value
4936
+ // that is `[masked]` and nothing else for any value that is there. A recording is written this way.
4937
+ match: import_zod3.z.enum(["subset", "exact"]).optional(),
4938
+ // How many requests the stub answers, failures included; a used-up stub lets the next matching one
4939
+ // answer.
4940
+ times: import_zod3.z.union([import_zod3.z.literal("always"), import_zod3.z.literal("once"), import_zod3.z.number().int().positive()]).default("always"),
4941
+ response: responseSchema.optional(),
4942
+ failure: failureSchema.optional()
4943
+ }).superRefine((stub, ctx) => {
4944
+ const { response, failure } = stub;
4945
+ const need = (message, ...path11) => ctx.addIssue({ code: "custom", message, path: ["response", ...path11] });
4946
+ if (failure === void 0) {
4947
+ if (response === void 0) need("give a response or a failure");
4948
+ } else if (failure.type === "truncated_json") {
4949
+ if (response?.json === void 0) need("truncated_json cuts this body: give it", "json");
4950
+ } else if (response === void 0) {
4951
+ if (failure.type === "slow_stream") need("slow_stream sends this response slowly: give it");
4952
+ else if (failure.first !== void 0)
4953
+ need(`after the first ${failure.first} failed calls this response answers: give it`);
4954
+ } else if (failure.type !== "slow_stream" && failure.first === void 0) {
4955
+ need(
4956
+ `${failure.type} happens on every call, so this response is never sent: remove it or give failure.first`
4957
+ );
4958
+ }
4959
+ if (failure?.first !== void 0 && stub.times !== "always") {
4960
+ if ((stub.times === "once" ? 1 : stub.times) <= failure.first)
4961
+ ctx.addIssue({
4962
+ code: "custom",
4963
+ message: `the first ${failure.first} calls fail and count, so the response is never sent: give more than ${failure.first}, or leave it out`,
4964
+ path: ["times"]
4965
+ });
4966
+ }
4967
+ });
4968
+ var stubFileSchema = import_zod3.z.strictObject({
4969
+ version: import_zod3.z.literal(STUB_FILE_VERSION),
4970
+ stubs: import_zod3.z.array(stubSchema)
4971
+ });
4972
+ var StubFileError = class extends Error {
4973
+ code = "STUB_FILE_ERROR";
4974
+ /** One line per bad field, `path.to.field: what is wrong`. */
4975
+ issues;
4976
+ constructor(message, issues = []) {
4977
+ super(issues.length > 0 ? `${message}
4978
+ ${issues.map((i) => ` ${i}`).join("\n")}` : message);
4979
+ this.name = "StubFileError";
4980
+ this.issues = issues;
4981
+ }
4982
+ };
4983
+ function formatIssues(error) {
4984
+ return error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`);
4985
+ }
4986
+ function parseStubFile(text, file = "stub file") {
4987
+ const doc = (0, import_yaml2.parseDocument)(text, { schema: "core", resolveKnownTags: false });
4988
+ const problem = doc.errors[0] ?? doc.warnings[0];
4989
+ if (problem !== void 0) {
4990
+ const at = problem.linePos?.[0];
4991
+ throw new StubFileError(
4992
+ `Cannot parse ${file}: ${problem.code}${at === void 0 ? "" : ` at line ${at.line}, column ${at.col}`}`
4993
+ );
4994
+ }
4995
+ let raw;
4996
+ try {
4997
+ raw = doc.toJS();
4998
+ JSON.stringify(raw, (_key, value) => {
4999
+ if (typeof value === "number" && !Number.isFinite(value)) throw new Error("not finite");
5000
+ return value;
5001
+ });
5002
+ } catch {
5003
+ throw new StubFileError(
5004
+ `Cannot parse ${file}: it holds a value JSON cannot (an alias that holds itself, or a number that is not finite)`
5005
+ );
5006
+ }
5007
+ const result = stubFileSchema.safeParse(raw);
5008
+ if (!result.success) throw new StubFileError(`Invalid ${file}`, formatIssues(result.error));
5009
+ return result.data;
5010
+ }
5011
+
5012
+ // src/orchestrator/stubs.ts
5013
+ init_cjs_shims();
5014
+ var STUB_NOT_CALLED = "STUB_NOT_CALLED";
5015
+ function viaStubs(inner, scope) {
5016
+ return {
5017
+ async complete(req) {
5018
+ const res = await inner.complete(req);
5019
+ if (scope.journal.length + scope.dropped === 0)
5020
+ throw new ProviderError(
5021
+ STUB_NOT_CALLED,
5022
+ "the answer did not come from the stub server: the provider of this run was not pointed at it, so the answer is dropped"
5023
+ );
5024
+ return res;
5025
+ },
5026
+ estimateCost: () => ({ cost_usd: 0, priced: true })
5027
+ };
5028
+ }
5029
+ var nothingSeen = (stubs) => ({
5030
+ never_called: stubs.map((_, i) => i),
5031
+ unmatched: []
5032
+ });
5033
+ function unusedPlaces(stubs, unused) {
5034
+ const places = /* @__PURE__ */ new Set();
5035
+ let u = unused.length - 1;
5036
+ for (let i = stubs.length - 1; i >= 0 && u >= 0; i -= 1) {
5037
+ if (JSON.stringify(stubs[i]) !== JSON.stringify(unused[u])) continue;
5038
+ places.add(i);
5039
+ u -= 1;
5040
+ }
5041
+ return places;
5042
+ }
5043
+ async function inStubScope(server, name, stubs, seen, fn) {
5044
+ const scope = server.scope(name, stubs);
5045
+ try {
5046
+ return await fn(scope);
5047
+ } finally {
5048
+ const unused = unusedPlaces(stubs, scope.close());
5049
+ seen.never_called = seen.never_called.filter((i) => unused.has(i));
5050
+ for (const entry of scope.journal)
5051
+ if (!entry.matched) seen.unmatched.push({ scope: name, method: entry.method });
5052
+ }
5053
+ }
5054
+
4114
5055
  // src/orchestrator/run.ts
4115
5056
  var DEFAULT_MAX_TOKENS3 = 1024;
4116
5057
  var PLUNE_VERSION = "0.1.0";
@@ -4124,7 +5065,7 @@ var RunConfigError = class extends Error {
4124
5065
  var CACHE_MISS_CODE = "CACHE_MISS";
4125
5066
  function answerParses(output, assertions) {
4126
5067
  return assertions.every(
4127
- (a) => a.type !== "json-schema" || extractJson(output, a.extract ?? "auto").ok
5068
+ (a) => a.type !== "json-schema" && a.type !== "json-verify" || extractJson(output, a.extract ?? "auto").ok
4128
5069
  );
4129
5070
  }
4130
5071
  function resolvePrompt(template, vars) {
@@ -4160,26 +5101,28 @@ async function assess(p, output, input, transcript) {
4160
5101
  const advice = [];
4161
5102
  let assertionError;
4162
5103
  for (const assertion of p.assertions) {
4163
- const own2 = assertion.type === "llm-judge" ? assertion.provider : void 0;
4164
- const jev = own2?.type === "jev" ? own2 : void 0;
4165
- const judgeCfg = own2 === void 0 || own2.type === "jev" ? p.providerConfig : { ...p.providerConfig, ...own2 };
5104
+ const own3 = assertion.type === "llm-judge" ? assertion.provider : void 0;
5105
+ const jev = own3?.type === "jev" ? own3 : void 0;
5106
+ const judgeCfg = own3 === void 0 || own3.type === "jev" ? p.providerConfig : { ...p.providerConfig, ...own3 };
4166
5107
  let judgedBy;
4167
5108
  const judge = () => {
4168
5109
  if (jev !== void 0) {
4169
5110
  if (p.jevJudge === void 0) throw new Error("this run cannot build the jev judge of an llm-judge check");
4170
- const inner2 = p.jevJudge(jev, (usd) => {
4171
- judgeCost += usd;
5111
+ const inner2 = p.jevJudge(jev, (c) => {
5112
+ judgeCost += c.cost_usd;
5113
+ if (c.priced === false) judgeUnpriced = true;
4172
5114
  });
4173
5115
  return {
4174
5116
  ask: (q) => inner2.ask(q),
4175
- decide: (q) => {
4176
- judgedBy = `jev/${jev.model}`;
4177
- return inner2.decide(q);
5117
+ decide: async (q) => {
5118
+ const answer = await inner2.decide(q);
5119
+ judgedBy = `jev/${answer.model}`;
5120
+ return answer;
4178
5121
  }
4179
5122
  };
4180
5123
  }
4181
- let provider = p.provider;
4182
- if (own2 !== void 0) {
5124
+ let provider = p.judgeProvider ?? p.provider;
5125
+ if (own3 !== void 0) {
4183
5126
  if (p.resolveJudge === void 0)
4184
5127
  throw new Error("this run cannot build the judge named by the provider of an llm-judge check");
4185
5128
  provider = p.resolveJudge(judgeCfg);
@@ -4241,7 +5184,15 @@ async function runRow(p) {
4241
5184
  if (p.dryRun) {
4242
5185
  const est = estimateUsage(prompt5, maxTokens);
4243
5186
  const cost = p.provider.estimateCost(est);
4244
- return dryRunRow(p.row.vars, { ...est, ...costFields(cost) });
5187
+ let judged = 0;
5188
+ let unpriced = cost.priced === false;
5189
+ for (const a of p.assertions) {
5190
+ if (a.type !== "llm-judge" || a.provider?.type !== "jev" || p.jevCost === void 0) continue;
5191
+ const c = p.jevCost(a.provider.model, Math.ceil((prompt5.length + maxTokens * 4 + a.criteria.length) / 3));
5192
+ judged += c.cost_usd;
5193
+ if (c.priced === false) unpriced = true;
5194
+ }
5195
+ return dryRunRow(p.row.vars, { ...est, cost_usd: cost.cost_usd + judged, ...unpriced ? { priced: false } : cost.priced === void 0 ? {} : { priced: cost.priced } });
4245
5196
  }
4246
5197
  const key = cacheKey(
4247
5198
  {
@@ -4423,13 +5374,53 @@ function resolveTemplate(ev, baseDir) {
4423
5374
  if (ev.prompt !== void 0) return ev.prompt;
4424
5375
  if (ev.prompt_file !== void 0) {
4425
5376
  try {
4426
- return fs3.readFileSync(path3.resolve(baseDir, ev.prompt_file), "utf8");
5377
+ return fs4.readFileSync(path3.resolve(baseDir, ev.prompt_file), "utf8");
4427
5378
  } catch {
4428
5379
  throw new RunConfigError(`Eval "${ev.id}": prompt_file not found: ${ev.prompt_file}`);
4429
5380
  }
4430
5381
  }
4431
5382
  throw new RunConfigError(`Eval "${ev.id}" has neither prompt nor prompt_file`);
4432
5383
  }
5384
+ var MAX_STUB_FILE_BYTES = 1024 * 1024;
5385
+ function resolveStubs(ev, deps, cacheStrict) {
5386
+ const file = ev.stubs;
5387
+ if (file === void 0) return void 0;
5388
+ const dir = path3.resolve(deps.baseDir);
5389
+ const full = path3.resolve(dir, file);
5390
+ const inside = path3.relative(dir, full);
5391
+ if (inside === "" || inside === ".." || inside.startsWith(`..${path3.sep}`) || path3.isAbsolute(inside))
5392
+ throw new RunConfigError(`Eval "${ev.id}": stubs must name a file inside the folder of the config: ${file}`);
5393
+ let text;
5394
+ try {
5395
+ const stat2 = fs4.statSync(full);
5396
+ if (stat2.isDirectory()) throw new RunConfigError(`Eval "${ev.id}": stubs is a folder, not a file: ${file}`);
5397
+ if (stat2.size > MAX_STUB_FILE_BYTES)
5398
+ throw new RunConfigError(`Eval "${ev.id}": stubs file is over 1 MiB: ${file}`);
5399
+ text = fs4.readFileSync(full, "utf8");
5400
+ } catch (err) {
5401
+ if (err instanceof RunConfigError) throw err;
5402
+ throw new RunConfigError(`Eval "${ev.id}": stubs file not found: ${file}`);
5403
+ }
5404
+ let stubs;
5405
+ try {
5406
+ ({ stubs } = parseStubFile(text, file));
5407
+ } catch (err) {
5408
+ if (err instanceof StubFileError && err.issues.some((issue) => issue.startsWith("version:")))
5409
+ throw new RunConfigError(
5410
+ `Eval "${ev.id}": ${file} is not a stub file: a stub file has version: 1 at its top`
5411
+ );
5412
+ throw new RunConfigError(`Eval "${ev.id}": ${err.message}`);
5413
+ }
5414
+ if (cacheStrict)
5415
+ throw new RunConfigError(
5416
+ `Eval "${ev.id}" has stubs: a stubbed answer is never cached, so --cache-strict cannot answer it`
5417
+ );
5418
+ if (deps.stubServer === void 0)
5419
+ throw new RunConfigError(
5420
+ `Eval "${ev.id}" has stubs, and this run cannot start a stub server (PLUNE_MOCK_PROVIDER=1 answers every call itself and takes no stubs)`
5421
+ );
5422
+ return stubs;
5423
+ }
4433
5424
  function summarize(evals, durationMs) {
4434
5425
  const summary = {
4435
5426
  total: 0,
@@ -4448,6 +5439,7 @@ function summarize(evals, durationMs) {
4448
5439
  errored: 0,
4449
5440
  saved: { input_tokens: 0, output_tokens: 0, cost_usd: 0 }
4450
5441
  };
5442
+ let stubbed = 0;
4451
5443
  for (const ev of evals) {
4452
5444
  for (const row of ev.rows) {
4453
5445
  summary.total += 1;
@@ -4456,13 +5448,14 @@ function summarize(evals, durationMs) {
4456
5448
  cache.saved.input_tokens += row.cache_saved?.input_tokens ?? 0;
4457
5449
  cache.saved.output_tokens += row.cache_saved?.output_tokens ?? 0;
4458
5450
  cache.saved.cost_usd += row.cache_saved?.cost_usd ?? 0;
4459
- if (row.cached) cache.from_cache += 1;
5451
+ if (row.stubbed === true) stubbed += 1;
5452
+ else if (row.cached) cache.from_cache += 1;
4460
5453
  else if (row.error?.code === CACHE_MISS_CODE) cache.missed += 1;
4461
5454
  else if (row.output !== null) cache.from_model += 1;
4462
5455
  else if (row.error !== void 0) cache.errored += 1;
4463
5456
  }
4464
5457
  }
4465
- return { ...summary, cache };
5458
+ return { ...summary, cache: stubbed > 0 ? { ...cache, stubbed } : cache };
4466
5459
  }
4467
5460
  function agenticProvider(ev, providerConfig, deps, cacheStrict) {
4468
5461
  if (cacheStrict)
@@ -4498,22 +5491,28 @@ async function runOrchestration(config, options, deps) {
4498
5491
  const models = config.providers ?? [config.provider];
4499
5492
  const prepared = selectEvals(config.evals, options.only).map((ev) => {
4500
5493
  const template = resolveTemplate(ev, deps.baseDir);
5494
+ const stubs = resolveStubs(ev, deps, cacheStrict);
4501
5495
  const rows = deps.loadDataset(ev.dataset, deps.baseDir);
4502
5496
  for (const row of rows) {
4503
5497
  resolvePrompt(template, row.vars);
4504
5498
  }
4505
5499
  const cells = models.map((model) => {
4506
5500
  const providerConfig = { ...model, ...ev.provider };
5501
+ const hangs = stubs?.findIndex((stub) => stub.failure?.type === "timeout") ?? -1;
5502
+ if (hangs !== -1 && providerConfig.timeout === void 0)
5503
+ throw new RunConfigError(
5504
+ `Eval "${ev.id}": stubs.${hangs} of ${ev.stubs} is a timeout failure and the provider of the eval sets no timeout, so each attempt would wait as long as the provider SDK does by default (minutes): set provider.timeout, in milliseconds, at the root or on the eval`
5505
+ );
4507
5506
  const agentic = ev.mcp === void 0 || dryRun ? void 0 : agenticProvider(ev, providerConfig, deps, cacheStrict);
4508
5507
  return { providerConfig, agentic };
4509
5508
  });
4510
- return { ev, template, rows, cells };
5509
+ return { ev, template, rows, cells, stubs };
4511
5510
  });
4512
5511
  const judges = /* @__PURE__ */ new Map();
4513
5512
  const resolveJudge = (cfg) => {
4514
5513
  const key = canonicalJson(cfg);
4515
- const known = judges.get(key);
4516
- if (known !== void 0) return known;
5514
+ const known2 = judges.get(key);
5515
+ if (known2 !== void 0) return known2;
4517
5516
  const made = deps.resolveProvider(cfg);
4518
5517
  judges.set(key, made);
4519
5518
  return made;
@@ -4523,14 +5522,15 @@ async function runOrchestration(config, options, deps) {
4523
5522
  throw new RunConfigError(
4524
5523
  "--tool-description needs an eval with mcp in this run: no tool is offered otherwise"
4525
5524
  );
4526
- cellLoop: for (const { ev, template, rows, cells } of prepared) {
5525
+ cellLoop: for (const { ev, template, rows, cells, stubs } of prepared) {
4527
5526
  for (const { providerConfig, agentic } of cells) {
4528
5527
  const provider = agentic ?? deps.resolveProvider(providerConfig);
5528
+ const seen = stubs === void 0 || dryRun ? void 0 : nothingSeen(stubs);
4529
5529
  const limit2 = options.concurrency ?? providerConfig.concurrency ?? (ev.mcp !== void 0 ? 1 : 4);
4530
5530
  const runs = options.runs ?? ev.runs ?? config.runs ?? 1;
4531
5531
  const passThreshold = ev.pass_threshold ?? config.pass_threshold ?? 1;
4532
5532
  const assertions = [...config.defaults?.assertions ?? [], ...ev.assertions];
4533
- const rowResults = await mapLimit(rows, limit2, (row) => {
5533
+ const rowResults = await mapLimit(rows, limit2, (row, rowIndex) => {
4534
5534
  const params = {
4535
5535
  template,
4536
5536
  assertions,
@@ -4539,6 +5539,7 @@ async function runOrchestration(config, options, deps) {
4539
5539
  provider,
4540
5540
  resolveJudge,
4541
5541
  ...deps.jevJudge !== void 0 ? { jevJudge: deps.jevJudge } : {},
5542
+ ...deps.jevCost !== void 0 ? { jevCost: deps.jevCost } : {},
4542
5543
  embedder: deps.embedder,
4543
5544
  cache: deps.cache,
4544
5545
  now: deps.now,
@@ -4547,6 +5548,25 @@ async function runOrchestration(config, options, deps) {
4547
5548
  cacheStrict,
4548
5549
  ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {}
4549
5550
  };
5551
+ if (stubs !== void 0 && seen !== void 0) {
5552
+ return runRepeats(
5553
+ params,
5554
+ runs,
5555
+ passThreshold,
5556
+ async (p) => inStubScope(
5557
+ await deps.stubServer(),
5558
+ `${ev.id}.row${rowIndex + 1}${p.attempt === void 0 ? "" : `.run${p.attempt + 1}`}`,
5559
+ stubs,
5560
+ seen,
5561
+ (scope) => runRow({
5562
+ ...p,
5563
+ provider: viaStubs(deps.resolveProvider(providerConfig, scope.url), scope),
5564
+ judgeProvider: p.provider,
5565
+ noCache: true
5566
+ })
5567
+ )
5568
+ ).then((result) => ({ ...result, stubbed: true }));
5569
+ }
4550
5570
  if (ev.mcp === void 0) return runRepeats(params, runs, passThreshold);
4551
5571
  const agentParams = {
4552
5572
  ...params,
@@ -4573,7 +5593,8 @@ async function runOrchestration(config, options, deps) {
4573
5593
  rows: rowResults,
4574
5594
  passed,
4575
5595
  measured,
4576
- ...models.length > 1 ? { provider: { type: providerConfig.type, model: providerConfig.model } } : {}
5596
+ ...models.length > 1 ? { provider: { type: providerConfig.type, model: providerConfig.model } } : {},
5597
+ ...seen !== void 0 ? { stubs: seen } : {}
4577
5598
  });
4578
5599
  if (options.bail === true && !dryRun && !passed) break cellLoop;
4579
5600
  }
@@ -4598,7 +5619,7 @@ init_cjs_shims();
4598
5619
 
4599
5620
  // src/orchestrator/dataset.ts
4600
5621
  init_cjs_shims();
4601
- var fs4 = __toESM(require("fs"), 1);
5622
+ var fs5 = __toESM(require("fs"), 1);
4602
5623
  var path4 = __toESM(require("path"), 1);
4603
5624
  function loadDataset(ref5, baseDir) {
4604
5625
  if (typeof ref5 !== "string") {
@@ -4607,7 +5628,7 @@ function loadDataset(ref5, baseDir) {
4607
5628
  const file = path4.resolve(baseDir, ref5);
4608
5629
  let content;
4609
5630
  try {
4610
- content = fs4.readFileSync(file, "utf8");
5631
+ content = fs5.readFileSync(file, "utf8");
4611
5632
  } catch (err) {
4612
5633
  throw new RunConfigError(
4613
5634
  err.code === "ENOENT" ? `${ref5}: dataset file not found (looked for ${file})` : `${ref5}: cannot read the dataset file (${err.message})`
@@ -4622,9 +5643,9 @@ function loadDataset(ref5, baseDir) {
4622
5643
  } catch (err) {
4623
5644
  throw new RunConfigError(`${ref5}:${i + 1}: not valid JSON (${err.message})`);
4624
5645
  }
4625
- const vars = isObject2(row) ? row["vars"] : void 0;
4626
- if (!isObject2(vars)) {
4627
- const why = isObject2(row) && "vars" in row ? `vars: Invalid input: expected record, received ${typeName(vars)}` : 'this row has no "vars"';
5646
+ const vars = isObject3(row) ? row["vars"] : void 0;
5647
+ if (!isObject3(vars)) {
5648
+ const why = isObject3(row) && "vars" in row ? `vars: Invalid input: expected record, received ${typeName(vars)}` : 'this row has no "vars"';
4628
5649
  throw new RunConfigError(
4629
5650
  `${ref5}:${i + 1}: a dataset row must be { "vars": { ... } }; ${why}`
4630
5651
  );
@@ -4633,7 +5654,7 @@ function loadDataset(ref5, baseDir) {
4633
5654
  });
4634
5655
  return rows;
4635
5656
  }
4636
- function isObject2(value) {
5657
+ function isObject3(value) {
4637
5658
  return typeof value === "object" && value !== null && !Array.isArray(value);
4638
5659
  }
4639
5660
  function typeName(value) {
@@ -4645,7 +5666,7 @@ init_cjs_shims();
4645
5666
  var JEV_BASE_URL = "https://api.typesafe.ai";
4646
5667
  var JEV_KEY_ENV = "TYPESAFE_API_KEY";
4647
5668
  var JEV_MAX_STATE_CHARS = 16e3;
4648
- var JEV_USD_PER_1M_INPUT_TOKENS = 0.042;
5669
+ var JEV_BASE_URL_ENV = "PLUNE_JEV_BASE_URL";
4649
5670
  var DEFAULT_TIMEOUT_MS = 3e4;
4650
5671
  var INSTRUCTIONS = "Does the answer meet the criterion?";
4651
5672
  var YES = "the answer meets the criterion";
@@ -4661,6 +5682,27 @@ ${q.output}
4661
5682
  Criterion:
4662
5683
  ${q.criteria}`;
4663
5684
  }
5685
+ function jevBaseUrl(env) {
5686
+ const own3 = env[JEV_BASE_URL_ENV];
5687
+ const [name, value] = own3 !== void 0 && own3 !== "" ? [JEV_BASE_URL_ENV, own3] : ["TYPESAFE_BASE_URL", env["TYPESAFE_BASE_URL"]];
5688
+ if (value === void 0 || value === "") return JEV_BASE_URL;
5689
+ let url;
5690
+ try {
5691
+ url = new URL(value);
5692
+ } catch {
5693
+ url = void 0;
5694
+ }
5695
+ const ok = url !== void 0 && url.protocol === "https:" && (url.hostname === "typesafe.ai" || url.hostname.endsWith(".typesafe.ai"));
5696
+ if (!ok)
5697
+ throw new Error(
5698
+ `${name} is ${value}: the jev judge asks only an https address under typesafe.ai, so that another model is not judged and reported as Jev. ` + (name === JEV_BASE_URL_ENV ? `Unset it or set it to ${JEV_BASE_URL}` : `Set ${JEV_BASE_URL_ENV}=${JEV_BASE_URL} for plune and keep TYPESAFE_BASE_URL for your other tools`)
5699
+ );
5700
+ return value.replace(/\/+$/, "");
5701
+ }
5702
+ function jevCost(model, inputTokens, pricing) {
5703
+ return resolveCostEntry({ input_tokens: inputTokens, output_tokens: 0 }, model, void 0, pricing);
5704
+ }
5705
+ var jevTokenEstimate = (chars) => Math.ceil(chars / 3);
4664
5706
  function probability(json) {
4665
5707
  const answer = json?.answers?.q;
4666
5708
  const p = answer?.type === "noul" ? answer.noul : void 0;
@@ -4672,6 +5714,7 @@ function makeJevJudge(cfg, deps) {
4672
5714
  return {
4673
5715
  ask: () => Promise.reject(new Error("a jev judge answers a yes-or-no question only: it cannot judge this kind of check")),
4674
5716
  async decide(q) {
5717
+ const base = jevBaseUrl(deps.env);
4675
5718
  const key = deps.env[JEV_KEY_ENV];
4676
5719
  if (key === void 0 || key === "")
4677
5720
  throw new AuthError(`${JEV_KEY_ENV} is not set: the jev judge of an llm-judge check needs it`, JEV_KEY_ENV);
@@ -4688,7 +5731,7 @@ function makeJevJudge(cfg, deps) {
4688
5731
  });
4689
5732
  const send = async () => {
4690
5733
  try {
4691
- return await deps.fetchFn(`${JEV_BASE_URL}/v1/systemone`, {
5734
+ return await deps.fetchFn(`${base}/v1/systemone`, {
4692
5735
  method: "POST",
4693
5736
  headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
4694
5737
  body,
@@ -4707,9 +5750,11 @@ function makeJevJudge(cfg, deps) {
4707
5750
  const json = await res.json();
4708
5751
  const p = probability(json);
4709
5752
  const tokens = json.usage?.input_tokens;
4710
- const billed = typeof tokens === "number" && tokens >= 0 ? tokens : Math.ceil(state.length / 3);
4711
- deps.onCost(billed / 1e6 * JEV_USD_PER_1M_INPUT_TOKENS);
4712
- return p;
5753
+ const billed = typeof tokens === "number" && tokens >= 0 ? tokens : jevTokenEstimate(state.length);
5754
+ const answered = json.model;
5755
+ const model = typeof answered === "string" && answered !== "" ? answered : cfg.model;
5756
+ deps.onCost(jevCost(model, billed, deps.pricing));
5757
+ return { probability: p, model };
4713
5758
  }
4714
5759
  };
4715
5760
  }
@@ -4723,6 +5768,416 @@ function warnJevExperimental(write = (l) => process.stderr.write(l)) {
4723
5768
  );
4724
5769
  }
4725
5770
 
5771
+ // src/mock/server.ts
5772
+ init_cjs_shims();
5773
+ var http = __toESM(require("http"), 1);
5774
+ var JOURNAL_MAX_ENTRIES = 1e3;
5775
+ var MAX_CONNECTIONS = 256;
5776
+ var REAL_TIMERS = {
5777
+ now: () => performance.now(),
5778
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
5779
+ clearTimeout: (handle) => clearTimeout(handle)
5780
+ };
5781
+ var SLOW_STREAM_STEP_MS = 50;
5782
+ var MASK = "[masked]";
5783
+ var SECRET_NAME = /auth|key|token|secret|cookie|password|passwd|pwd|credential|sig|jwt|session|csrf|otp|code|assertion/i;
5784
+ var SCOPE_NAME = /^(?!\.{1,2}$)[A-Za-z0-9._-]+$/;
5785
+ var DOT_SEGMENT = /^(\.|%2e){1,2}$/i;
5786
+ var MAX_BODY_BYTES = 16 * 1024 * 1024;
5787
+ function pathMatcher(pattern) {
5788
+ const tokens = pattern.match(/\*\*|[^]/g) ?? [];
5789
+ const n = tokens.length;
5790
+ const skipWildcards = (at) => {
5791
+ for (let i = 0; i < n; i += 1)
5792
+ if (at[i] && (tokens[i] === "*" || tokens[i] === "**")) at[i + 1] = 1;
5793
+ };
5794
+ return (path11) => {
5795
+ let at = new Uint8Array(n + 1);
5796
+ at[0] = 1;
5797
+ skipWildcards(at);
5798
+ for (let c = 0; c < path11.length; c += 1) {
5799
+ const ch = path11[c];
5800
+ const next = new Uint8Array(n + 1);
5801
+ for (let i = 0; i < n; i += 1) {
5802
+ if (!at[i]) continue;
5803
+ const token = tokens[i];
5804
+ if (token === "**" || token === "*" && ch !== "/") next[i] = 1;
5805
+ else if (token !== "*" && token === ch) next[i + 1] = 1;
5806
+ }
5807
+ skipWildcards(next);
5808
+ at = next;
5809
+ }
5810
+ return at[n] === 1;
5811
+ };
5812
+ }
5813
+ function matchesSubset(expected, actual) {
5814
+ if (Array.isArray(expected))
5815
+ return Array.isArray(actual) && actual.length === expected.length && expected.every((item, i) => matchesSubset(item, actual[i]));
5816
+ if (expected !== null && typeof expected === "object")
5817
+ return actual !== null && typeof actual === "object" && !Array.isArray(actual) && Object.entries(expected).every(
5818
+ ([k, v]) => Object.hasOwn(actual, k) && matchesSubset(v, actual[k])
5819
+ );
5820
+ return expected === actual;
5821
+ }
5822
+ function maskedTextMatches(expected, actual) {
5823
+ const parts = expected.split(MASK);
5824
+ const first2 = parts[0];
5825
+ const last = parts[parts.length - 1];
5826
+ if (parts.length === 1) return expected === actual;
5827
+ if (actual.length < first2.length + last.length) return false;
5828
+ if (!actual.startsWith(first2) || !actual.endsWith(last)) return false;
5829
+ const end = actual.length - last.length;
5830
+ let at = first2.length;
5831
+ for (const part of parts.slice(1, -1)) {
5832
+ const found = actual.indexOf(part, at);
5833
+ if (found === -1 || found + part.length > end) return false;
5834
+ at = found + part.length;
5835
+ }
5836
+ return true;
5837
+ }
5838
+ function matchesExact(expected, actual) {
5839
+ if (expected === MASK) return actual !== void 0;
5840
+ if (typeof expected === "string")
5841
+ return typeof actual === "string" && maskedTextMatches(expected, actual);
5842
+ if (Array.isArray(expected))
5843
+ return Array.isArray(actual) && actual.length === expected.length && expected.every((item, i) => matchesExact(item, actual[i]));
5844
+ if (expected !== null && typeof expected === "object")
5845
+ return actual !== null && typeof actual === "object" && !Array.isArray(actual) && Object.keys(actual).length === Object.keys(expected).length && Object.entries(expected).every(
5846
+ ([k, v]) => Object.hasOwn(actual, k) && matchesExact(v, actual[k])
5847
+ );
5848
+ return expected === actual;
5849
+ }
5850
+ function notLocal(req, port, bound = "127.0.0.1") {
5851
+ const names = ["127.0.0.1", "localhost", "[::1]", bound.includes(":") ? `[${bound}]` : bound];
5852
+ const hosts = names.flatMap((name) => port === 80 ? [name, `${name}:80`] : [`${name}:${port}`]);
5853
+ const host = (req.headers.host ?? "").toLowerCase();
5854
+ const { origin } = req.headers;
5855
+ return !hosts.includes(host) || origin !== void 0 && !hosts.some((h) => origin.toLowerCase() === `http://${h}`);
5856
+ }
5857
+ var NOT_LOCAL_MESSAGE = "This server answers only a request addressed to 127.0.0.1, localhost or [::1] with its own port, and none a web page of another origin sent";
5858
+ function maskedHeaders(headers) {
5859
+ const out = {};
5860
+ for (const [name, value] of Object.entries(headers)) {
5861
+ if (value === void 0) continue;
5862
+ out[name] = SECRET_NAME.test(name) ? MASK : Array.isArray(value) ? value.join(", ") : value;
5863
+ }
5864
+ return out;
5865
+ }
5866
+ function maskedQuery(params) {
5867
+ return [...params].map(
5868
+ ([k, v]) => `${encodeURIComponent(k)}=${SECRET_NAME.test(k) ? MASK : encodeURIComponent(v)}`
5869
+ ).join("&");
5870
+ }
5871
+ function renderBody(response) {
5872
+ if (response.sse !== void 0) {
5873
+ const events = response.sse.map((chunk2) => {
5874
+ const { event, data } = typeof chunk2 === "string" ? { event: void 0, data: chunk2 } : chunk2;
5875
+ const line = typeof data === "string" ? data : JSON.stringify(data);
5876
+ return `${event === void 0 ? "" : `event: ${event}
5877
+ `}data: ${line}
5878
+
5879
+ `;
5880
+ });
5881
+ return { type: "text/event-stream", body: Buffer.from(events.join("")) };
5882
+ }
5883
+ if (response.text !== void 0)
5884
+ return { type: "text/plain; charset=utf-8", body: Buffer.from(response.text) };
5885
+ if (response.json !== void 0)
5886
+ return { type: "application/json", body: Buffer.from(JSON.stringify(response.json)) };
5887
+ return { body: Buffer.alloc(0) };
5888
+ }
5889
+ function responseHeaders(response, type, length) {
5890
+ const headers = {};
5891
+ if (type !== void 0) headers["content-type"] = type;
5892
+ if (response.sse === void 0) headers["content-length"] = length;
5893
+ else headers["cache-control"] = "no-cache";
5894
+ for (const [name, value] of Object.entries(response.headers)) headers[name.toLowerCase()] = value;
5895
+ return headers;
5896
+ }
5897
+ function sendJson(res, status, body, headers = {}) {
5898
+ const text = JSON.stringify(body);
5899
+ res.writeHead(status, {
5900
+ "content-type": "application/json",
5901
+ "content-length": Buffer.byteLength(text),
5902
+ ...headers
5903
+ });
5904
+ res.end(text);
5905
+ }
5906
+ var providerError = (type, code, message) => ({
5907
+ type: "error",
5908
+ error: { type, code, message }
5909
+ });
5910
+ function writeSlowly(res, body, bytesPerSec, timers) {
5911
+ const startedAt = timers.now();
5912
+ const step = Math.max(1, Math.round(bytesPerSec * SLOW_STREAM_STEP_MS / 1e3));
5913
+ let sent = 0;
5914
+ let handle;
5915
+ const tick = () => {
5916
+ const due = Math.min(
5917
+ body.length,
5918
+ Math.floor((timers.now() - startedAt) * bytesPerSec / 1e3)
5919
+ );
5920
+ if (due > sent) {
5921
+ res.write(body.subarray(sent, due));
5922
+ sent = due;
5923
+ }
5924
+ if (sent >= body.length) {
5925
+ res.end();
5926
+ return;
5927
+ }
5928
+ const nextAt = startedAt + Math.min(body.length, sent + step) * 1e3 / bytesPerSec;
5929
+ handle = timers.setTimeout(tick, Math.max(1, Math.ceil(nextAt - timers.now())));
5930
+ };
5931
+ tick();
5932
+ return () => timers.clearTimeout(handle);
5933
+ }
5934
+ async function start(options = {}) {
5935
+ const host = options.host ?? "127.0.0.1";
5936
+ const journalBodyCap = options.journalBodyCap ?? 64 * 1024;
5937
+ const timers = options.timers ?? REAL_TIMERS;
5938
+ const scopes = /* @__PURE__ */ new Map();
5939
+ const unrouted = [];
5940
+ let unroutedDropped = 0;
5941
+ let closing;
5942
+ const record = (journal, entry) => {
5943
+ journal.push(entry);
5944
+ if (journal.length <= JOURNAL_MAX_ENTRIES) return 0;
5945
+ journal.shift();
5946
+ return 1;
5947
+ };
5948
+ function answer(req, res, body) {
5949
+ const target = req.url ?? "";
5950
+ const queryAt = target.indexOf("?");
5951
+ const rawPath = queryAt === -1 ? target : target.slice(0, queryAt);
5952
+ const segments = rawPath.split("/");
5953
+ const badTarget = segments[0] !== "" || segments.length < 2 || segments[1] === "" && segments.length > 2 || segments.some((segment2) => DOT_SEGMENT.test(segment2));
5954
+ const name = badTarget ? "" : segments[1];
5955
+ const method = req.method ?? "GET";
5956
+ const path11 = badTarget ? rawPath : rawPath.slice(name.length + 1) || "/";
5957
+ const entry = {
5958
+ scope: name,
5959
+ method,
5960
+ path: path11,
5961
+ query: maskedQuery(new URLSearchParams(queryAt === -1 ? "" : target.slice(queryAt + 1))),
5962
+ headers: maskedHeaders(req.headers),
5963
+ body: body.subarray(0, journalBodyCap).toString("utf8"),
5964
+ bodyTruncated: body.length > journalBodyCap,
5965
+ matched: false
5966
+ };
5967
+ const refuse = (status, type, message, open2) => sendJson(res, status, {
5968
+ error: { type, message, method, ...open2 === void 0 ? {} : { scope: open2 } }
5969
+ });
5970
+ const scope = badTarget ? void 0 : scopes.get(name);
5971
+ if (scope === void 0) {
5972
+ unroutedDropped += record(unrouted, entry);
5973
+ if (badTarget)
5974
+ refuse(
5975
+ 400,
5976
+ "mock_bad_target",
5977
+ 'Bad request target: it starts with "/<scope>" and holds no "." or ".." segment'
5978
+ );
5979
+ else
5980
+ refuse(
5981
+ 404,
5982
+ "mock_no_stub",
5983
+ `No open scope for this ${method} request: the first path segment names the scope`
5984
+ );
5985
+ return;
5986
+ }
5987
+ scope.dropped += record(scope.journal, entry);
5988
+ let json;
5989
+ let parsed2 = false;
5990
+ const live = scope.stubs.find(({ stub, matches, calls }) => {
5991
+ if (stub.times !== "always" && calls >= (stub.times === "once" ? 1 : stub.times))
5992
+ return false;
5993
+ if (stub.method !== method || !matches(path11)) return false;
5994
+ const exact = stub.match === "exact";
5995
+ if (stub.body === void 0 && !exact) return true;
5996
+ if (!parsed2) {
5997
+ parsed2 = true;
5998
+ try {
5999
+ json = JSON.parse(body.toString("utf8"));
6000
+ } catch {
6001
+ json = void 0;
6002
+ }
6003
+ }
6004
+ if (!exact) return matchesSubset(stub.body, json);
6005
+ return stub.body === void 0 ? json === void 0 : matchesExact(stub.body, json);
6006
+ });
6007
+ if (live === void 0) {
6008
+ refuse(
6009
+ 404,
6010
+ "mock_no_stub",
6011
+ `No stub matches this ${method} request in scope "${name}": compare its path and body in the journal of the scope with the stubs`,
6012
+ name
6013
+ );
6014
+ return;
6015
+ }
6016
+ entry.matched = true;
6017
+ live.calls += 1;
6018
+ const response = live.stub.response ?? { status: 200, headers: {} };
6019
+ const rendered = renderBody(response);
6020
+ const head = (length) => {
6021
+ res.writeHead(response.status, responseHeaders(response, rendered.type, length));
6022
+ };
6023
+ const { failure } = live.stub;
6024
+ if (failure === void 0 || failure.first !== void 0 && live.calls > failure.first) {
6025
+ head(rendered.body.length);
6026
+ res.end(rendered.body);
6027
+ return;
6028
+ }
6029
+ const hold = (stop = () => void 0) => {
6030
+ const abort = () => {
6031
+ stop();
6032
+ res.destroy();
6033
+ };
6034
+ scope.held.add(abort);
6035
+ res.on("close", () => {
6036
+ stop();
6037
+ scope.held.delete(abort);
6038
+ });
6039
+ };
6040
+ switch (failure.type) {
6041
+ case "timeout":
6042
+ hold();
6043
+ return;
6044
+ case "reset":
6045
+ req.socket.resetAndDestroy();
6046
+ return;
6047
+ case "http_429":
6048
+ sendJson(
6049
+ res,
6050
+ 429,
6051
+ providerError("rate_limit_error", "rate_limit_exceeded", "Rate limit exceeded (stub)"),
6052
+ { "retry-after": String(failure.retry_after_seconds) }
6053
+ );
6054
+ return;
6055
+ case "http_500":
6056
+ sendJson(
6057
+ res,
6058
+ 500,
6059
+ providerError("api_error", "internal_error", "Internal server error (stub)")
6060
+ );
6061
+ return;
6062
+ case "slow_stream":
6063
+ head(rendered.body.length);
6064
+ res.flushHeaders();
6065
+ hold(writeSlowly(res, rendered.body, failure.bytes_per_sec, timers));
6066
+ return;
6067
+ case "truncated_json": {
6068
+ const cut = rendered.body.subarray(0, Math.floor(rendered.body.length / 2));
6069
+ if (failure.content_length === "cut") {
6070
+ head(cut.length);
6071
+ res.end(cut);
6072
+ } else {
6073
+ head(rendered.body.length);
6074
+ res.write(cut, () => res.destroy());
6075
+ }
6076
+ return;
6077
+ }
6078
+ }
6079
+ }
6080
+ let port = 0;
6081
+ const server = http.createServer((req, res) => {
6082
+ if (notLocal(req, port, host)) {
6083
+ req.resume();
6084
+ sendJson(res, 403, { error: { type: "mock_not_local", message: NOT_LOCAL_MESSAGE } });
6085
+ return;
6086
+ }
6087
+ const chunks = [];
6088
+ let size = 0;
6089
+ req.on("error", () => void 0);
6090
+ req.on("data", (chunk2) => {
6091
+ size += chunk2.length;
6092
+ if (size <= MAX_BODY_BYTES) chunks.push(chunk2);
6093
+ else chunks.length = 0;
6094
+ });
6095
+ req.on("end", () => {
6096
+ if (size > MAX_BODY_BYTES) {
6097
+ sendJson(res, 413, {
6098
+ error: { type: "mock_body_too_large", message: "Request body over 16 MiB" }
6099
+ });
6100
+ return;
6101
+ }
6102
+ try {
6103
+ answer(req, res, Buffer.concat(chunks));
6104
+ } catch {
6105
+ if (res.headersSent) res.destroy();
6106
+ else
6107
+ sendJson(res, 500, {
6108
+ error: { type: "mock_internal", message: "The stub server failed on this request" }
6109
+ });
6110
+ }
6111
+ });
6112
+ });
6113
+ server.maxConnections = MAX_CONNECTIONS;
6114
+ await new Promise((resolve9, reject) => {
6115
+ server.once("error", reject);
6116
+ server.listen(options.port ?? 0, host, () => {
6117
+ server.off("error", reject);
6118
+ resolve9();
6119
+ });
6120
+ });
6121
+ ({ port } = server.address());
6122
+ const url = `http://${host.includes(":") ? `[${host}]` : host}:${port}`;
6123
+ return {
6124
+ url,
6125
+ port,
6126
+ unrouted,
6127
+ get unroutedDropped() {
6128
+ return unroutedDropped;
6129
+ },
6130
+ scope(name, stubs = []) {
6131
+ if (closing !== void 0) throw new Error("The server is closed: it takes no new scope");
6132
+ if (!SCOPE_NAME.test(name))
6133
+ throw new Error(
6134
+ `Bad scope name "${name}": letters, digits, ".", "_" and "-" only, and not "." or ".."`
6135
+ );
6136
+ if (scopes.has(name)) throw new Error(`Scope "${name}" is already open`);
6137
+ const state = { stubs: [], journal: [], dropped: 0, held: /* @__PURE__ */ new Set() };
6138
+ scopes.set(name, state);
6139
+ const scope = {
6140
+ name,
6141
+ url: `${url}/${name}`,
6142
+ journal: state.journal,
6143
+ get dropped() {
6144
+ return state.dropped;
6145
+ },
6146
+ add(...inputs) {
6147
+ for (const input of inputs) {
6148
+ const result = stubSchema.safeParse(input);
6149
+ if (!result.success)
6150
+ throw new Error(`Invalid stub: ${formatIssues(result.error).join("; ")}`);
6151
+ state.stubs.push({
6152
+ stub: result.data,
6153
+ matches: result.data.match === "exact" ? (path11) => maskedTextMatches(result.data.path, path11) : pathMatcher(result.data.path),
6154
+ calls: 0
6155
+ });
6156
+ }
6157
+ },
6158
+ close() {
6159
+ if (scopes.get(name) === state) scopes.delete(name);
6160
+ const unused = state.stubs.filter((s) => s.calls === 0).map((s) => s.stub);
6161
+ state.stubs = [];
6162
+ for (const abort of [...state.held]) abort();
6163
+ return unused;
6164
+ }
6165
+ };
6166
+ scope.add(...stubs);
6167
+ return scope;
6168
+ },
6169
+ close() {
6170
+ closing ??= new Promise((resolve9) => {
6171
+ for (const state of scopes.values()) for (const abort of [...state.held]) abort();
6172
+ scopes.clear();
6173
+ server.close(() => resolve9());
6174
+ server.closeAllConnections();
6175
+ });
6176
+ return closing;
6177
+ }
6178
+ };
6179
+ }
6180
+
4726
6181
  // src/cli/commands/run.ts
4727
6182
  var NOOP_CACHE = { get: () => void 0, set: () => {
4728
6183
  }, delete: () => {
@@ -4749,12 +6204,12 @@ function parseToolDescriptions(values) {
4749
6204
  const file = text.slice(1);
4750
6205
  try {
4751
6206
  const full = path5.resolve(file);
4752
- const stat2 = fs5.statSync(full);
6207
+ const stat2 = fs6.statSync(full);
4753
6208
  if (!stat2.isFile())
4754
6209
  throw new RunConfigError(`--tool-description ${tool}: ${file} is not a file`);
4755
6210
  if (stat2.size > MAX_DESCRIPTION_BYTES)
4756
6211
  throw new RunConfigError(`--tool-description ${tool}: ${file} is over 64 KB`);
4757
- text = fs5.readFileSync(full, "utf8").replace(/\r?\n$/, "");
6212
+ text = fs6.readFileSync(full, "utf8").replace(/\r?\n$/, "");
4758
6213
  } catch (err) {
4759
6214
  if (err instanceof RunConfigError) throw err;
4760
6215
  throw new RunConfigError(`--tool-description ${tool}: cannot read ${file}`);
@@ -4772,7 +6227,7 @@ function mockScript(env) {
4772
6227
  if (file === void 0 || file === "") return void 0;
4773
6228
  let text;
4774
6229
  try {
4775
- text = fs5.readFileSync(path5.resolve(file), "utf8");
6230
+ text = fs6.readFileSync(path5.resolve(file), "utf8");
4776
6231
  } catch {
4777
6232
  throw new RunConfigError(`PLUNE_MOCK_SCRIPT: cannot read ${file}`);
4778
6233
  }
@@ -4806,11 +6261,11 @@ function resolveProviderFor(config, dryRun) {
4806
6261
  return () => makeMockProvider(script);
4807
6262
  }
4808
6263
  if (dryRun) return (cfg) => makeEstimateProvider(cfg, config.pricing);
4809
- return (cfg) => getProvider(cfg, process.env, config.pricing);
6264
+ return (cfg, stubOrigin) => getProvider(cfg, process.env, config.pricing, stubOrigin);
4810
6265
  }
4811
6266
  function buildRealDeps(config, baseDir, dryRun) {
4812
6267
  const dir = path5.join(baseDir, ".plune");
4813
- fs5.mkdirSync(dir, { recursive: true });
6268
+ fs6.mkdirSync(dir, { recursive: true });
4814
6269
  return {
4815
6270
  resolveProvider: resolveProviderFor(config, dryRun),
4816
6271
  embedder: getDefaultEmbedder(),
@@ -4823,27 +6278,58 @@ function buildRealDeps(config, baseDir, dryRun) {
4823
6278
  ...isMockMode(process.env) ? {} : {
4824
6279
  jevJudge: (cfg, onCost) => {
4825
6280
  warnJevExperimental();
4826
- return makeJevJudge(cfg, { env: process.env, fetchFn: fetch, onCost });
4827
- }
6281
+ return makeJevJudge(cfg, {
6282
+ env: process.env,
6283
+ fetchFn: fetch,
6284
+ onCost,
6285
+ ...config.pricing !== void 0 ? { pricing: config.pricing } : {}
6286
+ });
6287
+ },
6288
+ jevCost: (model, inputTokens) => jevCost(model, inputTokens, config.pricing)
4828
6289
  }
4829
6290
  };
4830
6291
  }
4831
6292
  function persist(result, baseDir) {
4832
6293
  const dir = path5.join(baseDir, ".plune");
4833
- fs5.mkdirSync(dir, { recursive: true });
4834
- fs5.writeFileSync(path5.join(dir, "last-run.json"), JSON.stringify(result, null, 2));
6294
+ fs6.mkdirSync(dir, { recursive: true });
6295
+ fs6.writeFileSync(path5.join(dir, "last-run.json"), JSON.stringify(result, null, 2));
6296
+ }
6297
+ function stubWarnings(config, result) {
6298
+ return result.evals.flatMap((ev) => {
6299
+ if (ev.stubs === void 0) return [];
6300
+ const { never_called: never, unmatched } = ev.stubs;
6301
+ const file = config.evals.find((e) => e.id === baseEvalId(ev))?.stubs ?? "its stub file";
6302
+ return [
6303
+ ...never.length > 0 ? [`${never.map((i) => `stubs.${i}`).join(", ")} of ${file} ${never.length === 1 ? "was" : "were"} never called`] : [],
6304
+ ...unmatched.length > 0 ? [
6305
+ `${unmatched.length} request${unmatched.length === 1 ? "" : "s"} matched no stub: ` + unmatched.map((u) => `${u.method} in ${u.scope}`).join(", ")
6306
+ ] : []
6307
+ ].map((line) => `eval "${ev.id}": ${line}`);
6308
+ });
6309
+ }
6310
+ function jevAddressCheck(config, env) {
6311
+ const checks = [...config.defaults?.assertions ?? [], ...config.evals.flatMap((ev) => ev.assertions)];
6312
+ if (!checks.some((a) => a.type === "llm-judge" && a.provider?.type === "jev")) return;
6313
+ try {
6314
+ jevBaseUrl(env);
6315
+ } catch (err) {
6316
+ throw new RunConfigError(err.message);
6317
+ }
4835
6318
  }
4836
6319
  async function handleRun(options, depsFactory) {
4837
6320
  const config = await loadConfig(
4838
6321
  options.configPath !== void 0 ? { configPath: options.configPath } : {}
4839
6322
  );
4840
6323
  const baseDir = options.configPath !== void 0 ? path5.dirname(path5.resolve(options.configPath)) : process.cwd();
6324
+ jevAddressCheck(config, process.env);
4841
6325
  for (const warning of [...mcpSecretWarnings(config), ...selfJudgeWarnings(config)])
4842
6326
  process.stderr.write(`warning: ${warning}
4843
6327
  `);
4844
6328
  const toolDescriptions = options.toolDescription !== void 0 && options.toolDescription.length > 0 ? parseToolDescriptions(options.toolDescription) : void 0;
4845
6329
  const factory = depsFactory ?? ((c, d) => buildRealDeps(c, d, options.dryRun));
4846
- const deps = factory(config, baseDir);
6330
+ const given = factory(config, baseDir);
6331
+ let stubServer;
6332
+ const deps = depsFactory === void 0 && isMockMode(process.env) ? given : { ...given, stubServer: () => stubServer ??= (given.stubServer ?? start)() };
4847
6333
  try {
4848
6334
  const stale = deps.cache.staleEntries ?? 0;
4849
6335
  if (stale > 0) {
@@ -4879,6 +6365,8 @@ async function handleRun(options, depsFactory) {
4879
6365
  `
4880
6366
  );
4881
6367
  }
6368
+ for (const warning of stubWarnings(config, result)) process.stderr.write(`warning: ${warning}
6369
+ `);
4882
6370
  if (options.dryRun) {
4883
6371
  const agentic = new Set(config.evals.filter((ev) => ev.mcp !== void 0).map((ev) => ev.id));
4884
6372
  if (result.evals.some((ev) => agentic.has(ev.id)))
@@ -4890,164 +6378,173 @@ async function handleRun(options, depsFactory) {
4890
6378
  return result;
4891
6379
  } finally {
4892
6380
  deps.cache.close();
6381
+ if (stubServer !== void 0) await stubServer.then((server) => server.close(), () => void 0);
4893
6382
  }
4894
6383
  }
4895
6384
 
4896
6385
  // src/cli/commands/sync.ts
4897
6386
  init_cjs_shims();
4898
6387
  var import_node_crypto2 = require("crypto");
4899
- var fs6 = __toESM(require("fs"), 1);
6388
+ var fs7 = __toESM(require("fs"), 1);
4900
6389
  var path6 = __toESM(require("path"), 1);
4901
6390
 
4902
6391
  // src/types/run-result-schema.ts
4903
6392
  init_cjs_shims();
4904
- var import_zod3 = require("zod");
6393
+ var import_zod4 = require("zod");
4905
6394
  var RUN_RESULT_SCHEMA_VERSION = 1;
4906
- var binaryVerdictSchema = import_zod3.z.object({
4907
- question: import_zod3.z.string().min(1),
4908
- passed: import_zod3.z.boolean()
6395
+ var binaryVerdictSchema = import_zod4.z.object({
6396
+ question: import_zod4.z.string().min(1),
6397
+ passed: import_zod4.z.boolean()
4909
6398
  });
4910
- var assertionResultRecordSchema2 = import_zod3.z.object({
4911
- type: import_zod3.z.string(),
4912
- passed: import_zod3.z.boolean(),
4913
- score: import_zod3.z.number().optional(),
4914
- reason: import_zod3.z.string().optional(),
4915
- binaryVerdicts: import_zod3.z.array(binaryVerdictSchema).optional(),
6399
+ var assertionResultRecordSchema2 = import_zod4.z.object({
6400
+ type: import_zod4.z.string(),
6401
+ passed: import_zod4.z.boolean(),
6402
+ score: import_zod4.z.number().optional(),
6403
+ reason: import_zod4.z.string().optional(),
6404
+ binaryVerdicts: import_zod4.z.array(binaryVerdictSchema).optional(),
4916
6405
  /** plune-ai/cli#373. Optional and additive — a RunResult written before it validates unchanged. */
4917
- judge_model: import_zod3.z.string().optional()
6406
+ judge_model: import_zod4.z.string().optional()
4918
6407
  });
4919
- var usageSchema = import_zod3.z.object({
4920
- input_tokens: import_zod3.z.number(),
4921
- output_tokens: import_zod3.z.number(),
4922
- cost_usd: import_zod3.z.number(),
6408
+ var usageSchema = import_zod4.z.object({
6409
+ input_tokens: import_zod4.z.number(),
6410
+ output_tokens: import_zod4.z.number(),
6411
+ cost_usd: import_zod4.z.number(),
4923
6412
  /** cli#151. Optional and additive — a RunResult written before it validates unchanged. */
4924
- priced: import_zod3.z.boolean().optional()
6413
+ priced: import_zod4.z.boolean().optional()
4925
6414
  });
4926
- var runErrorSchema = import_zod3.z.object({
4927
- code: import_zod3.z.string(),
4928
- message: import_zod3.z.string()
6415
+ var runErrorSchema = import_zod4.z.object({
6416
+ code: import_zod4.z.string(),
6417
+ message: import_zod4.z.string()
4929
6418
  });
4930
- var savedSchema = import_zod3.z.object({
4931
- input_tokens: import_zod3.z.number(),
4932
- output_tokens: import_zod3.z.number(),
4933
- cost_usd: import_zod3.z.number()
6419
+ var savedSchema = import_zod4.z.object({
6420
+ input_tokens: import_zod4.z.number(),
6421
+ output_tokens: import_zod4.z.number(),
6422
+ cost_usd: import_zod4.z.number()
4934
6423
  });
4935
- var rowResultSchema = import_zod3.z.object({
4936
- vars: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()),
4937
- output: import_zod3.z.string().nullable(),
4938
- cached: import_zod3.z.boolean(),
6424
+ var rowResultSchema = import_zod4.z.object({
6425
+ vars: import_zod4.z.record(import_zod4.z.string(), import_zod4.z.unknown()),
6426
+ output: import_zod4.z.string().nullable(),
6427
+ cached: import_zod4.z.boolean(),
6428
+ /** A row of an eval with `stubs`. Kept by the parser so that `plune sync` can see it and refuse the upload. */
6429
+ stubbed: import_zod4.z.boolean().optional(),
4939
6430
  usage: usageSchema.optional(),
4940
- latency_ms: import_zod3.z.number().optional(),
6431
+ latency_ms: import_zod4.z.number().optional(),
4941
6432
  error: runErrorSchema.optional(),
4942
- assertions: import_zod3.z.array(assertionResultRecordSchema2),
6433
+ assertions: import_zod4.z.array(assertionResultRecordSchema2),
4943
6434
  cache_saved: savedSchema.optional(),
4944
6435
  /** Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
4945
- inconclusive: import_zod3.z.enum(ROW_INCONCLUSIVE).optional(),
6436
+ inconclusive: import_zod4.z.enum(ROW_INCONCLUSIVE).optional(),
4946
6437
  /** Repeats (`runs` above 1). Optional and additive — a RunResult without it validates unchanged. */
4947
- attempts: import_zod3.z.object({
4948
- runs: import_zod3.z.number(),
4949
- pass_threshold: import_zod3.z.number(),
4950
- passed: import_zod3.z.number(),
4951
- failed: import_zod3.z.number(),
4952
- errored: import_zod3.z.number(),
4953
- results: import_zod3.z.array(
4954
- import_zod3.z.object({
4955
- output: import_zod3.z.string().nullable(),
4956
- cached: import_zod3.z.boolean(),
6438
+ attempts: import_zod4.z.object({
6439
+ runs: import_zod4.z.number(),
6440
+ pass_threshold: import_zod4.z.number(),
6441
+ passed: import_zod4.z.number(),
6442
+ failed: import_zod4.z.number(),
6443
+ errored: import_zod4.z.number(),
6444
+ results: import_zod4.z.array(
6445
+ import_zod4.z.object({
6446
+ output: import_zod4.z.string().nullable(),
6447
+ cached: import_zod4.z.boolean(),
4957
6448
  usage: usageSchema.optional(),
4958
- latency_ms: import_zod3.z.number().optional(),
6449
+ latency_ms: import_zod4.z.number().optional(),
4959
6450
  error: runErrorSchema.optional(),
4960
- assertions: import_zod3.z.array(assertionResultRecordSchema2),
6451
+ assertions: import_zod4.z.array(assertionResultRecordSchema2),
4961
6452
  cache_saved: savedSchema.optional()
4962
6453
  })
4963
6454
  )
4964
6455
  }).optional(),
4965
6456
  /** The tool loop of an eval with an `mcp` server. Optional and additive — a RunResult without it validates unchanged. */
4966
- agent: import_zod3.z.object({
4967
- server: import_zod3.z.string(),
4968
- tools: import_zod3.z.array(
4969
- import_zod3.z.object({
4970
- name: import_zod3.z.string(),
4971
- offered: import_zod3.z.boolean(),
4972
- annotations: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).optional()
6457
+ agent: import_zod4.z.object({
6458
+ server: import_zod4.z.string(),
6459
+ tools: import_zod4.z.array(
6460
+ import_zod4.z.object({
6461
+ name: import_zod4.z.string(),
6462
+ offered: import_zod4.z.boolean(),
6463
+ annotations: import_zod4.z.record(import_zod4.z.string(), import_zod4.z.unknown()).optional()
4973
6464
  })
4974
6465
  ),
4975
- steps: import_zod3.z.array(
4976
- import_zod3.z.object({
4977
- index: import_zod3.z.number(),
4978
- text: import_zod3.z.string(),
4979
- finish_reason: import_zod3.z.string().optional(),
6466
+ steps: import_zod4.z.array(
6467
+ import_zod4.z.object({
6468
+ index: import_zod4.z.number(),
6469
+ text: import_zod4.z.string(),
6470
+ finish_reason: import_zod4.z.string().optional(),
4980
6471
  usage: usageSchema,
4981
- calls: import_zod3.z.array(
4982
- import_zod3.z.object({
4983
- id: import_zod3.z.string(),
4984
- name: import_zod3.z.string(),
4985
- args: import_zod3.z.unknown(),
4986
- executed: import_zod3.z.boolean(),
4987
- is_error: import_zod3.z.boolean(),
4988
- error_kind: import_zod3.z.enum(["content", "protocol", "timeout", "not-offered", "bad-arguments"]).optional(),
4989
- duration_ms: import_zod3.z.number().optional(),
4990
- result: import_zod3.z.object({ text: import_zod3.z.string(), bytes: import_zod3.z.number(), truncated: import_zod3.z.boolean() }).optional()
6472
+ calls: import_zod4.z.array(
6473
+ import_zod4.z.object({
6474
+ id: import_zod4.z.string(),
6475
+ name: import_zod4.z.string(),
6476
+ args: import_zod4.z.unknown(),
6477
+ executed: import_zod4.z.boolean(),
6478
+ is_error: import_zod4.z.boolean(),
6479
+ error_kind: import_zod4.z.enum(["content", "protocol", "timeout", "not-offered", "bad-arguments"]).optional(),
6480
+ duration_ms: import_zod4.z.number().optional(),
6481
+ result: import_zod4.z.object({ text: import_zod4.z.string(), bytes: import_zod4.z.number(), truncated: import_zod4.z.boolean() }).optional()
4991
6482
  })
4992
6483
  ),
4993
6484
  /** Optional and additive: the step whose request first offered a changed list. */
4994
- offered_changed: import_zod3.z.object({ added: import_zod3.z.array(import_zod3.z.string()), removed: import_zod3.z.array(import_zod3.z.string()) }).optional()
6485
+ offered_changed: import_zod4.z.object({ added: import_zod4.z.array(import_zod4.z.string()), removed: import_zod4.z.array(import_zod4.z.string()) }).optional()
4995
6486
  })
4996
6487
  ),
4997
- stop: import_zod3.z.object({
4998
- reason: import_zod3.z.enum(["complete", "limit", "error"]),
4999
- limit: import_zod3.z.enum(["max_steps", "max_tool_calls", "max_total_tokens", "timeout_ms", "tool_timeout_ms"]).optional()
6488
+ stop: import_zod4.z.object({
6489
+ reason: import_zod4.z.enum(["complete", "limit", "error"]),
6490
+ limit: import_zod4.z.enum(["max_steps", "max_tool_calls", "max_total_tokens", "timeout_ms", "tool_timeout_ms"]).optional()
5000
6491
  }),
5001
- collection: import_zod3.z.enum(["complete", "partial"]),
6492
+ collection: import_zod4.z.enum(["complete", "partial"]),
5002
6493
  /** Heuristic findings, never a verdict. Optional and additive. */
5003
- advice: import_zod3.z.array(
5004
- import_zod3.z.object({
5005
- type: import_zod3.z.string(),
5006
- reason: import_zod3.z.string(),
5007
- tool: import_zod3.z.string().optional(),
5008
- steps: import_zod3.z.array(import_zod3.z.number()).optional(),
5009
- count: import_zod3.z.number().optional(),
5010
- paths: import_zod3.z.array(import_zod3.z.string()).optional()
6494
+ advice: import_zod4.z.array(
6495
+ import_zod4.z.object({
6496
+ type: import_zod4.z.string(),
6497
+ reason: import_zod4.z.string(),
6498
+ tool: import_zod4.z.string().optional(),
6499
+ steps: import_zod4.z.array(import_zod4.z.number()).optional(),
6500
+ count: import_zod4.z.number().optional(),
6501
+ paths: import_zod4.z.array(import_zod4.z.string()).optional()
5011
6502
  })
5012
6503
  ).optional(),
5013
- description_overrides: import_zod3.z.array(import_zod3.z.object({ tool: import_zod3.z.string(), sha256: import_zod3.z.string() })).optional()
6504
+ description_overrides: import_zod4.z.array(import_zod4.z.object({ tool: import_zod4.z.string(), sha256: import_zod4.z.string() })).optional()
5014
6505
  }).optional()
5015
6506
  });
5016
- var summarySchema = import_zod3.z.object({
5017
- total: import_zod3.z.number(),
5018
- passed: import_zod3.z.number(),
5019
- failed: import_zod3.z.number(),
5020
- errored: import_zod3.z.number(),
6507
+ var summarySchema = import_zod4.z.object({
6508
+ total: import_zod4.z.number(),
6509
+ passed: import_zod4.z.number(),
6510
+ failed: import_zod4.z.number(),
6511
+ errored: import_zod4.z.number(),
5021
6512
  /** Optional and additive — a RunResult written before them validates unchanged. */
5022
- blocked: import_zod3.z.number().optional(),
5023
- skipped: import_zod3.z.number().optional(),
5024
- cost_usd: import_zod3.z.number(),
5025
- duration_ms: import_zod3.z.number(),
5026
- cache: import_zod3.z.object({
5027
- from_cache: import_zod3.z.number(),
5028
- from_model: import_zod3.z.number(),
5029
- missed: import_zod3.z.number(),
5030
- errored: import_zod3.z.number(),
5031
- saved: import_zod3.z.object({ input_tokens: import_zod3.z.number(), output_tokens: import_zod3.z.number(), cost_usd: import_zod3.z.number() })
6513
+ blocked: import_zod4.z.number().optional(),
6514
+ skipped: import_zod4.z.number().optional(),
6515
+ cost_usd: import_zod4.z.number(),
6516
+ duration_ms: import_zod4.z.number(),
6517
+ cache: import_zod4.z.object({
6518
+ from_cache: import_zod4.z.number(),
6519
+ from_model: import_zod4.z.number(),
6520
+ missed: import_zod4.z.number(),
6521
+ errored: import_zod4.z.number(),
6522
+ stubbed: import_zod4.z.number().optional(),
6523
+ saved: import_zod4.z.object({ input_tokens: import_zod4.z.number(), output_tokens: import_zod4.z.number(), cost_usd: import_zod4.z.number() })
5032
6524
  }).optional()
5033
6525
  });
5034
- var evalResultSchema = import_zod3.z.object({
5035
- id: import_zod3.z.string(),
5036
- tags: import_zod3.z.array(import_zod3.z.string()),
5037
- rows: import_zod3.z.array(rowResultSchema),
5038
- passed: import_zod3.z.boolean(),
6526
+ var evalResultSchema = import_zod4.z.object({
6527
+ id: import_zod4.z.string(),
6528
+ tags: import_zod4.z.array(import_zod4.z.string()),
6529
+ rows: import_zod4.z.array(rowResultSchema),
6530
+ passed: import_zod4.z.boolean(),
5039
6531
  /** What the eval measured, for the pass-rate gate of `plune diff`. Optional and additive. */
5040
- measured: import_zod3.z.object({
5041
- runs: import_zod3.z.number(),
5042
- rows: import_zod3.z.number(),
5043
- rows_hash: import_zod3.z.string(),
5044
- assertions_hash: import_zod3.z.string(),
5045
- model: import_zod3.z.string().optional()
6532
+ measured: import_zod4.z.object({
6533
+ runs: import_zod4.z.number(),
6534
+ rows: import_zod4.z.number(),
6535
+ rows_hash: import_zod4.z.string(),
6536
+ assertions_hash: import_zod4.z.string(),
6537
+ model: import_zod4.z.string().optional()
5046
6538
  }).optional(),
5047
6539
  /** The type and model of a cell of a multi-model run. Optional and additive. */
5048
- provider: import_zod3.z.object({ type: import_zod3.z.string(), model: import_zod3.z.string() }).optional(),
6540
+ provider: import_zod4.z.object({ type: import_zod4.z.string(), model: import_zod4.z.string() }).optional(),
6541
+ /** The mark of an eval answered from stubs, kept for the same reason as a row's `stubbed`. */
6542
+ stubs: import_zod4.z.object({
6543
+ never_called: import_zod4.z.array(import_zod4.z.number()),
6544
+ unmatched: import_zod4.z.array(import_zod4.z.object({ scope: import_zod4.z.string(), method: import_zod4.z.string() }))
6545
+ }).optional(),
5049
6546
  /** The link to the eval's trace in your own observability (Langfuse, OTel). Optional and additive; `plune sync` drops one `traceUrlProblem` refuses. */
5050
- traceUrl: import_zod3.z.string().optional()
6547
+ traceUrl: import_zod4.z.string().optional()
5051
6548
  });
5052
6549
  var TRACE_URL_MAX = 2048;
5053
6550
  function traceUrlProblem(value) {
@@ -5065,16 +6562,16 @@ function traceUrlProblem(value) {
5065
6562
  if (parsed2.username !== "" || parsed2.password !== "") return "must carry no user name or password";
5066
6563
  return void 0;
5067
6564
  }
5068
- var runResultSchema = import_zod3.z.object({
5069
- schemaVersion: import_zod3.z.literal(RUN_RESULT_SCHEMA_VERSION),
5070
- plune_version: import_zod3.z.string(),
5071
- started_at: import_zod3.z.string(),
5072
- finished_at: import_zod3.z.string(),
5073
- config_hash: import_zod3.z.string(),
6565
+ var runResultSchema = import_zod4.z.object({
6566
+ schemaVersion: import_zod4.z.literal(RUN_RESULT_SCHEMA_VERSION),
6567
+ plune_version: import_zod4.z.string(),
6568
+ started_at: import_zod4.z.string(),
6569
+ finished_at: import_zod4.z.string(),
6570
+ config_hash: import_zod4.z.string(),
5074
6571
  /** cli#244. The result of `--dry-run`. Optional and additive — a RunResult without it validates unchanged. */
5075
- dry_run: import_zod3.z.boolean().optional(),
6572
+ dry_run: import_zod4.z.boolean().optional(),
5076
6573
  summary: summarySchema,
5077
- evals: import_zod3.z.array(evalResultSchema)
6574
+ evals: import_zod4.z.array(evalResultSchema)
5078
6575
  });
5079
6576
  function parseRunResult(value) {
5080
6577
  return runResultSchema.parse(value);
@@ -5082,11 +6579,30 @@ function parseRunResult(value) {
5082
6579
 
5083
6580
  // src/cli/api-url.ts
5084
6581
  init_cjs_shims();
5085
- var DEFAULT_API_URL = "https://beta-api.plune.ai";
6582
+ var PRODUCTION_API_URL = "https://api.plune.ai";
6583
+ var BETA_API_URL = "https://beta-api.plune.ai";
6584
+ var DEFAULT_API_URL = PRODUCTION_API_URL;
6585
+ var DASHBOARDS = /* @__PURE__ */ new Map([
6586
+ [PRODUCTION_API_URL, "https://app.plune.ai"],
6587
+ [BETA_API_URL, "https://beta.plune.ai"]
6588
+ ]);
5086
6589
  function resolveApiUrl(explicit) {
5087
- const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
6590
+ const raw = explicit?.trim() || process.env["PLUNE_API_URL"]?.trim() || DEFAULT_API_URL;
5088
6591
  return raw.replace(/\/+$/, "");
5089
6592
  }
6593
+ function knownApi(apiUrl) {
6594
+ try {
6595
+ const origin = new URL(apiUrl.trim()).origin;
6596
+ return DASHBOARDS.has(origin) ? origin : void 0;
6597
+ } catch {
6598
+ return void 0;
6599
+ }
6600
+ }
6601
+ function tokenRefusedBy(apiUrl = resolveApiUrl()) {
6602
+ const named = `The address that refused it is ${apiUrl}.`;
6603
+ if (knownApi(apiUrl) !== PRODUCTION_API_URL) return named;
6604
+ return `${named} A token from a beta account works only on the beta: run "plune login" with a token from ${DASHBOARDS.get(PRODUCTION_API_URL)}, or set PLUNE_API_URL=${BETA_API_URL} to keep using the beta account.`;
6605
+ }
5090
6606
 
5091
6607
  // src/cli/credentials.ts
5092
6608
  init_cjs_shims();
@@ -5206,9 +6722,9 @@ var NotLoggedInError = class extends Error {
5206
6722
  }
5207
6723
  };
5208
6724
  var TokenRejectedError = class extends Error {
5209
- constructor() {
6725
+ constructor(apiUrl = resolveApiUrl()) {
5210
6726
  super(
5211
- 'Your API token was rejected (revoked or invalid). Run "plune login" with a fresh token.'
6727
+ `Your API token was rejected (revoked or invalid). Run "plune login" with a fresh token. ${tokenRefusedBy(apiUrl)}`
5212
6728
  );
5213
6729
  this.name = "TokenRejectedError";
5214
6730
  }
@@ -5239,7 +6755,7 @@ function readRun(cwd, file, warn) {
5239
6755
  const target = file !== void 0 ? path6.resolve(cwd, file) : path6.join(cwd, ".plune", "last-run.json");
5240
6756
  let raw;
5241
6757
  try {
5242
- raw = fs6.readFileSync(target, "utf8");
6758
+ raw = fs7.readFileSync(target, "utf8");
5243
6759
  } catch {
5244
6760
  throw new SyncFileError(
5245
6761
  file !== void 0 ? `Run file not found: ${target}` : 'No run to sync. Run "plune run" first (or pass --file <path>).'
@@ -5252,11 +6768,18 @@ function readRun(cwd, file, warn) {
5252
6768
  throw new SyncFileError(`Run file is not valid JSON: ${target}`);
5253
6769
  }
5254
6770
  dropBadTraceLinks(json, warn);
6771
+ let run;
5255
6772
  try {
5256
- return parseRunResult(json);
6773
+ run = parseRunResult(json);
5257
6774
  } catch {
5258
6775
  throw new SyncFileError(`Run file does not match the RunResult schema: ${target}`);
5259
6776
  }
6777
+ const stubbed = stubbedEvals(run);
6778
+ if (stubbed.length > 0)
6779
+ throw new SyncFileError(
6780
+ `This run is not uploaded: its evals ${stubbed.join(", ")} were answered from stubs, not by a model. Run them without stubs, or sync a run of the other evals (plune run --only).`
6781
+ );
6782
+ return run;
5260
6783
  }
5261
6784
  function dropBadTraceLinks(json, warn) {
5262
6785
  const evals = json?.evals;
@@ -5321,7 +6844,7 @@ async function handleSync(deps = {}) {
5321
6844
  }
5322
6845
  if (!res.ok) {
5323
6846
  const detail = await safeErrorDetail(res);
5324
- if (res.status === 401) throw new TokenRejectedError();
6847
+ if (res.status === 401) throw new TokenRejectedError(apiUrl);
5325
6848
  throw new SyncHttpError(res.status, detail);
5326
6849
  }
5327
6850
  const body = await res.json().catch(() => ({}));
@@ -5363,7 +6886,7 @@ var path10 = __toESM(require("path"), 1);
5363
6886
  init_cjs_shims();
5364
6887
  var import_node_fs5 = require("fs");
5365
6888
  var import_node_stream = require("stream");
5366
- var import_node_http = require("http");
6889
+ var import_node_http2 = require("http");
5367
6890
  var import_node_https = require("https");
5368
6891
  var BACKOFF_BASE_MS = 300;
5369
6892
  var BACKOFF_CAP_MS = 1e4;
@@ -5376,12 +6899,12 @@ function parseRetryAfter(raw, now = Date.now()) {
5376
6899
  if (!Number.isFinite(seconds)) return null;
5377
6900
  return Math.min(Math.max(seconds, 0) * 1e3, RETRY_AFTER_CAP_MS);
5378
6901
  }
5379
- var POOLS = { "http:": new import_node_http.Agent({ keepAlive: true }), "https:": new import_node_https.Agent({ keepAlive: true }) };
6902
+ var POOLS = { "http:": new import_node_http2.Agent({ keepAlive: true }), "https:": new import_node_https.Agent({ keepAlive: true }) };
5380
6903
  var IDLE_MS = 3e5;
5381
6904
  function nodeTransport(url, init, idleMs = IDLE_MS) {
5382
6905
  return new Promise((resolve9, reject) => {
5383
6906
  const target = new URL(url);
5384
- const send = target.protocol === "https:" ? import_node_https.request : import_node_http.request;
6907
+ const send = target.protocol === "https:" ? import_node_https.request : import_node_http2.request;
5385
6908
  const agent = POOLS[target.protocol === "https:" ? "https:" : "http:"];
5386
6909
  const req = send(target, { method: init.method, headers: init.headers, agent }, (res) => {
5387
6910
  const chunks = [];
@@ -5412,7 +6935,7 @@ var withoutLength = (headers) => Object.fromEntries(Object.entries(headers).filt
5412
6935
  function nodePut(url, headers, source, idleMs) {
5413
6936
  return new Promise((resolve9, reject) => {
5414
6937
  const target = new URL(url);
5415
- const send = target.protocol === "https:" ? import_node_https.request : import_node_http.request;
6938
+ const send = target.protocol === "https:" ? import_node_https.request : import_node_http2.request;
5416
6939
  const length = "body" in source ? source.body.length : source.size;
5417
6940
  let answered;
5418
6941
  const settle = (err) => answered !== void 0 ? resolve9(answered) : reject(err);
@@ -5619,7 +7142,7 @@ var BUCKET_CODES = /* @__PURE__ */ new Set([
5619
7142
 
5620
7143
  // src/reporter-core/fallback.ts
5621
7144
  init_cjs_shims();
5622
- var fs7 = __toESM(require("fs"), 1);
7145
+ var fs8 = __toESM(require("fs"), 1);
5623
7146
  var path8 = __toESM(require("path"), 1);
5624
7147
  var DEFAULT_FALLBACK_PATH = path8.join(".plune", "pending-results.jsonl");
5625
7148
 
@@ -5672,12 +7195,12 @@ var TYPE_BY_EXTENSION = {
5672
7195
  var READ_NOT_KEPT = /* @__PURE__ */ new Set(["application/plune.metadata+json", "application/plune.findings+json"]);
5673
7196
  var NAME_MAX = 200;
5674
7197
  function nameOf(file) {
5675
- const own2 = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : (0, import_node_path3.basename)(file.path));
7198
+ const own3 = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : (0, import_node_path3.basename)(file.path));
5676
7199
  const fileExt = file.path === void 0 ? "" : (0, import_node_path3.extname)(file.path);
5677
- const ownExt = (0, import_node_path3.extname)(own2);
7200
+ const ownExt = (0, import_node_path3.extname)(own3);
5678
7201
  const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
5679
7202
  const ext = typed ? ownExt : fileExt;
5680
- let stem = typed ? own2.slice(0, -ownExt.length) : own2;
7203
+ let stem = typed ? own3.slice(0, -ownExt.length) : own3;
5681
7204
  if (stem.length + ext.length > NAME_MAX) {
5682
7205
  stem = stem.slice(0, Math.max(0, NAME_MAX - ext.length));
5683
7206
  if (/[\uD800-\uDBFF]$/.test(stem)) stem = stem.slice(0, -1);
@@ -5815,9 +7338,9 @@ function fileSender(options) {
5815
7338
  if (out.ok) countsOf(kind).uploaded += 1;
5816
7339
  else failed(job, out.detail || out.kind);
5817
7340
  }
5818
- async function uploadToBucket(job, size, first) {
7341
+ async function uploadToBucket(job, size, first2) {
5819
7342
  const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
5820
- let link = first;
7343
+ let link = first2;
5821
7344
  for (let renewed = false; ; ) {
5822
7345
  const put = await client.put(link.url, link.headers, source);
5823
7346
  if (put.ok) break;
@@ -5830,8 +7353,8 @@ function fileSender(options) {
5830
7353
  link = fresh;
5831
7354
  }
5832
7355
  requests += 1;
5833
- const done = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
5834
- if (!done.ok) return failedToBucket(job, codeOf2(done));
7356
+ const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
7357
+ if (!done2.ok) return failedToBucket(job, codeOf2(done2));
5835
7358
  countsOf(job.kind).uploaded += 1;
5836
7359
  }
5837
7360
  let free = uploadsAtOnce;
@@ -5997,9 +7520,9 @@ function fileSender(options) {
5997
7520
  const toComplete = [];
5998
7521
  await Promise.all(
5999
7522
  puts.map(
6000
- ({ s, link: first }) => gated(async () => {
7523
+ ({ s, link: first2 }) => gated(async () => {
6001
7524
  const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
6002
- let link = first;
7525
+ let link = first2;
6003
7526
  for (let renewed = false; ; ) {
6004
7527
  const put = await client.put(link.url, link.headers, source);
6005
7528
  if (put.ok) break;
@@ -6185,7 +7708,7 @@ function fileSender(options) {
6185
7708
 
6186
7709
  // src/cli/commands/cairn-artifact.ts
6187
7710
  init_cjs_shims();
6188
- var fs8 = __toESM(require("fs/promises"), 1);
7711
+ var fs9 = __toESM(require("fs/promises"), 1);
6189
7712
  var path9 = __toESM(require("path"), 1);
6190
7713
 
6191
7714
  // src/importers/trace-url.ts
@@ -7748,14 +9271,14 @@ var NoCairnRunsError = class extends Error {
7748
9271
  }
7749
9272
  };
7750
9273
  async function findLatestCairnRun(runsDir = "runs") {
7751
- const entries = await fs8.readdir(runsDir, { withFileTypes: true }).catch(() => null);
9274
+ const entries = await fs9.readdir(runsDir, { withFileTypes: true }).catch(() => null);
7752
9275
  if (entries === null) throw new NoCairnRunsError(runsDir);
7753
9276
  let newest;
7754
9277
  for (const entry of entries) {
7755
9278
  if (!entry.isDirectory()) continue;
7756
9279
  const dir = path9.join(runsDir, entry.name);
7757
9280
  try {
7758
- const report = await fs8.lstat(path9.join(dir, "report.json"));
9281
+ const report = await fs9.lstat(path9.join(dir, "report.json"));
7759
9282
  if (!report.isFile()) continue;
7760
9283
  if (newest === void 0 || report.mtimeMs > newest.at) {
7761
9284
  newest = { dir, at: report.mtimeMs };
@@ -7806,13 +9329,13 @@ var CairnEvidenceAmbiguousError = class extends Error {
7806
9329
  };
7807
9330
  var asRecord = (v) => typeof v === "object" && v !== null ? v : {};
7808
9331
  var str = (v, fallback = "") => typeof v === "string" && v !== "" ? v : fallback;
7809
- var own = (rec, key) => Object.hasOwn(rec, key) ? rec[key] : void 0;
9332
+ var own2 = (rec, key) => Object.hasOwn(rec, key) ? rec[key] : void 0;
7810
9333
  var MAX_ARTIFACT_BYTES = 32 * 1024 * 1024;
7811
9334
  var MAX_MCP_CASES = 5e3;
7812
9335
  async function checkSize(dir, file) {
7813
9336
  let size;
7814
9337
  try {
7815
- const st = await fs8.stat(path9.join(dir, file));
9338
+ const st = await fs9.stat(path9.join(dir, file));
7816
9339
  if (!st.isFile()) throw new CairnArtifactShapeError(file, "", "is not a regular file");
7817
9340
  size = st.size;
7818
9341
  } catch (e) {
@@ -7830,20 +9353,20 @@ async function checkSize(dir, file) {
7830
9353
  }
7831
9354
  async function readJson(file) {
7832
9355
  try {
7833
- return JSON.parse(await fs8.readFile(file, "utf8"));
9356
+ return JSON.parse(await fs9.readFile(file, "utf8"));
7834
9357
  } catch {
7835
9358
  return void 0;
7836
9359
  }
7837
9360
  }
7838
9361
  var ARGS_CHARS2 = 200;
7839
- var SECRET_NAME = /key|token|secret|password|passwd|auth|cookie|credential/i;
9362
+ var SECRET_NAME2 = /key|token|secret|password|passwd|auth|cookie|credential/i;
7840
9363
  var maskNamed = (v, depth = 0) => {
7841
9364
  if (depth > 16) return "[deep]";
7842
9365
  if (Array.isArray(v)) return v.slice(0, 50).map((x) => maskNamed(x, depth + 1));
7843
9366
  if (typeof v === "object" && v !== null) {
7844
9367
  const out = {};
7845
9368
  for (const [k, x] of Object.entries(v).slice(0, 50)) {
7846
- out[k] = SECRET_NAME.test(k) ? "***" : maskNamed(x, depth + 1);
9369
+ out[k] = SECRET_NAME2.test(k) ? "***" : maskNamed(x, depth + 1);
7847
9370
  }
7848
9371
  return out;
7849
9372
  }
@@ -7870,7 +9393,7 @@ async function readMcpEvidence(dir, states) {
7870
9393
  if (!await checkSize(dir, file)) return void 0;
7871
9394
  let raw;
7872
9395
  try {
7873
- raw = JSON.parse(await fs8.readFile(path9.join(dir, file), "utf8"));
9396
+ raw = JSON.parse(await fs9.readFile(path9.join(dir, file), "utf8"));
7874
9397
  } catch {
7875
9398
  throw new CairnArtifactShapeError(file, "", "is not valid JSON");
7876
9399
  }
@@ -7884,7 +9407,7 @@ async function readMcpEvidence(dir, states) {
7884
9407
  throw new CairnArtifactShapeError(file, `[${i}]`, "must be an object");
7885
9408
  }
7886
9409
  const rec = item;
7887
- const id = own(rec, "stableId");
9410
+ const id = own2(rec, "stableId");
7888
9411
  if (typeof id !== "string" || !states.has(id)) {
7889
9412
  throw new CairnArtifactShapeError(
7890
9413
  file,
@@ -7895,18 +9418,18 @@ async function readMcpEvidence(dir, states) {
7895
9418
  if (byId.has(id)) {
7896
9419
  throw new CairnArtifactShapeError(file, `[${i}].stableId`, "appears more than once");
7897
9420
  }
7898
- if (own(rec, "state") !== states.get(id)) {
9421
+ if (own2(rec, "state") !== states.get(id)) {
7899
9422
  throw new CairnArtifactShapeError(
7900
9423
  file,
7901
9424
  `[${i}].state`,
7902
9425
  "does not agree with the state in report.json"
7903
9426
  );
7904
9427
  }
7905
- const request = own(rec, "request");
9428
+ const request = own2(rec, "request");
7906
9429
  if (request !== void 0 && typeof request !== "string") {
7907
9430
  throw new CairnArtifactShapeError(file, `[${i}].request`, "must be text");
7908
9431
  }
7909
- const durationMs = own(rec, "durationMs");
9432
+ const durationMs = own2(rec, "durationMs");
7910
9433
  if (durationMs !== void 0 && typeof durationMs !== "number") {
7911
9434
  throw new CairnArtifactShapeError(file, `[${i}].durationMs`, "must be a number");
7912
9435
  }
@@ -7924,7 +9447,7 @@ function expectedOfMcp(type, adversarial) {
7924
9447
  return adversarial ? "The server rejects the call, or handles the value without harm." : "The server rejects the call: it does not act on a value the tool's inputSchema forbids.";
7925
9448
  }
7926
9449
  async function casesFromMcp(dir, report) {
7927
- const list2 = own(report, "cases");
9450
+ const list2 = own2(report, "cases");
7928
9451
  if (!Array.isArray(list2))
7929
9452
  throw new CairnArtifactShapeError("report.json", "cases", "must be a list");
7930
9453
  if (list2.length > MAX_MCP_CASES) {
@@ -7942,7 +9465,7 @@ async function casesFromMcp(dir, report) {
7942
9465
  }
7943
9466
  const c = raw;
7944
9467
  const text = (key) => {
7945
- const v = own(c, key);
9468
+ const v = own2(c, key);
7946
9469
  if (typeof v !== "string" || v === "") {
7947
9470
  throw new CairnArtifactShapeError("report.json", `${at}.${key}`, "must be text");
7948
9471
  }
@@ -7972,14 +9495,14 @@ async function casesFromMcp(dir, report) {
7972
9495
  }
7973
9496
  states.set(stableId, state);
7974
9497
  const kind = type;
7975
- const technique = own(c, "technique");
9498
+ const technique = own2(c, "technique");
7976
9499
  return {
7977
9500
  stableId,
7978
9501
  name,
7979
9502
  tool,
7980
9503
  type: kind,
7981
9504
  state,
7982
- adversarial: own(c, "adversarialStyle") !== void 0,
9505
+ adversarial: own2(c, "adversarialStyle") !== void 0,
7983
9506
  ...typeof technique === "string" ? { technique } : {}
7984
9507
  };
7985
9508
  });
@@ -8015,7 +9538,7 @@ function casesFromDesign(report, notes) {
8015
9538
  const c = asRecord(raw);
8016
9539
  const steps = (Array.isArray(c["steps"]) ? c["steps"] : []).map((s) => str(s)).filter((s) => s !== "");
8017
9540
  const title = str(c["title"], "untitled case");
8018
- const link = own(c, "traceUrl") ?? void 0;
9541
+ const link = own2(c, "traceUrl") ?? void 0;
8019
9542
  const said = [];
8020
9543
  const traceUrl = traceUrlOf(link, title, said);
8021
9544
  if (said.length > 0) {
@@ -8085,11 +9608,11 @@ async function readCairnRun(dir, deps = {}) {
8085
9608
  }
8086
9609
  cases = casesFromApi(report, verdicts);
8087
9610
  } else if (mode === "mcp") {
8088
- cases = own(report, "cases") === void 0 && Array.isArray(own(report, "testCases")) ? casesFromDesign(report, deps.notes ?? []) : await casesFromMcp(dir, report);
9611
+ cases = own2(report, "cases") === void 0 && Array.isArray(own2(report, "testCases")) ? casesFromDesign(report, deps.notes ?? []) : await casesFromMcp(dir, report);
8089
9612
  } else {
8090
9613
  cases = casesFromDesign(report, deps.notes ?? []);
8091
9614
  }
8092
- const tokens = own(asRecord(own(report, "cost")), "totalTokens");
9615
+ const tokens = own2(asRecord(own2(report, "cost")), "totalTokens");
8093
9616
  return {
8094
9617
  schemaVersion: INGEST_SCHEMA_VERSION,
8095
9618
  run: {
@@ -8107,7 +9630,7 @@ var clip = (s) => s.slice(0, DECLARED.text).replace(/[\uD800-\uDBFF]$/, "");
8107
9630
  async function readCairnSessionFiles(dir) {
8108
9631
  const raw = await readJson(path9.join(dir, "screencasts", "screencasts.json"));
8109
9632
  if (!Array.isArray(raw)) return void 0;
8110
- const root = await fs8.realpath(dir).catch(() => path9.resolve(dir));
9633
+ const root = await fs9.realpath(dir).catch(() => path9.resolve(dir));
8111
9634
  const within = (p) => {
8112
9635
  const rel = path9.relative(root, p);
8113
9636
  return rel !== "" && !rel.startsWith("..") && !path9.isAbsolute(rel);
@@ -8116,10 +9639,10 @@ async function readCairnSessionFiles(dir) {
8116
9639
  const inside = async (p) => {
8117
9640
  if (typeof p !== "string" || p === "") return void 0;
8118
9641
  const abs = path9.resolve(root, p);
8119
- const real = await fs8.realpath(abs).catch(() => void 0);
9642
+ const real = await fs9.realpath(abs).catch(() => void 0);
8120
9643
  if (within(abs) && (real === void 0 || within(real))) {
8121
9644
  const file = real ?? abs;
8122
- const size = await fs8.stat(file).then((s) => s.size, () => void 0);
9645
+ const size = await fs9.stat(file).then((s) => s.size, () => void 0);
8123
9646
  return { path: file, rel: path9.relative(root, abs).split(path9.sep).join("/"), ...size !== void 0 ? { size } : {} };
8124
9647
  }
8125
9648
  outside += 1;
@@ -8132,11 +9655,11 @@ async function readCairnSessionFiles(dir) {
8132
9655
  const rec = asRecord(entry);
8133
9656
  const found = [];
8134
9657
  for (const kind of ["video", "trace"]) {
8135
- const at = await inside(own(rec, kind));
9658
+ const at = await inside(own2(rec, kind));
8136
9659
  if (at !== void 0) found.push({ file: { path: at.path, ...at.size !== void 0 ? { size: at.size } : {} }, rel: at.rel, kind });
8137
9660
  }
8138
9661
  if (found.length === 0) continue;
8139
- const stableId = own(rec, "stableId");
9662
+ const stableId = own2(rec, "stableId");
8140
9663
  if (typeof stableId !== "string" || stableId === "") {
8141
9664
  unmapped += 1;
8142
9665
  continue;
@@ -8144,7 +9667,7 @@ async function readCairnSessionFiles(dir) {
8144
9667
  byCase.set(stableId, [...byCase.get(stableId) ?? [], ...found.map((f) => f.file)]);
8145
9668
  const declared = screencasts.get(stableId) ?? [];
8146
9669
  const keys = new Set(declared.flatMap((s) => s.files.map((f) => f.key)));
8147
- const title = clip(str(own(rec, "test")));
9670
+ const title = clip(str(own2(rec, "test")));
8148
9671
  const files = found.filter((f) => {
8149
9672
  if ((f.file.size ?? 0) < 1 || f.rel.length > DECLARED.text || path9.basename(f.file.path).length > DECLARED.name || keys.has(f.rel)) return false;
8150
9673
  keys.add(f.rel);
@@ -8152,14 +9675,14 @@ async function readCairnSessionFiles(dir) {
8152
9675
  });
8153
9676
  if (title === "" || files.length === 0 || declared.length >= DECLARED.perCase) continue;
8154
9677
  for (const f of files) f.file.key = f.rel;
8155
- const timing = own(rec, "timing");
9678
+ const timing = own2(rec, "timing");
8156
9679
  declared.push({
8157
9680
  title,
8158
9681
  ...timing === "trace" || timing === "estimated" ? { timing } : {},
8159
- chapters: (Array.isArray(own(rec, "chapters")) ? own(rec, "chapters") : []).flatMap((c) => {
9682
+ chapters: (Array.isArray(own2(rec, "chapters")) ? own2(rec, "chapters") : []).flatMap((c) => {
8160
9683
  const chapter = asRecord(c);
8161
- const t = clip(str(own(chapter, "title")));
8162
- const atMs = own(chapter, "atMs");
9684
+ const t = clip(str(own2(chapter, "title")));
9685
+ const atMs = own2(chapter, "atMs");
8163
9686
  return t !== "" && Number.isInteger(atMs) && atMs >= 0 ? [{ title: t, atMs }] : [];
8164
9687
  }).slice(0, DECLARED.chapters),
8165
9688
  files: files.map((f) => ({ key: f.rel, name: path9.basename(f.file.path), kind: f.kind, size: f.file.size }))
@@ -8177,8 +9700,8 @@ var IngestNotLoggedInError = class extends Error {
8177
9700
  }
8178
9701
  };
8179
9702
  var IngestTokenRejectedError = class extends Error {
8180
- constructor() {
8181
- super('Your API token was rejected (401). Run "plune login" again with a fresh token.');
9703
+ constructor(apiUrl = resolveApiUrl()) {
9704
+ super(`Your API token was rejected (401). Run "plune login" again with a fresh token. ${tokenRefusedBy(apiUrl)}`);
8182
9705
  this.name = "IngestTokenRejectedError";
8183
9706
  }
8184
9707
  };
@@ -8374,7 +9897,7 @@ async function handleIngest(deps) {
8374
9897
  }
8375
9898
  if (!res.ok) {
8376
9899
  const detail = await safeErrorDetail2(res);
8377
- if (res.status === 401) throw new IngestTokenRejectedError();
9900
+ if (res.status === 401) throw new IngestTokenRejectedError(apiUrl);
8378
9901
  throw new IngestHttpError(res.status, detail);
8379
9902
  }
8380
9903
  const body = await res.json().catch(() => ({}));