@plune-ai/cli 0.39.16 → 0.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,6 +1756,19 @@ 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
1774
  // A full version, never an alias: `jev-latest` would change the judge under a run without a word.
@@ -1232,6 +1867,7 @@ var assertionConfigSchema = z.discriminatedUnion("type", [
1232
1867
  containsAnyAssertionSchema,
1233
1868
  containsAllAssertionSchema,
1234
1869
  jsonSchemaAssertionSchema,
1870
+ jsonVerifyAssertionSchema,
1235
1871
  llmJudgeAssertionSchema,
1236
1872
  semanticSimilarityAssertionSchema,
1237
1873
  faithfulnessAssertionSchema,
@@ -1265,14 +1901,14 @@ var mcpServersSchema = z.record(z.string().min(1), mcpServerSchema).superRefine(
1265
1901
  for (const [name, server] of Object.entries(servers)) {
1266
1902
  const issue = (message) => ctx.addIssue({ code: "custom", path: [name], message });
1267
1903
  const stdio = server.command !== void 0;
1268
- const http = server.url !== void 0;
1269
- if (stdio && http)
1904
+ const http2 = server.url !== void 0;
1905
+ if (stdio && http2)
1270
1906
  issue(`server "${name}" has both command and url; give command (stdio) or url (HTTP), not both`);
1271
- else if (!stdio && !http)
1907
+ else if (!stdio && !http2)
1272
1908
  issue(`server "${name}" needs command (a stdio server) or url (an HTTP server)`);
1273
1909
  else if (stdio && server.headers !== void 0)
1274
1910
  issue(`server "${name}": headers are for a server at url, not one started with command`);
1275
- else if (http && (server.args ?? server.env ?? server.cwd) !== void 0)
1911
+ else if (http2 && (server.args ?? server.env ?? server.cwd) !== void 0)
1276
1912
  issue(`server "${name}": args, env and cwd are for a server started with command, not one at url`);
1277
1913
  }
1278
1914
  });
@@ -1292,7 +1928,9 @@ var evalConfigSchema = z.object({
1292
1928
  dataset: datasetRefSchema,
1293
1929
  assertions: z.array(assertionConfigSchema),
1294
1930
  ...evalRepeatsShape,
1295
- 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()
1296
1934
  }).refine(
1297
1935
  (data) => !(data.prompt !== void 0 && data.prompt_file !== void 0),
1298
1936
  { message: "prompt and prompt_file are mutually exclusive" }
@@ -1337,6 +1975,12 @@ var pluneConfigSchema = z.object({
1337
1975
  });
1338
1976
  }
1339
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
+ });
1340
1984
  const server = evalConfig.mcp?.server;
1341
1985
  if (server === void 0) {
1342
1986
  const misplaced = (assertions, path12) => assertions.forEach((a, j) => {
@@ -1360,8 +2004,8 @@ var pluneConfigSchema = z.object({
1360
2004
  });
1361
2005
  }).transform(({ provider, ...rest }) => {
1362
2006
  if (!Array.isArray(provider)) return { provider, ...rest };
1363
- const [first, ...others] = provider;
1364
- 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 };
1365
2009
  });
1366
2010
 
1367
2011
  // src/config/env-overrides.ts
@@ -1536,7 +2180,7 @@ async function loadConfig(opts = {}) {
1536
2180
  }
1537
2181
  let parsed2;
1538
2182
  try {
1539
- parsed2 = parse(raw);
2183
+ parsed2 = parse2(raw);
1540
2184
  } catch (err) {
1541
2185
  throw new YamlParseError(
1542
2186
  `YAML parse error in ${resolvedPath}: ${err.message}`
@@ -1856,7 +2500,7 @@ function warnReasoningEffortNotSent(model, effort) {
1856
2500
  `
1857
2501
  );
1858
2502
  }
1859
- var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2503
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1860
2504
  function toAnthropicMessages(messages) {
1861
2505
  return messages.map((m) => {
1862
2506
  if (m.role === "user") return { role: "user", content: m.content };
@@ -1878,13 +2522,13 @@ function toAnthropicMessages(messages) {
1878
2522
  type: "tool_use",
1879
2523
  id: c.id,
1880
2524
  name: c.name,
1881
- input: isObject(c.args) ? c.args : {}
2525
+ input: isObject2(c.args) ? c.args : {}
1882
2526
  }))
1883
2527
  ]
1884
2528
  };
1885
2529
  });
1886
2530
  }
1887
- function makeAnthropicProvider(config, env, pricing) {
2531
+ function makeAnthropicProvider(config, env, pricing, stubOrigin) {
1888
2532
  const apiKey = env[ENV_VAR];
1889
2533
  if (apiKey === void 0 || apiKey.trim() === "") {
1890
2534
  throw new AuthError(
@@ -1895,6 +2539,8 @@ function makeAnthropicProvider(config, env, pricing) {
1895
2539
  const client = new Anthropic({
1896
2540
  apiKey,
1897
2541
  maxRetries: 0,
2542
+ // The client adds `/v1/messages` itself.
2543
+ ...stubOrigin !== void 0 ? { baseURL: stubOrigin } : {},
1898
2544
  ...config.timeout !== void 0 ? { timeout: config.timeout } : {}
1899
2545
  });
1900
2546
  const maxRetries = config.max_retries ?? DEFAULT_MAX_RETRIES;
@@ -2088,12 +2734,13 @@ function makeOpenAiCompatibleProvider(opts) {
2088
2734
  }
2089
2735
  };
2090
2736
  }
2091
- function makeOpenAiProvider(config, env, pricing) {
2737
+ function makeOpenAiProvider(config, env, pricing, stubOrigin) {
2092
2738
  return makeOpenAiCompatibleProvider({
2093
2739
  config,
2094
2740
  env,
2095
2741
  pricing,
2096
2742
  apiKeyEnv: "OPENAI_API_KEY",
2743
+ ...stubOrigin !== void 0 ? { baseURL: `${stubOrigin}/v1` } : {},
2097
2744
  maxCompletionTokens: true,
2098
2745
  sendsReasoningEffort: true
2099
2746
  });
@@ -2102,13 +2749,13 @@ function makeOpenAiProvider(config, env, pricing) {
2102
2749
  // src/providers/openrouter.ts
2103
2750
  init_esm_shims();
2104
2751
  var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
2105
- function makeOpenRouterProvider(config, env, pricing) {
2752
+ function makeOpenRouterProvider(config, env, pricing, stubOrigin) {
2106
2753
  return makeOpenAiCompatibleProvider({
2107
2754
  config,
2108
2755
  env,
2109
2756
  pricing,
2110
2757
  apiKeyEnv: "OPENROUTER_API_KEY",
2111
- baseURL: OPENROUTER_BASE_URL,
2758
+ baseURL: stubOrigin !== void 0 ? `${stubOrigin}/api/v1` : OPENROUTER_BASE_URL,
2112
2759
  reportsCost: true
2113
2760
  // OpenRouter reports the call's actual cost via usage.cost (ADR-PRC02)
2114
2761
  });
@@ -2124,13 +2771,13 @@ function createProviderRegistry() {
2124
2771
  }
2125
2772
  factories.set(name, factory);
2126
2773
  },
2127
- resolve(name, config, env, pricing) {
2774
+ resolve(name, config, env, pricing, stubOrigin) {
2128
2775
  const factory = factories.get(name);
2129
2776
  if (factory === void 0) {
2130
- const known = [...factories.keys()].join(", ") || "(none)";
2131
- 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}.`);
2132
2779
  }
2133
- return factory(config, env, pricing);
2780
+ return factory(config, env, pricing, stubOrigin);
2134
2781
  },
2135
2782
  has(name) {
2136
2783
  return factories.has(name);
@@ -2144,8 +2791,8 @@ function createDefaultRegistry() {
2144
2791
  registry.register("openrouter", makeOpenRouterProvider);
2145
2792
  return registry;
2146
2793
  }
2147
- function getProvider(config, env, pricing) {
2148
- 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);
2149
2796
  }
2150
2797
 
2151
2798
  // src/providers/estimate.ts
@@ -2485,7 +3132,7 @@ init_esm_shims();
2485
3132
 
2486
3133
  // src/orchestrator/run.ts
2487
3134
  init_esm_shims();
2488
- import * as fs3 from "fs";
3135
+ import * as fs4 from "fs";
2489
3136
  import * as path4 from "path";
2490
3137
 
2491
3138
  // src/assertions/json-extract.ts
@@ -2521,23 +3168,23 @@ function* balancedRuns(s) {
2521
3168
  while (i < s.length) {
2522
3169
  const rel = s.slice(i).search(/[{[]/);
2523
3170
  if (rel === -1) return;
2524
- const start = i + rel;
2525
- const run = balancedFrom(s, start);
3171
+ const start2 = i + rel;
3172
+ const run = balancedFrom(s, start2);
2526
3173
  if (run === null) {
2527
- i = start + 1;
3174
+ i = start2 + 1;
2528
3175
  } else {
2529
3176
  yield run;
2530
- i = start + run.length;
3177
+ i = start2 + run.length;
2531
3178
  }
2532
3179
  }
2533
3180
  }
2534
- function balancedFrom(s, start) {
2535
- const open2 = s[start];
3181
+ function balancedFrom(s, start2) {
3182
+ const open2 = s[start2];
2536
3183
  const close = open2 === "{" ? "}" : "]";
2537
3184
  let depth = 0;
2538
3185
  let inString = false;
2539
3186
  let escaped = false;
2540
- for (let i = start; i < s.length; i++) {
3187
+ for (let i = start2; i < s.length; i++) {
2541
3188
  const ch = s[i];
2542
3189
  if (inString) {
2543
3190
  if (escaped) escaped = false;
@@ -2551,7 +3198,7 @@ function balancedFrom(s, start) {
2551
3198
  depth++;
2552
3199
  } else if (ch === close) {
2553
3200
  depth--;
2554
- if (depth === 0) return s.slice(start, i + 1);
3201
+ if (depth === 0) return s.slice(start2, i + 1);
2555
3202
  }
2556
3203
  }
2557
3204
  return null;
@@ -2680,6 +3327,93 @@ var jsonSchema = {
2680
3327
  }
2681
3328
  };
2682
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
+
2683
3417
  // src/assertions/semantic-similarity.ts
2684
3418
  init_esm_shims();
2685
3419
  var DEFAULT_THRESHOLD = 0.8;
@@ -3090,9 +3824,9 @@ var firstTool = check((ctx) => {
3090
3824
  const { tool } = ctx.params;
3091
3825
  const t = transcriptOf("first-tool", ctx);
3092
3826
  checkNames("first-tool", t, [tool]);
3093
- const first = callsOf(t)[0];
3094
- if (first?.call.name === tool) return pass;
3095
- 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);
3096
3830
  return fail(
3097
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`
3098
3832
  );
@@ -3283,8 +4017,8 @@ function createAssertionRegistry() {
3283
4017
  resolve(type) {
3284
4018
  const impl = impls.get(type);
3285
4019
  if (impl === void 0) {
3286
- const known = [...impls.keys()].join(", ") || "(none)";
3287
- 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}.`);
3288
4022
  }
3289
4023
  return impl;
3290
4024
  },
@@ -3303,6 +4037,7 @@ function createDefaultRegistry2() {
3303
4037
  registry.register("contains-any", containsAny);
3304
4038
  registry.register("contains-all", containsAll);
3305
4039
  registry.register("json-schema", jsonSchema);
4040
+ registry.register("json-verify", jsonVerify);
3306
4041
  registry.register("semantic-similarity", semanticSimilarity);
3307
4042
  registry.register("llm-judge", llmJudge);
3308
4043
  registry.register("faithfulness", faithfulness);
@@ -3338,6 +4073,7 @@ var ASSERTION_CLASSES = {
3338
4073
  "contains-any": "deterministic",
3339
4074
  "contains-all": "deterministic",
3340
4075
  "json-schema": "deterministic",
4076
+ "json-verify": "deterministic",
3341
4077
  // A score against the author's threshold. They decide the row as they always have.
3342
4078
  "semantic-similarity": "measure",
3343
4079
  "llm-judge": "measure",
@@ -3461,6 +4197,13 @@ function rowStatus(row) {
3461
4197
  if (row.error !== void 0) return "errored";
3462
4198
  return row.assertions.every((a) => a.passed) ? "passed" : "failed";
3463
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
+ }
3464
4207
 
3465
4208
  // src/orchestrator/agent.ts
3466
4209
  init_esm_shims();
@@ -3502,7 +4245,7 @@ var CAMEL = /[a-z0-9](?:Id|Ids|Uuid|Key|Slug|Number|Ref|Identifier)$/;
3502
4245
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3503
4246
  var isIdKey = (key) => WHOLE.test(key) || SNAKE.test(key) || CAMEL.test(key);
3504
4247
  var isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3505
- 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);
3506
4249
  var EMAIL = /@/;
3507
4250
  function segment(key) {
3508
4251
  const plain = /^[A-Za-z_][\w-]*$/.test(key) && key.length <= 40 && !UUID.test(key) && !EMAIL.test(key);
@@ -3517,7 +4260,7 @@ function noteValue(out, v, at) {
3517
4260
  where.add(at);
3518
4261
  out.values.set(h, where);
3519
4262
  }
3520
- function walk(value, path12, depth, out) {
4263
+ function walk2(value, path12, depth, out) {
3521
4264
  if (depth > SCAN_DEPTH) return;
3522
4265
  if (typeof value === "string" && UUID.test(value)) {
3523
4266
  const at = cap(path12 === "" ? "(root)" : path12);
@@ -3525,17 +4268,17 @@ function walk(value, path12, depth, out) {
3525
4268
  noteValue(out, value, at);
3526
4269
  }
3527
4270
  if (Array.isArray(value)) {
3528
- 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);
3529
4272
  return;
3530
4273
  }
3531
4274
  if (!isRecord3(value)) return;
3532
4275
  for (const [key, v] of Object.entries(value)) {
3533
4276
  const at = cap(path12 === "" ? segment(key) : `${path12}.${segment(key)}`);
3534
- 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))) {
3535
4278
  out.paths.add(at);
3536
4279
  for (const x of Array.isArray(v) ? v : [v]) noteValue(out, x, at);
3537
4280
  }
3538
- walk(v, at, depth + 1, out);
4281
+ walk2(v, at, depth + 1, out);
3539
4282
  }
3540
4283
  }
3541
4284
  function scanIds(result) {
@@ -3544,13 +4287,13 @@ function scanIds(result) {
3544
4287
  if (isRecord3(result)) {
3545
4288
  if (result.structuredContent !== void 0) {
3546
4289
  readable = true;
3547
- walk(result.structuredContent, "", 0, found);
4290
+ walk2(result.structuredContent, "", 0, found);
3548
4291
  }
3549
4292
  if (Array.isArray(result.content))
3550
4293
  for (const block of result.content) {
3551
4294
  if (!isRecord3(block) || block.type !== "text" || typeof block.text !== "string") continue;
3552
4295
  try {
3553
- walk(JSON.parse(block.text), "", 0, found);
4296
+ walk2(JSON.parse(block.text), "", 0, found);
3554
4297
  readable = true;
3555
4298
  } catch {
3556
4299
  }
@@ -3593,7 +4336,7 @@ function strip(value, depth, st) {
3593
4336
  for (const [key, v] of Object.entries(value)) {
3594
4337
  let name = redactUuids(key);
3595
4338
  for (let n = 2; name !== key && Object.hasOwn(out, name); n++) name = `${ID_MARK}#${n}`;
3596
- 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);
3597
4340
  }
3598
4341
  return out;
3599
4342
  }
@@ -3831,8 +4574,8 @@ async function runAgentRow(p) {
3831
4574
  );
3832
4575
  for (const t of listed) {
3833
4576
  const isOffered = offered.includes(t);
3834
- const known = transcript.tools.find((k) => k.name === t.name);
3835
- 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;
3836
4579
  else
3837
4580
  transcript.tools.push({
3838
4581
  name: t.name,
@@ -4077,6 +4820,200 @@ async function runAgentRow(p) {
4077
4820
  };
4078
4821
  }
4079
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
+
4080
5017
  // src/orchestrator/run.ts
4081
5018
  var DEFAULT_MAX_TOKENS3 = 1024;
4082
5019
  var PLUNE_VERSION = "0.1.0";
@@ -4090,7 +5027,7 @@ var RunConfigError = class extends Error {
4090
5027
  var CACHE_MISS_CODE = "CACHE_MISS";
4091
5028
  function answerParses(output, assertions) {
4092
5029
  return assertions.every(
4093
- (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
4094
5031
  );
4095
5032
  }
4096
5033
  function resolvePrompt(template, vars) {
@@ -4126,9 +5063,9 @@ async function assess(p, output, input, transcript) {
4126
5063
  const advice = [];
4127
5064
  let assertionError;
4128
5065
  for (const assertion of p.assertions) {
4129
- const own2 = assertion.type === "llm-judge" ? assertion.provider : void 0;
4130
- const jev = own2?.type === "jev" ? own2 : void 0;
4131
- 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 };
4132
5069
  let judgedBy;
4133
5070
  const judge = () => {
4134
5071
  if (jev !== void 0) {
@@ -4146,8 +5083,8 @@ async function assess(p, output, input, transcript) {
4146
5083
  }
4147
5084
  };
4148
5085
  }
4149
- let provider = p.provider;
4150
- if (own2 !== void 0) {
5086
+ let provider = p.judgeProvider ?? p.provider;
5087
+ if (own3 !== void 0) {
4151
5088
  if (p.resolveJudge === void 0)
4152
5089
  throw new Error("this run cannot build the judge named by the provider of an llm-judge check");
4153
5090
  provider = p.resolveJudge(judgeCfg);
@@ -4399,13 +5336,53 @@ function resolveTemplate(ev, baseDir) {
4399
5336
  if (ev.prompt !== void 0) return ev.prompt;
4400
5337
  if (ev.prompt_file !== void 0) {
4401
5338
  try {
4402
- return fs3.readFileSync(path4.resolve(baseDir, ev.prompt_file), "utf8");
5339
+ return fs4.readFileSync(path4.resolve(baseDir, ev.prompt_file), "utf8");
4403
5340
  } catch {
4404
5341
  throw new RunConfigError(`Eval "${ev.id}": prompt_file not found: ${ev.prompt_file}`);
4405
5342
  }
4406
5343
  }
4407
5344
  throw new RunConfigError(`Eval "${ev.id}" has neither prompt nor prompt_file`);
4408
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
+ }
4409
5386
  function summarize(evals, durationMs) {
4410
5387
  const summary = {
4411
5388
  total: 0,
@@ -4424,6 +5401,7 @@ function summarize(evals, durationMs) {
4424
5401
  errored: 0,
4425
5402
  saved: { input_tokens: 0, output_tokens: 0, cost_usd: 0 }
4426
5403
  };
5404
+ let stubbed = 0;
4427
5405
  for (const ev of evals) {
4428
5406
  for (const row of ev.rows) {
4429
5407
  summary.total += 1;
@@ -4432,13 +5410,14 @@ function summarize(evals, durationMs) {
4432
5410
  cache.saved.input_tokens += row.cache_saved?.input_tokens ?? 0;
4433
5411
  cache.saved.output_tokens += row.cache_saved?.output_tokens ?? 0;
4434
5412
  cache.saved.cost_usd += row.cache_saved?.cost_usd ?? 0;
4435
- if (row.cached) cache.from_cache += 1;
5413
+ if (row.stubbed === true) stubbed += 1;
5414
+ else if (row.cached) cache.from_cache += 1;
4436
5415
  else if (row.error?.code === CACHE_MISS_CODE) cache.missed += 1;
4437
5416
  else if (row.output !== null) cache.from_model += 1;
4438
5417
  else if (row.error !== void 0) cache.errored += 1;
4439
5418
  }
4440
5419
  }
4441
- return { ...summary, cache };
5420
+ return { ...summary, cache: stubbed > 0 ? { ...cache, stubbed } : cache };
4442
5421
  }
4443
5422
  function agenticProvider(ev, providerConfig, deps, cacheStrict) {
4444
5423
  if (cacheStrict)
@@ -4474,22 +5453,28 @@ async function runOrchestration(config, options, deps) {
4474
5453
  const models = config.providers ?? [config.provider];
4475
5454
  const prepared = selectEvals(config.evals, options.only).map((ev) => {
4476
5455
  const template = resolveTemplate(ev, deps.baseDir);
5456
+ const stubs = resolveStubs(ev, deps, cacheStrict);
4477
5457
  const rows = deps.loadDataset(ev.dataset, deps.baseDir);
4478
5458
  for (const row of rows) {
4479
5459
  resolvePrompt(template, row.vars);
4480
5460
  }
4481
5461
  const cells = models.map((model) => {
4482
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
+ );
4483
5468
  const agentic = ev.mcp === void 0 || dryRun ? void 0 : agenticProvider(ev, providerConfig, deps, cacheStrict);
4484
5469
  return { providerConfig, agentic };
4485
5470
  });
4486
- return { ev, template, rows, cells };
5471
+ return { ev, template, rows, cells, stubs };
4487
5472
  });
4488
5473
  const judges = /* @__PURE__ */ new Map();
4489
5474
  const resolveJudge = (cfg) => {
4490
5475
  const key = canonicalJson(cfg);
4491
- const known = judges.get(key);
4492
- if (known !== void 0) return known;
5476
+ const known2 = judges.get(key);
5477
+ if (known2 !== void 0) return known2;
4493
5478
  const made = deps.resolveProvider(cfg);
4494
5479
  judges.set(key, made);
4495
5480
  return made;
@@ -4499,14 +5484,15 @@ async function runOrchestration(config, options, deps) {
4499
5484
  throw new RunConfigError(
4500
5485
  "--tool-description needs an eval with mcp in this run: no tool is offered otherwise"
4501
5486
  );
4502
- cellLoop: for (const { ev, template, rows, cells } of prepared) {
5487
+ cellLoop: for (const { ev, template, rows, cells, stubs } of prepared) {
4503
5488
  for (const { providerConfig, agentic } of cells) {
4504
5489
  const provider = agentic ?? deps.resolveProvider(providerConfig);
5490
+ const seen = stubs === void 0 || dryRun ? void 0 : nothingSeen(stubs);
4505
5491
  const limit2 = options.concurrency ?? providerConfig.concurrency ?? (ev.mcp !== void 0 ? 1 : 4);
4506
5492
  const runs = options.runs ?? ev.runs ?? config.runs ?? 1;
4507
5493
  const passThreshold = ev.pass_threshold ?? config.pass_threshold ?? 1;
4508
5494
  const assertions = [...config.defaults?.assertions ?? [], ...ev.assertions];
4509
- const rowResults = await mapLimit(rows, limit2, (row) => {
5495
+ const rowResults = await mapLimit(rows, limit2, (row, rowIndex) => {
4510
5496
  const params = {
4511
5497
  template,
4512
5498
  assertions,
@@ -4524,6 +5510,25 @@ async function runOrchestration(config, options, deps) {
4524
5510
  cacheStrict,
4525
5511
  ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {}
4526
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
+ }
4527
5532
  if (ev.mcp === void 0) return runRepeats(params, runs, passThreshold);
4528
5533
  const agentParams = {
4529
5534
  ...params,
@@ -4550,7 +5555,8 @@ async function runOrchestration(config, options, deps) {
4550
5555
  rows: rowResults,
4551
5556
  passed,
4552
5557
  measured,
4553
- ...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 } : {}
4554
5560
  });
4555
5561
  if (options.bail === true && !dryRun && !passed) break cellLoop;
4556
5562
  }
@@ -4575,7 +5581,7 @@ init_esm_shims();
4575
5581
 
4576
5582
  // src/orchestrator/dataset.ts
4577
5583
  init_esm_shims();
4578
- import * as fs4 from "fs";
5584
+ import * as fs5 from "fs";
4579
5585
  import * as path5 from "path";
4580
5586
  function loadDataset(ref5, baseDir) {
4581
5587
  if (typeof ref5 !== "string") {
@@ -4584,7 +5590,7 @@ function loadDataset(ref5, baseDir) {
4584
5590
  const file = path5.resolve(baseDir, ref5);
4585
5591
  let content;
4586
5592
  try {
4587
- content = fs4.readFileSync(file, "utf8");
5593
+ content = fs5.readFileSync(file, "utf8");
4588
5594
  } catch (err) {
4589
5595
  throw new RunConfigError(
4590
5596
  err.code === "ENOENT" ? `${ref5}: dataset file not found (looked for ${file})` : `${ref5}: cannot read the dataset file (${err.message})`
@@ -4599,9 +5605,9 @@ function loadDataset(ref5, baseDir) {
4599
5605
  } catch (err) {
4600
5606
  throw new RunConfigError(`${ref5}:${i + 1}: not valid JSON (${err.message})`);
4601
5607
  }
4602
- const vars = isObject2(row) ? row["vars"] : void 0;
4603
- if (!isObject2(vars)) {
4604
- 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"';
4605
5611
  throw new RunConfigError(
4606
5612
  `${ref5}:${i + 1}: a dataset row must be { "vars": { ... } }; ${why}`
4607
5613
  );
@@ -4610,7 +5616,7 @@ function loadDataset(ref5, baseDir) {
4610
5616
  });
4611
5617
  return rows;
4612
5618
  }
4613
- function isObject2(value) {
5619
+ function isObject3(value) {
4614
5620
  return typeof value === "object" && value !== null && !Array.isArray(value);
4615
5621
  }
4616
5622
  function typeName(value) {
@@ -4639,8 +5645,8 @@ Criterion:
4639
5645
  ${q.criteria}`;
4640
5646
  }
4641
5647
  function jevBaseUrl(env) {
4642
- const own2 = env[JEV_BASE_URL_ENV];
4643
- const [name, value] = own2 !== void 0 && own2 !== "" ? [JEV_BASE_URL_ENV, own2] : ["TYPESAFE_BASE_URL", env["TYPESAFE_BASE_URL"]];
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"]];
4644
5650
  if (value === void 0 || value === "") return JEV_BASE_URL;
4645
5651
  let url;
4646
5652
  try {
@@ -4724,6 +5730,418 @@ function warnJevExperimental(write = (l) => process.stderr.write(l)) {
4724
5730
  );
4725
5731
  }
4726
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
+ const site = req.headers["sec-fetch-site"];
5818
+ return !hosts.includes(host) || origin !== void 0 && !hosts.some((h) => origin.toLowerCase() === `http://${h}`) || // Fail closed: of the four values a browser sends, `cross-site` and `same-site` are another origin.
5819
+ site !== void 0 && !["same-origin", "none"].includes(String(site).toLowerCase());
5820
+ }
5821
+ 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 browser marks as sent from another origin";
5822
+ function maskedHeaders(headers) {
5823
+ const out = {};
5824
+ for (const [name, value] of Object.entries(headers)) {
5825
+ if (value === void 0) continue;
5826
+ out[name] = SECRET_NAME.test(name) ? MASK : Array.isArray(value) ? value.join(", ") : value;
5827
+ }
5828
+ return out;
5829
+ }
5830
+ function maskedQuery(params) {
5831
+ return [...params].map(
5832
+ ([k, v]) => `${encodeURIComponent(k)}=${SECRET_NAME.test(k) ? MASK : encodeURIComponent(v)}`
5833
+ ).join("&");
5834
+ }
5835
+ function renderBody(response) {
5836
+ if (response.sse !== void 0) {
5837
+ const events = response.sse.map((chunk2) => {
5838
+ const { event, data } = typeof chunk2 === "string" ? { event: void 0, data: chunk2 } : chunk2;
5839
+ const line = typeof data === "string" ? data : JSON.stringify(data);
5840
+ return `${event === void 0 ? "" : `event: ${event}
5841
+ `}data: ${line}
5842
+
5843
+ `;
5844
+ });
5845
+ return { type: "text/event-stream", body: Buffer.from(events.join("")) };
5846
+ }
5847
+ if (response.text !== void 0)
5848
+ return { type: "text/plain; charset=utf-8", body: Buffer.from(response.text) };
5849
+ if (response.json !== void 0)
5850
+ return { type: "application/json", body: Buffer.from(JSON.stringify(response.json)) };
5851
+ return { body: Buffer.alloc(0) };
5852
+ }
5853
+ function responseHeaders(response, type, length) {
5854
+ const headers = {};
5855
+ if (type !== void 0) headers["content-type"] = type;
5856
+ if (response.sse === void 0) headers["content-length"] = length;
5857
+ else headers["cache-control"] = "no-cache";
5858
+ for (const [name, value] of Object.entries(response.headers)) headers[name.toLowerCase()] = value;
5859
+ return headers;
5860
+ }
5861
+ function sendJson(res, status, body, headers = {}) {
5862
+ const text = JSON.stringify(body);
5863
+ res.writeHead(status, {
5864
+ "content-type": "application/json",
5865
+ "content-length": Buffer.byteLength(text),
5866
+ ...headers
5867
+ });
5868
+ res.end(text);
5869
+ }
5870
+ var providerError = (type, code, message) => ({
5871
+ type: "error",
5872
+ error: { type, code, message }
5873
+ });
5874
+ function writeSlowly(res, body, bytesPerSec, timers) {
5875
+ const startedAt = timers.now();
5876
+ const step = Math.max(1, Math.round(bytesPerSec * SLOW_STREAM_STEP_MS / 1e3));
5877
+ let sent = 0;
5878
+ let handle;
5879
+ const tick = () => {
5880
+ const due = Math.min(
5881
+ body.length,
5882
+ Math.floor((timers.now() - startedAt) * bytesPerSec / 1e3)
5883
+ );
5884
+ if (due > sent) {
5885
+ res.write(body.subarray(sent, due));
5886
+ sent = due;
5887
+ }
5888
+ if (sent >= body.length) {
5889
+ res.end();
5890
+ return;
5891
+ }
5892
+ const nextAt = startedAt + Math.min(body.length, sent + step) * 1e3 / bytesPerSec;
5893
+ handle = timers.setTimeout(tick, Math.max(1, Math.ceil(nextAt - timers.now())));
5894
+ };
5895
+ tick();
5896
+ return () => timers.clearTimeout(handle);
5897
+ }
5898
+ async function start(options = {}) {
5899
+ const host = options.host ?? "127.0.0.1";
5900
+ const journalBodyCap = options.journalBodyCap ?? 64 * 1024;
5901
+ const timers = options.timers ?? REAL_TIMERS;
5902
+ const scopes = /* @__PURE__ */ new Map();
5903
+ const unrouted = [];
5904
+ let unroutedDropped = 0;
5905
+ let closing;
5906
+ const record = (journal, entry) => {
5907
+ journal.push(entry);
5908
+ if (journal.length <= JOURNAL_MAX_ENTRIES) return 0;
5909
+ journal.shift();
5910
+ return 1;
5911
+ };
5912
+ function answer(req, res, body) {
5913
+ const target = req.url ?? "";
5914
+ const queryAt = target.indexOf("?");
5915
+ const rawPath = queryAt === -1 ? target : target.slice(0, queryAt);
5916
+ const segments = rawPath.split("/");
5917
+ const badTarget = segments[0] !== "" || segments.length < 2 || segments[1] === "" && segments.length > 2 || segments.some((segment2) => DOT_SEGMENT.test(segment2));
5918
+ const name = badTarget ? "" : segments[1];
5919
+ const method = req.method ?? "GET";
5920
+ const path12 = badTarget ? rawPath : rawPath.slice(name.length + 1) || "/";
5921
+ const entry = {
5922
+ scope: name,
5923
+ method,
5924
+ path: path12,
5925
+ query: maskedQuery(new URLSearchParams(queryAt === -1 ? "" : target.slice(queryAt + 1))),
5926
+ headers: maskedHeaders(req.headers),
5927
+ body: body.subarray(0, journalBodyCap).toString("utf8"),
5928
+ bodyTruncated: body.length > journalBodyCap,
5929
+ matched: false
5930
+ };
5931
+ const refuse = (status, type, message, open2) => sendJson(res, status, {
5932
+ error: { type, message, method, ...open2 === void 0 ? {} : { scope: open2 } }
5933
+ });
5934
+ const scope = badTarget ? void 0 : scopes.get(name);
5935
+ if (scope === void 0) {
5936
+ unroutedDropped += record(unrouted, entry);
5937
+ if (badTarget)
5938
+ refuse(
5939
+ 400,
5940
+ "mock_bad_target",
5941
+ 'Bad request target: it starts with "/<scope>" and holds no "." or ".." segment'
5942
+ );
5943
+ else
5944
+ refuse(
5945
+ 404,
5946
+ "mock_no_stub",
5947
+ `No open scope for this ${method} request: the first path segment names the scope`
5948
+ );
5949
+ return;
5950
+ }
5951
+ scope.dropped += record(scope.journal, entry);
5952
+ let json;
5953
+ let parsed2 = false;
5954
+ const live = scope.stubs.find(({ stub, matches, calls }) => {
5955
+ if (stub.times !== "always" && calls >= (stub.times === "once" ? 1 : stub.times))
5956
+ return false;
5957
+ if (stub.method !== method || !matches(path12)) return false;
5958
+ const exact = stub.match === "exact";
5959
+ if (stub.body === void 0 && !exact) return true;
5960
+ if (!parsed2) {
5961
+ parsed2 = true;
5962
+ try {
5963
+ json = JSON.parse(body.toString("utf8"));
5964
+ } catch {
5965
+ json = void 0;
5966
+ }
5967
+ }
5968
+ if (!exact) return matchesSubset(stub.body, json);
5969
+ return stub.body === void 0 ? json === void 0 : matchesExact(stub.body, json);
5970
+ });
5971
+ if (live === void 0) {
5972
+ refuse(
5973
+ 404,
5974
+ "mock_no_stub",
5975
+ `No stub matches this ${method} request in scope "${name}": compare its path and body in the journal of the scope with the stubs`,
5976
+ name
5977
+ );
5978
+ return;
5979
+ }
5980
+ entry.matched = true;
5981
+ live.calls += 1;
5982
+ const response = live.stub.response ?? { status: 200, headers: {} };
5983
+ const rendered = renderBody(response);
5984
+ const head = (length) => {
5985
+ res.writeHead(response.status, responseHeaders(response, rendered.type, length));
5986
+ };
5987
+ const { failure } = live.stub;
5988
+ if (failure === void 0 || failure.first !== void 0 && live.calls > failure.first) {
5989
+ head(rendered.body.length);
5990
+ res.end(rendered.body);
5991
+ return;
5992
+ }
5993
+ const hold = (stop = () => void 0) => {
5994
+ const abort = () => {
5995
+ stop();
5996
+ res.destroy();
5997
+ };
5998
+ scope.held.add(abort);
5999
+ res.on("close", () => {
6000
+ stop();
6001
+ scope.held.delete(abort);
6002
+ });
6003
+ };
6004
+ switch (failure.type) {
6005
+ case "timeout":
6006
+ hold();
6007
+ return;
6008
+ case "reset":
6009
+ req.socket.resetAndDestroy();
6010
+ return;
6011
+ case "http_429":
6012
+ sendJson(
6013
+ res,
6014
+ 429,
6015
+ providerError("rate_limit_error", "rate_limit_exceeded", "Rate limit exceeded (stub)"),
6016
+ { "retry-after": String(failure.retry_after_seconds) }
6017
+ );
6018
+ return;
6019
+ case "http_500":
6020
+ sendJson(
6021
+ res,
6022
+ 500,
6023
+ providerError("api_error", "internal_error", "Internal server error (stub)")
6024
+ );
6025
+ return;
6026
+ case "slow_stream":
6027
+ head(rendered.body.length);
6028
+ res.flushHeaders();
6029
+ hold(writeSlowly(res, rendered.body, failure.bytes_per_sec, timers));
6030
+ return;
6031
+ case "truncated_json": {
6032
+ const cut = rendered.body.subarray(0, Math.floor(rendered.body.length / 2));
6033
+ if (failure.content_length === "cut") {
6034
+ head(cut.length);
6035
+ res.end(cut);
6036
+ } else {
6037
+ head(rendered.body.length);
6038
+ res.write(cut, () => res.destroy());
6039
+ }
6040
+ return;
6041
+ }
6042
+ }
6043
+ }
6044
+ let port = 0;
6045
+ const server = http.createServer((req, res) => {
6046
+ if (notLocal(req, port, host)) {
6047
+ req.resume();
6048
+ sendJson(res, 403, { error: { type: "mock_not_local", message: NOT_LOCAL_MESSAGE } });
6049
+ return;
6050
+ }
6051
+ const chunks = [];
6052
+ let size = 0;
6053
+ req.on("error", () => void 0);
6054
+ req.on("data", (chunk2) => {
6055
+ size += chunk2.length;
6056
+ if (size <= MAX_BODY_BYTES) chunks.push(chunk2);
6057
+ else chunks.length = 0;
6058
+ });
6059
+ req.on("end", () => {
6060
+ if (size > MAX_BODY_BYTES) {
6061
+ sendJson(res, 413, {
6062
+ error: { type: "mock_body_too_large", message: "Request body over 16 MiB" }
6063
+ });
6064
+ return;
6065
+ }
6066
+ try {
6067
+ answer(req, res, Buffer.concat(chunks));
6068
+ } catch {
6069
+ if (res.headersSent) res.destroy();
6070
+ else
6071
+ sendJson(res, 500, {
6072
+ error: { type: "mock_internal", message: "The stub server failed on this request" }
6073
+ });
6074
+ }
6075
+ });
6076
+ });
6077
+ server.maxConnections = MAX_CONNECTIONS;
6078
+ await new Promise((resolve9, reject) => {
6079
+ server.once("error", reject);
6080
+ server.listen(options.port ?? 0, host, () => {
6081
+ server.off("error", reject);
6082
+ resolve9();
6083
+ });
6084
+ });
6085
+ ({ port } = server.address());
6086
+ const url = `http://${host.includes(":") ? `[${host}]` : host}:${port}`;
6087
+ return {
6088
+ url,
6089
+ port,
6090
+ unrouted,
6091
+ get unroutedDropped() {
6092
+ return unroutedDropped;
6093
+ },
6094
+ scope(name, stubs = []) {
6095
+ if (closing !== void 0) throw new Error("The server is closed: it takes no new scope");
6096
+ if (!SCOPE_NAME.test(name))
6097
+ throw new Error(
6098
+ `Bad scope name "${name}": letters, digits, ".", "_" and "-" only, and not "." or ".."`
6099
+ );
6100
+ if (scopes.has(name)) throw new Error(`Scope "${name}" is already open`);
6101
+ const state = { stubs: [], journal: [], dropped: 0, held: /* @__PURE__ */ new Set() };
6102
+ scopes.set(name, state);
6103
+ const scope = {
6104
+ name,
6105
+ url: `${url}/${name}`,
6106
+ journal: state.journal,
6107
+ get dropped() {
6108
+ return state.dropped;
6109
+ },
6110
+ add(...inputs) {
6111
+ for (const input of inputs) {
6112
+ const result = stubSchema.safeParse(input);
6113
+ if (!result.success)
6114
+ throw new Error(`Invalid stub: ${formatIssues(result.error).join("; ")}`);
6115
+ state.stubs.push({
6116
+ stub: result.data,
6117
+ matches: result.data.match === "exact" ? (path12) => maskedTextMatches(result.data.path, path12) : pathMatcher(result.data.path),
6118
+ calls: 0
6119
+ });
6120
+ }
6121
+ },
6122
+ close() {
6123
+ if (scopes.get(name) === state) scopes.delete(name);
6124
+ const unused = state.stubs.filter((s) => s.calls === 0).map((s) => s.stub);
6125
+ state.stubs = [];
6126
+ for (const abort of [...state.held]) abort();
6127
+ return unused;
6128
+ }
6129
+ };
6130
+ scope.add(...stubs);
6131
+ return scope;
6132
+ },
6133
+ close() {
6134
+ closing ??= new Promise((resolve9) => {
6135
+ for (const state of scopes.values()) for (const abort of [...state.held]) abort();
6136
+ scopes.clear();
6137
+ server.close(() => resolve9());
6138
+ server.closeAllConnections();
6139
+ });
6140
+ return closing;
6141
+ }
6142
+ };
6143
+ }
6144
+
4727
6145
  // src/cli/commands/run.ts
4728
6146
  var NOOP_CACHE = { get: () => void 0, set: () => {
4729
6147
  }, delete: () => {
@@ -4750,12 +6168,12 @@ function parseToolDescriptions(values) {
4750
6168
  const file = text.slice(1);
4751
6169
  try {
4752
6170
  const full = path6.resolve(file);
4753
- const stat2 = fs5.statSync(full);
6171
+ const stat2 = fs6.statSync(full);
4754
6172
  if (!stat2.isFile())
4755
6173
  throw new RunConfigError(`--tool-description ${tool}: ${file} is not a file`);
4756
6174
  if (stat2.size > MAX_DESCRIPTION_BYTES)
4757
6175
  throw new RunConfigError(`--tool-description ${tool}: ${file} is over 64 KB`);
4758
- text = fs5.readFileSync(full, "utf8").replace(/\r?\n$/, "");
6176
+ text = fs6.readFileSync(full, "utf8").replace(/\r?\n$/, "");
4759
6177
  } catch (err) {
4760
6178
  if (err instanceof RunConfigError) throw err;
4761
6179
  throw new RunConfigError(`--tool-description ${tool}: cannot read ${file}`);
@@ -4773,7 +6191,7 @@ function mockScript(env) {
4773
6191
  if (file === void 0 || file === "") return void 0;
4774
6192
  let text;
4775
6193
  try {
4776
- text = fs5.readFileSync(path6.resolve(file), "utf8");
6194
+ text = fs6.readFileSync(path6.resolve(file), "utf8");
4777
6195
  } catch {
4778
6196
  throw new RunConfigError(`PLUNE_MOCK_SCRIPT: cannot read ${file}`);
4779
6197
  }
@@ -4807,11 +6225,11 @@ function resolveProviderFor(config, dryRun) {
4807
6225
  return () => makeMockProvider(script);
4808
6226
  }
4809
6227
  if (dryRun) return (cfg) => makeEstimateProvider(cfg, config.pricing);
4810
- return (cfg) => getProvider(cfg, process.env, config.pricing);
6228
+ return (cfg, stubOrigin) => getProvider(cfg, process.env, config.pricing, stubOrigin);
4811
6229
  }
4812
6230
  function buildRealDeps(config, baseDir, dryRun) {
4813
6231
  const dir = path6.join(baseDir, ".plune");
4814
- fs5.mkdirSync(dir, { recursive: true });
6232
+ fs6.mkdirSync(dir, { recursive: true });
4815
6233
  return {
4816
6234
  resolveProvider: resolveProviderFor(config, dryRun),
4817
6235
  embedder: getDefaultEmbedder(),
@@ -4837,8 +6255,21 @@ function buildRealDeps(config, baseDir, dryRun) {
4837
6255
  }
4838
6256
  function persist(result, baseDir) {
4839
6257
  const dir = path6.join(baseDir, ".plune");
4840
- fs5.mkdirSync(dir, { recursive: true });
4841
- fs5.writeFileSync(path6.join(dir, "last-run.json"), JSON.stringify(result, null, 2));
6258
+ fs6.mkdirSync(dir, { recursive: true });
6259
+ fs6.writeFileSync(path6.join(dir, "last-run.json"), JSON.stringify(result, null, 2));
6260
+ }
6261
+ function stubWarnings(config, result) {
6262
+ return result.evals.flatMap((ev) => {
6263
+ if (ev.stubs === void 0) return [];
6264
+ const { never_called: never, unmatched } = ev.stubs;
6265
+ const file = config.evals.find((e) => e.id === baseEvalId(ev))?.stubs ?? "its stub file";
6266
+ return [
6267
+ ...never.length > 0 ? [`${never.map((i) => `stubs.${i}`).join(", ")} of ${file} ${never.length === 1 ? "was" : "were"} never called`] : [],
6268
+ ...unmatched.length > 0 ? [
6269
+ `${unmatched.length} request${unmatched.length === 1 ? "" : "s"} matched no stub: ` + unmatched.map((u) => `${u.method} in ${u.scope}`).join(", ")
6270
+ ] : []
6271
+ ].map((line) => `eval "${ev.id}": ${line}`);
6272
+ });
4842
6273
  }
4843
6274
  function jevAddressCheck(config, env) {
4844
6275
  const checks = [...config.defaults?.assertions ?? [], ...config.evals.flatMap((ev) => ev.assertions)];
@@ -4860,7 +6291,9 @@ async function handleRun(options, depsFactory) {
4860
6291
  `);
4861
6292
  const toolDescriptions = options.toolDescription !== void 0 && options.toolDescription.length > 0 ? parseToolDescriptions(options.toolDescription) : void 0;
4862
6293
  const factory = depsFactory ?? ((c, d) => buildRealDeps(c, d, options.dryRun));
4863
- const deps = factory(config, baseDir);
6294
+ const given = factory(config, baseDir);
6295
+ let stubServer;
6296
+ const deps = depsFactory === void 0 && isMockMode(process.env) ? given : { ...given, stubServer: () => stubServer ??= (given.stubServer ?? start)() };
4864
6297
  try {
4865
6298
  const stale = deps.cache.staleEntries ?? 0;
4866
6299
  if (stale > 0) {
@@ -4896,6 +6329,8 @@ async function handleRun(options, depsFactory) {
4896
6329
  `
4897
6330
  );
4898
6331
  }
6332
+ for (const warning of stubWarnings(config, result)) process.stderr.write(`warning: ${warning}
6333
+ `);
4899
6334
  if (options.dryRun) {
4900
6335
  const agentic = new Set(config.evals.filter((ev) => ev.mcp !== void 0).map((ev) => ev.id));
4901
6336
  if (result.evals.some((ev) => agentic.has(ev.id)))
@@ -4907,164 +6342,173 @@ async function handleRun(options, depsFactory) {
4907
6342
  return result;
4908
6343
  } finally {
4909
6344
  deps.cache.close();
6345
+ if (stubServer !== void 0) await stubServer.then((server) => server.close(), () => void 0);
4910
6346
  }
4911
6347
  }
4912
6348
 
4913
6349
  // src/cli/commands/sync.ts
4914
6350
  init_esm_shims();
4915
6351
  import { createHash as createHash2 } from "crypto";
4916
- import * as fs6 from "fs";
6352
+ import * as fs7 from "fs";
4917
6353
  import * as path7 from "path";
4918
6354
 
4919
6355
  // src/types/run-result-schema.ts
4920
6356
  init_esm_shims();
4921
- import { z as z3 } from "zod";
6357
+ import { z as z4 } from "zod";
4922
6358
  var RUN_RESULT_SCHEMA_VERSION = 1;
4923
- var binaryVerdictSchema = z3.object({
4924
- question: z3.string().min(1),
4925
- passed: z3.boolean()
6359
+ var binaryVerdictSchema = z4.object({
6360
+ question: z4.string().min(1),
6361
+ passed: z4.boolean()
4926
6362
  });
4927
- var assertionResultRecordSchema2 = z3.object({
4928
- type: z3.string(),
4929
- passed: z3.boolean(),
4930
- score: z3.number().optional(),
4931
- reason: z3.string().optional(),
4932
- binaryVerdicts: z3.array(binaryVerdictSchema).optional(),
6363
+ var assertionResultRecordSchema2 = z4.object({
6364
+ type: z4.string(),
6365
+ passed: z4.boolean(),
6366
+ score: z4.number().optional(),
6367
+ reason: z4.string().optional(),
6368
+ binaryVerdicts: z4.array(binaryVerdictSchema).optional(),
4933
6369
  /** plune-ai/cli#373. Optional and additive — a RunResult written before it validates unchanged. */
4934
- judge_model: z3.string().optional()
6370
+ judge_model: z4.string().optional()
4935
6371
  });
4936
- var usageSchema = z3.object({
4937
- input_tokens: z3.number(),
4938
- output_tokens: z3.number(),
4939
- cost_usd: z3.number(),
6372
+ var usageSchema = z4.object({
6373
+ input_tokens: z4.number(),
6374
+ output_tokens: z4.number(),
6375
+ cost_usd: z4.number(),
4940
6376
  /** cli#151. Optional and additive — a RunResult written before it validates unchanged. */
4941
- priced: z3.boolean().optional()
6377
+ priced: z4.boolean().optional()
4942
6378
  });
4943
- var runErrorSchema = z3.object({
4944
- code: z3.string(),
4945
- message: z3.string()
6379
+ var runErrorSchema = z4.object({
6380
+ code: z4.string(),
6381
+ message: z4.string()
4946
6382
  });
4947
- var savedSchema = z3.object({
4948
- input_tokens: z3.number(),
4949
- output_tokens: z3.number(),
4950
- cost_usd: z3.number()
6383
+ var savedSchema = z4.object({
6384
+ input_tokens: z4.number(),
6385
+ output_tokens: z4.number(),
6386
+ cost_usd: z4.number()
4951
6387
  });
4952
- var rowResultSchema = z3.object({
4953
- vars: z3.record(z3.string(), z3.unknown()),
4954
- output: z3.string().nullable(),
4955
- cached: z3.boolean(),
6388
+ var rowResultSchema = z4.object({
6389
+ vars: z4.record(z4.string(), z4.unknown()),
6390
+ output: z4.string().nullable(),
6391
+ cached: z4.boolean(),
6392
+ /** A row of an eval with `stubs`. Kept by the parser so that `plune sync` can see it and refuse the upload. */
6393
+ stubbed: z4.boolean().optional(),
4956
6394
  usage: usageSchema.optional(),
4957
- latency_ms: z3.number().optional(),
6395
+ latency_ms: z4.number().optional(),
4958
6396
  error: runErrorSchema.optional(),
4959
- assertions: z3.array(assertionResultRecordSchema2),
6397
+ assertions: z4.array(assertionResultRecordSchema2),
4960
6398
  cache_saved: savedSchema.optional(),
4961
6399
  /** Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
4962
- inconclusive: z3.enum(ROW_INCONCLUSIVE).optional(),
6400
+ inconclusive: z4.enum(ROW_INCONCLUSIVE).optional(),
4963
6401
  /** Repeats (`runs` above 1). Optional and additive — a RunResult without it validates unchanged. */
4964
- attempts: z3.object({
4965
- runs: z3.number(),
4966
- pass_threshold: z3.number(),
4967
- passed: z3.number(),
4968
- failed: z3.number(),
4969
- errored: z3.number(),
4970
- results: z3.array(
4971
- z3.object({
4972
- output: z3.string().nullable(),
4973
- cached: z3.boolean(),
6402
+ attempts: z4.object({
6403
+ runs: z4.number(),
6404
+ pass_threshold: z4.number(),
6405
+ passed: z4.number(),
6406
+ failed: z4.number(),
6407
+ errored: z4.number(),
6408
+ results: z4.array(
6409
+ z4.object({
6410
+ output: z4.string().nullable(),
6411
+ cached: z4.boolean(),
4974
6412
  usage: usageSchema.optional(),
4975
- latency_ms: z3.number().optional(),
6413
+ latency_ms: z4.number().optional(),
4976
6414
  error: runErrorSchema.optional(),
4977
- assertions: z3.array(assertionResultRecordSchema2),
6415
+ assertions: z4.array(assertionResultRecordSchema2),
4978
6416
  cache_saved: savedSchema.optional()
4979
6417
  })
4980
6418
  )
4981
6419
  }).optional(),
4982
6420
  /** The tool loop of an eval with an `mcp` server. Optional and additive — a RunResult without it validates unchanged. */
4983
- agent: z3.object({
4984
- server: z3.string(),
4985
- tools: z3.array(
4986
- z3.object({
4987
- name: z3.string(),
4988
- offered: z3.boolean(),
4989
- annotations: z3.record(z3.string(), z3.unknown()).optional()
6421
+ agent: z4.object({
6422
+ server: z4.string(),
6423
+ tools: z4.array(
6424
+ z4.object({
6425
+ name: z4.string(),
6426
+ offered: z4.boolean(),
6427
+ annotations: z4.record(z4.string(), z4.unknown()).optional()
4990
6428
  })
4991
6429
  ),
4992
- steps: z3.array(
4993
- z3.object({
4994
- index: z3.number(),
4995
- text: z3.string(),
4996
- finish_reason: z3.string().optional(),
6430
+ steps: z4.array(
6431
+ z4.object({
6432
+ index: z4.number(),
6433
+ text: z4.string(),
6434
+ finish_reason: z4.string().optional(),
4997
6435
  usage: usageSchema,
4998
- calls: z3.array(
4999
- z3.object({
5000
- id: z3.string(),
5001
- name: z3.string(),
5002
- args: z3.unknown(),
5003
- executed: z3.boolean(),
5004
- is_error: z3.boolean(),
5005
- error_kind: z3.enum(["content", "protocol", "timeout", "not-offered", "bad-arguments"]).optional(),
5006
- duration_ms: z3.number().optional(),
5007
- result: z3.object({ text: z3.string(), bytes: z3.number(), truncated: z3.boolean() }).optional()
6436
+ calls: z4.array(
6437
+ z4.object({
6438
+ id: z4.string(),
6439
+ name: z4.string(),
6440
+ args: z4.unknown(),
6441
+ executed: z4.boolean(),
6442
+ is_error: z4.boolean(),
6443
+ error_kind: z4.enum(["content", "protocol", "timeout", "not-offered", "bad-arguments"]).optional(),
6444
+ duration_ms: z4.number().optional(),
6445
+ result: z4.object({ text: z4.string(), bytes: z4.number(), truncated: z4.boolean() }).optional()
5008
6446
  })
5009
6447
  ),
5010
6448
  /** Optional and additive: the step whose request first offered a changed list. */
5011
- offered_changed: z3.object({ added: z3.array(z3.string()), removed: z3.array(z3.string()) }).optional()
6449
+ offered_changed: z4.object({ added: z4.array(z4.string()), removed: z4.array(z4.string()) }).optional()
5012
6450
  })
5013
6451
  ),
5014
- stop: z3.object({
5015
- reason: z3.enum(["complete", "limit", "error"]),
5016
- limit: z3.enum(["max_steps", "max_tool_calls", "max_total_tokens", "timeout_ms", "tool_timeout_ms"]).optional()
6452
+ stop: z4.object({
6453
+ reason: z4.enum(["complete", "limit", "error"]),
6454
+ limit: z4.enum(["max_steps", "max_tool_calls", "max_total_tokens", "timeout_ms", "tool_timeout_ms"]).optional()
5017
6455
  }),
5018
- collection: z3.enum(["complete", "partial"]),
6456
+ collection: z4.enum(["complete", "partial"]),
5019
6457
  /** Heuristic findings, never a verdict. Optional and additive. */
5020
- advice: z3.array(
5021
- z3.object({
5022
- type: z3.string(),
5023
- reason: z3.string(),
5024
- tool: z3.string().optional(),
5025
- steps: z3.array(z3.number()).optional(),
5026
- count: z3.number().optional(),
5027
- paths: z3.array(z3.string()).optional()
6458
+ advice: z4.array(
6459
+ z4.object({
6460
+ type: z4.string(),
6461
+ reason: z4.string(),
6462
+ tool: z4.string().optional(),
6463
+ steps: z4.array(z4.number()).optional(),
6464
+ count: z4.number().optional(),
6465
+ paths: z4.array(z4.string()).optional()
5028
6466
  })
5029
6467
  ).optional(),
5030
- description_overrides: z3.array(z3.object({ tool: z3.string(), sha256: z3.string() })).optional()
6468
+ description_overrides: z4.array(z4.object({ tool: z4.string(), sha256: z4.string() })).optional()
5031
6469
  }).optional()
5032
6470
  });
5033
- var summarySchema = z3.object({
5034
- total: z3.number(),
5035
- passed: z3.number(),
5036
- failed: z3.number(),
5037
- errored: z3.number(),
6471
+ var summarySchema = z4.object({
6472
+ total: z4.number(),
6473
+ passed: z4.number(),
6474
+ failed: z4.number(),
6475
+ errored: z4.number(),
5038
6476
  /** Optional and additive — a RunResult written before them validates unchanged. */
5039
- blocked: z3.number().optional(),
5040
- skipped: z3.number().optional(),
5041
- cost_usd: z3.number(),
5042
- duration_ms: z3.number(),
5043
- cache: z3.object({
5044
- from_cache: z3.number(),
5045
- from_model: z3.number(),
5046
- missed: z3.number(),
5047
- errored: z3.number(),
5048
- saved: z3.object({ input_tokens: z3.number(), output_tokens: z3.number(), cost_usd: z3.number() })
6477
+ blocked: z4.number().optional(),
6478
+ skipped: z4.number().optional(),
6479
+ cost_usd: z4.number(),
6480
+ duration_ms: z4.number(),
6481
+ cache: z4.object({
6482
+ from_cache: z4.number(),
6483
+ from_model: z4.number(),
6484
+ missed: z4.number(),
6485
+ errored: z4.number(),
6486
+ stubbed: z4.number().optional(),
6487
+ saved: z4.object({ input_tokens: z4.number(), output_tokens: z4.number(), cost_usd: z4.number() })
5049
6488
  }).optional()
5050
6489
  });
5051
- var evalResultSchema = z3.object({
5052
- id: z3.string(),
5053
- tags: z3.array(z3.string()),
5054
- rows: z3.array(rowResultSchema),
5055
- passed: z3.boolean(),
6490
+ var evalResultSchema = z4.object({
6491
+ id: z4.string(),
6492
+ tags: z4.array(z4.string()),
6493
+ rows: z4.array(rowResultSchema),
6494
+ passed: z4.boolean(),
5056
6495
  /** What the eval measured, for the pass-rate gate of `plune diff`. Optional and additive. */
5057
- measured: z3.object({
5058
- runs: z3.number(),
5059
- rows: z3.number(),
5060
- rows_hash: z3.string(),
5061
- assertions_hash: z3.string(),
5062
- model: z3.string().optional()
6496
+ measured: z4.object({
6497
+ runs: z4.number(),
6498
+ rows: z4.number(),
6499
+ rows_hash: z4.string(),
6500
+ assertions_hash: z4.string(),
6501
+ model: z4.string().optional()
5063
6502
  }).optional(),
5064
6503
  /** The type and model of a cell of a multi-model run. Optional and additive. */
5065
- provider: z3.object({ type: z3.string(), model: z3.string() }).optional(),
6504
+ provider: z4.object({ type: z4.string(), model: z4.string() }).optional(),
6505
+ /** The mark of an eval answered from stubs, kept for the same reason as a row's `stubbed`. */
6506
+ stubs: z4.object({
6507
+ never_called: z4.array(z4.number()),
6508
+ unmatched: z4.array(z4.object({ scope: z4.string(), method: z4.string() }))
6509
+ }).optional(),
5066
6510
  /** The link to the eval's trace in your own observability (Langfuse, OTel). Optional and additive; `plune sync` drops one `traceUrlProblem` refuses. */
5067
- traceUrl: z3.string().optional()
6511
+ traceUrl: z4.string().optional()
5068
6512
  });
5069
6513
  var TRACE_URL_MAX = 2048;
5070
6514
  function traceUrlProblem(value) {
@@ -5082,16 +6526,16 @@ function traceUrlProblem(value) {
5082
6526
  if (parsed2.username !== "" || parsed2.password !== "") return "must carry no user name or password";
5083
6527
  return void 0;
5084
6528
  }
5085
- var runResultSchema = z3.object({
5086
- schemaVersion: z3.literal(RUN_RESULT_SCHEMA_VERSION),
5087
- plune_version: z3.string(),
5088
- started_at: z3.string(),
5089
- finished_at: z3.string(),
5090
- config_hash: z3.string(),
6529
+ var runResultSchema = z4.object({
6530
+ schemaVersion: z4.literal(RUN_RESULT_SCHEMA_VERSION),
6531
+ plune_version: z4.string(),
6532
+ started_at: z4.string(),
6533
+ finished_at: z4.string(),
6534
+ config_hash: z4.string(),
5091
6535
  /** cli#244. The result of `--dry-run`. Optional and additive — a RunResult without it validates unchanged. */
5092
- dry_run: z3.boolean().optional(),
6536
+ dry_run: z4.boolean().optional(),
5093
6537
  summary: summarySchema,
5094
- evals: z3.array(evalResultSchema)
6538
+ evals: z4.array(evalResultSchema)
5095
6539
  });
5096
6540
  function parseRunResult(value) {
5097
6541
  return runResultSchema.parse(value);
@@ -5099,11 +6543,30 @@ function parseRunResult(value) {
5099
6543
 
5100
6544
  // src/cli/api-url.ts
5101
6545
  init_esm_shims();
5102
- var DEFAULT_API_URL = "https://beta-api.plune.ai";
6546
+ var PRODUCTION_API_URL = "https://api.plune.ai";
6547
+ var BETA_API_URL = "https://beta-api.plune.ai";
6548
+ var DEFAULT_API_URL = PRODUCTION_API_URL;
6549
+ var DASHBOARDS = /* @__PURE__ */ new Map([
6550
+ [PRODUCTION_API_URL, "https://app.plune.ai"],
6551
+ [BETA_API_URL, "https://beta.plune.ai"]
6552
+ ]);
5103
6553
  function resolveApiUrl(explicit) {
5104
- const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
6554
+ const raw = explicit?.trim() || process.env["PLUNE_API_URL"]?.trim() || DEFAULT_API_URL;
5105
6555
  return raw.replace(/\/+$/, "");
5106
6556
  }
6557
+ function knownApi(apiUrl) {
6558
+ try {
6559
+ const origin = new URL(apiUrl.trim()).origin;
6560
+ return DASHBOARDS.has(origin) ? origin : void 0;
6561
+ } catch {
6562
+ return void 0;
6563
+ }
6564
+ }
6565
+ function tokenRefusedBy(apiUrl = resolveApiUrl()) {
6566
+ const named = `The address that refused it is ${apiUrl}.`;
6567
+ if (knownApi(apiUrl) !== PRODUCTION_API_URL) return named;
6568
+ 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.`;
6569
+ }
5107
6570
 
5108
6571
  // src/cli/credentials.ts
5109
6572
  init_esm_shims();
@@ -5223,9 +6686,9 @@ var NotLoggedInError = class extends Error {
5223
6686
  }
5224
6687
  };
5225
6688
  var TokenRejectedError = class extends Error {
5226
- constructor() {
6689
+ constructor(apiUrl = resolveApiUrl()) {
5227
6690
  super(
5228
- 'Your API token was rejected (revoked or invalid). Run "plune login" with a fresh token.'
6691
+ `Your API token was rejected (revoked or invalid). Run "plune login" with a fresh token. ${tokenRefusedBy(apiUrl)}`
5229
6692
  );
5230
6693
  this.name = "TokenRejectedError";
5231
6694
  }
@@ -5256,7 +6719,7 @@ function readRun(cwd, file, warn) {
5256
6719
  const target = file !== void 0 ? path7.resolve(cwd, file) : path7.join(cwd, ".plune", "last-run.json");
5257
6720
  let raw;
5258
6721
  try {
5259
- raw = fs6.readFileSync(target, "utf8");
6722
+ raw = fs7.readFileSync(target, "utf8");
5260
6723
  } catch {
5261
6724
  throw new SyncFileError(
5262
6725
  file !== void 0 ? `Run file not found: ${target}` : 'No run to sync. Run "plune run" first (or pass --file <path>).'
@@ -5269,11 +6732,18 @@ function readRun(cwd, file, warn) {
5269
6732
  throw new SyncFileError(`Run file is not valid JSON: ${target}`);
5270
6733
  }
5271
6734
  dropBadTraceLinks(json, warn);
6735
+ let run;
5272
6736
  try {
5273
- return parseRunResult(json);
6737
+ run = parseRunResult(json);
5274
6738
  } catch {
5275
6739
  throw new SyncFileError(`Run file does not match the RunResult schema: ${target}`);
5276
6740
  }
6741
+ const stubbed = stubbedEvals(run);
6742
+ if (stubbed.length > 0)
6743
+ throw new SyncFileError(
6744
+ `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).`
6745
+ );
6746
+ return run;
5277
6747
  }
5278
6748
  function dropBadTraceLinks(json, warn) {
5279
6749
  const evals = json?.evals;
@@ -5338,7 +6808,7 @@ async function handleSync(deps = {}) {
5338
6808
  }
5339
6809
  if (!res.ok) {
5340
6810
  const detail = await safeErrorDetail(res);
5341
- if (res.status === 401) throw new TokenRejectedError();
6811
+ if (res.status === 401) throw new TokenRejectedError(apiUrl);
5342
6812
  throw new SyncHttpError(res.status, detail);
5343
6813
  }
5344
6814
  const body = await res.json().catch(() => ({}));
@@ -5636,7 +7106,7 @@ var BUCKET_CODES = /* @__PURE__ */ new Set([
5636
7106
 
5637
7107
  // src/reporter-core/fallback.ts
5638
7108
  init_esm_shims();
5639
- import * as fs7 from "fs";
7109
+ import * as fs8 from "fs";
5640
7110
  import * as path9 from "path";
5641
7111
  var DEFAULT_FALLBACK_PATH = path9.join(".plune", "pending-results.jsonl");
5642
7112
 
@@ -5689,12 +7159,12 @@ var TYPE_BY_EXTENSION = {
5689
7159
  var READ_NOT_KEPT = /* @__PURE__ */ new Set(["application/plune.metadata+json", "application/plune.findings+json"]);
5690
7160
  var NAME_MAX = 200;
5691
7161
  function nameOf(file) {
5692
- const own2 = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : basename3(file.path));
7162
+ const own3 = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : basename3(file.path));
5693
7163
  const fileExt = file.path === void 0 ? "" : extname(file.path);
5694
- const ownExt = extname(own2);
7164
+ const ownExt = extname(own3);
5695
7165
  const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
5696
7166
  const ext = typed ? ownExt : fileExt;
5697
- let stem = typed ? own2.slice(0, -ownExt.length) : own2;
7167
+ let stem = typed ? own3.slice(0, -ownExt.length) : own3;
5698
7168
  if (stem.length + ext.length > NAME_MAX) {
5699
7169
  stem = stem.slice(0, Math.max(0, NAME_MAX - ext.length));
5700
7170
  if (/[\uD800-\uDBFF]$/.test(stem)) stem = stem.slice(0, -1);
@@ -5832,9 +7302,9 @@ function fileSender(options) {
5832
7302
  if (out.ok) countsOf(kind).uploaded += 1;
5833
7303
  else failed(job, out.detail || out.kind);
5834
7304
  }
5835
- async function uploadToBucket(job, size, first) {
7305
+ async function uploadToBucket(job, size, first2) {
5836
7306
  const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
5837
- let link = first;
7307
+ let link = first2;
5838
7308
  for (let renewed = false; ; ) {
5839
7309
  const put = await client.put(link.url, link.headers, source);
5840
7310
  if (put.ok) break;
@@ -5847,8 +7317,8 @@ function fileSender(options) {
5847
7317
  link = fresh;
5848
7318
  }
5849
7319
  requests += 1;
5850
- const done = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
5851
- if (!done.ok) return failedToBucket(job, codeOf2(done));
7320
+ const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
7321
+ if (!done2.ok) return failedToBucket(job, codeOf2(done2));
5852
7322
  countsOf(job.kind).uploaded += 1;
5853
7323
  }
5854
7324
  let free = uploadsAtOnce;
@@ -6014,9 +7484,9 @@ function fileSender(options) {
6014
7484
  const toComplete = [];
6015
7485
  await Promise.all(
6016
7486
  puts.map(
6017
- ({ s, link: first }) => gated(async () => {
7487
+ ({ s, link: first2 }) => gated(async () => {
6018
7488
  const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
6019
- let link = first;
7489
+ let link = first2;
6020
7490
  for (let renewed = false; ; ) {
6021
7491
  const put = await client.put(link.url, link.headers, source);
6022
7492
  if (put.ok) break;
@@ -6202,7 +7672,7 @@ function fileSender(options) {
6202
7672
 
6203
7673
  // src/cli/commands/cairn-artifact.ts
6204
7674
  init_esm_shims();
6205
- import * as fs8 from "fs/promises";
7675
+ import * as fs9 from "fs/promises";
6206
7676
  import * as path10 from "path";
6207
7677
 
6208
7678
  // src/importers/trace-url.ts
@@ -7765,14 +9235,14 @@ var NoCairnRunsError = class extends Error {
7765
9235
  }
7766
9236
  };
7767
9237
  async function findLatestCairnRun(runsDir = "runs") {
7768
- const entries = await fs8.readdir(runsDir, { withFileTypes: true }).catch(() => null);
9238
+ const entries = await fs9.readdir(runsDir, { withFileTypes: true }).catch(() => null);
7769
9239
  if (entries === null) throw new NoCairnRunsError(runsDir);
7770
9240
  let newest;
7771
9241
  for (const entry of entries) {
7772
9242
  if (!entry.isDirectory()) continue;
7773
9243
  const dir = path10.join(runsDir, entry.name);
7774
9244
  try {
7775
- const report = await fs8.lstat(path10.join(dir, "report.json"));
9245
+ const report = await fs9.lstat(path10.join(dir, "report.json"));
7776
9246
  if (!report.isFile()) continue;
7777
9247
  if (newest === void 0 || report.mtimeMs > newest.at) {
7778
9248
  newest = { dir, at: report.mtimeMs };
@@ -7823,13 +9293,13 @@ var CairnEvidenceAmbiguousError = class extends Error {
7823
9293
  };
7824
9294
  var asRecord = (v) => typeof v === "object" && v !== null ? v : {};
7825
9295
  var str = (v, fallback = "") => typeof v === "string" && v !== "" ? v : fallback;
7826
- var own = (rec, key) => Object.hasOwn(rec, key) ? rec[key] : void 0;
9296
+ var own2 = (rec, key) => Object.hasOwn(rec, key) ? rec[key] : void 0;
7827
9297
  var MAX_ARTIFACT_BYTES = 32 * 1024 * 1024;
7828
9298
  var MAX_MCP_CASES = 5e3;
7829
9299
  async function checkSize(dir, file) {
7830
9300
  let size;
7831
9301
  try {
7832
- const st = await fs8.stat(path10.join(dir, file));
9302
+ const st = await fs9.stat(path10.join(dir, file));
7833
9303
  if (!st.isFile()) throw new CairnArtifactShapeError(file, "", "is not a regular file");
7834
9304
  size = st.size;
7835
9305
  } catch (e) {
@@ -7847,20 +9317,20 @@ async function checkSize(dir, file) {
7847
9317
  }
7848
9318
  async function readJson(file) {
7849
9319
  try {
7850
- return JSON.parse(await fs8.readFile(file, "utf8"));
9320
+ return JSON.parse(await fs9.readFile(file, "utf8"));
7851
9321
  } catch {
7852
9322
  return void 0;
7853
9323
  }
7854
9324
  }
7855
9325
  var ARGS_CHARS2 = 200;
7856
- var SECRET_NAME = /key|token|secret|password|passwd|auth|cookie|credential/i;
9326
+ var SECRET_NAME2 = /key|token|secret|password|passwd|auth|cookie|credential/i;
7857
9327
  var maskNamed = (v, depth = 0) => {
7858
9328
  if (depth > 16) return "[deep]";
7859
9329
  if (Array.isArray(v)) return v.slice(0, 50).map((x) => maskNamed(x, depth + 1));
7860
9330
  if (typeof v === "object" && v !== null) {
7861
9331
  const out = {};
7862
9332
  for (const [k, x] of Object.entries(v).slice(0, 50)) {
7863
- out[k] = SECRET_NAME.test(k) ? "***" : maskNamed(x, depth + 1);
9333
+ out[k] = SECRET_NAME2.test(k) ? "***" : maskNamed(x, depth + 1);
7864
9334
  }
7865
9335
  return out;
7866
9336
  }
@@ -7887,7 +9357,7 @@ async function readMcpEvidence(dir, states) {
7887
9357
  if (!await checkSize(dir, file)) return void 0;
7888
9358
  let raw;
7889
9359
  try {
7890
- raw = JSON.parse(await fs8.readFile(path10.join(dir, file), "utf8"));
9360
+ raw = JSON.parse(await fs9.readFile(path10.join(dir, file), "utf8"));
7891
9361
  } catch {
7892
9362
  throw new CairnArtifactShapeError(file, "", "is not valid JSON");
7893
9363
  }
@@ -7901,7 +9371,7 @@ async function readMcpEvidence(dir, states) {
7901
9371
  throw new CairnArtifactShapeError(file, `[${i}]`, "must be an object");
7902
9372
  }
7903
9373
  const rec = item;
7904
- const id = own(rec, "stableId");
9374
+ const id = own2(rec, "stableId");
7905
9375
  if (typeof id !== "string" || !states.has(id)) {
7906
9376
  throw new CairnArtifactShapeError(
7907
9377
  file,
@@ -7912,18 +9382,18 @@ async function readMcpEvidence(dir, states) {
7912
9382
  if (byId.has(id)) {
7913
9383
  throw new CairnArtifactShapeError(file, `[${i}].stableId`, "appears more than once");
7914
9384
  }
7915
- if (own(rec, "state") !== states.get(id)) {
9385
+ if (own2(rec, "state") !== states.get(id)) {
7916
9386
  throw new CairnArtifactShapeError(
7917
9387
  file,
7918
9388
  `[${i}].state`,
7919
9389
  "does not agree with the state in report.json"
7920
9390
  );
7921
9391
  }
7922
- const request = own(rec, "request");
9392
+ const request = own2(rec, "request");
7923
9393
  if (request !== void 0 && typeof request !== "string") {
7924
9394
  throw new CairnArtifactShapeError(file, `[${i}].request`, "must be text");
7925
9395
  }
7926
- const durationMs = own(rec, "durationMs");
9396
+ const durationMs = own2(rec, "durationMs");
7927
9397
  if (durationMs !== void 0 && typeof durationMs !== "number") {
7928
9398
  throw new CairnArtifactShapeError(file, `[${i}].durationMs`, "must be a number");
7929
9399
  }
@@ -7941,7 +9411,7 @@ function expectedOfMcp(type, adversarial) {
7941
9411
  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.";
7942
9412
  }
7943
9413
  async function casesFromMcp(dir, report) {
7944
- const list2 = own(report, "cases");
9414
+ const list2 = own2(report, "cases");
7945
9415
  if (!Array.isArray(list2))
7946
9416
  throw new CairnArtifactShapeError("report.json", "cases", "must be a list");
7947
9417
  if (list2.length > MAX_MCP_CASES) {
@@ -7959,7 +9429,7 @@ async function casesFromMcp(dir, report) {
7959
9429
  }
7960
9430
  const c = raw;
7961
9431
  const text = (key) => {
7962
- const v = own(c, key);
9432
+ const v = own2(c, key);
7963
9433
  if (typeof v !== "string" || v === "") {
7964
9434
  throw new CairnArtifactShapeError("report.json", `${at}.${key}`, "must be text");
7965
9435
  }
@@ -7989,14 +9459,14 @@ async function casesFromMcp(dir, report) {
7989
9459
  }
7990
9460
  states.set(stableId, state);
7991
9461
  const kind = type;
7992
- const technique = own(c, "technique");
9462
+ const technique = own2(c, "technique");
7993
9463
  return {
7994
9464
  stableId,
7995
9465
  name,
7996
9466
  tool,
7997
9467
  type: kind,
7998
9468
  state,
7999
- adversarial: own(c, "adversarialStyle") !== void 0,
9469
+ adversarial: own2(c, "adversarialStyle") !== void 0,
8000
9470
  ...typeof technique === "string" ? { technique } : {}
8001
9471
  };
8002
9472
  });
@@ -8032,7 +9502,7 @@ function casesFromDesign(report, notes) {
8032
9502
  const c = asRecord(raw);
8033
9503
  const steps = (Array.isArray(c["steps"]) ? c["steps"] : []).map((s) => str(s)).filter((s) => s !== "");
8034
9504
  const title = str(c["title"], "untitled case");
8035
- const link = own(c, "traceUrl") ?? void 0;
9505
+ const link = own2(c, "traceUrl") ?? void 0;
8036
9506
  const said = [];
8037
9507
  const traceUrl = traceUrlOf(link, title, said);
8038
9508
  if (said.length > 0) {
@@ -8102,11 +9572,11 @@ async function readCairnRun(dir, deps = {}) {
8102
9572
  }
8103
9573
  cases = casesFromApi(report, verdicts);
8104
9574
  } else if (mode === "mcp") {
8105
- cases = own(report, "cases") === void 0 && Array.isArray(own(report, "testCases")) ? casesFromDesign(report, deps.notes ?? []) : await casesFromMcp(dir, report);
9575
+ cases = own2(report, "cases") === void 0 && Array.isArray(own2(report, "testCases")) ? casesFromDesign(report, deps.notes ?? []) : await casesFromMcp(dir, report);
8106
9576
  } else {
8107
9577
  cases = casesFromDesign(report, deps.notes ?? []);
8108
9578
  }
8109
- const tokens = own(asRecord(own(report, "cost")), "totalTokens");
9579
+ const tokens = own2(asRecord(own2(report, "cost")), "totalTokens");
8110
9580
  return {
8111
9581
  schemaVersion: INGEST_SCHEMA_VERSION,
8112
9582
  run: {
@@ -8124,7 +9594,7 @@ var clip = (s) => s.slice(0, DECLARED.text).replace(/[\uD800-\uDBFF]$/, "");
8124
9594
  async function readCairnSessionFiles(dir) {
8125
9595
  const raw = await readJson(path10.join(dir, "screencasts", "screencasts.json"));
8126
9596
  if (!Array.isArray(raw)) return void 0;
8127
- const root = await fs8.realpath(dir).catch(() => path10.resolve(dir));
9597
+ const root = await fs9.realpath(dir).catch(() => path10.resolve(dir));
8128
9598
  const within = (p) => {
8129
9599
  const rel = path10.relative(root, p);
8130
9600
  return rel !== "" && !rel.startsWith("..") && !path10.isAbsolute(rel);
@@ -8133,10 +9603,10 @@ async function readCairnSessionFiles(dir) {
8133
9603
  const inside = async (p) => {
8134
9604
  if (typeof p !== "string" || p === "") return void 0;
8135
9605
  const abs = path10.resolve(root, p);
8136
- const real = await fs8.realpath(abs).catch(() => void 0);
9606
+ const real = await fs9.realpath(abs).catch(() => void 0);
8137
9607
  if (within(abs) && (real === void 0 || within(real))) {
8138
9608
  const file = real ?? abs;
8139
- const size = await fs8.stat(file).then((s) => s.size, () => void 0);
9609
+ const size = await fs9.stat(file).then((s) => s.size, () => void 0);
8140
9610
  return { path: file, rel: path10.relative(root, abs).split(path10.sep).join("/"), ...size !== void 0 ? { size } : {} };
8141
9611
  }
8142
9612
  outside += 1;
@@ -8149,11 +9619,11 @@ async function readCairnSessionFiles(dir) {
8149
9619
  const rec = asRecord(entry);
8150
9620
  const found = [];
8151
9621
  for (const kind of ["video", "trace"]) {
8152
- const at = await inside(own(rec, kind));
9622
+ const at = await inside(own2(rec, kind));
8153
9623
  if (at !== void 0) found.push({ file: { path: at.path, ...at.size !== void 0 ? { size: at.size } : {} }, rel: at.rel, kind });
8154
9624
  }
8155
9625
  if (found.length === 0) continue;
8156
- const stableId = own(rec, "stableId");
9626
+ const stableId = own2(rec, "stableId");
8157
9627
  if (typeof stableId !== "string" || stableId === "") {
8158
9628
  unmapped += 1;
8159
9629
  continue;
@@ -8161,7 +9631,7 @@ async function readCairnSessionFiles(dir) {
8161
9631
  byCase.set(stableId, [...byCase.get(stableId) ?? [], ...found.map((f) => f.file)]);
8162
9632
  const declared = screencasts.get(stableId) ?? [];
8163
9633
  const keys = new Set(declared.flatMap((s) => s.files.map((f) => f.key)));
8164
- const title = clip(str(own(rec, "test")));
9634
+ const title = clip(str(own2(rec, "test")));
8165
9635
  const files = found.filter((f) => {
8166
9636
  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;
8167
9637
  keys.add(f.rel);
@@ -8169,14 +9639,14 @@ async function readCairnSessionFiles(dir) {
8169
9639
  });
8170
9640
  if (title === "" || files.length === 0 || declared.length >= DECLARED.perCase) continue;
8171
9641
  for (const f of files) f.file.key = f.rel;
8172
- const timing = own(rec, "timing");
9642
+ const timing = own2(rec, "timing");
8173
9643
  declared.push({
8174
9644
  title,
8175
9645
  ...timing === "trace" || timing === "estimated" ? { timing } : {},
8176
- chapters: (Array.isArray(own(rec, "chapters")) ? own(rec, "chapters") : []).flatMap((c) => {
9646
+ chapters: (Array.isArray(own2(rec, "chapters")) ? own2(rec, "chapters") : []).flatMap((c) => {
8177
9647
  const chapter = asRecord(c);
8178
- const t = clip(str(own(chapter, "title")));
8179
- const atMs = own(chapter, "atMs");
9648
+ const t = clip(str(own2(chapter, "title")));
9649
+ const atMs = own2(chapter, "atMs");
8180
9650
  return t !== "" && Number.isInteger(atMs) && atMs >= 0 ? [{ title: t, atMs }] : [];
8181
9651
  }).slice(0, DECLARED.chapters),
8182
9652
  files: files.map((f) => ({ key: f.rel, name: path10.basename(f.file.path), kind: f.kind, size: f.file.size }))
@@ -8194,8 +9664,8 @@ var IngestNotLoggedInError = class extends Error {
8194
9664
  }
8195
9665
  };
8196
9666
  var IngestTokenRejectedError = class extends Error {
8197
- constructor() {
8198
- super('Your API token was rejected (401). Run "plune login" again with a fresh token.');
9667
+ constructor(apiUrl = resolveApiUrl()) {
9668
+ super(`Your API token was rejected (401). Run "plune login" again with a fresh token. ${tokenRefusedBy(apiUrl)}`);
8199
9669
  this.name = "IngestTokenRejectedError";
8200
9670
  }
8201
9671
  };
@@ -8391,7 +9861,7 @@ async function handleIngest(deps) {
8391
9861
  }
8392
9862
  if (!res.ok) {
8393
9863
  const detail = await safeErrorDetail2(res);
8394
- if (res.status === 401) throw new IngestTokenRejectedError();
9864
+ if (res.status === 401) throw new IngestTokenRejectedError(apiUrl);
8395
9865
  throw new IngestHttpError(res.status, detail);
8396
9866
  }
8397
9867
  const body = await res.json().catch(() => ({}));