@plune-ai/cli 0.39.16 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -5
- package/dist/cli.cjs +3754 -1252
- package/dist/{execute-DLNnhkEM.d.cts → execute-CD55D0di.d.cts} +6 -0
- package/dist/{execute-DLNnhkEM.d.ts → execute-CD55D0di.d.ts} +6 -0
- package/dist/index.cjs +1737 -269
- package/dist/index.d.cts +168 -6
- package/dist/index.d.ts +168 -6
- package/dist/index.js +1736 -268
- package/dist/mcp-http.cjs +4 -4
- package/dist/mcp-http.d.cts +1 -1
- package/dist/mcp-http.d.ts +1 -1
- package/dist/mcp-http.js +4 -4
- package/dist/mcp-tools.cjs +4 -4
- package/dist/mcp-tools.d.cts +1 -1
- package/dist/mcp-tools.d.ts +1 -1
- package/dist/mcp-tools.js +4 -4
- package/dist/reporter-core.cjs +28 -5
- package/dist/reporter-core.d.cts +1 -1
- package/dist/reporter-core.d.ts +1 -1
- package/dist/reporter-core.js +28 -5
- package/package.json +1 -1
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
|
|
30
|
-
if (
|
|
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
|
|
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((
|
|
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 =
|
|
235
|
-
if (url.password !== "") url.password =
|
|
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,
|
|
238
|
-
return url.href.replaceAll("%2A%2A%2A",
|
|
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,
|
|
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) ?
|
|
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
|
|
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
|
-
|
|
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
|
|
438
|
+
let done2 = false;
|
|
439
439
|
const finish = () => {
|
|
440
|
-
if (
|
|
441
|
-
|
|
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
|
|
503
|
+
const start2 = transport.start.bind(transport);
|
|
504
504
|
transport.start = async () => {
|
|
505
|
-
await
|
|
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
|
|
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 (
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
755
|
+
done2();
|
|
756
756
|
resolve9({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
|
|
757
757
|
};
|
|
758
758
|
const stop = () => {
|
|
759
|
-
|
|
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 (
|
|
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
|
|
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
|
|
1269
|
-
if (stdio &&
|
|
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 && !
|
|
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 (
|
|
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 [
|
|
1364
|
-
return others.length === 0 ? { provider:
|
|
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 =
|
|
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
|
|
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:
|
|
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
|
|
2131
|
-
throw new Error(`Unknown provider type "${name}". Registered providers: ${
|
|
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
|
|
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
|
|
2525
|
-
const run = balancedFrom(s,
|
|
3171
|
+
const start2 = i + rel;
|
|
3172
|
+
const run = balancedFrom(s, start2);
|
|
2526
3173
|
if (run === null) {
|
|
2527
|
-
i =
|
|
3174
|
+
i = start2 + 1;
|
|
2528
3175
|
} else {
|
|
2529
3176
|
yield run;
|
|
2530
|
-
i =
|
|
3177
|
+
i = start2 + run.length;
|
|
2531
3178
|
}
|
|
2532
3179
|
}
|
|
2533
3180
|
}
|
|
2534
|
-
function balancedFrom(s,
|
|
2535
|
-
const open2 = s[
|
|
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 =
|
|
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(
|
|
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
|
|
3094
|
-
if (
|
|
3095
|
-
const got =
|
|
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
|
|
3287
|
-
throw new Error(`Unknown assertion type "${type}". Registered: ${
|
|
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
|
|
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
|
|
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))
|
|
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) && (
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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) && (
|
|
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
|
|
3835
|
-
if (
|
|
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
|
|
4130
|
-
const jev =
|
|
4131
|
-
const judgeCfg =
|
|
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 (
|
|
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
|
|
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.
|
|
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
|
|
4492
|
-
if (
|
|
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
|
|
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 =
|
|
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 =
|
|
4603
|
-
if (!
|
|
4604
|
-
const why =
|
|
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
|
|
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
|
|
4643
|
-
const [name, value] =
|
|
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,416 @@ 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
|
+
return !hosts.includes(host) || origin !== void 0 && !hosts.some((h) => origin.toLowerCase() === `http://${h}`);
|
|
5818
|
+
}
|
|
5819
|
+
var NOT_LOCAL_MESSAGE = "This server answers only a request addressed to 127.0.0.1, localhost or [::1] with its own port, and none a web page of another origin sent";
|
|
5820
|
+
function maskedHeaders(headers) {
|
|
5821
|
+
const out = {};
|
|
5822
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
5823
|
+
if (value === void 0) continue;
|
|
5824
|
+
out[name] = SECRET_NAME.test(name) ? MASK : Array.isArray(value) ? value.join(", ") : value;
|
|
5825
|
+
}
|
|
5826
|
+
return out;
|
|
5827
|
+
}
|
|
5828
|
+
function maskedQuery(params) {
|
|
5829
|
+
return [...params].map(
|
|
5830
|
+
([k, v]) => `${encodeURIComponent(k)}=${SECRET_NAME.test(k) ? MASK : encodeURIComponent(v)}`
|
|
5831
|
+
).join("&");
|
|
5832
|
+
}
|
|
5833
|
+
function renderBody(response) {
|
|
5834
|
+
if (response.sse !== void 0) {
|
|
5835
|
+
const events = response.sse.map((chunk2) => {
|
|
5836
|
+
const { event, data } = typeof chunk2 === "string" ? { event: void 0, data: chunk2 } : chunk2;
|
|
5837
|
+
const line = typeof data === "string" ? data : JSON.stringify(data);
|
|
5838
|
+
return `${event === void 0 ? "" : `event: ${event}
|
|
5839
|
+
`}data: ${line}
|
|
5840
|
+
|
|
5841
|
+
`;
|
|
5842
|
+
});
|
|
5843
|
+
return { type: "text/event-stream", body: Buffer.from(events.join("")) };
|
|
5844
|
+
}
|
|
5845
|
+
if (response.text !== void 0)
|
|
5846
|
+
return { type: "text/plain; charset=utf-8", body: Buffer.from(response.text) };
|
|
5847
|
+
if (response.json !== void 0)
|
|
5848
|
+
return { type: "application/json", body: Buffer.from(JSON.stringify(response.json)) };
|
|
5849
|
+
return { body: Buffer.alloc(0) };
|
|
5850
|
+
}
|
|
5851
|
+
function responseHeaders(response, type, length) {
|
|
5852
|
+
const headers = {};
|
|
5853
|
+
if (type !== void 0) headers["content-type"] = type;
|
|
5854
|
+
if (response.sse === void 0) headers["content-length"] = length;
|
|
5855
|
+
else headers["cache-control"] = "no-cache";
|
|
5856
|
+
for (const [name, value] of Object.entries(response.headers)) headers[name.toLowerCase()] = value;
|
|
5857
|
+
return headers;
|
|
5858
|
+
}
|
|
5859
|
+
function sendJson(res, status, body, headers = {}) {
|
|
5860
|
+
const text = JSON.stringify(body);
|
|
5861
|
+
res.writeHead(status, {
|
|
5862
|
+
"content-type": "application/json",
|
|
5863
|
+
"content-length": Buffer.byteLength(text),
|
|
5864
|
+
...headers
|
|
5865
|
+
});
|
|
5866
|
+
res.end(text);
|
|
5867
|
+
}
|
|
5868
|
+
var providerError = (type, code, message) => ({
|
|
5869
|
+
type: "error",
|
|
5870
|
+
error: { type, code, message }
|
|
5871
|
+
});
|
|
5872
|
+
function writeSlowly(res, body, bytesPerSec, timers) {
|
|
5873
|
+
const startedAt = timers.now();
|
|
5874
|
+
const step = Math.max(1, Math.round(bytesPerSec * SLOW_STREAM_STEP_MS / 1e3));
|
|
5875
|
+
let sent = 0;
|
|
5876
|
+
let handle;
|
|
5877
|
+
const tick = () => {
|
|
5878
|
+
const due = Math.min(
|
|
5879
|
+
body.length,
|
|
5880
|
+
Math.floor((timers.now() - startedAt) * bytesPerSec / 1e3)
|
|
5881
|
+
);
|
|
5882
|
+
if (due > sent) {
|
|
5883
|
+
res.write(body.subarray(sent, due));
|
|
5884
|
+
sent = due;
|
|
5885
|
+
}
|
|
5886
|
+
if (sent >= body.length) {
|
|
5887
|
+
res.end();
|
|
5888
|
+
return;
|
|
5889
|
+
}
|
|
5890
|
+
const nextAt = startedAt + Math.min(body.length, sent + step) * 1e3 / bytesPerSec;
|
|
5891
|
+
handle = timers.setTimeout(tick, Math.max(1, Math.ceil(nextAt - timers.now())));
|
|
5892
|
+
};
|
|
5893
|
+
tick();
|
|
5894
|
+
return () => timers.clearTimeout(handle);
|
|
5895
|
+
}
|
|
5896
|
+
async function start(options = {}) {
|
|
5897
|
+
const host = options.host ?? "127.0.0.1";
|
|
5898
|
+
const journalBodyCap = options.journalBodyCap ?? 64 * 1024;
|
|
5899
|
+
const timers = options.timers ?? REAL_TIMERS;
|
|
5900
|
+
const scopes = /* @__PURE__ */ new Map();
|
|
5901
|
+
const unrouted = [];
|
|
5902
|
+
let unroutedDropped = 0;
|
|
5903
|
+
let closing;
|
|
5904
|
+
const record = (journal, entry) => {
|
|
5905
|
+
journal.push(entry);
|
|
5906
|
+
if (journal.length <= JOURNAL_MAX_ENTRIES) return 0;
|
|
5907
|
+
journal.shift();
|
|
5908
|
+
return 1;
|
|
5909
|
+
};
|
|
5910
|
+
function answer(req, res, body) {
|
|
5911
|
+
const target = req.url ?? "";
|
|
5912
|
+
const queryAt = target.indexOf("?");
|
|
5913
|
+
const rawPath = queryAt === -1 ? target : target.slice(0, queryAt);
|
|
5914
|
+
const segments = rawPath.split("/");
|
|
5915
|
+
const badTarget = segments[0] !== "" || segments.length < 2 || segments[1] === "" && segments.length > 2 || segments.some((segment2) => DOT_SEGMENT.test(segment2));
|
|
5916
|
+
const name = badTarget ? "" : segments[1];
|
|
5917
|
+
const method = req.method ?? "GET";
|
|
5918
|
+
const path12 = badTarget ? rawPath : rawPath.slice(name.length + 1) || "/";
|
|
5919
|
+
const entry = {
|
|
5920
|
+
scope: name,
|
|
5921
|
+
method,
|
|
5922
|
+
path: path12,
|
|
5923
|
+
query: maskedQuery(new URLSearchParams(queryAt === -1 ? "" : target.slice(queryAt + 1))),
|
|
5924
|
+
headers: maskedHeaders(req.headers),
|
|
5925
|
+
body: body.subarray(0, journalBodyCap).toString("utf8"),
|
|
5926
|
+
bodyTruncated: body.length > journalBodyCap,
|
|
5927
|
+
matched: false
|
|
5928
|
+
};
|
|
5929
|
+
const refuse = (status, type, message, open2) => sendJson(res, status, {
|
|
5930
|
+
error: { type, message, method, ...open2 === void 0 ? {} : { scope: open2 } }
|
|
5931
|
+
});
|
|
5932
|
+
const scope = badTarget ? void 0 : scopes.get(name);
|
|
5933
|
+
if (scope === void 0) {
|
|
5934
|
+
unroutedDropped += record(unrouted, entry);
|
|
5935
|
+
if (badTarget)
|
|
5936
|
+
refuse(
|
|
5937
|
+
400,
|
|
5938
|
+
"mock_bad_target",
|
|
5939
|
+
'Bad request target: it starts with "/<scope>" and holds no "." or ".." segment'
|
|
5940
|
+
);
|
|
5941
|
+
else
|
|
5942
|
+
refuse(
|
|
5943
|
+
404,
|
|
5944
|
+
"mock_no_stub",
|
|
5945
|
+
`No open scope for this ${method} request: the first path segment names the scope`
|
|
5946
|
+
);
|
|
5947
|
+
return;
|
|
5948
|
+
}
|
|
5949
|
+
scope.dropped += record(scope.journal, entry);
|
|
5950
|
+
let json;
|
|
5951
|
+
let parsed2 = false;
|
|
5952
|
+
const live = scope.stubs.find(({ stub, matches, calls }) => {
|
|
5953
|
+
if (stub.times !== "always" && calls >= (stub.times === "once" ? 1 : stub.times))
|
|
5954
|
+
return false;
|
|
5955
|
+
if (stub.method !== method || !matches(path12)) return false;
|
|
5956
|
+
const exact = stub.match === "exact";
|
|
5957
|
+
if (stub.body === void 0 && !exact) return true;
|
|
5958
|
+
if (!parsed2) {
|
|
5959
|
+
parsed2 = true;
|
|
5960
|
+
try {
|
|
5961
|
+
json = JSON.parse(body.toString("utf8"));
|
|
5962
|
+
} catch {
|
|
5963
|
+
json = void 0;
|
|
5964
|
+
}
|
|
5965
|
+
}
|
|
5966
|
+
if (!exact) return matchesSubset(stub.body, json);
|
|
5967
|
+
return stub.body === void 0 ? json === void 0 : matchesExact(stub.body, json);
|
|
5968
|
+
});
|
|
5969
|
+
if (live === void 0) {
|
|
5970
|
+
refuse(
|
|
5971
|
+
404,
|
|
5972
|
+
"mock_no_stub",
|
|
5973
|
+
`No stub matches this ${method} request in scope "${name}": compare its path and body in the journal of the scope with the stubs`,
|
|
5974
|
+
name
|
|
5975
|
+
);
|
|
5976
|
+
return;
|
|
5977
|
+
}
|
|
5978
|
+
entry.matched = true;
|
|
5979
|
+
live.calls += 1;
|
|
5980
|
+
const response = live.stub.response ?? { status: 200, headers: {} };
|
|
5981
|
+
const rendered = renderBody(response);
|
|
5982
|
+
const head = (length) => {
|
|
5983
|
+
res.writeHead(response.status, responseHeaders(response, rendered.type, length));
|
|
5984
|
+
};
|
|
5985
|
+
const { failure } = live.stub;
|
|
5986
|
+
if (failure === void 0 || failure.first !== void 0 && live.calls > failure.first) {
|
|
5987
|
+
head(rendered.body.length);
|
|
5988
|
+
res.end(rendered.body);
|
|
5989
|
+
return;
|
|
5990
|
+
}
|
|
5991
|
+
const hold = (stop = () => void 0) => {
|
|
5992
|
+
const abort = () => {
|
|
5993
|
+
stop();
|
|
5994
|
+
res.destroy();
|
|
5995
|
+
};
|
|
5996
|
+
scope.held.add(abort);
|
|
5997
|
+
res.on("close", () => {
|
|
5998
|
+
stop();
|
|
5999
|
+
scope.held.delete(abort);
|
|
6000
|
+
});
|
|
6001
|
+
};
|
|
6002
|
+
switch (failure.type) {
|
|
6003
|
+
case "timeout":
|
|
6004
|
+
hold();
|
|
6005
|
+
return;
|
|
6006
|
+
case "reset":
|
|
6007
|
+
req.socket.resetAndDestroy();
|
|
6008
|
+
return;
|
|
6009
|
+
case "http_429":
|
|
6010
|
+
sendJson(
|
|
6011
|
+
res,
|
|
6012
|
+
429,
|
|
6013
|
+
providerError("rate_limit_error", "rate_limit_exceeded", "Rate limit exceeded (stub)"),
|
|
6014
|
+
{ "retry-after": String(failure.retry_after_seconds) }
|
|
6015
|
+
);
|
|
6016
|
+
return;
|
|
6017
|
+
case "http_500":
|
|
6018
|
+
sendJson(
|
|
6019
|
+
res,
|
|
6020
|
+
500,
|
|
6021
|
+
providerError("api_error", "internal_error", "Internal server error (stub)")
|
|
6022
|
+
);
|
|
6023
|
+
return;
|
|
6024
|
+
case "slow_stream":
|
|
6025
|
+
head(rendered.body.length);
|
|
6026
|
+
res.flushHeaders();
|
|
6027
|
+
hold(writeSlowly(res, rendered.body, failure.bytes_per_sec, timers));
|
|
6028
|
+
return;
|
|
6029
|
+
case "truncated_json": {
|
|
6030
|
+
const cut = rendered.body.subarray(0, Math.floor(rendered.body.length / 2));
|
|
6031
|
+
if (failure.content_length === "cut") {
|
|
6032
|
+
head(cut.length);
|
|
6033
|
+
res.end(cut);
|
|
6034
|
+
} else {
|
|
6035
|
+
head(rendered.body.length);
|
|
6036
|
+
res.write(cut, () => res.destroy());
|
|
6037
|
+
}
|
|
6038
|
+
return;
|
|
6039
|
+
}
|
|
6040
|
+
}
|
|
6041
|
+
}
|
|
6042
|
+
let port = 0;
|
|
6043
|
+
const server = http.createServer((req, res) => {
|
|
6044
|
+
if (notLocal(req, port, host)) {
|
|
6045
|
+
req.resume();
|
|
6046
|
+
sendJson(res, 403, { error: { type: "mock_not_local", message: NOT_LOCAL_MESSAGE } });
|
|
6047
|
+
return;
|
|
6048
|
+
}
|
|
6049
|
+
const chunks = [];
|
|
6050
|
+
let size = 0;
|
|
6051
|
+
req.on("error", () => void 0);
|
|
6052
|
+
req.on("data", (chunk2) => {
|
|
6053
|
+
size += chunk2.length;
|
|
6054
|
+
if (size <= MAX_BODY_BYTES) chunks.push(chunk2);
|
|
6055
|
+
else chunks.length = 0;
|
|
6056
|
+
});
|
|
6057
|
+
req.on("end", () => {
|
|
6058
|
+
if (size > MAX_BODY_BYTES) {
|
|
6059
|
+
sendJson(res, 413, {
|
|
6060
|
+
error: { type: "mock_body_too_large", message: "Request body over 16 MiB" }
|
|
6061
|
+
});
|
|
6062
|
+
return;
|
|
6063
|
+
}
|
|
6064
|
+
try {
|
|
6065
|
+
answer(req, res, Buffer.concat(chunks));
|
|
6066
|
+
} catch {
|
|
6067
|
+
if (res.headersSent) res.destroy();
|
|
6068
|
+
else
|
|
6069
|
+
sendJson(res, 500, {
|
|
6070
|
+
error: { type: "mock_internal", message: "The stub server failed on this request" }
|
|
6071
|
+
});
|
|
6072
|
+
}
|
|
6073
|
+
});
|
|
6074
|
+
});
|
|
6075
|
+
server.maxConnections = MAX_CONNECTIONS;
|
|
6076
|
+
await new Promise((resolve9, reject) => {
|
|
6077
|
+
server.once("error", reject);
|
|
6078
|
+
server.listen(options.port ?? 0, host, () => {
|
|
6079
|
+
server.off("error", reject);
|
|
6080
|
+
resolve9();
|
|
6081
|
+
});
|
|
6082
|
+
});
|
|
6083
|
+
({ port } = server.address());
|
|
6084
|
+
const url = `http://${host.includes(":") ? `[${host}]` : host}:${port}`;
|
|
6085
|
+
return {
|
|
6086
|
+
url,
|
|
6087
|
+
port,
|
|
6088
|
+
unrouted,
|
|
6089
|
+
get unroutedDropped() {
|
|
6090
|
+
return unroutedDropped;
|
|
6091
|
+
},
|
|
6092
|
+
scope(name, stubs = []) {
|
|
6093
|
+
if (closing !== void 0) throw new Error("The server is closed: it takes no new scope");
|
|
6094
|
+
if (!SCOPE_NAME.test(name))
|
|
6095
|
+
throw new Error(
|
|
6096
|
+
`Bad scope name "${name}": letters, digits, ".", "_" and "-" only, and not "." or ".."`
|
|
6097
|
+
);
|
|
6098
|
+
if (scopes.has(name)) throw new Error(`Scope "${name}" is already open`);
|
|
6099
|
+
const state = { stubs: [], journal: [], dropped: 0, held: /* @__PURE__ */ new Set() };
|
|
6100
|
+
scopes.set(name, state);
|
|
6101
|
+
const scope = {
|
|
6102
|
+
name,
|
|
6103
|
+
url: `${url}/${name}`,
|
|
6104
|
+
journal: state.journal,
|
|
6105
|
+
get dropped() {
|
|
6106
|
+
return state.dropped;
|
|
6107
|
+
},
|
|
6108
|
+
add(...inputs) {
|
|
6109
|
+
for (const input of inputs) {
|
|
6110
|
+
const result = stubSchema.safeParse(input);
|
|
6111
|
+
if (!result.success)
|
|
6112
|
+
throw new Error(`Invalid stub: ${formatIssues(result.error).join("; ")}`);
|
|
6113
|
+
state.stubs.push({
|
|
6114
|
+
stub: result.data,
|
|
6115
|
+
matches: result.data.match === "exact" ? (path12) => maskedTextMatches(result.data.path, path12) : pathMatcher(result.data.path),
|
|
6116
|
+
calls: 0
|
|
6117
|
+
});
|
|
6118
|
+
}
|
|
6119
|
+
},
|
|
6120
|
+
close() {
|
|
6121
|
+
if (scopes.get(name) === state) scopes.delete(name);
|
|
6122
|
+
const unused = state.stubs.filter((s) => s.calls === 0).map((s) => s.stub);
|
|
6123
|
+
state.stubs = [];
|
|
6124
|
+
for (const abort of [...state.held]) abort();
|
|
6125
|
+
return unused;
|
|
6126
|
+
}
|
|
6127
|
+
};
|
|
6128
|
+
scope.add(...stubs);
|
|
6129
|
+
return scope;
|
|
6130
|
+
},
|
|
6131
|
+
close() {
|
|
6132
|
+
closing ??= new Promise((resolve9) => {
|
|
6133
|
+
for (const state of scopes.values()) for (const abort of [...state.held]) abort();
|
|
6134
|
+
scopes.clear();
|
|
6135
|
+
server.close(() => resolve9());
|
|
6136
|
+
server.closeAllConnections();
|
|
6137
|
+
});
|
|
6138
|
+
return closing;
|
|
6139
|
+
}
|
|
6140
|
+
};
|
|
6141
|
+
}
|
|
6142
|
+
|
|
4727
6143
|
// src/cli/commands/run.ts
|
|
4728
6144
|
var NOOP_CACHE = { get: () => void 0, set: () => {
|
|
4729
6145
|
}, delete: () => {
|
|
@@ -4750,12 +6166,12 @@ function parseToolDescriptions(values) {
|
|
|
4750
6166
|
const file = text.slice(1);
|
|
4751
6167
|
try {
|
|
4752
6168
|
const full = path6.resolve(file);
|
|
4753
|
-
const stat2 =
|
|
6169
|
+
const stat2 = fs6.statSync(full);
|
|
4754
6170
|
if (!stat2.isFile())
|
|
4755
6171
|
throw new RunConfigError(`--tool-description ${tool}: ${file} is not a file`);
|
|
4756
6172
|
if (stat2.size > MAX_DESCRIPTION_BYTES)
|
|
4757
6173
|
throw new RunConfigError(`--tool-description ${tool}: ${file} is over 64 KB`);
|
|
4758
|
-
text =
|
|
6174
|
+
text = fs6.readFileSync(full, "utf8").replace(/\r?\n$/, "");
|
|
4759
6175
|
} catch (err) {
|
|
4760
6176
|
if (err instanceof RunConfigError) throw err;
|
|
4761
6177
|
throw new RunConfigError(`--tool-description ${tool}: cannot read ${file}`);
|
|
@@ -4773,7 +6189,7 @@ function mockScript(env) {
|
|
|
4773
6189
|
if (file === void 0 || file === "") return void 0;
|
|
4774
6190
|
let text;
|
|
4775
6191
|
try {
|
|
4776
|
-
text =
|
|
6192
|
+
text = fs6.readFileSync(path6.resolve(file), "utf8");
|
|
4777
6193
|
} catch {
|
|
4778
6194
|
throw new RunConfigError(`PLUNE_MOCK_SCRIPT: cannot read ${file}`);
|
|
4779
6195
|
}
|
|
@@ -4807,11 +6223,11 @@ function resolveProviderFor(config, dryRun) {
|
|
|
4807
6223
|
return () => makeMockProvider(script);
|
|
4808
6224
|
}
|
|
4809
6225
|
if (dryRun) return (cfg) => makeEstimateProvider(cfg, config.pricing);
|
|
4810
|
-
return (cfg) => getProvider(cfg, process.env, config.pricing);
|
|
6226
|
+
return (cfg, stubOrigin) => getProvider(cfg, process.env, config.pricing, stubOrigin);
|
|
4811
6227
|
}
|
|
4812
6228
|
function buildRealDeps(config, baseDir, dryRun) {
|
|
4813
6229
|
const dir = path6.join(baseDir, ".plune");
|
|
4814
|
-
|
|
6230
|
+
fs6.mkdirSync(dir, { recursive: true });
|
|
4815
6231
|
return {
|
|
4816
6232
|
resolveProvider: resolveProviderFor(config, dryRun),
|
|
4817
6233
|
embedder: getDefaultEmbedder(),
|
|
@@ -4837,8 +6253,21 @@ function buildRealDeps(config, baseDir, dryRun) {
|
|
|
4837
6253
|
}
|
|
4838
6254
|
function persist(result, baseDir) {
|
|
4839
6255
|
const dir = path6.join(baseDir, ".plune");
|
|
4840
|
-
|
|
4841
|
-
|
|
6256
|
+
fs6.mkdirSync(dir, { recursive: true });
|
|
6257
|
+
fs6.writeFileSync(path6.join(dir, "last-run.json"), JSON.stringify(result, null, 2));
|
|
6258
|
+
}
|
|
6259
|
+
function stubWarnings(config, result) {
|
|
6260
|
+
return result.evals.flatMap((ev) => {
|
|
6261
|
+
if (ev.stubs === void 0) return [];
|
|
6262
|
+
const { never_called: never, unmatched } = ev.stubs;
|
|
6263
|
+
const file = config.evals.find((e) => e.id === baseEvalId(ev))?.stubs ?? "its stub file";
|
|
6264
|
+
return [
|
|
6265
|
+
...never.length > 0 ? [`${never.map((i) => `stubs.${i}`).join(", ")} of ${file} ${never.length === 1 ? "was" : "were"} never called`] : [],
|
|
6266
|
+
...unmatched.length > 0 ? [
|
|
6267
|
+
`${unmatched.length} request${unmatched.length === 1 ? "" : "s"} matched no stub: ` + unmatched.map((u) => `${u.method} in ${u.scope}`).join(", ")
|
|
6268
|
+
] : []
|
|
6269
|
+
].map((line) => `eval "${ev.id}": ${line}`);
|
|
6270
|
+
});
|
|
4842
6271
|
}
|
|
4843
6272
|
function jevAddressCheck(config, env) {
|
|
4844
6273
|
const checks = [...config.defaults?.assertions ?? [], ...config.evals.flatMap((ev) => ev.assertions)];
|
|
@@ -4860,7 +6289,9 @@ async function handleRun(options, depsFactory) {
|
|
|
4860
6289
|
`);
|
|
4861
6290
|
const toolDescriptions = options.toolDescription !== void 0 && options.toolDescription.length > 0 ? parseToolDescriptions(options.toolDescription) : void 0;
|
|
4862
6291
|
const factory = depsFactory ?? ((c, d) => buildRealDeps(c, d, options.dryRun));
|
|
4863
|
-
const
|
|
6292
|
+
const given = factory(config, baseDir);
|
|
6293
|
+
let stubServer;
|
|
6294
|
+
const deps = depsFactory === void 0 && isMockMode(process.env) ? given : { ...given, stubServer: () => stubServer ??= (given.stubServer ?? start)() };
|
|
4864
6295
|
try {
|
|
4865
6296
|
const stale = deps.cache.staleEntries ?? 0;
|
|
4866
6297
|
if (stale > 0) {
|
|
@@ -4896,6 +6327,8 @@ async function handleRun(options, depsFactory) {
|
|
|
4896
6327
|
`
|
|
4897
6328
|
);
|
|
4898
6329
|
}
|
|
6330
|
+
for (const warning of stubWarnings(config, result)) process.stderr.write(`warning: ${warning}
|
|
6331
|
+
`);
|
|
4899
6332
|
if (options.dryRun) {
|
|
4900
6333
|
const agentic = new Set(config.evals.filter((ev) => ev.mcp !== void 0).map((ev) => ev.id));
|
|
4901
6334
|
if (result.evals.some((ev) => agentic.has(ev.id)))
|
|
@@ -4907,164 +6340,173 @@ async function handleRun(options, depsFactory) {
|
|
|
4907
6340
|
return result;
|
|
4908
6341
|
} finally {
|
|
4909
6342
|
deps.cache.close();
|
|
6343
|
+
if (stubServer !== void 0) await stubServer.then((server) => server.close(), () => void 0);
|
|
4910
6344
|
}
|
|
4911
6345
|
}
|
|
4912
6346
|
|
|
4913
6347
|
// src/cli/commands/sync.ts
|
|
4914
6348
|
init_esm_shims();
|
|
4915
6349
|
import { createHash as createHash2 } from "crypto";
|
|
4916
|
-
import * as
|
|
6350
|
+
import * as fs7 from "fs";
|
|
4917
6351
|
import * as path7 from "path";
|
|
4918
6352
|
|
|
4919
6353
|
// src/types/run-result-schema.ts
|
|
4920
6354
|
init_esm_shims();
|
|
4921
|
-
import { z as
|
|
6355
|
+
import { z as z4 } from "zod";
|
|
4922
6356
|
var RUN_RESULT_SCHEMA_VERSION = 1;
|
|
4923
|
-
var binaryVerdictSchema =
|
|
4924
|
-
question:
|
|
4925
|
-
passed:
|
|
6357
|
+
var binaryVerdictSchema = z4.object({
|
|
6358
|
+
question: z4.string().min(1),
|
|
6359
|
+
passed: z4.boolean()
|
|
4926
6360
|
});
|
|
4927
|
-
var assertionResultRecordSchema2 =
|
|
4928
|
-
type:
|
|
4929
|
-
passed:
|
|
4930
|
-
score:
|
|
4931
|
-
reason:
|
|
4932
|
-
binaryVerdicts:
|
|
6361
|
+
var assertionResultRecordSchema2 = z4.object({
|
|
6362
|
+
type: z4.string(),
|
|
6363
|
+
passed: z4.boolean(),
|
|
6364
|
+
score: z4.number().optional(),
|
|
6365
|
+
reason: z4.string().optional(),
|
|
6366
|
+
binaryVerdicts: z4.array(binaryVerdictSchema).optional(),
|
|
4933
6367
|
/** plune-ai/cli#373. Optional and additive — a RunResult written before it validates unchanged. */
|
|
4934
|
-
judge_model:
|
|
6368
|
+
judge_model: z4.string().optional()
|
|
4935
6369
|
});
|
|
4936
|
-
var usageSchema =
|
|
4937
|
-
input_tokens:
|
|
4938
|
-
output_tokens:
|
|
4939
|
-
cost_usd:
|
|
6370
|
+
var usageSchema = z4.object({
|
|
6371
|
+
input_tokens: z4.number(),
|
|
6372
|
+
output_tokens: z4.number(),
|
|
6373
|
+
cost_usd: z4.number(),
|
|
4940
6374
|
/** cli#151. Optional and additive — a RunResult written before it validates unchanged. */
|
|
4941
|
-
priced:
|
|
6375
|
+
priced: z4.boolean().optional()
|
|
4942
6376
|
});
|
|
4943
|
-
var runErrorSchema =
|
|
4944
|
-
code:
|
|
4945
|
-
message:
|
|
6377
|
+
var runErrorSchema = z4.object({
|
|
6378
|
+
code: z4.string(),
|
|
6379
|
+
message: z4.string()
|
|
4946
6380
|
});
|
|
4947
|
-
var savedSchema =
|
|
4948
|
-
input_tokens:
|
|
4949
|
-
output_tokens:
|
|
4950
|
-
cost_usd:
|
|
6381
|
+
var savedSchema = z4.object({
|
|
6382
|
+
input_tokens: z4.number(),
|
|
6383
|
+
output_tokens: z4.number(),
|
|
6384
|
+
cost_usd: z4.number()
|
|
4951
6385
|
});
|
|
4952
|
-
var rowResultSchema =
|
|
4953
|
-
vars:
|
|
4954
|
-
output:
|
|
4955
|
-
cached:
|
|
6386
|
+
var rowResultSchema = z4.object({
|
|
6387
|
+
vars: z4.record(z4.string(), z4.unknown()),
|
|
6388
|
+
output: z4.string().nullable(),
|
|
6389
|
+
cached: z4.boolean(),
|
|
6390
|
+
/** A row of an eval with `stubs`. Kept by the parser so that `plune sync` can see it and refuse the upload. */
|
|
6391
|
+
stubbed: z4.boolean().optional(),
|
|
4956
6392
|
usage: usageSchema.optional(),
|
|
4957
|
-
latency_ms:
|
|
6393
|
+
latency_ms: z4.number().optional(),
|
|
4958
6394
|
error: runErrorSchema.optional(),
|
|
4959
|
-
assertions:
|
|
6395
|
+
assertions: z4.array(assertionResultRecordSchema2),
|
|
4960
6396
|
cache_saved: savedSchema.optional(),
|
|
4961
6397
|
/** Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
|
|
4962
|
-
inconclusive:
|
|
6398
|
+
inconclusive: z4.enum(ROW_INCONCLUSIVE).optional(),
|
|
4963
6399
|
/** Repeats (`runs` above 1). Optional and additive — a RunResult without it validates unchanged. */
|
|
4964
|
-
attempts:
|
|
4965
|
-
runs:
|
|
4966
|
-
pass_threshold:
|
|
4967
|
-
passed:
|
|
4968
|
-
failed:
|
|
4969
|
-
errored:
|
|
4970
|
-
results:
|
|
4971
|
-
|
|
4972
|
-
output:
|
|
4973
|
-
cached:
|
|
6400
|
+
attempts: z4.object({
|
|
6401
|
+
runs: z4.number(),
|
|
6402
|
+
pass_threshold: z4.number(),
|
|
6403
|
+
passed: z4.number(),
|
|
6404
|
+
failed: z4.number(),
|
|
6405
|
+
errored: z4.number(),
|
|
6406
|
+
results: z4.array(
|
|
6407
|
+
z4.object({
|
|
6408
|
+
output: z4.string().nullable(),
|
|
6409
|
+
cached: z4.boolean(),
|
|
4974
6410
|
usage: usageSchema.optional(),
|
|
4975
|
-
latency_ms:
|
|
6411
|
+
latency_ms: z4.number().optional(),
|
|
4976
6412
|
error: runErrorSchema.optional(),
|
|
4977
|
-
assertions:
|
|
6413
|
+
assertions: z4.array(assertionResultRecordSchema2),
|
|
4978
6414
|
cache_saved: savedSchema.optional()
|
|
4979
6415
|
})
|
|
4980
6416
|
)
|
|
4981
6417
|
}).optional(),
|
|
4982
6418
|
/** The tool loop of an eval with an `mcp` server. Optional and additive — a RunResult without it validates unchanged. */
|
|
4983
|
-
agent:
|
|
4984
|
-
server:
|
|
4985
|
-
tools:
|
|
4986
|
-
|
|
4987
|
-
name:
|
|
4988
|
-
offered:
|
|
4989
|
-
annotations:
|
|
6419
|
+
agent: z4.object({
|
|
6420
|
+
server: z4.string(),
|
|
6421
|
+
tools: z4.array(
|
|
6422
|
+
z4.object({
|
|
6423
|
+
name: z4.string(),
|
|
6424
|
+
offered: z4.boolean(),
|
|
6425
|
+
annotations: z4.record(z4.string(), z4.unknown()).optional()
|
|
4990
6426
|
})
|
|
4991
6427
|
),
|
|
4992
|
-
steps:
|
|
4993
|
-
|
|
4994
|
-
index:
|
|
4995
|
-
text:
|
|
4996
|
-
finish_reason:
|
|
6428
|
+
steps: z4.array(
|
|
6429
|
+
z4.object({
|
|
6430
|
+
index: z4.number(),
|
|
6431
|
+
text: z4.string(),
|
|
6432
|
+
finish_reason: z4.string().optional(),
|
|
4997
6433
|
usage: usageSchema,
|
|
4998
|
-
calls:
|
|
4999
|
-
|
|
5000
|
-
id:
|
|
5001
|
-
name:
|
|
5002
|
-
args:
|
|
5003
|
-
executed:
|
|
5004
|
-
is_error:
|
|
5005
|
-
error_kind:
|
|
5006
|
-
duration_ms:
|
|
5007
|
-
result:
|
|
6434
|
+
calls: z4.array(
|
|
6435
|
+
z4.object({
|
|
6436
|
+
id: z4.string(),
|
|
6437
|
+
name: z4.string(),
|
|
6438
|
+
args: z4.unknown(),
|
|
6439
|
+
executed: z4.boolean(),
|
|
6440
|
+
is_error: z4.boolean(),
|
|
6441
|
+
error_kind: z4.enum(["content", "protocol", "timeout", "not-offered", "bad-arguments"]).optional(),
|
|
6442
|
+
duration_ms: z4.number().optional(),
|
|
6443
|
+
result: z4.object({ text: z4.string(), bytes: z4.number(), truncated: z4.boolean() }).optional()
|
|
5008
6444
|
})
|
|
5009
6445
|
),
|
|
5010
6446
|
/** Optional and additive: the step whose request first offered a changed list. */
|
|
5011
|
-
offered_changed:
|
|
6447
|
+
offered_changed: z4.object({ added: z4.array(z4.string()), removed: z4.array(z4.string()) }).optional()
|
|
5012
6448
|
})
|
|
5013
6449
|
),
|
|
5014
|
-
stop:
|
|
5015
|
-
reason:
|
|
5016
|
-
limit:
|
|
6450
|
+
stop: z4.object({
|
|
6451
|
+
reason: z4.enum(["complete", "limit", "error"]),
|
|
6452
|
+
limit: z4.enum(["max_steps", "max_tool_calls", "max_total_tokens", "timeout_ms", "tool_timeout_ms"]).optional()
|
|
5017
6453
|
}),
|
|
5018
|
-
collection:
|
|
6454
|
+
collection: z4.enum(["complete", "partial"]),
|
|
5019
6455
|
/** Heuristic findings, never a verdict. Optional and additive. */
|
|
5020
|
-
advice:
|
|
5021
|
-
|
|
5022
|
-
type:
|
|
5023
|
-
reason:
|
|
5024
|
-
tool:
|
|
5025
|
-
steps:
|
|
5026
|
-
count:
|
|
5027
|
-
paths:
|
|
6456
|
+
advice: z4.array(
|
|
6457
|
+
z4.object({
|
|
6458
|
+
type: z4.string(),
|
|
6459
|
+
reason: z4.string(),
|
|
6460
|
+
tool: z4.string().optional(),
|
|
6461
|
+
steps: z4.array(z4.number()).optional(),
|
|
6462
|
+
count: z4.number().optional(),
|
|
6463
|
+
paths: z4.array(z4.string()).optional()
|
|
5028
6464
|
})
|
|
5029
6465
|
).optional(),
|
|
5030
|
-
description_overrides:
|
|
6466
|
+
description_overrides: z4.array(z4.object({ tool: z4.string(), sha256: z4.string() })).optional()
|
|
5031
6467
|
}).optional()
|
|
5032
6468
|
});
|
|
5033
|
-
var summarySchema =
|
|
5034
|
-
total:
|
|
5035
|
-
passed:
|
|
5036
|
-
failed:
|
|
5037
|
-
errored:
|
|
6469
|
+
var summarySchema = z4.object({
|
|
6470
|
+
total: z4.number(),
|
|
6471
|
+
passed: z4.number(),
|
|
6472
|
+
failed: z4.number(),
|
|
6473
|
+
errored: z4.number(),
|
|
5038
6474
|
/** Optional and additive — a RunResult written before them validates unchanged. */
|
|
5039
|
-
blocked:
|
|
5040
|
-
skipped:
|
|
5041
|
-
cost_usd:
|
|
5042
|
-
duration_ms:
|
|
5043
|
-
cache:
|
|
5044
|
-
from_cache:
|
|
5045
|
-
from_model:
|
|
5046
|
-
missed:
|
|
5047
|
-
errored:
|
|
5048
|
-
|
|
6475
|
+
blocked: z4.number().optional(),
|
|
6476
|
+
skipped: z4.number().optional(),
|
|
6477
|
+
cost_usd: z4.number(),
|
|
6478
|
+
duration_ms: z4.number(),
|
|
6479
|
+
cache: z4.object({
|
|
6480
|
+
from_cache: z4.number(),
|
|
6481
|
+
from_model: z4.number(),
|
|
6482
|
+
missed: z4.number(),
|
|
6483
|
+
errored: z4.number(),
|
|
6484
|
+
stubbed: z4.number().optional(),
|
|
6485
|
+
saved: z4.object({ input_tokens: z4.number(), output_tokens: z4.number(), cost_usd: z4.number() })
|
|
5049
6486
|
}).optional()
|
|
5050
6487
|
});
|
|
5051
|
-
var evalResultSchema =
|
|
5052
|
-
id:
|
|
5053
|
-
tags:
|
|
5054
|
-
rows:
|
|
5055
|
-
passed:
|
|
6488
|
+
var evalResultSchema = z4.object({
|
|
6489
|
+
id: z4.string(),
|
|
6490
|
+
tags: z4.array(z4.string()),
|
|
6491
|
+
rows: z4.array(rowResultSchema),
|
|
6492
|
+
passed: z4.boolean(),
|
|
5056
6493
|
/** What the eval measured, for the pass-rate gate of `plune diff`. Optional and additive. */
|
|
5057
|
-
measured:
|
|
5058
|
-
runs:
|
|
5059
|
-
rows:
|
|
5060
|
-
rows_hash:
|
|
5061
|
-
assertions_hash:
|
|
5062
|
-
model:
|
|
6494
|
+
measured: z4.object({
|
|
6495
|
+
runs: z4.number(),
|
|
6496
|
+
rows: z4.number(),
|
|
6497
|
+
rows_hash: z4.string(),
|
|
6498
|
+
assertions_hash: z4.string(),
|
|
6499
|
+
model: z4.string().optional()
|
|
5063
6500
|
}).optional(),
|
|
5064
6501
|
/** The type and model of a cell of a multi-model run. Optional and additive. */
|
|
5065
|
-
provider:
|
|
6502
|
+
provider: z4.object({ type: z4.string(), model: z4.string() }).optional(),
|
|
6503
|
+
/** The mark of an eval answered from stubs, kept for the same reason as a row's `stubbed`. */
|
|
6504
|
+
stubs: z4.object({
|
|
6505
|
+
never_called: z4.array(z4.number()),
|
|
6506
|
+
unmatched: z4.array(z4.object({ scope: z4.string(), method: z4.string() }))
|
|
6507
|
+
}).optional(),
|
|
5066
6508
|
/** The link to the eval's trace in your own observability (Langfuse, OTel). Optional and additive; `plune sync` drops one `traceUrlProblem` refuses. */
|
|
5067
|
-
traceUrl:
|
|
6509
|
+
traceUrl: z4.string().optional()
|
|
5068
6510
|
});
|
|
5069
6511
|
var TRACE_URL_MAX = 2048;
|
|
5070
6512
|
function traceUrlProblem(value) {
|
|
@@ -5082,16 +6524,16 @@ function traceUrlProblem(value) {
|
|
|
5082
6524
|
if (parsed2.username !== "" || parsed2.password !== "") return "must carry no user name or password";
|
|
5083
6525
|
return void 0;
|
|
5084
6526
|
}
|
|
5085
|
-
var runResultSchema =
|
|
5086
|
-
schemaVersion:
|
|
5087
|
-
plune_version:
|
|
5088
|
-
started_at:
|
|
5089
|
-
finished_at:
|
|
5090
|
-
config_hash:
|
|
6527
|
+
var runResultSchema = z4.object({
|
|
6528
|
+
schemaVersion: z4.literal(RUN_RESULT_SCHEMA_VERSION),
|
|
6529
|
+
plune_version: z4.string(),
|
|
6530
|
+
started_at: z4.string(),
|
|
6531
|
+
finished_at: z4.string(),
|
|
6532
|
+
config_hash: z4.string(),
|
|
5091
6533
|
/** cli#244. The result of `--dry-run`. Optional and additive — a RunResult without it validates unchanged. */
|
|
5092
|
-
dry_run:
|
|
6534
|
+
dry_run: z4.boolean().optional(),
|
|
5093
6535
|
summary: summarySchema,
|
|
5094
|
-
evals:
|
|
6536
|
+
evals: z4.array(evalResultSchema)
|
|
5095
6537
|
});
|
|
5096
6538
|
function parseRunResult(value) {
|
|
5097
6539
|
return runResultSchema.parse(value);
|
|
@@ -5099,11 +6541,30 @@ function parseRunResult(value) {
|
|
|
5099
6541
|
|
|
5100
6542
|
// src/cli/api-url.ts
|
|
5101
6543
|
init_esm_shims();
|
|
5102
|
-
var
|
|
6544
|
+
var PRODUCTION_API_URL = "https://api.plune.ai";
|
|
6545
|
+
var BETA_API_URL = "https://beta-api.plune.ai";
|
|
6546
|
+
var DEFAULT_API_URL = PRODUCTION_API_URL;
|
|
6547
|
+
var DASHBOARDS = /* @__PURE__ */ new Map([
|
|
6548
|
+
[PRODUCTION_API_URL, "https://app.plune.ai"],
|
|
6549
|
+
[BETA_API_URL, "https://beta.plune.ai"]
|
|
6550
|
+
]);
|
|
5103
6551
|
function resolveApiUrl(explicit) {
|
|
5104
|
-
const raw = explicit
|
|
6552
|
+
const raw = explicit?.trim() || process.env["PLUNE_API_URL"]?.trim() || DEFAULT_API_URL;
|
|
5105
6553
|
return raw.replace(/\/+$/, "");
|
|
5106
6554
|
}
|
|
6555
|
+
function knownApi(apiUrl) {
|
|
6556
|
+
try {
|
|
6557
|
+
const origin = new URL(apiUrl.trim()).origin;
|
|
6558
|
+
return DASHBOARDS.has(origin) ? origin : void 0;
|
|
6559
|
+
} catch {
|
|
6560
|
+
return void 0;
|
|
6561
|
+
}
|
|
6562
|
+
}
|
|
6563
|
+
function tokenRefusedBy(apiUrl = resolveApiUrl()) {
|
|
6564
|
+
const named = `The address that refused it is ${apiUrl}.`;
|
|
6565
|
+
if (knownApi(apiUrl) !== PRODUCTION_API_URL) return named;
|
|
6566
|
+
return `${named} A token from a beta account works only on the beta: run "plune login" with a token from ${DASHBOARDS.get(PRODUCTION_API_URL)}, or set PLUNE_API_URL=${BETA_API_URL} to keep using the beta account.`;
|
|
6567
|
+
}
|
|
5107
6568
|
|
|
5108
6569
|
// src/cli/credentials.ts
|
|
5109
6570
|
init_esm_shims();
|
|
@@ -5223,9 +6684,9 @@ var NotLoggedInError = class extends Error {
|
|
|
5223
6684
|
}
|
|
5224
6685
|
};
|
|
5225
6686
|
var TokenRejectedError = class extends Error {
|
|
5226
|
-
constructor() {
|
|
6687
|
+
constructor(apiUrl = resolveApiUrl()) {
|
|
5227
6688
|
super(
|
|
5228
|
-
|
|
6689
|
+
`Your API token was rejected (revoked or invalid). Run "plune login" with a fresh token. ${tokenRefusedBy(apiUrl)}`
|
|
5229
6690
|
);
|
|
5230
6691
|
this.name = "TokenRejectedError";
|
|
5231
6692
|
}
|
|
@@ -5256,7 +6717,7 @@ function readRun(cwd, file, warn) {
|
|
|
5256
6717
|
const target = file !== void 0 ? path7.resolve(cwd, file) : path7.join(cwd, ".plune", "last-run.json");
|
|
5257
6718
|
let raw;
|
|
5258
6719
|
try {
|
|
5259
|
-
raw =
|
|
6720
|
+
raw = fs7.readFileSync(target, "utf8");
|
|
5260
6721
|
} catch {
|
|
5261
6722
|
throw new SyncFileError(
|
|
5262
6723
|
file !== void 0 ? `Run file not found: ${target}` : 'No run to sync. Run "plune run" first (or pass --file <path>).'
|
|
@@ -5269,11 +6730,18 @@ function readRun(cwd, file, warn) {
|
|
|
5269
6730
|
throw new SyncFileError(`Run file is not valid JSON: ${target}`);
|
|
5270
6731
|
}
|
|
5271
6732
|
dropBadTraceLinks(json, warn);
|
|
6733
|
+
let run;
|
|
5272
6734
|
try {
|
|
5273
|
-
|
|
6735
|
+
run = parseRunResult(json);
|
|
5274
6736
|
} catch {
|
|
5275
6737
|
throw new SyncFileError(`Run file does not match the RunResult schema: ${target}`);
|
|
5276
6738
|
}
|
|
6739
|
+
const stubbed = stubbedEvals(run);
|
|
6740
|
+
if (stubbed.length > 0)
|
|
6741
|
+
throw new SyncFileError(
|
|
6742
|
+
`This run is not uploaded: its evals ${stubbed.join(", ")} were answered from stubs, not by a model. Run them without stubs, or sync a run of the other evals (plune run --only).`
|
|
6743
|
+
);
|
|
6744
|
+
return run;
|
|
5277
6745
|
}
|
|
5278
6746
|
function dropBadTraceLinks(json, warn) {
|
|
5279
6747
|
const evals = json?.evals;
|
|
@@ -5338,7 +6806,7 @@ async function handleSync(deps = {}) {
|
|
|
5338
6806
|
}
|
|
5339
6807
|
if (!res.ok) {
|
|
5340
6808
|
const detail = await safeErrorDetail(res);
|
|
5341
|
-
if (res.status === 401) throw new TokenRejectedError();
|
|
6809
|
+
if (res.status === 401) throw new TokenRejectedError(apiUrl);
|
|
5342
6810
|
throw new SyncHttpError(res.status, detail);
|
|
5343
6811
|
}
|
|
5344
6812
|
const body = await res.json().catch(() => ({}));
|
|
@@ -5636,7 +7104,7 @@ var BUCKET_CODES = /* @__PURE__ */ new Set([
|
|
|
5636
7104
|
|
|
5637
7105
|
// src/reporter-core/fallback.ts
|
|
5638
7106
|
init_esm_shims();
|
|
5639
|
-
import * as
|
|
7107
|
+
import * as fs8 from "fs";
|
|
5640
7108
|
import * as path9 from "path";
|
|
5641
7109
|
var DEFAULT_FALLBACK_PATH = path9.join(".plune", "pending-results.jsonl");
|
|
5642
7110
|
|
|
@@ -5689,12 +7157,12 @@ var TYPE_BY_EXTENSION = {
|
|
|
5689
7157
|
var READ_NOT_KEPT = /* @__PURE__ */ new Set(["application/plune.metadata+json", "application/plune.findings+json"]);
|
|
5690
7158
|
var NAME_MAX = 200;
|
|
5691
7159
|
function nameOf(file) {
|
|
5692
|
-
const
|
|
7160
|
+
const own3 = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : basename3(file.path));
|
|
5693
7161
|
const fileExt = file.path === void 0 ? "" : extname(file.path);
|
|
5694
|
-
const ownExt = extname(
|
|
7162
|
+
const ownExt = extname(own3);
|
|
5695
7163
|
const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
|
|
5696
7164
|
const ext = typed ? ownExt : fileExt;
|
|
5697
|
-
let stem = typed ?
|
|
7165
|
+
let stem = typed ? own3.slice(0, -ownExt.length) : own3;
|
|
5698
7166
|
if (stem.length + ext.length > NAME_MAX) {
|
|
5699
7167
|
stem = stem.slice(0, Math.max(0, NAME_MAX - ext.length));
|
|
5700
7168
|
if (/[\uD800-\uDBFF]$/.test(stem)) stem = stem.slice(0, -1);
|
|
@@ -5832,9 +7300,9 @@ function fileSender(options) {
|
|
|
5832
7300
|
if (out.ok) countsOf(kind).uploaded += 1;
|
|
5833
7301
|
else failed(job, out.detail || out.kind);
|
|
5834
7302
|
}
|
|
5835
|
-
async function uploadToBucket(job, size,
|
|
7303
|
+
async function uploadToBucket(job, size, first2) {
|
|
5836
7304
|
const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
|
|
5837
|
-
let link =
|
|
7305
|
+
let link = first2;
|
|
5838
7306
|
for (let renewed = false; ; ) {
|
|
5839
7307
|
const put = await client.put(link.url, link.headers, source);
|
|
5840
7308
|
if (put.ok) break;
|
|
@@ -5847,8 +7315,8 @@ function fileSender(options) {
|
|
|
5847
7315
|
link = fresh;
|
|
5848
7316
|
}
|
|
5849
7317
|
requests += 1;
|
|
5850
|
-
const
|
|
5851
|
-
if (!
|
|
7318
|
+
const done2 = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
|
|
7319
|
+
if (!done2.ok) return failedToBucket(job, codeOf2(done2));
|
|
5852
7320
|
countsOf(job.kind).uploaded += 1;
|
|
5853
7321
|
}
|
|
5854
7322
|
let free = uploadsAtOnce;
|
|
@@ -6014,9 +7482,9 @@ function fileSender(options) {
|
|
|
6014
7482
|
const toComplete = [];
|
|
6015
7483
|
await Promise.all(
|
|
6016
7484
|
puts.map(
|
|
6017
|
-
({ s, link:
|
|
7485
|
+
({ s, link: first2 }) => gated(async () => {
|
|
6018
7486
|
const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
|
|
6019
|
-
let link =
|
|
7487
|
+
let link = first2;
|
|
6020
7488
|
for (let renewed = false; ; ) {
|
|
6021
7489
|
const put = await client.put(link.url, link.headers, source);
|
|
6022
7490
|
if (put.ok) break;
|
|
@@ -6202,7 +7670,7 @@ function fileSender(options) {
|
|
|
6202
7670
|
|
|
6203
7671
|
// src/cli/commands/cairn-artifact.ts
|
|
6204
7672
|
init_esm_shims();
|
|
6205
|
-
import * as
|
|
7673
|
+
import * as fs9 from "fs/promises";
|
|
6206
7674
|
import * as path10 from "path";
|
|
6207
7675
|
|
|
6208
7676
|
// src/importers/trace-url.ts
|
|
@@ -7765,14 +9233,14 @@ var NoCairnRunsError = class extends Error {
|
|
|
7765
9233
|
}
|
|
7766
9234
|
};
|
|
7767
9235
|
async function findLatestCairnRun(runsDir = "runs") {
|
|
7768
|
-
const entries = await
|
|
9236
|
+
const entries = await fs9.readdir(runsDir, { withFileTypes: true }).catch(() => null);
|
|
7769
9237
|
if (entries === null) throw new NoCairnRunsError(runsDir);
|
|
7770
9238
|
let newest;
|
|
7771
9239
|
for (const entry of entries) {
|
|
7772
9240
|
if (!entry.isDirectory()) continue;
|
|
7773
9241
|
const dir = path10.join(runsDir, entry.name);
|
|
7774
9242
|
try {
|
|
7775
|
-
const report = await
|
|
9243
|
+
const report = await fs9.lstat(path10.join(dir, "report.json"));
|
|
7776
9244
|
if (!report.isFile()) continue;
|
|
7777
9245
|
if (newest === void 0 || report.mtimeMs > newest.at) {
|
|
7778
9246
|
newest = { dir, at: report.mtimeMs };
|
|
@@ -7823,13 +9291,13 @@ var CairnEvidenceAmbiguousError = class extends Error {
|
|
|
7823
9291
|
};
|
|
7824
9292
|
var asRecord = (v) => typeof v === "object" && v !== null ? v : {};
|
|
7825
9293
|
var str = (v, fallback = "") => typeof v === "string" && v !== "" ? v : fallback;
|
|
7826
|
-
var
|
|
9294
|
+
var own2 = (rec, key) => Object.hasOwn(rec, key) ? rec[key] : void 0;
|
|
7827
9295
|
var MAX_ARTIFACT_BYTES = 32 * 1024 * 1024;
|
|
7828
9296
|
var MAX_MCP_CASES = 5e3;
|
|
7829
9297
|
async function checkSize(dir, file) {
|
|
7830
9298
|
let size;
|
|
7831
9299
|
try {
|
|
7832
|
-
const st = await
|
|
9300
|
+
const st = await fs9.stat(path10.join(dir, file));
|
|
7833
9301
|
if (!st.isFile()) throw new CairnArtifactShapeError(file, "", "is not a regular file");
|
|
7834
9302
|
size = st.size;
|
|
7835
9303
|
} catch (e) {
|
|
@@ -7847,20 +9315,20 @@ async function checkSize(dir, file) {
|
|
|
7847
9315
|
}
|
|
7848
9316
|
async function readJson(file) {
|
|
7849
9317
|
try {
|
|
7850
|
-
return JSON.parse(await
|
|
9318
|
+
return JSON.parse(await fs9.readFile(file, "utf8"));
|
|
7851
9319
|
} catch {
|
|
7852
9320
|
return void 0;
|
|
7853
9321
|
}
|
|
7854
9322
|
}
|
|
7855
9323
|
var ARGS_CHARS2 = 200;
|
|
7856
|
-
var
|
|
9324
|
+
var SECRET_NAME2 = /key|token|secret|password|passwd|auth|cookie|credential/i;
|
|
7857
9325
|
var maskNamed = (v, depth = 0) => {
|
|
7858
9326
|
if (depth > 16) return "[deep]";
|
|
7859
9327
|
if (Array.isArray(v)) return v.slice(0, 50).map((x) => maskNamed(x, depth + 1));
|
|
7860
9328
|
if (typeof v === "object" && v !== null) {
|
|
7861
9329
|
const out = {};
|
|
7862
9330
|
for (const [k, x] of Object.entries(v).slice(0, 50)) {
|
|
7863
|
-
out[k] =
|
|
9331
|
+
out[k] = SECRET_NAME2.test(k) ? "***" : maskNamed(x, depth + 1);
|
|
7864
9332
|
}
|
|
7865
9333
|
return out;
|
|
7866
9334
|
}
|
|
@@ -7887,7 +9355,7 @@ async function readMcpEvidence(dir, states) {
|
|
|
7887
9355
|
if (!await checkSize(dir, file)) return void 0;
|
|
7888
9356
|
let raw;
|
|
7889
9357
|
try {
|
|
7890
|
-
raw = JSON.parse(await
|
|
9358
|
+
raw = JSON.parse(await fs9.readFile(path10.join(dir, file), "utf8"));
|
|
7891
9359
|
} catch {
|
|
7892
9360
|
throw new CairnArtifactShapeError(file, "", "is not valid JSON");
|
|
7893
9361
|
}
|
|
@@ -7901,7 +9369,7 @@ async function readMcpEvidence(dir, states) {
|
|
|
7901
9369
|
throw new CairnArtifactShapeError(file, `[${i}]`, "must be an object");
|
|
7902
9370
|
}
|
|
7903
9371
|
const rec = item;
|
|
7904
|
-
const id =
|
|
9372
|
+
const id = own2(rec, "stableId");
|
|
7905
9373
|
if (typeof id !== "string" || !states.has(id)) {
|
|
7906
9374
|
throw new CairnArtifactShapeError(
|
|
7907
9375
|
file,
|
|
@@ -7912,18 +9380,18 @@ async function readMcpEvidence(dir, states) {
|
|
|
7912
9380
|
if (byId.has(id)) {
|
|
7913
9381
|
throw new CairnArtifactShapeError(file, `[${i}].stableId`, "appears more than once");
|
|
7914
9382
|
}
|
|
7915
|
-
if (
|
|
9383
|
+
if (own2(rec, "state") !== states.get(id)) {
|
|
7916
9384
|
throw new CairnArtifactShapeError(
|
|
7917
9385
|
file,
|
|
7918
9386
|
`[${i}].state`,
|
|
7919
9387
|
"does not agree with the state in report.json"
|
|
7920
9388
|
);
|
|
7921
9389
|
}
|
|
7922
|
-
const request =
|
|
9390
|
+
const request = own2(rec, "request");
|
|
7923
9391
|
if (request !== void 0 && typeof request !== "string") {
|
|
7924
9392
|
throw new CairnArtifactShapeError(file, `[${i}].request`, "must be text");
|
|
7925
9393
|
}
|
|
7926
|
-
const durationMs =
|
|
9394
|
+
const durationMs = own2(rec, "durationMs");
|
|
7927
9395
|
if (durationMs !== void 0 && typeof durationMs !== "number") {
|
|
7928
9396
|
throw new CairnArtifactShapeError(file, `[${i}].durationMs`, "must be a number");
|
|
7929
9397
|
}
|
|
@@ -7941,7 +9409,7 @@ function expectedOfMcp(type, adversarial) {
|
|
|
7941
9409
|
return adversarial ? "The server rejects the call, or handles the value without harm." : "The server rejects the call: it does not act on a value the tool's inputSchema forbids.";
|
|
7942
9410
|
}
|
|
7943
9411
|
async function casesFromMcp(dir, report) {
|
|
7944
|
-
const list2 =
|
|
9412
|
+
const list2 = own2(report, "cases");
|
|
7945
9413
|
if (!Array.isArray(list2))
|
|
7946
9414
|
throw new CairnArtifactShapeError("report.json", "cases", "must be a list");
|
|
7947
9415
|
if (list2.length > MAX_MCP_CASES) {
|
|
@@ -7959,7 +9427,7 @@ async function casesFromMcp(dir, report) {
|
|
|
7959
9427
|
}
|
|
7960
9428
|
const c = raw;
|
|
7961
9429
|
const text = (key) => {
|
|
7962
|
-
const v =
|
|
9430
|
+
const v = own2(c, key);
|
|
7963
9431
|
if (typeof v !== "string" || v === "") {
|
|
7964
9432
|
throw new CairnArtifactShapeError("report.json", `${at}.${key}`, "must be text");
|
|
7965
9433
|
}
|
|
@@ -7989,14 +9457,14 @@ async function casesFromMcp(dir, report) {
|
|
|
7989
9457
|
}
|
|
7990
9458
|
states.set(stableId, state);
|
|
7991
9459
|
const kind = type;
|
|
7992
|
-
const technique =
|
|
9460
|
+
const technique = own2(c, "technique");
|
|
7993
9461
|
return {
|
|
7994
9462
|
stableId,
|
|
7995
9463
|
name,
|
|
7996
9464
|
tool,
|
|
7997
9465
|
type: kind,
|
|
7998
9466
|
state,
|
|
7999
|
-
adversarial:
|
|
9467
|
+
adversarial: own2(c, "adversarialStyle") !== void 0,
|
|
8000
9468
|
...typeof technique === "string" ? { technique } : {}
|
|
8001
9469
|
};
|
|
8002
9470
|
});
|
|
@@ -8032,7 +9500,7 @@ function casesFromDesign(report, notes) {
|
|
|
8032
9500
|
const c = asRecord(raw);
|
|
8033
9501
|
const steps = (Array.isArray(c["steps"]) ? c["steps"] : []).map((s) => str(s)).filter((s) => s !== "");
|
|
8034
9502
|
const title = str(c["title"], "untitled case");
|
|
8035
|
-
const link =
|
|
9503
|
+
const link = own2(c, "traceUrl") ?? void 0;
|
|
8036
9504
|
const said = [];
|
|
8037
9505
|
const traceUrl = traceUrlOf(link, title, said);
|
|
8038
9506
|
if (said.length > 0) {
|
|
@@ -8102,11 +9570,11 @@ async function readCairnRun(dir, deps = {}) {
|
|
|
8102
9570
|
}
|
|
8103
9571
|
cases = casesFromApi(report, verdicts);
|
|
8104
9572
|
} else if (mode === "mcp") {
|
|
8105
|
-
cases =
|
|
9573
|
+
cases = own2(report, "cases") === void 0 && Array.isArray(own2(report, "testCases")) ? casesFromDesign(report, deps.notes ?? []) : await casesFromMcp(dir, report);
|
|
8106
9574
|
} else {
|
|
8107
9575
|
cases = casesFromDesign(report, deps.notes ?? []);
|
|
8108
9576
|
}
|
|
8109
|
-
const tokens =
|
|
9577
|
+
const tokens = own2(asRecord(own2(report, "cost")), "totalTokens");
|
|
8110
9578
|
return {
|
|
8111
9579
|
schemaVersion: INGEST_SCHEMA_VERSION,
|
|
8112
9580
|
run: {
|
|
@@ -8124,7 +9592,7 @@ var clip = (s) => s.slice(0, DECLARED.text).replace(/[\uD800-\uDBFF]$/, "");
|
|
|
8124
9592
|
async function readCairnSessionFiles(dir) {
|
|
8125
9593
|
const raw = await readJson(path10.join(dir, "screencasts", "screencasts.json"));
|
|
8126
9594
|
if (!Array.isArray(raw)) return void 0;
|
|
8127
|
-
const root = await
|
|
9595
|
+
const root = await fs9.realpath(dir).catch(() => path10.resolve(dir));
|
|
8128
9596
|
const within = (p) => {
|
|
8129
9597
|
const rel = path10.relative(root, p);
|
|
8130
9598
|
return rel !== "" && !rel.startsWith("..") && !path10.isAbsolute(rel);
|
|
@@ -8133,10 +9601,10 @@ async function readCairnSessionFiles(dir) {
|
|
|
8133
9601
|
const inside = async (p) => {
|
|
8134
9602
|
if (typeof p !== "string" || p === "") return void 0;
|
|
8135
9603
|
const abs = path10.resolve(root, p);
|
|
8136
|
-
const real = await
|
|
9604
|
+
const real = await fs9.realpath(abs).catch(() => void 0);
|
|
8137
9605
|
if (within(abs) && (real === void 0 || within(real))) {
|
|
8138
9606
|
const file = real ?? abs;
|
|
8139
|
-
const size = await
|
|
9607
|
+
const size = await fs9.stat(file).then((s) => s.size, () => void 0);
|
|
8140
9608
|
return { path: file, rel: path10.relative(root, abs).split(path10.sep).join("/"), ...size !== void 0 ? { size } : {} };
|
|
8141
9609
|
}
|
|
8142
9610
|
outside += 1;
|
|
@@ -8149,11 +9617,11 @@ async function readCairnSessionFiles(dir) {
|
|
|
8149
9617
|
const rec = asRecord(entry);
|
|
8150
9618
|
const found = [];
|
|
8151
9619
|
for (const kind of ["video", "trace"]) {
|
|
8152
|
-
const at = await inside(
|
|
9620
|
+
const at = await inside(own2(rec, kind));
|
|
8153
9621
|
if (at !== void 0) found.push({ file: { path: at.path, ...at.size !== void 0 ? { size: at.size } : {} }, rel: at.rel, kind });
|
|
8154
9622
|
}
|
|
8155
9623
|
if (found.length === 0) continue;
|
|
8156
|
-
const stableId =
|
|
9624
|
+
const stableId = own2(rec, "stableId");
|
|
8157
9625
|
if (typeof stableId !== "string" || stableId === "") {
|
|
8158
9626
|
unmapped += 1;
|
|
8159
9627
|
continue;
|
|
@@ -8161,7 +9629,7 @@ async function readCairnSessionFiles(dir) {
|
|
|
8161
9629
|
byCase.set(stableId, [...byCase.get(stableId) ?? [], ...found.map((f) => f.file)]);
|
|
8162
9630
|
const declared = screencasts.get(stableId) ?? [];
|
|
8163
9631
|
const keys = new Set(declared.flatMap((s) => s.files.map((f) => f.key)));
|
|
8164
|
-
const title = clip(str(
|
|
9632
|
+
const title = clip(str(own2(rec, "test")));
|
|
8165
9633
|
const files = found.filter((f) => {
|
|
8166
9634
|
if ((f.file.size ?? 0) < 1 || f.rel.length > DECLARED.text || path10.basename(f.file.path).length > DECLARED.name || keys.has(f.rel)) return false;
|
|
8167
9635
|
keys.add(f.rel);
|
|
@@ -8169,14 +9637,14 @@ async function readCairnSessionFiles(dir) {
|
|
|
8169
9637
|
});
|
|
8170
9638
|
if (title === "" || files.length === 0 || declared.length >= DECLARED.perCase) continue;
|
|
8171
9639
|
for (const f of files) f.file.key = f.rel;
|
|
8172
|
-
const timing =
|
|
9640
|
+
const timing = own2(rec, "timing");
|
|
8173
9641
|
declared.push({
|
|
8174
9642
|
title,
|
|
8175
9643
|
...timing === "trace" || timing === "estimated" ? { timing } : {},
|
|
8176
|
-
chapters: (Array.isArray(
|
|
9644
|
+
chapters: (Array.isArray(own2(rec, "chapters")) ? own2(rec, "chapters") : []).flatMap((c) => {
|
|
8177
9645
|
const chapter = asRecord(c);
|
|
8178
|
-
const t = clip(str(
|
|
8179
|
-
const atMs =
|
|
9646
|
+
const t = clip(str(own2(chapter, "title")));
|
|
9647
|
+
const atMs = own2(chapter, "atMs");
|
|
8180
9648
|
return t !== "" && Number.isInteger(atMs) && atMs >= 0 ? [{ title: t, atMs }] : [];
|
|
8181
9649
|
}).slice(0, DECLARED.chapters),
|
|
8182
9650
|
files: files.map((f) => ({ key: f.rel, name: path10.basename(f.file.path), kind: f.kind, size: f.file.size }))
|
|
@@ -8194,8 +9662,8 @@ var IngestNotLoggedInError = class extends Error {
|
|
|
8194
9662
|
}
|
|
8195
9663
|
};
|
|
8196
9664
|
var IngestTokenRejectedError = class extends Error {
|
|
8197
|
-
constructor() {
|
|
8198
|
-
super(
|
|
9665
|
+
constructor(apiUrl = resolveApiUrl()) {
|
|
9666
|
+
super(`Your API token was rejected (401). Run "plune login" again with a fresh token. ${tokenRefusedBy(apiUrl)}`);
|
|
8199
9667
|
this.name = "IngestTokenRejectedError";
|
|
8200
9668
|
}
|
|
8201
9669
|
};
|
|
@@ -8391,7 +9859,7 @@ async function handleIngest(deps) {
|
|
|
8391
9859
|
}
|
|
8392
9860
|
if (!res.ok) {
|
|
8393
9861
|
const detail = await safeErrorDetail2(res);
|
|
8394
|
-
if (res.status === 401) throw new IngestTokenRejectedError();
|
|
9862
|
+
if (res.status === 401) throw new IngestTokenRejectedError(apiUrl);
|
|
8395
9863
|
throw new IngestHttpError(res.status, detail);
|
|
8396
9864
|
}
|
|
8397
9865
|
const body = await res.json().catch(() => ({}));
|