@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.cjs CHANGED
@@ -50,16 +50,16 @@ function machineless(raw, repoRoot, home) {
50
50
  if (repoRoot === void 0) text = text.replace(ANY_HOME, "~");
51
51
  return text;
52
52
  }
53
- function pathIn(path9) {
54
- const parts = path9.split(/[\\/]+/);
53
+ function pathIn(path11) {
54
+ const parts = path11.split(/[\\/]+/);
55
55
  while (parts.length > 1 && parts.at(-1) === "") parts.pop();
56
56
  if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
57
57
  const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
58
- const escaped = /^\/(?!\/)/.test(path9) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
58
+ const escaped = /^\/(?!\/)/.test(path11) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
59
59
  const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
60
60
  return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
61
61
  }
62
- var import_node_fs, import_node_os, import_node_path, import_node_util, printable, PATH_START, HEADLINE_LIMIT, ANY_HOME;
62
+ var import_node_fs, import_node_os, import_node_path, import_node_util, printable, mediaTypeOf, TEXT_TYPES, PATH_START, HEADLINE_LIMIT, ANY_HOME;
63
63
  var init_failure_detail = __esm({
64
64
  "src/reporter-core/failure-detail.ts"() {
65
65
  "use strict";
@@ -69,6 +69,8 @@ var init_failure_detail = __esm({
69
69
  import_node_path = require("path");
70
70
  import_node_util = require("util");
71
71
  printable = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, "?");
72
+ mediaTypeOf = (contentType) => contentType?.split(";")[0]?.trim().toLowerCase() || void 0;
73
+ TEXT_TYPES = /* @__PURE__ */ new Set(["application/json", "text/plain"]);
72
74
  PATH_START = "(?<![\\w.~%/\\\\-])";
73
75
  HEADLINE_LIMIT = 8 * 1024;
74
76
  ANY_HOME = /(?<=^|[\s'"`(=,[])(?:(?:file|webpack|webpack-internal):(?:\\*\/){2,3})?(?:\\*\/home\\*\/|\\*\/Users\\*\/|[A-Za-z]:[\\/]+Users[\\/]+)[^\\/\s'"`:*?<>|]+/g;
@@ -86,9 +88,9 @@ var init_exit_codes = __esm({
86
88
  });
87
89
 
88
90
  // src/mcp-testing/connect/journal.ts
89
- function openJournal(path9, redact) {
90
- if (path9 === void 0) return NONE;
91
- const fd = (0, import_node_fs2.openSync)(path9, "w", 384);
91
+ function openJournal(path11, redact) {
92
+ if (path11 === void 0) return NONE;
93
+ const fd = (0, import_node_fs2.openSync)(path11, "w", 384);
92
94
  if (process.platform !== "win32") (0, import_node_fs2.fchmodSync)(fd, 384);
93
95
  const start = import_node_perf_hooks.performance.now();
94
96
  let closed = false;
@@ -440,18 +442,18 @@ function readLines(stream, onLine, stats) {
440
442
  if (stats !== void 0 && rest.length > stats.high) stats.high = rest.length;
441
443
  partial = rest.slice(0, STDERR_LINE_LIMIT);
442
444
  };
443
- return new Promise((resolve8) => {
445
+ return new Promise((resolve9) => {
444
446
  let done = false;
445
447
  const finish = () => {
446
448
  if (done) return;
447
449
  done = true;
448
450
  feed(decoder.end());
449
451
  if (partial !== "") onLine(partial.endsWith("\r") ? partial.slice(0, -1) : partial);
450
- resolve8();
452
+ resolve9();
451
453
  };
452
454
  stream.on(
453
455
  "data",
454
- (chunk) => feed(typeof chunk === "string" ? chunk : decoder.write(chunk))
456
+ (chunk2) => feed(typeof chunk2 === "string" ? chunk2 : decoder.write(chunk2))
455
457
  );
456
458
  stream.once("end", finish);
457
459
  stream.once("close", finish);
@@ -522,9 +524,9 @@ function watchOverflow(transport, over) {
522
524
  const buffer = transport._readBuffer;
523
525
  const append = buffer?.append?.bind(buffer);
524
526
  if (buffer === void 0 || append === void 0) return;
525
- buffer.append = (chunk) => {
527
+ buffer.append = (chunk2) => {
526
528
  try {
527
- append(chunk);
529
+ append(chunk2);
528
530
  } catch (err) {
529
531
  over();
530
532
  throw err;
@@ -745,7 +747,7 @@ async function openSession(config, options = {}) {
745
747
  const stdin = transport._process?.stdin;
746
748
  if (stdin === null || stdin === void 0 || stdin.writableEnded)
747
749
  throw spawnError !== void 0 ? await toConnectError(spawnError) : new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
748
- return new Promise((resolve8, reject) => {
750
+ return new Promise((resolve9, reject) => {
749
751
  const done = () => {
750
752
  clearTimeout(timer2);
751
753
  listeners.delete(listener);
@@ -759,7 +761,7 @@ async function openSession(config, options = {}) {
759
761
  const frame2 = parsed(line);
760
762
  if (!answers(frame2, id)) return;
761
763
  done();
762
- resolve8({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
764
+ resolve9({ frame: frame2, text: clean(line).slice(0, RAW_TEXT) });
763
765
  };
764
766
  const stop = () => {
765
767
  done();
@@ -839,10 +841,10 @@ async function openSession(config, options = {}) {
839
841
  const proc = transport._process;
840
842
  if (proc === void 0) return true;
841
843
  if (proc.exitCode !== null || proc.signalCode !== null) return true;
842
- const exited = new Promise((resolve8) => proc.once("exit", () => resolve8(true)));
844
+ const exited = new Promise((resolve9) => proc.once("exit", () => resolve9(true)));
843
845
  proc.stdin?.end();
844
846
  let timer2;
845
- const late = new Promise((resolve8) => timer2 = setTimeout(() => resolve8(false), waitMs));
847
+ const late = new Promise((resolve9) => timer2 = setTimeout(() => resolve9(false), waitMs));
846
848
  const result = await Promise.race([exited, late]);
847
849
  clearTimeout(timer2);
848
850
  return result;
@@ -1502,11 +1504,11 @@ var pluneConfigSchema = import_zod.z.object({
1502
1504
  config.evals.forEach((evalConfig, i) => {
1503
1505
  const server = evalConfig.mcp?.server;
1504
1506
  if (server === void 0) {
1505
- const misplaced = (assertions, path9) => assertions.forEach((a, j) => {
1507
+ const misplaced = (assertions, path11) => assertions.forEach((a, j) => {
1506
1508
  if (TOOL_CALL_TYPES.has(a.type))
1507
1509
  ctx.addIssue({
1508
1510
  code: "custom",
1509
- path: [...path9, j, "type"],
1511
+ path: [...path11, j, "type"],
1510
1512
  message: `"${a.type}" reads the tool calls of an eval with mcp, and eval "${evalConfig.id}" has no mcp block`
1511
1513
  });
1512
1514
  });
@@ -1675,7 +1677,7 @@ function normalizeProviderError(err, secret, envVar) {
1675
1677
  }
1676
1678
 
1677
1679
  // src/providers/retry.ts
1678
- var defaultSleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
1680
+ var defaultSleep = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
1679
1681
  function retryAfterMs(err) {
1680
1682
  if (typeof err !== "object" || err === null || !("headers" in err)) return void 0;
1681
1683
  const raw = readHeader(err.headers, "retry-after");
@@ -1697,7 +1699,7 @@ function readHeader(headers, name) {
1697
1699
  return typeof v === "string" || typeof v === "number" ? v : void 0;
1698
1700
  }
1699
1701
  async function withRetry(fn, options) {
1700
- const { base_delay_ms = 500, sleep = defaultSleep, random = Math.random } = options;
1702
+ const { base_delay_ms = 500, sleep: sleep2 = defaultSleep, random = Math.random } = options;
1701
1703
  const maxRetries = Math.max(0, Math.floor(options.max_retries));
1702
1704
  let attempt = 0;
1703
1705
  for (; ; ) {
@@ -1713,7 +1715,7 @@ async function withRetry(fn, options) {
1713
1715
  const backoff = base_delay_ms * 2 ** attempt;
1714
1716
  const jitter = backoff * 0.1 * random();
1715
1717
  const delay = Math.max(backoff + jitter, retryAfterMs(err) ?? 0);
1716
- await sleep(delay);
1718
+ await sleep2(delay);
1717
1719
  attempt += 1;
1718
1720
  }
1719
1721
  }
@@ -2129,6 +2131,13 @@ function makeEstimateProvider(config, pricing) {
2129
2131
 
2130
2132
  // src/providers/mock.ts
2131
2133
  init_cjs_shims();
2134
+ function picked(pick, tools) {
2135
+ const words = pick.toLowerCase().split(/\s+/).filter(Boolean);
2136
+ const hits = tools.filter(
2137
+ (t) => words.every((w) => (t.description ?? "").toLowerCase().includes(w))
2138
+ );
2139
+ return hits.length === 1 ? hits[0].name : void 0;
2140
+ }
2132
2141
  var USAGE = { input_tokens: 10, output_tokens: 5 };
2133
2142
  function parseMockScript(text) {
2134
2143
  let parsed2;
@@ -2143,7 +2152,7 @@ function parseMockScript(text) {
2143
2152
  if (t !== void 0 && typeof t !== "string") return false;
2144
2153
  if (calls === void 0) return true;
2145
2154
  return Array.isArray(calls) && calls.every(
2146
- (c) => typeof c === "object" && c !== null && typeof c.name === "string"
2155
+ (c) => typeof c === "object" && c !== null && (typeof c.name === "string" || typeof c.pick === "string")
2147
2156
  );
2148
2157
  };
2149
2158
  if (!Array.isArray(parsed2) || parsed2.length === 0 || !parsed2.every(isStep))
@@ -2162,14 +2171,13 @@ function makeMockProvider(script) {
2162
2171
  respond: (req) => {
2163
2172
  const step = req.messages.filter((m) => m.role === "assistant").length;
2164
2173
  const entry = script[Math.min(step, script.length - 1)];
2165
- const calls = entry.tool_calls ?? [];
2174
+ const calls = (entry.tool_calls ?? []).flatMap((c) => {
2175
+ const name = "name" in c ? c.name : picked(c.pick, req.tools);
2176
+ return name === void 0 ? [] : [{ name, args: c.args ?? {} }];
2177
+ });
2166
2178
  return Promise.resolve({
2167
2179
  text: entry.text ?? "",
2168
- tool_calls: calls.map((c, i) => ({
2169
- id: `call_${step}_${i}`,
2170
- name: c.name,
2171
- args: c.args ?? {}
2172
- })),
2180
+ tool_calls: calls.map((c, i) => ({ id: `call_${step}_${i}`, ...c })),
2173
2181
  usage: USAGE,
2174
2182
  finish_reason: calls.length > 0 ? "tool_calls" : "stop"
2175
2183
  });
@@ -2218,7 +2226,7 @@ var XenovaEmbedder = class {
2218
2226
  throw new Error(
2219
2227
  "The `semantic-similarity` and RAG assertions need local embeddings, which ship separately: install @huggingface/transformers to enable them. Every other assertion works without it."
2220
2228
  );
2221
- }).then(({ pipeline }) => pipeline("feature-extraction", MODEL_ID));
2229
+ }).then(({ pipeline: pipeline2 }) => pipeline2("feature-extraction", MODEL_ID));
2222
2230
  return this.extractor;
2223
2231
  }
2224
2232
  };
@@ -3381,9 +3389,9 @@ var testCaseBaseSchema = import_zod2.z.object({
3381
3389
  schemaVersion: import_zod2.z.literal(TEST_CASE_SCHEMA_VERSION),
3382
3390
  id: import_zod2.z.string().min(1),
3383
3391
  externalKeys: import_zod2.z.array(externalKeySchema).optional(),
3384
- /** ADR 0045 / plune#1246 — optional, purely additive; schemaVersion stays 2. */
3392
+ /** Optional, purely additive; schemaVersion stays 2. */
3385
3393
  is_flaky: import_zod2.z.boolean().optional(),
3386
- /** ADR 0045 / plune#1246 — optional, purely additive; schemaVersion stays 2. */
3394
+ /** Optional, purely additive; schemaVersion stays 2. */
3387
3395
  is_muted: import_zod2.z.boolean().optional()
3388
3396
  });
3389
3397
  var testCaseSchema = import_zod2.z.discriminatedUnion("type", [
@@ -3449,7 +3457,7 @@ function segment(key) {
3449
3457
  const plain = /^[A-Za-z_][\w-]*$/.test(key) && key.length <= 40 && !UUID.test(key) && !EMAIL.test(key);
3450
3458
  return plain ? key : "*";
3451
3459
  }
3452
- var cap = (path9) => path9.length > MAX_PATH ? path9.slice(0, MAX_PATH) : path9;
3460
+ var cap = (path11) => path11.length > MAX_PATH ? path11.slice(0, MAX_PATH) : path11;
3453
3461
  var hashOf = (v) => sha256(v).slice(0, 16);
3454
3462
  function noteValue(out, v, at) {
3455
3463
  if (typeof v !== "string" || v.length < MIN_VALUE) return;
@@ -3458,20 +3466,20 @@ function noteValue(out, v, at) {
3458
3466
  where.add(at);
3459
3467
  out.values.set(h, where);
3460
3468
  }
3461
- function walk(value, path9, depth, out) {
3469
+ function walk(value, path11, depth, out) {
3462
3470
  if (depth > SCAN_DEPTH) return;
3463
3471
  if (typeof value === "string" && UUID.test(value)) {
3464
- const at = cap(path9 === "" ? "(root)" : path9);
3472
+ const at = cap(path11 === "" ? "(root)" : path11);
3465
3473
  out.paths.add(at);
3466
3474
  noteValue(out, value, at);
3467
3475
  }
3468
3476
  if (Array.isArray(value)) {
3469
- for (const item of value.slice(0, SCAN_ITEMS)) walk(item, `${path9}[]`, depth + 1, out);
3477
+ for (const item of value.slice(0, SCAN_ITEMS)) walk(item, `${path11}[]`, depth + 1, out);
3470
3478
  return;
3471
3479
  }
3472
3480
  if (!isRecord3(value)) return;
3473
3481
  for (const [key, v] of Object.entries(value)) {
3474
- const at = cap(path9 === "" ? segment(key) : `${path9}.${segment(key)}`);
3482
+ const at = cap(path11 === "" ? segment(key) : `${path11}.${segment(key)}`);
3475
3483
  if (isIdKey(key) && (isScalar(v) || Array.isArray(v) && v.length > 0 && v.every(isScalar))) {
3476
3484
  out.paths.add(at);
3477
3485
  for (const x of Array.isArray(v) ? v : [v]) noteValue(out, x, at);
@@ -4594,7 +4602,7 @@ var rowResultSchema = import_zod3.z.object({
4594
4602
  error: runErrorSchema.optional(),
4595
4603
  assertions: import_zod3.z.array(assertionResultRecordSchema2),
4596
4604
  cache_saved: savedSchema.optional(),
4597
- /** ADR 0045. Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
4605
+ /** Optional and additive — the same enum the platform validates on `POST /v1/runs`. */
4598
4606
  inconclusive: import_zod3.z.enum(ROW_INCONCLUSIVE).optional(),
4599
4607
  /** Repeats (`runs` above 1). Optional and additive — a RunResult without it validates unchanged. */
4600
4608
  attempts: import_zod3.z.object({
@@ -4671,7 +4679,7 @@ var summarySchema = import_zod3.z.object({
4671
4679
  passed: import_zod3.z.number(),
4672
4680
  failed: import_zod3.z.number(),
4673
4681
  errored: import_zod3.z.number(),
4674
- /** plune#1245. Optional and additive — a RunResult written before them validates unchanged. */
4682
+ /** Optional and additive — a RunResult written before them validates unchanged. */
4675
4683
  blocked: import_zod3.z.number().optional(),
4676
4684
  skipped: import_zod3.z.number().optional(),
4677
4685
  cost_usd: import_zod3.z.number(),
@@ -4810,7 +4818,7 @@ var JobReporter = class {
4810
4818
  }
4811
4819
  /**
4812
4820
  * The upload is in: every row is on the platform. `subjectId` is what the job works on, learnt from the upload's
4813
- * answer (the run an ingest landed in): the platform takes it while the job names none (#1279).
4821
+ * answer (the run an ingest landed in): the platform takes it while the job names none.
4814
4822
  */
4815
4823
  async uploaded(at) {
4816
4824
  if (this.id === void 0) return;
@@ -4975,12 +4983,803 @@ function reportSyncFailure(err, write) {
4975
4983
 
4976
4984
  // src/cli/commands/ingest.ts
4977
4985
  init_cjs_shims();
4986
+ var import_node_fs8 = require("fs");
4987
+ var path10 = __toESM(require("path"), 1);
4988
+
4989
+ // src/reporter-core/client.ts
4990
+ init_cjs_shims();
4991
+ var import_node_fs5 = require("fs");
4992
+ var import_node_stream = require("stream");
4993
+ var import_node_http = require("http");
4994
+ var import_node_https = require("https");
4995
+ var BACKOFF_BASE_MS = 300;
4996
+ var BACKOFF_CAP_MS = 1e4;
4997
+ var DEFAULT_RETRIES = 2;
4998
+ var RETRY_AFTER_CAP_MS = 6e4;
4999
+ function parseRetryAfter(raw, now = Date.now()) {
5000
+ const text = raw?.trim();
5001
+ if (text === void 0 || text === "") return null;
5002
+ const seconds = /^\d+(\.\d+)?$/.test(text) ? Number(text) : (Date.parse(text) - now) / 1e3;
5003
+ if (!Number.isFinite(seconds)) return null;
5004
+ return Math.min(Math.max(seconds, 0) * 1e3, RETRY_AFTER_CAP_MS);
5005
+ }
5006
+ var POOLS = { "http:": new import_node_http.Agent({ keepAlive: true }), "https:": new import_node_https.Agent({ keepAlive: true }) };
5007
+ var IDLE_MS = 3e5;
5008
+ function nodeTransport(url, init, idleMs = IDLE_MS) {
5009
+ return new Promise((resolve9, reject) => {
5010
+ const target = new URL(url);
5011
+ const send = target.protocol === "https:" ? import_node_https.request : import_node_http.request;
5012
+ const agent = POOLS[target.protocol === "https:" ? "https:" : "http:"];
5013
+ const req = send(target, { method: init.method, headers: init.headers, agent }, (res) => {
5014
+ const chunks = [];
5015
+ res.on("data", (chunk2) => chunks.push(chunk2));
5016
+ res.on("error", reject);
5017
+ res.on("end", () => {
5018
+ const status = res.statusCode ?? 0;
5019
+ const text = Buffer.concat(chunks).toString("utf8");
5020
+ resolve9({
5021
+ ok: status >= 200 && status <= 299,
5022
+ status,
5023
+ headers: {
5024
+ get: (name) => {
5025
+ const value = res.headers[name.toLowerCase()];
5026
+ return value === void 0 ? null : Array.isArray(value) ? value.join(", ") : value;
5027
+ }
5028
+ },
5029
+ json: async () => JSON.parse(text)
5030
+ });
5031
+ });
5032
+ });
5033
+ req.setTimeout(idleMs, () => req.destroy(new Error(`no answer from ${target.origin} in ${idleMs} ms`)));
5034
+ req.on("error", reject);
5035
+ req.end(init.body);
5036
+ });
5037
+ }
5038
+ var withoutLength = (headers) => Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== "content-length"));
5039
+ function nodePut(url, headers, source, idleMs) {
5040
+ return new Promise((resolve9, reject) => {
5041
+ const target = new URL(url);
5042
+ const send = target.protocol === "https:" ? import_node_https.request : import_node_http.request;
5043
+ const length = "body" in source ? source.body.length : source.size;
5044
+ let answered;
5045
+ const settle = (err) => answered !== void 0 ? resolve9(answered) : reject(err);
5046
+ const req = send(
5047
+ target,
5048
+ { method: "PUT", headers: { ...withoutLength(headers), "content-length": String(length) } },
5049
+ (res) => {
5050
+ const retry = res.headers["retry-after"];
5051
+ answered = { status: res.statusCode ?? 0, retryAfter: Array.isArray(retry) ? retry[0] ?? null : retry ?? null };
5052
+ res.on("error", settle);
5053
+ res.on("close", () => {
5054
+ resolve9(answered);
5055
+ req.destroy();
5056
+ });
5057
+ res.resume();
5058
+ }
5059
+ );
5060
+ req.setTimeout(idleMs, () => req.destroy(Object.assign(new Error("idle"), { code: "ETIMEDOUT" })));
5061
+ req.on("error", settle);
5062
+ if ("body" in source) req.end(source.body);
5063
+ else (0, import_node_stream.pipeline)((0, import_node_fs5.createReadStream)(source.path), req, (err) => err ? settle(err) : void 0);
5064
+ });
5065
+ }
5066
+ var codeOfError = (err) => {
5067
+ const code = err?.code;
5068
+ return typeof code === "string" && /^[A-Z0-9_]{2,40}$/.test(code) ? code : "network";
5069
+ };
5070
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5071
+ async function detailOf(res) {
5072
+ try {
5073
+ const body = await res.json();
5074
+ const q = body.quota;
5075
+ return {
5076
+ ...typeof body.shardsExpected === "number" && Number.isInteger(body.shardsExpected) ? { shardsExpected: body.shardsExpected } : {},
5077
+ detail: typeof body.error === "string" ? body.error : "",
5078
+ ...typeof q === "object" && q !== null && !Array.isArray(q) ? { quota: q } : {},
5079
+ ...typeof body.code === "string" && /^[a-z0-9_]{1,60}$/.test(body.code) ? { code: body.code } : {}
5080
+ };
5081
+ } catch {
5082
+ return { detail: "" };
5083
+ }
5084
+ }
5085
+ function describeQuota(q) {
5086
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
5087
+ const kind = typeof q["kind"] === "string" ? q["kind"].slice(0, 60) : "limit";
5088
+ const [used, limit2] = [num(q["used"]), num(q["limit"])];
5089
+ const parts = [used !== void 0 && limit2 !== void 0 ? `${kind}: ${used} of ${limit2} used` : kind];
5090
+ if (typeof q["resetsAt"] === "string" && q["resetsAt"] !== "") parts.push(`resets ${q["resetsAt"].slice(0, 40)}`);
5091
+ return parts.join(", ");
5092
+ }
5093
+ function classify(status) {
5094
+ if (status === 401 || status === 403) return "auth";
5095
+ if (status === 409) return "conflict";
5096
+ if (status === 400) return "invalid";
5097
+ if (status === 429 || status >= 500) return "unavailable";
5098
+ return "other";
5099
+ }
5100
+ function createClient(opts) {
5101
+ const doFetch = opts.fetchImpl ?? nodeTransport;
5102
+ const wait = opts.wait ?? sleep;
5103
+ const uploadRetries = opts.uploadRetries === void 0 ? void 0 : Math.max(0, Math.floor(opts.uploadRetries));
5104
+ const random = opts.random ?? Math.random;
5105
+ const now = opts.now ?? Date.now;
5106
+ let pausedUntil = 0;
5107
+ const jittered = (ms) => Math.round(ms * (1 + random() * 0.5));
5108
+ async function backOff(attempt, said) {
5109
+ opts.onRetry?.();
5110
+ const ms = jittered(said ?? Math.min(BACKOFF_BASE_MS * 2 ** attempt, BACKOFF_CAP_MS));
5111
+ const until = now() + ms;
5112
+ pausedUntil = Math.max(pausedUntil, until);
5113
+ await wait(ms);
5114
+ return until;
5115
+ }
5116
+ async function respectPause(mine) {
5117
+ const left = pausedUntil - now();
5118
+ if (pausedUntil > mine && left > 0) await wait(left + Math.round(random() * 250));
5119
+ }
5120
+ const base = opts.apiUrl.replace(/\/+$/, "");
5121
+ const scrub = (text) => opts.token === "" ? text : text.split(opts.token).join("***");
5122
+ async function send(method, path11, payload, retries = DEFAULT_RETRIES) {
5123
+ let last = {
5124
+ kind: "unavailable",
5125
+ status: null,
5126
+ detail: "no attempt was made"
5127
+ };
5128
+ let mine = 0;
5129
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
5130
+ await respectPause(mine);
5131
+ let res;
5132
+ try {
5133
+ res = await doFetch(`${base}${path11}`, {
5134
+ method,
5135
+ headers: { "content-type": payload?.type ?? "application/json", authorization: `Bearer ${opts.token}` },
5136
+ // A DELETE carries none. Sending `"undefined"` as a body is what a naive
5137
+ // `JSON.stringify(body)` would do, and some proxies answer that with a 400 nobody can
5138
+ // explain.
5139
+ ...payload === void 0 ? {} : { body: payload.body }
5140
+ });
5141
+ } catch (err) {
5142
+ last = { kind: "unavailable", status: null, detail: scrub(String(err)) };
5143
+ if (attempt >= Math.min(retries, DEFAULT_RETRIES)) break;
5144
+ mine = await backOff(attempt, null);
5145
+ continue;
5146
+ }
5147
+ if (res.ok) {
5148
+ if (res.status === 204) return { ok: true, status: res.status, body: void 0 };
5149
+ try {
5150
+ return { ok: true, status: res.status, body: await res.json() };
5151
+ } catch {
5152
+ return { ok: false, kind: "other", status: res.status, detail: "the answer was not JSON" };
5153
+ }
5154
+ }
5155
+ const said = await detailOf(res);
5156
+ const kind = classify(res.status);
5157
+ last = { kind, status: res.status, detail: scrub(said.detail), ...said.code !== void 0 ? { code: said.code } : {}, ...said.shardsExpected !== void 0 ? { shardsExpected: said.shardsExpected } : {} };
5158
+ if (kind !== "unavailable") break;
5159
+ const said429 = parseRetryAfter(res.headers.get("retry-after"), now());
5160
+ if (res.status === 429 && (said.quota !== void 0 || said429 === null)) {
5161
+ last.kind = "invalid";
5162
+ last.detail = `quota exceeded (${said.quota === void 0 ? "no Retry-After" : scrub(describeQuota(said.quota))})`;
5163
+ if (said.detail) last.detail += ` \u2014 ${scrub(said.detail)}`;
5164
+ break;
5165
+ }
5166
+ if (attempt >= (said429 === null ? Math.min(retries, DEFAULT_RETRIES) : retries)) break;
5167
+ mine = await backOff(attempt, said429);
5168
+ }
5169
+ return { ok: false, ...last };
5170
+ }
5171
+ return {
5172
+ post: (path11, body, retries) => send("POST", path11, { body: JSON.stringify(body), type: "application/json" }, retries),
5173
+ upload: (path11, bytes, contentType) => send("POST", path11, { body: bytes, type: contentType }, uploadRetries ?? DEFAULT_RETRIES),
5174
+ del: (path11) => send("DELETE", path11),
5175
+ get: (path11) => send("GET", path11),
5176
+ async put(url, headers, source) {
5177
+ const putRetries = uploadRetries ?? 3;
5178
+ let last = { ok: false, status: null, code: "network" };
5179
+ let mine = 0;
5180
+ for (let attempt = 0; attempt <= putRetries; attempt += 1) {
5181
+ await respectPause(mine);
5182
+ try {
5183
+ let status;
5184
+ let retryAfter;
5185
+ if (opts.fetchImpl === void 0) ({ status, retryAfter } = await nodePut(url, headers, source, IDLE_MS));
5186
+ else {
5187
+ const body = "body" in source ? source.body : await (0, import_node_fs5.openAsBlob)(source.path);
5188
+ const res = await opts.fetchImpl(url, { method: "PUT", headers: withoutLength(headers), body });
5189
+ await res.arrayBuffer().catch(() => void 0);
5190
+ status = res.status;
5191
+ retryAfter = res.headers.get("retry-after");
5192
+ }
5193
+ if (status >= 200 && status <= 299) return { ok: true };
5194
+ last = { ok: false, status, code: `bucket_${status}` };
5195
+ if (status < 500 && status !== 429) return last;
5196
+ const said = parseRetryAfter(retryAfter, now());
5197
+ if (attempt >= (said === null ? Math.min(putRetries, 3) : putRetries)) return last;
5198
+ mine = await backOff(attempt, said);
5199
+ continue;
5200
+ } catch (err) {
5201
+ last = { ok: false, status: null, code: codeOfError(err) };
5202
+ }
5203
+ if (attempt >= Math.min(putRetries, 3)) return last;
5204
+ mine = await backOff(attempt, null);
5205
+ }
5206
+ return last;
5207
+ }
5208
+ };
5209
+ }
5210
+
5211
+ // src/reporter-core/env.ts
5212
+ init_cjs_shims();
5213
+ var path7 = __toESM(require("path"), 1);
5214
+ var UPLOAD_RETRIES = { min: 0, max: 20, default: 6 };
5215
+
5216
+ // src/reporter-core/session.ts
5217
+ init_cjs_shims();
5218
+ var import_node_crypto4 = require("crypto");
5219
+ var import_node_fs7 = require("fs");
5220
+ var import_node_path3 = require("path");
5221
+ var import_node_util2 = require("util");
5222
+ init_failure_detail();
5223
+
5224
+ // src/reporter-core/files-batch.ts
5225
+ init_cjs_shims();
5226
+ var import_node_crypto3 = require("crypto");
5227
+ var import_node_fs6 = require("fs");
5228
+ var FILES_BATCH_MAX = 100;
5229
+ var DIRECT_BATCH_BYTES = 6 * 1024 * 1024;
5230
+ var BATCH_PIPELINES = 2;
5231
+ async function sha256File(path11) {
5232
+ const hash = (0, import_node_crypto3.createHash)("sha256");
5233
+ for await (const part of (0, import_node_fs6.createReadStream)(path11)) hash.update(part);
5234
+ return hash.digest("hex");
5235
+ }
5236
+ var sha256Bytes = (bytes) => (0, import_node_crypto3.createHash)("sha256").update(bytes).digest("hex");
5237
+ var BUCKET_CODES = /* @__PURE__ */ new Set([
5238
+ "bucket_unreachable",
5239
+ "not_connected",
5240
+ "platform_not_configured",
5241
+ "upload_expired",
5242
+ "file_mismatch",
5243
+ "file_missing"
5244
+ ]);
5245
+
5246
+ // src/reporter-core/fallback.ts
5247
+ init_cjs_shims();
5248
+ var fs7 = __toESM(require("fs"), 1);
4978
5249
  var path8 = __toESM(require("path"), 1);
5250
+ var DEFAULT_FALLBACK_PATH = path8.join(".plune", "pending-results.jsonl");
5251
+
5252
+ // src/reporter-core/session.ts
5253
+ var SCREENSHOT_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp"]);
5254
+ var SCREENSHOT_BYTES = 2 * 1024 * 1024;
5255
+ var SCREENSHOTS_PER_RESULT = 20;
5256
+ var TEXT_BYTES = 512 * 1024;
5257
+ var TEXTS_PER_RESULT = 10;
5258
+ var UTF8 = new import_node_util2.TextDecoder("utf-8", { fatal: true });
5259
+ var TYPE_BY_EXTENSION = {
5260
+ ".png": "image/png",
5261
+ ".jpg": "image/jpeg",
5262
+ ".jpeg": "image/jpeg",
5263
+ ".webp": "image/webp"
5264
+ };
5265
+ var METADATA_TYPE = "application/plune.metadata+json";
5266
+ var NAME_MAX = 200;
5267
+ function nameOf(file) {
5268
+ const own2 = file.name.split(/[\\/]/).pop()?.trim() || (file.path === void 0 ? "" : (0, import_node_path3.basename)(file.path));
5269
+ const fileExt = file.path === void 0 ? "" : (0, import_node_path3.extname)(file.path);
5270
+ const ownExt = (0, import_node_path3.extname)(own2);
5271
+ const typed = ownExt !== "" && (ownExt.toLowerCase() === fileExt.toLowerCase() || TYPE_BY_EXTENSION[ownExt.toLowerCase()] !== void 0);
5272
+ const ext = typed ? ownExt : fileExt;
5273
+ let stem = typed ? own2.slice(0, -ownExt.length) : own2;
5274
+ if (stem.length + ext.length > NAME_MAX) {
5275
+ stem = stem.slice(0, Math.max(0, NAME_MAX - ext.length));
5276
+ if (/[\uD800-\uDBFF]$/.test(stem)) stem = stem.slice(0, -1);
5277
+ }
5278
+ return `${stem}${ext}`;
5279
+ }
5280
+ var SKIPPED = {
5281
+ hidden: "its name starts with an underscore, which hides an attachment in Playwright's own reports too",
5282
+ type: "Plune takes PNG, JPEG and WebP",
5283
+ limit: `a result holds at most ${SCREENSHOTS_PER_RESULT}`,
5284
+ missing: "the file cannot be read on this machine",
5285
+ size: "Plune takes a file of at most 2 MB",
5286
+ textLimit: `a result holds at most ${TEXTS_PER_RESULT} text files`,
5287
+ textSize: "Plune takes a text file of at most 512 KiB",
5288
+ empty: "the file is empty",
5289
+ binary: "the file holds a NUL byte, and Plune takes UTF-8 text without one",
5290
+ encoding: "Plune takes UTF-8 text only",
5291
+ noStorage: "no storage bucket is connected to this project"
5292
+ };
5293
+ var BUCKET_FOUND = "plune: storage bucket found for this project \u2014 screenshots, text, trace and video go straight to it over short-lived links.";
5294
+ var KINDS = {
5295
+ screenshot: { label: "screenshot", bytes: SCREENSHOT_BYTES, room: SCREENSHOTS_PER_RESULT, limit: "limit", size: "size" },
5296
+ text: { label: "text file", bytes: TEXT_BYTES, room: TEXTS_PER_RESULT, limit: "textLimit", size: "textSize" },
5297
+ // Only the label is used: a file of this kind has no home in the database, so no ceiling of its own is known here.
5298
+ file: { label: "file", bytes: 0, room: 0, limit: "limit", size: "size" }
5299
+ };
5300
+ function kindOf2(type) {
5301
+ if (type.startsWith("image/")) return "screenshot";
5302
+ return TEXT_TYPES.has(type) ? "text" : "file";
5303
+ }
5304
+ var codeOf2 = (out) => out.code ?? (out.status === null ? "network" : `http_${out.status}`);
5305
+ function linkOf(item) {
5306
+ const link = item;
5307
+ if (typeof link?.id !== "string" || typeof link.url !== "string") return void 0;
5308
+ const headers = typeof link.headers === "object" && link.headers !== null ? link.headers : {};
5309
+ return { id: link.id, url: link.url, headers };
5310
+ }
5311
+ function textTypeOf(contentType, type) {
5312
+ const charset = /;\s*charset\s*=\s*"?([^\s";]+)"?/i.exec(contentType)?.[1];
5313
+ return charset?.toLowerCase() === "utf-8" ? `${type}; charset=utf-8` : type;
5314
+ }
5315
+ function textRefusal(bytes) {
5316
+ if (bytes.length > TEXT_BYTES) return "textSize";
5317
+ if (bytes.length === 0) return "empty";
5318
+ if (bytes.includes(0)) return "binary";
5319
+ try {
5320
+ UTF8.decode(bytes);
5321
+ } catch {
5322
+ return "encoding";
5323
+ }
5324
+ return void 0;
5325
+ }
5326
+ var BATCH_BYTES = 8 * 1024 * 1024;
5327
+ var ENVELOPE_BYTES = Buffer.byteLength(JSON.stringify({ results: [] }));
5328
+ function chunk(items, size) {
5329
+ const out = [];
5330
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
5331
+ return out;
5332
+ }
5333
+ function fileSender(options) {
5334
+ const { client, log, stats, uploadsAtOnce, uploadRetries } = options;
5335
+ const without = options.without ?? "its result is reported without it";
5336
+ let retried = 0;
5337
+ let uploadMs = 0;
5338
+ let requests = 0;
5339
+ let existed = 0;
5340
+ let batchMissing = false;
5341
+ const skipsSaid = /* @__PURE__ */ new Set();
5342
+ const countsOf = (kind) => kind === "text" ? stats.textFiles : kind === "file" ? stats.otherFiles : stats.screenshots;
5343
+ let bucketSeen = false;
5344
+ let noStorage = 0;
5345
+ let uploadsMissing = false;
5346
+ const failedSaid = /* @__PURE__ */ new Set();
5347
+ const codesSaid = /* @__PURE__ */ new Set();
5348
+ const rooms = /* @__PURE__ */ new Map();
5349
+ function skip(kind, name, why) {
5350
+ countsOf(kind).skipped += 1;
5351
+ if (why === "noStorage") noStorage += 1;
5352
+ const said = why === "noStorage" ? why : `${kind}/${why}`;
5353
+ if (skipsSaid.has(said)) return;
5354
+ skipsSaid.add(said);
5355
+ if (why === "noStorage") log(`plune: "${name}" not stored \u2014 ${SKIPPED[why]}.`);
5356
+ else log(`plune: ${KINDS[kind].label} "${name}" not uploaded \u2014 ${SKIPPED[why]}.`);
5357
+ }
5358
+ const filesOf = (job) => `/v1/${job.owner ?? "results"}/${encodeURIComponent(job.id)}/files`;
5359
+ function ask(job, size) {
5360
+ requests += 1;
5361
+ return client.post(`${filesOf(job)}/uploads`, {
5362
+ files: [{ name: job.name, contentType: job.type, size }]
5363
+ }, uploadRetries);
5364
+ }
5365
+ function failed(job, why) {
5366
+ countsOf(job.kind).failed += 1;
5367
+ if (!failedSaid.has(job.kind)) {
5368
+ failedSaid.add(job.kind);
5369
+ log(`plune: could not upload a ${KINDS[job.kind].label} (${why}) \u2014 ${without}.`);
5370
+ }
5371
+ }
5372
+ function failedToBucket(job, code) {
5373
+ countsOf(job.kind).failed += 1;
5374
+ if (codesSaid.has(code)) return;
5375
+ codesSaid.add(code);
5376
+ log(`plune: "${job.name}" not uploaded to your bucket (${code}) \u2014 ${without}.`);
5377
+ }
5378
+ function refusedHere(job, size) {
5379
+ if (job.kind === "screenshot") {
5380
+ if (!SCREENSHOT_TYPES.has(job.type)) return "type";
5381
+ if (size > SCREENSHOT_BYTES) return "size";
5382
+ }
5383
+ if (job.kind === "text" && size > TEXT_BYTES) return "textSize";
5384
+ return void 0;
5385
+ }
5386
+ async function uploadDirect(job, size) {
5387
+ const { kind } = job;
5388
+ if (kind === "file") return skip(kind, job.name, "noStorage");
5389
+ const { bytes: ceiling, size: tooBig } = KINDS[kind];
5390
+ if (size > ceiling) return skip(kind, job.name, tooBig);
5391
+ let bytes;
5392
+ if (job.body !== void 0) bytes = job.body;
5393
+ else {
5394
+ try {
5395
+ bytes = await import_node_fs7.promises.readFile(job.path);
5396
+ } catch {
5397
+ return skip(kind, job.name, "missing");
5398
+ }
5399
+ }
5400
+ const refusal = kind === "text" ? textRefusal(bytes) : void 0;
5401
+ if (refusal !== void 0) return skip(kind, job.name, refusal);
5402
+ requests += 1;
5403
+ const out = await client.upload(
5404
+ `${filesOf(job)}?name=${encodeURIComponent(job.name)}`,
5405
+ bytes,
5406
+ job.type
5407
+ );
5408
+ if (out.ok) countsOf(kind).uploaded += 1;
5409
+ else failed(job, out.detail || out.kind);
5410
+ }
5411
+ async function uploadToBucket(job, size, first) {
5412
+ const source = job.body !== void 0 ? { body: job.body } : { path: job.path, size };
5413
+ let link = first;
5414
+ for (let renewed = false; ; ) {
5415
+ const put = await client.put(link.url, link.headers, source);
5416
+ if (put.ok) break;
5417
+ if (put.status !== 403 || renewed) return failedToBucket(job, put.code);
5418
+ renewed = true;
5419
+ const again = await ask(job, size);
5420
+ if (!again.ok) return failedToBucket(job, codeOf2(again));
5421
+ const fresh = linkOf(again.body?.files?.[0]);
5422
+ if (fresh === void 0) return failedToBucket(job, "bad_answer");
5423
+ link = fresh;
5424
+ }
5425
+ requests += 1;
5426
+ const done = await client.post(`/v1/files/${encodeURIComponent(link.id)}/complete`, {}, uploadRetries);
5427
+ if (!done.ok) return failedToBucket(job, codeOf2(done));
5428
+ countsOf(job.kind).uploaded += 1;
5429
+ }
5430
+ let free = uploadsAtOnce;
5431
+ const waiting = [];
5432
+ async function gated(work) {
5433
+ if (free === 0) await new Promise((resolve9) => waiting.push(resolve9));
5434
+ else free -= 1;
5435
+ try {
5436
+ return await work();
5437
+ } finally {
5438
+ const next = waiting.shift();
5439
+ if (next !== void 0) next();
5440
+ else free += 1;
5441
+ }
5442
+ }
5443
+ async function plan(job) {
5444
+ const { kind } = job;
5445
+ let size;
5446
+ if (job.body !== void 0) size = job.body.length;
5447
+ else if (job.path === void 0) return void skip(kind, job.name, "missing");
5448
+ else {
5449
+ try {
5450
+ size = (await import_node_fs7.promises.stat(job.path)).size;
5451
+ } catch {
5452
+ return void skip(kind, job.name, "missing");
5453
+ }
5454
+ }
5455
+ if (size === 0) return void skip(kind, job.name, "empty");
5456
+ const direct = () => {
5457
+ if (kind === "file") return void skip(kind, job.name, "noStorage");
5458
+ const roomKey = `${job.id}/${kind}`;
5459
+ const left = rooms.get(roomKey) ?? KINDS[kind].room;
5460
+ if (left === 0) return void skip(kind, job.name, KINDS[kind].limit);
5461
+ rooms.set(roomKey, left - 1);
5462
+ return () => uploadDirect(job, size);
5463
+ };
5464
+ if (uploadsMissing) return direct();
5465
+ const out = await gated(() => ask(job, size));
5466
+ if (!out.ok) {
5467
+ if (out.status === 404 && out.detail === "" && out.code === void 0) {
5468
+ uploadsMissing = true;
5469
+ return direct();
5470
+ }
5471
+ if (out.code !== void 0) failedToBucket(job, out.code);
5472
+ else failed(job, out.detail || out.kind);
5473
+ return void 0;
5474
+ }
5475
+ const item = out.body?.files?.[0];
5476
+ if (item?.skipped === "no_storage") return void skip(kind, job.name, refusedHere(job, size) ?? "noStorage");
5477
+ if (item?.direct === true) return direct();
5478
+ const link = linkOf(item);
5479
+ if (link === void 0) return void failed(job, "bad_answer");
5480
+ if (!bucketSeen) {
5481
+ bucketSeen = true;
5482
+ log(BUCKET_FOUND);
5483
+ }
5484
+ return () => uploadToBucket(job, size, link);
5485
+ }
5486
+ async function uploadEach(jobs) {
5487
+ const byResult = /* @__PURE__ */ new Map();
5488
+ for (const job of jobs) byResult.set(job.id, [...byResult.get(job.id) ?? [], job]);
5489
+ await Promise.all(
5490
+ [...byResult.values()].map(async (group) => {
5491
+ const work = [];
5492
+ for (const job of group) {
5493
+ const act = await plan(job);
5494
+ if (act !== void 0) work.push(gated(act));
5495
+ }
5496
+ await Promise.all(work);
5497
+ })
5498
+ );
5499
+ }
5500
+ async function measure(job) {
5501
+ let size;
5502
+ if (job.body !== void 0) size = job.body.length;
5503
+ else if (job.path === void 0) return void skip(job.kind, job.name, "missing");
5504
+ else {
5505
+ try {
5506
+ size = (await import_node_fs7.promises.stat(job.path)).size;
5507
+ } catch {
5508
+ return void skip(job.kind, job.name, "missing");
5509
+ }
5510
+ }
5511
+ if (size === 0) return void skip(job.kind, job.name, "empty");
5512
+ return size;
5513
+ }
5514
+ const routeMissing = (out) => !out.ok && out.status === 404 && out.detail === "" && out.code === void 0;
5515
+ function takeRoom(job) {
5516
+ if (job.kind === "file") {
5517
+ skip(job.kind, job.name, "noStorage");
5518
+ return false;
5519
+ }
5520
+ const roomKey = `${job.id}/${job.kind}`;
5521
+ const left = rooms.get(roomKey) ?? KINDS[job.kind].room;
5522
+ if (left === 0) {
5523
+ skip(job.kind, job.name, KINDS[job.kind].limit);
5524
+ return false;
5525
+ }
5526
+ rooms.set(roomKey, left - 1);
5527
+ return true;
5528
+ }
5529
+ function refusedItem(job, size, item) {
5530
+ const code = item.code ?? "refused";
5531
+ if (code === "duplicate") existed += 1;
5532
+ else if (code === "no_storage") skip(job.kind, job.name, refusedHere(job, size) ?? "noStorage");
5533
+ else if (code === "too_many_files") skip(job.kind, job.name, KINDS[job.kind].limit);
5534
+ else if (BUCKET_CODES.has(code)) failedToBucket(job, code);
5535
+ else failed(job, code);
5536
+ }
5537
+ const itemPause = (round) => new Promise((r) => setTimeout(r, Math.min(250 * 2 ** round, 4e3)));
5538
+ async function batchOf(jobs) {
5539
+ if (batchMissing) return uploadEach(jobs);
5540
+ const sized = [];
5541
+ for (const job of jobs) {
5542
+ const size = await measure(job);
5543
+ if (size === void 0) continue;
5544
+ try {
5545
+ sized.push({ job, size, sha256: job.body !== void 0 ? sha256Bytes(job.body) : await sha256File(job.path) });
5546
+ } catch {
5547
+ skip(job.kind, job.name, "missing");
5548
+ }
5549
+ }
5550
+ if (sized.length === 0) return;
5551
+ const announced = await gated(() => {
5552
+ requests += 1;
5553
+ return client.post(
5554
+ "/v1/files/uploads-batch",
5555
+ { items: sized.map((s) => ({ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 })) },
5556
+ uploadRetries
5557
+ );
5558
+ });
5559
+ if (routeMissing(announced)) {
5560
+ batchMissing = true;
5561
+ return uploadEach(sized.map((s) => s.job));
5562
+ }
5563
+ const verdicts = announced.ok ? announced.body?.items : void 0;
5564
+ if (!announced.ok || !Array.isArray(verdicts) || verdicts.length !== sized.length) {
5565
+ for (const s of sized) {
5566
+ if (announced.ok) failed(s.job, "bad_answer");
5567
+ else if (announced.code !== void 0) failedToBucket(s.job, announced.code);
5568
+ else failed(s.job, announced.detail || announced.kind);
5569
+ }
5570
+ return;
5571
+ }
5572
+ const puts = [];
5573
+ const directs = [];
5574
+ sized.forEach((s, i) => {
5575
+ const v = verdicts[i] ?? {};
5576
+ if (v.status === "exists") existed += 1;
5577
+ else if (v.status === "direct") {
5578
+ if (takeRoom(s.job)) directs.push(s);
5579
+ } else if (v.status === "upload") {
5580
+ const link = linkOf(v);
5581
+ if (link === void 0) return failed(s.job, "bad_answer");
5582
+ if (!bucketSeen) {
5583
+ bucketSeen = true;
5584
+ log(BUCKET_FOUND);
5585
+ }
5586
+ puts.push({ s, link });
5587
+ } else if (v.status === "refused") refusedItem(s.job, s.size, v);
5588
+ else failed(s.job, "bad_answer");
5589
+ });
5590
+ const toComplete = [];
5591
+ await Promise.all(
5592
+ puts.map(
5593
+ ({ s, link: first }) => gated(async () => {
5594
+ const source = s.job.body !== void 0 ? { body: s.job.body } : { path: s.job.path, size: s.size };
5595
+ let link = first;
5596
+ for (let renewed = false; ; ) {
5597
+ const put = await client.put(link.url, link.headers, source);
5598
+ if (put.ok) break;
5599
+ if (put.status !== 403 || renewed) return failedToBucket(s.job, put.code);
5600
+ renewed = true;
5601
+ requests += 1;
5602
+ const again = await client.post(
5603
+ "/v1/files/uploads-batch",
5604
+ { items: [{ resultId: s.job.id, name: s.job.name, contentType: s.job.type, size: s.size, sha256: s.sha256 }] },
5605
+ uploadRetries
5606
+ );
5607
+ const fresh = again.ok ? linkOf(again.body?.items?.[0]) : void 0;
5608
+ if (fresh === void 0) return failedToBucket(s.job, again.ok ? "bad_answer" : codeOf2(again));
5609
+ link = fresh;
5610
+ }
5611
+ toComplete.push({ job: s.job, id: link.id });
5612
+ })
5613
+ )
5614
+ );
5615
+ await complete(toComplete);
5616
+ await sendDirect(directs);
5617
+ }
5618
+ async function complete(items) {
5619
+ for (let round = 0; items.length > 0; round += 1) {
5620
+ const out = await gated(() => {
5621
+ requests += 1;
5622
+ return client.post("/v1/files/complete-batch", { ids: items.map((i) => i.id) }, uploadRetries);
5623
+ });
5624
+ if (routeMissing(out)) {
5625
+ await Promise.all(
5626
+ items.map(
5627
+ (i) => gated(async () => {
5628
+ requests += 1;
5629
+ const one = await client.post(`/v1/files/${encodeURIComponent(i.id)}/complete`, {}, uploadRetries);
5630
+ if (one.ok) countsOf(i.job.kind).uploaded += 1;
5631
+ else failedToBucket(i.job, codeOf2(one));
5632
+ })
5633
+ )
5634
+ );
5635
+ return;
5636
+ }
5637
+ const verdicts = out.ok ? out.body?.items : void 0;
5638
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== items.length) {
5639
+ for (const i of items) failedToBucket(i.job, out.ok ? "bad_answer" : codeOf2(out));
5640
+ return;
5641
+ }
5642
+ const again = [];
5643
+ items.forEach((i, at) => {
5644
+ const v = verdicts[at] ?? {};
5645
+ if (v.status === "ready") countsOf(i.job.kind).uploaded += 1;
5646
+ else if (v.retryable === true && round < Math.min(uploadRetries, 3)) again.push(i);
5647
+ else refusedItem(i.job, 0, v.status === "refused" ? v : { code: "bad_answer" });
5648
+ });
5649
+ items = again;
5650
+ if (items.length > 0) {
5651
+ retried += items.length;
5652
+ await itemPause(round);
5653
+ }
5654
+ }
5655
+ }
5656
+ async function sendDirect(items) {
5657
+ const groups = [];
5658
+ let bytes = 0;
5659
+ for (const item of items) {
5660
+ const group = groups[groups.length - 1];
5661
+ if (group === void 0 || group.length >= FILES_BATCH_MAX || bytes + item.size > DIRECT_BATCH_BYTES) {
5662
+ groups.push([item]);
5663
+ bytes = item.size;
5664
+ } else {
5665
+ group.push(item);
5666
+ bytes += item.size;
5667
+ }
5668
+ }
5669
+ for (const group of groups) {
5670
+ const body = [];
5671
+ const sent = [];
5672
+ for (const { job, size } of group) {
5673
+ const { kind } = job;
5674
+ if (size > KINDS[kind].bytes) {
5675
+ skip(kind, job.name, KINDS[kind].size);
5676
+ continue;
5677
+ }
5678
+ let data;
5679
+ try {
5680
+ data = job.body ?? await import_node_fs7.promises.readFile(job.path);
5681
+ } catch {
5682
+ skip(kind, job.name, "missing");
5683
+ continue;
5684
+ }
5685
+ const refusal = kind === "text" ? textRefusal(data) : void 0;
5686
+ if (refusal !== void 0) {
5687
+ skip(kind, job.name, refusal);
5688
+ continue;
5689
+ }
5690
+ body.push({ resultId: job.id, name: job.name, contentType: job.type, data: data.toString("base64") });
5691
+ sent.push({ job, size });
5692
+ }
5693
+ if (body.length === 0) continue;
5694
+ const out = await gated(() => {
5695
+ requests += 1;
5696
+ return client.post("/v1/files/direct-batch", { items: body }, uploadRetries);
5697
+ });
5698
+ if (routeMissing(out)) {
5699
+ batchMissing = true;
5700
+ for (const { job, size } of sent) await gated(() => uploadDirect(job, size));
5701
+ continue;
5702
+ }
5703
+ const verdicts = out.ok ? out.body?.items : void 0;
5704
+ if (!out.ok || !Array.isArray(verdicts) || verdicts.length !== sent.length) {
5705
+ for (const { job } of sent) failed(job, out.ok ? "bad_answer" : out.detail || out.kind);
5706
+ continue;
5707
+ }
5708
+ sent.forEach(({ job }, i) => {
5709
+ const v = verdicts[i] ?? {};
5710
+ if (v.status === "stored") countsOf(job.kind).uploaded += 1;
5711
+ else if (v.status === "exists") existed += 1;
5712
+ else refusedItem(job, 0, v.status === "refused" ? v : { code: "bad_answer" });
5713
+ });
5714
+ }
5715
+ }
5716
+ async function uploadBatched(jobs) {
5717
+ const batches = chunk(jobs, FILES_BATCH_MAX);
5718
+ let next = 0;
5719
+ await Promise.all(
5720
+ Array.from({ length: Math.min(BATCH_PIPELINES, batches.length) }, async () => {
5721
+ for (let at = next++; at < batches.length; at = next++) await batchOf(batches[at]);
5722
+ })
5723
+ );
5724
+ }
5725
+ async function upload(items, filesByKey) {
5726
+ if (filesByKey.size === 0 || !Array.isArray(items)) return;
5727
+ const jobs = [];
5728
+ for (const item of items) {
5729
+ if (item?.status !== "accepted" || typeof item.id !== "string" || typeof item.resultKey !== "string") continue;
5730
+ for (const file of filesByKey.get(item.resultKey) ?? []) {
5731
+ const type = mediaTypeOf(file.contentType) ?? (file.path === void 0 ? void 0 : TYPE_BY_EXTENSION[(0, import_node_path3.extname)(file.path).toLowerCase()]);
5732
+ if (type === void 0 || type === METADATA_TYPE) continue;
5733
+ const kind = kindOf2(type);
5734
+ if (kind !== "text" && file.path === void 0) continue;
5735
+ const name = nameOf(file);
5736
+ if (file.name.startsWith("_")) skip(kind, name, "hidden");
5737
+ else {
5738
+ jobs.push({
5739
+ id: item.id,
5740
+ kind,
5741
+ name,
5742
+ type: kind === "text" ? textTypeOf(file.contentType ?? "", type) : type,
5743
+ ...file.body !== void 0 ? { body: file.body } : {},
5744
+ ...file.path !== void 0 ? { path: file.path } : {}
5745
+ });
5746
+ }
5747
+ }
5748
+ }
5749
+ const started = Date.now();
5750
+ if (batchMissing) await uploadEach(jobs);
5751
+ else await uploadBatched(jobs);
5752
+ uploadMs += Date.now() - started;
5753
+ }
5754
+ return {
5755
+ upload,
5756
+ uploadEach,
5757
+ onRetry: () => void (retried += 1),
5758
+ get bucketSeen() {
5759
+ return bucketSeen;
5760
+ },
5761
+ get noStorage() {
5762
+ return noStorage;
5763
+ },
5764
+ get existed() {
5765
+ return existed;
5766
+ },
5767
+ get retried() {
5768
+ return retried;
5769
+ },
5770
+ get uploadMs() {
5771
+ return uploadMs;
5772
+ },
5773
+ get requests() {
5774
+ return requests;
5775
+ }
5776
+ };
5777
+ }
4979
5778
 
4980
5779
  // src/cli/commands/cairn-artifact.ts
4981
5780
  init_cjs_shims();
4982
- var fs7 = __toESM(require("fs/promises"), 1);
4983
- var path7 = __toESM(require("path"), 1);
5781
+ var fs8 = __toESM(require("fs/promises"), 1);
5782
+ var path9 = __toESM(require("path"), 1);
4984
5783
 
4985
5784
  // src/mcp-testing/scan/config/config.ts
4986
5785
  init_cjs_shims();
@@ -5672,13 +6471,21 @@ var CATALOG = [
5672
6471
  check2({
5673
6472
  id: "base-jsonrpc-parse-error",
5674
6473
  title: "Invalid JSON is a parse error",
5675
- description: "A message that is not valid JSON gets the error -32700 with id: null.",
6474
+ description: "A message that is not valid JSON gets the error -32700 with id: null. Over HTTP only: on stdio the client may not send such a line at all, and stdio-parse-error-advice reads the answer there. Over HTTP the endpoint is open to any POST, not only to what an MCP client writes, so the JSON-RPC 2.0 rule stands there: an input it cannot accept gets an error (https://modelcontextprotocol.io/specification/2025-11-25/basic/transports, Sending Messages to the Server).",
5676
6475
  level: "MUST",
5677
6476
  derived: true,
5678
6477
  derivation: "basic/index, Messages: MCP messages MUST follow JSON-RPC 2.0; JSON-RPC 2.0 section 5 gives -32700 and a null id to a parse error.",
5679
6478
  specRefs: [ref4(L2, "basic/index", "Messages")],
5680
6479
  eras: BOTH3,
5681
- transports: ANY
6480
+ transports: HTTP
6481
+ }),
6482
+ unscored("advice", {
6483
+ id: "stdio-parse-error-advice",
6484
+ title: "Invalid JSON on stdio is answered with a parse error (advice)",
6485
+ description: `A line that is not valid JSON gets the error -32700 with id: null. Advice, not a requirement: the client "MUST NOT write anything to the server's stdin that is not a valid MCP message", so what a server does with one is not specified.`,
6486
+ specRefs: [ref4(L2, LT, "stdio")],
6487
+ eras: BOTH3,
6488
+ transports: ["stdio"]
5682
6489
  }),
5683
6490
  check2({
5684
6491
  id: "base-unknown-method-error",
@@ -6076,7 +6883,7 @@ var CATALOG = [
6076
6883
  check2({
6077
6884
  id: "http-modern-get-delete-405",
6078
6885
  title: "A modern-only server answers GET and DELETE with 405",
6079
- 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.",
6886
+ description: "A server of the 2026-07-28 revision only answers GET and DELETE on its endpoint with 405 Method Not Allowed. A server that also serves 2025-11-25 (dual-era) is not-applicable: its server/discover names an earlier revision, or it answers an initialize sent as a 2025-11-25 client sends it.",
6080
6887
  level: "SHOULD",
6081
6888
  specRefs: [ref4(M2, MT, "Earlier Streamable HTTP Revisions")],
6082
6889
  eras: ["modern"],
@@ -6252,7 +7059,7 @@ var CATALOG = [
6252
7059
  check2({
6253
7060
  id: "mod-no-session-id",
6254
7061
  title: "A modern-only server neither mints nor echoes a session id",
6255
- 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.",
7062
+ description: "server/discover sent with an Mcp-Session-Id gets an answer without Mcp-Session-Id. A dual-era server (supportedVersions names a revision before 2026-07-28, or it answers an initialize sent as a 2025-11-25 client sends it) is not-applicable.",
6256
7063
  level: "SHOULD",
6257
7064
  specRefs: [ref4(M2, MT, "Earlier Streamable HTTP Revisions")],
6258
7065
  eras: MODERN3,
@@ -6390,7 +7197,7 @@ var BY_ID = new Map(CATALOG.map((e) => [e.id, e]));
6390
7197
 
6391
7198
  // src/mcp-testing/conformance/profile.ts
6392
7199
  init_cjs_shims();
6393
- var import_node_crypto3 = require("crypto");
7200
+ var import_node_crypto5 = require("crypto");
6394
7201
 
6395
7202
  // src/mcp-testing/report/human.ts
6396
7203
  init_exit_codes();
@@ -6523,14 +7330,14 @@ var NoCairnRunsError = class extends Error {
6523
7330
  }
6524
7331
  };
6525
7332
  async function findLatestCairnRun(runsDir = "runs") {
6526
- const entries = await fs7.readdir(runsDir, { withFileTypes: true }).catch(() => null);
7333
+ const entries = await fs8.readdir(runsDir, { withFileTypes: true }).catch(() => null);
6527
7334
  if (entries === null) throw new NoCairnRunsError(runsDir);
6528
7335
  let newest;
6529
7336
  for (const entry of entries) {
6530
7337
  if (!entry.isDirectory()) continue;
6531
- const dir = path7.join(runsDir, entry.name);
7338
+ const dir = path9.join(runsDir, entry.name);
6532
7339
  try {
6533
- const report = await fs7.lstat(path7.join(dir, "report.json"));
7340
+ const report = await fs8.lstat(path9.join(dir, "report.json"));
6534
7341
  if (!report.isFile()) continue;
6535
7342
  if (newest === void 0 || report.mtimeMs > newest.at) {
6536
7343
  newest = { dir, at: report.mtimeMs };
@@ -6587,7 +7394,7 @@ var MAX_MCP_CASES = 5e3;
6587
7394
  async function checkSize(dir, file) {
6588
7395
  let size;
6589
7396
  try {
6590
- const st = await fs7.stat(path7.join(dir, file));
7397
+ const st = await fs8.stat(path9.join(dir, file));
6591
7398
  if (!st.isFile()) throw new CairnArtifactShapeError(file, "", "is not a regular file");
6592
7399
  size = st.size;
6593
7400
  } catch (e) {
@@ -6605,7 +7412,7 @@ async function checkSize(dir, file) {
6605
7412
  }
6606
7413
  async function readJson(file) {
6607
7414
  try {
6608
- return JSON.parse(await fs7.readFile(file, "utf8"));
7415
+ return JSON.parse(await fs8.readFile(file, "utf8"));
6609
7416
  } catch {
6610
7417
  return void 0;
6611
7418
  }
@@ -6645,7 +7452,7 @@ async function readMcpEvidence(dir, states) {
6645
7452
  if (!await checkSize(dir, file)) return void 0;
6646
7453
  let raw;
6647
7454
  try {
6648
- raw = JSON.parse(await fs7.readFile(path7.join(dir, file), "utf8"));
7455
+ raw = JSON.parse(await fs8.readFile(path9.join(dir, file), "utf8"));
6649
7456
  } catch {
6650
7457
  throw new CairnArtifactShapeError(file, "", "is not valid JSON");
6651
7458
  }
@@ -6775,7 +7582,7 @@ async function casesFromMcp(dir, report) {
6775
7582
  });
6776
7583
  }
6777
7584
  async function defaultReadEvidence(dir) {
6778
- const raw = await readJson(path7.join(dir, "api-evidence.json"));
7585
+ const raw = await readJson(path9.join(dir, "api-evidence.json"));
6779
7586
  if (!Array.isArray(raw)) return void 0;
6780
7587
  return raw.map((r) => {
6781
7588
  const rec = asRecord(r);
@@ -6819,7 +7626,7 @@ function casesFromApi(report, verdicts) {
6819
7626
  }
6820
7627
  async function readCairnRun(dir, deps = {}) {
6821
7628
  await checkSize(dir, "report.json");
6822
- const raw = await readJson(path7.join(dir, "report.json"));
7629
+ const raw = await readJson(path9.join(dir, "report.json"));
6823
7630
  if (raw === void 0) throw new CairnRunNotFoundError(dir);
6824
7631
  const report = asRecord(raw);
6825
7632
  if (report["schemaVersion"] !== SUPPORTED_ARTIFACT_VERSION) {
@@ -6851,13 +7658,46 @@ async function readCairnRun(dir, deps = {}) {
6851
7658
  return {
6852
7659
  schemaVersion: INGEST_SCHEMA_VERSION,
6853
7660
  run: {
6854
- runId: str(report["runId"], path7.basename(dir)),
7661
+ runId: str(report["runId"], path9.basename(dir)),
6855
7662
  mode,
6856
7663
  target: str(report["url"], "unknown")
6857
7664
  },
6858
7665
  cases
6859
7666
  };
6860
7667
  }
7668
+ async function readCairnSessionFiles(dir) {
7669
+ const raw = await readJson(path9.join(dir, "screencasts", "screencasts.json"));
7670
+ if (!Array.isArray(raw)) return void 0;
7671
+ const root = await fs8.realpath(dir).catch(() => path9.resolve(dir));
7672
+ const within = (p) => {
7673
+ const rel = path9.relative(root, p);
7674
+ return rel !== "" && !rel.startsWith("..") && !path9.isAbsolute(rel);
7675
+ };
7676
+ let outside = 0;
7677
+ const inside = async (p) => {
7678
+ if (typeof p !== "string" || p === "") return void 0;
7679
+ const abs = path9.resolve(root, p);
7680
+ const real = await fs8.realpath(abs).catch(() => void 0);
7681
+ if (within(abs) && (real === void 0 || within(real))) return real ?? abs;
7682
+ outside += 1;
7683
+ return void 0;
7684
+ };
7685
+ const byCase = /* @__PURE__ */ new Map();
7686
+ let unmapped = 0;
7687
+ for (const entry of raw) {
7688
+ const rec = asRecord(entry);
7689
+ const files = [];
7690
+ for (const p of [own(rec, "video"), own(rec, "trace")]) {
7691
+ const file = await inside(p);
7692
+ if (file !== void 0) files.push(file);
7693
+ }
7694
+ if (files.length === 0) continue;
7695
+ const stableId = own(rec, "stableId");
7696
+ if (typeof stableId !== "string" || stableId === "") unmapped += 1;
7697
+ else byCase.set(stableId, [...byCase.get(stableId) ?? [], ...files]);
7698
+ }
7699
+ return { byCase, unmapped, outside };
7700
+ }
6861
7701
 
6862
7702
  // src/cli/commands/ingest.ts
6863
7703
  var IngestNotLoggedInError = class extends Error {
@@ -6886,6 +7726,131 @@ var IngestHttpError = class extends Error {
6886
7726
  }
6887
7727
  status;
6888
7728
  };
7729
+ var SESSION_FILE_MAX = 100 * 1024 * 1024;
7730
+ var SESSION_UPLOADS_AT_ONCE = 4;
7731
+ var TYPE_BY_EXTENSION2 = { ".webm": "video/webm", ".zip": "application/zip" };
7732
+ function itemsOf(body) {
7733
+ const items = body?.items;
7734
+ if (!Array.isArray(items)) return void 0;
7735
+ return items.flatMap((raw) => {
7736
+ const i = raw ?? {};
7737
+ if (typeof i["stableId"] !== "string") return [];
7738
+ const reviewItemId = typeof i["reviewItemId"] === "string" && i["reviewItemId"] !== "" ? i["reviewItemId"] : void 0;
7739
+ const resultId = typeof i["resultId"] === "string" && i["resultId"] !== "" ? i["resultId"] : void 0;
7740
+ if (reviewItemId === void 0 && resultId === void 0) return [];
7741
+ return [{ stableId: i["stableId"], ...reviewItemId !== void 0 ? { reviewItemId } : {}, ...resultId !== void 0 ? { resultId } : {} }];
7742
+ });
7743
+ }
7744
+ var RESULT_PAGES_MAX = 100;
7745
+ var namesOf = (files) => new Set(Array.isArray(files) ? files.flatMap((f) => typeof f?.name === "string" ? [f.name] : []) : []);
7746
+ async function heldBy(client, runId, jobs) {
7747
+ const held = /* @__PURE__ */ new Map();
7748
+ for (const job of jobs) {
7749
+ const key = targetOf(job);
7750
+ if (held.has(key) || job.owner !== "review-items") continue;
7751
+ const out = await client.get(`/v1/review-items/${encodeURIComponent(job.id)}`);
7752
+ held.set(key, out.ok ? namesOf(out.body?.files) : void 0);
7753
+ }
7754
+ const results = jobs.filter((j) => j.owner === void 0);
7755
+ if (results.length === 0) return held;
7756
+ let byResult = /* @__PURE__ */ new Map();
7757
+ let before;
7758
+ for (let page = 0; ; page += 1) {
7759
+ if (runId === "" || page >= RESULT_PAGES_MAX) {
7760
+ byResult = void 0;
7761
+ break;
7762
+ }
7763
+ const query = before === void 0 ? "" : `?before=${encodeURIComponent(before)}`;
7764
+ const out = await client.get(`/v1/runs/${encodeURIComponent(runId)}/results${query}`);
7765
+ if (!out.ok || !Array.isArray(out.body?.results)) {
7766
+ byResult = void 0;
7767
+ break;
7768
+ }
7769
+ for (const r of out.body.results) {
7770
+ if (typeof r?.id === "string") byResult.set(r.id, namesOf(r.files));
7771
+ }
7772
+ if (typeof out.body.next !== "string" || out.body.next === "") break;
7773
+ before = out.body.next;
7774
+ }
7775
+ for (const job of results) held.set(targetOf(job), byResult === void 0 ? void 0 : byResult.get(job.id) ?? /* @__PURE__ */ new Set());
7776
+ return held;
7777
+ }
7778
+ var targetOf = (job) => `${job.owner ?? "results"}/${job.id}`;
7779
+ async function sendSessionFiles(dir, sent, platform) {
7780
+ const session = await readCairnSessionFiles(dir);
7781
+ if (session === void 0 || session.byCase.size === 0 && session.unmapped === 0 && session.outside === 0) return [];
7782
+ if (sent.items === void 0) {
7783
+ return ["session files not uploaded \u2014 this Plune is older than the routes that take them"];
7784
+ }
7785
+ const lines = [];
7786
+ if (session.outside > 0) lines.push(`${session.outside} file(s) not uploaded \u2014 the path leaves the run directory`);
7787
+ if (session.unmapped > 0) lines.push(`${session.unmapped} recording(s) name no case \u2014 not uploaded`);
7788
+ let jobs = [];
7789
+ let tooBig = 0;
7790
+ const placed = /* @__PURE__ */ new Set();
7791
+ for (const item of sent.items) {
7792
+ const paths = session.byCase.get(item.stableId);
7793
+ if (paths === void 0 || placed.has(item.stableId)) continue;
7794
+ placed.add(item.stableId);
7795
+ for (const file of paths) {
7796
+ const name = path10.basename(file);
7797
+ const size = await import_node_fs8.promises.stat(file).then((s) => s.size, () => void 0);
7798
+ if (size !== void 0 && size > SESSION_FILE_MAX) {
7799
+ tooBig += 1;
7800
+ lines.push(`"${name}" skipped \u2014 larger than the ${SESSION_FILE_MAX / (1024 * 1024)} MiB a session file may be`);
7801
+ continue;
7802
+ }
7803
+ const type = TYPE_BY_EXTENSION2[path10.extname(file).toLowerCase()] ?? "application/octet-stream";
7804
+ jobs.push({
7805
+ id: item.reviewItemId ?? item.resultId,
7806
+ ...item.reviewItemId !== void 0 ? { owner: "review-items" } : {},
7807
+ kind: "file",
7808
+ name,
7809
+ type,
7810
+ path: file
7811
+ });
7812
+ }
7813
+ }
7814
+ const unplaced = [...session.byCase.keys()].filter((stableId) => !placed.has(stableId)).length;
7815
+ if (unplaced > 0) lines.push(`${unplaced} case(s) with recordings got no proposal or result in this run \u2014 not uploaded`);
7816
+ const client = createClient({
7817
+ apiUrl: platform.apiUrl,
7818
+ token: platform.token,
7819
+ uploadRetries: UPLOAD_RETRIES.default,
7820
+ ...platform.fetchImpl !== void 0 ? { fetchImpl: platform.fetchImpl } : {}
7821
+ });
7822
+ if (sent.repeat && jobs.length > 0) {
7823
+ const held = await heldBy(client, sent.runId, jobs);
7824
+ let already = 0;
7825
+ let unknown = 0;
7826
+ jobs = jobs.filter((job) => {
7827
+ const names = held.get(targetOf(job));
7828
+ if (names === void 0) unknown += 1;
7829
+ else if (names.has(job.name)) already += 1;
7830
+ else return true;
7831
+ return false;
7832
+ });
7833
+ if (unknown > 0) lines.push(`${unknown} file(s) not sent again \u2014 what the platform holds could not be read`);
7834
+ lines.push(`${already} file(s) already on the platform, ${jobs.length} sent`);
7835
+ }
7836
+ const counts = { screenshots: { uploaded: 0, skipped: 0, failed: 0 }, textFiles: { uploaded: 0, skipped: 0, failed: 0 }, otherFiles: { uploaded: 0, skipped: 0, failed: 0 } };
7837
+ if (jobs.length > 0) {
7838
+ const notes = [];
7839
+ const files = fileSender({
7840
+ client,
7841
+ log: (line) => notes.push(line.replace(/^plune: /, "")),
7842
+ stats: counts,
7843
+ uploadsAtOnce: SESSION_UPLOADS_AT_ONCE,
7844
+ uploadRetries: UPLOAD_RETRIES.default,
7845
+ without: "the run is recorded without it"
7846
+ });
7847
+ await files.uploadEach(jobs);
7848
+ lines.push(...notes.filter((n) => !n.startsWith("storage bucket found")));
7849
+ }
7850
+ const { uploaded, skipped, failed } = counts.otherFiles;
7851
+ const total = `${uploaded} session file(s) uploaded` + (skipped + tooBig > 0 ? `, ${skipped + tooBig} skipped` : "") + (failed > 0 ? `, ${failed} failed to upload` : "");
7852
+ return [total, ...lines];
7853
+ }
6889
7854
  async function safeErrorDetail2(res) {
6890
7855
  try {
6891
7856
  const body = await res.json();
@@ -6903,10 +7868,14 @@ async function handleIngest(deps) {
6903
7868
  const doFetch = deps.fetchImpl ?? fetch;
6904
7869
  const endpoint = `${apiUrl}/v1/ingest/cairn`;
6905
7870
  const job = new JobReporter(doFetch, apiUrl, token, "ingest");
6906
- await job.open(path8.basename(path8.resolve(dir)), payload.cases.length);
7871
+ await job.open(path10.basename(path10.resolve(dir)), payload.cases.length);
6907
7872
  try {
6908
- const result = await upload();
7873
+ const { result, ...sent } = await upload();
6909
7874
  await job.uploaded({ subjectId: result.runId || void 0 });
7875
+ const files = await sendSessionFiles(dir, { ...sent, runId: result.runId }, { apiUrl, token, ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {} }).catch(
7876
+ () => ["session files not uploaded (an unexpected error) \u2014 the run is recorded"]
7877
+ );
7878
+ if (files.length > 0) result.files = files;
6910
7879
  await job.finish({ ok: true });
6911
7880
  if (job.problem !== void 0) result.jobProblem = job.problem;
6912
7881
  return result;
@@ -6931,12 +7900,13 @@ async function handleIngest(deps) {
6931
7900
  throw new IngestHttpError(res.status, detail);
6932
7901
  }
6933
7902
  const body = await res.json().catch(() => ({}));
6934
- return {
7903
+ const result = {
6935
7904
  runId: typeof body.runId === "string" ? body.runId : "",
6936
7905
  linked: typeof body.linked === "number" ? body.linked : 0,
6937
7906
  proposed: typeof body.proposed === "number" ? body.proposed : 0,
6938
7907
  skipped: typeof body.skipped === "number" ? body.skipped : 0
6939
7908
  };
7909
+ return { result, items: itemsOf(body), repeat: res.status === 200 };
6940
7910
  }
6941
7911
  }
6942
7912
  function reportIngestFailure(err, write) {
@@ -6957,7 +7927,8 @@ function formatIngestResult(r) {
6957
7927
  `Ingested Cairn run \u2192 ${r.runId}`,
6958
7928
  ` ${r.linked} result(s) attached to existing cases`,
6959
7929
  ` ${r.proposed} case(s) proposed \u2014 review them in Plune to accept`,
6960
- ` ${r.skipped} skipped (already queued, already rejected, repeated, or never executed)`
7930
+ ` ${r.skipped} skipped (already queued, already rejected, repeated, or never executed)`,
7931
+ ...(r.files ?? []).map((line, i) => i === 0 ? ` ${line}` : ` ${line}`)
6961
7932
  ];
6962
7933
  return `${lines.join("\n")}
6963
7934
  `;