@plune-ai/cli 0.34.5 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -5,6 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
8
11
  var __export = (target, all) => {
9
12
  for (var name in all)
10
13
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -27,6 +30,895 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
30
  ));
28
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
32
 
33
+ // node_modules/.pnpm/tsup@8.5.1_postcss@8.5.15_tsx@4.22.4_typescript@5.9.3_yaml@2.9.0/node_modules/tsup/assets/cjs_shims.js
34
+ var getImportMetaUrl, importMetaUrl;
35
+ var init_cjs_shims = __esm({
36
+ "node_modules/.pnpm/tsup@8.5.1_postcss@8.5.15_tsx@4.22.4_typescript@5.9.3_yaml@2.9.0/node_modules/tsup/assets/cjs_shims.js"() {
37
+ "use strict";
38
+ getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
+ importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
40
+ }
41
+ });
42
+
43
+ // src/reporter-core/failure-detail.ts
44
+ function machineless(raw, repoRoot, home) {
45
+ let text = (0, import_node_util.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
46
+ const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
47
+ if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
48
+ const own = pathIn(home);
49
+ if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
50
+ if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
51
+ return text;
52
+ }
53
+ function pathIn(path9) {
54
+ const parts = path9.split(/[\\/]+/);
55
+ while (parts.length > 1 && parts.at(-1) === "") parts.pop();
56
+ if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
57
+ const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
58
+ const escaped = /^\/(?!\/)/.test(path9) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
59
+ const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
60
+ return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
61
+ }
62
+ var import_node_fs, import_node_os, import_node_path, import_node_util, printable, PATH_START, HEADLINE_LIMIT, ANY_HOME;
63
+ var init_failure_detail = __esm({
64
+ "src/reporter-core/failure-detail.ts"() {
65
+ "use strict";
66
+ init_cjs_shims();
67
+ import_node_fs = require("fs");
68
+ import_node_os = require("os");
69
+ import_node_path = require("path");
70
+ import_node_util = require("util");
71
+ printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "?");
72
+ PATH_START = "(?<![\\w.~%/\\\\-])";
73
+ HEADLINE_LIMIT = 8 * 1024;
74
+ ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
75
+ }
76
+ });
77
+
78
+ // src/mcp-testing/exit-codes.ts
79
+ var MCP_EXIT;
80
+ var init_exit_codes = __esm({
81
+ "src/mcp-testing/exit-codes.ts"() {
82
+ "use strict";
83
+ init_cjs_shims();
84
+ MCP_EXIT = { ok: 0, violations: 1, usage: 2, unmeasured: 3 };
85
+ }
86
+ });
87
+
88
+ // src/mcp-testing/connect/journal.ts
89
+ function openJournal(path9, redact) {
90
+ if (path9 === void 0) return NONE;
91
+ const fd = (0, import_node_fs2.openSync)(path9, "w", 384);
92
+ if (process.platform !== "win32") (0, import_node_fs2.fchmodSync)(fd, 384);
93
+ const start = import_node_perf_hooks.performance.now();
94
+ let closed = false;
95
+ return {
96
+ write(dir, fields) {
97
+ if (closed) return;
98
+ const dtMs = Math.round((import_node_perf_hooks.performance.now() - start) * 1e3) / 1e3;
99
+ const line = {
100
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
101
+ dtMs,
102
+ dir,
103
+ ...redact.value(fields)
104
+ };
105
+ (0, import_node_fs2.writeSync)(fd, JSON.stringify(line) + "\n");
106
+ },
107
+ close() {
108
+ if (closed) return;
109
+ closed = true;
110
+ (0, import_node_fs2.closeSync)(fd);
111
+ }
112
+ };
113
+ }
114
+ var import_node_fs2, import_node_perf_hooks, NONE;
115
+ var init_journal = __esm({
116
+ "src/mcp-testing/connect/journal.ts"() {
117
+ "use strict";
118
+ init_cjs_shims();
119
+ import_node_fs2 = require("fs");
120
+ import_node_perf_hooks = require("perf_hooks");
121
+ NONE = { write: () => {
122
+ }, close: () => {
123
+ } };
124
+ }
125
+ });
126
+
127
+ // src/mcp-testing/connect/processes.ts
128
+ function parseProcessTable(text) {
129
+ return text.split(/\r?\n/).flatMap((line) => {
130
+ const [pid, ppid, ...started] = line.trim().split(/\s+/);
131
+ const proc = { pid: Number(pid), ppid: Number(ppid), started: started.join(" ") };
132
+ return Number.isInteger(proc.pid) && Number.isInteger(proc.ppid) && proc.started !== "" ? [proc] : [];
133
+ });
134
+ }
135
+ function processTable() {
136
+ if (process.platform === "win32") {
137
+ const out2 = (0, import_node_child_process.spawnSync)(
138
+ "powershell.exe",
139
+ ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_TABLE],
140
+ {
141
+ encoding: "utf8",
142
+ windowsHide: true,
143
+ timeout: 15e3,
144
+ stdio: ["ignore", "pipe", "ignore"]
145
+ }
146
+ );
147
+ return parseProcessTable(out2.stdout ?? "");
148
+ }
149
+ if (process.platform === "linux") {
150
+ return (0, import_node_fs3.readdirSync)("/proc").flatMap((name) => {
151
+ if (!/^\d+$/.test(name)) return [];
152
+ try {
153
+ const stat = (0, import_node_fs3.readFileSync)(`/proc/${name}/stat`, "utf8");
154
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
155
+ return parseProcessTable(`${name} ${fields[1]} ${fields[19]}`);
156
+ } catch {
157
+ return [];
158
+ }
159
+ });
160
+ }
161
+ const out = (0, import_node_child_process.spawnSync)("ps", ["-A", "-o", "pid=,ppid=,lstart="], {
162
+ encoding: "utf8",
163
+ timeout: 15e3
164
+ });
165
+ return parseProcessTable(out.stdout ?? "");
166
+ }
167
+ function readTable() {
168
+ try {
169
+ return processTable();
170
+ } catch {
171
+ return [];
172
+ }
173
+ }
174
+ function descendantsOf(root) {
175
+ const table = readTable();
176
+ const startOf = new Map(table.map((p) => [p.pid, Number(p.started)]));
177
+ const found = [];
178
+ const queue = [root];
179
+ while (queue.length > 0) {
180
+ const parent = queue.shift();
181
+ for (const p of table) {
182
+ if (p.ppid !== parent || p.pid === parent || found.some((f) => f.pid === p.pid)) continue;
183
+ if (Number(p.started) < (startOf.get(parent) ?? 0)) continue;
184
+ found.push(p);
185
+ queue.push(p.pid);
186
+ }
187
+ }
188
+ return found;
189
+ }
190
+ function survivors(noted, now) {
191
+ const current = new Set(now.map((p) => `${p.pid} ${p.started}`));
192
+ return noted.filter((p) => current.has(`${p.pid} ${p.started}`)).map((p) => p.pid);
193
+ }
194
+ function killAll(pids) {
195
+ for (const pid of pids) {
196
+ try {
197
+ process.kill(pid, "SIGKILL");
198
+ } catch {
199
+ }
200
+ }
201
+ }
202
+ function killSurvivors(noted) {
203
+ if (noted.length > 0) killAll(survivors(noted, readTable()));
204
+ }
205
+ function track(session) {
206
+ if (open.size === 0) {
207
+ process.on("SIGINT", onSignal);
208
+ process.on("SIGTERM", onSignal);
209
+ process.on("exit", onExit);
210
+ }
211
+ open.add(session);
212
+ return () => {
213
+ if (!open.delete(session) || open.size > 0) return;
214
+ process.off("SIGINT", onSignal);
215
+ process.off("SIGTERM", onSignal);
216
+ process.off("exit", onExit);
217
+ };
218
+ }
219
+ async function closeAllSessions() {
220
+ await Promise.all([...open].map((session) => session.close()));
221
+ }
222
+ var import_node_child_process, import_node_fs3, WINDOWS_TABLE, open, interrupted, onSignal, onExit;
223
+ var init_processes = __esm({
224
+ "src/mcp-testing/connect/processes.ts"() {
225
+ "use strict";
226
+ init_cjs_shims();
227
+ import_node_child_process = require("child_process");
228
+ import_node_fs3 = require("fs");
229
+ WINDOWS_TABLE = 'Get-CimInstance Win32_Process | ForEach-Object { try { "{0} {1} {2}" -f $_.ProcessId, $_.ParentProcessId, $_.CreationDate.ToFileTimeUtc() } catch {} }';
230
+ open = /* @__PURE__ */ new Set();
231
+ interrupted = false;
232
+ onSignal = (signal) => {
233
+ const code = signal === "SIGINT" ? 130 : 143;
234
+ if (interrupted) {
235
+ for (const session of open) session.killNow();
236
+ process.exit(code);
237
+ }
238
+ interrupted = true;
239
+ void closeAllSessions().finally(() => process.exit(code));
240
+ };
241
+ onExit = () => {
242
+ for (const session of open) session.killNow();
243
+ };
244
+ }
245
+ });
246
+
247
+ // src/mcp-testing/connect/redact.ts
248
+ function maskUrl(raw) {
249
+ let url;
250
+ try {
251
+ url = new URL(raw);
252
+ } catch {
253
+ return raw;
254
+ }
255
+ if (url.username !== "") url.username = MASK;
256
+ if (url.password !== "") url.password = MASK;
257
+ for (const name of [...url.searchParams.keys()])
258
+ if (SECRET_QUERY.has(name.toLowerCase())) url.searchParams.set(name, MASK);
259
+ return url.href.replaceAll("%2A%2A%2A", MASK);
260
+ }
261
+ function secretsOf(target) {
262
+ const secrets = { values: [], named: [], urls: [] };
263
+ if (target.kind === "stdio") {
264
+ for (const value of Object.values(target.env)) secrets.values.push(value);
265
+ for (const arg of target.args) secrets.values.push(arg);
266
+ return secrets;
267
+ }
268
+ for (const value of Object.values(target.headers)) {
269
+ secrets.values.push(value);
270
+ const [scheme, credentials, ...rest] = value.trim().split(/\s+/);
271
+ if (credentials === void 0 || rest.length > 0) continue;
272
+ secrets.values.push(credentials);
273
+ if (scheme?.toLowerCase() !== "basic") continue;
274
+ const pair = Buffer.from(credentials, "base64").toString("utf8");
275
+ const colon = pair.indexOf(":");
276
+ if (colon < 0) continue;
277
+ secrets.values.push(pair, pair.slice(0, colon));
278
+ secrets.named.push(pair.slice(colon + 1));
279
+ }
280
+ let url;
281
+ try {
282
+ url = new URL(target.url);
283
+ } catch {
284
+ return secrets;
285
+ }
286
+ secrets.values.push(url.username, decoded(url.username));
287
+ secrets.named.push(url.password, decoded(url.password));
288
+ for (const [name, value] of rawQuery(url.search)) {
289
+ if (SECRET_QUERY.has(decoded(name).toLowerCase()))
290
+ secrets.named.push(value, decoded(value.replaceAll("+", " ")));
291
+ }
292
+ for (const [name, value] of url.searchParams)
293
+ if (SECRET_QUERY.has(name.toLowerCase())) secrets.named.push(value);
294
+ secrets.urls.push(target.url, url.href, url.href.replace(/\/$/, ""));
295
+ return secrets;
296
+ }
297
+ function createRedactor(secrets, opts = {}) {
298
+ const forms = /* @__PURE__ */ new Set();
299
+ const add = (secret) => {
300
+ forms.add(secret);
301
+ forms.add(encodeURIComponent(secret));
302
+ forms.add(JSON.stringify(secret).slice(1, -1));
303
+ };
304
+ for (const secret of secrets) if (secret.length >= MIN_SECRET_LENGTH) add(secret);
305
+ for (const secret of opts.named ?? []) if (secret !== "") add(secret);
306
+ const longestFirst = (items) => [...new Set(items)].sort((a, b) => b.length - a.length);
307
+ const ordered = longestFirst(forms);
308
+ const urls = longestFirst(opts.url?.raw ?? []).filter((raw) => raw !== "");
309
+ const text = (input) => ordered.reduce(
310
+ (out, secret) => out.replaceAll(secret, MASK),
311
+ urls.reduce((out, raw) => out.replaceAll(raw, opts.url.masked), input)
312
+ );
313
+ const value = (input, depth = 0) => {
314
+ if (typeof input === "string") return text(input);
315
+ if (input === null || typeof input !== "object") return input;
316
+ if (depth >= MAX_DEPTH) return "[cut: too deep]";
317
+ if (Array.isArray(input)) return input.map((item) => value(item, depth + 1));
318
+ return Object.fromEntries(
319
+ Object.entries(input).map(([k, v]) => [text(k), value(v, depth + 1)])
320
+ );
321
+ };
322
+ return { text, value: (input) => value(input) };
323
+ }
324
+ function redactorFor(target) {
325
+ const { values, named, urls } = secretsOf(target);
326
+ return createRedactor(values, {
327
+ named,
328
+ ...target.kind === "stdio" ? {} : { url: { raw: urls, masked: maskUrl(target.url) } }
329
+ });
330
+ }
331
+ function describeTarget(target, redact) {
332
+ const masked = (entries, secret) => Object.fromEntries(
333
+ Object.entries(entries).map(([name, value]) => [
334
+ name,
335
+ secret(name) ? MASK : redact.text(value)
336
+ ])
337
+ );
338
+ if (target.kind === "stdio") {
339
+ return {
340
+ transport: "stdio",
341
+ command: redact.text(target.command),
342
+ args: target.args.map(redact.text),
343
+ env: masked(target.env, isSecretEnv),
344
+ ...target.cwd !== void 0 ? { cwd: target.cwd } : {}
345
+ };
346
+ }
347
+ return {
348
+ transport: target.kind,
349
+ url: redact.text(maskUrl(target.url)),
350
+ headers: masked(target.headers, isSecretHeader)
351
+ };
352
+ }
353
+ var MASK, MIN_SECRET_LENGTH, MAX_DEPTH, SECRET_HEADERS, SECRET_HEADER_PART, SECRET_ENV_PART, SECRET_QUERY, isSecretHeader, isSecretEnv, decoded, rawQuery;
354
+ var init_redact = __esm({
355
+ "src/mcp-testing/connect/redact.ts"() {
356
+ "use strict";
357
+ init_cjs_shims();
358
+ MASK = "***";
359
+ MIN_SECRET_LENGTH = 8;
360
+ MAX_DEPTH = 64;
361
+ SECRET_HEADERS = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie"]);
362
+ SECRET_HEADER_PART = /key|token|secret|auth/i;
363
+ SECRET_ENV_PART = /KEY|TOKEN|SECRET|PASSWORD/i;
364
+ SECRET_QUERY = /* @__PURE__ */ new Set(["token", "key", "secret", "password", "api_key", "access_token"]);
365
+ isSecretHeader = (name) => SECRET_HEADERS.has(name.toLowerCase()) || SECRET_HEADER_PART.test(name);
366
+ isSecretEnv = (name) => SECRET_ENV_PART.test(name);
367
+ decoded = (text) => {
368
+ try {
369
+ return decodeURIComponent(text);
370
+ } catch {
371
+ return text;
372
+ }
373
+ };
374
+ rawQuery = (search) => search.slice(1).split("&").filter((pair) => pair !== "").map((pair) => {
375
+ const eq = pair.indexOf("=");
376
+ return eq < 0 ? [pair, ""] : [pair.slice(0, eq), pair.slice(eq + 1)];
377
+ });
378
+ }
379
+ });
380
+
381
+ // src/mcp-testing/connect/session.ts
382
+ var session_exports = {};
383
+ __export(session_exports, {
384
+ ConnectError: () => ConnectError,
385
+ STDIO_MESSAGE_LIMIT: () => STDIO_MESSAGE_LIMIT,
386
+ closeAllSessions: () => closeAllSessions,
387
+ openSession: () => openSession
388
+ });
389
+ function answers(frame, id) {
390
+ if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
391
+ const f = frame;
392
+ if (!("result" in f) && !("error" in f)) return false;
393
+ return id === null ? "error" in f && (f["id"] === null || f["id"] === void 0) : f["id"] === id;
394
+ }
395
+ function fromEventStream(text, id) {
396
+ for (const line of text.split(/\r?\n/)) {
397
+ if (!line.startsWith("data:")) continue;
398
+ const frame = parsed(line.slice(5).trim());
399
+ if (answers(frame, id)) return frame;
400
+ }
401
+ return void 0;
402
+ }
403
+ function createTransport(target) {
404
+ if (target.kind === "stdio") {
405
+ return new import_stdio.StdioClientTransport({
406
+ command: target.command,
407
+ args: target.args,
408
+ env: target.env,
409
+ stderr: "pipe",
410
+ maxBufferSize: STDIO_MESSAGE_LIMIT,
411
+ ...target.cwd !== void 0 ? { cwd: target.cwd } : {}
412
+ });
413
+ }
414
+ const options = {
415
+ requestInit: { headers: target.headers },
416
+ redirectPolicy: "same-origin"
417
+ };
418
+ return target.kind === "sse" ? new import_client.SSEClientTransport(new URL(target.url), options) : new import_client.StreamableHTTPClientTransport(new URL(target.url), options);
419
+ }
420
+ function tap(transport, journal, on) {
421
+ const send = transport.send.bind(transport);
422
+ transport.send = (message, options) => {
423
+ journal.write("out", { frame: message });
424
+ on.frame("out", message);
425
+ return send(message, options);
426
+ };
427
+ const logged = /* @__PURE__ */ new WeakSet();
428
+ intercept(transport, "onmessage", (message) => {
429
+ if (logged.has(message)) return;
430
+ logged.add(message);
431
+ journal.write("in", { frame: message });
432
+ on.frame("in", message);
433
+ });
434
+ intercept(transport, "onclose", on.closed);
435
+ intercept(transport, "onerror", on.error);
436
+ }
437
+ function intercept(transport, name, before) {
438
+ let handler;
439
+ Object.defineProperty(transport, name, {
440
+ configurable: true,
441
+ get: () => {
442
+ const current = handler;
443
+ return current && ((...args) => {
444
+ before(...args);
445
+ current(...args);
446
+ });
447
+ },
448
+ set: (fn) => handler = fn
449
+ });
450
+ }
451
+ function watchStdout(transport, journal, seen) {
452
+ const start = transport.start.bind(transport);
453
+ transport.start = async () => {
454
+ await start();
455
+ const stdout = transport._process?.stdout;
456
+ if (stdout === null || stdout === void 0) return;
457
+ (0, import_node_readline.createInterface)({ input: stdout, crlfDelay: Infinity }).on("line", (line) => {
458
+ const isMessage = isJsonRpc(line);
459
+ if (!isMessage) journal.write("noise", { line });
460
+ seen(line, isMessage);
461
+ });
462
+ };
463
+ }
464
+ function watchOverflow(transport, over) {
465
+ const buffer = transport._readBuffer;
466
+ const append = buffer?.append?.bind(buffer);
467
+ if (buffer === void 0 || append === void 0) return;
468
+ buffer.append = (chunk) => {
469
+ try {
470
+ append(chunk);
471
+ } catch (err) {
472
+ over();
473
+ throw err;
474
+ }
475
+ };
476
+ }
477
+ function isJsonRpc(line) {
478
+ try {
479
+ const parsed2 = JSON.parse(line);
480
+ return parsed2 !== null && typeof parsed2 === "object" && parsed2.jsonrpc === "2.0";
481
+ } catch {
482
+ return false;
483
+ }
484
+ }
485
+ function kindOf(err, stdio, transportClosed) {
486
+ if (err instanceof import_client.SdkError && err.code === import_client.SdkErrorCode.RequestTimeout) return "timeout";
487
+ const code = err?.code;
488
+ if (stdio && typeof code === "string" && /^(ENOENT|EACCES|EPERM|ENOTDIR|EINVAL)$/.test(code))
489
+ return "could-not-start";
490
+ if (stdio) return transportClosed ? "exited-early" : "protocol";
491
+ if (err instanceof import_client.UnauthorizedError) return "auth";
492
+ const status = err instanceof import_client.SdkHttpError ? Number(err.status) : err instanceof import_client.SseError ? err.code : void 0;
493
+ if (status === 401 || status === 403) return "auth";
494
+ if (status !== void 0 && status >= 300 && status < 400) return "network";
495
+ if (err instanceof import_client.SseError && status === void 0) return "network";
496
+ if (err instanceof TypeError || err?.cause?.code !== void 0)
497
+ return "network";
498
+ return "protocol";
499
+ }
500
+ async function openSession(config) {
501
+ const { target } = config;
502
+ const stdio = target.kind === "stdio";
503
+ const redact = redactorFor(target);
504
+ const clean = (text) => printable(redact.text(machineless(text, void 0, (0, import_node_os2.homedir)())));
505
+ const journal = openJournal(config.debugOut, redact);
506
+ journal.write("meta", describeTarget(target, redact));
507
+ const transport = createTransport(target);
508
+ let transportClosed = false;
509
+ let spawnError;
510
+ const handshake = {
511
+ offered: void 0,
512
+ result: void 0
513
+ };
514
+ tap(transport, journal, {
515
+ frame: (dir, message) => {
516
+ const m = message;
517
+ if (dir === "out" && m.method === "initialize") {
518
+ handshake.id = m.id;
519
+ handshake.offered = m.params?.protocolVersion;
520
+ } else if (dir === "in" && handshake.id !== void 0 && m.id === handshake.id)
521
+ handshake.result = m.result;
522
+ },
523
+ closed: () => transportClosed = true,
524
+ error: (err) => {
525
+ if (spawnError === void 0 && err.syscall?.startsWith("spawn") === true)
526
+ spawnError = err;
527
+ }
528
+ });
529
+ let noted;
530
+ const serverPid = () => transport instanceof import_stdio.StdioClientTransport ? transport.pid : null;
531
+ const note = () => {
532
+ const pid = serverPid();
533
+ if (pid !== null) noted = { pid, tree: descendantsOf(pid) };
534
+ };
535
+ let tooLarge = false;
536
+ const tail = [];
537
+ const noise = { count: 0, first: [] };
538
+ const listeners = /* @__PURE__ */ new Set();
539
+ const seen = (line, isMessage) => {
540
+ if (!isMessage) {
541
+ noise.count++;
542
+ if (noise.first.length < 3) noise.first.push(clean(line).slice(0, 200));
543
+ }
544
+ for (const listener of [...listeners]) listener(line);
545
+ };
546
+ let stderrDone = Promise.resolve();
547
+ if (transport instanceof import_stdio.StdioClientTransport && transport.stderr !== null) {
548
+ const lines = (0, import_node_readline.createInterface)({ input: transport.stderr, crlfDelay: Infinity });
549
+ lines.on("line", (line) => {
550
+ journal.write("stderr", { line });
551
+ tail.push(clean(line));
552
+ if (tail.length > TAIL_LINES) tail.shift();
553
+ });
554
+ stderrDone = new Promise((resolve8) => lines.once("close", resolve8));
555
+ watchStdout(transport, journal, seen);
556
+ watchOverflow(transport, () => {
557
+ if (tooLarge) return;
558
+ tooLarge = true;
559
+ note();
560
+ });
561
+ }
562
+ const toConnectError = async (err) => {
563
+ if (transportClosed) await Promise.race([stderrDone, new Promise((r) => setTimeout(r, 500))]);
564
+ const cause = spawnError ?? err;
565
+ const kind = tooLarge ? "too-large" : kindOf(cause, stdio, transportClosed);
566
+ const [lead, withDetail] = LEAD[kind];
567
+ const detail = withDetail ? clean(firstLine(cause instanceof Error ? cause.message : String(cause))) : "";
568
+ const error = new ConnectError(kind, detail === "" ? `${lead}.` : `${lead}: ${detail}`, [
569
+ ...tail
570
+ ]);
571
+ journal.write("error", { kind, message: error.message });
572
+ return error;
573
+ };
574
+ let closing;
575
+ const shutdown = async () => {
576
+ note();
577
+ await transport.close().catch(() => {
578
+ });
579
+ killSurvivors(noted?.tree ?? []);
580
+ untrack();
581
+ journal.close();
582
+ };
583
+ const closable = {
584
+ close: () => closing ??= shutdown(),
585
+ killNow: () => {
586
+ const pid = serverPid() ?? noted?.pid;
587
+ if (pid === void 0 || pid === null) return;
588
+ const tree = [...descendantsOf(pid), ...noted?.tree ?? []].map((p) => p.pid);
589
+ killAll([.../* @__PURE__ */ new Set([...tree, pid])]);
590
+ }
591
+ };
592
+ const untrack = track(closable);
593
+ const client = new import_client.Client({ name: "plune", version: config.clientVersion ?? "0.0.0" });
594
+ let timer;
595
+ try {
596
+ await Promise.race([
597
+ client.connect(transport, { timeout: config.timeoutMs }),
598
+ new Promise((_, reject) => {
599
+ timer = setTimeout(
600
+ () => reject(new import_client.SdkError(import_client.SdkErrorCode.RequestTimeout, "no answer")),
601
+ config.timeoutMs
602
+ );
603
+ })
604
+ ]);
605
+ } catch (err) {
606
+ if (closing === void 0) {
607
+ const error = await toConnectError(err);
608
+ await closable.close();
609
+ throw error;
610
+ }
611
+ } finally {
612
+ clearTimeout(timer);
613
+ }
614
+ if (closing !== void 0) {
615
+ await closing;
616
+ throw new Error("The session was closed while it was connecting.");
617
+ }
618
+ const info = client.getServerVersion();
619
+ return {
620
+ redact,
621
+ server: info === void 0 ? void 0 : { name: String(info.name), version: String(info.version) },
622
+ handshake: { offered: handshake.offered, result: handshake.result },
623
+ stderrTail: () => [...tail],
624
+ async request(method, params, options) {
625
+ try {
626
+ return await client.request(
627
+ params === void 0 ? { method } : { method, params },
628
+ AS_SENT,
629
+ { timeout: options?.timeoutMs ?? config.timeoutMs }
630
+ );
631
+ } catch (err) {
632
+ if (err instanceof import_client.ProtocolError)
633
+ throw new import_client.ProtocolError(err.code, clean(err.message), redact.value(err.data));
634
+ throw await toConnectError(err);
635
+ }
636
+ },
637
+ fetchForOrigin(origin) {
638
+ const allowed = new URL(origin).origin;
639
+ const own = target.kind !== "stdio" && new URL(target.url).origin === allowed;
640
+ return async (input, init) => {
641
+ const url = new URL(input);
642
+ if (url.origin !== allowed)
643
+ throw new Error(
644
+ `fetchForOrigin(${allowed}) refuses a request to another origin, ${url.origin}.`
645
+ );
646
+ const headers = new Headers(init?.headers);
647
+ if (own) {
648
+ for (const [name, value] of Object.entries(target.headers))
649
+ if (!headers.has(name)) headers.set(name, value);
650
+ }
651
+ return fetch(url, { ...init, headers, redirect: "manual" });
652
+ };
653
+ },
654
+ async raw(body, id, options) {
655
+ const ms = options?.timeoutMs ?? config.timeoutMs;
656
+ if (target.kind === "sse")
657
+ throw new ConnectError("protocol", "Messages of its own go over stdio and Streamable HTTP only, not HTTP+SSE.", []);
658
+ journal.write("out", { raw: body });
659
+ const noAnswer = () => new ConnectError("timeout", `${LEAD.timeout[0]}.`, [...tail]);
660
+ if (target.kind === "stdio") {
661
+ const stdin = transport._process?.stdin;
662
+ if (stdin === null || stdin === void 0 || stdin.writableEnded)
663
+ throw new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
664
+ return new Promise((resolve8, reject) => {
665
+ const timer2 = setTimeout(() => {
666
+ listeners.delete(listener);
667
+ reject(noAnswer());
668
+ }, ms);
669
+ const listener = (line) => {
670
+ const frame2 = parsed(line);
671
+ if (!answers(frame2, id)) return;
672
+ clearTimeout(timer2);
673
+ listeners.delete(listener);
674
+ resolve8({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
675
+ };
676
+ listeners.add(listener);
677
+ stdin.write(`${body}
678
+ `);
679
+ });
680
+ }
681
+ const state = transport;
682
+ const headers = new Headers(target.headers);
683
+ headers.set("content-type", "application/json");
684
+ headers.set("accept", "application/json, text/event-stream");
685
+ if (state.sessionId !== void 0) headers.set("mcp-session-id", state.sessionId);
686
+ if (state._protocolVersion !== void 0) headers.set("mcp-protocol-version", state._protocolVersion);
687
+ const lost = async (err) => err?.name === "TimeoutError" ? noAnswer() : toConnectError(err);
688
+ let text = "";
689
+ let frame;
690
+ let status;
691
+ try {
692
+ const res = await fetch(target.url, {
693
+ method: "POST",
694
+ headers,
695
+ body,
696
+ redirect: "manual",
697
+ signal: AbortSignal.timeout(ms)
698
+ });
699
+ status = res.status;
700
+ const sse = (res.headers.get("content-type") ?? "").includes("text/event-stream");
701
+ if (res.body !== null) {
702
+ const reader = res.body.getReader();
703
+ const decoder = new TextDecoder();
704
+ for (; ; ) {
705
+ const { done, value } = await reader.read();
706
+ if (done) break;
707
+ text += decoder.decode(value, { stream: true });
708
+ if (sse && (frame = fromEventStream(text, id)) !== void 0) break;
709
+ if (text.length > STDIO_MESSAGE_LIMIT) break;
710
+ }
711
+ await reader.cancel().catch(() => {
712
+ });
713
+ }
714
+ if (!sse) {
715
+ const whole = parsed(text);
716
+ if (whole !== null && typeof whole === "object" && !Array.isArray(whole))
717
+ frame = whole;
718
+ }
719
+ } catch (err) {
720
+ throw await lost(err);
721
+ }
722
+ journal.write("in", frame !== void 0 ? { frame } : { status, raw: text.slice(0, RAW_TEXT) });
723
+ return { frame, status, text: clean(text).slice(0, RAW_TEXT) };
724
+ },
725
+ stdoutNoise: () => ({ count: noise.count, first: [...noise.first] }),
726
+ async endInput(waitMs) {
727
+ const proc = transport._process;
728
+ if (proc === void 0) return true;
729
+ if (proc.exitCode !== null || proc.signalCode !== null) return true;
730
+ const exited = new Promise((resolve8) => proc.once("exit", () => resolve8(true)));
731
+ proc.stdin?.end();
732
+ let timer2;
733
+ const late = new Promise((resolve8) => timer2 = setTimeout(() => resolve8(false), waitMs));
734
+ const result = await Promise.race([exited, late]);
735
+ clearTimeout(timer2);
736
+ return result;
737
+ },
738
+ close: closable.close
739
+ };
740
+ }
741
+ var import_node_os2, import_node_readline, import_client, import_stdio, ConnectError, RAW_TEXT, parsed, TAIL_LINES, STDIO_MESSAGE_LIMIT, AS_SENT, firstLine, LEAD;
742
+ var init_session = __esm({
743
+ "src/mcp-testing/connect/session.ts"() {
744
+ "use strict";
745
+ init_cjs_shims();
746
+ import_node_os2 = require("os");
747
+ import_node_readline = require("readline");
748
+ import_client = require("@modelcontextprotocol/client");
749
+ import_stdio = require("@modelcontextprotocol/client/stdio");
750
+ init_failure_detail();
751
+ init_exit_codes();
752
+ init_journal();
753
+ init_processes();
754
+ init_redact();
755
+ init_processes();
756
+ ConnectError = class extends Error {
757
+ constructor(kind, message, stderrTail) {
758
+ super(message);
759
+ this.kind = kind;
760
+ this.stderrTail = stderrTail;
761
+ this.name = "ConnectError";
762
+ }
763
+ kind;
764
+ stderrTail;
765
+ exitCode = MCP_EXIT.usage;
766
+ };
767
+ RAW_TEXT = 2e3;
768
+ parsed = (text) => {
769
+ try {
770
+ return JSON.parse(text);
771
+ } catch {
772
+ return void 0;
773
+ }
774
+ };
775
+ TAIL_LINES = 20;
776
+ STDIO_MESSAGE_LIMIT = 10 * 1024 * 1024;
777
+ AS_SENT = {
778
+ "~standard": { version: 1, vendor: "plune", validate: (value) => ({ value }) }
779
+ };
780
+ firstLine = (text) => text.split(/\r?\n/)[0] ?? "";
781
+ LEAD = {
782
+ "could-not-start": ["Could not start the server command", true],
783
+ "exited-early": ["The server process exited before it answered", false],
784
+ "too-large": [
785
+ `The server sent a message larger than ${STDIO_MESSAGE_LIMIT / 1024 / 1024} MB, the most plune reads in one stdio message; a long list belongs in pages (nextCursor)`,
786
+ false
787
+ ],
788
+ timeout: ["The server did not answer within --timeout", false],
789
+ protocol: ["The server did not answer as an MCP server", true],
790
+ auth: ["The server refused the credentials", true],
791
+ network: ["Could not reach the server", true]
792
+ };
793
+ }
794
+ });
795
+
796
+ // src/mcp-testing/connect/safe-tools.ts
797
+ function selectSafeTools(tools, opts = {}) {
798
+ const selection = { safe: [], skipped: [] };
799
+ for (const tool of tools) {
800
+ const reason = skipReason(tool, opts.allowWrite === true);
801
+ if (reason === void 0) selection.safe.push(tool);
802
+ else selection.skipped.push({ tool, reason });
803
+ }
804
+ return selection;
805
+ }
806
+ function skipReason(tool, allowWrite) {
807
+ if (tool === null || typeof tool !== "object" || typeof tool.name !== "string")
808
+ return "malformed";
809
+ const { annotations, inputSchema } = tool;
810
+ const readOnly = annotations?.readOnlyHint === true;
811
+ if (!readOnly && !allowWrite) return "not-read-only";
812
+ const hint = annotations?.destructiveHint;
813
+ if (hint === true || hint !== void 0 && typeof hint !== "boolean") return "destructive";
814
+ if (!readOnly && hint !== false) return "no-destructive-hint";
815
+ const required = inputSchema?.required;
816
+ if (required !== void 0 && !Array.isArray(required)) return "malformed";
817
+ if (Array.isArray(required) && required.length > 0) return "required-arguments";
818
+ if (mayRequire(inputSchema)) return "required-arguments";
819
+ return void 0;
820
+ }
821
+ function mayRequire(schema) {
822
+ if (schema === null || typeof schema !== "object") return false;
823
+ const s = schema;
824
+ if (["allOf", "anyOf", "oneOf", "$ref", "dependentRequired"].some((k) => k in s)) return true;
825
+ return typeof s.minProperties === "number" && s.minProperties > 0;
826
+ }
827
+ var init_safe_tools = __esm({
828
+ "src/mcp-testing/connect/safe-tools.ts"() {
829
+ "use strict";
830
+ init_cjs_shims();
831
+ }
832
+ });
833
+
834
+ // src/mcp-testing/connect/tools.ts
835
+ var tools_exports = {};
836
+ __export(tools_exports, {
837
+ MAX_PAGES: () => MAX_PAGES,
838
+ asTools: () => asTools,
839
+ callTool: () => callTool,
840
+ callableTools: () => callableTools,
841
+ listAll: () => listAll
842
+ });
843
+ async function listAll(session, method, key, opts = {}) {
844
+ const items = [];
845
+ let malformed = false;
846
+ let cursor;
847
+ for (let pages = 1; pages <= MAX_PAGES; pages++) {
848
+ if (opts.signal?.aborted === true)
849
+ return { items, pages: pages - 1, complete: false, malformed };
850
+ const page = await session.request(
851
+ method,
852
+ cursor === void 0 ? void 0 : { cursor },
853
+ opts.timeoutMs === void 0 ? {} : { timeoutMs: opts.timeoutMs }
854
+ );
855
+ const listed = isRecord3(page) ? page[key] : void 0;
856
+ if (Array.isArray(listed)) for (const item of listed) items.push(item);
857
+ else malformed = true;
858
+ cursor = isRecord3(page) && typeof page.nextCursor === "string" && page.nextCursor !== "" ? page.nextCursor : void 0;
859
+ if (cursor === void 0) return { items, pages, complete: true, malformed };
860
+ }
861
+ return { items, pages: MAX_PAGES, complete: false, malformed };
862
+ }
863
+ function asTools(items) {
864
+ const tools = [];
865
+ const unnamed = /* @__PURE__ */ new Map();
866
+ for (const t of items) {
867
+ const name = isRecord3(t) ? t.name : void 0;
868
+ if (typeof name === "string" && name !== "") {
869
+ tools.push(t);
870
+ continue;
871
+ }
872
+ const tool = { ...isRecord3(t) ? t : {}, name: "" };
873
+ unnamed.set(tool, name === void 0 ? "(no name)" : String(JSON.stringify(name)));
874
+ tools.push(tool);
875
+ }
876
+ return { tools, unnamed };
877
+ }
878
+ function callableTools(tools, unnamed, opts = {}) {
879
+ const counts = /* @__PURE__ */ new Map();
880
+ for (const t of tools) if (!unnamed.has(t)) counts.set(t.name, (counts.get(t.name) ?? 0) + 1);
881
+ const refused = [];
882
+ const candidates = [];
883
+ for (const t of tools) {
884
+ const label = unnamed.get(t);
885
+ if (label !== void 0) refused.push({ tool: label, reason: "invalid-name" });
886
+ else if ((counts.get(t.name) ?? 0) > 1)
887
+ refused.push({ tool: t.name, reason: "duplicate-name" });
888
+ else candidates.push(t);
889
+ }
890
+ const { safe, skipped } = selectSafeTools(candidates, opts);
891
+ return {
892
+ safe,
893
+ skipped: [...refused, ...skipped.map((s) => ({ tool: s.tool.name, reason: s.reason }))]
894
+ };
895
+ }
896
+ async function callTool(session, name, timeoutMs, args = {}) {
897
+ try {
898
+ const result = await session.request("tools/call", { name, arguments: args }, { timeoutMs });
899
+ return { kind: "result", result };
900
+ } catch (err) {
901
+ if (err instanceof ConnectError) {
902
+ if (err.kind === "auth") throw err;
903
+ return err.kind === "timeout" ? { kind: "timeout" } : { kind: "lost", message: err.message };
904
+ }
905
+ if (err instanceof import_client2.ProtocolError) return { kind: "error", message: err.message };
906
+ throw err;
907
+ }
908
+ }
909
+ var import_client2, MAX_PAGES, isRecord3;
910
+ var init_tools = __esm({
911
+ "src/mcp-testing/connect/tools.ts"() {
912
+ "use strict";
913
+ init_cjs_shims();
914
+ import_client2 = require("@modelcontextprotocol/client");
915
+ init_safe_tools();
916
+ init_session();
917
+ MAX_PAGES = 100;
918
+ isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
919
+ }
920
+ });
921
+
30
922
  // src/index.ts
31
923
  var src_exports = {};
32
924
  __export(src_exports, {
@@ -53,20 +945,20 @@ __export(src_exports, {
53
945
  testCaseSchema: () => testCaseSchema
54
946
  });
55
947
  module.exports = __toCommonJS(src_exports);
56
-
57
- // node_modules/.pnpm/tsup@8.5.1_postcss@8.5.15_tsx@4.22.4_typescript@5.9.3_yaml@2.9.0/node_modules/tsup/assets/cjs_shims.js
58
- var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
59
- var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
948
+ init_cjs_shims();
60
949
 
61
950
  // src/cli/commands/run.ts
951
+ init_cjs_shims();
62
952
  var fs5 = __toESM(require("fs"), 1);
63
- var path4 = __toESM(require("path"), 1);
953
+ var path5 = __toESM(require("path"), 1);
64
954
 
65
955
  // src/config/loader.ts
956
+ init_cjs_shims();
66
957
  var fs2 = __toESM(require("fs/promises"), 1);
67
958
  var import_yaml = require("yaml");
68
959
 
69
960
  // src/config/env-overrides.ts
961
+ init_cjs_shims();
70
962
  function applyEnvOverrides(config, env) {
71
963
  const result = structuredClone(config);
72
964
  if (env["PLUNE_PROVIDER"] !== void 0) {
@@ -87,6 +979,7 @@ function applyEnvOverrides(config, env) {
87
979
  }
88
980
 
89
981
  // src/config/errors.ts
982
+ init_cjs_shims();
90
983
  var ConfigNotFoundError = class extends Error {
91
984
  code = "CFG_NOT_FOUND";
92
985
  constructor(message) {
@@ -112,6 +1005,7 @@ var ConfigValidationError = class extends Error {
112
1005
  };
113
1006
 
114
1007
  // src/config/discover.ts
1008
+ init_cjs_shims();
115
1009
  var fs = __toESM(require("fs"), 1);
116
1010
  var path = __toESM(require("path"), 1);
117
1011
  var FILENAME = "plune.yaml";
@@ -142,7 +1036,100 @@ function discoverConfigPath(cwd, override) {
142
1036
  );
143
1037
  }
144
1038
 
1039
+ // src/config/mcp.ts
1040
+ init_cjs_shims();
1041
+ var path2 = __toESM(require("path"), 1);
1042
+ var MCP_LIMIT_DEFAULTS = {
1043
+ max_steps: 10,
1044
+ max_tool_calls: 20,
1045
+ max_total_tokens: 1e5,
1046
+ timeout_ms: 12e4,
1047
+ tool_timeout_ms: 3e4
1048
+ };
1049
+ function mcpLimits(config, evalConfig) {
1050
+ return { ...MCP_LIMIT_DEFAULTS, ...config.mcp?.limits, ...evalConfig.mcp?.limits };
1051
+ }
1052
+ var REFERENCE = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
1053
+ function expandVars(value, env) {
1054
+ const literal = (text) => {
1055
+ if (text.includes("${")) throw new Error('has a "${" that is not ${NAME} or ${NAME:-default}');
1056
+ return text;
1057
+ };
1058
+ let out = "";
1059
+ let last = 0;
1060
+ for (const match of value.matchAll(REFERENCE)) {
1061
+ const [whole, name, fallback] = match;
1062
+ out += literal(value.slice(last, match.index));
1063
+ const set = env[name];
1064
+ if (set !== void 0 && set !== "") out += set;
1065
+ else if (fallback !== void 0) out += fallback;
1066
+ else
1067
+ throw new Error(
1068
+ `\${${name}} is not set or is empty, and has no default (\${${name}:-default})`
1069
+ );
1070
+ last = match.index + whole.length;
1071
+ }
1072
+ return out + literal(value.slice(last));
1073
+ }
1074
+ function serverValues(server) {
1075
+ const out = [];
1076
+ if (server.command !== void 0) out.push(["command", server.command]);
1077
+ (server.args ?? []).forEach((arg, i) => out.push([`args.${i}`, arg]));
1078
+ for (const [key, value] of Object.entries(server.env ?? {})) out.push([`env.${key}`, value]);
1079
+ if (server.cwd !== void 0) out.push(["cwd", server.cwd]);
1080
+ if (server.url !== void 0) out.push(["url", server.url]);
1081
+ for (const [key, value] of Object.entries(server.headers ?? {}))
1082
+ out.push([`headers.${key}`, value]);
1083
+ return out;
1084
+ }
1085
+ function mcpVariableIssues(config, env) {
1086
+ const issues = [];
1087
+ for (const [name, server] of Object.entries(config.mcp?.servers ?? {})) {
1088
+ for (const [field, value] of serverValues(server)) {
1089
+ try {
1090
+ expandVars(value, env);
1091
+ } catch (err) {
1092
+ issues.push(`mcp.servers.${name}.${field}: ${err.message}`);
1093
+ }
1094
+ }
1095
+ }
1096
+ return issues;
1097
+ }
1098
+ function resolveMcpServer(server, env = process.env, baseDir = process.cwd()) {
1099
+ const fill = (value) => expandVars(value, env);
1100
+ const fillAll = (entries = {}) => Object.fromEntries(Object.entries(entries).map(([key, value]) => [key, fill(value)]));
1101
+ if (server.url !== void 0)
1102
+ return { kind: "http", url: fill(server.url), headers: fillAll(server.headers) };
1103
+ return {
1104
+ kind: "stdio",
1105
+ command: fill(server.command),
1106
+ args: (server.args ?? []).map(fill),
1107
+ env: fillAll(server.env),
1108
+ ...server.cwd !== void 0 ? { cwd: path2.resolve(baseDir, fill(server.cwd)) } : {}
1109
+ };
1110
+ }
1111
+ var SECRET_KEY = /authorization|token|key|secret|password/i;
1112
+ function mcpSecretWarnings(config) {
1113
+ const warnings = [];
1114
+ for (const [name, server] of Object.entries(config.mcp?.servers ?? {})) {
1115
+ for (const [field, entries] of [
1116
+ ["env", server.env],
1117
+ ["headers", server.headers]
1118
+ ]) {
1119
+ for (const [key, value] of Object.entries(entries ?? {})) {
1120
+ if (SECRET_KEY.test(key) && !value.includes("${")) {
1121
+ warnings.push(
1122
+ `mcp.servers.${name}.${field}.${key} looks like a secret written into plune.yaml; use \${VAR} so it comes from the environment.`
1123
+ );
1124
+ }
1125
+ }
1126
+ }
1127
+ }
1128
+ return warnings;
1129
+ }
1130
+
145
1131
  // src/config/schema.ts
1132
+ init_cjs_shims();
146
1133
  var import_zod = require("zod");
147
1134
  var providerConfigSchema = import_zod.z.object({
148
1135
  type: import_zod.z.enum(["anthropic", "openai", "openrouter"]),
@@ -196,7 +1183,8 @@ var llmJudgeAssertionSchema = import_zod.z.object({
196
1183
  type: import_zod.z.literal("llm-judge"),
197
1184
  criteria: import_zod.z.string().min(1),
198
1185
  provider: providerConfigSchema.partial().optional(),
199
- pass_threshold: import_zod.z.number().min(0).max(1).optional()
1186
+ // The judge's score floor, not the eval's share of passing runs (that one is `evalRepeatsShape`).
1187
+ pass_threshold: import_zod.z.number().min(0, "pass_threshold (llm-judge: minimum judge score) must be between 0 and 1").max(1, "pass_threshold (llm-judge: minimum judge score) must be between 0 and 1").optional()
200
1188
  });
201
1189
  var semanticSimilarityAssertionSchema = import_zod.z.object({
202
1190
  type: import_zod.z.literal("semantic-similarity"),
@@ -219,6 +1207,54 @@ var contextPrecisionAssertionSchema = import_zod.z.object({
219
1207
  question: import_zod.z.string().min(1),
220
1208
  threshold: import_zod.z.number().min(0).max(1).optional()
221
1209
  });
1210
+ var toolName = import_zod.z.string().min(1);
1211
+ var count = import_zod.z.number().int().min(1);
1212
+ var toolCallAssertionSchemas = [
1213
+ import_zod.z.object({ type: import_zod.z.literal("tool-called"), tool: toolName, min_count: count.optional() }),
1214
+ import_zod.z.object({ type: import_zod.z.literal("tool-not-called"), tool: toolName }),
1215
+ import_zod.z.object({
1216
+ type: import_zod.z.literal("tool-args"),
1217
+ tool: toolName,
1218
+ args: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()),
1219
+ match: import_zod.z.enum(["partial", "exact", "ignore"]).optional(),
1220
+ min_count: count.optional()
1221
+ }),
1222
+ import_zod.z.object({
1223
+ type: import_zod.z.literal("tool-order"),
1224
+ tools: import_zod.z.array(toolName).min(1),
1225
+ strict: import_zod.z.boolean().optional()
1226
+ }),
1227
+ import_zod.z.object({ type: import_zod.z.literal("only-tools"), tools: import_zod.z.array(toolName) }),
1228
+ import_zod.z.object({ type: import_zod.z.literal("first-tool"), tool: toolName }),
1229
+ import_zod.z.object({ type: import_zod.z.literal("no-tool-errors"), tool: toolName.optional() }),
1230
+ import_zod.z.object({
1231
+ type: import_zod.z.literal("tool-call-count"),
1232
+ tool: toolName.optional(),
1233
+ min: import_zod.z.number().int().min(0).optional(),
1234
+ max: import_zod.z.number().int().min(0).optional()
1235
+ }).refine((a) => a.min !== void 0 || a.max !== void 0, {
1236
+ message: "tool-call-count needs min, max or both"
1237
+ }).refine((a) => a.min === void 0 || a.max === void 0 || a.min <= a.max, {
1238
+ message: "tool-call-count: min is above max"
1239
+ }),
1240
+ import_zod.z.object({ type: import_zod.z.literal("no-repeated-call"), tool: toolName.optional() }),
1241
+ import_zod.z.object({ type: import_zod.z.literal("token-budget"), max: count }),
1242
+ import_zod.z.object({ type: import_zod.z.literal("tool-latency"), max_ms: import_zod.z.number().positive(), tool: toolName.optional() }),
1243
+ import_zod.z.object({
1244
+ type: import_zod.z.literal("tool-result-size"),
1245
+ max_bytes: import_zod.z.number().int().min(0),
1246
+ tool: toolName.optional()
1247
+ }),
1248
+ import_zod.z.object({
1249
+ type: import_zod.z.literal("tool-result-schema"),
1250
+ schema: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()),
1251
+ tool: toolName.optional()
1252
+ }),
1253
+ import_zod.z.object({ type: import_zod.z.literal("no-destructive-tool") })
1254
+ ];
1255
+ var TOOL_CALL_TYPES = new Set(
1256
+ toolCallAssertionSchemas.map((s) => s.shape.type.value)
1257
+ );
222
1258
  var assertionConfigSchema = import_zod.z.discriminatedUnion("type", [
223
1259
  exactMatchAssertionSchema,
224
1260
  containsAssertionSchema,
@@ -229,8 +1265,53 @@ var assertionConfigSchema = import_zod.z.discriminatedUnion("type", [
229
1265
  semanticSimilarityAssertionSchema,
230
1266
  faithfulnessAssertionSchema,
231
1267
  answerRelevanceAssertionSchema,
232
- contextPrecisionAssertionSchema
1268
+ contextPrecisionAssertionSchema,
1269
+ ...toolCallAssertionSchemas
233
1270
  ]);
1271
+ var MAX_RUNS = 100;
1272
+ var SHARE_MESSAGE = "pass_threshold (eval: share of runs that must pass) must be greater than 0 and at most 1";
1273
+ var evalRepeatsShape = {
1274
+ runs: import_zod.z.number().int().min(1).max(MAX_RUNS).optional(),
1275
+ pass_threshold: import_zod.z.number().gt(0, SHARE_MESSAGE).max(1, SHARE_MESSAGE).optional()
1276
+ };
1277
+ var MAX_TIMER_MS = 2147483647;
1278
+ var limit = import_zod.z.number().int().positive();
1279
+ var mcpLimitsSchema = import_zod.z.object({
1280
+ max_steps: limit.optional(),
1281
+ max_tool_calls: limit.optional(),
1282
+ max_total_tokens: limit.optional(),
1283
+ timeout_ms: limit.max(MAX_TIMER_MS).optional(),
1284
+ tool_timeout_ms: limit.max(MAX_TIMER_MS).optional()
1285
+ }).strict();
1286
+ var mcpServerSchema = import_zod.z.object({
1287
+ command: import_zod.z.string().min(1).optional(),
1288
+ args: import_zod.z.array(import_zod.z.string()).optional(),
1289
+ env: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional(),
1290
+ cwd: import_zod.z.string().min(1).optional(),
1291
+ url: import_zod.z.string().min(1).optional(),
1292
+ headers: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional()
1293
+ }).strict();
1294
+ var mcpServersSchema = import_zod.z.record(import_zod.z.string().min(1), mcpServerSchema).superRefine((servers, ctx) => {
1295
+ for (const [name, server] of Object.entries(servers)) {
1296
+ const issue = (message) => ctx.addIssue({ code: "custom", path: [name], message });
1297
+ const stdio = server.command !== void 0;
1298
+ const http = server.url !== void 0;
1299
+ if (stdio && http)
1300
+ issue(`server "${name}" has both command and url; give command (stdio) or url (HTTP), not both`);
1301
+ else if (!stdio && !http)
1302
+ issue(`server "${name}" needs command (a stdio server) or url (an HTTP server)`);
1303
+ else if (stdio && server.headers !== void 0)
1304
+ issue(`server "${name}": headers are for a server at url, not one started with command`);
1305
+ else if (http && (server.args ?? server.env ?? server.cwd) !== void 0)
1306
+ issue(`server "${name}": args, env and cwd are for a server started with command, not one at url`);
1307
+ }
1308
+ });
1309
+ var mcpRootSchema = import_zod.z.object({ servers: mcpServersSchema, limits: mcpLimitsSchema.optional() }).strict();
1310
+ var evalMcpSchema = import_zod.z.object({
1311
+ server: import_zod.z.string().min(1),
1312
+ allowed_tools: import_zod.z.array(import_zod.z.string().min(1)).min(1, "allowed_tools must name at least one tool; leave it out to allow every tool the server lists").optional(),
1313
+ limits: mcpLimitsSchema.optional()
1314
+ }).strict();
234
1315
  var evalConfigSchema = import_zod.z.object({
235
1316
  id: import_zod.z.string().min(1).regex(/^[a-z0-9_-]+$/, "id must be lowercase slug"),
236
1317
  description: import_zod.z.string().optional(),
@@ -239,7 +1320,9 @@ var evalConfigSchema = import_zod.z.object({
239
1320
  prompt: import_zod.z.string().optional(),
240
1321
  prompt_file: import_zod.z.string().optional(),
241
1322
  dataset: datasetRefSchema,
242
- assertions: import_zod.z.array(assertionConfigSchema)
1323
+ assertions: import_zod.z.array(assertionConfigSchema),
1324
+ ...evalRepeatsShape,
1325
+ mcp: evalMcpSchema.optional()
243
1326
  }).refine(
244
1327
  (data) => !(data.prompt !== void 0 && data.prompt_file !== void 0),
245
1328
  { message: "prompt and prompt_file are mutually exclusive" }
@@ -249,8 +1332,34 @@ var pluneConfigSchema = import_zod.z.object({
249
1332
  provider: providerConfigSchema,
250
1333
  defaults: import_zod.z.object({ assertions: import_zod.z.array(assertionConfigSchema).optional() }).optional(),
251
1334
  pricing: pricingSchema.optional(),
1335
+ ...evalRepeatsShape,
1336
+ // A CLI older than this block stops on it: the root is strict.
1337
+ mcp: mcpRootSchema.optional(),
252
1338
  evals: import_zod.z.array(evalConfigSchema).min(1)
253
- }).strict();
1339
+ }).strict().superRefine((config, ctx) => {
1340
+ config.evals.forEach((evalConfig, i) => {
1341
+ const server = evalConfig.mcp?.server;
1342
+ if (server === void 0) {
1343
+ const misplaced = (assertions, path9) => assertions.forEach((a, j) => {
1344
+ if (TOOL_CALL_TYPES.has(a.type))
1345
+ ctx.addIssue({
1346
+ code: "custom",
1347
+ path: [...path9, j, "type"],
1348
+ message: `"${a.type}" reads the tool calls of an eval with mcp, and eval "${evalConfig.id}" has no mcp block`
1349
+ });
1350
+ });
1351
+ misplaced(config.defaults?.assertions ?? [], ["defaults", "assertions"]);
1352
+ misplaced(evalConfig.assertions, ["evals", i, "assertions"]);
1353
+ return;
1354
+ }
1355
+ if (config.mcp?.servers[server] !== void 0) return;
1356
+ ctx.addIssue({
1357
+ code: "custom",
1358
+ path: ["evals", i, "mcp", "server"],
1359
+ message: `eval "${evalConfig.id}" uses MCP server "${server}", which mcp.servers does not define`
1360
+ });
1361
+ });
1362
+ });
254
1363
 
255
1364
  // src/config/loader.ts
256
1365
  async function loadConfig(opts = {}) {
@@ -262,15 +1371,15 @@ async function loadConfig(opts = {}) {
262
1371
  } catch {
263
1372
  throw new ConfigNotFoundError(`Cannot read config file: ${resolvedPath}`);
264
1373
  }
265
- let parsed;
1374
+ let parsed2;
266
1375
  try {
267
- parsed = (0, import_yaml.parse)(raw);
1376
+ parsed2 = (0, import_yaml.parse)(raw);
268
1377
  } catch (err) {
269
1378
  throw new YamlParseError(
270
1379
  `YAML parse error in ${resolvedPath}: ${err.message}`
271
1380
  );
272
1381
  }
273
- const result = pluneConfigSchema.safeParse(parsed);
1382
+ const result = pluneConfigSchema.safeParse(parsed2);
274
1383
  if (!result.success) {
275
1384
  const issues = result.error.issues.map(
276
1385
  (issue) => `${issue.path.join(".")}: ${issue.message}`
@@ -280,13 +1389,28 @@ async function loadConfig(opts = {}) {
280
1389
  issues
281
1390
  );
282
1391
  }
283
- return applyEnvOverrides(result.data, env);
1392
+ const config = result.data;
1393
+ const unset = mcpVariableIssues(config, env);
1394
+ if (unset.length > 0)
1395
+ throw new ConfigValidationError(`Config validation failed in ${resolvedPath}`, unset);
1396
+ return applyEnvOverrides(config, env);
284
1397
  }
285
1398
 
1399
+ // src/providers/index.ts
1400
+ init_cjs_shims();
1401
+
1402
+ // src/providers/registry.ts
1403
+ init_cjs_shims();
1404
+
286
1405
  // src/providers/anthropic.ts
1406
+ init_cjs_shims();
287
1407
  var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
288
1408
 
1409
+ // src/providers/retry.ts
1410
+ init_cjs_shims();
1411
+
289
1412
  // src/providers/errors.ts
1413
+ init_cjs_shims();
290
1414
  var NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
291
1415
  "ECONNRESET",
292
1416
  "ETIMEDOUT",
@@ -375,7 +1499,7 @@ function normalizeProviderError(err, secret, envVar) {
375
1499
  }
376
1500
 
377
1501
  // src/providers/retry.ts
378
- var defaultSleep = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
1502
+ var defaultSleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
379
1503
  function retryAfterMs(err) {
380
1504
  if (typeof err !== "object" || err === null || !("headers" in err)) return void 0;
381
1505
  const raw = readHeader(err.headers, "retry-after");
@@ -419,7 +1543,11 @@ async function withRetry(fn, options) {
419
1543
  }
420
1544
  }
421
1545
 
1546
+ // src/providers/cost.ts
1547
+ init_cjs_shims();
1548
+
422
1549
  // src/providers/prices.ts
1550
+ init_cjs_shims();
423
1551
  var PRICE_TABLE = {
424
1552
  // Anthropic, current models. Source: platform.claude.com/docs/en/about-claude/pricing — base
425
1553
  // input and output tokens per million, read on 2026-09-29, kept here per thousand.
@@ -480,6 +1608,39 @@ function resolveCostEntry(usage, model, reportedCostUsd, overrides, deps = {}) {
480
1608
  // src/providers/anthropic.ts
481
1609
  var ENV_VAR = "ANTHROPIC_API_KEY";
482
1610
  var DEFAULT_MAX_RETRIES = 2;
1611
+ var STOP = {
1612
+ tool_use: "tool_calls",
1613
+ end_turn: "stop",
1614
+ max_tokens: "length"
1615
+ };
1616
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1617
+ function toAnthropicMessages(messages) {
1618
+ return messages.map((m) => {
1619
+ if (m.role === "user") return { role: "user", content: m.content };
1620
+ if (m.role === "tool")
1621
+ return {
1622
+ role: "user",
1623
+ content: m.results.map((r) => ({
1624
+ type: "tool_result",
1625
+ tool_use_id: r.id,
1626
+ content: r.content,
1627
+ is_error: r.is_error
1628
+ }))
1629
+ };
1630
+ return {
1631
+ role: "assistant",
1632
+ content: [
1633
+ ...m.text !== "" ? [{ type: "text", text: m.text }] : [],
1634
+ ...m.tool_calls.map((c) => ({
1635
+ type: "tool_use",
1636
+ id: c.id,
1637
+ name: c.name,
1638
+ input: isObject(c.args) ? c.args : {}
1639
+ }))
1640
+ ]
1641
+ };
1642
+ });
1643
+ }
483
1644
  function makeAnthropicProvider(config, env, pricing) {
484
1645
  const apiKey = env[ENV_VAR];
485
1646
  if (apiKey === void 0 || apiKey.trim() === "") {
@@ -519,6 +1680,35 @@ function makeAnthropicProvider(config, env, pricing) {
519
1680
  throw normalizeProviderError(err, apiKey, ENV_VAR);
520
1681
  }
521
1682
  },
1683
+ async respond(req) {
1684
+ try {
1685
+ const res = await withRetry(
1686
+ () => client.messages.create({
1687
+ model: req.model,
1688
+ max_tokens: req.max_tokens,
1689
+ ...req.temperature !== void 0 ? { temperature: req.temperature } : {},
1690
+ messages: toAnthropicMessages(req.messages),
1691
+ tools: req.tools.map((t) => ({
1692
+ name: t.name,
1693
+ ...t.description !== void 0 ? { description: t.description } : {},
1694
+ input_schema: { ...t.input_schema, type: "object" }
1695
+ }))
1696
+ }),
1697
+ { max_retries: maxRetries }
1698
+ );
1699
+ const stop = res.stop_reason ?? void 0;
1700
+ return {
1701
+ text: res.content.map((block) => block.type === "text" ? block.text : "").join(""),
1702
+ tool_calls: res.content.flatMap(
1703
+ (block) => block.type === "tool_use" ? [{ id: block.id, name: block.name, args: block.input }] : []
1704
+ ),
1705
+ usage: { input_tokens: res.usage.input_tokens, output_tokens: res.usage.output_tokens },
1706
+ ...stop !== void 0 ? { finish_reason: STOP[stop] ?? stop } : {}
1707
+ };
1708
+ } catch (err) {
1709
+ throw normalizeProviderError(err, apiKey, ENV_VAR);
1710
+ }
1711
+ },
522
1712
  estimateCost(usage, reportedCostUsd) {
523
1713
  return resolveCostEntry(usage, config.model, reportedCostUsd, pricing);
524
1714
  }
@@ -526,7 +1716,39 @@ function makeAnthropicProvider(config, env, pricing) {
526
1716
  }
527
1717
 
528
1718
  // src/providers/openai.ts
1719
+ init_cjs_shims();
529
1720
  var import_openai = __toESM(require("openai"), 1);
1721
+ function toOpenAiMessages(messages) {
1722
+ return messages.flatMap((m) => {
1723
+ if (m.role === "user") return [{ role: "user", content: m.content }];
1724
+ if (m.role === "tool")
1725
+ return m.results.map((r) => ({ role: "tool", tool_call_id: r.id, content: r.content }));
1726
+ return [
1727
+ {
1728
+ role: "assistant",
1729
+ content: m.text === "" ? null : m.text,
1730
+ ...m.tool_calls.length > 0 ? {
1731
+ tool_calls: m.tool_calls.map((c) => ({
1732
+ id: c.id,
1733
+ type: "function",
1734
+ function: {
1735
+ name: c.name,
1736
+ arguments: typeof c.args === "string" ? c.args : JSON.stringify(c.args ?? {})
1737
+ }
1738
+ }))
1739
+ } : {}
1740
+ }
1741
+ ];
1742
+ });
1743
+ }
1744
+ function parseToolArguments(id, name, raw) {
1745
+ try {
1746
+ const args = JSON.parse(raw === "" ? "{}" : raw);
1747
+ if (typeof args === "object" && args !== null && !Array.isArray(args)) return { id, name, args };
1748
+ } catch {
1749
+ }
1750
+ return { id, name, args: raw, args_invalid: true };
1751
+ }
530
1752
  var DEFAULT_MAX_RETRIES2 = 2;
531
1753
  function makeOpenAiCompatibleProvider(opts) {
532
1754
  const { config, env, pricing, apiKeyEnv, baseURL, reportsCost } = opts;
@@ -575,6 +1797,45 @@ function makeOpenAiCompatibleProvider(opts) {
575
1797
  throw normalizeProviderError(err, apiKey, apiKeyEnv);
576
1798
  }
577
1799
  },
1800
+ async respond(req) {
1801
+ try {
1802
+ const res = await withRetry(
1803
+ () => client.chat.completions.create({
1804
+ model: req.model,
1805
+ ...req.temperature !== void 0 ? { temperature: req.temperature } : {},
1806
+ max_tokens: req.max_tokens,
1807
+ messages: toOpenAiMessages(req.messages),
1808
+ tools: req.tools.map((t) => ({
1809
+ type: "function",
1810
+ function: {
1811
+ name: t.name,
1812
+ ...t.description !== void 0 ? { description: t.description } : {},
1813
+ parameters: t.input_schema
1814
+ }
1815
+ })),
1816
+ ...reportsCost ? { usage: { include: true } } : {}
1817
+ }),
1818
+ { max_retries: maxRetries }
1819
+ );
1820
+ const reportedCost = reportsCost ? res.usage?.cost : void 0;
1821
+ const choice = res.choices[0];
1822
+ const finish = choice?.error !== void 0 ? "error" : choice?.finish_reason;
1823
+ return {
1824
+ text: choice?.message?.content ?? "",
1825
+ tool_calls: (choice?.message?.tool_calls ?? []).flatMap(
1826
+ (c) => c.type === "function" ? [parseToolArguments(c.id, c.function.name, c.function.arguments)] : []
1827
+ ),
1828
+ usage: {
1829
+ input_tokens: res.usage?.prompt_tokens ?? 0,
1830
+ output_tokens: res.usage?.completion_tokens ?? 0
1831
+ },
1832
+ ...typeof finish === "string" ? { finish_reason: finish } : {},
1833
+ ...typeof reportedCost === "number" ? { cost_usd: reportedCost } : {}
1834
+ };
1835
+ } catch (err) {
1836
+ throw normalizeProviderError(err, apiKey, apiKeyEnv);
1837
+ }
1838
+ },
578
1839
  estimateCost(usage, reportedCostUsd) {
579
1840
  return resolveCostEntry(usage, config.model, reportedCostUsd, pricing);
580
1841
  }
@@ -585,6 +1846,7 @@ function makeOpenAiProvider(config, env, pricing) {
585
1846
  }
586
1847
 
587
1848
  // src/providers/openrouter.ts
1849
+ init_cjs_shims();
588
1850
  var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
589
1851
  function makeOpenRouterProvider(config, env, pricing) {
590
1852
  return makeOpenAiCompatibleProvider({
@@ -633,6 +1895,7 @@ function getProvider(config, env, pricing) {
633
1895
  }
634
1896
 
635
1897
  // src/providers/estimate.ts
1898
+ init_cjs_shims();
636
1899
  function makeEstimateProvider(config, pricing) {
637
1900
  return {
638
1901
  complete: () => Promise.reject(
@@ -643,17 +1906,62 @@ function makeEstimateProvider(config, pricing) {
643
1906
  }
644
1907
 
645
1908
  // src/providers/mock.ts
646
- function makeMockProvider() {
1909
+ init_cjs_shims();
1910
+ var USAGE = { input_tokens: 10, output_tokens: 5 };
1911
+ function parseMockScript(text) {
1912
+ let parsed2;
1913
+ try {
1914
+ parsed2 = JSON.parse(text);
1915
+ } catch {
1916
+ throw new Error("is not JSON");
1917
+ }
1918
+ const isStep = (s) => {
1919
+ if (typeof s !== "object" || s === null || Array.isArray(s)) return false;
1920
+ const { text: t, tool_calls: calls } = s;
1921
+ if (t !== void 0 && typeof t !== "string") return false;
1922
+ if (calls === void 0) return true;
1923
+ return Array.isArray(calls) && calls.every(
1924
+ (c) => typeof c === "object" && c !== null && typeof c.name === "string"
1925
+ );
1926
+ };
1927
+ if (!Array.isArray(parsed2) || parsed2.length === 0 || !parsed2.every(isStep))
1928
+ throw new Error(
1929
+ 'must be a non-empty list of steps, each { "text": "\u2026" } or { "tool_calls": [{ "name": "\u2026", "args": {} }] }'
1930
+ );
1931
+ return parsed2;
1932
+ }
1933
+ function makeMockProvider(script) {
647
1934
  return {
648
1935
  complete: () => Promise.resolve({
649
1936
  output: "mock response",
650
- usage: { input_tokens: 10, output_tokens: 5 }
1937
+ usage: USAGE
651
1938
  }),
1939
+ ...script !== void 0 ? {
1940
+ respond: (req) => {
1941
+ const step = req.messages.filter((m) => m.role === "assistant").length;
1942
+ const entry = script[Math.min(step, script.length - 1)];
1943
+ const calls = entry.tool_calls ?? [];
1944
+ return Promise.resolve({
1945
+ text: entry.text ?? "",
1946
+ tool_calls: calls.map((c, i) => ({
1947
+ id: `call_${step}_${i}`,
1948
+ name: c.name,
1949
+ args: c.args ?? {}
1950
+ })),
1951
+ usage: USAGE,
1952
+ finish_reason: calls.length > 0 ? "tool_calls" : "stop"
1953
+ });
1954
+ }
1955
+ } : {},
652
1956
  estimateCost: () => ({ cost_usd: 0 })
653
1957
  };
654
1958
  }
655
1959
 
1960
+ // src/embeddings/index.ts
1961
+ init_cjs_shims();
1962
+
656
1963
  // src/embeddings/cosine.ts
1964
+ init_cjs_shims();
657
1965
  function cosine(a, b) {
658
1966
  if (a.length !== b.length) {
659
1967
  throw new Error(`cosine: vector length mismatch (${a.length} vs ${b.length})`);
@@ -673,6 +1981,7 @@ function cosine(a, b) {
673
1981
  }
674
1982
 
675
1983
  // src/embeddings/embedder.ts
1984
+ init_cjs_shims();
676
1985
  var MODEL_ID = "Xenova/all-MiniLM-L6-v2";
677
1986
  var XenovaEmbedder = class {
678
1987
  extractor;
@@ -696,13 +2005,19 @@ function getDefaultEmbedder() {
696
2005
  return defaultEmbedder ??= new XenovaEmbedder();
697
2006
  }
698
2007
 
2008
+ // src/cache/index.ts
2009
+ init_cjs_shims();
2010
+
699
2011
  // src/cache/cache.ts
2012
+ init_cjs_shims();
700
2013
  var import_node_module = require("module");
701
2014
 
702
2015
  // src/util/hash.ts
2016
+ init_cjs_shims();
703
2017
  var import_node_crypto = require("crypto");
704
2018
 
705
2019
  // src/util/canonical-json.ts
2020
+ init_cjs_shims();
706
2021
  function normalizeValue(value) {
707
2022
  if (value === null) return null;
708
2023
  if (typeof value === "boolean") return value;
@@ -749,9 +2064,17 @@ function sha256(input) {
749
2064
  }
750
2065
  var CACHE_POLICY_VERSION = 1;
751
2066
  function cacheKey(inputs, policyVersion = CACHE_POLICY_VERSION) {
752
- const { provider, model, temperature, max_tokens, prompt_resolved } = inputs;
2067
+ const { provider, model, temperature, max_tokens, prompt_resolved, attempt } = inputs;
753
2068
  return sha256(
754
- canonicalJson({ provider, model, temperature, max_tokens, prompt_resolved, policy: policyVersion })
2069
+ canonicalJson({
2070
+ provider,
2071
+ model,
2072
+ temperature,
2073
+ max_tokens,
2074
+ prompt_resolved,
2075
+ policy: policyVersion,
2076
+ ...attempt !== void 0 && attempt > 0 ? { attempt } : {}
2077
+ })
755
2078
  );
756
2079
  }
757
2080
  function configHash(config) {
@@ -897,11 +2220,16 @@ var NoOpCache = class {
897
2220
  }
898
2221
  };
899
2222
 
2223
+ // src/orchestrator/index.ts
2224
+ init_cjs_shims();
2225
+
900
2226
  // src/orchestrator/run.ts
2227
+ init_cjs_shims();
901
2228
  var fs3 = __toESM(require("fs"), 1);
902
- var path2 = __toESM(require("path"), 1);
2229
+ var path3 = __toESM(require("path"), 1);
903
2230
 
904
2231
  // src/assertions/json-extract.ts
2232
+ init_cjs_shims();
905
2233
  function extractJson(output, mode) {
906
2234
  if (mode === "strict") {
907
2235
  return tryParse(output.trim());
@@ -944,8 +2272,8 @@ function* balancedRuns(s) {
944
2272
  }
945
2273
  }
946
2274
  function balancedFrom(s, start) {
947
- const open = s[start];
948
- const close = open === "{" ? "}" : "]";
2275
+ const open2 = s[start];
2276
+ const close = open2 === "{" ? "}" : "]";
949
2277
  let depth = 0;
950
2278
  let inString = false;
951
2279
  let escaped = false;
@@ -959,7 +2287,7 @@ function balancedFrom(s, start) {
959
2287
  }
960
2288
  if (ch === '"') {
961
2289
  inString = true;
962
- } else if (ch === open) {
2290
+ } else if (ch === open2) {
963
2291
  depth++;
964
2292
  } else if (ch === close) {
965
2293
  depth--;
@@ -969,7 +2297,17 @@ function balancedFrom(s, start) {
969
2297
  return null;
970
2298
  }
971
2299
 
2300
+ // src/assertions/index.ts
2301
+ init_cjs_shims();
2302
+
2303
+ // src/assertions/registry.ts
2304
+ init_cjs_shims();
2305
+
2306
+ // src/assertions/exact-match.ts
2307
+ init_cjs_shims();
2308
+
972
2309
  // src/assertions/interpolate.ts
2310
+ init_cjs_shims();
973
2311
  var PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/g;
974
2312
  function interpolate(template, ctx) {
975
2313
  return template.replace(PLACEHOLDER, (match, key) => {
@@ -1005,6 +2343,7 @@ var exactMatch = {
1005
2343
  };
1006
2344
 
1007
2345
  // src/assertions/contains.ts
2346
+ init_cjs_shims();
1008
2347
  function norm(s, ignoreCase) {
1009
2348
  return ignoreCase ? s.toLowerCase() : s;
1010
2349
  }
@@ -1041,6 +2380,7 @@ var containsAll = {
1041
2380
  };
1042
2381
 
1043
2382
  // src/assertions/json-schema.ts
2383
+ init_cjs_shims();
1044
2384
  var import_ajv = require("ajv");
1045
2385
  var jsonSchema = {
1046
2386
  run(ctx) {
@@ -1073,6 +2413,7 @@ var jsonSchema = {
1073
2413
  };
1074
2414
 
1075
2415
  // src/assertions/semantic-similarity.ts
2416
+ init_cjs_shims();
1076
2417
  var DEFAULT_THRESHOLD = 0.8;
1077
2418
  var semanticSimilarity = {
1078
2419
  async run(ctx) {
@@ -1095,7 +2436,11 @@ var semanticSimilarity = {
1095
2436
  }
1096
2437
  };
1097
2438
 
2439
+ // src/assertions/llm-judge.ts
2440
+ init_cjs_shims();
2441
+
1098
2442
  // src/assertions/judge-helpers.ts
2443
+ init_cjs_shims();
1099
2444
  async function askJson(judge, prompt5) {
1100
2445
  const text = await judge.ask(prompt5);
1101
2446
  const result = extractJson(text, "auto");
@@ -1165,6 +2510,7 @@ var llmJudge = {
1165
2510
  };
1166
2511
 
1167
2512
  // src/assertions/faithfulness.ts
2513
+ init_cjs_shims();
1168
2514
  var DEFAULT_THRESHOLD2 = 0.7;
1169
2515
  function prompt2(context, output) {
1170
2516
  return `Extract the atomic factual claims from the OUTPUT and judge whether each is supported by the CONTEXT. Respond ONLY with JSON: {"statements":[{"claim":"<text>","faithful":<true|false>}]}.
@@ -1190,6 +2536,7 @@ var faithfulness = {
1190
2536
  };
1191
2537
 
1192
2538
  // src/assertions/answer-relevance.ts
2539
+ init_cjs_shims();
1193
2540
  var DEFAULT_THRESHOLD3 = 0.7;
1194
2541
  function prompt3(output) {
1195
2542
  return `Generate the questions that the OUTPUT directly and fully answers. Respond ONLY with JSON: {"questions": ["<question>", ...]}.
@@ -1228,32 +2575,378 @@ var answerRelevance = {
1228
2575
  };
1229
2576
 
1230
2577
  // src/assertions/context-precision.ts
2578
+ init_cjs_shims();
1231
2579
  var DEFAULT_THRESHOLD4 = 0.7;
1232
2580
  function prompt4(context, question) {
1233
2581
  return `Judge from 0 to 1 how well the CONTEXT provides the information needed to answer the QUESTION. Respond ONLY with JSON: {"score": <0..1>, "reason": "<short explanation>"}.
1234
2582
 
1235
- QUESTION: ${question}
2583
+ QUESTION: ${question}
2584
+
2585
+ CONTEXT:
2586
+ ${context}`;
2587
+ }
2588
+ var contextPrecision = {
2589
+ async run(ctx) {
2590
+ if (ctx.judge === void 0) {
2591
+ throw new Error("context-precision requires a judge in the AssertionContext");
2592
+ }
2593
+ const context = interpolate(ctx.params.context, ctx);
2594
+ const question = interpolate(ctx.params.question, ctx);
2595
+ const threshold = ctx.params.threshold ?? DEFAULT_THRESHOLD4;
2596
+ const { score, reason } = parseScored(await askJson(ctx.judge, prompt4(context, question)));
2597
+ const passed = score >= threshold;
2598
+ return {
2599
+ passed,
2600
+ score,
2601
+ reason: reason ?? `context-precision ${score.toFixed(3)} vs threshold ${threshold}`
2602
+ };
2603
+ }
2604
+ };
2605
+
2606
+ // src/assertions/tool-calls/calls.ts
2607
+ init_cjs_shims();
2608
+
2609
+ // src/assertions/tool-calls/transcript.ts
2610
+ init_cjs_shims();
2611
+ var AssertionRunError = class extends Error {
2612
+ constructor(code, message) {
2613
+ super(message);
2614
+ this.code = code;
2615
+ this.name = "AssertionRunError";
2616
+ }
2617
+ code;
2618
+ };
2619
+ var AFTER = " The assertions after it in this row were not run.";
2620
+ function check(body) {
2621
+ return {
2622
+ run(ctx) {
2623
+ try {
2624
+ return Promise.resolve(body(ctx));
2625
+ } catch (err) {
2626
+ return Promise.reject(err);
2627
+ }
2628
+ }
2629
+ };
2630
+ }
2631
+ var pass = { passed: true };
2632
+ var fail = (reason) => ({ passed: false, reason });
2633
+ function unmeasured(type, why) {
2634
+ return new AssertionRunError(
2635
+ "ASSERTION_UNMEASURED",
2636
+ `${type}: not measured because ${why}.${AFTER}`
2637
+ );
2638
+ }
2639
+ function transcriptOf(type, ctx) {
2640
+ if (ctx.transcript === void 0)
2641
+ throw unmeasured(type, "there is no tool loop to read (the eval has no mcp block)");
2642
+ return ctx.transcript;
2643
+ }
2644
+ function callsOf(t) {
2645
+ return t.steps.flatMap((s) => s.calls.map((call) => ({ step: s.index, call })));
2646
+ }
2647
+ function callsFor(t, tool) {
2648
+ const all = callsOf(t);
2649
+ return tool === void 0 ? all : all.filter((c) => c.call.name === tool);
2650
+ }
2651
+ function checkNames(type, t, names) {
2652
+ const offered = t.tools.filter((x) => x.offered).map((x) => x.name);
2653
+ const unknown = names.find((n) => n !== void 0 && !offered.includes(n));
2654
+ if (unknown === void 0) return;
2655
+ const list = offered.length > 0 ? offered.join(", ") : "(none)";
2656
+ throw new AssertionRunError(
2657
+ "ASSERTION_UNKNOWN_TOOL",
2658
+ `${type}: no tool "${unknown}" was offered to the model; offered: ${list}.${AFTER}`
2659
+ );
2660
+ }
2661
+ function absence(type, t, what) {
2662
+ if (t.collection === "complete") return pass;
2663
+ const why = t.stop.reason === "limit" ? `the loop was stopped by ${t.stop.limit ?? "a limit"}` : "the transcript is partial (a stored excerpt was cut)";
2664
+ throw unmeasured(
2665
+ type,
2666
+ `${why}, so ${what} may be in what was not seen; nothing was found in what was`
2667
+ );
2668
+ }
2669
+ var ARGS_CHARS = 80;
2670
+ var LISTED = 5;
2671
+ function describeArgs(args) {
2672
+ const text = redactSecrets(JSON.stringify(args) ?? "undefined");
2673
+ return text.length > ARGS_CHARS ? `${text.slice(0, ARGS_CHARS)} (cut)` : text;
2674
+ }
2675
+ function describeCall({ step, call }) {
2676
+ return `step ${step} ${call.name} ${describeArgs(call.args)}`;
2677
+ }
2678
+ function describeCalls(calls, detail = describeCall) {
2679
+ if (calls.length === 0) return "no tool call";
2680
+ const shown = calls.slice(0, LISTED).map(detail).join("; ");
2681
+ return calls.length > LISTED ? `${shown} (and ${calls.length - LISTED} more)` : shown;
2682
+ }
2683
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
2684
+ function sameJson(a, b) {
2685
+ return a !== void 0 && b !== void 0 && canonicalJson(a) === canonicalJson(b);
2686
+ }
2687
+
2688
+ // src/assertions/tool-calls/calls.ts
2689
+ var toolCalled = check((ctx) => {
2690
+ const { tool, min_count: min = 1 } = ctx.params;
2691
+ const t = transcriptOf("tool-called", ctx);
2692
+ checkNames("tool-called", t, [tool]);
2693
+ const calls = callsFor(t, tool);
2694
+ if (calls.length >= min) return pass;
2695
+ return fail(
2696
+ `expected "${tool}" called at least ${plural(min, "time")}; got ${calls.length} (${describeCalls(callsOf(t))}); check that the tool's description tells the model when to use it`
2697
+ );
2698
+ });
2699
+ var toolNotCalled = check((ctx) => {
2700
+ const { tool } = ctx.params;
2701
+ const t = transcriptOf("tool-not-called", ctx);
2702
+ checkNames("tool-not-called", t, [tool]);
2703
+ const calls = callsFor(t, tool);
2704
+ if (calls.length === 0) return absence("tool-not-called", t, `a call to "${tool}"`);
2705
+ return fail(
2706
+ `expected "${tool}" never called; got ${plural(calls.length, "call")}: ${describeCalls(calls)}; check what in the prompt or the tool list led the model to it`
2707
+ );
2708
+ });
2709
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2710
+ function partialMatch(expected, actual) {
2711
+ if (!isRecord(expected)) return sameJson(expected, actual);
2712
+ return isRecord(actual) && Object.entries(expected).every(
2713
+ ([k, v]) => Object.hasOwn(actual, k) && partialMatch(v, actual[k])
2714
+ );
2715
+ }
2716
+ function interpolateDeep(value, ctx) {
2717
+ if (typeof value === "string") return interpolate(value, ctx);
2718
+ if (Array.isArray(value)) return value.map((v) => interpolateDeep(v, ctx));
2719
+ if (isRecord(value))
2720
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, interpolateDeep(v, ctx)]));
2721
+ return value;
2722
+ }
2723
+ var toolArgs = check((ctx) => {
2724
+ const { tool, match = "partial", min_count: min = 1 } = ctx.params;
2725
+ const t = transcriptOf("tool-args", ctx);
2726
+ checkNames("tool-args", t, [tool]);
2727
+ const args = interpolateDeep(ctx.params.args, ctx);
2728
+ const matches = (actual) => match === "ignore" || (match === "exact" ? sameJson(args, actual) : partialMatch(args, actual));
2729
+ const calls = callsFor(t, tool);
2730
+ const hits = calls.filter((c) => matches(c.call.args)).length;
2731
+ if (hits >= min) return pass;
2732
+ return fail(
2733
+ `expected a call to "${tool}" with arguments ${describeArgs(args)} (${match}) at least ${plural(min, "time")}; got ${hits} of ${plural(calls.length, "call")}: ${describeCalls(calls)}; check the argument names and values against the tool's input schema`
2734
+ );
2735
+ });
2736
+ var onlyTools = check((ctx) => {
2737
+ const { tools } = ctx.params;
2738
+ const t = transcriptOf("only-tools", ctx);
2739
+ checkNames("only-tools", t, tools);
2740
+ const off = callsOf(t).filter((c) => !tools.includes(c.call.name));
2741
+ if (off.length === 0) return absence("only-tools", t, "a call to another tool");
2742
+ const allowed = tools.length > 0 ? `only ${tools.join(", ")} called` : "no tool call";
2743
+ return fail(
2744
+ `expected ${allowed}; got ${describeCalls(off)}; check whether allowed_tools should leave the others out`
2745
+ );
2746
+ });
2747
+
2748
+ // src/assertions/tool-calls/order.ts
2749
+ init_cjs_shims();
2750
+ function inOrder(names, tools) {
2751
+ let next = 0;
2752
+ for (const n of names) if (n === tools[next]) next++;
2753
+ return next === tools.length;
2754
+ }
2755
+ var toolOrder = check((ctx) => {
2756
+ const { tools, strict = false } = ctx.params;
2757
+ const t = transcriptOf("tool-order", ctx);
2758
+ checkNames("tool-order", t, tools);
2759
+ const calls = callsOf(t);
2760
+ const names = calls.map((c) => c.call.name);
2761
+ const ok = strict ? names.length === tools.length && names.every((n, i) => n === tools[i]) : inOrder(names, tools);
2762
+ if (ok) return pass;
2763
+ const wanted = tools.join(" \u2192 ");
2764
+ return fail(
2765
+ `expected ${strict ? `exactly the calls ${wanted}` : `calls in the order ${wanted}`}; got ${describeCalls(calls)}; check whether the model had what it needed for each step before it`
2766
+ );
2767
+ });
2768
+ var firstTool = check((ctx) => {
2769
+ const { tool } = ctx.params;
2770
+ const t = transcriptOf("first-tool", ctx);
2771
+ checkNames("first-tool", t, [tool]);
2772
+ const first = callsOf(t)[0];
2773
+ if (first?.call.name === tool) return pass;
2774
+ const got = first === void 0 ? "no tool call at all: the model answered without one" : describeCall(first);
2775
+ return fail(
2776
+ `expected the first call to be "${tool}"; got ${got}; check that the prompt and the tool's description point the model to it first`
2777
+ );
2778
+ });
2779
+ var noRepeatedCall = check((ctx) => {
2780
+ const { tool } = ctx.params;
2781
+ const t = transcriptOf("no-repeated-call", ctx);
2782
+ checkNames("no-repeated-call", t, [tool]);
2783
+ const calls = callsOf(t);
2784
+ for (let i = 1; i < calls.length; i++) {
2785
+ const [prev, cur] = [calls[i - 1], calls[i]];
2786
+ if (tool !== void 0 && cur.call.name !== tool) continue;
2787
+ if (prev.call.name === cur.call.name && sameJson(prev.call.args, cur.call.args))
2788
+ return fail(
2789
+ `expected no call repeated right after itself; got ${describeCall(prev)} then ${describeCall(cur)}; check whether the first answer told the model what it needed`
2790
+ );
2791
+ }
2792
+ return pass;
2793
+ });
1236
2794
 
1237
- CONTEXT:
1238
- ${context}`;
2795
+ // src/assertions/tool-calls/errors.ts
2796
+ init_cjs_shims();
2797
+ var import_ajv2 = require("ajv");
2798
+ function failedOn(found) {
2799
+ const why = new Map(found.map((f) => [f.c, f.why]));
2800
+ return describeCalls(
2801
+ found.map((f) => f.c),
2802
+ (c) => `${describeCall(c)}: ${why.get(c)}`
2803
+ );
1239
2804
  }
1240
- var contextPrecision = {
1241
- async run(ctx) {
1242
- if (ctx.judge === void 0) {
1243
- throw new Error("context-precision requires a judge in the AssertionContext");
2805
+ var noToolErrors = check((ctx) => {
2806
+ const { tool } = ctx.params;
2807
+ const t = transcriptOf("no-tool-errors", ctx);
2808
+ checkNames("no-tool-errors", t, [tool]);
2809
+ const errors = callsFor(t, tool).filter((c) => c.call.is_error);
2810
+ if (errors.length === 0) return absence("no-tool-errors", t, "a call with an error");
2811
+ return fail(
2812
+ `expected no tool call with an error; got ${describeCalls(errors, (c) => `${describeCall(c)} (${c.call.error_kind ?? "error"})`)}; check the arguments the model sent against the tool's input schema`
2813
+ );
2814
+ });
2815
+ function riskOf(name, annotations) {
2816
+ if (annotations?.readOnlyHint === true || annotations?.destructiveHint === false)
2817
+ return void 0;
2818
+ if (annotations === void 0)
2819
+ return `"${name}" declares no annotations, and MCP treats a missing hint as possibly destructive`;
2820
+ if (annotations.destructiveHint === true) return `"${name}" declares destructiveHint: true`;
2821
+ return `"${name}" declares neither readOnlyHint: true nor destructiveHint: false`;
2822
+ }
2823
+ var noDestructiveTool = check((ctx) => {
2824
+ const t = transcriptOf("no-destructive-tool", ctx);
2825
+ if (t.tools.length === 0)
2826
+ throw unmeasured("no-destructive-tool", "there is no tools/list with annotations to read");
2827
+ const listed = new Map(t.tools.map((x) => [x.name, x.annotations]));
2828
+ const risky = [];
2829
+ for (const c of callsOf(t)) {
2830
+ if (!listed.has(c.call.name)) continue;
2831
+ const why = riskOf(c.call.name, listed.get(c.call.name));
2832
+ if (why !== void 0) risky.push({ c, why });
2833
+ }
2834
+ if (risky.length === 0) return absence("no-destructive-tool", t, "a call to a destructive tool");
2835
+ return fail(
2836
+ `expected no call to a tool that may be destructive; got ${failedOn(risky)}; the hints are the server's own claim, so check them on the server`
2837
+ );
2838
+ });
2839
+ var toolResultSchema = check((ctx) => {
2840
+ const type = "tool-result-schema";
2841
+ const { tool } = ctx.params;
2842
+ const t = transcriptOf(type, ctx);
2843
+ checkNames(type, t, [tool]);
2844
+ const ajv = new import_ajv2.Ajv({ allErrors: true });
2845
+ let validate;
2846
+ try {
2847
+ validate = ajv.compile(ctx.params.schema);
2848
+ } catch (err) {
2849
+ return fail(`invalid schema: ${err.message}`);
2850
+ }
2851
+ const answered = callsFor(t, tool).filter((c) => c.call.executed && !c.call.is_error);
2852
+ const bad = [];
2853
+ let unread;
2854
+ for (const c of answered) {
2855
+ const result = c.call.result;
2856
+ if (result === void 0 || result.truncated) {
2857
+ unread ??= result === void 0 ? `${describeCall(c)} has no result` : `the result of ${describeCall(c)} was cut to its excerpt`;
2858
+ continue;
1244
2859
  }
1245
- const context = interpolate(ctx.params.context, ctx);
1246
- const question = interpolate(ctx.params.question, ctx);
1247
- const threshold = ctx.params.threshold ?? DEFAULT_THRESHOLD4;
1248
- const { score, reason } = parseScored(await askJson(ctx.judge, prompt4(context, question)));
1249
- const passed = score >= threshold;
1250
- return {
1251
- passed,
1252
- score,
1253
- reason: reason ?? `context-precision ${score.toFixed(3)} vs threshold ${threshold}`
1254
- };
2860
+ let value;
2861
+ try {
2862
+ value = JSON.parse(result.text);
2863
+ } catch {
2864
+ bad.push({ c, why: "not JSON" });
2865
+ continue;
2866
+ }
2867
+ if (!validate(value))
2868
+ bad.push({ c, why: ajv.errorsText(validate.errors, { separator: "; " }) });
1255
2869
  }
1256
- };
2870
+ if (bad.length > 0) {
2871
+ const scope = tool === void 0 ? "every result" : `every result of "${tool}"`;
2872
+ return fail(
2873
+ `expected ${scope} to fit the schema; got ${failedOn(bad)}; check the tool's outputSchema against what it returns`
2874
+ );
2875
+ }
2876
+ if (unread !== void 0) throw unmeasured(type, unread);
2877
+ if (answered.length === 0)
2878
+ throw unmeasured(type, "no call answered, so there is no result to check");
2879
+ return pass;
2880
+ });
2881
+
2882
+ // src/assertions/tool-calls/measures.ts
2883
+ init_cjs_shims();
2884
+ var toolCallCount = check((ctx) => {
2885
+ const { tool, min, max } = ctx.params;
2886
+ const t = transcriptOf("tool-call-count", ctx);
2887
+ checkNames("tool-call-count", t, [tool]);
2888
+ const calls = callsFor(t, tool);
2889
+ const n = calls.length;
2890
+ if ((min === void 0 || n >= min) && (max === void 0 || n <= max)) return pass;
2891
+ const bound = min === void 0 ? `at most ${plural(max, "call")}` : max === void 0 ? `at least ${plural(min, "call")}` : `${min} to ${max} calls`;
2892
+ const of = tool === void 0 ? "" : ` to "${tool}"`;
2893
+ return fail(
2894
+ `expected ${bound}${of}; got ${n}: ${describeCalls(calls)}; check the limits and whether the model had what it needed`
2895
+ );
2896
+ });
2897
+ var tokenBudget = check((ctx) => {
2898
+ const { max } = ctx.params;
2899
+ const t = transcriptOf("token-budget", ctx);
2900
+ if (t.steps.length === 0)
2901
+ throw unmeasured("token-budget", "no model step was recorded, so there are no tokens to count");
2902
+ const per = t.steps.map((s) => ({
2903
+ step: s.index,
2904
+ tokens: s.usage.input_tokens + s.usage.output_tokens
2905
+ }));
2906
+ const total = per.reduce((a, s) => a + s.tokens, 0);
2907
+ if (total <= max) return pass;
2908
+ const steps = per.map((s) => `step ${s.step}: ${s.tokens}`).join(", ");
2909
+ return fail(
2910
+ `expected at most ${max} tokens (input + output, every step); got ${total} (${steps}); check the size of the tool descriptions and results the model reads every step`
2911
+ );
2912
+ });
2913
+ function eachCall(type, calls, value, bound) {
2914
+ const ran = calls.filter((c) => c.call.executed);
2915
+ const over = ran.filter((c) => (value(c) ?? 0) > bound.max);
2916
+ if (over.length > 0)
2917
+ return fail(
2918
+ `expected ${bound.expected}; got ${describeCalls(over, (c) => `${describeCall(c)}: ${value(c)} ${bound.unit}`)}; ${bound.hint}`
2919
+ );
2920
+ const missing = ran.find((c) => value(c) === void 0);
2921
+ if (missing !== void 0)
2922
+ throw unmeasured(type, `${describeCall(missing)} ran and its ${bound.unit} were not recorded`);
2923
+ if (ran.length === 0) throw unmeasured(type, "no call ran, so there is nothing to measure");
2924
+ return pass;
2925
+ }
2926
+ var toolLatency = check((ctx) => {
2927
+ const { tool, max_ms: max } = ctx.params;
2928
+ const t = transcriptOf("tool-latency", ctx);
2929
+ checkNames("tool-latency", t, [tool]);
2930
+ const scope = tool === void 0 ? "every call" : `every call to "${tool}"`;
2931
+ return eachCall("tool-latency", callsFor(t, tool), (c) => c.call.duration_ms, {
2932
+ max,
2933
+ unit: "ms",
2934
+ expected: `${scope} within ${max} ms`,
2935
+ hint: "check the server for what makes the call slow"
2936
+ });
2937
+ });
2938
+ var toolResultSize = check((ctx) => {
2939
+ const { tool, max_bytes: max } = ctx.params;
2940
+ const t = transcriptOf("tool-result-size", ctx);
2941
+ checkNames("tool-result-size", t, [tool]);
2942
+ const scope = tool === void 0 ? "every result" : `every result of "${tool}"`;
2943
+ return eachCall("tool-result-size", callsFor(t, tool), (c) => c.call.result?.bytes, {
2944
+ max,
2945
+ unit: "bytes",
2946
+ expected: `${scope} at most ${max} bytes`,
2947
+ hint: "check whether the tool can page or filter what it returns"
2948
+ });
2949
+ });
1257
2950
 
1258
2951
  // src/assertions/registry.ts
1259
2952
  function createAssertionRegistry() {
@@ -1275,6 +2968,9 @@ function createAssertionRegistry() {
1275
2968
  },
1276
2969
  has(type) {
1277
2970
  return impls.has(type);
2971
+ },
2972
+ types() {
2973
+ return [...impls.keys()];
1278
2974
  }
1279
2975
  };
1280
2976
  }
@@ -1290,6 +2986,20 @@ function createDefaultRegistry2() {
1290
2986
  registry.register("faithfulness", faithfulness);
1291
2987
  registry.register("answer-relevance", answerRelevance);
1292
2988
  registry.register("context-precision", contextPrecision);
2989
+ registry.register("tool-called", toolCalled);
2990
+ registry.register("tool-not-called", toolNotCalled);
2991
+ registry.register("tool-args", toolArgs);
2992
+ registry.register("tool-order", toolOrder);
2993
+ registry.register("only-tools", onlyTools);
2994
+ registry.register("first-tool", firstTool);
2995
+ registry.register("no-tool-errors", noToolErrors);
2996
+ registry.register("tool-call-count", toolCallCount);
2997
+ registry.register("no-repeated-call", noRepeatedCall);
2998
+ registry.register("token-budget", tokenBudget);
2999
+ registry.register("tool-latency", toolLatency);
3000
+ registry.register("tool-result-size", toolResultSize);
3001
+ registry.register("tool-result-schema", toolResultSchema);
3002
+ registry.register("no-destructive-tool", noDestructiveTool);
1293
3003
  return registry;
1294
3004
  }
1295
3005
  var defaultRegistry;
@@ -1298,7 +3008,38 @@ function getAssertion(type) {
1298
3008
  return defaultRegistry.resolve(type);
1299
3009
  }
1300
3010
 
3011
+ // src/assertions/classes.ts
3012
+ init_cjs_shims();
3013
+ var ASSERTION_CLASSES = {
3014
+ "exact-match": "deterministic",
3015
+ contains: "deterministic",
3016
+ "contains-any": "deterministic",
3017
+ "contains-all": "deterministic",
3018
+ "json-schema": "deterministic",
3019
+ // A score against the author's threshold. They decide the row as they always have.
3020
+ "semantic-similarity": "measure",
3021
+ "llm-judge": "measure",
3022
+ faithfulness: "measure",
3023
+ "answer-relevance": "measure",
3024
+ "context-precision": "measure",
3025
+ "tool-called": "deterministic",
3026
+ "tool-not-called": "deterministic",
3027
+ "tool-args": "deterministic",
3028
+ "tool-order": "deterministic",
3029
+ "only-tools": "deterministic",
3030
+ "first-tool": "deterministic",
3031
+ "no-tool-errors": "deterministic",
3032
+ "tool-call-count": "measure",
3033
+ "no-repeated-call": "heuristic",
3034
+ "token-budget": "measure",
3035
+ "tool-latency": "measure",
3036
+ "tool-result-size": "measure",
3037
+ "tool-result-schema": "deterministic",
3038
+ "no-destructive-tool": "deterministic"
3039
+ };
3040
+
1301
3041
  // src/orchestrator/judge.ts
3042
+ init_cjs_shims();
1302
3043
  var DEFAULT_MAX_TOKENS = 1024;
1303
3044
  function buildJudge(provider, cfg, onUsage) {
1304
3045
  return {
@@ -1317,7 +3058,8 @@ function buildJudge(provider, cfg, onUsage) {
1317
3058
  }
1318
3059
 
1319
3060
  // src/orchestrator/concurrency.ts
1320
- async function mapLimit(items, limit, fn) {
3061
+ init_cjs_shims();
3062
+ async function mapLimit(items, limit2, fn) {
1321
3063
  const results = new Array(items.length);
1322
3064
  let next = 0;
1323
3065
  const worker = async () => {
@@ -1327,13 +3069,17 @@ async function mapLimit(items, limit, fn) {
1327
3069
  results[i] = await fn(items[i], i);
1328
3070
  }
1329
3071
  };
1330
- const safeLimit = Number.isFinite(limit) && limit >= 1 ? Math.floor(limit) : 1;
3072
+ const safeLimit = Number.isFinite(limit2) && limit2 >= 1 ? Math.floor(limit2) : 1;
1331
3073
  const workerCount = Math.min(safeLimit, items.length);
1332
3074
  await Promise.all(Array.from({ length: workerCount }, () => worker()));
1333
3075
  return results;
1334
3076
  }
1335
3077
 
3078
+ // src/types/results.ts
3079
+ init_cjs_shims();
3080
+
1336
3081
  // src/types/test-case-schema.ts
3082
+ init_cjs_shims();
1337
3083
  var import_zod2 = require("zod");
1338
3084
  var TEST_CASE_SCHEMA_VERSION = 2;
1339
3085
  var externalKeySchema = import_zod2.z.object({
@@ -1391,8 +3137,301 @@ function rowStatus(row) {
1391
3137
  return row.assertions.every((a) => a.passed) ? "passed" : "failed";
1392
3138
  }
1393
3139
 
1394
- // src/orchestrator/run.ts
3140
+ // src/orchestrator/agent.ts
3141
+ init_cjs_shims();
3142
+
3143
+ // src/orchestrator/tool-names.ts
3144
+ init_cjs_shims();
3145
+ var SAFE = /^[a-zA-Z0-9_-]{1,64}$/;
3146
+ var MAX = 64;
3147
+ function wireNames(names) {
3148
+ const toWire = /* @__PURE__ */ new Map();
3149
+ const toServer = /* @__PURE__ */ new Map();
3150
+ for (const name of names)
3151
+ if (SAFE.test(name) && !toServer.has(name)) {
3152
+ toWire.set(name, name);
3153
+ toServer.set(name, name);
3154
+ }
3155
+ for (const name of names) {
3156
+ if (toWire.has(name)) continue;
3157
+ const base = name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, MAX) || "tool";
3158
+ let wire = base;
3159
+ for (let n = 2; toServer.has(wire); n++) wire = `${base.slice(0, MAX - `_${n}`.length)}_${n}`;
3160
+ toWire.set(name, wire);
3161
+ toServer.set(wire, name);
3162
+ }
3163
+ return { toWire, toServer };
3164
+ }
3165
+
3166
+ // src/orchestrator/agent.ts
3167
+ var EXCERPT_BYTES = 4 * 1024;
3168
+ var TRANSCRIPT_BYTES = 256 * 1024;
1395
3169
  var DEFAULT_MAX_TOKENS2 = 1024;
3170
+ var LimitStop = class extends Error {
3171
+ constructor(limit2) {
3172
+ super(`stopped by ${limit2}`);
3173
+ this.limit = limit2;
3174
+ }
3175
+ limit;
3176
+ };
3177
+ var AgentError = class extends Error {
3178
+ constructor(code, message) {
3179
+ super(message);
3180
+ this.code = code;
3181
+ }
3182
+ code;
3183
+ };
3184
+ var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3185
+ function resultText(result) {
3186
+ if (!isRecord2(result)) return JSON.stringify(result) ?? "";
3187
+ const content = Array.isArray(result.content) ? result.content : [];
3188
+ if (content.length === 0 && result.structuredContent !== void 0)
3189
+ return JSON.stringify(result.structuredContent);
3190
+ return content.map(
3191
+ (b) => isRecord2(b) && b.type === "text" && typeof b.text === "string" ? b.text : JSON.stringify(b)
3192
+ ).join("\n");
3193
+ }
3194
+ function excerpts() {
3195
+ let left = TRANSCRIPT_BYTES;
3196
+ const state = {
3197
+ any: false,
3198
+ cut(text) {
3199
+ const whole = Buffer.from(text, "utf8");
3200
+ const keep = Math.max(0, Math.min(EXCERPT_BYTES, left, whole.length));
3201
+ left -= keep;
3202
+ const truncated = keep < whole.length;
3203
+ if (truncated) state.any = true;
3204
+ const kept = truncated ? whole.subarray(0, keep).toString("utf8").replace(/�$/, "") : text;
3205
+ return { text: kept, bytes: whole.length, truncated };
3206
+ }
3207
+ };
3208
+ return state;
3209
+ }
3210
+ function listedTools(items) {
3211
+ const seen = /* @__PURE__ */ new Set();
3212
+ return items.filter((t) => {
3213
+ if (!isRecord2(t) || typeof t.name !== "string" || t.name === "" || seen.has(t.name))
3214
+ return false;
3215
+ seen.add(t.name);
3216
+ return true;
3217
+ });
3218
+ }
3219
+ async function runAgentRow(p) {
3220
+ const t0 = p.now();
3221
+ const prompt5 = resolvePrompt(p.template, p.row.vars);
3222
+ const temperature = p.providerConfig.temperature;
3223
+ const maxTokens = p.providerConfig.max_tokens ?? DEFAULT_MAX_TOKENS2;
3224
+ const { limits } = p;
3225
+ if (p.dryRun) {
3226
+ const one = estimateUsage(prompt5, maxTokens);
3227
+ const est = {
3228
+ input_tokens: one.input_tokens * limits.max_steps,
3229
+ output_tokens: one.output_tokens * limits.max_steps
3230
+ };
3231
+ return {
3232
+ vars: p.row.vars,
3233
+ output: null,
3234
+ cached: false,
3235
+ usage: { ...est, ...costFields(p.provider.estimateCost(est)) },
3236
+ assertions: []
3237
+ };
3238
+ }
3239
+ const respond = p.provider.respond.bind(p.provider);
3240
+ const deadline = t0 + limits.timeout_ms;
3241
+ const bounded = (work) => {
3242
+ const ms = deadline - p.now();
3243
+ let timer;
3244
+ return Promise.race([
3245
+ work,
3246
+ new Promise((_, reject) => {
3247
+ timer = setTimeout(() => reject(new LimitStop("timeout_ms")), Math.max(0, ms));
3248
+ })
3249
+ ]).finally(() => clearTimeout(timer));
3250
+ };
3251
+ const transcript = {
3252
+ server: p.server,
3253
+ tools: [],
3254
+ steps: [],
3255
+ stop: { reason: "complete" },
3256
+ collection: "complete"
3257
+ };
3258
+ const kept = excerpts();
3259
+ const usages = [];
3260
+ let output = "";
3261
+ let error;
3262
+ let session;
3263
+ try {
3264
+ const opening = p.connect(p.server, limits.timeout_ms);
3265
+ try {
3266
+ session = await bounded(opening);
3267
+ } catch (err) {
3268
+ void opening.then(
3269
+ (s) => s.close(),
3270
+ () => {
3271
+ }
3272
+ );
3273
+ if (err instanceof LimitStop) throw err;
3274
+ throw new AgentError("MCP_CONNECT", err.message);
3275
+ }
3276
+ let listed;
3277
+ try {
3278
+ listed = listedTools(await bounded(session.listTools(limits.tool_timeout_ms)));
3279
+ } catch (err) {
3280
+ if (err instanceof LimitStop) throw err;
3281
+ throw new AgentError("MCP_LIST_TOOLS", `tools/list failed: ${err.message}`);
3282
+ }
3283
+ const offered = listed.filter(
3284
+ (t) => p.allowedTools === void 0 || p.allowedTools.includes(t.name)
3285
+ );
3286
+ transcript.tools = listed.map((t) => ({
3287
+ name: t.name,
3288
+ offered: offered.includes(t),
3289
+ ...isRecord2(t.annotations) ? { annotations: t.annotations } : {}
3290
+ }));
3291
+ const names = wireNames(offered.map((t) => t.name));
3292
+ const tools = offered.map((t) => ({
3293
+ name: names.toWire.get(t.name),
3294
+ ...typeof t.description === "string" ? { description: t.description } : {},
3295
+ input_schema: isRecord2(t.inputSchema) ? t.inputSchema : { type: "object" }
3296
+ }));
3297
+ const messages = [{ role: "user", content: prompt5 }];
3298
+ let calls = 0;
3299
+ let tokens = 0;
3300
+ for (let index = 1; ; index++) {
3301
+ const res = await bounded(
3302
+ respond({
3303
+ provider: p.providerConfig.type,
3304
+ model: p.providerConfig.model,
3305
+ ...temperature !== void 0 ? { temperature } : {},
3306
+ max_tokens: maxTokens,
3307
+ messages,
3308
+ tools
3309
+ })
3310
+ );
3311
+ const usage2 = {
3312
+ ...res.usage,
3313
+ ...costFields(p.provider.estimateCost(res.usage, res.cost_usd))
3314
+ };
3315
+ usages.push(usage2);
3316
+ tokens += res.usage.input_tokens + res.usage.output_tokens;
3317
+ output = res.text;
3318
+ const records2 = res.tool_calls.map((c) => ({
3319
+ id: c.id,
3320
+ name: names.toServer.get(c.name) ?? c.name,
3321
+ args: c.args,
3322
+ executed: false,
3323
+ is_error: false
3324
+ }));
3325
+ const step = {
3326
+ index,
3327
+ text: kept.cut(res.text).text,
3328
+ ...res.finish_reason !== void 0 ? { finish_reason: res.finish_reason } : {},
3329
+ usage: usage2,
3330
+ calls: records2
3331
+ };
3332
+ transcript.steps.push(step);
3333
+ if (res.finish_reason === "error")
3334
+ throw new AgentError(
3335
+ "PROVIDER_ERROR",
3336
+ "The provider answered with an error instead of a turn."
3337
+ );
3338
+ if (res.tool_calls.length === 0) break;
3339
+ if (res.finish_reason === "length")
3340
+ throw new AgentError(
3341
+ "AGENT_CUT_OFF",
3342
+ `Step ${index} hit max_tokens in the middle of a tool call.`
3343
+ );
3344
+ if (index >= limits.max_steps) throw new LimitStop("max_steps");
3345
+ if (tokens > limits.max_total_tokens) throw new LimitStop("max_total_tokens");
3346
+ const results = [];
3347
+ const answer = (rec, c, content) => results.push({ id: c.id, content, is_error: rec.is_error });
3348
+ for (const [i, c] of res.tool_calls.entries()) {
3349
+ const rec = records2[i];
3350
+ if (calls >= limits.max_tool_calls) throw new LimitStop("max_tool_calls");
3351
+ calls++;
3352
+ const server = names.toServer.get(c.name);
3353
+ if (server === void 0) {
3354
+ Object.assign(rec, { is_error: true, error_kind: "not-offered" });
3355
+ answer(rec, c, `Tool "${c.name}" is not available.`);
3356
+ continue;
3357
+ }
3358
+ if (c.args_invalid === true || !isRecord2(c.args)) {
3359
+ Object.assign(rec, { is_error: true, error_kind: "bad-arguments" });
3360
+ answer(rec, c, "The arguments are not a JSON object.");
3361
+ continue;
3362
+ }
3363
+ const started = p.now();
3364
+ rec.executed = true;
3365
+ const got = await bounded(session.callTool(server, c.args, limits.tool_timeout_ms));
3366
+ rec.duration_ms = p.now() - started;
3367
+ if (got.kind === "timeout") {
3368
+ Object.assign(rec, { is_error: true, error_kind: "timeout" });
3369
+ throw new LimitStop("tool_timeout_ms");
3370
+ }
3371
+ if (got.kind === "lost") throw new AgentError("MCP_SERVER_LOST", got.message);
3372
+ const text = got.kind === "error" ? got.message : resultText(got.result);
3373
+ if (got.kind === "error") Object.assign(rec, { is_error: true, error_kind: "protocol" });
3374
+ else if (isRecord2(got.result) && got.result.isError === true)
3375
+ Object.assign(rec, { is_error: true, error_kind: "content" });
3376
+ rec.result = kept.cut(text);
3377
+ answer(rec, c, text);
3378
+ }
3379
+ messages.push(
3380
+ { role: "assistant", text: res.text, tool_calls: res.tool_calls },
3381
+ { role: "tool", results }
3382
+ );
3383
+ }
3384
+ } catch (err) {
3385
+ if (err instanceof LimitStop) transcript.stop = { reason: "limit", limit: err.limit };
3386
+ else {
3387
+ transcript.stop = { reason: "error" };
3388
+ error = err instanceof AgentError ? { code: err.code, message: err.message } : toRunError(err);
3389
+ }
3390
+ } finally {
3391
+ await session?.close().catch(() => {
3392
+ });
3393
+ }
3394
+ if (transcript.stop.reason !== "complete" || kept.any) transcript.collection = "partial";
3395
+ const mask = session?.redact;
3396
+ const agent = mask?.value(transcript) ?? transcript;
3397
+ const spent = usages.length > 0 ? { usage: sumUsage(usages) } : {};
3398
+ if (error !== void 0) {
3399
+ return {
3400
+ vars: p.row.vars,
3401
+ output: null,
3402
+ cached: false,
3403
+ ...spent,
3404
+ latency_ms: p.now() - t0,
3405
+ error: { code: error.code, message: mask?.text(error.message) ?? error.message },
3406
+ assertions: [],
3407
+ agent
3408
+ };
3409
+ }
3410
+ const { records, assertionError, judgeCost, judgeUnpriced, advice } = await assess(
3411
+ p,
3412
+ output,
3413
+ agent
3414
+ );
3415
+ if (advice.length > 0) agent.advice = advice;
3416
+ const usage = sumUsage(usages);
3417
+ return {
3418
+ vars: p.row.vars,
3419
+ output: mask?.text(output) ?? output,
3420
+ cached: false,
3421
+ usage: {
3422
+ ...usage,
3423
+ cost_usd: usage.cost_usd + judgeCost,
3424
+ ...judgeUnpriced ? { priced: false } : {}
3425
+ },
3426
+ latency_ms: p.now() - t0,
3427
+ ...assertionError !== void 0 ? { error: assertionError } : {},
3428
+ assertions: records,
3429
+ agent
3430
+ };
3431
+ }
3432
+
3433
+ // src/orchestrator/run.ts
3434
+ var DEFAULT_MAX_TOKENS3 = 1024;
1396
3435
  var PLUNE_VERSION = "0.1.0";
1397
3436
  var RunConfigError = class extends Error {
1398
3437
  code = "CONFIG_ERROR";
@@ -1416,7 +3455,7 @@ function resolvePrompt(template, vars) {
1416
3455
  });
1417
3456
  }
1418
3457
  function toRunError(err) {
1419
- if (err instanceof ProviderError || err instanceof AuthError) {
3458
+ if (err instanceof ProviderError || err instanceof AuthError || err instanceof AssertionRunError) {
1420
3459
  return { code: err.code, message: err.message };
1421
3460
  }
1422
3461
  return { code: "ERROR", message: err instanceof Error ? err.message : String(err) };
@@ -1430,11 +3469,55 @@ function pricedField(priced) {
1430
3469
  function costFields(c) {
1431
3470
  return { cost_usd: c.cost_usd, ...pricedField(c.priced) };
1432
3471
  }
3472
+ async function assess(p, output, transcript) {
3473
+ let judgeCost = 0;
3474
+ let judgeUnpriced = false;
3475
+ const judge = buildJudge(p.provider, p.providerConfig, (u) => {
3476
+ const c = p.provider.estimateCost(u);
3477
+ judgeCost += c.cost_usd;
3478
+ if (c.priced === false) judgeUnpriced = true;
3479
+ });
3480
+ const records = [];
3481
+ const advice = [];
3482
+ let assertionError;
3483
+ for (const assertion of p.assertions) {
3484
+ const run = () => getAssertion(assertion.type).run({
3485
+ output,
3486
+ vars: p.row.vars,
3487
+ row: p.row,
3488
+ params: assertion,
3489
+ embedder: p.embedder,
3490
+ judge,
3491
+ ...transcript !== void 0 ? { transcript } : {}
3492
+ });
3493
+ if (ASSERTION_CLASSES[assertion.type] === "heuristic") {
3494
+ const found = await run().then(
3495
+ (r) => r.passed ? void 0 : r.reason ?? "no reason given",
3496
+ (err) => toRunError(err).message
3497
+ );
3498
+ if (found !== void 0) advice.push({ type: assertion.type, reason: found });
3499
+ continue;
3500
+ }
3501
+ try {
3502
+ const result = await run();
3503
+ records.push({
3504
+ type: assertion.type,
3505
+ passed: result.passed,
3506
+ ...result.score !== void 0 ? { score: result.score } : {},
3507
+ ...result.reason !== void 0 ? { reason: result.reason } : {}
3508
+ });
3509
+ } catch (err) {
3510
+ assertionError = toRunError(err);
3511
+ break;
3512
+ }
3513
+ }
3514
+ return { records, assertionError, judgeCost, judgeUnpriced, advice };
3515
+ }
1433
3516
  async function runRow(p) {
1434
3517
  const t0 = p.now();
1435
3518
  const prompt5 = resolvePrompt(p.template, p.row.vars);
1436
3519
  const temperature = p.providerConfig.temperature;
1437
- const maxTokens = p.providerConfig.max_tokens ?? DEFAULT_MAX_TOKENS2;
3520
+ const maxTokens = p.providerConfig.max_tokens ?? DEFAULT_MAX_TOKENS3;
1438
3521
  if (p.dryRun) {
1439
3522
  const est = estimateUsage(prompt5, maxTokens);
1440
3523
  const cost = p.provider.estimateCost(est);
@@ -1447,7 +3530,8 @@ async function runRow(p) {
1447
3530
  model: p.providerConfig.model,
1448
3531
  temperature: temperature ?? 0,
1449
3532
  max_tokens: maxTokens,
1450
- prompt_resolved: prompt5
3533
+ prompt_resolved: prompt5,
3534
+ ...p.attempt !== void 0 ? { attempt: p.attempt } : {}
1451
3535
  },
1452
3536
  p.policyVersion
1453
3537
  );
@@ -1517,36 +3601,7 @@ async function runRow(p) {
1517
3601
  };
1518
3602
  }
1519
3603
  }
1520
- let judgeCost = 0;
1521
- let judgeUnpriced = false;
1522
- const judge = buildJudge(p.provider, p.providerConfig, (u) => {
1523
- const c = p.provider.estimateCost(u);
1524
- judgeCost += c.cost_usd;
1525
- if (c.priced === false) judgeUnpriced = true;
1526
- });
1527
- const records = [];
1528
- let assertionError;
1529
- for (const assertion of p.assertions) {
1530
- try {
1531
- const result = await getAssertion(assertion.type).run({
1532
- output,
1533
- vars: p.row.vars,
1534
- row: p.row,
1535
- params: assertion,
1536
- embedder: p.embedder,
1537
- judge
1538
- });
1539
- records.push({
1540
- type: assertion.type,
1541
- passed: result.passed,
1542
- ...result.score !== void 0 ? { score: result.score } : {},
1543
- ...result.reason !== void 0 ? { reason: result.reason } : {}
1544
- });
1545
- } catch (err) {
1546
- assertionError = toRunError(err);
1547
- break;
1548
- }
1549
- }
3604
+ const { records, assertionError, judgeCost, judgeUnpriced } = await assess(p, output);
1550
3605
  const finalUsage = {
1551
3606
  ...usage,
1552
3607
  cost_usd: usage.cost_usd + judgeCost,
@@ -1564,6 +3619,79 @@ async function runRow(p) {
1564
3619
  assertions: records
1565
3620
  };
1566
3621
  }
3622
+ function neededPasses(passThreshold, runs) {
3623
+ return Math.max(1, Math.ceil(passThreshold * runs - 1e-9));
3624
+ }
3625
+ function toAttempt(r) {
3626
+ return {
3627
+ output: r.output,
3628
+ cached: r.cached,
3629
+ ...r.usage !== void 0 ? { usage: r.usage } : {},
3630
+ ...r.latency_ms !== void 0 ? { latency_ms: r.latency_ms } : {},
3631
+ ...r.error !== void 0 ? { error: r.error } : {},
3632
+ assertions: r.assertions,
3633
+ ...r.cache_saved !== void 0 ? { cache_saved: r.cache_saved } : {}
3634
+ };
3635
+ }
3636
+ function sumTokens(parts) {
3637
+ return parts.reduce(
3638
+ (a, u) => ({
3639
+ input_tokens: a.input_tokens + u.input_tokens,
3640
+ output_tokens: a.output_tokens + u.output_tokens,
3641
+ cost_usd: a.cost_usd + u.cost_usd
3642
+ }),
3643
+ { input_tokens: 0, output_tokens: 0, cost_usd: 0 }
3644
+ );
3645
+ }
3646
+ function sumUsage(parts) {
3647
+ const priced = parts.some((u) => u.priced === false) ? false : parts.some((u) => u.priced === true) ? true : void 0;
3648
+ return { ...sumTokens(parts), ...pricedField(priced) };
3649
+ }
3650
+ async function runRepeats(p, runs, passThreshold, run = runRow) {
3651
+ if (runs <= 1) return run(p);
3652
+ const counts = { runs, pass_threshold: passThreshold, passed: 0, failed: 0, errored: 0 };
3653
+ if (p.dryRun) {
3654
+ const one = await run(p);
3655
+ const u = one.usage;
3656
+ const usage = u === void 0 ? void 0 : {
3657
+ ...u,
3658
+ input_tokens: u.input_tokens * runs,
3659
+ output_tokens: u.output_tokens * runs,
3660
+ cost_usd: u.cost_usd * runs
3661
+ };
3662
+ return {
3663
+ ...one,
3664
+ ...usage !== void 0 ? { usage } : {},
3665
+ attempts: { ...counts, results: [] }
3666
+ };
3667
+ }
3668
+ const rows = [];
3669
+ for (let attempt = 0; attempt < runs; attempt += 1) {
3670
+ rows.push(await run({ ...p, attempt }));
3671
+ }
3672
+ const states = rows.map(rowStatus);
3673
+ const passed = states.filter((s) => s === "passed").length;
3674
+ const failed = states.filter((s) => s === "failed").length;
3675
+ const errored = runs - passed - failed;
3676
+ const needed = neededPasses(passThreshold, runs);
3677
+ const verdict = passed >= needed ? "passed" : passed + errored >= needed ? "errored" : "failed";
3678
+ const shown = rows[states.indexOf(verdict)];
3679
+ const usages = rows.flatMap((r) => r.usage !== void 0 ? [r.usage] : []);
3680
+ const saved = rows.flatMap((r) => r.cache_saved !== void 0 ? [r.cache_saved] : []);
3681
+ const latencies = rows.flatMap((r) => r.latency_ms !== void 0 ? [r.latency_ms] : []);
3682
+ return {
3683
+ vars: p.row.vars,
3684
+ output: shown.output,
3685
+ cached: rows.every((r) => r.cached),
3686
+ ...usages.length > 0 ? { usage: sumUsage(usages) } : {},
3687
+ ...latencies.length > 0 ? { latency_ms: latencies.reduce((a, b) => a + b, 0) } : {},
3688
+ ...saved.length > 0 ? { cache_saved: sumTokens(saved) } : {},
3689
+ ...shown.error !== void 0 ? { error: shown.error } : {},
3690
+ assertions: shown.assertions,
3691
+ attempts: { ...counts, passed, failed, errored, results: rows.map(toAttempt) },
3692
+ ...shown.agent !== void 0 ? { agent: shown.agent } : {}
3693
+ };
3694
+ }
1567
3695
  function selectEvals(evals, only) {
1568
3696
  if (only === void 0 || only.length === 0) return evals;
1569
3697
  return evals.filter(
@@ -1576,7 +3704,7 @@ function resolveTemplate(ev, baseDir) {
1576
3704
  if (ev.prompt !== void 0) return ev.prompt;
1577
3705
  if (ev.prompt_file !== void 0) {
1578
3706
  try {
1579
- return fs3.readFileSync(path2.resolve(baseDir, ev.prompt_file), "utf8");
3707
+ return fs3.readFileSync(path3.resolve(baseDir, ev.prompt_file), "utf8");
1580
3708
  } catch {
1581
3709
  throw new RunConfigError(`Eval "${ev.id}": prompt_file not found: ${ev.prompt_file}`);
1582
3710
  }
@@ -1606,18 +3734,34 @@ function summarize(evals, durationMs) {
1606
3734
  summary.total += 1;
1607
3735
  summary[rowStatus(row)] += 1;
1608
3736
  summary.cost_usd += row.usage?.cost_usd ?? 0;
1609
- if (row.cached) {
1610
- cache.from_cache += 1;
1611
- cache.saved.input_tokens += row.cache_saved?.input_tokens ?? 0;
1612
- cache.saved.output_tokens += row.cache_saved?.output_tokens ?? 0;
1613
- cache.saved.cost_usd += row.cache_saved?.cost_usd ?? 0;
1614
- } else if (row.error?.code === CACHE_MISS_CODE) cache.missed += 1;
3737
+ cache.saved.input_tokens += row.cache_saved?.input_tokens ?? 0;
3738
+ cache.saved.output_tokens += row.cache_saved?.output_tokens ?? 0;
3739
+ cache.saved.cost_usd += row.cache_saved?.cost_usd ?? 0;
3740
+ if (row.cached) cache.from_cache += 1;
3741
+ else if (row.error?.code === CACHE_MISS_CODE) cache.missed += 1;
1615
3742
  else if (row.output !== null) cache.from_model += 1;
1616
3743
  else if (row.error !== void 0) cache.errored += 1;
1617
3744
  }
1618
3745
  }
1619
3746
  return { ...summary, cache };
1620
3747
  }
3748
+ function agenticProvider(config, ev, deps, cacheStrict) {
3749
+ if (cacheStrict)
3750
+ throw new RunConfigError(
3751
+ `Eval "${ev.id}" uses MCP server "${ev.mcp.server}": its tool loop is never cached, so --cache-strict cannot answer it`
3752
+ );
3753
+ const providerConfig = { ...config.provider, ...ev.provider };
3754
+ const provider = deps.resolveProvider(providerConfig);
3755
+ if (provider.respond === void 0)
3756
+ throw new RunConfigError(
3757
+ `Eval "${ev.id}" uses MCP server "${ev.mcp.server}", and this provider cannot call tools, so nothing would be measured (under PLUNE_MOCK_PROVIDER=1, PLUNE_MOCK_SCRIPT names the scripted model steps)`
3758
+ );
3759
+ if (deps.connectMcp === void 0)
3760
+ throw new RunConfigError(
3761
+ `Eval "${ev.id}" uses MCP server "${ev.mcp.server}", and this run cannot connect to one`
3762
+ );
3763
+ return provider;
3764
+ }
1621
3765
  async function runOrchestration(config, options, deps) {
1622
3766
  const noCache = options.noCache ?? false;
1623
3767
  const cacheStrict = options.cacheStrict ?? false;
@@ -1627,6 +3771,9 @@ async function runOrchestration(config, options, deps) {
1627
3771
  if (noCache && options.cacheMaxAgeMs !== void 0) {
1628
3772
  throw new RunConfigError("--no-cache and --cache-max-age cannot be used together");
1629
3773
  }
3774
+ if (options.runs !== void 0 && !(Number.isInteger(options.runs) && options.runs >= 1 && options.runs <= MAX_RUNS)) {
3775
+ throw new RunConfigError(`--runs must be a whole number from 1 to ${MAX_RUNS}`);
3776
+ }
1630
3777
  const started = deps.now();
1631
3778
  const dryRun = options.dryRun ?? false;
1632
3779
  const evalResults = [];
@@ -1636,18 +3783,19 @@ async function runOrchestration(config, options, deps) {
1636
3783
  for (const row of rows) {
1637
3784
  resolvePrompt(template, row.vars);
1638
3785
  }
1639
- return { ev, template, rows };
3786
+ const agentic = ev.mcp === void 0 || dryRun ? void 0 : agenticProvider(config, ev, deps, cacheStrict);
3787
+ return { ev, template, rows, agentic };
1640
3788
  });
1641
- for (const { ev, template, rows } of prepared) {
3789
+ for (const { ev, template, rows, agentic } of prepared) {
1642
3790
  const providerConfig = { ...config.provider, ...ev.provider };
1643
- const provider = deps.resolveProvider(providerConfig);
1644
- const limit = options.concurrency ?? providerConfig.concurrency ?? 4;
1645
- const rowResults = await mapLimit(
1646
- rows,
1647
- limit,
1648
- (row) => runRow({
3791
+ const provider = agentic ?? deps.resolveProvider(providerConfig);
3792
+ const limit2 = options.concurrency ?? providerConfig.concurrency ?? (ev.mcp !== void 0 ? 1 : 4);
3793
+ const runs = options.runs ?? ev.runs ?? config.runs ?? 1;
3794
+ const passThreshold = ev.pass_threshold ?? config.pass_threshold ?? 1;
3795
+ const rowResults = await mapLimit(rows, limit2, (row) => {
3796
+ const params = {
1649
3797
  template,
1650
- // `defaults.assertions` apply to every eval, ahead of its own (#2415).
3798
+ // `defaults.assertions` apply to every eval, ahead of its own.
1651
3799
  assertions: [...config.defaults?.assertions ?? [], ...ev.assertions],
1652
3800
  row,
1653
3801
  providerConfig,
@@ -1659,8 +3807,18 @@ async function runOrchestration(config, options, deps) {
1659
3807
  noCache,
1660
3808
  cacheStrict,
1661
3809
  ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {}
1662
- })
1663
- );
3810
+ };
3811
+ if (ev.mcp === void 0) return runRepeats(params, runs, passThreshold);
3812
+ const agentParams = {
3813
+ ...params,
3814
+ server: ev.mcp.server,
3815
+ ...ev.mcp.allowed_tools !== void 0 ? { allowedTools: ev.mcp.allowed_tools } : {},
3816
+ limits: mcpLimits(config, ev),
3817
+ // A dry run connects nowhere; the loop never calls this then.
3818
+ connect: deps.connectMcp ?? (() => Promise.reject(new Error("no MCP connection")))
3819
+ };
3820
+ return runRepeats(agentParams, runs, passThreshold, runAgentRow);
3821
+ });
1664
3822
  const passed = rowResults.every((r) => rowStatus(r) === "passed");
1665
3823
  evalResults.push({ id: ev.id, tags: ev.tags ?? [], rows: rowResults, passed });
1666
3824
  if (options.bail === true && !passed) break;
@@ -1678,14 +3836,18 @@ async function runOrchestration(config, options, deps) {
1678
3836
  };
1679
3837
  }
1680
3838
 
3839
+ // src/orchestrator/exit-code.ts
3840
+ init_cjs_shims();
3841
+
1681
3842
  // src/orchestrator/dataset.ts
3843
+ init_cjs_shims();
1682
3844
  var fs4 = __toESM(require("fs"), 1);
1683
- var path3 = __toESM(require("path"), 1);
3845
+ var path4 = __toESM(require("path"), 1);
1684
3846
  function loadDataset(ref, baseDir) {
1685
3847
  if (typeof ref !== "string") {
1686
3848
  return ref.examples;
1687
3849
  }
1688
- const content = fs4.readFileSync(path3.resolve(baseDir, ref), "utf8");
3850
+ const content = fs4.readFileSync(path4.resolve(baseDir, ref), "utf8");
1689
3851
  const rows = [];
1690
3852
  content.split(/\r?\n/).forEach((line, i) => {
1691
3853
  if (line.trim().length === 0) return;
@@ -1695,9 +3857,9 @@ function loadDataset(ref, baseDir) {
1695
3857
  } catch (err) {
1696
3858
  throw new RunConfigError(`${ref}:${i + 1}: not valid JSON (${err.message})`);
1697
3859
  }
1698
- const vars = isObject(row) ? row["vars"] : void 0;
1699
- if (!isObject(vars)) {
1700
- const why = isObject(row) && "vars" in row ? `vars: Invalid input: expected record, received ${typeName(vars)}` : 'this row has no "vars"';
3860
+ const vars = isObject2(row) ? row["vars"] : void 0;
3861
+ if (!isObject2(vars)) {
3862
+ const why = isObject2(row) && "vars" in row ? `vars: Invalid input: expected record, received ${typeName(vars)}` : 'this row has no "vars"';
1701
3863
  throw new RunConfigError(
1702
3864
  `${ref}:${i + 1}: a dataset row must be { "vars": { ... } }; ${why}`
1703
3865
  );
@@ -1706,7 +3868,7 @@ function loadDataset(ref, baseDir) {
1706
3868
  });
1707
3869
  return rows;
1708
3870
  }
1709
- function isObject(value) {
3871
+ function isObject2(value) {
1710
3872
  return typeof value === "object" && value !== null && !Array.isArray(value);
1711
3873
  }
1712
3874
  function typeName(value) {
@@ -1722,33 +3884,72 @@ var NOOP_CACHE = { get: () => void 0, set: () => {
1722
3884
  function isMockMode(env) {
1723
3885
  return env["PLUNE_MOCK_PROVIDER"] === "1";
1724
3886
  }
3887
+ function mockScript(env) {
3888
+ const file = env["PLUNE_MOCK_SCRIPT"];
3889
+ if (file === void 0 || file === "") return void 0;
3890
+ let text;
3891
+ try {
3892
+ text = fs5.readFileSync(path5.resolve(file), "utf8");
3893
+ } catch {
3894
+ throw new RunConfigError(`PLUNE_MOCK_SCRIPT: cannot read ${file}`);
3895
+ }
3896
+ try {
3897
+ return parseMockScript(text);
3898
+ } catch (err) {
3899
+ throw new RunConfigError(`PLUNE_MOCK_SCRIPT: ${file} ${err.message}`);
3900
+ }
3901
+ }
3902
+ function makeMcpConnect(config, baseDir, env) {
3903
+ return async (name, timeoutMs) => {
3904
+ const server = config.mcp?.servers[name];
3905
+ if (server === void 0) throw new Error(`mcp.servers has no "${name}"`);
3906
+ const target = resolveMcpServer(server, env, baseDir);
3907
+ const [{ openSession: openSession2 }, { listAll: listAll2, callTool: callTool2 }] = await Promise.all([
3908
+ Promise.resolve().then(() => (init_session(), session_exports)),
3909
+ Promise.resolve().then(() => (init_tools(), tools_exports))
3910
+ ]);
3911
+ const session = await openSession2({ target, timeoutMs });
3912
+ return {
3913
+ redact: session.redact,
3914
+ listTools: async (ms) => (await listAll2(session, "tools/list", "tools", { timeoutMs: ms })).items,
3915
+ callTool: (tool, args, ms) => callTool2(session, tool, ms, args),
3916
+ close: () => session.close()
3917
+ };
3918
+ };
3919
+ }
1725
3920
  function resolveProviderFor(config, dryRun) {
1726
- if (isMockMode(process.env)) return () => makeMockProvider();
3921
+ if (isMockMode(process.env)) {
3922
+ const script = mockScript(process.env);
3923
+ return () => makeMockProvider(script);
3924
+ }
1727
3925
  if (dryRun) return (cfg) => makeEstimateProvider(cfg, config.pricing);
1728
3926
  return (cfg) => getProvider(cfg, process.env, config.pricing);
1729
3927
  }
1730
3928
  function buildRealDeps(config, baseDir, dryRun) {
1731
- const dir = path4.join(baseDir, ".plune");
3929
+ const dir = path5.join(baseDir, ".plune");
1732
3930
  fs5.mkdirSync(dir, { recursive: true });
1733
3931
  return {
1734
3932
  resolveProvider: resolveProviderFor(config, dryRun),
1735
3933
  embedder: getDefaultEmbedder(),
1736
- cache: dryRun ? NOOP_CACHE : openCache(path4.join(dir, "cache.db")),
3934
+ cache: dryRun ? NOOP_CACHE : openCache(path5.join(dir, "cache.db")),
1737
3935
  now: Date.now,
1738
3936
  loadDataset,
1739
- baseDir
3937
+ baseDir,
3938
+ connectMcp: makeMcpConnect(config, baseDir, process.env)
1740
3939
  };
1741
3940
  }
1742
3941
  function persist(result, baseDir) {
1743
- const dir = path4.join(baseDir, ".plune");
3942
+ const dir = path5.join(baseDir, ".plune");
1744
3943
  fs5.mkdirSync(dir, { recursive: true });
1745
- fs5.writeFileSync(path4.join(dir, "last-run.json"), JSON.stringify(result, null, 2));
3944
+ fs5.writeFileSync(path5.join(dir, "last-run.json"), JSON.stringify(result, null, 2));
1746
3945
  }
1747
3946
  async function handleRun(options, depsFactory) {
1748
3947
  const config = await loadConfig(
1749
3948
  options.configPath !== void 0 ? { configPath: options.configPath } : {}
1750
3949
  );
1751
- const baseDir = options.configPath !== void 0 ? path4.dirname(path4.resolve(options.configPath)) : process.cwd();
3950
+ const baseDir = options.configPath !== void 0 ? path5.dirname(path5.resolve(options.configPath)) : process.cwd();
3951
+ for (const warning of mcpSecretWarnings(config)) process.stderr.write(`warning: ${warning}
3952
+ `);
1752
3953
  const factory = depsFactory ?? ((c, d) => buildRealDeps(c, d, options.dryRun));
1753
3954
  const deps = factory(config, baseDir);
1754
3955
  try {
@@ -1766,10 +3967,18 @@ async function handleRun(options, depsFactory) {
1766
3967
  ...options.noCache !== void 0 ? { noCache: options.noCache } : {},
1767
3968
  ...options.bail !== void 0 ? { bail: options.bail } : {},
1768
3969
  ...options.cacheStrict === true ? { cacheStrict: true } : {},
1769
- ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {}
3970
+ ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {},
3971
+ ...options.runs !== void 0 ? { runs: options.runs } : {}
1770
3972
  },
1771
3973
  deps
1772
3974
  );
3975
+ if (options.dryRun) {
3976
+ const agentic = new Set(config.evals.filter((ev) => ev.mcp !== void 0).map((ev) => ev.id));
3977
+ if (result.evals.some((ev) => agentic.has(ev.id)))
3978
+ process.stderr.write(
3979
+ "dry run: an eval with mcp is priced as max_steps model calls of its prompt; tool schemas and tool results are not counted\n"
3980
+ );
3981
+ }
1773
3982
  persist(result, baseDir);
1774
3983
  return result;
1775
3984
  } finally {
@@ -1778,11 +3987,13 @@ async function handleRun(options, depsFactory) {
1778
3987
  }
1779
3988
 
1780
3989
  // src/cli/commands/sync.ts
3990
+ init_cjs_shims();
1781
3991
  var import_node_crypto2 = require("crypto");
1782
3992
  var fs6 = __toESM(require("fs"), 1);
1783
- var path5 = __toESM(require("path"), 1);
3993
+ var path6 = __toESM(require("path"), 1);
1784
3994
 
1785
3995
  // src/types/run-result-schema.ts
3996
+ init_cjs_shims();
1786
3997
  var import_zod3 = require("zod");
1787
3998
  var RUN_RESULT_SCHEMA_VERSION = 1;
1788
3999
  var binaryVerdictSchema = import_zod3.z.object({
@@ -1807,6 +4018,11 @@ var runErrorSchema = import_zod3.z.object({
1807
4018
  code: import_zod3.z.string(),
1808
4019
  message: import_zod3.z.string()
1809
4020
  });
4021
+ var savedSchema = import_zod3.z.object({
4022
+ input_tokens: import_zod3.z.number(),
4023
+ output_tokens: import_zod3.z.number(),
4024
+ cost_usd: import_zod3.z.number()
4025
+ });
1810
4026
  var rowResultSchema = import_zod3.z.object({
1811
4027
  vars: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()),
1812
4028
  output: import_zod3.z.string().nullable(),
@@ -1815,9 +4031,66 @@ var rowResultSchema = import_zod3.z.object({
1815
4031
  latency_ms: import_zod3.z.number().optional(),
1816
4032
  error: runErrorSchema.optional(),
1817
4033
  assertions: import_zod3.z.array(assertionResultRecordSchema2),
1818
- cache_saved: import_zod3.z.object({ input_tokens: import_zod3.z.number(), output_tokens: import_zod3.z.number(), cost_usd: import_zod3.z.number() }).optional(),
4034
+ cache_saved: savedSchema.optional(),
1819
4035
  /** ADR 0045. Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
1820
- inconclusive: import_zod3.z.enum(ROW_INCONCLUSIVE).optional()
4036
+ inconclusive: import_zod3.z.enum(ROW_INCONCLUSIVE).optional(),
4037
+ /** Repeats (`runs` above 1). Optional and additive — a RunResult without it validates unchanged. */
4038
+ attempts: import_zod3.z.object({
4039
+ runs: import_zod3.z.number(),
4040
+ pass_threshold: import_zod3.z.number(),
4041
+ passed: import_zod3.z.number(),
4042
+ failed: import_zod3.z.number(),
4043
+ errored: import_zod3.z.number(),
4044
+ results: import_zod3.z.array(
4045
+ import_zod3.z.object({
4046
+ output: import_zod3.z.string().nullable(),
4047
+ cached: import_zod3.z.boolean(),
4048
+ usage: usageSchema.optional(),
4049
+ latency_ms: import_zod3.z.number().optional(),
4050
+ error: runErrorSchema.optional(),
4051
+ assertions: import_zod3.z.array(assertionResultRecordSchema2),
4052
+ cache_saved: savedSchema.optional()
4053
+ })
4054
+ )
4055
+ }).optional(),
4056
+ /** The tool loop of an eval with an `mcp` server. Optional and additive — a RunResult without it validates unchanged. */
4057
+ agent: import_zod3.z.object({
4058
+ server: import_zod3.z.string(),
4059
+ tools: import_zod3.z.array(
4060
+ import_zod3.z.object({
4061
+ name: import_zod3.z.string(),
4062
+ offered: import_zod3.z.boolean(),
4063
+ annotations: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).optional()
4064
+ })
4065
+ ),
4066
+ steps: import_zod3.z.array(
4067
+ import_zod3.z.object({
4068
+ index: import_zod3.z.number(),
4069
+ text: import_zod3.z.string(),
4070
+ finish_reason: import_zod3.z.string().optional(),
4071
+ usage: usageSchema,
4072
+ calls: import_zod3.z.array(
4073
+ import_zod3.z.object({
4074
+ id: import_zod3.z.string(),
4075
+ name: import_zod3.z.string(),
4076
+ args: import_zod3.z.unknown(),
4077
+ executed: import_zod3.z.boolean(),
4078
+ is_error: import_zod3.z.boolean(),
4079
+ error_kind: import_zod3.z.enum(["content", "protocol", "timeout", "not-offered", "bad-arguments"]).optional(),
4080
+ duration_ms: import_zod3.z.number().optional(),
4081
+ result: import_zod3.z.object({ text: import_zod3.z.string(), bytes: import_zod3.z.number(), truncated: import_zod3.z.boolean() }).optional()
4082
+ })
4083
+ )
4084
+ })
4085
+ ),
4086
+ stop: import_zod3.z.object({
4087
+ reason: import_zod3.z.enum(["complete", "limit", "error"]),
4088
+ limit: import_zod3.z.enum(["max_steps", "max_tool_calls", "max_total_tokens", "timeout_ms", "tool_timeout_ms"]).optional()
4089
+ }),
4090
+ collection: import_zod3.z.enum(["complete", "partial"]),
4091
+ /** Heuristic findings, never a verdict. Optional and additive. */
4092
+ advice: import_zod3.z.array(import_zod3.z.object({ type: import_zod3.z.string(), reason: import_zod3.z.string() })).optional()
4093
+ }).optional()
1821
4094
  });
1822
4095
  var summarySchema = import_zod3.z.object({
1823
4096
  total: import_zod3.z.number(),
@@ -1857,6 +4130,7 @@ function parseRunResult(value) {
1857
4130
  }
1858
4131
 
1859
4132
  // src/cli/api-url.ts
4133
+ init_cjs_shims();
1860
4134
  var DEFAULT_API_URL = "https://beta-api.plune.ai";
1861
4135
  function resolveApiUrl(explicit) {
1862
4136
  const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
@@ -1864,25 +4138,27 @@ function resolveApiUrl(explicit) {
1864
4138
  }
1865
4139
 
1866
4140
  // src/cli/credentials.ts
1867
- var import_node_fs = require("fs");
1868
- var import_node_os = require("os");
1869
- var import_node_path = require("path");
4141
+ init_cjs_shims();
4142
+ var import_node_fs4 = require("fs");
4143
+ var import_node_os3 = require("os");
4144
+ var import_node_path2 = require("path");
1870
4145
  function credentialsFile() {
1871
- const base = process.env["XDG_CONFIG_HOME"]?.trim() || (0, import_node_path.join)((0, import_node_os.homedir)(), ".config");
1872
- return (0, import_node_path.join)(base, "plune", "credentials.json");
4146
+ const base = process.env["XDG_CONFIG_HOME"]?.trim() || (0, import_node_path2.join)((0, import_node_os3.homedir)(), ".config");
4147
+ return (0, import_node_path2.join)(base, "plune", "credentials.json");
1873
4148
  }
1874
4149
  function loadToken() {
1875
4150
  const fromEnv = process.env["PLUNE_TOKEN"]?.trim();
1876
4151
  if (fromEnv !== void 0 && fromEnv !== "") return fromEnv;
1877
4152
  try {
1878
- const parsed = JSON.parse((0, import_node_fs.readFileSync)(credentialsFile(), "utf-8"));
1879
- return typeof parsed.token === "string" && parsed.token.length > 0 ? parsed.token : null;
4153
+ const parsed2 = JSON.parse((0, import_node_fs4.readFileSync)(credentialsFile(), "utf-8"));
4154
+ return typeof parsed2.token === "string" && parsed2.token.length > 0 ? parsed2.token : null;
1880
4155
  } catch {
1881
4156
  return null;
1882
4157
  }
1883
4158
  }
1884
4159
 
1885
4160
  // src/cli/gate.ts
4161
+ init_cjs_shims();
1886
4162
  function gateExit(verdict, runnerCode) {
1887
4163
  if (verdict?.statusEvent === "terminated") {
1888
4164
  return { code: 1, line: "plune: gate failed \u2014 the run was terminated, so it has no verdict to pass on." };
@@ -1891,14 +4167,15 @@ function gateExit(verdict, runnerCode) {
1891
4167
  if (counts == null) return { code: 1, line: "plune: gate failed \u2014 no verdict from the platform, and no verdict is no pass." };
1892
4168
  const n = (status) => counts[status] ?? 0;
1893
4169
  const notRun = verdict?.notRun?.length ?? 0;
1894
- if (runnerCode !== void 0 && notRun === 0 && Object.values(counts).every((k) => !k)) {
1895
- return { code: runnerCode, line: `plune: gate \u2014 no result reached the run, so the exit code is the command's own (${runnerCode}).` };
4170
+ if (notRun === 0 && Object.values(counts).every((k) => !k)) {
4171
+ return runnerCode !== void 0 ? { code: runnerCode, line: `plune: gate \u2014 no result reached the run, so the exit code is the command's own (${runnerCode}).` } : { code: 1, line: "plune: gate failed \u2014 no result reached the run, so there is nothing to pass." };
1896
4172
  }
1897
4173
  const said = `${n("failed")} failed \xB7 ${n("broken")} broken \xB7 ${notRun} not run \xB7 ${n("muted")} muted`;
1898
4174
  return n("failed") + n("broken") > 0 || notRun > 0 ? { code: 1, line: `plune: gate failed \u2014 ${said}` } : { code: 0, line: `plune: gate passed \u2014 ${said}` };
1899
4175
  }
1900
4176
 
1901
4177
  // src/cli/commands/job-reporter.ts
4178
+ init_cjs_shims();
1902
4179
  var JOB_TIMEOUT_MS = 5e3;
1903
4180
  var JOB_SUBJECT_NAME_MAX = 200;
1904
4181
  var JOB_REASON_MAX = 2e3;
@@ -2008,7 +4285,7 @@ var SyncHttpError = class extends Error {
2008
4285
  status;
2009
4286
  };
2010
4287
  function readRun(cwd, file) {
2011
- const target = file !== void 0 ? path5.resolve(cwd, file) : path5.join(cwd, ".plune", "last-run.json");
4288
+ const target = file !== void 0 ? path6.resolve(cwd, file) : path6.join(cwd, ".plune", "last-run.json");
2012
4289
  let raw;
2013
4290
  try {
2014
4291
  raw = fs6.readFileSync(target, "utf8");
@@ -2049,7 +4326,7 @@ async function handleSync(deps = {}) {
2049
4326
  const idempotencyKey = (0, import_node_crypto2.createHash)("sha256").update(payload).digest("hex");
2050
4327
  const bearer = token;
2051
4328
  const job = new JobReporter(doFetch, apiUrl, bearer, "sync");
2052
- await job.open(path5.basename(deps.file !== void 0 ? path5.resolve(cwd, deps.file) : cwd), run.summary.total);
4329
+ await job.open(path6.basename(deps.file !== void 0 ? path6.resolve(cwd, deps.file) : cwd), run.summary.total);
2053
4330
  try {
2054
4331
  const result = await upload();
2055
4332
  await job.finish({ ok: true });
@@ -2111,11 +4388,13 @@ function reportSyncFailure(err, write) {
2111
4388
  }
2112
4389
 
2113
4390
  // src/cli/commands/ingest.ts
2114
- var path7 = __toESM(require("path"), 1);
4391
+ init_cjs_shims();
4392
+ var path8 = __toESM(require("path"), 1);
2115
4393
 
2116
4394
  // src/cli/commands/cairn-artifact.ts
4395
+ init_cjs_shims();
2117
4396
  var fs7 = __toESM(require("fs/promises"), 1);
2118
- var path6 = __toESM(require("path"), 1);
4397
+ var path7 = __toESM(require("path"), 1);
2119
4398
  var SUPPORTED_ARTIFACT_VERSION = 1;
2120
4399
  var INGEST_SCHEMA_VERSION = 1;
2121
4400
  var NoCairnRunsError = class extends Error {
@@ -2130,9 +4409,9 @@ async function findLatestCairnRun(runsDir = "runs") {
2130
4409
  let newest;
2131
4410
  for (const entry of entries) {
2132
4411
  if (!entry.isDirectory()) continue;
2133
- const dir = path6.join(runsDir, entry.name);
4412
+ const dir = path7.join(runsDir, entry.name);
2134
4413
  try {
2135
- const report = await fs7.lstat(path6.join(dir, "report.json"));
4414
+ const report = await fs7.lstat(path7.join(dir, "report.json"));
2136
4415
  if (!report.isFile()) continue;
2137
4416
  if (newest === void 0 || report.mtimeMs > newest.at) {
2138
4417
  newest = { dir, at: report.mtimeMs };
@@ -2183,7 +4462,7 @@ async function readJson(file) {
2183
4462
  }
2184
4463
  }
2185
4464
  async function defaultReadEvidence(dir) {
2186
- const raw = await readJson(path6.join(dir, "api-evidence.json"));
4465
+ const raw = await readJson(path7.join(dir, "api-evidence.json"));
2187
4466
  if (!Array.isArray(raw)) return void 0;
2188
4467
  return raw.map((r) => {
2189
4468
  const rec = asRecord(r);
@@ -2226,7 +4505,7 @@ function casesFromApi(report, verdicts) {
2226
4505
  });
2227
4506
  }
2228
4507
  async function readCairnRun(dir, deps = {}) {
2229
- const raw = await readJson(path6.join(dir, "report.json"));
4508
+ const raw = await readJson(path7.join(dir, "report.json"));
2230
4509
  if (raw === void 0) throw new CairnRunNotFoundError(dir);
2231
4510
  const report = asRecord(raw);
2232
4511
  if (report["schemaVersion"] !== SUPPORTED_ARTIFACT_VERSION) {
@@ -2256,7 +4535,7 @@ async function readCairnRun(dir, deps = {}) {
2256
4535
  return {
2257
4536
  schemaVersion: INGEST_SCHEMA_VERSION,
2258
4537
  run: {
2259
- runId: str(report["runId"], path6.basename(dir)),
4538
+ runId: str(report["runId"], path7.basename(dir)),
2260
4539
  mode,
2261
4540
  target: str(report["url"], "unknown")
2262
4541
  },
@@ -2308,7 +4587,7 @@ async function handleIngest(deps) {
2308
4587
  const doFetch = deps.fetchImpl ?? fetch;
2309
4588
  const endpoint = `${apiUrl}/v1/ingest/cairn`;
2310
4589
  const job = new JobReporter(doFetch, apiUrl, token, "ingest");
2311
- await job.open(path7.basename(path7.resolve(dir)), payload.cases.length);
4590
+ await job.open(path8.basename(path8.resolve(dir)), payload.cases.length);
2312
4591
  try {
2313
4592
  const result = await upload();
2314
4593
  await job.uploaded({ subjectId: result.runId || void 0 });