@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.js CHANGED
@@ -26,26 +26,28 @@ function machineless(raw, repoRoot, home) {
26
26
  let text = stripVTControlCharacters(raw).replaceAll("\x1B", "");
27
27
  const root = repoRoot === void 0 ? void 0 : pathIn(repoRoot);
28
28
  if (root !== void 0) text = text.replace(new RegExp(`${PATH_START}${root.source}[\\\\/]+`, root.flags), "");
29
- const own = pathIn(home);
30
- if (own !== void 0) text = text.replace(new RegExp(`${PATH_START}${own.source}(?![\\w.-])`, own.flags), "~");
29
+ const own2 = pathIn(home);
30
+ if (own2 !== void 0) text = text.replace(new RegExp(`${PATH_START}${own2.source}(?![\\w.-])`, own2.flags), "~");
31
31
  if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
32
32
  return text;
33
33
  }
34
- function pathIn(path10) {
35
- const parts = path10.split(/[\\/]+/);
34
+ function pathIn(path12) {
35
+ const parts = path12.split(/[\\/]+/);
36
36
  while (parts.length > 1 && parts.at(-1) === "") parts.pop();
37
37
  if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
38
38
  const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
39
- const escaped = /^\/(?!\/)/.test(path10) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
39
+ const escaped = /^\/(?!\/)/.test(path12) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
40
40
  const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
41
41
  return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
42
42
  }
43
- var printable, PATH_START, HEADLINE_LIMIT, ANY_HOME;
43
+ var printable, mediaTypeOf, TEXT_TYPES, PATH_START, HEADLINE_LIMIT, ANY_HOME;
44
44
  var init_failure_detail = __esm({
45
45
  "src/reporter-core/failure-detail.ts"() {
46
46
  "use strict";
47
47
  init_esm_shims();
48
48
  printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "?");
49
+ mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
50
+ TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
49
51
  PATH_START = "(?<![\\w.~%/\\\\-])";
50
52
  HEADLINE_LIMIT = 8 * 1024;
51
53
  ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
@@ -65,9 +67,9 @@ var init_exit_codes = __esm({
65
67
  // src/mcp-testing/connect/journal.ts
66
68
  import { closeSync, fchmodSync, openSync, writeSync } from "fs";
67
69
  import { performance } from "perf_hooks";
68
- function openJournal(path10, redact) {
69
- if (path10 === void 0) return NONE;
70
- const fd = openSync(path10, "w", 384);
70
+ function openJournal(path12, redact) {
71
+ if (path12 === void 0) return NONE;
72
+ const fd = openSync(path12, "w", 384);
71
73
  if (process.platform !== "win32") fchmodSync(fd, 384);
72
74
  const start = performance.now();
73
75
  let closed = false;
@@ -129,8 +131,8 @@ function processTable() {
129
131
  return readdirSync("/proc").flatMap((name) => {
130
132
  if (!/^\d+$/.test(name)) return [];
131
133
  try {
132
- const stat = readFileSync3(`/proc/${name}/stat`, "utf8");
133
- const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
134
+ const stat2 = readFileSync3(`/proc/${name}/stat`, "utf8");
135
+ const fields = stat2.slice(stat2.lastIndexOf(")") + 2).split(" ");
134
136
  return parseProcessTable(`${name} ${fields[1]} ${fields[19]}`);
135
137
  } catch {
136
138
  return [];
@@ -359,11 +361,15 @@ var init_redact = __esm({
359
361
  var session_exports = {};
360
362
  __export(session_exports, {
361
363
  ConnectError: () => ConnectError,
364
+ STDERR_LINE_LIMIT: () => STDERR_LINE_LIMIT,
362
365
  STDIO_MESSAGE_LIMIT: () => STDIO_MESSAGE_LIMIT,
363
366
  closeAllSessions: () => closeAllSessions,
364
- openSession: () => openSession
367
+ headerValue: () => headerValue,
368
+ openSession: () => openSession,
369
+ readLines: () => readLines
365
370
  });
366
371
  import { homedir as homedir2 } from "os";
372
+ import { StringDecoder } from "string_decoder";
367
373
  import { createInterface } from "readline";
368
374
  import {
369
375
  Client,
@@ -377,6 +383,26 @@ import {
377
383
  UnauthorizedError
378
384
  } from "@modelcontextprotocol/client";
379
385
  import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
386
+ function headerValue(value) {
387
+ const plain = /^[\x21-\x7e]([\x20-\x7e]*[\x21-\x7e])?$/.test(value) && !/^=\?base64\?.*\?=$/.test(value);
388
+ return plain ? value : `=?base64?${Buffer.from(value, "utf8").toString("base64")}?=`;
389
+ }
390
+ function modernHeaders(body, version) {
391
+ const m = parsed(body);
392
+ if (m === null || typeof m !== "object" || Array.isArray(m)) return [];
393
+ const { method, params } = m;
394
+ if (typeof method !== "string") return [];
395
+ const meta = params?.["_meta"];
396
+ const v = meta?.["io.modelcontextprotocol/protocolVersion"];
397
+ const headers = [
398
+ ["mcp-protocol-version", typeof v === "string" ? v : version],
399
+ ["mcp-method", method]
400
+ ];
401
+ const name = method === "resources/read" ? params?.["uri"] : params?.["name"];
402
+ if (["tools/call", "resources/read", "prompts/get"].includes(method) && typeof name === "string")
403
+ headers.push(["mcp-name", headerValue(name)]);
404
+ return headers;
405
+ }
380
406
  function answers(frame, id) {
381
407
  if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return false;
382
408
  const f = frame;
@@ -391,6 +417,40 @@ function fromEventStream(text, id) {
391
417
  }
392
418
  return void 0;
393
419
  }
420
+ function readLines(stream, onLine, stats) {
421
+ const decoder = new StringDecoder("utf8");
422
+ let partial = "";
423
+ const feed = (text) => {
424
+ let from = 0;
425
+ for (let nl = text.indexOf("\n", from); nl >= 0; nl = text.indexOf("\n", from)) {
426
+ const whole = partial + text.slice(from, nl);
427
+ if (stats !== void 0 && whole.length > stats.high) stats.high = whole.length;
428
+ const line = whole.slice(0, STDERR_LINE_LIMIT);
429
+ partial = "";
430
+ onLine(line.endsWith("\r") ? line.slice(0, -1) : line);
431
+ from = nl + 1;
432
+ }
433
+ const rest = partial + text.slice(from);
434
+ if (stats !== void 0 && rest.length > stats.high) stats.high = rest.length;
435
+ partial = rest.slice(0, STDERR_LINE_LIMIT);
436
+ };
437
+ return new Promise((resolve9) => {
438
+ let done = false;
439
+ const finish = () => {
440
+ if (done) return;
441
+ done = true;
442
+ feed(decoder.end());
443
+ if (partial !== "") onLine(partial.endsWith("\r") ? partial.slice(0, -1) : partial);
444
+ resolve9();
445
+ };
446
+ stream.on(
447
+ "data",
448
+ (chunk2) => feed(typeof chunk2 === "string" ? chunk2 : decoder.write(chunk2))
449
+ );
450
+ stream.once("end", finish);
451
+ stream.once("close", finish);
452
+ });
453
+ }
394
454
  function createTransport(target) {
395
455
  if (target.kind === "stdio") {
396
456
  return new StdioClientTransport({
@@ -456,9 +516,9 @@ function watchOverflow(transport, over) {
456
516
  const buffer = transport._readBuffer;
457
517
  const append = buffer?.append?.bind(buffer);
458
518
  if (buffer === void 0 || append === void 0) return;
459
- buffer.append = (chunk) => {
519
+ buffer.append = (chunk2) => {
460
520
  try {
461
- append(chunk);
521
+ append(chunk2);
462
522
  } catch (err) {
463
523
  over();
464
524
  throw err;
@@ -488,7 +548,7 @@ function kindOf(err, stdio, transportClosed) {
488
548
  return "network";
489
549
  return "protocol";
490
550
  }
491
- async function openSession(config) {
551
+ async function openSession(config, options = {}) {
492
552
  const { target } = config;
493
553
  const stdio = target.kind === "stdio";
494
554
  const redact = redactorFor(target);
@@ -498,10 +558,12 @@ async function openSession(config) {
498
558
  const transport = createTransport(target);
499
559
  let transportClosed = false;
500
560
  let spawnError;
561
+ const stopped = /* @__PURE__ */ new Set();
501
562
  const handshake = {
502
563
  offered: void 0,
503
564
  result: void 0
504
565
  };
566
+ const notifications = /* @__PURE__ */ new Map();
505
567
  tap(transport, journal, {
506
568
  frame: (dir, message) => {
507
569
  const m = message;
@@ -510,11 +572,18 @@ async function openSession(config) {
510
572
  handshake.offered = m.params?.protocolVersion;
511
573
  } else if (dir === "in" && handshake.id !== void 0 && m.id === handshake.id)
512
574
  handshake.result = m.result;
575
+ if (dir === "in" && m.id === void 0 && typeof m.method === "string")
576
+ notifications.set(m.method, (notifications.get(m.method) ?? 0) + 1);
577
+ },
578
+ closed: () => {
579
+ transportClosed = true;
580
+ for (const stop of [...stopped]) stop();
513
581
  },
514
- closed: () => transportClosed = true,
515
582
  error: (err) => {
516
- if (spawnError === void 0 && err.syscall?.startsWith("spawn") === true)
583
+ if (spawnError === void 0 && err.syscall?.startsWith("spawn") === true) {
517
584
  spawnError = err;
585
+ for (const stop of [...stopped]) stop();
586
+ }
518
587
  }
519
588
  });
520
589
  let noted;
@@ -526,23 +595,30 @@ async function openSession(config) {
526
595
  let tooLarge = false;
527
596
  const tail = [];
528
597
  const noise = { count: 0, first: [] };
598
+ const traffic = [];
599
+ const methods = /* @__PURE__ */ new Map();
600
+ const heard = (frame) => {
601
+ if (frame === null || typeof frame !== "object" || Array.isArray(frame)) return;
602
+ const f = frame;
603
+ const method = "method" in f || f["id"] === void 0 ? void 0 : methods.get(f["id"]);
604
+ traffic.push(method === void 0 ? { frame: f } : { frame: f, method });
605
+ };
529
606
  const listeners = /* @__PURE__ */ new Set();
530
607
  const seen = (line, isMessage) => {
531
608
  if (!isMessage) {
532
609
  noise.count++;
533
610
  if (noise.first.length < 3) noise.first.push(clean(line).slice(0, 200));
534
611
  }
612
+ if (isMessage) heard(parsed(line));
535
613
  for (const listener of [...listeners]) listener(line);
536
614
  };
537
615
  let stderrDone = Promise.resolve();
538
616
  if (transport instanceof StdioClientTransport && transport.stderr !== null) {
539
- const lines = createInterface({ input: transport.stderr, crlfDelay: Infinity });
540
- lines.on("line", (line) => {
617
+ stderrDone = readLines(transport.stderr, (line) => {
541
618
  journal.write("stderr", { line });
542
619
  tail.push(clean(line));
543
620
  if (tail.length > TAIL_LINES) tail.shift();
544
621
  });
545
- stderrDone = new Promise((resolve8) => lines.once("close", resolve8));
546
622
  watchStdout(transport, journal, seen);
547
623
  watchOverflow(transport, () => {
548
624
  if (tooLarge) return;
@@ -582,10 +658,19 @@ async function openSession(config) {
582
658
  };
583
659
  const untrack = track(closable);
584
660
  const client = new Client({ name: "plune", version: config.clientVersion ?? "0.0.0" });
661
+ const modern = options.modern;
662
+ if (modern !== void 0) {
663
+ transport.onmessage = () => {
664
+ };
665
+ transport.onerror = () => {
666
+ };
667
+ transport.onclose = () => {
668
+ };
669
+ }
585
670
  let timer;
586
671
  try {
587
672
  await Promise.race([
588
- client.connect(transport, { timeout: config.timeoutMs }),
673
+ modern === void 0 ? client.connect(transport, { timeout: config.timeoutMs }) : transport.start(),
589
674
  new Promise((_, reject) => {
590
675
  timer = setTimeout(
591
676
  () => reject(new SdkError(SdkErrorCode.RequestTimeout, "no answer")),
@@ -612,12 +697,12 @@ async function openSession(config) {
612
697
  server: info === void 0 ? void 0 : { name: String(info.name), version: String(info.version) },
613
698
  handshake: { offered: handshake.offered, result: handshake.result },
614
699
  stderrTail: () => [...tail],
615
- async request(method, params, options) {
700
+ async request(method, params, options2) {
616
701
  try {
617
702
  return await client.request(
618
703
  params === void 0 ? { method } : { method, params },
619
704
  AS_SENT,
620
- { timeout: options?.timeoutMs ?? config.timeoutMs }
705
+ { timeout: options2?.timeoutMs ?? config.timeoutMs }
621
706
  );
622
707
  } catch (err) {
623
708
  if (err instanceof ProtocolError)
@@ -627,7 +712,7 @@ async function openSession(config) {
627
712
  },
628
713
  fetchForOrigin(origin) {
629
714
  const allowed = new URL(origin).origin;
630
- const own = target.kind !== "stdio" && new URL(target.url).origin === allowed;
715
+ const own2 = target.kind !== "stdio" && new URL(target.url).origin === allowed;
631
716
  return async (input, init) => {
632
717
  const url = new URL(input);
633
718
  if (url.origin !== allowed)
@@ -635,36 +720,47 @@ async function openSession(config) {
635
720
  `fetchForOrigin(${allowed}) refuses a request to another origin, ${url.origin}.`
636
721
  );
637
722
  const headers = new Headers(init?.headers);
638
- if (own) {
723
+ if (own2) {
639
724
  for (const [name, value] of Object.entries(target.headers))
640
725
  if (!headers.has(name)) headers.set(name, value);
641
726
  }
642
727
  return fetch(url, { ...init, headers, redirect: "manual" });
643
728
  };
644
729
  },
645
- async raw(body, id, options) {
646
- const ms = options?.timeoutMs ?? config.timeoutMs;
730
+ async raw(body, id, options2) {
731
+ const ms = options2?.timeoutMs ?? config.timeoutMs;
647
732
  if (target.kind === "sse")
648
733
  throw new ConnectError("protocol", "Messages of its own go over stdio and Streamable HTTP only, not HTTP+SSE.", []);
649
734
  journal.write("out", { raw: body });
650
735
  const noAnswer = () => new ConnectError("timeout", `${LEAD.timeout[0]}.`, [...tail]);
736
+ const sent = parsed(body);
737
+ if (typeof sent?.method === "string" && sent.id !== void 0) methods.set(sent.id, sent.method);
651
738
  if (target.kind === "stdio") {
652
739
  const stdin = transport._process?.stdin;
653
740
  if (stdin === null || stdin === void 0 || stdin.writableEnded)
654
- throw new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
655
- return new Promise((resolve8, reject) => {
656
- const timer2 = setTimeout(() => {
741
+ throw spawnError !== void 0 ? await toConnectError(spawnError) : new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
742
+ return new Promise((resolve9, reject) => {
743
+ const done = () => {
744
+ clearTimeout(timer2);
657
745
  listeners.delete(listener);
746
+ stopped.delete(stop);
747
+ };
748
+ const timer2 = setTimeout(() => {
749
+ done();
658
750
  reject(noAnswer());
659
751
  }, ms);
660
752
  const listener = (line) => {
661
753
  const frame2 = parsed(line);
662
754
  if (!answers(frame2, id)) return;
663
- clearTimeout(timer2);
664
- listeners.delete(listener);
665
- resolve8({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
755
+ done();
756
+ resolve9({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
757
+ };
758
+ const stop = () => {
759
+ done();
760
+ void toConnectError(spawnError ?? new Error("closed")).then(reject);
666
761
  };
667
762
  listeners.add(listener);
763
+ stopped.add(stop);
668
764
  stdin.write(`${body}
669
765
  `);
670
766
  });
@@ -675,6 +771,11 @@ async function openSession(config) {
675
771
  headers.set("accept", "application/json, text/event-stream");
676
772
  if (state.sessionId !== void 0) headers.set("mcp-session-id", state.sessionId);
677
773
  if (state._protocolVersion !== void 0) headers.set("mcp-protocol-version", state._protocolVersion);
774
+ if (modern !== void 0) for (const [name, value] of modernHeaders(body, modern.version)) headers.set(name, value);
775
+ for (const [name, value] of options2?.headers ?? []) {
776
+ if (value === null) headers.delete(name);
777
+ else headers.set(name, value);
778
+ }
678
779
  const lost = async (err) => err?.name === "TimeoutError" ? noAnswer() : toConnectError(err);
679
780
  let text = "";
680
781
  let frame;
@@ -706,22 +807,36 @@ async function openSession(config) {
706
807
  const whole = parsed(text);
707
808
  if (whole !== null && typeof whole === "object" && !Array.isArray(whole))
708
809
  frame = whole;
709
- }
810
+ heard(frame);
811
+ } else
812
+ for (const line of text.split(/\r?\n/)) if (line.startsWith("data:")) heard(parsed(line.slice(5).trim()));
710
813
  } catch (err) {
711
814
  throw await lost(err);
712
815
  }
713
- journal.write("in", frame !== void 0 ? { frame } : { status, raw: text.slice(0, RAW_TEXT) });
816
+ journal.write("in", frame !== void 0 ? { frame } : { status, raw: clean(text).slice(0, RAW_TEXT) });
714
817
  return { frame, status, text: clean(text).slice(0, RAW_TEXT) };
715
818
  },
819
+ async notify(body) {
820
+ if (target.kind !== "stdio")
821
+ throw new ConnectError("protocol", "notify is for a stdio server.", []);
822
+ const stdin = transport._process?.stdin;
823
+ if (stdin === null || stdin === void 0 || stdin.writableEnded)
824
+ throw spawnError !== void 0 ? await toConnectError(spawnError) : new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
825
+ journal.write("out", { raw: body });
826
+ stdin.write(`${body}
827
+ `);
828
+ },
829
+ traffic: () => traffic,
716
830
  stdoutNoise: () => ({ count: noise.count, first: [...noise.first] }),
831
+ notified: (method) => notifications.get(method) ?? 0,
717
832
  async endInput(waitMs) {
718
833
  const proc = transport._process;
719
834
  if (proc === void 0) return true;
720
835
  if (proc.exitCode !== null || proc.signalCode !== null) return true;
721
- const exited = new Promise((resolve8) => proc.once("exit", () => resolve8(true)));
836
+ const exited = new Promise((resolve9) => proc.once("exit", () => resolve9(true)));
722
837
  proc.stdin?.end();
723
838
  let timer2;
724
- const late = new Promise((resolve8) => timer2 = setTimeout(() => resolve8(false), waitMs));
839
+ const late = new Promise((resolve9) => timer2 = setTimeout(() => resolve9(false), waitMs));
725
840
  const result = await Promise.race([exited, late]);
726
841
  clearTimeout(timer2);
727
842
  return result;
@@ -729,7 +844,7 @@ async function openSession(config) {
729
844
  close: closable.close
730
845
  };
731
846
  }
732
- var ConnectError, RAW_TEXT, parsed, TAIL_LINES, STDIO_MESSAGE_LIMIT, AS_SENT, firstLine, LEAD;
847
+ var ConnectError, RAW_TEXT, parsed, TAIL_LINES, STDERR_LINE_LIMIT, STDIO_MESSAGE_LIMIT, AS_SENT, firstLine, LEAD;
733
848
  var init_session = __esm({
734
849
  "src/mcp-testing/connect/session.ts"() {
735
850
  "use strict";
@@ -760,6 +875,7 @@ var init_session = __esm({
760
875
  }
761
876
  };
762
877
  TAIL_LINES = 20;
878
+ STDERR_LINE_LIMIT = 64 * 1024;
763
879
  STDIO_MESSAGE_LIMIT = 10 * 1024 * 1024;
764
880
  AS_SENT = {
765
881
  "~standard": { version: 1, vendor: "plune", validate: (value) => ({ value }) }
@@ -840,10 +956,10 @@ async function listAll(session, method, key, opts = {}) {
840
956
  cursor === void 0 ? void 0 : { cursor },
841
957
  opts.timeoutMs === void 0 ? {} : { timeoutMs: opts.timeoutMs }
842
958
  );
843
- const listed = isRecord3(page) ? page[key] : void 0;
959
+ const listed = isRecord5(page) ? page[key] : void 0;
844
960
  if (Array.isArray(listed)) for (const item of listed) items.push(item);
845
961
  else malformed = true;
846
- cursor = isRecord3(page) && typeof page.nextCursor === "string" && page.nextCursor !== "" ? page.nextCursor : void 0;
962
+ cursor = isRecord5(page) && typeof page.nextCursor === "string" && page.nextCursor !== "" ? page.nextCursor : void 0;
847
963
  if (cursor === void 0) return { items, pages, complete: true, malformed };
848
964
  }
849
965
  return { items, pages: MAX_PAGES, complete: false, malformed };
@@ -852,12 +968,12 @@ function asTools(items) {
852
968
  const tools = [];
853
969
  const unnamed = /* @__PURE__ */ new Map();
854
970
  for (const t of items) {
855
- const name = isRecord3(t) ? t.name : void 0;
971
+ const name = isRecord5(t) ? t.name : void 0;
856
972
  if (typeof name === "string" && name !== "") {
857
973
  tools.push(t);
858
974
  continue;
859
975
  }
860
- const tool = { ...isRecord3(t) ? t : {}, name: "" };
976
+ const tool = { ...isRecord5(t) ? t : {}, name: "" };
861
977
  unnamed.set(tool, name === void 0 ? "(no name)" : String(JSON.stringify(name)));
862
978
  tools.push(tool);
863
979
  }
@@ -875,9 +991,9 @@ function callableTools(tools, unnamed, opts = {}) {
875
991
  refused.push({ tool: t.name, reason: "duplicate-name" });
876
992
  else candidates.push(t);
877
993
  }
878
- const { safe, skipped } = selectSafeTools(candidates, opts);
994
+ const { safe: safe2, skipped } = selectSafeTools(candidates, opts);
879
995
  return {
880
- safe,
996
+ safe: safe2,
881
997
  skipped: [...refused, ...skipped.map((s) => ({ tool: s.tool.name, reason: s.reason }))]
882
998
  };
883
999
  }
@@ -894,7 +1010,7 @@ async function callTool(session, name, timeoutMs, args = {}) {
894
1010
  throw err;
895
1011
  }
896
1012
  }
897
- var MAX_PAGES, isRecord3;
1013
+ var MAX_PAGES, isRecord5;
898
1014
  var init_tools = __esm({
899
1015
  "src/mcp-testing/connect/tools.ts"() {
900
1016
  "use strict";
@@ -902,7 +1018,7 @@ var init_tools = __esm({
902
1018
  init_safe_tools();
903
1019
  init_session();
904
1020
  MAX_PAGES = 100;
905
- isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1021
+ isRecord5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
906
1022
  }
907
1023
  });
908
1024
 
@@ -921,24 +1037,6 @@ import { parse } from "yaml";
921
1037
 
922
1038
  // src/config/env-overrides.ts
923
1039
  init_esm_shims();
924
- function applyEnvOverrides(config, env) {
925
- const result = structuredClone(config);
926
- if (env["PLUNE_PROVIDER"] !== void 0) {
927
- result.provider.type = env["PLUNE_PROVIDER"];
928
- }
929
- if (env["PLUNE_MODEL"] !== void 0) {
930
- result.provider.model = env["PLUNE_MODEL"];
931
- }
932
- if (env["PLUNE_TIMEOUT"] !== void 0) {
933
- const n = Number(env["PLUNE_TIMEOUT"]);
934
- if (!isNaN(n)) result.provider.timeout = n;
935
- }
936
- if (env["PLUNE_MAX_RETRIES"] !== void 0) {
937
- const n = Number(env["PLUNE_MAX_RETRIES"]);
938
- if (!isNaN(n)) result.provider.max_retries = n;
939
- }
940
- return result;
941
- }
942
1040
 
943
1041
  // src/config/errors.ts
944
1042
  init_esm_shims();
@@ -966,6 +1064,34 @@ var ConfigValidationError = class extends Error {
966
1064
  }
967
1065
  };
968
1066
 
1067
+ // src/config/env-overrides.ts
1068
+ function applyEnvOverrides(config, env) {
1069
+ const result = structuredClone(config);
1070
+ const all = result.providers ?? [result.provider];
1071
+ if (result.providers !== void 0) {
1072
+ for (const name of ["PLUNE_PROVIDER", "PLUNE_MODEL"])
1073
+ if (env[name] !== void 0)
1074
+ throw new ConfigValidationError("Config validation failed", [
1075
+ `${name} sets one model, but the config lists ${result.providers.length}: remove it or list a single model`
1076
+ ]);
1077
+ }
1078
+ if (env["PLUNE_PROVIDER"] !== void 0) {
1079
+ result.provider.type = env["PLUNE_PROVIDER"];
1080
+ }
1081
+ if (env["PLUNE_MODEL"] !== void 0) {
1082
+ result.provider.model = env["PLUNE_MODEL"];
1083
+ }
1084
+ if (env["PLUNE_TIMEOUT"] !== void 0) {
1085
+ const n = Number(env["PLUNE_TIMEOUT"]);
1086
+ if (!isNaN(n)) for (const p of all) p.timeout = n;
1087
+ }
1088
+ if (env["PLUNE_MAX_RETRIES"] !== void 0) {
1089
+ const n = Number(env["PLUNE_MAX_RETRIES"]);
1090
+ if (!isNaN(n)) for (const p of all) p.max_retries = n;
1091
+ }
1092
+ return result;
1093
+ }
1094
+
969
1095
  // src/config/discover.ts
970
1096
  init_esm_shims();
971
1097
  import * as fs from "fs";
@@ -1104,6 +1230,13 @@ var providerConfigSchema = z.object({
1104
1230
  // The values the OpenAI SDK's Chat Completions `reasoning_effort` accepts; only `openai` sends it.
1105
1231
  reasoning_effort: z.enum(["none", "minimal", "low", "medium", "high", "xhigh"]).optional()
1106
1232
  });
1233
+ var providerListSchema = z.array(providerConfigSchema).min(1);
1234
+ var providerField = z.any().transform((value, ctx) => {
1235
+ const r = (Array.isArray(value) ? providerListSchema : providerConfigSchema).safeParse(value);
1236
+ if (r.success) return r.data;
1237
+ for (const issue of r.error.issues) ctx.addIssue({ code: "custom", message: issue.message, path: issue.path });
1238
+ return z.NEVER;
1239
+ });
1107
1240
  var modelPriceSchema = z.object({
1108
1241
  input_per_1k_usd: z.number().nonnegative(),
1109
1242
  output_per_1k_usd: z.number().nonnegative()
@@ -1293,7 +1426,8 @@ var evalConfigSchema = z.object({
1293
1426
  );
1294
1427
  var pluneConfigSchema = z.object({
1295
1428
  version: z.literal(1),
1296
- provider: providerConfigSchema,
1429
+ // One object, or a non-empty list of models to run every eval against (a one-element list is the object).
1430
+ provider: providerField,
1297
1431
  defaults: z.object({ assertions: z.array(assertionConfigSchema).optional() }).optional(),
1298
1432
  pricing: pricingSchema.optional(),
1299
1433
  ...evalRepeatsShape,
@@ -1301,14 +1435,42 @@ var pluneConfigSchema = z.object({
1301
1435
  mcp: mcpRootSchema.optional(),
1302
1436
  evals: z.array(evalConfigSchema).min(1)
1303
1437
  }).strict().superRefine((config, ctx) => {
1438
+ if (Array.isArray(config.provider)) {
1439
+ const pairs = /* @__PURE__ */ new Set();
1440
+ const byModel = /* @__PURE__ */ new Map();
1441
+ config.provider.forEach((p, i) => {
1442
+ const pair = `${p.type}/${p.model}`;
1443
+ if (pairs.has(pair))
1444
+ ctx.addIssue({ code: "custom", path: ["provider", i], message: `provider "${pair}" is listed twice` });
1445
+ pairs.add(pair);
1446
+ const other = byModel.get(p.model);
1447
+ if (other !== void 0 && other !== p.type)
1448
+ ctx.addIssue({
1449
+ code: "custom",
1450
+ path: ["provider", i, "model"],
1451
+ message: `model "${p.model}" is listed under ${other} and ${p.type}: cell ids are built from the model name`
1452
+ });
1453
+ byModel.set(p.model, p.type);
1454
+ });
1455
+ if (config.provider.length > 1)
1456
+ config.evals.forEach((ev, i) => {
1457
+ for (const key of ["type", "model"])
1458
+ if (ev.provider?.[key] !== void 0)
1459
+ ctx.addIssue({
1460
+ code: "custom",
1461
+ path: ["evals", i, "provider", key],
1462
+ message: `eval "${ev.id}" sets provider.${key}, but the root provider lists several models: the models come from the root list`
1463
+ });
1464
+ });
1465
+ }
1304
1466
  config.evals.forEach((evalConfig, i) => {
1305
1467
  const server = evalConfig.mcp?.server;
1306
1468
  if (server === void 0) {
1307
- const misplaced = (assertions, path10) => assertions.forEach((a, j) => {
1469
+ const misplaced = (assertions, path12) => assertions.forEach((a, j) => {
1308
1470
  if (TOOL_CALL_TYPES.has(a.type))
1309
1471
  ctx.addIssue({
1310
1472
  code: "custom",
1311
- path: [...path10, j, "type"],
1473
+ path: [...path12, j, "type"],
1312
1474
  message: `"${a.type}" reads the tool calls of an eval with mcp, and eval "${evalConfig.id}" has no mcp block`
1313
1475
  });
1314
1476
  });
@@ -1323,6 +1485,10 @@ var pluneConfigSchema = z.object({
1323
1485
  message: `eval "${evalConfig.id}" uses MCP server "${server}", which mcp.servers does not define`
1324
1486
  });
1325
1487
  });
1488
+ }).transform(({ provider, ...rest }) => {
1489
+ if (!Array.isArray(provider)) return { provider, ...rest };
1490
+ const [first, ...others] = provider;
1491
+ return others.length === 0 ? { provider: first, ...rest } : { provider: first, providers: provider, ...rest };
1326
1492
  });
1327
1493
 
1328
1494
  // src/config/loader.ts
@@ -1360,6 +1526,16 @@ async function loadConfig(opts = {}) {
1360
1526
  return applyEnvOverrides(config, env);
1361
1527
  }
1362
1528
 
1529
+ // src/config/model-matrix.ts
1530
+ init_esm_shims();
1531
+ function selfJudgeWarnings(config) {
1532
+ if ((config.providers?.length ?? 0) < 2) return [];
1533
+ const inherited = (config.defaults?.assertions ?? []).some((a) => a.type === "llm-judge" && a.provider === void 0);
1534
+ return config.evals.filter((ev) => inherited || ev.assertions.some((a) => a.type === "llm-judge" && a.provider === void 0)).map(
1535
+ (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`
1536
+ );
1537
+ }
1538
+
1363
1539
  // src/providers/index.ts
1364
1540
  init_esm_shims();
1365
1541
 
@@ -1463,7 +1639,7 @@ function normalizeProviderError(err, secret, envVar) {
1463
1639
  }
1464
1640
 
1465
1641
  // src/providers/retry.ts
1466
- var defaultSleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
1642
+ var defaultSleep = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
1467
1643
  function retryAfterMs(err) {
1468
1644
  if (typeof err !== "object" || err === null || !("headers" in err)) return void 0;
1469
1645
  const raw = readHeader(err.headers, "retry-after");
@@ -1485,7 +1661,7 @@ function readHeader(headers, name) {
1485
1661
  return typeof v === "string" || typeof v === "number" ? v : void 0;
1486
1662
  }
1487
1663
  async function withRetry(fn, options) {
1488
- const { base_delay_ms = 500, sleep = defaultSleep, random = Math.random } = options;
1664
+ const { base_delay_ms = 500, sleep: sleep2 = defaultSleep, random = Math.random } = options;
1489
1665
  const maxRetries = Math.max(0, Math.floor(options.max_retries));
1490
1666
  let attempt = 0;
1491
1667
  for (; ; ) {
@@ -1501,7 +1677,7 @@ async function withRetry(fn, options) {
1501
1677
  const backoff = base_delay_ms * 2 ** attempt;
1502
1678
  const jitter = backoff * 0.1 * random();
1503
1679
  const delay = Math.max(backoff + jitter, retryAfterMs(err) ?? 0);
1504
- await sleep(delay);
1680
+ await sleep2(delay);
1505
1681
  attempt += 1;
1506
1682
  }
1507
1683
  }
@@ -1917,6 +2093,13 @@ function makeEstimateProvider(config, pricing) {
1917
2093
 
1918
2094
  // src/providers/mock.ts
1919
2095
  init_esm_shims();
2096
+ function picked(pick, tools) {
2097
+ const words = pick.toLowerCase().split(/\s+/).filter(Boolean);
2098
+ const hits = tools.filter(
2099
+ (t) => words.every((w) => (t.description ?? "").toLowerCase().includes(w))
2100
+ );
2101
+ return hits.length === 1 ? hits[0].name : void 0;
2102
+ }
1920
2103
  var USAGE = { input_tokens: 10, output_tokens: 5 };
1921
2104
  function parseMockScript(text) {
1922
2105
  let parsed2;
@@ -1931,7 +2114,7 @@ function parseMockScript(text) {
1931
2114
  if (t !== void 0 && typeof t !== "string") return false;
1932
2115
  if (calls === void 0) return true;
1933
2116
  return Array.isArray(calls) && calls.every(
1934
- (c) => typeof c === "object" && c !== null && typeof c.name === "string"
2117
+ (c) => typeof c === "object" && c !== null && (typeof c.name === "string" || typeof c.pick === "string")
1935
2118
  );
1936
2119
  };
1937
2120
  if (!Array.isArray(parsed2) || parsed2.length === 0 || !parsed2.every(isStep))
@@ -1950,14 +2133,13 @@ function makeMockProvider(script) {
1950
2133
  respond: (req) => {
1951
2134
  const step = req.messages.filter((m) => m.role === "assistant").length;
1952
2135
  const entry = script[Math.min(step, script.length - 1)];
1953
- const calls = entry.tool_calls ?? [];
2136
+ const calls = (entry.tool_calls ?? []).flatMap((c) => {
2137
+ const name = "name" in c ? c.name : picked(c.pick, req.tools);
2138
+ return name === void 0 ? [] : [{ name, args: c.args ?? {} }];
2139
+ });
1954
2140
  return Promise.resolve({
1955
2141
  text: entry.text ?? "",
1956
- tool_calls: calls.map((c, i) => ({
1957
- id: `call_${step}_${i}`,
1958
- name: c.name,
1959
- args: c.args ?? {}
1960
- })),
2142
+ tool_calls: calls.map((c, i) => ({ id: `call_${step}_${i}`, ...c })),
1961
2143
  usage: USAGE,
1962
2144
  finish_reason: calls.length > 0 ? "tool_calls" : "stop"
1963
2145
  });
@@ -2006,7 +2188,7 @@ var XenovaEmbedder = class {
2006
2188
  throw new Error(
2007
2189
  "The `semantic-similarity` and RAG assertions need local embeddings, which ship separately: install @huggingface/transformers to enable them. Every other assertion works without it."
2008
2190
  );
2009
- }).then(({ pipeline }) => pipeline("feature-extraction", MODEL_ID));
2191
+ }).then(({ pipeline: pipeline2 }) => pipeline2("feature-extraction", MODEL_ID));
2010
2192
  return this.extractor;
2011
2193
  }
2012
2194
  };
@@ -2319,6 +2501,14 @@ init_esm_shims();
2319
2501
  // src/assertions/interpolate.ts
2320
2502
  init_esm_shims();
2321
2503
  var PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/g;
2504
+ var EXPECTED = /\{\{\s*expected\s*\}\}/;
2505
+ function usesExpected(params) {
2506
+ if (typeof params === "string") return EXPECTED.test(params);
2507
+ if (Array.isArray(params)) return params.some(usesExpected);
2508
+ if (params !== null && typeof params === "object")
2509
+ return Object.values(params).some(usesExpected);
2510
+ return false;
2511
+ }
2322
2512
  function interpolate(template, ctx) {
2323
2513
  return template.replace(PLACEHOLDER, (match, key) => {
2324
2514
  if (key === "expected") {
@@ -2662,10 +2852,10 @@ function checkNames(type, t, names) {
2662
2852
  const offered = t.tools.filter((x) => x.offered).map((x) => x.name);
2663
2853
  const unknown = names.find((n) => n !== void 0 && !offered.includes(n));
2664
2854
  if (unknown === void 0) return;
2665
- const list = offered.length > 0 ? offered.join(", ") : "(none)";
2855
+ const list2 = offered.length > 0 ? offered.join(", ") : "(none)";
2666
2856
  throw new AssertionRunError(
2667
2857
  "ASSERTION_UNKNOWN_TOOL",
2668
- `${type}: no tool "${unknown}" was offered to the model; offered: ${list}.${AFTER}`
2858
+ `${type}: no tool "${unknown}" was offered to the model; offered: ${list2}.${AFTER}`
2669
2859
  );
2670
2860
  }
2671
2861
  function absence(type, t, what, reads) {
@@ -2760,6 +2950,38 @@ var onlyTools = check((ctx) => {
2760
2950
 
2761
2951
  // src/assertions/tool-calls/order.ts
2762
2952
  init_esm_shims();
2953
+
2954
+ // src/util/tool-calls.ts
2955
+ init_esm_shims();
2956
+ var PAGINATION_KEYS = [
2957
+ "cursor",
2958
+ "page",
2959
+ "offset",
2960
+ "limit",
2961
+ "after",
2962
+ "before",
2963
+ "start",
2964
+ "pageToken",
2965
+ "page_token",
2966
+ "nextCursor",
2967
+ "next_cursor"
2968
+ ];
2969
+ var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2970
+ function sameValue(a, b) {
2971
+ return a !== void 0 && b !== void 0 && canonicalJson(a) === canonicalJson(b);
2972
+ }
2973
+ function withoutPagination(args) {
2974
+ if (!isRecord2(args)) return args;
2975
+ return Object.fromEntries(Object.entries(args).filter(([k]) => !PAGINATION_KEYS.includes(k)));
2976
+ }
2977
+ function isIdenticalCall(a, b) {
2978
+ return a.name === b.name && sameValue(a.args, b.args);
2979
+ }
2980
+ function isPageTurn(a, b) {
2981
+ return a.name === b.name && !isIdenticalCall(a, b) && sameValue(withoutPagination(a.args), withoutPagination(b.args));
2982
+ }
2983
+
2984
+ // src/assertions/tool-calls/order.ts
2763
2985
  function inOrder(names, tools) {
2764
2986
  let next = 0;
2765
2987
  for (const n of names) if (n === tools[next]) next++;
@@ -2797,7 +3019,7 @@ var noRepeatedCall = check((ctx) => {
2797
3019
  for (let i = 1; i < calls.length; i++) {
2798
3020
  const [prev, cur] = [calls[i - 1], calls[i]];
2799
3021
  if (tool !== void 0 && cur.call.name !== tool) continue;
2800
- if (prev.call.name === cur.call.name && sameJson(prev.call.args, cur.call.args))
3022
+ if (isIdenticalCall(prev.call, cur.call))
2801
3023
  return fail(
2802
3024
  `expected no call repeated right after itself; got ${describeCall(prev)} then ${describeCall(cur)}; check whether the first answer told the model what it needed`
2803
3025
  );
@@ -3129,9 +3351,9 @@ var testCaseBaseSchema = z2.object({
3129
3351
  schemaVersion: z2.literal(TEST_CASE_SCHEMA_VERSION),
3130
3352
  id: z2.string().min(1),
3131
3353
  externalKeys: z2.array(externalKeySchema).optional(),
3132
- /** ADR 0045 / plune#1246 — optional, purely additive; schemaVersion stays 2. */
3354
+ /** Optional, purely additive; schemaVersion stays 2. */
3133
3355
  is_flaky: z2.boolean().optional(),
3134
- /** ADR 0045 / plune#1246 — optional, purely additive; schemaVersion stays 2. */
3356
+ /** Optional, purely additive; schemaVersion stays 2. */
3135
3357
  is_muted: z2.boolean().optional()
3136
3358
  });
3137
3359
  var testCaseSchema = z2.discriminatedUnion("type", [
@@ -3177,6 +3399,159 @@ function wireNames(names) {
3177
3399
  return { toWire, toServer };
3178
3400
  }
3179
3401
 
3402
+ // src/orchestrator/friction.ts
3403
+ init_esm_shims();
3404
+ var SCAN_DEPTH = 6;
3405
+ var SCAN_ITEMS = 50;
3406
+ var MAX_PATHS = 10;
3407
+ var MAX_PATH = 120;
3408
+ var MIN_VALUE = 6;
3409
+ var WORDS = "id|ids|key|uuid|slug|number|ref|identifier";
3410
+ var WHOLE = new RegExp(`^(?:${WORDS})$`, "i");
3411
+ var SNAKE = new RegExp(`_(?:${WORDS})$`, "i");
3412
+ var CAMEL = /[a-z0-9](?:Id|Ids|Uuid|Key|Slug|Number|Ref|Identifier)$/;
3413
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3414
+ var isIdKey = (key) => WHOLE.test(key) || SNAKE.test(key) || CAMEL.test(key);
3415
+ var isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3416
+ var isScalar = (v) => typeof v === "string" && v !== "" || typeof v === "number" && Number.isFinite(v);
3417
+ var EMAIL = /@/;
3418
+ function segment(key) {
3419
+ const plain = /^[A-Za-z_][\w-]*$/.test(key) && key.length <= 40 && !UUID.test(key) && !EMAIL.test(key);
3420
+ return plain ? key : "*";
3421
+ }
3422
+ var cap = (path12) => path12.length > MAX_PATH ? path12.slice(0, MAX_PATH) : path12;
3423
+ var hashOf = (v) => sha256(v).slice(0, 16);
3424
+ function noteValue(out, v, at) {
3425
+ if (typeof v !== "string" || v.length < MIN_VALUE) return;
3426
+ const h = hashOf(v);
3427
+ const where = out.values.get(h) ?? /* @__PURE__ */ new Set();
3428
+ where.add(at);
3429
+ out.values.set(h, where);
3430
+ }
3431
+ function walk(value, path12, depth, out) {
3432
+ if (depth > SCAN_DEPTH) return;
3433
+ if (typeof value === "string" && UUID.test(value)) {
3434
+ const at = cap(path12 === "" ? "(root)" : path12);
3435
+ out.paths.add(at);
3436
+ noteValue(out, value, at);
3437
+ }
3438
+ if (Array.isArray(value)) {
3439
+ for (const item of value.slice(0, SCAN_ITEMS)) walk(item, `${path12}[]`, depth + 1, out);
3440
+ return;
3441
+ }
3442
+ if (!isRecord3(value)) return;
3443
+ for (const [key, v] of Object.entries(value)) {
3444
+ const at = cap(path12 === "" ? segment(key) : `${path12}.${segment(key)}`);
3445
+ if (isIdKey(key) && (isScalar(v) || Array.isArray(v) && v.length > 0 && v.every(isScalar))) {
3446
+ out.paths.add(at);
3447
+ for (const x of Array.isArray(v) ? v : [v]) noteValue(out, x, at);
3448
+ }
3449
+ walk(v, at, depth + 1, out);
3450
+ }
3451
+ }
3452
+ function scanIds(result) {
3453
+ const found = { paths: /* @__PURE__ */ new Set(), values: /* @__PURE__ */ new Map() };
3454
+ let readable = false;
3455
+ if (isRecord3(result)) {
3456
+ if (result.structuredContent !== void 0) {
3457
+ readable = true;
3458
+ walk(result.structuredContent, "", 0, found);
3459
+ }
3460
+ if (Array.isArray(result.content))
3461
+ for (const block of result.content) {
3462
+ if (!isRecord3(block) || block.type !== "text" || typeof block.text !== "string") continue;
3463
+ try {
3464
+ walk(JSON.parse(block.text), "", 0, found);
3465
+ readable = true;
3466
+ } catch {
3467
+ }
3468
+ }
3469
+ }
3470
+ if (!readable) return { unreadable: "the answer is not JSON" };
3471
+ return {
3472
+ paths: [...found.paths].sort().slice(0, MAX_PATHS),
3473
+ values: [...found.values].map(([hash, at]) => ({ hash, paths: [...at].sort() }))
3474
+ };
3475
+ }
3476
+ var list = (steps) => steps.join(", ");
3477
+ function frictionAdvice(calls) {
3478
+ const acc = /* @__PURE__ */ new Map();
3479
+ const add = (type, tool, steps, paths = [], note) => {
3480
+ const key = `${type}\0${tool}`;
3481
+ let a = acc.get(key);
3482
+ if (a === void 0) {
3483
+ a = { type, tool, steps: /* @__PURE__ */ new Set(), count: 0, paths: /* @__PURE__ */ new Set(), note };
3484
+ acc.set(key, a);
3485
+ }
3486
+ steps.forEach((s) => a.steps.add(s));
3487
+ paths.forEach((p) => a.paths.add(p));
3488
+ a.count++;
3489
+ };
3490
+ const sent = calls.filter((c) => c.executed);
3491
+ for (let j = 1; j < sent.length; j++) {
3492
+ const [prev, cur] = [sent[j - 1], sent[j]];
3493
+ if (isIdenticalCall(prev, cur)) add("identical-retry", cur.name, [prev.step, cur.step]);
3494
+ else if (isPageTurn(prev, cur)) add("pagination-continuation", cur.name, [prev.step, cur.step]);
3495
+ }
3496
+ for (const [j, cur] of sent.entries()) {
3497
+ if (cur.is_error) continue;
3498
+ const before = sent.slice(0, j).filter(
3499
+ (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.
3500
+ !isIdenticalCall(e, cur) && !isPageTurn(e, cur)
3501
+ );
3502
+ if (before.length === 0) continue;
3503
+ const scans = [cur, ...before].map((c) => c.ids);
3504
+ const unread = scans.some((x) => x === void 0 || "unreadable" in x);
3505
+ if (unread || cur.ids === void 0 || "unreadable" in cur.ids) {
3506
+ const named = scans.find((x) => x !== void 0 && "unreadable" in x);
3507
+ const why = named !== void 0 && "unreadable" in named ? named.unreadable : "no answer was kept";
3508
+ add("friction-unmeasured", cur.name, [...before.map((e) => e.step), cur.step], [], why);
3509
+ continue;
3510
+ }
3511
+ const mine = new Map(cur.ids.values.map((v) => [v.hash, v.paths]));
3512
+ const shared = before.filter((e) => {
3513
+ const ids = e.ids;
3514
+ return ids.values.some((v) => mine.has(v.hash));
3515
+ });
3516
+ if (shared.length === 0) continue;
3517
+ const seen = new Set(
3518
+ shared.flatMap((e) => e.ids.values.map((v) => v.hash))
3519
+ );
3520
+ const paths = [...mine].filter(([h]) => seen.has(h)).flatMap(([, p]) => p);
3521
+ add("search-after-id", cur.name, [...shared.map((e) => e.step), cur.step], paths);
3522
+ }
3523
+ return [...acc.values()].map((a) => {
3524
+ const steps = [...a.steps].sort((x, y) => x - y);
3525
+ const paths = [...a.paths].sort();
3526
+ const base = {
3527
+ type: a.type,
3528
+ tool: a.tool,
3529
+ steps,
3530
+ count: a.count,
3531
+ ...paths.length > 0 ? { paths } : {}
3532
+ };
3533
+ if (a.type === "identical-retry")
3534
+ return {
3535
+ ...base,
3536
+ 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`
3537
+ };
3538
+ if (a.type === "pagination-continuation")
3539
+ return {
3540
+ ...base,
3541
+ 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`
3542
+ };
3543
+ if (a.type === "search-after-id")
3544
+ return {
3545
+ ...base,
3546
+ 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`
3547
+ };
3548
+ return {
3549
+ ...base,
3550
+ 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`
3551
+ };
3552
+ });
3553
+ }
3554
+
3180
3555
  // src/orchestrator/agent.ts
3181
3556
  var EXCERPT_BYTES = 4 * 1024;
3182
3557
  var TRANSCRIPT_BYTES = 256 * 1024;
@@ -3195,14 +3570,14 @@ var AgentError = class extends Error {
3195
3570
  }
3196
3571
  code;
3197
3572
  };
3198
- var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3573
+ var isRecord4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3199
3574
  function resultText(result) {
3200
- if (!isRecord2(result)) return JSON.stringify(result) ?? "";
3575
+ if (!isRecord4(result)) return JSON.stringify(result) ?? "";
3201
3576
  const content = Array.isArray(result.content) ? result.content : [];
3202
3577
  if (content.length === 0 && result.structuredContent !== void 0)
3203
3578
  return JSON.stringify(result.structuredContent);
3204
3579
  return content.map(
3205
- (b) => isRecord2(b) && b.type === "text" && typeof b.text === "string" ? b.text : JSON.stringify(b)
3580
+ (b) => isRecord4(b) && b.type === "text" && typeof b.text === "string" ? b.text : JSON.stringify(b)
3206
3581
  ).join("\n");
3207
3582
  }
3208
3583
  function excerpts() {
@@ -3224,7 +3599,7 @@ function excerpts() {
3224
3599
  function listedTools(items) {
3225
3600
  const seen = /* @__PURE__ */ new Set();
3226
3601
  return items.filter((t) => {
3227
- if (!isRecord2(t) || typeof t.name !== "string" || t.name === "" || seen.has(t.name))
3602
+ if (!isRecord4(t) || typeof t.name !== "string" || t.name === "" || seen.has(t.name))
3228
3603
  return false;
3229
3604
  seen.add(t.name);
3230
3605
  return true;
@@ -3242,13 +3617,7 @@ async function runAgentRow(p) {
3242
3617
  input_tokens: one.input_tokens * limits.max_steps,
3243
3618
  output_tokens: one.output_tokens * limits.max_steps
3244
3619
  };
3245
- return {
3246
- vars: p.row.vars,
3247
- output: null,
3248
- cached: false,
3249
- usage: { ...est, ...costFields(p.provider.estimateCost(est)) },
3250
- assertions: []
3251
- };
3620
+ return dryRunRow(p.row.vars, { ...est, ...costFields(p.provider.estimateCost(est)) });
3252
3621
  }
3253
3622
  const respond = p.provider.respond.bind(p.provider);
3254
3623
  const deadline = t0 + limits.timeout_ms;
@@ -3274,6 +3643,9 @@ async function runAgentRow(p) {
3274
3643
  let output = "";
3275
3644
  let error;
3276
3645
  let session;
3646
+ const scanned = /* @__PURE__ */ new Map();
3647
+ const overrides = p.toolDescriptions ?? {};
3648
+ const replaced = /* @__PURE__ */ new Set();
3277
3649
  try {
3278
3650
  const opening = p.connect(p.server, limits.timeout_ms);
3279
3651
  try {
@@ -3291,7 +3663,7 @@ async function runAgentRow(p) {
3291
3663
  let names = wireNames([]);
3292
3664
  let tools = [];
3293
3665
  let offeredNames = [];
3294
- const list = async () => {
3666
+ const list2 = async () => {
3295
3667
  let listed;
3296
3668
  try {
3297
3669
  listed = listedTools(await bounded(open2.listTools(limits.tool_timeout_ms)));
@@ -3310,7 +3682,7 @@ async function runAgentRow(p) {
3310
3682
  transcript.tools.push({
3311
3683
  name: t.name,
3312
3684
  offered: isOffered,
3313
- ...isRecord2(t.annotations) ? { annotations: t.annotations } : {}
3685
+ ...isRecord4(t.annotations) ? { annotations: t.annotations } : {}
3314
3686
  });
3315
3687
  }
3316
3688
  const now = offered.map((t) => t.name);
@@ -3318,14 +3690,19 @@ async function runAgentRow(p) {
3318
3690
  const removed = offeredNames.filter((n) => !now.includes(n));
3319
3691
  offeredNames = now;
3320
3692
  names = wireNames(now);
3321
- tools = offered.map((t) => ({
3322
- name: names.toWire.get(t.name),
3323
- ...typeof t.description === "string" ? { description: t.description } : {},
3324
- input_schema: isRecord2(t.inputSchema) ? t.inputSchema : { type: "object" }
3325
- }));
3693
+ tools = offered.map((t) => {
3694
+ const swap = overrides[t.name];
3695
+ if (swap !== void 0) replaced.add(t.name);
3696
+ const description = swap ?? (typeof t.description === "string" ? t.description : void 0);
3697
+ return {
3698
+ name: names.toWire.get(t.name),
3699
+ ...description !== void 0 ? { description } : {},
3700
+ input_schema: isRecord4(t.inputSchema) ? t.inputSchema : { type: "object" }
3701
+ };
3702
+ });
3326
3703
  return added.length + removed.length > 0 ? { added, removed } : void 0;
3327
3704
  };
3328
- await list();
3705
+ await list2();
3329
3706
  const messages = [{ role: "user", content: prompt5 }];
3330
3707
  let calls = 0;
3331
3708
  let tokens = 0;
@@ -3391,7 +3768,7 @@ async function runAgentRow(p) {
3391
3768
  answer(rec, c, `Tool "${c.name}" is not available.`);
3392
3769
  continue;
3393
3770
  }
3394
- if (c.args_invalid === true || !isRecord2(c.args)) {
3771
+ if (c.args_invalid === true || !isRecord4(c.args)) {
3395
3772
  Object.assign(rec, { is_error: true, error_kind: "bad-arguments" });
3396
3773
  answer(rec, c, "The arguments are not a JSON object.");
3397
3774
  continue;
@@ -3407,9 +3784,10 @@ async function runAgentRow(p) {
3407
3784
  if (got.kind === "lost") throw new AgentError("MCP_SERVER_LOST", got.message);
3408
3785
  const text = got.kind === "error" ? got.message : resultText(got.result);
3409
3786
  if (got.kind === "error") Object.assign(rec, { is_error: true, error_kind: "protocol" });
3410
- else if (isRecord2(got.result) && got.result.isError === true)
3787
+ else if (isRecord4(got.result) && got.result.isError === true)
3411
3788
  Object.assign(rec, { is_error: true, error_kind: "content" });
3412
3789
  succeeded ||= !rec.is_error;
3790
+ if (got.kind === "result" && !rec.is_error) scanned.set(rec, scanIds(got.result));
3413
3791
  rec.result = kept.cut(text);
3414
3792
  answer(rec, c, text);
3415
3793
  }
@@ -3417,7 +3795,7 @@ async function runAgentRow(p) {
3417
3795
  { role: "assistant", text: res.text, tool_calls: res.tool_calls },
3418
3796
  { role: "tool", results }
3419
3797
  );
3420
- if (succeeded) changed = await list();
3798
+ if (succeeded) changed = await list2();
3421
3799
  }
3422
3800
  } catch (err) {
3423
3801
  if (err instanceof LimitStop) transcript.stop = { reason: "limit", limit: err.limit };
@@ -3430,8 +3808,27 @@ async function runAgentRow(p) {
3430
3808
  });
3431
3809
  }
3432
3810
  if (transcript.stop.reason !== "complete" || kept.any) transcript.collection = "partial";
3811
+ const friction = error === void 0 ? frictionAdvice(
3812
+ transcript.steps.flatMap(
3813
+ (s) => s.calls.map(
3814
+ (c) => ({
3815
+ step: s.index,
3816
+ name: c.name,
3817
+ args: c.args,
3818
+ executed: c.executed,
3819
+ is_error: c.is_error,
3820
+ ...scanned.has(c) ? { ids: scanned.get(c) } : {}
3821
+ })
3822
+ )
3823
+ )
3824
+ ) : [];
3433
3825
  const mask = session?.redact;
3434
3826
  const agent = mask?.value(transcript) ?? transcript;
3827
+ if (replaced.size > 0)
3828
+ agent.description_overrides = [...replaced].sort().map((tool) => ({
3829
+ tool,
3830
+ sha256: sha256(overrides[tool])
3831
+ }));
3435
3832
  const spent = usages.length > 0 ? { usage: sumUsage(usages) } : {};
3436
3833
  if (error !== void 0) {
3437
3834
  return {
@@ -3450,7 +3847,12 @@ async function runAgentRow(p) {
3450
3847
  output,
3451
3848
  agent
3452
3849
  );
3453
- if (advice.length > 0) agent.advice = advice;
3850
+ const covered = p.assertions.filter((x) => x.type === "no-repeated-call");
3851
+ const signals = (mask?.value(friction) ?? friction).filter(
3852
+ (f) => !(f.type === "identical-retry" && covered.some((c) => c.tool === void 0 || c.tool === f.tool))
3853
+ );
3854
+ const findings = [...advice, ...signals];
3855
+ if (findings.length > 0) agent.advice = findings;
3454
3856
  const usage = sumUsage(usages);
3455
3857
  return {
3456
3858
  vars: p.row.vars,
@@ -3507,6 +3909,9 @@ function pricedField(priced) {
3507
3909
  function costFields(c) {
3508
3910
  return { cost_usd: c.cost_usd, ...pricedField(c.priced) };
3509
3911
  }
3912
+ function dryRunRow(vars, usage) {
3913
+ return { vars, output: null, cached: false, usage, inconclusive: "skipped", assertions: [] };
3914
+ }
3510
3915
  async function assess(p, output, transcript) {
3511
3916
  let judgeCost = 0;
3512
3917
  let judgeUnpriced = false;
@@ -3519,7 +3924,10 @@ async function assess(p, output, transcript) {
3519
3924
  const advice = [];
3520
3925
  let assertionError;
3521
3926
  for (const assertion of p.assertions) {
3522
- const run = () => getAssertion(assertion.type).run({
3927
+ const run = () => usesExpected(assertion) && (p.row.expected === void 0 || p.row.expected === "") ? Promise.resolve({
3928
+ passed: false,
3929
+ reason: "the row has no expected value, and this check compares against {{expected}}"
3930
+ }) : getAssertion(assertion.type).run({
3523
3931
  output,
3524
3932
  vars: p.row.vars,
3525
3933
  row: p.row,
@@ -3559,8 +3967,7 @@ async function runRow(p) {
3559
3967
  if (p.dryRun) {
3560
3968
  const est = estimateUsage(prompt5, maxTokens);
3561
3969
  const cost = p.provider.estimateCost(est);
3562
- const usage2 = { ...est, ...costFields(cost) };
3563
- return { vars: p.row.vars, output: null, cached: false, usage: usage2, assertions: [] };
3970
+ return dryRunRow(p.row.vars, { ...est, ...costFields(cost) });
3564
3971
  }
3565
3972
  const key = cacheKey(
3566
3973
  {
@@ -3783,12 +4190,11 @@ function summarize(evals, durationMs) {
3783
4190
  }
3784
4191
  return { ...summary, cache };
3785
4192
  }
3786
- function agenticProvider(config, ev, deps, cacheStrict) {
4193
+ function agenticProvider(ev, providerConfig, deps, cacheStrict) {
3787
4194
  if (cacheStrict)
3788
4195
  throw new RunConfigError(
3789
4196
  `Eval "${ev.id}" uses MCP server "${ev.mcp.server}": its tool loop is never cached, so --cache-strict cannot answer it`
3790
4197
  );
3791
- const providerConfig = { ...config.provider, ...ev.provider };
3792
4198
  const provider = deps.resolveProvider(providerConfig);
3793
4199
  if (provider.respond === void 0)
3794
4200
  throw new RunConfigError(
@@ -3815,51 +4221,77 @@ async function runOrchestration(config, options, deps) {
3815
4221
  const started = deps.now();
3816
4222
  const dryRun = options.dryRun ?? false;
3817
4223
  const evalResults = [];
4224
+ const models = config.providers ?? [config.provider];
3818
4225
  const prepared = selectEvals(config.evals, options.only).map((ev) => {
3819
4226
  const template = resolveTemplate(ev, deps.baseDir);
3820
4227
  const rows = deps.loadDataset(ev.dataset, deps.baseDir);
3821
4228
  for (const row of rows) {
3822
4229
  resolvePrompt(template, row.vars);
3823
4230
  }
3824
- const agentic = ev.mcp === void 0 || dryRun ? void 0 : agenticProvider(config, ev, deps, cacheStrict);
3825
- return { ev, template, rows, agentic };
4231
+ const cells = models.map((model) => {
4232
+ const providerConfig = { ...model, ...ev.provider };
4233
+ const agentic = ev.mcp === void 0 || dryRun ? void 0 : agenticProvider(ev, providerConfig, deps, cacheStrict);
4234
+ return { providerConfig, agentic };
4235
+ });
4236
+ return { ev, template, rows, cells };
3826
4237
  });
3827
- for (const { ev, template, rows, agentic } of prepared) {
3828
- const providerConfig = { ...config.provider, ...ev.provider };
3829
- const provider = agentic ?? deps.resolveProvider(providerConfig);
3830
- const limit2 = options.concurrency ?? providerConfig.concurrency ?? (ev.mcp !== void 0 ? 1 : 4);
3831
- const runs = options.runs ?? ev.runs ?? config.runs ?? 1;
3832
- const passThreshold = ev.pass_threshold ?? config.pass_threshold ?? 1;
3833
- const rowResults = await mapLimit(rows, limit2, (row) => {
3834
- const params = {
3835
- template,
3836
- // `defaults.assertions` apply to every eval, ahead of its own.
3837
- assertions: [...config.defaults?.assertions ?? [], ...ev.assertions],
3838
- row,
3839
- providerConfig,
3840
- provider,
3841
- embedder: deps.embedder,
3842
- cache: deps.cache,
3843
- now: deps.now,
3844
- dryRun,
3845
- noCache,
3846
- cacheStrict,
3847
- ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {}
3848
- };
3849
- if (ev.mcp === void 0) return runRepeats(params, runs, passThreshold);
3850
- const agentParams = {
3851
- ...params,
3852
- server: ev.mcp.server,
3853
- ...ev.mcp.allowed_tools !== void 0 ? { allowedTools: ev.mcp.allowed_tools } : {},
3854
- limits: mcpLimits(config, ev),
3855
- // A dry run connects nowhere; the loop never calls this then.
3856
- connect: deps.connectMcp ?? (() => Promise.reject(new Error("no MCP connection")))
4238
+ const swapped = Object.keys(options.toolDescriptions ?? {}).length > 0;
4239
+ if (swapped && !prepared.some((x) => x.ev.mcp !== void 0))
4240
+ throw new RunConfigError(
4241
+ "--tool-description needs an eval with mcp in this run: no tool is offered otherwise"
4242
+ );
4243
+ cellLoop: for (const { ev, template, rows, cells } of prepared) {
4244
+ for (const { providerConfig, agentic } of cells) {
4245
+ const provider = agentic ?? deps.resolveProvider(providerConfig);
4246
+ const limit2 = options.concurrency ?? providerConfig.concurrency ?? (ev.mcp !== void 0 ? 1 : 4);
4247
+ const runs = options.runs ?? ev.runs ?? config.runs ?? 1;
4248
+ const passThreshold = ev.pass_threshold ?? config.pass_threshold ?? 1;
4249
+ const assertions = [...config.defaults?.assertions ?? [], ...ev.assertions];
4250
+ const rowResults = await mapLimit(rows, limit2, (row) => {
4251
+ const params = {
4252
+ template,
4253
+ assertions,
4254
+ row,
4255
+ providerConfig,
4256
+ provider,
4257
+ embedder: deps.embedder,
4258
+ cache: deps.cache,
4259
+ now: deps.now,
4260
+ dryRun,
4261
+ noCache,
4262
+ cacheStrict,
4263
+ ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {}
4264
+ };
4265
+ if (ev.mcp === void 0) return runRepeats(params, runs, passThreshold);
4266
+ const agentParams = {
4267
+ ...params,
4268
+ server: ev.mcp.server,
4269
+ ...ev.mcp.allowed_tools !== void 0 ? { allowedTools: ev.mcp.allowed_tools } : {},
4270
+ limits: mcpLimits(config, ev),
4271
+ ...options.toolDescriptions !== void 0 ? { toolDescriptions: options.toolDescriptions } : {},
4272
+ // A dry run connects nowhere; the loop never calls this then.
4273
+ connect: deps.connectMcp ?? (() => Promise.reject(new Error("no MCP connection")))
4274
+ };
4275
+ return runRepeats(agentParams, runs, passThreshold, runAgentRow);
4276
+ });
4277
+ const passed = !dryRun && rowResults.every((r) => rowStatus(r) === "passed");
4278
+ const measured = {
4279
+ runs,
4280
+ rows: rows.length,
4281
+ rows_hash: sha256(canonicalJson(rows.map((r) => canonicalJson(r.vars)).sort())),
4282
+ assertions_hash: sha256(canonicalJson(assertions)),
4283
+ model: `${providerConfig.type}/${providerConfig.model}`
3857
4284
  };
3858
- return runRepeats(agentParams, runs, passThreshold, runAgentRow);
3859
- });
3860
- const passed = rowResults.every((r) => rowStatus(r) === "passed");
3861
- evalResults.push({ id: ev.id, tags: ev.tags ?? [], rows: rowResults, passed });
3862
- if (options.bail === true && !passed) break;
4285
+ evalResults.push({
4286
+ id: models.length > 1 ? `${ev.id}@${providerConfig.model}` : ev.id,
4287
+ tags: ev.tags ?? [],
4288
+ rows: rowResults,
4289
+ passed,
4290
+ measured,
4291
+ ...models.length > 1 ? { provider: { type: providerConfig.type, model: providerConfig.model } } : {}
4292
+ });
4293
+ if (options.bail === true && !dryRun && !passed) break cellLoop;
4294
+ }
3863
4295
  }
3864
4296
  const finished = deps.now();
3865
4297
  const summary = summarize(evalResults, finished - started);
@@ -3869,6 +4301,8 @@ async function runOrchestration(config, options, deps) {
3869
4301
  started_at: new Date(started).toISOString(),
3870
4302
  finished_at: new Date(finished).toISOString(),
3871
4303
  config_hash: configHash(config),
4304
+ // The one fact every reader of the result asks: was anything measured (plune-ai/cli#244).
4305
+ ...dryRun ? { dry_run: true } : {},
3872
4306
  summary,
3873
4307
  evals: evalResults
3874
4308
  };
@@ -3881,11 +4315,19 @@ init_esm_shims();
3881
4315
  init_esm_shims();
3882
4316
  import * as fs4 from "fs";
3883
4317
  import * as path5 from "path";
3884
- function loadDataset(ref, baseDir) {
3885
- if (typeof ref !== "string") {
3886
- return ref.examples;
4318
+ function loadDataset(ref5, baseDir) {
4319
+ if (typeof ref5 !== "string") {
4320
+ return ref5.examples;
4321
+ }
4322
+ const file = path5.resolve(baseDir, ref5);
4323
+ let content;
4324
+ try {
4325
+ content = fs4.readFileSync(file, "utf8");
4326
+ } catch (err) {
4327
+ throw new RunConfigError(
4328
+ err.code === "ENOENT" ? `${ref5}: dataset file not found (looked for ${file})` : `${ref5}: cannot read the dataset file (${err.message})`
4329
+ );
3887
4330
  }
3888
- const content = fs4.readFileSync(path5.resolve(baseDir, ref), "utf8");
3889
4331
  const rows = [];
3890
4332
  content.split(/\r?\n/).forEach((line, i) => {
3891
4333
  if (line.trim().length === 0) return;
@@ -3893,13 +4335,13 @@ function loadDataset(ref, baseDir) {
3893
4335
  try {
3894
4336
  row = JSON.parse(line.trim());
3895
4337
  } catch (err) {
3896
- throw new RunConfigError(`${ref}:${i + 1}: not valid JSON (${err.message})`);
4338
+ throw new RunConfigError(`${ref5}:${i + 1}: not valid JSON (${err.message})`);
3897
4339
  }
3898
4340
  const vars = isObject2(row) ? row["vars"] : void 0;
3899
4341
  if (!isObject2(vars)) {
3900
4342
  const why = isObject2(row) && "vars" in row ? `vars: Invalid input: expected record, received ${typeName(vars)}` : 'this row has no "vars"';
3901
4343
  throw new RunConfigError(
3902
- `${ref}:${i + 1}: a dataset row must be { "vars": { ... } }; ${why}`
4344
+ `${ref5}:${i + 1}: a dataset row must be { "vars": { ... } }; ${why}`
3903
4345
  );
3904
4346
  }
3905
4347
  rows.push(row);
@@ -3922,6 +4364,41 @@ var NOOP_CACHE = { get: () => void 0, set: () => {
3922
4364
  function isMockMode(env) {
3923
4365
  return env["PLUNE_MOCK_PROVIDER"] === "1";
3924
4366
  }
4367
+ var MAX_DESCRIPTION_BYTES = 64 * 1024;
4368
+ function parseToolDescriptions(values) {
4369
+ const out = {};
4370
+ for (const v of values) {
4371
+ const eq = v.indexOf("=");
4372
+ const tool = eq < 0 ? "" : v.slice(0, eq).trim();
4373
+ let text = eq < 0 ? "" : v.slice(eq + 1);
4374
+ if (tool === "" || text === "")
4375
+ throw new RunConfigError(
4376
+ `--tool-description must be <tool>=<text> or <tool>=@<file> (got "${tool === "" ? v : tool + "="}")`
4377
+ );
4378
+ if (Object.hasOwn(out, tool))
4379
+ throw new RunConfigError(`--tool-description names "${tool}" twice`);
4380
+ if (text.startsWith("@")) {
4381
+ const file = text.slice(1);
4382
+ try {
4383
+ const full = path6.resolve(file);
4384
+ const stat2 = fs5.statSync(full);
4385
+ if (!stat2.isFile())
4386
+ throw new RunConfigError(`--tool-description ${tool}: ${file} is not a file`);
4387
+ if (stat2.size > MAX_DESCRIPTION_BYTES)
4388
+ throw new RunConfigError(`--tool-description ${tool}: ${file} is over 64 KB`);
4389
+ text = fs5.readFileSync(full, "utf8").replace(/\r?\n$/, "");
4390
+ } catch (err) {
4391
+ if (err instanceof RunConfigError) throw err;
4392
+ throw new RunConfigError(`--tool-description ${tool}: cannot read ${file}`);
4393
+ }
4394
+ if (text === "") throw new RunConfigError(`--tool-description ${tool}: ${file} is empty`);
4395
+ }
4396
+ if (Buffer.byteLength(text, "utf8") > MAX_DESCRIPTION_BYTES)
4397
+ throw new RunConfigError(`--tool-description ${tool}: the text is over 64 KB`);
4398
+ out[tool] = text;
4399
+ }
4400
+ return out;
4401
+ }
3925
4402
  function mockScript(env) {
3926
4403
  const file = env["PLUNE_MOCK_SCRIPT"];
3927
4404
  if (file === void 0 || file === "") return void 0;
@@ -3986,8 +4463,10 @@ async function handleRun(options, depsFactory) {
3986
4463
  options.configPath !== void 0 ? { configPath: options.configPath } : {}
3987
4464
  );
3988
4465
  const baseDir = options.configPath !== void 0 ? path6.dirname(path6.resolve(options.configPath)) : process.cwd();
3989
- for (const warning of mcpSecretWarnings(config)) process.stderr.write(`warning: ${warning}
4466
+ for (const warning of [...mcpSecretWarnings(config), ...selfJudgeWarnings(config)])
4467
+ process.stderr.write(`warning: ${warning}
3990
4468
  `);
4469
+ const toolDescriptions = options.toolDescription !== void 0 && options.toolDescription.length > 0 ? parseToolDescriptions(options.toolDescription) : void 0;
3991
4470
  const factory = depsFactory ?? ((c, d) => buildRealDeps(c, d, options.dryRun));
3992
4471
  const deps = factory(config, baseDir);
3993
4472
  try {
@@ -4006,10 +4485,25 @@ async function handleRun(options, depsFactory) {
4006
4485
  ...options.bail !== void 0 ? { bail: options.bail } : {},
4007
4486
  ...options.cacheStrict === true ? { cacheStrict: true } : {},
4008
4487
  ...options.cacheMaxAgeMs !== void 0 ? { cacheMaxAgeMs: options.cacheMaxAgeMs } : {},
4009
- ...options.runs !== void 0 ? { runs: options.runs } : {}
4488
+ ...options.runs !== void 0 ? { runs: options.runs } : {},
4489
+ ...toolDescriptions !== void 0 ? { toolDescriptions } : {}
4010
4490
  },
4011
4491
  deps
4012
4492
  );
4493
+ for (const tool of Object.keys(toolDescriptions ?? {})) {
4494
+ const used = result.evals.some(
4495
+ (ev) => ev.rows.some(
4496
+ (r) => (r.agent?.description_overrides ?? []).some(
4497
+ (o) => o.tool === tool
4498
+ )
4499
+ )
4500
+ );
4501
+ if (!used && !options.dryRun)
4502
+ process.stderr.write(
4503
+ `warning: --tool-description ${tool}: no row offered a tool of that name, nothing was replaced
4504
+ `
4505
+ );
4506
+ }
4013
4507
  if (options.dryRun) {
4014
4508
  const agentic = new Set(config.evals.filter((ev) => ev.mcp !== void 0).map((ev) => ev.id));
4015
4509
  if (result.evals.some((ev) => agentic.has(ev.id)))
@@ -4017,7 +4511,7 @@ async function handleRun(options, depsFactory) {
4017
4511
  "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"
4018
4512
  );
4019
4513
  }
4020
- persist(result, baseDir);
4514
+ if (result.dry_run !== true) persist(result, baseDir);
4021
4515
  return result;
4022
4516
  } finally {
4023
4517
  deps.cache.close();
@@ -4070,7 +4564,7 @@ var rowResultSchema = z3.object({
4070
4564
  error: runErrorSchema.optional(),
4071
4565
  assertions: z3.array(assertionResultRecordSchema2),
4072
4566
  cache_saved: savedSchema.optional(),
4073
- /** ADR 0045. Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
4567
+ /** Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
4074
4568
  inconclusive: z3.enum(ROW_INCONCLUSIVE).optional(),
4075
4569
  /** Repeats (`runs` above 1). Optional and additive — a RunResult without it validates unchanged. */
4076
4570
  attempts: z3.object({
@@ -4129,7 +4623,17 @@ var rowResultSchema = z3.object({
4129
4623
  }),
4130
4624
  collection: z3.enum(["complete", "partial"]),
4131
4625
  /** Heuristic findings, never a verdict. Optional and additive. */
4132
- advice: z3.array(z3.object({ type: z3.string(), reason: z3.string() })).optional()
4626
+ advice: z3.array(
4627
+ z3.object({
4628
+ type: z3.string(),
4629
+ reason: z3.string(),
4630
+ tool: z3.string().optional(),
4631
+ steps: z3.array(z3.number()).optional(),
4632
+ count: z3.number().optional(),
4633
+ paths: z3.array(z3.string()).optional()
4634
+ })
4635
+ ).optional(),
4636
+ description_overrides: z3.array(z3.object({ tool: z3.string(), sha256: z3.string() })).optional()
4133
4637
  }).optional()
4134
4638
  });
4135
4639
  var summarySchema = z3.object({
@@ -4137,7 +4641,7 @@ var summarySchema = z3.object({
4137
4641
  passed: z3.number(),
4138
4642
  failed: z3.number(),
4139
4643
  errored: z3.number(),
4140
- /** plune#1245. Optional and additive — a RunResult written before them validates unchanged. */
4644
+ /** Optional and additive — a RunResult written before them validates unchanged. */
4141
4645
  blocked: z3.number().optional(),
4142
4646
  skipped: z3.number().optional(),
4143
4647
  cost_usd: z3.number(),
@@ -4154,7 +4658,17 @@ var evalResultSchema = z3.object({
4154
4658
  id: z3.string(),
4155
4659
  tags: z3.array(z3.string()),
4156
4660
  rows: z3.array(rowResultSchema),
4157
- passed: z3.boolean()
4661
+ passed: z3.boolean(),
4662
+ /** What the eval measured, for the pass-rate gate of `plune diff`. Optional and additive. */
4663
+ measured: z3.object({
4664
+ runs: z3.number(),
4665
+ rows: z3.number(),
4666
+ rows_hash: z3.string(),
4667
+ assertions_hash: z3.string(),
4668
+ model: z3.string().optional()
4669
+ }).optional(),
4670
+ /** The type and model of a cell of a multi-model run. Optional and additive. */
4671
+ provider: z3.object({ type: z3.string(), model: z3.string() }).optional()
4158
4672
  });
4159
4673
  var runResultSchema = z3.object({
4160
4674
  schemaVersion: z3.literal(RUN_RESULT_SCHEMA_VERSION),
@@ -4162,6 +4676,8 @@ var runResultSchema = z3.object({
4162
4676
  started_at: z3.string(),
4163
4677
  finished_at: z3.string(),
4164
4678
  config_hash: z3.string(),
4679
+ /** cli#244. The result of `--dry-run`. Optional and additive — a RunResult without it validates unchanged. */
4680
+ dry_run: z3.boolean().optional(),
4165
4681
  summary: summarySchema,
4166
4682
  evals: z3.array(evalResultSchema)
4167
4683
  });
@@ -4264,7 +4780,7 @@ var JobReporter = class {
4264
4780
  }
4265
4781
  /**
4266
4782
  * The upload is in: every row is on the platform. `subjectId` is what the job works on, learnt from the upload's
4267
- * answer (the run an ingest landed in): the platform takes it while the job names none (#1279).
4783
+ * answer (the run an ingest landed in): the platform takes it while the job names none.
4268
4784
  */
4269
4785
  async uploaded(at) {
4270
4786
  if (this.id === void 0) return;
@@ -4429,96 +4945,2622 @@ function reportSyncFailure(err, write) {
4429
4945
 
4430
4946
  // src/cli/commands/ingest.ts
4431
4947
  init_esm_shims();
4432
- import * as path9 from "path";
4948
+ import { promises as disk2 } from "fs";
4949
+ import * as path11 from "path";
4433
4950
 
4434
- // src/cli/commands/cairn-artifact.ts
4951
+ // src/reporter-core/client.ts
4435
4952
  init_esm_shims();
4436
- import * as fs7 from "fs/promises";
4437
- import * as path8 from "path";
4438
- var SUPPORTED_ARTIFACT_VERSION = 1;
4439
- var INGEST_SCHEMA_VERSION = 1;
4440
- var NoCairnRunsError = class extends Error {
4441
- constructor(runsDir) {
4442
- super(`No Cairn run found under ${runsDir} \u2014 name the directory instead: plune ingest <dir>.`);
4443
- this.name = "NoCairnRunsError";
4444
- }
4445
- };
4446
- async function findLatestCairnRun(runsDir = "runs") {
4447
- const entries = await fs7.readdir(runsDir, { withFileTypes: true }).catch(() => null);
4448
- if (entries === null) throw new NoCairnRunsError(runsDir);
4449
- let newest;
4450
- for (const entry of entries) {
4451
- if (!entry.isDirectory()) continue;
4452
- const dir = path8.join(runsDir, entry.name);
4453
- try {
4454
- const report = await fs7.lstat(path8.join(dir, "report.json"));
4455
- if (!report.isFile()) continue;
4456
- if (newest === void 0 || report.mtimeMs > newest.at) {
4457
- newest = { dir, at: report.mtimeMs };
4458
- }
4459
- } catch {
4460
- }
4461
- }
4462
- if (newest === void 0) throw new NoCairnRunsError(runsDir);
4463
- return newest.dir;
4953
+ import { createReadStream, openAsBlob } from "fs";
4954
+ import { pipeline } from "stream";
4955
+ import { Agent as HttpAgent, request as httpRequest } from "http";
4956
+ import { Agent as HttpsAgent, request as httpsRequest } from "https";
4957
+ var BACKOFF_BASE_MS = 300;
4958
+ var BACKOFF_CAP_MS = 1e4;
4959
+ var DEFAULT_RETRIES = 2;
4960
+ var RETRY_AFTER_CAP_MS = 6e4;
4961
+ function parseRetryAfter(raw, now = Date.now()) {
4962
+ const text = raw?.trim();
4963
+ if (text === void 0 || text === "") return null;
4964
+ const seconds = /^\d+(\.\d+)?$/.test(text) ? Number(text) : (Date.parse(text) - now) / 1e3;
4965
+ if (!Number.isFinite(seconds)) return null;
4966
+ return Math.min(Math.max(seconds, 0) * 1e3, RETRY_AFTER_CAP_MS);
4967
+ }
4968
+ var POOLS = { "http:": new HttpAgent({ keepAlive: true }), "https:": new HttpsAgent({ keepAlive: true }) };
4969
+ var IDLE_MS = 3e5;
4970
+ function nodeTransport(url, init, idleMs = IDLE_MS) {
4971
+ return new Promise((resolve9, reject) => {
4972
+ const target = new URL(url);
4973
+ const send = target.protocol === "https:" ? httpsRequest : httpRequest;
4974
+ const agent = POOLS[target.protocol === "https:" ? "https:" : "http:"];
4975
+ const req = send(target, { method: init.method, headers: init.headers, agent }, (res) => {
4976
+ const chunks = [];
4977
+ res.on("data", (chunk2) => chunks.push(chunk2));
4978
+ res.on("error", reject);
4979
+ res.on("end", () => {
4980
+ const status = res.statusCode ?? 0;
4981
+ const text = Buffer.concat(chunks).toString("utf8");
4982
+ resolve9({
4983
+ ok: status >= 200 && status <= 299,
4984
+ status,
4985
+ headers: {
4986
+ get: (name) => {
4987
+ const value = res.headers[name.toLowerCase()];
4988
+ return value === void 0 ? null : Array.isArray(value) ? value.join(", ") : value;
4989
+ }
4990
+ },
4991
+ json: async () => JSON.parse(text)
4992
+ });
4993
+ });
4994
+ });
4995
+ req.setTimeout(idleMs, () => req.destroy(new Error(`no answer from ${target.origin} in ${idleMs} ms`)));
4996
+ req.on("error", reject);
4997
+ req.end(init.body);
4998
+ });
4464
4999
  }
4465
- var CairnRunNotFoundError = class extends Error {
4466
- constructor(dir) {
4467
- super(
4468
- `No Cairn run found in ${dir} \u2014 expected a report.json written by "cairn design|explore|api".`
4469
- );
4470
- this.name = "CairnRunNotFoundError";
4471
- }
4472
- };
4473
- var CairnRunVersionError = class extends Error {
4474
- constructor(found) {
4475
- super(
4476
- 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.`
4477
- );
4478
- this.name = "CairnRunVersionError";
4479
- }
4480
- };
4481
- var CairnRunPartialError = class extends Error {
4482
- constructor(reason) {
4483
- super(`That Cairn run did not finish, so its cases are incomplete: ${reason}`);
4484
- this.name = "CairnRunPartialError";
4485
- }
4486
- };
4487
- var CairnEvidenceAmbiguousError = class extends Error {
4488
- constructor(name) {
4489
- super(
4490
- `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.`
5000
+ var withoutLength = (headers) => Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-length"));
5001
+ function nodePut(url, headers, source, idleMs) {
5002
+ return new Promise((resolve9, reject) => {
5003
+ const target = new URL(url);
5004
+ const send = target.protocol === "https:" ? httpsRequest : httpRequest;
5005
+ const length = "body" in source ? source.body.length : source.size;
5006
+ let answered;
5007
+ const settle = (err) => answered !== void 0 ? resolve9(answered) : reject(err);
5008
+ const req = send(
5009
+ target,
5010
+ { method: "PUT", headers: { ...withoutLength(headers), "content-length": String(length) } },
5011
+ (res) => {
5012
+ const retry = res.headers["retry-after"];
5013
+ answered = { status: res.statusCode ?? 0, retryAfter: Array.isArray(retry) ? retry[0] ?? null : retry ?? null };
5014
+ res.on("error", settle);
5015
+ res.on("close", () => {
5016
+ resolve9(answered);
5017
+ req.destroy();
5018
+ });
5019
+ res.resume();
5020
+ }
4491
5021
  );
4492
- this.name = "CairnEvidenceAmbiguousError";
4493
- }
5022
+ req.setTimeout(idleMs, () => req.destroy(Object.assign(new Error("idle"), { code: "ETIMEDOUT" })));
5023
+ req.on("error", settle);
5024
+ if ("body" in source) req.end(source.body);
5025
+ else pipeline(createReadStream(source.path), req, (err) => err ? settle(err) : void 0);
5026
+ });
5027
+ }
5028
+ var codeOfError = (err) => {
5029
+ const code = err?.code;
5030
+ return typeof code === "string" && /^[A-Z0-9_]{2,40}$/.test(code) ? code : "network";
4494
5031
  };
4495
- var asRecord = (v) => typeof v === "object" && v !== null ? v : {};
4496
- var str = (v, fallback = "") => typeof v === "string" && v !== "" ? v : fallback;
4497
- async function readJson(file) {
5032
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5033
+ async function detailOf(res) {
4498
5034
  try {
4499
- return JSON.parse(await fs7.readFile(file, "utf8"));
5035
+ const body = await res.json();
5036
+ const q = body.quota;
5037
+ return {
5038
+ ...typeof body.shardsExpected === "number" && Number.isInteger(body.shardsExpected) ? { shardsExpected: body.shardsExpected } : {},
5039
+ detail: typeof body.error === "string" ? body.error : "",
5040
+ ...typeof q === "object" && q !== null && !Array.isArray(q) ? { quota: q } : {},
5041
+ ...typeof body.code === "string" && /^[a-z0-9_]{1,60}$/.test(body.code) ? { code: body.code } : {}
5042
+ };
4500
5043
  } catch {
4501
- return void 0;
5044
+ return { detail: "" };
4502
5045
  }
4503
5046
  }
4504
- async function defaultReadEvidence(dir) {
4505
- const raw = await readJson(path8.join(dir, "api-evidence.json"));
4506
- if (!Array.isArray(raw)) return void 0;
4507
- return raw.map((r) => {
4508
- const rec = asRecord(r);
4509
- const error = str(rec["error"]);
4510
- return { name: str(rec["name"]), passed: rec["passed"] === true, ...error !== "" ? { error } : {} };
4511
- });
5047
+ function describeQuota(q) {
5048
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
5049
+ const kind = typeof q["kind"] === "string" ? q["kind"].slice(0, 60) : "limit";
5050
+ const [used, limit2] = [num(q["used"]), num(q["limit"])];
5051
+ const parts = [used !== void 0 && limit2 !== void 0 ? `${kind}: ${used} of ${limit2} used` : kind];
5052
+ if (typeof q["resetsAt"] === "string" && q["resetsAt"] !== "") parts.push(`resets ${q["resetsAt"].slice(0, 40)}`);
5053
+ return parts.join(", ");
4512
5054
  }
4513
- function casesFromDesign(report) {
4514
- const list = Array.isArray(report["testCases"]) ? report["testCases"] : [];
4515
- return list.map((raw) => {
4516
- const c = asRecord(raw);
4517
- const steps = (Array.isArray(c["steps"]) ? c["steps"] : []).map((s) => str(s)).filter((s) => s !== "");
4518
- return {
4519
- stableId: str(c["stableId"]),
4520
- title: str(c["title"], "untitled case"),
4521
- execution: c["execution"] === "manual" ? "manual" : "auto",
5055
+ function classify(status) {
5056
+ if (status === 401 || status === 403) return "auth";
5057
+ if (status === 409) return "conflict";
5058
+ if (status === 400) return "invalid";
5059
+ if (status === 429 || status >= 500) return "unavailable";
5060
+ return "other";
5061
+ }
5062
+ function createClient(opts) {
5063
+ const doFetch = opts.fetchImpl ?? nodeTransport;
5064
+ const wait = opts.wait ?? sleep;
5065
+ const uploadRetries = opts.uploadRetries === void 0 ? void 0 : Math.max(0, Math.floor(opts.uploadRetries));
5066
+ const random = opts.random ?? Math.random;
5067
+ const now = opts.now ?? Date.now;
5068
+ let pausedUntil = 0;
5069
+ const jittered = (ms) => Math.round(ms * (1 + random() * 0.5));
5070
+ async function backOff(attempt, said) {
5071
+ opts.onRetry?.();
5072
+ const ms = jittered(said ?? Math.min(BACKOFF_BASE_MS * 2 ** attempt, BACKOFF_CAP_MS));
5073
+ const until = now() + ms;
5074
+ pausedUntil = Math.max(pausedUntil, until);
5075
+ await wait(ms);
5076
+ return until;
5077
+ }
5078
+ async function respectPause(mine) {
5079
+ const left = pausedUntil - now();
5080
+ if (pausedUntil > mine && left > 0) await wait(left + Math.round(random() * 250));
5081
+ }
5082
+ const base = opts.apiUrl.replace(/\/+$/, "");
5083
+ const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
5084
+ async function send(method, path12, payload, retries = DEFAULT_RETRIES) {
5085
+ let last = {
5086
+ kind: "unavailable",
5087
+ status: null,
5088
+ detail: "no attempt was made"
5089
+ };
5090
+ let mine = 0;
5091
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
5092
+ await respectPause(mine);
5093
+ let res;
5094
+ try {
5095
+ res = await doFetch(`${base}${path12}`, {
5096
+ method,
5097
+ headers: { "content-type": payload?.type ?? "application/json", authorization: `Bearer ${opts.token}` },
5098
+ // A DELETE carries none. Sending `"undefined"` as a body is what a naive
5099
+ // `JSON.stringify(body)` would do, and some proxies answer that with a 400 nobody can
5100
+ // explain.
5101
+ ...payload === void 0 ? {} : { body: payload.body }
5102
+ });
5103
+ } catch (err) {
5104
+ last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
5105
+ if (attempt >= Math.min(retries, DEFAULT_RETRIES)) break;
5106
+ mine = await backOff(attempt, null);
5107
+ continue;
5108
+ }
5109
+ if (res.ok) {
5110
+ if (res.status === 204) return { ok: true, status: res.status, body: void 0 };
5111
+ try {
5112
+ return { ok: true, status: res.status, body: await res.json() };
5113
+ } catch {
5114
+ return { ok: false, kind: "other", status: res.status, detail: "the answer was not JSON" };
5115
+ }
5116
+ }
5117
+ const said = await detailOf(res);
5118
+ const kind = classify(res.status);
5119
+ last = { kind, status: res.status, detail: scrub(said.detail), ...said.code !== void 0 ? { code: said.code } : {}, ...said.shardsExpected !== void 0 ? { shardsExpected: said.shardsExpected } : {} };
5120
+ if (kind !== "unavailable") break;
5121
+ const said429 = parseRetryAfter(res.headers.get("retry-after"), now());
5122
+ if (res.status === 429 && (said.quota !== void 0 || said429 === null)) {
5123
+ last.kind = "invalid";
5124
+ last.detail = `quota exceeded (${said.quota === void 0 ? "no Retry-After" : scrub(describeQuota(said.quota))})`;
5125
+ if (said.detail) last.detail += ` \u2014 ${scrub(said.detail)}`;
5126
+ break;
5127
+ }
5128
+ if (attempt >= (said429 === null ? Math.min(retries, DEFAULT_RETRIES) : retries)) break;
5129
+ mine = await backOff(attempt, said429);
5130
+ }
5131
+ return { ok: false, ...last };
5132
+ }
5133
+ return {
5134
+ post: (path12, body, retries) => send("POST", path12, { body: JSON.stringify(body), type: "application/json" }, retries),
5135
+ upload: (path12, bytes, contentType) => send("POST", path12, { body: bytes, type: contentType }, uploadRetries ?? DEFAULT_RETRIES),
5136
+ del: (path12) => send("DELETE", path12),
5137
+ get: (path12) => send("GET", path12),
5138
+ async put(url, headers, source) {
5139
+ const putRetries = uploadRetries ?? 3;
5140
+ let last = { ok: false, status: null, code: "network" };
5141
+ let mine = 0;
5142
+ for (let attempt = 0; attempt <= putRetries; attempt += 1) {
5143
+ await respectPause(mine);
5144
+ try {
5145
+ let status;
5146
+ let retryAfter;
5147
+ if (opts.fetchImpl === void 0) ({ status, retryAfter } = await nodePut(url, headers, source, IDLE_MS));
5148
+ else {
5149
+ const body = "body" in source ? source.body : await openAsBlob(source.path);
5150
+ const res = await opts.fetchImpl(url, { method: "PUT", headers: withoutLength(headers), body });
5151
+ await res.arrayBuffer().catch(() => void 0);
5152
+ status = res.status;
5153
+ retryAfter = res.headers.get("retry-after");
5154
+ }
5155
+ if (status >= 200 && status <= 299) return { ok: true };
5156
+ last = { ok: false, status, code: `bucket_${status}` };
5157
+ if (status < 500 && status !== 429) return last;
5158
+ const said = parseRetryAfter(retryAfter, now());
5159
+ if (attempt >= (said === null ? Math.min(putRetries, 3) : putRetries)) return last;
5160
+ mine = await backOff(attempt, said);
5161
+ continue;
5162
+ } catch (err) {
5163
+ last = { ok: false, status: null, code: codeOfError(err) };
5164
+ }
5165
+ if (attempt >= Math.min(putRetries, 3)) return last;
5166
+ mine = await backOff(attempt, null);
5167
+ }
5168
+ return last;
5169
+ }
5170
+ };
5171
+ }
5172
+
5173
+ // src/reporter-core/env.ts
5174
+ init_esm_shims();
5175
+ import * as path8 from "path";
5176
+ var UPLOAD_RETRIES = { min: 0, max: 20, default: 6 };
5177
+
5178
+ // src/reporter-core/session.ts
5179
+ init_esm_shims();
5180
+ import { createHash as createHash4, randomUUID } from "crypto";
5181
+ import { promises as disk } from "fs";
5182
+ import { basename as basename3, extname } from "path";
5183
+ import { TextDecoder as TextDecoder2 } from "util";
5184
+ init_failure_detail();
5185
+
5186
+ // src/reporter-core/files-batch.ts
5187
+ init_esm_shims();
5188
+ import { createHash as createHash3 } from "crypto";
5189
+ import { createReadStream as createReadStream2 } from "fs";
5190
+ var FILES_BATCH_MAX = 100;
5191
+ var DIRECT_BATCH_BYTES = 6 * 1024 * 1024;
5192
+ var BATCH_PIPELINES = 2;
5193
+ async function sha256File(path12) {
5194
+ const hash = createHash3("sha256");
5195
+ for await (const part of createReadStream2(path12)) hash.update(part);
5196
+ return hash.digest("hex");
5197
+ }
5198
+ var sha256Bytes = (bytes) => createHash3("sha256").update(bytes).digest("hex");
5199
+ var BUCKET_CODES = /* @__PURE__ */ new Set([
5200
+ "bucket_unreachable",
5201
+ "not_connected",
5202
+ "platform_not_configured",
5203
+ "upload_expired",
5204
+ "file_mismatch",
5205
+ "file_missing"
5206
+ ]);
5207
+
5208
+ // src/reporter-core/fallback.ts
5209
+ init_esm_shims();
5210
+ import * as fs7 from "fs";
5211
+ import * as path9 from "path";
5212
+ var DEFAULT_FALLBACK_PATH = path9.join(".plune", "pending-results.jsonl");
5213
+
5214
+ // src/reporter-core/session.ts
5215
+ var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
5216
+ var SCREENSHOT_BYTES = 2 * 1024 * 1024;
5217
+ var SCREENSHOTS_PER_RESULT = 20;
5218
+ var TEXT_BYTES = 512 * 1024;
5219
+ var TEXTS_PER_RESULT = 10;
5220
+ var UTF8 = new TextDecoder2("utf-8", { fatal: true });
5221
+ var TYPE_BY_EXTENSION = {
5222
+ ".png": "image/png",
5223
+ ".jpg": "image/jpeg",
5224
+ ".jpeg": "image/jpeg",
5225
+ ".webp": "image/webp"
5226
+ };
5227
+ var METADATA_TYPE = "application/plune.metadata+json";
5228
+ var NAME_MAX = 200;
5229
+ function nameOf(file) {
5230
+ const own2 = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : basename3(file.path));
5231
+ const fileExt = file.path === void 0 ? "" : extname(file.path);
5232
+ const ownExt = extname(own2);
5233
+ const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
5234
+ const ext = typed ? ownExt : fileExt;
5235
+ let stem = typed ? own2.slice(0, -ownExt.length) : own2;
5236
+ if (stem.length + ext.length > NAME_MAX) {
5237
+ stem = stem.slice(0, Math.max(0, NAME_MAX - ext.length));
5238
+ if (/[\uD800-\uDBFF]$/.test(stem)) stem = stem.slice(0, -1);
5239
+ }
5240
+ return `${stem}${ext}`;
5241
+ }
5242
+ var SKIPPED = {
5243
+ hidden: "its name starts with an underscore, which hides an attachment in Playwright's own reports too",
5244
+ type: "Plune takes PNG, JPEG and WebP",
5245
+ limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
5246
+ missing: "the file cannot be read on this machine",
5247
+ size: "Plune takes a file of at most 2 MB",
5248
+ textLimit: `a result holds at most ${TEXTS_PER_RESULT} text files`,
5249
+ textSize: "Plune takes a text file of at most 512 KiB",
5250
+ empty: "the file is empty",
5251
+ binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
5252
+ encoding: "Plune takes UTF-8 text only",
5253
+ noStorage: "no storage bucket is connected to this project"
5254
+ };
5255
+ var BUCKET_FOUND = "plune: storage bucket found for this project \u2014 screenshots, text, trace and video go straight to it over short-lived links.";
5256
+ var KINDS = {
5257
+ screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
5258
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" },
5259
+ // 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.
5260
+ file: { label: "file", bytes: 0, room: 0, limit: "limit", size: "size" }
5261
+ };
5262
+ function kindOf2(type) {
5263
+ if (type.startsWith("image/")) return "screenshot";
5264
+ return TEXT_TYPES.has(type) ? "text" : "file";
5265
+ }
5266
+ var codeOf2 = (out) => out.code ?? (out.status === null ? "network" : `http_${out.status}`);
5267
+ function linkOf(item) {
5268
+ const link = item;
5269
+ if (typeof link?.id !== "string" || typeof link.url !== "string") return void 0;
5270
+ const headers = typeof link.headers === "object" && link.headers !== null ? link.headers : {};
5271
+ return { id: link.id, url: link.url, headers };
5272
+ }
5273
+ function textTypeOf(contentType, type) {
5274
+ const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
5275
+ return charset?.toLowerCase() === "utf-8" ? `${type}; charset=utf-8` : type;
5276
+ }
5277
+ function textRefusal(bytes) {
5278
+ if (bytes.length > TEXT_BYTES) return "textSize";
5279
+ if (bytes.length === 0) return "empty";
5280
+ if (bytes.includes(0)) return "binary";
5281
+ try {
5282
+ UTF8.decode(bytes);
5283
+ } catch {
5284
+ return "encoding";
5285
+ }
5286
+ return void 0;
5287
+ }
5288
+ var BATCH_BYTES = 8 * 1024 * 1024;
5289
+ var ENVELOPE_BYTES = Buffer.byteLength(JSON.stringify({ results: [] }));
5290
+ function chunk(items, size) {
5291
+ const out = [];
5292
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
5293
+ return out;
5294
+ }
5295
+ function fileSender(options) {
5296
+ const { client, log, stats, uploadsAtOnce, uploadRetries } = options;
5297
+ const without = options.without ?? "its result is reported without it";
5298
+ let retried = 0;
5299
+ let uploadMs = 0;
5300
+ let requests = 0;
5301
+ let existed = 0;
5302
+ let batchMissing = false;
5303
+ const skipsSaid = /* @__PURE__ */ new Set();
5304
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
5305
+ let bucketSeen = false;
5306
+ let noStorage = 0;
5307
+ let uploadsMissing = false;
5308
+ const failedSaid = /* @__PURE__ */ new Set();
5309
+ const codesSaid = /* @__PURE__ */ new Set();
5310
+ const rooms = /* @__PURE__ */ new Map();
5311
+ function skip(kind, name, why) {
5312
+ countsOf(kind).skipped += 1;
5313
+ if (why === "noStorage") noStorage += 1;
5314
+ const said = why === "noStorage" ? why : `${kind}/${why}`;
5315
+ if (skipsSaid.has(said)) return;
5316
+ skipsSaid.add(said);
5317
+ if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
5318
+ else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
5319
+ }
5320
+ const filesOf = (job) => `/v1/${job.owner ?? "results"}/${encodeURIComponent(job.id)}/files`;
5321
+ function ask(job, size) {
5322
+ requests += 1;
5323
+ return client.post(`${filesOf(job)}/uploads`, {
5324
+ files: [{ name: job.name, contentType: job.type, size }]
5325
+ }, uploadRetries);
5326
+ }
5327
+ function failed(job, why) {
5328
+ countsOf(job.kind).failed += 1;
5329
+ if (!failedSaid.has(job.kind)) {
5330
+ failedSaid.add(job.kind);
5331
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 ${without}.`);
5332
+ }
5333
+ }
5334
+ function failedToBucket(job, code) {
5335
+ countsOf(job.kind).failed += 1;
5336
+ if (codesSaid.has(code)) return;
5337
+ codesSaid.add(code);
5338
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 ${without}.`);
5339
+ }
5340
+ function refusedHere(job, size) {
5341
+ if (job.kind === "screenshot") {
5342
+ if (!SCREENSHOT_TYPES.has(job.type)) return "type";
5343
+ if (size > SCREENSHOT_BYTES) return "size";
5344
+ }
5345
+ if (job.kind === "text" && size > TEXT_BYTES) return "textSize";
5346
+ return void 0;
5347
+ }
5348
+ async function uploadDirect(job, size) {
5349
+ const { kind } = job;
5350
+ if (kind === "file") return skip(kind, job.name, "noStorage");
5351
+ const { bytes: ceiling, size: tooBig } = KINDS[kind];
5352
+ if (size > ceiling) return skip(kind, job.name, tooBig);
5353
+ let bytes;
5354
+ if (job.body !== void 0) bytes = job.body;
5355
+ else {
5356
+ try {
5357
+ bytes = await disk.readFile(job.path);
5358
+ } catch {
5359
+ return skip(kind, job.name, "missing");
5360
+ }
5361
+ }
5362
+ const refusal = kind === "text" ? textRefusal(bytes) : void 0;
5363
+ if (refusal !== void 0) return skip(kind, job.name, refusal);
5364
+ requests += 1;
5365
+ const out = await client.upload(
5366
+ `${filesOf(job)}?name=${encodeURIComponent(job.name)}`,
5367
+ bytes,
5368
+ job.type
5369
+ );
5370
+ if (out.ok) countsOf(kind).uploaded += 1;
5371
+ else failed(job, out.detail || out.kind);
5372
+ }
5373
+ async function uploadToBucket(job, size, first) {
5374
+ const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
5375
+ let link = first;
5376
+ for (let renewed = false; ; ) {
5377
+ const put = await client.put(link.url, link.headers, source);
5378
+ if (put.ok) break;
5379
+ if (put.status !== 403 || renewed) return failedToBucket(job, put.code);
5380
+ renewed = true;
5381
+ const again = await ask(job, size);
5382
+ if (!again.ok) return failedToBucket(job, codeOf2(again));
5383
+ const fresh = linkOf(again.body?.files?.[0]);
5384
+ if (fresh === void 0) return failedToBucket(job, "bad_answer");
5385
+ link = fresh;
5386
+ }
5387
+ requests += 1;
5388
+ const done = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
5389
+ if (!done.ok) return failedToBucket(job, codeOf2(done));
5390
+ countsOf(job.kind).uploaded += 1;
5391
+ }
5392
+ let free = uploadsAtOnce;
5393
+ const waiting = [];
5394
+ async function gated(work) {
5395
+ if (free === 0) await new Promise((resolve9) => waiting.push(resolve9));
5396
+ else free -= 1;
5397
+ try {
5398
+ return await work();
5399
+ } finally {
5400
+ const next = waiting.shift();
5401
+ if (next !== void 0) next();
5402
+ else free += 1;
5403
+ }
5404
+ }
5405
+ async function plan(job) {
5406
+ const { kind } = job;
5407
+ let size;
5408
+ if (job.body !== void 0) size = job.body.length;
5409
+ else if (job.path === void 0) return void skip(kind, job.name, "missing");
5410
+ else {
5411
+ try {
5412
+ size = (await disk.stat(job.path)).size;
5413
+ } catch {
5414
+ return void skip(kind, job.name, "missing");
5415
+ }
5416
+ }
5417
+ if (size === 0) return void skip(kind, job.name, "empty");
5418
+ const direct = () => {
5419
+ if (kind === "file") return void skip(kind, job.name, "noStorage");
5420
+ const roomKey = `${job.id}/${kind}`;
5421
+ const left = rooms.get(roomKey) ?? KINDS[kind].room;
5422
+ if (left === 0) return void skip(kind, job.name, KINDS[kind].limit);
5423
+ rooms.set(roomKey, left - 1);
5424
+ return () => uploadDirect(job, size);
5425
+ };
5426
+ if (uploadsMissing) return direct();
5427
+ const out = await gated(() => ask(job, size));
5428
+ if (!out.ok) {
5429
+ if (out.status === 404 && out.detail === "" && out.code === void 0) {
5430
+ uploadsMissing = true;
5431
+ return direct();
5432
+ }
5433
+ if (out.code !== void 0) failedToBucket(job, out.code);
5434
+ else failed(job, out.detail || out.kind);
5435
+ return void 0;
5436
+ }
5437
+ const item = out.body?.files?.[0];
5438
+ if (item?.skipped === "no_storage") return void skip(kind, job.name, refusedHere(job, size) ?? "noStorage");
5439
+ if (item?.direct === true) return direct();
5440
+ const link = linkOf(item);
5441
+ if (link === void 0) return void failed(job, "bad_answer");
5442
+ if (!bucketSeen) {
5443
+ bucketSeen = true;
5444
+ log(BUCKET_FOUND);
5445
+ }
5446
+ return () => uploadToBucket(job, size, link);
5447
+ }
5448
+ async function uploadEach(jobs) {
5449
+ const byResult = /* @__PURE__ */ new Map();
5450
+ for (const job of jobs) byResult.set(job.id, [...byResult.get(job.id) ?? [], job]);
5451
+ await Promise.all(
5452
+ [...byResult.values()].map(async (group) => {
5453
+ const work = [];
5454
+ for (const job of group) {
5455
+ const act = await plan(job);
5456
+ if (act !== void 0) work.push(gated(act));
5457
+ }
5458
+ await Promise.all(work);
5459
+ })
5460
+ );
5461
+ }
5462
+ async function measure(job) {
5463
+ let size;
5464
+ if (job.body !== void 0) size = job.body.length;
5465
+ else if (job.path === void 0) return void skip(job.kind, job.name, "missing");
5466
+ else {
5467
+ try {
5468
+ size = (await disk.stat(job.path)).size;
5469
+ } catch {
5470
+ return void skip(job.kind, job.name, "missing");
5471
+ }
5472
+ }
5473
+ if (size === 0) return void skip(job.kind, job.name, "empty");
5474
+ return size;
5475
+ }
5476
+ const routeMissing = (out) => !out.ok && out.status === 404 && out.detail === "" && out.code === void 0;
5477
+ function takeRoom(job) {
5478
+ if (job.kind === "file") {
5479
+ skip(job.kind, job.name, "noStorage");
5480
+ return false;
5481
+ }
5482
+ const roomKey = `${job.id}/${job.kind}`;
5483
+ const left = rooms.get(roomKey) ?? KINDS[job.kind].room;
5484
+ if (left === 0) {
5485
+ skip(job.kind, job.name, KINDS[job.kind].limit);
5486
+ return false;
5487
+ }
5488
+ rooms.set(roomKey, left - 1);
5489
+ return true;
5490
+ }
5491
+ function refusedItem(job, size, item) {
5492
+ const code = item.code ?? "refused";
5493
+ if (code === "duplicate") existed += 1;
5494
+ else if (code === "no_storage") skip(job.kind, job.name, refusedHere(job, size) ?? "noStorage");
5495
+ else if (code === "too_many_files") skip(job.kind, job.name, KINDS[job.kind].limit);
5496
+ else if (BUCKET_CODES.has(code)) failedToBucket(job, code);
5497
+ else failed(job, code);
5498
+ }
5499
+ const itemPause = (round) => new Promise((r) => setTimeout(r, Math.min(250 * 2 ** round, 4e3)));
5500
+ async function batchOf(jobs) {
5501
+ if (batchMissing) return uploadEach(jobs);
5502
+ const sized = [];
5503
+ for (const job of jobs) {
5504
+ const size = await measure(job);
5505
+ if (size === void 0) continue;
5506
+ try {
5507
+ sized.push({ job, size, sha256: job.body !== void 0 ? sha256Bytes(job.body) : await sha256File(job.path) });
5508
+ } catch {
5509
+ skip(job.kind, job.name, "missing");
5510
+ }
5511
+ }
5512
+ if (sized.length === 0) return;
5513
+ const announced = await gated(() => {
5514
+ requests += 1;
5515
+ return client.post(
5516
+ "/v1/files/uploads-batch",
5517
+ { items: sized.map((s) => ({ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 })) },
5518
+ uploadRetries
5519
+ );
5520
+ });
5521
+ if (routeMissing(announced)) {
5522
+ batchMissing = true;
5523
+ return uploadEach(sized.map((s) => s.job));
5524
+ }
5525
+ const verdicts = announced.ok ? announced.body?.items : void 0;
5526
+ if (!announced.ok || !Array.isArray(verdicts) || verdicts.length !== sized.length) {
5527
+ for (const s of sized) {
5528
+ if (announced.ok) failed(s.job, "bad_answer");
5529
+ else if (announced.code !== void 0) failedToBucket(s.job, announced.code);
5530
+ else failed(s.job, announced.detail || announced.kind);
5531
+ }
5532
+ return;
5533
+ }
5534
+ const puts = [];
5535
+ const directs = [];
5536
+ sized.forEach((s, i) => {
5537
+ const v = verdicts[i] ?? {};
5538
+ if (v.status === "exists") existed += 1;
5539
+ else if (v.status === "direct") {
5540
+ if (takeRoom(s.job)) directs.push(s);
5541
+ } else if (v.status === "upload") {
5542
+ const link = linkOf(v);
5543
+ if (link === void 0) return failed(s.job, "bad_answer");
5544
+ if (!bucketSeen) {
5545
+ bucketSeen = true;
5546
+ log(BUCKET_FOUND);
5547
+ }
5548
+ puts.push({ s, link });
5549
+ } else if (v.status === "refused") refusedItem(s.job, s.size, v);
5550
+ else failed(s.job, "bad_answer");
5551
+ });
5552
+ const toComplete = [];
5553
+ await Promise.all(
5554
+ puts.map(
5555
+ ({ s, link: first }) => gated(async () => {
5556
+ const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
5557
+ let link = first;
5558
+ for (let renewed = false; ; ) {
5559
+ const put = await client.put(link.url, link.headers, source);
5560
+ if (put.ok) break;
5561
+ if (put.status !== 403 || renewed) return failedToBucket(s.job, put.code);
5562
+ renewed = true;
5563
+ requests += 1;
5564
+ const again = await client.post(
5565
+ "/v1/files/uploads-batch",
5566
+ { items: [{ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 }] },
5567
+ uploadRetries
5568
+ );
5569
+ const fresh = again.ok ? linkOf(again.body?.items?.[0]) : void 0;
5570
+ if (fresh === void 0) return failedToBucket(s.job, again.ok ? "bad_answer" : codeOf2(again));
5571
+ link = fresh;
5572
+ }
5573
+ toComplete.push({ job: s.job, id: link.id });
5574
+ })
5575
+ )
5576
+ );
5577
+ await complete(toComplete);
5578
+ await sendDirect(directs);
5579
+ }
5580
+ async function complete(items) {
5581
+ for (let round = 0; items.length > 0; round += 1) {
5582
+ const out = await gated(() => {
5583
+ requests += 1;
5584
+ return client.post("/v1/files/complete-batch", { ids: items.map((i) => i.id) }, uploadRetries);
5585
+ });
5586
+ if (routeMissing(out)) {
5587
+ await Promise.all(
5588
+ items.map(
5589
+ (i) => gated(async () => {
5590
+ requests += 1;
5591
+ const one = await client.post(`/v1/files/${encodeURIComponent(i.id)}/complete`, {}, uploadRetries);
5592
+ if (one.ok) countsOf(i.job.kind).uploaded += 1;
5593
+ else failedToBucket(i.job, codeOf2(one));
5594
+ })
5595
+ )
5596
+ );
5597
+ return;
5598
+ }
5599
+ const verdicts = out.ok ? out.body?.items : void 0;
5600
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== items.length) {
5601
+ for (const i of items) failedToBucket(i.job, out.ok ? "bad_answer" : codeOf2(out));
5602
+ return;
5603
+ }
5604
+ const again = [];
5605
+ items.forEach((i, at) => {
5606
+ const v = verdicts[at] ?? {};
5607
+ if (v.status === "ready") countsOf(i.job.kind).uploaded += 1;
5608
+ else if (v.retryable === true && round < Math.min(uploadRetries, 3)) again.push(i);
5609
+ else refusedItem(i.job, 0, v.status === "refused" ? v : { code: "bad_answer" });
5610
+ });
5611
+ items = again;
5612
+ if (items.length > 0) {
5613
+ retried += items.length;
5614
+ await itemPause(round);
5615
+ }
5616
+ }
5617
+ }
5618
+ async function sendDirect(items) {
5619
+ const groups = [];
5620
+ let bytes = 0;
5621
+ for (const item of items) {
5622
+ const group = groups[groups.length - 1];
5623
+ if (group === void 0 || group.length >= FILES_BATCH_MAX || bytes + item.size > DIRECT_BATCH_BYTES) {
5624
+ groups.push([item]);
5625
+ bytes = item.size;
5626
+ } else {
5627
+ group.push(item);
5628
+ bytes += item.size;
5629
+ }
5630
+ }
5631
+ for (const group of groups) {
5632
+ const body = [];
5633
+ const sent = [];
5634
+ for (const { job, size } of group) {
5635
+ const { kind } = job;
5636
+ if (size > KINDS[kind].bytes) {
5637
+ skip(kind, job.name, KINDS[kind].size);
5638
+ continue;
5639
+ }
5640
+ let data;
5641
+ try {
5642
+ data = job.body ?? await disk.readFile(job.path);
5643
+ } catch {
5644
+ skip(kind, job.name, "missing");
5645
+ continue;
5646
+ }
5647
+ const refusal = kind === "text" ? textRefusal(data) : void 0;
5648
+ if (refusal !== void 0) {
5649
+ skip(kind, job.name, refusal);
5650
+ continue;
5651
+ }
5652
+ body.push({ resultId: job.id, name: job.name, contentType: job.type, data: data.toString("base64") });
5653
+ sent.push({ job, size });
5654
+ }
5655
+ if (body.length === 0) continue;
5656
+ const out = await gated(() => {
5657
+ requests += 1;
5658
+ return client.post("/v1/files/direct-batch", { items: body }, uploadRetries);
5659
+ });
5660
+ if (routeMissing(out)) {
5661
+ batchMissing = true;
5662
+ for (const { job, size } of sent) await gated(() => uploadDirect(job, size));
5663
+ continue;
5664
+ }
5665
+ const verdicts = out.ok ? out.body?.items : void 0;
5666
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== sent.length) {
5667
+ for (const { job } of sent) failed(job, out.ok ? "bad_answer" : out.detail || out.kind);
5668
+ continue;
5669
+ }
5670
+ sent.forEach(({ job }, i) => {
5671
+ const v = verdicts[i] ?? {};
5672
+ if (v.status === "stored") countsOf(job.kind).uploaded += 1;
5673
+ else if (v.status === "exists") existed += 1;
5674
+ else refusedItem(job, 0, v.status === "refused" ? v : { code: "bad_answer" });
5675
+ });
5676
+ }
5677
+ }
5678
+ async function uploadBatched(jobs) {
5679
+ const batches = chunk(jobs, FILES_BATCH_MAX);
5680
+ let next = 0;
5681
+ await Promise.all(
5682
+ Array.from({ length: Math.min(BATCH_PIPELINES, batches.length) }, async () => {
5683
+ for (let at = next++; at < batches.length; at = next++) await batchOf(batches[at]);
5684
+ })
5685
+ );
5686
+ }
5687
+ async function upload(items, filesByKey) {
5688
+ if (filesByKey.size === 0 || !Array.isArray(items)) return;
5689
+ const jobs = [];
5690
+ for (const item of items) {
5691
+ if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
5692
+ for (const file of filesByKey.get(item.resultKey) ?? []) {
5693
+ const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[extname(file.path).toLowerCase()]);
5694
+ if (type === void 0 || type === METADATA_TYPE) continue;
5695
+ const kind = kindOf2(type);
5696
+ if (kind !== "text" && file.path === void 0) continue;
5697
+ const name = nameOf(file);
5698
+ if (file.name.startsWith("_")) skip(kind, name, "hidden");
5699
+ else {
5700
+ jobs.push({
5701
+ id: item.id,
5702
+ kind,
5703
+ name,
5704
+ type: kind === "text" ? textTypeOf(file.contentType ?? "", type) : type,
5705
+ ...file.body !== void 0 ? { body: file.body } : {},
5706
+ ...file.path !== void 0 ? { path: file.path } : {}
5707
+ });
5708
+ }
5709
+ }
5710
+ }
5711
+ const started = Date.now();
5712
+ if (batchMissing) await uploadEach(jobs);
5713
+ else await uploadBatched(jobs);
5714
+ uploadMs += Date.now() - started;
5715
+ }
5716
+ return {
5717
+ upload,
5718
+ uploadEach,
5719
+ onRetry: () => void (retried += 1),
5720
+ get bucketSeen() {
5721
+ return bucketSeen;
5722
+ },
5723
+ get noStorage() {
5724
+ return noStorage;
5725
+ },
5726
+ get existed() {
5727
+ return existed;
5728
+ },
5729
+ get retried() {
5730
+ return retried;
5731
+ },
5732
+ get uploadMs() {
5733
+ return uploadMs;
5734
+ },
5735
+ get requests() {
5736
+ return requests;
5737
+ }
5738
+ };
5739
+ }
5740
+
5741
+ // src/cli/commands/cairn-artifact.ts
5742
+ init_esm_shims();
5743
+ import * as fs8 from "fs/promises";
5744
+ import * as path10 from "path";
5745
+
5746
+ // src/mcp-testing/scan/config/config.ts
5747
+ init_esm_shims();
5748
+
5749
+ // src/mcp-testing/report/human.ts
5750
+ init_esm_shims();
5751
+ init_failure_detail();
5752
+
5753
+ // src/mcp-testing/conformance/score.ts
5754
+ init_esm_shims();
5755
+ init_exit_codes();
5756
+
5757
+ // src/mcp-testing/conformance/catalog.ts
5758
+ init_esm_shims();
5759
+
5760
+ // src/mcp-testing/conformance/apps-catalog.ts
5761
+ init_esm_shims();
5762
+ var BOTH = ["legacy", "modern"];
5763
+ var APPS_SPEC_URL = "https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx";
5764
+ var ref = (section) => ({
5765
+ revision: "2026-01-26",
5766
+ page: "apps.mdx",
5767
+ section,
5768
+ url: APPS_SPEC_URL
5769
+ });
5770
+ var FORMAT = "UI Resource Format";
5771
+ var DISCOVERY = "Resource Discovery";
5772
+ var apps = (s) => ({
5773
+ ...s,
5774
+ suite: "apps",
5775
+ kind: "check",
5776
+ derived: s.derived ?? false,
5777
+ needsFixture: s.needsFixture ?? false,
5778
+ transports: ["stdio", "http"],
5779
+ eras: BOTH
5780
+ });
5781
+ var APPS_CATALOG = [
5782
+ apps({
5783
+ id: "apps-ui-resource-uri-scheme",
5784
+ title: "The address of a UI resource starts with ui://",
5785
+ 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.",
5786
+ level: "MUST",
5787
+ derived: true,
5788
+ 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.',
5789
+ specRefs: [ref(FORMAT), ref(DISCOVERY)]
5790
+ }),
5791
+ apps({
5792
+ id: "apps-ui-resource-exists",
5793
+ title: "The resource a tool names can be read",
5794
+ 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.",
5795
+ level: "MUST",
5796
+ derived: true,
5797
+ 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.`,
5798
+ specRefs: [ref(DISCOVERY)]
5799
+ }),
5800
+ apps({
5801
+ id: "apps-ui-mime-type",
5802
+ title: "The content of a UI resource is text/html;profile=mcp-app",
5803
+ 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).',
5804
+ level: "MUST",
5805
+ derivation: 'Content Requirements: "`mimeType` MUST be `text/html;profile=mcp-app` (other types reserved for future extensions)"',
5806
+ specRefs: [ref(FORMAT)]
5807
+ }),
5808
+ apps({
5809
+ id: "apps-ui-content-payload",
5810
+ title: "The content is one of text and blob, and is an HTML5 document",
5811
+ 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.",
5812
+ level: "MUST",
5813
+ derived: true,
5814
+ 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.',
5815
+ specRefs: [ref(FORMAT)]
5816
+ }),
5817
+ apps({
5818
+ id: "apps-ui-listed-mime",
5819
+ title: "A listed UI resource has the mimeType text/html;profile=mcp-app",
5820
+ 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.",
5821
+ level: "SHOULD",
5822
+ derivation: 'UIResource.mimeType: "SHOULD be `text/html;profile=mcp-app` for HTML-based UIs in the initial MVP."',
5823
+ specRefs: [ref(FORMAT)]
5824
+ }),
5825
+ apps({
5826
+ id: "apps-ui-visibility-values",
5827
+ title: "visibility holds only model and app",
5828
+ description: 'Where a tool sets _meta.ui.visibility, it is an array whose every element is "model" or "app".',
5829
+ level: "SHOULD",
5830
+ derived: true,
5831
+ 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.',
5832
+ specRefs: [ref(DISCOVERY)]
5833
+ }),
5834
+ apps({
5835
+ id: "apps-ui-tool-text-fallback",
5836
+ title: "A tool with a UI also returns content",
5837
+ 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).",
5838
+ level: "MUST",
5839
+ needsFixture: true,
5840
+ 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.',
5841
+ specRefs: [ref("Client<>Server Capability Negotiation")]
5842
+ }),
5843
+ apps({
5844
+ id: "apps-ui-meta-shapes",
5845
+ title: "csp, permissions, domain and prefersBorder have the shapes of the text",
5846
+ 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).",
5847
+ level: "SHOULD",
5848
+ derived: true,
5849
+ 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.',
5850
+ specRefs: [ref(FORMAT)]
5851
+ })
5852
+ ];
5853
+
5854
+ // src/mcp-testing/conformance/auth-catalog.ts
5855
+ init_esm_shims();
5856
+ var L = "2025-11-25";
5857
+ var M = "2026-07-28";
5858
+ var BOTH2 = ["legacy", "modern"];
5859
+ var MODERN = ["modern"];
5860
+ var ref2 = (revision, page, section) => ({
5861
+ revision,
5862
+ page,
5863
+ section
5864
+ });
5865
+ var AUTH = "basic/authorization";
5866
+ var DISCOVERY2 = "basic/authorization/authorization-server-discovery";
5867
+ var SECURITY = "basic/authorization/security-considerations";
5868
+ var REGISTRATION = "basic/authorization/client-registration";
5869
+ var oauth = (s) => ({
5870
+ ...s,
5871
+ suite: "oauth",
5872
+ kind: "check",
5873
+ derived: s.derived ?? false,
5874
+ needsFixture: s.needsFixture ?? false,
5875
+ transports: ["http"]
5876
+ });
5877
+ var OAUTH_CATALOG = [
5878
+ oauth({
5879
+ id: "oauth-requires-auth",
5880
+ title: "A request without a token gets 401",
5881
+ 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).",
5882
+ level: "MUST",
5883
+ specRefs: [ref2(L, AUTH, "Error Handling"), ref2(M, AUTH, "Error Handling")],
5884
+ eras: BOTH2
5885
+ }),
5886
+ oauth({
5887
+ id: "oauth-challenge-bearer",
5888
+ title: "The 401 carries a Bearer challenge",
5889
+ description: "The 401 answer has a WWW-Authenticate header with the scheme Bearer.",
5890
+ level: "MUST",
5891
+ derived: true,
5892
+ 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.`,
5893
+ specRefs: [
5894
+ ref2(L, AUTH, "Protected Resource Metadata Discovery Requirements"),
5895
+ ref2(M, DISCOVERY2, "Protected Resource Metadata Discovery Requirements")
5896
+ ],
5897
+ eras: BOTH2
5898
+ }),
5899
+ oauth({
5900
+ id: "oauth-prm-reachable",
5901
+ title: "The protected resource metadata can be found",
5902
+ 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.",
5903
+ level: "MUST",
5904
+ specRefs: [
5905
+ ref2(L, AUTH, "Protected Resource Metadata Discovery Requirements"),
5906
+ ref2(M, DISCOVERY2, "Protected Resource Metadata Discovery Requirements")
5907
+ ],
5908
+ eras: BOTH2
5909
+ }),
5910
+ oauth({
5911
+ id: "oauth-challenge-metadata-url",
5912
+ title: "resource_metadata names a URL that serves the document",
5913
+ 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.",
5914
+ level: "MUST",
5915
+ derived: true,
5916
+ 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.',
5917
+ specRefs: [
5918
+ ref2(L, AUTH, "Protected Resource Metadata Discovery Requirements"),
5919
+ ref2(M, DISCOVERY2, "Protected Resource Metadata Discovery Requirements")
5920
+ ],
5921
+ eras: BOTH2
5922
+ }),
5923
+ oauth({
5924
+ id: "oauth-prm-valid",
5925
+ title: "The protected resource metadata names an authorization server",
5926
+ 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).",
5927
+ level: "MUST",
5928
+ derived: true,
5929
+ 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.`,
5930
+ specRefs: [
5931
+ ref2(L, AUTH, "Authorization Server Location"),
5932
+ ref2(M, DISCOVERY2, "Authorization Server Location")
5933
+ ],
5934
+ eras: BOTH2
5935
+ }),
5936
+ oauth({
5937
+ id: "oauth-challenge-scope",
5938
+ title: "The 401 names the scope it needs",
5939
+ description: "WWW-Authenticate has a scope parameter.",
5940
+ level: "SHOULD",
5941
+ specRefs: [
5942
+ ref2(L, AUTH, "Protected Resource Metadata Discovery Requirements"),
5943
+ ref2(M, AUTH, "Scope Selection Strategy")
5944
+ ],
5945
+ eras: BOTH2
5946
+ }),
5947
+ oauth({
5948
+ id: "oauth-as-metadata-discoverable",
5949
+ title: "The authorization server publishes metadata",
5950
+ 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).",
5951
+ level: "MUST",
5952
+ specRefs: [
5953
+ ref2(L, AUTH, "Authorization Server Metadata Discovery"),
5954
+ ref2(M, DISCOVERY2, "Authorization Server Metadata Discovery")
5955
+ ],
5956
+ eras: BOTH2
5957
+ }),
5958
+ oauth({
5959
+ id: "oauth-as-issuer-matches",
5960
+ title: "The issuer of the metadata is the issuer it was found by",
5961
+ description: "The issuer member of the metadata document is identical, character for character, to the issuer identifier the well-known URL was built from.",
5962
+ level: "MUST",
5963
+ derived: true,
5964
+ 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.',
5965
+ specRefs: [ref2(M, DISCOVERY2, "Authorization Server Metadata Discovery")],
5966
+ eras: MODERN
5967
+ }),
5968
+ oauth({
5969
+ id: "oauth-as-https",
5970
+ title: "The authorization endpoints are HTTPS",
5971
+ 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.",
5972
+ level: "MUST",
5973
+ specRefs: [ref2(L, AUTH, "Communication Security"), ref2(M, SECURITY, "Communication Security")],
5974
+ eras: BOTH2
5975
+ }),
5976
+ oauth({
5977
+ id: "oauth-as-pkce-advertised",
5978
+ title: "The authorization server advertises PKCE",
5979
+ description: "The metadata has code_challenge_methods_supported.",
5980
+ level: "MUST",
5981
+ derived: true,
5982
+ 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).',
5983
+ specRefs: [
5984
+ ref2(L, AUTH, "Authorization Code Protection"),
5985
+ ref2(M, SECURITY, "Authorization Code Protection")
5986
+ ],
5987
+ eras: BOTH2
5988
+ }),
5989
+ oauth({
5990
+ id: "oauth-as-pkce-s256",
5991
+ title: "PKCE with S256 is advertised",
5992
+ description: "code_challenge_methods_supported lists S256.",
5993
+ level: "SHOULD",
5994
+ derived: true,
5995
+ 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.",
5996
+ specRefs: [
5997
+ ref2(L, AUTH, "Authorization Code Protection"),
5998
+ ref2(M, SECURITY, "Authorization Code Protection")
5999
+ ],
6000
+ eras: BOTH2
6001
+ }),
6002
+ oauth({
6003
+ id: "oauth-as-iss-advertised",
6004
+ title: "The authorization server advertises the iss parameter",
6005
+ description: "The metadata has authorization_response_iss_parameter_supported: true.",
6006
+ level: "SHOULD",
6007
+ specRefs: [ref2(M, AUTH, "Authorization Response Validation")],
6008
+ eras: MODERN
6009
+ }),
6010
+ oauth({
6011
+ id: "oauth-as-cimd-advertised",
6012
+ title: "The authorization server advertises Client ID Metadata Documents",
6013
+ description: "The metadata has client_id_metadata_document_supported: true.",
6014
+ level: "SHOULD",
6015
+ specRefs: [
6016
+ ref2(L, AUTH, "Client ID Metadata Documents"),
6017
+ ref2(M, REGISTRATION, "Client ID Metadata Documents")
6018
+ ],
6019
+ eras: BOTH2
6020
+ }),
6021
+ oauth({
6022
+ id: "oauth-neg-invalid-token-401",
6023
+ title: "A token that is not valid gets 401",
6024
+ description: "A request with a bearer token the authorization server never issued answers 401.",
6025
+ level: "MUST",
6026
+ specRefs: [ref2(L, AUTH, "Token Handling"), ref2(M, AUTH, "Token Handling")],
6027
+ eras: BOTH2
6028
+ }),
6029
+ oauth({
6030
+ id: "oauth-neg-wrong-audience",
6031
+ title: "A token issued for another resource is refused",
6032
+ 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.",
6033
+ level: "MUST",
6034
+ specRefs: [
6035
+ ref2(L, AUTH, "Token Handling"),
6036
+ ref2(L, AUTH, "Access Token Privilege Restriction"),
6037
+ ref2(M, AUTH, "Token Handling"),
6038
+ ref2(M, SECURITY, "Token Audience Binding and Validation")
6039
+ ],
6040
+ eras: BOTH2,
6041
+ needsFixture: true
6042
+ }),
6043
+ oauth({
6044
+ id: "oauth-e2e-token-works",
6045
+ title: "A token issued for the server is accepted",
6046
+ 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.",
6047
+ level: "MUST",
6048
+ derived: true,
6049
+ 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.',
6050
+ specRefs: [ref2(L, AUTH, "Token Handling"), ref2(M, AUTH, "Token Handling")],
6051
+ eras: BOTH2,
6052
+ needsFixture: true
6053
+ }),
6054
+ oauth({
6055
+ id: "oauth-neg-insufficient-scope",
6056
+ title: "A token with too narrow a scope gets 403 with insufficient_scope",
6057
+ 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.',
6058
+ level: "SHOULD",
6059
+ derived: true,
6060
+ 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.`,
6061
+ specRefs: [
6062
+ ref2(L, AUTH, "Runtime Insufficient Scope Errors"),
6063
+ ref2(M, AUTH, "Runtime Insufficient Scope Errors")
6064
+ ],
6065
+ eras: BOTH2,
6066
+ needsFixture: true
6067
+ }),
6068
+ oauth({
6069
+ id: "oauth-authz-response-iss",
6070
+ title: "iss in the authorization response is the issuer, and is advertised",
6071
+ 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.',
6072
+ level: "MUST",
6073
+ derived: true,
6074
+ 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.',
6075
+ specRefs: [ref2(M, AUTH, "Authorization Response Validation")],
6076
+ eras: MODERN,
6077
+ needsFixture: true
6078
+ }),
6079
+ oauth({
6080
+ id: "oauth-neg-pkce-wrong-verifier",
6081
+ title: "A code exchanged with a wrong code_verifier is refused",
6082
+ 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.',
6083
+ level: "MUST",
6084
+ derived: true,
6085
+ 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.',
6086
+ specRefs: [
6087
+ ref2(L, AUTH, "Authorization Code Protection"),
6088
+ ref2(M, SECURITY, "Authorization Code Protection")
6089
+ ],
6090
+ eras: BOTH2,
6091
+ needsFixture: true
6092
+ }),
6093
+ oauth({
6094
+ id: "oauth-neg-token-redirect-mismatch",
6095
+ title: "A code exchanged with another redirect_uri is refused as such",
6096
+ 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).',
6097
+ level: "MUST",
6098
+ derived: true,
6099
+ 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.',
6100
+ specRefs: [ref2(L, AUTH, "Open Redirection"), ref2(M, SECURITY, "Open Redirection")],
6101
+ eras: BOTH2,
6102
+ needsFixture: true
6103
+ }),
6104
+ oauth({
6105
+ id: "oauth-reg-prereg",
6106
+ title: "A pre-registered client is accepted",
6107
+ 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.",
6108
+ level: "SHOULD",
6109
+ derived: true,
6110
+ 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.',
6111
+ specRefs: [ref2(L, AUTH, "Preregistration"), ref2(M, REGISTRATION, "Pre-registration")],
6112
+ eras: BOTH2
6113
+ }),
6114
+ oauth({
6115
+ id: "oauth-reg-dcr",
6116
+ title: "Dynamic client registration works",
6117
+ 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.",
6118
+ level: "MAY",
6119
+ specRefs: [
6120
+ ref2(L, AUTH, "Dynamic Client Registration"),
6121
+ ref2(M, REGISTRATION, "Dynamic Client Registration")
6122
+ ],
6123
+ eras: BOTH2
6124
+ }),
6125
+ oauth({
6126
+ id: "oauth-reg-dcr-http-redirect-rejected",
6127
+ title: "A redirect over http outside loopback is not registered",
6128
+ 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.",
6129
+ level: "MUST",
6130
+ derived: true,
6131
+ 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.',
6132
+ specRefs: [
6133
+ ref2(L, AUTH, "Communication Security"),
6134
+ ref2(L, AUTH, "Open Redirection"),
6135
+ ref2(M, SECURITY, "Communication Security"),
6136
+ ref2(M, SECURITY, "Open Redirection")
6137
+ ],
6138
+ eras: BOTH2
6139
+ }),
6140
+ oauth({
6141
+ id: "oauth-reg-cimd",
6142
+ title: "A client_id that is a URL is read as a document",
6143
+ 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.",
6144
+ level: "MUST",
6145
+ derived: true,
6146
+ 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.',
6147
+ specRefs: [
6148
+ ref2(L, AUTH, "Client ID Metadata Documents"),
6149
+ ref2(M, REGISTRATION, "Client ID Metadata Documents")
6150
+ ],
6151
+ eras: BOTH2,
6152
+ needsFixture: true
6153
+ }),
6154
+ oauth({
6155
+ id: "oauth-token-format",
6156
+ title: "The token response has access_token and token_type Bearer",
6157
+ 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.",
6158
+ level: "MUST",
6159
+ derived: true,
6160
+ 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.',
6161
+ specRefs: [ref2(L, AUTH, "Token Requirements"), ref2(M, AUTH, "Token Requirements")],
6162
+ eras: BOTH2,
6163
+ needsFixture: true
6164
+ }),
6165
+ oauth({
6166
+ id: "oauth-neg-invalid-client",
6167
+ title: "A client that does not exist is not accepted",
6168
+ 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.",
6169
+ level: "MUST",
6170
+ derived: true,
6171
+ 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).',
6172
+ specRefs: [ref2(L, AUTH, "Open Redirection"), ref2(M, SECURITY, "Open Redirection")],
6173
+ eras: BOTH2,
6174
+ needsFixture: true
6175
+ }),
6176
+ oauth({
6177
+ id: "oauth-neg-authorize-redirect-mismatch",
6178
+ title: "A redirect URI that is not registered is not redirected to",
6179
+ 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.",
6180
+ level: "MUST",
6181
+ derived: false,
6182
+ 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."',
6183
+ specRefs: [ref2(L, AUTH, "Open Redirection"), ref2(M, SECURITY, "Open Redirection")],
6184
+ eras: BOTH2,
6185
+ needsFixture: true
6186
+ })
6187
+ ];
6188
+
6189
+ // src/mcp-testing/conformance/tasks-catalog.ts
6190
+ init_esm_shims();
6191
+ var TASKS_SPEC_URL = "https://github.com/modelcontextprotocol/ext-tasks/blob/main/specification/2026-07-28/tasks.md";
6192
+ var MODERN2 = ["modern"];
6193
+ var ref3 = (section) => ({
6194
+ revision: "2026-07-28",
6195
+ page: "tasks.md",
6196
+ section,
6197
+ url: TASKS_SPEC_URL
6198
+ });
6199
+ var tasks = (s) => ({
6200
+ ...s,
6201
+ suite: "tasks",
6202
+ kind: "check",
6203
+ derived: s.derived ?? false,
6204
+ // Every check reads a task, and a task comes from a tool the user names in --fixture.
6205
+ needsFixture: s.needsFixture ?? true,
6206
+ transports: s.transports ?? ["stdio", "http"],
6207
+ eras: MODERN2
6208
+ });
6209
+ var TASKS_CATALOG = [
6210
+ tasks({
6211
+ id: "tasks-result-type",
6212
+ title: 'A task handle has resultType "task", and no other result has it',
6213
+ 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".',
6214
+ level: "MUST",
6215
+ 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`."',
6216
+ specRefs: [ref3("Polymorphic Results"), ref3("Task Creation")]
6217
+ }),
6218
+ tasks({
6219
+ id: "tasks-undeclared-no-task",
6220
+ title: "A client that did not declare the extension is given no task",
6221
+ 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.",
6222
+ level: "MUST",
6223
+ 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."',
6224
+ specRefs: [ref3("Capability Negotiation")]
6225
+ }),
6226
+ tasks({
6227
+ id: "tasks-undeclared-capability-error",
6228
+ title: "tasks/get, tasks/update and tasks/cancel without the declaration are -32021",
6229
+ 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.",
6230
+ level: "MUST",
6231
+ 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.',
6232
+ specRefs: [ref3("Protocol Errors"), ref3("Capability Negotiation")]
6233
+ }),
6234
+ tasks({
6235
+ id: "tasks-get-status-shape",
6236
+ title: 'tasks/get answers a task with resultType "complete" and the fields of a task',
6237
+ 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.',
6238
+ level: "MUST",
6239
+ derived: true,
6240
+ 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".',
6241
+ specRefs: [ref3("Task Polling"), ref3("Tasks")]
6242
+ }),
6243
+ tasks({
6244
+ id: "tasks-status-payload",
6245
+ title: "completed has a result, failed an error, input_required inputRequests",
6246
+ 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).",
6247
+ level: "MUST",
6248
+ 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."',
6249
+ specRefs: [ref3("Task Polling")]
6250
+ }),
6251
+ tasks({
6252
+ id: "tasks-ttl-poll-integers",
6253
+ title: "ttlMs is an integer or null, pollIntervalMs an integer",
6254
+ 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.",
6255
+ level: "SHOULD",
6256
+ derived: true,
6257
+ 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.',
6258
+ specRefs: [ref3("Tasks")]
6259
+ }),
6260
+ tasks({
6261
+ id: "tasks-unknown-id-get",
6262
+ title: "tasks/get for an unknown taskId is -32602",
6263
+ 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).",
6264
+ level: "MUST",
6265
+ derivation: 'Protocol Errors: "Invalid or nonexistent `taskId`: `-32602` (Invalid params)" and "Servers **MUST** return this error for `tasks/get`."',
6266
+ specRefs: [ref3("Protocol Errors")]
6267
+ }),
6268
+ tasks({
6269
+ id: "tasks-unknown-id-update-cancel",
6270
+ title: "tasks/update and tasks/cancel for an unknown taskId are -32602",
6271
+ 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).",
6272
+ level: "SHOULD",
6273
+ derivation: 'Protocol Errors: "Servers **SHOULD** return this error for `tasks/update` and `tasks/cancel`."',
6274
+ specRefs: [ref3("Protocol Errors")]
6275
+ }),
6276
+ tasks({
6277
+ id: "tasks-cancel-ack",
6278
+ title: "tasks/cancel is acknowledged with an empty result",
6279
+ 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.',
6280
+ level: "MUST",
6281
+ 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."',
6282
+ specRefs: [ref3("Task Cancellation")]
6283
+ }),
6284
+ tasks({
6285
+ id: "tasks-update-ack",
6286
+ title: "tasks/update is acknowledged with an empty result",
6287
+ 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.',
6288
+ level: "MUST",
6289
+ 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."',
6290
+ specRefs: [ref3("Task Update Requests")]
6291
+ }),
6292
+ tasks({
6293
+ id: "tasks-failed-status-message",
6294
+ title: "A failed task has a statusMessage",
6295
+ 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).",
6296
+ level: "SHOULD",
6297
+ 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."',
6298
+ specRefs: [ref3("Task Execution Errors")]
6299
+ }),
6300
+ tasks({
6301
+ id: "tasks-http-name-header",
6302
+ title: "tasks/get with Mcp-Name set to the taskId is accepted",
6303
+ 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).",
6304
+ level: "SHOULD",
6305
+ derived: true,
6306
+ 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.',
6307
+ specRefs: [ref3("Streamable HTTP: Routing Headers")],
6308
+ transports: ["http"]
6309
+ }),
6310
+ tasks({
6311
+ id: "tasks-input-request-keys-unique",
6312
+ title: "An inputRequests key never names two different requests",
6313
+ 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.",
6314
+ level: "MUST",
6315
+ derived: true,
6316
+ 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.',
6317
+ specRefs: [ref3("Task Update Requests")]
6318
+ })
6319
+ ];
6320
+
6321
+ // src/mcp-testing/conformance/catalog.ts
6322
+ var L2 = "2025-11-25";
6323
+ var M2 = "2026-07-28";
6324
+ var BOTH3 = ["legacy", "modern"];
6325
+ var MODERN3 = ["modern"];
6326
+ var ANY = ["stdio", "http"];
6327
+ var check2 = (s) => ({
6328
+ ...s,
6329
+ suite: "protocol",
6330
+ kind: "check",
6331
+ derived: s.derived ?? false,
6332
+ needsFixture: s.needsFixture ?? false
6333
+ });
6334
+ var ref4 = (revision, page, section) => ({ revision, page, section });
6335
+ var unscored = (kind, s) => ({
6336
+ ...check2({ ...s, level: null }),
6337
+ kind
6338
+ });
6339
+ var HTTP = ["http"];
6340
+ var LT = "basic/transports";
6341
+ var MT = "basic/transports/streamable-http";
6342
+ var CATALOG = [
6343
+ // Lifecycle
6344
+ check2({
6345
+ id: "life-initialize-result",
6346
+ title: "initialize answers with protocolVersion, capabilities and serverInfo",
6347
+ description: "The result of initialize holds the protocol version the server chose, its capabilities and its serverInfo.",
6348
+ level: "MUST",
6349
+ specRefs: [ref4(L2, "basic/lifecycle", "Initialization")],
6350
+ eras: ["legacy"],
6351
+ transports: ANY
6352
+ }),
6353
+ check2({
6354
+ id: "life-version-negotiation",
6355
+ title: "The protocol version is negotiated",
6356
+ description: "Asked for a version it supports, the server answers with that version; asked for one it does not, with another version it supports.",
6357
+ level: "MUST",
6358
+ specRefs: [ref4(L2, "basic/lifecycle", "Version Negotiation")],
6359
+ eras: ["legacy"],
6360
+ transports: ANY
6361
+ }),
6362
+ check2({
6363
+ id: "life-capabilities-declared-served",
6364
+ title: "Every declared capability is served",
6365
+ description: "For each capability declared (tools, resources, prompts, logging, completions), the matching request does not answer Method not found (-32601).",
6366
+ level: "MUST",
6367
+ derived: true,
6368
+ derivation: "basic/lifecycle, Operation: only negotiated capabilities are used; the server pages: a server that supports a feature MUST declare its capability.",
6369
+ specRefs: [ref4(L2, "basic/lifecycle", "Operation")],
6370
+ eras: BOTH3,
6371
+ transports: ANY
6372
+ }),
6373
+ check2({
6374
+ id: "life-capabilities-served-declared",
6375
+ title: "Every served list is declared",
6376
+ description: "When tools/list, resources/list or prompts/list answers, the matching capability is declared.",
6377
+ level: "MUST",
6378
+ specRefs: [
6379
+ ref4(L2, "server/tools", "Capabilities"),
6380
+ ref4(L2, "server/resources", "Capabilities"),
6381
+ ref4(L2, "server/prompts", "Capabilities")
6382
+ ],
6383
+ eras: BOTH3,
6384
+ transports: ANY
6385
+ }),
6386
+ check2({
6387
+ id: "life-ping-empty-result",
6388
+ title: "ping answers with an empty result",
6389
+ description: "ping is answered promptly with result: {}.",
6390
+ level: "MUST",
6391
+ specRefs: [ref4(L2, "basic/utilities/ping", "Behavior Requirements")],
6392
+ eras: ["legacy"],
6393
+ transports: ANY
6394
+ }),
6395
+ // The 2026-07-28 revision: server/discover and the per-request metadata, run first (the rest stands on discover).
6396
+ check2({
6397
+ id: "mod-discover-result",
6398
+ title: "server/discover answers a complete DiscoverResult",
6399
+ 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).',
6400
+ level: "MUST",
6401
+ specRefs: [ref4(M2, "server/discover", "Discovery"), ref4(M2, "basic/versioning", "Protocol Version Negotiation")],
6402
+ eras: MODERN3,
6403
+ transports: ANY
6404
+ }),
6405
+ check2({
6406
+ id: "mod-discover-server-info",
6407
+ title: "server/discover names the server in _meta",
6408
+ description: 'The DiscoverResult has _meta["io.modelcontextprotocol/serverInfo"] with a name and a version.',
6409
+ level: "SHOULD",
6410
+ specRefs: [ref4(M2, "server/discover", "DiscoverResult"), ref4(M2, "basic/index", "_meta")],
6411
+ eras: MODERN3,
6412
+ transports: ANY
6413
+ }),
6414
+ check2({
6415
+ id: "mod-meta-required-fields",
6416
+ title: "A request without a required _meta field is Invalid params",
6417
+ 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.",
6418
+ level: "MUST",
6419
+ specRefs: [ref4(M2, "basic/index", "_meta"), ref4(M2, MT, "Server Validation")],
6420
+ eras: MODERN3,
6421
+ transports: ANY
6422
+ }),
6423
+ check2({
6424
+ id: "mod-unsupported-version",
6425
+ title: "An unsupported protocol version is UnsupportedProtocolVersion",
6426
+ description: "server/discover for revision 1900-01-01 gets -32022 with data.supported, a non-empty list; over HTTP with status 400.",
6427
+ level: "MUST",
6428
+ specRefs: [ref4(M2, "basic/versioning", "Protocol Version Negotiation"), ref4(M2, MT, "Protocol Version Header")],
6429
+ eras: MODERN3,
6430
+ transports: ANY
6431
+ }),
6432
+ // Base protocol
6433
+ check2({
6434
+ id: "base-jsonrpc-parse-error",
6435
+ title: "Invalid JSON is a parse error",
6436
+ 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).",
6437
+ level: "MUST",
6438
+ derived: true,
6439
+ 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.",
6440
+ specRefs: [ref4(L2, "basic/index", "Messages")],
6441
+ eras: BOTH3,
6442
+ transports: HTTP
6443
+ }),
6444
+ unscored("advice", {
6445
+ id: "stdio-parse-error-advice",
6446
+ title: "Invalid JSON on stdio is answered with a parse error (advice)",
6447
+ 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.`,
6448
+ specRefs: [ref4(L2, LT, "stdio")],
6449
+ eras: BOTH3,
6450
+ transports: ["stdio"]
6451
+ }),
6452
+ check2({
6453
+ id: "base-unknown-method-error",
6454
+ title: "An unknown method is Method not found",
6455
+ description: "A request for a method the server does not have gets the error -32601.",
6456
+ level: "MUST",
6457
+ derived: true,
6458
+ 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.",
6459
+ specRefs: [ref4(L2, "basic/index", "Messages")],
6460
+ eras: BOTH3,
6461
+ transports: ANY
6462
+ }),
6463
+ check2({
6464
+ id: "base-response-id-matches",
6465
+ title: "A response carries the id of its request",
6466
+ 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.",
6467
+ level: "MUST",
6468
+ specRefs: [ref4(L2, "basic/index", "Responses"), ref4(M2, "basic/index", "Responses")],
6469
+ eras: BOTH3,
6470
+ transports: ANY
6471
+ }),
6472
+ check2({
6473
+ id: "base-invalid-params-error",
6474
+ title: "Plainly wrong parameters are Invalid params",
6475
+ description: "A request with plainly wrong parameters (tools/call without name) gets -32602, not -32603 and not a result.",
6476
+ level: "SHOULD",
6477
+ specRefs: [ref4(L2, "server/tools", "Error Handling")],
6478
+ eras: BOTH3,
6479
+ transports: ANY
6480
+ }),
6481
+ // Tools
6482
+ check2({
6483
+ id: "tools-list-shape",
6484
+ title: "Every listed tool has a name and an inputSchema object",
6485
+ description: "Each entry of tools/list has a string name and an inputSchema that is an object, not null.",
6486
+ level: "MUST",
6487
+ specRefs: [ref4(L2, "server/tools", "Tool")],
6488
+ eras: BOTH3,
6489
+ transports: ANY
6490
+ }),
6491
+ check2({
6492
+ id: "tools-input-schema-valid",
6493
+ title: "Every inputSchema is a valid object schema",
6494
+ 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.',
6495
+ level: "MUST",
6496
+ specRefs: [ref4(L2, "basic/index", "JSON Schema Usage")],
6497
+ eras: BOTH3,
6498
+ transports: ANY
6499
+ }),
6500
+ check2({
6501
+ id: "tools-output-schema-valid",
6502
+ title: "Every outputSchema is a valid schema",
6503
+ description: "An outputSchema, when given, is valid in its dialect; before 2026-07-28 its root is an object, from then on any type.",
6504
+ level: "MUST",
6505
+ specRefs: [ref4(L2, "server/tools", "Output Schema"), ref4(M2, "changelog", "Minor changes")],
6506
+ eras: BOTH3,
6507
+ transports: ANY
6508
+ }),
6509
+ check2({
6510
+ id: "tools-structured-conformant",
6511
+ title: "structuredContent conforms to the outputSchema",
6512
+ description: "The structuredContent of a call (from the fixture) conforms to the tool's outputSchema.",
6513
+ level: "MUST",
6514
+ specRefs: [ref4(L2, "server/tools", "Output Schema")],
6515
+ eras: BOTH3,
6516
+ transports: ANY,
6517
+ needsFixture: true
6518
+ }),
6519
+ check2({
6520
+ id: "tools-structured-has-text",
6521
+ title: "structuredContent is also given as text",
6522
+ description: "A result with structuredContent also has a text block with the serialized JSON.",
6523
+ level: "SHOULD",
6524
+ specRefs: [ref4(L2, "server/tools", "Structured Content")],
6525
+ eras: BOTH3,
6526
+ transports: ANY,
6527
+ needsFixture: true
6528
+ }),
6529
+ check2({
6530
+ id: "tools-name-format",
6531
+ title: "Tool names use the allowed characters",
6532
+ description: "Each tool name is 1 to 128 characters of A-Z, a-z, 0-9, _, - and ., without spaces or commas.",
6533
+ level: "SHOULD",
6534
+ specRefs: [ref4(L2, "server/tools", "Tool Names")],
6535
+ eras: BOTH3,
6536
+ transports: ANY
6537
+ }),
6538
+ check2({
6539
+ id: "tools-name-unique",
6540
+ title: "Tool names are unique",
6541
+ description: "No two tools of the server share a name, across every page of tools/list.",
6542
+ level: "SHOULD",
6543
+ specRefs: [ref4(L2, "server/tools", "Tool Names")],
6544
+ eras: BOTH3,
6545
+ transports: ANY
6546
+ }),
6547
+ check2({
6548
+ id: "tools-call-unknown-error",
6549
+ title: "Calling an unknown tool is a protocol error",
6550
+ description: "tools/call for a tool that does not exist gets a JSON-RPC error, not a result with isError.",
6551
+ level: "SHOULD",
6552
+ specRefs: [ref4(L2, "server/tools", "Error Handling")],
6553
+ eras: BOTH3,
6554
+ transports: ANY
6555
+ }),
6556
+ check2({
6557
+ id: "tools-list-order-stable",
6558
+ title: "tools/list keeps its order",
6559
+ description: "Two calls of tools/list give the tools in the same order.",
6560
+ level: "SHOULD",
6561
+ specRefs: [ref4(M2, "server/tools", "Capabilities")],
6562
+ eras: ["modern"],
6563
+ transports: ANY
6564
+ }),
6565
+ // Resources
6566
+ check2({
6567
+ id: "resources-list-shape",
6568
+ title: "Every listed resource has a uri and a name",
6569
+ description: "Each entry of resources/list has uri and name.",
6570
+ level: "MUST",
6571
+ derived: true,
6572
+ derivation: 'server/resources, Resource: uri and name are listed without "Optional"; no keyword.',
6573
+ specRefs: [ref4(L2, "server/resources", "Resource")],
6574
+ eras: BOTH3,
6575
+ transports: ANY
6576
+ }),
6577
+ check2({
6578
+ id: "resources-read-listed",
6579
+ title: "A listed resource can be read",
6580
+ description: "resources/read of the first listed resource answers with contents, each with a uri and exactly one of text and blob.",
6581
+ level: "MUST",
6582
+ derived: true,
6583
+ derivation: "server/resources, Resource Contents: a content is text or binary data under its uri; no keyword.",
6584
+ specRefs: [ref4(L2, "server/resources", "Resource Contents")],
6585
+ eras: BOTH3,
6586
+ transports: ANY
6587
+ }),
6588
+ check2({
6589
+ id: "resources-read-not-found",
6590
+ title: "Reading an unknown resource is an error",
6591
+ description: "resources/read of a uri that does not exist gets -32002, not empty contents.",
6592
+ level: "SHOULD",
6593
+ specRefs: [ref4(L2, "server/resources", "Error Handling")],
6594
+ eras: ["legacy"],
6595
+ transports: ANY
6596
+ }),
6597
+ check2({
6598
+ id: "resources-templates-shape",
6599
+ title: "Every resource template has a uriTemplate and a name",
6600
+ description: "Each entry of resources/templates/list has uriTemplate and name.",
6601
+ level: "MUST",
6602
+ derived: true,
6603
+ derivation: "server/resources, Resource Templates: every example template has uriTemplate and name; no keyword.",
6604
+ specRefs: [ref4(L2, "server/resources", "Resource Templates")],
6605
+ eras: BOTH3,
6606
+ transports: ANY
6607
+ }),
6608
+ // Prompts
6609
+ check2({
6610
+ id: "prompts-list-shape",
6611
+ title: "Every listed prompt has a name",
6612
+ description: "Each entry of prompts/list has name; arguments, when given, is a list of objects with name.",
6613
+ level: "MUST",
6614
+ derived: true,
6615
+ derivation: 'server/prompts, Prompt: name is listed without "Optional", arguments is optional; no keyword.',
6616
+ specRefs: [ref4(L2, "server/prompts", "Prompt")],
6617
+ eras: BOTH3,
6618
+ transports: ANY
6619
+ }),
6620
+ check2({
6621
+ id: "prompts-get-unknown-error",
6622
+ title: "Getting an unknown prompt is an error",
6623
+ description: "prompts/get with a name that does not exist gets a JSON-RPC error.",
6624
+ level: "SHOULD",
6625
+ specRefs: [ref4(L2, "server/prompts", "Error Handling")],
6626
+ eras: BOTH3,
6627
+ transports: ANY
6628
+ }),
6629
+ // Pagination
6630
+ check2({
6631
+ id: "pagination-walk-complete",
6632
+ title: "Paging through a list ends, without repeats",
6633
+ description: "Following nextCursor ends within the page limit and no entry comes back on a later page.",
6634
+ level: "SHOULD",
6635
+ specRefs: [ref4(L2, "server/utilities/pagination", "Implementation Guidelines")],
6636
+ eras: BOTH3,
6637
+ transports: ANY
6638
+ }),
6639
+ check2({
6640
+ id: "pagination-invalid-cursor",
6641
+ title: "An invalid cursor is Invalid params",
6642
+ description: "A list request with a cursor the server never gave gets -32602.",
6643
+ level: "SHOULD",
6644
+ specRefs: [ref4(L2, "server/utilities/pagination", "Error Handling")],
6645
+ eras: BOTH3,
6646
+ transports: ANY
6647
+ }),
6648
+ // Utilities
6649
+ check2({
6650
+ id: "logging-set-level",
6651
+ title: "logging/setLevel is accepted when logging is declared",
6652
+ description: "A server that declares logging accepts logging/setLevel.",
6653
+ level: "SHOULD",
6654
+ derived: true,
6655
+ derivation: "server/utilities/logging: the MUST is on declaring the capability, not on handling logging/setLevel, so handling it is a SHOULD.",
6656
+ specRefs: [ref4(L2, "server/utilities/logging", "Capabilities")],
6657
+ eras: ["legacy"],
6658
+ transports: ANY
6659
+ }),
6660
+ check2({
6661
+ id: "completion-complete",
6662
+ title: "completion/complete answers when completions is declared",
6663
+ description: "A server that declares completions answers completion/complete with a valid result.",
6664
+ level: "SHOULD",
6665
+ derived: true,
6666
+ 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.",
6667
+ specRefs: [ref4(L2, "server/utilities/completion", "Capabilities")],
6668
+ eras: BOTH3,
6669
+ transports: ANY
6670
+ }),
6671
+ // The 2026-07-28 revision: what changed for every transport.
6672
+ check2({
6673
+ id: "mod-removed-methods",
6674
+ title: "The methods the revision removed are Method not found",
6675
+ 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.",
6676
+ level: "MUST",
6677
+ derived: true,
6678
+ 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.",
6679
+ specRefs: [ref4(M2, "changelog", "Major changes"), ref4(M2, MT, "Protocol Version Header")],
6680
+ eras: MODERN3,
6681
+ transports: ANY
6682
+ }),
6683
+ check2({
6684
+ id: "mod-stateless-no-prior-context",
6685
+ title: "A list answers on a fresh connection with no request before it",
6686
+ 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.",
6687
+ level: "MUST",
6688
+ specRefs: [ref4(M2, "basic/index", "Statelessness")],
6689
+ eras: MODERN3,
6690
+ transports: ANY
6691
+ }),
6692
+ check2({
6693
+ id: "mod-list-stable-across-connections",
6694
+ title: "The lists do not vary per connection",
6695
+ 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.",
6696
+ level: "MUST",
6697
+ specRefs: [
6698
+ ref4(M2, "server/tools", "Capabilities"),
6699
+ ref4(M2, "server/prompts", "Capabilities"),
6700
+ ref4(M2, "server/resources", "Capabilities")
6701
+ ],
6702
+ eras: MODERN3,
6703
+ transports: ANY
6704
+ }),
6705
+ check2({
6706
+ id: "mod-resource-not-found",
6707
+ title: "Reading an unknown resource is Invalid params",
6708
+ description: "resources/read of a uri that does not exist gets -32602; -32002, the code of earlier revisions, fails.",
6709
+ level: "MUST",
6710
+ specRefs: [ref4(M2, "server/resources", "Error Handling"), ref4(M2, "basic/index", "Error Codes")],
6711
+ eras: MODERN3,
6712
+ transports: ANY
6713
+ }),
6714
+ check2({
6715
+ id: "mod-resource-no-empty-contents",
6716
+ title: "An unknown resource is not empty contents",
6717
+ description: "resources/read of a uri that does not exist does not answer a result with an empty contents list.",
6718
+ level: "MUST",
6719
+ specRefs: [ref4(M2, "server/resources", "Error Handling")],
6720
+ eras: MODERN3,
6721
+ transports: ANY
6722
+ }),
6723
+ check2({
6724
+ id: "mod-cache-hints-coverage",
6725
+ title: "Every cacheable result has ttlMs and cacheScope",
6726
+ 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.",
6727
+ level: "MUST",
6728
+ specRefs: [ref4(M2, "server/utilities/caching", "Cacheable Results")],
6729
+ eras: MODERN3,
6730
+ transports: ANY
6731
+ }),
6732
+ check2({
6733
+ id: "mod-cache-ttl-valid",
6734
+ title: "ttlMs is an integer of at least 0",
6735
+ description: "Every ttlMs on those results is an integer number of milliseconds, 0 or more.",
6736
+ level: "MUST",
6737
+ specRefs: [ref4(M2, "server/utilities/caching", "Time-to-Live (TTL) Field")],
6738
+ eras: MODERN3,
6739
+ transports: ANY
6740
+ }),
6741
+ check2({
6742
+ id: "mod-cache-scope-valid",
6743
+ title: 'cacheScope is "public" or "private"',
6744
+ description: 'Every cacheScope on those results is exactly "public" or "private".',
6745
+ level: "MUST",
6746
+ derived: true,
6747
+ 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.',
6748
+ specRefs: [ref4(M2, "server/utilities/caching", "Cache Scope Field")],
6749
+ eras: MODERN3,
6750
+ transports: ANY
6751
+ }),
6752
+ check2({
6753
+ id: "mod-cache-scope-stable-pages",
6754
+ title: "All pages of a list have the same cacheScope",
6755
+ description: "Every page of a paginated list carries the cacheScope of its first page. Without a list of two pages, not-applicable.",
6756
+ level: "MUST",
6757
+ specRefs: [ref4(M2, "server/utilities/caching", "Interaction with Pagination")],
6758
+ eras: MODERN3,
6759
+ transports: ANY
6760
+ }),
6761
+ check2({
6762
+ id: "mod-undeclared-capability",
6763
+ title: "A capability the client did not declare is asked for with -32021",
6764
+ 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).',
6765
+ level: "MUST",
6766
+ specRefs: [ref4(M2, "basic/index", "_meta")],
6767
+ eras: MODERN3,
6768
+ transports: ANY,
6769
+ needsFixture: true
6770
+ }),
6771
+ // Subscriptions: one subscriptions/listen per run, watched for a short time and then cancelled.
6772
+ check2({
6773
+ id: "mod-sub-ack-first",
6774
+ title: "A subscription is acknowledged first",
6775
+ 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.",
6776
+ level: "MUST",
6777
+ specRefs: [ref4(M2, "basic/patterns/subscriptions", "Acknowledgment")],
6778
+ eras: MODERN3,
6779
+ transports: ANY
6780
+ }),
6781
+ check2({
6782
+ id: "mod-sub-filter-and-tag",
6783
+ title: "A subscription gets only what it asked for, each tagged",
6784
+ 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).",
6785
+ level: "MUST",
6786
+ specRefs: [ref4(M2, "basic/patterns/subscriptions", "Opening a Stream"), ref4(M2, "basic/index", "_meta")],
6787
+ eras: MODERN3,
6788
+ transports: ANY
6789
+ }),
6790
+ check2({
6791
+ id: "mod-sub-graceful-close",
6792
+ title: "A subscription the server ends gets a successful response",
6793
+ 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).",
6794
+ level: "SHOULD",
6795
+ specRefs: [ref4(M2, "basic/patterns/subscriptions", "Graceful Closure")],
6796
+ eras: MODERN3,
6797
+ transports: ANY
6798
+ }),
6799
+ // Streamable HTTP on the wire: raw requests, never an MCP client (../raw-http.ts).
6800
+ check2({
6801
+ id: "http-notification-202",
6802
+ title: "A notification POST is 202 with no body, or an error status",
6803
+ 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.",
6804
+ level: "MUST",
6805
+ specRefs: [ref4(L2, LT, "Sending Messages to the Server"), ref4(M2, MT, "Sending Messages")],
6806
+ eras: BOTH3,
6807
+ transports: HTTP
6808
+ }),
6809
+ check2({
6810
+ id: "http-request-content-type",
6811
+ title: "A request is answered as application/json or text/event-stream",
6812
+ description: "The answer to a JSON-RPC request has Content-Type application/json or text/event-stream.",
6813
+ level: "MUST",
6814
+ specRefs: [ref4(L2, LT, "Sending Messages to the Server"), ref4(M2, MT, "Sending Messages")],
6815
+ eras: BOTH3,
6816
+ transports: HTTP
6817
+ }),
6818
+ check2({
6819
+ id: "http-response-utf8",
6820
+ title: "The answer is UTF-8 JSON",
6821
+ 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.",
6822
+ level: "MUST",
6823
+ specRefs: [ref4(L2, LT, "Transports")],
6824
+ eras: BOTH3,
6825
+ transports: HTTP
6826
+ }),
6827
+ check2({
6828
+ id: "http-single-endpoint",
6829
+ title: "The MCP endpoint takes POST",
6830
+ description: "The URL under test takes a valid JSON-RPC request by POST: not 404 (other than a JSON-RPC -32601) and not 405.",
6831
+ level: "MUST",
6832
+ specRefs: [ref4(L2, LT, "Streamable HTTP"), ref4(M2, MT, "Streamable HTTP")],
6833
+ eras: BOTH3,
6834
+ transports: HTTP
6835
+ }),
6836
+ check2({
6837
+ id: "http-get-stream-or-405",
6838
+ title: "GET opens an SSE stream or is 405",
6839
+ description: "A GET with Accept: text/event-stream gets Content-Type text/event-stream or 405 Method Not Allowed.",
6840
+ level: "MUST",
6841
+ specRefs: [ref4(L2, LT, "Listening for Messages from the Server")],
6842
+ eras: ["legacy"],
6843
+ transports: HTTP
6844
+ }),
6845
+ check2({
6846
+ id: "http-modern-get-delete-405",
6847
+ title: "A modern-only server answers GET and DELETE with 405",
6848
+ 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.",
6849
+ level: "SHOULD",
6850
+ specRefs: [ref4(M2, MT, "Earlier Streamable HTTP Revisions")],
6851
+ eras: ["modern"],
6852
+ transports: HTTP
6853
+ }),
6854
+ check2({
6855
+ id: "http-session-id-visible-ascii",
6856
+ title: "A session id is visible ASCII",
6857
+ description: "An MCP-Session-Id the server assigns holds only characters 0x21 to 0x7E. Without one, not-applicable.",
6858
+ level: "MUST",
6859
+ specRefs: [ref4(L2, LT, "Session Management")],
6860
+ eras: ["legacy"],
6861
+ transports: HTTP
6862
+ }),
6863
+ check2({
6864
+ id: "http-session-required-400",
6865
+ title: "A request without the session id is 400",
6866
+ description: "When the server assigned a session id, a request other than initialize without MCP-Session-Id gets 400 Bad Request.",
6867
+ level: "SHOULD",
6868
+ specRefs: [ref4(L2, LT, "Session Management")],
6869
+ eras: ["legacy"],
6870
+ transports: HTTP
6871
+ }),
6872
+ check2({
6873
+ id: "http-protocol-version-header-invalid-400",
6874
+ title: "An invalid MCP-Protocol-Version is 400",
6875
+ description: "A request after initialize with an MCP-Protocol-Version that is not a revision gets 400 Bad Request.",
6876
+ level: "MUST",
6877
+ specRefs: [ref4(L2, LT, "Protocol Version Header")],
6878
+ eras: ["legacy"],
6879
+ transports: HTTP
6880
+ }),
6881
+ check2({
6882
+ id: "http-concurrent-posts-matched",
6883
+ title: "Concurrent POSTs each get their own answer",
6884
+ description: "Several POSTs sent at once, each with its own id, are each answered with the id of their request.",
6885
+ level: "MUST",
6886
+ derived: true,
6887
+ 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.",
6888
+ specRefs: [ref4(L2, LT, "Sending Messages to the Server"), ref4(M2, "basic/index", "Responses")],
6889
+ eras: BOTH3,
6890
+ transports: HTTP
6891
+ }),
6892
+ check2({
6893
+ id: "http-sse-event-ids-unique",
6894
+ title: "SSE event ids are unique in the session",
6895
+ description: "When the server gives SSE events an id, no id comes back twice across the streams of the session. Without ids, not-applicable.",
6896
+ level: "MUST",
6897
+ specRefs: [ref4(L2, LT, "Resumability and Redelivery")],
6898
+ eras: ["legacy"],
6899
+ transports: HTTP
6900
+ }),
6901
+ check2({
6902
+ id: "http-sse-stream-closes",
6903
+ title: "The SSE stream of a request ends after its response",
6904
+ description: "When a request is answered over SSE, the server closes the stream once the response is sent.",
6905
+ level: "SHOULD",
6906
+ specRefs: [ref4(L2, LT, "Sending Messages to the Server"), ref4(M2, MT, "Receiving Messages")],
6907
+ eras: BOTH3,
6908
+ transports: HTTP
6909
+ }),
6910
+ check2({
6911
+ id: "http-sse-no-server-requests",
6912
+ title: "The SSE stream of a request holds no request of the server",
6913
+ description: "The SSE answer to a request holds its response and notifications, never a JSON-RPC request of the server.",
6914
+ level: "MUST",
6915
+ specRefs: [ref4(M2, MT, "Receiving Messages")],
6916
+ eras: ["modern"],
6917
+ transports: HTTP
6918
+ }),
6919
+ check2({
6920
+ id: "http-accel-buffering-header",
6921
+ title: "An SSE answer sends X-Accel-Buffering: no",
6922
+ description: "A response that opens an SSE stream has the header X-Accel-Buffering: no.",
6923
+ level: "SHOULD",
6924
+ specRefs: [ref4(M2, MT, "Receiving Messages")],
6925
+ eras: ["modern"],
6926
+ transports: HTTP
6927
+ }),
6928
+ check2({
6929
+ id: "http-close-cancels",
6930
+ title: "Closing the SSE stream cancels the request",
6931
+ 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).",
6932
+ level: "MUST",
6933
+ specRefs: [ref4(M2, MT, "Cancellation")],
6934
+ eras: ["modern"],
6935
+ transports: HTTP,
6936
+ needsFixture: true
6937
+ }),
6938
+ // The request headers of the 2026-07-28 revision, each probe a POST of its own.
6939
+ check2({
6940
+ id: "mod-unimplemented-method",
6941
+ title: "An unknown method over HTTP is 404 with -32601",
6942
+ description: "A POST of a method the server does not implement gets 404 Not Found and the JSON-RPC error -32601.",
6943
+ level: "MUST",
6944
+ specRefs: [ref4(M2, MT, "Protocol Version Header")],
6945
+ eras: MODERN3,
6946
+ transports: HTTP
6947
+ }),
6948
+ check2({
6949
+ id: "mod-header-protocol-version-mismatch",
6950
+ title: "An MCP-Protocol-Version unlike the body is HeaderMismatch",
6951
+ description: "server/discover with MCP-Protocol-Version: 2025-11-25 and 2026-07-28 in _meta gets 400 and -32020.",
6952
+ level: "MUST",
6953
+ specRefs: [ref4(M2, MT, "Protocol Version Header"), ref4(M2, MT, "Server Validation")],
6954
+ eras: MODERN3,
6955
+ transports: HTTP
6956
+ }),
6957
+ check2({
6958
+ id: "mod-header-method-mismatch",
6959
+ title: "An Mcp-Method unlike the body is HeaderMismatch",
6960
+ description: "server/discover sent with Mcp-Method: tools/list gets 400 and -32020.",
6961
+ level: "MUST",
6962
+ specRefs: [ref4(M2, MT, "Server Validation")],
6963
+ eras: MODERN3,
6964
+ transports: HTTP
6965
+ }),
6966
+ check2({
6967
+ id: "mod-header-name-mismatch",
6968
+ title: "An Mcp-Name unlike the body is HeaderMismatch",
6969
+ 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.",
6970
+ level: "MUST",
6971
+ specRefs: [ref4(M2, MT, "Standard Request Headers"), ref4(M2, MT, "Server Validation"), ref4(M2, MT, "Case Sensitivity")],
6972
+ eras: MODERN3,
6973
+ transports: HTTP
6974
+ }),
6975
+ check2({
6976
+ id: "mod-header-missing-rejected",
6977
+ title: "A request without a required header is HeaderMismatch",
6978
+ 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.",
6979
+ level: "MUST",
6980
+ specRefs: [ref4(M2, MT, "Server Validation"), ref4(M2, MT, "Standard Request Headers"), ref4(M2, MT, "Protocol Version Header")],
6981
+ eras: MODERN3,
6982
+ transports: HTTP
6983
+ }),
6984
+ check2({
6985
+ id: "mod-header-names-case-insensitive",
6986
+ title: "Header names are read in any case",
6987
+ 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.",
6988
+ level: "MUST",
6989
+ specRefs: [ref4(M2, MT, "Case Sensitivity")],
6990
+ eras: MODERN3,
6991
+ transports: HTTP
6992
+ }),
6993
+ check2({
6994
+ id: "mod-header-name-base64-decoded",
6995
+ title: "A Base64 Mcp-Name is decoded before it is compared",
6996
+ 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.",
6997
+ level: "MUST",
6998
+ specRefs: [ref4(M2, MT, "Value Encoding")],
6999
+ eras: MODERN3,
7000
+ transports: HTTP
7001
+ }),
7002
+ check2({
7003
+ id: "mod-param-header-mismatch",
7004
+ title: "An Mcp-Param header unlike the body, or missing, is HeaderMismatch",
7005
+ 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.",
7006
+ level: "MUST",
7007
+ specRefs: [ref4(M2, MT, "Server Behavior for Custom Headers")],
7008
+ eras: MODERN3,
7009
+ transports: HTTP,
7010
+ needsFixture: true
7011
+ }),
7012
+ check2({
7013
+ id: "mod-x-mcp-header-declarations",
7014
+ title: "Every x-mcp-header declaration is valid",
7015
+ 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.",
7016
+ level: "MUST",
7017
+ specRefs: [ref4(M2, "server/tools", "x-mcp-header"), ref4(M2, MT, "Schema Extension")],
7018
+ eras: MODERN3,
7019
+ transports: HTTP
7020
+ }),
7021
+ check2({
7022
+ id: "mod-no-session-id",
7023
+ title: "A modern-only server neither mints nor echoes a session id",
7024
+ 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.",
7025
+ level: "SHOULD",
7026
+ specRefs: [ref4(M2, MT, "Earlier Streamable HTTP Revisions")],
7027
+ eras: MODERN3,
7028
+ transports: HTTP
7029
+ }),
7030
+ // These two change the server's state, each in a session of its own made for it, so they come last.
7031
+ check2({
7032
+ id: "http-session-terminated-404",
7033
+ title: "A terminated session is 404",
7034
+ 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.",
7035
+ level: "MUST",
7036
+ specRefs: [ref4(L2, LT, "Session Management")],
7037
+ eras: ["legacy"],
7038
+ transports: HTTP
7039
+ }),
7040
+ check2({
7041
+ id: "http-sse-no-broadcast",
7042
+ title: "A message goes to one SSE stream, not to each",
7043
+ description: "With two GET streams open, a message of the server (made by the first --fixture call) arrives on one of them only.",
7044
+ level: "MUST",
7045
+ specRefs: [ref4(L2, LT, "Multiple Connections")],
7046
+ eras: ["legacy"],
7047
+ transports: HTTP,
7048
+ needsFixture: true
7049
+ }),
7050
+ // A local server against DNS rebinding: only for localhost, 127.0.0.1, [::1] and *.localhost.
7051
+ check2({
7052
+ id: "http-origin-invalid-403",
7053
+ title: "A foreign Origin is refused with 403",
7054
+ 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).",
7055
+ level: "MUST",
7056
+ specRefs: [ref4(L2, LT, "Security Warning"), ref4(M2, MT, "Security & Endpoint")],
7057
+ eras: BOTH3,
7058
+ transports: HTTP
7059
+ }),
7060
+ unscored("control", {
7061
+ id: "http-origin-localhost-accepted",
7062
+ title: "An Origin of localhost is accepted",
7063
+ 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.",
7064
+ specRefs: [ref4(L2, LT, "Security Warning"), ref4(M2, MT, "Security & Endpoint")],
7065
+ eras: BOTH3,
7066
+ transports: HTTP
7067
+ }),
7068
+ unscored("control", {
7069
+ id: "http-origin-absent-accepted",
7070
+ title: "A request without Origin is accepted",
7071
+ description: "A request with no Origin (not from a browser) is accepted: the specification speaks only of an Origin that is present and invalid.",
7072
+ specRefs: [ref4(L2, LT, "Security Warning"), ref4(M2, MT, "Security & Endpoint")],
7073
+ eras: BOTH3,
7074
+ transports: HTTP
7075
+ }),
7076
+ check2({
7077
+ id: "http-bind-loopback",
7078
+ title: "A local server listens on loopback only",
7079
+ 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).",
7080
+ level: "SHOULD",
7081
+ specRefs: [ref4(L2, LT, "Security Warning"), ref4(M2, MT, "Security & Endpoint")],
7082
+ eras: BOTH3,
7083
+ transports: HTTP
7084
+ }),
7085
+ unscored("advice", {
7086
+ id: "http-host-rebinding-advice",
7087
+ title: "A foreign Host is refused (advice outside the specification)",
7088
+ 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.",
7089
+ specRefs: [ref4(L2, LT, "Security Warning"), ref4(M2, MT, "Security & Endpoint")],
7090
+ eras: BOTH3,
7091
+ transports: HTTP
7092
+ }),
7093
+ // The 2026-07-28 revision over the whole run: these read every message the run got back, so they come after the rest.
7094
+ check2({
7095
+ id: "mod-result-type-present",
7096
+ title: "Every result has a known resultType",
7097
+ 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.',
7098
+ level: "MUST",
7099
+ specRefs: [ref4(M2, "basic/index", "ResultType")],
7100
+ eras: MODERN3,
7101
+ transports: ANY
7102
+ }),
7103
+ check2({
7104
+ id: "mod-error-code-range",
7105
+ title: "No error code of the reserved range is invented",
7106
+ 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.",
7107
+ level: "MUST",
7108
+ specRefs: [ref4(M2, "basic/index", "Error Codes")],
7109
+ eras: MODERN3,
7110
+ transports: ANY
7111
+ }),
7112
+ check2({
7113
+ id: "mod-logs-need-log-level",
7114
+ title: "No log message for a request without logLevel",
7115
+ 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.",
7116
+ level: "MUST",
7117
+ specRefs: [ref4(M2, "server/utilities/logging", "Per-request log level")],
7118
+ eras: MODERN3,
7119
+ transports: ANY
7120
+ }),
7121
+ check2({
7122
+ id: "mod-wire-schema-valid",
7123
+ title: "Every message conforms to the schema of the revision",
7124
+ 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.",
7125
+ level: "MUST",
7126
+ derived: true,
7127
+ 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.",
7128
+ specRefs: [ref4(M2, "basic/index", "Schema")],
7129
+ eras: MODERN3,
7130
+ transports: ANY
7131
+ }),
7132
+ // stdio
7133
+ check2({
7134
+ id: "stdio-stdout-clean",
7135
+ title: "stdout holds only MCP messages",
7136
+ description: "Every line the server writes to stdout is one whole JSON-RPC message, with no newline inside it.",
7137
+ level: "MUST",
7138
+ specRefs: [ref4(L2, "basic/transports", "stdio"), ref4(M2, "basic/transports/stdio", "stdio")],
7139
+ eras: BOTH3,
7140
+ transports: ["stdio"]
7141
+ }),
7142
+ check2({
7143
+ id: "stdio-exit-on-eof",
7144
+ title: "The server exits when stdin closes",
7145
+ description: "After its stdin is closed the server process ends within a short time.",
7146
+ level: "SHOULD",
7147
+ specRefs: [ref4(M2, "basic/transports/stdio", "Shutdown")],
7148
+ eras: BOTH3,
7149
+ transports: ["stdio"]
7150
+ }),
7151
+ // The oauth suite (auth-catalog.ts)
7152
+ ...OAUTH_CATALOG,
7153
+ // The apps suite (apps-catalog.ts)
7154
+ ...APPS_CATALOG,
7155
+ // The tasks suite (tasks-catalog.ts)
7156
+ ...TASKS_CATALOG
7157
+ ];
7158
+ var BY_ID = new Map(CATALOG.map((e) => [e.id, e]));
7159
+
7160
+ // src/mcp-testing/conformance/profile.ts
7161
+ init_esm_shims();
7162
+ import { createHash as createHash5 } from "crypto";
7163
+
7164
+ // src/mcp-testing/report/human.ts
7165
+ init_exit_codes();
7166
+
7167
+ // src/mcp-testing/snapshot/index.ts
7168
+ init_esm_shims();
7169
+
7170
+ // src/mcp-testing/snapshot/snapshot.ts
7171
+ init_esm_shims();
7172
+
7173
+ // src/mcp-testing/snapshot/diff.ts
7174
+ init_esm_shims();
7175
+
7176
+ // src/mcp-testing/report/human.ts
7177
+ var noCommands = (text) => text.replace(/^([\s\u0085]*)::/gm, "$1?::").replaceAll("##[", "##?[");
7178
+
7179
+ // src/mcp-testing/scan/descriptions.ts
7180
+ init_esm_shims();
7181
+
7182
+ // src/mcp-testing/scan/phrases.ts
7183
+ init_esm_shims();
7184
+ var DESCRIPTION_PHRASES = {
7185
+ version: 1,
7186
+ rules: {
7187
+ "scan/desc/override-instruction": [
7188
+ "\\b(?:ignore|disregard|forget|override) (?:all |any )?(?:of )?(?:the |your |my )?(?:previous|prior|above|earlier|preceding|other|system) (?:instructions?|prompts?|messages?|rules?|context)",
7189
+ "\\b(?:ignore|disregard) (?:all |any )?(?:of )?(?:the |your )?(?:previous|prior|above|earlier|preceding)\\b",
7190
+ "\\bnew (?:system )?instructions:",
7191
+ "\\byou are now (?:a|an|in)\\b"
7192
+ ],
7193
+ "scan/desc/sensitive-path": [
7194
+ "(?<![\\w.~])(?:~/)?\\.ssh\\b",
7195
+ "\\bid_(?:rsa|dsa|ecdsa|ed25519)\\b",
7196
+ "(?<![\\w.~])(?:~/)?\\.aws/(?:credentials|config)\\b",
7197
+ "(?<![\\w.~])(?:~/)?\\.env\\b",
7198
+ "(?<![\\w.~])(?:~/)?\\.(?:npmrc|pypirc|netrc|pgpass|git-credentials)\\b",
7199
+ "(?<![\\w.~])(?:~/)?\\.(?:docker/config\\.json|kube/config|gnupg|config/gcloud)\\b",
7200
+ "/etc/(?:shadow|passwd)\\b",
7201
+ "\\bcredentials\\.json\\b",
7202
+ "\\bread (?:the )?(?:contents? of )?(?:the |any |a )?(?:file|files)\\b"
7203
+ ],
7204
+ "scan/desc/conceal-from-user": [
7205
+ "\\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",
7206
+ "\\bwithout (?:telling|informing|notifying|alerting) (?:the )?user",
7207
+ "\\b(?:hide|conceal|keep) (?:this |it |that )?(?:secret |hidden )?from (?:the )?user",
7208
+ "\\bthe user (?:must|should) not (?:know|see|be told)"
7209
+ ],
7210
+ "scan/desc/call-other-tool-first": [
7211
+ "\\b(?:before|prior to) (?:using|calling|invoking|running) this tool,? (?:you )?(?:must |should |always )?(?:first )?(?:call|use|invoke|run)\\b",
7212
+ "\\b(?:always |must )?(?:first )?(?:call|invoke|run) (?:the )?[\\w.-]+ (?:tool )?(?:first|beforehand|before (?:this|using this|calling this))\\b",
7213
+ "\\binstead of (?:this tool|calling this tool|using this tool),? (?:call|use|invoke)\\b"
7214
+ ],
7215
+ "scan/desc/param-asks-for-context": [
7216
+ "\\b(?:the )?(?:entire|full|whole|complete) (?:conversation|chat|dialog(?:ue)?|history|context|transcript)",
7217
+ "\\bconversation history\\b",
7218
+ "\\b(?:all |the )?(?:previous|prior|earlier) messages\\b",
7219
+ "\\bsystem prompt\\b",
7220
+ "\\b(?:contents?|text) of (?:the |any |a )?(?:file|files|document)\\b",
7221
+ "\\b(?:output|result|response) (?:of|from) (?:the |another |other |any )?(?:tools?)\\b"
7222
+ ]
7223
+ }
7224
+ };
7225
+
7226
+ // src/mcp-testing/scan/descriptions.ts
7227
+ var MAX_TEXT_BYTES = 1024 * 1024;
7228
+ var EXCERPT = 80;
7229
+ var U = (cp) => `U+${cp.toString(16).toUpperCase().padStart(4, "0")}`;
7230
+ var SHOWN = /^[\p{L}\p{N}\p{P}\p{S} ]$/u;
7231
+ function visible(s, max = EXCERPT) {
7232
+ const pieces = [];
7233
+ let len = 0;
7234
+ for (const ch of s) {
7235
+ const piece = SHOWN.test(ch) ? ch : `[${U(ch.codePointAt(0))}]`;
7236
+ pieces.push(piece);
7237
+ len += [...piece].length;
7238
+ if (len > max) {
7239
+ while (len > max - 3) len -= [...pieces.pop()].length;
7240
+ return `${pieces.join("")}...`;
7241
+ }
7242
+ }
7243
+ return pieces.join("");
7244
+ }
7245
+ var EMOJI = new RegExp("\\p{Extended_Pictographic}", "u");
7246
+ var PHRASES = Object.fromEntries(
7247
+ Object.entries(DESCRIPTION_PHRASES.rules).map(([id, list2]) => [id, new RegExp(list2.map((p) => `(?:${p.replace(/ /g, "\\s+")})`).join("|"), "giu")])
7248
+ );
7249
+
7250
+ // src/mcp-testing/scan/config/json-tree.ts
7251
+ init_esm_shims();
7252
+
7253
+ // src/mcp-testing/scan/config/config.ts
7254
+ var MAX_FILE_BYTES = 8 * 1024 * 1024;
7255
+ var MAX_VALUE = 64 * 1024;
7256
+ var SHOWN_NAME = 64;
7257
+ var KNOWN_FORMATS = [
7258
+ ["github-token", /(?<![A-Za-z0-9])(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]{36,}/],
7259
+ ["aws-access-key-id", /(?<![A-Za-z0-9])(?:AKIA|ASIA|AGPA|AIDA|AROA)[A-Z2-7]{16}(?![A-Za-z0-9])/],
7260
+ ["slack-token", /(?<![A-Za-z0-9])xox[abprs]-[A-Za-z0-9-]{10,}/],
7261
+ ["stripe-key", /(?<![A-Za-z0-9])[rs]k_live_[A-Za-z0-9]{16,}/],
7262
+ ["anthropic-key", /(?<![A-Za-z0-9])sk-ant-[A-Za-z0-9_-]{20,}/],
7263
+ ["openai-key", /(?<![A-Za-z0-9])sk-(?:proj|svcacct)-[A-Za-z0-9_-]{32,}/],
7264
+ ["google-api-key", /(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{35}/],
7265
+ ["npm-token", /(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/],
7266
+ ["gitlab-token", /(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20}/],
7267
+ ["private-key", /-----BEGIN (?:[A-Z]+ )*PRIVATE KEY-----/]
7268
+ ];
7269
+ var KEY_PREFIX = /^\s*(?:gh[pousr]_|github_pat_|AKIA|ASIA|AGPA|AIDA|AROA|xox[abprs]-|[rs]k_live_|sk-ant-|AIza|npm_|glpat-|-----BEGIN )/;
7270
+ var NAME_FORMATS = KNOWN_FORMATS.map(
7271
+ ([, re]) => new RegExp(re.source.replace("(?<![A-Za-z0-9])", "").replace("(?![A-Za-z0-9])", ""), re.flags)
7272
+ );
7273
+ var tokenish = (name) => {
7274
+ const head = name.slice(0, 256);
7275
+ return KEY_PREFIX.test(head) || NAME_FORMATS.some((re) => re.test(head));
7276
+ };
7277
+ var safe = (name) => noCommands(visible(tokenish(name) ? "[key]" : name, SHOWN_NAME));
7278
+ var safeText = (text) => noCommands(
7279
+ visible(
7280
+ text.slice(0, 1024).replace(/[^\\/]+/g, (seg) => tokenish(seg) ? "[key]" : seg),
7281
+ 400
7282
+ )
7283
+ );
7284
+
7285
+ // src/cli/commands/cairn-artifact.ts
7286
+ var SUPPORTED_ARTIFACT_VERSION = 1;
7287
+ var INGEST_SCHEMA_VERSION = 1;
7288
+ var NoCairnRunsError = class extends Error {
7289
+ constructor(runsDir) {
7290
+ super(`No Cairn run found under ${runsDir} \u2014 name the directory instead: plune ingest <dir>.`);
7291
+ this.name = "NoCairnRunsError";
7292
+ }
7293
+ };
7294
+ async function findLatestCairnRun(runsDir = "runs") {
7295
+ const entries = await fs8.readdir(runsDir, { withFileTypes: true }).catch(() => null);
7296
+ if (entries === null) throw new NoCairnRunsError(runsDir);
7297
+ let newest;
7298
+ for (const entry of entries) {
7299
+ if (!entry.isDirectory()) continue;
7300
+ const dir = path10.join(runsDir, entry.name);
7301
+ try {
7302
+ const report = await fs8.lstat(path10.join(dir, "report.json"));
7303
+ if (!report.isFile()) continue;
7304
+ if (newest === void 0 || report.mtimeMs > newest.at) {
7305
+ newest = { dir, at: report.mtimeMs };
7306
+ }
7307
+ } catch {
7308
+ }
7309
+ }
7310
+ if (newest === void 0) throw new NoCairnRunsError(runsDir);
7311
+ return newest.dir;
7312
+ }
7313
+ var CairnRunNotFoundError = class extends Error {
7314
+ constructor(dir) {
7315
+ super(
7316
+ `No Cairn run found in ${dir} \u2014 expected a report.json written by "cairn design|explore|api".`
7317
+ );
7318
+ this.name = "CairnRunNotFoundError";
7319
+ }
7320
+ };
7321
+ var CairnRunVersionError = class extends Error {
7322
+ constructor(found) {
7323
+ super(
7324
+ 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.`
7325
+ );
7326
+ this.name = "CairnRunVersionError";
7327
+ }
7328
+ };
7329
+ var CairnRunPartialError = class extends Error {
7330
+ constructor(reason) {
7331
+ super(`That Cairn run did not finish, so its cases are incomplete: ${reason}`);
7332
+ this.name = "CairnRunPartialError";
7333
+ }
7334
+ };
7335
+ var CairnArtifactShapeError = class extends Error {
7336
+ constructor(file, field, problem) {
7337
+ super(
7338
+ `Cannot read this Cairn run: ${file}${field === "" ? "" : field.startsWith("[") ? field : ` ${field}`} ${problem}. Nothing was uploaded.`
7339
+ );
7340
+ this.name = "CairnArtifactShapeError";
7341
+ }
7342
+ };
7343
+ var CairnEvidenceAmbiguousError = class extends Error {
7344
+ constructor(name) {
7345
+ super(
7346
+ `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.`
7347
+ );
7348
+ this.name = "CairnEvidenceAmbiguousError";
7349
+ }
7350
+ };
7351
+ var asRecord = (v) => typeof v === "object" && v !== null ? v : {};
7352
+ var str = (v, fallback = "") => typeof v === "string" && v !== "" ? v : fallback;
7353
+ var own = (rec, key) => Object.hasOwn(rec, key) ? rec[key] : void 0;
7354
+ var MAX_ARTIFACT_BYTES = 32 * 1024 * 1024;
7355
+ var MAX_MCP_CASES = 5e3;
7356
+ async function checkSize(dir, file) {
7357
+ let size;
7358
+ try {
7359
+ const st = await fs8.stat(path10.join(dir, file));
7360
+ if (!st.isFile()) throw new CairnArtifactShapeError(file, "", "is not a regular file");
7361
+ size = st.size;
7362
+ } catch (e) {
7363
+ if (e instanceof CairnArtifactShapeError) throw e;
7364
+ return false;
7365
+ }
7366
+ if (size > MAX_ARTIFACT_BYTES) {
7367
+ throw new CairnArtifactShapeError(
7368
+ file,
7369
+ "",
7370
+ `is larger than ${MAX_ARTIFACT_BYTES / (1024 * 1024)} MiB`
7371
+ );
7372
+ }
7373
+ return true;
7374
+ }
7375
+ async function readJson(file) {
7376
+ try {
7377
+ return JSON.parse(await fs8.readFile(file, "utf8"));
7378
+ } catch {
7379
+ return void 0;
7380
+ }
7381
+ }
7382
+ var ARGS_CHARS2 = 200;
7383
+ var SECRET_NAME = /key|token|secret|password|passwd|auth|cookie|credential/i;
7384
+ var maskNamed = (v, depth = 0) => {
7385
+ if (depth > 16) return "[deep]";
7386
+ if (Array.isArray(v)) return v.slice(0, 50).map((x) => maskNamed(x, depth + 1));
7387
+ if (typeof v === "object" && v !== null) {
7388
+ const out = {};
7389
+ for (const [k, x] of Object.entries(v).slice(0, 50)) {
7390
+ out[k] = SECRET_NAME.test(k) ? "***" : maskNamed(x, depth + 1);
7391
+ }
7392
+ return out;
7393
+ }
7394
+ return v;
7395
+ };
7396
+ function describeMcpArgs(request) {
7397
+ let text = request.slice(0, 4096);
7398
+ try {
7399
+ text = JSON.stringify(maskNamed(JSON.parse(text)));
7400
+ } catch {
7401
+ }
7402
+ const masked = safeText(redactSecrets(text));
7403
+ return masked.length > ARGS_CHARS2 ? `${masked.slice(0, ARGS_CHARS2)} (cut)` : masked;
7404
+ }
7405
+ var MCP_STATES = /* @__PURE__ */ new Set([
7406
+ "passed",
7407
+ "failed",
7408
+ "not-sent",
7409
+ "could-not-run",
7410
+ "needs-review"
7411
+ ]);
7412
+ async function readMcpEvidence(dir, states) {
7413
+ const file = "mcp-evidence.json";
7414
+ if (!await checkSize(dir, file)) return void 0;
7415
+ let raw;
7416
+ try {
7417
+ raw = JSON.parse(await fs8.readFile(path10.join(dir, file), "utf8"));
7418
+ } catch {
7419
+ throw new CairnArtifactShapeError(file, "", "is not valid JSON");
7420
+ }
7421
+ if (!Array.isArray(raw)) throw new CairnArtifactShapeError(file, "", "must be a list");
7422
+ if (raw.length > MAX_MCP_CASES) {
7423
+ throw new CairnArtifactShapeError(file, "", `lists more than ${MAX_MCP_CASES} entries`);
7424
+ }
7425
+ const byId = /* @__PURE__ */ new Map();
7426
+ raw.forEach((item, i) => {
7427
+ if (typeof item !== "object" || item === null || Array.isArray(item)) {
7428
+ throw new CairnArtifactShapeError(file, `[${i}]`, "must be an object");
7429
+ }
7430
+ const rec = item;
7431
+ const id = own(rec, "stableId");
7432
+ if (typeof id !== "string" || !states.has(id)) {
7433
+ throw new CairnArtifactShapeError(
7434
+ file,
7435
+ `[${i}].stableId`,
7436
+ "does not name a case of report.json"
7437
+ );
7438
+ }
7439
+ if (byId.has(id)) {
7440
+ throw new CairnArtifactShapeError(file, `[${i}].stableId`, "appears more than once");
7441
+ }
7442
+ if (own(rec, "state") !== states.get(id)) {
7443
+ throw new CairnArtifactShapeError(
7444
+ file,
7445
+ `[${i}].state`,
7446
+ "does not agree with the state in report.json"
7447
+ );
7448
+ }
7449
+ const request = own(rec, "request");
7450
+ if (request !== void 0 && typeof request !== "string") {
7451
+ throw new CairnArtifactShapeError(file, `[${i}].request`, "must be text");
7452
+ }
7453
+ const durationMs = own(rec, "durationMs");
7454
+ if (durationMs !== void 0 && typeof durationMs !== "number") {
7455
+ throw new CairnArtifactShapeError(file, `[${i}].durationMs`, "must be a number");
7456
+ }
7457
+ byId.set(id, {
7458
+ sent: typeof durationMs === "number",
7459
+ ...request !== void 0 ? { request } : {}
7460
+ });
7461
+ });
7462
+ return byId;
7463
+ }
7464
+ function expectedOfMcp(type, adversarial) {
7465
+ if (type === "Positive") {
7466
+ return "The call finishes without an error, and the answer fits the tool's outputSchema when it has one.";
7467
+ }
7468
+ 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.";
7469
+ }
7470
+ async function casesFromMcp(dir, report) {
7471
+ const list2 = own(report, "cases");
7472
+ if (!Array.isArray(list2))
7473
+ throw new CairnArtifactShapeError("report.json", "cases", "must be a list");
7474
+ if (list2.length > MAX_MCP_CASES) {
7475
+ throw new CairnArtifactShapeError(
7476
+ "report.json",
7477
+ "cases",
7478
+ `lists more than ${MAX_MCP_CASES} cases`
7479
+ );
7480
+ }
7481
+ const states = /* @__PURE__ */ new Map();
7482
+ const parsed2 = list2.map((raw, i) => {
7483
+ const at = `cases[${i}]`;
7484
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
7485
+ throw new CairnArtifactShapeError("report.json", at, "must be an object");
7486
+ }
7487
+ const c = raw;
7488
+ const text = (key) => {
7489
+ const v = own(c, key);
7490
+ if (typeof v !== "string" || v === "") {
7491
+ throw new CairnArtifactShapeError("report.json", `${at}.${key}`, "must be text");
7492
+ }
7493
+ return v;
7494
+ };
7495
+ const stableId = text("stableId");
7496
+ const name = text("name");
7497
+ const tool = text("tool");
7498
+ const type = text("type");
7499
+ const state = text("state");
7500
+ if (type !== "Positive" && type !== "Negative") {
7501
+ throw new CairnArtifactShapeError(
7502
+ "report.json",
7503
+ `${at}.type`,
7504
+ `is "${safe(type)}", not Positive or Negative`
7505
+ );
7506
+ }
7507
+ if (!MCP_STATES.has(state)) {
7508
+ throw new CairnArtifactShapeError(
7509
+ "report.json",
7510
+ `${at}.state`,
7511
+ `is "${safe(state)}", a state this CLI does not know`
7512
+ );
7513
+ }
7514
+ if (states.has(stableId)) {
7515
+ throw new CairnArtifactShapeError("report.json", `${at}.stableId`, "appears more than once");
7516
+ }
7517
+ states.set(stableId, state);
7518
+ const kind = type;
7519
+ const technique = own(c, "technique");
7520
+ return {
7521
+ stableId,
7522
+ name,
7523
+ tool,
7524
+ type: kind,
7525
+ state,
7526
+ adversarial: own(c, "adversarialStyle") !== void 0,
7527
+ ...typeof technique === "string" ? { technique } : {}
7528
+ };
7529
+ });
7530
+ const evidence = await readMcpEvidence(dir, states);
7531
+ return parsed2.map((c) => {
7532
+ const e = evidence?.get(c.stableId);
7533
+ const verdict = c.state === "passed" ? "passed" : c.state === "failed" ? "failed" : c.state === "could-not-run" && e?.sent === true ? "blocked" : void 0;
7534
+ const args = e?.request !== void 0 ? ` ${describeMcpArgs(e.request)}` : "";
7535
+ return {
7536
+ stableId: c.stableId,
7537
+ title: safeText(c.name),
7538
+ execution: "auto",
7539
+ steps: [`tools/call ${safe(c.tool)}${args}`],
7540
+ expected: expectedOfMcp(c.type, c.adversarial),
7541
+ ...verdict !== void 0 ? { verdict } : {},
7542
+ ...c.technique !== void 0 ? { technique: safeText(c.technique) } : {}
7543
+ };
7544
+ });
7545
+ }
7546
+ async function defaultReadEvidence(dir) {
7547
+ const raw = await readJson(path10.join(dir, "api-evidence.json"));
7548
+ if (!Array.isArray(raw)) return void 0;
7549
+ return raw.map((r) => {
7550
+ const rec = asRecord(r);
7551
+ const error = str(rec["error"]);
7552
+ return { name: str(rec["name"]), passed: rec["passed"] === true, ...error !== "" ? { error } : {} };
7553
+ });
7554
+ }
7555
+ function casesFromDesign(report) {
7556
+ const list2 = Array.isArray(report["testCases"]) ? report["testCases"] : [];
7557
+ return list2.map((raw) => {
7558
+ const c = asRecord(raw);
7559
+ const steps = (Array.isArray(c["steps"]) ? c["steps"] : []).map((s) => str(s)).filter((s) => s !== "");
7560
+ return {
7561
+ stableId: str(c["stableId"]),
7562
+ title: str(c["title"], "untitled case"),
7563
+ execution: c["execution"] === "manual" ? "manual" : "auto",
4522
7564
  steps: steps.length > 0 ? steps : ["(no steps recorded)"],
4523
7565
  expected: str(c["expected"], "(no expected result recorded)"),
4524
7566
  ...typeof c["technique"] === "string" ? { technique: c["technique"] } : {},
@@ -4527,8 +7569,8 @@ function casesFromDesign(report) {
4527
7569
  });
4528
7570
  }
4529
7571
  function casesFromApi(report, verdicts) {
4530
- const list = Array.isArray(report["cases"]) ? report["cases"] : [];
4531
- return list.map((raw) => {
7572
+ const list2 = Array.isArray(report["cases"]) ? report["cases"] : [];
7573
+ return list2.map((raw) => {
4532
7574
  const c = asRecord(raw);
4533
7575
  const name = str(c["name"], "unnamed operation");
4534
7576
  const request = `${str(c["method"], "GET")} ${str(c["path"], "/")}`;
@@ -4545,7 +7587,8 @@ function casesFromApi(report, verdicts) {
4545
7587
  });
4546
7588
  }
4547
7589
  async function readCairnRun(dir, deps = {}) {
4548
- const raw = await readJson(path8.join(dir, "report.json"));
7590
+ await checkSize(dir, "report.json");
7591
+ const raw = await readJson(path10.join(dir, "report.json"));
4549
7592
  if (raw === void 0) throw new CairnRunNotFoundError(dir);
4550
7593
  const report = asRecord(raw);
4551
7594
  if (report["schemaVersion"] !== SUPPORTED_ARTIFACT_VERSION) {
@@ -4555,7 +7598,7 @@ async function readCairnRun(dir, deps = {}) {
4555
7598
  throw new CairnRunPartialError(str(report["error"], "no reason recorded"));
4556
7599
  }
4557
7600
  const mode = report["mode"];
4558
- if (mode !== "design" && mode !== "explore" && mode !== "api") {
7601
+ if (mode !== "design" && mode !== "explore" && mode !== "api" && mode !== "mcp") {
4559
7602
  throw new CairnRunVersionError(
4560
7603
  `${SUPPORTED_ARTIFACT_VERSION} (unknown run mode ${String(mode)})`
4561
7604
  );
@@ -4569,19 +7612,54 @@ async function readCairnRun(dir, deps = {}) {
4569
7612
  verdicts.set(e.name, e.error !== void 0 ? "blocked" : e.passed ? "passed" : "failed");
4570
7613
  }
4571
7614
  cases = casesFromApi(report, verdicts);
7615
+ } else if (mode === "mcp") {
7616
+ cases = await casesFromMcp(dir, report);
4572
7617
  } else {
4573
7618
  cases = casesFromDesign(report);
4574
7619
  }
4575
7620
  return {
4576
7621
  schemaVersion: INGEST_SCHEMA_VERSION,
4577
7622
  run: {
4578
- runId: str(report["runId"], path8.basename(dir)),
7623
+ runId: str(report["runId"], path10.basename(dir)),
4579
7624
  mode,
4580
7625
  target: str(report["url"], "unknown")
4581
7626
  },
4582
7627
  cases
4583
7628
  };
4584
7629
  }
7630
+ async function readCairnSessionFiles(dir) {
7631
+ const raw = await readJson(path10.join(dir, "screencasts", "screencasts.json"));
7632
+ if (!Array.isArray(raw)) return void 0;
7633
+ const root = await fs8.realpath(dir).catch(() => path10.resolve(dir));
7634
+ const within = (p) => {
7635
+ const rel = path10.relative(root, p);
7636
+ return rel !== "" && !rel.startsWith("..") && !path10.isAbsolute(rel);
7637
+ };
7638
+ let outside = 0;
7639
+ const inside = async (p) => {
7640
+ if (typeof p !== "string" || p === "") return void 0;
7641
+ const abs = path10.resolve(root, p);
7642
+ const real = await fs8.realpath(abs).catch(() => void 0);
7643
+ if (within(abs) && (real === void 0 || within(real))) return real ?? abs;
7644
+ outside += 1;
7645
+ return void 0;
7646
+ };
7647
+ const byCase = /* @__PURE__ */ new Map();
7648
+ let unmapped = 0;
7649
+ for (const entry of raw) {
7650
+ const rec = asRecord(entry);
7651
+ const files = [];
7652
+ for (const p of [own(rec, "video"), own(rec, "trace")]) {
7653
+ const file = await inside(p);
7654
+ if (file !== void 0) files.push(file);
7655
+ }
7656
+ if (files.length === 0) continue;
7657
+ const stableId = own(rec, "stableId");
7658
+ if (typeof stableId !== "string" || stableId === "") unmapped += 1;
7659
+ else byCase.set(stableId, [...byCase.get(stableId) ?? [], ...files]);
7660
+ }
7661
+ return { byCase, unmapped, outside };
7662
+ }
4585
7663
 
4586
7664
  // src/cli/commands/ingest.ts
4587
7665
  var IngestNotLoggedInError = class extends Error {
@@ -4610,6 +7688,131 @@ var IngestHttpError = class extends Error {
4610
7688
  }
4611
7689
  status;
4612
7690
  };
7691
+ var SESSION_FILE_MAX = 100 * 1024 * 1024;
7692
+ var SESSION_UPLOADS_AT_ONCE = 4;
7693
+ var TYPE_BY_EXTENSION2 = { ".webm": "video/webm", ".zip": "application/zip" };
7694
+ function itemsOf(body) {
7695
+ const items = body?.items;
7696
+ if (!Array.isArray(items)) return void 0;
7697
+ return items.flatMap((raw) => {
7698
+ const i = raw ?? {};
7699
+ if (typeof i["stableId"] !== "string") return [];
7700
+ const reviewItemId = typeof i["reviewItemId"] === "string" && i["reviewItemId"] !== "" ? i["reviewItemId"] : void 0;
7701
+ const resultId = typeof i["resultId"] === "string" && i["resultId"] !== "" ? i["resultId"] : void 0;
7702
+ if (reviewItemId === void 0 && resultId === void 0) return [];
7703
+ return [{ stableId: i["stableId"], ...reviewItemId !== void 0 ? { reviewItemId } : {}, ...resultId !== void 0 ? { resultId } : {} }];
7704
+ });
7705
+ }
7706
+ var RESULT_PAGES_MAX = 100;
7707
+ var namesOf = (files) => new Set(Array.isArray(files) ? files.flatMap((f) => typeof f?.name === "string" ? [f.name] : []) : []);
7708
+ async function heldBy(client, runId, jobs) {
7709
+ const held = /* @__PURE__ */ new Map();
7710
+ for (const job of jobs) {
7711
+ const key = targetOf(job);
7712
+ if (held.has(key) || job.owner !== "review-items") continue;
7713
+ const out = await client.get(`/v1/review-items/${encodeURIComponent(job.id)}`);
7714
+ held.set(key, out.ok ? namesOf(out.body?.files) : void 0);
7715
+ }
7716
+ const results = jobs.filter((j) => j.owner === void 0);
7717
+ if (results.length === 0) return held;
7718
+ let byResult = /* @__PURE__ */ new Map();
7719
+ let before;
7720
+ for (let page = 0; ; page += 1) {
7721
+ if (runId === "" || page >= RESULT_PAGES_MAX) {
7722
+ byResult = void 0;
7723
+ break;
7724
+ }
7725
+ const query = before === void 0 ? "" : `?before=${encodeURIComponent(before)}`;
7726
+ const out = await client.get(`/v1/runs/${encodeURIComponent(runId)}/results${query}`);
7727
+ if (!out.ok || !Array.isArray(out.body?.results)) {
7728
+ byResult = void 0;
7729
+ break;
7730
+ }
7731
+ for (const r of out.body.results) {
7732
+ if (typeof r?.id === "string") byResult.set(r.id, namesOf(r.files));
7733
+ }
7734
+ if (typeof out.body.next !== "string" || out.body.next === "") break;
7735
+ before = out.body.next;
7736
+ }
7737
+ for (const job of results) held.set(targetOf(job), byResult === void 0 ? void 0 : byResult.get(job.id) ?? /* @__PURE__ */ new Set());
7738
+ return held;
7739
+ }
7740
+ var targetOf = (job) => `${job.owner ?? "results"}/${job.id}`;
7741
+ async function sendSessionFiles(dir, sent, platform) {
7742
+ const session = await readCairnSessionFiles(dir);
7743
+ if (session === void 0 || session.byCase.size === 0 && session.unmapped === 0 && session.outside === 0) return [];
7744
+ if (sent.items === void 0) {
7745
+ return ["session files not uploaded \u2014 this Plune is older than the routes that take them"];
7746
+ }
7747
+ const lines = [];
7748
+ if (session.outside > 0) lines.push(`${session.outside} file(s) not uploaded \u2014 the path leaves the run directory`);
7749
+ if (session.unmapped > 0) lines.push(`${session.unmapped} recording(s) name no case \u2014 not uploaded`);
7750
+ let jobs = [];
7751
+ let tooBig = 0;
7752
+ const placed = /* @__PURE__ */ new Set();
7753
+ for (const item of sent.items) {
7754
+ const paths = session.byCase.get(item.stableId);
7755
+ if (paths === void 0 || placed.has(item.stableId)) continue;
7756
+ placed.add(item.stableId);
7757
+ for (const file of paths) {
7758
+ const name = path11.basename(file);
7759
+ const size = await disk2.stat(file).then((s) => s.size, () => void 0);
7760
+ if (size !== void 0 && size > SESSION_FILE_MAX) {
7761
+ tooBig += 1;
7762
+ lines.push(`"${name}" skipped \u2014 larger than the ${SESSION_FILE_MAX / (1024 * 1024)} MiB a session file may be`);
7763
+ continue;
7764
+ }
7765
+ const type = TYPE_BY_EXTENSION2[path11.extname(file).toLowerCase()] ?? "application/octet-stream";
7766
+ jobs.push({
7767
+ id: item.reviewItemId ?? item.resultId,
7768
+ ...item.reviewItemId !== void 0 ? { owner: "review-items" } : {},
7769
+ kind: "file",
7770
+ name,
7771
+ type,
7772
+ path: file
7773
+ });
7774
+ }
7775
+ }
7776
+ const unplaced = [...session.byCase.keys()].filter((stableId) => !placed.has(stableId)).length;
7777
+ if (unplaced > 0) lines.push(`${unplaced} case(s) with recordings got no proposal or result in this run \u2014 not uploaded`);
7778
+ const client = createClient({
7779
+ apiUrl: platform.apiUrl,
7780
+ token: platform.token,
7781
+ uploadRetries: UPLOAD_RETRIES.default,
7782
+ ...platform.fetchImpl !== void 0 ? { fetchImpl: platform.fetchImpl } : {}
7783
+ });
7784
+ if (sent.repeat && jobs.length > 0) {
7785
+ const held = await heldBy(client, sent.runId, jobs);
7786
+ let already = 0;
7787
+ let unknown = 0;
7788
+ jobs = jobs.filter((job) => {
7789
+ const names = held.get(targetOf(job));
7790
+ if (names === void 0) unknown += 1;
7791
+ else if (names.has(job.name)) already += 1;
7792
+ else return true;
7793
+ return false;
7794
+ });
7795
+ if (unknown > 0) lines.push(`${unknown} file(s) not sent again \u2014 what the platform holds could not be read`);
7796
+ lines.push(`${already} file(s) already on the platform, ${jobs.length} sent`);
7797
+ }
7798
+ const counts = { screenshots: { uploaded: 0, skipped: 0, failed: 0 }, textFiles: { uploaded: 0, skipped: 0, failed: 0 }, otherFiles: { uploaded: 0, skipped: 0, failed: 0 } };
7799
+ if (jobs.length > 0) {
7800
+ const notes = [];
7801
+ const files = fileSender({
7802
+ client,
7803
+ log: (line) => notes.push(line.replace(/^plune: /, "")),
7804
+ stats: counts,
7805
+ uploadsAtOnce: SESSION_UPLOADS_AT_ONCE,
7806
+ uploadRetries: UPLOAD_RETRIES.default,
7807
+ without: "the run is recorded without it"
7808
+ });
7809
+ await files.uploadEach(jobs);
7810
+ lines.push(...notes.filter((n) => !n.startsWith("storage bucket found")));
7811
+ }
7812
+ const { uploaded, skipped, failed } = counts.otherFiles;
7813
+ const total = `${uploaded} session file(s) uploaded` + (skipped + tooBig > 0 ? `, ${skipped + tooBig} skipped` : "") + (failed > 0 ? `, ${failed} failed to upload` : "");
7814
+ return [total, ...lines];
7815
+ }
4613
7816
  async function safeErrorDetail2(res) {
4614
7817
  try {
4615
7818
  const body = await res.json();
@@ -4627,10 +7830,14 @@ async function handleIngest(deps) {
4627
7830
  const doFetch = deps.fetchImpl ?? fetch;
4628
7831
  const endpoint = `${apiUrl}/v1/ingest/cairn`;
4629
7832
  const job = new JobReporter(doFetch, apiUrl, token, "ingest");
4630
- await job.open(path9.basename(path9.resolve(dir)), payload.cases.length);
7833
+ await job.open(path11.basename(path11.resolve(dir)), payload.cases.length);
4631
7834
  try {
4632
- const result = await upload();
7835
+ const { result, ...sent } = await upload();
4633
7836
  await job.uploaded({ subjectId: result.runId || void 0 });
7837
+ const files = await sendSessionFiles(dir, { ...sent, runId: result.runId }, { apiUrl, token, ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {} }).catch(
7838
+ () => ["session files not uploaded (an unexpected error) \u2014 the run is recorded"]
7839
+ );
7840
+ if (files.length > 0) result.files = files;
4634
7841
  await job.finish({ ok: true });
4635
7842
  if (job.problem !== void 0) result.jobProblem = job.problem;
4636
7843
  return result;
@@ -4655,16 +7862,17 @@ async function handleIngest(deps) {
4655
7862
  throw new IngestHttpError(res.status, detail);
4656
7863
  }
4657
7864
  const body = await res.json().catch(() => ({}));
4658
- return {
7865
+ const result = {
4659
7866
  runId: typeof body.runId === "string" ? body.runId : "",
4660
7867
  linked: typeof body.linked === "number" ? body.linked : 0,
4661
7868
  proposed: typeof body.proposed === "number" ? body.proposed : 0,
4662
7869
  skipped: typeof body.skipped === "number" ? body.skipped : 0
4663
7870
  };
7871
+ return { result, items: itemsOf(body), repeat: res.status === 200 };
4664
7872
  }
4665
7873
  }
4666
7874
  function reportIngestFailure(err, write) {
4667
- if (err instanceof IngestNotLoggedInError || err instanceof IngestTokenRejectedError || err instanceof CairnRunNotFoundError || err instanceof NoCairnRunsError || err instanceof CairnRunVersionError || err instanceof CairnRunPartialError || err instanceof CairnEvidenceAmbiguousError) {
7875
+ 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) {
4668
7876
  write(`${err.message}
4669
7877
  `);
4670
7878
  return 2;
@@ -4681,7 +7889,8 @@ function formatIngestResult(r) {
4681
7889
  `Ingested Cairn run \u2192 ${r.runId}`,
4682
7890
  ` ${r.linked} result(s) attached to existing cases`,
4683
7891
  ` ${r.proposed} case(s) proposed \u2014 review them in Plune to accept`,
4684
- ` ${r.skipped} skipped (already queued, already rejected, repeated, or never executed)`
7892
+ ` ${r.skipped} skipped (already queued, already rejected, repeated, or never executed)`,
7893
+ ...(r.files ?? []).map((line, i) => i === 0 ? ` ${line}` : ` ${line}`)
4685
7894
  ];
4686
7895
  return `${lines.join("\n")}
4687
7896
  `;