@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/README.md +51 -15
- package/dist/cli.cjs +10559 -7370
- package/dist/index.cjs +2409 -130
- package/dist/index.d.cts +447 -1
- package/dist/index.d.ts +447 -1
- package/dist/index.js +2430 -129
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,926 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __esm = (fn, res) => function __init() {
|
|
4
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
5
|
+
};
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// 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/esm_shims.js
|
|
12
|
+
import path from "path";
|
|
13
|
+
import { fileURLToPath } from "url";
|
|
14
|
+
var init_esm_shims = __esm({
|
|
15
|
+
"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/esm_shims.js"() {
|
|
16
|
+
"use strict";
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
// src/reporter-core/failure-detail.ts
|
|
21
|
+
import { existsSync as existsSync2 } from "fs";
|
|
22
|
+
import { homedir } from "os";
|
|
23
|
+
import { dirname as dirname2, join as join2, posix, resolve as resolve4 } from "path";
|
|
24
|
+
import { stripVTControlCharacters } from "util";
|
|
25
|
+
function machineless(raw, repoRoot, home) {
|
|
26
|
+
let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
|
|
27
|
+
const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
|
|
28
|
+
if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
|
|
29
|
+
const own = pathIn(home);
|
|
30
|
+
if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
|
|
31
|
+
if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
|
|
32
|
+
return text;
|
|
33
|
+
}
|
|
34
|
+
function pathIn(path10) {
|
|
35
|
+
const parts = path10.split(/[\\/]+/);
|
|
36
|
+
while (parts.length > 1 && parts.at(-1) === "") parts.pop();
|
|
37
|
+
if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
|
|
38
|
+
const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
|
|
39
|
+
const escaped = /^\/(?!\/)/.test(path10) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
|
|
40
|
+
const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
|
|
41
|
+
return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
|
|
42
|
+
}
|
|
43
|
+
var printable, PATH_START, HEADLINE_LIMIT, ANY_HOME;
|
|
44
|
+
var init_failure_detail = __esm({
|
|
45
|
+
"src/reporter-core/failure-detail.ts"() {
|
|
46
|
+
"use strict";
|
|
47
|
+
init_esm_shims();
|
|
48
|
+
printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "?");
|
|
49
|
+
PATH_START = "(?<![\\w.~%/\\\\-])";
|
|
50
|
+
HEADLINE_LIMIT = 8 * 1024;
|
|
51
|
+
ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// src/mcp-testing/exit-codes.ts
|
|
56
|
+
var MCP_EXIT;
|
|
57
|
+
var init_exit_codes = __esm({
|
|
58
|
+
"src/mcp-testing/exit-codes.ts"() {
|
|
59
|
+
"use strict";
|
|
60
|
+
init_esm_shims();
|
|
61
|
+
MCP_EXIT = { ok: 0, violations: 1, usage: 2, unmeasured: 3 };
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// src/mcp-testing/connect/journal.ts
|
|
66
|
+
import { closeSync, fchmodSync, openSync, writeSync } from "fs";
|
|
67
|
+
import { performance } from "perf_hooks";
|
|
68
|
+
function openJournal(path10, redact) {
|
|
69
|
+
if (path10 === void 0) return NONE;
|
|
70
|
+
const fd = openSync(path10, "w", 384);
|
|
71
|
+
if (process.platform !== "win32") fchmodSync(fd, 384);
|
|
72
|
+
const start = performance.now();
|
|
73
|
+
let closed = false;
|
|
74
|
+
return {
|
|
75
|
+
write(dir, fields) {
|
|
76
|
+
if (closed) return;
|
|
77
|
+
const dtMs = Math.round((performance.now() - start) * 1e3) / 1e3;
|
|
78
|
+
const line = {
|
|
79
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
80
|
+
dtMs,
|
|
81
|
+
dir,
|
|
82
|
+
...redact.value(fields)
|
|
83
|
+
};
|
|
84
|
+
writeSync(fd, JSON.stringify(line) + "\n");
|
|
85
|
+
},
|
|
86
|
+
close() {
|
|
87
|
+
if (closed) return;
|
|
88
|
+
closed = true;
|
|
89
|
+
closeSync(fd);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
var NONE;
|
|
94
|
+
var init_journal = __esm({
|
|
95
|
+
"src/mcp-testing/connect/journal.ts"() {
|
|
96
|
+
"use strict";
|
|
97
|
+
init_esm_shims();
|
|
98
|
+
NONE = { write: () => {
|
|
99
|
+
}, close: () => {
|
|
100
|
+
} };
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
// src/mcp-testing/connect/processes.ts
|
|
105
|
+
import { spawnSync } from "child_process";
|
|
106
|
+
import { readdirSync, readFileSync as readFileSync3 } from "fs";
|
|
107
|
+
function parseProcessTable(text) {
|
|
108
|
+
return text.split(/\r?\n/).flatMap((line) => {
|
|
109
|
+
const [pid, ppid, ...started] = line.trim().split(/\s+/);
|
|
110
|
+
const proc = { pid: Number(pid), ppid: Number(ppid), started: started.join(" ") };
|
|
111
|
+
return Number.isInteger(proc.pid) && Number.isInteger(proc.ppid) && proc.started !== "" ? [proc] : [];
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
function processTable() {
|
|
115
|
+
if (process.platform === "win32") {
|
|
116
|
+
const out2 = spawnSync(
|
|
117
|
+
"powershell.exe",
|
|
118
|
+
["-NoProfile", "-NonInteractive", "-Command", WINDOWS_TABLE],
|
|
119
|
+
{
|
|
120
|
+
encoding: "utf8",
|
|
121
|
+
windowsHide: true,
|
|
122
|
+
timeout: 15e3,
|
|
123
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
124
|
+
}
|
|
125
|
+
);
|
|
126
|
+
return parseProcessTable(out2.stdout ?? "");
|
|
127
|
+
}
|
|
128
|
+
if (process.platform === "linux") {
|
|
129
|
+
return readdirSync("/proc").flatMap((name) => {
|
|
130
|
+
if (!/^\d+$/.test(name)) return [];
|
|
131
|
+
try {
|
|
132
|
+
const stat = readFileSync3(`/proc/${name}/stat`, "utf8");
|
|
133
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
134
|
+
return parseProcessTable(`${name} ${fields[1]} ${fields[19]}`);
|
|
135
|
+
} catch {
|
|
136
|
+
return [];
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
const out = spawnSync("ps", ["-A", "-o", "pid=,ppid=,lstart="], {
|
|
141
|
+
encoding: "utf8",
|
|
142
|
+
timeout: 15e3
|
|
143
|
+
});
|
|
144
|
+
return parseProcessTable(out.stdout ?? "");
|
|
145
|
+
}
|
|
146
|
+
function readTable() {
|
|
147
|
+
try {
|
|
148
|
+
return processTable();
|
|
149
|
+
} catch {
|
|
150
|
+
return [];
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function descendantsOf(root) {
|
|
154
|
+
const table = readTable();
|
|
155
|
+
const startOf = new Map(table.map((p) => [p.pid, Number(p.started)]));
|
|
156
|
+
const found = [];
|
|
157
|
+
const queue = [root];
|
|
158
|
+
while (queue.length > 0) {
|
|
159
|
+
const parent = queue.shift();
|
|
160
|
+
for (const p of table) {
|
|
161
|
+
if (p.ppid !== parent || p.pid === parent || found.some((f) => f.pid === p.pid)) continue;
|
|
162
|
+
if (Number(p.started) < (startOf.get(parent) ?? 0)) continue;
|
|
163
|
+
found.push(p);
|
|
164
|
+
queue.push(p.pid);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return found;
|
|
168
|
+
}
|
|
169
|
+
function survivors(noted, now) {
|
|
170
|
+
const current = new Set(now.map((p) => `${p.pid} ${p.started}`));
|
|
171
|
+
return noted.filter((p) => current.has(`${p.pid} ${p.started}`)).map((p) => p.pid);
|
|
172
|
+
}
|
|
173
|
+
function killAll(pids) {
|
|
174
|
+
for (const pid of pids) {
|
|
175
|
+
try {
|
|
176
|
+
process.kill(pid, "SIGKILL");
|
|
177
|
+
} catch {
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function killSurvivors(noted) {
|
|
182
|
+
if (noted.length > 0) killAll(survivors(noted, readTable()));
|
|
183
|
+
}
|
|
184
|
+
function track(session) {
|
|
185
|
+
if (open.size === 0) {
|
|
186
|
+
process.on("SIGINT", onSignal);
|
|
187
|
+
process.on("SIGTERM", onSignal);
|
|
188
|
+
process.on("exit", onExit);
|
|
189
|
+
}
|
|
190
|
+
open.add(session);
|
|
191
|
+
return () => {
|
|
192
|
+
if (!open.delete(session) || open.size > 0) return;
|
|
193
|
+
process.off("SIGINT", onSignal);
|
|
194
|
+
process.off("SIGTERM", onSignal);
|
|
195
|
+
process.off("exit", onExit);
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
async function closeAllSessions() {
|
|
199
|
+
await Promise.all([...open].map((session) => session.close()));
|
|
200
|
+
}
|
|
201
|
+
var WINDOWS_TABLE, open, interrupted, onSignal, onExit;
|
|
202
|
+
var init_processes = __esm({
|
|
203
|
+
"src/mcp-testing/connect/processes.ts"() {
|
|
204
|
+
"use strict";
|
|
205
|
+
init_esm_shims();
|
|
206
|
+
WINDOWS_TABLE = 'Get-CimInstance Win32_Process | ForEach-Object { try { "{0} {1} {2}" -f $_.ProcessId, $_.ParentProcessId, $_.CreationDate.ToFileTimeUtc() } catch {} }';
|
|
207
|
+
open = /* @__PURE__ */ new Set();
|
|
208
|
+
interrupted = false;
|
|
209
|
+
onSignal = (signal) => {
|
|
210
|
+
const code = signal === "SIGINT" ? 130 : 143;
|
|
211
|
+
if (interrupted) {
|
|
212
|
+
for (const session of open) session.killNow();
|
|
213
|
+
process.exit(code);
|
|
214
|
+
}
|
|
215
|
+
interrupted = true;
|
|
216
|
+
void closeAllSessions().finally(() => process.exit(code));
|
|
217
|
+
};
|
|
218
|
+
onExit = () => {
|
|
219
|
+
for (const session of open) session.killNow();
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
// src/mcp-testing/connect/redact.ts
|
|
225
|
+
function maskUrl(raw) {
|
|
226
|
+
let url;
|
|
227
|
+
try {
|
|
228
|
+
url = new URL(raw);
|
|
229
|
+
} catch {
|
|
230
|
+
return raw;
|
|
231
|
+
}
|
|
232
|
+
if (url.username !== "") url.username = MASK;
|
|
233
|
+
if (url.password !== "") url.password = MASK;
|
|
234
|
+
for (const name of [...url.searchParams.keys()])
|
|
235
|
+
if (SECRET_QUERY.has(name.toLowerCase())) url.searchParams.set(name, MASK);
|
|
236
|
+
return url.href.replaceAll("%2A%2A%2A", MASK);
|
|
237
|
+
}
|
|
238
|
+
function secretsOf(target) {
|
|
239
|
+
const secrets = { values: [], named: [], urls: [] };
|
|
240
|
+
if (target.kind === "stdio") {
|
|
241
|
+
for (const value of Object.values(target.env)) secrets.values.push(value);
|
|
242
|
+
for (const arg of target.args) secrets.values.push(arg);
|
|
243
|
+
return secrets;
|
|
244
|
+
}
|
|
245
|
+
for (const value of Object.values(target.headers)) {
|
|
246
|
+
secrets.values.push(value);
|
|
247
|
+
const [scheme, credentials, ...rest] = value.trim().split(/\s+/);
|
|
248
|
+
if (credentials === void 0 || rest.length > 0) continue;
|
|
249
|
+
secrets.values.push(credentials);
|
|
250
|
+
if (scheme?.toLowerCase() !== "basic") continue;
|
|
251
|
+
const pair = Buffer.from(credentials, "base64").toString("utf8");
|
|
252
|
+
const colon = pair.indexOf(":");
|
|
253
|
+
if (colon < 0) continue;
|
|
254
|
+
secrets.values.push(pair, pair.slice(0, colon));
|
|
255
|
+
secrets.named.push(pair.slice(colon + 1));
|
|
256
|
+
}
|
|
257
|
+
let url;
|
|
258
|
+
try {
|
|
259
|
+
url = new URL(target.url);
|
|
260
|
+
} catch {
|
|
261
|
+
return secrets;
|
|
262
|
+
}
|
|
263
|
+
secrets.values.push(url.username, decoded(url.username));
|
|
264
|
+
secrets.named.push(url.password, decoded(url.password));
|
|
265
|
+
for (const [name, value] of rawQuery(url.search)) {
|
|
266
|
+
if (SECRET_QUERY.has(decoded(name).toLowerCase()))
|
|
267
|
+
secrets.named.push(value, decoded(value.replaceAll("+", " ")));
|
|
268
|
+
}
|
|
269
|
+
for (const [name, value] of url.searchParams)
|
|
270
|
+
if (SECRET_QUERY.has(name.toLowerCase())) secrets.named.push(value);
|
|
271
|
+
secrets.urls.push(target.url, url.href, url.href.replace(/\/$/, ""));
|
|
272
|
+
return secrets;
|
|
273
|
+
}
|
|
274
|
+
function createRedactor(secrets, opts = {}) {
|
|
275
|
+
const forms = /* @__PURE__ */ new Set();
|
|
276
|
+
const add = (secret) => {
|
|
277
|
+
forms.add(secret);
|
|
278
|
+
forms.add(encodeURIComponent(secret));
|
|
279
|
+
forms.add(JSON.stringify(secret).slice(1, -1));
|
|
280
|
+
};
|
|
281
|
+
for (const secret of secrets) if (secret.length >= MIN_SECRET_LENGTH) add(secret);
|
|
282
|
+
for (const secret of opts.named ?? []) if (secret !== "") add(secret);
|
|
283
|
+
const longestFirst = (items) => [...new Set(items)].sort((a, b) => b.length - a.length);
|
|
284
|
+
const ordered = longestFirst(forms);
|
|
285
|
+
const urls = longestFirst(opts.url?.raw ?? []).filter((raw) => raw !== "");
|
|
286
|
+
const text = (input) => ordered.reduce(
|
|
287
|
+
(out, secret) => out.replaceAll(secret, MASK),
|
|
288
|
+
urls.reduce((out, raw) => out.replaceAll(raw, opts.url.masked), input)
|
|
289
|
+
);
|
|
290
|
+
const value = (input, depth = 0) => {
|
|
291
|
+
if (typeof input === "string") return text(input);
|
|
292
|
+
if (input === null || typeof input !== "object") return input;
|
|
293
|
+
if (depth >= MAX_DEPTH) return "[cut: too deep]";
|
|
294
|
+
if (Array.isArray(input)) return input.map((item) => value(item, depth + 1));
|
|
295
|
+
return Object.fromEntries(
|
|
296
|
+
Object.entries(input).map(([k, v]) => [text(k), value(v, depth + 1)])
|
|
297
|
+
);
|
|
298
|
+
};
|
|
299
|
+
return { text, value: (input) => value(input) };
|
|
300
|
+
}
|
|
301
|
+
function redactorFor(target) {
|
|
302
|
+
const { values, named, urls } = secretsOf(target);
|
|
303
|
+
return createRedactor(values, {
|
|
304
|
+
named,
|
|
305
|
+
...target.kind === "stdio" ? {} : { url: { raw: urls, masked: maskUrl(target.url) } }
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
function describeTarget(target, redact) {
|
|
309
|
+
const masked = (entries, secret) => Object.fromEntries(
|
|
310
|
+
Object.entries(entries).map(([name, value]) => [
|
|
311
|
+
name,
|
|
312
|
+
secret(name) ? MASK : redact.text(value)
|
|
313
|
+
])
|
|
314
|
+
);
|
|
315
|
+
if (target.kind === "stdio") {
|
|
316
|
+
return {
|
|
317
|
+
transport: "stdio",
|
|
318
|
+
command: redact.text(target.command),
|
|
319
|
+
args: target.args.map(redact.text),
|
|
320
|
+
env: masked(target.env, isSecretEnv),
|
|
321
|
+
...target.cwd !== void 0 ? { cwd: target.cwd } : {}
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
return {
|
|
325
|
+
transport: target.kind,
|
|
326
|
+
url: redact.text(maskUrl(target.url)),
|
|
327
|
+
headers: masked(target.headers, isSecretHeader)
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
var MASK, MIN_SECRET_LENGTH, MAX_DEPTH, SECRET_HEADERS, SECRET_HEADER_PART, SECRET_ENV_PART, SECRET_QUERY, isSecretHeader, isSecretEnv, decoded, rawQuery;
|
|
331
|
+
var init_redact = __esm({
|
|
332
|
+
"src/mcp-testing/connect/redact.ts"() {
|
|
333
|
+
"use strict";
|
|
334
|
+
init_esm_shims();
|
|
335
|
+
MASK = "***";
|
|
336
|
+
MIN_SECRET_LENGTH = 8;
|
|
337
|
+
MAX_DEPTH = 64;
|
|
338
|
+
SECRET_HEADERS = /* @__PURE__ */ new Set(["authorization", "proxy-authorization", "cookie", "set-cookie"]);
|
|
339
|
+
SECRET_HEADER_PART = /key|token|secret|auth/i;
|
|
340
|
+
SECRET_ENV_PART = /KEY|TOKEN|SECRET|PASSWORD/i;
|
|
341
|
+
SECRET_QUERY = /* @__PURE__ */ new Set(["token", "key", "secret", "password", "api_key", "access_token"]);
|
|
342
|
+
isSecretHeader = (name) => SECRET_HEADERS.has(name.toLowerCase()) || SECRET_HEADER_PART.test(name);
|
|
343
|
+
isSecretEnv = (name) => SECRET_ENV_PART.test(name);
|
|
344
|
+
decoded = (text) => {
|
|
345
|
+
try {
|
|
346
|
+
return decodeURIComponent(text);
|
|
347
|
+
} catch {
|
|
348
|
+
return text;
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
rawQuery = (search) => search.slice(1).split("&").filter((pair) => pair !== "").map((pair) => {
|
|
352
|
+
const eq = pair.indexOf("=");
|
|
353
|
+
return eq < 0 ? [pair, ""] : [pair.slice(0, eq), pair.slice(eq + 1)];
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
// src/mcp-testing/connect/session.ts
|
|
359
|
+
var session_exports = {};
|
|
360
|
+
__export(session_exports, {
|
|
361
|
+
ConnectError: () => ConnectError,
|
|
362
|
+
STDIO_MESSAGE_LIMIT: () => STDIO_MESSAGE_LIMIT,
|
|
363
|
+
closeAllSessions: () => closeAllSessions,
|
|
364
|
+
openSession: () => openSession
|
|
365
|
+
});
|
|
366
|
+
import { homedir as homedir2 } from "os";
|
|
367
|
+
import { createInterface } from "readline";
|
|
368
|
+
import {
|
|
369
|
+
Client,
|
|
370
|
+
ProtocolError,
|
|
371
|
+
SdkError,
|
|
372
|
+
SdkErrorCode,
|
|
373
|
+
SdkHttpError,
|
|
374
|
+
SSEClientTransport,
|
|
375
|
+
SseError,
|
|
376
|
+
StreamableHTTPClientTransport,
|
|
377
|
+
UnauthorizedError
|
|
378
|
+
} from "@modelcontextprotocol/client";
|
|
379
|
+
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
|
380
|
+
function answers(frame, id) {
|
|
381
|
+
if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
|
|
382
|
+
const f = frame;
|
|
383
|
+
if (!("result" in f) && !("error" in f)) return false;
|
|
384
|
+
return id === null ? "error" in f && (f["id"] === null || f["id"] === void 0) : f["id"] === id;
|
|
385
|
+
}
|
|
386
|
+
function fromEventStream(text, id) {
|
|
387
|
+
for (const line of text.split(/\r?\n/)) {
|
|
388
|
+
if (!line.startsWith("data:")) continue;
|
|
389
|
+
const frame = parsed(line.slice(5).trim());
|
|
390
|
+
if (answers(frame, id)) return frame;
|
|
391
|
+
}
|
|
392
|
+
return void 0;
|
|
393
|
+
}
|
|
394
|
+
function createTransport(target) {
|
|
395
|
+
if (target.kind === "stdio") {
|
|
396
|
+
return new StdioClientTransport({
|
|
397
|
+
command: target.command,
|
|
398
|
+
args: target.args,
|
|
399
|
+
env: target.env,
|
|
400
|
+
stderr: "pipe",
|
|
401
|
+
maxBufferSize: STDIO_MESSAGE_LIMIT,
|
|
402
|
+
...target.cwd !== void 0 ? { cwd: target.cwd } : {}
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
const options = {
|
|
406
|
+
requestInit: { headers: target.headers },
|
|
407
|
+
redirectPolicy: "same-origin"
|
|
408
|
+
};
|
|
409
|
+
return target.kind === "sse" ? new SSEClientTransport(new URL(target.url), options) : new StreamableHTTPClientTransport(new URL(target.url), options);
|
|
410
|
+
}
|
|
411
|
+
function tap(transport, journal, on) {
|
|
412
|
+
const send = transport.send.bind(transport);
|
|
413
|
+
transport.send = (message, options) => {
|
|
414
|
+
journal.write("out", { frame: message });
|
|
415
|
+
on.frame("out", message);
|
|
416
|
+
return send(message, options);
|
|
417
|
+
};
|
|
418
|
+
const logged = /* @__PURE__ */ new WeakSet();
|
|
419
|
+
intercept(transport, "onmessage", (message) => {
|
|
420
|
+
if (logged.has(message)) return;
|
|
421
|
+
logged.add(message);
|
|
422
|
+
journal.write("in", { frame: message });
|
|
423
|
+
on.frame("in", message);
|
|
424
|
+
});
|
|
425
|
+
intercept(transport, "onclose", on.closed);
|
|
426
|
+
intercept(transport, "onerror", on.error);
|
|
427
|
+
}
|
|
428
|
+
function intercept(transport, name, before) {
|
|
429
|
+
let handler;
|
|
430
|
+
Object.defineProperty(transport, name, {
|
|
431
|
+
configurable: true,
|
|
432
|
+
get: () => {
|
|
433
|
+
const current = handler;
|
|
434
|
+
return current && ((...args) => {
|
|
435
|
+
before(...args);
|
|
436
|
+
current(...args);
|
|
437
|
+
});
|
|
438
|
+
},
|
|
439
|
+
set: (fn) => handler = fn
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
function watchStdout(transport, journal, seen) {
|
|
443
|
+
const start = transport.start.bind(transport);
|
|
444
|
+
transport.start = async () => {
|
|
445
|
+
await start();
|
|
446
|
+
const stdout = transport._process?.stdout;
|
|
447
|
+
if (stdout === null || stdout === void 0) return;
|
|
448
|
+
createInterface({ input: stdout, crlfDelay: Infinity }).on("line", (line) => {
|
|
449
|
+
const isMessage = isJsonRpc(line);
|
|
450
|
+
if (!isMessage) journal.write("noise", { line });
|
|
451
|
+
seen(line, isMessage);
|
|
452
|
+
});
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
function watchOverflow(transport, over) {
|
|
456
|
+
const buffer = transport._readBuffer;
|
|
457
|
+
const append = buffer?.append?.bind(buffer);
|
|
458
|
+
if (buffer === void 0 || append === void 0) return;
|
|
459
|
+
buffer.append = (chunk) => {
|
|
460
|
+
try {
|
|
461
|
+
append(chunk);
|
|
462
|
+
} catch (err) {
|
|
463
|
+
over();
|
|
464
|
+
throw err;
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
function isJsonRpc(line) {
|
|
469
|
+
try {
|
|
470
|
+
const parsed2 = JSON.parse(line);
|
|
471
|
+
return parsed2 !== null && typeof parsed2 === "object" && parsed2.jsonrpc === "2.0";
|
|
472
|
+
} catch {
|
|
473
|
+
return false;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
function kindOf(err, stdio, transportClosed) {
|
|
477
|
+
if (err instanceof SdkError && err.code === SdkErrorCode.RequestTimeout) return "timeout";
|
|
478
|
+
const code = err?.code;
|
|
479
|
+
if (stdio && typeof code === "string" && /^(ENOENT|EACCES|EPERM|ENOTDIR|EINVAL)$/.test(code))
|
|
480
|
+
return "could-not-start";
|
|
481
|
+
if (stdio) return transportClosed ? "exited-early" : "protocol";
|
|
482
|
+
if (err instanceof UnauthorizedError) return "auth";
|
|
483
|
+
const status = err instanceof SdkHttpError ? Number(err.status) : err instanceof SseError ? err.code : void 0;
|
|
484
|
+
if (status === 401 || status === 403) return "auth";
|
|
485
|
+
if (status !== void 0 && status >= 300 && status < 400) return "network";
|
|
486
|
+
if (err instanceof SseError && status === void 0) return "network";
|
|
487
|
+
if (err instanceof TypeError || err?.cause?.code !== void 0)
|
|
488
|
+
return "network";
|
|
489
|
+
return "protocol";
|
|
490
|
+
}
|
|
491
|
+
async function openSession(config) {
|
|
492
|
+
const { target } = config;
|
|
493
|
+
const stdio = target.kind === "stdio";
|
|
494
|
+
const redact = redactorFor(target);
|
|
495
|
+
const clean = (text) => printable(redact.text(machineless(text, void 0, homedir2())));
|
|
496
|
+
const journal = openJournal(config.debugOut, redact);
|
|
497
|
+
journal.write("meta", describeTarget(target, redact));
|
|
498
|
+
const transport = createTransport(target);
|
|
499
|
+
let transportClosed = false;
|
|
500
|
+
let spawnError;
|
|
501
|
+
const handshake = {
|
|
502
|
+
offered: void 0,
|
|
503
|
+
result: void 0
|
|
504
|
+
};
|
|
505
|
+
tap(transport, journal, {
|
|
506
|
+
frame: (dir, message) => {
|
|
507
|
+
const m = message;
|
|
508
|
+
if (dir === "out" && m.method === "initialize") {
|
|
509
|
+
handshake.id = m.id;
|
|
510
|
+
handshake.offered = m.params?.protocolVersion;
|
|
511
|
+
} else if (dir === "in" && handshake.id !== void 0 && m.id === handshake.id)
|
|
512
|
+
handshake.result = m.result;
|
|
513
|
+
},
|
|
514
|
+
closed: () => transportClosed = true,
|
|
515
|
+
error: (err) => {
|
|
516
|
+
if (spawnError === void 0 && err.syscall?.startsWith("spawn") === true)
|
|
517
|
+
spawnError = err;
|
|
518
|
+
}
|
|
519
|
+
});
|
|
520
|
+
let noted;
|
|
521
|
+
const serverPid = () => transport instanceof StdioClientTransport ? transport.pid : null;
|
|
522
|
+
const note = () => {
|
|
523
|
+
const pid = serverPid();
|
|
524
|
+
if (pid !== null) noted = { pid, tree: descendantsOf(pid) };
|
|
525
|
+
};
|
|
526
|
+
let tooLarge = false;
|
|
527
|
+
const tail = [];
|
|
528
|
+
const noise = { count: 0, first: [] };
|
|
529
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
530
|
+
const seen = (line, isMessage) => {
|
|
531
|
+
if (!isMessage) {
|
|
532
|
+
noise.count++;
|
|
533
|
+
if (noise.first.length < 3) noise.first.push(clean(line).slice(0, 200));
|
|
534
|
+
}
|
|
535
|
+
for (const listener of [...listeners]) listener(line);
|
|
536
|
+
};
|
|
537
|
+
let stderrDone = Promise.resolve();
|
|
538
|
+
if (transport instanceof StdioClientTransport && transport.stderr !== null) {
|
|
539
|
+
const lines = createInterface({ input: transport.stderr, crlfDelay: Infinity });
|
|
540
|
+
lines.on("line", (line) => {
|
|
541
|
+
journal.write("stderr", { line });
|
|
542
|
+
tail.push(clean(line));
|
|
543
|
+
if (tail.length > TAIL_LINES) tail.shift();
|
|
544
|
+
});
|
|
545
|
+
stderrDone = new Promise((resolve8) => lines.once("close", resolve8));
|
|
546
|
+
watchStdout(transport, journal, seen);
|
|
547
|
+
watchOverflow(transport, () => {
|
|
548
|
+
if (tooLarge) return;
|
|
549
|
+
tooLarge = true;
|
|
550
|
+
note();
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
const toConnectError = async (err) => {
|
|
554
|
+
if (transportClosed) await Promise.race([stderrDone, new Promise((r) => setTimeout(r, 500))]);
|
|
555
|
+
const cause = spawnError ?? err;
|
|
556
|
+
const kind = tooLarge ? "too-large" : kindOf(cause, stdio, transportClosed);
|
|
557
|
+
const [lead, withDetail] = LEAD[kind];
|
|
558
|
+
const detail = withDetail ? clean(firstLine(cause instanceof Error ? cause.message : String(cause))) : "";
|
|
559
|
+
const error = new ConnectError(kind, detail === "" ? `${lead}.` : `${lead}: ${detail}`, [
|
|
560
|
+
...tail
|
|
561
|
+
]);
|
|
562
|
+
journal.write("error", { kind, message: error.message });
|
|
563
|
+
return error;
|
|
564
|
+
};
|
|
565
|
+
let closing;
|
|
566
|
+
const shutdown = async () => {
|
|
567
|
+
note();
|
|
568
|
+
await transport.close().catch(() => {
|
|
569
|
+
});
|
|
570
|
+
killSurvivors(noted?.tree ?? []);
|
|
571
|
+
untrack();
|
|
572
|
+
journal.close();
|
|
573
|
+
};
|
|
574
|
+
const closable = {
|
|
575
|
+
close: () => closing ??= shutdown(),
|
|
576
|
+
killNow: () => {
|
|
577
|
+
const pid = serverPid() ?? noted?.pid;
|
|
578
|
+
if (pid === void 0 || pid === null) return;
|
|
579
|
+
const tree = [...descendantsOf(pid), ...noted?.tree ?? []].map((p) => p.pid);
|
|
580
|
+
killAll([.../* @__PURE__ */ new Set([...tree, pid])]);
|
|
581
|
+
}
|
|
582
|
+
};
|
|
583
|
+
const untrack = track(closable);
|
|
584
|
+
const client = new Client({ name: "plune", version: config.clientVersion ?? "0.0.0" });
|
|
585
|
+
let timer;
|
|
586
|
+
try {
|
|
587
|
+
await Promise.race([
|
|
588
|
+
client.connect(transport, { timeout: config.timeoutMs }),
|
|
589
|
+
new Promise((_, reject) => {
|
|
590
|
+
timer = setTimeout(
|
|
591
|
+
() => reject(new SdkError(SdkErrorCode.RequestTimeout, "no answer")),
|
|
592
|
+
config.timeoutMs
|
|
593
|
+
);
|
|
594
|
+
})
|
|
595
|
+
]);
|
|
596
|
+
} catch (err) {
|
|
597
|
+
if (closing === void 0) {
|
|
598
|
+
const error = await toConnectError(err);
|
|
599
|
+
await closable.close();
|
|
600
|
+
throw error;
|
|
601
|
+
}
|
|
602
|
+
} finally {
|
|
603
|
+
clearTimeout(timer);
|
|
604
|
+
}
|
|
605
|
+
if (closing !== void 0) {
|
|
606
|
+
await closing;
|
|
607
|
+
throw new Error("The session was closed while it was connecting.");
|
|
608
|
+
}
|
|
609
|
+
const info = client.getServerVersion();
|
|
610
|
+
return {
|
|
611
|
+
redact,
|
|
612
|
+
server: info === void 0 ? void 0 : { name: String(info.name), version: String(info.version) },
|
|
613
|
+
handshake: { offered: handshake.offered, result: handshake.result },
|
|
614
|
+
stderrTail: () => [...tail],
|
|
615
|
+
async request(method, params, options) {
|
|
616
|
+
try {
|
|
617
|
+
return await client.request(
|
|
618
|
+
params === void 0 ? { method } : { method, params },
|
|
619
|
+
AS_SENT,
|
|
620
|
+
{ timeout: options?.timeoutMs ?? config.timeoutMs }
|
|
621
|
+
);
|
|
622
|
+
} catch (err) {
|
|
623
|
+
if (err instanceof ProtocolError)
|
|
624
|
+
throw new ProtocolError(err.code, clean(err.message), redact.value(err.data));
|
|
625
|
+
throw await toConnectError(err);
|
|
626
|
+
}
|
|
627
|
+
},
|
|
628
|
+
fetchForOrigin(origin) {
|
|
629
|
+
const allowed = new URL(origin).origin;
|
|
630
|
+
const own = target.kind !== "stdio" && new URL(target.url).origin === allowed;
|
|
631
|
+
return async (input, init) => {
|
|
632
|
+
const url = new URL(input);
|
|
633
|
+
if (url.origin !== allowed)
|
|
634
|
+
throw new Error(
|
|
635
|
+
`fetchForOrigin(${allowed}) refuses a request to another origin, ${url.origin}.`
|
|
636
|
+
);
|
|
637
|
+
const headers = new Headers(init?.headers);
|
|
638
|
+
if (own) {
|
|
639
|
+
for (const [name, value] of Object.entries(target.headers))
|
|
640
|
+
if (!headers.has(name)) headers.set(name, value);
|
|
641
|
+
}
|
|
642
|
+
return fetch(url, { ...init, headers, redirect: "manual" });
|
|
643
|
+
};
|
|
644
|
+
},
|
|
645
|
+
async raw(body, id, options) {
|
|
646
|
+
const ms = options?.timeoutMs ?? config.timeoutMs;
|
|
647
|
+
if (target.kind === "sse")
|
|
648
|
+
throw new ConnectError("protocol", "Messages of its own go over stdio and Streamable HTTP only, not HTTP+SSE.", []);
|
|
649
|
+
journal.write("out", { raw: body });
|
|
650
|
+
const noAnswer = () => new ConnectError("timeout", `${LEAD.timeout[0]}.`, [...tail]);
|
|
651
|
+
if (target.kind === "stdio") {
|
|
652
|
+
const stdin = transport._process?.stdin;
|
|
653
|
+
if (stdin === null || stdin === void 0 || stdin.writableEnded)
|
|
654
|
+
throw new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
|
|
655
|
+
return new Promise((resolve8, reject) => {
|
|
656
|
+
const timer2 = setTimeout(() => {
|
|
657
|
+
listeners.delete(listener);
|
|
658
|
+
reject(noAnswer());
|
|
659
|
+
}, ms);
|
|
660
|
+
const listener = (line) => {
|
|
661
|
+
const frame2 = parsed(line);
|
|
662
|
+
if (!answers(frame2, id)) return;
|
|
663
|
+
clearTimeout(timer2);
|
|
664
|
+
listeners.delete(listener);
|
|
665
|
+
resolve8({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
|
|
666
|
+
};
|
|
667
|
+
listeners.add(listener);
|
|
668
|
+
stdin.write(`${body}
|
|
669
|
+
`);
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
const state = transport;
|
|
673
|
+
const headers = new Headers(target.headers);
|
|
674
|
+
headers.set("content-type", "application/json");
|
|
675
|
+
headers.set("accept", "application/json, text/event-stream");
|
|
676
|
+
if (state.sessionId !== void 0) headers.set("mcp-session-id", state.sessionId);
|
|
677
|
+
if (state._protocolVersion !== void 0) headers.set("mcp-protocol-version", state._protocolVersion);
|
|
678
|
+
const lost = async (err) => err?.name === "TimeoutError" ? noAnswer() : toConnectError(err);
|
|
679
|
+
let text = "";
|
|
680
|
+
let frame;
|
|
681
|
+
let status;
|
|
682
|
+
try {
|
|
683
|
+
const res = await fetch(target.url, {
|
|
684
|
+
method: "POST",
|
|
685
|
+
headers,
|
|
686
|
+
body,
|
|
687
|
+
redirect: "manual",
|
|
688
|
+
signal: AbortSignal.timeout(ms)
|
|
689
|
+
});
|
|
690
|
+
status = res.status;
|
|
691
|
+
const sse = (res.headers.get("content-type") ?? "").includes("text/event-stream");
|
|
692
|
+
if (res.body !== null) {
|
|
693
|
+
const reader = res.body.getReader();
|
|
694
|
+
const decoder = new TextDecoder();
|
|
695
|
+
for (; ; ) {
|
|
696
|
+
const { done, value } = await reader.read();
|
|
697
|
+
if (done) break;
|
|
698
|
+
text += decoder.decode(value, { stream: true });
|
|
699
|
+
if (sse && (frame = fromEventStream(text, id)) !== void 0) break;
|
|
700
|
+
if (text.length > STDIO_MESSAGE_LIMIT) break;
|
|
701
|
+
}
|
|
702
|
+
await reader.cancel().catch(() => {
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
if (!sse) {
|
|
706
|
+
const whole = parsed(text);
|
|
707
|
+
if (whole !== null && typeof whole === "object" && !Array.isArray(whole))
|
|
708
|
+
frame = whole;
|
|
709
|
+
}
|
|
710
|
+
} catch (err) {
|
|
711
|
+
throw await lost(err);
|
|
712
|
+
}
|
|
713
|
+
journal.write("in", frame !== void 0 ? { frame } : { status, raw: text.slice(0, RAW_TEXT) });
|
|
714
|
+
return { frame, status, text: clean(text).slice(0, RAW_TEXT) };
|
|
715
|
+
},
|
|
716
|
+
stdoutNoise: () => ({ count: noise.count, first: [...noise.first] }),
|
|
717
|
+
async endInput(waitMs) {
|
|
718
|
+
const proc = transport._process;
|
|
719
|
+
if (proc === void 0) return true;
|
|
720
|
+
if (proc.exitCode !== null || proc.signalCode !== null) return true;
|
|
721
|
+
const exited = new Promise((resolve8) => proc.once("exit", () => resolve8(true)));
|
|
722
|
+
proc.stdin?.end();
|
|
723
|
+
let timer2;
|
|
724
|
+
const late = new Promise((resolve8) => timer2 = setTimeout(() => resolve8(false), waitMs));
|
|
725
|
+
const result = await Promise.race([exited, late]);
|
|
726
|
+
clearTimeout(timer2);
|
|
727
|
+
return result;
|
|
728
|
+
},
|
|
729
|
+
close: closable.close
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
var ConnectError, RAW_TEXT, parsed, TAIL_LINES, STDIO_MESSAGE_LIMIT, AS_SENT, firstLine, LEAD;
|
|
733
|
+
var init_session = __esm({
|
|
734
|
+
"src/mcp-testing/connect/session.ts"() {
|
|
735
|
+
"use strict";
|
|
736
|
+
init_esm_shims();
|
|
737
|
+
init_failure_detail();
|
|
738
|
+
init_exit_codes();
|
|
739
|
+
init_journal();
|
|
740
|
+
init_processes();
|
|
741
|
+
init_redact();
|
|
742
|
+
init_processes();
|
|
743
|
+
ConnectError = class extends Error {
|
|
744
|
+
constructor(kind, message, stderrTail) {
|
|
745
|
+
super(message);
|
|
746
|
+
this.kind = kind;
|
|
747
|
+
this.stderrTail = stderrTail;
|
|
748
|
+
this.name = "ConnectError";
|
|
749
|
+
}
|
|
750
|
+
kind;
|
|
751
|
+
stderrTail;
|
|
752
|
+
exitCode = MCP_EXIT.usage;
|
|
753
|
+
};
|
|
754
|
+
RAW_TEXT = 2e3;
|
|
755
|
+
parsed = (text) => {
|
|
756
|
+
try {
|
|
757
|
+
return JSON.parse(text);
|
|
758
|
+
} catch {
|
|
759
|
+
return void 0;
|
|
760
|
+
}
|
|
761
|
+
};
|
|
762
|
+
TAIL_LINES = 20;
|
|
763
|
+
STDIO_MESSAGE_LIMIT = 10 * 1024 * 1024;
|
|
764
|
+
AS_SENT = {
|
|
765
|
+
"~standard": { version: 1, vendor: "plune", validate: (value) => ({ value }) }
|
|
766
|
+
};
|
|
767
|
+
firstLine = (text) => text.split(/\r?\n/)[0] ?? "";
|
|
768
|
+
LEAD = {
|
|
769
|
+
"could-not-start": ["Could not start the server command", true],
|
|
770
|
+
"exited-early": ["The server process exited before it answered", false],
|
|
771
|
+
"too-large": [
|
|
772
|
+
`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)`,
|
|
773
|
+
false
|
|
774
|
+
],
|
|
775
|
+
timeout: ["The server did not answer within --timeout", false],
|
|
776
|
+
protocol: ["The server did not answer as an MCP server", true],
|
|
777
|
+
auth: ["The server refused the credentials", true],
|
|
778
|
+
network: ["Could not reach the server", true]
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
});
|
|
782
|
+
|
|
783
|
+
// src/mcp-testing/connect/safe-tools.ts
|
|
784
|
+
function selectSafeTools(tools, opts = {}) {
|
|
785
|
+
const selection = { safe: [], skipped: [] };
|
|
786
|
+
for (const tool of tools) {
|
|
787
|
+
const reason = skipReason(tool, opts.allowWrite === true);
|
|
788
|
+
if (reason === void 0) selection.safe.push(tool);
|
|
789
|
+
else selection.skipped.push({ tool, reason });
|
|
790
|
+
}
|
|
791
|
+
return selection;
|
|
792
|
+
}
|
|
793
|
+
function skipReason(tool, allowWrite) {
|
|
794
|
+
if (tool === null || typeof tool !== "object" || typeof tool.name !== "string")
|
|
795
|
+
return "malformed";
|
|
796
|
+
const { annotations, inputSchema } = tool;
|
|
797
|
+
const readOnly = annotations?.readOnlyHint === true;
|
|
798
|
+
if (!readOnly && !allowWrite) return "not-read-only";
|
|
799
|
+
const hint = annotations?.destructiveHint;
|
|
800
|
+
if (hint === true || hint !== void 0 && typeof hint !== "boolean") return "destructive";
|
|
801
|
+
if (!readOnly && hint !== false) return "no-destructive-hint";
|
|
802
|
+
const required = inputSchema?.required;
|
|
803
|
+
if (required !== void 0 && !Array.isArray(required)) return "malformed";
|
|
804
|
+
if (Array.isArray(required) && required.length > 0) return "required-arguments";
|
|
805
|
+
if (mayRequire(inputSchema)) return "required-arguments";
|
|
806
|
+
return void 0;
|
|
807
|
+
}
|
|
808
|
+
function mayRequire(schema) {
|
|
809
|
+
if (schema === null || typeof schema !== "object") return false;
|
|
810
|
+
const s = schema;
|
|
811
|
+
if (["allOf", "anyOf", "oneOf", "$ref", "dependentRequired"].some((k) => k in s)) return true;
|
|
812
|
+
return typeof s.minProperties === "number" && s.minProperties > 0;
|
|
813
|
+
}
|
|
814
|
+
var init_safe_tools = __esm({
|
|
815
|
+
"src/mcp-testing/connect/safe-tools.ts"() {
|
|
816
|
+
"use strict";
|
|
817
|
+
init_esm_shims();
|
|
818
|
+
}
|
|
819
|
+
});
|
|
820
|
+
|
|
821
|
+
// src/mcp-testing/connect/tools.ts
|
|
822
|
+
var tools_exports = {};
|
|
823
|
+
__export(tools_exports, {
|
|
824
|
+
MAX_PAGES: () => MAX_PAGES,
|
|
825
|
+
asTools: () => asTools,
|
|
826
|
+
callTool: () => callTool,
|
|
827
|
+
callableTools: () => callableTools,
|
|
828
|
+
listAll: () => listAll
|
|
829
|
+
});
|
|
830
|
+
import { ProtocolError as ProtocolError2 } from "@modelcontextprotocol/client";
|
|
831
|
+
async function listAll(session, method, key, opts = {}) {
|
|
832
|
+
const items = [];
|
|
833
|
+
let malformed = false;
|
|
834
|
+
let cursor;
|
|
835
|
+
for (let pages = 1; pages <= MAX_PAGES; pages++) {
|
|
836
|
+
if (opts.signal?.aborted === true)
|
|
837
|
+
return { items, pages: pages - 1, complete: false, malformed };
|
|
838
|
+
const page = await session.request(
|
|
839
|
+
method,
|
|
840
|
+
cursor === void 0 ? void 0 : { cursor },
|
|
841
|
+
opts.timeoutMs === void 0 ? {} : { timeoutMs: opts.timeoutMs }
|
|
842
|
+
);
|
|
843
|
+
const listed = isRecord3(page) ? page[key] : void 0;
|
|
844
|
+
if (Array.isArray(listed)) for (const item of listed) items.push(item);
|
|
845
|
+
else malformed = true;
|
|
846
|
+
cursor = isRecord3(page) && typeof page.nextCursor === "string" && page.nextCursor !== "" ? page.nextCursor : void 0;
|
|
847
|
+
if (cursor === void 0) return { items, pages, complete: true, malformed };
|
|
848
|
+
}
|
|
849
|
+
return { items, pages: MAX_PAGES, complete: false, malformed };
|
|
850
|
+
}
|
|
851
|
+
function asTools(items) {
|
|
852
|
+
const tools = [];
|
|
853
|
+
const unnamed = /* @__PURE__ */ new Map();
|
|
854
|
+
for (const t of items) {
|
|
855
|
+
const name = isRecord3(t) ? t.name : void 0;
|
|
856
|
+
if (typeof name === "string" && name !== "") {
|
|
857
|
+
tools.push(t);
|
|
858
|
+
continue;
|
|
859
|
+
}
|
|
860
|
+
const tool = { ...isRecord3(t) ? t : {}, name: "" };
|
|
861
|
+
unnamed.set(tool, name === void 0 ? "(no name)" : String(JSON.stringify(name)));
|
|
862
|
+
tools.push(tool);
|
|
863
|
+
}
|
|
864
|
+
return { tools, unnamed };
|
|
865
|
+
}
|
|
866
|
+
function callableTools(tools, unnamed, opts = {}) {
|
|
867
|
+
const counts = /* @__PURE__ */ new Map();
|
|
868
|
+
for (const t of tools) if (!unnamed.has(t)) counts.set(t.name, (counts.get(t.name) ?? 0) + 1);
|
|
869
|
+
const refused = [];
|
|
870
|
+
const candidates = [];
|
|
871
|
+
for (const t of tools) {
|
|
872
|
+
const label = unnamed.get(t);
|
|
873
|
+
if (label !== void 0) refused.push({ tool: label, reason: "invalid-name" });
|
|
874
|
+
else if ((counts.get(t.name) ?? 0) > 1)
|
|
875
|
+
refused.push({ tool: t.name, reason: "duplicate-name" });
|
|
876
|
+
else candidates.push(t);
|
|
877
|
+
}
|
|
878
|
+
const { safe, skipped } = selectSafeTools(candidates, opts);
|
|
879
|
+
return {
|
|
880
|
+
safe,
|
|
881
|
+
skipped: [...refused, ...skipped.map((s) => ({ tool: s.tool.name, reason: s.reason }))]
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
async function callTool(session, name, timeoutMs, args = {}) {
|
|
885
|
+
try {
|
|
886
|
+
const result = await session.request("tools/call", { name, arguments: args }, { timeoutMs });
|
|
887
|
+
return { kind: "result", result };
|
|
888
|
+
} catch (err) {
|
|
889
|
+
if (err instanceof ConnectError) {
|
|
890
|
+
if (err.kind === "auth") throw err;
|
|
891
|
+
return err.kind === "timeout" ? { kind: "timeout" } : { kind: "lost", message: err.message };
|
|
892
|
+
}
|
|
893
|
+
if (err instanceof ProtocolError2) return { kind: "error", message: err.message };
|
|
894
|
+
throw err;
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
var MAX_PAGES, isRecord3;
|
|
898
|
+
var init_tools = __esm({
|
|
899
|
+
"src/mcp-testing/connect/tools.ts"() {
|
|
900
|
+
"use strict";
|
|
901
|
+
init_esm_shims();
|
|
902
|
+
init_safe_tools();
|
|
903
|
+
init_session();
|
|
904
|
+
MAX_PAGES = 100;
|
|
905
|
+
isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
906
|
+
}
|
|
907
|
+
});
|
|
908
|
+
|
|
909
|
+
// src/index.ts
|
|
910
|
+
init_esm_shims();
|
|
911
|
+
|
|
1
912
|
// src/cli/commands/run.ts
|
|
913
|
+
init_esm_shims();
|
|
2
914
|
import * as fs5 from "fs";
|
|
3
|
-
import * as
|
|
915
|
+
import * as path6 from "path";
|
|
4
916
|
|
|
5
917
|
// src/config/loader.ts
|
|
918
|
+
init_esm_shims();
|
|
6
919
|
import * as fs2 from "fs/promises";
|
|
7
920
|
import { parse } from "yaml";
|
|
8
921
|
|
|
9
922
|
// src/config/env-overrides.ts
|
|
923
|
+
init_esm_shims();
|
|
10
924
|
function applyEnvOverrides(config, env) {
|
|
11
925
|
const result = structuredClone(config);
|
|
12
926
|
if (env["PLUNE_PROVIDER"] !== void 0) {
|
|
@@ -27,6 +941,7 @@ function applyEnvOverrides(config, env) {
|
|
|
27
941
|
}
|
|
28
942
|
|
|
29
943
|
// src/config/errors.ts
|
|
944
|
+
init_esm_shims();
|
|
30
945
|
var ConfigNotFoundError = class extends Error {
|
|
31
946
|
code = "CFG_NOT_FOUND";
|
|
32
947
|
constructor(message) {
|
|
@@ -52,8 +967,9 @@ var ConfigValidationError = class extends Error {
|
|
|
52
967
|
};
|
|
53
968
|
|
|
54
969
|
// src/config/discover.ts
|
|
970
|
+
init_esm_shims();
|
|
55
971
|
import * as fs from "fs";
|
|
56
|
-
import * as
|
|
972
|
+
import * as path2 from "path";
|
|
57
973
|
var FILENAME = "plune.yaml";
|
|
58
974
|
var MAX_STEPS = 50;
|
|
59
975
|
function discoverConfigPath(cwd, override) {
|
|
@@ -66,11 +982,11 @@ function discoverConfigPath(cwd, override) {
|
|
|
66
982
|
let dir = cwd;
|
|
67
983
|
let steps = 0;
|
|
68
984
|
while (steps < MAX_STEPS) {
|
|
69
|
-
const candidate =
|
|
985
|
+
const candidate = path2.join(dir, FILENAME);
|
|
70
986
|
if (fs.existsSync(candidate)) {
|
|
71
987
|
return candidate;
|
|
72
988
|
}
|
|
73
|
-
const parent =
|
|
989
|
+
const parent = path2.dirname(dir);
|
|
74
990
|
if (parent === dir) {
|
|
75
991
|
break;
|
|
76
992
|
}
|
|
@@ -82,7 +998,100 @@ function discoverConfigPath(cwd, override) {
|
|
|
82
998
|
);
|
|
83
999
|
}
|
|
84
1000
|
|
|
1001
|
+
// src/config/mcp.ts
|
|
1002
|
+
init_esm_shims();
|
|
1003
|
+
import * as path3 from "path";
|
|
1004
|
+
var MCP_LIMIT_DEFAULTS = {
|
|
1005
|
+
max_steps: 10,
|
|
1006
|
+
max_tool_calls: 20,
|
|
1007
|
+
max_total_tokens: 1e5,
|
|
1008
|
+
timeout_ms: 12e4,
|
|
1009
|
+
tool_timeout_ms: 3e4
|
|
1010
|
+
};
|
|
1011
|
+
function mcpLimits(config, evalConfig) {
|
|
1012
|
+
return { ...MCP_LIMIT_DEFAULTS, ...config.mcp?.limits, ...evalConfig.mcp?.limits };
|
|
1013
|
+
}
|
|
1014
|
+
var REFERENCE = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
|
|
1015
|
+
function expandVars(value, env) {
|
|
1016
|
+
const literal = (text) => {
|
|
1017
|
+
if (text.includes("${")) throw new Error('has a "${" that is not ${NAME} or ${NAME:-default}');
|
|
1018
|
+
return text;
|
|
1019
|
+
};
|
|
1020
|
+
let out = "";
|
|
1021
|
+
let last = 0;
|
|
1022
|
+
for (const match of value.matchAll(REFERENCE)) {
|
|
1023
|
+
const [whole, name, fallback] = match;
|
|
1024
|
+
out += literal(value.slice(last, match.index));
|
|
1025
|
+
const set = env[name];
|
|
1026
|
+
if (set !== void 0 && set !== "") out += set;
|
|
1027
|
+
else if (fallback !== void 0) out += fallback;
|
|
1028
|
+
else
|
|
1029
|
+
throw new Error(
|
|
1030
|
+
`\${${name}} is not set or is empty, and has no default (\${${name}:-default})`
|
|
1031
|
+
);
|
|
1032
|
+
last = match.index + whole.length;
|
|
1033
|
+
}
|
|
1034
|
+
return out + literal(value.slice(last));
|
|
1035
|
+
}
|
|
1036
|
+
function serverValues(server) {
|
|
1037
|
+
const out = [];
|
|
1038
|
+
if (server.command !== void 0) out.push(["command", server.command]);
|
|
1039
|
+
(server.args ?? []).forEach((arg, i) => out.push([`args.${i}`, arg]));
|
|
1040
|
+
for (const [key, value] of Object.entries(server.env ?? {})) out.push([`env.${key}`, value]);
|
|
1041
|
+
if (server.cwd !== void 0) out.push(["cwd", server.cwd]);
|
|
1042
|
+
if (server.url !== void 0) out.push(["url", server.url]);
|
|
1043
|
+
for (const [key, value] of Object.entries(server.headers ?? {}))
|
|
1044
|
+
out.push([`headers.${key}`, value]);
|
|
1045
|
+
return out;
|
|
1046
|
+
}
|
|
1047
|
+
function mcpVariableIssues(config, env) {
|
|
1048
|
+
const issues = [];
|
|
1049
|
+
for (const [name, server] of Object.entries(config.mcp?.servers ?? {})) {
|
|
1050
|
+
for (const [field, value] of serverValues(server)) {
|
|
1051
|
+
try {
|
|
1052
|
+
expandVars(value, env);
|
|
1053
|
+
} catch (err) {
|
|
1054
|
+
issues.push(`mcp.servers.${name}.${field}: ${err.message}`);
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
return issues;
|
|
1059
|
+
}
|
|
1060
|
+
function resolveMcpServer(server, env = process.env, baseDir = process.cwd()) {
|
|
1061
|
+
const fill = (value) => expandVars(value, env);
|
|
1062
|
+
const fillAll = (entries = {}) => Object.fromEntries(Object.entries(entries).map(([key, value]) => [key, fill(value)]));
|
|
1063
|
+
if (server.url !== void 0)
|
|
1064
|
+
return { kind: "http", url: fill(server.url), headers: fillAll(server.headers) };
|
|
1065
|
+
return {
|
|
1066
|
+
kind: "stdio",
|
|
1067
|
+
command: fill(server.command),
|
|
1068
|
+
args: (server.args ?? []).map(fill),
|
|
1069
|
+
env: fillAll(server.env),
|
|
1070
|
+
...server.cwd !== void 0 ? { cwd: path3.resolve(baseDir, fill(server.cwd)) } : {}
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
var SECRET_KEY = /authorization|token|key|secret|password/i;
|
|
1074
|
+
function mcpSecretWarnings(config) {
|
|
1075
|
+
const warnings = [];
|
|
1076
|
+
for (const [name, server] of Object.entries(config.mcp?.servers ?? {})) {
|
|
1077
|
+
for (const [field, entries] of [
|
|
1078
|
+
["env", server.env],
|
|
1079
|
+
["headers", server.headers]
|
|
1080
|
+
]) {
|
|
1081
|
+
for (const [key, value] of Object.entries(entries ?? {})) {
|
|
1082
|
+
if (SECRET_KEY.test(key) && !value.includes("${")) {
|
|
1083
|
+
warnings.push(
|
|
1084
|
+
`mcp.servers.${name}.${field}.${key} looks like a secret written into plune.yaml; use \${VAR} so it comes from the environment.`
|
|
1085
|
+
);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
return warnings;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
85
1093
|
// src/config/schema.ts
|
|
1094
|
+
init_esm_shims();
|
|
86
1095
|
import { z } from "zod";
|
|
87
1096
|
var providerConfigSchema = z.object({
|
|
88
1097
|
type: z.enum(["anthropic", "openai", "openrouter"]),
|
|
@@ -136,7 +1145,8 @@ var llmJudgeAssertionSchema = z.object({
|
|
|
136
1145
|
type: z.literal("llm-judge"),
|
|
137
1146
|
criteria: z.string().min(1),
|
|
138
1147
|
provider: providerConfigSchema.partial().optional(),
|
|
139
|
-
|
|
1148
|
+
// The judge's score floor, not the eval's share of passing runs (that one is `evalRepeatsShape`).
|
|
1149
|
+
pass_threshold: 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()
|
|
140
1150
|
});
|
|
141
1151
|
var semanticSimilarityAssertionSchema = z.object({
|
|
142
1152
|
type: z.literal("semantic-similarity"),
|
|
@@ -159,6 +1169,54 @@ var contextPrecisionAssertionSchema = z.object({
|
|
|
159
1169
|
question: z.string().min(1),
|
|
160
1170
|
threshold: z.number().min(0).max(1).optional()
|
|
161
1171
|
});
|
|
1172
|
+
var toolName = z.string().min(1);
|
|
1173
|
+
var count = z.number().int().min(1);
|
|
1174
|
+
var toolCallAssertionSchemas = [
|
|
1175
|
+
z.object({ type: z.literal("tool-called"), tool: toolName, min_count: count.optional() }),
|
|
1176
|
+
z.object({ type: z.literal("tool-not-called"), tool: toolName }),
|
|
1177
|
+
z.object({
|
|
1178
|
+
type: z.literal("tool-args"),
|
|
1179
|
+
tool: toolName,
|
|
1180
|
+
args: z.record(z.string(), z.unknown()),
|
|
1181
|
+
match: z.enum(["partial", "exact", "ignore"]).optional(),
|
|
1182
|
+
min_count: count.optional()
|
|
1183
|
+
}),
|
|
1184
|
+
z.object({
|
|
1185
|
+
type: z.literal("tool-order"),
|
|
1186
|
+
tools: z.array(toolName).min(1),
|
|
1187
|
+
strict: z.boolean().optional()
|
|
1188
|
+
}),
|
|
1189
|
+
z.object({ type: z.literal("only-tools"), tools: z.array(toolName) }),
|
|
1190
|
+
z.object({ type: z.literal("first-tool"), tool: toolName }),
|
|
1191
|
+
z.object({ type: z.literal("no-tool-errors"), tool: toolName.optional() }),
|
|
1192
|
+
z.object({
|
|
1193
|
+
type: z.literal("tool-call-count"),
|
|
1194
|
+
tool: toolName.optional(),
|
|
1195
|
+
min: z.number().int().min(0).optional(),
|
|
1196
|
+
max: z.number().int().min(0).optional()
|
|
1197
|
+
}).refine((a) => a.min !== void 0 || a.max !== void 0, {
|
|
1198
|
+
message: "tool-call-count needs min, max or both"
|
|
1199
|
+
}).refine((a) => a.min === void 0 || a.max === void 0 || a.min <= a.max, {
|
|
1200
|
+
message: "tool-call-count: min is above max"
|
|
1201
|
+
}),
|
|
1202
|
+
z.object({ type: z.literal("no-repeated-call"), tool: toolName.optional() }),
|
|
1203
|
+
z.object({ type: z.literal("token-budget"), max: count }),
|
|
1204
|
+
z.object({ type: z.literal("tool-latency"), max_ms: z.number().positive(), tool: toolName.optional() }),
|
|
1205
|
+
z.object({
|
|
1206
|
+
type: z.literal("tool-result-size"),
|
|
1207
|
+
max_bytes: z.number().int().min(0),
|
|
1208
|
+
tool: toolName.optional()
|
|
1209
|
+
}),
|
|
1210
|
+
z.object({
|
|
1211
|
+
type: z.literal("tool-result-schema"),
|
|
1212
|
+
schema: z.record(z.string(), z.unknown()),
|
|
1213
|
+
tool: toolName.optional()
|
|
1214
|
+
}),
|
|
1215
|
+
z.object({ type: z.literal("no-destructive-tool") })
|
|
1216
|
+
];
|
|
1217
|
+
var TOOL_CALL_TYPES = new Set(
|
|
1218
|
+
toolCallAssertionSchemas.map((s) => s.shape.type.value)
|
|
1219
|
+
);
|
|
162
1220
|
var assertionConfigSchema = z.discriminatedUnion("type", [
|
|
163
1221
|
exactMatchAssertionSchema,
|
|
164
1222
|
containsAssertionSchema,
|
|
@@ -169,8 +1227,53 @@ var assertionConfigSchema = z.discriminatedUnion("type", [
|
|
|
169
1227
|
semanticSimilarityAssertionSchema,
|
|
170
1228
|
faithfulnessAssertionSchema,
|
|
171
1229
|
answerRelevanceAssertionSchema,
|
|
172
|
-
contextPrecisionAssertionSchema
|
|
1230
|
+
contextPrecisionAssertionSchema,
|
|
1231
|
+
...toolCallAssertionSchemas
|
|
173
1232
|
]);
|
|
1233
|
+
var MAX_RUNS = 100;
|
|
1234
|
+
var SHARE_MESSAGE = "pass_threshold (eval: share of runs that must pass) must be greater than 0 and at most 1";
|
|
1235
|
+
var evalRepeatsShape = {
|
|
1236
|
+
runs: z.number().int().min(1).max(MAX_RUNS).optional(),
|
|
1237
|
+
pass_threshold: z.number().gt(0, SHARE_MESSAGE).max(1, SHARE_MESSAGE).optional()
|
|
1238
|
+
};
|
|
1239
|
+
var MAX_TIMER_MS = 2147483647;
|
|
1240
|
+
var limit = z.number().int().positive();
|
|
1241
|
+
var mcpLimitsSchema = z.object({
|
|
1242
|
+
max_steps: limit.optional(),
|
|
1243
|
+
max_tool_calls: limit.optional(),
|
|
1244
|
+
max_total_tokens: limit.optional(),
|
|
1245
|
+
timeout_ms: limit.max(MAX_TIMER_MS).optional(),
|
|
1246
|
+
tool_timeout_ms: limit.max(MAX_TIMER_MS).optional()
|
|
1247
|
+
}).strict();
|
|
1248
|
+
var mcpServerSchema = z.object({
|
|
1249
|
+
command: z.string().min(1).optional(),
|
|
1250
|
+
args: z.array(z.string()).optional(),
|
|
1251
|
+
env: z.record(z.string(), z.string()).optional(),
|
|
1252
|
+
cwd: z.string().min(1).optional(),
|
|
1253
|
+
url: z.string().min(1).optional(),
|
|
1254
|
+
headers: z.record(z.string(), z.string()).optional()
|
|
1255
|
+
}).strict();
|
|
1256
|
+
var mcpServersSchema = z.record(z.string().min(1), mcpServerSchema).superRefine((servers, ctx) => {
|
|
1257
|
+
for (const [name, server] of Object.entries(servers)) {
|
|
1258
|
+
const issue = (message) => ctx.addIssue({ code: "custom", path: [name], message });
|
|
1259
|
+
const stdio = server.command !== void 0;
|
|
1260
|
+
const http = server.url !== void 0;
|
|
1261
|
+
if (stdio && http)
|
|
1262
|
+
issue(`server "${name}" has both command and url; give command (stdio) or url (HTTP), not both`);
|
|
1263
|
+
else if (!stdio && !http)
|
|
1264
|
+
issue(`server "${name}" needs command (a stdio server) or url (an HTTP server)`);
|
|
1265
|
+
else if (stdio && server.headers !== void 0)
|
|
1266
|
+
issue(`server "${name}": headers are for a server at url, not one started with command`);
|
|
1267
|
+
else if (http && (server.args ?? server.env ?? server.cwd) !== void 0)
|
|
1268
|
+
issue(`server "${name}": args, env and cwd are for a server started with command, not one at url`);
|
|
1269
|
+
}
|
|
1270
|
+
});
|
|
1271
|
+
var mcpRootSchema = z.object({ servers: mcpServersSchema, limits: mcpLimitsSchema.optional() }).strict();
|
|
1272
|
+
var evalMcpSchema = z.object({
|
|
1273
|
+
server: z.string().min(1),
|
|
1274
|
+
allowed_tools: z.array(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(),
|
|
1275
|
+
limits: mcpLimitsSchema.optional()
|
|
1276
|
+
}).strict();
|
|
174
1277
|
var evalConfigSchema = z.object({
|
|
175
1278
|
id: z.string().min(1).regex(/^[a-z0-9_-]+$/, "id must be lowercase slug"),
|
|
176
1279
|
description: z.string().optional(),
|
|
@@ -179,7 +1282,9 @@ var evalConfigSchema = z.object({
|
|
|
179
1282
|
prompt: z.string().optional(),
|
|
180
1283
|
prompt_file: z.string().optional(),
|
|
181
1284
|
dataset: datasetRefSchema,
|
|
182
|
-
assertions: z.array(assertionConfigSchema)
|
|
1285
|
+
assertions: z.array(assertionConfigSchema),
|
|
1286
|
+
...evalRepeatsShape,
|
|
1287
|
+
mcp: evalMcpSchema.optional()
|
|
183
1288
|
}).refine(
|
|
184
1289
|
(data) => !(data.prompt !== void 0 && data.prompt_file !== void 0),
|
|
185
1290
|
{ message: "prompt and prompt_file are mutually exclusive" }
|
|
@@ -189,8 +1294,34 @@ var pluneConfigSchema = z.object({
|
|
|
189
1294
|
provider: providerConfigSchema,
|
|
190
1295
|
defaults: z.object({ assertions: z.array(assertionConfigSchema).optional() }).optional(),
|
|
191
1296
|
pricing: pricingSchema.optional(),
|
|
1297
|
+
...evalRepeatsShape,
|
|
1298
|
+
// A CLI older than this block stops on it: the root is strict.
|
|
1299
|
+
mcp: mcpRootSchema.optional(),
|
|
192
1300
|
evals: z.array(evalConfigSchema).min(1)
|
|
193
|
-
}).strict()
|
|
1301
|
+
}).strict().superRefine((config, ctx) => {
|
|
1302
|
+
config.evals.forEach((evalConfig, i) => {
|
|
1303
|
+
const server = evalConfig.mcp?.server;
|
|
1304
|
+
if (server === void 0) {
|
|
1305
|
+
const misplaced = (assertions, path10) => assertions.forEach((a, j) => {
|
|
1306
|
+
if (TOOL_CALL_TYPES.has(a.type))
|
|
1307
|
+
ctx.addIssue({
|
|
1308
|
+
code: "custom",
|
|
1309
|
+
path: [...path10, j, "type"],
|
|
1310
|
+
message: `"${a.type}" reads the tool calls of an eval with mcp, and eval "${evalConfig.id}" has no mcp block`
|
|
1311
|
+
});
|
|
1312
|
+
});
|
|
1313
|
+
misplaced(config.defaults?.assertions ?? [], ["defaults", "assertions"]);
|
|
1314
|
+
misplaced(evalConfig.assertions, ["evals", i, "assertions"]);
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
if (config.mcp?.servers[server] !== void 0) return;
|
|
1318
|
+
ctx.addIssue({
|
|
1319
|
+
code: "custom",
|
|
1320
|
+
path: ["evals", i, "mcp", "server"],
|
|
1321
|
+
message: `eval "${evalConfig.id}" uses MCP server "${server}", which mcp.servers does not define`
|
|
1322
|
+
});
|
|
1323
|
+
});
|
|
1324
|
+
});
|
|
194
1325
|
|
|
195
1326
|
// src/config/loader.ts
|
|
196
1327
|
async function loadConfig(opts = {}) {
|
|
@@ -202,15 +1333,15 @@ async function loadConfig(opts = {}) {
|
|
|
202
1333
|
} catch {
|
|
203
1334
|
throw new ConfigNotFoundError(`Cannot read config file: ${resolvedPath}`);
|
|
204
1335
|
}
|
|
205
|
-
let
|
|
1336
|
+
let parsed2;
|
|
206
1337
|
try {
|
|
207
|
-
|
|
1338
|
+
parsed2 = parse(raw);
|
|
208
1339
|
} catch (err) {
|
|
209
1340
|
throw new YamlParseError(
|
|
210
1341
|
`YAML parse error in ${resolvedPath}: ${err.message}`
|
|
211
1342
|
);
|
|
212
1343
|
}
|
|
213
|
-
const result = pluneConfigSchema.safeParse(
|
|
1344
|
+
const result = pluneConfigSchema.safeParse(parsed2);
|
|
214
1345
|
if (!result.success) {
|
|
215
1346
|
const issues = result.error.issues.map(
|
|
216
1347
|
(issue) => `${issue.path.join(".")}: ${issue.message}`
|
|
@@ -220,13 +1351,28 @@ async function loadConfig(opts = {}) {
|
|
|
220
1351
|
issues
|
|
221
1352
|
);
|
|
222
1353
|
}
|
|
223
|
-
|
|
1354
|
+
const config = result.data;
|
|
1355
|
+
const unset = mcpVariableIssues(config, env);
|
|
1356
|
+
if (unset.length > 0)
|
|
1357
|
+
throw new ConfigValidationError(`Config validation failed in ${resolvedPath}`, unset);
|
|
1358
|
+
return applyEnvOverrides(config, env);
|
|
224
1359
|
}
|
|
225
1360
|
|
|
1361
|
+
// src/providers/index.ts
|
|
1362
|
+
init_esm_shims();
|
|
1363
|
+
|
|
1364
|
+
// src/providers/registry.ts
|
|
1365
|
+
init_esm_shims();
|
|
1366
|
+
|
|
226
1367
|
// src/providers/anthropic.ts
|
|
1368
|
+
init_esm_shims();
|
|
227
1369
|
import Anthropic from "@anthropic-ai/sdk";
|
|
228
1370
|
|
|
1371
|
+
// src/providers/retry.ts
|
|
1372
|
+
init_esm_shims();
|
|
1373
|
+
|
|
229
1374
|
// src/providers/errors.ts
|
|
1375
|
+
init_esm_shims();
|
|
230
1376
|
var NETWORK_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
231
1377
|
"ECONNRESET",
|
|
232
1378
|
"ETIMEDOUT",
|
|
@@ -315,7 +1461,7 @@ function normalizeProviderError(err, secret, envVar) {
|
|
|
315
1461
|
}
|
|
316
1462
|
|
|
317
1463
|
// src/providers/retry.ts
|
|
318
|
-
var defaultSleep = (ms) => new Promise((
|
|
1464
|
+
var defaultSleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
|
|
319
1465
|
function retryAfterMs(err) {
|
|
320
1466
|
if (typeof err !== "object" || err === null || !("headers" in err)) return void 0;
|
|
321
1467
|
const raw = readHeader(err.headers, "retry-after");
|
|
@@ -359,7 +1505,11 @@ async function withRetry(fn, options) {
|
|
|
359
1505
|
}
|
|
360
1506
|
}
|
|
361
1507
|
|
|
1508
|
+
// src/providers/cost.ts
|
|
1509
|
+
init_esm_shims();
|
|
1510
|
+
|
|
362
1511
|
// src/providers/prices.ts
|
|
1512
|
+
init_esm_shims();
|
|
363
1513
|
var PRICE_TABLE = {
|
|
364
1514
|
// Anthropic, current models. Source: platform.claude.com/docs/en/about-claude/pricing — base
|
|
365
1515
|
// input and output tokens per million, read on 2026-09-29, kept here per thousand.
|
|
@@ -420,6 +1570,39 @@ function resolveCostEntry(usage, model, reportedCostUsd, overrides, deps = {}) {
|
|
|
420
1570
|
// src/providers/anthropic.ts
|
|
421
1571
|
var ENV_VAR = "ANTHROPIC_API_KEY";
|
|
422
1572
|
var DEFAULT_MAX_RETRIES = 2;
|
|
1573
|
+
var STOP = {
|
|
1574
|
+
tool_use: "tool_calls",
|
|
1575
|
+
end_turn: "stop",
|
|
1576
|
+
max_tokens: "length"
|
|
1577
|
+
};
|
|
1578
|
+
var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
1579
|
+
function toAnthropicMessages(messages) {
|
|
1580
|
+
return messages.map((m) => {
|
|
1581
|
+
if (m.role === "user") return { role: "user", content: m.content };
|
|
1582
|
+
if (m.role === "tool")
|
|
1583
|
+
return {
|
|
1584
|
+
role: "user",
|
|
1585
|
+
content: m.results.map((r) => ({
|
|
1586
|
+
type: "tool_result",
|
|
1587
|
+
tool_use_id: r.id,
|
|
1588
|
+
content: r.content,
|
|
1589
|
+
is_error: r.is_error
|
|
1590
|
+
}))
|
|
1591
|
+
};
|
|
1592
|
+
return {
|
|
1593
|
+
role: "assistant",
|
|
1594
|
+
content: [
|
|
1595
|
+
...m.text !== "" ? [{ type: "text", text: m.text }] : [],
|
|
1596
|
+
...m.tool_calls.map((c) => ({
|
|
1597
|
+
type: "tool_use",
|
|
1598
|
+
id: c.id,
|
|
1599
|
+
name: c.name,
|
|
1600
|
+
input: isObject(c.args) ? c.args : {}
|
|
1601
|
+
}))
|
|
1602
|
+
]
|
|
1603
|
+
};
|
|
1604
|
+
});
|
|
1605
|
+
}
|
|
423
1606
|
function makeAnthropicProvider(config, env, pricing) {
|
|
424
1607
|
const apiKey = env[ENV_VAR];
|
|
425
1608
|
if (apiKey === void 0 || apiKey.trim() === "") {
|
|
@@ -459,6 +1642,35 @@ function makeAnthropicProvider(config, env, pricing) {
|
|
|
459
1642
|
throw normalizeProviderError(err, apiKey, ENV_VAR);
|
|
460
1643
|
}
|
|
461
1644
|
},
|
|
1645
|
+
async respond(req) {
|
|
1646
|
+
try {
|
|
1647
|
+
const res = await withRetry(
|
|
1648
|
+
() => client.messages.create({
|
|
1649
|
+
model: req.model,
|
|
1650
|
+
max_tokens: req.max_tokens,
|
|
1651
|
+
...req.temperature !== void 0 ? { temperature: req.temperature } : {},
|
|
1652
|
+
messages: toAnthropicMessages(req.messages),
|
|
1653
|
+
tools: req.tools.map((t) => ({
|
|
1654
|
+
name: t.name,
|
|
1655
|
+
...t.description !== void 0 ? { description: t.description } : {},
|
|
1656
|
+
input_schema: { ...t.input_schema, type: "object" }
|
|
1657
|
+
}))
|
|
1658
|
+
}),
|
|
1659
|
+
{ max_retries: maxRetries }
|
|
1660
|
+
);
|
|
1661
|
+
const stop = res.stop_reason ?? void 0;
|
|
1662
|
+
return {
|
|
1663
|
+
text: res.content.map((block) => block.type === "text" ? block.text : "").join(""),
|
|
1664
|
+
tool_calls: res.content.flatMap(
|
|
1665
|
+
(block) => block.type === "tool_use" ? [{ id: block.id, name: block.name, args: block.input }] : []
|
|
1666
|
+
),
|
|
1667
|
+
usage: { input_tokens: res.usage.input_tokens, output_tokens: res.usage.output_tokens },
|
|
1668
|
+
...stop !== void 0 ? { finish_reason: STOP[stop] ?? stop } : {}
|
|
1669
|
+
};
|
|
1670
|
+
} catch (err) {
|
|
1671
|
+
throw normalizeProviderError(err, apiKey, ENV_VAR);
|
|
1672
|
+
}
|
|
1673
|
+
},
|
|
462
1674
|
estimateCost(usage, reportedCostUsd) {
|
|
463
1675
|
return resolveCostEntry(usage, config.model, reportedCostUsd, pricing);
|
|
464
1676
|
}
|
|
@@ -466,7 +1678,39 @@ function makeAnthropicProvider(config, env, pricing) {
|
|
|
466
1678
|
}
|
|
467
1679
|
|
|
468
1680
|
// src/providers/openai.ts
|
|
1681
|
+
init_esm_shims();
|
|
469
1682
|
import OpenAI from "openai";
|
|
1683
|
+
function toOpenAiMessages(messages) {
|
|
1684
|
+
return messages.flatMap((m) => {
|
|
1685
|
+
if (m.role === "user") return [{ role: "user", content: m.content }];
|
|
1686
|
+
if (m.role === "tool")
|
|
1687
|
+
return m.results.map((r) => ({ role: "tool", tool_call_id: r.id, content: r.content }));
|
|
1688
|
+
return [
|
|
1689
|
+
{
|
|
1690
|
+
role: "assistant",
|
|
1691
|
+
content: m.text === "" ? null : m.text,
|
|
1692
|
+
...m.tool_calls.length > 0 ? {
|
|
1693
|
+
tool_calls: m.tool_calls.map((c) => ({
|
|
1694
|
+
id: c.id,
|
|
1695
|
+
type: "function",
|
|
1696
|
+
function: {
|
|
1697
|
+
name: c.name,
|
|
1698
|
+
arguments: typeof c.args === "string" ? c.args : JSON.stringify(c.args ?? {})
|
|
1699
|
+
}
|
|
1700
|
+
}))
|
|
1701
|
+
} : {}
|
|
1702
|
+
}
|
|
1703
|
+
];
|
|
1704
|
+
});
|
|
1705
|
+
}
|
|
1706
|
+
function parseToolArguments(id, name, raw) {
|
|
1707
|
+
try {
|
|
1708
|
+
const args = JSON.parse(raw === "" ? "{}" : raw);
|
|
1709
|
+
if (typeof args === "object" && args !== null && !Array.isArray(args)) return { id, name, args };
|
|
1710
|
+
} catch {
|
|
1711
|
+
}
|
|
1712
|
+
return { id, name, args: raw, args_invalid: true };
|
|
1713
|
+
}
|
|
470
1714
|
var DEFAULT_MAX_RETRIES2 = 2;
|
|
471
1715
|
function makeOpenAiCompatibleProvider(opts) {
|
|
472
1716
|
const { config, env, pricing, apiKeyEnv, baseURL, reportsCost } = opts;
|
|
@@ -515,6 +1759,45 @@ function makeOpenAiCompatibleProvider(opts) {
|
|
|
515
1759
|
throw normalizeProviderError(err, apiKey, apiKeyEnv);
|
|
516
1760
|
}
|
|
517
1761
|
},
|
|
1762
|
+
async respond(req) {
|
|
1763
|
+
try {
|
|
1764
|
+
const res = await withRetry(
|
|
1765
|
+
() => client.chat.completions.create({
|
|
1766
|
+
model: req.model,
|
|
1767
|
+
...req.temperature !== void 0 ? { temperature: req.temperature } : {},
|
|
1768
|
+
max_tokens: req.max_tokens,
|
|
1769
|
+
messages: toOpenAiMessages(req.messages),
|
|
1770
|
+
tools: req.tools.map((t) => ({
|
|
1771
|
+
type: "function",
|
|
1772
|
+
function: {
|
|
1773
|
+
name: t.name,
|
|
1774
|
+
...t.description !== void 0 ? { description: t.description } : {},
|
|
1775
|
+
parameters: t.input_schema
|
|
1776
|
+
}
|
|
1777
|
+
})),
|
|
1778
|
+
...reportsCost ? { usage: { include: true } } : {}
|
|
1779
|
+
}),
|
|
1780
|
+
{ max_retries: maxRetries }
|
|
1781
|
+
);
|
|
1782
|
+
const reportedCost = reportsCost ? res.usage?.cost : void 0;
|
|
1783
|
+
const choice = res.choices[0];
|
|
1784
|
+
const finish = choice?.error !== void 0 ? "error" : choice?.finish_reason;
|
|
1785
|
+
return {
|
|
1786
|
+
text: choice?.message?.content ?? "",
|
|
1787
|
+
tool_calls: (choice?.message?.tool_calls ?? []).flatMap(
|
|
1788
|
+
(c) => c.type === "function" ? [parseToolArguments(c.id, c.function.name, c.function.arguments)] : []
|
|
1789
|
+
),
|
|
1790
|
+
usage: {
|
|
1791
|
+
input_tokens: res.usage?.prompt_tokens ?? 0,
|
|
1792
|
+
output_tokens: res.usage?.completion_tokens ?? 0
|
|
1793
|
+
},
|
|
1794
|
+
...typeof finish === "string" ? { finish_reason: finish } : {},
|
|
1795
|
+
...typeof reportedCost === "number" ? { cost_usd: reportedCost } : {}
|
|
1796
|
+
};
|
|
1797
|
+
} catch (err) {
|
|
1798
|
+
throw normalizeProviderError(err, apiKey, apiKeyEnv);
|
|
1799
|
+
}
|
|
1800
|
+
},
|
|
518
1801
|
estimateCost(usage, reportedCostUsd) {
|
|
519
1802
|
return resolveCostEntry(usage, config.model, reportedCostUsd, pricing);
|
|
520
1803
|
}
|
|
@@ -525,6 +1808,7 @@ function makeOpenAiProvider(config, env, pricing) {
|
|
|
525
1808
|
}
|
|
526
1809
|
|
|
527
1810
|
// src/providers/openrouter.ts
|
|
1811
|
+
init_esm_shims();
|
|
528
1812
|
var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
|
|
529
1813
|
function makeOpenRouterProvider(config, env, pricing) {
|
|
530
1814
|
return makeOpenAiCompatibleProvider({
|
|
@@ -573,6 +1857,7 @@ function getProvider(config, env, pricing) {
|
|
|
573
1857
|
}
|
|
574
1858
|
|
|
575
1859
|
// src/providers/estimate.ts
|
|
1860
|
+
init_esm_shims();
|
|
576
1861
|
function makeEstimateProvider(config, pricing) {
|
|
577
1862
|
return {
|
|
578
1863
|
complete: () => Promise.reject(
|
|
@@ -583,17 +1868,62 @@ function makeEstimateProvider(config, pricing) {
|
|
|
583
1868
|
}
|
|
584
1869
|
|
|
585
1870
|
// src/providers/mock.ts
|
|
586
|
-
|
|
1871
|
+
init_esm_shims();
|
|
1872
|
+
var USAGE = { input_tokens: 10, output_tokens: 5 };
|
|
1873
|
+
function parseMockScript(text) {
|
|
1874
|
+
let parsed2;
|
|
1875
|
+
try {
|
|
1876
|
+
parsed2 = JSON.parse(text);
|
|
1877
|
+
} catch {
|
|
1878
|
+
throw new Error("is not JSON");
|
|
1879
|
+
}
|
|
1880
|
+
const isStep = (s) => {
|
|
1881
|
+
if (typeof s !== "object" || s === null || Array.isArray(s)) return false;
|
|
1882
|
+
const { text: t, tool_calls: calls } = s;
|
|
1883
|
+
if (t !== void 0 && typeof t !== "string") return false;
|
|
1884
|
+
if (calls === void 0) return true;
|
|
1885
|
+
return Array.isArray(calls) && calls.every(
|
|
1886
|
+
(c) => typeof c === "object" && c !== null && typeof c.name === "string"
|
|
1887
|
+
);
|
|
1888
|
+
};
|
|
1889
|
+
if (!Array.isArray(parsed2) || parsed2.length === 0 || !parsed2.every(isStep))
|
|
1890
|
+
throw new Error(
|
|
1891
|
+
'must be a non-empty list of steps, each { "text": "\u2026" } or { "tool_calls": [{ "name": "\u2026", "args": {} }] }'
|
|
1892
|
+
);
|
|
1893
|
+
return parsed2;
|
|
1894
|
+
}
|
|
1895
|
+
function makeMockProvider(script) {
|
|
587
1896
|
return {
|
|
588
1897
|
complete: () => Promise.resolve({
|
|
589
1898
|
output: "mock response",
|
|
590
|
-
usage:
|
|
1899
|
+
usage: USAGE
|
|
591
1900
|
}),
|
|
1901
|
+
...script !== void 0 ? {
|
|
1902
|
+
respond: (req) => {
|
|
1903
|
+
const step = req.messages.filter((m) => m.role === "assistant").length;
|
|
1904
|
+
const entry = script[Math.min(step, script.length - 1)];
|
|
1905
|
+
const calls = entry.tool_calls ?? [];
|
|
1906
|
+
return Promise.resolve({
|
|
1907
|
+
text: entry.text ?? "",
|
|
1908
|
+
tool_calls: calls.map((c, i) => ({
|
|
1909
|
+
id: `call_${step}_${i}`,
|
|
1910
|
+
name: c.name,
|
|
1911
|
+
args: c.args ?? {}
|
|
1912
|
+
})),
|
|
1913
|
+
usage: USAGE,
|
|
1914
|
+
finish_reason: calls.length > 0 ? "tool_calls" : "stop"
|
|
1915
|
+
});
|
|
1916
|
+
}
|
|
1917
|
+
} : {},
|
|
592
1918
|
estimateCost: () => ({ cost_usd: 0 })
|
|
593
1919
|
};
|
|
594
1920
|
}
|
|
595
1921
|
|
|
1922
|
+
// src/embeddings/index.ts
|
|
1923
|
+
init_esm_shims();
|
|
1924
|
+
|
|
596
1925
|
// src/embeddings/cosine.ts
|
|
1926
|
+
init_esm_shims();
|
|
597
1927
|
function cosine(a, b) {
|
|
598
1928
|
if (a.length !== b.length) {
|
|
599
1929
|
throw new Error(`cosine: vector length mismatch (${a.length} vs ${b.length})`);
|
|
@@ -613,6 +1943,7 @@ function cosine(a, b) {
|
|
|
613
1943
|
}
|
|
614
1944
|
|
|
615
1945
|
// src/embeddings/embedder.ts
|
|
1946
|
+
init_esm_shims();
|
|
616
1947
|
var MODEL_ID = "Xenova/all-MiniLM-L6-v2";
|
|
617
1948
|
var XenovaEmbedder = class {
|
|
618
1949
|
extractor;
|
|
@@ -636,13 +1967,19 @@ function getDefaultEmbedder() {
|
|
|
636
1967
|
return defaultEmbedder ??= new XenovaEmbedder();
|
|
637
1968
|
}
|
|
638
1969
|
|
|
1970
|
+
// src/cache/index.ts
|
|
1971
|
+
init_esm_shims();
|
|
1972
|
+
|
|
639
1973
|
// src/cache/cache.ts
|
|
1974
|
+
init_esm_shims();
|
|
640
1975
|
import { createRequire } from "module";
|
|
641
1976
|
|
|
642
1977
|
// src/util/hash.ts
|
|
1978
|
+
init_esm_shims();
|
|
643
1979
|
import { createHash } from "crypto";
|
|
644
1980
|
|
|
645
1981
|
// src/util/canonical-json.ts
|
|
1982
|
+
init_esm_shims();
|
|
646
1983
|
function normalizeValue(value) {
|
|
647
1984
|
if (value === null) return null;
|
|
648
1985
|
if (typeof value === "boolean") return value;
|
|
@@ -689,9 +2026,17 @@ function sha256(input) {
|
|
|
689
2026
|
}
|
|
690
2027
|
var CACHE_POLICY_VERSION = 1;
|
|
691
2028
|
function cacheKey(inputs, policyVersion = CACHE_POLICY_VERSION) {
|
|
692
|
-
const { provider, model, temperature, max_tokens, prompt_resolved } = inputs;
|
|
2029
|
+
const { provider, model, temperature, max_tokens, prompt_resolved, attempt } = inputs;
|
|
693
2030
|
return sha256(
|
|
694
|
-
canonicalJson({
|
|
2031
|
+
canonicalJson({
|
|
2032
|
+
provider,
|
|
2033
|
+
model,
|
|
2034
|
+
temperature,
|
|
2035
|
+
max_tokens,
|
|
2036
|
+
prompt_resolved,
|
|
2037
|
+
policy: policyVersion,
|
|
2038
|
+
...attempt !== void 0 && attempt > 0 ? { attempt } : {}
|
|
2039
|
+
})
|
|
695
2040
|
);
|
|
696
2041
|
}
|
|
697
2042
|
function configHash(config) {
|
|
@@ -837,11 +2182,16 @@ var NoOpCache = class {
|
|
|
837
2182
|
}
|
|
838
2183
|
};
|
|
839
2184
|
|
|
2185
|
+
// src/orchestrator/index.ts
|
|
2186
|
+
init_esm_shims();
|
|
2187
|
+
|
|
840
2188
|
// src/orchestrator/run.ts
|
|
2189
|
+
init_esm_shims();
|
|
841
2190
|
import * as fs3 from "fs";
|
|
842
|
-
import * as
|
|
2191
|
+
import * as path4 from "path";
|
|
843
2192
|
|
|
844
2193
|
// src/assertions/json-extract.ts
|
|
2194
|
+
init_esm_shims();
|
|
845
2195
|
function extractJson(output, mode) {
|
|
846
2196
|
if (mode === "strict") {
|
|
847
2197
|
return tryParse(output.trim());
|
|
@@ -884,8 +2234,8 @@ function* balancedRuns(s) {
|
|
|
884
2234
|
}
|
|
885
2235
|
}
|
|
886
2236
|
function balancedFrom(s, start) {
|
|
887
|
-
const
|
|
888
|
-
const close =
|
|
2237
|
+
const open2 = s[start];
|
|
2238
|
+
const close = open2 === "{" ? "}" : "]";
|
|
889
2239
|
let depth = 0;
|
|
890
2240
|
let inString = false;
|
|
891
2241
|
let escaped = false;
|
|
@@ -899,7 +2249,7 @@ function balancedFrom(s, start) {
|
|
|
899
2249
|
}
|
|
900
2250
|
if (ch === '"') {
|
|
901
2251
|
inString = true;
|
|
902
|
-
} else if (ch ===
|
|
2252
|
+
} else if (ch === open2) {
|
|
903
2253
|
depth++;
|
|
904
2254
|
} else if (ch === close) {
|
|
905
2255
|
depth--;
|
|
@@ -909,7 +2259,17 @@ function balancedFrom(s, start) {
|
|
|
909
2259
|
return null;
|
|
910
2260
|
}
|
|
911
2261
|
|
|
2262
|
+
// src/assertions/index.ts
|
|
2263
|
+
init_esm_shims();
|
|
2264
|
+
|
|
2265
|
+
// src/assertions/registry.ts
|
|
2266
|
+
init_esm_shims();
|
|
2267
|
+
|
|
2268
|
+
// src/assertions/exact-match.ts
|
|
2269
|
+
init_esm_shims();
|
|
2270
|
+
|
|
912
2271
|
// src/assertions/interpolate.ts
|
|
2272
|
+
init_esm_shims();
|
|
913
2273
|
var PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/g;
|
|
914
2274
|
function interpolate(template, ctx) {
|
|
915
2275
|
return template.replace(PLACEHOLDER, (match, key) => {
|
|
@@ -945,6 +2305,7 @@ var exactMatch = {
|
|
|
945
2305
|
};
|
|
946
2306
|
|
|
947
2307
|
// src/assertions/contains.ts
|
|
2308
|
+
init_esm_shims();
|
|
948
2309
|
function norm(s, ignoreCase) {
|
|
949
2310
|
return ignoreCase ? s.toLowerCase() : s;
|
|
950
2311
|
}
|
|
@@ -981,6 +2342,7 @@ var containsAll = {
|
|
|
981
2342
|
};
|
|
982
2343
|
|
|
983
2344
|
// src/assertions/json-schema.ts
|
|
2345
|
+
init_esm_shims();
|
|
984
2346
|
import { Ajv } from "ajv";
|
|
985
2347
|
var jsonSchema = {
|
|
986
2348
|
run(ctx) {
|
|
@@ -1013,6 +2375,7 @@ var jsonSchema = {
|
|
|
1013
2375
|
};
|
|
1014
2376
|
|
|
1015
2377
|
// src/assertions/semantic-similarity.ts
|
|
2378
|
+
init_esm_shims();
|
|
1016
2379
|
var DEFAULT_THRESHOLD = 0.8;
|
|
1017
2380
|
var semanticSimilarity = {
|
|
1018
2381
|
async run(ctx) {
|
|
@@ -1035,7 +2398,11 @@ var semanticSimilarity = {
|
|
|
1035
2398
|
}
|
|
1036
2399
|
};
|
|
1037
2400
|
|
|
2401
|
+
// src/assertions/llm-judge.ts
|
|
2402
|
+
init_esm_shims();
|
|
2403
|
+
|
|
1038
2404
|
// src/assertions/judge-helpers.ts
|
|
2405
|
+
init_esm_shims();
|
|
1039
2406
|
async function askJson(judge, prompt5) {
|
|
1040
2407
|
const text = await judge.ask(prompt5);
|
|
1041
2408
|
const result = extractJson(text, "auto");
|
|
@@ -1105,6 +2472,7 @@ var llmJudge = {
|
|
|
1105
2472
|
};
|
|
1106
2473
|
|
|
1107
2474
|
// src/assertions/faithfulness.ts
|
|
2475
|
+
init_esm_shims();
|
|
1108
2476
|
var DEFAULT_THRESHOLD2 = 0.7;
|
|
1109
2477
|
function prompt2(context, output) {
|
|
1110
2478
|
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>}]}.
|
|
@@ -1130,6 +2498,7 @@ var faithfulness = {
|
|
|
1130
2498
|
};
|
|
1131
2499
|
|
|
1132
2500
|
// src/assertions/answer-relevance.ts
|
|
2501
|
+
init_esm_shims();
|
|
1133
2502
|
var DEFAULT_THRESHOLD3 = 0.7;
|
|
1134
2503
|
function prompt3(output) {
|
|
1135
2504
|
return `Generate the questions that the OUTPUT directly and fully answers. Respond ONLY with JSON: {"questions": ["<question>", ...]}.
|
|
@@ -1168,32 +2537,378 @@ var answerRelevance = {
|
|
|
1168
2537
|
};
|
|
1169
2538
|
|
|
1170
2539
|
// src/assertions/context-precision.ts
|
|
2540
|
+
init_esm_shims();
|
|
1171
2541
|
var DEFAULT_THRESHOLD4 = 0.7;
|
|
1172
2542
|
function prompt4(context, question) {
|
|
1173
2543
|
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>"}.
|
|
1174
2544
|
|
|
1175
|
-
QUESTION: ${question}
|
|
2545
|
+
QUESTION: ${question}
|
|
2546
|
+
|
|
2547
|
+
CONTEXT:
|
|
2548
|
+
${context}`;
|
|
2549
|
+
}
|
|
2550
|
+
var contextPrecision = {
|
|
2551
|
+
async run(ctx) {
|
|
2552
|
+
if (ctx.judge === void 0) {
|
|
2553
|
+
throw new Error("context-precision requires a judge in the AssertionContext");
|
|
2554
|
+
}
|
|
2555
|
+
const context = interpolate(ctx.params.context, ctx);
|
|
2556
|
+
const question = interpolate(ctx.params.question, ctx);
|
|
2557
|
+
const threshold = ctx.params.threshold ?? DEFAULT_THRESHOLD4;
|
|
2558
|
+
const { score, reason } = parseScored(await askJson(ctx.judge, prompt4(context, question)));
|
|
2559
|
+
const passed = score >= threshold;
|
|
2560
|
+
return {
|
|
2561
|
+
passed,
|
|
2562
|
+
score,
|
|
2563
|
+
reason: reason ?? `context-precision ${score.toFixed(3)} vs threshold ${threshold}`
|
|
2564
|
+
};
|
|
2565
|
+
}
|
|
2566
|
+
};
|
|
2567
|
+
|
|
2568
|
+
// src/assertions/tool-calls/calls.ts
|
|
2569
|
+
init_esm_shims();
|
|
2570
|
+
|
|
2571
|
+
// src/assertions/tool-calls/transcript.ts
|
|
2572
|
+
init_esm_shims();
|
|
2573
|
+
var AssertionRunError = class extends Error {
|
|
2574
|
+
constructor(code, message) {
|
|
2575
|
+
super(message);
|
|
2576
|
+
this.code = code;
|
|
2577
|
+
this.name = "AssertionRunError";
|
|
2578
|
+
}
|
|
2579
|
+
code;
|
|
2580
|
+
};
|
|
2581
|
+
var AFTER = " The assertions after it in this row were not run.";
|
|
2582
|
+
function check(body) {
|
|
2583
|
+
return {
|
|
2584
|
+
run(ctx) {
|
|
2585
|
+
try {
|
|
2586
|
+
return Promise.resolve(body(ctx));
|
|
2587
|
+
} catch (err) {
|
|
2588
|
+
return Promise.reject(err);
|
|
2589
|
+
}
|
|
2590
|
+
}
|
|
2591
|
+
};
|
|
2592
|
+
}
|
|
2593
|
+
var pass = { passed: true };
|
|
2594
|
+
var fail = (reason) => ({ passed: false, reason });
|
|
2595
|
+
function unmeasured(type, why) {
|
|
2596
|
+
return new AssertionRunError(
|
|
2597
|
+
"ASSERTION_UNMEASURED",
|
|
2598
|
+
`${type}: not measured because ${why}.${AFTER}`
|
|
2599
|
+
);
|
|
2600
|
+
}
|
|
2601
|
+
function transcriptOf(type, ctx) {
|
|
2602
|
+
if (ctx.transcript === void 0)
|
|
2603
|
+
throw unmeasured(type, "there is no tool loop to read (the eval has no mcp block)");
|
|
2604
|
+
return ctx.transcript;
|
|
2605
|
+
}
|
|
2606
|
+
function callsOf(t) {
|
|
2607
|
+
return t.steps.flatMap((s) => s.calls.map((call) => ({ step: s.index, call })));
|
|
2608
|
+
}
|
|
2609
|
+
function callsFor(t, tool) {
|
|
2610
|
+
const all = callsOf(t);
|
|
2611
|
+
return tool === void 0 ? all : all.filter((c) => c.call.name === tool);
|
|
2612
|
+
}
|
|
2613
|
+
function checkNames(type, t, names) {
|
|
2614
|
+
const offered = t.tools.filter((x) => x.offered).map((x) => x.name);
|
|
2615
|
+
const unknown = names.find((n) => n !== void 0 && !offered.includes(n));
|
|
2616
|
+
if (unknown === void 0) return;
|
|
2617
|
+
const list = offered.length > 0 ? offered.join(", ") : "(none)";
|
|
2618
|
+
throw new AssertionRunError(
|
|
2619
|
+
"ASSERTION_UNKNOWN_TOOL",
|
|
2620
|
+
`${type}: no tool "${unknown}" was offered to the model; offered: ${list}.${AFTER}`
|
|
2621
|
+
);
|
|
2622
|
+
}
|
|
2623
|
+
function absence(type, t, what) {
|
|
2624
|
+
if (t.collection === "complete") return pass;
|
|
2625
|
+
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)";
|
|
2626
|
+
throw unmeasured(
|
|
2627
|
+
type,
|
|
2628
|
+
`${why}, so ${what} may be in what was not seen; nothing was found in what was`
|
|
2629
|
+
);
|
|
2630
|
+
}
|
|
2631
|
+
var ARGS_CHARS = 80;
|
|
2632
|
+
var LISTED = 5;
|
|
2633
|
+
function describeArgs(args) {
|
|
2634
|
+
const text = redactSecrets(JSON.stringify(args) ?? "undefined");
|
|
2635
|
+
return text.length > ARGS_CHARS ? `${text.slice(0, ARGS_CHARS)} (cut)` : text;
|
|
2636
|
+
}
|
|
2637
|
+
function describeCall({ step, call }) {
|
|
2638
|
+
return `step ${step} ${call.name} ${describeArgs(call.args)}`;
|
|
2639
|
+
}
|
|
2640
|
+
function describeCalls(calls, detail = describeCall) {
|
|
2641
|
+
if (calls.length === 0) return "no tool call";
|
|
2642
|
+
const shown = calls.slice(0, LISTED).map(detail).join("; ");
|
|
2643
|
+
return calls.length > LISTED ? `${shown} (and ${calls.length - LISTED} more)` : shown;
|
|
2644
|
+
}
|
|
2645
|
+
var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
2646
|
+
function sameJson(a, b) {
|
|
2647
|
+
return a !== void 0 && b !== void 0 && canonicalJson(a) === canonicalJson(b);
|
|
2648
|
+
}
|
|
2649
|
+
|
|
2650
|
+
// src/assertions/tool-calls/calls.ts
|
|
2651
|
+
var toolCalled = check((ctx) => {
|
|
2652
|
+
const { tool, min_count: min = 1 } = ctx.params;
|
|
2653
|
+
const t = transcriptOf("tool-called", ctx);
|
|
2654
|
+
checkNames("tool-called", t, [tool]);
|
|
2655
|
+
const calls = callsFor(t, tool);
|
|
2656
|
+
if (calls.length >= min) return pass;
|
|
2657
|
+
return fail(
|
|
2658
|
+
`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`
|
|
2659
|
+
);
|
|
2660
|
+
});
|
|
2661
|
+
var toolNotCalled = check((ctx) => {
|
|
2662
|
+
const { tool } = ctx.params;
|
|
2663
|
+
const t = transcriptOf("tool-not-called", ctx);
|
|
2664
|
+
checkNames("tool-not-called", t, [tool]);
|
|
2665
|
+
const calls = callsFor(t, tool);
|
|
2666
|
+
if (calls.length === 0) return absence("tool-not-called", t, `a call to "${tool}"`);
|
|
2667
|
+
return fail(
|
|
2668
|
+
`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`
|
|
2669
|
+
);
|
|
2670
|
+
});
|
|
2671
|
+
var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
2672
|
+
function partialMatch(expected, actual) {
|
|
2673
|
+
if (!isRecord(expected)) return sameJson(expected, actual);
|
|
2674
|
+
return isRecord(actual) && Object.entries(expected).every(
|
|
2675
|
+
([k, v]) => Object.hasOwn(actual, k) && partialMatch(v, actual[k])
|
|
2676
|
+
);
|
|
2677
|
+
}
|
|
2678
|
+
function interpolateDeep(value, ctx) {
|
|
2679
|
+
if (typeof value === "string") return interpolate(value, ctx);
|
|
2680
|
+
if (Array.isArray(value)) return value.map((v) => interpolateDeep(v, ctx));
|
|
2681
|
+
if (isRecord(value))
|
|
2682
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, interpolateDeep(v, ctx)]));
|
|
2683
|
+
return value;
|
|
2684
|
+
}
|
|
2685
|
+
var toolArgs = check((ctx) => {
|
|
2686
|
+
const { tool, match = "partial", min_count: min = 1 } = ctx.params;
|
|
2687
|
+
const t = transcriptOf("tool-args", ctx);
|
|
2688
|
+
checkNames("tool-args", t, [tool]);
|
|
2689
|
+
const args = interpolateDeep(ctx.params.args, ctx);
|
|
2690
|
+
const matches = (actual) => match === "ignore" || (match === "exact" ? sameJson(args, actual) : partialMatch(args, actual));
|
|
2691
|
+
const calls = callsFor(t, tool);
|
|
2692
|
+
const hits = calls.filter((c) => matches(c.call.args)).length;
|
|
2693
|
+
if (hits >= min) return pass;
|
|
2694
|
+
return fail(
|
|
2695
|
+
`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`
|
|
2696
|
+
);
|
|
2697
|
+
});
|
|
2698
|
+
var onlyTools = check((ctx) => {
|
|
2699
|
+
const { tools } = ctx.params;
|
|
2700
|
+
const t = transcriptOf("only-tools", ctx);
|
|
2701
|
+
checkNames("only-tools", t, tools);
|
|
2702
|
+
const off = callsOf(t).filter((c) => !tools.includes(c.call.name));
|
|
2703
|
+
if (off.length === 0) return absence("only-tools", t, "a call to another tool");
|
|
2704
|
+
const allowed = tools.length > 0 ? `only ${tools.join(", ")} called` : "no tool call";
|
|
2705
|
+
return fail(
|
|
2706
|
+
`expected ${allowed}; got ${describeCalls(off)}; check whether allowed_tools should leave the others out`
|
|
2707
|
+
);
|
|
2708
|
+
});
|
|
2709
|
+
|
|
2710
|
+
// src/assertions/tool-calls/order.ts
|
|
2711
|
+
init_esm_shims();
|
|
2712
|
+
function inOrder(names, tools) {
|
|
2713
|
+
let next = 0;
|
|
2714
|
+
for (const n of names) if (n === tools[next]) next++;
|
|
2715
|
+
return next === tools.length;
|
|
2716
|
+
}
|
|
2717
|
+
var toolOrder = check((ctx) => {
|
|
2718
|
+
const { tools, strict = false } = ctx.params;
|
|
2719
|
+
const t = transcriptOf("tool-order", ctx);
|
|
2720
|
+
checkNames("tool-order", t, tools);
|
|
2721
|
+
const calls = callsOf(t);
|
|
2722
|
+
const names = calls.map((c) => c.call.name);
|
|
2723
|
+
const ok = strict ? names.length === tools.length && names.every((n, i) => n === tools[i]) : inOrder(names, tools);
|
|
2724
|
+
if (ok) return pass;
|
|
2725
|
+
const wanted = tools.join(" \u2192 ");
|
|
2726
|
+
return fail(
|
|
2727
|
+
`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`
|
|
2728
|
+
);
|
|
2729
|
+
});
|
|
2730
|
+
var firstTool = check((ctx) => {
|
|
2731
|
+
const { tool } = ctx.params;
|
|
2732
|
+
const t = transcriptOf("first-tool", ctx);
|
|
2733
|
+
checkNames("first-tool", t, [tool]);
|
|
2734
|
+
const first = callsOf(t)[0];
|
|
2735
|
+
if (first?.call.name === tool) return pass;
|
|
2736
|
+
const got = first === void 0 ? "no tool call at all: the model answered without one" : describeCall(first);
|
|
2737
|
+
return fail(
|
|
2738
|
+
`expected the first call to be "${tool}"; got ${got}; check that the prompt and the tool's description point the model to it first`
|
|
2739
|
+
);
|
|
2740
|
+
});
|
|
2741
|
+
var noRepeatedCall = check((ctx) => {
|
|
2742
|
+
const { tool } = ctx.params;
|
|
2743
|
+
const t = transcriptOf("no-repeated-call", ctx);
|
|
2744
|
+
checkNames("no-repeated-call", t, [tool]);
|
|
2745
|
+
const calls = callsOf(t);
|
|
2746
|
+
for (let i = 1; i < calls.length; i++) {
|
|
2747
|
+
const [prev, cur] = [calls[i - 1], calls[i]];
|
|
2748
|
+
if (tool !== void 0 && cur.call.name !== tool) continue;
|
|
2749
|
+
if (prev.call.name === cur.call.name && sameJson(prev.call.args, cur.call.args))
|
|
2750
|
+
return fail(
|
|
2751
|
+
`expected no call repeated right after itself; got ${describeCall(prev)} then ${describeCall(cur)}; check whether the first answer told the model what it needed`
|
|
2752
|
+
);
|
|
2753
|
+
}
|
|
2754
|
+
return pass;
|
|
2755
|
+
});
|
|
1176
2756
|
|
|
1177
|
-
|
|
1178
|
-
|
|
2757
|
+
// src/assertions/tool-calls/errors.ts
|
|
2758
|
+
init_esm_shims();
|
|
2759
|
+
import { Ajv as Ajv2 } from "ajv";
|
|
2760
|
+
function failedOn(found) {
|
|
2761
|
+
const why = new Map(found.map((f) => [f.c, f.why]));
|
|
2762
|
+
return describeCalls(
|
|
2763
|
+
found.map((f) => f.c),
|
|
2764
|
+
(c) => `${describeCall(c)}: ${why.get(c)}`
|
|
2765
|
+
);
|
|
1179
2766
|
}
|
|
1180
|
-
var
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
2767
|
+
var noToolErrors = check((ctx) => {
|
|
2768
|
+
const { tool } = ctx.params;
|
|
2769
|
+
const t = transcriptOf("no-tool-errors", ctx);
|
|
2770
|
+
checkNames("no-tool-errors", t, [tool]);
|
|
2771
|
+
const errors = callsFor(t, tool).filter((c) => c.call.is_error);
|
|
2772
|
+
if (errors.length === 0) return absence("no-tool-errors", t, "a call with an error");
|
|
2773
|
+
return fail(
|
|
2774
|
+
`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`
|
|
2775
|
+
);
|
|
2776
|
+
});
|
|
2777
|
+
function riskOf(name, annotations) {
|
|
2778
|
+
if (annotations?.readOnlyHint === true || annotations?.destructiveHint === false)
|
|
2779
|
+
return void 0;
|
|
2780
|
+
if (annotations === void 0)
|
|
2781
|
+
return `"${name}" declares no annotations, and MCP treats a missing hint as possibly destructive`;
|
|
2782
|
+
if (annotations.destructiveHint === true) return `"${name}" declares destructiveHint: true`;
|
|
2783
|
+
return `"${name}" declares neither readOnlyHint: true nor destructiveHint: false`;
|
|
2784
|
+
}
|
|
2785
|
+
var noDestructiveTool = check((ctx) => {
|
|
2786
|
+
const t = transcriptOf("no-destructive-tool", ctx);
|
|
2787
|
+
if (t.tools.length === 0)
|
|
2788
|
+
throw unmeasured("no-destructive-tool", "there is no tools/list with annotations to read");
|
|
2789
|
+
const listed = new Map(t.tools.map((x) => [x.name, x.annotations]));
|
|
2790
|
+
const risky = [];
|
|
2791
|
+
for (const c of callsOf(t)) {
|
|
2792
|
+
if (!listed.has(c.call.name)) continue;
|
|
2793
|
+
const why = riskOf(c.call.name, listed.get(c.call.name));
|
|
2794
|
+
if (why !== void 0) risky.push({ c, why });
|
|
2795
|
+
}
|
|
2796
|
+
if (risky.length === 0) return absence("no-destructive-tool", t, "a call to a destructive tool");
|
|
2797
|
+
return fail(
|
|
2798
|
+
`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`
|
|
2799
|
+
);
|
|
2800
|
+
});
|
|
2801
|
+
var toolResultSchema = check((ctx) => {
|
|
2802
|
+
const type = "tool-result-schema";
|
|
2803
|
+
const { tool } = ctx.params;
|
|
2804
|
+
const t = transcriptOf(type, ctx);
|
|
2805
|
+
checkNames(type, t, [tool]);
|
|
2806
|
+
const ajv = new Ajv2({ allErrors: true });
|
|
2807
|
+
let validate;
|
|
2808
|
+
try {
|
|
2809
|
+
validate = ajv.compile(ctx.params.schema);
|
|
2810
|
+
} catch (err) {
|
|
2811
|
+
return fail(`invalid schema: ${err.message}`);
|
|
2812
|
+
}
|
|
2813
|
+
const answered = callsFor(t, tool).filter((c) => c.call.executed && !c.call.is_error);
|
|
2814
|
+
const bad = [];
|
|
2815
|
+
let unread;
|
|
2816
|
+
for (const c of answered) {
|
|
2817
|
+
const result = c.call.result;
|
|
2818
|
+
if (result === void 0 || result.truncated) {
|
|
2819
|
+
unread ??= result === void 0 ? `${describeCall(c)} has no result` : `the result of ${describeCall(c)} was cut to its excerpt`;
|
|
2820
|
+
continue;
|
|
1184
2821
|
}
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
};
|
|
2822
|
+
let value;
|
|
2823
|
+
try {
|
|
2824
|
+
value = JSON.parse(result.text);
|
|
2825
|
+
} catch {
|
|
2826
|
+
bad.push({ c, why: "not JSON" });
|
|
2827
|
+
continue;
|
|
2828
|
+
}
|
|
2829
|
+
if (!validate(value))
|
|
2830
|
+
bad.push({ c, why: ajv.errorsText(validate.errors, { separator: "; " }) });
|
|
1195
2831
|
}
|
|
1196
|
-
|
|
2832
|
+
if (bad.length > 0) {
|
|
2833
|
+
const scope = tool === void 0 ? "every result" : `every result of "${tool}"`;
|
|
2834
|
+
return fail(
|
|
2835
|
+
`expected ${scope} to fit the schema; got ${failedOn(bad)}; check the tool's outputSchema against what it returns`
|
|
2836
|
+
);
|
|
2837
|
+
}
|
|
2838
|
+
if (unread !== void 0) throw unmeasured(type, unread);
|
|
2839
|
+
if (answered.length === 0)
|
|
2840
|
+
throw unmeasured(type, "no call answered, so there is no result to check");
|
|
2841
|
+
return pass;
|
|
2842
|
+
});
|
|
2843
|
+
|
|
2844
|
+
// src/assertions/tool-calls/measures.ts
|
|
2845
|
+
init_esm_shims();
|
|
2846
|
+
var toolCallCount = check((ctx) => {
|
|
2847
|
+
const { tool, min, max } = ctx.params;
|
|
2848
|
+
const t = transcriptOf("tool-call-count", ctx);
|
|
2849
|
+
checkNames("tool-call-count", t, [tool]);
|
|
2850
|
+
const calls = callsFor(t, tool);
|
|
2851
|
+
const n = calls.length;
|
|
2852
|
+
if ((min === void 0 || n >= min) && (max === void 0 || n <= max)) return pass;
|
|
2853
|
+
const bound = min === void 0 ? `at most ${plural(max, "call")}` : max === void 0 ? `at least ${plural(min, "call")}` : `${min} to ${max} calls`;
|
|
2854
|
+
const of = tool === void 0 ? "" : ` to "${tool}"`;
|
|
2855
|
+
return fail(
|
|
2856
|
+
`expected ${bound}${of}; got ${n}: ${describeCalls(calls)}; check the limits and whether the model had what it needed`
|
|
2857
|
+
);
|
|
2858
|
+
});
|
|
2859
|
+
var tokenBudget = check((ctx) => {
|
|
2860
|
+
const { max } = ctx.params;
|
|
2861
|
+
const t = transcriptOf("token-budget", ctx);
|
|
2862
|
+
if (t.steps.length === 0)
|
|
2863
|
+
throw unmeasured("token-budget", "no model step was recorded, so there are no tokens to count");
|
|
2864
|
+
const per = t.steps.map((s) => ({
|
|
2865
|
+
step: s.index,
|
|
2866
|
+
tokens: s.usage.input_tokens + s.usage.output_tokens
|
|
2867
|
+
}));
|
|
2868
|
+
const total = per.reduce((a, s) => a + s.tokens, 0);
|
|
2869
|
+
if (total <= max) return pass;
|
|
2870
|
+
const steps = per.map((s) => `step ${s.step}: ${s.tokens}`).join(", ");
|
|
2871
|
+
return fail(
|
|
2872
|
+
`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`
|
|
2873
|
+
);
|
|
2874
|
+
});
|
|
2875
|
+
function eachCall(type, calls, value, bound) {
|
|
2876
|
+
const ran = calls.filter((c) => c.call.executed);
|
|
2877
|
+
const over = ran.filter((c) => (value(c) ?? 0) > bound.max);
|
|
2878
|
+
if (over.length > 0)
|
|
2879
|
+
return fail(
|
|
2880
|
+
`expected ${bound.expected}; got ${describeCalls(over, (c) => `${describeCall(c)}: ${value(c)} ${bound.unit}`)}; ${bound.hint}`
|
|
2881
|
+
);
|
|
2882
|
+
const missing = ran.find((c) => value(c) === void 0);
|
|
2883
|
+
if (missing !== void 0)
|
|
2884
|
+
throw unmeasured(type, `${describeCall(missing)} ran and its ${bound.unit} were not recorded`);
|
|
2885
|
+
if (ran.length === 0) throw unmeasured(type, "no call ran, so there is nothing to measure");
|
|
2886
|
+
return pass;
|
|
2887
|
+
}
|
|
2888
|
+
var toolLatency = check((ctx) => {
|
|
2889
|
+
const { tool, max_ms: max } = ctx.params;
|
|
2890
|
+
const t = transcriptOf("tool-latency", ctx);
|
|
2891
|
+
checkNames("tool-latency", t, [tool]);
|
|
2892
|
+
const scope = tool === void 0 ? "every call" : `every call to "${tool}"`;
|
|
2893
|
+
return eachCall("tool-latency", callsFor(t, tool), (c) => c.call.duration_ms, {
|
|
2894
|
+
max,
|
|
2895
|
+
unit: "ms",
|
|
2896
|
+
expected: `${scope} within ${max} ms`,
|
|
2897
|
+
hint: "check the server for what makes the call slow"
|
|
2898
|
+
});
|
|
2899
|
+
});
|
|
2900
|
+
var toolResultSize = check((ctx) => {
|
|
2901
|
+
const { tool, max_bytes: max } = ctx.params;
|
|
2902
|
+
const t = transcriptOf("tool-result-size", ctx);
|
|
2903
|
+
checkNames("tool-result-size", t, [tool]);
|
|
2904
|
+
const scope = tool === void 0 ? "every result" : `every result of "${tool}"`;
|
|
2905
|
+
return eachCall("tool-result-size", callsFor(t, tool), (c) => c.call.result?.bytes, {
|
|
2906
|
+
max,
|
|
2907
|
+
unit: "bytes",
|
|
2908
|
+
expected: `${scope} at most ${max} bytes`,
|
|
2909
|
+
hint: "check whether the tool can page or filter what it returns"
|
|
2910
|
+
});
|
|
2911
|
+
});
|
|
1197
2912
|
|
|
1198
2913
|
// src/assertions/registry.ts
|
|
1199
2914
|
function createAssertionRegistry() {
|
|
@@ -1215,6 +2930,9 @@ function createAssertionRegistry() {
|
|
|
1215
2930
|
},
|
|
1216
2931
|
has(type) {
|
|
1217
2932
|
return impls.has(type);
|
|
2933
|
+
},
|
|
2934
|
+
types() {
|
|
2935
|
+
return [...impls.keys()];
|
|
1218
2936
|
}
|
|
1219
2937
|
};
|
|
1220
2938
|
}
|
|
@@ -1230,6 +2948,20 @@ function createDefaultRegistry2() {
|
|
|
1230
2948
|
registry.register("faithfulness", faithfulness);
|
|
1231
2949
|
registry.register("answer-relevance", answerRelevance);
|
|
1232
2950
|
registry.register("context-precision", contextPrecision);
|
|
2951
|
+
registry.register("tool-called", toolCalled);
|
|
2952
|
+
registry.register("tool-not-called", toolNotCalled);
|
|
2953
|
+
registry.register("tool-args", toolArgs);
|
|
2954
|
+
registry.register("tool-order", toolOrder);
|
|
2955
|
+
registry.register("only-tools", onlyTools);
|
|
2956
|
+
registry.register("first-tool", firstTool);
|
|
2957
|
+
registry.register("no-tool-errors", noToolErrors);
|
|
2958
|
+
registry.register("tool-call-count", toolCallCount);
|
|
2959
|
+
registry.register("no-repeated-call", noRepeatedCall);
|
|
2960
|
+
registry.register("token-budget", tokenBudget);
|
|
2961
|
+
registry.register("tool-latency", toolLatency);
|
|
2962
|
+
registry.register("tool-result-size", toolResultSize);
|
|
2963
|
+
registry.register("tool-result-schema", toolResultSchema);
|
|
2964
|
+
registry.register("no-destructive-tool", noDestructiveTool);
|
|
1233
2965
|
return registry;
|
|
1234
2966
|
}
|
|
1235
2967
|
var defaultRegistry;
|
|
@@ -1238,7 +2970,38 @@ function getAssertion(type) {
|
|
|
1238
2970
|
return defaultRegistry.resolve(type);
|
|
1239
2971
|
}
|
|
1240
2972
|
|
|
2973
|
+
// src/assertions/classes.ts
|
|
2974
|
+
init_esm_shims();
|
|
2975
|
+
var ASSERTION_CLASSES = {
|
|
2976
|
+
"exact-match": "deterministic",
|
|
2977
|
+
contains: "deterministic",
|
|
2978
|
+
"contains-any": "deterministic",
|
|
2979
|
+
"contains-all": "deterministic",
|
|
2980
|
+
"json-schema": "deterministic",
|
|
2981
|
+
// A score against the author's threshold. They decide the row as they always have.
|
|
2982
|
+
"semantic-similarity": "measure",
|
|
2983
|
+
"llm-judge": "measure",
|
|
2984
|
+
faithfulness: "measure",
|
|
2985
|
+
"answer-relevance": "measure",
|
|
2986
|
+
"context-precision": "measure",
|
|
2987
|
+
"tool-called": "deterministic",
|
|
2988
|
+
"tool-not-called": "deterministic",
|
|
2989
|
+
"tool-args": "deterministic",
|
|
2990
|
+
"tool-order": "deterministic",
|
|
2991
|
+
"only-tools": "deterministic",
|
|
2992
|
+
"first-tool": "deterministic",
|
|
2993
|
+
"no-tool-errors": "deterministic",
|
|
2994
|
+
"tool-call-count": "measure",
|
|
2995
|
+
"no-repeated-call": "heuristic",
|
|
2996
|
+
"token-budget": "measure",
|
|
2997
|
+
"tool-latency": "measure",
|
|
2998
|
+
"tool-result-size": "measure",
|
|
2999
|
+
"tool-result-schema": "deterministic",
|
|
3000
|
+
"no-destructive-tool": "deterministic"
|
|
3001
|
+
};
|
|
3002
|
+
|
|
1241
3003
|
// src/orchestrator/judge.ts
|
|
3004
|
+
init_esm_shims();
|
|
1242
3005
|
var DEFAULT_MAX_TOKENS = 1024;
|
|
1243
3006
|
function buildJudge(provider, cfg, onUsage) {
|
|
1244
3007
|
return {
|
|
@@ -1257,7 +3020,8 @@ function buildJudge(provider, cfg, onUsage) {
|
|
|
1257
3020
|
}
|
|
1258
3021
|
|
|
1259
3022
|
// src/orchestrator/concurrency.ts
|
|
1260
|
-
|
|
3023
|
+
init_esm_shims();
|
|
3024
|
+
async function mapLimit(items, limit2, fn) {
|
|
1261
3025
|
const results = new Array(items.length);
|
|
1262
3026
|
let next = 0;
|
|
1263
3027
|
const worker = async () => {
|
|
@@ -1267,13 +3031,17 @@ async function mapLimit(items, limit, fn) {
|
|
|
1267
3031
|
results[i] = await fn(items[i], i);
|
|
1268
3032
|
}
|
|
1269
3033
|
};
|
|
1270
|
-
const safeLimit = Number.isFinite(
|
|
3034
|
+
const safeLimit = Number.isFinite(limit2) && limit2 >= 1 ? Math.floor(limit2) : 1;
|
|
1271
3035
|
const workerCount = Math.min(safeLimit, items.length);
|
|
1272
3036
|
await Promise.all(Array.from({ length: workerCount }, () => worker()));
|
|
1273
3037
|
return results;
|
|
1274
3038
|
}
|
|
1275
3039
|
|
|
3040
|
+
// src/types/results.ts
|
|
3041
|
+
init_esm_shims();
|
|
3042
|
+
|
|
1276
3043
|
// src/types/test-case-schema.ts
|
|
3044
|
+
init_esm_shims();
|
|
1277
3045
|
import { z as z2 } from "zod";
|
|
1278
3046
|
var TEST_CASE_SCHEMA_VERSION = 2;
|
|
1279
3047
|
var externalKeySchema = z2.object({
|
|
@@ -1331,8 +3099,301 @@ function rowStatus(row) {
|
|
|
1331
3099
|
return row.assertions.every((a) => a.passed) ? "passed" : "failed";
|
|
1332
3100
|
}
|
|
1333
3101
|
|
|
1334
|
-
// src/orchestrator/
|
|
3102
|
+
// src/orchestrator/agent.ts
|
|
3103
|
+
init_esm_shims();
|
|
3104
|
+
|
|
3105
|
+
// src/orchestrator/tool-names.ts
|
|
3106
|
+
init_esm_shims();
|
|
3107
|
+
var SAFE = /^[a-zA-Z0-9_-]{1,64}$/;
|
|
3108
|
+
var MAX = 64;
|
|
3109
|
+
function wireNames(names) {
|
|
3110
|
+
const toWire = /* @__PURE__ */ new Map();
|
|
3111
|
+
const toServer = /* @__PURE__ */ new Map();
|
|
3112
|
+
for (const name of names)
|
|
3113
|
+
if (SAFE.test(name) && !toServer.has(name)) {
|
|
3114
|
+
toWire.set(name, name);
|
|
3115
|
+
toServer.set(name, name);
|
|
3116
|
+
}
|
|
3117
|
+
for (const name of names) {
|
|
3118
|
+
if (toWire.has(name)) continue;
|
|
3119
|
+
const base = name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, MAX) || "tool";
|
|
3120
|
+
let wire = base;
|
|
3121
|
+
for (let n = 2; toServer.has(wire); n++) wire = `${base.slice(0, MAX - `_${n}`.length)}_${n}`;
|
|
3122
|
+
toWire.set(name, wire);
|
|
3123
|
+
toServer.set(wire, name);
|
|
3124
|
+
}
|
|
3125
|
+
return { toWire, toServer };
|
|
3126
|
+
}
|
|
3127
|
+
|
|
3128
|
+
// src/orchestrator/agent.ts
|
|
3129
|
+
var EXCERPT_BYTES = 4 * 1024;
|
|
3130
|
+
var TRANSCRIPT_BYTES = 256 * 1024;
|
|
1335
3131
|
var DEFAULT_MAX_TOKENS2 = 1024;
|
|
3132
|
+
var LimitStop = class extends Error {
|
|
3133
|
+
constructor(limit2) {
|
|
3134
|
+
super(`stopped by ${limit2}`);
|
|
3135
|
+
this.limit = limit2;
|
|
3136
|
+
}
|
|
3137
|
+
limit;
|
|
3138
|
+
};
|
|
3139
|
+
var AgentError = class extends Error {
|
|
3140
|
+
constructor(code, message) {
|
|
3141
|
+
super(message);
|
|
3142
|
+
this.code = code;
|
|
3143
|
+
}
|
|
3144
|
+
code;
|
|
3145
|
+
};
|
|
3146
|
+
var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
3147
|
+
function resultText(result) {
|
|
3148
|
+
if (!isRecord2(result)) return JSON.stringify(result) ?? "";
|
|
3149
|
+
const content = Array.isArray(result.content) ? result.content : [];
|
|
3150
|
+
if (content.length === 0 && result.structuredContent !== void 0)
|
|
3151
|
+
return JSON.stringify(result.structuredContent);
|
|
3152
|
+
return content.map(
|
|
3153
|
+
(b) => isRecord2(b) && b.type === "text" && typeof b.text === "string" ? b.text : JSON.stringify(b)
|
|
3154
|
+
).join("\n");
|
|
3155
|
+
}
|
|
3156
|
+
function excerpts() {
|
|
3157
|
+
let left = TRANSCRIPT_BYTES;
|
|
3158
|
+
const state = {
|
|
3159
|
+
any: false,
|
|
3160
|
+
cut(text) {
|
|
3161
|
+
const whole = Buffer.from(text, "utf8");
|
|
3162
|
+
const keep = Math.max(0, Math.min(EXCERPT_BYTES, left, whole.length));
|
|
3163
|
+
left -= keep;
|
|
3164
|
+
const truncated = keep < whole.length;
|
|
3165
|
+
if (truncated) state.any = true;
|
|
3166
|
+
const kept = truncated ? whole.subarray(0, keep).toString("utf8").replace(/�$/, "") : text;
|
|
3167
|
+
return { text: kept, bytes: whole.length, truncated };
|
|
3168
|
+
}
|
|
3169
|
+
};
|
|
3170
|
+
return state;
|
|
3171
|
+
}
|
|
3172
|
+
function listedTools(items) {
|
|
3173
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3174
|
+
return items.filter((t) => {
|
|
3175
|
+
if (!isRecord2(t) || typeof t.name !== "string" || t.name === "" || seen.has(t.name))
|
|
3176
|
+
return false;
|
|
3177
|
+
seen.add(t.name);
|
|
3178
|
+
return true;
|
|
3179
|
+
});
|
|
3180
|
+
}
|
|
3181
|
+
async function runAgentRow(p) {
|
|
3182
|
+
const t0 = p.now();
|
|
3183
|
+
const prompt5 = resolvePrompt(p.template, p.row.vars);
|
|
3184
|
+
const temperature = p.providerConfig.temperature;
|
|
3185
|
+
const maxTokens = p.providerConfig.max_tokens ?? DEFAULT_MAX_TOKENS2;
|
|
3186
|
+
const { limits } = p;
|
|
3187
|
+
if (p.dryRun) {
|
|
3188
|
+
const one = estimateUsage(prompt5, maxTokens);
|
|
3189
|
+
const est = {
|
|
3190
|
+
input_tokens: one.input_tokens * limits.max_steps,
|
|
3191
|
+
output_tokens: one.output_tokens * limits.max_steps
|
|
3192
|
+
};
|
|
3193
|
+
return {
|
|
3194
|
+
vars: p.row.vars,
|
|
3195
|
+
output: null,
|
|
3196
|
+
cached: false,
|
|
3197
|
+
usage: { ...est, ...costFields(p.provider.estimateCost(est)) },
|
|
3198
|
+
assertions: []
|
|
3199
|
+
};
|
|
3200
|
+
}
|
|
3201
|
+
const respond = p.provider.respond.bind(p.provider);
|
|
3202
|
+
const deadline = t0 + limits.timeout_ms;
|
|
3203
|
+
const bounded = (work) => {
|
|
3204
|
+
const ms = deadline - p.now();
|
|
3205
|
+
let timer;
|
|
3206
|
+
return Promise.race([
|
|
3207
|
+
work,
|
|
3208
|
+
new Promise((_, reject) => {
|
|
3209
|
+
timer = setTimeout(() => reject(new LimitStop("timeout_ms")), Math.max(0, ms));
|
|
3210
|
+
})
|
|
3211
|
+
]).finally(() => clearTimeout(timer));
|
|
3212
|
+
};
|
|
3213
|
+
const transcript = {
|
|
3214
|
+
server: p.server,
|
|
3215
|
+
tools: [],
|
|
3216
|
+
steps: [],
|
|
3217
|
+
stop: { reason: "complete" },
|
|
3218
|
+
collection: "complete"
|
|
3219
|
+
};
|
|
3220
|
+
const kept = excerpts();
|
|
3221
|
+
const usages = [];
|
|
3222
|
+
let output = "";
|
|
3223
|
+
let error;
|
|
3224
|
+
let session;
|
|
3225
|
+
try {
|
|
3226
|
+
const opening = p.connect(p.server, limits.timeout_ms);
|
|
3227
|
+
try {
|
|
3228
|
+
session = await bounded(opening);
|
|
3229
|
+
} catch (err) {
|
|
3230
|
+
void opening.then(
|
|
3231
|
+
(s) => s.close(),
|
|
3232
|
+
() => {
|
|
3233
|
+
}
|
|
3234
|
+
);
|
|
3235
|
+
if (err instanceof LimitStop) throw err;
|
|
3236
|
+
throw new AgentError("MCP_CONNECT", err.message);
|
|
3237
|
+
}
|
|
3238
|
+
let listed;
|
|
3239
|
+
try {
|
|
3240
|
+
listed = listedTools(await bounded(session.listTools(limits.tool_timeout_ms)));
|
|
3241
|
+
} catch (err) {
|
|
3242
|
+
if (err instanceof LimitStop) throw err;
|
|
3243
|
+
throw new AgentError("MCP_LIST_TOOLS", `tools/list failed: ${err.message}`);
|
|
3244
|
+
}
|
|
3245
|
+
const offered = listed.filter(
|
|
3246
|
+
(t) => p.allowedTools === void 0 || p.allowedTools.includes(t.name)
|
|
3247
|
+
);
|
|
3248
|
+
transcript.tools = listed.map((t) => ({
|
|
3249
|
+
name: t.name,
|
|
3250
|
+
offered: offered.includes(t),
|
|
3251
|
+
...isRecord2(t.annotations) ? { annotations: t.annotations } : {}
|
|
3252
|
+
}));
|
|
3253
|
+
const names = wireNames(offered.map((t) => t.name));
|
|
3254
|
+
const tools = offered.map((t) => ({
|
|
3255
|
+
name: names.toWire.get(t.name),
|
|
3256
|
+
...typeof t.description === "string" ? { description: t.description } : {},
|
|
3257
|
+
input_schema: isRecord2(t.inputSchema) ? t.inputSchema : { type: "object" }
|
|
3258
|
+
}));
|
|
3259
|
+
const messages = [{ role: "user", content: prompt5 }];
|
|
3260
|
+
let calls = 0;
|
|
3261
|
+
let tokens = 0;
|
|
3262
|
+
for (let index = 1; ; index++) {
|
|
3263
|
+
const res = await bounded(
|
|
3264
|
+
respond({
|
|
3265
|
+
provider: p.providerConfig.type,
|
|
3266
|
+
model: p.providerConfig.model,
|
|
3267
|
+
...temperature !== void 0 ? { temperature } : {},
|
|
3268
|
+
max_tokens: maxTokens,
|
|
3269
|
+
messages,
|
|
3270
|
+
tools
|
|
3271
|
+
})
|
|
3272
|
+
);
|
|
3273
|
+
const usage2 = {
|
|
3274
|
+
...res.usage,
|
|
3275
|
+
...costFields(p.provider.estimateCost(res.usage, res.cost_usd))
|
|
3276
|
+
};
|
|
3277
|
+
usages.push(usage2);
|
|
3278
|
+
tokens += res.usage.input_tokens + res.usage.output_tokens;
|
|
3279
|
+
output = res.text;
|
|
3280
|
+
const records2 = res.tool_calls.map((c) => ({
|
|
3281
|
+
id: c.id,
|
|
3282
|
+
name: names.toServer.get(c.name) ?? c.name,
|
|
3283
|
+
args: c.args,
|
|
3284
|
+
executed: false,
|
|
3285
|
+
is_error: false
|
|
3286
|
+
}));
|
|
3287
|
+
const step = {
|
|
3288
|
+
index,
|
|
3289
|
+
text: kept.cut(res.text).text,
|
|
3290
|
+
...res.finish_reason !== void 0 ? { finish_reason: res.finish_reason } : {},
|
|
3291
|
+
usage: usage2,
|
|
3292
|
+
calls: records2
|
|
3293
|
+
};
|
|
3294
|
+
transcript.steps.push(step);
|
|
3295
|
+
if (res.finish_reason === "error")
|
|
3296
|
+
throw new AgentError(
|
|
3297
|
+
"PROVIDER_ERROR",
|
|
3298
|
+
"The provider answered with an error instead of a turn."
|
|
3299
|
+
);
|
|
3300
|
+
if (res.tool_calls.length === 0) break;
|
|
3301
|
+
if (res.finish_reason === "length")
|
|
3302
|
+
throw new AgentError(
|
|
3303
|
+
"AGENT_CUT_OFF",
|
|
3304
|
+
`Step ${index} hit max_tokens in the middle of a tool call.`
|
|
3305
|
+
);
|
|
3306
|
+
if (index >= limits.max_steps) throw new LimitStop("max_steps");
|
|
3307
|
+
if (tokens > limits.max_total_tokens) throw new LimitStop("max_total_tokens");
|
|
3308
|
+
const results = [];
|
|
3309
|
+
const answer = (rec, c, content) => results.push({ id: c.id, content, is_error: rec.is_error });
|
|
3310
|
+
for (const [i, c] of res.tool_calls.entries()) {
|
|
3311
|
+
const rec = records2[i];
|
|
3312
|
+
if (calls >= limits.max_tool_calls) throw new LimitStop("max_tool_calls");
|
|
3313
|
+
calls++;
|
|
3314
|
+
const server = names.toServer.get(c.name);
|
|
3315
|
+
if (server === void 0) {
|
|
3316
|
+
Object.assign(rec, { is_error: true, error_kind: "not-offered" });
|
|
3317
|
+
answer(rec, c, `Tool "${c.name}" is not available.`);
|
|
3318
|
+
continue;
|
|
3319
|
+
}
|
|
3320
|
+
if (c.args_invalid === true || !isRecord2(c.args)) {
|
|
3321
|
+
Object.assign(rec, { is_error: true, error_kind: "bad-arguments" });
|
|
3322
|
+
answer(rec, c, "The arguments are not a JSON object.");
|
|
3323
|
+
continue;
|
|
3324
|
+
}
|
|
3325
|
+
const started = p.now();
|
|
3326
|
+
rec.executed = true;
|
|
3327
|
+
const got = await bounded(session.callTool(server, c.args, limits.tool_timeout_ms));
|
|
3328
|
+
rec.duration_ms = p.now() - started;
|
|
3329
|
+
if (got.kind === "timeout") {
|
|
3330
|
+
Object.assign(rec, { is_error: true, error_kind: "timeout" });
|
|
3331
|
+
throw new LimitStop("tool_timeout_ms");
|
|
3332
|
+
}
|
|
3333
|
+
if (got.kind === "lost") throw new AgentError("MCP_SERVER_LOST", got.message);
|
|
3334
|
+
const text = got.kind === "error" ? got.message : resultText(got.result);
|
|
3335
|
+
if (got.kind === "error") Object.assign(rec, { is_error: true, error_kind: "protocol" });
|
|
3336
|
+
else if (isRecord2(got.result) && got.result.isError === true)
|
|
3337
|
+
Object.assign(rec, { is_error: true, error_kind: "content" });
|
|
3338
|
+
rec.result = kept.cut(text);
|
|
3339
|
+
answer(rec, c, text);
|
|
3340
|
+
}
|
|
3341
|
+
messages.push(
|
|
3342
|
+
{ role: "assistant", text: res.text, tool_calls: res.tool_calls },
|
|
3343
|
+
{ role: "tool", results }
|
|
3344
|
+
);
|
|
3345
|
+
}
|
|
3346
|
+
} catch (err) {
|
|
3347
|
+
if (err instanceof LimitStop) transcript.stop = { reason: "limit", limit: err.limit };
|
|
3348
|
+
else {
|
|
3349
|
+
transcript.stop = { reason: "error" };
|
|
3350
|
+
error = err instanceof AgentError ? { code: err.code, message: err.message } : toRunError(err);
|
|
3351
|
+
}
|
|
3352
|
+
} finally {
|
|
3353
|
+
await session?.close().catch(() => {
|
|
3354
|
+
});
|
|
3355
|
+
}
|
|
3356
|
+
if (transcript.stop.reason !== "complete" || kept.any) transcript.collection = "partial";
|
|
3357
|
+
const mask = session?.redact;
|
|
3358
|
+
const agent = mask?.value(transcript) ?? transcript;
|
|
3359
|
+
const spent = usages.length > 0 ? { usage: sumUsage(usages) } : {};
|
|
3360
|
+
if (error !== void 0) {
|
|
3361
|
+
return {
|
|
3362
|
+
vars: p.row.vars,
|
|
3363
|
+
output: null,
|
|
3364
|
+
cached: false,
|
|
3365
|
+
...spent,
|
|
3366
|
+
latency_ms: p.now() - t0,
|
|
3367
|
+
error: { code: error.code, message: mask?.text(error.message) ?? error.message },
|
|
3368
|
+
assertions: [],
|
|
3369
|
+
agent
|
|
3370
|
+
};
|
|
3371
|
+
}
|
|
3372
|
+
const { records, assertionError, judgeCost, judgeUnpriced, advice } = await assess(
|
|
3373
|
+
p,
|
|
3374
|
+
output,
|
|
3375
|
+
agent
|
|
3376
|
+
);
|
|
3377
|
+
if (advice.length > 0) agent.advice = advice;
|
|
3378
|
+
const usage = sumUsage(usages);
|
|
3379
|
+
return {
|
|
3380
|
+
vars: p.row.vars,
|
|
3381
|
+
output: mask?.text(output) ?? output,
|
|
3382
|
+
cached: false,
|
|
3383
|
+
usage: {
|
|
3384
|
+
...usage,
|
|
3385
|
+
cost_usd: usage.cost_usd + judgeCost,
|
|
3386
|
+
...judgeUnpriced ? { priced: false } : {}
|
|
3387
|
+
},
|
|
3388
|
+
latency_ms: p.now() - t0,
|
|
3389
|
+
...assertionError !== void 0 ? { error: assertionError } : {},
|
|
3390
|
+
assertions: records,
|
|
3391
|
+
agent
|
|
3392
|
+
};
|
|
3393
|
+
}
|
|
3394
|
+
|
|
3395
|
+
// src/orchestrator/run.ts
|
|
3396
|
+
var DEFAULT_MAX_TOKENS3 = 1024;
|
|
1336
3397
|
var PLUNE_VERSION = "0.1.0";
|
|
1337
3398
|
var RunConfigError = class extends Error {
|
|
1338
3399
|
code = "CONFIG_ERROR";
|
|
@@ -1356,7 +3417,7 @@ function resolvePrompt(template, vars) {
|
|
|
1356
3417
|
});
|
|
1357
3418
|
}
|
|
1358
3419
|
function toRunError(err) {
|
|
1359
|
-
if (err instanceof ProviderError || err instanceof AuthError) {
|
|
3420
|
+
if (err instanceof ProviderError || err instanceof AuthError || err instanceof AssertionRunError) {
|
|
1360
3421
|
return { code: err.code, message: err.message };
|
|
1361
3422
|
}
|
|
1362
3423
|
return { code: "ERROR", message: err instanceof Error ? err.message : String(err) };
|
|
@@ -1370,11 +3431,55 @@ function pricedField(priced) {
|
|
|
1370
3431
|
function costFields(c) {
|
|
1371
3432
|
return { cost_usd: c.cost_usd, ...pricedField(c.priced) };
|
|
1372
3433
|
}
|
|
3434
|
+
async function assess(p, output, transcript) {
|
|
3435
|
+
let judgeCost = 0;
|
|
3436
|
+
let judgeUnpriced = false;
|
|
3437
|
+
const judge = buildJudge(p.provider, p.providerConfig, (u) => {
|
|
3438
|
+
const c = p.provider.estimateCost(u);
|
|
3439
|
+
judgeCost += c.cost_usd;
|
|
3440
|
+
if (c.priced === false) judgeUnpriced = true;
|
|
3441
|
+
});
|
|
3442
|
+
const records = [];
|
|
3443
|
+
const advice = [];
|
|
3444
|
+
let assertionError;
|
|
3445
|
+
for (const assertion of p.assertions) {
|
|
3446
|
+
const run = () => getAssertion(assertion.type).run({
|
|
3447
|
+
output,
|
|
3448
|
+
vars: p.row.vars,
|
|
3449
|
+
row: p.row,
|
|
3450
|
+
params: assertion,
|
|
3451
|
+
embedder: p.embedder,
|
|
3452
|
+
judge,
|
|
3453
|
+
...transcript !== void 0 ? { transcript } : {}
|
|
3454
|
+
});
|
|
3455
|
+
if (ASSERTION_CLASSES[assertion.type] === "heuristic") {
|
|
3456
|
+
const found = await run().then(
|
|
3457
|
+
(r) => r.passed ? void 0 : r.reason ?? "no reason given",
|
|
3458
|
+
(err) => toRunError(err).message
|
|
3459
|
+
);
|
|
3460
|
+
if (found !== void 0) advice.push({ type: assertion.type, reason: found });
|
|
3461
|
+
continue;
|
|
3462
|
+
}
|
|
3463
|
+
try {
|
|
3464
|
+
const result = await run();
|
|
3465
|
+
records.push({
|
|
3466
|
+
type: assertion.type,
|
|
3467
|
+
passed: result.passed,
|
|
3468
|
+
...result.score !== void 0 ? { score: result.score } : {},
|
|
3469
|
+
...result.reason !== void 0 ? { reason: result.reason } : {}
|
|
3470
|
+
});
|
|
3471
|
+
} catch (err) {
|
|
3472
|
+
assertionError = toRunError(err);
|
|
3473
|
+
break;
|
|
3474
|
+
}
|
|
3475
|
+
}
|
|
3476
|
+
return { records, assertionError, judgeCost, judgeUnpriced, advice };
|
|
3477
|
+
}
|
|
1373
3478
|
async function runRow(p) {
|
|
1374
3479
|
const t0 = p.now();
|
|
1375
3480
|
const prompt5 = resolvePrompt(p.template, p.row.vars);
|
|
1376
3481
|
const temperature = p.providerConfig.temperature;
|
|
1377
|
-
const maxTokens = p.providerConfig.max_tokens ??
|
|
3482
|
+
const maxTokens = p.providerConfig.max_tokens ?? DEFAULT_MAX_TOKENS3;
|
|
1378
3483
|
if (p.dryRun) {
|
|
1379
3484
|
const est = estimateUsage(prompt5, maxTokens);
|
|
1380
3485
|
const cost = p.provider.estimateCost(est);
|
|
@@ -1387,7 +3492,8 @@ async function runRow(p) {
|
|
|
1387
3492
|
model: p.providerConfig.model,
|
|
1388
3493
|
temperature: temperature ?? 0,
|
|
1389
3494
|
max_tokens: maxTokens,
|
|
1390
|
-
prompt_resolved: prompt5
|
|
3495
|
+
prompt_resolved: prompt5,
|
|
3496
|
+
...p.attempt !== void 0 ? { attempt: p.attempt } : {}
|
|
1391
3497
|
},
|
|
1392
3498
|
p.policyVersion
|
|
1393
3499
|
);
|
|
@@ -1457,36 +3563,7 @@ async function runRow(p) {
|
|
|
1457
3563
|
};
|
|
1458
3564
|
}
|
|
1459
3565
|
}
|
|
1460
|
-
|
|
1461
|
-
let judgeUnpriced = false;
|
|
1462
|
-
const judge = buildJudge(p.provider, p.providerConfig, (u) => {
|
|
1463
|
-
const c = p.provider.estimateCost(u);
|
|
1464
|
-
judgeCost += c.cost_usd;
|
|
1465
|
-
if (c.priced === false) judgeUnpriced = true;
|
|
1466
|
-
});
|
|
1467
|
-
const records = [];
|
|
1468
|
-
let assertionError;
|
|
1469
|
-
for (const assertion of p.assertions) {
|
|
1470
|
-
try {
|
|
1471
|
-
const result = await getAssertion(assertion.type).run({
|
|
1472
|
-
output,
|
|
1473
|
-
vars: p.row.vars,
|
|
1474
|
-
row: p.row,
|
|
1475
|
-
params: assertion,
|
|
1476
|
-
embedder: p.embedder,
|
|
1477
|
-
judge
|
|
1478
|
-
});
|
|
1479
|
-
records.push({
|
|
1480
|
-
type: assertion.type,
|
|
1481
|
-
passed: result.passed,
|
|
1482
|
-
...result.score !== void 0 ? { score: result.score } : {},
|
|
1483
|
-
...result.reason !== void 0 ? { reason: result.reason } : {}
|
|
1484
|
-
});
|
|
1485
|
-
} catch (err) {
|
|
1486
|
-
assertionError = toRunError(err);
|
|
1487
|
-
break;
|
|
1488
|
-
}
|
|
1489
|
-
}
|
|
3566
|
+
const { records, assertionError, judgeCost, judgeUnpriced } = await assess(p, output);
|
|
1490
3567
|
const finalUsage = {
|
|
1491
3568
|
...usage,
|
|
1492
3569
|
cost_usd: usage.cost_usd + judgeCost,
|
|
@@ -1504,6 +3581,79 @@ async function runRow(p) {
|
|
|
1504
3581
|
assertions: records
|
|
1505
3582
|
};
|
|
1506
3583
|
}
|
|
3584
|
+
function neededPasses(passThreshold, runs) {
|
|
3585
|
+
return Math.max(1, Math.ceil(passThreshold * runs - 1e-9));
|
|
3586
|
+
}
|
|
3587
|
+
function toAttempt(r) {
|
|
3588
|
+
return {
|
|
3589
|
+
output: r.output,
|
|
3590
|
+
cached: r.cached,
|
|
3591
|
+
...r.usage !== void 0 ? { usage: r.usage } : {},
|
|
3592
|
+
...r.latency_ms !== void 0 ? { latency_ms: r.latency_ms } : {},
|
|
3593
|
+
...r.error !== void 0 ? { error: r.error } : {},
|
|
3594
|
+
assertions: r.assertions,
|
|
3595
|
+
...r.cache_saved !== void 0 ? { cache_saved: r.cache_saved } : {}
|
|
3596
|
+
};
|
|
3597
|
+
}
|
|
3598
|
+
function sumTokens(parts) {
|
|
3599
|
+
return parts.reduce(
|
|
3600
|
+
(a, u) => ({
|
|
3601
|
+
input_tokens: a.input_tokens + u.input_tokens,
|
|
3602
|
+
output_tokens: a.output_tokens + u.output_tokens,
|
|
3603
|
+
cost_usd: a.cost_usd + u.cost_usd
|
|
3604
|
+
}),
|
|
3605
|
+
{ input_tokens: 0, output_tokens: 0, cost_usd: 0 }
|
|
3606
|
+
);
|
|
3607
|
+
}
|
|
3608
|
+
function sumUsage(parts) {
|
|
3609
|
+
const priced = parts.some((u) => u.priced === false) ? false : parts.some((u) => u.priced === true) ? true : void 0;
|
|
3610
|
+
return { ...sumTokens(parts), ...pricedField(priced) };
|
|
3611
|
+
}
|
|
3612
|
+
async function runRepeats(p, runs, passThreshold, run = runRow) {
|
|
3613
|
+
if (runs <= 1) return run(p);
|
|
3614
|
+
const counts = { runs, pass_threshold: passThreshold, passed: 0, failed: 0, errored: 0 };
|
|
3615
|
+
if (p.dryRun) {
|
|
3616
|
+
const one = await run(p);
|
|
3617
|
+
const u = one.usage;
|
|
3618
|
+
const usage = u === void 0 ? void 0 : {
|
|
3619
|
+
...u,
|
|
3620
|
+
input_tokens: u.input_tokens * runs,
|
|
3621
|
+
output_tokens: u.output_tokens * runs,
|
|
3622
|
+
cost_usd: u.cost_usd * runs
|
|
3623
|
+
};
|
|
3624
|
+
return {
|
|
3625
|
+
...one,
|
|
3626
|
+
...usage !== void 0 ? { usage } : {},
|
|
3627
|
+
attempts: { ...counts, results: [] }
|
|
3628
|
+
};
|
|
3629
|
+
}
|
|
3630
|
+
const rows = [];
|
|
3631
|
+
for (let attempt = 0; attempt < runs; attempt += 1) {
|
|
3632
|
+
rows.push(await run({ ...p, attempt }));
|
|
3633
|
+
}
|
|
3634
|
+
const states = rows.map(rowStatus);
|
|
3635
|
+
const passed = states.filter((s) => s === "passed").length;
|
|
3636
|
+
const failed = states.filter((s) => s === "failed").length;
|
|
3637
|
+
const errored = runs - passed - failed;
|
|
3638
|
+
const needed = neededPasses(passThreshold, runs);
|
|
3639
|
+
const verdict = passed >= needed ? "passed" : passed + errored >= needed ? "errored" : "failed";
|
|
3640
|
+
const shown = rows[states.indexOf(verdict)];
|
|
3641
|
+
const usages = rows.flatMap((r) => r.usage !== void 0 ? [r.usage] : []);
|
|
3642
|
+
const saved = rows.flatMap((r) => r.cache_saved !== void 0 ? [r.cache_saved] : []);
|
|
3643
|
+
const latencies = rows.flatMap((r) => r.latency_ms !== void 0 ? [r.latency_ms] : []);
|
|
3644
|
+
return {
|
|
3645
|
+
vars: p.row.vars,
|
|
3646
|
+
output: shown.output,
|
|
3647
|
+
cached: rows.every((r) => r.cached),
|
|
3648
|
+
...usages.length > 0 ? { usage: sumUsage(usages) } : {},
|
|
3649
|
+
...latencies.length > 0 ? { latency_ms: latencies.reduce((a, b) => a + b, 0) } : {},
|
|
3650
|
+
...saved.length > 0 ? { cache_saved: sumTokens(saved) } : {},
|
|
3651
|
+
...shown.error !== void 0 ? { error: shown.error } : {},
|
|
3652
|
+
assertions: shown.assertions,
|
|
3653
|
+
attempts: { ...counts, passed, failed, errored, results: rows.map(toAttempt) },
|
|
3654
|
+
...shown.agent !== void 0 ? { agent: shown.agent } : {}
|
|
3655
|
+
};
|
|
3656
|
+
}
|
|
1507
3657
|
function selectEvals(evals, only) {
|
|
1508
3658
|
if (only === void 0 || only.length === 0) return evals;
|
|
1509
3659
|
return evals.filter(
|
|
@@ -1516,7 +3666,7 @@ function resolveTemplate(ev, baseDir) {
|
|
|
1516
3666
|
if (ev.prompt !== void 0) return ev.prompt;
|
|
1517
3667
|
if (ev.prompt_file !== void 0) {
|
|
1518
3668
|
try {
|
|
1519
|
-
return fs3.readFileSync(
|
|
3669
|
+
return fs3.readFileSync(path4.resolve(baseDir, ev.prompt_file), "utf8");
|
|
1520
3670
|
} catch {
|
|
1521
3671
|
throw new RunConfigError(`Eval "${ev.id}": prompt_file not found: ${ev.prompt_file}`);
|
|
1522
3672
|
}
|
|
@@ -1546,18 +3696,34 @@ function summarize(evals, durationMs) {
|
|
|
1546
3696
|
summary.total += 1;
|
|
1547
3697
|
summary[rowStatus(row)] += 1;
|
|
1548
3698
|
summary.cost_usd += row.usage?.cost_usd ?? 0;
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
} else if (row.error?.code === CACHE_MISS_CODE) cache.missed += 1;
|
|
3699
|
+
cache.saved.input_tokens += row.cache_saved?.input_tokens ?? 0;
|
|
3700
|
+
cache.saved.output_tokens += row.cache_saved?.output_tokens ?? 0;
|
|
3701
|
+
cache.saved.cost_usd += row.cache_saved?.cost_usd ?? 0;
|
|
3702
|
+
if (row.cached) cache.from_cache += 1;
|
|
3703
|
+
else if (row.error?.code === CACHE_MISS_CODE) cache.missed += 1;
|
|
1555
3704
|
else if (row.output !== null) cache.from_model += 1;
|
|
1556
3705
|
else if (row.error !== void 0) cache.errored += 1;
|
|
1557
3706
|
}
|
|
1558
3707
|
}
|
|
1559
3708
|
return { ...summary, cache };
|
|
1560
3709
|
}
|
|
3710
|
+
function agenticProvider(config, ev, deps, cacheStrict) {
|
|
3711
|
+
if (cacheStrict)
|
|
3712
|
+
throw new RunConfigError(
|
|
3713
|
+
`Eval "${ev.id}" uses MCP server "${ev.mcp.server}": its tool loop is never cached, so --cache-strict cannot answer it`
|
|
3714
|
+
);
|
|
3715
|
+
const providerConfig = { ...config.provider, ...ev.provider };
|
|
3716
|
+
const provider = deps.resolveProvider(providerConfig);
|
|
3717
|
+
if (provider.respond === void 0)
|
|
3718
|
+
throw new RunConfigError(
|
|
3719
|
+
`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)`
|
|
3720
|
+
);
|
|
3721
|
+
if (deps.connectMcp === void 0)
|
|
3722
|
+
throw new RunConfigError(
|
|
3723
|
+
`Eval "${ev.id}" uses MCP server "${ev.mcp.server}", and this run cannot connect to one`
|
|
3724
|
+
);
|
|
3725
|
+
return provider;
|
|
3726
|
+
}
|
|
1561
3727
|
async function runOrchestration(config, options, deps) {
|
|
1562
3728
|
const noCache = options.noCache ?? false;
|
|
1563
3729
|
const cacheStrict = options.cacheStrict ?? false;
|
|
@@ -1567,6 +3733,9 @@ async function runOrchestration(config, options, deps) {
|
|
|
1567
3733
|
if (noCache && options.cacheMaxAgeMs !== void 0) {
|
|
1568
3734
|
throw new RunConfigError("--no-cache and --cache-max-age cannot be used together");
|
|
1569
3735
|
}
|
|
3736
|
+
if (options.runs !== void 0 && !(Number.isInteger(options.runs) && options.runs >= 1 && options.runs <= MAX_RUNS)) {
|
|
3737
|
+
throw new RunConfigError(`--runs must be a whole number from 1 to ${MAX_RUNS}`);
|
|
3738
|
+
}
|
|
1570
3739
|
const started = deps.now();
|
|
1571
3740
|
const dryRun = options.dryRun ?? false;
|
|
1572
3741
|
const evalResults = [];
|
|
@@ -1576,18 +3745,19 @@ async function runOrchestration(config, options, deps) {
|
|
|
1576
3745
|
for (const row of rows) {
|
|
1577
3746
|
resolvePrompt(template, row.vars);
|
|
1578
3747
|
}
|
|
1579
|
-
|
|
3748
|
+
const agentic = ev.mcp === void 0 || dryRun ? void 0 : agenticProvider(config, ev, deps, cacheStrict);
|
|
3749
|
+
return { ev, template, rows, agentic };
|
|
1580
3750
|
});
|
|
1581
|
-
for (const { ev, template, rows } of prepared) {
|
|
3751
|
+
for (const { ev, template, rows, agentic } of prepared) {
|
|
1582
3752
|
const providerConfig = { ...config.provider, ...ev.provider };
|
|
1583
|
-
const provider = deps.resolveProvider(providerConfig);
|
|
1584
|
-
const
|
|
1585
|
-
const
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
3753
|
+
const provider = agentic ?? deps.resolveProvider(providerConfig);
|
|
3754
|
+
const limit2 = options.concurrency ?? providerConfig.concurrency ?? (ev.mcp !== void 0 ? 1 : 4);
|
|
3755
|
+
const runs = options.runs ?? ev.runs ?? config.runs ?? 1;
|
|
3756
|
+
const passThreshold = ev.pass_threshold ?? config.pass_threshold ?? 1;
|
|
3757
|
+
const rowResults = await mapLimit(rows, limit2, (row) => {
|
|
3758
|
+
const params = {
|
|
1589
3759
|
template,
|
|
1590
|
-
// `defaults.assertions` apply to every eval, ahead of its own
|
|
3760
|
+
// `defaults.assertions` apply to every eval, ahead of its own.
|
|
1591
3761
|
assertions: [...config.defaults?.assertions ?? [], ...ev.assertions],
|
|
1592
3762
|
row,
|
|
1593
3763
|
providerConfig,
|
|
@@ -1599,8 +3769,18 @@ async function runOrchestration(config, options, deps) {
|
|
|
1599
3769
|
noCache,
|
|
1600
3770
|
cacheStrict,
|
|
1601
3771
|
...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {}
|
|
1602
|
-
}
|
|
1603
|
-
|
|
3772
|
+
};
|
|
3773
|
+
if (ev.mcp === void 0) return runRepeats(params, runs, passThreshold);
|
|
3774
|
+
const agentParams = {
|
|
3775
|
+
...params,
|
|
3776
|
+
server: ev.mcp.server,
|
|
3777
|
+
...ev.mcp.allowed_tools !== void 0 ? { allowedTools: ev.mcp.allowed_tools } : {},
|
|
3778
|
+
limits: mcpLimits(config, ev),
|
|
3779
|
+
// A dry run connects nowhere; the loop never calls this then.
|
|
3780
|
+
connect: deps.connectMcp ?? (() => Promise.reject(new Error("no MCP connection")))
|
|
3781
|
+
};
|
|
3782
|
+
return runRepeats(agentParams, runs, passThreshold, runAgentRow);
|
|
3783
|
+
});
|
|
1604
3784
|
const passed = rowResults.every((r) => rowStatus(r) === "passed");
|
|
1605
3785
|
evalResults.push({ id: ev.id, tags: ev.tags ?? [], rows: rowResults, passed });
|
|
1606
3786
|
if (options.bail === true && !passed) break;
|
|
@@ -1618,14 +3798,18 @@ async function runOrchestration(config, options, deps) {
|
|
|
1618
3798
|
};
|
|
1619
3799
|
}
|
|
1620
3800
|
|
|
3801
|
+
// src/orchestrator/exit-code.ts
|
|
3802
|
+
init_esm_shims();
|
|
3803
|
+
|
|
1621
3804
|
// src/orchestrator/dataset.ts
|
|
3805
|
+
init_esm_shims();
|
|
1622
3806
|
import * as fs4 from "fs";
|
|
1623
|
-
import * as
|
|
3807
|
+
import * as path5 from "path";
|
|
1624
3808
|
function loadDataset(ref, baseDir) {
|
|
1625
3809
|
if (typeof ref !== "string") {
|
|
1626
3810
|
return ref.examples;
|
|
1627
3811
|
}
|
|
1628
|
-
const content = fs4.readFileSync(
|
|
3812
|
+
const content = fs4.readFileSync(path5.resolve(baseDir, ref), "utf8");
|
|
1629
3813
|
const rows = [];
|
|
1630
3814
|
content.split(/\r?\n/).forEach((line, i) => {
|
|
1631
3815
|
if (line.trim().length === 0) return;
|
|
@@ -1635,9 +3819,9 @@ function loadDataset(ref, baseDir) {
|
|
|
1635
3819
|
} catch (err) {
|
|
1636
3820
|
throw new RunConfigError(`${ref}:${i + 1}: not valid JSON (${err.message})`);
|
|
1637
3821
|
}
|
|
1638
|
-
const vars =
|
|
1639
|
-
if (!
|
|
1640
|
-
const why =
|
|
3822
|
+
const vars = isObject2(row) ? row["vars"] : void 0;
|
|
3823
|
+
if (!isObject2(vars)) {
|
|
3824
|
+
const why = isObject2(row) && "vars" in row ? `vars: Invalid input: expected record, received ${typeName(vars)}` : 'this row has no "vars"';
|
|
1641
3825
|
throw new RunConfigError(
|
|
1642
3826
|
`${ref}:${i + 1}: a dataset row must be { "vars": { ... } }; ${why}`
|
|
1643
3827
|
);
|
|
@@ -1646,7 +3830,7 @@ function loadDataset(ref, baseDir) {
|
|
|
1646
3830
|
});
|
|
1647
3831
|
return rows;
|
|
1648
3832
|
}
|
|
1649
|
-
function
|
|
3833
|
+
function isObject2(value) {
|
|
1650
3834
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1651
3835
|
}
|
|
1652
3836
|
function typeName(value) {
|
|
@@ -1662,33 +3846,72 @@ var NOOP_CACHE = { get: () => void 0, set: () => {
|
|
|
1662
3846
|
function isMockMode(env) {
|
|
1663
3847
|
return env["PLUNE_MOCK_PROVIDER"] === "1";
|
|
1664
3848
|
}
|
|
3849
|
+
function mockScript(env) {
|
|
3850
|
+
const file = env["PLUNE_MOCK_SCRIPT"];
|
|
3851
|
+
if (file === void 0 || file === "") return void 0;
|
|
3852
|
+
let text;
|
|
3853
|
+
try {
|
|
3854
|
+
text = fs5.readFileSync(path6.resolve(file), "utf8");
|
|
3855
|
+
} catch {
|
|
3856
|
+
throw new RunConfigError(`PLUNE_MOCK_SCRIPT: cannot read ${file}`);
|
|
3857
|
+
}
|
|
3858
|
+
try {
|
|
3859
|
+
return parseMockScript(text);
|
|
3860
|
+
} catch (err) {
|
|
3861
|
+
throw new RunConfigError(`PLUNE_MOCK_SCRIPT: ${file} ${err.message}`);
|
|
3862
|
+
}
|
|
3863
|
+
}
|
|
3864
|
+
function makeMcpConnect(config, baseDir, env) {
|
|
3865
|
+
return async (name, timeoutMs) => {
|
|
3866
|
+
const server = config.mcp?.servers[name];
|
|
3867
|
+
if (server === void 0) throw new Error(`mcp.servers has no "${name}"`);
|
|
3868
|
+
const target = resolveMcpServer(server, env, baseDir);
|
|
3869
|
+
const [{ openSession: openSession2 }, { listAll: listAll2, callTool: callTool2 }] = await Promise.all([
|
|
3870
|
+
Promise.resolve().then(() => (init_session(), session_exports)),
|
|
3871
|
+
Promise.resolve().then(() => (init_tools(), tools_exports))
|
|
3872
|
+
]);
|
|
3873
|
+
const session = await openSession2({ target, timeoutMs });
|
|
3874
|
+
return {
|
|
3875
|
+
redact: session.redact,
|
|
3876
|
+
listTools: async (ms) => (await listAll2(session, "tools/list", "tools", { timeoutMs: ms })).items,
|
|
3877
|
+
callTool: (tool, args, ms) => callTool2(session, tool, ms, args),
|
|
3878
|
+
close: () => session.close()
|
|
3879
|
+
};
|
|
3880
|
+
};
|
|
3881
|
+
}
|
|
1665
3882
|
function resolveProviderFor(config, dryRun) {
|
|
1666
|
-
if (isMockMode(process.env))
|
|
3883
|
+
if (isMockMode(process.env)) {
|
|
3884
|
+
const script = mockScript(process.env);
|
|
3885
|
+
return () => makeMockProvider(script);
|
|
3886
|
+
}
|
|
1667
3887
|
if (dryRun) return (cfg) => makeEstimateProvider(cfg, config.pricing);
|
|
1668
3888
|
return (cfg) => getProvider(cfg, process.env, config.pricing);
|
|
1669
3889
|
}
|
|
1670
3890
|
function buildRealDeps(config, baseDir, dryRun) {
|
|
1671
|
-
const dir =
|
|
3891
|
+
const dir = path6.join(baseDir, ".plune");
|
|
1672
3892
|
fs5.mkdirSync(dir, { recursive: true });
|
|
1673
3893
|
return {
|
|
1674
3894
|
resolveProvider: resolveProviderFor(config, dryRun),
|
|
1675
3895
|
embedder: getDefaultEmbedder(),
|
|
1676
|
-
cache: dryRun ? NOOP_CACHE : openCache(
|
|
3896
|
+
cache: dryRun ? NOOP_CACHE : openCache(path6.join(dir, "cache.db")),
|
|
1677
3897
|
now: Date.now,
|
|
1678
3898
|
loadDataset,
|
|
1679
|
-
baseDir
|
|
3899
|
+
baseDir,
|
|
3900
|
+
connectMcp: makeMcpConnect(config, baseDir, process.env)
|
|
1680
3901
|
};
|
|
1681
3902
|
}
|
|
1682
3903
|
function persist(result, baseDir) {
|
|
1683
|
-
const dir =
|
|
3904
|
+
const dir = path6.join(baseDir, ".plune");
|
|
1684
3905
|
fs5.mkdirSync(dir, { recursive: true });
|
|
1685
|
-
fs5.writeFileSync(
|
|
3906
|
+
fs5.writeFileSync(path6.join(dir, "last-run.json"), JSON.stringify(result, null, 2));
|
|
1686
3907
|
}
|
|
1687
3908
|
async function handleRun(options, depsFactory) {
|
|
1688
3909
|
const config = await loadConfig(
|
|
1689
3910
|
options.configPath !== void 0 ? { configPath: options.configPath } : {}
|
|
1690
3911
|
);
|
|
1691
|
-
const baseDir = options.configPath !== void 0 ?
|
|
3912
|
+
const baseDir = options.configPath !== void 0 ? path6.dirname(path6.resolve(options.configPath)) : process.cwd();
|
|
3913
|
+
for (const warning of mcpSecretWarnings(config)) process.stderr.write(`warning: ${warning}
|
|
3914
|
+
`);
|
|
1692
3915
|
const factory = depsFactory ?? ((c, d) => buildRealDeps(c, d, options.dryRun));
|
|
1693
3916
|
const deps = factory(config, baseDir);
|
|
1694
3917
|
try {
|
|
@@ -1706,10 +3929,18 @@ async function handleRun(options, depsFactory) {
|
|
|
1706
3929
|
...options.noCache !== void 0 ? { noCache: options.noCache } : {},
|
|
1707
3930
|
...options.bail !== void 0 ? { bail: options.bail } : {},
|
|
1708
3931
|
...options.cacheStrict === true ? { cacheStrict: true } : {},
|
|
1709
|
-
...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {}
|
|
3932
|
+
...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {},
|
|
3933
|
+
...options.runs !== void 0 ? { runs: options.runs } : {}
|
|
1710
3934
|
},
|
|
1711
3935
|
deps
|
|
1712
3936
|
);
|
|
3937
|
+
if (options.dryRun) {
|
|
3938
|
+
const agentic = new Set(config.evals.filter((ev) => ev.mcp !== void 0).map((ev) => ev.id));
|
|
3939
|
+
if (result.evals.some((ev) => agentic.has(ev.id)))
|
|
3940
|
+
process.stderr.write(
|
|
3941
|
+
"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"
|
|
3942
|
+
);
|
|
3943
|
+
}
|
|
1713
3944
|
persist(result, baseDir);
|
|
1714
3945
|
return result;
|
|
1715
3946
|
} finally {
|
|
@@ -1718,11 +3949,13 @@ async function handleRun(options, depsFactory) {
|
|
|
1718
3949
|
}
|
|
1719
3950
|
|
|
1720
3951
|
// src/cli/commands/sync.ts
|
|
3952
|
+
init_esm_shims();
|
|
1721
3953
|
import { createHash as createHash2 } from "crypto";
|
|
1722
3954
|
import * as fs6 from "fs";
|
|
1723
|
-
import * as
|
|
3955
|
+
import * as path7 from "path";
|
|
1724
3956
|
|
|
1725
3957
|
// src/types/run-result-schema.ts
|
|
3958
|
+
init_esm_shims();
|
|
1726
3959
|
import { z as z3 } from "zod";
|
|
1727
3960
|
var RUN_RESULT_SCHEMA_VERSION = 1;
|
|
1728
3961
|
var binaryVerdictSchema = z3.object({
|
|
@@ -1747,6 +3980,11 @@ var runErrorSchema = z3.object({
|
|
|
1747
3980
|
code: z3.string(),
|
|
1748
3981
|
message: z3.string()
|
|
1749
3982
|
});
|
|
3983
|
+
var savedSchema = z3.object({
|
|
3984
|
+
input_tokens: z3.number(),
|
|
3985
|
+
output_tokens: z3.number(),
|
|
3986
|
+
cost_usd: z3.number()
|
|
3987
|
+
});
|
|
1750
3988
|
var rowResultSchema = z3.object({
|
|
1751
3989
|
vars: z3.record(z3.string(), z3.unknown()),
|
|
1752
3990
|
output: z3.string().nullable(),
|
|
@@ -1755,9 +3993,66 @@ var rowResultSchema = z3.object({
|
|
|
1755
3993
|
latency_ms: z3.number().optional(),
|
|
1756
3994
|
error: runErrorSchema.optional(),
|
|
1757
3995
|
assertions: z3.array(assertionResultRecordSchema2),
|
|
1758
|
-
cache_saved:
|
|
3996
|
+
cache_saved: savedSchema.optional(),
|
|
1759
3997
|
/** ADR 0045. Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
|
|
1760
|
-
inconclusive: z3.enum(ROW_INCONCLUSIVE).optional()
|
|
3998
|
+
inconclusive: z3.enum(ROW_INCONCLUSIVE).optional(),
|
|
3999
|
+
/** Repeats (`runs` above 1). Optional and additive — a RunResult without it validates unchanged. */
|
|
4000
|
+
attempts: z3.object({
|
|
4001
|
+
runs: z3.number(),
|
|
4002
|
+
pass_threshold: z3.number(),
|
|
4003
|
+
passed: z3.number(),
|
|
4004
|
+
failed: z3.number(),
|
|
4005
|
+
errored: z3.number(),
|
|
4006
|
+
results: z3.array(
|
|
4007
|
+
z3.object({
|
|
4008
|
+
output: z3.string().nullable(),
|
|
4009
|
+
cached: z3.boolean(),
|
|
4010
|
+
usage: usageSchema.optional(),
|
|
4011
|
+
latency_ms: z3.number().optional(),
|
|
4012
|
+
error: runErrorSchema.optional(),
|
|
4013
|
+
assertions: z3.array(assertionResultRecordSchema2),
|
|
4014
|
+
cache_saved: savedSchema.optional()
|
|
4015
|
+
})
|
|
4016
|
+
)
|
|
4017
|
+
}).optional(),
|
|
4018
|
+
/** The tool loop of an eval with an `mcp` server. Optional and additive — a RunResult without it validates unchanged. */
|
|
4019
|
+
agent: z3.object({
|
|
4020
|
+
server: z3.string(),
|
|
4021
|
+
tools: z3.array(
|
|
4022
|
+
z3.object({
|
|
4023
|
+
name: z3.string(),
|
|
4024
|
+
offered: z3.boolean(),
|
|
4025
|
+
annotations: z3.record(z3.string(), z3.unknown()).optional()
|
|
4026
|
+
})
|
|
4027
|
+
),
|
|
4028
|
+
steps: z3.array(
|
|
4029
|
+
z3.object({
|
|
4030
|
+
index: z3.number(),
|
|
4031
|
+
text: z3.string(),
|
|
4032
|
+
finish_reason: z3.string().optional(),
|
|
4033
|
+
usage: usageSchema,
|
|
4034
|
+
calls: z3.array(
|
|
4035
|
+
z3.object({
|
|
4036
|
+
id: z3.string(),
|
|
4037
|
+
name: z3.string(),
|
|
4038
|
+
args: z3.unknown(),
|
|
4039
|
+
executed: z3.boolean(),
|
|
4040
|
+
is_error: z3.boolean(),
|
|
4041
|
+
error_kind: z3.enum(["content", "protocol", "timeout", "not-offered", "bad-arguments"]).optional(),
|
|
4042
|
+
duration_ms: z3.number().optional(),
|
|
4043
|
+
result: z3.object({ text: z3.string(), bytes: z3.number(), truncated: z3.boolean() }).optional()
|
|
4044
|
+
})
|
|
4045
|
+
)
|
|
4046
|
+
})
|
|
4047
|
+
),
|
|
4048
|
+
stop: z3.object({
|
|
4049
|
+
reason: z3.enum(["complete", "limit", "error"]),
|
|
4050
|
+
limit: z3.enum(["max_steps", "max_tool_calls", "max_total_tokens", "timeout_ms", "tool_timeout_ms"]).optional()
|
|
4051
|
+
}),
|
|
4052
|
+
collection: z3.enum(["complete", "partial"]),
|
|
4053
|
+
/** Heuristic findings, never a verdict. Optional and additive. */
|
|
4054
|
+
advice: z3.array(z3.object({ type: z3.string(), reason: z3.string() })).optional()
|
|
4055
|
+
}).optional()
|
|
1761
4056
|
});
|
|
1762
4057
|
var summarySchema = z3.object({
|
|
1763
4058
|
total: z3.number(),
|
|
@@ -1797,6 +4092,7 @@ function parseRunResult(value) {
|
|
|
1797
4092
|
}
|
|
1798
4093
|
|
|
1799
4094
|
// src/cli/api-url.ts
|
|
4095
|
+
init_esm_shims();
|
|
1800
4096
|
var DEFAULT_API_URL = "https://beta-api.plune.ai";
|
|
1801
4097
|
function resolveApiUrl(explicit) {
|
|
1802
4098
|
const raw = explicit ?? process.env["PLUNE_API_URL"] ?? DEFAULT_API_URL;
|
|
@@ -1804,25 +4100,27 @@ function resolveApiUrl(explicit) {
|
|
|
1804
4100
|
}
|
|
1805
4101
|
|
|
1806
4102
|
// src/cli/credentials.ts
|
|
1807
|
-
|
|
1808
|
-
import {
|
|
1809
|
-
import {
|
|
4103
|
+
init_esm_shims();
|
|
4104
|
+
import { chmodSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync5, rmSync, writeFileSync as writeFileSync2 } from "fs";
|
|
4105
|
+
import { homedir as homedir3 } from "os";
|
|
4106
|
+
import { dirname as dirname4, join as join4 } from "path";
|
|
1810
4107
|
function credentialsFile() {
|
|
1811
|
-
const base = process.env["XDG_CONFIG_HOME"]?.trim() ||
|
|
1812
|
-
return
|
|
4108
|
+
const base = process.env["XDG_CONFIG_HOME"]?.trim() || join4(homedir3(), ".config");
|
|
4109
|
+
return join4(base, "plune", "credentials.json");
|
|
1813
4110
|
}
|
|
1814
4111
|
function loadToken() {
|
|
1815
4112
|
const fromEnv = process.env["PLUNE_TOKEN"]?.trim();
|
|
1816
4113
|
if (fromEnv !== void 0 && fromEnv !== "") return fromEnv;
|
|
1817
4114
|
try {
|
|
1818
|
-
const
|
|
1819
|
-
return typeof
|
|
4115
|
+
const parsed2 = JSON.parse(readFileSync5(credentialsFile(), "utf-8"));
|
|
4116
|
+
return typeof parsed2.token === "string" && parsed2.token.length > 0 ? parsed2.token : null;
|
|
1820
4117
|
} catch {
|
|
1821
4118
|
return null;
|
|
1822
4119
|
}
|
|
1823
4120
|
}
|
|
1824
4121
|
|
|
1825
4122
|
// src/cli/gate.ts
|
|
4123
|
+
init_esm_shims();
|
|
1826
4124
|
function gateExit(verdict, runnerCode) {
|
|
1827
4125
|
if (verdict?.statusEvent === "terminated") {
|
|
1828
4126
|
return { code: 1, line: "plune: gate failed \u2014 the run was terminated, so it has no verdict to pass on." };
|
|
@@ -1831,14 +4129,15 @@ function gateExit(verdict, runnerCode) {
|
|
|
1831
4129
|
if (counts == null) return { code: 1, line: "plune: gate failed \u2014 no verdict from the platform, and no verdict is no pass." };
|
|
1832
4130
|
const n = (status) => counts[status] ?? 0;
|
|
1833
4131
|
const notRun = verdict?.notRun?.length ?? 0;
|
|
1834
|
-
if (
|
|
1835
|
-
return { code: runnerCode, line: `plune: gate \u2014 no result reached the run, so the exit code is the command's own (${runnerCode}).` };
|
|
4132
|
+
if (notRun === 0 && Object.values(counts).every((k) => !k)) {
|
|
4133
|
+
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." };
|
|
1836
4134
|
}
|
|
1837
4135
|
const said = `${n("failed")} failed \xB7 ${n("broken")} broken \xB7 ${notRun} not run \xB7 ${n("muted")} muted`;
|
|
1838
4136
|
return n("failed") + n("broken") > 0 || notRun > 0 ? { code: 1, line: `plune: gate failed \u2014 ${said}` } : { code: 0, line: `plune: gate passed \u2014 ${said}` };
|
|
1839
4137
|
}
|
|
1840
4138
|
|
|
1841
4139
|
// src/cli/commands/job-reporter.ts
|
|
4140
|
+
init_esm_shims();
|
|
1842
4141
|
var JOB_TIMEOUT_MS = 5e3;
|
|
1843
4142
|
var JOB_SUBJECT_NAME_MAX = 200;
|
|
1844
4143
|
var JOB_REASON_MAX = 2e3;
|
|
@@ -1948,7 +4247,7 @@ var SyncHttpError = class extends Error {
|
|
|
1948
4247
|
status;
|
|
1949
4248
|
};
|
|
1950
4249
|
function readRun(cwd, file) {
|
|
1951
|
-
const target = file !== void 0 ?
|
|
4250
|
+
const target = file !== void 0 ? path7.resolve(cwd, file) : path7.join(cwd, ".plune", "last-run.json");
|
|
1952
4251
|
let raw;
|
|
1953
4252
|
try {
|
|
1954
4253
|
raw = fs6.readFileSync(target, "utf8");
|
|
@@ -1989,7 +4288,7 @@ async function handleSync(deps = {}) {
|
|
|
1989
4288
|
const idempotencyKey = createHash2("sha256").update(payload).digest("hex");
|
|
1990
4289
|
const bearer = token;
|
|
1991
4290
|
const job = new JobReporter(doFetch, apiUrl, bearer, "sync");
|
|
1992
|
-
await job.open(
|
|
4291
|
+
await job.open(path7.basename(deps.file !== void 0 ? path7.resolve(cwd, deps.file) : cwd), run.summary.total);
|
|
1993
4292
|
try {
|
|
1994
4293
|
const result = await upload();
|
|
1995
4294
|
await job.finish({ ok: true });
|
|
@@ -2051,11 +4350,13 @@ function reportSyncFailure(err, write) {
|
|
|
2051
4350
|
}
|
|
2052
4351
|
|
|
2053
4352
|
// src/cli/commands/ingest.ts
|
|
2054
|
-
|
|
4353
|
+
init_esm_shims();
|
|
4354
|
+
import * as path9 from "path";
|
|
2055
4355
|
|
|
2056
4356
|
// src/cli/commands/cairn-artifact.ts
|
|
4357
|
+
init_esm_shims();
|
|
2057
4358
|
import * as fs7 from "fs/promises";
|
|
2058
|
-
import * as
|
|
4359
|
+
import * as path8 from "path";
|
|
2059
4360
|
var SUPPORTED_ARTIFACT_VERSION = 1;
|
|
2060
4361
|
var INGEST_SCHEMA_VERSION = 1;
|
|
2061
4362
|
var NoCairnRunsError = class extends Error {
|
|
@@ -2070,9 +4371,9 @@ async function findLatestCairnRun(runsDir = "runs") {
|
|
|
2070
4371
|
let newest;
|
|
2071
4372
|
for (const entry of entries) {
|
|
2072
4373
|
if (!entry.isDirectory()) continue;
|
|
2073
|
-
const dir =
|
|
4374
|
+
const dir = path8.join(runsDir, entry.name);
|
|
2074
4375
|
try {
|
|
2075
|
-
const report = await fs7.lstat(
|
|
4376
|
+
const report = await fs7.lstat(path8.join(dir, "report.json"));
|
|
2076
4377
|
if (!report.isFile()) continue;
|
|
2077
4378
|
if (newest === void 0 || report.mtimeMs > newest.at) {
|
|
2078
4379
|
newest = { dir, at: report.mtimeMs };
|
|
@@ -2123,7 +4424,7 @@ async function readJson(file) {
|
|
|
2123
4424
|
}
|
|
2124
4425
|
}
|
|
2125
4426
|
async function defaultReadEvidence(dir) {
|
|
2126
|
-
const raw = await readJson(
|
|
4427
|
+
const raw = await readJson(path8.join(dir, "api-evidence.json"));
|
|
2127
4428
|
if (!Array.isArray(raw)) return void 0;
|
|
2128
4429
|
return raw.map((r) => {
|
|
2129
4430
|
const rec = asRecord(r);
|
|
@@ -2166,7 +4467,7 @@ function casesFromApi(report, verdicts) {
|
|
|
2166
4467
|
});
|
|
2167
4468
|
}
|
|
2168
4469
|
async function readCairnRun(dir, deps = {}) {
|
|
2169
|
-
const raw = await readJson(
|
|
4470
|
+
const raw = await readJson(path8.join(dir, "report.json"));
|
|
2170
4471
|
if (raw === void 0) throw new CairnRunNotFoundError(dir);
|
|
2171
4472
|
const report = asRecord(raw);
|
|
2172
4473
|
if (report["schemaVersion"] !== SUPPORTED_ARTIFACT_VERSION) {
|
|
@@ -2196,7 +4497,7 @@ async function readCairnRun(dir, deps = {}) {
|
|
|
2196
4497
|
return {
|
|
2197
4498
|
schemaVersion: INGEST_SCHEMA_VERSION,
|
|
2198
4499
|
run: {
|
|
2199
|
-
runId: str(report["runId"],
|
|
4500
|
+
runId: str(report["runId"], path8.basename(dir)),
|
|
2200
4501
|
mode,
|
|
2201
4502
|
target: str(report["url"], "unknown")
|
|
2202
4503
|
},
|
|
@@ -2248,7 +4549,7 @@ async function handleIngest(deps) {
|
|
|
2248
4549
|
const doFetch = deps.fetchImpl ?? fetch;
|
|
2249
4550
|
const endpoint = `${apiUrl}/v1/ingest/cairn`;
|
|
2250
4551
|
const job = new JobReporter(doFetch, apiUrl, token, "ingest");
|
|
2251
|
-
await job.open(
|
|
4552
|
+
await job.open(path9.basename(path9.resolve(dir)), payload.cases.length);
|
|
2252
4553
|
try {
|
|
2253
4554
|
const result = await upload();
|
|
2254
4555
|
await job.uploaded({ subjectId: result.runId || void 0 });
|