@plune-ai/cli 0.38.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
@@ -31,21 +31,23 @@ function machineless(raw, repoRoot, home) {
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;
@@ -432,18 +434,18 @@ function readLines(stream, onLine, stats) {
432
434
  if (stats !== void 0 && rest.length > stats.high) stats.high = rest.length;
433
435
  partial = rest.slice(0, STDERR_LINE_LIMIT);
434
436
  };
435
- return new Promise((resolve8) => {
437
+ return new Promise((resolve9) => {
436
438
  let done = false;
437
439
  const finish = () => {
438
440
  if (done) return;
439
441
  done = true;
440
442
  feed(decoder.end());
441
443
  if (partial !== "") onLine(partial.endsWith("\r") ? partial.slice(0, -1) : partial);
442
- resolve8();
444
+ resolve9();
443
445
  };
444
446
  stream.on(
445
447
  "data",
446
- (chunk) => feed(typeof chunk === "string" ? chunk : decoder.write(chunk))
448
+ (chunk2) => feed(typeof chunk2 === "string" ? chunk2 : decoder.write(chunk2))
447
449
  );
448
450
  stream.once("end", finish);
449
451
  stream.once("close", finish);
@@ -514,9 +516,9 @@ function watchOverflow(transport, over) {
514
516
  const buffer = transport._readBuffer;
515
517
  const append = buffer?.append?.bind(buffer);
516
518
  if (buffer === void 0 || append === void 0) return;
517
- buffer.append = (chunk) => {
519
+ buffer.append = (chunk2) => {
518
520
  try {
519
- append(chunk);
521
+ append(chunk2);
520
522
  } catch (err) {
521
523
  over();
522
524
  throw err;
@@ -737,7 +739,7 @@ async function openSession(config, options = {}) {
737
739
  const stdin = transport._process?.stdin;
738
740
  if (stdin === null || stdin === void 0 || stdin.writableEnded)
739
741
  throw spawnError !== void 0 ? await toConnectError(spawnError) : new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
740
- return new Promise((resolve8, reject) => {
742
+ return new Promise((resolve9, reject) => {
741
743
  const done = () => {
742
744
  clearTimeout(timer2);
743
745
  listeners.delete(listener);
@@ -751,7 +753,7 @@ async function openSession(config, options = {}) {
751
753
  const frame2 = parsed(line);
752
754
  if (!answers(frame2, id)) return;
753
755
  done();
754
- resolve8({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
756
+ resolve9({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
755
757
  };
756
758
  const stop = () => {
757
759
  done();
@@ -831,10 +833,10 @@ async function openSession(config, options = {}) {
831
833
  const proc = transport._process;
832
834
  if (proc === void 0) return true;
833
835
  if (proc.exitCode !== null || proc.signalCode !== null) return true;
834
- const exited = new Promise((resolve8) => proc.once("exit", () => resolve8(true)));
836
+ const exited = new Promise((resolve9) => proc.once("exit", () => resolve9(true)));
835
837
  proc.stdin?.end();
836
838
  let timer2;
837
- const late = new Promise((resolve8) => timer2 = setTimeout(() => resolve8(false), waitMs));
839
+ const late = new Promise((resolve9) => timer2 = setTimeout(() => resolve9(false), waitMs));
838
840
  const result = await Promise.race([exited, late]);
839
841
  clearTimeout(timer2);
840
842
  return result;
@@ -1464,11 +1466,11 @@ var pluneConfigSchema = z.object({
1464
1466
  config.evals.forEach((evalConfig, i) => {
1465
1467
  const server = evalConfig.mcp?.server;
1466
1468
  if (server === void 0) {
1467
- const misplaced = (assertions, path10) => assertions.forEach((a, j) => {
1469
+ const misplaced = (assertions, path12) => assertions.forEach((a, j) => {
1468
1470
  if (TOOL_CALL_TYPES.has(a.type))
1469
1471
  ctx.addIssue({
1470
1472
  code: "custom",
1471
- path: [...path10, j, "type"],
1473
+ path: [...path12, j, "type"],
1472
1474
  message: `"${a.type}" reads the tool calls of an eval with mcp, and eval "${evalConfig.id}" has no mcp block`
1473
1475
  });
1474
1476
  });
@@ -1637,7 +1639,7 @@ function normalizeProviderError(err, secret, envVar) {
1637
1639
  }
1638
1640
 
1639
1641
  // src/providers/retry.ts
1640
- var defaultSleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
1642
+ var defaultSleep = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
1641
1643
  function retryAfterMs(err) {
1642
1644
  if (typeof err !== "object" || err === null || !("headers" in err)) return void 0;
1643
1645
  const raw = readHeader(err.headers, "retry-after");
@@ -1659,7 +1661,7 @@ function readHeader(headers, name) {
1659
1661
  return typeof v === "string" || typeof v === "number" ? v : void 0;
1660
1662
  }
1661
1663
  async function withRetry(fn, options) {
1662
- const { base_delay_ms = 500, sleep = defaultSleep, random = Math.random } = options;
1664
+ const { base_delay_ms = 500, sleep: sleep2 = defaultSleep, random = Math.random } = options;
1663
1665
  const maxRetries = Math.max(0, Math.floor(options.max_retries));
1664
1666
  let attempt = 0;
1665
1667
  for (; ; ) {
@@ -1675,7 +1677,7 @@ async function withRetry(fn, options) {
1675
1677
  const backoff = base_delay_ms * 2 ** attempt;
1676
1678
  const jitter = backoff * 0.1 * random();
1677
1679
  const delay = Math.max(backoff + jitter, retryAfterMs(err) ?? 0);
1678
- await sleep(delay);
1680
+ await sleep2(delay);
1679
1681
  attempt += 1;
1680
1682
  }
1681
1683
  }
@@ -2091,6 +2093,13 @@ function makeEstimateProvider(config, pricing) {
2091
2093
 
2092
2094
  // src/providers/mock.ts
2093
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
+ }
2094
2103
  var USAGE = { input_tokens: 10, output_tokens: 5 };
2095
2104
  function parseMockScript(text) {
2096
2105
  let parsed2;
@@ -2105,7 +2114,7 @@ function parseMockScript(text) {
2105
2114
  if (t !== void 0 && typeof t !== "string") return false;
2106
2115
  if (calls === void 0) return true;
2107
2116
  return Array.isArray(calls) && calls.every(
2108
- (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")
2109
2118
  );
2110
2119
  };
2111
2120
  if (!Array.isArray(parsed2) || parsed2.length === 0 || !parsed2.every(isStep))
@@ -2124,14 +2133,13 @@ function makeMockProvider(script) {
2124
2133
  respond: (req) => {
2125
2134
  const step = req.messages.filter((m) => m.role === "assistant").length;
2126
2135
  const entry = script[Math.min(step, script.length - 1)];
2127
- 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
+ });
2128
2140
  return Promise.resolve({
2129
2141
  text: entry.text ?? "",
2130
- tool_calls: calls.map((c, i) => ({
2131
- id: `call_${step}_${i}`,
2132
- name: c.name,
2133
- args: c.args ?? {}
2134
- })),
2142
+ tool_calls: calls.map((c, i) => ({ id: `call_${step}_${i}`, ...c })),
2135
2143
  usage: USAGE,
2136
2144
  finish_reason: calls.length > 0 ? "tool_calls" : "stop"
2137
2145
  });
@@ -2180,7 +2188,7 @@ var XenovaEmbedder = class {
2180
2188
  throw new Error(
2181
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."
2182
2190
  );
2183
- }).then(({ pipeline }) => pipeline("feature-extraction", MODEL_ID));
2191
+ }).then(({ pipeline: pipeline2 }) => pipeline2("feature-extraction", MODEL_ID));
2184
2192
  return this.extractor;
2185
2193
  }
2186
2194
  };
@@ -3343,9 +3351,9 @@ var testCaseBaseSchema = z2.object({
3343
3351
  schemaVersion: z2.literal(TEST_CASE_SCHEMA_VERSION),
3344
3352
  id: z2.string().min(1),
3345
3353
  externalKeys: z2.array(externalKeySchema).optional(),
3346
- /** ADR 0045 / plune#1246 — optional, purely additive; schemaVersion stays 2. */
3354
+ /** Optional, purely additive; schemaVersion stays 2. */
3347
3355
  is_flaky: z2.boolean().optional(),
3348
- /** ADR 0045 / plune#1246 — optional, purely additive; schemaVersion stays 2. */
3356
+ /** Optional, purely additive; schemaVersion stays 2. */
3349
3357
  is_muted: z2.boolean().optional()
3350
3358
  });
3351
3359
  var testCaseSchema = z2.discriminatedUnion("type", [
@@ -3411,7 +3419,7 @@ function segment(key) {
3411
3419
  const plain = /^[A-Za-z_][\w-]*$/.test(key) && key.length <= 40 && !UUID.test(key) && !EMAIL.test(key);
3412
3420
  return plain ? key : "*";
3413
3421
  }
3414
- var cap = (path10) => path10.length > MAX_PATH ? path10.slice(0, MAX_PATH) : path10;
3422
+ var cap = (path12) => path12.length > MAX_PATH ? path12.slice(0, MAX_PATH) : path12;
3415
3423
  var hashOf = (v) => sha256(v).slice(0, 16);
3416
3424
  function noteValue(out, v, at) {
3417
3425
  if (typeof v !== "string" || v.length < MIN_VALUE) return;
@@ -3420,20 +3428,20 @@ function noteValue(out, v, at) {
3420
3428
  where.add(at);
3421
3429
  out.values.set(h, where);
3422
3430
  }
3423
- function walk(value, path10, depth, out) {
3431
+ function walk(value, path12, depth, out) {
3424
3432
  if (depth > SCAN_DEPTH) return;
3425
3433
  if (typeof value === "string" && UUID.test(value)) {
3426
- const at = cap(path10 === "" ? "(root)" : path10);
3434
+ const at = cap(path12 === "" ? "(root)" : path12);
3427
3435
  out.paths.add(at);
3428
3436
  noteValue(out, value, at);
3429
3437
  }
3430
3438
  if (Array.isArray(value)) {
3431
- for (const item of value.slice(0, SCAN_ITEMS)) walk(item, `${path10}[]`, depth + 1, out);
3439
+ for (const item of value.slice(0, SCAN_ITEMS)) walk(item, `${path12}[]`, depth + 1, out);
3432
3440
  return;
3433
3441
  }
3434
3442
  if (!isRecord3(value)) return;
3435
3443
  for (const [key, v] of Object.entries(value)) {
3436
- const at = cap(path10 === "" ? segment(key) : `${path10}.${segment(key)}`);
3444
+ const at = cap(path12 === "" ? segment(key) : `${path12}.${segment(key)}`);
3437
3445
  if (isIdKey(key) && (isScalar(v) || Array.isArray(v) && v.length > 0 && v.every(isScalar))) {
3438
3446
  out.paths.add(at);
3439
3447
  for (const x of Array.isArray(v) ? v : [v]) noteValue(out, x, at);
@@ -4556,7 +4564,7 @@ var rowResultSchema = z3.object({
4556
4564
  error: runErrorSchema.optional(),
4557
4565
  assertions: z3.array(assertionResultRecordSchema2),
4558
4566
  cache_saved: savedSchema.optional(),
4559
- /** 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`. */
4560
4568
  inconclusive: z3.enum(ROW_INCONCLUSIVE).optional(),
4561
4569
  /** Repeats (`runs` above 1). Optional and additive — a RunResult without it validates unchanged. */
4562
4570
  attempts: z3.object({
@@ -4633,7 +4641,7 @@ var summarySchema = z3.object({
4633
4641
  passed: z3.number(),
4634
4642
  failed: z3.number(),
4635
4643
  errored: z3.number(),
4636
- /** plune#1245. Optional and additive — a RunResult written before them validates unchanged. */
4644
+ /** Optional and additive — a RunResult written before them validates unchanged. */
4637
4645
  blocked: z3.number().optional(),
4638
4646
  skipped: z3.number().optional(),
4639
4647
  cost_usd: z3.number(),
@@ -4772,7 +4780,7 @@ var JobReporter = class {
4772
4780
  }
4773
4781
  /**
4774
4782
  * The upload is in: every row is on the platform. `subjectId` is what the job works on, learnt from the upload's
4775
- * 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.
4776
4784
  */
4777
4785
  async uploaded(at) {
4778
4786
  if (this.id === void 0) return;
@@ -4937,12 +4945,803 @@ function reportSyncFailure(err, write) {
4937
4945
 
4938
4946
  // src/cli/commands/ingest.ts
4939
4947
  init_esm_shims();
4948
+ import { promises as disk2 } from "fs";
4949
+ import * as path11 from "path";
4950
+
4951
+ // src/reporter-core/client.ts
4952
+ init_esm_shims();
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
+ });
4999
+ }
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
+ }
5021
+ );
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";
5031
+ };
5032
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5033
+ async function detailOf(res) {
5034
+ try {
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
+ };
5043
+ } catch {
5044
+ return { detail: "" };
5045
+ }
5046
+ }
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(", ");
5054
+ }
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";
4940
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
+ }
4941
5740
 
4942
5741
  // src/cli/commands/cairn-artifact.ts
4943
5742
  init_esm_shims();
4944
- import * as fs7 from "fs/promises";
4945
- import * as path8 from "path";
5743
+ import * as fs8 from "fs/promises";
5744
+ import * as path10 from "path";
4946
5745
 
4947
5746
  // src/mcp-testing/scan/config/config.ts
4948
5747
  init_esm_shims();
@@ -5634,13 +6433,21 @@ var CATALOG = [
5634
6433
  check2({
5635
6434
  id: "base-jsonrpc-parse-error",
5636
6435
  title: "Invalid JSON is a parse error",
5637
- description: "A message that is not valid JSON gets the error -32700 with id: null.",
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).",
5638
6437
  level: "MUST",
5639
6438
  derived: true,
5640
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.",
5641
6440
  specRefs: [ref4(L2, "basic/index", "Messages")],
5642
6441
  eras: BOTH3,
5643
- transports: ANY
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"]
5644
6451
  }),
5645
6452
  check2({
5646
6453
  id: "base-unknown-method-error",
@@ -6038,7 +6845,7 @@ var CATALOG = [
6038
6845
  check2({
6039
6846
  id: "http-modern-get-delete-405",
6040
6847
  title: "A modern-only server answers GET and DELETE with 405",
6041
- 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 answers initialize (dual-era) is not-applicable.",
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.",
6042
6849
  level: "SHOULD",
6043
6850
  specRefs: [ref4(M2, MT, "Earlier Streamable HTTP Revisions")],
6044
6851
  eras: ["modern"],
@@ -6214,7 +7021,7 @@ var CATALOG = [
6214
7021
  check2({
6215
7022
  id: "mod-no-session-id",
6216
7023
  title: "A modern-only server neither mints nor echoes a session id",
6217
- 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) is not-applicable.",
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.",
6218
7025
  level: "SHOULD",
6219
7026
  specRefs: [ref4(M2, MT, "Earlier Streamable HTTP Revisions")],
6220
7027
  eras: MODERN3,
@@ -6352,7 +7159,7 @@ var BY_ID = new Map(CATALOG.map((e) => [e.id, e]));
6352
7159
 
6353
7160
  // src/mcp-testing/conformance/profile.ts
6354
7161
  init_esm_shims();
6355
- import { createHash as createHash3 } from "crypto";
7162
+ import { createHash as createHash5 } from "crypto";
6356
7163
 
6357
7164
  // src/mcp-testing/report/human.ts
6358
7165
  init_exit_codes();
@@ -6485,14 +7292,14 @@ var NoCairnRunsError = class extends Error {
6485
7292
  }
6486
7293
  };
6487
7294
  async function findLatestCairnRun(runsDir = "runs") {
6488
- const entries = await fs7.readdir(runsDir, { withFileTypes: true }).catch(() => null);
7295
+ const entries = await fs8.readdir(runsDir, { withFileTypes: true }).catch(() => null);
6489
7296
  if (entries === null) throw new NoCairnRunsError(runsDir);
6490
7297
  let newest;
6491
7298
  for (const entry of entries) {
6492
7299
  if (!entry.isDirectory()) continue;
6493
- const dir = path8.join(runsDir, entry.name);
7300
+ const dir = path10.join(runsDir, entry.name);
6494
7301
  try {
6495
- const report = await fs7.lstat(path8.join(dir, "report.json"));
7302
+ const report = await fs8.lstat(path10.join(dir, "report.json"));
6496
7303
  if (!report.isFile()) continue;
6497
7304
  if (newest === void 0 || report.mtimeMs > newest.at) {
6498
7305
  newest = { dir, at: report.mtimeMs };
@@ -6549,7 +7356,7 @@ var MAX_MCP_CASES = 5e3;
6549
7356
  async function checkSize(dir, file) {
6550
7357
  let size;
6551
7358
  try {
6552
- const st = await fs7.stat(path8.join(dir, file));
7359
+ const st = await fs8.stat(path10.join(dir, file));
6553
7360
  if (!st.isFile()) throw new CairnArtifactShapeError(file, "", "is not a regular file");
6554
7361
  size = st.size;
6555
7362
  } catch (e) {
@@ -6567,7 +7374,7 @@ async function checkSize(dir, file) {
6567
7374
  }
6568
7375
  async function readJson(file) {
6569
7376
  try {
6570
- return JSON.parse(await fs7.readFile(file, "utf8"));
7377
+ return JSON.parse(await fs8.readFile(file, "utf8"));
6571
7378
  } catch {
6572
7379
  return void 0;
6573
7380
  }
@@ -6607,7 +7414,7 @@ async function readMcpEvidence(dir, states) {
6607
7414
  if (!await checkSize(dir, file)) return void 0;
6608
7415
  let raw;
6609
7416
  try {
6610
- raw = JSON.parse(await fs7.readFile(path8.join(dir, file), "utf8"));
7417
+ raw = JSON.parse(await fs8.readFile(path10.join(dir, file), "utf8"));
6611
7418
  } catch {
6612
7419
  throw new CairnArtifactShapeError(file, "", "is not valid JSON");
6613
7420
  }
@@ -6737,7 +7544,7 @@ async function casesFromMcp(dir, report) {
6737
7544
  });
6738
7545
  }
6739
7546
  async function defaultReadEvidence(dir) {
6740
- const raw = await readJson(path8.join(dir, "api-evidence.json"));
7547
+ const raw = await readJson(path10.join(dir, "api-evidence.json"));
6741
7548
  if (!Array.isArray(raw)) return void 0;
6742
7549
  return raw.map((r) => {
6743
7550
  const rec = asRecord(r);
@@ -6781,7 +7588,7 @@ function casesFromApi(report, verdicts) {
6781
7588
  }
6782
7589
  async function readCairnRun(dir, deps = {}) {
6783
7590
  await checkSize(dir, "report.json");
6784
- const raw = await readJson(path8.join(dir, "report.json"));
7591
+ const raw = await readJson(path10.join(dir, "report.json"));
6785
7592
  if (raw === void 0) throw new CairnRunNotFoundError(dir);
6786
7593
  const report = asRecord(raw);
6787
7594
  if (report["schemaVersion"] !== SUPPORTED_ARTIFACT_VERSION) {
@@ -6813,13 +7620,46 @@ async function readCairnRun(dir, deps = {}) {
6813
7620
  return {
6814
7621
  schemaVersion: INGEST_SCHEMA_VERSION,
6815
7622
  run: {
6816
- runId: str(report["runId"], path8.basename(dir)),
7623
+ runId: str(report["runId"], path10.basename(dir)),
6817
7624
  mode,
6818
7625
  target: str(report["url"], "unknown")
6819
7626
  },
6820
7627
  cases
6821
7628
  };
6822
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
+ }
6823
7663
 
6824
7664
  // src/cli/commands/ingest.ts
6825
7665
  var IngestNotLoggedInError = class extends Error {
@@ -6848,6 +7688,131 @@ var IngestHttpError = class extends Error {
6848
7688
  }
6849
7689
  status;
6850
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
+ }
6851
7816
  async function safeErrorDetail2(res) {
6852
7817
  try {
6853
7818
  const body = await res.json();
@@ -6865,10 +7830,14 @@ async function handleIngest(deps) {
6865
7830
  const doFetch = deps.fetchImpl ?? fetch;
6866
7831
  const endpoint = `${apiUrl}/v1/ingest/cairn`;
6867
7832
  const job = new JobReporter(doFetch, apiUrl, token, "ingest");
6868
- await job.open(path9.basename(path9.resolve(dir)), payload.cases.length);
7833
+ await job.open(path11.basename(path11.resolve(dir)), payload.cases.length);
6869
7834
  try {
6870
- const result = await upload();
7835
+ const { result, ...sent } = await upload();
6871
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;
6872
7841
  await job.finish({ ok: true });
6873
7842
  if (job.problem !== void 0) result.jobProblem = job.problem;
6874
7843
  return result;
@@ -6893,12 +7862,13 @@ async function handleIngest(deps) {
6893
7862
  throw new IngestHttpError(res.status, detail);
6894
7863
  }
6895
7864
  const body = await res.json().catch(() => ({}));
6896
- return {
7865
+ const result = {
6897
7866
  runId: typeof body.runId === "string" ? body.runId : "",
6898
7867
  linked: typeof body.linked === "number" ? body.linked : 0,
6899
7868
  proposed: typeof body.proposed === "number" ? body.proposed : 0,
6900
7869
  skipped: typeof body.skipped === "number" ? body.skipped : 0
6901
7870
  };
7871
+ return { result, items: itemsOf(body), repeat: res.status === 200 };
6902
7872
  }
6903
7873
  }
6904
7874
  function reportIngestFailure(err, write) {
@@ -6919,7 +7889,8 @@ function formatIngestResult(r) {
6919
7889
  `Ingested Cairn run \u2192 ${r.runId}`,
6920
7890
  ` ${r.linked} result(s) attached to existing cases`,
6921
7891
  ` ${r.proposed} case(s) proposed \u2014 review them in Plune to accept`,
6922
- ` ${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}`)
6923
7894
  ];
6924
7895
  return `${lines.join("\n")}
6925
7896
  `;