@plune-ai/cli 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -45,21 +45,21 @@ function machineless(raw, repoRoot, home) {
45
45
  let text = (0, import_node_util.stripVTControlCharacters)(raw).replaceAll("\x1B", "");
46
46
  const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
47
47
  if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
48
- const own = pathIn(home);
49
- if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
48
+ const own2 = pathIn(home);
49
+ if (own2 !== void 0) text = text.replace(new RegExp(`${PATH_START}${own2.source}(?![\\w.-])`, own2.flags), "~");
50
50
  if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
51
51
  return text;
52
52
  }
53
- function pathIn(path9) {
54
- const parts = path9.split(/[\\/]+/);
53
+ function pathIn(path11) {
54
+ const parts = path11.split(/[\\/]+/);
55
55
  while (parts.length > 1 && parts.at(-1) === "") parts.pop();
56
56
  if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
57
57
  const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
58
- const escaped = /^\/(?!\/)/.test(path9) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
58
+ const escaped = /^\/(?!\/)/.test(path11) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
59
59
  const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
60
60
  return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
61
61
  }
62
- var import_node_fs, import_node_os, import_node_path, import_node_util, printable, PATH_START, HEADLINE_LIMIT, ANY_HOME;
62
+ var import_node_fs, import_node_os, import_node_path, import_node_util, printable, mediaTypeOf, TEXT_TYPES, PATH_START, HEADLINE_LIMIT, ANY_HOME;
63
63
  var init_failure_detail = __esm({
64
64
  "src/reporter-core/failure-detail.ts"() {
65
65
  "use strict";
@@ -69,6 +69,8 @@ var init_failure_detail = __esm({
69
69
  import_node_path = require("path");
70
70
  import_node_util = require("util");
71
71
  printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "?");
72
+ mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
73
+ TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
72
74
  PATH_START = "(?<![\\w.~%/\\\\-])";
73
75
  HEADLINE_LIMIT = 8 * 1024;
74
76
  ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
@@ -86,9 +88,9 @@ var init_exit_codes = __esm({
86
88
  });
87
89
 
88
90
  // src/mcp-testing/connect/journal.ts
89
- function openJournal(path9, redact) {
90
- if (path9 === void 0) return NONE;
91
- const fd = (0, import_node_fs2.openSync)(path9, "w", 384);
91
+ function openJournal(path11, redact) {
92
+ if (path11 === void 0) return NONE;
93
+ const fd = (0, import_node_fs2.openSync)(path11, "w", 384);
92
94
  if (process.platform !== "win32") (0, import_node_fs2.fchmodSync)(fd, 384);
93
95
  const start = import_node_perf_hooks.performance.now();
94
96
  let closed = false;
@@ -150,8 +152,8 @@ function processTable() {
150
152
  return (0, import_node_fs3.readdirSync)("/proc").flatMap((name) => {
151
153
  if (!/^\d+$/.test(name)) return [];
152
154
  try {
153
- const stat = (0, import_node_fs3.readFileSync)(`/proc/${name}/stat`, "utf8");
154
- const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
155
+ const stat2 = (0, import_node_fs3.readFileSync)(`/proc/${name}/stat`, "utf8");
156
+ const fields = stat2.slice(stat2.lastIndexOf(")") + 2).split(" ");
155
157
  return parseProcessTable(`${name} ${fields[1]} ${fields[19]}`);
156
158
  } catch {
157
159
  return [];
@@ -382,10 +384,33 @@ var init_redact = __esm({
382
384
  var session_exports = {};
383
385
  __export(session_exports, {
384
386
  ConnectError: () => ConnectError,
387
+ STDERR_LINE_LIMIT: () => STDERR_LINE_LIMIT,
385
388
  STDIO_MESSAGE_LIMIT: () => STDIO_MESSAGE_LIMIT,
386
389
  closeAllSessions: () => closeAllSessions,
387
- openSession: () => openSession
390
+ headerValue: () => headerValue,
391
+ openSession: () => openSession,
392
+ readLines: () => readLines
388
393
  });
394
+ function headerValue(value) {
395
+ const plain = /^[\x21-\x7e]([\x20-\x7e]*[\x21-\x7e])?$/.test(value) && !/^=\?base64\?.*\?=$/.test(value);
396
+ return plain ? value : `=?base64?${Buffer.from(value, "utf8").toString("base64")}?=`;
397
+ }
398
+ function modernHeaders(body, version) {
399
+ const m = parsed(body);
400
+ if (m === null || typeof m !== "object" || Array.isArray(m)) return [];
401
+ const { method, params } = m;
402
+ if (typeof method !== "string") return [];
403
+ const meta = params?.["_meta"];
404
+ const v = meta?.["io.modelcontextprotocol/protocolVersion"];
405
+ const headers = [
406
+ ["mcp-protocol-version", typeof v === "string" ? v : version],
407
+ ["mcp-method", method]
408
+ ];
409
+ const name = method === "resources/read" ? params?.["uri"] : params?.["name"];
410
+ if (["tools/call", "resources/read", "prompts/get"].includes(method) && typeof name === "string")
411
+ headers.push(["mcp-name", headerValue(name)]);
412
+ return headers;
413
+ }
389
414
  function answers(frame, id) {
390
415
  if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
391
416
  const f = frame;
@@ -400,6 +425,40 @@ function fromEventStream(text, id) {
400
425
  }
401
426
  return void 0;
402
427
  }
428
+ function readLines(stream, onLine, stats) {
429
+ const decoder = new import_node_string_decoder.StringDecoder("utf8");
430
+ let partial = "";
431
+ const feed = (text) => {
432
+ let from = 0;
433
+ for (let nl = text.indexOf("\n", from); nl >= 0; nl = text.indexOf("\n", from)) {
434
+ const whole = partial + text.slice(from, nl);
435
+ if (stats !== void 0 && whole.length > stats.high) stats.high = whole.length;
436
+ const line = whole.slice(0, STDERR_LINE_LIMIT);
437
+ partial = "";
438
+ onLine(line.endsWith("\r") ? line.slice(0, -1) : line);
439
+ from = nl + 1;
440
+ }
441
+ const rest = partial + text.slice(from);
442
+ if (stats !== void 0 && rest.length > stats.high) stats.high = rest.length;
443
+ partial = rest.slice(0, STDERR_LINE_LIMIT);
444
+ };
445
+ return new Promise((resolve9) => {
446
+ let done = false;
447
+ const finish = () => {
448
+ if (done) return;
449
+ done = true;
450
+ feed(decoder.end());
451
+ if (partial !== "") onLine(partial.endsWith("\r") ? partial.slice(0, -1) : partial);
452
+ resolve9();
453
+ };
454
+ stream.on(
455
+ "data",
456
+ (chunk2) => feed(typeof chunk2 === "string" ? chunk2 : decoder.write(chunk2))
457
+ );
458
+ stream.once("end", finish);
459
+ stream.once("close", finish);
460
+ });
461
+ }
403
462
  function createTransport(target) {
404
463
  if (target.kind === "stdio") {
405
464
  return new import_stdio.StdioClientTransport({
@@ -465,9 +524,9 @@ function watchOverflow(transport, over) {
465
524
  const buffer = transport._readBuffer;
466
525
  const append = buffer?.append?.bind(buffer);
467
526
  if (buffer === void 0 || append === void 0) return;
468
- buffer.append = (chunk) => {
527
+ buffer.append = (chunk2) => {
469
528
  try {
470
- append(chunk);
529
+ append(chunk2);
471
530
  } catch (err) {
472
531
  over();
473
532
  throw err;
@@ -497,7 +556,7 @@ function kindOf(err, stdio, transportClosed) {
497
556
  return "network";
498
557
  return "protocol";
499
558
  }
500
- async function openSession(config) {
559
+ async function openSession(config, options = {}) {
501
560
  const { target } = config;
502
561
  const stdio = target.kind === "stdio";
503
562
  const redact = redactorFor(target);
@@ -507,10 +566,12 @@ async function openSession(config) {
507
566
  const transport = createTransport(target);
508
567
  let transportClosed = false;
509
568
  let spawnError;
569
+ const stopped = /* @__PURE__ */ new Set();
510
570
  const handshake = {
511
571
  offered: void 0,
512
572
  result: void 0
513
573
  };
574
+ const notifications = /* @__PURE__ */ new Map();
514
575
  tap(transport, journal, {
515
576
  frame: (dir, message) => {
516
577
  const m = message;
@@ -519,11 +580,18 @@ async function openSession(config) {
519
580
  handshake.offered = m.params?.protocolVersion;
520
581
  } else if (dir === "in" && handshake.id !== void 0 && m.id === handshake.id)
521
582
  handshake.result = m.result;
583
+ if (dir === "in" && m.id === void 0 && typeof m.method === "string")
584
+ notifications.set(m.method, (notifications.get(m.method) ?? 0) + 1);
585
+ },
586
+ closed: () => {
587
+ transportClosed = true;
588
+ for (const stop of [...stopped]) stop();
522
589
  },
523
- closed: () => transportClosed = true,
524
590
  error: (err) => {
525
- if (spawnError === void 0 && err.syscall?.startsWith("spawn") === true)
591
+ if (spawnError === void 0 && err.syscall?.startsWith("spawn") === true) {
526
592
  spawnError = err;
593
+ for (const stop of [...stopped]) stop();
594
+ }
527
595
  }
528
596
  });
529
597
  let noted;
@@ -535,23 +603,30 @@ async function openSession(config) {
535
603
  let tooLarge = false;
536
604
  const tail = [];
537
605
  const noise = { count: 0, first: [] };
606
+ const traffic = [];
607
+ const methods = /* @__PURE__ */ new Map();
608
+ const heard = (frame) => {
609
+ if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return;
610
+ const f = frame;
611
+ const method = "method" in f || f["id"] === void 0 ? void 0 : methods.get(f["id"]);
612
+ traffic.push(method === void 0 ? { frame: f } : { frame: f, method });
613
+ };
538
614
  const listeners = /* @__PURE__ */ new Set();
539
615
  const seen = (line, isMessage) => {
540
616
  if (!isMessage) {
541
617
  noise.count++;
542
618
  if (noise.first.length < 3) noise.first.push(clean(line).slice(0, 200));
543
619
  }
620
+ if (isMessage) heard(parsed(line));
544
621
  for (const listener of [...listeners]) listener(line);
545
622
  };
546
623
  let stderrDone = Promise.resolve();
547
624
  if (transport instanceof import_stdio.StdioClientTransport && transport.stderr !== null) {
548
- const lines = (0, import_node_readline.createInterface)({ input: transport.stderr, crlfDelay: Infinity });
549
- lines.on("line", (line) => {
625
+ stderrDone = readLines(transport.stderr, (line) => {
550
626
  journal.write("stderr", { line });
551
627
  tail.push(clean(line));
552
628
  if (tail.length > TAIL_LINES) tail.shift();
553
629
  });
554
- stderrDone = new Promise((resolve8) => lines.once("close", resolve8));
555
630
  watchStdout(transport, journal, seen);
556
631
  watchOverflow(transport, () => {
557
632
  if (tooLarge) return;
@@ -591,10 +666,19 @@ async function openSession(config) {
591
666
  };
592
667
  const untrack = track(closable);
593
668
  const client = new import_client.Client({ name: "plune", version: config.clientVersion ?? "0.0.0" });
669
+ const modern = options.modern;
670
+ if (modern !== void 0) {
671
+ transport.onmessage = () => {
672
+ };
673
+ transport.onerror = () => {
674
+ };
675
+ transport.onclose = () => {
676
+ };
677
+ }
594
678
  let timer;
595
679
  try {
596
680
  await Promise.race([
597
- client.connect(transport, { timeout: config.timeoutMs }),
681
+ modern === void 0 ? client.connect(transport, { timeout: config.timeoutMs }) : transport.start(),
598
682
  new Promise((_, reject) => {
599
683
  timer = setTimeout(
600
684
  () => reject(new import_client.SdkError(import_client.SdkErrorCode.RequestTimeout, "no answer")),
@@ -621,12 +705,12 @@ async function openSession(config) {
621
705
  server: info === void 0 ? void 0 : { name: String(info.name), version: String(info.version) },
622
706
  handshake: { offered: handshake.offered, result: handshake.result },
623
707
  stderrTail: () => [...tail],
624
- async request(method, params, options) {
708
+ async request(method, params, options2) {
625
709
  try {
626
710
  return await client.request(
627
711
  params === void 0 ? { method } : { method, params },
628
712
  AS_SENT,
629
- { timeout: options?.timeoutMs ?? config.timeoutMs }
713
+ { timeout: options2?.timeoutMs ?? config.timeoutMs }
630
714
  );
631
715
  } catch (err) {
632
716
  if (err instanceof import_client.ProtocolError)
@@ -636,7 +720,7 @@ async function openSession(config) {
636
720
  },
637
721
  fetchForOrigin(origin) {
638
722
  const allowed = new URL(origin).origin;
639
- const own = target.kind !== "stdio" && new URL(target.url).origin === allowed;
723
+ const own2 = target.kind !== "stdio" && new URL(target.url).origin === allowed;
640
724
  return async (input, init) => {
641
725
  const url = new URL(input);
642
726
  if (url.origin !== allowed)
@@ -644,36 +728,47 @@ async function openSession(config) {
644
728
  `fetchForOrigin(${allowed}) refuses a request to another origin, ${url.origin}.`
645
729
  );
646
730
  const headers = new Headers(init?.headers);
647
- if (own) {
731
+ if (own2) {
648
732
  for (const [name, value] of Object.entries(target.headers))
649
733
  if (!headers.has(name)) headers.set(name, value);
650
734
  }
651
735
  return fetch(url, { ...init, headers, redirect: "manual" });
652
736
  };
653
737
  },
654
- async raw(body, id, options) {
655
- const ms = options?.timeoutMs ?? config.timeoutMs;
738
+ async raw(body, id, options2) {
739
+ const ms = options2?.timeoutMs ?? config.timeoutMs;
656
740
  if (target.kind === "sse")
657
741
  throw new ConnectError("protocol", "Messages of its own go over stdio and Streamable HTTP only, not HTTP+SSE.", []);
658
742
  journal.write("out", { raw: body });
659
743
  const noAnswer = () => new ConnectError("timeout", `${LEAD.timeout[0]}.`, [...tail]);
744
+ const sent = parsed(body);
745
+ if (typeof sent?.method === "string" && sent.id !== void 0) methods.set(sent.id, sent.method);
660
746
  if (target.kind === "stdio") {
661
747
  const stdin = transport._process?.stdin;
662
748
  if (stdin === null || stdin === void 0 || stdin.writableEnded)
663
- throw new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
664
- return new Promise((resolve8, reject) => {
665
- const timer2 = setTimeout(() => {
749
+ throw spawnError !== void 0 ? await toConnectError(spawnError) : new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
750
+ return new Promise((resolve9, reject) => {
751
+ const done = () => {
752
+ clearTimeout(timer2);
666
753
  listeners.delete(listener);
754
+ stopped.delete(stop);
755
+ };
756
+ const timer2 = setTimeout(() => {
757
+ done();
667
758
  reject(noAnswer());
668
759
  }, ms);
669
760
  const listener = (line) => {
670
761
  const frame2 = parsed(line);
671
762
  if (!answers(frame2, id)) return;
672
- clearTimeout(timer2);
673
- listeners.delete(listener);
674
- resolve8({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
763
+ done();
764
+ resolve9({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
765
+ };
766
+ const stop = () => {
767
+ done();
768
+ void toConnectError(spawnError ?? new Error("closed")).then(reject);
675
769
  };
676
770
  listeners.add(listener);
771
+ stopped.add(stop);
677
772
  stdin.write(`${body}
678
773
  `);
679
774
  });
@@ -684,6 +779,11 @@ async function openSession(config) {
684
779
  headers.set("accept", "application/json, text/event-stream");
685
780
  if (state.sessionId !== void 0) headers.set("mcp-session-id", state.sessionId);
686
781
  if (state._protocolVersion !== void 0) headers.set("mcp-protocol-version", state._protocolVersion);
782
+ if (modern !== void 0) for (const [name, value] of modernHeaders(body, modern.version)) headers.set(name, value);
783
+ for (const [name, value] of options2?.headers ?? []) {
784
+ if (value === null) headers.delete(name);
785
+ else headers.set(name, value);
786
+ }
687
787
  const lost = async (err) => err?.name === "TimeoutError" ? noAnswer() : toConnectError(err);
688
788
  let text = "";
689
789
  let frame;
@@ -715,22 +815,36 @@ async function openSession(config) {
715
815
  const whole = parsed(text);
716
816
  if (whole !== null && typeof whole === "object" && !Array.isArray(whole))
717
817
  frame = whole;
718
- }
818
+ heard(frame);
819
+ } else
820
+ for (const line of text.split(/\r?\n/)) if (line.startsWith("data:")) heard(parsed(line.slice(5).trim()));
719
821
  } catch (err) {
720
822
  throw await lost(err);
721
823
  }
722
- journal.write("in", frame !== void 0 ? { frame } : { status, raw: text.slice(0, RAW_TEXT) });
824
+ journal.write("in", frame !== void 0 ? { frame } : { status, raw: clean(text).slice(0, RAW_TEXT) });
723
825
  return { frame, status, text: clean(text).slice(0, RAW_TEXT) };
724
826
  },
827
+ async notify(body) {
828
+ if (target.kind !== "stdio")
829
+ throw new ConnectError("protocol", "notify is for a stdio server.", []);
830
+ const stdin = transport._process?.stdin;
831
+ if (stdin === null || stdin === void 0 || stdin.writableEnded)
832
+ throw spawnError !== void 0 ? await toConnectError(spawnError) : new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
833
+ journal.write("out", { raw: body });
834
+ stdin.write(`${body}
835
+ `);
836
+ },
837
+ traffic: () => traffic,
725
838
  stdoutNoise: () => ({ count: noise.count, first: [...noise.first] }),
839
+ notified: (method) => notifications.get(method) ?? 0,
726
840
  async endInput(waitMs) {
727
841
  const proc = transport._process;
728
842
  if (proc === void 0) return true;
729
843
  if (proc.exitCode !== null || proc.signalCode !== null) return true;
730
- const exited = new Promise((resolve8) => proc.once("exit", () => resolve8(true)));
844
+ const exited = new Promise((resolve9) => proc.once("exit", () => resolve9(true)));
731
845
  proc.stdin?.end();
732
846
  let timer2;
733
- const late = new Promise((resolve8) => timer2 = setTimeout(() => resolve8(false), waitMs));
847
+ const late = new Promise((resolve9) => timer2 = setTimeout(() => resolve9(false), waitMs));
734
848
  const result = await Promise.race([exited, late]);
735
849
  clearTimeout(timer2);
736
850
  return result;
@@ -738,12 +852,13 @@ async function openSession(config) {
738
852
  close: closable.close
739
853
  };
740
854
  }
741
- var import_node_os2, import_node_readline, import_client, import_stdio, ConnectError, RAW_TEXT, parsed, TAIL_LINES, STDIO_MESSAGE_LIMIT, AS_SENT, firstLine, LEAD;
855
+ var import_node_os2, import_node_string_decoder, import_node_readline, import_client, import_stdio, ConnectError, RAW_TEXT, parsed, TAIL_LINES, STDERR_LINE_LIMIT, STDIO_MESSAGE_LIMIT, AS_SENT, firstLine, LEAD;
742
856
  var init_session = __esm({
743
857
  "src/mcp-testing/connect/session.ts"() {
744
858
  "use strict";
745
859
  init_cjs_shims();
746
860
  import_node_os2 = require("os");
861
+ import_node_string_decoder = require("string_decoder");
747
862
  import_node_readline = require("readline");
748
863
  import_client = require("@modelcontextprotocol/client");
749
864
  import_stdio = require("@modelcontextprotocol/client/stdio");
@@ -773,6 +888,7 @@ var init_session = __esm({
773
888
  }
774
889
  };
775
890
  TAIL_LINES = 20;
891
+ STDERR_LINE_LIMIT = 64 * 1024;
776
892
  STDIO_MESSAGE_LIMIT = 10 * 1024 * 1024;
777
893
  AS_SENT = {
778
894
  "~standard": { version: 1, vendor: "plune", validate: (value) => ({ value }) }
@@ -852,10 +968,10 @@ async function listAll(session, method, key, opts = {}) {
852
968
  cursor === void 0 ? void 0 : { cursor },
853
969
  opts.timeoutMs === void 0 ? {} : { timeoutMs: opts.timeoutMs }
854
970
  );
855
- const listed = isRecord3(page) ? page[key] : void 0;
971
+ const listed = isRecord5(page) ? page[key] : void 0;
856
972
  if (Array.isArray(listed)) for (const item of listed) items.push(item);
857
973
  else malformed = true;
858
- cursor = isRecord3(page) && typeof page.nextCursor === "string" && page.nextCursor !== "" ? page.nextCursor : void 0;
974
+ cursor = isRecord5(page) && typeof page.nextCursor === "string" && page.nextCursor !== "" ? page.nextCursor : void 0;
859
975
  if (cursor === void 0) return { items, pages, complete: true, malformed };
860
976
  }
861
977
  return { items, pages: MAX_PAGES, complete: false, malformed };
@@ -864,12 +980,12 @@ function asTools(items) {
864
980
  const tools = [];
865
981
  const unnamed = /* @__PURE__ */ new Map();
866
982
  for (const t of items) {
867
- const name = isRecord3(t) ? t.name : void 0;
983
+ const name = isRecord5(t) ? t.name : void 0;
868
984
  if (typeof name === "string" && name !== "") {
869
985
  tools.push(t);
870
986
  continue;
871
987
  }
872
- const tool = { ...isRecord3(t) ? t : {}, name: "" };
988
+ const tool = { ...isRecord5(t) ? t : {}, name: "" };
873
989
  unnamed.set(tool, name === void 0 ? "(no name)" : String(JSON.stringify(name)));
874
990
  tools.push(tool);
875
991
  }
@@ -887,9 +1003,9 @@ function callableTools(tools, unnamed, opts = {}) {
887
1003
  refused.push({ tool: t.name, reason: "duplicate-name" });
888
1004
  else candidates.push(t);
889
1005
  }
890
- const { safe, skipped } = selectSafeTools(candidates, opts);
1006
+ const { safe: safe2, skipped } = selectSafeTools(candidates, opts);
891
1007
  return {
892
- safe,
1008
+ safe: safe2,
893
1009
  skipped: [...refused, ...skipped.map((s) => ({ tool: s.tool.name, reason: s.reason }))]
894
1010
  };
895
1011
  }
@@ -906,7 +1022,7 @@ async function callTool(session, name, timeoutMs, args = {}) {
906
1022
  throw err;
907
1023
  }
908
1024
  }
909
- var import_client2, MAX_PAGES, isRecord3;
1025
+ var import_client2, MAX_PAGES, isRecord5;
910
1026
  var init_tools = __esm({
911
1027
  "src/mcp-testing/connect/tools.ts"() {
912
1028
  "use strict";
@@ -915,7 +1031,7 @@ var init_tools = __esm({
915
1031
  init_safe_tools();
916
1032
  init_session();
917
1033
  MAX_PAGES = 100;
918
- isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1034
+ isRecord5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
919
1035
  }
920
1036
  });
921
1037
 
@@ -959,24 +1075,6 @@ var import_yaml = require("yaml");
959
1075
 
960
1076
  // src/config/env-overrides.ts
961
1077
  init_cjs_shims();
962
- function applyEnvOverrides(config, env) {
963
- const result = structuredClone(config);
964
- if (env["PLUNE_PROVIDER"] !== void 0) {
965
- result.provider.type = env["PLUNE_PROVIDER"];
966
- }
967
- if (env["PLUNE_MODEL"] !== void 0) {
968
- result.provider.model = env["PLUNE_MODEL"];
969
- }
970
- if (env["PLUNE_TIMEOUT"] !== void 0) {
971
- const n = Number(env["PLUNE_TIMEOUT"]);
972
- if (!isNaN(n)) result.provider.timeout = n;
973
- }
974
- if (env["PLUNE_MAX_RETRIES"] !== void 0) {
975
- const n = Number(env["PLUNE_MAX_RETRIES"]);
976
- if (!isNaN(n)) result.provider.max_retries = n;
977
- }
978
- return result;
979
- }
980
1078
 
981
1079
  // src/config/errors.ts
982
1080
  init_cjs_shims();
@@ -1004,6 +1102,34 @@ var ConfigValidationError = class extends Error {
1004
1102
  }
1005
1103
  };
1006
1104
 
1105
+ // src/config/env-overrides.ts
1106
+ function applyEnvOverrides(config, env) {
1107
+ const result = structuredClone(config);
1108
+ const all = result.providers ?? [result.provider];
1109
+ if (result.providers !== void 0) {
1110
+ for (const name of ["PLUNE_PROVIDER", "PLUNE_MODEL"])
1111
+ if (env[name] !== void 0)
1112
+ throw new ConfigValidationError("Config validation failed", [
1113
+ `${name} sets one model, but the config lists ${result.providers.length}: remove it or list a single model`
1114
+ ]);
1115
+ }
1116
+ if (env["PLUNE_PROVIDER"] !== void 0) {
1117
+ result.provider.type = env["PLUNE_PROVIDER"];
1118
+ }
1119
+ if (env["PLUNE_MODEL"] !== void 0) {
1120
+ result.provider.model = env["PLUNE_MODEL"];
1121
+ }
1122
+ if (env["PLUNE_TIMEOUT"] !== void 0) {
1123
+ const n = Number(env["PLUNE_TIMEOUT"]);
1124
+ if (!isNaN(n)) for (const p of all) p.timeout = n;
1125
+ }
1126
+ if (env["PLUNE_MAX_RETRIES"] !== void 0) {
1127
+ const n = Number(env["PLUNE_MAX_RETRIES"]);
1128
+ if (!isNaN(n)) for (const p of all) p.max_retries = n;
1129
+ }
1130
+ return result;
1131
+ }
1132
+
1007
1133
  // src/config/discover.ts
1008
1134
  init_cjs_shims();
1009
1135
  var fs = __toESM(require("fs"), 1);
@@ -1142,6 +1268,13 @@ var providerConfigSchema = import_zod.z.object({
1142
1268
  // The values the OpenAI SDK's Chat Completions `reasoning_effort` accepts; only `openai` sends it.
1143
1269
  reasoning_effort: import_zod.z.enum(["none", "minimal", "low", "medium", "high", "xhigh"]).optional()
1144
1270
  });
1271
+ var providerListSchema = import_zod.z.array(providerConfigSchema).min(1);
1272
+ var providerField = import_zod.z.any().transform((value, ctx) => {
1273
+ const r = (Array.isArray(value) ? providerListSchema : providerConfigSchema).safeParse(value);
1274
+ if (r.success) return r.data;
1275
+ for (const issue of r.error.issues) ctx.addIssue({ code: "custom", message: issue.message, path: issue.path });
1276
+ return import_zod.z.NEVER;
1277
+ });
1145
1278
  var modelPriceSchema = import_zod.z.object({
1146
1279
  input_per_1k_usd: import_zod.z.number().nonnegative(),
1147
1280
  output_per_1k_usd: import_zod.z.number().nonnegative()
@@ -1331,7 +1464,8 @@ var evalConfigSchema = import_zod.z.object({
1331
1464
  );
1332
1465
  var pluneConfigSchema = import_zod.z.object({
1333
1466
  version: import_zod.z.literal(1),
1334
- provider: providerConfigSchema,
1467
+ // One object, or a non-empty list of models to run every eval against (a one-element list is the object).
1468
+ provider: providerField,
1335
1469
  defaults: import_zod.z.object({ assertions: import_zod.z.array(assertionConfigSchema).optional() }).optional(),
1336
1470
  pricing: pricingSchema.optional(),
1337
1471
  ...evalRepeatsShape,
@@ -1339,14 +1473,42 @@ var pluneConfigSchema = import_zod.z.object({
1339
1473
  mcp: mcpRootSchema.optional(),
1340
1474
  evals: import_zod.z.array(evalConfigSchema).min(1)
1341
1475
  }).strict().superRefine((config, ctx) => {
1476
+ if (Array.isArray(config.provider)) {
1477
+ const pairs = /* @__PURE__ */ new Set();
1478
+ const byModel = /* @__PURE__ */ new Map();
1479
+ config.provider.forEach((p, i) => {
1480
+ const pair = `${p.type}/${p.model}`;
1481
+ if (pairs.has(pair))
1482
+ ctx.addIssue({ code: "custom", path: ["provider", i], message: `provider "${pair}" is listed twice` });
1483
+ pairs.add(pair);
1484
+ const other = byModel.get(p.model);
1485
+ if (other !== void 0 && other !== p.type)
1486
+ ctx.addIssue({
1487
+ code: "custom",
1488
+ path: ["provider", i, "model"],
1489
+ message: `model "${p.model}" is listed under ${other} and ${p.type}: cell ids are built from the model name`
1490
+ });
1491
+ byModel.set(p.model, p.type);
1492
+ });
1493
+ if (config.provider.length > 1)
1494
+ config.evals.forEach((ev, i) => {
1495
+ for (const key of ["type", "model"])
1496
+ if (ev.provider?.[key] !== void 0)
1497
+ ctx.addIssue({
1498
+ code: "custom",
1499
+ path: ["evals", i, "provider", key],
1500
+ message: `eval "${ev.id}" sets provider.${key}, but the root provider lists several models: the models come from the root list`
1501
+ });
1502
+ });
1503
+ }
1342
1504
  config.evals.forEach((evalConfig, i) => {
1343
1505
  const server = evalConfig.mcp?.server;
1344
1506
  if (server === void 0) {
1345
- const misplaced = (assertions, path9) => assertions.forEach((a, j) => {
1507
+ const misplaced = (assertions, path11) => assertions.forEach((a, j) => {
1346
1508
  if (TOOL_CALL_TYPES.has(a.type))
1347
1509
  ctx.addIssue({
1348
1510
  code: "custom",
1349
- path: [...path9, j, "type"],
1511
+ path: [...path11, j, "type"],
1350
1512
  message: `"${a.type}" reads the tool calls of an eval with mcp, and eval "${evalConfig.id}" has no mcp block`
1351
1513
  });
1352
1514
  });
@@ -1361,6 +1523,10 @@ var pluneConfigSchema = import_zod.z.object({
1361
1523
  message: `eval "${evalConfig.id}" uses MCP server "${server}", which mcp.servers does not define`
1362
1524
  });
1363
1525
  });
1526
+ }).transform(({ provider, ...rest }) => {
1527
+ if (!Array.isArray(provider)) return { provider, ...rest };
1528
+ const [first, ...others] = provider;
1529
+ return others.length === 0 ? { provider: first, ...rest } : { provider: first, providers: provider, ...rest };
1364
1530
  });
1365
1531
 
1366
1532
  // src/config/loader.ts
@@ -1398,6 +1564,16 @@ async function loadConfig(opts = {}) {
1398
1564
  return applyEnvOverrides(config, env);
1399
1565
  }
1400
1566
 
1567
+ // src/config/model-matrix.ts
1568
+ init_cjs_shims();
1569
+ function selfJudgeWarnings(config) {
1570
+ if ((config.providers?.length ?? 0) < 2) return [];
1571
+ const inherited = (config.defaults?.assertions ?? []).some((a) => a.type === "llm-judge" && a.provider === void 0);
1572
+ return config.evals.filter((ev) => inherited || ev.assertions.some((a) => a.type === "llm-judge" && a.provider === void 0)).map(
1573
+ (ev) => `eval "${ev.id}" has an llm-judge check without a provider: with several models each model judges its own answer, which favours it. Set provider on the check to name one judge for all`
1574
+ );
1575
+ }
1576
+
1401
1577
  // src/providers/index.ts
1402
1578
  init_cjs_shims();
1403
1579
 
@@ -1501,7 +1677,7 @@ function normalizeProviderError(err, secret, envVar) {
1501
1677
  }
1502
1678
 
1503
1679
  // src/providers/retry.ts
1504
- var defaultSleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
1680
+ var defaultSleep = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
1505
1681
  function retryAfterMs(err) {
1506
1682
  if (typeof err !== "object" || err === null || !("headers" in err)) return void 0;
1507
1683
  const raw = readHeader(err.headers, "retry-after");
@@ -1523,7 +1699,7 @@ function readHeader(headers, name) {
1523
1699
  return typeof v === "string" || typeof v === "number" ? v : void 0;
1524
1700
  }
1525
1701
  async function withRetry(fn, options) {
1526
- const { base_delay_ms = 500, sleep = defaultSleep, random = Math.random } = options;
1702
+ const { base_delay_ms = 500, sleep: sleep2 = defaultSleep, random = Math.random } = options;
1527
1703
  const maxRetries = Math.max(0, Math.floor(options.max_retries));
1528
1704
  let attempt = 0;
1529
1705
  for (; ; ) {
@@ -1539,7 +1715,7 @@ async function withRetry(fn, options) {
1539
1715
  const backoff = base_delay_ms * 2 ** attempt;
1540
1716
  const jitter = backoff * 0.1 * random();
1541
1717
  const delay = Math.max(backoff + jitter, retryAfterMs(err) ?? 0);
1542
- await sleep(delay);
1718
+ await sleep2(delay);
1543
1719
  attempt += 1;
1544
1720
  }
1545
1721
  }
@@ -1955,6 +2131,13 @@ function makeEstimateProvider(config, pricing) {
1955
2131
 
1956
2132
  // src/providers/mock.ts
1957
2133
  init_cjs_shims();
2134
+ function picked(pick, tools) {
2135
+ const words = pick.toLowerCase().split(/\s+/).filter(Boolean);
2136
+ const hits = tools.filter(
2137
+ (t) => words.every((w) => (t.description ?? "").toLowerCase().includes(w))
2138
+ );
2139
+ return hits.length === 1 ? hits[0].name : void 0;
2140
+ }
1958
2141
  var USAGE = { input_tokens: 10, output_tokens: 5 };
1959
2142
  function parseMockScript(text) {
1960
2143
  let parsed2;
@@ -1969,7 +2152,7 @@ function parseMockScript(text) {
1969
2152
  if (t !== void 0 && typeof t !== "string") return false;
1970
2153
  if (calls === void 0) return true;
1971
2154
  return Array.isArray(calls) && calls.every(
1972
- (c) => typeof c === "object" && c !== null && typeof c.name === "string"
2155
+ (c) => typeof c === "object" && c !== null && (typeof c.name === "string" || typeof c.pick === "string")
1973
2156
  );
1974
2157
  };
1975
2158
  if (!Array.isArray(parsed2) || parsed2.length === 0 || !parsed2.every(isStep))
@@ -1988,14 +2171,13 @@ function makeMockProvider(script) {
1988
2171
  respond: (req) => {
1989
2172
  const step = req.messages.filter((m) => m.role === "assistant").length;
1990
2173
  const entry = script[Math.min(step, script.length - 1)];
1991
- const calls = entry.tool_calls ?? [];
2174
+ const calls = (entry.tool_calls ?? []).flatMap((c) => {
2175
+ const name = "name" in c ? c.name : picked(c.pick, req.tools);
2176
+ return name === void 0 ? [] : [{ name, args: c.args ?? {} }];
2177
+ });
1992
2178
  return Promise.resolve({
1993
2179
  text: entry.text ?? "",
1994
- tool_calls: calls.map((c, i) => ({
1995
- id: `call_${step}_${i}`,
1996
- name: c.name,
1997
- args: c.args ?? {}
1998
- })),
2180
+ tool_calls: calls.map((c, i) => ({ id: `call_${step}_${i}`, ...c })),
1999
2181
  usage: USAGE,
2000
2182
  finish_reason: calls.length > 0 ? "tool_calls" : "stop"
2001
2183
  });
@@ -2044,7 +2226,7 @@ var XenovaEmbedder = class {
2044
2226
  throw new Error(
2045
2227
  "The `semantic-similarity` and RAG assertions need local embeddings, which ship separately: install @huggingface/transformers to enable them. Every other assertion works without it."
2046
2228
  );
2047
- }).then(({ pipeline }) => pipeline("feature-extraction", MODEL_ID));
2229
+ }).then(({ pipeline: pipeline2 }) => pipeline2("feature-extraction", MODEL_ID));
2048
2230
  return this.extractor;
2049
2231
  }
2050
2232
  };
@@ -2357,6 +2539,14 @@ init_cjs_shims();
2357
2539
  // src/assertions/interpolate.ts
2358
2540
  init_cjs_shims();
2359
2541
  var PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/g;
2542
+ var EXPECTED = /\{\{\s*expected\s*\}\}/;
2543
+ function usesExpected(params) {
2544
+ if (typeof params === "string") return EXPECTED.test(params);
2545
+ if (Array.isArray(params)) return params.some(usesExpected);
2546
+ if (params !== null && typeof params === "object")
2547
+ return Object.values(params).some(usesExpected);
2548
+ return false;
2549
+ }
2360
2550
  function interpolate(template, ctx) {
2361
2551
  return template.replace(PLACEHOLDER, (match, key) => {
2362
2552
  if (key === "expected") {
@@ -2700,10 +2890,10 @@ function checkNames(type, t, names) {
2700
2890
  const offered = t.tools.filter((x) => x.offered).map((x) => x.name);
2701
2891
  const unknown = names.find((n) => n !== void 0 && !offered.includes(n));
2702
2892
  if (unknown === void 0) return;
2703
- const list = offered.length > 0 ? offered.join(", ") : "(none)";
2893
+ const list2 = offered.length > 0 ? offered.join(", ") : "(none)";
2704
2894
  throw new AssertionRunError(
2705
2895
  "ASSERTION_UNKNOWN_TOOL",
2706
- `${type}: no tool "${unknown}" was offered to the model; offered: ${list}.${AFTER}`
2896
+ `${type}: no tool "${unknown}" was offered to the model; offered: ${list2}.${AFTER}`
2707
2897
  );
2708
2898
  }
2709
2899
  function absence(type, t, what, reads) {
@@ -2798,6 +2988,38 @@ var onlyTools = check((ctx) => {
2798
2988
 
2799
2989
  // src/assertions/tool-calls/order.ts
2800
2990
  init_cjs_shims();
2991
+
2992
+ // src/util/tool-calls.ts
2993
+ init_cjs_shims();
2994
+ var PAGINATION_KEYS = [
2995
+ "cursor",
2996
+ "page",
2997
+ "offset",
2998
+ "limit",
2999
+ "after",
3000
+ "before",
3001
+ "start",
3002
+ "pageToken",
3003
+ "page_token",
3004
+ "nextCursor",
3005
+ "next_cursor"
3006
+ ];
3007
+ var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3008
+ function sameValue(a, b) {
3009
+ return a !== void 0 && b !== void 0 && canonicalJson(a) === canonicalJson(b);
3010
+ }
3011
+ function withoutPagination(args) {
3012
+ if (!isRecord2(args)) return args;
3013
+ return Object.fromEntries(Object.entries(args).filter(([k]) => !PAGINATION_KEYS.includes(k)));
3014
+ }
3015
+ function isIdenticalCall(a, b) {
3016
+ return a.name === b.name && sameValue(a.args, b.args);
3017
+ }
3018
+ function isPageTurn(a, b) {
3019
+ return a.name === b.name && !isIdenticalCall(a, b) && sameValue(withoutPagination(a.args), withoutPagination(b.args));
3020
+ }
3021
+
3022
+ // src/assertions/tool-calls/order.ts
2801
3023
  function inOrder(names, tools) {
2802
3024
  let next = 0;
2803
3025
  for (const n of names) if (n === tools[next]) next++;
@@ -2835,7 +3057,7 @@ var noRepeatedCall = check((ctx) => {
2835
3057
  for (let i = 1; i < calls.length; i++) {
2836
3058
  const [prev, cur] = [calls[i - 1], calls[i]];
2837
3059
  if (tool !== void 0 && cur.call.name !== tool) continue;
2838
- if (prev.call.name === cur.call.name && sameJson(prev.call.args, cur.call.args))
3060
+ if (isIdenticalCall(prev.call, cur.call))
2839
3061
  return fail(
2840
3062
  `expected no call repeated right after itself; got ${describeCall(prev)} then ${describeCall(cur)}; check whether the first answer told the model what it needed`
2841
3063
  );
@@ -3167,9 +3389,9 @@ var testCaseBaseSchema = import_zod2.z.object({
3167
3389
  schemaVersion: import_zod2.z.literal(TEST_CASE_SCHEMA_VERSION),
3168
3390
  id: import_zod2.z.string().min(1),
3169
3391
  externalKeys: import_zod2.z.array(externalKeySchema).optional(),
3170
- /** ADR 0045 / plune#1246 — optional, purely additive; schemaVersion stays 2. */
3392
+ /** Optional, purely additive; schemaVersion stays 2. */
3171
3393
  is_flaky: import_zod2.z.boolean().optional(),
3172
- /** ADR 0045 / plune#1246 — optional, purely additive; schemaVersion stays 2. */
3394
+ /** Optional, purely additive; schemaVersion stays 2. */
3173
3395
  is_muted: import_zod2.z.boolean().optional()
3174
3396
  });
3175
3397
  var testCaseSchema = import_zod2.z.discriminatedUnion("type", [
@@ -3215,6 +3437,159 @@ function wireNames(names) {
3215
3437
  return { toWire, toServer };
3216
3438
  }
3217
3439
 
3440
+ // src/orchestrator/friction.ts
3441
+ init_cjs_shims();
3442
+ var SCAN_DEPTH = 6;
3443
+ var SCAN_ITEMS = 50;
3444
+ var MAX_PATHS = 10;
3445
+ var MAX_PATH = 120;
3446
+ var MIN_VALUE = 6;
3447
+ var WORDS = "id|ids|key|uuid|slug|number|ref|identifier";
3448
+ var WHOLE = new RegExp(`^(?:${WORDS})$`, "i");
3449
+ var SNAKE = new RegExp(`_(?:${WORDS})$`, "i");
3450
+ var CAMEL = /[a-z0-9](?:Id|Ids|Uuid|Key|Slug|Number|Ref|Identifier)$/;
3451
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3452
+ var isIdKey = (key) => WHOLE.test(key) || SNAKE.test(key) || CAMEL.test(key);
3453
+ var isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3454
+ var isScalar = (v) => typeof v === "string" && v !== "" || typeof v === "number" && Number.isFinite(v);
3455
+ var EMAIL = /@/;
3456
+ function segment(key) {
3457
+ const plain = /^[A-Za-z_][\w-]*$/.test(key) && key.length <= 40 && !UUID.test(key) && !EMAIL.test(key);
3458
+ return plain ? key : "*";
3459
+ }
3460
+ var cap = (path11) => path11.length > MAX_PATH ? path11.slice(0, MAX_PATH) : path11;
3461
+ var hashOf = (v) => sha256(v).slice(0, 16);
3462
+ function noteValue(out, v, at) {
3463
+ if (typeof v !== "string" || v.length < MIN_VALUE) return;
3464
+ const h = hashOf(v);
3465
+ const where = out.values.get(h) ?? /* @__PURE__ */ new Set();
3466
+ where.add(at);
3467
+ out.values.set(h, where);
3468
+ }
3469
+ function walk(value, path11, depth, out) {
3470
+ if (depth > SCAN_DEPTH) return;
3471
+ if (typeof value === "string" && UUID.test(value)) {
3472
+ const at = cap(path11 === "" ? "(root)" : path11);
3473
+ out.paths.add(at);
3474
+ noteValue(out, value, at);
3475
+ }
3476
+ if (Array.isArray(value)) {
3477
+ for (const item of value.slice(0, SCAN_ITEMS)) walk(item, `${path11}[]`, depth + 1, out);
3478
+ return;
3479
+ }
3480
+ if (!isRecord3(value)) return;
3481
+ for (const [key, v] of Object.entries(value)) {
3482
+ const at = cap(path11 === "" ? segment(key) : `${path11}.${segment(key)}`);
3483
+ if (isIdKey(key) && (isScalar(v) || Array.isArray(v) && v.length > 0 && v.every(isScalar))) {
3484
+ out.paths.add(at);
3485
+ for (const x of Array.isArray(v) ? v : [v]) noteValue(out, x, at);
3486
+ }
3487
+ walk(v, at, depth + 1, out);
3488
+ }
3489
+ }
3490
+ function scanIds(result) {
3491
+ const found = { paths: /* @__PURE__ */ new Set(), values: /* @__PURE__ */ new Map() };
3492
+ let readable = false;
3493
+ if (isRecord3(result)) {
3494
+ if (result.structuredContent !== void 0) {
3495
+ readable = true;
3496
+ walk(result.structuredContent, "", 0, found);
3497
+ }
3498
+ if (Array.isArray(result.content))
3499
+ for (const block of result.content) {
3500
+ if (!isRecord3(block) || block.type !== "text" || typeof block.text !== "string") continue;
3501
+ try {
3502
+ walk(JSON.parse(block.text), "", 0, found);
3503
+ readable = true;
3504
+ } catch {
3505
+ }
3506
+ }
3507
+ }
3508
+ if (!readable) return { unreadable: "the answer is not JSON" };
3509
+ return {
3510
+ paths: [...found.paths].sort().slice(0, MAX_PATHS),
3511
+ values: [...found.values].map(([hash, at]) => ({ hash, paths: [...at].sort() }))
3512
+ };
3513
+ }
3514
+ var list = (steps) => steps.join(", ");
3515
+ function frictionAdvice(calls) {
3516
+ const acc = /* @__PURE__ */ new Map();
3517
+ const add = (type, tool, steps, paths = [], note) => {
3518
+ const key = `${type}\0${tool}`;
3519
+ let a = acc.get(key);
3520
+ if (a === void 0) {
3521
+ a = { type, tool, steps: /* @__PURE__ */ new Set(), count: 0, paths: /* @__PURE__ */ new Set(), note };
3522
+ acc.set(key, a);
3523
+ }
3524
+ steps.forEach((s) => a.steps.add(s));
3525
+ paths.forEach((p) => a.paths.add(p));
3526
+ a.count++;
3527
+ };
3528
+ const sent = calls.filter((c) => c.executed);
3529
+ for (let j = 1; j < sent.length; j++) {
3530
+ const [prev, cur] = [sent[j - 1], sent[j]];
3531
+ if (isIdenticalCall(prev, cur)) add("identical-retry", cur.name, [prev.step, cur.step]);
3532
+ else if (isPageTurn(prev, cur)) add("pagination-continuation", cur.name, [prev.step, cur.step]);
3533
+ }
3534
+ for (const [j, cur] of sent.entries()) {
3535
+ if (cur.is_error) continue;
3536
+ const before = sent.slice(0, j).filter(
3537
+ (e) => e.step < cur.step && e.name === cur.name && !e.is_error && // The same arguments, or a page turn, is another signal and not a search after an identifier.
3538
+ !isIdenticalCall(e, cur) && !isPageTurn(e, cur)
3539
+ );
3540
+ if (before.length === 0) continue;
3541
+ const scans = [cur, ...before].map((c) => c.ids);
3542
+ const unread = scans.some((x) => x === void 0 || "unreadable" in x);
3543
+ if (unread || cur.ids === void 0 || "unreadable" in cur.ids) {
3544
+ const named = scans.find((x) => x !== void 0 && "unreadable" in x);
3545
+ const why = named !== void 0 && "unreadable" in named ? named.unreadable : "no answer was kept";
3546
+ add("friction-unmeasured", cur.name, [...before.map((e) => e.step), cur.step], [], why);
3547
+ continue;
3548
+ }
3549
+ const mine = new Map(cur.ids.values.map((v) => [v.hash, v.paths]));
3550
+ const shared = before.filter((e) => {
3551
+ const ids = e.ids;
3552
+ return ids.values.some((v) => mine.has(v.hash));
3553
+ });
3554
+ if (shared.length === 0) continue;
3555
+ const seen = new Set(
3556
+ shared.flatMap((e) => e.ids.values.map((v) => v.hash))
3557
+ );
3558
+ const paths = [...mine].filter(([h]) => seen.has(h)).flatMap(([, p]) => p);
3559
+ add("search-after-id", cur.name, [...shared.map((e) => e.step), cur.step], paths);
3560
+ }
3561
+ return [...acc.values()].map((a) => {
3562
+ const steps = [...a.steps].sort((x, y) => x - y);
3563
+ const paths = [...a.paths].sort();
3564
+ const base = {
3565
+ type: a.type,
3566
+ tool: a.tool,
3567
+ steps,
3568
+ count: a.count,
3569
+ ...paths.length > 0 ? { paths } : {}
3570
+ };
3571
+ if (a.type === "identical-retry")
3572
+ return {
3573
+ ...base,
3574
+ reason: `${a.tool} was called again ${a.count} time(s) with the same arguments right after itself (steps ${list(steps)}); this may be fine if the first call failed or the state changed in between`
3575
+ };
3576
+ if (a.type === "pagination-continuation")
3577
+ return {
3578
+ ...base,
3579
+ reason: `${a.tool} continued through a list with a new page or cursor ${a.count} time(s) (steps ${list(steps)}); this is not a repeat and may be exactly what the task needs`
3580
+ };
3581
+ if (a.type === "search-after-id")
3582
+ return {
3583
+ ...base,
3584
+ reason: `${a.tool} was called again ${a.count} time(s) with other arguments and it returned a record that an earlier step had already returned (identifier at ${paths.join(", ")}; steps ${list(steps)}); this may be fine if the model needed the record again`
3585
+ };
3586
+ return {
3587
+ ...base,
3588
+ reason: `${a.tool}: not measured, ${a.note ?? "the answer could not be read"}, so identifiers were not looked for (steps ${list(steps)}); this is not the same as finding none`
3589
+ };
3590
+ });
3591
+ }
3592
+
3218
3593
  // src/orchestrator/agent.ts
3219
3594
  var EXCERPT_BYTES = 4 * 1024;
3220
3595
  var TRANSCRIPT_BYTES = 256 * 1024;
@@ -3233,14 +3608,14 @@ var AgentError = class extends Error {
3233
3608
  }
3234
3609
  code;
3235
3610
  };
3236
- var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3611
+ var isRecord4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3237
3612
  function resultText(result) {
3238
- if (!isRecord2(result)) return JSON.stringify(result) ?? "";
3613
+ if (!isRecord4(result)) return JSON.stringify(result) ?? "";
3239
3614
  const content = Array.isArray(result.content) ? result.content : [];
3240
3615
  if (content.length === 0 && result.structuredContent !== void 0)
3241
3616
  return JSON.stringify(result.structuredContent);
3242
3617
  return content.map(
3243
- (b) => isRecord2(b) && b.type === "text" && typeof b.text === "string" ? b.text : JSON.stringify(b)
3618
+ (b) => isRecord4(b) && b.type === "text" && typeof b.text === "string" ? b.text : JSON.stringify(b)
3244
3619
  ).join("\n");
3245
3620
  }
3246
3621
  function excerpts() {
@@ -3262,7 +3637,7 @@ function excerpts() {
3262
3637
  function listedTools(items) {
3263
3638
  const seen = /* @__PURE__ */ new Set();
3264
3639
  return items.filter((t) => {
3265
- if (!isRecord2(t) || typeof t.name !== "string" || t.name === "" || seen.has(t.name))
3640
+ if (!isRecord4(t) || typeof t.name !== "string" || t.name === "" || seen.has(t.name))
3266
3641
  return false;
3267
3642
  seen.add(t.name);
3268
3643
  return true;
@@ -3280,13 +3655,7 @@ async function runAgentRow(p) {
3280
3655
  input_tokens: one.input_tokens * limits.max_steps,
3281
3656
  output_tokens: one.output_tokens * limits.max_steps
3282
3657
  };
3283
- return {
3284
- vars: p.row.vars,
3285
- output: null,
3286
- cached: false,
3287
- usage: { ...est, ...costFields(p.provider.estimateCost(est)) },
3288
- assertions: []
3289
- };
3658
+ return dryRunRow(p.row.vars, { ...est, ...costFields(p.provider.estimateCost(est)) });
3290
3659
  }
3291
3660
  const respond = p.provider.respond.bind(p.provider);
3292
3661
  const deadline = t0 + limits.timeout_ms;
@@ -3312,6 +3681,9 @@ async function runAgentRow(p) {
3312
3681
  let output = "";
3313
3682
  let error;
3314
3683
  let session;
3684
+ const scanned = /* @__PURE__ */ new Map();
3685
+ const overrides = p.toolDescriptions ?? {};
3686
+ const replaced = /* @__PURE__ */ new Set();
3315
3687
  try {
3316
3688
  const opening = p.connect(p.server, limits.timeout_ms);
3317
3689
  try {
@@ -3329,7 +3701,7 @@ async function runAgentRow(p) {
3329
3701
  let names = wireNames([]);
3330
3702
  let tools = [];
3331
3703
  let offeredNames = [];
3332
- const list = async () => {
3704
+ const list2 = async () => {
3333
3705
  let listed;
3334
3706
  try {
3335
3707
  listed = listedTools(await bounded(open2.listTools(limits.tool_timeout_ms)));
@@ -3348,7 +3720,7 @@ async function runAgentRow(p) {
3348
3720
  transcript.tools.push({
3349
3721
  name: t.name,
3350
3722
  offered: isOffered,
3351
- ...isRecord2(t.annotations) ? { annotations: t.annotations } : {}
3723
+ ...isRecord4(t.annotations) ? { annotations: t.annotations } : {}
3352
3724
  });
3353
3725
  }
3354
3726
  const now = offered.map((t) => t.name);
@@ -3356,14 +3728,19 @@ async function runAgentRow(p) {
3356
3728
  const removed = offeredNames.filter((n) => !now.includes(n));
3357
3729
  offeredNames = now;
3358
3730
  names = wireNames(now);
3359
- tools = offered.map((t) => ({
3360
- name: names.toWire.get(t.name),
3361
- ...typeof t.description === "string" ? { description: t.description } : {},
3362
- input_schema: isRecord2(t.inputSchema) ? t.inputSchema : { type: "object" }
3363
- }));
3731
+ tools = offered.map((t) => {
3732
+ const swap = overrides[t.name];
3733
+ if (swap !== void 0) replaced.add(t.name);
3734
+ const description = swap ?? (typeof t.description === "string" ? t.description : void 0);
3735
+ return {
3736
+ name: names.toWire.get(t.name),
3737
+ ...description !== void 0 ? { description } : {},
3738
+ input_schema: isRecord4(t.inputSchema) ? t.inputSchema : { type: "object" }
3739
+ };
3740
+ });
3364
3741
  return added.length + removed.length > 0 ? { added, removed } : void 0;
3365
3742
  };
3366
- await list();
3743
+ await list2();
3367
3744
  const messages = [{ role: "user", content: prompt5 }];
3368
3745
  let calls = 0;
3369
3746
  let tokens = 0;
@@ -3429,7 +3806,7 @@ async function runAgentRow(p) {
3429
3806
  answer(rec, c, `Tool "${c.name}" is not available.`);
3430
3807
  continue;
3431
3808
  }
3432
- if (c.args_invalid === true || !isRecord2(c.args)) {
3809
+ if (c.args_invalid === true || !isRecord4(c.args)) {
3433
3810
  Object.assign(rec, { is_error: true, error_kind: "bad-arguments" });
3434
3811
  answer(rec, c, "The arguments are not a JSON object.");
3435
3812
  continue;
@@ -3445,9 +3822,10 @@ async function runAgentRow(p) {
3445
3822
  if (got.kind === "lost") throw new AgentError("MCP_SERVER_LOST", got.message);
3446
3823
  const text = got.kind === "error" ? got.message : resultText(got.result);
3447
3824
  if (got.kind === "error") Object.assign(rec, { is_error: true, error_kind: "protocol" });
3448
- else if (isRecord2(got.result) && got.result.isError === true)
3825
+ else if (isRecord4(got.result) && got.result.isError === true)
3449
3826
  Object.assign(rec, { is_error: true, error_kind: "content" });
3450
3827
  succeeded ||= !rec.is_error;
3828
+ if (got.kind === "result" && !rec.is_error) scanned.set(rec, scanIds(got.result));
3451
3829
  rec.result = kept.cut(text);
3452
3830
  answer(rec, c, text);
3453
3831
  }
@@ -3455,7 +3833,7 @@ async function runAgentRow(p) {
3455
3833
  { role: "assistant", text: res.text, tool_calls: res.tool_calls },
3456
3834
  { role: "tool", results }
3457
3835
  );
3458
- if (succeeded) changed = await list();
3836
+ if (succeeded) changed = await list2();
3459
3837
  }
3460
3838
  } catch (err) {
3461
3839
  if (err instanceof LimitStop) transcript.stop = { reason: "limit", limit: err.limit };
@@ -3468,8 +3846,27 @@ async function runAgentRow(p) {
3468
3846
  });
3469
3847
  }
3470
3848
  if (transcript.stop.reason !== "complete" || kept.any) transcript.collection = "partial";
3849
+ const friction = error === void 0 ? frictionAdvice(
3850
+ transcript.steps.flatMap(
3851
+ (s) => s.calls.map(
3852
+ (c) => ({
3853
+ step: s.index,
3854
+ name: c.name,
3855
+ args: c.args,
3856
+ executed: c.executed,
3857
+ is_error: c.is_error,
3858
+ ...scanned.has(c) ? { ids: scanned.get(c) } : {}
3859
+ })
3860
+ )
3861
+ )
3862
+ ) : [];
3471
3863
  const mask = session?.redact;
3472
3864
  const agent = mask?.value(transcript) ?? transcript;
3865
+ if (replaced.size > 0)
3866
+ agent.description_overrides = [...replaced].sort().map((tool) => ({
3867
+ tool,
3868
+ sha256: sha256(overrides[tool])
3869
+ }));
3473
3870
  const spent = usages.length > 0 ? { usage: sumUsage(usages) } : {};
3474
3871
  if (error !== void 0) {
3475
3872
  return {
@@ -3488,7 +3885,12 @@ async function runAgentRow(p) {
3488
3885
  output,
3489
3886
  agent
3490
3887
  );
3491
- if (advice.length > 0) agent.advice = advice;
3888
+ const covered = p.assertions.filter((x) => x.type === "no-repeated-call");
3889
+ const signals = (mask?.value(friction) ?? friction).filter(
3890
+ (f) => !(f.type === "identical-retry" && covered.some((c) => c.tool === void 0 || c.tool === f.tool))
3891
+ );
3892
+ const findings = [...advice, ...signals];
3893
+ if (findings.length > 0) agent.advice = findings;
3492
3894
  const usage = sumUsage(usages);
3493
3895
  return {
3494
3896
  vars: p.row.vars,
@@ -3545,6 +3947,9 @@ function pricedField(priced) {
3545
3947
  function costFields(c) {
3546
3948
  return { cost_usd: c.cost_usd, ...pricedField(c.priced) };
3547
3949
  }
3950
+ function dryRunRow(vars, usage) {
3951
+ return { vars, output: null, cached: false, usage, inconclusive: "skipped", assertions: [] };
3952
+ }
3548
3953
  async function assess(p, output, transcript) {
3549
3954
  let judgeCost = 0;
3550
3955
  let judgeUnpriced = false;
@@ -3557,7 +3962,10 @@ async function assess(p, output, transcript) {
3557
3962
  const advice = [];
3558
3963
  let assertionError;
3559
3964
  for (const assertion of p.assertions) {
3560
- const run = () => getAssertion(assertion.type).run({
3965
+ const run = () => usesExpected(assertion) && (p.row.expected === void 0 || p.row.expected === "") ? Promise.resolve({
3966
+ passed: false,
3967
+ reason: "the row has no expected value, and this check compares against {{expected}}"
3968
+ }) : getAssertion(assertion.type).run({
3561
3969
  output,
3562
3970
  vars: p.row.vars,
3563
3971
  row: p.row,
@@ -3597,8 +4005,7 @@ async function runRow(p) {
3597
4005
  if (p.dryRun) {
3598
4006
  const est = estimateUsage(prompt5, maxTokens);
3599
4007
  const cost = p.provider.estimateCost(est);
3600
- const usage2 = { ...est, ...costFields(cost) };
3601
- return { vars: p.row.vars, output: null, cached: false, usage: usage2, assertions: [] };
4008
+ return dryRunRow(p.row.vars, { ...est, ...costFields(cost) });
3602
4009
  }
3603
4010
  const key = cacheKey(
3604
4011
  {
@@ -3821,12 +4228,11 @@ function summarize(evals, durationMs) {
3821
4228
  }
3822
4229
  return { ...summary, cache };
3823
4230
  }
3824
- function agenticProvider(config, ev, deps, cacheStrict) {
4231
+ function agenticProvider(ev, providerConfig, deps, cacheStrict) {
3825
4232
  if (cacheStrict)
3826
4233
  throw new RunConfigError(
3827
4234
  `Eval "${ev.id}" uses MCP server "${ev.mcp.server}": its tool loop is never cached, so --cache-strict cannot answer it`
3828
4235
  );
3829
- const providerConfig = { ...config.provider, ...ev.provider };
3830
4236
  const provider = deps.resolveProvider(providerConfig);
3831
4237
  if (provider.respond === void 0)
3832
4238
  throw new RunConfigError(
@@ -3853,51 +4259,77 @@ async function runOrchestration(config, options, deps) {
3853
4259
  const started = deps.now();
3854
4260
  const dryRun = options.dryRun ?? false;
3855
4261
  const evalResults = [];
4262
+ const models = config.providers ?? [config.provider];
3856
4263
  const prepared = selectEvals(config.evals, options.only).map((ev) => {
3857
4264
  const template = resolveTemplate(ev, deps.baseDir);
3858
4265
  const rows = deps.loadDataset(ev.dataset, deps.baseDir);
3859
4266
  for (const row of rows) {
3860
4267
  resolvePrompt(template, row.vars);
3861
4268
  }
3862
- const agentic = ev.mcp === void 0 || dryRun ? void 0 : agenticProvider(config, ev, deps, cacheStrict);
3863
- return { ev, template, rows, agentic };
4269
+ const cells = models.map((model) => {
4270
+ const providerConfig = { ...model, ...ev.provider };
4271
+ const agentic = ev.mcp === void 0 || dryRun ? void 0 : agenticProvider(ev, providerConfig, deps, cacheStrict);
4272
+ return { providerConfig, agentic };
4273
+ });
4274
+ return { ev, template, rows, cells };
3864
4275
  });
3865
- for (const { ev, template, rows, agentic } of prepared) {
3866
- const providerConfig = { ...config.provider, ...ev.provider };
3867
- const provider = agentic ?? deps.resolveProvider(providerConfig);
3868
- const limit2 = options.concurrency ?? providerConfig.concurrency ?? (ev.mcp !== void 0 ? 1 : 4);
3869
- const runs = options.runs ?? ev.runs ?? config.runs ?? 1;
3870
- const passThreshold = ev.pass_threshold ?? config.pass_threshold ?? 1;
3871
- const rowResults = await mapLimit(rows, limit2, (row) => {
3872
- const params = {
3873
- template,
3874
- // `defaults.assertions` apply to every eval, ahead of its own.
3875
- assertions: [...config.defaults?.assertions ?? [], ...ev.assertions],
3876
- row,
3877
- providerConfig,
3878
- provider,
3879
- embedder: deps.embedder,
3880
- cache: deps.cache,
3881
- now: deps.now,
3882
- dryRun,
3883
- noCache,
3884
- cacheStrict,
3885
- ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {}
3886
- };
3887
- if (ev.mcp === void 0) return runRepeats(params, runs, passThreshold);
3888
- const agentParams = {
3889
- ...params,
3890
- server: ev.mcp.server,
3891
- ...ev.mcp.allowed_tools !== void 0 ? { allowedTools: ev.mcp.allowed_tools } : {},
3892
- limits: mcpLimits(config, ev),
3893
- // A dry run connects nowhere; the loop never calls this then.
3894
- connect: deps.connectMcp ?? (() => Promise.reject(new Error("no MCP connection")))
4276
+ const swapped = Object.keys(options.toolDescriptions ?? {}).length > 0;
4277
+ if (swapped && !prepared.some((x) => x.ev.mcp !== void 0))
4278
+ throw new RunConfigError(
4279
+ "--tool-description needs an eval with mcp in this run: no tool is offered otherwise"
4280
+ );
4281
+ cellLoop: for (const { ev, template, rows, cells } of prepared) {
4282
+ for (const { providerConfig, agentic } of cells) {
4283
+ const provider = agentic ?? deps.resolveProvider(providerConfig);
4284
+ const limit2 = options.concurrency ?? providerConfig.concurrency ?? (ev.mcp !== void 0 ? 1 : 4);
4285
+ const runs = options.runs ?? ev.runs ?? config.runs ?? 1;
4286
+ const passThreshold = ev.pass_threshold ?? config.pass_threshold ?? 1;
4287
+ const assertions = [...config.defaults?.assertions ?? [], ...ev.assertions];
4288
+ const rowResults = await mapLimit(rows, limit2, (row) => {
4289
+ const params = {
4290
+ template,
4291
+ assertions,
4292
+ row,
4293
+ providerConfig,
4294
+ provider,
4295
+ embedder: deps.embedder,
4296
+ cache: deps.cache,
4297
+ now: deps.now,
4298
+ dryRun,
4299
+ noCache,
4300
+ cacheStrict,
4301
+ ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {}
4302
+ };
4303
+ if (ev.mcp === void 0) return runRepeats(params, runs, passThreshold);
4304
+ const agentParams = {
4305
+ ...params,
4306
+ server: ev.mcp.server,
4307
+ ...ev.mcp.allowed_tools !== void 0 ? { allowedTools: ev.mcp.allowed_tools } : {},
4308
+ limits: mcpLimits(config, ev),
4309
+ ...options.toolDescriptions !== void 0 ? { toolDescriptions: options.toolDescriptions } : {},
4310
+ // A dry run connects nowhere; the loop never calls this then.
4311
+ connect: deps.connectMcp ?? (() => Promise.reject(new Error("no MCP connection")))
4312
+ };
4313
+ return runRepeats(agentParams, runs, passThreshold, runAgentRow);
4314
+ });
4315
+ const passed = !dryRun && rowResults.every((r) => rowStatus(r) === "passed");
4316
+ const measured = {
4317
+ runs,
4318
+ rows: rows.length,
4319
+ rows_hash: sha256(canonicalJson(rows.map((r) => canonicalJson(r.vars)).sort())),
4320
+ assertions_hash: sha256(canonicalJson(assertions)),
4321
+ model: `${providerConfig.type}/${providerConfig.model}`
3895
4322
  };
3896
- return runRepeats(agentParams, runs, passThreshold, runAgentRow);
3897
- });
3898
- const passed = rowResults.every((r) => rowStatus(r) === "passed");
3899
- evalResults.push({ id: ev.id, tags: ev.tags ?? [], rows: rowResults, passed });
3900
- if (options.bail === true && !passed) break;
4323
+ evalResults.push({
4324
+ id: models.length > 1 ? `${ev.id}@${providerConfig.model}` : ev.id,
4325
+ tags: ev.tags ?? [],
4326
+ rows: rowResults,
4327
+ passed,
4328
+ measured,
4329
+ ...models.length > 1 ? { provider: { type: providerConfig.type, model: providerConfig.model } } : {}
4330
+ });
4331
+ if (options.bail === true && !dryRun && !passed) break cellLoop;
4332
+ }
3901
4333
  }
3902
4334
  const finished = deps.now();
3903
4335
  const summary = summarize(evalResults, finished - started);
@@ -3907,6 +4339,8 @@ async function runOrchestration(config, options, deps) {
3907
4339
  started_at: new Date(started).toISOString(),
3908
4340
  finished_at: new Date(finished).toISOString(),
3909
4341
  config_hash: configHash(config),
4342
+ // The one fact every reader of the result asks: was anything measured (plune-ai/cli#244).
4343
+ ...dryRun ? { dry_run: true } : {},
3910
4344
  summary,
3911
4345
  evals: evalResults
3912
4346
  };
@@ -3919,11 +4353,19 @@ init_cjs_shims();
3919
4353
  init_cjs_shims();
3920
4354
  var fs4 = __toESM(require("fs"), 1);
3921
4355
  var path4 = __toESM(require("path"), 1);
3922
- function loadDataset(ref, baseDir) {
3923
- if (typeof ref !== "string") {
3924
- return ref.examples;
4356
+ function loadDataset(ref5, baseDir) {
4357
+ if (typeof ref5 !== "string") {
4358
+ return ref5.examples;
4359
+ }
4360
+ const file = path4.resolve(baseDir, ref5);
4361
+ let content;
4362
+ try {
4363
+ content = fs4.readFileSync(file, "utf8");
4364
+ } catch (err) {
4365
+ throw new RunConfigError(
4366
+ err.code === "ENOENT" ? `${ref5}: dataset file not found (looked for ${file})` : `${ref5}: cannot read the dataset file (${err.message})`
4367
+ );
3925
4368
  }
3926
- const content = fs4.readFileSync(path4.resolve(baseDir, ref), "utf8");
3927
4369
  const rows = [];
3928
4370
  content.split(/\r?\n/).forEach((line, i) => {
3929
4371
  if (line.trim().length === 0) return;
@@ -3931,13 +4373,13 @@ function loadDataset(ref, baseDir) {
3931
4373
  try {
3932
4374
  row = JSON.parse(line.trim());
3933
4375
  } catch (err) {
3934
- throw new RunConfigError(`${ref}:${i + 1}: not valid JSON (${err.message})`);
4376
+ throw new RunConfigError(`${ref5}:${i + 1}: not valid JSON (${err.message})`);
3935
4377
  }
3936
4378
  const vars = isObject2(row) ? row["vars"] : void 0;
3937
4379
  if (!isObject2(vars)) {
3938
4380
  const why = isObject2(row) && "vars" in row ? `vars: Invalid input: expected record, received ${typeName(vars)}` : 'this row has no "vars"';
3939
4381
  throw new RunConfigError(
3940
- `${ref}:${i + 1}: a dataset row must be { "vars": { ... } }; ${why}`
4382
+ `${ref5}:${i + 1}: a dataset row must be { "vars": { ... } }; ${why}`
3941
4383
  );
3942
4384
  }
3943
4385
  rows.push(row);
@@ -3960,6 +4402,41 @@ var NOOP_CACHE = { get: () => void 0, set: () => {
3960
4402
  function isMockMode(env) {
3961
4403
  return env["PLUNE_MOCK_PROVIDER"] === "1";
3962
4404
  }
4405
+ var MAX_DESCRIPTION_BYTES = 64 * 1024;
4406
+ function parseToolDescriptions(values) {
4407
+ const out = {};
4408
+ for (const v of values) {
4409
+ const eq = v.indexOf("=");
4410
+ const tool = eq < 0 ? "" : v.slice(0, eq).trim();
4411
+ let text = eq < 0 ? "" : v.slice(eq + 1);
4412
+ if (tool === "" || text === "")
4413
+ throw new RunConfigError(
4414
+ `--tool-description must be <tool>=<text> or <tool>=@<file> (got "${tool === "" ? v : tool + "="}")`
4415
+ );
4416
+ if (Object.hasOwn(out, tool))
4417
+ throw new RunConfigError(`--tool-description names "${tool}" twice`);
4418
+ if (text.startsWith("@")) {
4419
+ const file = text.slice(1);
4420
+ try {
4421
+ const full = path5.resolve(file);
4422
+ const stat2 = fs5.statSync(full);
4423
+ if (!stat2.isFile())
4424
+ throw new RunConfigError(`--tool-description ${tool}: ${file} is not a file`);
4425
+ if (stat2.size > MAX_DESCRIPTION_BYTES)
4426
+ throw new RunConfigError(`--tool-description ${tool}: ${file} is over 64 KB`);
4427
+ text = fs5.readFileSync(full, "utf8").replace(/\r?\n$/, "");
4428
+ } catch (err) {
4429
+ if (err instanceof RunConfigError) throw err;
4430
+ throw new RunConfigError(`--tool-description ${tool}: cannot read ${file}`);
4431
+ }
4432
+ if (text === "") throw new RunConfigError(`--tool-description ${tool}: ${file} is empty`);
4433
+ }
4434
+ if (Buffer.byteLength(text, "utf8") > MAX_DESCRIPTION_BYTES)
4435
+ throw new RunConfigError(`--tool-description ${tool}: the text is over 64 KB`);
4436
+ out[tool] = text;
4437
+ }
4438
+ return out;
4439
+ }
3963
4440
  function mockScript(env) {
3964
4441
  const file = env["PLUNE_MOCK_SCRIPT"];
3965
4442
  if (file === void 0 || file === "") return void 0;
@@ -4024,8 +4501,10 @@ async function handleRun(options, depsFactory) {
4024
4501
  options.configPath !== void 0 ? { configPath: options.configPath } : {}
4025
4502
  );
4026
4503
  const baseDir = options.configPath !== void 0 ? path5.dirname(path5.resolve(options.configPath)) : process.cwd();
4027
- for (const warning of mcpSecretWarnings(config)) process.stderr.write(`warning: ${warning}
4504
+ for (const warning of [...mcpSecretWarnings(config), ...selfJudgeWarnings(config)])
4505
+ process.stderr.write(`warning: ${warning}
4028
4506
  `);
4507
+ const toolDescriptions = options.toolDescription !== void 0 && options.toolDescription.length > 0 ? parseToolDescriptions(options.toolDescription) : void 0;
4029
4508
  const factory = depsFactory ?? ((c, d) => buildRealDeps(c, d, options.dryRun));
4030
4509
  const deps = factory(config, baseDir);
4031
4510
  try {
@@ -4044,10 +4523,25 @@ async function handleRun(options, depsFactory) {
4044
4523
  ...options.bail !== void 0 ? { bail: options.bail } : {},
4045
4524
  ...options.cacheStrict === true ? { cacheStrict: true } : {},
4046
4525
  ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {},
4047
- ...options.runs !== void 0 ? { runs: options.runs } : {}
4526
+ ...options.runs !== void 0 ? { runs: options.runs } : {},
4527
+ ...toolDescriptions !== void 0 ? { toolDescriptions } : {}
4048
4528
  },
4049
4529
  deps
4050
4530
  );
4531
+ for (const tool of Object.keys(toolDescriptions ?? {})) {
4532
+ const used = result.evals.some(
4533
+ (ev) => ev.rows.some(
4534
+ (r) => (r.agent?.description_overrides ?? []).some(
4535
+ (o) => o.tool === tool
4536
+ )
4537
+ )
4538
+ );
4539
+ if (!used && !options.dryRun)
4540
+ process.stderr.write(
4541
+ `warning: --tool-description ${tool}: no row offered a tool of that name, nothing was replaced
4542
+ `
4543
+ );
4544
+ }
4051
4545
  if (options.dryRun) {
4052
4546
  const agentic = new Set(config.evals.filter((ev) => ev.mcp !== void 0).map((ev) => ev.id));
4053
4547
  if (result.evals.some((ev) => agentic.has(ev.id)))
@@ -4055,7 +4549,7 @@ async function handleRun(options, depsFactory) {
4055
4549
  "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"
4056
4550
  );
4057
4551
  }
4058
- persist(result, baseDir);
4552
+ if (result.dry_run !== true) persist(result, baseDir);
4059
4553
  return result;
4060
4554
  } finally {
4061
4555
  deps.cache.close();
@@ -4108,7 +4602,7 @@ var rowResultSchema = import_zod3.z.object({
4108
4602
  error: runErrorSchema.optional(),
4109
4603
  assertions: import_zod3.z.array(assertionResultRecordSchema2),
4110
4604
  cache_saved: savedSchema.optional(),
4111
- /** ADR 0045. Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
4605
+ /** Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
4112
4606
  inconclusive: import_zod3.z.enum(ROW_INCONCLUSIVE).optional(),
4113
4607
  /** Repeats (`runs` above 1). Optional and additive — a RunResult without it validates unchanged. */
4114
4608
  attempts: import_zod3.z.object({
@@ -4167,7 +4661,17 @@ var rowResultSchema = import_zod3.z.object({
4167
4661
  }),
4168
4662
  collection: import_zod3.z.enum(["complete", "partial"]),
4169
4663
  /** Heuristic findings, never a verdict. Optional and additive. */
4170
- advice: import_zod3.z.array(import_zod3.z.object({ type: import_zod3.z.string(), reason: import_zod3.z.string() })).optional()
4664
+ advice: import_zod3.z.array(
4665
+ import_zod3.z.object({
4666
+ type: import_zod3.z.string(),
4667
+ reason: import_zod3.z.string(),
4668
+ tool: import_zod3.z.string().optional(),
4669
+ steps: import_zod3.z.array(import_zod3.z.number()).optional(),
4670
+ count: import_zod3.z.number().optional(),
4671
+ paths: import_zod3.z.array(import_zod3.z.string()).optional()
4672
+ })
4673
+ ).optional(),
4674
+ description_overrides: import_zod3.z.array(import_zod3.z.object({ tool: import_zod3.z.string(), sha256: import_zod3.z.string() })).optional()
4171
4675
  }).optional()
4172
4676
  });
4173
4677
  var summarySchema = import_zod3.z.object({
@@ -4175,7 +4679,7 @@ var summarySchema = import_zod3.z.object({
4175
4679
  passed: import_zod3.z.number(),
4176
4680
  failed: import_zod3.z.number(),
4177
4681
  errored: import_zod3.z.number(),
4178
- /** plune#1245. Optional and additive — a RunResult written before them validates unchanged. */
4682
+ /** Optional and additive — a RunResult written before them validates unchanged. */
4179
4683
  blocked: import_zod3.z.number().optional(),
4180
4684
  skipped: import_zod3.z.number().optional(),
4181
4685
  cost_usd: import_zod3.z.number(),
@@ -4192,7 +4696,17 @@ var evalResultSchema = import_zod3.z.object({
4192
4696
  id: import_zod3.z.string(),
4193
4697
  tags: import_zod3.z.array(import_zod3.z.string()),
4194
4698
  rows: import_zod3.z.array(rowResultSchema),
4195
- passed: import_zod3.z.boolean()
4699
+ passed: import_zod3.z.boolean(),
4700
+ /** What the eval measured, for the pass-rate gate of `plune diff`. Optional and additive. */
4701
+ measured: import_zod3.z.object({
4702
+ runs: import_zod3.z.number(),
4703
+ rows: import_zod3.z.number(),
4704
+ rows_hash: import_zod3.z.string(),
4705
+ assertions_hash: import_zod3.z.string(),
4706
+ model: import_zod3.z.string().optional()
4707
+ }).optional(),
4708
+ /** The type and model of a cell of a multi-model run. Optional and additive. */
4709
+ provider: import_zod3.z.object({ type: import_zod3.z.string(), model: import_zod3.z.string() }).optional()
4196
4710
  });
4197
4711
  var runResultSchema = import_zod3.z.object({
4198
4712
  schemaVersion: import_zod3.z.literal(RUN_RESULT_SCHEMA_VERSION),
@@ -4200,6 +4714,8 @@ var runResultSchema = import_zod3.z.object({
4200
4714
  started_at: import_zod3.z.string(),
4201
4715
  finished_at: import_zod3.z.string(),
4202
4716
  config_hash: import_zod3.z.string(),
4717
+ /** cli#244. The result of `--dry-run`. Optional and additive — a RunResult without it validates unchanged. */
4718
+ dry_run: import_zod3.z.boolean().optional(),
4203
4719
  summary: summarySchema,
4204
4720
  evals: import_zod3.z.array(evalResultSchema)
4205
4721
  });
@@ -4302,7 +4818,7 @@ var JobReporter = class {
4302
4818
  }
4303
4819
  /**
4304
4820
  * The upload is in: every row is on the platform. `subjectId` is what the job works on, learnt from the upload's
4305
- * answer (the run an ingest landed in): the platform takes it while the job names none (#1279).
4821
+ * answer (the run an ingest landed in): the platform takes it while the job names none.
4306
4822
  */
4307
4823
  async uploaded(at) {
4308
4824
  if (this.id === void 0) return;
@@ -4467,96 +4983,2622 @@ function reportSyncFailure(err, write) {
4467
4983
 
4468
4984
  // src/cli/commands/ingest.ts
4469
4985
  init_cjs_shims();
4470
- var path8 = __toESM(require("path"), 1);
4986
+ var import_node_fs8 = require("fs");
4987
+ var path10 = __toESM(require("path"), 1);
4471
4988
 
4472
- // src/cli/commands/cairn-artifact.ts
4989
+ // src/reporter-core/client.ts
4473
4990
  init_cjs_shims();
4474
- var fs7 = __toESM(require("fs/promises"), 1);
4475
- var path7 = __toESM(require("path"), 1);
4476
- var SUPPORTED_ARTIFACT_VERSION = 1;
4477
- var INGEST_SCHEMA_VERSION = 1;
4478
- var NoCairnRunsError = class extends Error {
4479
- constructor(runsDir) {
4480
- super(`No Cairn run found under ${runsDir} \u2014 name the directory instead: plune ingest <dir>.`);
4481
- this.name = "NoCairnRunsError";
4482
- }
4483
- };
4484
- async function findLatestCairnRun(runsDir = "runs") {
4485
- const entries = await fs7.readdir(runsDir, { withFileTypes: true }).catch(() => null);
4486
- if (entries === null) throw new NoCairnRunsError(runsDir);
4487
- let newest;
4488
- for (const entry of entries) {
4489
- if (!entry.isDirectory()) continue;
4490
- const dir = path7.join(runsDir, entry.name);
4491
- try {
4492
- const report = await fs7.lstat(path7.join(dir, "report.json"));
4493
- if (!report.isFile()) continue;
4494
- if (newest === void 0 || report.mtimeMs > newest.at) {
4495
- newest = { dir, at: report.mtimeMs };
4496
- }
4497
- } catch {
4498
- }
4499
- }
4500
- if (newest === void 0) throw new NoCairnRunsError(runsDir);
4501
- return newest.dir;
4991
+ var import_node_fs5 = require("fs");
4992
+ var import_node_stream = require("stream");
4993
+ var import_node_http = require("http");
4994
+ var import_node_https = require("https");
4995
+ var BACKOFF_BASE_MS = 300;
4996
+ var BACKOFF_CAP_MS = 1e4;
4997
+ var DEFAULT_RETRIES = 2;
4998
+ var RETRY_AFTER_CAP_MS = 6e4;
4999
+ function parseRetryAfter(raw, now = Date.now()) {
5000
+ const text = raw?.trim();
5001
+ if (text === void 0 || text === "") return null;
5002
+ const seconds = /^\d+(\.\d+)?$/.test(text) ? Number(text) : (Date.parse(text) - now) / 1e3;
5003
+ if (!Number.isFinite(seconds)) return null;
5004
+ return Math.min(Math.max(seconds, 0) * 1e3, RETRY_AFTER_CAP_MS);
5005
+ }
5006
+ var POOLS = { "http:": new import_node_http.Agent({ keepAlive: true }), "https:": new import_node_https.Agent({ keepAlive: true }) };
5007
+ var IDLE_MS = 3e5;
5008
+ function nodeTransport(url, init, idleMs = IDLE_MS) {
5009
+ return new Promise((resolve9, reject) => {
5010
+ const target = new URL(url);
5011
+ const send = target.protocol === "https:" ? import_node_https.request : import_node_http.request;
5012
+ const agent = POOLS[target.protocol === "https:" ? "https:" : "http:"];
5013
+ const req = send(target, { method: init.method, headers: init.headers, agent }, (res) => {
5014
+ const chunks = [];
5015
+ res.on("data", (chunk2) => chunks.push(chunk2));
5016
+ res.on("error", reject);
5017
+ res.on("end", () => {
5018
+ const status = res.statusCode ?? 0;
5019
+ const text = Buffer.concat(chunks).toString("utf8");
5020
+ resolve9({
5021
+ ok: status >= 200 && status <= 299,
5022
+ status,
5023
+ headers: {
5024
+ get: (name) => {
5025
+ const value = res.headers[name.toLowerCase()];
5026
+ return value === void 0 ? null : Array.isArray(value) ? value.join(", ") : value;
5027
+ }
5028
+ },
5029
+ json: async () => JSON.parse(text)
5030
+ });
5031
+ });
5032
+ });
5033
+ req.setTimeout(idleMs, () => req.destroy(new Error(`no answer from ${target.origin} in ${idleMs} ms`)));
5034
+ req.on("error", reject);
5035
+ req.end(init.body);
5036
+ });
4502
5037
  }
4503
- var CairnRunNotFoundError = class extends Error {
4504
- constructor(dir) {
4505
- super(
4506
- `No Cairn run found in ${dir} \u2014 expected a report.json written by "cairn design|explore|api".`
4507
- );
4508
- this.name = "CairnRunNotFoundError";
4509
- }
4510
- };
4511
- var CairnRunVersionError = class extends Error {
4512
- constructor(found) {
4513
- super(
4514
- found === void 0 ? "This run predates versioned Cairn artifacts. Re-run it with Cairn 0.7.0 or newer, which stamps the format so it can be read safely." : `Unsupported Cairn artifact version ${String(found)} (this CLI reads version ${SUPPORTED_ARTIFACT_VERSION}). Upgrade @plune-ai/cli.`
4515
- );
4516
- this.name = "CairnRunVersionError";
4517
- }
4518
- };
4519
- var CairnRunPartialError = class extends Error {
4520
- constructor(reason) {
4521
- super(`That Cairn run did not finish, so its cases are incomplete: ${reason}`);
4522
- this.name = "CairnRunPartialError";
4523
- }
4524
- };
4525
- var CairnEvidenceAmbiguousError = class extends Error {
4526
- constructor(name) {
4527
- super(
4528
- `Cannot attach results safely: the operation "${name}" appears more than once in this run's evidence, and the evidence file carries no case identity to disambiguate it. Nothing was uploaded.`
5038
+ var withoutLength = (headers) => Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-length"));
5039
+ function nodePut(url, headers, source, idleMs) {
5040
+ return new Promise((resolve9, reject) => {
5041
+ const target = new URL(url);
5042
+ const send = target.protocol === "https:" ? import_node_https.request : import_node_http.request;
5043
+ const length = "body" in source ? source.body.length : source.size;
5044
+ let answered;
5045
+ const settle = (err) => answered !== void 0 ? resolve9(answered) : reject(err);
5046
+ const req = send(
5047
+ target,
5048
+ { method: "PUT", headers: { ...withoutLength(headers), "content-length": String(length) } },
5049
+ (res) => {
5050
+ const retry = res.headers["retry-after"];
5051
+ answered = { status: res.statusCode ?? 0, retryAfter: Array.isArray(retry) ? retry[0] ?? null : retry ?? null };
5052
+ res.on("error", settle);
5053
+ res.on("close", () => {
5054
+ resolve9(answered);
5055
+ req.destroy();
5056
+ });
5057
+ res.resume();
5058
+ }
4529
5059
  );
4530
- this.name = "CairnEvidenceAmbiguousError";
4531
- }
5060
+ req.setTimeout(idleMs, () => req.destroy(Object.assign(new Error("idle"), { code: "ETIMEDOUT" })));
5061
+ req.on("error", settle);
5062
+ if ("body" in source) req.end(source.body);
5063
+ else (0, import_node_stream.pipeline)((0, import_node_fs5.createReadStream)(source.path), req, (err) => err ? settle(err) : void 0);
5064
+ });
5065
+ }
5066
+ var codeOfError = (err) => {
5067
+ const code = err?.code;
5068
+ return typeof code === "string" && /^[A-Z0-9_]{2,40}$/.test(code) ? code : "network";
4532
5069
  };
4533
- var asRecord = (v) => typeof v === "object" && v !== null ? v : {};
4534
- var str = (v, fallback = "") => typeof v === "string" && v !== "" ? v : fallback;
4535
- async function readJson(file) {
5070
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5071
+ async function detailOf(res) {
4536
5072
  try {
4537
- return JSON.parse(await fs7.readFile(file, "utf8"));
5073
+ const body = await res.json();
5074
+ const q = body.quota;
5075
+ return {
5076
+ ...typeof body.shardsExpected === "number" && Number.isInteger(body.shardsExpected) ? { shardsExpected: body.shardsExpected } : {},
5077
+ detail: typeof body.error === "string" ? body.error : "",
5078
+ ...typeof q === "object" && q !== null && !Array.isArray(q) ? { quota: q } : {},
5079
+ ...typeof body.code === "string" && /^[a-z0-9_]{1,60}$/.test(body.code) ? { code: body.code } : {}
5080
+ };
4538
5081
  } catch {
4539
- return void 0;
5082
+ return { detail: "" };
4540
5083
  }
4541
5084
  }
4542
- async function defaultReadEvidence(dir) {
4543
- const raw = await readJson(path7.join(dir, "api-evidence.json"));
4544
- if (!Array.isArray(raw)) return void 0;
4545
- return raw.map((r) => {
4546
- const rec = asRecord(r);
4547
- const error = str(rec["error"]);
4548
- return { name: str(rec["name"]), passed: rec["passed"] === true, ...error !== "" ? { error } : {} };
4549
- });
5085
+ function describeQuota(q) {
5086
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
5087
+ const kind = typeof q["kind"] === "string" ? q["kind"].slice(0, 60) : "limit";
5088
+ const [used, limit2] = [num(q["used"]), num(q["limit"])];
5089
+ const parts = [used !== void 0 && limit2 !== void 0 ? `${kind}: ${used} of ${limit2} used` : kind];
5090
+ if (typeof q["resetsAt"] === "string" && q["resetsAt"] !== "") parts.push(`resets ${q["resetsAt"].slice(0, 40)}`);
5091
+ return parts.join(", ");
4550
5092
  }
4551
- function casesFromDesign(report) {
4552
- const list = Array.isArray(report["testCases"]) ? report["testCases"] : [];
4553
- return list.map((raw) => {
4554
- const c = asRecord(raw);
4555
- const steps = (Array.isArray(c["steps"]) ? c["steps"] : []).map((s) => str(s)).filter((s) => s !== "");
4556
- return {
4557
- stableId: str(c["stableId"]),
4558
- title: str(c["title"], "untitled case"),
4559
- execution: c["execution"] === "manual" ? "manual" : "auto",
5093
+ function classify(status) {
5094
+ if (status === 401 || status === 403) return "auth";
5095
+ if (status === 409) return "conflict";
5096
+ if (status === 400) return "invalid";
5097
+ if (status === 429 || status >= 500) return "unavailable";
5098
+ return "other";
5099
+ }
5100
+ function createClient(opts) {
5101
+ const doFetch = opts.fetchImpl ?? nodeTransport;
5102
+ const wait = opts.wait ?? sleep;
5103
+ const uploadRetries = opts.uploadRetries === void 0 ? void 0 : Math.max(0, Math.floor(opts.uploadRetries));
5104
+ const random = opts.random ?? Math.random;
5105
+ const now = opts.now ?? Date.now;
5106
+ let pausedUntil = 0;
5107
+ const jittered = (ms) => Math.round(ms * (1 + random() * 0.5));
5108
+ async function backOff(attempt, said) {
5109
+ opts.onRetry?.();
5110
+ const ms = jittered(said ?? Math.min(BACKOFF_BASE_MS * 2 ** attempt, BACKOFF_CAP_MS));
5111
+ const until = now() + ms;
5112
+ pausedUntil = Math.max(pausedUntil, until);
5113
+ await wait(ms);
5114
+ return until;
5115
+ }
5116
+ async function respectPause(mine) {
5117
+ const left = pausedUntil - now();
5118
+ if (pausedUntil > mine && left > 0) await wait(left + Math.round(random() * 250));
5119
+ }
5120
+ const base = opts.apiUrl.replace(/\/+$/, "");
5121
+ const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
5122
+ async function send(method, path11, payload, retries = DEFAULT_RETRIES) {
5123
+ let last = {
5124
+ kind: "unavailable",
5125
+ status: null,
5126
+ detail: "no attempt was made"
5127
+ };
5128
+ let mine = 0;
5129
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
5130
+ await respectPause(mine);
5131
+ let res;
5132
+ try {
5133
+ res = await doFetch(`${base}${path11}`, {
5134
+ method,
5135
+ headers: { "content-type": payload?.type ?? "application/json", authorization: `Bearer ${opts.token}` },
5136
+ // A DELETE carries none. Sending `"undefined"` as a body is what a naive
5137
+ // `JSON.stringify(body)` would do, and some proxies answer that with a 400 nobody can
5138
+ // explain.
5139
+ ...payload === void 0 ? {} : { body: payload.body }
5140
+ });
5141
+ } catch (err) {
5142
+ last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
5143
+ if (attempt >= Math.min(retries, DEFAULT_RETRIES)) break;
5144
+ mine = await backOff(attempt, null);
5145
+ continue;
5146
+ }
5147
+ if (res.ok) {
5148
+ if (res.status === 204) return { ok: true, status: res.status, body: void 0 };
5149
+ try {
5150
+ return { ok: true, status: res.status, body: await res.json() };
5151
+ } catch {
5152
+ return { ok: false, kind: "other", status: res.status, detail: "the answer was not JSON" };
5153
+ }
5154
+ }
5155
+ const said = await detailOf(res);
5156
+ const kind = classify(res.status);
5157
+ last = { kind, status: res.status, detail: scrub(said.detail), ...said.code !== void 0 ? { code: said.code } : {}, ...said.shardsExpected !== void 0 ? { shardsExpected: said.shardsExpected } : {} };
5158
+ if (kind !== "unavailable") break;
5159
+ const said429 = parseRetryAfter(res.headers.get("retry-after"), now());
5160
+ if (res.status === 429 && (said.quota !== void 0 || said429 === null)) {
5161
+ last.kind = "invalid";
5162
+ last.detail = `quota exceeded (${said.quota === void 0 ? "no Retry-After" : scrub(describeQuota(said.quota))})`;
5163
+ if (said.detail) last.detail += ` \u2014 ${scrub(said.detail)}`;
5164
+ break;
5165
+ }
5166
+ if (attempt >= (said429 === null ? Math.min(retries, DEFAULT_RETRIES) : retries)) break;
5167
+ mine = await backOff(attempt, said429);
5168
+ }
5169
+ return { ok: false, ...last };
5170
+ }
5171
+ return {
5172
+ post: (path11, body, retries) => send("POST", path11, { body: JSON.stringify(body), type: "application/json" }, retries),
5173
+ upload: (path11, bytes, contentType) => send("POST", path11, { body: bytes, type: contentType }, uploadRetries ?? DEFAULT_RETRIES),
5174
+ del: (path11) => send("DELETE", path11),
5175
+ get: (path11) => send("GET", path11),
5176
+ async put(url, headers, source) {
5177
+ const putRetries = uploadRetries ?? 3;
5178
+ let last = { ok: false, status: null, code: "network" };
5179
+ let mine = 0;
5180
+ for (let attempt = 0; attempt <= putRetries; attempt += 1) {
5181
+ await respectPause(mine);
5182
+ try {
5183
+ let status;
5184
+ let retryAfter;
5185
+ if (opts.fetchImpl === void 0) ({ status, retryAfter } = await nodePut(url, headers, source, IDLE_MS));
5186
+ else {
5187
+ const body = "body" in source ? source.body : await (0, import_node_fs5.openAsBlob)(source.path);
5188
+ const res = await opts.fetchImpl(url, { method: "PUT", headers: withoutLength(headers), body });
5189
+ await res.arrayBuffer().catch(() => void 0);
5190
+ status = res.status;
5191
+ retryAfter = res.headers.get("retry-after");
5192
+ }
5193
+ if (status >= 200 && status <= 299) return { ok: true };
5194
+ last = { ok: false, status, code: `bucket_${status}` };
5195
+ if (status < 500 && status !== 429) return last;
5196
+ const said = parseRetryAfter(retryAfter, now());
5197
+ if (attempt >= (said === null ? Math.min(putRetries, 3) : putRetries)) return last;
5198
+ mine = await backOff(attempt, said);
5199
+ continue;
5200
+ } catch (err) {
5201
+ last = { ok: false, status: null, code: codeOfError(err) };
5202
+ }
5203
+ if (attempt >= Math.min(putRetries, 3)) return last;
5204
+ mine = await backOff(attempt, null);
5205
+ }
5206
+ return last;
5207
+ }
5208
+ };
5209
+ }
5210
+
5211
+ // src/reporter-core/env.ts
5212
+ init_cjs_shims();
5213
+ var path7 = __toESM(require("path"), 1);
5214
+ var UPLOAD_RETRIES = { min: 0, max: 20, default: 6 };
5215
+
5216
+ // src/reporter-core/session.ts
5217
+ init_cjs_shims();
5218
+ var import_node_crypto4 = require("crypto");
5219
+ var import_node_fs7 = require("fs");
5220
+ var import_node_path3 = require("path");
5221
+ var import_node_util2 = require("util");
5222
+ init_failure_detail();
5223
+
5224
+ // src/reporter-core/files-batch.ts
5225
+ init_cjs_shims();
5226
+ var import_node_crypto3 = require("crypto");
5227
+ var import_node_fs6 = require("fs");
5228
+ var FILES_BATCH_MAX = 100;
5229
+ var DIRECT_BATCH_BYTES = 6 * 1024 * 1024;
5230
+ var BATCH_PIPELINES = 2;
5231
+ async function sha256File(path11) {
5232
+ const hash = (0, import_node_crypto3.createHash)("sha256");
5233
+ for await (const part of (0, import_node_fs6.createReadStream)(path11)) hash.update(part);
5234
+ return hash.digest("hex");
5235
+ }
5236
+ var sha256Bytes = (bytes) => (0, import_node_crypto3.createHash)("sha256").update(bytes).digest("hex");
5237
+ var BUCKET_CODES = /* @__PURE__ */ new Set([
5238
+ "bucket_unreachable",
5239
+ "not_connected",
5240
+ "platform_not_configured",
5241
+ "upload_expired",
5242
+ "file_mismatch",
5243
+ "file_missing"
5244
+ ]);
5245
+
5246
+ // src/reporter-core/fallback.ts
5247
+ init_cjs_shims();
5248
+ var fs7 = __toESM(require("fs"), 1);
5249
+ var path8 = __toESM(require("path"), 1);
5250
+ var DEFAULT_FALLBACK_PATH = path8.join(".plune", "pending-results.jsonl");
5251
+
5252
+ // src/reporter-core/session.ts
5253
+ var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
5254
+ var SCREENSHOT_BYTES = 2 * 1024 * 1024;
5255
+ var SCREENSHOTS_PER_RESULT = 20;
5256
+ var TEXT_BYTES = 512 * 1024;
5257
+ var TEXTS_PER_RESULT = 10;
5258
+ var UTF8 = new import_node_util2.TextDecoder("utf-8", { fatal: true });
5259
+ var TYPE_BY_EXTENSION = {
5260
+ ".png": "image/png",
5261
+ ".jpg": "image/jpeg",
5262
+ ".jpeg": "image/jpeg",
5263
+ ".webp": "image/webp"
5264
+ };
5265
+ var METADATA_TYPE = "application/plune.metadata+json";
5266
+ var NAME_MAX = 200;
5267
+ function nameOf(file) {
5268
+ const own2 = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : (0, import_node_path3.basename)(file.path));
5269
+ const fileExt = file.path === void 0 ? "" : (0, import_node_path3.extname)(file.path);
5270
+ const ownExt = (0, import_node_path3.extname)(own2);
5271
+ const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
5272
+ const ext = typed ? ownExt : fileExt;
5273
+ let stem = typed ? own2.slice(0, -ownExt.length) : own2;
5274
+ if (stem.length + ext.length > NAME_MAX) {
5275
+ stem = stem.slice(0, Math.max(0, NAME_MAX - ext.length));
5276
+ if (/[\uD800-\uDBFF]$/.test(stem)) stem = stem.slice(0, -1);
5277
+ }
5278
+ return `${stem}${ext}`;
5279
+ }
5280
+ var SKIPPED = {
5281
+ hidden: "its name starts with an underscore, which hides an attachment in Playwright's own reports too",
5282
+ type: "Plune takes PNG, JPEG and WebP",
5283
+ limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
5284
+ missing: "the file cannot be read on this machine",
5285
+ size: "Plune takes a file of at most 2 MB",
5286
+ textLimit: `a result holds at most ${TEXTS_PER_RESULT} text files`,
5287
+ textSize: "Plune takes a text file of at most 512 KiB",
5288
+ empty: "the file is empty",
5289
+ binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
5290
+ encoding: "Plune takes UTF-8 text only",
5291
+ noStorage: "no storage bucket is connected to this project"
5292
+ };
5293
+ var BUCKET_FOUND = "plune: storage bucket found for this project \u2014 screenshots, text, trace and video go straight to it over short-lived links.";
5294
+ var KINDS = {
5295
+ screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
5296
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" },
5297
+ // Only the label is used: a file of this kind has no home in the database, so no ceiling of its own is known here.
5298
+ file: { label: "file", bytes: 0, room: 0, limit: "limit", size: "size" }
5299
+ };
5300
+ function kindOf2(type) {
5301
+ if (type.startsWith("image/")) return "screenshot";
5302
+ return TEXT_TYPES.has(type) ? "text" : "file";
5303
+ }
5304
+ var codeOf2 = (out) => out.code ?? (out.status === null ? "network" : `http_${out.status}`);
5305
+ function linkOf(item) {
5306
+ const link = item;
5307
+ if (typeof link?.id !== "string" || typeof link.url !== "string") return void 0;
5308
+ const headers = typeof link.headers === "object" && link.headers !== null ? link.headers : {};
5309
+ return { id: link.id, url: link.url, headers };
5310
+ }
5311
+ function textTypeOf(contentType, type) {
5312
+ const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
5313
+ return charset?.toLowerCase() === "utf-8" ? `${type}; charset=utf-8` : type;
5314
+ }
5315
+ function textRefusal(bytes) {
5316
+ if (bytes.length > TEXT_BYTES) return "textSize";
5317
+ if (bytes.length === 0) return "empty";
5318
+ if (bytes.includes(0)) return "binary";
5319
+ try {
5320
+ UTF8.decode(bytes);
5321
+ } catch {
5322
+ return "encoding";
5323
+ }
5324
+ return void 0;
5325
+ }
5326
+ var BATCH_BYTES = 8 * 1024 * 1024;
5327
+ var ENVELOPE_BYTES = Buffer.byteLength(JSON.stringify({ results: [] }));
5328
+ function chunk(items, size) {
5329
+ const out = [];
5330
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
5331
+ return out;
5332
+ }
5333
+ function fileSender(options) {
5334
+ const { client, log, stats, uploadsAtOnce, uploadRetries } = options;
5335
+ const without = options.without ?? "its result is reported without it";
5336
+ let retried = 0;
5337
+ let uploadMs = 0;
5338
+ let requests = 0;
5339
+ let existed = 0;
5340
+ let batchMissing = false;
5341
+ const skipsSaid = /* @__PURE__ */ new Set();
5342
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
5343
+ let bucketSeen = false;
5344
+ let noStorage = 0;
5345
+ let uploadsMissing = false;
5346
+ const failedSaid = /* @__PURE__ */ new Set();
5347
+ const codesSaid = /* @__PURE__ */ new Set();
5348
+ const rooms = /* @__PURE__ */ new Map();
5349
+ function skip(kind, name, why) {
5350
+ countsOf(kind).skipped += 1;
5351
+ if (why === "noStorage") noStorage += 1;
5352
+ const said = why === "noStorage" ? why : `${kind}/${why}`;
5353
+ if (skipsSaid.has(said)) return;
5354
+ skipsSaid.add(said);
5355
+ if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
5356
+ else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
5357
+ }
5358
+ const filesOf = (job) => `/v1/${job.owner ?? "results"}/${encodeURIComponent(job.id)}/files`;
5359
+ function ask(job, size) {
5360
+ requests += 1;
5361
+ return client.post(`${filesOf(job)}/uploads`, {
5362
+ files: [{ name: job.name, contentType: job.type, size }]
5363
+ }, uploadRetries);
5364
+ }
5365
+ function failed(job, why) {
5366
+ countsOf(job.kind).failed += 1;
5367
+ if (!failedSaid.has(job.kind)) {
5368
+ failedSaid.add(job.kind);
5369
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 ${without}.`);
5370
+ }
5371
+ }
5372
+ function failedToBucket(job, code) {
5373
+ countsOf(job.kind).failed += 1;
5374
+ if (codesSaid.has(code)) return;
5375
+ codesSaid.add(code);
5376
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 ${without}.`);
5377
+ }
5378
+ function refusedHere(job, size) {
5379
+ if (job.kind === "screenshot") {
5380
+ if (!SCREENSHOT_TYPES.has(job.type)) return "type";
5381
+ if (size > SCREENSHOT_BYTES) return "size";
5382
+ }
5383
+ if (job.kind === "text" && size > TEXT_BYTES) return "textSize";
5384
+ return void 0;
5385
+ }
5386
+ async function uploadDirect(job, size) {
5387
+ const { kind } = job;
5388
+ if (kind === "file") return skip(kind, job.name, "noStorage");
5389
+ const { bytes: ceiling, size: tooBig } = KINDS[kind];
5390
+ if (size > ceiling) return skip(kind, job.name, tooBig);
5391
+ let bytes;
5392
+ if (job.body !== void 0) bytes = job.body;
5393
+ else {
5394
+ try {
5395
+ bytes = await import_node_fs7.promises.readFile(job.path);
5396
+ } catch {
5397
+ return skip(kind, job.name, "missing");
5398
+ }
5399
+ }
5400
+ const refusal = kind === "text" ? textRefusal(bytes) : void 0;
5401
+ if (refusal !== void 0) return skip(kind, job.name, refusal);
5402
+ requests += 1;
5403
+ const out = await client.upload(
5404
+ `${filesOf(job)}?name=${encodeURIComponent(job.name)}`,
5405
+ bytes,
5406
+ job.type
5407
+ );
5408
+ if (out.ok) countsOf(kind).uploaded += 1;
5409
+ else failed(job, out.detail || out.kind);
5410
+ }
5411
+ async function uploadToBucket(job, size, first) {
5412
+ const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
5413
+ let link = first;
5414
+ for (let renewed = false; ; ) {
5415
+ const put = await client.put(link.url, link.headers, source);
5416
+ if (put.ok) break;
5417
+ if (put.status !== 403 || renewed) return failedToBucket(job, put.code);
5418
+ renewed = true;
5419
+ const again = await ask(job, size);
5420
+ if (!again.ok) return failedToBucket(job, codeOf2(again));
5421
+ const fresh = linkOf(again.body?.files?.[0]);
5422
+ if (fresh === void 0) return failedToBucket(job, "bad_answer");
5423
+ link = fresh;
5424
+ }
5425
+ requests += 1;
5426
+ const done = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
5427
+ if (!done.ok) return failedToBucket(job, codeOf2(done));
5428
+ countsOf(job.kind).uploaded += 1;
5429
+ }
5430
+ let free = uploadsAtOnce;
5431
+ const waiting = [];
5432
+ async function gated(work) {
5433
+ if (free === 0) await new Promise((resolve9) => waiting.push(resolve9));
5434
+ else free -= 1;
5435
+ try {
5436
+ return await work();
5437
+ } finally {
5438
+ const next = waiting.shift();
5439
+ if (next !== void 0) next();
5440
+ else free += 1;
5441
+ }
5442
+ }
5443
+ async function plan(job) {
5444
+ const { kind } = job;
5445
+ let size;
5446
+ if (job.body !== void 0) size = job.body.length;
5447
+ else if (job.path === void 0) return void skip(kind, job.name, "missing");
5448
+ else {
5449
+ try {
5450
+ size = (await import_node_fs7.promises.stat(job.path)).size;
5451
+ } catch {
5452
+ return void skip(kind, job.name, "missing");
5453
+ }
5454
+ }
5455
+ if (size === 0) return void skip(kind, job.name, "empty");
5456
+ const direct = () => {
5457
+ if (kind === "file") return void skip(kind, job.name, "noStorage");
5458
+ const roomKey = `${job.id}/${kind}`;
5459
+ const left = rooms.get(roomKey) ?? KINDS[kind].room;
5460
+ if (left === 0) return void skip(kind, job.name, KINDS[kind].limit);
5461
+ rooms.set(roomKey, left - 1);
5462
+ return () => uploadDirect(job, size);
5463
+ };
5464
+ if (uploadsMissing) return direct();
5465
+ const out = await gated(() => ask(job, size));
5466
+ if (!out.ok) {
5467
+ if (out.status === 404 && out.detail === "" && out.code === void 0) {
5468
+ uploadsMissing = true;
5469
+ return direct();
5470
+ }
5471
+ if (out.code !== void 0) failedToBucket(job, out.code);
5472
+ else failed(job, out.detail || out.kind);
5473
+ return void 0;
5474
+ }
5475
+ const item = out.body?.files?.[0];
5476
+ if (item?.skipped === "no_storage") return void skip(kind, job.name, refusedHere(job, size) ?? "noStorage");
5477
+ if (item?.direct === true) return direct();
5478
+ const link = linkOf(item);
5479
+ if (link === void 0) return void failed(job, "bad_answer");
5480
+ if (!bucketSeen) {
5481
+ bucketSeen = true;
5482
+ log(BUCKET_FOUND);
5483
+ }
5484
+ return () => uploadToBucket(job, size, link);
5485
+ }
5486
+ async function uploadEach(jobs) {
5487
+ const byResult = /* @__PURE__ */ new Map();
5488
+ for (const job of jobs) byResult.set(job.id, [...byResult.get(job.id) ?? [], job]);
5489
+ await Promise.all(
5490
+ [...byResult.values()].map(async (group) => {
5491
+ const work = [];
5492
+ for (const job of group) {
5493
+ const act = await plan(job);
5494
+ if (act !== void 0) work.push(gated(act));
5495
+ }
5496
+ await Promise.all(work);
5497
+ })
5498
+ );
5499
+ }
5500
+ async function measure(job) {
5501
+ let size;
5502
+ if (job.body !== void 0) size = job.body.length;
5503
+ else if (job.path === void 0) return void skip(job.kind, job.name, "missing");
5504
+ else {
5505
+ try {
5506
+ size = (await import_node_fs7.promises.stat(job.path)).size;
5507
+ } catch {
5508
+ return void skip(job.kind, job.name, "missing");
5509
+ }
5510
+ }
5511
+ if (size === 0) return void skip(job.kind, job.name, "empty");
5512
+ return size;
5513
+ }
5514
+ const routeMissing = (out) => !out.ok && out.status === 404 && out.detail === "" && out.code === void 0;
5515
+ function takeRoom(job) {
5516
+ if (job.kind === "file") {
5517
+ skip(job.kind, job.name, "noStorage");
5518
+ return false;
5519
+ }
5520
+ const roomKey = `${job.id}/${job.kind}`;
5521
+ const left = rooms.get(roomKey) ?? KINDS[job.kind].room;
5522
+ if (left === 0) {
5523
+ skip(job.kind, job.name, KINDS[job.kind].limit);
5524
+ return false;
5525
+ }
5526
+ rooms.set(roomKey, left - 1);
5527
+ return true;
5528
+ }
5529
+ function refusedItem(job, size, item) {
5530
+ const code = item.code ?? "refused";
5531
+ if (code === "duplicate") existed += 1;
5532
+ else if (code === "no_storage") skip(job.kind, job.name, refusedHere(job, size) ?? "noStorage");
5533
+ else if (code === "too_many_files") skip(job.kind, job.name, KINDS[job.kind].limit);
5534
+ else if (BUCKET_CODES.has(code)) failedToBucket(job, code);
5535
+ else failed(job, code);
5536
+ }
5537
+ const itemPause = (round) => new Promise((r) => setTimeout(r, Math.min(250 * 2 ** round, 4e3)));
5538
+ async function batchOf(jobs) {
5539
+ if (batchMissing) return uploadEach(jobs);
5540
+ const sized = [];
5541
+ for (const job of jobs) {
5542
+ const size = await measure(job);
5543
+ if (size === void 0) continue;
5544
+ try {
5545
+ sized.push({ job, size, sha256: job.body !== void 0 ? sha256Bytes(job.body) : await sha256File(job.path) });
5546
+ } catch {
5547
+ skip(job.kind, job.name, "missing");
5548
+ }
5549
+ }
5550
+ if (sized.length === 0) return;
5551
+ const announced = await gated(() => {
5552
+ requests += 1;
5553
+ return client.post(
5554
+ "/v1/files/uploads-batch",
5555
+ { items: sized.map((s) => ({ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 })) },
5556
+ uploadRetries
5557
+ );
5558
+ });
5559
+ if (routeMissing(announced)) {
5560
+ batchMissing = true;
5561
+ return uploadEach(sized.map((s) => s.job));
5562
+ }
5563
+ const verdicts = announced.ok ? announced.body?.items : void 0;
5564
+ if (!announced.ok || !Array.isArray(verdicts) || verdicts.length !== sized.length) {
5565
+ for (const s of sized) {
5566
+ if (announced.ok) failed(s.job, "bad_answer");
5567
+ else if (announced.code !== void 0) failedToBucket(s.job, announced.code);
5568
+ else failed(s.job, announced.detail || announced.kind);
5569
+ }
5570
+ return;
5571
+ }
5572
+ const puts = [];
5573
+ const directs = [];
5574
+ sized.forEach((s, i) => {
5575
+ const v = verdicts[i] ?? {};
5576
+ if (v.status === "exists") existed += 1;
5577
+ else if (v.status === "direct") {
5578
+ if (takeRoom(s.job)) directs.push(s);
5579
+ } else if (v.status === "upload") {
5580
+ const link = linkOf(v);
5581
+ if (link === void 0) return failed(s.job, "bad_answer");
5582
+ if (!bucketSeen) {
5583
+ bucketSeen = true;
5584
+ log(BUCKET_FOUND);
5585
+ }
5586
+ puts.push({ s, link });
5587
+ } else if (v.status === "refused") refusedItem(s.job, s.size, v);
5588
+ else failed(s.job, "bad_answer");
5589
+ });
5590
+ const toComplete = [];
5591
+ await Promise.all(
5592
+ puts.map(
5593
+ ({ s, link: first }) => gated(async () => {
5594
+ const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
5595
+ let link = first;
5596
+ for (let renewed = false; ; ) {
5597
+ const put = await client.put(link.url, link.headers, source);
5598
+ if (put.ok) break;
5599
+ if (put.status !== 403 || renewed) return failedToBucket(s.job, put.code);
5600
+ renewed = true;
5601
+ requests += 1;
5602
+ const again = await client.post(
5603
+ "/v1/files/uploads-batch",
5604
+ { items: [{ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 }] },
5605
+ uploadRetries
5606
+ );
5607
+ const fresh = again.ok ? linkOf(again.body?.items?.[0]) : void 0;
5608
+ if (fresh === void 0) return failedToBucket(s.job, again.ok ? "bad_answer" : codeOf2(again));
5609
+ link = fresh;
5610
+ }
5611
+ toComplete.push({ job: s.job, id: link.id });
5612
+ })
5613
+ )
5614
+ );
5615
+ await complete(toComplete);
5616
+ await sendDirect(directs);
5617
+ }
5618
+ async function complete(items) {
5619
+ for (let round = 0; items.length > 0; round += 1) {
5620
+ const out = await gated(() => {
5621
+ requests += 1;
5622
+ return client.post("/v1/files/complete-batch", { ids: items.map((i) => i.id) }, uploadRetries);
5623
+ });
5624
+ if (routeMissing(out)) {
5625
+ await Promise.all(
5626
+ items.map(
5627
+ (i) => gated(async () => {
5628
+ requests += 1;
5629
+ const one = await client.post(`/v1/files/${encodeURIComponent(i.id)}/complete`, {}, uploadRetries);
5630
+ if (one.ok) countsOf(i.job.kind).uploaded += 1;
5631
+ else failedToBucket(i.job, codeOf2(one));
5632
+ })
5633
+ )
5634
+ );
5635
+ return;
5636
+ }
5637
+ const verdicts = out.ok ? out.body?.items : void 0;
5638
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== items.length) {
5639
+ for (const i of items) failedToBucket(i.job, out.ok ? "bad_answer" : codeOf2(out));
5640
+ return;
5641
+ }
5642
+ const again = [];
5643
+ items.forEach((i, at) => {
5644
+ const v = verdicts[at] ?? {};
5645
+ if (v.status === "ready") countsOf(i.job.kind).uploaded += 1;
5646
+ else if (v.retryable === true && round < Math.min(uploadRetries, 3)) again.push(i);
5647
+ else refusedItem(i.job, 0, v.status === "refused" ? v : { code: "bad_answer" });
5648
+ });
5649
+ items = again;
5650
+ if (items.length > 0) {
5651
+ retried += items.length;
5652
+ await itemPause(round);
5653
+ }
5654
+ }
5655
+ }
5656
+ async function sendDirect(items) {
5657
+ const groups = [];
5658
+ let bytes = 0;
5659
+ for (const item of items) {
5660
+ const group = groups[groups.length - 1];
5661
+ if (group === void 0 || group.length >= FILES_BATCH_MAX || bytes + item.size > DIRECT_BATCH_BYTES) {
5662
+ groups.push([item]);
5663
+ bytes = item.size;
5664
+ } else {
5665
+ group.push(item);
5666
+ bytes += item.size;
5667
+ }
5668
+ }
5669
+ for (const group of groups) {
5670
+ const body = [];
5671
+ const sent = [];
5672
+ for (const { job, size } of group) {
5673
+ const { kind } = job;
5674
+ if (size > KINDS[kind].bytes) {
5675
+ skip(kind, job.name, KINDS[kind].size);
5676
+ continue;
5677
+ }
5678
+ let data;
5679
+ try {
5680
+ data = job.body ?? await import_node_fs7.promises.readFile(job.path);
5681
+ } catch {
5682
+ skip(kind, job.name, "missing");
5683
+ continue;
5684
+ }
5685
+ const refusal = kind === "text" ? textRefusal(data) : void 0;
5686
+ if (refusal !== void 0) {
5687
+ skip(kind, job.name, refusal);
5688
+ continue;
5689
+ }
5690
+ body.push({ resultId: job.id, name: job.name, contentType: job.type, data: data.toString("base64") });
5691
+ sent.push({ job, size });
5692
+ }
5693
+ if (body.length === 0) continue;
5694
+ const out = await gated(() => {
5695
+ requests += 1;
5696
+ return client.post("/v1/files/direct-batch", { items: body }, uploadRetries);
5697
+ });
5698
+ if (routeMissing(out)) {
5699
+ batchMissing = true;
5700
+ for (const { job, size } of sent) await gated(() => uploadDirect(job, size));
5701
+ continue;
5702
+ }
5703
+ const verdicts = out.ok ? out.body?.items : void 0;
5704
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== sent.length) {
5705
+ for (const { job } of sent) failed(job, out.ok ? "bad_answer" : out.detail || out.kind);
5706
+ continue;
5707
+ }
5708
+ sent.forEach(({ job }, i) => {
5709
+ const v = verdicts[i] ?? {};
5710
+ if (v.status === "stored") countsOf(job.kind).uploaded += 1;
5711
+ else if (v.status === "exists") existed += 1;
5712
+ else refusedItem(job, 0, v.status === "refused" ? v : { code: "bad_answer" });
5713
+ });
5714
+ }
5715
+ }
5716
+ async function uploadBatched(jobs) {
5717
+ const batches = chunk(jobs, FILES_BATCH_MAX);
5718
+ let next = 0;
5719
+ await Promise.all(
5720
+ Array.from({ length: Math.min(BATCH_PIPELINES, batches.length) }, async () => {
5721
+ for (let at = next++; at < batches.length; at = next++) await batchOf(batches[at]);
5722
+ })
5723
+ );
5724
+ }
5725
+ async function upload(items, filesByKey) {
5726
+ if (filesByKey.size === 0 || !Array.isArray(items)) return;
5727
+ const jobs = [];
5728
+ for (const item of items) {
5729
+ if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
5730
+ for (const file of filesByKey.get(item.resultKey) ?? []) {
5731
+ const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[(0, import_node_path3.extname)(file.path).toLowerCase()]);
5732
+ if (type === void 0 || type === METADATA_TYPE) continue;
5733
+ const kind = kindOf2(type);
5734
+ if (kind !== "text" && file.path === void 0) continue;
5735
+ const name = nameOf(file);
5736
+ if (file.name.startsWith("_")) skip(kind, name, "hidden");
5737
+ else {
5738
+ jobs.push({
5739
+ id: item.id,
5740
+ kind,
5741
+ name,
5742
+ type: kind === "text" ? textTypeOf(file.contentType ?? "", type) : type,
5743
+ ...file.body !== void 0 ? { body: file.body } : {},
5744
+ ...file.path !== void 0 ? { path: file.path } : {}
5745
+ });
5746
+ }
5747
+ }
5748
+ }
5749
+ const started = Date.now();
5750
+ if (batchMissing) await uploadEach(jobs);
5751
+ else await uploadBatched(jobs);
5752
+ uploadMs += Date.now() - started;
5753
+ }
5754
+ return {
5755
+ upload,
5756
+ uploadEach,
5757
+ onRetry: () => void (retried += 1),
5758
+ get bucketSeen() {
5759
+ return bucketSeen;
5760
+ },
5761
+ get noStorage() {
5762
+ return noStorage;
5763
+ },
5764
+ get existed() {
5765
+ return existed;
5766
+ },
5767
+ get retried() {
5768
+ return retried;
5769
+ },
5770
+ get uploadMs() {
5771
+ return uploadMs;
5772
+ },
5773
+ get requests() {
5774
+ return requests;
5775
+ }
5776
+ };
5777
+ }
5778
+
5779
+ // src/cli/commands/cairn-artifact.ts
5780
+ init_cjs_shims();
5781
+ var fs8 = __toESM(require("fs/promises"), 1);
5782
+ var path9 = __toESM(require("path"), 1);
5783
+
5784
+ // src/mcp-testing/scan/config/config.ts
5785
+ init_cjs_shims();
5786
+
5787
+ // src/mcp-testing/report/human.ts
5788
+ init_cjs_shims();
5789
+ init_failure_detail();
5790
+
5791
+ // src/mcp-testing/conformance/score.ts
5792
+ init_cjs_shims();
5793
+ init_exit_codes();
5794
+
5795
+ // src/mcp-testing/conformance/catalog.ts
5796
+ init_cjs_shims();
5797
+
5798
+ // src/mcp-testing/conformance/apps-catalog.ts
5799
+ init_cjs_shims();
5800
+ var BOTH = ["legacy", "modern"];
5801
+ var APPS_SPEC_URL = "https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx";
5802
+ var ref = (section) => ({
5803
+ revision: "2026-01-26",
5804
+ page: "apps.mdx",
5805
+ section,
5806
+ url: APPS_SPEC_URL
5807
+ });
5808
+ var FORMAT = "UI Resource Format";
5809
+ var DISCOVERY = "Resource Discovery";
5810
+ var apps = (s) => ({
5811
+ ...s,
5812
+ suite: "apps",
5813
+ kind: "check",
5814
+ derived: s.derived ?? false,
5815
+ needsFixture: s.needsFixture ?? false,
5816
+ transports: ["stdio", "http"],
5817
+ eras: BOTH
5818
+ });
5819
+ var APPS_CATALOG = [
5820
+ apps({
5821
+ id: "apps-ui-resource-uri-scheme",
5822
+ title: "The address of a UI resource starts with ui://",
5823
+ description: "Every _meta.ui.resourceUri a tool names is a string that starts with ui://, and so is the address of every listed resource of the MCP Apps media type.",
5824
+ level: "MUST",
5825
+ derived: true,
5826
+ derivation: 'UIResource.uri: "MUST use the `ui://` URI scheme to distinguish UI resources from other MCP resource types."; Content Requirements: "URI MUST start with `ui://` scheme". Both sentences are about the address of a UI resource; that the address a tool names in _meta.ui.resourceUri ("URI of UI resource for rendering tool results") is one, and that a listed resource of the MCP Apps media type is one, is read from the text.',
5827
+ specRefs: [ref(FORMAT), ref(DISCOVERY)]
5828
+ }),
5829
+ apps({
5830
+ id: "apps-ui-resource-exists",
5831
+ title: "The resource a tool names can be read",
5832
+ description: "resources/read of each ui:// resource a tool names in _meta.ui.resourceUri answers a result with contents. The error of the revision of the session for a resource that does not exist (-32002 up to 2025-11-25, -32602 from 2026-07-28) is a failure; any other error, and an empty contents list, say nothing of whether the resource exists and are could-not-run. Over 32 addresses, the rest are not read and the verdict is could-not-run.",
5833
+ level: "MUST",
5834
+ derived: true,
5835
+ derivation: `Resource Discovery, Behavior: "Resource MUST exist on the server". The extension text names no error for a missing resource, so which answer says it is missing is taken from the core protocol's answer to resources/read of a resource that does not exist in the revision of the session: -32002 up to 2025-11-25 (resources-read-not-found), -32602 from 2026-07-28 (mod-resource-not-found). Any other error says nothing of whether the resource exists.`,
5836
+ specRefs: [ref(DISCOVERY)]
5837
+ }),
5838
+ apps({
5839
+ id: "apps-ui-mime-type",
5840
+ title: "The content of a UI resource is text/html;profile=mcp-app",
5841
+ description: 'Each content that resources/read answers for a UI resource has the mimeType text/html;profile=mcp-app (compared as a media type: letter case and spaces around ";" do not matter).',
5842
+ level: "MUST",
5843
+ derivation: 'Content Requirements: "`mimeType` MUST be `text/html;profile=mcp-app` (other types reserved for future extensions)"',
5844
+ specRefs: [ref(FORMAT)]
5845
+ }),
5846
+ apps({
5847
+ id: "apps-ui-content-payload",
5848
+ title: "The content is one of text and blob, and is an HTML5 document",
5849
+ description: "Each content of a UI resource has exactly one of text (a string) and blob (base64), and the HTML it holds opens with an HTML5 doctype. A resource over 4 MiB, or with comments or white space past the first 2048 characters before the doctype, is not judged: could-not-run.",
5850
+ level: "MUST",
5851
+ derived: true,
5852
+ derivation: 'Content Requirements: "Content MUST be provided via either `text` (string) or `blob` (base64-encoded)" and "Content MUST be valid HTML5 document". The text gives no criterion for a valid HTML5 document (its example is `<!DOCTYPE html><html>...</html>`); this checker judges the least: the document opens with the HTML5 doctype (after a byte order mark, white space and comments). It never parses, opens or runs the HTML. "either ... or" is read as exactly one of the two.',
5853
+ specRefs: [ref(FORMAT)]
5854
+ }),
5855
+ apps({
5856
+ id: "apps-ui-listed-mime",
5857
+ title: "A listed UI resource has the mimeType text/html;profile=mcp-app",
5858
+ description: "Every ui:// resource in resources/list that has a mimeType has text/html;profile=mcp-app; a listed resource without one is not judged (the field is optional, and the sentence is about its value). A server may leave UI-only resources out of the list; then there is nothing to read.",
5859
+ level: "SHOULD",
5860
+ derivation: 'UIResource.mimeType: "SHOULD be `text/html;profile=mcp-app` for HTML-based UIs in the initial MVP."',
5861
+ specRefs: [ref(FORMAT)]
5862
+ }),
5863
+ apps({
5864
+ id: "apps-ui-visibility-values",
5865
+ title: "visibility holds only model and app",
5866
+ description: 'Where a tool sets _meta.ui.visibility, it is an array whose every element is "model" or "app".',
5867
+ level: "SHOULD",
5868
+ derived: true,
5869
+ derivation: 'No sentence says MUST or SHOULD about the values: McpUiToolMeta types visibility as `Array<"model" | "app">` and lists the two values ("`"model"`: Tool is visible to and callable by the agent", "`"app"`: Tool is callable by the app from the same server connection only"); Visibility: "`visibility` defaults to `["model", "app"]` if omitted". A requirement the text states only as a type has no keyword, so the level is SHOULD.',
5870
+ specRefs: [ref(DISCOVERY)]
5871
+ }),
5872
+ apps({
5873
+ id: "apps-ui-tool-text-fallback",
5874
+ title: "A tool with a UI also returns content",
5875
+ description: "A tool that has _meta.ui and that --fixture names is called, and its result has a content array with at least one block that says something: a text that is not blank, an image, audio, a resource or a resource link. Only the tools the fixture names are called; without one the check is could-not-run (needs-input).",
5876
+ level: "MUST",
5877
+ needsFixture: true,
5878
+ derivation: 'Graceful Degradation: "Tools MUST return meaningful content array even when UI is available". The text does not say what is meaningful; only an absent, empty or blank content is judged. A result with isError is not judged.',
5879
+ specRefs: [ref("Client<>Server Capability Negotiation")]
5880
+ }),
5881
+ apps({
5882
+ id: "apps-ui-meta-shapes",
5883
+ title: "csp, permissions, domain and prefersBorder have the shapes of the text",
5884
+ description: "In _meta.ui of a listed or read UI resource: csp is an object whose connectDomains, resourceDomains, frameDomains and baseUriDomains are arrays of strings; permissions is an object whose camera, microphone, geolocation and clipboardWrite are objects; domain is a string; prefersBorder is a boolean. A tool's _meta.ui is an object. Other members are not judged, and neither is the format of a domain (it depends on the host).",
5885
+ level: "SHOULD",
5886
+ derived: true,
5887
+ derivation: 'The shapes are those of the interfaces UIResourceMeta and McpUiResourceCsp; no sentence says MUST or SHOULD about them. For domain the text says "Servers MUST consult host-specific documentation for the expected domain format", which no check can read. A requirement the text states only as a type has no keyword, so the level is SHOULD.',
5888
+ specRefs: [ref(FORMAT)]
5889
+ })
5890
+ ];
5891
+
5892
+ // src/mcp-testing/conformance/auth-catalog.ts
5893
+ init_cjs_shims();
5894
+ var L = "2025-11-25";
5895
+ var M = "2026-07-28";
5896
+ var BOTH2 = ["legacy", "modern"];
5897
+ var MODERN = ["modern"];
5898
+ var ref2 = (revision, page, section) => ({
5899
+ revision,
5900
+ page,
5901
+ section
5902
+ });
5903
+ var AUTH = "basic/authorization";
5904
+ var DISCOVERY2 = "basic/authorization/authorization-server-discovery";
5905
+ var SECURITY = "basic/authorization/security-considerations";
5906
+ var REGISTRATION = "basic/authorization/client-registration";
5907
+ var oauth = (s) => ({
5908
+ ...s,
5909
+ suite: "oauth",
5910
+ kind: "check",
5911
+ derived: s.derived ?? false,
5912
+ needsFixture: s.needsFixture ?? false,
5913
+ transports: ["http"]
5914
+ });
5915
+ var OAUTH_CATALOG = [
5916
+ oauth({
5917
+ id: "oauth-requires-auth",
5918
+ title: "A request without a token gets 401",
5919
+ description: "The MCP endpoint, asked without a token, answers 401 Unauthorized. A 2xx answer means the server is public: every check of the suite is then not-applicable (no-auth).",
5920
+ level: "MUST",
5921
+ specRefs: [ref2(L, AUTH, "Error Handling"), ref2(M, AUTH, "Error Handling")],
5922
+ eras: BOTH2
5923
+ }),
5924
+ oauth({
5925
+ id: "oauth-challenge-bearer",
5926
+ title: "The 401 carries a Bearer challenge",
5927
+ description: "The 401 answer has a WWW-Authenticate header with the scheme Bearer.",
5928
+ level: "MUST",
5929
+ derived: true,
5930
+ derivation: `RFC 6750 section 3: "All challenges defined by this specification MUST use the auth-scheme value Bearer"; basic/authorization, Protected Resource Metadata Discovery Requirements: clients MUST be able to parse WWW-Authenticate headers of 401 answers. No MCP sentence says MUST about the scheme of the server's challenge.`,
5931
+ specRefs: [
5932
+ ref2(L, AUTH, "Protected Resource Metadata Discovery Requirements"),
5933
+ ref2(M, DISCOVERY2, "Protected Resource Metadata Discovery Requirements")
5934
+ ],
5935
+ eras: BOTH2
5936
+ }),
5937
+ oauth({
5938
+ id: "oauth-prm-reachable",
5939
+ title: "The protected resource metadata can be found",
5940
+ description: "The server implements at least one of the two mechanisms: resource_metadata in WWW-Authenticate, or a document at the RFC 9728 well-known URI (with the path of the endpoint, or at the root). At least one of them serves a JSON document.",
5941
+ level: "MUST",
5942
+ specRefs: [
5943
+ ref2(L, AUTH, "Protected Resource Metadata Discovery Requirements"),
5944
+ ref2(M, DISCOVERY2, "Protected Resource Metadata Discovery Requirements")
5945
+ ],
5946
+ eras: BOTH2
5947
+ }),
5948
+ oauth({
5949
+ id: "oauth-challenge-metadata-url",
5950
+ title: "resource_metadata names a URL that serves the document",
5951
+ description: "When WWW-Authenticate has resource_metadata, it is an absolute URL and it answers 200 with a JSON object. A challenge without the parameter is not a violation: the well-known URI is the other mechanism.",
5952
+ level: "MUST",
5953
+ derived: true,
5954
+ derivation: 'RFC 9728 section 5.1 defines resource_metadata as "the URL of the protected resource metadata". The MCP text makes the parameter one of two mechanisms, so only a parameter that is present is judged.',
5955
+ specRefs: [
5956
+ ref2(L, AUTH, "Protected Resource Metadata Discovery Requirements"),
5957
+ ref2(M, DISCOVERY2, "Protected Resource Metadata Discovery Requirements")
5958
+ ],
5959
+ eras: BOTH2
5960
+ }),
5961
+ oauth({
5962
+ id: "oauth-prm-valid",
5963
+ title: "The protected resource metadata names an authorization server",
5964
+ description: "The document is a JSON object whose authorization_servers lists at least one URL, and whose resource is the URL of the server under test (or the resource named in the configuration).",
5965
+ level: "MUST",
5966
+ derived: true,
5967
+ derivation: `authorization_servers: quoted ("MUST include the authorization_servers field containing at least one authorization server"). resource: RFC 9728 section 3.3 ("The resource value returned MUST be identical to the protected resource's resource identifier"), read from the RFC, not from the MCP text.`,
5968
+ specRefs: [
5969
+ ref2(L, AUTH, "Authorization Server Location"),
5970
+ ref2(M, DISCOVERY2, "Authorization Server Location")
5971
+ ],
5972
+ eras: BOTH2
5973
+ }),
5974
+ oauth({
5975
+ id: "oauth-challenge-scope",
5976
+ title: "The 401 names the scope it needs",
5977
+ description: "WWW-Authenticate has a scope parameter.",
5978
+ level: "SHOULD",
5979
+ specRefs: [
5980
+ ref2(L, AUTH, "Protected Resource Metadata Discovery Requirements"),
5981
+ ref2(M, AUTH, "Scope Selection Strategy")
5982
+ ],
5983
+ eras: BOTH2
5984
+ }),
5985
+ oauth({
5986
+ id: "oauth-as-metadata-discoverable",
5987
+ title: "The authorization server publishes metadata",
5988
+ description: "For the first authorization_servers entry, a JSON document is served at one of the well-known locations in the order of the specification: RFC 8414 and OpenID Connect Discovery with the path inserted, OpenID Connect Discovery with the path appended (an issuer with a path), or RFC 8414 and OpenID Connect Discovery at the root (an issuer without one).",
5989
+ level: "MUST",
5990
+ specRefs: [
5991
+ ref2(L, AUTH, "Authorization Server Metadata Discovery"),
5992
+ ref2(M, DISCOVERY2, "Authorization Server Metadata Discovery")
5993
+ ],
5994
+ eras: BOTH2
5995
+ }),
5996
+ oauth({
5997
+ id: "oauth-as-issuer-matches",
5998
+ title: "The issuer of the metadata is the issuer it was found by",
5999
+ description: "The issuer member of the metadata document is identical, character for character, to the issuer identifier the well-known URL was built from.",
6000
+ level: "MUST",
6001
+ derived: true,
6002
+ derivation: '2026-07-28 authorization-server-discovery quotes the rule as a duty of the client ("the issuer value in the document MUST be identical to the issuer identifier used to construct the well-known URL"), from RFC 8414 section 3.3; that the server serves such a document is derived. 2025-11-25 has no such sentence, so the check is for the modern era only.',
6003
+ specRefs: [ref2(M, DISCOVERY2, "Authorization Server Metadata Discovery")],
6004
+ eras: MODERN
6005
+ }),
6006
+ oauth({
6007
+ id: "oauth-as-https",
6008
+ title: "The authorization endpoints are HTTPS",
6009
+ description: "The authorization, token and registration endpoints in the metadata are https URLs. An authorization server on a loopback name is not-applicable: the test setup of a local server.",
6010
+ level: "MUST",
6011
+ specRefs: [ref2(L, AUTH, "Communication Security"), ref2(M, SECURITY, "Communication Security")],
6012
+ eras: BOTH2
6013
+ }),
6014
+ oauth({
6015
+ id: "oauth-as-pkce-advertised",
6016
+ title: "The authorization server advertises PKCE",
6017
+ description: "The metadata has code_challenge_methods_supported.",
6018
+ level: "MUST",
6019
+ derived: true,
6020
+ derivation: 'Authorization Code Protection: "If code_challenge_methods_supported is absent, the authorization server does not support PKCE and MCP clients MUST refuse to proceed" (a duty of the client); "Authorization servers providing OpenID Connect Discovery MUST include code_challenge_methods_supported in their metadata" (quoted, for those servers only).',
6021
+ specRefs: [
6022
+ ref2(L, AUTH, "Authorization Code Protection"),
6023
+ ref2(M, SECURITY, "Authorization Code Protection")
6024
+ ],
6025
+ eras: BOTH2
6026
+ }),
6027
+ oauth({
6028
+ id: "oauth-as-pkce-s256",
6029
+ title: "PKCE with S256 is advertised",
6030
+ description: "code_challenge_methods_supported lists S256.",
6031
+ level: "SHOULD",
6032
+ derived: true,
6033
+ derivation: "The text says clients MUST use S256 when technically capable; that the server lists it is derived. The specification checks only that the field is present.",
6034
+ specRefs: [
6035
+ ref2(L, AUTH, "Authorization Code Protection"),
6036
+ ref2(M, SECURITY, "Authorization Code Protection")
6037
+ ],
6038
+ eras: BOTH2
6039
+ }),
6040
+ oauth({
6041
+ id: "oauth-as-iss-advertised",
6042
+ title: "The authorization server advertises the iss parameter",
6043
+ description: "The metadata has authorization_response_iss_parameter_supported: true.",
6044
+ level: "SHOULD",
6045
+ specRefs: [ref2(M, AUTH, "Authorization Response Validation")],
6046
+ eras: MODERN
6047
+ }),
6048
+ oauth({
6049
+ id: "oauth-as-cimd-advertised",
6050
+ title: "The authorization server advertises Client ID Metadata Documents",
6051
+ description: "The metadata has client_id_metadata_document_supported: true.",
6052
+ level: "SHOULD",
6053
+ specRefs: [
6054
+ ref2(L, AUTH, "Client ID Metadata Documents"),
6055
+ ref2(M, REGISTRATION, "Client ID Metadata Documents")
6056
+ ],
6057
+ eras: BOTH2
6058
+ }),
6059
+ oauth({
6060
+ id: "oauth-neg-invalid-token-401",
6061
+ title: "A token that is not valid gets 401",
6062
+ description: "A request with a bearer token the authorization server never issued answers 401.",
6063
+ level: "MUST",
6064
+ specRefs: [ref2(L, AUTH, "Token Handling"), ref2(M, AUTH, "Token Handling")],
6065
+ eras: BOTH2
6066
+ }),
6067
+ oauth({
6068
+ id: "oauth-neg-wrong-audience",
6069
+ title: "A token issued for another resource is refused",
6070
+ description: "A token the authorization server issued for another resource (the resource parameter names a different URL) gets 401 from the server under test, while a token issued for the server itself is accepted (the control: a server that refuses every token proves nothing). Needs credentials the authorization server accepts for the client-credentials grant, given in --config.",
6071
+ level: "MUST",
6072
+ specRefs: [
6073
+ ref2(L, AUTH, "Token Handling"),
6074
+ ref2(L, AUTH, "Access Token Privilege Restriction"),
6075
+ ref2(M, AUTH, "Token Handling"),
6076
+ ref2(M, SECURITY, "Token Audience Binding and Validation")
6077
+ ],
6078
+ eras: BOTH2,
6079
+ needsFixture: true
6080
+ }),
6081
+ oauth({
6082
+ id: "oauth-e2e-token-works",
6083
+ title: "A token issued for the server is accepted",
6084
+ description: "With the client-credentials grant given in --config, the client asks the token endpoint of the authorization server for a token for the server (the resource parameter), and makes the one request the suite uses to tell a protected server from an open one with it. The request that got 401 without a token must now succeed. A 2xx is a pass. A 401 is a failure only when the token is of type Bearer, is a JWT whose aud holds the resource asked for, and the challenge does not name insufficient_scope; in every other case (another token type, an opaque token or an aud that does not show the audience, insufficient_scope, a token endpoint that refuses the client, 403 or another answer) the check is could-not-run. The token is masked in every output and is not revoked.",
6085
+ level: "MUST",
6086
+ derived: true,
6087
+ derivation: 'Token Handling quotes "MCP servers MUST only accept tokens that are valid for use with their own resources" and "Invalid or expired tokens MUST receive a HTTP 401 response". That a token is valid for the server is not a given: the check verifies from the token what it can (a Bearer token type, and a JWT aud that holds the resource asked for) and, when it cannot, the verdict is could-not-run. A 401 to a token so shown is the converse of what is quoted: derived, and not higher than the quoted MUST. Assumption stated: clock skew between the authorization server and the server cannot be told apart from a refusal.',
6088
+ specRefs: [ref2(L, AUTH, "Token Handling"), ref2(M, AUTH, "Token Handling")],
6089
+ eras: BOTH2,
6090
+ needsFixture: true
6091
+ }),
6092
+ oauth({
6093
+ id: "oauth-neg-insufficient-scope",
6094
+ title: "A token with too narrow a scope gets 403 with insufficient_scope",
6095
+ description: 'With the client-credentials grant and narrowScopes given in --config, a token with the full scopes is asked for first and must be accepted by the one request the suite uses to tell a protected server from an open one (the control). A token with narrowScopes, which the operator says is not enough for the endpoint, is then asked for and sent with the same request: 403 with a Bearer challenge that names error="insufficient_scope" is a pass; 401, or 403 without that error, is a failure of a SHOULD. A 2xx cannot be judged, because the request the suite makes may not need the wider scope: it is could-not-run, as is a token endpoint that does not issue a narrower token. Both tokens are masked in every output and are not revoked.',
6096
+ level: "SHOULD",
6097
+ derived: true,
6098
+ derivation: `Runtime Insufficient Scope Errors says: "When a client makes a request with an access token with insufficient scope during runtime operations, the server SHOULD respond with: HTTP 403 Forbidden status code (per RFC 6750 Section 3.1)" and a WWW-Authenticate header with the Bearer scheme and the parameter error="insufficient_scope". The wording is the same in both revisions. That a token is insufficient is not known from outside: it is what narrowScopes says in --config, so the check asks for the narrow token only when the full-scope token is accepted and the authorization server has issued a narrower one, and takes the operator's word that the endpoint needs the wider scope. The level is that of the quoted SHOULD.`,
6099
+ specRefs: [
6100
+ ref2(L, AUTH, "Runtime Insufficient Scope Errors"),
6101
+ ref2(M, AUTH, "Runtime Insufficient Scope Errors")
6102
+ ],
6103
+ eras: BOTH2,
6104
+ needsFixture: true
6105
+ }),
6106
+ oauth({
6107
+ id: "oauth-authz-response-iss",
6108
+ title: "iss in the authorization response is the issuer, and is advertised",
6109
+ description: 'With auth "headless" and a pre-registered client in --config, one authorization request is made. Where the test environment answers with a redirect that carries a code, the iss of that redirect is read: if present it must be the issuer of the metadata, exactly, and the metadata must advertise authorization_response_iss_parameter_supported: true; if the metadata advertises it, iss must be present. Where the endpoint shows a sign-in, the check is could-not-run (needs-input). The code is not exchanged; it expires on the server.',
6110
+ level: "MUST",
6111
+ derived: true,
6112
+ derivation: 'Authorization Response Validation says: "Authorization servers that include the iss parameter MUST advertise this by setting authorization_response_iss_parameter_supported to true in their metadata (RFC9207 Section 2.3)", and gives the rows a client applies: advertised and iss absent is rejected, and a present iss is compared with the recorded issuer by simple string comparison. That a server sends an iss equal to its issuer, and sends one when it advertises, is the converse of those client rules and of RFC 9207 section 2, which is not in the saved text: derived. The level is that of the quoted MUST; the text also says "MCP authorization servers SHOULD include the iss parameter in authorization responses", which is why a server that sends none and advertises none is not-applicable, not failed.',
6113
+ specRefs: [ref2(M, AUTH, "Authorization Response Validation")],
6114
+ eras: MODERN,
6115
+ needsFixture: true
6116
+ }),
6117
+ oauth({
6118
+ id: "oauth-neg-pkce-wrong-verifier",
6119
+ title: "A code exchanged with a wrong code_verifier is refused",
6120
+ description: 'With auth "headless" and a pre-registered client, a correct exchange (the control) must give a token; then a fresh code, sent with a code_verifier that does not match its code_challenge, must be refused. A token for the wrong verifier is a failure. Where the endpoint shows a sign-in, the check is could-not-run (needs-input). Every token issued is reported as issued and not revoked.',
6121
+ level: "MUST",
6122
+ derived: true,
6123
+ derivation: 'Authorization Code Protection says "MCP clients MUST implement PKCE according to OAuth 2.1 Section 7.5.2" and that PKCE ensures "that only the original requestor can exchange an authorization code for tokens". Those sentences are about the client and the purpose; that a server checks the verifier is RFC 7636 section 4.6, which is not in the saved text: derived. The level is not higher than the quoted MUST.',
6124
+ specRefs: [
6125
+ ref2(L, AUTH, "Authorization Code Protection"),
6126
+ ref2(M, SECURITY, "Authorization Code Protection")
6127
+ ],
6128
+ eras: BOTH2,
6129
+ needsFixture: true
6130
+ }),
6131
+ oauth({
6132
+ id: "oauth-neg-token-redirect-mismatch",
6133
+ title: "A code exchanged with another redirect_uri is refused as such",
6134
+ description: 'With auth "headless" and a pre-registered client, after the control exchange a fresh code is sent to the token endpoint with a redirect_uri other than the one of the authorization request. A token is a failure. A refusal whose answer names the redirect_uri is a pass; a bare invalid_grant does not show that the redirect_uri was compared and is could-not-run, not passed. Where the endpoint shows a sign-in, the check is could-not-run (needs-input).',
6135
+ level: "MUST",
6136
+ derived: true,
6137
+ derivation: 'Open Redirection says "Authorization servers MUST validate exact redirect URIs against pre-registered values to prevent redirection attacks" about the authorization request. That the token endpoint compares the redirect_uri of the exchange with the one of the authorization request is RFC 6749 section 4.1.3, which is not in the saved text: derived. The level is not higher than the quoted MUST.',
6138
+ specRefs: [ref2(L, AUTH, "Open Redirection"), ref2(M, SECURITY, "Open Redirection")],
6139
+ eras: BOTH2,
6140
+ needsFixture: true
6141
+ }),
6142
+ oauth({
6143
+ id: "oauth-reg-prereg",
6144
+ title: "A pre-registered client is accepted",
6145
+ description: "The client_id of a pre-registered client (from --config) is accepted at the authorization endpoint: the request is answered with a redirect that carries no error, not with invalid_client. Only the client_id and the redirect URI are sent; no secret goes to the authorization endpoint. A page that shows a sign-in cannot be told from one that shows an error, and is could-not-run.",
6146
+ level: "SHOULD",
6147
+ derived: true,
6148
+ derivation: 'The text says "MCP clients SHOULD support an option for static client credentials such as those supplied by a pre-registration flow", a duty of the client. That a server accepts such a client is derived, and its level is not higher than the quoted SHOULD.',
6149
+ specRefs: [ref2(L, AUTH, "Preregistration"), ref2(M, REGISTRATION, "Pre-registration")],
6150
+ eras: BOTH2
6151
+ }),
6152
+ oauth({
6153
+ id: "oauth-reg-dcr",
6154
+ title: "Dynamic client registration works",
6155
+ description: "When the metadata names a registration_endpoint and --config allows a client to be created, a registration (RFC 7591) with a correct body (application_type native, a loopback redirect URI) answers 201 with a client_id. The client is deleted afterwards (RFC 7592) when the server gave the means; otherwise the report names the client that remains on the authorization server. In 2026-07-28 the method is deprecated in favour of Client ID Metadata Documents.",
6156
+ level: "MAY",
6157
+ specRefs: [
6158
+ ref2(L, AUTH, "Dynamic Client Registration"),
6159
+ ref2(M, REGISTRATION, "Dynamic Client Registration")
6160
+ ],
6161
+ eras: BOTH2
6162
+ }),
6163
+ oauth({
6164
+ id: "oauth-reg-dcr-http-redirect-rejected",
6165
+ title: "A redirect over http outside loopback is not registered",
6166
+ description: "A registration whose redirect URI is http on a name that is not loopback is refused, while the same registration with a loopback redirect URI (the control) is accepted. A client made by a server that accepts the fault is deleted, or named in the report when it cannot be.",
6167
+ level: "MUST",
6168
+ derived: true,
6169
+ derivation: 'Communication Security: "All redirect URIs MUST be either localhost or use HTTPS." The sentence is about redirect URIs; that an authorization server refuses to register one is derived.',
6170
+ specRefs: [
6171
+ ref2(L, AUTH, "Communication Security"),
6172
+ ref2(L, AUTH, "Open Redirection"),
6173
+ ref2(M, SECURITY, "Communication Security"),
6174
+ ref2(M, SECURITY, "Open Redirection")
6175
+ ],
6176
+ eras: BOTH2
6177
+ }),
6178
+ oauth({
6179
+ id: "oauth-reg-cimd",
6180
+ title: "A client_id that is a URL is read as a document",
6181
+ description: "When the metadata advertises client_id_metadata_document_supported, the client_id URL of a document the user hosts (--config registration.clientIdMetadataUrl) is accepted at the authorization endpoint, and the URL of a document whose client_id does not match it (clientIdMetadataMismatchUrl) is refused. Without the second URL only the first half is seen, and the check is could-not-run.",
6182
+ level: "MUST",
6183
+ derived: true,
6184
+ derivation: 'Authorization servers "MUST validate that the fetched document\u2019s client_id matches the URL exactly" (quoted). That a server takes a good document and completes the authorization is derived.',
6185
+ specRefs: [
6186
+ ref2(L, AUTH, "Client ID Metadata Documents"),
6187
+ ref2(M, REGISTRATION, "Client ID Metadata Documents")
6188
+ ],
6189
+ eras: BOTH2,
6190
+ needsFixture: true
6191
+ }),
6192
+ oauth({
6193
+ id: "oauth-token-format",
6194
+ title: "The token response has access_token and token_type Bearer",
6195
+ description: "The answer of the token endpoint (client-credentials, from --config) is a JSON object with access_token and token_type Bearer (the value is case insensitive). An absent expires_in is said in the result but does not fail the check: RFC 6749 only recommends it. A token_type other than Bearer (for example DPoP) fails the check: the text of MCP has the token sent as Authorization: Bearer.",
6196
+ level: "MUST",
6197
+ derived: true,
6198
+ derivation: 'RFC 6749 section 5.1: access_token and token_type are REQUIRED, expires_in is RECOMMENDED; the Token Requirements of the specification use the token as "Authorization: Bearer". No MCP sentence says MUST about the response of the token endpoint.',
6199
+ specRefs: [ref2(L, AUTH, "Token Requirements"), ref2(M, AUTH, "Token Requirements")],
6200
+ eras: BOTH2,
6201
+ needsFixture: true
6202
+ }),
6203
+ oauth({
6204
+ id: "oauth-neg-invalid-client",
6205
+ title: "A client that does not exist is not accepted",
6206
+ description: "A made-up client_id is not accepted at the authorization endpoint (it is not redirected to the redirect URI, with a code or with an error) and, when --config has client credentials, a made-up client is not given a token at the token endpoint (HTTP 400 or 401). The pre-registered client is the control for each half: it must not be refused. A server that sends every client to a sign-in page cannot be judged. The made-up client sends made-up credentials, never the real ones.",
6207
+ level: "MUST",
6208
+ derived: true,
6209
+ derivation: 'RFC 6749 section 4.1.2.1: if "the client identifier is missing or invalid, the authorization server SHOULD inform the resource owner of the error and MUST NOT automatically redirect the user-agent to the invalid redirection URI" (the authorization half); section 5.2: invalid_client is "Client authentication failed (e.g., unknown client...)" (the token half, which has no MUST of its own). The MCP text says only that authorization servers "MUST validate exact redirect URIs against pre-registered values" (Open Redirection).',
6210
+ specRefs: [ref2(L, AUTH, "Open Redirection"), ref2(M, SECURITY, "Open Redirection")],
6211
+ eras: BOTH2,
6212
+ needsFixture: true
6213
+ }),
6214
+ oauth({
6215
+ id: "oauth-neg-authorize-redirect-mismatch",
6216
+ title: "A redirect URI that is not registered is not redirected to",
6217
+ description: "An authorization request with the pre-registered client and a redirect URI that is not registered (https://plune-conformance-other.invalid/callback, never a real host and never followed) is not answered with a redirect to that URI, neither with a code nor with an error. The same request with the registered redirect URI is the control: it must not be refused. A redirect to a sign-in page of the server that only carries the other URI in a parameter is not a violation, and cannot be judged either.",
6218
+ level: "MUST",
6219
+ derived: false,
6220
+ derivation: 'Open Redirection: "Authorization servers MUST validate exact redirect URIs against pre-registered values to prevent redirection attacks." RFC 6749 section 4.1.2.1: if the request fails due to a missing, invalid, or mismatching redirection URI, the server "MUST NOT automatically redirect the user-agent to the invalid redirection URI."',
6221
+ specRefs: [ref2(L, AUTH, "Open Redirection"), ref2(M, SECURITY, "Open Redirection")],
6222
+ eras: BOTH2,
6223
+ needsFixture: true
6224
+ })
6225
+ ];
6226
+
6227
+ // src/mcp-testing/conformance/tasks-catalog.ts
6228
+ init_cjs_shims();
6229
+ var TASKS_SPEC_URL = "https://github.com/modelcontextprotocol/ext-tasks/blob/main/specification/2026-07-28/tasks.md";
6230
+ var MODERN2 = ["modern"];
6231
+ var ref3 = (section) => ({
6232
+ revision: "2026-07-28",
6233
+ page: "tasks.md",
6234
+ section,
6235
+ url: TASKS_SPEC_URL
6236
+ });
6237
+ var tasks = (s) => ({
6238
+ ...s,
6239
+ suite: "tasks",
6240
+ kind: "check",
6241
+ derived: s.derived ?? false,
6242
+ // Every check reads a task, and a task comes from a tool the user names in --fixture.
6243
+ needsFixture: s.needsFixture ?? true,
6244
+ transports: s.transports ?? ["stdio", "http"],
6245
+ eras: MODERN2
6246
+ });
6247
+ var TASKS_CATALOG = [
6248
+ tasks({
6249
+ id: "tasks-result-type",
6250
+ title: 'A task handle has resultType "task", and no other result has it',
6251
+ description: 'The result of the --fixture call that made a task has resultType "task", a string taskId and a status of the specification. A result that carries a task handle (a string taskId and a status) without resultType "task" fails; so does any other result the run got (server/discover, tools/list, tasks/get, a call that made no task) that has resultType "task".',
6252
+ level: "MUST",
6253
+ derivation: 'Polymorphic Results: "Servers **MUST** set `resultType` to `"task"` when returning a `CreateTaskResult` so that clients can distinguish it from a standard result. Servers **MUST NOT** set `resultType` to `"task"` on result types other than `CreateTaskResult`."',
6254
+ specRefs: [ref3("Polymorphic Results"), ref3("Task Creation")]
6255
+ }),
6256
+ tasks({
6257
+ id: "tasks-undeclared-no-task",
6258
+ title: "A client that did not declare the extension is given no task",
6259
+ description: "The --fixture call that made a task for a client that declared the extension is sent once more without the declaration. The answer is not a task handle (a result of another kind, or an error, is not judged further). The first call, the control, has to have made a task: otherwise the check is could-not-run.",
6260
+ level: "MUST",
6261
+ derivation: 'Capability Negotiation: "A server **MUST NOT** return `CreateTaskResult` to a client that did not include the extension capability on its request, regardless of prior declarations."',
6262
+ specRefs: [ref3("Capability Negotiation")]
6263
+ }),
6264
+ tasks({
6265
+ id: "tasks-undeclared-capability-error",
6266
+ title: "tasks/get, tasks/update and tasks/cancel without the declaration are -32021",
6267
+ description: "Each of the three methods, sent for the task the run made but without the extension in the client capabilities, is answered with the error -32021 whose data.requiredCapabilities.extensions names io.modelcontextprotocol/tasks. The same tasks/get with the declaration has to be accepted (the control). The run may cancel its own task this way if the server accepts the request.",
6268
+ level: "MUST",
6269
+ derivation: 'Protocol Errors: "Servers **MUST** return this error for non-declaring clients issuing `tasks/get`, `tasks/update`, and `tasks/cancel` requests." with "Missing required client capabilities: `-32021` (Missing Required Client Capability)". The error shape (data.requiredCapabilities) is the example of Capability Negotiation: no sentence says MUST about data.',
6270
+ specRefs: [ref3("Protocol Errors"), ref3("Capability Negotiation")]
6271
+ }),
6272
+ tasks({
6273
+ id: "tasks-get-status-shape",
6274
+ title: 'tasks/get answers a task with resultType "complete" and the fields of a task',
6275
+ description: 'Each tasks/get answer of the run is a result with resultType "complete", the taskId asked for, one of the five statuses (working, input_required, completed, failed, cancelled), createdAt and lastUpdatedAt as ISO 8601 date-times, and a ttlMs member. At most 6 polls of one task, within 5 seconds, by the pollIntervalMs the server gives kept between 20 and 1000 ms.',
6276
+ level: "MUST",
6277
+ derived: true,
6278
+ derivation: 'Response: "The `resultType` field **MUST** be set to `"complete"` on this object as it is the standard result shape for the `tasks/get` request." and "the server **MUST** return a a `Task` object with status `working`". The required fields (taskId, status, createdAt, lastUpdatedAt, ttlMs) are those of the interface Task, which no sentence with a keyword repeats; the set of statuses is that of "Tasks can be in one of the following states".',
6279
+ specRefs: [ref3("Task Polling"), ref3("Tasks")]
6280
+ }),
6281
+ tasks({
6282
+ id: "tasks-status-payload",
6283
+ title: "completed has a result, failed an error, input_required inputRequests",
6284
+ description: "Of the tasks/get answers the run got: one with status completed has a result object, one with failed has an error object, one with input_required has an inputRequests object. A status the run never saw is not judged; if it saw none of the three, the check is not-applicable (not-offered).",
6285
+ level: "MUST",
6286
+ derivation: 'Response: "If the status is `input_required`, the server **MUST** return a `Task` object with status `input_required` and an `inputRequests` field"; "If the status is `completed`, the server **MUST** return a `Task` object with status `completed` and a `result` field containing the final result of the task."; "If the status is `failed`, the server **MUST** return a `Task` object with status `failed` and the error that occurred during execution."',
6287
+ specRefs: [ref3("Task Polling")]
6288
+ }),
6289
+ tasks({
6290
+ id: "tasks-ttl-poll-integers",
6291
+ title: "ttlMs is an integer or null, pollIntervalMs an integer",
6292
+ description: "In the task handle and in each tasks/get answer, ttlMs is an integer (milliseconds) or null, and pollIntervalMs, when present, is an integer. A fraction, a string or a missing ttlMs fails.",
6293
+ level: "SHOULD",
6294
+ derived: true,
6295
+ derivation: 'No sentence says MUST or SHOULD about the types: the interface Task has "ttlMs: number | null;" with "Time-to-live duration from creation in integer milliseconds, null for unlimited." and "pollIntervalMs?: number;" with "Suggested polling interval in integer milliseconds." (schema.ts adds `@format int`). A requirement the text states only as a type has no keyword, so the level is SHOULD.',
6296
+ specRefs: [ref3("Tasks")]
6297
+ }),
6298
+ tasks({
6299
+ id: "tasks-unknown-id-get",
6300
+ title: "tasks/get for an unknown taskId is -32602",
6301
+ description: "tasks/get for a taskId the server never made answers the error -32602. The same request for the task the run made has to be accepted (the control).",
6302
+ level: "MUST",
6303
+ derivation: 'Protocol Errors: "Invalid or nonexistent `taskId`: `-32602` (Invalid params)" and "Servers **MUST** return this error for `tasks/get`."',
6304
+ specRefs: [ref3("Protocol Errors")]
6305
+ }),
6306
+ tasks({
6307
+ id: "tasks-unknown-id-update-cancel",
6308
+ title: "tasks/update and tasks/cancel for an unknown taskId are -32602",
6309
+ description: "tasks/update and tasks/cancel for a taskId the server never made answer the error -32602. The same requests for a task the run made have to be accepted (the controls: tasks-update-ack and tasks-cancel-ack).",
6310
+ level: "SHOULD",
6311
+ derivation: 'Protocol Errors: "Servers **SHOULD** return this error for `tasks/update` and `tasks/cancel`."',
6312
+ specRefs: [ref3("Protocol Errors")]
6313
+ }),
6314
+ tasks({
6315
+ id: "tasks-cancel-ack",
6316
+ title: "tasks/cancel is acknowledged with an empty result",
6317
+ description: 'tasks/cancel for a task the run made (a second one, not polled before) answers a result with resultType "complete" and nothing else but _meta. An error is a failure only when tasks/get shows the task still working or input_required; for a task that already ended it says nothing and is could-not-run.',
6318
+ level: "MUST",
6319
+ derivation: 'Task Cancellation: "On success, the server **MUST** acknowledge the request with an empty result." and "The `resultType` field **MUST** be set to `"complete"` on `CancelTaskResult` as it is the standard result shape for the `tasks/cancel` request."',
6320
+ specRefs: [ref3("Task Cancellation")]
6321
+ }),
6322
+ tasks({
6323
+ id: "tasks-update-ack",
6324
+ title: "tasks/update is acknowledged with an empty result",
6325
+ description: 'tasks/update with an empty inputResponses map for a task the run made answers a result with resultType "complete" and nothing else but _meta. An error says nothing about the acknowledgement (no key is outstanding, which the text says a server SHOULD ignore): could-not-run.',
6326
+ level: "MUST",
6327
+ derivation: 'Task Update Requests: "On success, the server **MUST** acknowledge the request with an empty result." and "The `resultType` field **MUST** be set to `"complete"` on `UpdateTaskResult` as it is the standard result shape for the `tasks/update` request."',
6328
+ specRefs: [ref3("Task Update Requests")]
6329
+ }),
6330
+ tasks({
6331
+ id: "tasks-failed-status-message",
6332
+ title: "A failed task has a statusMessage",
6333
+ description: "A tasks/get answer with status failed has a statusMessage string. If the run saw no failed task, the check is not-applicable (not-offered).",
6334
+ level: "SHOULD",
6335
+ derivation: 'Task Execution Errors: "The `tasks/get` response **SHOULD** include a `statusMessage` field with diagnostic information about the failure, and **MUST** include the `error` field with the JSON-RPC error."',
6336
+ specRefs: [ref3("Task Execution Errors")]
6337
+ }),
6338
+ tasks({
6339
+ id: "tasks-http-name-header",
6340
+ title: "tasks/get with Mcp-Name set to the taskId is accepted",
6341
+ description: "Over Streamable HTTP, tasks/get sent with Mcp-Name equal to params.taskId and Mcp-Method equal to tasks/get is answered with a result, not with the HeaderMismatch error (-32020).",
6342
+ level: "SHOULD",
6343
+ derived: true,
6344
+ derivation: 'Streamable HTTP: Routing Headers: "the client **MUST** set the `Mcp-Name` header to the value of `params.taskId`." The sentence is about the client; that a server accepts a request that does it is read from it, and no sentence says MUST or SHOULD about the server, so the level is SHOULD.',
6345
+ specRefs: [ref3("Streamable HTTP: Routing Headers")],
6346
+ transports: ["http"]
6347
+ }),
6348
+ tasks({
6349
+ id: "tasks-input-request-keys-unique",
6350
+ title: "An inputRequests key never names two different requests",
6351
+ description: "Across the tasks/get answers of one task, a key of inputRequests that appears again holds the same request. At least two answers with inputRequests are needed, otherwise the check is not-applicable (not-offered). That a key is not reused after its response was delivered is not judged: the run never answers a request.",
6352
+ level: "MUST",
6353
+ derived: true,
6354
+ derivation: 'Task Update Requests: "Each request key in `inputRequests` **MUST** be unique over the lifetime of a single task. A server **MUST NOT** reuse a key for a subsequent server-to-client request after a response for that key has been delivered, and **MUST NOT** use the same key to refer to two distinct requests over a task\'s lifetime." The check judges the second half only, which is the part a client that never answers can see.',
6355
+ specRefs: [ref3("Task Update Requests")]
6356
+ })
6357
+ ];
6358
+
6359
+ // src/mcp-testing/conformance/catalog.ts
6360
+ var L2 = "2025-11-25";
6361
+ var M2 = "2026-07-28";
6362
+ var BOTH3 = ["legacy", "modern"];
6363
+ var MODERN3 = ["modern"];
6364
+ var ANY = ["stdio", "http"];
6365
+ var check2 = (s) => ({
6366
+ ...s,
6367
+ suite: "protocol",
6368
+ kind: "check",
6369
+ derived: s.derived ?? false,
6370
+ needsFixture: s.needsFixture ?? false
6371
+ });
6372
+ var ref4 = (revision, page, section) => ({ revision, page, section });
6373
+ var unscored = (kind, s) => ({
6374
+ ...check2({ ...s, level: null }),
6375
+ kind
6376
+ });
6377
+ var HTTP = ["http"];
6378
+ var LT = "basic/transports";
6379
+ var MT = "basic/transports/streamable-http";
6380
+ var CATALOG = [
6381
+ // Lifecycle
6382
+ check2({
6383
+ id: "life-initialize-result",
6384
+ title: "initialize answers with protocolVersion, capabilities and serverInfo",
6385
+ description: "The result of initialize holds the protocol version the server chose, its capabilities and its serverInfo.",
6386
+ level: "MUST",
6387
+ specRefs: [ref4(L2, "basic/lifecycle", "Initialization")],
6388
+ eras: ["legacy"],
6389
+ transports: ANY
6390
+ }),
6391
+ check2({
6392
+ id: "life-version-negotiation",
6393
+ title: "The protocol version is negotiated",
6394
+ description: "Asked for a version it supports, the server answers with that version; asked for one it does not, with another version it supports.",
6395
+ level: "MUST",
6396
+ specRefs: [ref4(L2, "basic/lifecycle", "Version Negotiation")],
6397
+ eras: ["legacy"],
6398
+ transports: ANY
6399
+ }),
6400
+ check2({
6401
+ id: "life-capabilities-declared-served",
6402
+ title: "Every declared capability is served",
6403
+ description: "For each capability declared (tools, resources, prompts, logging, completions), the matching request does not answer Method not found (-32601).",
6404
+ level: "MUST",
6405
+ derived: true,
6406
+ derivation: "basic/lifecycle, Operation: only negotiated capabilities are used; the server pages: a server that supports a feature MUST declare its capability.",
6407
+ specRefs: [ref4(L2, "basic/lifecycle", "Operation")],
6408
+ eras: BOTH3,
6409
+ transports: ANY
6410
+ }),
6411
+ check2({
6412
+ id: "life-capabilities-served-declared",
6413
+ title: "Every served list is declared",
6414
+ description: "When tools/list, resources/list or prompts/list answers, the matching capability is declared.",
6415
+ level: "MUST",
6416
+ specRefs: [
6417
+ ref4(L2, "server/tools", "Capabilities"),
6418
+ ref4(L2, "server/resources", "Capabilities"),
6419
+ ref4(L2, "server/prompts", "Capabilities")
6420
+ ],
6421
+ eras: BOTH3,
6422
+ transports: ANY
6423
+ }),
6424
+ check2({
6425
+ id: "life-ping-empty-result",
6426
+ title: "ping answers with an empty result",
6427
+ description: "ping is answered promptly with result: {}.",
6428
+ level: "MUST",
6429
+ specRefs: [ref4(L2, "basic/utilities/ping", "Behavior Requirements")],
6430
+ eras: ["legacy"],
6431
+ transports: ANY
6432
+ }),
6433
+ // The 2026-07-28 revision: server/discover and the per-request metadata, run first (the rest stands on discover).
6434
+ check2({
6435
+ id: "mod-discover-result",
6436
+ title: "server/discover answers a complete DiscoverResult",
6437
+ description: 'server/discover answers resultType "complete", supportedVersions (a non-empty list of strings that names the revision of the run) and capabilities (an object). Without it every other modern check is could-not-run (prerequisite-failed).',
6438
+ level: "MUST",
6439
+ specRefs: [ref4(M2, "server/discover", "Discovery"), ref4(M2, "basic/versioning", "Protocol Version Negotiation")],
6440
+ eras: MODERN3,
6441
+ transports: ANY
6442
+ }),
6443
+ check2({
6444
+ id: "mod-discover-server-info",
6445
+ title: "server/discover names the server in _meta",
6446
+ description: 'The DiscoverResult has _meta["io.modelcontextprotocol/serverInfo"] with a name and a version.',
6447
+ level: "SHOULD",
6448
+ specRefs: [ref4(M2, "server/discover", "DiscoverResult"), ref4(M2, "basic/index", "_meta")],
6449
+ eras: MODERN3,
6450
+ transports: ANY
6451
+ }),
6452
+ check2({
6453
+ id: "mod-meta-required-fields",
6454
+ title: "A request without a required _meta field is Invalid params",
6455
+ description: "server/discover without io.modelcontextprotocol/protocolVersion, and again without io.modelcontextprotocol/clientCapabilities, each gets -32602, over HTTP with status 400. Ambiguous in the text: over HTTP a body without the version also differs from its MCP-Protocol-Version header, so -32020 (HeaderMismatch) is taken for that probe as well.",
6456
+ level: "MUST",
6457
+ specRefs: [ref4(M2, "basic/index", "_meta"), ref4(M2, MT, "Server Validation")],
6458
+ eras: MODERN3,
6459
+ transports: ANY
6460
+ }),
6461
+ check2({
6462
+ id: "mod-unsupported-version",
6463
+ title: "An unsupported protocol version is UnsupportedProtocolVersion",
6464
+ description: "server/discover for revision 1900-01-01 gets -32022 with data.supported, a non-empty list; over HTTP with status 400.",
6465
+ level: "MUST",
6466
+ specRefs: [ref4(M2, "basic/versioning", "Protocol Version Negotiation"), ref4(M2, MT, "Protocol Version Header")],
6467
+ eras: MODERN3,
6468
+ transports: ANY
6469
+ }),
6470
+ // Base protocol
6471
+ check2({
6472
+ id: "base-jsonrpc-parse-error",
6473
+ title: "Invalid JSON is a parse error",
6474
+ description: "A message that is not valid JSON gets the error -32700 with id: null. Over HTTP only: on stdio the client may not send such a line at all, and stdio-parse-error-advice reads the answer there. Over HTTP the endpoint is open to any POST, not only to what an MCP client writes, so the JSON-RPC 2.0 rule stands there: an input it cannot accept gets an error (https://modelcontextprotocol.io/specification/2025-11-25/basic/transports, Sending Messages to the Server).",
6475
+ level: "MUST",
6476
+ derived: true,
6477
+ derivation: "basic/index, Messages: MCP messages MUST follow JSON-RPC 2.0; JSON-RPC 2.0 section 5 gives -32700 and a null id to a parse error.",
6478
+ specRefs: [ref4(L2, "basic/index", "Messages")],
6479
+ eras: BOTH3,
6480
+ transports: HTTP
6481
+ }),
6482
+ unscored("advice", {
6483
+ id: "stdio-parse-error-advice",
6484
+ title: "Invalid JSON on stdio is answered with a parse error (advice)",
6485
+ description: `A line that is not valid JSON gets the error -32700 with id: null. Advice, not a requirement: the client "MUST NOT write anything to the server's stdin that is not a valid MCP message", so what a server does with one is not specified.`,
6486
+ specRefs: [ref4(L2, LT, "stdio")],
6487
+ eras: BOTH3,
6488
+ transports: ["stdio"]
6489
+ }),
6490
+ check2({
6491
+ id: "base-unknown-method-error",
6492
+ title: "An unknown method is Method not found",
6493
+ description: "A request for a method the server does not have gets the error -32601.",
6494
+ level: "MUST",
6495
+ derived: true,
6496
+ derivation: "basic/index, Messages: MCP messages MUST follow JSON-RPC 2.0; JSON-RPC 2.0 section 5.1 names -32601 for a method that does not exist.",
6497
+ specRefs: [ref4(L2, "basic/index", "Messages")],
6498
+ eras: BOTH3,
6499
+ transports: ANY
6500
+ }),
6501
+ check2({
6502
+ id: "base-response-id-matches",
6503
+ title: "A response carries the id of its request",
6504
+ description: "The id of a response is the id of the request; it holds exactly one of result and error; the id is not null for a valid request.",
6505
+ level: "MUST",
6506
+ specRefs: [ref4(L2, "basic/index", "Responses"), ref4(M2, "basic/index", "Responses")],
6507
+ eras: BOTH3,
6508
+ transports: ANY
6509
+ }),
6510
+ check2({
6511
+ id: "base-invalid-params-error",
6512
+ title: "Plainly wrong parameters are Invalid params",
6513
+ description: "A request with plainly wrong parameters (tools/call without name) gets -32602, not -32603 and not a result.",
6514
+ level: "SHOULD",
6515
+ specRefs: [ref4(L2, "server/tools", "Error Handling")],
6516
+ eras: BOTH3,
6517
+ transports: ANY
6518
+ }),
6519
+ // Tools
6520
+ check2({
6521
+ id: "tools-list-shape",
6522
+ title: "Every listed tool has a name and an inputSchema object",
6523
+ description: "Each entry of tools/list has a string name and an inputSchema that is an object, not null.",
6524
+ level: "MUST",
6525
+ specRefs: [ref4(L2, "server/tools", "Tool")],
6526
+ eras: BOTH3,
6527
+ transports: ANY
6528
+ }),
6529
+ check2({
6530
+ id: "tools-input-schema-valid",
6531
+ title: "Every inputSchema is a valid object schema",
6532
+ description: 'Each inputSchema has type: "object" and is valid in its declared ($schema) or default (2020-12) dialect; an unknown dialect is reported, not a crash.',
6533
+ level: "MUST",
6534
+ specRefs: [ref4(L2, "basic/index", "JSON Schema Usage")],
6535
+ eras: BOTH3,
6536
+ transports: ANY
6537
+ }),
6538
+ check2({
6539
+ id: "tools-output-schema-valid",
6540
+ title: "Every outputSchema is a valid schema",
6541
+ description: "An outputSchema, when given, is valid in its dialect; before 2026-07-28 its root is an object, from then on any type.",
6542
+ level: "MUST",
6543
+ specRefs: [ref4(L2, "server/tools", "Output Schema"), ref4(M2, "changelog", "Minor changes")],
6544
+ eras: BOTH3,
6545
+ transports: ANY
6546
+ }),
6547
+ check2({
6548
+ id: "tools-structured-conformant",
6549
+ title: "structuredContent conforms to the outputSchema",
6550
+ description: "The structuredContent of a call (from the fixture) conforms to the tool's outputSchema.",
6551
+ level: "MUST",
6552
+ specRefs: [ref4(L2, "server/tools", "Output Schema")],
6553
+ eras: BOTH3,
6554
+ transports: ANY,
6555
+ needsFixture: true
6556
+ }),
6557
+ check2({
6558
+ id: "tools-structured-has-text",
6559
+ title: "structuredContent is also given as text",
6560
+ description: "A result with structuredContent also has a text block with the serialized JSON.",
6561
+ level: "SHOULD",
6562
+ specRefs: [ref4(L2, "server/tools", "Structured Content")],
6563
+ eras: BOTH3,
6564
+ transports: ANY,
6565
+ needsFixture: true
6566
+ }),
6567
+ check2({
6568
+ id: "tools-name-format",
6569
+ title: "Tool names use the allowed characters",
6570
+ description: "Each tool name is 1 to 128 characters of A-Z, a-z, 0-9, _, - and ., without spaces or commas.",
6571
+ level: "SHOULD",
6572
+ specRefs: [ref4(L2, "server/tools", "Tool Names")],
6573
+ eras: BOTH3,
6574
+ transports: ANY
6575
+ }),
6576
+ check2({
6577
+ id: "tools-name-unique",
6578
+ title: "Tool names are unique",
6579
+ description: "No two tools of the server share a name, across every page of tools/list.",
6580
+ level: "SHOULD",
6581
+ specRefs: [ref4(L2, "server/tools", "Tool Names")],
6582
+ eras: BOTH3,
6583
+ transports: ANY
6584
+ }),
6585
+ check2({
6586
+ id: "tools-call-unknown-error",
6587
+ title: "Calling an unknown tool is a protocol error",
6588
+ description: "tools/call for a tool that does not exist gets a JSON-RPC error, not a result with isError.",
6589
+ level: "SHOULD",
6590
+ specRefs: [ref4(L2, "server/tools", "Error Handling")],
6591
+ eras: BOTH3,
6592
+ transports: ANY
6593
+ }),
6594
+ check2({
6595
+ id: "tools-list-order-stable",
6596
+ title: "tools/list keeps its order",
6597
+ description: "Two calls of tools/list give the tools in the same order.",
6598
+ level: "SHOULD",
6599
+ specRefs: [ref4(M2, "server/tools", "Capabilities")],
6600
+ eras: ["modern"],
6601
+ transports: ANY
6602
+ }),
6603
+ // Resources
6604
+ check2({
6605
+ id: "resources-list-shape",
6606
+ title: "Every listed resource has a uri and a name",
6607
+ description: "Each entry of resources/list has uri and name.",
6608
+ level: "MUST",
6609
+ derived: true,
6610
+ derivation: 'server/resources, Resource: uri and name are listed without "Optional"; no keyword.',
6611
+ specRefs: [ref4(L2, "server/resources", "Resource")],
6612
+ eras: BOTH3,
6613
+ transports: ANY
6614
+ }),
6615
+ check2({
6616
+ id: "resources-read-listed",
6617
+ title: "A listed resource can be read",
6618
+ description: "resources/read of the first listed resource answers with contents, each with a uri and exactly one of text and blob.",
6619
+ level: "MUST",
6620
+ derived: true,
6621
+ derivation: "server/resources, Resource Contents: a content is text or binary data under its uri; no keyword.",
6622
+ specRefs: [ref4(L2, "server/resources", "Resource Contents")],
6623
+ eras: BOTH3,
6624
+ transports: ANY
6625
+ }),
6626
+ check2({
6627
+ id: "resources-read-not-found",
6628
+ title: "Reading an unknown resource is an error",
6629
+ description: "resources/read of a uri that does not exist gets -32002, not empty contents.",
6630
+ level: "SHOULD",
6631
+ specRefs: [ref4(L2, "server/resources", "Error Handling")],
6632
+ eras: ["legacy"],
6633
+ transports: ANY
6634
+ }),
6635
+ check2({
6636
+ id: "resources-templates-shape",
6637
+ title: "Every resource template has a uriTemplate and a name",
6638
+ description: "Each entry of resources/templates/list has uriTemplate and name.",
6639
+ level: "MUST",
6640
+ derived: true,
6641
+ derivation: "server/resources, Resource Templates: every example template has uriTemplate and name; no keyword.",
6642
+ specRefs: [ref4(L2, "server/resources", "Resource Templates")],
6643
+ eras: BOTH3,
6644
+ transports: ANY
6645
+ }),
6646
+ // Prompts
6647
+ check2({
6648
+ id: "prompts-list-shape",
6649
+ title: "Every listed prompt has a name",
6650
+ description: "Each entry of prompts/list has name; arguments, when given, is a list of objects with name.",
6651
+ level: "MUST",
6652
+ derived: true,
6653
+ derivation: 'server/prompts, Prompt: name is listed without "Optional", arguments is optional; no keyword.',
6654
+ specRefs: [ref4(L2, "server/prompts", "Prompt")],
6655
+ eras: BOTH3,
6656
+ transports: ANY
6657
+ }),
6658
+ check2({
6659
+ id: "prompts-get-unknown-error",
6660
+ title: "Getting an unknown prompt is an error",
6661
+ description: "prompts/get with a name that does not exist gets a JSON-RPC error.",
6662
+ level: "SHOULD",
6663
+ specRefs: [ref4(L2, "server/prompts", "Error Handling")],
6664
+ eras: BOTH3,
6665
+ transports: ANY
6666
+ }),
6667
+ // Pagination
6668
+ check2({
6669
+ id: "pagination-walk-complete",
6670
+ title: "Paging through a list ends, without repeats",
6671
+ description: "Following nextCursor ends within the page limit and no entry comes back on a later page.",
6672
+ level: "SHOULD",
6673
+ specRefs: [ref4(L2, "server/utilities/pagination", "Implementation Guidelines")],
6674
+ eras: BOTH3,
6675
+ transports: ANY
6676
+ }),
6677
+ check2({
6678
+ id: "pagination-invalid-cursor",
6679
+ title: "An invalid cursor is Invalid params",
6680
+ description: "A list request with a cursor the server never gave gets -32602.",
6681
+ level: "SHOULD",
6682
+ specRefs: [ref4(L2, "server/utilities/pagination", "Error Handling")],
6683
+ eras: BOTH3,
6684
+ transports: ANY
6685
+ }),
6686
+ // Utilities
6687
+ check2({
6688
+ id: "logging-set-level",
6689
+ title: "logging/setLevel is accepted when logging is declared",
6690
+ description: "A server that declares logging accepts logging/setLevel.",
6691
+ level: "SHOULD",
6692
+ derived: true,
6693
+ derivation: "server/utilities/logging: the MUST is on declaring the capability, not on handling logging/setLevel, so handling it is a SHOULD.",
6694
+ specRefs: [ref4(L2, "server/utilities/logging", "Capabilities")],
6695
+ eras: ["legacy"],
6696
+ transports: ANY
6697
+ }),
6698
+ check2({
6699
+ id: "completion-complete",
6700
+ title: "completion/complete answers when completions is declared",
6701
+ description: "A server that declares completions answers completion/complete with a valid result.",
6702
+ level: "SHOULD",
6703
+ derived: true,
6704
+ derivation: "server/utilities/completion, Capabilities: the MUST is on declaring the capability, not on the answer to completion/complete, so the answer is a SHOULD.",
6705
+ specRefs: [ref4(L2, "server/utilities/completion", "Capabilities")],
6706
+ eras: BOTH3,
6707
+ transports: ANY
6708
+ }),
6709
+ // The 2026-07-28 revision: what changed for every transport.
6710
+ check2({
6711
+ id: "mod-removed-methods",
6712
+ title: "The methods the revision removed are Method not found",
6713
+ description: "ping, logging/setLevel, resources/subscribe, resources/unsubscribe and initialize, each sent with the modern _meta, get -32601, over HTTP with status 404. initialize goes on a connection of its own; a dual-era server that answers it with an initialize result is not counted for it, since the text lets initialize select the legacy era (basic/versioning, Backward Compatibility) while a request with modern _meta is served in the modern one: the two rules meet there.",
6714
+ level: "MUST",
6715
+ derived: true,
6716
+ derivation: "changelog, Major changes 2, 4 and 5 remove these methods; streamable-http, Protocol Version Header: a method the server does not implement MUST get 404 and -32601. No sentence names the answer to a removed method itself.",
6717
+ specRefs: [ref4(M2, "changelog", "Major changes"), ref4(M2, MT, "Protocol Version Header")],
6718
+ eras: MODERN3,
6719
+ transports: ANY
6720
+ }),
6721
+ check2({
6722
+ id: "mod-stateless-no-prior-context",
6723
+ title: "A list answers on a fresh connection with no request before it",
6724
+ description: "On a new connection the first request is tools/list (else prompts/list, else resources/list, whichever is declared), not server/discover, and it answers a result.",
6725
+ level: "MUST",
6726
+ specRefs: [ref4(M2, "basic/index", "Statelessness")],
6727
+ eras: MODERN3,
6728
+ transports: ANY
6729
+ }),
6730
+ check2({
6731
+ id: "mod-list-stable-across-connections",
6732
+ title: "The lists do not vary per connection",
6733
+ description: "tools/list, prompts/list and resources/list (those declared) hold the same entries on the run's connection, after all its other requests, and on a new connection with the same credentials.",
6734
+ level: "MUST",
6735
+ specRefs: [
6736
+ ref4(M2, "server/tools", "Capabilities"),
6737
+ ref4(M2, "server/prompts", "Capabilities"),
6738
+ ref4(M2, "server/resources", "Capabilities")
6739
+ ],
6740
+ eras: MODERN3,
6741
+ transports: ANY
6742
+ }),
6743
+ check2({
6744
+ id: "mod-resource-not-found",
6745
+ title: "Reading an unknown resource is Invalid params",
6746
+ description: "resources/read of a uri that does not exist gets -32602; -32002, the code of earlier revisions, fails.",
6747
+ level: "MUST",
6748
+ specRefs: [ref4(M2, "server/resources", "Error Handling"), ref4(M2, "basic/index", "Error Codes")],
6749
+ eras: MODERN3,
6750
+ transports: ANY
6751
+ }),
6752
+ check2({
6753
+ id: "mod-resource-no-empty-contents",
6754
+ title: "An unknown resource is not empty contents",
6755
+ description: "resources/read of a uri that does not exist does not answer a result with an empty contents list.",
6756
+ level: "MUST",
6757
+ specRefs: [ref4(M2, "server/resources", "Error Handling")],
6758
+ eras: MODERN3,
6759
+ transports: ANY
6760
+ }),
6761
+ check2({
6762
+ id: "mod-cache-hints-coverage",
6763
+ title: "Every cacheable result has ttlMs and cacheScope",
6764
+ description: "Each complete result of server/discover, tools/list, prompts/list, resources/list, resources/templates/list (every page) and resources/read (the first listed resource) has ttlMs and cacheScope; the lists only when their capability is declared.",
6765
+ level: "MUST",
6766
+ specRefs: [ref4(M2, "server/utilities/caching", "Cacheable Results")],
6767
+ eras: MODERN3,
6768
+ transports: ANY
6769
+ }),
6770
+ check2({
6771
+ id: "mod-cache-ttl-valid",
6772
+ title: "ttlMs is an integer of at least 0",
6773
+ description: "Every ttlMs on those results is an integer number of milliseconds, 0 or more.",
6774
+ level: "MUST",
6775
+ specRefs: [ref4(M2, "server/utilities/caching", "Time-to-Live (TTL) Field")],
6776
+ eras: MODERN3,
6777
+ transports: ANY
6778
+ }),
6779
+ check2({
6780
+ id: "mod-cache-scope-valid",
6781
+ title: 'cacheScope is "public" or "private"',
6782
+ description: 'Every cacheScope on those results is exactly "public" or "private".',
6783
+ level: "MUST",
6784
+ derived: true,
6785
+ derivation: 'server/utilities/caching, Cache Scope Field: the field "indicates ... either "public" or "private"" and its table has these two values, with no keyword on the value itself; the schema of the revision (schema.json, CacheableResult) makes it an enum of the two.',
6786
+ specRefs: [ref4(M2, "server/utilities/caching", "Cache Scope Field")],
6787
+ eras: MODERN3,
6788
+ transports: ANY
6789
+ }),
6790
+ check2({
6791
+ id: "mod-cache-scope-stable-pages",
6792
+ title: "All pages of a list have the same cacheScope",
6793
+ description: "Every page of a paginated list carries the cacheScope of its first page. Without a list of two pages, not-applicable.",
6794
+ level: "MUST",
6795
+ specRefs: [ref4(M2, "server/utilities/caching", "Interaction with Pagination")],
6796
+ eras: MODERN3,
6797
+ transports: ANY
6798
+ }),
6799
+ check2({
6800
+ id: "mod-undeclared-capability",
6801
+ title: "A capability the client did not declare is asked for with -32021",
6802
+ description: 'This checker declares no client capability. A --fixture call the server cannot serve without one gets -32021 with data.requiredCapabilities naming it (over HTTP, status 400), never an input request for sampling, elicitation or roots. The schema makes requiredCapabilities a ClientCapabilities object while the text says it "lists" them: an object with at least one capability is taken. Without --fixture, could-not-run (needs-input).',
6803
+ level: "MUST",
6804
+ specRefs: [ref4(M2, "basic/index", "_meta")],
6805
+ eras: MODERN3,
6806
+ transports: ANY,
6807
+ needsFixture: true
6808
+ }),
6809
+ // Subscriptions: one subscriptions/listen per run, watched for a short time and then cancelled.
6810
+ check2({
6811
+ id: "mod-sub-ack-first",
6812
+ title: "A subscription is acknowledged first",
6813
+ description: "The first message of subscriptions/listen with its subscription id is notifications/subscriptions/acknowledged, carrying that id in _meta. Without a subscribable capability (tools, prompts or resources listChanged, resources subscribe), not-applicable.",
6814
+ level: "MUST",
6815
+ specRefs: [ref4(M2, "basic/patterns/subscriptions", "Acknowledgment")],
6816
+ eras: MODERN3,
6817
+ transports: ANY
6818
+ }),
6819
+ check2({
6820
+ id: "mod-sub-filter-and-tag",
6821
+ title: "A subscription gets only what it asked for, each tagged",
6822
+ description: "The subscription asks for one kind of notification; every notification after the acknowledgment is of that kind and carries io.modelcontextprotocol/subscriptionId. When nothing changed while it was watched, there is no notification to judge: not-applicable (not-offered).",
6823
+ level: "MUST",
6824
+ specRefs: [ref4(M2, "basic/patterns/subscriptions", "Opening a Stream"), ref4(M2, "basic/index", "_meta")],
6825
+ eras: MODERN3,
6826
+ transports: ANY
6827
+ }),
6828
+ check2({
6829
+ id: "mod-sub-graceful-close",
6830
+ title: "A subscription the server ends gets a successful response",
6831
+ description: "When the server ends the subscription while it is watched, it first answers subscriptions/listen with a result. The text asks this when the server ends a subscription on its own initiative; a cancel of the client asks for no response, so a subscription the server keeps open is not-applicable (not-offered).",
6832
+ level: "SHOULD",
6833
+ specRefs: [ref4(M2, "basic/patterns/subscriptions", "Graceful Closure")],
6834
+ eras: MODERN3,
6835
+ transports: ANY
6836
+ }),
6837
+ // Streamable HTTP on the wire: raw requests, never an MCP client (../raw-http.ts).
6838
+ check2({
6839
+ id: "http-notification-202",
6840
+ title: "A notification POST is 202 with no body, or an error status",
6841
+ description: "A POST holding only a notification the server accepts gets 202 Accepted and an empty body; one it does not accept gets an HTTP error status. Another 2xx, or a 202 with a body, fails.",
6842
+ level: "MUST",
6843
+ specRefs: [ref4(L2, LT, "Sending Messages to the Server"), ref4(M2, MT, "Sending Messages")],
6844
+ eras: BOTH3,
6845
+ transports: HTTP
6846
+ }),
6847
+ check2({
6848
+ id: "http-request-content-type",
6849
+ title: "A request is answered as application/json or text/event-stream",
6850
+ description: "The answer to a JSON-RPC request has Content-Type application/json or text/event-stream.",
6851
+ level: "MUST",
6852
+ specRefs: [ref4(L2, LT, "Sending Messages to the Server"), ref4(M2, MT, "Sending Messages")],
6853
+ eras: BOTH3,
6854
+ transports: HTTP
6855
+ }),
6856
+ check2({
6857
+ id: "http-response-utf8",
6858
+ title: "The answer is UTF-8 JSON",
6859
+ description: "The body of the answer to a request is valid UTF-8, and its message (or the data of each SSE event) is JSON.",
6860
+ level: "MUST",
6861
+ specRefs: [ref4(L2, LT, "Transports")],
6862
+ eras: BOTH3,
6863
+ transports: HTTP
6864
+ }),
6865
+ check2({
6866
+ id: "http-single-endpoint",
6867
+ title: "The MCP endpoint takes POST",
6868
+ description: "The URL under test takes a valid JSON-RPC request by POST: not 404 (other than a JSON-RPC -32601) and not 405.",
6869
+ level: "MUST",
6870
+ specRefs: [ref4(L2, LT, "Streamable HTTP"), ref4(M2, MT, "Streamable HTTP")],
6871
+ eras: BOTH3,
6872
+ transports: HTTP
6873
+ }),
6874
+ check2({
6875
+ id: "http-get-stream-or-405",
6876
+ title: "GET opens an SSE stream or is 405",
6877
+ description: "A GET with Accept: text/event-stream gets Content-Type text/event-stream or 405 Method Not Allowed.",
6878
+ level: "MUST",
6879
+ specRefs: [ref4(L2, LT, "Listening for Messages from the Server")],
6880
+ eras: ["legacy"],
6881
+ transports: HTTP
6882
+ }),
6883
+ check2({
6884
+ id: "http-modern-get-delete-405",
6885
+ title: "A modern-only server answers GET and DELETE with 405",
6886
+ description: "A server of the 2026-07-28 revision only answers GET and DELETE on its endpoint with 405 Method Not Allowed. A server that also serves 2025-11-25 (dual-era) is not-applicable: its server/discover names an earlier revision, or it answers an initialize sent as a 2025-11-25 client sends it.",
6887
+ level: "SHOULD",
6888
+ specRefs: [ref4(M2, MT, "Earlier Streamable HTTP Revisions")],
6889
+ eras: ["modern"],
6890
+ transports: HTTP
6891
+ }),
6892
+ check2({
6893
+ id: "http-session-id-visible-ascii",
6894
+ title: "A session id is visible ASCII",
6895
+ description: "An MCP-Session-Id the server assigns holds only characters 0x21 to 0x7E. Without one, not-applicable.",
6896
+ level: "MUST",
6897
+ specRefs: [ref4(L2, LT, "Session Management")],
6898
+ eras: ["legacy"],
6899
+ transports: HTTP
6900
+ }),
6901
+ check2({
6902
+ id: "http-session-required-400",
6903
+ title: "A request without the session id is 400",
6904
+ description: "When the server assigned a session id, a request other than initialize without MCP-Session-Id gets 400 Bad Request.",
6905
+ level: "SHOULD",
6906
+ specRefs: [ref4(L2, LT, "Session Management")],
6907
+ eras: ["legacy"],
6908
+ transports: HTTP
6909
+ }),
6910
+ check2({
6911
+ id: "http-protocol-version-header-invalid-400",
6912
+ title: "An invalid MCP-Protocol-Version is 400",
6913
+ description: "A request after initialize with an MCP-Protocol-Version that is not a revision gets 400 Bad Request.",
6914
+ level: "MUST",
6915
+ specRefs: [ref4(L2, LT, "Protocol Version Header")],
6916
+ eras: ["legacy"],
6917
+ transports: HTTP
6918
+ }),
6919
+ check2({
6920
+ id: "http-concurrent-posts-matched",
6921
+ title: "Concurrent POSTs each get their own answer",
6922
+ description: "Several POSTs sent at once, each with its own id, are each answered with the id of their request.",
6923
+ level: "MUST",
6924
+ derived: true,
6925
+ derivation: "basic/transports: every JSON-RPC message MUST be a new HTTP POST request; basic/index, Responses: a response carries the id of its request. Nothing is said of concurrency itself.",
6926
+ specRefs: [ref4(L2, LT, "Sending Messages to the Server"), ref4(M2, "basic/index", "Responses")],
6927
+ eras: BOTH3,
6928
+ transports: HTTP
6929
+ }),
6930
+ check2({
6931
+ id: "http-sse-event-ids-unique",
6932
+ title: "SSE event ids are unique in the session",
6933
+ description: "When the server gives SSE events an id, no id comes back twice across the streams of the session. Without ids, not-applicable.",
6934
+ level: "MUST",
6935
+ specRefs: [ref4(L2, LT, "Resumability and Redelivery")],
6936
+ eras: ["legacy"],
6937
+ transports: HTTP
6938
+ }),
6939
+ check2({
6940
+ id: "http-sse-stream-closes",
6941
+ title: "The SSE stream of a request ends after its response",
6942
+ description: "When a request is answered over SSE, the server closes the stream once the response is sent.",
6943
+ level: "SHOULD",
6944
+ specRefs: [ref4(L2, LT, "Sending Messages to the Server"), ref4(M2, MT, "Receiving Messages")],
6945
+ eras: BOTH3,
6946
+ transports: HTTP
6947
+ }),
6948
+ check2({
6949
+ id: "http-sse-no-server-requests",
6950
+ title: "The SSE stream of a request holds no request of the server",
6951
+ description: "The SSE answer to a request holds its response and notifications, never a JSON-RPC request of the server.",
6952
+ level: "MUST",
6953
+ specRefs: [ref4(M2, MT, "Receiving Messages")],
6954
+ eras: ["modern"],
6955
+ transports: HTTP
6956
+ }),
6957
+ check2({
6958
+ id: "http-accel-buffering-header",
6959
+ title: "An SSE answer sends X-Accel-Buffering: no",
6960
+ description: "A response that opens an SSE stream has the header X-Accel-Buffering: no.",
6961
+ level: "SHOULD",
6962
+ specRefs: [ref4(M2, MT, "Receiving Messages")],
6963
+ eras: ["modern"],
6964
+ transports: HTTP
6965
+ }),
6966
+ check2({
6967
+ id: "http-close-cancels",
6968
+ title: "Closing the SSE stream cancels the request",
6969
+ description: "Closing the SSE answer of a long call is taken as its cancellation: the server sends nothing more for it. It shows only in the effects of a tool, so this run cannot see it yet: could-not-run (needs-input).",
6970
+ level: "MUST",
6971
+ specRefs: [ref4(M2, MT, "Cancellation")],
6972
+ eras: ["modern"],
6973
+ transports: HTTP,
6974
+ needsFixture: true
6975
+ }),
6976
+ // The request headers of the 2026-07-28 revision, each probe a POST of its own.
6977
+ check2({
6978
+ id: "mod-unimplemented-method",
6979
+ title: "An unknown method over HTTP is 404 with -32601",
6980
+ description: "A POST of a method the server does not implement gets 404 Not Found and the JSON-RPC error -32601.",
6981
+ level: "MUST",
6982
+ specRefs: [ref4(M2, MT, "Protocol Version Header")],
6983
+ eras: MODERN3,
6984
+ transports: HTTP
6985
+ }),
6986
+ check2({
6987
+ id: "mod-header-protocol-version-mismatch",
6988
+ title: "An MCP-Protocol-Version unlike the body is HeaderMismatch",
6989
+ description: "server/discover with MCP-Protocol-Version: 2025-11-25 and 2026-07-28 in _meta gets 400 and -32020.",
6990
+ level: "MUST",
6991
+ specRefs: [ref4(M2, MT, "Protocol Version Header"), ref4(M2, MT, "Server Validation")],
6992
+ eras: MODERN3,
6993
+ transports: HTTP
6994
+ }),
6995
+ check2({
6996
+ id: "mod-header-method-mismatch",
6997
+ title: "An Mcp-Method unlike the body is HeaderMismatch",
6998
+ description: "server/discover sent with Mcp-Method: tools/list gets 400 and -32020.",
6999
+ level: "MUST",
7000
+ specRefs: [ref4(M2, MT, "Server Validation")],
7001
+ eras: MODERN3,
7002
+ transports: HTTP
7003
+ }),
7004
+ check2({
7005
+ id: "mod-header-name-mismatch",
7006
+ title: "An Mcp-Name unlike the body is HeaderMismatch",
7007
+ description: "resources/read of the first listed resource (else prompts/get of the first prompt, else tools/call of the first --fixture tool) with Mcp-Name in another case gets 400 and -32020: header values are case-sensitive. A tool outside --fixture is never the target. Without a target, not-applicable.",
7008
+ level: "MUST",
7009
+ specRefs: [ref4(M2, MT, "Standard Request Headers"), ref4(M2, MT, "Server Validation"), ref4(M2, MT, "Case Sensitivity")],
7010
+ eras: MODERN3,
7011
+ transports: HTTP
7012
+ }),
7013
+ check2({
7014
+ id: "mod-header-missing-rejected",
7015
+ title: "A request without a required header is HeaderMismatch",
7016
+ description: "server/discover without MCP-Protocol-Version, server/discover without Mcp-Method, and the Mcp-Name target without Mcp-Name, each get 400 and -32020. The first is not counted for a server whose supportedVersions names a revision before 2025-06-18: it MAY take a request without the header as 2025-03-26.",
7017
+ level: "MUST",
7018
+ specRefs: [ref4(M2, MT, "Server Validation"), ref4(M2, MT, "Standard Request Headers"), ref4(M2, MT, "Protocol Version Header")],
7019
+ eras: MODERN3,
7020
+ transports: HTTP
7021
+ }),
7022
+ check2({
7023
+ id: "mod-header-names-case-insensitive",
7024
+ title: "Header names are read in any case",
7025
+ description: "server/discover with its standard headers named in lower case, and again in upper case, answers a result both times. The names go out as written (node:http), not as fetch would normalise them.",
7026
+ level: "MUST",
7027
+ specRefs: [ref4(M2, MT, "Case Sensitivity")],
7028
+ eras: MODERN3,
7029
+ transports: HTTP
7030
+ }),
7031
+ check2({
7032
+ id: "mod-header-name-base64-decoded",
7033
+ title: "A Base64 Mcp-Name is decoded before it is compared",
7034
+ description: "The Mcp-Name target (a name or uri that is not plain ASCII when there is one) sent as =?base64?\u2026?= is not refused with -32020. The text obliges clients to encode only values that are not plain ASCII, and servers to decode any encoded value; when every name is plain ASCII, one is encoded all the same.",
7035
+ level: "MUST",
7036
+ specRefs: [ref4(M2, MT, "Value Encoding")],
7037
+ eras: MODERN3,
7038
+ transports: HTTP
7039
+ }),
7040
+ check2({
7041
+ id: "mod-param-header-mismatch",
7042
+ title: "An Mcp-Param header unlike the body, or missing, is HeaderMismatch",
7043
+ description: "For a --fixture tool whose inputSchema marks a property with x-mcp-header and whose arguments give it a value: a wrong Mcp-Param-{Name}, and no Mcp-Param-{Name} at all, each get 400 and -32020. Only a --fixture tool is the target. Without such a tool, not-applicable.",
7044
+ level: "MUST",
7045
+ specRefs: [ref4(M2, MT, "Server Behavior for Custom Headers")],
7046
+ eras: MODERN3,
7047
+ transports: HTTP,
7048
+ needsFixture: true
7049
+ }),
7050
+ check2({
7051
+ id: "mod-x-mcp-header-declarations",
7052
+ title: "Every x-mcp-header declaration is valid",
7053
+ description: "Each x-mcp-header in an inputSchema is a non-empty HTTP token, unique without regard to case in its schema, on a string, integer or boolean property reached only through properties (not items, a composition, a condition or $ref). Over stdio a client MAY ignore the annotation, so the check is for HTTP only.",
7054
+ level: "MUST",
7055
+ specRefs: [ref4(M2, "server/tools", "x-mcp-header"), ref4(M2, MT, "Schema Extension")],
7056
+ eras: MODERN3,
7057
+ transports: HTTP
7058
+ }),
7059
+ check2({
7060
+ id: "mod-no-session-id",
7061
+ title: "A modern-only server neither mints nor echoes a session id",
7062
+ description: "server/discover sent with an Mcp-Session-Id gets an answer without Mcp-Session-Id. A dual-era server (supportedVersions names a revision before 2026-07-28, or it answers an initialize sent as a 2025-11-25 client sends it) is not-applicable.",
7063
+ level: "SHOULD",
7064
+ specRefs: [ref4(M2, MT, "Earlier Streamable HTTP Revisions")],
7065
+ eras: MODERN3,
7066
+ transports: HTTP
7067
+ }),
7068
+ // These two change the server's state, each in a session of its own made for it, so they come last.
7069
+ check2({
7070
+ id: "http-session-terminated-404",
7071
+ title: "A terminated session is 404",
7072
+ description: "After a DELETE with MCP-Session-Id that the server takes (not 405), a request with that session id gets 404 Not Found. Only a session this run made is deleted.",
7073
+ level: "MUST",
7074
+ specRefs: [ref4(L2, LT, "Session Management")],
7075
+ eras: ["legacy"],
7076
+ transports: HTTP
7077
+ }),
7078
+ check2({
7079
+ id: "http-sse-no-broadcast",
7080
+ title: "A message goes to one SSE stream, not to each",
7081
+ description: "With two GET streams open, a message of the server (made by the first --fixture call) arrives on one of them only.",
7082
+ level: "MUST",
7083
+ specRefs: [ref4(L2, LT, "Multiple Connections")],
7084
+ eras: ["legacy"],
7085
+ transports: HTTP,
7086
+ needsFixture: true
7087
+ }),
7088
+ // A local server against DNS rebinding: only for localhost, 127.0.0.1, [::1] and *.localhost.
7089
+ check2({
7090
+ id: "http-origin-invalid-403",
7091
+ title: "A foreign Origin is refused with 403",
7092
+ description: "A request with Origin: https://evil.example gets 403 Forbidden. It proves nothing when the control with a localhost Origin is refused as well: then could-not-run (prerequisite-failed).",
7093
+ level: "MUST",
7094
+ specRefs: [ref4(L2, LT, "Security Warning"), ref4(M2, MT, "Security & Endpoint")],
7095
+ eras: BOTH3,
7096
+ transports: HTTP
7097
+ }),
7098
+ unscored("control", {
7099
+ id: "http-origin-localhost-accepted",
7100
+ title: "An Origin of localhost is accepted",
7101
+ description: "A request with Origin: http://localhost:<port> is accepted. Not a requirement: without it, a 403 to a foreign Origin shows a server that refuses everything, not a protection.",
7102
+ specRefs: [ref4(L2, LT, "Security Warning"), ref4(M2, MT, "Security & Endpoint")],
7103
+ eras: BOTH3,
7104
+ transports: HTTP
7105
+ }),
7106
+ unscored("control", {
7107
+ id: "http-origin-absent-accepted",
7108
+ title: "A request without Origin is accepted",
7109
+ description: "A request with no Origin (not from a browser) is accepted: the specification speaks only of an Origin that is present and invalid.",
7110
+ specRefs: [ref4(L2, LT, "Security Warning"), ref4(M2, MT, "Security & Endpoint")],
7111
+ eras: BOTH3,
7112
+ transports: HTTP
7113
+ }),
7114
+ check2({
7115
+ id: "http-bind-loopback",
7116
+ title: "A local server listens on loopback only",
7117
+ description: "The port of a local server cannot be reached at an outside address of this machine. Without an outside address to try, could-not-run (needs-input).",
7118
+ level: "SHOULD",
7119
+ specRefs: [ref4(L2, LT, "Security Warning"), ref4(M2, MT, "Security & Endpoint")],
7120
+ eras: BOTH3,
7121
+ transports: HTTP
7122
+ }),
7123
+ unscored("advice", {
7124
+ id: "http-host-rebinding-advice",
7125
+ title: "A foreign Host is refused (advice outside the specification)",
7126
+ description: "Not a requirement of the specification, practical advice: a local server that accepts a request with Host: evil.example relies on the Origin check alone against DNS rebinding.",
7127
+ specRefs: [ref4(L2, LT, "Security Warning"), ref4(M2, MT, "Security & Endpoint")],
7128
+ eras: BOTH3,
7129
+ transports: HTTP
7130
+ }),
7131
+ // The 2026-07-28 revision over the whole run: these read every message the run got back, so they come after the rest.
7132
+ check2({
7133
+ id: "mod-result-type-present",
7134
+ title: "Every result has a known resultType",
7135
+ description: 'Every result the run got has resultType "complete" or "input_required". Extensions MAY add values, which the text does not let a client name in advance: another value passes only when the server declares capabilities.extensions, and is said so.',
7136
+ level: "MUST",
7137
+ specRefs: [ref4(M2, "basic/index", "ResultType")],
7138
+ eras: MODERN3,
7139
+ transports: ANY
7140
+ }),
7141
+ check2({
7142
+ id: "mod-error-code-range",
7143
+ title: "No error code of the reserved range is invented",
7144
+ description: "No error the run got has a code from -32099 to -32020 other than -32020, -32021 and -32022, nor -32002 or -32042, which the revision retired. Whether a defined code is used for its meaning is not judged here.",
7145
+ level: "MUST",
7146
+ specRefs: [ref4(M2, "basic/index", "Error Codes")],
7147
+ eras: MODERN3,
7148
+ transports: ANY
7149
+ }),
7150
+ check2({
7151
+ id: "mod-logs-need-log-level",
7152
+ title: "No log message for a request without logLevel",
7153
+ description: "No request of the run set io.modelcontextprotocol/logLevel, so no notifications/message came back. Logging is deprecated in this revision: a server that does not declare logging is not-applicable.",
7154
+ level: "MUST",
7155
+ specRefs: [ref4(M2, "server/utilities/logging", "Per-request log level")],
7156
+ eras: MODERN3,
7157
+ transports: ANY
7158
+ }),
7159
+ check2({
7160
+ id: "mod-wire-schema-valid",
7161
+ title: "Every message conforms to the schema of the revision",
7162
+ description: "Every message the run got validates against schema.json of 2026-07-28: a response against the result of the method it answers (InputRequiredResult for input_required), an error against JSONRPCErrorResponse, a notification of a known method against its definition. The schema file is shipped with the checker, its SHA-256 in the result. The schema gives an error no null id, while JSON-RPC 2.0 answers a message whose id could not be read with id: null: that null is taken as the absent id.",
7163
+ level: "MUST",
7164
+ derived: true,
7165
+ derivation: "basic/index, Messages: every message MUST follow JSON-RPC 2.0; basic/index, Schema: the TypeScript schema is the source of truth for all protocol messages and structures, and schema.json is generated from it. No sentence says MUST about conforming to the schema itself.",
7166
+ specRefs: [ref4(M2, "basic/index", "Schema")],
7167
+ eras: MODERN3,
7168
+ transports: ANY
7169
+ }),
7170
+ // stdio
7171
+ check2({
7172
+ id: "stdio-stdout-clean",
7173
+ title: "stdout holds only MCP messages",
7174
+ description: "Every line the server writes to stdout is one whole JSON-RPC message, with no newline inside it.",
7175
+ level: "MUST",
7176
+ specRefs: [ref4(L2, "basic/transports", "stdio"), ref4(M2, "basic/transports/stdio", "stdio")],
7177
+ eras: BOTH3,
7178
+ transports: ["stdio"]
7179
+ }),
7180
+ check2({
7181
+ id: "stdio-exit-on-eof",
7182
+ title: "The server exits when stdin closes",
7183
+ description: "After its stdin is closed the server process ends within a short time.",
7184
+ level: "SHOULD",
7185
+ specRefs: [ref4(M2, "basic/transports/stdio", "Shutdown")],
7186
+ eras: BOTH3,
7187
+ transports: ["stdio"]
7188
+ }),
7189
+ // The oauth suite (auth-catalog.ts)
7190
+ ...OAUTH_CATALOG,
7191
+ // The apps suite (apps-catalog.ts)
7192
+ ...APPS_CATALOG,
7193
+ // The tasks suite (tasks-catalog.ts)
7194
+ ...TASKS_CATALOG
7195
+ ];
7196
+ var BY_ID = new Map(CATALOG.map((e) => [e.id, e]));
7197
+
7198
+ // src/mcp-testing/conformance/profile.ts
7199
+ init_cjs_shims();
7200
+ var import_node_crypto5 = require("crypto");
7201
+
7202
+ // src/mcp-testing/report/human.ts
7203
+ init_exit_codes();
7204
+
7205
+ // src/mcp-testing/snapshot/index.ts
7206
+ init_cjs_shims();
7207
+
7208
+ // src/mcp-testing/snapshot/snapshot.ts
7209
+ init_cjs_shims();
7210
+
7211
+ // src/mcp-testing/snapshot/diff.ts
7212
+ init_cjs_shims();
7213
+
7214
+ // src/mcp-testing/report/human.ts
7215
+ var noCommands = (text) => text.replace(/^([\s\u0085]*)::/gm, "$1?::").replaceAll("##[", "##?[");
7216
+
7217
+ // src/mcp-testing/scan/descriptions.ts
7218
+ init_cjs_shims();
7219
+
7220
+ // src/mcp-testing/scan/phrases.ts
7221
+ init_cjs_shims();
7222
+ var DESCRIPTION_PHRASES = {
7223
+ version: 1,
7224
+ rules: {
7225
+ "scan/desc/override-instruction": [
7226
+ "\\b(?:ignore|disregard|forget|override) (?:all |any )?(?:of )?(?:the |your |my )?(?:previous|prior|above|earlier|preceding|other|system) (?:instructions?|prompts?|messages?|rules?|context)",
7227
+ "\\b(?:ignore|disregard) (?:all |any )?(?:of )?(?:the |your )?(?:previous|prior|above|earlier|preceding)\\b",
7228
+ "\\bnew (?:system )?instructions:",
7229
+ "\\byou are now (?:a|an|in)\\b"
7230
+ ],
7231
+ "scan/desc/sensitive-path": [
7232
+ "(?<![\\w.~])(?:~/)?\\.ssh\\b",
7233
+ "\\bid_(?:rsa|dsa|ecdsa|ed25519)\\b",
7234
+ "(?<![\\w.~])(?:~/)?\\.aws/(?:credentials|config)\\b",
7235
+ "(?<![\\w.~])(?:~/)?\\.env\\b",
7236
+ "(?<![\\w.~])(?:~/)?\\.(?:npmrc|pypirc|netrc|pgpass|git-credentials)\\b",
7237
+ "(?<![\\w.~])(?:~/)?\\.(?:docker/config\\.json|kube/config|gnupg|config/gcloud)\\b",
7238
+ "/etc/(?:shadow|passwd)\\b",
7239
+ "\\bcredentials\\.json\\b",
7240
+ "\\bread (?:the )?(?:contents? of )?(?:the |any |a )?(?:file|files)\\b"
7241
+ ],
7242
+ "scan/desc/conceal-from-user": [
7243
+ "\\b(?:do not|don't|dont|never) (?:tell|inform|notify|alert|mention (?:this |it )?to|reveal (?:this |it )?to|show (?:this |it )?to) (?:the )?user",
7244
+ "\\bwithout (?:telling|informing|notifying|alerting) (?:the )?user",
7245
+ "\\b(?:hide|conceal|keep) (?:this |it |that )?(?:secret |hidden )?from (?:the )?user",
7246
+ "\\bthe user (?:must|should) not (?:know|see|be told)"
7247
+ ],
7248
+ "scan/desc/call-other-tool-first": [
7249
+ "\\b(?:before|prior to) (?:using|calling|invoking|running) this tool,? (?:you )?(?:must |should |always )?(?:first )?(?:call|use|invoke|run)\\b",
7250
+ "\\b(?:always |must )?(?:first )?(?:call|invoke|run) (?:the )?[\\w.-]+ (?:tool )?(?:first|beforehand|before (?:this|using this|calling this))\\b",
7251
+ "\\binstead of (?:this tool|calling this tool|using this tool),? (?:call|use|invoke)\\b"
7252
+ ],
7253
+ "scan/desc/param-asks-for-context": [
7254
+ "\\b(?:the )?(?:entire|full|whole|complete) (?:conversation|chat|dialog(?:ue)?|history|context|transcript)",
7255
+ "\\bconversation history\\b",
7256
+ "\\b(?:all |the )?(?:previous|prior|earlier) messages\\b",
7257
+ "\\bsystem prompt\\b",
7258
+ "\\b(?:contents?|text) of (?:the |any |a )?(?:file|files|document)\\b",
7259
+ "\\b(?:output|result|response) (?:of|from) (?:the |another |other |any )?(?:tools?)\\b"
7260
+ ]
7261
+ }
7262
+ };
7263
+
7264
+ // src/mcp-testing/scan/descriptions.ts
7265
+ var MAX_TEXT_BYTES = 1024 * 1024;
7266
+ var EXCERPT = 80;
7267
+ var U = (cp) => `U+${cp.toString(16).toUpperCase().padStart(4, "0")}`;
7268
+ var SHOWN = /^[\p{L}\p{N}\p{P}\p{S} ]$/u;
7269
+ function visible(s, max = EXCERPT) {
7270
+ const pieces = [];
7271
+ let len = 0;
7272
+ for (const ch of s) {
7273
+ const piece = SHOWN.test(ch) ? ch : `[${U(ch.codePointAt(0))}]`;
7274
+ pieces.push(piece);
7275
+ len += [...piece].length;
7276
+ if (len > max) {
7277
+ while (len > max - 3) len -= [...pieces.pop()].length;
7278
+ return `${pieces.join("")}...`;
7279
+ }
7280
+ }
7281
+ return pieces.join("");
7282
+ }
7283
+ var EMOJI = new RegExp("\\p{Extended_Pictographic}", "u");
7284
+ var PHRASES = Object.fromEntries(
7285
+ Object.entries(DESCRIPTION_PHRASES.rules).map(([id, list2]) => [id, new RegExp(list2.map((p) => `(?:${p.replace(/ /g, "\\s+")})`).join("|"), "giu")])
7286
+ );
7287
+
7288
+ // src/mcp-testing/scan/config/json-tree.ts
7289
+ init_cjs_shims();
7290
+
7291
+ // src/mcp-testing/scan/config/config.ts
7292
+ var MAX_FILE_BYTES = 8 * 1024 * 1024;
7293
+ var MAX_VALUE = 64 * 1024;
7294
+ var SHOWN_NAME = 64;
7295
+ var KNOWN_FORMATS = [
7296
+ ["github-token", /(?<![A-Za-z0-9])(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]{36,}/],
7297
+ ["aws-access-key-id", /(?<![A-Za-z0-9])(?:AKIA|ASIA|AGPA|AIDA|AROA)[A-Z2-7]{16}(?![A-Za-z0-9])/],
7298
+ ["slack-token", /(?<![A-Za-z0-9])xox[abprs]-[A-Za-z0-9-]{10,}/],
7299
+ ["stripe-key", /(?<![A-Za-z0-9])[rs]k_live_[A-Za-z0-9]{16,}/],
7300
+ ["anthropic-key", /(?<![A-Za-z0-9])sk-ant-[A-Za-z0-9_-]{20,}/],
7301
+ ["openai-key", /(?<![A-Za-z0-9])sk-(?:proj|svcacct)-[A-Za-z0-9_-]{32,}/],
7302
+ ["google-api-key", /(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{35}/],
7303
+ ["npm-token", /(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/],
7304
+ ["gitlab-token", /(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20}/],
7305
+ ["private-key", /-----BEGIN (?:[A-Z]+ )*PRIVATE KEY-----/]
7306
+ ];
7307
+ var KEY_PREFIX = /^\s*(?:gh[pousr]_|github_pat_|AKIA|ASIA|AGPA|AIDA|AROA|xox[abprs]-|[rs]k_live_|sk-ant-|AIza|npm_|glpat-|-----BEGIN )/;
7308
+ var NAME_FORMATS = KNOWN_FORMATS.map(
7309
+ ([, re]) => new RegExp(re.source.replace("(?<![A-Za-z0-9])", "").replace("(?![A-Za-z0-9])", ""), re.flags)
7310
+ );
7311
+ var tokenish = (name) => {
7312
+ const head = name.slice(0, 256);
7313
+ return KEY_PREFIX.test(head) || NAME_FORMATS.some((re) => re.test(head));
7314
+ };
7315
+ var safe = (name) => noCommands(visible(tokenish(name) ? "[key]" : name, SHOWN_NAME));
7316
+ var safeText = (text) => noCommands(
7317
+ visible(
7318
+ text.slice(0, 1024).replace(/[^\\/]+/g, (seg) => tokenish(seg) ? "[key]" : seg),
7319
+ 400
7320
+ )
7321
+ );
7322
+
7323
+ // src/cli/commands/cairn-artifact.ts
7324
+ var SUPPORTED_ARTIFACT_VERSION = 1;
7325
+ var INGEST_SCHEMA_VERSION = 1;
7326
+ var NoCairnRunsError = class extends Error {
7327
+ constructor(runsDir) {
7328
+ super(`No Cairn run found under ${runsDir} \u2014 name the directory instead: plune ingest <dir>.`);
7329
+ this.name = "NoCairnRunsError";
7330
+ }
7331
+ };
7332
+ async function findLatestCairnRun(runsDir = "runs") {
7333
+ const entries = await fs8.readdir(runsDir, { withFileTypes: true }).catch(() => null);
7334
+ if (entries === null) throw new NoCairnRunsError(runsDir);
7335
+ let newest;
7336
+ for (const entry of entries) {
7337
+ if (!entry.isDirectory()) continue;
7338
+ const dir = path9.join(runsDir, entry.name);
7339
+ try {
7340
+ const report = await fs8.lstat(path9.join(dir, "report.json"));
7341
+ if (!report.isFile()) continue;
7342
+ if (newest === void 0 || report.mtimeMs > newest.at) {
7343
+ newest = { dir, at: report.mtimeMs };
7344
+ }
7345
+ } catch {
7346
+ }
7347
+ }
7348
+ if (newest === void 0) throw new NoCairnRunsError(runsDir);
7349
+ return newest.dir;
7350
+ }
7351
+ var CairnRunNotFoundError = class extends Error {
7352
+ constructor(dir) {
7353
+ super(
7354
+ `No Cairn run found in ${dir} \u2014 expected a report.json written by "cairn design|explore|api".`
7355
+ );
7356
+ this.name = "CairnRunNotFoundError";
7357
+ }
7358
+ };
7359
+ var CairnRunVersionError = class extends Error {
7360
+ constructor(found) {
7361
+ super(
7362
+ found === void 0 ? "This run predates versioned Cairn artifacts. Re-run it with Cairn 0.7.0 or newer, which stamps the format so it can be read safely." : `Unsupported Cairn artifact version ${String(found)} (this CLI reads version ${SUPPORTED_ARTIFACT_VERSION}). Upgrade @plune-ai/cli.`
7363
+ );
7364
+ this.name = "CairnRunVersionError";
7365
+ }
7366
+ };
7367
+ var CairnRunPartialError = class extends Error {
7368
+ constructor(reason) {
7369
+ super(`That Cairn run did not finish, so its cases are incomplete: ${reason}`);
7370
+ this.name = "CairnRunPartialError";
7371
+ }
7372
+ };
7373
+ var CairnArtifactShapeError = class extends Error {
7374
+ constructor(file, field, problem) {
7375
+ super(
7376
+ `Cannot read this Cairn run: ${file}${field === "" ? "" : field.startsWith("[") ? field : ` ${field}`} ${problem}. Nothing was uploaded.`
7377
+ );
7378
+ this.name = "CairnArtifactShapeError";
7379
+ }
7380
+ };
7381
+ var CairnEvidenceAmbiguousError = class extends Error {
7382
+ constructor(name) {
7383
+ super(
7384
+ `Cannot attach results safely: the operation "${name}" appears more than once in this run's evidence, and the evidence file carries no case identity to disambiguate it. Nothing was uploaded.`
7385
+ );
7386
+ this.name = "CairnEvidenceAmbiguousError";
7387
+ }
7388
+ };
7389
+ var asRecord = (v) => typeof v === "object" && v !== null ? v : {};
7390
+ var str = (v, fallback = "") => typeof v === "string" && v !== "" ? v : fallback;
7391
+ var own = (rec, key) => Object.hasOwn(rec, key) ? rec[key] : void 0;
7392
+ var MAX_ARTIFACT_BYTES = 32 * 1024 * 1024;
7393
+ var MAX_MCP_CASES = 5e3;
7394
+ async function checkSize(dir, file) {
7395
+ let size;
7396
+ try {
7397
+ const st = await fs8.stat(path9.join(dir, file));
7398
+ if (!st.isFile()) throw new CairnArtifactShapeError(file, "", "is not a regular file");
7399
+ size = st.size;
7400
+ } catch (e) {
7401
+ if (e instanceof CairnArtifactShapeError) throw e;
7402
+ return false;
7403
+ }
7404
+ if (size > MAX_ARTIFACT_BYTES) {
7405
+ throw new CairnArtifactShapeError(
7406
+ file,
7407
+ "",
7408
+ `is larger than ${MAX_ARTIFACT_BYTES / (1024 * 1024)} MiB`
7409
+ );
7410
+ }
7411
+ return true;
7412
+ }
7413
+ async function readJson(file) {
7414
+ try {
7415
+ return JSON.parse(await fs8.readFile(file, "utf8"));
7416
+ } catch {
7417
+ return void 0;
7418
+ }
7419
+ }
7420
+ var ARGS_CHARS2 = 200;
7421
+ var SECRET_NAME = /key|token|secret|password|passwd|auth|cookie|credential/i;
7422
+ var maskNamed = (v, depth = 0) => {
7423
+ if (depth > 16) return "[deep]";
7424
+ if (Array.isArray(v)) return v.slice(0, 50).map((x) => maskNamed(x, depth + 1));
7425
+ if (typeof v === "object" && v !== null) {
7426
+ const out = {};
7427
+ for (const [k, x] of Object.entries(v).slice(0, 50)) {
7428
+ out[k] = SECRET_NAME.test(k) ? "***" : maskNamed(x, depth + 1);
7429
+ }
7430
+ return out;
7431
+ }
7432
+ return v;
7433
+ };
7434
+ function describeMcpArgs(request) {
7435
+ let text = request.slice(0, 4096);
7436
+ try {
7437
+ text = JSON.stringify(maskNamed(JSON.parse(text)));
7438
+ } catch {
7439
+ }
7440
+ const masked = safeText(redactSecrets(text));
7441
+ return masked.length > ARGS_CHARS2 ? `${masked.slice(0, ARGS_CHARS2)} (cut)` : masked;
7442
+ }
7443
+ var MCP_STATES = /* @__PURE__ */ new Set([
7444
+ "passed",
7445
+ "failed",
7446
+ "not-sent",
7447
+ "could-not-run",
7448
+ "needs-review"
7449
+ ]);
7450
+ async function readMcpEvidence(dir, states) {
7451
+ const file = "mcp-evidence.json";
7452
+ if (!await checkSize(dir, file)) return void 0;
7453
+ let raw;
7454
+ try {
7455
+ raw = JSON.parse(await fs8.readFile(path9.join(dir, file), "utf8"));
7456
+ } catch {
7457
+ throw new CairnArtifactShapeError(file, "", "is not valid JSON");
7458
+ }
7459
+ if (!Array.isArray(raw)) throw new CairnArtifactShapeError(file, "", "must be a list");
7460
+ if (raw.length > MAX_MCP_CASES) {
7461
+ throw new CairnArtifactShapeError(file, "", `lists more than ${MAX_MCP_CASES} entries`);
7462
+ }
7463
+ const byId = /* @__PURE__ */ new Map();
7464
+ raw.forEach((item, i) => {
7465
+ if (typeof item !== "object" || item === null || Array.isArray(item)) {
7466
+ throw new CairnArtifactShapeError(file, `[${i}]`, "must be an object");
7467
+ }
7468
+ const rec = item;
7469
+ const id = own(rec, "stableId");
7470
+ if (typeof id !== "string" || !states.has(id)) {
7471
+ throw new CairnArtifactShapeError(
7472
+ file,
7473
+ `[${i}].stableId`,
7474
+ "does not name a case of report.json"
7475
+ );
7476
+ }
7477
+ if (byId.has(id)) {
7478
+ throw new CairnArtifactShapeError(file, `[${i}].stableId`, "appears more than once");
7479
+ }
7480
+ if (own(rec, "state") !== states.get(id)) {
7481
+ throw new CairnArtifactShapeError(
7482
+ file,
7483
+ `[${i}].state`,
7484
+ "does not agree with the state in report.json"
7485
+ );
7486
+ }
7487
+ const request = own(rec, "request");
7488
+ if (request !== void 0 && typeof request !== "string") {
7489
+ throw new CairnArtifactShapeError(file, `[${i}].request`, "must be text");
7490
+ }
7491
+ const durationMs = own(rec, "durationMs");
7492
+ if (durationMs !== void 0 && typeof durationMs !== "number") {
7493
+ throw new CairnArtifactShapeError(file, `[${i}].durationMs`, "must be a number");
7494
+ }
7495
+ byId.set(id, {
7496
+ sent: typeof durationMs === "number",
7497
+ ...request !== void 0 ? { request } : {}
7498
+ });
7499
+ });
7500
+ return byId;
7501
+ }
7502
+ function expectedOfMcp(type, adversarial) {
7503
+ if (type === "Positive") {
7504
+ return "The call finishes without an error, and the answer fits the tool's outputSchema when it has one.";
7505
+ }
7506
+ return adversarial ? "The server rejects the call, or handles the value without harm." : "The server rejects the call: it does not act on a value the tool's inputSchema forbids.";
7507
+ }
7508
+ async function casesFromMcp(dir, report) {
7509
+ const list2 = own(report, "cases");
7510
+ if (!Array.isArray(list2))
7511
+ throw new CairnArtifactShapeError("report.json", "cases", "must be a list");
7512
+ if (list2.length > MAX_MCP_CASES) {
7513
+ throw new CairnArtifactShapeError(
7514
+ "report.json",
7515
+ "cases",
7516
+ `lists more than ${MAX_MCP_CASES} cases`
7517
+ );
7518
+ }
7519
+ const states = /* @__PURE__ */ new Map();
7520
+ const parsed2 = list2.map((raw, i) => {
7521
+ const at = `cases[${i}]`;
7522
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
7523
+ throw new CairnArtifactShapeError("report.json", at, "must be an object");
7524
+ }
7525
+ const c = raw;
7526
+ const text = (key) => {
7527
+ const v = own(c, key);
7528
+ if (typeof v !== "string" || v === "") {
7529
+ throw new CairnArtifactShapeError("report.json", `${at}.${key}`, "must be text");
7530
+ }
7531
+ return v;
7532
+ };
7533
+ const stableId = text("stableId");
7534
+ const name = text("name");
7535
+ const tool = text("tool");
7536
+ const type = text("type");
7537
+ const state = text("state");
7538
+ if (type !== "Positive" && type !== "Negative") {
7539
+ throw new CairnArtifactShapeError(
7540
+ "report.json",
7541
+ `${at}.type`,
7542
+ `is "${safe(type)}", not Positive or Negative`
7543
+ );
7544
+ }
7545
+ if (!MCP_STATES.has(state)) {
7546
+ throw new CairnArtifactShapeError(
7547
+ "report.json",
7548
+ `${at}.state`,
7549
+ `is "${safe(state)}", a state this CLI does not know`
7550
+ );
7551
+ }
7552
+ if (states.has(stableId)) {
7553
+ throw new CairnArtifactShapeError("report.json", `${at}.stableId`, "appears more than once");
7554
+ }
7555
+ states.set(stableId, state);
7556
+ const kind = type;
7557
+ const technique = own(c, "technique");
7558
+ return {
7559
+ stableId,
7560
+ name,
7561
+ tool,
7562
+ type: kind,
7563
+ state,
7564
+ adversarial: own(c, "adversarialStyle") !== void 0,
7565
+ ...typeof technique === "string" ? { technique } : {}
7566
+ };
7567
+ });
7568
+ const evidence = await readMcpEvidence(dir, states);
7569
+ return parsed2.map((c) => {
7570
+ const e = evidence?.get(c.stableId);
7571
+ const verdict = c.state === "passed" ? "passed" : c.state === "failed" ? "failed" : c.state === "could-not-run" && e?.sent === true ? "blocked" : void 0;
7572
+ const args = e?.request !== void 0 ? ` ${describeMcpArgs(e.request)}` : "";
7573
+ return {
7574
+ stableId: c.stableId,
7575
+ title: safeText(c.name),
7576
+ execution: "auto",
7577
+ steps: [`tools/call ${safe(c.tool)}${args}`],
7578
+ expected: expectedOfMcp(c.type, c.adversarial),
7579
+ ...verdict !== void 0 ? { verdict } : {},
7580
+ ...c.technique !== void 0 ? { technique: safeText(c.technique) } : {}
7581
+ };
7582
+ });
7583
+ }
7584
+ async function defaultReadEvidence(dir) {
7585
+ const raw = await readJson(path9.join(dir, "api-evidence.json"));
7586
+ if (!Array.isArray(raw)) return void 0;
7587
+ return raw.map((r) => {
7588
+ const rec = asRecord(r);
7589
+ const error = str(rec["error"]);
7590
+ return { name: str(rec["name"]), passed: rec["passed"] === true, ...error !== "" ? { error } : {} };
7591
+ });
7592
+ }
7593
+ function casesFromDesign(report) {
7594
+ const list2 = Array.isArray(report["testCases"]) ? report["testCases"] : [];
7595
+ return list2.map((raw) => {
7596
+ const c = asRecord(raw);
7597
+ const steps = (Array.isArray(c["steps"]) ? c["steps"] : []).map((s) => str(s)).filter((s) => s !== "");
7598
+ return {
7599
+ stableId: str(c["stableId"]),
7600
+ title: str(c["title"], "untitled case"),
7601
+ execution: c["execution"] === "manual" ? "manual" : "auto",
4560
7602
  steps: steps.length > 0 ? steps : ["(no steps recorded)"],
4561
7603
  expected: str(c["expected"], "(no expected result recorded)"),
4562
7604
  ...typeof c["technique"] === "string" ? { technique: c["technique"] } : {},
@@ -4565,8 +7607,8 @@ function casesFromDesign(report) {
4565
7607
  });
4566
7608
  }
4567
7609
  function casesFromApi(report, verdicts) {
4568
- const list = Array.isArray(report["cases"]) ? report["cases"] : [];
4569
- return list.map((raw) => {
7610
+ const list2 = Array.isArray(report["cases"]) ? report["cases"] : [];
7611
+ return list2.map((raw) => {
4570
7612
  const c = asRecord(raw);
4571
7613
  const name = str(c["name"], "unnamed operation");
4572
7614
  const request = `${str(c["method"], "GET")} ${str(c["path"], "/")}`;
@@ -4583,7 +7625,8 @@ function casesFromApi(report, verdicts) {
4583
7625
  });
4584
7626
  }
4585
7627
  async function readCairnRun(dir, deps = {}) {
4586
- const raw = await readJson(path7.join(dir, "report.json"));
7628
+ await checkSize(dir, "report.json");
7629
+ const raw = await readJson(path9.join(dir, "report.json"));
4587
7630
  if (raw === void 0) throw new CairnRunNotFoundError(dir);
4588
7631
  const report = asRecord(raw);
4589
7632
  if (report["schemaVersion"] !== SUPPORTED_ARTIFACT_VERSION) {
@@ -4593,7 +7636,7 @@ async function readCairnRun(dir, deps = {}) {
4593
7636
  throw new CairnRunPartialError(str(report["error"], "no reason recorded"));
4594
7637
  }
4595
7638
  const mode = report["mode"];
4596
- if (mode !== "design" && mode !== "explore" && mode !== "api") {
7639
+ if (mode !== "design" && mode !== "explore" && mode !== "api" && mode !== "mcp") {
4597
7640
  throw new CairnRunVersionError(
4598
7641
  `${SUPPORTED_ARTIFACT_VERSION} (unknown run mode ${String(mode)})`
4599
7642
  );
@@ -4607,19 +7650,54 @@ async function readCairnRun(dir, deps = {}) {
4607
7650
  verdicts.set(e.name, e.error !== void 0 ? "blocked" : e.passed ? "passed" : "failed");
4608
7651
  }
4609
7652
  cases = casesFromApi(report, verdicts);
7653
+ } else if (mode === "mcp") {
7654
+ cases = await casesFromMcp(dir, report);
4610
7655
  } else {
4611
7656
  cases = casesFromDesign(report);
4612
7657
  }
4613
7658
  return {
4614
7659
  schemaVersion: INGEST_SCHEMA_VERSION,
4615
7660
  run: {
4616
- runId: str(report["runId"], path7.basename(dir)),
7661
+ runId: str(report["runId"], path9.basename(dir)),
4617
7662
  mode,
4618
7663
  target: str(report["url"], "unknown")
4619
7664
  },
4620
7665
  cases
4621
7666
  };
4622
7667
  }
7668
+ async function readCairnSessionFiles(dir) {
7669
+ const raw = await readJson(path9.join(dir, "screencasts", "screencasts.json"));
7670
+ if (!Array.isArray(raw)) return void 0;
7671
+ const root = await fs8.realpath(dir).catch(() => path9.resolve(dir));
7672
+ const within = (p) => {
7673
+ const rel = path9.relative(root, p);
7674
+ return rel !== "" && !rel.startsWith("..") && !path9.isAbsolute(rel);
7675
+ };
7676
+ let outside = 0;
7677
+ const inside = async (p) => {
7678
+ if (typeof p !== "string" || p === "") return void 0;
7679
+ const abs = path9.resolve(root, p);
7680
+ const real = await fs8.realpath(abs).catch(() => void 0);
7681
+ if (within(abs) && (real === void 0 || within(real))) return real ?? abs;
7682
+ outside += 1;
7683
+ return void 0;
7684
+ };
7685
+ const byCase = /* @__PURE__ */ new Map();
7686
+ let unmapped = 0;
7687
+ for (const entry of raw) {
7688
+ const rec = asRecord(entry);
7689
+ const files = [];
7690
+ for (const p of [own(rec, "video"), own(rec, "trace")]) {
7691
+ const file = await inside(p);
7692
+ if (file !== void 0) files.push(file);
7693
+ }
7694
+ if (files.length === 0) continue;
7695
+ const stableId = own(rec, "stableId");
7696
+ if (typeof stableId !== "string" || stableId === "") unmapped += 1;
7697
+ else byCase.set(stableId, [...byCase.get(stableId) ?? [], ...files]);
7698
+ }
7699
+ return { byCase, unmapped, outside };
7700
+ }
4623
7701
 
4624
7702
  // src/cli/commands/ingest.ts
4625
7703
  var IngestNotLoggedInError = class extends Error {
@@ -4648,6 +7726,131 @@ var IngestHttpError = class extends Error {
4648
7726
  }
4649
7727
  status;
4650
7728
  };
7729
+ var SESSION_FILE_MAX = 100 * 1024 * 1024;
7730
+ var SESSION_UPLOADS_AT_ONCE = 4;
7731
+ var TYPE_BY_EXTENSION2 = { ".webm": "video/webm", ".zip": "application/zip" };
7732
+ function itemsOf(body) {
7733
+ const items = body?.items;
7734
+ if (!Array.isArray(items)) return void 0;
7735
+ return items.flatMap((raw) => {
7736
+ const i = raw ?? {};
7737
+ if (typeof i["stableId"] !== "string") return [];
7738
+ const reviewItemId = typeof i["reviewItemId"] === "string" && i["reviewItemId"] !== "" ? i["reviewItemId"] : void 0;
7739
+ const resultId = typeof i["resultId"] === "string" && i["resultId"] !== "" ? i["resultId"] : void 0;
7740
+ if (reviewItemId === void 0 && resultId === void 0) return [];
7741
+ return [{ stableId: i["stableId"], ...reviewItemId !== void 0 ? { reviewItemId } : {}, ...resultId !== void 0 ? { resultId } : {} }];
7742
+ });
7743
+ }
7744
+ var RESULT_PAGES_MAX = 100;
7745
+ var namesOf = (files) => new Set(Array.isArray(files) ? files.flatMap((f) => typeof f?.name === "string" ? [f.name] : []) : []);
7746
+ async function heldBy(client, runId, jobs) {
7747
+ const held = /* @__PURE__ */ new Map();
7748
+ for (const job of jobs) {
7749
+ const key = targetOf(job);
7750
+ if (held.has(key) || job.owner !== "review-items") continue;
7751
+ const out = await client.get(`/v1/review-items/${encodeURIComponent(job.id)}`);
7752
+ held.set(key, out.ok ? namesOf(out.body?.files) : void 0);
7753
+ }
7754
+ const results = jobs.filter((j) => j.owner === void 0);
7755
+ if (results.length === 0) return held;
7756
+ let byResult = /* @__PURE__ */ new Map();
7757
+ let before;
7758
+ for (let page = 0; ; page += 1) {
7759
+ if (runId === "" || page >= RESULT_PAGES_MAX) {
7760
+ byResult = void 0;
7761
+ break;
7762
+ }
7763
+ const query = before === void 0 ? "" : `?before=${encodeURIComponent(before)}`;
7764
+ const out = await client.get(`/v1/runs/${encodeURIComponent(runId)}/results${query}`);
7765
+ if (!out.ok || !Array.isArray(out.body?.results)) {
7766
+ byResult = void 0;
7767
+ break;
7768
+ }
7769
+ for (const r of out.body.results) {
7770
+ if (typeof r?.id === "string") byResult.set(r.id, namesOf(r.files));
7771
+ }
7772
+ if (typeof out.body.next !== "string" || out.body.next === "") break;
7773
+ before = out.body.next;
7774
+ }
7775
+ for (const job of results) held.set(targetOf(job), byResult === void 0 ? void 0 : byResult.get(job.id) ?? /* @__PURE__ */ new Set());
7776
+ return held;
7777
+ }
7778
+ var targetOf = (job) => `${job.owner ?? "results"}/${job.id}`;
7779
+ async function sendSessionFiles(dir, sent, platform) {
7780
+ const session = await readCairnSessionFiles(dir);
7781
+ if (session === void 0 || session.byCase.size === 0 && session.unmapped === 0 && session.outside === 0) return [];
7782
+ if (sent.items === void 0) {
7783
+ return ["session files not uploaded \u2014 this Plune is older than the routes that take them"];
7784
+ }
7785
+ const lines = [];
7786
+ if (session.outside > 0) lines.push(`${session.outside} file(s) not uploaded \u2014 the path leaves the run directory`);
7787
+ if (session.unmapped > 0) lines.push(`${session.unmapped} recording(s) name no case \u2014 not uploaded`);
7788
+ let jobs = [];
7789
+ let tooBig = 0;
7790
+ const placed = /* @__PURE__ */ new Set();
7791
+ for (const item of sent.items) {
7792
+ const paths = session.byCase.get(item.stableId);
7793
+ if (paths === void 0 || placed.has(item.stableId)) continue;
7794
+ placed.add(item.stableId);
7795
+ for (const file of paths) {
7796
+ const name = path10.basename(file);
7797
+ const size = await import_node_fs8.promises.stat(file).then((s) => s.size, () => void 0);
7798
+ if (size !== void 0 && size > SESSION_FILE_MAX) {
7799
+ tooBig += 1;
7800
+ lines.push(`"${name}" skipped \u2014 larger than the ${SESSION_FILE_MAX / (1024 * 1024)} MiB a session file may be`);
7801
+ continue;
7802
+ }
7803
+ const type = TYPE_BY_EXTENSION2[path10.extname(file).toLowerCase()] ?? "application/octet-stream";
7804
+ jobs.push({
7805
+ id: item.reviewItemId ?? item.resultId,
7806
+ ...item.reviewItemId !== void 0 ? { owner: "review-items" } : {},
7807
+ kind: "file",
7808
+ name,
7809
+ type,
7810
+ path: file
7811
+ });
7812
+ }
7813
+ }
7814
+ const unplaced = [...session.byCase.keys()].filter((stableId) => !placed.has(stableId)).length;
7815
+ if (unplaced > 0) lines.push(`${unplaced} case(s) with recordings got no proposal or result in this run \u2014 not uploaded`);
7816
+ const client = createClient({
7817
+ apiUrl: platform.apiUrl,
7818
+ token: platform.token,
7819
+ uploadRetries: UPLOAD_RETRIES.default,
7820
+ ...platform.fetchImpl !== void 0 ? { fetchImpl: platform.fetchImpl } : {}
7821
+ });
7822
+ if (sent.repeat && jobs.length > 0) {
7823
+ const held = await heldBy(client, sent.runId, jobs);
7824
+ let already = 0;
7825
+ let unknown = 0;
7826
+ jobs = jobs.filter((job) => {
7827
+ const names = held.get(targetOf(job));
7828
+ if (names === void 0) unknown += 1;
7829
+ else if (names.has(job.name)) already += 1;
7830
+ else return true;
7831
+ return false;
7832
+ });
7833
+ if (unknown > 0) lines.push(`${unknown} file(s) not sent again \u2014 what the platform holds could not be read`);
7834
+ lines.push(`${already} file(s) already on the platform, ${jobs.length} sent`);
7835
+ }
7836
+ const counts = { screenshots: { uploaded: 0, skipped: 0, failed: 0 }, textFiles: { uploaded: 0, skipped: 0, failed: 0 }, otherFiles: { uploaded: 0, skipped: 0, failed: 0 } };
7837
+ if (jobs.length > 0) {
7838
+ const notes = [];
7839
+ const files = fileSender({
7840
+ client,
7841
+ log: (line) => notes.push(line.replace(/^plune: /, "")),
7842
+ stats: counts,
7843
+ uploadsAtOnce: SESSION_UPLOADS_AT_ONCE,
7844
+ uploadRetries: UPLOAD_RETRIES.default,
7845
+ without: "the run is recorded without it"
7846
+ });
7847
+ await files.uploadEach(jobs);
7848
+ lines.push(...notes.filter((n) => !n.startsWith("storage bucket found")));
7849
+ }
7850
+ const { uploaded, skipped, failed } = counts.otherFiles;
7851
+ const total = `${uploaded} session file(s) uploaded` + (skipped + tooBig > 0 ? `, ${skipped + tooBig} skipped` : "") + (failed > 0 ? `, ${failed} failed to upload` : "");
7852
+ return [total, ...lines];
7853
+ }
4651
7854
  async function safeErrorDetail2(res) {
4652
7855
  try {
4653
7856
  const body = await res.json();
@@ -4665,10 +7868,14 @@ async function handleIngest(deps) {
4665
7868
  const doFetch = deps.fetchImpl ?? fetch;
4666
7869
  const endpoint = `${apiUrl}/v1/ingest/cairn`;
4667
7870
  const job = new JobReporter(doFetch, apiUrl, token, "ingest");
4668
- await job.open(path8.basename(path8.resolve(dir)), payload.cases.length);
7871
+ await job.open(path10.basename(path10.resolve(dir)), payload.cases.length);
4669
7872
  try {
4670
- const result = await upload();
7873
+ const { result, ...sent } = await upload();
4671
7874
  await job.uploaded({ subjectId: result.runId || void 0 });
7875
+ const files = await sendSessionFiles(dir, { ...sent, runId: result.runId }, { apiUrl, token, ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {} }).catch(
7876
+ () => ["session files not uploaded (an unexpected error) \u2014 the run is recorded"]
7877
+ );
7878
+ if (files.length > 0) result.files = files;
4672
7879
  await job.finish({ ok: true });
4673
7880
  if (job.problem !== void 0) result.jobProblem = job.problem;
4674
7881
  return result;
@@ -4693,16 +7900,17 @@ async function handleIngest(deps) {
4693
7900
  throw new IngestHttpError(res.status, detail);
4694
7901
  }
4695
7902
  const body = await res.json().catch(() => ({}));
4696
- return {
7903
+ const result = {
4697
7904
  runId: typeof body.runId === "string" ? body.runId : "",
4698
7905
  linked: typeof body.linked === "number" ? body.linked : 0,
4699
7906
  proposed: typeof body.proposed === "number" ? body.proposed : 0,
4700
7907
  skipped: typeof body.skipped === "number" ? body.skipped : 0
4701
7908
  };
7909
+ return { result, items: itemsOf(body), repeat: res.status === 200 };
4702
7910
  }
4703
7911
  }
4704
7912
  function reportIngestFailure(err, write) {
4705
- if (err instanceof IngestNotLoggedInError || err instanceof IngestTokenRejectedError || err instanceof CairnRunNotFoundError || err instanceof NoCairnRunsError || err instanceof CairnRunVersionError || err instanceof CairnRunPartialError || err instanceof CairnEvidenceAmbiguousError) {
7913
+ if (err instanceof IngestNotLoggedInError || err instanceof IngestTokenRejectedError || err instanceof CairnRunNotFoundError || err instanceof NoCairnRunsError || err instanceof CairnRunVersionError || err instanceof CairnRunPartialError || err instanceof CairnEvidenceAmbiguousError || err instanceof CairnArtifactShapeError) {
4706
7914
  write(`${err.message}
4707
7915
  `);
4708
7916
  return 2;
@@ -4719,7 +7927,8 @@ function formatIngestResult(r) {
4719
7927
  `Ingested Cairn run \u2192 ${r.runId}`,
4720
7928
  ` ${r.linked} result(s) attached to existing cases`,
4721
7929
  ` ${r.proposed} case(s) proposed \u2014 review them in Plune to accept`,
4722
- ` ${r.skipped} skipped (already queued, already rejected, repeated, or never executed)`
7930
+ ` ${r.skipped} skipped (already queued, already rejected, repeated, or never executed)`,
7931
+ ...(r.files ?? []).map((line, i) => i === 0 ? ` ${line}` : ` ${line}`)
4723
7932
  ];
4724
7933
  return `${lines.join("\n")}
4725
7934
  `;