@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.js CHANGED
@@ -26,8 +26,8 @@ function machineless(raw, repoRoot, home) {
26
26
  let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
27
27
  const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
28
28
  if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
29
- const own2 = pathIn(home);
30
- if (own2 !== void 0) text = text.replace(new RegExp(`${PATH_START}${own2.source}(?![\\w.-])`, own2.flags), "~");
29
+ const own3 = pathIn(home);
30
+ if (own3 !== void 0) text = text.replace(new RegExp(`${PATH_START}${own3.source}(?![\\w.-])`, own3.flags), "~");
31
31
  if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
32
32
  return text;
33
33
  }
@@ -66,17 +66,17 @@ var init_exit_codes = __esm({
66
66
 
67
67
  // src/mcp-testing/connect/journal.ts
68
68
  import { closeSync, fchmodSync, openSync, writeSync } from "fs";
69
- import { performance } from "perf_hooks";
69
+ import { performance as performance2 } from "perf_hooks";
70
70
  function openJournal(path12, redact) {
71
71
  if (path12 === void 0) return NONE;
72
72
  const fd = openSync(path12, "w", 384);
73
73
  if (process.platform !== "win32") fchmodSync(fd, 384);
74
- const start = performance.now();
74
+ const start2 = performance2.now();
75
75
  let closed = false;
76
76
  return {
77
77
  write(dir, fields) {
78
78
  if (closed) return;
79
- const dtMs = Math.round((performance.now() - start) * 1e3) / 1e3;
79
+ const dtMs = Math.round((performance2.now() - start2) * 1e3) / 1e3;
80
80
  const line = {
81
81
  ts: (/* @__PURE__ */ new Date()).toISOString(),
82
82
  dtMs,
@@ -231,11 +231,11 @@ function maskUrl(raw) {
231
231
  } catch {
232
232
  return raw;
233
233
  }
234
- if (url.username !== "") url.username = MASK;
235
- if (url.password !== "") url.password = MASK;
234
+ if (url.username !== "") url.username = MASK2;
235
+ if (url.password !== "") url.password = MASK2;
236
236
  for (const name of [...url.searchParams.keys()])
237
- if (SECRET_QUERY.has(name.toLowerCase())) url.searchParams.set(name, MASK);
238
- return url.href.replaceAll("%2A%2A%2A", MASK);
237
+ if (SECRET_QUERY.has(name.toLowerCase())) url.searchParams.set(name, MASK2);
238
+ return url.href.replaceAll("%2A%2A%2A", MASK2);
239
239
  }
240
240
  function secretsOf(target) {
241
241
  const secrets = { values: [], named: [], urls: [] };
@@ -286,7 +286,7 @@ function createRedactor(secrets, opts = {}) {
286
286
  const ordered = longestFirst(forms);
287
287
  const urls = longestFirst(opts.url?.raw ?? []).filter((raw) => raw !== "");
288
288
  const text = (input) => ordered.reduce(
289
- (out, secret) => out.replaceAll(secret, MASK),
289
+ (out, secret) => out.replaceAll(secret, MASK2),
290
290
  urls.reduce((out, raw) => out.replaceAll(raw, opts.url.masked), input)
291
291
  );
292
292
  const value = (input, depth = 0) => {
@@ -311,7 +311,7 @@ function describeTarget(target, redact) {
311
311
  const masked = (entries, secret) => Object.fromEntries(
312
312
  Object.entries(entries).map(([name, value]) => [
313
313
  name,
314
- secret(name) ? MASK : redact.text(value)
314
+ secret(name) ? MASK2 : redact.text(value)
315
315
  ])
316
316
  );
317
317
  if (target.kind === "stdio") {
@@ -329,12 +329,12 @@ function describeTarget(target, redact) {
329
329
  headers: masked(target.headers, isSecretHeader)
330
330
  };
331
331
  }
332
- var MASK, MIN_SECRET_LENGTH, MAX_DEPTH, SECRET_HEADERS, SECRET_HEADER_PART, SECRET_ENV_PART, SECRET_QUERY, isSecretHeader, isSecretEnv, decoded, rawQuery;
332
+ var MASK2, MIN_SECRET_LENGTH, MAX_DEPTH, SECRET_HEADERS, SECRET_HEADER_PART, SECRET_ENV_PART, SECRET_QUERY, isSecretHeader, isSecretEnv, decoded, rawQuery;
333
333
  var init_redact = __esm({
334
334
  "src/mcp-testing/connect/redact.ts"() {
335
335
  "use strict";
336
336
  init_esm_shims();
337
- MASK = "***";
337
+ MASK2 = "***";
338
338
  MIN_SECRET_LENGTH = 8;
339
339
  MAX_DEPTH = 64;
340
340
  SECRET_HEADERS = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie"]);
@@ -435,10 +435,10 @@ function readLines(stream, onLine, stats) {
435
435
  partial = rest.slice(0, STDERR_LINE_LIMIT);
436
436
  };
437
437
  return new Promise((resolve9) => {
438
- let done = false;
438
+ let done2 = false;
439
439
  const finish = () => {
440
- if (done) return;
441
- done = true;
440
+ if (done2) return;
441
+ done2 = true;
442
442
  feed(decoder.end());
443
443
  if (partial !== "") onLine(partial.endsWith("\r") ? partial.slice(0, -1) : partial);
444
444
  resolve9();
@@ -500,9 +500,9 @@ function intercept(transport, name, before) {
500
500
  });
501
501
  }
502
502
  function watchStdout(transport, journal, seen) {
503
- const start = transport.start.bind(transport);
503
+ const start2 = transport.start.bind(transport);
504
504
  transport.start = async () => {
505
- await start();
505
+ await start2();
506
506
  const stdout = transport._process?.stdout;
507
507
  if (stdout === null || stdout === void 0) return;
508
508
  createInterface({ input: stdout, crlfDelay: Infinity }).on("line", (line) => {
@@ -712,7 +712,7 @@ async function openSession(config, options = {}) {
712
712
  },
713
713
  fetchForOrigin(origin) {
714
714
  const allowed = new URL(origin).origin;
715
- const own2 = target.kind !== "stdio" && new URL(target.url).origin === allowed;
715
+ const own3 = target.kind !== "stdio" && new URL(target.url).origin === allowed;
716
716
  return async (input, init) => {
717
717
  const url = new URL(input);
718
718
  if (url.origin !== allowed)
@@ -720,7 +720,7 @@ async function openSession(config, options = {}) {
720
720
  `fetchForOrigin(${allowed}) refuses a request to another origin, ${url.origin}.`
721
721
  );
722
722
  const headers = new Headers(init?.headers);
723
- if (own2) {
723
+ if (own3) {
724
724
  for (const [name, value] of Object.entries(target.headers))
725
725
  if (!headers.has(name)) headers.set(name, value);
726
726
  }
@@ -740,23 +740,23 @@ async function openSession(config, options = {}) {
740
740
  if (stdin === null || stdin === void 0 || stdin.writableEnded)
741
741
  throw spawnError !== void 0 ? await toConnectError(spawnError) : new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
742
742
  return new Promise((resolve9, reject) => {
743
- const done = () => {
743
+ const done2 = () => {
744
744
  clearTimeout(timer2);
745
745
  listeners.delete(listener);
746
746
  stopped.delete(stop);
747
747
  };
748
748
  const timer2 = setTimeout(() => {
749
- done();
749
+ done2();
750
750
  reject(noAnswer());
751
751
  }, ms);
752
752
  const listener = (line) => {
753
753
  const frame2 = parsed(line);
754
754
  if (!answers(frame2, id)) return;
755
- done();
755
+ done2();
756
756
  resolve9({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
757
757
  };
758
758
  const stop = () => {
759
- done();
759
+ done2();
760
760
  void toConnectError(spawnError ?? new Error("closed")).then(reject);
761
761
  };
762
762
  listeners.add(listener);
@@ -794,8 +794,8 @@ async function openSession(config, options = {}) {
794
794
  const reader = res.body.getReader();
795
795
  const decoder = new TextDecoder();
796
796
  for (; ; ) {
797
- const { done, value } = await reader.read();
798
- if (done) break;
797
+ const { done: done2, value } = await reader.read();
798
+ if (done2) break;
799
799
  text += decoder.decode(value, { stream: true });
800
800
  if (sse && (frame = fromEventStream(text, id)) !== void 0) break;
801
801
  if (text.length > STDIO_MESSAGE_LIMIT) break;
@@ -1027,13 +1027,13 @@ init_esm_shims();
1027
1027
 
1028
1028
  // src/cli/commands/run.ts
1029
1029
  init_esm_shims();
1030
- import * as fs5 from "fs";
1030
+ import * as fs6 from "fs";
1031
1031
  import * as path6 from "path";
1032
1032
 
1033
1033
  // src/config/loader.ts
1034
1034
  init_esm_shims();
1035
1035
  import * as fs2 from "fs/promises";
1036
- import { parse } from "yaml";
1036
+ import { parse as parse2 } from "yaml";
1037
1037
 
1038
1038
  // src/config/env-overrides.ts
1039
1039
  init_esm_shims();
@@ -1068,6 +1068,628 @@ var ConfigValidationError = class extends Error {
1068
1068
  init_esm_shims();
1069
1069
  import { z } from "zod";
1070
1070
 
1071
+ // src/json-verify/compare.ts
1072
+ init_esm_shims();
1073
+
1074
+ // src/json-verify/functions.ts
1075
+ init_esm_shims();
1076
+
1077
+ // src/json-verify/regex.ts
1078
+ init_esm_shims();
1079
+ var MAX_REGEX_NODES = 2e3;
1080
+ var SHORTHAND = { d: /\d/, w: /\w/, s: /\s/ };
1081
+ var CONTROL = { n: 10, r: 13, t: 9, f: 12, v: 11, "0": 0 };
1082
+ var SIMPLE_REPEAT = { "*": [0, Infinity], "+": [1, Infinity], "?": [0, 1] };
1083
+ var LINE_ENDS = /* @__PURE__ */ new Set([10, 13, 8232, 8233]);
1084
+ var QUANTIFIER = /[*+?]|\{(\d+)(?:(,)(\d*))?\}/y;
1085
+ function caseClass(code) {
1086
+ const upper = String.fromCharCode(code).toUpperCase();
1087
+ if (upper.length !== 1) return code;
1088
+ const folded = upper.charCodeAt(0);
1089
+ return code >= 128 && folded < 128 ? code : folded;
1090
+ }
1091
+ var caseClasses;
1092
+ function sameCase(code) {
1093
+ if (caseClasses === void 0) {
1094
+ const all = /* @__PURE__ */ new Map();
1095
+ for (let c = 0; c < 65536; c++) {
1096
+ const key = caseClass(c);
1097
+ const members = all.get(key);
1098
+ if (members === void 0) all.set(key, [c]);
1099
+ else members.push(c);
1100
+ }
1101
+ caseClasses = new Map([...all].filter(([, members]) => members.length > 1));
1102
+ }
1103
+ return caseClasses.get(caseClass(code)) ?? [code];
1104
+ }
1105
+ function parse(pattern, flags) {
1106
+ let i = 0;
1107
+ const fail2 = (what) => new Error(`${what} (character ${i} of the pattern)`);
1108
+ const ignoreCase = flags.includes("i");
1109
+ const fold = (test) => ignoreCase ? (code) => sameCase(code).some(test) : test;
1110
+ const literal = (code) => fold((c) => c === code);
1111
+ const shorthand = (e) => {
1112
+ const re = SHORTHAND[e.toLowerCase()];
1113
+ if (re === void 0) return void 0;
1114
+ const negated = e !== e.toLowerCase();
1115
+ return (code) => re.test(String.fromCharCode(code)) !== negated;
1116
+ };
1117
+ const escaped = (e) => {
1118
+ if (e === void 0) throw fail2("a backslash ends the pattern");
1119
+ if (e === "0" && /\d/.test(pattern[i] ?? "")) throw fail2("\\0 before a digit is not supported");
1120
+ const control = CONTROL[e];
1121
+ if (control !== void 0) return control;
1122
+ if (/[A-Za-z0-9]/.test(e)) throw fail2(`\\${e} is not supported`);
1123
+ return e.charCodeAt(0);
1124
+ };
1125
+ const classAtom = () => {
1126
+ const ch = pattern[i++];
1127
+ if (ch === void 0) throw fail2("a character class is not closed");
1128
+ if (ch !== "\\") return ch.charCodeAt(0);
1129
+ const e = pattern[i++];
1130
+ if (e === "b") return 8;
1131
+ return (e === void 0 ? void 0 : shorthand(e)) ?? escaped(e);
1132
+ };
1133
+ const parseClass = () => {
1134
+ const negated = pattern[i] === "^";
1135
+ if (negated) i++;
1136
+ const tests = [];
1137
+ while (pattern[i] !== "]") {
1138
+ const low = classAtom();
1139
+ if (typeof low !== "number") tests.push(low);
1140
+ else if (pattern[i] === "-" && pattern[i + 1] !== "]") {
1141
+ i++;
1142
+ const high = classAtom();
1143
+ if (typeof high !== "number" || high < low) throw fail2("a range in a character class is out of order");
1144
+ tests.push(fold((c) => c >= low && c <= high));
1145
+ } else tests.push(literal(low));
1146
+ }
1147
+ i++;
1148
+ return (code) => tests.some((test) => test(code)) !== negated;
1149
+ };
1150
+ const parseAtom = () => {
1151
+ const ch = pattern[i++];
1152
+ if (ch === "(") {
1153
+ if (pattern[i] === "?") {
1154
+ if (pattern[i + 1] !== ":") throw fail2("lookahead, lookbehind and named groups are not supported");
1155
+ i += 2;
1156
+ }
1157
+ const options2 = parseOptions();
1158
+ if (pattern[i] !== ")") throw fail2("a group is not closed");
1159
+ i++;
1160
+ return { t: "group", options: options2 };
1161
+ }
1162
+ if (ch === "[") return { t: "char", test: parseClass() };
1163
+ if (ch === ".") return { t: "char", test: flags.includes("s") ? () => true : (c) => !LINE_ENDS.has(c) };
1164
+ if (ch === "^" || ch === "$") return { t: "anchor", kind: ch };
1165
+ QUANTIFIER.lastIndex = i - 1;
1166
+ if (QUANTIFIER.test(pattern)) throw fail2("nothing to repeat");
1167
+ if (ch !== "\\") return { t: "char", test: literal(ch.charCodeAt(0)) };
1168
+ const e = pattern[i++];
1169
+ if (e === "b" || e === "B") return { t: "anchor", kind: e };
1170
+ const set = e === void 0 ? void 0 : shorthand(e);
1171
+ return { t: "char", test: set ?? literal(escaped(e)) };
1172
+ };
1173
+ const parseRepeat = (atom) => {
1174
+ QUANTIFIER.lastIndex = i;
1175
+ const m = QUANTIFIER.exec(pattern);
1176
+ if (m === null) return atom;
1177
+ i += m[0].length;
1178
+ if (atom.t === "anchor") throw fail2("an anchor cannot be repeated");
1179
+ const least = Number(m[1]);
1180
+ const counted = [least, m[2] === void 0 ? least : m[3] === "" ? Infinity : Number(m[3])];
1181
+ const [min, max] = SIMPLE_REPEAT[m[0]] ?? counted;
1182
+ if (max < min) throw fail2("a repeat has its numbers out of order");
1183
+ if (pattern[i] === "?") i++;
1184
+ return { t: "repeat", node: atom, min, max };
1185
+ };
1186
+ function parseOptions() {
1187
+ const options2 = [[]];
1188
+ while (i < pattern.length && pattern[i] !== ")") {
1189
+ if (pattern[i] === "|") {
1190
+ i++;
1191
+ options2.push([]);
1192
+ } else options2[options2.length - 1].push(parseRepeat(parseAtom()));
1193
+ }
1194
+ return options2;
1195
+ }
1196
+ const options = parseOptions();
1197
+ if (i < pattern.length) throw fail2('a ")" has no group to close');
1198
+ return options;
1199
+ }
1200
+ var CHAR = 0;
1201
+ var SPLIT = 1;
1202
+ var ANCHOR = 2;
1203
+ var MATCH = 3;
1204
+ var isWord = (text, at) => at >= 0 && at < text.length && /\w/.test(text[at]);
1205
+ function compileRegex(pattern, flags = "") {
1206
+ const options = parse(pattern, flags);
1207
+ const multiline = flags.includes("m");
1208
+ const states = [{ kind: MATCH, next: 0, other: 0 }];
1209
+ const tooLarge = () => new Error(`the pattern is too large once its repeats are written out (over ${MAX_REGEX_NODES} parts)`);
1210
+ const add = (state) => {
1211
+ if (states.length > MAX_REGEX_NODES) throw tooLarge();
1212
+ return states.push(state) - 1;
1213
+ };
1214
+ let built = 0;
1215
+ const build = (node, next) => {
1216
+ if (++built > MAX_REGEX_NODES) throw tooLarge();
1217
+ if (node.t === "char") return add({ kind: CHAR, next, other: 0, test: node.test });
1218
+ if (node.t === "anchor") return add({ kind: ANCHOR, next, other: 0, anchor: node.kind });
1219
+ if (node.t === "group") return buildOptions(node.options, next);
1220
+ let enter = next;
1221
+ if (node.max === Infinity) {
1222
+ enter = add({ kind: SPLIT, next: 0, other: next });
1223
+ states[enter].next = build(node.node, enter);
1224
+ } else
1225
+ for (let k = node.min; k < node.max; k++)
1226
+ enter = add({ kind: SPLIT, next: build(node.node, enter), other: enter });
1227
+ for (let k = 0; k < node.min; k++) enter = build(node.node, enter);
1228
+ return enter;
1229
+ };
1230
+ 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 }));
1231
+ const start2 = buildOptions(options, 0);
1232
+ const holds = (anchor, text, at) => {
1233
+ if (anchor === "b" || anchor === "B") return isWord(text, at - 1) !== isWord(text, at) === (anchor === "b");
1234
+ const edge = anchor === "^" ? at === 0 : at === text.length;
1235
+ return edge || multiline && LINE_ENDS.has(text.charCodeAt(anchor === "^" ? at - 1 : at));
1236
+ };
1237
+ return (text) => {
1238
+ const seen = new Int32Array(states.length).fill(-1);
1239
+ let matched = false;
1240
+ const enter = (list2, from, at2) => {
1241
+ const stack = [from];
1242
+ while (stack.length > 0) {
1243
+ const s = stack.pop();
1244
+ if (seen[s] === at2) continue;
1245
+ seen[s] = at2;
1246
+ const state = states[s];
1247
+ if (state.kind === SPLIT) stack.push(state.next, state.other);
1248
+ else if (state.kind === ANCHOR) {
1249
+ if (holds(state.anchor, text, at2)) stack.push(state.next);
1250
+ } else if (state.kind === MATCH) matched = true;
1251
+ else list2.push(s);
1252
+ }
1253
+ };
1254
+ let current = [];
1255
+ let at = 0;
1256
+ enter(current, start2, 0);
1257
+ while (!matched && at < text.length) {
1258
+ const code = text.charCodeAt(at++);
1259
+ const following = [];
1260
+ for (const s of current) if (states[s].test(code)) enter(following, states[s].next, at);
1261
+ enter(following, start2, at);
1262
+ current = following;
1263
+ }
1264
+ return matched;
1265
+ };
1266
+ }
1267
+
1268
+ // src/json-verify/functions.ts
1269
+ var MAX_REGEX_INPUT = 1e4;
1270
+ var MAX_REGEX_PATTERN = 500;
1271
+ var none = (args) => args.length === 0 ? void 0 : "takes no arguments";
1272
+ var oneNumber = (args) => args.length === 1 && typeof args[0] === "number" ? void 0 : "takes one number";
1273
+ var oneLength = (args) => args.length === 1 && Number.isInteger(args[0]) && args[0] >= 0 ? void 0 : "takes one whole number, 0 or more";
1274
+ var lengthOf = (v) => typeof v === "string" || Array.isArray(v) ? v.length : void 0;
1275
+ var is = (test) => ({ args: none, test });
1276
+ var matchers = /* @__PURE__ */ new Map();
1277
+ function matcher(pattern, flags) {
1278
+ const key = `${flags}/${pattern}`;
1279
+ let compiled = matchers.get(key);
1280
+ if (compiled === void 0) {
1281
+ compiled = compileRegex(pattern, flags);
1282
+ if (matchers.size >= 100) matchers.clear();
1283
+ matchers.set(key, compiled);
1284
+ }
1285
+ return compiled;
1286
+ }
1287
+ function regexArgs(args) {
1288
+ const [pattern, flags = ""] = args;
1289
+ if (args.length < 1 || args.length > 2 || typeof pattern !== "string" || typeof flags !== "string")
1290
+ return "takes a pattern in quotes and, optionally, flags in quotes";
1291
+ if (!/^(?!.*(.).*\1)[ims]*$/.test(flags)) return `takes the flags i, m and s, each at most once; got "${flags}"`;
1292
+ if (pattern.length > MAX_REGEX_PATTERN)
1293
+ return `takes a pattern of at most ${MAX_REGEX_PATTERN} characters; got ${pattern.length}`;
1294
+ try {
1295
+ matcher(pattern, flags);
1296
+ } catch (err) {
1297
+ return `has a pattern it cannot run: ${err.message}`;
1298
+ }
1299
+ return void 0;
1300
+ }
1301
+ var CHECK_FUNCTIONS = {
1302
+ isNotNull: is((v) => v !== null),
1303
+ isString: is((v) => typeof v === "string"),
1304
+ isNumber: is((v) => typeof v === "number"),
1305
+ isBoolean: is((v) => typeof v === "boolean"),
1306
+ isArray: is((v) => Array.isArray(v)),
1307
+ isObject: is((v) => typeof v === "object" && v !== null && !Array.isArray(v)),
1308
+ matchesRegex: {
1309
+ args: regexArgs,
1310
+ test(v, [pattern, flags]) {
1311
+ if (typeof v !== "string") return false;
1312
+ if (v.length > MAX_REGEX_INPUT)
1313
+ return `the value is ${v.length} characters long and a pattern is not run on more than ${MAX_REGEX_INPUT}`;
1314
+ return matcher(pattern, flags ?? "")(v);
1315
+ }
1316
+ },
1317
+ minLength: { args: oneLength, test: (v, [n]) => (lengthOf(v) ?? -1) >= n },
1318
+ maxLength: { args: oneLength, test: (v, [n]) => (lengthOf(v) ?? Infinity) <= n },
1319
+ gt: { args: oneNumber, test: (v, [n]) => typeof v === "number" && v > n },
1320
+ lt: { args: oneNumber, test: (v, [n]) => typeof v === "number" && v < n },
1321
+ oneOf: {
1322
+ args: (args) => args.length > 0 ? void 0 : "takes at least one value",
1323
+ test: (v, args) => args.includes(v)
1324
+ }
1325
+ };
1326
+ var known = (name) => Object.prototype.hasOwnProperty.call(CHECK_FUNCTIONS, name);
1327
+ var CheckSyntaxError = class extends Error {
1328
+ constructor(message) {
1329
+ super(message);
1330
+ this.name = "CheckSyntaxError";
1331
+ }
1332
+ };
1333
+ var CALL_START = /^@([A-Za-z_]\w*)(\()?/;
1334
+ var BARE_ARG = /^(?:-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)$/;
1335
+ function parseArgs(s, from, name) {
1336
+ const args = [];
1337
+ const bad = (what, at) => new CheckSyntaxError(`@${name}: ${what} at character ${at + 1} of ${JSON.stringify(s)}`);
1338
+ let i = from;
1339
+ const skipSpaces = () => {
1340
+ while (s[i] === " ") i++;
1341
+ };
1342
+ skipSpaces();
1343
+ if (s[i] === ")") return [args, i + 1];
1344
+ for (; ; ) {
1345
+ const quote = s[i];
1346
+ if (quote === '"' || quote === "'") {
1347
+ let text = "";
1348
+ for (i++; s[i] !== quote; i++) {
1349
+ if (i >= s.length) throw bad("a string is not closed", from);
1350
+ if (s[i] === "\\" && s[i + 1] === quote) i++;
1351
+ text += s[i];
1352
+ }
1353
+ i++;
1354
+ args.push(text);
1355
+ } else {
1356
+ const start2 = i;
1357
+ while (i < s.length && !" ,)".includes(s[i])) i++;
1358
+ const token = s.slice(start2, i);
1359
+ if (!BARE_ARG.test(token))
1360
+ throw bad(
1361
+ `argument ${args.length + 1} must be a number, true, false, null or a string in quotes, got ${JSON.stringify(token)}`,
1362
+ start2
1363
+ );
1364
+ const value = JSON.parse(token);
1365
+ if (typeof value === "number" && !Number.isFinite(value))
1366
+ throw bad(`argument ${args.length + 1} is not a finite number, got ${JSON.stringify(token)}`, start2);
1367
+ args.push(value);
1368
+ }
1369
+ skipSpaces();
1370
+ if (s[i] === ")") return [args, i + 1];
1371
+ if (s[i] !== ",") throw bad('expected "," or ")"', i);
1372
+ i++;
1373
+ skipSpaces();
1374
+ }
1375
+ }
1376
+ function parseExpectedString(s) {
1377
+ if (s.startsWith("@@")) return { literal: s.slice(1) };
1378
+ const first2 = CALL_START.exec(s);
1379
+ if (first2 === null) return { literal: s };
1380
+ if (first2[2] === void 0) {
1381
+ const after = s[first2[0].length];
1382
+ if (known(first2[1]) && (after === void 0 || after === " "))
1383
+ throw new CheckSyntaxError(
1384
+ `@${first2[1]} needs parentheses to be a check: @${first2[1]}(); for the text itself write @${s}`
1385
+ );
1386
+ return { literal: s };
1387
+ }
1388
+ const checks = [];
1389
+ let i = 0;
1390
+ while (i < s.length) {
1391
+ const call = CALL_START.exec(s.slice(i));
1392
+ if (call === null || call[2] === void 0)
1393
+ throw new CheckSyntaxError(
1394
+ `expected a check such as @isString() at character ${i + 1} of ${JSON.stringify(s)}; for the text itself write @${s}`
1395
+ );
1396
+ const name = call[1];
1397
+ if (!known(name))
1398
+ throw new CheckSyntaxError(
1399
+ `@${name} is not a check function (known: ${Object.keys(CHECK_FUNCTIONS).join(", ")}); for the text itself write @${s}`
1400
+ );
1401
+ const [args, end] = parseArgs(s, i + call[0].length, name);
1402
+ const text = s.slice(i, end);
1403
+ const wrong = CHECK_FUNCTIONS[name].args(args);
1404
+ if (wrong !== void 0) throw new CheckSyntaxError(`@${name} ${wrong}; got ${text}`);
1405
+ checks.push({ name, args, text });
1406
+ i = end;
1407
+ if (i < s.length && s[i] !== " ")
1408
+ throw new CheckSyntaxError(`checks are separated by a space: character ${i + 1} of ${JSON.stringify(s)}`);
1409
+ while (s[i] === " ") i++;
1410
+ }
1411
+ return { checks };
1412
+ }
1413
+ function firstFailedCheck(checks, actual) {
1414
+ for (const check3 of checks) {
1415
+ const result = CHECK_FUNCTIONS[check3.name].test(actual, check3.args);
1416
+ if (result === true) continue;
1417
+ return typeof result === "string" ? { check: check3, note: result } : { check: check3 };
1418
+ }
1419
+ return void 0;
1420
+ }
1421
+
1422
+ // src/json-verify/compare.ts
1423
+ var COMPARE_MODES = ["exact", "unordered", "contains"];
1424
+ var ExpectedJsonError = class extends Error {
1425
+ constructor(path12, message) {
1426
+ super(`${path12}: ${message}`);
1427
+ this.path = path12;
1428
+ this.name = "ExpectedJsonError";
1429
+ }
1430
+ path;
1431
+ };
1432
+ var MAX_MATCH_STEPS = 2e6;
1433
+ var MAX_INDEXED_KEYS = 50;
1434
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1435
+ var own = (o, key) => Object.prototype.hasOwnProperty.call(o, key);
1436
+ var typeOf = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
1437
+ var PLAIN_KEY = /^[A-Za-z_$][\w$]*$/;
1438
+ var keyPath = (path12, key) => PLAIN_KEY.test(key) ? `${path12}.${key}` : `${path12}[${JSON.stringify(key)}]`;
1439
+ function readMarker(exp) {
1440
+ const keys = Object.keys(exp);
1441
+ if (own(exp, "$literal")) {
1442
+ if (keys.length !== 1)
1443
+ return 'an object with $literal must have no other key; data with a key $literal goes inside {"$literal": ...}';
1444
+ return { value: exp.$literal, literal: true };
1445
+ }
1446
+ if (!own(exp, "$mode")) return void 0;
1447
+ if (keys.length !== 2 || !own(exp, "$value"))
1448
+ return 'an object with $mode must have exactly the keys $mode and $value; data with a key $mode goes inside {"$literal": ...}';
1449
+ const mode = exp.$mode;
1450
+ if (!COMPARE_MODES.includes(mode))
1451
+ return `$mode must be one of ${COMPARE_MODES.join(", ")}; got ${JSON.stringify(exp.$mode)}`;
1452
+ return { value: exp.$value, mode, literal: false };
1453
+ }
1454
+ var MAX_EXPECTED_DEPTH = 100;
1455
+ var JSON_LEAF = /* @__PURE__ */ new Set(["string", "number", "boolean", "object"]);
1456
+ function validateExpected(expected) {
1457
+ const issues = [];
1458
+ const visit = (exp, path12, depth, literal) => {
1459
+ if (depth > MAX_EXPECTED_DEPTH) {
1460
+ issues.push({ path: path12, message: `expected is nested deeper than ${MAX_EXPECTED_DEPTH} levels` });
1461
+ } else if (Array.isArray(exp)) {
1462
+ exp.forEach((item, i) => visit(item, `${path12}[${i}]`, depth + 1, literal));
1463
+ } else if (isObject(exp)) {
1464
+ const proto = Object.getPrototypeOf(exp);
1465
+ const marker = literal ? void 0 : readMarker(exp);
1466
+ if (proto !== Object.prototype && proto !== null)
1467
+ issues.push({ path: path12, message: "an object that is not plain JSON data" });
1468
+ else if (own(exp, "__proto__"))
1469
+ issues.push({ path: keyPath(path12, "__proto__"), message: "the key __proto__ is not supported in expected" });
1470
+ else if (typeof marker === "string") issues.push({ path: path12, message: marker });
1471
+ else if (marker === void 0)
1472
+ for (const key of Object.keys(exp)) visit(exp[key], keyPath(path12, key), depth + 1, literal);
1473
+ else visit(marker.value, path12, depth + 1, marker.literal);
1474
+ } else if (!literal && typeof exp === "string") {
1475
+ try {
1476
+ parseExpectedString(exp);
1477
+ } catch (err) {
1478
+ issues.push({ path: path12, message: err.message });
1479
+ }
1480
+ } else if (!JSON_LEAF.has(typeof exp) || typeof exp === "number" && !Number.isFinite(exp)) {
1481
+ const what = typeof exp === "number" || exp === void 0 ? String(exp) : `a ${typeof exp}`;
1482
+ issues.push({ path: path12, message: `${what} is not a JSON value` });
1483
+ }
1484
+ };
1485
+ visit(expected, "$", 0, false);
1486
+ return issues;
1487
+ }
1488
+ var done = (sink) => sink.list.length >= sink.limit || sink.budget.spent !== void 0;
1489
+ function walk(exp, act, mode, path12, sink, literal) {
1490
+ if (!literal && isObject(exp)) {
1491
+ const marker = readMarker(exp);
1492
+ if (marker !== void 0) {
1493
+ walk(marker.value, act, marker.mode ?? mode, path12, sink, marker.literal);
1494
+ return;
1495
+ }
1496
+ }
1497
+ if (!literal && typeof exp === "string") {
1498
+ const parsed2 = parseExpectedString(exp);
1499
+ if ("checks" in parsed2) {
1500
+ const failed = firstFailedCheck(parsed2.checks, act);
1501
+ if (failed !== void 0)
1502
+ sink.list.push({
1503
+ path: path12,
1504
+ reason: "function",
1505
+ expected: exp,
1506
+ actual: act,
1507
+ detail: failed.note === void 0 ? failed.check.text : `${failed.check.text}: ${failed.note}`
1508
+ });
1509
+ return;
1510
+ }
1511
+ exp = parsed2.literal;
1512
+ }
1513
+ if (typeOf(exp) !== typeOf(act)) {
1514
+ sink.list.push({ path: path12, reason: "type", expected: exp, actual: act });
1515
+ } else if (Array.isArray(exp)) {
1516
+ (mode === "exact" ? walkInOrder : walkAnyOrder)(exp, act, mode, path12, sink, literal);
1517
+ } else if (isObject(exp)) {
1518
+ walkObject(exp, act, mode, path12, sink, literal);
1519
+ } else if (exp !== act) {
1520
+ sink.list.push({ path: path12, reason: "value", expected: exp, actual: act });
1521
+ }
1522
+ }
1523
+ function walkObject(exp, act, mode, path12, sink, literal) {
1524
+ const keys = Object.keys(exp);
1525
+ if (sink.limit === 1) keys.sort((a, b) => Number(!isScalar(exp[a])) - Number(!isScalar(exp[b])));
1526
+ for (const key of keys) {
1527
+ if (done(sink)) return;
1528
+ const at = keyPath(path12, key);
1529
+ if (own(act, key)) walk(exp[key], act[key], mode, at, sink, literal);
1530
+ else sink.list.push({ path: at, reason: "missing-key", expected: exp[key] });
1531
+ }
1532
+ if (mode === "contains") return;
1533
+ for (const key of Object.keys(act))
1534
+ if (!own(exp, key)) sink.list.push({ path: keyPath(path12, key), reason: "extra-key", actual: act[key] });
1535
+ }
1536
+ function walkInOrder(exp, act, mode, path12, sink, literal) {
1537
+ const shared = Math.min(exp.length, act.length);
1538
+ for (let i = 0; i < shared && !done(sink); i++) walk(exp[i], act[i], mode, `${path12}[${i}]`, sink, literal);
1539
+ for (let i = shared; i < exp.length; i++)
1540
+ sink.list.push({ path: `${path12}[${i}]`, reason: "missing-element", expected: exp[i] });
1541
+ for (let i = shared; i < act.length; i++)
1542
+ sink.list.push({ path: `${path12}[${i}]`, reason: "extra-element", actual: act[i] });
1543
+ }
1544
+ var isScalar = (v) => typeof v !== "object" || v === null;
1545
+ function plainScalar(e, literal) {
1546
+ if (!isScalar(e)) return void 0;
1547
+ if (literal || typeof e !== "string") return { value: e };
1548
+ const parsed2 = parseExpectedString(e);
1549
+ return "literal" in parsed2 ? { value: parsed2.literal } : void 0;
1550
+ }
1551
+ var scalarKey = (v) => `${typeOf(v)}:${String(v)}`;
1552
+ function walkAnyOrder(exp, act, mode, path12, sink, literal) {
1553
+ const probing = sink.limit === 1;
1554
+ if (probing && (mode === "unordered" ? exp.length !== act.length : exp.length > act.length)) {
1555
+ sink.list.push({ path: path12, reason: "no-match" });
1556
+ return;
1557
+ }
1558
+ const { budget } = sink;
1559
+ const taken = new Uint8Array(act.length);
1560
+ const unmatched = [];
1561
+ const rest = [];
1562
+ const scalars = /* @__PURE__ */ new Map();
1563
+ for (let j = act.length - 1; j >= 0; j--) {
1564
+ if (!isScalar(act[j])) continue;
1565
+ const key = scalarKey(act[j]);
1566
+ const at = scalars.get(key);
1567
+ if (at === void 0) scalars.set(key, [j]);
1568
+ else at.push(j);
1569
+ }
1570
+ exp.forEach((e, i) => {
1571
+ const plain = plainScalar(e, literal);
1572
+ if (plain === void 0) return rest.push(i);
1573
+ const j = scalars.get(scalarKey(plain.value))?.pop();
1574
+ if (j === void 0) return unmatched.push(i);
1575
+ taken[j] = 1;
1576
+ });
1577
+ if (rest.length > 0 && !(probing && unmatched.length > 0)) {
1578
+ const open2 = [];
1579
+ for (let j = 0; j < act.length; j++) if (taken[j] === 0) open2.push(j);
1580
+ const fits = /* @__PURE__ */ new Map();
1581
+ const fit = (e, c) => {
1582
+ const at = e * open2.length + c;
1583
+ let known2 = fits.get(at);
1584
+ if (known2 === void 0) {
1585
+ if (--budget.steps < 0) {
1586
+ budget.spent = {
1587
+ path: path12,
1588
+ reason: "too-large",
1589
+ detail: `matching arrays in any order took more than ${MAX_MATCH_STEPS} comparisons of elements`
1590
+ };
1591
+ return false;
1592
+ }
1593
+ const probe = { list: [], limit: 1, budget };
1594
+ walk(exp[rest[e]], act[open2[c]], mode, path12, probe, literal);
1595
+ known2 = probe.list.length === 0;
1596
+ fits.set(at, known2);
1597
+ }
1598
+ return known2;
1599
+ };
1600
+ const all = open2.map((_, c) => c);
1601
+ const index = /* @__PURE__ */ new Map();
1602
+ const withValue = (key, value) => {
1603
+ let byValue = index.get(key);
1604
+ if (byValue === void 0) {
1605
+ if (index.size === MAX_INDEXED_KEYS) return void 0;
1606
+ byValue = /* @__PURE__ */ new Map();
1607
+ for (let c = 0; c < open2.length; c++) {
1608
+ const a = act[open2[c]];
1609
+ if (!isObject(a) || !own(a, key) || !isScalar(a[key])) continue;
1610
+ const list2 = byValue.get(scalarKey(a[key]));
1611
+ if (list2 === void 0) byValue.set(scalarKey(a[key]), [c]);
1612
+ else list2.push(c);
1613
+ }
1614
+ index.set(key, byValue);
1615
+ }
1616
+ return byValue.get(value) ?? [];
1617
+ };
1618
+ const lists = /* @__PURE__ */ new Map();
1619
+ const candidates = (e) => {
1620
+ let best = lists.get(e);
1621
+ if (best !== void 0) return best;
1622
+ best = all;
1623
+ const x = exp[rest[e]];
1624
+ if (isObject(x) && (literal || readMarker(x) === void 0))
1625
+ for (const key of Object.keys(x)) {
1626
+ const plain = plainScalar(x[key], literal);
1627
+ const list2 = plain === void 0 ? void 0 : withValue(key, scalarKey(plain.value));
1628
+ if (list2 !== void 0 && list2.length < best.length) best = list2;
1629
+ }
1630
+ lists.set(e, best);
1631
+ return best;
1632
+ };
1633
+ const holder = new Int32Array(open2.length).fill(-1);
1634
+ const seen = new Int32Array(open2.length).fill(-1);
1635
+ const place = (root) => {
1636
+ const elements = [root];
1637
+ const tried = [0];
1638
+ const reached = [];
1639
+ while (elements.length > 0) {
1640
+ const top = elements.length - 1;
1641
+ const e = elements[top];
1642
+ const list2 = candidates(e);
1643
+ let deeper = false;
1644
+ while (!deeper && tried[top] < list2.length) {
1645
+ const c = list2[(e + tried[top]++) % list2.length];
1646
+ if (seen[c] === root) continue;
1647
+ if (!fit(e, c)) {
1648
+ if (budget.spent !== void 0) return false;
1649
+ continue;
1650
+ }
1651
+ seen[c] = root;
1652
+ reached[top] = c;
1653
+ if (holder[c] === -1) {
1654
+ for (let k = top; k >= 0; k--) holder[reached[k]] = elements[k];
1655
+ return true;
1656
+ }
1657
+ elements.push(holder[c]);
1658
+ tried.push(0);
1659
+ deeper = true;
1660
+ }
1661
+ if (!deeper) {
1662
+ elements.pop();
1663
+ tried.pop();
1664
+ }
1665
+ }
1666
+ return false;
1667
+ };
1668
+ for (let e = 0; e < rest.length; e++) {
1669
+ const placed = place(e);
1670
+ if (budget.spent !== void 0) return;
1671
+ if (placed) continue;
1672
+ unmatched.push(rest[e]);
1673
+ if (probing) break;
1674
+ }
1675
+ holder.forEach((e, c) => {
1676
+ if (e !== -1) taken[open2[c]] = 1;
1677
+ });
1678
+ }
1679
+ for (const i of unmatched.sort((a, b) => a - b))
1680
+ sink.list.push({ path: `${path12}[${i}]`, reason: "no-match", expected: exp[i] });
1681
+ if (mode === "contains") return;
1682
+ for (let j = 0; j < act.length; j++)
1683
+ if (taken[j] === 0) sink.list.push({ path: `${path12}[${j}]`, reason: "extra-element", actual: act[j] });
1684
+ }
1685
+ function compareJson(expected, actual, options = {}) {
1686
+ const issue = validateExpected(expected)[0];
1687
+ if (issue !== void 0) throw new ExpectedJsonError(issue.path, issue.message);
1688
+ const sink = { list: [], limit: Infinity, budget: { steps: MAX_MATCH_STEPS } };
1689
+ walk(expected, actual, options.mode ?? "exact", "$", sink, false);
1690
+ return sink.budget.spent === void 0 ? sink.list : [sink.budget.spent];
1691
+ }
1692
+
1071
1693
  // src/util/duration.ts
1072
1694
  init_esm_shims();
1073
1695
  var MAX_TIMER_MS = 2147483647;
@@ -1134,9 +1756,23 @@ var jsonSchemaAssertionSchema = z.object({
1134
1756
  schema: z.record(z.string(), z.unknown()),
1135
1757
  extract: z.enum(["auto", "strict"]).optional()
1136
1758
  });
1759
+ var jsonVerifyAssertionSchema = z.strictObject({
1760
+ type: z.literal("json-verify"),
1761
+ // Optional to the parser so that a missing one gets the message below, not "Invalid input".
1762
+ expected: z.any().optional(),
1763
+ mode: z.enum(COMPARE_MODES).optional(),
1764
+ extract: z.enum(["auto", "strict"]).optional()
1765
+ }).superRefine((a, ctx) => {
1766
+ if (a.expected === void 0)
1767
+ ctx.addIssue({ code: "custom", path: ["expected"], message: "expected is required (null is written as null)" });
1768
+ else
1769
+ for (const issue of validateExpected(a.expected))
1770
+ ctx.addIssue({ code: "custom", path: ["expected"], message: `${issue.path}: ${issue.message}` });
1771
+ });
1137
1772
  var jevJudgeSchema = z.strictObject({
1138
1773
  type: z.literal("jev"),
1139
- model: z.string().min(1),
1774
+ // A full version, never an alias: `jev-latest` would change the judge under a run without a word.
1775
+ model: 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"),
1140
1776
  timeout: providerTimeoutSchema.optional()
1141
1777
  });
1142
1778
  var partialProviderSchema = providerConfigSchema.partial();
@@ -1231,6 +1867,7 @@ var assertionConfigSchema = z.discriminatedUnion("type", [
1231
1867
  containsAnyAssertionSchema,
1232
1868
  containsAllAssertionSchema,
1233
1869
  jsonSchemaAssertionSchema,
1870
+ jsonVerifyAssertionSchema,
1234
1871
  llmJudgeAssertionSchema,
1235
1872
  semanticSimilarityAssertionSchema,
1236
1873
  faithfulnessAssertionSchema,
@@ -1264,14 +1901,14 @@ var mcpServersSchema = z.record(z.string().min(1), mcpServerSchema).superRefine(
1264
1901
  for (const [name, server] of Object.entries(servers)) {
1265
1902
  const issue = (message) => ctx.addIssue({ code: "custom", path: [name], message });
1266
1903
  const stdio = server.command !== void 0;
1267
- const http = server.url !== void 0;
1268
- if (stdio && http)
1904
+ const http2 = server.url !== void 0;
1905
+ if (stdio && http2)
1269
1906
  issue(`server "${name}" has both command and url; give command (stdio) or url (HTTP), not both`);
1270
- else if (!stdio && !http)
1907
+ else if (!stdio && !http2)
1271
1908
  issue(`server "${name}" needs command (a stdio server) or url (an HTTP server)`);
1272
1909
  else if (stdio && server.headers !== void 0)
1273
1910
  issue(`server "${name}": headers are for a server at url, not one started with command`);
1274
- else if (http && (server.args ?? server.env ?? server.cwd) !== void 0)
1911
+ else if (http2 && (server.args ?? server.env ?? server.cwd) !== void 0)
1275
1912
  issue(`server "${name}": args, env and cwd are for a server started with command, not one at url`);
1276
1913
  }
1277
1914
  });
@@ -1291,7 +1928,9 @@ var evalConfigSchema = z.object({
1291
1928
  dataset: datasetRefSchema,
1292
1929
  assertions: z.array(assertionConfigSchema),
1293
1930
  ...evalRepeatsShape,
1294
- mcp: evalMcpSchema.optional()
1931
+ mcp: evalMcpSchema.optional(),
1932
+ // The path of a stub file; the file itself is read and checked when the run starts.
1933
+ stubs: z.string().min(1).optional()
1295
1934
  }).refine(
1296
1935
  (data) => !(data.prompt !== void 0 && data.prompt_file !== void 0),
1297
1936
  { message: "prompt and prompt_file are mutually exclusive" }
@@ -1336,6 +1975,12 @@ var pluneConfigSchema = z.object({
1336
1975
  });
1337
1976
  }
1338
1977
  config.evals.forEach((evalConfig, i) => {
1978
+ if (evalConfig.stubs !== void 0 && evalConfig.mcp !== void 0)
1979
+ ctx.addIssue({
1980
+ code: "custom",
1981
+ path: ["evals", i, "stubs"],
1982
+ message: `eval "${evalConfig.id}" has both stubs and mcp: stubs answer the model call of an eval without mcp`
1983
+ });
1339
1984
  const server = evalConfig.mcp?.server;
1340
1985
  if (server === void 0) {
1341
1986
  const misplaced = (assertions, path12) => assertions.forEach((a, j) => {
@@ -1359,8 +2004,8 @@ var pluneConfigSchema = z.object({
1359
2004
  });
1360
2005
  }).transform(({ provider, ...rest }) => {
1361
2006
  if (!Array.isArray(provider)) return { provider, ...rest };
1362
- const [first, ...others] = provider;
1363
- return others.length === 0 ? { provider: first, ...rest } : { provider: first, providers: provider, ...rest };
2007
+ const [first2, ...others] = provider;
2008
+ return others.length === 0 ? { provider: first2, ...rest } : { provider: first2, providers: provider, ...rest };
1364
2009
  });
1365
2010
 
1366
2011
  // src/config/env-overrides.ts
@@ -1535,7 +2180,7 @@ async function loadConfig(opts = {}) {
1535
2180
  }
1536
2181
  let parsed2;
1537
2182
  try {
1538
- parsed2 = parse(raw);
2183
+ parsed2 = parse2(raw);
1539
2184
  } catch (err) {
1540
2185
  throw new YamlParseError(
1541
2186
  `YAML parse error in ${resolvedPath}: ${err.message}`
@@ -1729,6 +2374,9 @@ init_esm_shims();
1729
2374
  // src/providers/prices.ts
1730
2375
  init_esm_shims();
1731
2376
  var PRICE_TABLE = {
2377
+ // TypeSafe Jev, the experimental judge of `llm-judge`: input tokens only, its output is not billed.
2378
+ // Source: docs.typesafe.ai, read on 2026-11-24 (USD 0.042 per million input tokens).
2379
+ "jev-1.14.0": { input_per_1k_usd: 42e-6, output_per_1k_usd: 0 },
1732
2380
  // Anthropic, current models. Source: platform.claude.com/docs/en/about-claude/pricing — base
1733
2381
  // input and output tokens per million, read on 2026-09-29, kept here per thousand.
1734
2382
  "claude-fable-5-1": { input_per_1k_usd: 0.01, output_per_1k_usd: 0.05 },
@@ -1852,7 +2500,7 @@ function warnReasoningEffortNotSent(model, effort) {
1852
2500
  `
1853
2501
  );
1854
2502
  }
1855
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2503
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1856
2504
  function toAnthropicMessages(messages) {
1857
2505
  return messages.map((m) => {
1858
2506
  if (m.role === "user") return { role: "user", content: m.content };
@@ -1874,13 +2522,13 @@ function toAnthropicMessages(messages) {
1874
2522
  type: "tool_use",
1875
2523
  id: c.id,
1876
2524
  name: c.name,
1877
- input: isObject(c.args) ? c.args : {}
2525
+ input: isObject2(c.args) ? c.args : {}
1878
2526
  }))
1879
2527
  ]
1880
2528
  };
1881
2529
  });
1882
2530
  }
1883
- function makeAnthropicProvider(config, env, pricing) {
2531
+ function makeAnthropicProvider(config, env, pricing, stubOrigin) {
1884
2532
  const apiKey = env[ENV_VAR];
1885
2533
  if (apiKey === void 0 || apiKey.trim() === "") {
1886
2534
  throw new AuthError(
@@ -1891,6 +2539,8 @@ function makeAnthropicProvider(config, env, pricing) {
1891
2539
  const client = new Anthropic({
1892
2540
  apiKey,
1893
2541
  maxRetries: 0,
2542
+ // The client adds `/v1/messages` itself.
2543
+ ...stubOrigin !== void 0 ? { baseURL: stubOrigin } : {},
1894
2544
  ...config.timeout !== void 0 ? { timeout: config.timeout } : {}
1895
2545
  });
1896
2546
  const maxRetries = config.max_retries ?? DEFAULT_MAX_RETRIES;
@@ -2084,12 +2734,13 @@ function makeOpenAiCompatibleProvider(opts) {
2084
2734
  }
2085
2735
  };
2086
2736
  }
2087
- function makeOpenAiProvider(config, env, pricing) {
2737
+ function makeOpenAiProvider(config, env, pricing, stubOrigin) {
2088
2738
  return makeOpenAiCompatibleProvider({
2089
2739
  config,
2090
2740
  env,
2091
2741
  pricing,
2092
2742
  apiKeyEnv: "OPENAI_API_KEY",
2743
+ ...stubOrigin !== void 0 ? { baseURL: `${stubOrigin}/v1` } : {},
2093
2744
  maxCompletionTokens: true,
2094
2745
  sendsReasoningEffort: true
2095
2746
  });
@@ -2098,13 +2749,13 @@ function makeOpenAiProvider(config, env, pricing) {
2098
2749
  // src/providers/openrouter.ts
2099
2750
  init_esm_shims();
2100
2751
  var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
2101
- function makeOpenRouterProvider(config, env, pricing) {
2752
+ function makeOpenRouterProvider(config, env, pricing, stubOrigin) {
2102
2753
  return makeOpenAiCompatibleProvider({
2103
2754
  config,
2104
2755
  env,
2105
2756
  pricing,
2106
2757
  apiKeyEnv: "OPENROUTER_API_KEY",
2107
- baseURL: OPENROUTER_BASE_URL,
2758
+ baseURL: stubOrigin !== void 0 ? `${stubOrigin}/api/v1` : OPENROUTER_BASE_URL,
2108
2759
  reportsCost: true
2109
2760
  // OpenRouter reports the call's actual cost via usage.cost (ADR-PRC02)
2110
2761
  });
@@ -2120,13 +2771,13 @@ function createProviderRegistry() {
2120
2771
  }
2121
2772
  factories.set(name, factory);
2122
2773
  },
2123
- resolve(name, config, env, pricing) {
2774
+ resolve(name, config, env, pricing, stubOrigin) {
2124
2775
  const factory = factories.get(name);
2125
2776
  if (factory === void 0) {
2126
- const known = [...factories.keys()].join(", ") || "(none)";
2127
- throw new Error(`Unknown provider type "${name}". Registered providers: ${known}.`);
2777
+ const known2 = [...factories.keys()].join(", ") || "(none)";
2778
+ throw new Error(`Unknown provider type "${name}". Registered providers: ${known2}.`);
2128
2779
  }
2129
- return factory(config, env, pricing);
2780
+ return factory(config, env, pricing, stubOrigin);
2130
2781
  },
2131
2782
  has(name) {
2132
2783
  return factories.has(name);
@@ -2140,8 +2791,8 @@ function createDefaultRegistry() {
2140
2791
  registry.register("openrouter", makeOpenRouterProvider);
2141
2792
  return registry;
2142
2793
  }
2143
- function getProvider(config, env, pricing) {
2144
- return createDefaultRegistry().resolve(config.type, config, env, pricing);
2794
+ function getProvider(config, env, pricing, stubOrigin) {
2795
+ return createDefaultRegistry().resolve(config.type, config, env, pricing, stubOrigin);
2145
2796
  }
2146
2797
 
2147
2798
  // src/providers/estimate.ts
@@ -2481,7 +3132,7 @@ init_esm_shims();
2481
3132
 
2482
3133
  // src/orchestrator/run.ts
2483
3134
  init_esm_shims();
2484
- import * as fs3 from "fs";
3135
+ import * as fs4 from "fs";
2485
3136
  import * as path4 from "path";
2486
3137
 
2487
3138
  // src/assertions/json-extract.ts
@@ -2517,23 +3168,23 @@ function* balancedRuns(s) {
2517
3168
  while (i < s.length) {
2518
3169
  const rel = s.slice(i).search(/[{[]/);
2519
3170
  if (rel === -1) return;
2520
- const start = i + rel;
2521
- const run = balancedFrom(s, start);
3171
+ const start2 = i + rel;
3172
+ const run = balancedFrom(s, start2);
2522
3173
  if (run === null) {
2523
- i = start + 1;
3174
+ i = start2 + 1;
2524
3175
  } else {
2525
3176
  yield run;
2526
- i = start + run.length;
3177
+ i = start2 + run.length;
2527
3178
  }
2528
3179
  }
2529
3180
  }
2530
- function balancedFrom(s, start) {
2531
- const open2 = s[start];
3181
+ function balancedFrom(s, start2) {
3182
+ const open2 = s[start2];
2532
3183
  const close = open2 === "{" ? "}" : "]";
2533
3184
  let depth = 0;
2534
3185
  let inString = false;
2535
3186
  let escaped = false;
2536
- for (let i = start; i < s.length; i++) {
3187
+ for (let i = start2; i < s.length; i++) {
2537
3188
  const ch = s[i];
2538
3189
  if (inString) {
2539
3190
  if (escaped) escaped = false;
@@ -2547,7 +3198,7 @@ function balancedFrom(s, start) {
2547
3198
  depth++;
2548
3199
  } else if (ch === close) {
2549
3200
  depth--;
2550
- if (depth === 0) return s.slice(start, i + 1);
3201
+ if (depth === 0) return s.slice(start2, i + 1);
2551
3202
  }
2552
3203
  }
2553
3204
  return null;
@@ -2676,6 +3327,93 @@ var jsonSchema = {
2676
3327
  }
2677
3328
  };
2678
3329
 
3330
+ // src/assertions/json-verify.ts
3331
+ init_esm_shims();
3332
+
3333
+ // src/json-verify/format.ts
3334
+ init_esm_shims();
3335
+ var MAX_FRAGMENT = 120;
3336
+ var MAX_FRAGMENT_DEPTH = 6;
3337
+ var MAX_LISTED = 10;
3338
+ var typeOf2 = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
3339
+ function fragment(value) {
3340
+ let out = "";
3341
+ const write = (v, depth) => {
3342
+ if (typeof v !== "object" || v === null) {
3343
+ out += JSON.stringify(typeof v === "string" ? v.slice(0, MAX_FRAGMENT) : v);
3344
+ } else if (depth === MAX_FRAGMENT_DEPTH) {
3345
+ out += "...";
3346
+ } else {
3347
+ const list2 = Array.isArray(v);
3348
+ out += list2 ? "[" : "{";
3349
+ let n = 0;
3350
+ for (const [key, item] of list2 ? v.entries() : Object.entries(v)) {
3351
+ if (out.length > MAX_FRAGMENT) return;
3352
+ if (n++ > 0) out += ",";
3353
+ if (!list2) out += `${JSON.stringify(key)}:`;
3354
+ write(item, depth + 1);
3355
+ }
3356
+ out += list2 ? "]" : "}";
3357
+ }
3358
+ };
3359
+ write(value, 0);
3360
+ if (out.length <= MAX_FRAGMENT) return out;
3361
+ const last = out.charCodeAt(MAX_FRAGMENT - 1);
3362
+ const end = last >= 55296 && last <= 56319 ? MAX_FRAGMENT - 1 : MAX_FRAGMENT;
3363
+ return `${out.slice(0, end)}...`;
3364
+ }
3365
+ function reasonText(m) {
3366
+ switch (m.reason) {
3367
+ case "missing-key":
3368
+ return "missing key";
3369
+ case "extra-key":
3370
+ return "extra key";
3371
+ case "type":
3372
+ return `type differs: expected ${typeOf2(m.expected)}, got ${typeOf2(m.actual)}`;
3373
+ case "value":
3374
+ return "value differs";
3375
+ case "function":
3376
+ return `function not satisfied: ${m.detail}`;
3377
+ case "missing-element":
3378
+ return "missing element";
3379
+ case "extra-element":
3380
+ return "extra element";
3381
+ case "no-match":
3382
+ return "no match for an array element";
3383
+ case "too-large":
3384
+ return `too large: ${m.detail}`;
3385
+ }
3386
+ }
3387
+ function formatMismatches(list2) {
3388
+ if (list2.length === 0) return "";
3389
+ const lines = [`${list2.length} ${list2.length === 1 ? "mismatch" : "mismatches"}`];
3390
+ for (const m of list2.slice(0, MAX_LISTED)) {
3391
+ lines.push(` ${m.path}: ${reasonText(m)}`);
3392
+ if (m.expected !== void 0) lines.push(` expected: ${fragment(m.expected)}`);
3393
+ if (m.actual !== void 0) lines.push(` actual: ${fragment(m.actual)}`);
3394
+ }
3395
+ if (list2.length > MAX_LISTED) lines.push(` and ${list2.length - MAX_LISTED} more`);
3396
+ return lines.join("\n");
3397
+ }
3398
+
3399
+ // src/assertions/json-verify.ts
3400
+ var jsonVerify = {
3401
+ run(ctx) {
3402
+ const extract = ctx.params.extract ?? "auto";
3403
+ const extracted = extractJson(ctx.output, extract);
3404
+ if (!extracted.ok) {
3405
+ return Promise.resolve({
3406
+ passed: false,
3407
+ reason: `output is not valid JSON (extract mode: ${extract})`
3408
+ });
3409
+ }
3410
+ const mismatches = compareJson(ctx.params.expected, extracted.value, { mode: ctx.params.mode ?? "exact" });
3411
+ return Promise.resolve(
3412
+ mismatches.length === 0 ? { passed: true } : { passed: false, reason: formatMismatches(mismatches) }
3413
+ );
3414
+ }
3415
+ };
3416
+
2679
3417
  // src/assertions/semantic-similarity.ts
2680
3418
  init_esm_shims();
2681
3419
  var DEFAULT_THRESHOLD = 0.8;
@@ -2768,7 +3506,7 @@ var llmJudge = {
2768
3506
  const criteria = interpolate(ctx.params.criteria, ctx);
2769
3507
  const threshold = ctx.params.pass_threshold ?? DEFAULT_PASS_THRESHOLD;
2770
3508
  if (ctx.judge.decide !== void 0) {
2771
- const p = await ctx.judge.decide({
3509
+ const { probability: p } = await ctx.judge.decide({
2772
3510
  criteria,
2773
3511
  output: ctx.output,
2774
3512
  ...ctx.input !== void 0 ? { input: ctx.input } : {}
@@ -3086,9 +3824,9 @@ var firstTool = check((ctx) => {
3086
3824
  const { tool } = ctx.params;
3087
3825
  const t = transcriptOf("first-tool", ctx);
3088
3826
  checkNames("first-tool", t, [tool]);
3089
- const first = callsOf(t)[0];
3090
- if (first?.call.name === tool) return pass;
3091
- const got = first === void 0 ? "no tool call at all: the model answered without one" : describeCall(first);
3827
+ const first2 = callsOf(t)[0];
3828
+ if (first2?.call.name === tool) return pass;
3829
+ const got = first2 === void 0 ? "no tool call at all: the model answered without one" : describeCall(first2);
3092
3830
  return fail(
3093
3831
  `expected the first call to be "${tool}"; got ${got}; check that the prompt and the tool's description point the model to it first`
3094
3832
  );
@@ -3279,8 +4017,8 @@ function createAssertionRegistry() {
3279
4017
  resolve(type) {
3280
4018
  const impl = impls.get(type);
3281
4019
  if (impl === void 0) {
3282
- const known = [...impls.keys()].join(", ") || "(none)";
3283
- throw new Error(`Unknown assertion type "${type}". Registered: ${known}.`);
4020
+ const known2 = [...impls.keys()].join(", ") || "(none)";
4021
+ throw new Error(`Unknown assertion type "${type}". Registered: ${known2}.`);
3284
4022
  }
3285
4023
  return impl;
3286
4024
  },
@@ -3299,6 +4037,7 @@ function createDefaultRegistry2() {
3299
4037
  registry.register("contains-any", containsAny);
3300
4038
  registry.register("contains-all", containsAll);
3301
4039
  registry.register("json-schema", jsonSchema);
4040
+ registry.register("json-verify", jsonVerify);
3302
4041
  registry.register("semantic-similarity", semanticSimilarity);
3303
4042
  registry.register("llm-judge", llmJudge);
3304
4043
  registry.register("faithfulness", faithfulness);
@@ -3334,6 +4073,7 @@ var ASSERTION_CLASSES = {
3334
4073
  "contains-any": "deterministic",
3335
4074
  "contains-all": "deterministic",
3336
4075
  "json-schema": "deterministic",
4076
+ "json-verify": "deterministic",
3337
4077
  // A score against the author's threshold. They decide the row as they always have.
3338
4078
  "semantic-similarity": "measure",
3339
4079
  "llm-judge": "measure",
@@ -3457,6 +4197,13 @@ function rowStatus(row) {
3457
4197
  if (row.error !== void 0) return "errored";
3458
4198
  return row.assertions.every((a) => a.passed) ? "passed" : "failed";
3459
4199
  }
4200
+ function stubbedEvals(run) {
4201
+ return run.evals.filter((ev) => ev.stubs !== void 0 || ev.rows.some((row) => row.stubbed === true)).map((ev) => ev.id);
4202
+ }
4203
+ function baseEvalId(ev) {
4204
+ const suffix = ev.provider === void 0 ? "" : `@${ev.provider.model}`;
4205
+ return suffix !== "" && ev.id.endsWith(suffix) ? ev.id.slice(0, -suffix.length) : ev.id;
4206
+ }
3460
4207
 
3461
4208
  // src/orchestrator/agent.ts
3462
4209
  init_esm_shims();
@@ -3498,7 +4245,7 @@ var CAMEL = /[a-z0-9](?:Id|Ids|Uuid|Key|Slug|Number|Ref|Identifier)$/;
3498
4245
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3499
4246
  var isIdKey = (key) => WHOLE.test(key) || SNAKE.test(key) || CAMEL.test(key);
3500
4247
  var isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3501
- var isScalar = (v) => typeof v === "string" && v !== "" || typeof v === "number" && Number.isFinite(v);
4248
+ var isScalar2 = (v) => typeof v === "string" && v !== "" || typeof v === "number" && Number.isFinite(v);
3502
4249
  var EMAIL = /@/;
3503
4250
  function segment(key) {
3504
4251
  const plain = /^[A-Za-z_][\w-]*$/.test(key) && key.length <= 40 && !UUID.test(key) && !EMAIL.test(key);
@@ -3513,7 +4260,7 @@ function noteValue(out, v, at) {
3513
4260
  where.add(at);
3514
4261
  out.values.set(h, where);
3515
4262
  }
3516
- function walk(value, path12, depth, out) {
4263
+ function walk2(value, path12, depth, out) {
3517
4264
  if (depth > SCAN_DEPTH) return;
3518
4265
  if (typeof value === "string" && UUID.test(value)) {
3519
4266
  const at = cap(path12 === "" ? "(root)" : path12);
@@ -3521,17 +4268,17 @@ function walk(value, path12, depth, out) {
3521
4268
  noteValue(out, value, at);
3522
4269
  }
3523
4270
  if (Array.isArray(value)) {
3524
- for (const item of value.slice(0, SCAN_ITEMS)) walk(item, `${path12}[]`, depth + 1, out);
4271
+ for (const item of value.slice(0, SCAN_ITEMS)) walk2(item, `${path12}[]`, depth + 1, out);
3525
4272
  return;
3526
4273
  }
3527
4274
  if (!isRecord3(value)) return;
3528
4275
  for (const [key, v] of Object.entries(value)) {
3529
4276
  const at = cap(path12 === "" ? segment(key) : `${path12}.${segment(key)}`);
3530
- if (isIdKey(key) && (isScalar(v) || Array.isArray(v) && v.length > 0 && v.every(isScalar))) {
4277
+ if (isIdKey(key) && (isScalar2(v) || Array.isArray(v) && v.length > 0 && v.every(isScalar2))) {
3531
4278
  out.paths.add(at);
3532
4279
  for (const x of Array.isArray(v) ? v : [v]) noteValue(out, x, at);
3533
4280
  }
3534
- walk(v, at, depth + 1, out);
4281
+ walk2(v, at, depth + 1, out);
3535
4282
  }
3536
4283
  }
3537
4284
  function scanIds(result) {
@@ -3540,13 +4287,13 @@ function scanIds(result) {
3540
4287
  if (isRecord3(result)) {
3541
4288
  if (result.structuredContent !== void 0) {
3542
4289
  readable = true;
3543
- walk(result.structuredContent, "", 0, found);
4290
+ walk2(result.structuredContent, "", 0, found);
3544
4291
  }
3545
4292
  if (Array.isArray(result.content))
3546
4293
  for (const block of result.content) {
3547
4294
  if (!isRecord3(block) || block.type !== "text" || typeof block.text !== "string") continue;
3548
4295
  try {
3549
- walk(JSON.parse(block.text), "", 0, found);
4296
+ walk2(JSON.parse(block.text), "", 0, found);
3550
4297
  readable = true;
3551
4298
  } catch {
3552
4299
  }
@@ -3589,7 +4336,7 @@ function strip(value, depth, st) {
3589
4336
  for (const [key, v] of Object.entries(value)) {
3590
4337
  let name = redactUuids(key);
3591
4338
  for (let n = 2; name !== key && Object.hasOwn(out, name); n++) name = `${ID_MARK}#${n}`;
3592
- 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);
4339
+ 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);
3593
4340
  }
3594
4341
  return out;
3595
4342
  }
@@ -3827,8 +4574,8 @@ async function runAgentRow(p) {
3827
4574
  );
3828
4575
  for (const t of listed) {
3829
4576
  const isOffered = offered.includes(t);
3830
- const known = transcript.tools.find((k) => k.name === t.name);
3831
- if (known !== void 0) known.offered ||= isOffered;
4577
+ const known2 = transcript.tools.find((k) => k.name === t.name);
4578
+ if (known2 !== void 0) known2.offered ||= isOffered;
3832
4579
  else
3833
4580
  transcript.tools.push({
3834
4581
  name: t.name,
@@ -4073,6 +4820,200 @@ async function runAgentRow(p) {
4073
4820
  };
4074
4821
  }
4075
4822
 
4823
+ // src/mock/schema.ts
4824
+ init_esm_shims();
4825
+ import * as fs3 from "fs/promises";
4826
+ import { validateHeaderName, validateHeaderValue } from "http";
4827
+ import { parseDocument } from "yaml";
4828
+ import { z as z3 } from "zod";
4829
+ var STUB_FILE_VERSION = 1;
4830
+ var sseChunkSchema = z3.union([
4831
+ z3.string(),
4832
+ z3.strictObject({ event: z3.string().min(1).optional(), data: z3.unknown() })
4833
+ ]);
4834
+ var responseSchema = z3.strictObject({
4835
+ status: z3.number().int().min(200).max(599).default(200),
4836
+ // Checked with the checks Node runs when it sends them, so a bad one fails here and not at a request.
4837
+ headers: z3.record(z3.string(), z3.string()).superRefine((headers, ctx) => {
4838
+ for (const [name, value] of Object.entries(headers)) {
4839
+ const check3 = (what, validate) => {
4840
+ try {
4841
+ validate();
4842
+ } catch {
4843
+ ctx.addIssue({ code: "custom", message: `not a valid header ${what}`, path: [name] });
4844
+ }
4845
+ };
4846
+ check3("name", () => validateHeaderName(name));
4847
+ check3("value", () => validateHeaderValue(name, value));
4848
+ }
4849
+ }).default({}),
4850
+ json: z3.unknown().optional(),
4851
+ text: z3.string().optional(),
4852
+ sse: z3.array(sseChunkSchema).optional()
4853
+ }).superRefine((r, ctx) => {
4854
+ const bodies = ["json", "text", "sse"].filter((k) => r[k] !== void 0);
4855
+ if (bodies.length > 1)
4856
+ ctx.addIssue({
4857
+ code: "custom",
4858
+ message: `give one body, not ${bodies.join(" and ")}`,
4859
+ path: [bodies[1]]
4860
+ });
4861
+ });
4862
+ var first = z3.number().int().positive().optional();
4863
+ var failureSchema = z3.discriminatedUnion("type", [
4864
+ // The request is read and never answered, until the client gives up or the scope closes.
4865
+ z3.strictObject({ type: z3.literal("timeout"), first }),
4866
+ // The connection is reset once the request is read; no response at all.
4867
+ z3.strictObject({ type: z3.literal("reset"), first }),
4868
+ z3.strictObject({
4869
+ type: z3.literal("http_429"),
4870
+ first,
4871
+ retry_after_seconds: z3.number().int().min(0).default(1)
4872
+ }),
4873
+ z3.strictObject({ type: z3.literal("http_500"), first }),
4874
+ // The stub's `response`, complete and correct, at this many bytes per second: a whole number, 1 or more.
4875
+ z3.strictObject({ type: z3.literal("slow_stream"), first, bytes_per_sec: z3.number().int().min(1) }),
4876
+ // The first half of the bytes of `response.json`. `full` declares the length of the whole body and closes
4877
+ // the connection after the half, as when a provider's connection drops: the client's read of the body
4878
+ // fails. `cut` declares the length of the half, as when something in between cut the body and re-framed
4879
+ // it: the response arrives whole and only parsing it fails.
4880
+ z3.strictObject({
4881
+ type: z3.literal("truncated_json"),
4882
+ first,
4883
+ content_length: z3.enum(["full", "cut"]).default("full")
4884
+ })
4885
+ ]);
4886
+ var stubSchema = z3.strictObject({
4887
+ method: z3.string().min(1).default("POST").transform((m) => m.toUpperCase()),
4888
+ // Exact, or with wildcards: `*` stands for any characters inside one path segment, `**` for anything,
4889
+ // slashes included. The query string takes no part in the match, so a path holds none.
4890
+ path: z3.string().regex(/^\/[^?#\s]*$/, 'must start with "/" and hold no "?", "#" or whitespace'),
4891
+ // A JSON subset of the request body: every key given here must be in the request with a matching value,
4892
+ // other keys of the request are ignored. Arrays match whole: same length, each item by the same rule.
4893
+ body: z3.unknown().optional(),
4894
+ // How `path` and `body` are compared. Left out, or `subset`: as said above. `exact`: the path is compared
4895
+ // as written, so `*` is a character, and `body` is the whole JSON body of the request, with the same
4896
+ // keys and values and nothing more; a stub without `body` then matches a request with no JSON body.
4897
+ // In an exact stub `[masked]` inside the path or a string of the body stands for any text, and a value
4898
+ // that is `[masked]` and nothing else for any value that is there. A recording is written this way.
4899
+ match: z3.enum(["subset", "exact"]).optional(),
4900
+ // How many requests the stub answers, failures included; a used-up stub lets the next matching one
4901
+ // answer.
4902
+ times: z3.union([z3.literal("always"), z3.literal("once"), z3.number().int().positive()]).default("always"),
4903
+ response: responseSchema.optional(),
4904
+ failure: failureSchema.optional()
4905
+ }).superRefine((stub, ctx) => {
4906
+ const { response, failure } = stub;
4907
+ const need = (message, ...path12) => ctx.addIssue({ code: "custom", message, path: ["response", ...path12] });
4908
+ if (failure === void 0) {
4909
+ if (response === void 0) need("give a response or a failure");
4910
+ } else if (failure.type === "truncated_json") {
4911
+ if (response?.json === void 0) need("truncated_json cuts this body: give it", "json");
4912
+ } else if (response === void 0) {
4913
+ if (failure.type === "slow_stream") need("slow_stream sends this response slowly: give it");
4914
+ else if (failure.first !== void 0)
4915
+ need(`after the first ${failure.first} failed calls this response answers: give it`);
4916
+ } else if (failure.type !== "slow_stream" && failure.first === void 0) {
4917
+ need(
4918
+ `${failure.type} happens on every call, so this response is never sent: remove it or give failure.first`
4919
+ );
4920
+ }
4921
+ if (failure?.first !== void 0 && stub.times !== "always") {
4922
+ if ((stub.times === "once" ? 1 : stub.times) <= failure.first)
4923
+ ctx.addIssue({
4924
+ code: "custom",
4925
+ message: `the first ${failure.first} calls fail and count, so the response is never sent: give more than ${failure.first}, or leave it out`,
4926
+ path: ["times"]
4927
+ });
4928
+ }
4929
+ });
4930
+ var stubFileSchema = z3.strictObject({
4931
+ version: z3.literal(STUB_FILE_VERSION),
4932
+ stubs: z3.array(stubSchema)
4933
+ });
4934
+ var StubFileError = class extends Error {
4935
+ code = "STUB_FILE_ERROR";
4936
+ /** One line per bad field, `path.to.field: what is wrong`. */
4937
+ issues;
4938
+ constructor(message, issues = []) {
4939
+ super(issues.length > 0 ? `${message}
4940
+ ${issues.map((i) => ` ${i}`).join("\n")}` : message);
4941
+ this.name = "StubFileError";
4942
+ this.issues = issues;
4943
+ }
4944
+ };
4945
+ function formatIssues(error) {
4946
+ return error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`);
4947
+ }
4948
+ function parseStubFile(text, file = "stub file") {
4949
+ const doc = parseDocument(text, { schema: "core", resolveKnownTags: false });
4950
+ const problem = doc.errors[0] ?? doc.warnings[0];
4951
+ if (problem !== void 0) {
4952
+ const at = problem.linePos?.[0];
4953
+ throw new StubFileError(
4954
+ `Cannot parse ${file}: ${problem.code}${at === void 0 ? "" : ` at line ${at.line}, column ${at.col}`}`
4955
+ );
4956
+ }
4957
+ let raw;
4958
+ try {
4959
+ raw = doc.toJS();
4960
+ JSON.stringify(raw, (_key, value) => {
4961
+ if (typeof value === "number" && !Number.isFinite(value)) throw new Error("not finite");
4962
+ return value;
4963
+ });
4964
+ } catch {
4965
+ throw new StubFileError(
4966
+ `Cannot parse ${file}: it holds a value JSON cannot (an alias that holds itself, or a number that is not finite)`
4967
+ );
4968
+ }
4969
+ const result = stubFileSchema.safeParse(raw);
4970
+ if (!result.success) throw new StubFileError(`Invalid ${file}`, formatIssues(result.error));
4971
+ return result.data;
4972
+ }
4973
+
4974
+ // src/orchestrator/stubs.ts
4975
+ init_esm_shims();
4976
+ var STUB_NOT_CALLED = "STUB_NOT_CALLED";
4977
+ function viaStubs(inner, scope) {
4978
+ return {
4979
+ async complete(req) {
4980
+ const res = await inner.complete(req);
4981
+ if (scope.journal.length + scope.dropped === 0)
4982
+ throw new ProviderError(
4983
+ STUB_NOT_CALLED,
4984
+ "the answer did not come from the stub server: the provider of this run was not pointed at it, so the answer is dropped"
4985
+ );
4986
+ return res;
4987
+ },
4988
+ estimateCost: () => ({ cost_usd: 0, priced: true })
4989
+ };
4990
+ }
4991
+ var nothingSeen = (stubs) => ({
4992
+ never_called: stubs.map((_, i) => i),
4993
+ unmatched: []
4994
+ });
4995
+ function unusedPlaces(stubs, unused) {
4996
+ const places = /* @__PURE__ */ new Set();
4997
+ let u = unused.length - 1;
4998
+ for (let i = stubs.length - 1; i >= 0 && u >= 0; i -= 1) {
4999
+ if (JSON.stringify(stubs[i]) !== JSON.stringify(unused[u])) continue;
5000
+ places.add(i);
5001
+ u -= 1;
5002
+ }
5003
+ return places;
5004
+ }
5005
+ async function inStubScope(server, name, stubs, seen, fn) {
5006
+ const scope = server.scope(name, stubs);
5007
+ try {
5008
+ return await fn(scope);
5009
+ } finally {
5010
+ const unused = unusedPlaces(stubs, scope.close());
5011
+ seen.never_called = seen.never_called.filter((i) => unused.has(i));
5012
+ for (const entry of scope.journal)
5013
+ if (!entry.matched) seen.unmatched.push({ scope: name, method: entry.method });
5014
+ }
5015
+ }
5016
+
4076
5017
  // src/orchestrator/run.ts
4077
5018
  var DEFAULT_MAX_TOKENS3 = 1024;
4078
5019
  var PLUNE_VERSION = "0.1.0";
@@ -4086,7 +5027,7 @@ var RunConfigError = class extends Error {
4086
5027
  var CACHE_MISS_CODE = "CACHE_MISS";
4087
5028
  function answerParses(output, assertions) {
4088
5029
  return assertions.every(
4089
- (a) => a.type !== "json-schema" || extractJson(output, a.extract ?? "auto").ok
5030
+ (a) => a.type !== "json-schema" && a.type !== "json-verify" || extractJson(output, a.extract ?? "auto").ok
4090
5031
  );
4091
5032
  }
4092
5033
  function resolvePrompt(template, vars) {
@@ -4122,26 +5063,28 @@ async function assess(p, output, input, transcript) {
4122
5063
  const advice = [];
4123
5064
  let assertionError;
4124
5065
  for (const assertion of p.assertions) {
4125
- const own2 = assertion.type === "llm-judge" ? assertion.provider : void 0;
4126
- const jev = own2?.type === "jev" ? own2 : void 0;
4127
- const judgeCfg = own2 === void 0 || own2.type === "jev" ? p.providerConfig : { ...p.providerConfig, ...own2 };
5066
+ const own3 = assertion.type === "llm-judge" ? assertion.provider : void 0;
5067
+ const jev = own3?.type === "jev" ? own3 : void 0;
5068
+ const judgeCfg = own3 === void 0 || own3.type === "jev" ? p.providerConfig : { ...p.providerConfig, ...own3 };
4128
5069
  let judgedBy;
4129
5070
  const judge = () => {
4130
5071
  if (jev !== void 0) {
4131
5072
  if (p.jevJudge === void 0) throw new Error("this run cannot build the jev judge of an llm-judge check");
4132
- const inner2 = p.jevJudge(jev, (usd) => {
4133
- judgeCost += usd;
5073
+ const inner2 = p.jevJudge(jev, (c) => {
5074
+ judgeCost += c.cost_usd;
5075
+ if (c.priced === false) judgeUnpriced = true;
4134
5076
  });
4135
5077
  return {
4136
5078
  ask: (q) => inner2.ask(q),
4137
- decide: (q) => {
4138
- judgedBy = `jev/${jev.model}`;
4139
- return inner2.decide(q);
5079
+ decide: async (q) => {
5080
+ const answer = await inner2.decide(q);
5081
+ judgedBy = `jev/${answer.model}`;
5082
+ return answer;
4140
5083
  }
4141
5084
  };
4142
5085
  }
4143
- let provider = p.provider;
4144
- if (own2 !== void 0) {
5086
+ let provider = p.judgeProvider ?? p.provider;
5087
+ if (own3 !== void 0) {
4145
5088
  if (p.resolveJudge === void 0)
4146
5089
  throw new Error("this run cannot build the judge named by the provider of an llm-judge check");
4147
5090
  provider = p.resolveJudge(judgeCfg);
@@ -4203,7 +5146,15 @@ async function runRow(p) {
4203
5146
  if (p.dryRun) {
4204
5147
  const est = estimateUsage(prompt5, maxTokens);
4205
5148
  const cost = p.provider.estimateCost(est);
4206
- return dryRunRow(p.row.vars, { ...est, ...costFields(cost) });
5149
+ let judged = 0;
5150
+ let unpriced = cost.priced === false;
5151
+ for (const a of p.assertions) {
5152
+ if (a.type !== "llm-judge" || a.provider?.type !== "jev" || p.jevCost === void 0) continue;
5153
+ const c = p.jevCost(a.provider.model, Math.ceil((prompt5.length + maxTokens * 4 + a.criteria.length) / 3));
5154
+ judged += c.cost_usd;
5155
+ if (c.priced === false) unpriced = true;
5156
+ }
5157
+ return dryRunRow(p.row.vars, { ...est, cost_usd: cost.cost_usd + judged, ...unpriced ? { priced: false } : cost.priced === void 0 ? {} : { priced: cost.priced } });
4207
5158
  }
4208
5159
  const key = cacheKey(
4209
5160
  {
@@ -4385,13 +5336,53 @@ function resolveTemplate(ev, baseDir) {
4385
5336
  if (ev.prompt !== void 0) return ev.prompt;
4386
5337
  if (ev.prompt_file !== void 0) {
4387
5338
  try {
4388
- return fs3.readFileSync(path4.resolve(baseDir, ev.prompt_file), "utf8");
5339
+ return fs4.readFileSync(path4.resolve(baseDir, ev.prompt_file), "utf8");
4389
5340
  } catch {
4390
5341
  throw new RunConfigError(`Eval "${ev.id}": prompt_file not found: ${ev.prompt_file}`);
4391
5342
  }
4392
5343
  }
4393
5344
  throw new RunConfigError(`Eval "${ev.id}" has neither prompt nor prompt_file`);
4394
5345
  }
5346
+ var MAX_STUB_FILE_BYTES = 1024 * 1024;
5347
+ function resolveStubs(ev, deps, cacheStrict) {
5348
+ const file = ev.stubs;
5349
+ if (file === void 0) return void 0;
5350
+ const dir = path4.resolve(deps.baseDir);
5351
+ const full = path4.resolve(dir, file);
5352
+ const inside = path4.relative(dir, full);
5353
+ if (inside === "" || inside === ".." || inside.startsWith(`..${path4.sep}`) || path4.isAbsolute(inside))
5354
+ throw new RunConfigError(`Eval "${ev.id}": stubs must name a file inside the folder of the config: ${file}`);
5355
+ let text;
5356
+ try {
5357
+ const stat2 = fs4.statSync(full);
5358
+ if (stat2.isDirectory()) throw new RunConfigError(`Eval "${ev.id}": stubs is a folder, not a file: ${file}`);
5359
+ if (stat2.size > MAX_STUB_FILE_BYTES)
5360
+ throw new RunConfigError(`Eval "${ev.id}": stubs file is over 1 MiB: ${file}`);
5361
+ text = fs4.readFileSync(full, "utf8");
5362
+ } catch (err) {
5363
+ if (err instanceof RunConfigError) throw err;
5364
+ throw new RunConfigError(`Eval "${ev.id}": stubs file not found: ${file}`);
5365
+ }
5366
+ let stubs;
5367
+ try {
5368
+ ({ stubs } = parseStubFile(text, file));
5369
+ } catch (err) {
5370
+ if (err instanceof StubFileError && err.issues.some((issue) => issue.startsWith("version:")))
5371
+ throw new RunConfigError(
5372
+ `Eval "${ev.id}": ${file} is not a stub file: a stub file has version: 1 at its top`
5373
+ );
5374
+ throw new RunConfigError(`Eval "${ev.id}": ${err.message}`);
5375
+ }
5376
+ if (cacheStrict)
5377
+ throw new RunConfigError(
5378
+ `Eval "${ev.id}" has stubs: a stubbed answer is never cached, so --cache-strict cannot answer it`
5379
+ );
5380
+ if (deps.stubServer === void 0)
5381
+ throw new RunConfigError(
5382
+ `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)`
5383
+ );
5384
+ return stubs;
5385
+ }
4395
5386
  function summarize(evals, durationMs) {
4396
5387
  const summary = {
4397
5388
  total: 0,
@@ -4410,6 +5401,7 @@ function summarize(evals, durationMs) {
4410
5401
  errored: 0,
4411
5402
  saved: { input_tokens: 0, output_tokens: 0, cost_usd: 0 }
4412
5403
  };
5404
+ let stubbed = 0;
4413
5405
  for (const ev of evals) {
4414
5406
  for (const row of ev.rows) {
4415
5407
  summary.total += 1;
@@ -4418,13 +5410,14 @@ function summarize(evals, durationMs) {
4418
5410
  cache.saved.input_tokens += row.cache_saved?.input_tokens ?? 0;
4419
5411
  cache.saved.output_tokens += row.cache_saved?.output_tokens ?? 0;
4420
5412
  cache.saved.cost_usd += row.cache_saved?.cost_usd ?? 0;
4421
- if (row.cached) cache.from_cache += 1;
5413
+ if (row.stubbed === true) stubbed += 1;
5414
+ else if (row.cached) cache.from_cache += 1;
4422
5415
  else if (row.error?.code === CACHE_MISS_CODE) cache.missed += 1;
4423
5416
  else if (row.output !== null) cache.from_model += 1;
4424
5417
  else if (row.error !== void 0) cache.errored += 1;
4425
5418
  }
4426
5419
  }
4427
- return { ...summary, cache };
5420
+ return { ...summary, cache: stubbed > 0 ? { ...cache, stubbed } : cache };
4428
5421
  }
4429
5422
  function agenticProvider(ev, providerConfig, deps, cacheStrict) {
4430
5423
  if (cacheStrict)
@@ -4460,22 +5453,28 @@ async function runOrchestration(config, options, deps) {
4460
5453
  const models = config.providers ?? [config.provider];
4461
5454
  const prepared = selectEvals(config.evals, options.only).map((ev) => {
4462
5455
  const template = resolveTemplate(ev, deps.baseDir);
5456
+ const stubs = resolveStubs(ev, deps, cacheStrict);
4463
5457
  const rows = deps.loadDataset(ev.dataset, deps.baseDir);
4464
5458
  for (const row of rows) {
4465
5459
  resolvePrompt(template, row.vars);
4466
5460
  }
4467
5461
  const cells = models.map((model) => {
4468
5462
  const providerConfig = { ...model, ...ev.provider };
5463
+ const hangs = stubs?.findIndex((stub) => stub.failure?.type === "timeout") ?? -1;
5464
+ if (hangs !== -1 && providerConfig.timeout === void 0)
5465
+ throw new RunConfigError(
5466
+ `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`
5467
+ );
4469
5468
  const agentic = ev.mcp === void 0 || dryRun ? void 0 : agenticProvider(ev, providerConfig, deps, cacheStrict);
4470
5469
  return { providerConfig, agentic };
4471
5470
  });
4472
- return { ev, template, rows, cells };
5471
+ return { ev, template, rows, cells, stubs };
4473
5472
  });
4474
5473
  const judges = /* @__PURE__ */ new Map();
4475
5474
  const resolveJudge = (cfg) => {
4476
5475
  const key = canonicalJson(cfg);
4477
- const known = judges.get(key);
4478
- if (known !== void 0) return known;
5476
+ const known2 = judges.get(key);
5477
+ if (known2 !== void 0) return known2;
4479
5478
  const made = deps.resolveProvider(cfg);
4480
5479
  judges.set(key, made);
4481
5480
  return made;
@@ -4485,14 +5484,15 @@ async function runOrchestration(config, options, deps) {
4485
5484
  throw new RunConfigError(
4486
5485
  "--tool-description needs an eval with mcp in this run: no tool is offered otherwise"
4487
5486
  );
4488
- cellLoop: for (const { ev, template, rows, cells } of prepared) {
5487
+ cellLoop: for (const { ev, template, rows, cells, stubs } of prepared) {
4489
5488
  for (const { providerConfig, agentic } of cells) {
4490
5489
  const provider = agentic ?? deps.resolveProvider(providerConfig);
5490
+ const seen = stubs === void 0 || dryRun ? void 0 : nothingSeen(stubs);
4491
5491
  const limit2 = options.concurrency ?? providerConfig.concurrency ?? (ev.mcp !== void 0 ? 1 : 4);
4492
5492
  const runs = options.runs ?? ev.runs ?? config.runs ?? 1;
4493
5493
  const passThreshold = ev.pass_threshold ?? config.pass_threshold ?? 1;
4494
5494
  const assertions = [...config.defaults?.assertions ?? [], ...ev.assertions];
4495
- const rowResults = await mapLimit(rows, limit2, (row) => {
5495
+ const rowResults = await mapLimit(rows, limit2, (row, rowIndex) => {
4496
5496
  const params = {
4497
5497
  template,
4498
5498
  assertions,
@@ -4501,6 +5501,7 @@ async function runOrchestration(config, options, deps) {
4501
5501
  provider,
4502
5502
  resolveJudge,
4503
5503
  ...deps.jevJudge !== void 0 ? { jevJudge: deps.jevJudge } : {},
5504
+ ...deps.jevCost !== void 0 ? { jevCost: deps.jevCost } : {},
4504
5505
  embedder: deps.embedder,
4505
5506
  cache: deps.cache,
4506
5507
  now: deps.now,
@@ -4509,6 +5510,25 @@ async function runOrchestration(config, options, deps) {
4509
5510
  cacheStrict,
4510
5511
  ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {}
4511
5512
  };
5513
+ if (stubs !== void 0 && seen !== void 0) {
5514
+ return runRepeats(
5515
+ params,
5516
+ runs,
5517
+ passThreshold,
5518
+ async (p) => inStubScope(
5519
+ await deps.stubServer(),
5520
+ `${ev.id}.row${rowIndex + 1}${p.attempt === void 0 ? "" : `.run${p.attempt + 1}`}`,
5521
+ stubs,
5522
+ seen,
5523
+ (scope) => runRow({
5524
+ ...p,
5525
+ provider: viaStubs(deps.resolveProvider(providerConfig, scope.url), scope),
5526
+ judgeProvider: p.provider,
5527
+ noCache: true
5528
+ })
5529
+ )
5530
+ ).then((result) => ({ ...result, stubbed: true }));
5531
+ }
4512
5532
  if (ev.mcp === void 0) return runRepeats(params, runs, passThreshold);
4513
5533
  const agentParams = {
4514
5534
  ...params,
@@ -4535,7 +5555,8 @@ async function runOrchestration(config, options, deps) {
4535
5555
  rows: rowResults,
4536
5556
  passed,
4537
5557
  measured,
4538
- ...models.length > 1 ? { provider: { type: providerConfig.type, model: providerConfig.model } } : {}
5558
+ ...models.length > 1 ? { provider: { type: providerConfig.type, model: providerConfig.model } } : {},
5559
+ ...seen !== void 0 ? { stubs: seen } : {}
4539
5560
  });
4540
5561
  if (options.bail === true && !dryRun && !passed) break cellLoop;
4541
5562
  }
@@ -4560,7 +5581,7 @@ init_esm_shims();
4560
5581
 
4561
5582
  // src/orchestrator/dataset.ts
4562
5583
  init_esm_shims();
4563
- import * as fs4 from "fs";
5584
+ import * as fs5 from "fs";
4564
5585
  import * as path5 from "path";
4565
5586
  function loadDataset(ref5, baseDir) {
4566
5587
  if (typeof ref5 !== "string") {
@@ -4569,7 +5590,7 @@ function loadDataset(ref5, baseDir) {
4569
5590
  const file = path5.resolve(baseDir, ref5);
4570
5591
  let content;
4571
5592
  try {
4572
- content = fs4.readFileSync(file, "utf8");
5593
+ content = fs5.readFileSync(file, "utf8");
4573
5594
  } catch (err) {
4574
5595
  throw new RunConfigError(
4575
5596
  err.code === "ENOENT" ? `${ref5}: dataset file not found (looked for ${file})` : `${ref5}: cannot read the dataset file (${err.message})`
@@ -4584,9 +5605,9 @@ function loadDataset(ref5, baseDir) {
4584
5605
  } catch (err) {
4585
5606
  throw new RunConfigError(`${ref5}:${i + 1}: not valid JSON (${err.message})`);
4586
5607
  }
4587
- const vars = isObject2(row) ? row["vars"] : void 0;
4588
- if (!isObject2(vars)) {
4589
- const why = isObject2(row) && "vars" in row ? `vars: Invalid input: expected record, received ${typeName(vars)}` : 'this row has no "vars"';
5608
+ const vars = isObject3(row) ? row["vars"] : void 0;
5609
+ if (!isObject3(vars)) {
5610
+ const why = isObject3(row) && "vars" in row ? `vars: Invalid input: expected record, received ${typeName(vars)}` : 'this row has no "vars"';
4590
5611
  throw new RunConfigError(
4591
5612
  `${ref5}:${i + 1}: a dataset row must be { "vars": { ... } }; ${why}`
4592
5613
  );
@@ -4595,7 +5616,7 @@ function loadDataset(ref5, baseDir) {
4595
5616
  });
4596
5617
  return rows;
4597
5618
  }
4598
- function isObject2(value) {
5619
+ function isObject3(value) {
4599
5620
  return typeof value === "object" && value !== null && !Array.isArray(value);
4600
5621
  }
4601
5622
  function typeName(value) {
@@ -4607,7 +5628,7 @@ init_esm_shims();
4607
5628
  var JEV_BASE_URL = "https://api.typesafe.ai";
4608
5629
  var JEV_KEY_ENV = "TYPESAFE_API_KEY";
4609
5630
  var JEV_MAX_STATE_CHARS = 16e3;
4610
- var JEV_USD_PER_1M_INPUT_TOKENS = 0.042;
5631
+ var JEV_BASE_URL_ENV = "PLUNE_JEV_BASE_URL";
4611
5632
  var DEFAULT_TIMEOUT_MS = 3e4;
4612
5633
  var INSTRUCTIONS = "Does the answer meet the criterion?";
4613
5634
  var YES = "the answer meets the criterion";
@@ -4623,6 +5644,27 @@ ${q.output}
4623
5644
  Criterion:
4624
5645
  ${q.criteria}`;
4625
5646
  }
5647
+ function jevBaseUrl(env) {
5648
+ const own3 = env[JEV_BASE_URL_ENV];
5649
+ const [name, value] = own3 !== void 0 && own3 !== "" ? [JEV_BASE_URL_ENV, own3] : ["TYPESAFE_BASE_URL", env["TYPESAFE_BASE_URL"]];
5650
+ if (value === void 0 || value === "") return JEV_BASE_URL;
5651
+ let url;
5652
+ try {
5653
+ url = new URL(value);
5654
+ } catch {
5655
+ url = void 0;
5656
+ }
5657
+ const ok = url !== void 0 && url.protocol === "https:" && (url.hostname === "typesafe.ai" || url.hostname.endsWith(".typesafe.ai"));
5658
+ if (!ok)
5659
+ throw new Error(
5660
+ `${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`)
5661
+ );
5662
+ return value.replace(/\/+$/, "");
5663
+ }
5664
+ function jevCost(model, inputTokens, pricing) {
5665
+ return resolveCostEntry({ input_tokens: inputTokens, output_tokens: 0 }, model, void 0, pricing);
5666
+ }
5667
+ var jevTokenEstimate = (chars) => Math.ceil(chars / 3);
4626
5668
  function probability(json) {
4627
5669
  const answer = json?.answers?.q;
4628
5670
  const p = answer?.type === "noul" ? answer.noul : void 0;
@@ -4634,6 +5676,7 @@ function makeJevJudge(cfg, deps) {
4634
5676
  return {
4635
5677
  ask: () => Promise.reject(new Error("a jev judge answers a yes-or-no question only: it cannot judge this kind of check")),
4636
5678
  async decide(q) {
5679
+ const base = jevBaseUrl(deps.env);
4637
5680
  const key = deps.env[JEV_KEY_ENV];
4638
5681
  if (key === void 0 || key === "")
4639
5682
  throw new AuthError(`${JEV_KEY_ENV} is not set: the jev judge of an llm-judge check needs it`, JEV_KEY_ENV);
@@ -4650,7 +5693,7 @@ function makeJevJudge(cfg, deps) {
4650
5693
  });
4651
5694
  const send = async () => {
4652
5695
  try {
4653
- return await deps.fetchFn(`${JEV_BASE_URL}/v1/systemone`, {
5696
+ return await deps.fetchFn(`${base}/v1/systemone`, {
4654
5697
  method: "POST",
4655
5698
  headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
4656
5699
  body,
@@ -4669,9 +5712,11 @@ function makeJevJudge(cfg, deps) {
4669
5712
  const json = await res.json();
4670
5713
  const p = probability(json);
4671
5714
  const tokens = json.usage?.input_tokens;
4672
- const billed = typeof tokens === "number" && tokens >= 0 ? tokens : Math.ceil(state.length / 3);
4673
- deps.onCost(billed / 1e6 * JEV_USD_PER_1M_INPUT_TOKENS);
4674
- return p;
5715
+ const billed = typeof tokens === "number" && tokens >= 0 ? tokens : jevTokenEstimate(state.length);
5716
+ const answered = json.model;
5717
+ const model = typeof answered === "string" && answered !== "" ? answered : cfg.model;
5718
+ deps.onCost(jevCost(model, billed, deps.pricing));
5719
+ return { probability: p, model };
4675
5720
  }
4676
5721
  };
4677
5722
  }
@@ -4685,6 +5730,416 @@ function warnJevExperimental(write = (l) => process.stderr.write(l)) {
4685
5730
  );
4686
5731
  }
4687
5732
 
5733
+ // src/mock/server.ts
5734
+ init_esm_shims();
5735
+ import * as http from "http";
5736
+ var JOURNAL_MAX_ENTRIES = 1e3;
5737
+ var MAX_CONNECTIONS = 256;
5738
+ var REAL_TIMERS = {
5739
+ now: () => performance.now(),
5740
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
5741
+ clearTimeout: (handle) => clearTimeout(handle)
5742
+ };
5743
+ var SLOW_STREAM_STEP_MS = 50;
5744
+ var MASK = "[masked]";
5745
+ var SECRET_NAME = /auth|key|token|secret|cookie|password|passwd|pwd|credential|sig|jwt|session|csrf|otp|code|assertion/i;
5746
+ var SCOPE_NAME = /^(?!\.{1,2}$)[A-Za-z0-9._-]+$/;
5747
+ var DOT_SEGMENT = /^(\.|%2e){1,2}$/i;
5748
+ var MAX_BODY_BYTES = 16 * 1024 * 1024;
5749
+ function pathMatcher(pattern) {
5750
+ const tokens = pattern.match(/\*\*|[^]/g) ?? [];
5751
+ const n = tokens.length;
5752
+ const skipWildcards = (at) => {
5753
+ for (let i = 0; i < n; i += 1)
5754
+ if (at[i] && (tokens[i] === "*" || tokens[i] === "**")) at[i + 1] = 1;
5755
+ };
5756
+ return (path12) => {
5757
+ let at = new Uint8Array(n + 1);
5758
+ at[0] = 1;
5759
+ skipWildcards(at);
5760
+ for (let c = 0; c < path12.length; c += 1) {
5761
+ const ch = path12[c];
5762
+ const next = new Uint8Array(n + 1);
5763
+ for (let i = 0; i < n; i += 1) {
5764
+ if (!at[i]) continue;
5765
+ const token = tokens[i];
5766
+ if (token === "**" || token === "*" && ch !== "/") next[i] = 1;
5767
+ else if (token !== "*" && token === ch) next[i + 1] = 1;
5768
+ }
5769
+ skipWildcards(next);
5770
+ at = next;
5771
+ }
5772
+ return at[n] === 1;
5773
+ };
5774
+ }
5775
+ function matchesSubset(expected, actual) {
5776
+ if (Array.isArray(expected))
5777
+ return Array.isArray(actual) && actual.length === expected.length && expected.every((item, i) => matchesSubset(item, actual[i]));
5778
+ if (expected !== null && typeof expected === "object")
5779
+ return actual !== null && typeof actual === "object" && !Array.isArray(actual) && Object.entries(expected).every(
5780
+ ([k, v]) => Object.hasOwn(actual, k) && matchesSubset(v, actual[k])
5781
+ );
5782
+ return expected === actual;
5783
+ }
5784
+ function maskedTextMatches(expected, actual) {
5785
+ const parts = expected.split(MASK);
5786
+ const first2 = parts[0];
5787
+ const last = parts[parts.length - 1];
5788
+ if (parts.length === 1) return expected === actual;
5789
+ if (actual.length < first2.length + last.length) return false;
5790
+ if (!actual.startsWith(first2) || !actual.endsWith(last)) return false;
5791
+ const end = actual.length - last.length;
5792
+ let at = first2.length;
5793
+ for (const part of parts.slice(1, -1)) {
5794
+ const found = actual.indexOf(part, at);
5795
+ if (found === -1 || found + part.length > end) return false;
5796
+ at = found + part.length;
5797
+ }
5798
+ return true;
5799
+ }
5800
+ function matchesExact(expected, actual) {
5801
+ if (expected === MASK) return actual !== void 0;
5802
+ if (typeof expected === "string")
5803
+ return typeof actual === "string" && maskedTextMatches(expected, actual);
5804
+ if (Array.isArray(expected))
5805
+ return Array.isArray(actual) && actual.length === expected.length && expected.every((item, i) => matchesExact(item, actual[i]));
5806
+ if (expected !== null && typeof expected === "object")
5807
+ return actual !== null && typeof actual === "object" && !Array.isArray(actual) && Object.keys(actual).length === Object.keys(expected).length && Object.entries(expected).every(
5808
+ ([k, v]) => Object.hasOwn(actual, k) && matchesExact(v, actual[k])
5809
+ );
5810
+ return expected === actual;
5811
+ }
5812
+ function notLocal(req, port, bound = "127.0.0.1") {
5813
+ const names = ["127.0.0.1", "localhost", "[::1]", bound.includes(":") ? `[${bound}]` : bound];
5814
+ const hosts = names.flatMap((name) => port === 80 ? [name, `${name}:80`] : [`${name}:${port}`]);
5815
+ const host = (req.headers.host ?? "").toLowerCase();
5816
+ const { origin } = req.headers;
5817
+ return !hosts.includes(host) || origin !== void 0 && !hosts.some((h) => origin.toLowerCase() === `http://${h}`);
5818
+ }
5819
+ 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";
5820
+ function maskedHeaders(headers) {
5821
+ const out = {};
5822
+ for (const [name, value] of Object.entries(headers)) {
5823
+ if (value === void 0) continue;
5824
+ out[name] = SECRET_NAME.test(name) ? MASK : Array.isArray(value) ? value.join(", ") : value;
5825
+ }
5826
+ return out;
5827
+ }
5828
+ function maskedQuery(params) {
5829
+ return [...params].map(
5830
+ ([k, v]) => `${encodeURIComponent(k)}=${SECRET_NAME.test(k) ? MASK : encodeURIComponent(v)}`
5831
+ ).join("&");
5832
+ }
5833
+ function renderBody(response) {
5834
+ if (response.sse !== void 0) {
5835
+ const events = response.sse.map((chunk2) => {
5836
+ const { event, data } = typeof chunk2 === "string" ? { event: void 0, data: chunk2 } : chunk2;
5837
+ const line = typeof data === "string" ? data : JSON.stringify(data);
5838
+ return `${event === void 0 ? "" : `event: ${event}
5839
+ `}data: ${line}
5840
+
5841
+ `;
5842
+ });
5843
+ return { type: "text/event-stream", body: Buffer.from(events.join("")) };
5844
+ }
5845
+ if (response.text !== void 0)
5846
+ return { type: "text/plain; charset=utf-8", body: Buffer.from(response.text) };
5847
+ if (response.json !== void 0)
5848
+ return { type: "application/json", body: Buffer.from(JSON.stringify(response.json)) };
5849
+ return { body: Buffer.alloc(0) };
5850
+ }
5851
+ function responseHeaders(response, type, length) {
5852
+ const headers = {};
5853
+ if (type !== void 0) headers["content-type"] = type;
5854
+ if (response.sse === void 0) headers["content-length"] = length;
5855
+ else headers["cache-control"] = "no-cache";
5856
+ for (const [name, value] of Object.entries(response.headers)) headers[name.toLowerCase()] = value;
5857
+ return headers;
5858
+ }
5859
+ function sendJson(res, status, body, headers = {}) {
5860
+ const text = JSON.stringify(body);
5861
+ res.writeHead(status, {
5862
+ "content-type": "application/json",
5863
+ "content-length": Buffer.byteLength(text),
5864
+ ...headers
5865
+ });
5866
+ res.end(text);
5867
+ }
5868
+ var providerError = (type, code, message) => ({
5869
+ type: "error",
5870
+ error: { type, code, message }
5871
+ });
5872
+ function writeSlowly(res, body, bytesPerSec, timers) {
5873
+ const startedAt = timers.now();
5874
+ const step = Math.max(1, Math.round(bytesPerSec * SLOW_STREAM_STEP_MS / 1e3));
5875
+ let sent = 0;
5876
+ let handle;
5877
+ const tick = () => {
5878
+ const due = Math.min(
5879
+ body.length,
5880
+ Math.floor((timers.now() - startedAt) * bytesPerSec / 1e3)
5881
+ );
5882
+ if (due > sent) {
5883
+ res.write(body.subarray(sent, due));
5884
+ sent = due;
5885
+ }
5886
+ if (sent >= body.length) {
5887
+ res.end();
5888
+ return;
5889
+ }
5890
+ const nextAt = startedAt + Math.min(body.length, sent + step) * 1e3 / bytesPerSec;
5891
+ handle = timers.setTimeout(tick, Math.max(1, Math.ceil(nextAt - timers.now())));
5892
+ };
5893
+ tick();
5894
+ return () => timers.clearTimeout(handle);
5895
+ }
5896
+ async function start(options = {}) {
5897
+ const host = options.host ?? "127.0.0.1";
5898
+ const journalBodyCap = options.journalBodyCap ?? 64 * 1024;
5899
+ const timers = options.timers ?? REAL_TIMERS;
5900
+ const scopes = /* @__PURE__ */ new Map();
5901
+ const unrouted = [];
5902
+ let unroutedDropped = 0;
5903
+ let closing;
5904
+ const record = (journal, entry) => {
5905
+ journal.push(entry);
5906
+ if (journal.length <= JOURNAL_MAX_ENTRIES) return 0;
5907
+ journal.shift();
5908
+ return 1;
5909
+ };
5910
+ function answer(req, res, body) {
5911
+ const target = req.url ?? "";
5912
+ const queryAt = target.indexOf("?");
5913
+ const rawPath = queryAt === -1 ? target : target.slice(0, queryAt);
5914
+ const segments = rawPath.split("/");
5915
+ const badTarget = segments[0] !== "" || segments.length < 2 || segments[1] === "" && segments.length > 2 || segments.some((segment2) => DOT_SEGMENT.test(segment2));
5916
+ const name = badTarget ? "" : segments[1];
5917
+ const method = req.method ?? "GET";
5918
+ const path12 = badTarget ? rawPath : rawPath.slice(name.length + 1) || "/";
5919
+ const entry = {
5920
+ scope: name,
5921
+ method,
5922
+ path: path12,
5923
+ query: maskedQuery(new URLSearchParams(queryAt === -1 ? "" : target.slice(queryAt + 1))),
5924
+ headers: maskedHeaders(req.headers),
5925
+ body: body.subarray(0, journalBodyCap).toString("utf8"),
5926
+ bodyTruncated: body.length > journalBodyCap,
5927
+ matched: false
5928
+ };
5929
+ const refuse = (status, type, message, open2) => sendJson(res, status, {
5930
+ error: { type, message, method, ...open2 === void 0 ? {} : { scope: open2 } }
5931
+ });
5932
+ const scope = badTarget ? void 0 : scopes.get(name);
5933
+ if (scope === void 0) {
5934
+ unroutedDropped += record(unrouted, entry);
5935
+ if (badTarget)
5936
+ refuse(
5937
+ 400,
5938
+ "mock_bad_target",
5939
+ 'Bad request target: it starts with "/<scope>" and holds no "." or ".." segment'
5940
+ );
5941
+ else
5942
+ refuse(
5943
+ 404,
5944
+ "mock_no_stub",
5945
+ `No open scope for this ${method} request: the first path segment names the scope`
5946
+ );
5947
+ return;
5948
+ }
5949
+ scope.dropped += record(scope.journal, entry);
5950
+ let json;
5951
+ let parsed2 = false;
5952
+ const live = scope.stubs.find(({ stub, matches, calls }) => {
5953
+ if (stub.times !== "always" && calls >= (stub.times === "once" ? 1 : stub.times))
5954
+ return false;
5955
+ if (stub.method !== method || !matches(path12)) return false;
5956
+ const exact = stub.match === "exact";
5957
+ if (stub.body === void 0 && !exact) return true;
5958
+ if (!parsed2) {
5959
+ parsed2 = true;
5960
+ try {
5961
+ json = JSON.parse(body.toString("utf8"));
5962
+ } catch {
5963
+ json = void 0;
5964
+ }
5965
+ }
5966
+ if (!exact) return matchesSubset(stub.body, json);
5967
+ return stub.body === void 0 ? json === void 0 : matchesExact(stub.body, json);
5968
+ });
5969
+ if (live === void 0) {
5970
+ refuse(
5971
+ 404,
5972
+ "mock_no_stub",
5973
+ `No stub matches this ${method} request in scope "${name}": compare its path and body in the journal of the scope with the stubs`,
5974
+ name
5975
+ );
5976
+ return;
5977
+ }
5978
+ entry.matched = true;
5979
+ live.calls += 1;
5980
+ const response = live.stub.response ?? { status: 200, headers: {} };
5981
+ const rendered = renderBody(response);
5982
+ const head = (length) => {
5983
+ res.writeHead(response.status, responseHeaders(response, rendered.type, length));
5984
+ };
5985
+ const { failure } = live.stub;
5986
+ if (failure === void 0 || failure.first !== void 0 && live.calls > failure.first) {
5987
+ head(rendered.body.length);
5988
+ res.end(rendered.body);
5989
+ return;
5990
+ }
5991
+ const hold = (stop = () => void 0) => {
5992
+ const abort = () => {
5993
+ stop();
5994
+ res.destroy();
5995
+ };
5996
+ scope.held.add(abort);
5997
+ res.on("close", () => {
5998
+ stop();
5999
+ scope.held.delete(abort);
6000
+ });
6001
+ };
6002
+ switch (failure.type) {
6003
+ case "timeout":
6004
+ hold();
6005
+ return;
6006
+ case "reset":
6007
+ req.socket.resetAndDestroy();
6008
+ return;
6009
+ case "http_429":
6010
+ sendJson(
6011
+ res,
6012
+ 429,
6013
+ providerError("rate_limit_error", "rate_limit_exceeded", "Rate limit exceeded (stub)"),
6014
+ { "retry-after": String(failure.retry_after_seconds) }
6015
+ );
6016
+ return;
6017
+ case "http_500":
6018
+ sendJson(
6019
+ res,
6020
+ 500,
6021
+ providerError("api_error", "internal_error", "Internal server error (stub)")
6022
+ );
6023
+ return;
6024
+ case "slow_stream":
6025
+ head(rendered.body.length);
6026
+ res.flushHeaders();
6027
+ hold(writeSlowly(res, rendered.body, failure.bytes_per_sec, timers));
6028
+ return;
6029
+ case "truncated_json": {
6030
+ const cut = rendered.body.subarray(0, Math.floor(rendered.body.length / 2));
6031
+ if (failure.content_length === "cut") {
6032
+ head(cut.length);
6033
+ res.end(cut);
6034
+ } else {
6035
+ head(rendered.body.length);
6036
+ res.write(cut, () => res.destroy());
6037
+ }
6038
+ return;
6039
+ }
6040
+ }
6041
+ }
6042
+ let port = 0;
6043
+ const server = http.createServer((req, res) => {
6044
+ if (notLocal(req, port, host)) {
6045
+ req.resume();
6046
+ sendJson(res, 403, { error: { type: "mock_not_local", message: NOT_LOCAL_MESSAGE } });
6047
+ return;
6048
+ }
6049
+ const chunks = [];
6050
+ let size = 0;
6051
+ req.on("error", () => void 0);
6052
+ req.on("data", (chunk2) => {
6053
+ size += chunk2.length;
6054
+ if (size <= MAX_BODY_BYTES) chunks.push(chunk2);
6055
+ else chunks.length = 0;
6056
+ });
6057
+ req.on("end", () => {
6058
+ if (size > MAX_BODY_BYTES) {
6059
+ sendJson(res, 413, {
6060
+ error: { type: "mock_body_too_large", message: "Request body over 16 MiB" }
6061
+ });
6062
+ return;
6063
+ }
6064
+ try {
6065
+ answer(req, res, Buffer.concat(chunks));
6066
+ } catch {
6067
+ if (res.headersSent) res.destroy();
6068
+ else
6069
+ sendJson(res, 500, {
6070
+ error: { type: "mock_internal", message: "The stub server failed on this request" }
6071
+ });
6072
+ }
6073
+ });
6074
+ });
6075
+ server.maxConnections = MAX_CONNECTIONS;
6076
+ await new Promise((resolve9, reject) => {
6077
+ server.once("error", reject);
6078
+ server.listen(options.port ?? 0, host, () => {
6079
+ server.off("error", reject);
6080
+ resolve9();
6081
+ });
6082
+ });
6083
+ ({ port } = server.address());
6084
+ const url = `http://${host.includes(":") ? `[${host}]` : host}:${port}`;
6085
+ return {
6086
+ url,
6087
+ port,
6088
+ unrouted,
6089
+ get unroutedDropped() {
6090
+ return unroutedDropped;
6091
+ },
6092
+ scope(name, stubs = []) {
6093
+ if (closing !== void 0) throw new Error("The server is closed: it takes no new scope");
6094
+ if (!SCOPE_NAME.test(name))
6095
+ throw new Error(
6096
+ `Bad scope name "${name}": letters, digits, ".", "_" and "-" only, and not "." or ".."`
6097
+ );
6098
+ if (scopes.has(name)) throw new Error(`Scope "${name}" is already open`);
6099
+ const state = { stubs: [], journal: [], dropped: 0, held: /* @__PURE__ */ new Set() };
6100
+ scopes.set(name, state);
6101
+ const scope = {
6102
+ name,
6103
+ url: `${url}/${name}`,
6104
+ journal: state.journal,
6105
+ get dropped() {
6106
+ return state.dropped;
6107
+ },
6108
+ add(...inputs) {
6109
+ for (const input of inputs) {
6110
+ const result = stubSchema.safeParse(input);
6111
+ if (!result.success)
6112
+ throw new Error(`Invalid stub: ${formatIssues(result.error).join("; ")}`);
6113
+ state.stubs.push({
6114
+ stub: result.data,
6115
+ matches: result.data.match === "exact" ? (path12) => maskedTextMatches(result.data.path, path12) : pathMatcher(result.data.path),
6116
+ calls: 0
6117
+ });
6118
+ }
6119
+ },
6120
+ close() {
6121
+ if (scopes.get(name) === state) scopes.delete(name);
6122
+ const unused = state.stubs.filter((s) => s.calls === 0).map((s) => s.stub);
6123
+ state.stubs = [];
6124
+ for (const abort of [...state.held]) abort();
6125
+ return unused;
6126
+ }
6127
+ };
6128
+ scope.add(...stubs);
6129
+ return scope;
6130
+ },
6131
+ close() {
6132
+ closing ??= new Promise((resolve9) => {
6133
+ for (const state of scopes.values()) for (const abort of [...state.held]) abort();
6134
+ scopes.clear();
6135
+ server.close(() => resolve9());
6136
+ server.closeAllConnections();
6137
+ });
6138
+ return closing;
6139
+ }
6140
+ };
6141
+ }
6142
+
4688
6143
  // src/cli/commands/run.ts
4689
6144
  var NOOP_CACHE = { get: () => void 0, set: () => {
4690
6145
  }, delete: () => {
@@ -4711,12 +6166,12 @@ function parseToolDescriptions(values) {
4711
6166
  const file = text.slice(1);
4712
6167
  try {
4713
6168
  const full = path6.resolve(file);
4714
- const stat2 = fs5.statSync(full);
6169
+ const stat2 = fs6.statSync(full);
4715
6170
  if (!stat2.isFile())
4716
6171
  throw new RunConfigError(`--tool-description ${tool}: ${file} is not a file`);
4717
6172
  if (stat2.size > MAX_DESCRIPTION_BYTES)
4718
6173
  throw new RunConfigError(`--tool-description ${tool}: ${file} is over 64 KB`);
4719
- text = fs5.readFileSync(full, "utf8").replace(/\r?\n$/, "");
6174
+ text = fs6.readFileSync(full, "utf8").replace(/\r?\n$/, "");
4720
6175
  } catch (err) {
4721
6176
  if (err instanceof RunConfigError) throw err;
4722
6177
  throw new RunConfigError(`--tool-description ${tool}: cannot read ${file}`);
@@ -4734,7 +6189,7 @@ function mockScript(env) {
4734
6189
  if (file === void 0 || file === "") return void 0;
4735
6190
  let text;
4736
6191
  try {
4737
- text = fs5.readFileSync(path6.resolve(file), "utf8");
6192
+ text = fs6.readFileSync(path6.resolve(file), "utf8");
4738
6193
  } catch {
4739
6194
  throw new RunConfigError(`PLUNE_MOCK_SCRIPT: cannot read ${file}`);
4740
6195
  }
@@ -4768,11 +6223,11 @@ function resolveProviderFor(config, dryRun) {
4768
6223
  return () => makeMockProvider(script);
4769
6224
  }
4770
6225
  if (dryRun) return (cfg) => makeEstimateProvider(cfg, config.pricing);
4771
- return (cfg) => getProvider(cfg, process.env, config.pricing);
6226
+ return (cfg, stubOrigin) => getProvider(cfg, process.env, config.pricing, stubOrigin);
4772
6227
  }
4773
6228
  function buildRealDeps(config, baseDir, dryRun) {
4774
6229
  const dir = path6.join(baseDir, ".plune");
4775
- fs5.mkdirSync(dir, { recursive: true });
6230
+ fs6.mkdirSync(dir, { recursive: true });
4776
6231
  return {
4777
6232
  resolveProvider: resolveProviderFor(config, dryRun),
4778
6233
  embedder: getDefaultEmbedder(),
@@ -4785,27 +6240,58 @@ function buildRealDeps(config, baseDir, dryRun) {
4785
6240
  ...isMockMode(process.env) ? {} : {
4786
6241
  jevJudge: (cfg, onCost) => {
4787
6242
  warnJevExperimental();
4788
- return makeJevJudge(cfg, { env: process.env, fetchFn: fetch, onCost });
4789
- }
6243
+ return makeJevJudge(cfg, {
6244
+ env: process.env,
6245
+ fetchFn: fetch,
6246
+ onCost,
6247
+ ...config.pricing !== void 0 ? { pricing: config.pricing } : {}
6248
+ });
6249
+ },
6250
+ jevCost: (model, inputTokens) => jevCost(model, inputTokens, config.pricing)
4790
6251
  }
4791
6252
  };
4792
6253
  }
4793
6254
  function persist(result, baseDir) {
4794
6255
  const dir = path6.join(baseDir, ".plune");
4795
- fs5.mkdirSync(dir, { recursive: true });
4796
- fs5.writeFileSync(path6.join(dir, "last-run.json"), JSON.stringify(result, null, 2));
6256
+ fs6.mkdirSync(dir, { recursive: true });
6257
+ fs6.writeFileSync(path6.join(dir, "last-run.json"), JSON.stringify(result, null, 2));
6258
+ }
6259
+ function stubWarnings(config, result) {
6260
+ return result.evals.flatMap((ev) => {
6261
+ if (ev.stubs === void 0) return [];
6262
+ const { never_called: never, unmatched } = ev.stubs;
6263
+ const file = config.evals.find((e) => e.id === baseEvalId(ev))?.stubs ?? "its stub file";
6264
+ return [
6265
+ ...never.length > 0 ? [`${never.map((i) => `stubs.${i}`).join(", ")} of ${file} ${never.length === 1 ? "was" : "were"} never called`] : [],
6266
+ ...unmatched.length > 0 ? [
6267
+ `${unmatched.length} request${unmatched.length === 1 ? "" : "s"} matched no stub: ` + unmatched.map((u) => `${u.method} in ${u.scope}`).join(", ")
6268
+ ] : []
6269
+ ].map((line) => `eval "${ev.id}": ${line}`);
6270
+ });
6271
+ }
6272
+ function jevAddressCheck(config, env) {
6273
+ const checks = [...config.defaults?.assertions ?? [], ...config.evals.flatMap((ev) => ev.assertions)];
6274
+ if (!checks.some((a) => a.type === "llm-judge" && a.provider?.type === "jev")) return;
6275
+ try {
6276
+ jevBaseUrl(env);
6277
+ } catch (err) {
6278
+ throw new RunConfigError(err.message);
6279
+ }
4797
6280
  }
4798
6281
  async function handleRun(options, depsFactory) {
4799
6282
  const config = await loadConfig(
4800
6283
  options.configPath !== void 0 ? { configPath: options.configPath } : {}
4801
6284
  );
4802
6285
  const baseDir = options.configPath !== void 0 ? path6.dirname(path6.resolve(options.configPath)) : process.cwd();
6286
+ jevAddressCheck(config, process.env);
4803
6287
  for (const warning of [...mcpSecretWarnings(config), ...selfJudgeWarnings(config)])
4804
6288
  process.stderr.write(`warning: ${warning}
4805
6289
  `);
4806
6290
  const toolDescriptions = options.toolDescription !== void 0 && options.toolDescription.length > 0 ? parseToolDescriptions(options.toolDescription) : void 0;
4807
6291
  const factory = depsFactory ?? ((c, d) => buildRealDeps(c, d, options.dryRun));
4808
- const deps = factory(config, baseDir);
6292
+ const given = factory(config, baseDir);
6293
+ let stubServer;
6294
+ const deps = depsFactory === void 0 && isMockMode(process.env) ? given : { ...given, stubServer: () => stubServer ??= (given.stubServer ?? start)() };
4809
6295
  try {
4810
6296
  const stale = deps.cache.staleEntries ?? 0;
4811
6297
  if (stale > 0) {
@@ -4841,6 +6327,8 @@ async function handleRun(options, depsFactory) {
4841
6327
  `
4842
6328
  );
4843
6329
  }
6330
+ for (const warning of stubWarnings(config, result)) process.stderr.write(`warning: ${warning}
6331
+ `);
4844
6332
  if (options.dryRun) {
4845
6333
  const agentic = new Set(config.evals.filter((ev) => ev.mcp !== void 0).map((ev) => ev.id));
4846
6334
  if (result.evals.some((ev) => agentic.has(ev.id)))
@@ -4852,164 +6340,173 @@ async function handleRun(options, depsFactory) {
4852
6340
  return result;
4853
6341
  } finally {
4854
6342
  deps.cache.close();
6343
+ if (stubServer !== void 0) await stubServer.then((server) => server.close(), () => void 0);
4855
6344
  }
4856
6345
  }
4857
6346
 
4858
6347
  // src/cli/commands/sync.ts
4859
6348
  init_esm_shims();
4860
6349
  import { createHash as createHash2 } from "crypto";
4861
- import * as fs6 from "fs";
6350
+ import * as fs7 from "fs";
4862
6351
  import * as path7 from "path";
4863
6352
 
4864
6353
  // src/types/run-result-schema.ts
4865
6354
  init_esm_shims();
4866
- import { z as z3 } from "zod";
6355
+ import { z as z4 } from "zod";
4867
6356
  var RUN_RESULT_SCHEMA_VERSION = 1;
4868
- var binaryVerdictSchema = z3.object({
4869
- question: z3.string().min(1),
4870
- passed: z3.boolean()
6357
+ var binaryVerdictSchema = z4.object({
6358
+ question: z4.string().min(1),
6359
+ passed: z4.boolean()
4871
6360
  });
4872
- var assertionResultRecordSchema2 = z3.object({
4873
- type: z3.string(),
4874
- passed: z3.boolean(),
4875
- score: z3.number().optional(),
4876
- reason: z3.string().optional(),
4877
- binaryVerdicts: z3.array(binaryVerdictSchema).optional(),
6361
+ var assertionResultRecordSchema2 = z4.object({
6362
+ type: z4.string(),
6363
+ passed: z4.boolean(),
6364
+ score: z4.number().optional(),
6365
+ reason: z4.string().optional(),
6366
+ binaryVerdicts: z4.array(binaryVerdictSchema).optional(),
4878
6367
  /** plune-ai/cli#373. Optional and additive — a RunResult written before it validates unchanged. */
4879
- judge_model: z3.string().optional()
6368
+ judge_model: z4.string().optional()
4880
6369
  });
4881
- var usageSchema = z3.object({
4882
- input_tokens: z3.number(),
4883
- output_tokens: z3.number(),
4884
- cost_usd: z3.number(),
6370
+ var usageSchema = z4.object({
6371
+ input_tokens: z4.number(),
6372
+ output_tokens: z4.number(),
6373
+ cost_usd: z4.number(),
4885
6374
  /** cli#151. Optional and additive — a RunResult written before it validates unchanged. */
4886
- priced: z3.boolean().optional()
6375
+ priced: z4.boolean().optional()
4887
6376
  });
4888
- var runErrorSchema = z3.object({
4889
- code: z3.string(),
4890
- message: z3.string()
6377
+ var runErrorSchema = z4.object({
6378
+ code: z4.string(),
6379
+ message: z4.string()
4891
6380
  });
4892
- var savedSchema = z3.object({
4893
- input_tokens: z3.number(),
4894
- output_tokens: z3.number(),
4895
- cost_usd: z3.number()
6381
+ var savedSchema = z4.object({
6382
+ input_tokens: z4.number(),
6383
+ output_tokens: z4.number(),
6384
+ cost_usd: z4.number()
4896
6385
  });
4897
- var rowResultSchema = z3.object({
4898
- vars: z3.record(z3.string(), z3.unknown()),
4899
- output: z3.string().nullable(),
4900
- cached: z3.boolean(),
6386
+ var rowResultSchema = z4.object({
6387
+ vars: z4.record(z4.string(), z4.unknown()),
6388
+ output: z4.string().nullable(),
6389
+ cached: z4.boolean(),
6390
+ /** A row of an eval with `stubs`. Kept by the parser so that `plune sync` can see it and refuse the upload. */
6391
+ stubbed: z4.boolean().optional(),
4901
6392
  usage: usageSchema.optional(),
4902
- latency_ms: z3.number().optional(),
6393
+ latency_ms: z4.number().optional(),
4903
6394
  error: runErrorSchema.optional(),
4904
- assertions: z3.array(assertionResultRecordSchema2),
6395
+ assertions: z4.array(assertionResultRecordSchema2),
4905
6396
  cache_saved: savedSchema.optional(),
4906
6397
  /** Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
4907
- inconclusive: z3.enum(ROW_INCONCLUSIVE).optional(),
6398
+ inconclusive: z4.enum(ROW_INCONCLUSIVE).optional(),
4908
6399
  /** Repeats (`runs` above 1). Optional and additive — a RunResult without it validates unchanged. */
4909
- attempts: z3.object({
4910
- runs: z3.number(),
4911
- pass_threshold: z3.number(),
4912
- passed: z3.number(),
4913
- failed: z3.number(),
4914
- errored: z3.number(),
4915
- results: z3.array(
4916
- z3.object({
4917
- output: z3.string().nullable(),
4918
- cached: z3.boolean(),
6400
+ attempts: z4.object({
6401
+ runs: z4.number(),
6402
+ pass_threshold: z4.number(),
6403
+ passed: z4.number(),
6404
+ failed: z4.number(),
6405
+ errored: z4.number(),
6406
+ results: z4.array(
6407
+ z4.object({
6408
+ output: z4.string().nullable(),
6409
+ cached: z4.boolean(),
4919
6410
  usage: usageSchema.optional(),
4920
- latency_ms: z3.number().optional(),
6411
+ latency_ms: z4.number().optional(),
4921
6412
  error: runErrorSchema.optional(),
4922
- assertions: z3.array(assertionResultRecordSchema2),
6413
+ assertions: z4.array(assertionResultRecordSchema2),
4923
6414
  cache_saved: savedSchema.optional()
4924
6415
  })
4925
6416
  )
4926
6417
  }).optional(),
4927
6418
  /** The tool loop of an eval with an `mcp` server. Optional and additive — a RunResult without it validates unchanged. */
4928
- agent: z3.object({
4929
- server: z3.string(),
4930
- tools: z3.array(
4931
- z3.object({
4932
- name: z3.string(),
4933
- offered: z3.boolean(),
4934
- annotations: z3.record(z3.string(), z3.unknown()).optional()
6419
+ agent: z4.object({
6420
+ server: z4.string(),
6421
+ tools: z4.array(
6422
+ z4.object({
6423
+ name: z4.string(),
6424
+ offered: z4.boolean(),
6425
+ annotations: z4.record(z4.string(), z4.unknown()).optional()
4935
6426
  })
4936
6427
  ),
4937
- steps: z3.array(
4938
- z3.object({
4939
- index: z3.number(),
4940
- text: z3.string(),
4941
- finish_reason: z3.string().optional(),
6428
+ steps: z4.array(
6429
+ z4.object({
6430
+ index: z4.number(),
6431
+ text: z4.string(),
6432
+ finish_reason: z4.string().optional(),
4942
6433
  usage: usageSchema,
4943
- calls: z3.array(
4944
- z3.object({
4945
- id: z3.string(),
4946
- name: z3.string(),
4947
- args: z3.unknown(),
4948
- executed: z3.boolean(),
4949
- is_error: z3.boolean(),
4950
- error_kind: z3.enum(["content", "protocol", "timeout", "not-offered", "bad-arguments"]).optional(),
4951
- duration_ms: z3.number().optional(),
4952
- result: z3.object({ text: z3.string(), bytes: z3.number(), truncated: z3.boolean() }).optional()
6434
+ calls: z4.array(
6435
+ z4.object({
6436
+ id: z4.string(),
6437
+ name: z4.string(),
6438
+ args: z4.unknown(),
6439
+ executed: z4.boolean(),
6440
+ is_error: z4.boolean(),
6441
+ error_kind: z4.enum(["content", "protocol", "timeout", "not-offered", "bad-arguments"]).optional(),
6442
+ duration_ms: z4.number().optional(),
6443
+ result: z4.object({ text: z4.string(), bytes: z4.number(), truncated: z4.boolean() }).optional()
4953
6444
  })
4954
6445
  ),
4955
6446
  /** Optional and additive: the step whose request first offered a changed list. */
4956
- offered_changed: z3.object({ added: z3.array(z3.string()), removed: z3.array(z3.string()) }).optional()
6447
+ offered_changed: z4.object({ added: z4.array(z4.string()), removed: z4.array(z4.string()) }).optional()
4957
6448
  })
4958
6449
  ),
4959
- stop: z3.object({
4960
- reason: z3.enum(["complete", "limit", "error"]),
4961
- limit: z3.enum(["max_steps", "max_tool_calls", "max_total_tokens", "timeout_ms", "tool_timeout_ms"]).optional()
6450
+ stop: z4.object({
6451
+ reason: z4.enum(["complete", "limit", "error"]),
6452
+ limit: z4.enum(["max_steps", "max_tool_calls", "max_total_tokens", "timeout_ms", "tool_timeout_ms"]).optional()
4962
6453
  }),
4963
- collection: z3.enum(["complete", "partial"]),
6454
+ collection: z4.enum(["complete", "partial"]),
4964
6455
  /** Heuristic findings, never a verdict. Optional and additive. */
4965
- advice: z3.array(
4966
- z3.object({
4967
- type: z3.string(),
4968
- reason: z3.string(),
4969
- tool: z3.string().optional(),
4970
- steps: z3.array(z3.number()).optional(),
4971
- count: z3.number().optional(),
4972
- paths: z3.array(z3.string()).optional()
6456
+ advice: z4.array(
6457
+ z4.object({
6458
+ type: z4.string(),
6459
+ reason: z4.string(),
6460
+ tool: z4.string().optional(),
6461
+ steps: z4.array(z4.number()).optional(),
6462
+ count: z4.number().optional(),
6463
+ paths: z4.array(z4.string()).optional()
4973
6464
  })
4974
6465
  ).optional(),
4975
- description_overrides: z3.array(z3.object({ tool: z3.string(), sha256: z3.string() })).optional()
6466
+ description_overrides: z4.array(z4.object({ tool: z4.string(), sha256: z4.string() })).optional()
4976
6467
  }).optional()
4977
6468
  });
4978
- var summarySchema = z3.object({
4979
- total: z3.number(),
4980
- passed: z3.number(),
4981
- failed: z3.number(),
4982
- errored: z3.number(),
6469
+ var summarySchema = z4.object({
6470
+ total: z4.number(),
6471
+ passed: z4.number(),
6472
+ failed: z4.number(),
6473
+ errored: z4.number(),
4983
6474
  /** Optional and additive — a RunResult written before them validates unchanged. */
4984
- blocked: z3.number().optional(),
4985
- skipped: z3.number().optional(),
4986
- cost_usd: z3.number(),
4987
- duration_ms: z3.number(),
4988
- cache: z3.object({
4989
- from_cache: z3.number(),
4990
- from_model: z3.number(),
4991
- missed: z3.number(),
4992
- errored: z3.number(),
4993
- saved: z3.object({ input_tokens: z3.number(), output_tokens: z3.number(), cost_usd: z3.number() })
6475
+ blocked: z4.number().optional(),
6476
+ skipped: z4.number().optional(),
6477
+ cost_usd: z4.number(),
6478
+ duration_ms: z4.number(),
6479
+ cache: z4.object({
6480
+ from_cache: z4.number(),
6481
+ from_model: z4.number(),
6482
+ missed: z4.number(),
6483
+ errored: z4.number(),
6484
+ stubbed: z4.number().optional(),
6485
+ saved: z4.object({ input_tokens: z4.number(), output_tokens: z4.number(), cost_usd: z4.number() })
4994
6486
  }).optional()
4995
6487
  });
4996
- var evalResultSchema = z3.object({
4997
- id: z3.string(),
4998
- tags: z3.array(z3.string()),
4999
- rows: z3.array(rowResultSchema),
5000
- passed: z3.boolean(),
6488
+ var evalResultSchema = z4.object({
6489
+ id: z4.string(),
6490
+ tags: z4.array(z4.string()),
6491
+ rows: z4.array(rowResultSchema),
6492
+ passed: z4.boolean(),
5001
6493
  /** What the eval measured, for the pass-rate gate of `plune diff`. Optional and additive. */
5002
- measured: z3.object({
5003
- runs: z3.number(),
5004
- rows: z3.number(),
5005
- rows_hash: z3.string(),
5006
- assertions_hash: z3.string(),
5007
- model: z3.string().optional()
6494
+ measured: z4.object({
6495
+ runs: z4.number(),
6496
+ rows: z4.number(),
6497
+ rows_hash: z4.string(),
6498
+ assertions_hash: z4.string(),
6499
+ model: z4.string().optional()
5008
6500
  }).optional(),
5009
6501
  /** The type and model of a cell of a multi-model run. Optional and additive. */
5010
- provider: z3.object({ type: z3.string(), model: z3.string() }).optional(),
6502
+ provider: z4.object({ type: z4.string(), model: z4.string() }).optional(),
6503
+ /** The mark of an eval answered from stubs, kept for the same reason as a row's `stubbed`. */
6504
+ stubs: z4.object({
6505
+ never_called: z4.array(z4.number()),
6506
+ unmatched: z4.array(z4.object({ scope: z4.string(), method: z4.string() }))
6507
+ }).optional(),
5011
6508
  /** The link to the eval's trace in your own observability (Langfuse, OTel). Optional and additive; `plune sync` drops one `traceUrlProblem` refuses. */
5012
- traceUrl: z3.string().optional()
6509
+ traceUrl: z4.string().optional()
5013
6510
  });
5014
6511
  var TRACE_URL_MAX = 2048;
5015
6512
  function traceUrlProblem(value) {
@@ -5027,16 +6524,16 @@ function traceUrlProblem(value) {
5027
6524
  if (parsed2.username !== "" || parsed2.password !== "") return "must carry no user name or password";
5028
6525
  return void 0;
5029
6526
  }
5030
- var runResultSchema = z3.object({
5031
- schemaVersion: z3.literal(RUN_RESULT_SCHEMA_VERSION),
5032
- plune_version: z3.string(),
5033
- started_at: z3.string(),
5034
- finished_at: z3.string(),
5035
- config_hash: z3.string(),
6527
+ var runResultSchema = z4.object({
6528
+ schemaVersion: z4.literal(RUN_RESULT_SCHEMA_VERSION),
6529
+ plune_version: z4.string(),
6530
+ started_at: z4.string(),
6531
+ finished_at: z4.string(),
6532
+ config_hash: z4.string(),
5036
6533
  /** cli#244. The result of `--dry-run`. Optional and additive — a RunResult without it validates unchanged. */
5037
- dry_run: z3.boolean().optional(),
6534
+ dry_run: z4.boolean().optional(),
5038
6535
  summary: summarySchema,
5039
- evals: z3.array(evalResultSchema)
6536
+ evals: z4.array(evalResultSchema)
5040
6537
  });
5041
6538
  function parseRunResult(value) {
5042
6539
  return runResultSchema.parse(value);
@@ -5044,11 +6541,30 @@ function parseRunResult(value) {
5044
6541
 
5045
6542
  // src/cli/api-url.ts
5046
6543
  init_esm_shims();
5047
- var DEFAULT_API_URL = "https://beta-api.plune.ai";
6544
+ var PRODUCTION_API_URL = "https://api.plune.ai";
6545
+ var BETA_API_URL = "https://beta-api.plune.ai";
6546
+ var DEFAULT_API_URL = PRODUCTION_API_URL;
6547
+ var DASHBOARDS = /* @__PURE__ */ new Map([
6548
+ [PRODUCTION_API_URL, "https://app.plune.ai"],
6549
+ [BETA_API_URL, "https://beta.plune.ai"]
6550
+ ]);
5048
6551
  function resolveApiUrl(explicit) {
5049
- const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
6552
+ const raw = explicit?.trim() || process.env["PLUNE_API_URL"]?.trim() || DEFAULT_API_URL;
5050
6553
  return raw.replace(/\/+$/, "");
5051
6554
  }
6555
+ function knownApi(apiUrl) {
6556
+ try {
6557
+ const origin = new URL(apiUrl.trim()).origin;
6558
+ return DASHBOARDS.has(origin) ? origin : void 0;
6559
+ } catch {
6560
+ return void 0;
6561
+ }
6562
+ }
6563
+ function tokenRefusedBy(apiUrl = resolveApiUrl()) {
6564
+ const named = `The address that refused it is ${apiUrl}.`;
6565
+ if (knownApi(apiUrl) !== PRODUCTION_API_URL) return named;
6566
+ 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.`;
6567
+ }
5052
6568
 
5053
6569
  // src/cli/credentials.ts
5054
6570
  init_esm_shims();
@@ -5168,9 +6684,9 @@ var NotLoggedInError = class extends Error {
5168
6684
  }
5169
6685
  };
5170
6686
  var TokenRejectedError = class extends Error {
5171
- constructor() {
6687
+ constructor(apiUrl = resolveApiUrl()) {
5172
6688
  super(
5173
- 'Your API token was rejected (revoked or invalid). Run "plune login" with a fresh token.'
6689
+ `Your API token was rejected (revoked or invalid). Run "plune login" with a fresh token. ${tokenRefusedBy(apiUrl)}`
5174
6690
  );
5175
6691
  this.name = "TokenRejectedError";
5176
6692
  }
@@ -5201,7 +6717,7 @@ function readRun(cwd, file, warn) {
5201
6717
  const target = file !== void 0 ? path7.resolve(cwd, file) : path7.join(cwd, ".plune", "last-run.json");
5202
6718
  let raw;
5203
6719
  try {
5204
- raw = fs6.readFileSync(target, "utf8");
6720
+ raw = fs7.readFileSync(target, "utf8");
5205
6721
  } catch {
5206
6722
  throw new SyncFileError(
5207
6723
  file !== void 0 ? `Run file not found: ${target}` : 'No run to sync. Run "plune run" first (or pass --file <path>).'
@@ -5214,11 +6730,18 @@ function readRun(cwd, file, warn) {
5214
6730
  throw new SyncFileError(`Run file is not valid JSON: ${target}`);
5215
6731
  }
5216
6732
  dropBadTraceLinks(json, warn);
6733
+ let run;
5217
6734
  try {
5218
- return parseRunResult(json);
6735
+ run = parseRunResult(json);
5219
6736
  } catch {
5220
6737
  throw new SyncFileError(`Run file does not match the RunResult schema: ${target}`);
5221
6738
  }
6739
+ const stubbed = stubbedEvals(run);
6740
+ if (stubbed.length > 0)
6741
+ throw new SyncFileError(
6742
+ `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).`
6743
+ );
6744
+ return run;
5222
6745
  }
5223
6746
  function dropBadTraceLinks(json, warn) {
5224
6747
  const evals = json?.evals;
@@ -5283,7 +6806,7 @@ async function handleSync(deps = {}) {
5283
6806
  }
5284
6807
  if (!res.ok) {
5285
6808
  const detail = await safeErrorDetail(res);
5286
- if (res.status === 401) throw new TokenRejectedError();
6809
+ if (res.status === 401) throw new TokenRejectedError(apiUrl);
5287
6810
  throw new SyncHttpError(res.status, detail);
5288
6811
  }
5289
6812
  const body = await res.json().catch(() => ({}));
@@ -5581,7 +7104,7 @@ var BUCKET_CODES = /* @__PURE__ */ new Set([
5581
7104
 
5582
7105
  // src/reporter-core/fallback.ts
5583
7106
  init_esm_shims();
5584
- import * as fs7 from "fs";
7107
+ import * as fs8 from "fs";
5585
7108
  import * as path9 from "path";
5586
7109
  var DEFAULT_FALLBACK_PATH = path9.join(".plune", "pending-results.jsonl");
5587
7110
 
@@ -5634,12 +7157,12 @@ var TYPE_BY_EXTENSION = {
5634
7157
  var READ_NOT_KEPT = /* @__PURE__ */ new Set(["application/plune.metadata+json", "application/plune.findings+json"]);
5635
7158
  var NAME_MAX = 200;
5636
7159
  function nameOf(file) {
5637
- const own2 = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : basename3(file.path));
7160
+ const own3 = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : basename3(file.path));
5638
7161
  const fileExt = file.path === void 0 ? "" : extname(file.path);
5639
- const ownExt = extname(own2);
7162
+ const ownExt = extname(own3);
5640
7163
  const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
5641
7164
  const ext = typed ? ownExt : fileExt;
5642
- let stem = typed ? own2.slice(0, -ownExt.length) : own2;
7165
+ let stem = typed ? own3.slice(0, -ownExt.length) : own3;
5643
7166
  if (stem.length + ext.length > NAME_MAX) {
5644
7167
  stem = stem.slice(0, Math.max(0, NAME_MAX - ext.length));
5645
7168
  if (/[\uD800-\uDBFF]$/.test(stem)) stem = stem.slice(0, -1);
@@ -5777,9 +7300,9 @@ function fileSender(options) {
5777
7300
  if (out.ok) countsOf(kind).uploaded += 1;
5778
7301
  else failed(job, out.detail || out.kind);
5779
7302
  }
5780
- async function uploadToBucket(job, size, first) {
7303
+ async function uploadToBucket(job, size, first2) {
5781
7304
  const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
5782
- let link = first;
7305
+ let link = first2;
5783
7306
  for (let renewed = false; ; ) {
5784
7307
  const put = await client.put(link.url, link.headers, source);
5785
7308
  if (put.ok) break;
@@ -5792,8 +7315,8 @@ function fileSender(options) {
5792
7315
  link = fresh;
5793
7316
  }
5794
7317
  requests += 1;
5795
- const done = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
5796
- if (!done.ok) return failedToBucket(job, codeOf2(done));
7318
+ const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
7319
+ if (!done2.ok) return failedToBucket(job, codeOf2(done2));
5797
7320
  countsOf(job.kind).uploaded += 1;
5798
7321
  }
5799
7322
  let free = uploadsAtOnce;
@@ -5959,9 +7482,9 @@ function fileSender(options) {
5959
7482
  const toComplete = [];
5960
7483
  await Promise.all(
5961
7484
  puts.map(
5962
- ({ s, link: first }) => gated(async () => {
7485
+ ({ s, link: first2 }) => gated(async () => {
5963
7486
  const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
5964
- let link = first;
7487
+ let link = first2;
5965
7488
  for (let renewed = false; ; ) {
5966
7489
  const put = await client.put(link.url, link.headers, source);
5967
7490
  if (put.ok) break;
@@ -6147,7 +7670,7 @@ function fileSender(options) {
6147
7670
 
6148
7671
  // src/cli/commands/cairn-artifact.ts
6149
7672
  init_esm_shims();
6150
- import * as fs8 from "fs/promises";
7673
+ import * as fs9 from "fs/promises";
6151
7674
  import * as path10 from "path";
6152
7675
 
6153
7676
  // src/importers/trace-url.ts
@@ -7710,14 +9233,14 @@ var NoCairnRunsError = class extends Error {
7710
9233
  }
7711
9234
  };
7712
9235
  async function findLatestCairnRun(runsDir = "runs") {
7713
- const entries = await fs8.readdir(runsDir, { withFileTypes: true }).catch(() => null);
9236
+ const entries = await fs9.readdir(runsDir, { withFileTypes: true }).catch(() => null);
7714
9237
  if (entries === null) throw new NoCairnRunsError(runsDir);
7715
9238
  let newest;
7716
9239
  for (const entry of entries) {
7717
9240
  if (!entry.isDirectory()) continue;
7718
9241
  const dir = path10.join(runsDir, entry.name);
7719
9242
  try {
7720
- const report = await fs8.lstat(path10.join(dir, "report.json"));
9243
+ const report = await fs9.lstat(path10.join(dir, "report.json"));
7721
9244
  if (!report.isFile()) continue;
7722
9245
  if (newest === void 0 || report.mtimeMs > newest.at) {
7723
9246
  newest = { dir, at: report.mtimeMs };
@@ -7768,13 +9291,13 @@ var CairnEvidenceAmbiguousError = class extends Error {
7768
9291
  };
7769
9292
  var asRecord = (v) => typeof v === "object" && v !== null ? v : {};
7770
9293
  var str = (v, fallback = "") => typeof v === "string" && v !== "" ? v : fallback;
7771
- var own = (rec, key) => Object.hasOwn(rec, key) ? rec[key] : void 0;
9294
+ var own2 = (rec, key) => Object.hasOwn(rec, key) ? rec[key] : void 0;
7772
9295
  var MAX_ARTIFACT_BYTES = 32 * 1024 * 1024;
7773
9296
  var MAX_MCP_CASES = 5e3;
7774
9297
  async function checkSize(dir, file) {
7775
9298
  let size;
7776
9299
  try {
7777
- const st = await fs8.stat(path10.join(dir, file));
9300
+ const st = await fs9.stat(path10.join(dir, file));
7778
9301
  if (!st.isFile()) throw new CairnArtifactShapeError(file, "", "is not a regular file");
7779
9302
  size = st.size;
7780
9303
  } catch (e) {
@@ -7792,20 +9315,20 @@ async function checkSize(dir, file) {
7792
9315
  }
7793
9316
  async function readJson(file) {
7794
9317
  try {
7795
- return JSON.parse(await fs8.readFile(file, "utf8"));
9318
+ return JSON.parse(await fs9.readFile(file, "utf8"));
7796
9319
  } catch {
7797
9320
  return void 0;
7798
9321
  }
7799
9322
  }
7800
9323
  var ARGS_CHARS2 = 200;
7801
- var SECRET_NAME = /key|token|secret|password|passwd|auth|cookie|credential/i;
9324
+ var SECRET_NAME2 = /key|token|secret|password|passwd|auth|cookie|credential/i;
7802
9325
  var maskNamed = (v, depth = 0) => {
7803
9326
  if (depth > 16) return "[deep]";
7804
9327
  if (Array.isArray(v)) return v.slice(0, 50).map((x) => maskNamed(x, depth + 1));
7805
9328
  if (typeof v === "object" && v !== null) {
7806
9329
  const out = {};
7807
9330
  for (const [k, x] of Object.entries(v).slice(0, 50)) {
7808
- out[k] = SECRET_NAME.test(k) ? "***" : maskNamed(x, depth + 1);
9331
+ out[k] = SECRET_NAME2.test(k) ? "***" : maskNamed(x, depth + 1);
7809
9332
  }
7810
9333
  return out;
7811
9334
  }
@@ -7832,7 +9355,7 @@ async function readMcpEvidence(dir, states) {
7832
9355
  if (!await checkSize(dir, file)) return void 0;
7833
9356
  let raw;
7834
9357
  try {
7835
- raw = JSON.parse(await fs8.readFile(path10.join(dir, file), "utf8"));
9358
+ raw = JSON.parse(await fs9.readFile(path10.join(dir, file), "utf8"));
7836
9359
  } catch {
7837
9360
  throw new CairnArtifactShapeError(file, "", "is not valid JSON");
7838
9361
  }
@@ -7846,7 +9369,7 @@ async function readMcpEvidence(dir, states) {
7846
9369
  throw new CairnArtifactShapeError(file, `[${i}]`, "must be an object");
7847
9370
  }
7848
9371
  const rec = item;
7849
- const id = own(rec, "stableId");
9372
+ const id = own2(rec, "stableId");
7850
9373
  if (typeof id !== "string" || !states.has(id)) {
7851
9374
  throw new CairnArtifactShapeError(
7852
9375
  file,
@@ -7857,18 +9380,18 @@ async function readMcpEvidence(dir, states) {
7857
9380
  if (byId.has(id)) {
7858
9381
  throw new CairnArtifactShapeError(file, `[${i}].stableId`, "appears more than once");
7859
9382
  }
7860
- if (own(rec, "state") !== states.get(id)) {
9383
+ if (own2(rec, "state") !== states.get(id)) {
7861
9384
  throw new CairnArtifactShapeError(
7862
9385
  file,
7863
9386
  `[${i}].state`,
7864
9387
  "does not agree with the state in report.json"
7865
9388
  );
7866
9389
  }
7867
- const request = own(rec, "request");
9390
+ const request = own2(rec, "request");
7868
9391
  if (request !== void 0 && typeof request !== "string") {
7869
9392
  throw new CairnArtifactShapeError(file, `[${i}].request`, "must be text");
7870
9393
  }
7871
- const durationMs = own(rec, "durationMs");
9394
+ const durationMs = own2(rec, "durationMs");
7872
9395
  if (durationMs !== void 0 && typeof durationMs !== "number") {
7873
9396
  throw new CairnArtifactShapeError(file, `[${i}].durationMs`, "must be a number");
7874
9397
  }
@@ -7886,7 +9409,7 @@ function expectedOfMcp(type, adversarial) {
7886
9409
  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.";
7887
9410
  }
7888
9411
  async function casesFromMcp(dir, report) {
7889
- const list2 = own(report, "cases");
9412
+ const list2 = own2(report, "cases");
7890
9413
  if (!Array.isArray(list2))
7891
9414
  throw new CairnArtifactShapeError("report.json", "cases", "must be a list");
7892
9415
  if (list2.length > MAX_MCP_CASES) {
@@ -7904,7 +9427,7 @@ async function casesFromMcp(dir, report) {
7904
9427
  }
7905
9428
  const c = raw;
7906
9429
  const text = (key) => {
7907
- const v = own(c, key);
9430
+ const v = own2(c, key);
7908
9431
  if (typeof v !== "string" || v === "") {
7909
9432
  throw new CairnArtifactShapeError("report.json", `${at}.${key}`, "must be text");
7910
9433
  }
@@ -7934,14 +9457,14 @@ async function casesFromMcp(dir, report) {
7934
9457
  }
7935
9458
  states.set(stableId, state);
7936
9459
  const kind = type;
7937
- const technique = own(c, "technique");
9460
+ const technique = own2(c, "technique");
7938
9461
  return {
7939
9462
  stableId,
7940
9463
  name,
7941
9464
  tool,
7942
9465
  type: kind,
7943
9466
  state,
7944
- adversarial: own(c, "adversarialStyle") !== void 0,
9467
+ adversarial: own2(c, "adversarialStyle") !== void 0,
7945
9468
  ...typeof technique === "string" ? { technique } : {}
7946
9469
  };
7947
9470
  });
@@ -7977,7 +9500,7 @@ function casesFromDesign(report, notes) {
7977
9500
  const c = asRecord(raw);
7978
9501
  const steps = (Array.isArray(c["steps"]) ? c["steps"] : []).map((s) => str(s)).filter((s) => s !== "");
7979
9502
  const title = str(c["title"], "untitled case");
7980
- const link = own(c, "traceUrl") ?? void 0;
9503
+ const link = own2(c, "traceUrl") ?? void 0;
7981
9504
  const said = [];
7982
9505
  const traceUrl = traceUrlOf(link, title, said);
7983
9506
  if (said.length > 0) {
@@ -8047,11 +9570,11 @@ async function readCairnRun(dir, deps = {}) {
8047
9570
  }
8048
9571
  cases = casesFromApi(report, verdicts);
8049
9572
  } else if (mode === "mcp") {
8050
- cases = own(report, "cases") === void 0 && Array.isArray(own(report, "testCases")) ? casesFromDesign(report, deps.notes ?? []) : await casesFromMcp(dir, report);
9573
+ cases = own2(report, "cases") === void 0 && Array.isArray(own2(report, "testCases")) ? casesFromDesign(report, deps.notes ?? []) : await casesFromMcp(dir, report);
8051
9574
  } else {
8052
9575
  cases = casesFromDesign(report, deps.notes ?? []);
8053
9576
  }
8054
- const tokens = own(asRecord(own(report, "cost")), "totalTokens");
9577
+ const tokens = own2(asRecord(own2(report, "cost")), "totalTokens");
8055
9578
  return {
8056
9579
  schemaVersion: INGEST_SCHEMA_VERSION,
8057
9580
  run: {
@@ -8069,7 +9592,7 @@ var clip = (s) => s.slice(0, DECLARED.text).replace(/[\uD800-\uDBFF]$/, "");
8069
9592
  async function readCairnSessionFiles(dir) {
8070
9593
  const raw = await readJson(path10.join(dir, "screencasts", "screencasts.json"));
8071
9594
  if (!Array.isArray(raw)) return void 0;
8072
- const root = await fs8.realpath(dir).catch(() => path10.resolve(dir));
9595
+ const root = await fs9.realpath(dir).catch(() => path10.resolve(dir));
8073
9596
  const within = (p) => {
8074
9597
  const rel = path10.relative(root, p);
8075
9598
  return rel !== "" && !rel.startsWith("..") && !path10.isAbsolute(rel);
@@ -8078,10 +9601,10 @@ async function readCairnSessionFiles(dir) {
8078
9601
  const inside = async (p) => {
8079
9602
  if (typeof p !== "string" || p === "") return void 0;
8080
9603
  const abs = path10.resolve(root, p);
8081
- const real = await fs8.realpath(abs).catch(() => void 0);
9604
+ const real = await fs9.realpath(abs).catch(() => void 0);
8082
9605
  if (within(abs) && (real === void 0 || within(real))) {
8083
9606
  const file = real ?? abs;
8084
- const size = await fs8.stat(file).then((s) => s.size, () => void 0);
9607
+ const size = await fs9.stat(file).then((s) => s.size, () => void 0);
8085
9608
  return { path: file, rel: path10.relative(root, abs).split(path10.sep).join("/"), ...size !== void 0 ? { size } : {} };
8086
9609
  }
8087
9610
  outside += 1;
@@ -8094,11 +9617,11 @@ async function readCairnSessionFiles(dir) {
8094
9617
  const rec = asRecord(entry);
8095
9618
  const found = [];
8096
9619
  for (const kind of ["video", "trace"]) {
8097
- const at = await inside(own(rec, kind));
9620
+ const at = await inside(own2(rec, kind));
8098
9621
  if (at !== void 0) found.push({ file: { path: at.path, ...at.size !== void 0 ? { size: at.size } : {} }, rel: at.rel, kind });
8099
9622
  }
8100
9623
  if (found.length === 0) continue;
8101
- const stableId = own(rec, "stableId");
9624
+ const stableId = own2(rec, "stableId");
8102
9625
  if (typeof stableId !== "string" || stableId === "") {
8103
9626
  unmapped += 1;
8104
9627
  continue;
@@ -8106,7 +9629,7 @@ async function readCairnSessionFiles(dir) {
8106
9629
  byCase.set(stableId, [...byCase.get(stableId) ?? [], ...found.map((f) => f.file)]);
8107
9630
  const declared = screencasts.get(stableId) ?? [];
8108
9631
  const keys = new Set(declared.flatMap((s) => s.files.map((f) => f.key)));
8109
- const title = clip(str(own(rec, "test")));
9632
+ const title = clip(str(own2(rec, "test")));
8110
9633
  const files = found.filter((f) => {
8111
9634
  if ((f.file.size ?? 0) < 1 || f.rel.length > DECLARED.text || path10.basename(f.file.path).length > DECLARED.name || keys.has(f.rel)) return false;
8112
9635
  keys.add(f.rel);
@@ -8114,14 +9637,14 @@ async function readCairnSessionFiles(dir) {
8114
9637
  });
8115
9638
  if (title === "" || files.length === 0 || declared.length >= DECLARED.perCase) continue;
8116
9639
  for (const f of files) f.file.key = f.rel;
8117
- const timing = own(rec, "timing");
9640
+ const timing = own2(rec, "timing");
8118
9641
  declared.push({
8119
9642
  title,
8120
9643
  ...timing === "trace" || timing === "estimated" ? { timing } : {},
8121
- chapters: (Array.isArray(own(rec, "chapters")) ? own(rec, "chapters") : []).flatMap((c) => {
9644
+ chapters: (Array.isArray(own2(rec, "chapters")) ? own2(rec, "chapters") : []).flatMap((c) => {
8122
9645
  const chapter = asRecord(c);
8123
- const t = clip(str(own(chapter, "title")));
8124
- const atMs = own(chapter, "atMs");
9646
+ const t = clip(str(own2(chapter, "title")));
9647
+ const atMs = own2(chapter, "atMs");
8125
9648
  return t !== "" && Number.isInteger(atMs) && atMs >= 0 ? [{ title: t, atMs }] : [];
8126
9649
  }).slice(0, DECLARED.chapters),
8127
9650
  files: files.map((f) => ({ key: f.rel, name: path10.basename(f.file.path), kind: f.kind, size: f.file.size }))
@@ -8139,8 +9662,8 @@ var IngestNotLoggedInError = class extends Error {
8139
9662
  }
8140
9663
  };
8141
9664
  var IngestTokenRejectedError = class extends Error {
8142
- constructor() {
8143
- super('Your API token was rejected (401). Run "plune login" again with a fresh token.');
9665
+ constructor(apiUrl = resolveApiUrl()) {
9666
+ super(`Your API token was rejected (401). Run "plune login" again with a fresh token. ${tokenRefusedBy(apiUrl)}`);
8144
9667
  this.name = "IngestTokenRejectedError";
8145
9668
  }
8146
9669
  };
@@ -8336,7 +9859,7 @@ async function handleIngest(deps) {
8336
9859
  }
8337
9860
  if (!res.ok) {
8338
9861
  const detail = await safeErrorDetail2(res);
8339
- if (res.status === 401) throw new IngestTokenRejectedError();
9862
+ if (res.status === 401) throw new IngestTokenRejectedError(apiUrl);
8340
9863
  throw new IngestHttpError(res.status, detail);
8341
9864
  }
8342
9865
  const body = await res.json().catch(() => ({}));