@plune-ai/cli 0.39.10 → 0.39.11

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/cli.cjs CHANGED
@@ -1078,7 +1078,7 @@ var init_retry = __esm({
1078
1078
  "use strict";
1079
1079
  init_cjs_shims();
1080
1080
  init_errors2();
1081
- defaultSleep = (ms) => new Promise((resolve23) => setTimeout(resolve23, ms));
1081
+ defaultSleep = (ms) => new Promise((resolve24) => setTimeout(resolve24, ms));
1082
1082
  }
1083
1083
  });
1084
1084
 
@@ -4771,14 +4771,14 @@ function readLines(stream, onLine, stats) {
4771
4771
  if (stats !== void 0 && rest.length > stats.high) stats.high = rest.length;
4772
4772
  partial = rest.slice(0, STDERR_LINE_LIMIT);
4773
4773
  };
4774
- return new Promise((resolve23) => {
4774
+ return new Promise((resolve24) => {
4775
4775
  let done = false;
4776
4776
  const finish = () => {
4777
4777
  if (done) return;
4778
4778
  done = true;
4779
4779
  feed(decoder.end());
4780
4780
  if (partial !== "") onLine(partial.endsWith("\r") ? partial.slice(0, -1) : partial);
4781
- resolve23();
4781
+ resolve24();
4782
4782
  };
4783
4783
  stream.on(
4784
4784
  "data",
@@ -5076,7 +5076,7 @@ async function openSession(config, options = {}) {
5076
5076
  const stdin = transport._process?.stdin;
5077
5077
  if (stdin === null || stdin === void 0 || stdin.writableEnded)
5078
5078
  throw spawnError !== void 0 ? await toConnectError(spawnError) : new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
5079
- return new Promise((resolve23, reject) => {
5079
+ return new Promise((resolve24, reject) => {
5080
5080
  const done = () => {
5081
5081
  clearTimeout(timer2);
5082
5082
  listeners.delete(listener);
@@ -5090,7 +5090,7 @@ async function openSession(config, options = {}) {
5090
5090
  const frame2 = parsed(line);
5091
5091
  if (!answers(frame2, id2)) return;
5092
5092
  done();
5093
- resolve23({ frame: frame2, text: clean3(line).slice(0, RAW_TEXT) });
5093
+ resolve24({ frame: frame2, text: clean3(line).slice(0, RAW_TEXT) });
5094
5094
  };
5095
5095
  const stop = () => {
5096
5096
  done();
@@ -5170,10 +5170,10 @@ async function openSession(config, options = {}) {
5170
5170
  const proc = transport._process;
5171
5171
  if (proc === void 0) return true;
5172
5172
  if (proc.exitCode !== null || proc.signalCode !== null) return true;
5173
- const exited = new Promise((resolve23) => proc.once("exit", () => resolve23(true)));
5173
+ const exited = new Promise((resolve24) => proc.once("exit", () => resolve24(true)));
5174
5174
  proc.stdin?.end();
5175
5175
  let timer2;
5176
- const late = new Promise((resolve23) => timer2 = setTimeout(() => resolve23(false), waitMs));
5176
+ const late = new Promise((resolve24) => timer2 = setTimeout(() => resolve24(false), waitMs));
5177
5177
  const result2 = await Promise.race([exited, late]);
5178
5178
  clearTimeout(timer2);
5179
5179
  return result2;
@@ -8908,7 +8908,7 @@ function parseRetryAfter(raw, now = Date.now()) {
8908
8908
  return Math.min(Math.max(seconds, 0) * 1e3, RETRY_AFTER_CAP_MS);
8909
8909
  }
8910
8910
  function nodeTransport(url, init, idleMs = IDLE_MS) {
8911
- return new Promise((resolve23, reject) => {
8911
+ return new Promise((resolve24, reject) => {
8912
8912
  const target4 = new URL(url);
8913
8913
  const send3 = target4.protocol === "https:" ? import_node_https.request : import_node_http.request;
8914
8914
  const agent = POOLS[target4.protocol === "https:" ? "https:" : "http:"];
@@ -8919,7 +8919,7 @@ function nodeTransport(url, init, idleMs = IDLE_MS) {
8919
8919
  res.on("end", () => {
8920
8920
  const status2 = res.statusCode ?? 0;
8921
8921
  const text6 = Buffer.concat(chunks).toString("utf8");
8922
- resolve23({
8922
+ resolve24({
8923
8923
  ok: status2 >= 200 && status2 <= 299,
8924
8924
  status: status2,
8925
8925
  headers: {
@@ -8938,12 +8938,12 @@ function nodeTransport(url, init, idleMs = IDLE_MS) {
8938
8938
  });
8939
8939
  }
8940
8940
  function nodePut(url, headers, source, idleMs) {
8941
- return new Promise((resolve23, reject) => {
8941
+ return new Promise((resolve24, reject) => {
8942
8942
  const target4 = new URL(url);
8943
8943
  const send3 = target4.protocol === "https:" ? import_node_https.request : import_node_http.request;
8944
8944
  const length = "body" in source ? source.body.length : source.size;
8945
8945
  let answered;
8946
- const settle = (err) => answered !== void 0 ? resolve23(answered) : reject(err);
8946
+ const settle = (err) => answered !== void 0 ? resolve24(answered) : reject(err);
8947
8947
  const req = send3(
8948
8948
  target4,
8949
8949
  { method: "PUT", headers: { ...withoutLength(headers), "content-length": String(length) } },
@@ -8952,7 +8952,7 @@ function nodePut(url, headers, source, idleMs) {
8952
8952
  answered = { status: res.statusCode ?? 0, retryAfter: Array.isArray(retry) ? retry[0] ?? null : retry ?? null };
8953
8953
  res.on("error", settle);
8954
8954
  res.on("close", () => {
8955
- resolve23(answered);
8955
+ resolve24(answered);
8956
8956
  req.destroy();
8957
8957
  });
8958
8958
  res.resume();
@@ -9728,7 +9728,7 @@ function fileSender(options) {
9728
9728
  let free = uploadsAtOnce;
9729
9729
  const waiting = [];
9730
9730
  async function gated(work) {
9731
- if (free === 0) await new Promise((resolve23) => waiting.push(resolve23));
9731
+ if (free === 0) await new Promise((resolve24) => waiting.push(resolve24));
9732
9732
  else free -= 1;
9733
9733
  try {
9734
9734
  return await work();
@@ -10788,14 +10788,14 @@ async function handleRunExec(options) {
10788
10788
  if (command === void 0) throw new RunCommandError("Nothing to run \u2014 pass a command after `--`.");
10789
10789
  const run = await handleRunStart(options);
10790
10790
  const spawnImpl = options.spawnImpl ?? import_node_child_process2.spawn;
10791
- const code = await new Promise((resolve23) => {
10791
+ const code = await new Promise((resolve24) => {
10792
10792
  const child = spawnImpl(command, args, {
10793
10793
  stdio: "inherit",
10794
10794
  shell: process.platform === "win32",
10795
10795
  env: { ...process.env, PLUNE_RUN: run.externalKey, PLUNE_PROCEED: "1" }
10796
10796
  });
10797
- child.on("close", (exitCode2) => resolve23(exitCode2 ?? 1));
10798
- child.on("error", () => resolve23(1));
10797
+ child.on("close", (exitCode2) => resolve24(exitCode2 ?? 1));
10798
+ child.on("error", () => resolve24(1));
10799
10799
  });
10800
10800
  return handleRunFinish(run.id, options, code);
10801
10801
  }
@@ -12764,7 +12764,7 @@ async function timeoutMessage(limit3, runId, ours, options) {
12764
12764
  if (!ours) return `${head}; run ${runId} is shared with other jobs and was left open - close it with "plune run finish ${runId}" once they are done, then import this report again.`;
12765
12765
  const wait = options.terminateWaitMs ?? 15e3;
12766
12766
  let timer;
12767
- const gaveUp = new Promise((resolve23) => timer = setTimeout(() => resolve23("gaveup"), wait));
12767
+ const gaveUp = new Promise((resolve24) => timer = setTimeout(() => resolve24("gaveup"), wait));
12768
12768
  const quiet = () => void 0;
12769
12769
  const closed = handleRunFinish(runId, { ...options, write: quiet, terminate: true, reason: `import timed out after ${limit3} s` }).then(
12770
12770
  () => true,
@@ -12870,7 +12870,7 @@ async function handleRunImport(options) {
12870
12870
  else {
12871
12871
  sent.catch(() => void 0);
12872
12872
  let timer;
12873
- const late = new Promise((resolve23) => timer = setTimeout(() => resolve23("late"), limit3 * 1e3));
12873
+ const late = new Promise((resolve24) => timer = setTimeout(() => resolve24("late"), limit3 * 1e3));
12874
12874
  const first = await Promise.race([sent, late]).finally(() => clearTimeout(timer));
12875
12875
  if (first === "late") {
12876
12876
  throw new ImportTimeoutError(await timeoutMessage(limit3, session2?.runId ?? null, !env.keepOpen, { ...options, apiUrl, token: token2 }));
@@ -13785,10 +13785,355 @@ evals:
13785
13785
  }
13786
13786
  });
13787
13787
 
13788
+ // src/config/init/from-openai-eval.ts
13789
+ var from_openai_eval_exports = {};
13790
+ __export(from_openai_eval_exports, {
13791
+ OpenAiEvalImportError: () => OpenAiEvalImportError,
13792
+ convertOpenAiEval: () => convertOpenAiEval,
13793
+ formatReport: () => formatReport2
13794
+ });
13795
+ function rewriteItemRefs(text6, prefix, seen, bad) {
13796
+ return text6.replace(ITEM_REF, (match, name) => {
13797
+ if (!FLAT.test(name)) {
13798
+ bad.add(name);
13799
+ return match;
13800
+ }
13801
+ seen.add(name);
13802
+ return `{{${prefix}${name}}}`;
13803
+ });
13804
+ }
13805
+ function hasNonText(messages) {
13806
+ const nonText = (content) => Array.isArray(content) ? content.some(nonText) : isObj(content) && typeof content.text !== "string";
13807
+ return Array.isArray(messages) && messages.some((m) => isObj(m) && nonText(m.content));
13808
+ }
13809
+ function textOf2(content) {
13810
+ if (typeof content === "string") return content;
13811
+ if (Array.isArray(content))
13812
+ return content.map(textOf2).filter((t) => t !== "").join("\n");
13813
+ if (isObj(content) && typeof content.text === "string") return content.text;
13814
+ return "";
13815
+ }
13816
+ function joinMessages(messages, keep = () => true) {
13817
+ if (!Array.isArray(messages)) return "";
13818
+ return messages.map((m) => isObj(m) ? textOf2(m.content) : "").filter((t) => t !== "" && keep(t)).join("\n\n");
13819
+ }
13820
+ function slug(name) {
13821
+ const s = typeof name === "string" ? name.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") : "";
13822
+ return s === "" ? "imported-eval" : s;
13823
+ }
13824
+ function criteriaOf(grader, seen, bad) {
13825
+ const more = (text6) => text6.replace(SAMPLE_REF, "").trim() !== "";
13826
+ return rewriteItemRefs(joinMessages(grader.input, more), "vars.", seen, bad).replace(
13827
+ SAMPLE_REF,
13828
+ "the OUTPUT"
13829
+ );
13830
+ }
13831
+ function judgeProvider(grader) {
13832
+ return typeof grader.model === "string" && grader.model !== "" ? { provider: { type: "openai", model: grader.model } } : {};
13833
+ }
13834
+ function convertGrader(grader, seen) {
13835
+ const type = typeof grader.type === "string" ? grader.type : "unknown";
13836
+ const subject2 = `${typeof grader.name === "string" ? grader.name : "(no name)"} [${type}]`;
13837
+ const skip = (note2) => ({
13838
+ line: { status: "not converted", subject: subject2, note: note2 }
13839
+ });
13840
+ if (type === "string_check" || type === "text_similarity") {
13841
+ if (typeof grader.input !== "string" || !OUTPUT_TEXT.test(grader.input.trim())) {
13842
+ return skip(
13843
+ `its input is ${JSON.stringify(grader.input)}; a check here reads the model's text answer ({{ sample.output_text }}) only`
13844
+ );
13845
+ }
13846
+ if (typeof grader.reference !== "string") return skip("it has no reference text");
13847
+ if (grader.reference === "" && !(type === "string_check" && grader.operation === "eq"))
13848
+ return skip("its reference is empty");
13849
+ if (SAMPLE_REF.test(grader.reference)) {
13850
+ SAMPLE_REF.lastIndex = 0;
13851
+ return skip(
13852
+ "its reference reads the model sample; a check here compares with the row or a fixed text"
13853
+ );
13854
+ }
13855
+ const local = /* @__PURE__ */ new Set();
13856
+ const bad = /* @__PURE__ */ new Set();
13857
+ const reference = rewriteItemRefs(grader.reference, "vars.", local, bad);
13858
+ if (bad.size > 0) return skip(`its reference points at ${badRefs(bad)}: ${NOT_FLAT}`);
13859
+ const ok2 = (assertion, status2, note2) => {
13860
+ local.forEach((n) => seen.add(n));
13861
+ return { assertion, line: { status: status2, subject: subject2, note: note2 } };
13862
+ };
13863
+ if (type === "string_check") {
13864
+ switch (grader.operation) {
13865
+ case "eq":
13866
+ return ok2({ type: "exact-match", value: reference }, "converted", "exact-match");
13867
+ case "like":
13868
+ return ok2({ type: "contains", value: reference }, "converted", "contains");
13869
+ case "ilike":
13870
+ return ok2(
13871
+ { type: "contains", value: reference, ignore_case: true },
13872
+ "converted",
13873
+ "contains, ignore_case"
13874
+ );
13875
+ default:
13876
+ return skip(
13877
+ `operation ${JSON.stringify(grader.operation)} has no check here (there is no negated check)`
13878
+ );
13879
+ }
13880
+ }
13881
+ if (grader.evaluation_metric !== "cosine") {
13882
+ return skip(
13883
+ `metric ${JSON.stringify(grader.evaluation_metric)} has no check here; only cosine has one (semantic-similarity)`
13884
+ );
13885
+ }
13886
+ const t = grader.pass_threshold;
13887
+ const inRange = typeof t === "number" && t >= 0 && t <= 1;
13888
+ return ok2(
13889
+ { type: "semantic-similarity", reference, ...inRange ? { threshold: t } : {} },
13890
+ "approximate",
13891
+ "semantic-similarity: the embedding model is a different, local one, so run it and look at the threshold again" + (t !== void 0 && !inRange ? `; pass_threshold ${JSON.stringify(t)} is not between 0 and 1 and was left out` : "")
13892
+ );
13893
+ }
13894
+ if (type === "score_model" || type === "label_model") {
13895
+ const local = /* @__PURE__ */ new Set();
13896
+ const bad = /* @__PURE__ */ new Set();
13897
+ const criteria = criteriaOf(grader, local, bad);
13898
+ if (bad.size > 0) return skip(`its messages point at ${badRefs(bad)}: ${NOT_FLAT}`);
13899
+ local.forEach((n) => seen.add(n));
13900
+ const parts = hasNonText(grader.input) ? "; parts of its messages that are not text were left out" : "";
13901
+ if (type === "label_model") return labelModel(grader, criteria, subject2, parts);
13902
+ if (criteria === "") return skip("its messages hold no text");
13903
+ const range = Array.isArray(grader.range) ? grader.range : [0, 1];
13904
+ const [min, max] = [range[0], range[1]];
13905
+ const t = grader.pass_threshold;
13906
+ let pass2 = {};
13907
+ let scale = "no pass_threshold in the grader, so the default of llm-judge applies";
13908
+ if (typeof t === "number" && typeof min === "number" && typeof max === "number" && max > min) {
13909
+ const scaled = Math.min(1, Math.max(0, (t - min) / (max - min)));
13910
+ pass2 = { pass_threshold: Number(scaled.toFixed(4)) };
13911
+ scale = `pass_threshold ${t} on ${min}..${max} became ${pass2.pass_threshold} on 0..1`;
13912
+ } else if (t !== void 0) {
13913
+ scale = `pass_threshold ${JSON.stringify(t)} could not be rescaled from the range ${JSON.stringify(grader.range)} and was left out, so the default of llm-judge applies`;
13914
+ }
13915
+ return {
13916
+ assertion: { type: "llm-judge", criteria, ...pass2, ...judgeProvider(grader) },
13917
+ line: {
13918
+ status: "approximate",
13919
+ subject: subject2,
13920
+ note: `llm-judge: the grader's messages are the criteria and the judge scores 0..1; ${scale}${parts}`
13921
+ }
13922
+ };
13923
+ }
13924
+ if (type === "python") return skip("a Python grader runs code; no check here runs code");
13925
+ return skip("this grader type has no check here");
13926
+ }
13927
+ function labelModel(grader, text6, subject2, parts) {
13928
+ const skip = (note2) => ({
13929
+ line: { status: "not converted", subject: subject2, note: note2 }
13930
+ });
13931
+ const labels = Array.isArray(grader.labels) ? grader.labels.filter((l) => typeof l === "string") : [];
13932
+ const passing = Array.isArray(grader.passing_labels) ? grader.passing_labels.filter((l) => typeof l === "string") : [];
13933
+ if (labels.length === 0 || passing.length === 0)
13934
+ return skip("it has no labels or no passing labels");
13935
+ const rule = `Pick one label for the OUTPUT from: ${labels.join(", ")}. Score 1 if the label is one of: ${passing.join(", ")}. Otherwise score 0.`;
13936
+ return {
13937
+ assertion: {
13938
+ type: "llm-judge",
13939
+ criteria: text6 === "" ? rule : `${text6}
13940
+
13941
+ ${rule}`,
13942
+ ...judgeProvider(grader)
13943
+ },
13944
+ line: {
13945
+ status: "approximate",
13946
+ subject: subject2,
13947
+ note: `llm-judge: the judge gives a score, 1 for a passing label, in place of the label itself${parts}`
13948
+ }
13949
+ };
13950
+ }
13951
+ function convertRows(items2, report) {
13952
+ const asText = /* @__PURE__ */ new Set();
13953
+ const rows = items2.map((raw, i) => {
13954
+ const item = isObj(raw) && "item" in raw ? raw.item : raw;
13955
+ if (!isObj(item)) throw new OpenAiEvalImportError(`test data row ${i + 1} is not an object`);
13956
+ const vars = Object.fromEntries(
13957
+ Object.entries(item).map(([key, value2]) => {
13958
+ if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean")
13959
+ return [key, value2];
13960
+ asText.add(key);
13961
+ return [key, JSON.stringify(value2)];
13962
+ })
13963
+ );
13964
+ return { vars };
13965
+ });
13966
+ if (asText.size > 0) {
13967
+ report.push({
13968
+ status: "check",
13969
+ subject: "test data",
13970
+ note: `written as JSON text, as a row value here is a string, a number or a boolean: ${[...asText].sort().join(", ")}`
13971
+ });
13972
+ }
13973
+ return rows;
13974
+ }
13975
+ function parseJsonl(text6) {
13976
+ const out = [];
13977
+ text6.split(/\r?\n/).forEach((line, i) => {
13978
+ if (line.trim() === "") return;
13979
+ try {
13980
+ out.push(JSON.parse(line));
13981
+ } catch {
13982
+ throw new OpenAiEvalImportError(`test data line ${i + 1} is not JSON`);
13983
+ }
13984
+ });
13985
+ return out;
13986
+ }
13987
+ function convertOpenAiEval({ evalObject, run, rows }) {
13988
+ if (!isObj(evalObject) || !Array.isArray(evalObject.testing_criteria)) {
13989
+ throw new OpenAiEvalImportError(
13990
+ "the eval file is not an eval object: it has no testing_criteria list (save the answer of GET /v1/evals/{eval_id})"
13991
+ );
13992
+ }
13993
+ if (run !== void 0 && !isObj(run))
13994
+ throw new OpenAiEvalImportError("the run file is not a run object");
13995
+ const id2 = slug(evalObject.name);
13996
+ const report = [];
13997
+ const seen = /* @__PURE__ */ new Set();
13998
+ const assertions = [];
13999
+ for (const grader of evalObject.testing_criteria) {
14000
+ const { assertion, line } = convertGrader(isObj(grader) ? grader : {}, seen);
14001
+ if (assertion !== void 0) assertions.push(assertion);
14002
+ report.push(line);
14003
+ }
14004
+ if (assertions.length === 0) {
14005
+ report.push({
14006
+ status: "check",
14007
+ subject: "checks",
14008
+ note: "no grader was converted: the eval has no checks until you add some"
14009
+ });
14010
+ }
14011
+ const source = isObj(run) && isObj(run.data_source) ? run.data_source : {};
14012
+ const template = isObj(source.input_messages) ? source.input_messages.template : void 0;
14013
+ const count6 = Array.isArray(template) ? template.length : 0;
14014
+ const inPrompt = /* @__PURE__ */ new Set();
14015
+ let prompt5 = rewriteItemRefs(joinMessages(template), "", inPrompt, /* @__PURE__ */ new Set());
14016
+ inPrompt.forEach((n) => seen.add(n));
14017
+ const left = [...new Set(prompt5.match(ANY_REF) ?? [])].filter(
14018
+ (m) => !inPrompt.has(m.slice(2, -2))
14019
+ );
14020
+ if (left.length > 0) {
14021
+ report.push({
14022
+ status: "check",
14023
+ subject: "prompt",
14024
+ note: `it still holds ${left.join(", ")}, which is not a field of a row: plune run refuses the prompt until you change it`
14025
+ });
14026
+ }
14027
+ if (hasNonText(template)) {
14028
+ report.push({
14029
+ status: "check",
14030
+ subject: "prompt",
14031
+ note: "parts of its messages that are not text were left out"
14032
+ });
14033
+ }
14034
+ const sampling = isObj(source.sampling_params) ? Object.keys(source.sampling_params).sort() : [];
14035
+ if (sampling.length > 0) {
14036
+ report.push({
14037
+ status: "check",
14038
+ subject: "model",
14039
+ note: `the sampling parameters of the run are not carried over: ${sampling.join(", ")}`
14040
+ });
14041
+ }
14042
+ if (prompt5 === "") {
14043
+ prompt5 = "Replace this line with your prompt.";
14044
+ report.push({
14045
+ status: "check",
14046
+ subject: "prompt",
14047
+ note: "no prompt template was found (give a run with --run): the prompt is a placeholder"
14048
+ });
14049
+ } else if (count6 > 1) {
14050
+ report.push({
14051
+ status: "check",
14052
+ subject: "prompt",
14053
+ note: `${count6} messages were joined into one prompt; their roles are not kept`
14054
+ });
14055
+ }
14056
+ let model = typeof source.model === "string" && source.model !== "" ? source.model : void 0;
14057
+ if (model === void 0) {
14058
+ model = "gpt-4o";
14059
+ report.push({
14060
+ status: "check",
14061
+ subject: "model",
14062
+ note: "no model was found (give a run with --run): it is set to gpt-4o"
14063
+ });
14064
+ }
14065
+ const inline = isObj(source.source) && Array.isArray(source.source.content) ? source.source.content : void 0;
14066
+ const fromFile = rows !== void 0 ? parseJsonl(rows) : [];
14067
+ const items2 = fromFile.length > 0 ? fromFile : inline;
14068
+ let dataset;
14069
+ let datasetField;
14070
+ if (items2 !== void 0 && items2.length > 0) {
14071
+ const path25 = `datasets/${id2}.jsonl`;
14072
+ dataset = {
14073
+ path: path25,
14074
+ jsonl: convertRows(items2, report).map((r) => JSON.stringify(r)).join("\n") + "\n"
14075
+ };
14076
+ datasetField = `./${path25}`;
14077
+ } else {
14078
+ const vars = Object.fromEntries([...seen].sort().map((n) => [n, "replace me"]));
14079
+ datasetField = { examples: [{ vars }] };
14080
+ report.push({
14081
+ status: "check",
14082
+ subject: "test data",
14083
+ note: rows !== void 0 ? "the test data file holds no rows: the dataset is one placeholder row" : "no test data was found (give the file with --data): the dataset is one placeholder row"
14084
+ });
14085
+ }
14086
+ const config = {
14087
+ version: 1,
14088
+ provider: { type: "openai", model },
14089
+ evals: [
14090
+ {
14091
+ id: id2,
14092
+ ...typeof evalObject.name === "string" ? { description: evalObject.name } : {},
14093
+ prompt: prompt5,
14094
+ dataset: datasetField,
14095
+ assertions
14096
+ }
14097
+ ]
14098
+ };
14099
+ const header3 = "# Plune configuration, written by `plune init --from-openai-eval`. Read the report it printed.\n";
14100
+ return { yaml: header3 + (0, import_yaml4.stringify)(config), ...dataset ? { dataset } : {}, report };
14101
+ }
14102
+ function formatReport2(report) {
14103
+ const count6 = (s) => report.filter((l) => l.status === s).length;
14104
+ return report.map((l) => ` ${l.status.padEnd(13)} ${l.subject}: ${l.note}`).join("\n") + `
14105
+
14106
+ ${count6("converted")} converted \xB7 ${count6("approximate")} approximate \xB7 ${count6("not converted")} not converted
14107
+ `;
14108
+ }
14109
+ var import_yaml4, OpenAiEvalImportError, isObj, ITEM_REF, ANY_REF, FLAT, NOT_FLAT, SAMPLE_REF, OUTPUT_TEXT, badRefs;
14110
+ var init_from_openai_eval = __esm({
14111
+ "src/config/init/from-openai-eval.ts"() {
14112
+ "use strict";
14113
+ init_cjs_shims();
14114
+ import_yaml4 = require("yaml");
14115
+ OpenAiEvalImportError = class extends Error {
14116
+ constructor(message2) {
14117
+ super(message2);
14118
+ this.name = "OpenAiEvalImportError";
14119
+ }
14120
+ };
14121
+ isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
14122
+ ITEM_REF = /\{\{\s*item\.([^{}]*?)\s*\}\}/g;
14123
+ ANY_REF = /\{\{[^{}]*\}\}/g;
14124
+ FLAT = /^\w+$/;
14125
+ NOT_FLAT = "a row here is flat, and a field a placeholder names is letters, digits and _";
14126
+ SAMPLE_REF = /\{\{\s*sample\.[\w.]+\s*\}\}/g;
14127
+ OUTPUT_TEXT = /^\{\{\s*sample\.output_text\s*\}\}$/;
14128
+ badRefs = (bad) => [...bad].sort().map((n) => `{{ item.${n} }}`).join(", ");
14129
+ }
14130
+ });
14131
+
13788
14132
  // src/cli/commands/init.ts
13789
14133
  var init_exports = {};
13790
14134
  __export(init_exports, {
13791
14135
  initCommand: () => initCommand,
14136
+ initFromOpenAiEval: () => initFromOpenAiEval,
13792
14137
  nextSteps: () => nextSteps
13793
14138
  });
13794
14139
  function reportWrite(cwd, rel, content, force) {
@@ -13815,13 +14160,46 @@ function nextSteps(keyVar) {
13815
14160
  }
13816
14161
  function keyVarOf(cwd) {
13817
14162
  try {
13818
- const cfg = (0, import_yaml4.parse)(fs17.readFileSync(path20.join(cwd, "plune.yaml"), "utf8"));
14163
+ const cfg = (0, import_yaml5.parse)(fs17.readFileSync(path20.join(cwd, "plune.yaml"), "utf8"));
13819
14164
  const type = cfg?.provider?.type;
13820
14165
  return typeof type === "string" && Object.hasOwn(PROVIDER_KEY_VARS, type) ? PROVIDER_KEY_VARS[type] : void 0;
13821
14166
  } catch {
13822
14167
  return void 0;
13823
14168
  }
13824
14169
  }
14170
+ async function initFromOpenAiEval(options) {
14171
+ const { cwd, force } = options;
14172
+ const { convertOpenAiEval: convertOpenAiEval2, formatReport: formatReport4, OpenAiEvalImportError: OpenAiEvalImportError2 } = await Promise.resolve().then(() => (init_from_openai_eval(), from_openai_eval_exports));
14173
+ const read = (file) => {
14174
+ try {
14175
+ return fs17.readFileSync(path20.resolve(cwd, file), "utf8").replace(/^/, "");
14176
+ } catch (err) {
14177
+ throw new OpenAiEvalImportError2(`cannot read ${file}: ${err.message}`);
14178
+ }
14179
+ };
14180
+ const json2 = (file) => {
14181
+ try {
14182
+ return JSON.parse(read(file));
14183
+ } catch (err) {
14184
+ if (err instanceof OpenAiEvalImportError2) throw err;
14185
+ throw new OpenAiEvalImportError2(`${file} is not JSON`);
14186
+ }
14187
+ };
14188
+ const converted = convertOpenAiEval2({
14189
+ evalObject: json2(options.evalPath),
14190
+ ...options.runPath !== void 0 ? { run: json2(options.runPath) } : {},
14191
+ ...options.dataPath !== void 0 ? { rows: read(options.dataPath) } : {}
14192
+ });
14193
+ try {
14194
+ reportWrite(cwd, "plune.yaml", converted.yaml, force);
14195
+ if (converted.dataset) reportWrite(cwd, converted.dataset.path, converted.dataset.jsonl, force);
14196
+ reportWrite(cwd, ".env.example", ENV_EXAMPLE_TPL, force);
14197
+ } catch (err) {
14198
+ throw new OpenAiEvalImportError2(`cannot write the files: ${err.message}`);
14199
+ }
14200
+ process.stdout.write("\n" + formatReport4(converted.report));
14201
+ process.stdout.write(nextSteps(keyVarOf(cwd)));
14202
+ }
13825
14203
  async function initCommand({ cwd, force, yes = false }) {
13826
14204
  if (yes) {
13827
14205
  reportWrite(cwd, "plune.yaml", PLUNE_YAML_TPL, force);
@@ -13833,14 +14211,14 @@ async function initCommand({ cwd, force, yes = false }) {
13833
14211
  }
13834
14212
  process.stdout.write(nextSteps(keyVarOf(cwd)));
13835
14213
  }
13836
- var fs17, path20, import_yaml4, TEMPLATES;
14214
+ var fs17, path20, import_yaml5, TEMPLATES;
13837
14215
  var init_init = __esm({
13838
14216
  "src/cli/commands/init.ts"() {
13839
14217
  "use strict";
13840
14218
  init_cjs_shims();
13841
14219
  fs17 = __toESM(require("fs"), 1);
13842
14220
  path20 = __toESM(require("path"), 1);
13843
- import_yaml4 = require("yaml");
14221
+ import_yaml5 = require("yaml");
13844
14222
  init_wizard();
13845
14223
  init_templates();
13846
14224
  TEMPLATES = [
@@ -15261,7 +15639,7 @@ function answeringParseErrors(answer) {
15261
15639
  async function serveMcpStdio(opts) {
15262
15640
  const input = process.stdin.pipe(answeringParseErrors((line) => process.stdout.write(line)));
15263
15641
  const transport = new import_stdio2.StdioServerTransport(input, process.stdout);
15264
- await new Promise((resolve23) => {
15642
+ await new Promise((resolve24) => {
15265
15643
  (0, import_stdio2.serveStdio)((ctx) => createPluneMcpServer(opts, ctx.era), {
15266
15644
  transport,
15267
15645
  onerror: (error) => {
@@ -15279,7 +15657,7 @@ async function serveMcpStdio(opts) {
15279
15657
  const owned = transport.onclose;
15280
15658
  transport.onclose = () => {
15281
15659
  owned?.();
15282
- resolve23();
15660
+ resolve24();
15283
15661
  };
15284
15662
  });
15285
15663
  }
@@ -15412,7 +15790,7 @@ var init_run3 = __esm({
15412
15790
  now: () => import_node_perf_hooks2.performance.now(),
15413
15791
  after(ms) {
15414
15792
  let timer;
15415
- const done = new Promise((resolve23) => timer = setTimeout(resolve23, ms));
15793
+ const done = new Promise((resolve24) => timer = setTimeout(resolve24, ms));
15416
15794
  return { done, cancel: () => clearTimeout(timer) };
15417
15795
  }
15418
15796
  };
@@ -17283,8 +17661,8 @@ var init_mcp_check = __esm({
17283
17661
 
17284
17662
  // src/mcp-testing/exceptions-file.ts
17285
17663
  function parseExceptionsFile(text6, name, today) {
17286
- const lines = new import_yaml5.LineCounter();
17287
- const doc = (0, import_yaml5.parseDocument)(text6, { lineCounter: lines });
17664
+ const lines = new import_yaml6.LineCounter();
17665
+ const doc = (0, import_yaml6.parseDocument)(text6, { lineCounter: lines });
17288
17666
  const lineOf = (node) => lines.linePos(node?.range?.[0] ?? 0).line;
17289
17667
  const problems = [];
17290
17668
  const fail3 = (node, message2) => problems.push(`${name}:${lineOf(node)}: ${message2}`);
@@ -17294,19 +17672,19 @@ function parseExceptionsFile(text6, name, today) {
17294
17672
  const expired = [];
17295
17673
  const root = doc.contents;
17296
17674
  if (problems.length === 0 && root !== null) {
17297
- const list3 = (0, import_yaml5.isMap)(root) ? root.get("ignore", true) : void 0;
17298
- if (!(0, import_yaml5.isMap)(root) || list3 !== void 0 && list3 !== null && !(0, import_yaml5.isSeq)(list3))
17675
+ const list3 = (0, import_yaml6.isMap)(root) ? root.get("ignore", true) : void 0;
17676
+ if (!(0, import_yaml6.isMap)(root) || list3 !== void 0 && list3 !== null && !(0, import_yaml6.isSeq)(list3))
17299
17677
  fail3(root, 'expected "ignore:" with a list of entries.');
17300
- else if ((0, import_yaml5.isSeq)(list3)) {
17678
+ else if ((0, import_yaml6.isSeq)(list3)) {
17301
17679
  for (const item of list3.items) {
17302
- if (!(0, import_yaml5.isMap)(item)) {
17680
+ if (!(0, import_yaml6.isMap)(item)) {
17303
17681
  fail3(item, "an entry needs rule and reason.");
17304
17682
  continue;
17305
17683
  }
17306
17684
  const field = (key) => {
17307
- const pair = item.items.find((p) => (0, import_yaml5.isScalar)(p.key) && p.key.value === key);
17685
+ const pair = item.items.find((p) => (0, import_yaml6.isScalar)(p.key) && p.key.value === key);
17308
17686
  if (pair === void 0) return void 0;
17309
- const plain = (0, import_yaml5.isScalar)(pair.value) ? pair.value.value : pair.value;
17687
+ const plain = (0, import_yaml6.isScalar)(pair.value) ? pair.value.value : pair.value;
17310
17688
  if (plain !== null && plain !== void 0 && typeof plain !== "string")
17311
17689
  fail3(
17312
17690
  pair.key,
@@ -17353,12 +17731,12 @@ function parseExceptionsFile(text6, name, today) {
17353
17731
  if (problems.length > 0) throw new ExceptionsFileError(problems.join("\n"));
17354
17732
  return { active, expired };
17355
17733
  }
17356
- var import_yaml5, ExceptionsFileError, DATE2, isDate2;
17734
+ var import_yaml6, ExceptionsFileError, DATE2, isDate2;
17357
17735
  var init_exceptions_file = __esm({
17358
17736
  "src/mcp-testing/exceptions-file.ts"() {
17359
17737
  "use strict";
17360
17738
  init_cjs_shims();
17361
- import_yaml5 = require("yaml");
17739
+ import_yaml6 = require("yaml");
17362
17740
  init_failure_detail();
17363
17741
  init_exit_codes();
17364
17742
  ExceptionsFileError = class extends Error {
@@ -19295,12 +19673,12 @@ function hostFetch(target4, req, signal) {
19295
19673
  for (const [n, v] of Object.entries(target4.headers)) if (!given.has(n.toLowerCase())) headers.push(n, v);
19296
19674
  for (const [n, v] of req.headers) headers.push(n, v);
19297
19675
  const send3 = url.protocol === "https:" ? import_node_https2.request : import_node_http2.request;
19298
- return new Promise((resolve23, reject) => {
19676
+ return new Promise((resolve24, reject) => {
19299
19677
  const r = send3(url, { method: req.method, headers, signal }, (res) => {
19300
19678
  const pairs2 = [];
19301
19679
  for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) pairs2.push([res.rawHeaders[i], res.rawHeaders[i + 1]]);
19302
19680
  const nobody = res.statusCode === 204 || res.statusCode === 304;
19303
- resolve23(
19681
+ resolve24(
19304
19682
  new Response(nobody ? null : import_node_stream3.Readable.toWeb(res), {
19305
19683
  status: res.statusCode ?? 0,
19306
19684
  headers: pairs2
@@ -23314,7 +23692,7 @@ var init_transport = __esm({
23314
23692
  const open2 = () => {
23315
23693
  let opened2 = () => {
23316
23694
  };
23317
- const ready2 = new Promise((resolve23) => opened2 = resolve23);
23695
+ const ready2 = new Promise((resolve24) => opened2 = resolve24);
23318
23696
  const req = {
23319
23697
  method: "GET",
23320
23698
  headers: [
@@ -28101,11 +28479,11 @@ var init_security = __esm({
28101
28479
  details
28102
28480
  };
28103
28481
  };
28104
- reach = (host, p) => new Promise((resolve23) => {
28482
+ reach = (host, p) => new Promise((resolve24) => {
28105
28483
  const socket = (0, import_node_net.connect)({ host, port: p });
28106
28484
  const done = (got2) => {
28107
28485
  socket.destroy();
28108
- resolve23(got2);
28486
+ resolve24(got2);
28109
28487
  };
28110
28488
  socket.setTimeout(CONNECT_MS, () => done(`no answer in ${CONNECT_MS} ms`));
28111
28489
  socket.once("connect", () => done("open"));
@@ -28986,7 +29364,7 @@ var init_tasks = __esm({
28986
29364
  reason: "needs-input",
28987
29365
  actual
28988
29366
  });
28989
- sleep3 = (ms) => new Promise((resolve23) => setTimeout(resolve23, ms));
29367
+ sleep3 = (ms) => new Promise((resolve24) => setTimeout(resolve24, ms));
28990
29368
  results3 = (answers3) => answers3.flatMap((a) => a.kind === "result" ? [a.result] : []);
28991
29369
  resultType2 = async (ctx) => {
28992
29370
  const s = await ready(ctx);
@@ -29447,11 +29825,11 @@ function parseRegistration(value2, label2) {
29447
29825
  return reg;
29448
29826
  }
29449
29827
  function readYaml(source) {
29450
- const parsed4 = (0, import_yaml6.parseDocument)(source, { merge: false, schema: "core", uniqueKeys: true });
29828
+ const parsed4 = (0, import_yaml7.parseDocument)(source, { merge: false, schema: "core", uniqueKeys: true });
29451
29829
  const first = parsed4.errors[0];
29452
29830
  if (first !== void 0)
29453
29831
  throw new UsageError(`--config: the file is not valid YAML (${first.code}).`);
29454
- (0, import_yaml6.visit)(parsed4, {
29832
+ (0, import_yaml7.visit)(parsed4, {
29455
29833
  Alias() {
29456
29834
  throw new UsageError("--config: YAML aliases and anchors are not allowed.");
29457
29835
  },
@@ -29462,7 +29840,7 @@ function readYaml(source) {
29462
29840
  throw new UsageError(`--config: a YAML tag (${node.tag.slice(0, 40)}) is not allowed.`);
29463
29841
  },
29464
29842
  Pair(_key, pair) {
29465
- if ((0, import_yaml6.isScalar)(pair.key) && pair.key.value === "<<")
29843
+ if ((0, import_yaml7.isScalar)(pair.key) && pair.key.value === "<<")
29466
29844
  throw new UsageError("--config: a YAML merge key (<<) is not allowed.");
29467
29845
  }
29468
29846
  });
@@ -29552,13 +29930,13 @@ function loadOauthConfig(path25) {
29552
29930
  }
29553
29931
  return parseOauthConfig(source, /\.ya?ml$/i.test(path25) ? "yaml" : "json");
29554
29932
  }
29555
- var import_node_fs16, import_yaml6, TOP, REGISTRATION2, METHODS, MODES, SECRET_KEY2, ENV_NAME, isObject6, MAX_CONFIG_BYTES, tooLarge;
29933
+ var import_node_fs16, import_yaml7, TOP, REGISTRATION2, METHODS, MODES, SECRET_KEY2, ENV_NAME, isObject6, MAX_CONFIG_BYTES, tooLarge;
29556
29934
  var init_auth_config = __esm({
29557
29935
  "src/mcp-testing/conformance/checks/auth-config.ts"() {
29558
29936
  "use strict";
29559
29937
  init_cjs_shims();
29560
29938
  import_node_fs16 = require("fs");
29561
- import_yaml6 = require("yaml");
29939
+ import_yaml7 = require("yaml");
29562
29940
  init_options();
29563
29941
  TOP = /* @__PURE__ */ new Set([
29564
29942
  "protocolVersions",
@@ -31206,8 +31584,8 @@ var init_config = __esm({
31206
31584
 
31207
31585
  // src/mcp-testing/scan/exceptions.ts
31208
31586
  function parseScanExceptions(text6, name, today, opts = {}) {
31209
- const lines = new import_yaml7.LineCounter();
31210
- const doc = (0, import_yaml7.parseDocument)(text6, { lineCounter: lines });
31587
+ const lines = new import_yaml8.LineCounter();
31588
+ const doc = (0, import_yaml8.parseDocument)(text6, { lineCounter: lines });
31211
31589
  const lineOf = (node) => lines.linePos(node?.range?.[0] ?? 0).line;
31212
31590
  const problems = [];
31213
31591
  const fail3 = (node, message2) => problems.push(`${name}:${lineOf(node)}: ${message2}`);
@@ -31217,25 +31595,25 @@ function parseScanExceptions(text6, name, today, opts = {}) {
31217
31595
  const expired = [];
31218
31596
  const root = doc.contents;
31219
31597
  if (problems.length === 0 && root !== null) {
31220
- const list3 = (0, import_yaml7.isMap)(root) ? root.get("ignore", true) : void 0;
31221
- if (!(0, import_yaml7.isMap)(root) || list3 !== void 0 && list3 !== null && !(0, import_yaml7.isSeq)(list3))
31598
+ const list3 = (0, import_yaml8.isMap)(root) ? root.get("ignore", true) : void 0;
31599
+ if (!(0, import_yaml8.isMap)(root) || list3 !== void 0 && list3 !== null && !(0, import_yaml8.isSeq)(list3))
31222
31600
  fail3(root, 'expected "ignore:" with a list of entries.');
31223
- else if (root.items.some((p) => !((0, import_yaml7.isScalar)(p.key) && p.key.value === "ignore")))
31601
+ else if (root.items.some((p) => !((0, import_yaml8.isScalar)(p.key) && p.key.value === "ignore")))
31224
31602
  fail3(
31225
31603
  root,
31226
- `the only key of this file is "ignore:"; "${printable(String(root.items.map((p) => (0, import_yaml7.isScalar)(p.key) ? p.key.value : "?").find((k) => k !== "ignore")))}" is a typo or is not read.`
31604
+ `the only key of this file is "ignore:"; "${printable(String(root.items.map((p) => (0, import_yaml8.isScalar)(p.key) ? p.key.value : "?").find((k) => k !== "ignore")))}" is a typo or is not read.`
31227
31605
  );
31228
- else if ((0, import_yaml7.isSeq)(list3)) {
31606
+ else if ((0, import_yaml8.isSeq)(list3)) {
31229
31607
  for (const item of list3.items) {
31230
- if (!(0, import_yaml7.isMap)(item)) {
31608
+ if (!(0, import_yaml8.isMap)(item)) {
31231
31609
  fail3(item, "an entry needs rule, scope, reason and expires.");
31232
31610
  continue;
31233
31611
  }
31234
- const pair = (map, key) => map.items.find((p) => (0, import_yaml7.isScalar)(p.key) && p.key.value === key);
31612
+ const pair = (map, key) => map.items.find((p) => (0, import_yaml8.isScalar)(p.key) && p.key.value === key);
31235
31613
  const str2 = (map, key) => {
31236
31614
  const p = pair(map, key);
31237
31615
  if (p === void 0) return void 0;
31238
- const plain = (0, import_yaml7.isScalar)(p.value) ? p.value.value : p.value;
31616
+ const plain = (0, import_yaml8.isScalar)(p.value) ? p.value.value : p.value;
31239
31617
  if (plain !== null && plain !== void 0 && typeof plain !== "string") {
31240
31618
  fail3(
31241
31619
  p.key,
@@ -31250,7 +31628,7 @@ function parseScanExceptions(text6, name, today, opts = {}) {
31250
31628
  let server2;
31251
31629
  let path25;
31252
31630
  const scope = pair(item, "scope");
31253
- if (scope !== void 0 && (0, import_yaml7.isMap)(scope.value)) {
31631
+ if (scope !== void 0 && (0, import_yaml8.isMap)(scope.value)) {
31254
31632
  server2 = str2(scope.value, "server");
31255
31633
  path25 = str2(scope.value, "path");
31256
31634
  } else server2 = str2(item, "scope");
@@ -31302,12 +31680,12 @@ function covers2(e, f) {
31302
31680
  if (e.rule !== f.rule || e.server !== f.target) return false;
31303
31681
  return e.path === void 0 || f.path === e.path || f.path.startsWith(`${e.path}.`) || f.path.startsWith(`${e.path}[`) || f.path.startsWith(`${e.path}/`);
31304
31682
  }
31305
- var import_yaml7, MAX_EXCEPTION_DAYS, DATE3, isDate3, days;
31683
+ var import_yaml8, MAX_EXCEPTION_DAYS, DATE3, isDate3, days;
31306
31684
  var init_exceptions2 = __esm({
31307
31685
  "src/mcp-testing/scan/exceptions.ts"() {
31308
31686
  "use strict";
31309
31687
  init_cjs_shims();
31310
- import_yaml7 = require("yaml");
31688
+ import_yaml8 = require("yaml");
31311
31689
  init_failure_detail();
31312
31690
  init_exceptions_file();
31313
31691
  MAX_EXCEPTION_DAYS = 180;
@@ -32007,9 +32385,9 @@ async function startPage() {
32007
32385
  server2.headersTimeout = 5e3;
32008
32386
  server2.requestTimeout = 5e3;
32009
32387
  server2.keepAliveTimeout = 1e3;
32010
- await new Promise((resolve23, reject) => {
32388
+ await new Promise((resolve24, reject) => {
32011
32389
  server2.once("error", reject);
32012
- server2.listen(0, "127.0.0.1", resolve23);
32390
+ server2.listen(0, "127.0.0.1", resolve24);
32013
32391
  });
32014
32392
  const { address, port: port2 } = server2.address();
32015
32393
  return {
@@ -32022,9 +32400,9 @@ async function startPage() {
32022
32400
  requestTimeout: server2.requestTimeout,
32023
32401
  keepAliveTimeout: server2.keepAliveTimeout
32024
32402
  },
32025
- close: () => new Promise((resolve23) => {
32403
+ close: () => new Promise((resolve24) => {
32026
32404
  server2.closeAllConnections();
32027
- server2.close(() => resolve23());
32405
+ server2.close(() => resolve24());
32028
32406
  })
32029
32407
  };
32030
32408
  }
@@ -34247,21 +34625,37 @@ async function defaultReadEvidence(dir) {
34247
34625
  return { name: str(rec["name"]), passed: rec["passed"] === true, ...error !== "" ? { error } : {} };
34248
34626
  });
34249
34627
  }
34250
- function casesFromDesign(report) {
34628
+ function casesFromDesign(report, notes) {
34251
34629
  const list3 = Array.isArray(report["testCases"]) ? report["testCases"] : [];
34252
- return list3.map((raw) => {
34630
+ const refused = /* @__PURE__ */ new Map();
34631
+ const cases = list3.map((raw) => {
34253
34632
  const c = asRecord2(raw);
34254
34633
  const steps = (Array.isArray(c["steps"]) ? c["steps"] : []).map((s) => str(s)).filter((s) => s !== "");
34634
+ const title = str(c["title"], "untitled case");
34635
+ const link = own2(c, "traceUrl") ?? void 0;
34636
+ const said3 = [];
34637
+ const traceUrl = traceUrlOf(link, title, said3);
34638
+ if (said3.length > 0) {
34639
+ const key = typeof link === "string" ? link.trim() : typeof link;
34640
+ const before = refused.get(key) ?? 0;
34641
+ if (before === 0) notes.push(...said3);
34642
+ refused.set(key, before + 1);
34643
+ }
34255
34644
  return {
34256
34645
  stableId: str(c["stableId"]),
34257
- title: str(c["title"], "untitled case"),
34646
+ title,
34258
34647
  execution: c["execution"] === "manual" ? "manual" : "auto",
34259
34648
  steps: steps.length > 0 ? steps : ["(no steps recorded)"],
34260
34649
  expected: str(c["expected"], "(no expected result recorded)"),
34261
34650
  ...typeof c["technique"] === "string" ? { technique: c["technique"] } : {},
34262
- ...typeof c["priority"] === "string" ? { priority: c["priority"] } : {}
34651
+ ...typeof c["priority"] === "string" ? { priority: c["priority"] } : {},
34652
+ ...traceUrl !== void 0 ? { traceUrl } : {}
34263
34653
  };
34264
34654
  });
34655
+ for (const times of refused.values()) {
34656
+ if (times > 1) notes.push(`plune: ${times - 1} more case(s) carry the same trace link \u2014 sent without it.`);
34657
+ }
34658
+ return cases;
34265
34659
  }
34266
34660
  function casesFromApi(report, verdicts) {
34267
34661
  const list3 = Array.isArray(report["cases"]) ? report["cases"] : [];
@@ -34308,9 +34702,9 @@ async function readCairnRun(dir, deps = {}) {
34308
34702
  }
34309
34703
  cases = casesFromApi(report, verdicts);
34310
34704
  } else if (mode === "mcp") {
34311
- cases = own2(report, "cases") === void 0 && Array.isArray(own2(report, "testCases")) ? casesFromDesign(report) : await casesFromMcp(dir, report);
34705
+ cases = own2(report, "cases") === void 0 && Array.isArray(own2(report, "testCases")) ? casesFromDesign(report, deps.notes ?? []) : await casesFromMcp(dir, report);
34312
34706
  } else {
34313
- cases = casesFromDesign(report);
34707
+ cases = casesFromDesign(report, deps.notes ?? []);
34314
34708
  }
34315
34709
  const tokens2 = own2(asRecord2(own2(report, "cost")), "totalTokens");
34316
34710
  return {
@@ -34396,6 +34790,7 @@ var init_cairn_artifact = __esm({
34396
34790
  init_cjs_shims();
34397
34791
  fs18 = __toESM(require("fs/promises"), 1);
34398
34792
  path22 = __toESM(require("path"), 1);
34793
+ init_trace_url();
34399
34794
  init_config();
34400
34795
  init_errors2();
34401
34796
  SUPPORTED_ARTIFACT_VERSION = 1;
@@ -34618,7 +35013,8 @@ async function handleIngest(deps) {
34618
35013
  const token2 = (deps.loadToken ?? loadToken)();
34619
35014
  if (token2 === null) throw new IngestNotLoggedInError();
34620
35015
  const dir = deps.dir ?? await findLatestCairnRun(deps.runsDir);
34621
- const payload2 = await readCairnRun(dir);
35016
+ const notes = [];
35017
+ const payload2 = await readCairnRun(dir, { notes });
34622
35018
  const session2 = await readCairnSessionFiles(dir).catch(() => void 0);
34623
35019
  for (const c of payload2.cases) {
34624
35020
  const screencasts = session2?.screencasts.get(c.stableId);
@@ -34636,6 +35032,7 @@ async function handleIngest(deps) {
34636
35032
  );
34637
35033
  if (files.length > 0) result2.files = files;
34638
35034
  if (sent.repeat) result2.repeat = true;
35035
+ if (notes.length > 0) result2.notes = notes;
34639
35036
  await job.finish({ ok: true });
34640
35037
  if (job.problem !== void 0) result2.jobProblem = job.problem;
34641
35038
  return result2;
@@ -34686,6 +35083,7 @@ function formatIngestResult(r) {
34686
35083
  const files = (r.files ?? []).map((line, i) => i === 0 ? ` ${line}` : ` ${line}`);
34687
35084
  if (r.repeat === true) {
34688
35085
  return `${[
35086
+ ...r.notes ?? [],
34689
35087
  `This Cairn run was already ingested \u2192 ${r.runId}`,
34690
35088
  " nothing new was proposed or attached; a run with a new run id is ingested as new",
34691
35089
  ...files
@@ -34693,6 +35091,7 @@ function formatIngestResult(r) {
34693
35091
  `;
34694
35092
  }
34695
35093
  const lines = [
35094
+ ...r.notes ?? [],
34696
35095
  `Ingested Cairn run \u2192 ${r.runId}`,
34697
35096
  ` ${r.linked} result(s) attached to existing cases`,
34698
35097
  ` ${r.proposed} case(s) proposed \u2014 review them in Plune to accept`,
@@ -34759,7 +35158,7 @@ __export(requirements_import_exports, {
34759
35158
  cut: () => cut4,
34760
35159
  flat: () => flat2,
34761
35160
  formatDiscover: () => formatDiscover,
34762
- formatReport: () => formatReport2,
35161
+ formatReport: () => formatReport3,
34763
35162
  handleRequirementsImport: () => handleRequirementsImport,
34764
35163
  parseMap: () => parseMap,
34765
35164
  parseTableSpec: () => parseTableSpec,
@@ -34954,7 +35353,7 @@ function formatDiscover(file, r) {
34954
35353
  );
34955
35354
  return out.join("\n") + "\n";
34956
35355
  }
34957
- function formatReport2(report) {
35356
+ function formatReport3(report) {
34958
35357
  const s = report.summary;
34959
35358
  const out = [`create ${s.create} \xB7 update ${s.update} \xB7 unchanged ${s.unchanged} \xB7 skip ${s.skip}`];
34960
35359
  if (report.emptyTemplate === true) {
@@ -35394,13 +35793,13 @@ async function handleAutomate(deps) {
35394
35793
  const viaShell = process.platform === "win32" && /\.(cmd|bat)$/i.test(executable);
35395
35794
  const quoted = (s) => `"${s.replace(/"/g, '""')}"`;
35396
35795
  const spawnImpl = deps.spawnImpl ?? import_node_child_process5.spawn;
35397
- const runCairn = (args, capture) => new Promise((resolve23) => {
35796
+ const runCairn = (args, capture) => new Promise((resolve24) => {
35398
35797
  const opts = { cwd: repo, env: childEnv, stdio: ["ignore", capture ? "pipe" : 2, 2] };
35399
35798
  const child = isScript ? spawnImpl(process.execPath, [executable, ...args], opts) : viaShell ? spawnImpl([executable, ...args].map(quoted).join(" "), { ...opts, shell: true }) : spawnImpl(executable, args, opts);
35400
35799
  let out = "";
35401
35800
  child.stdout?.on("data", (chunk2) => void (out += chunk2.toString("utf8")));
35402
- child.on("close", (exitCode2) => resolve23({ code: exitCode2 ?? 1, out }));
35403
- child.on("error", () => resolve23({ code: -1, out }));
35801
+ child.on("close", (exitCode2) => resolve24({ code: exitCode2 ?? 1, out }));
35802
+ child.on("error", () => resolve24({ code: -1, out }));
35404
35803
  });
35405
35804
  const { code } = await runCairn(["automate", "--run", runDir, ...deps.cairnArgs ?? []], false);
35406
35805
  if (code === -1) throw new CairnMissingError(command);
@@ -36234,23 +36633,48 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36234
36633
  }
36235
36634
  }
36236
36635
  );
36237
- program.command("init").description("Scaffold plune.yaml (interactive), an example dataset, and .env.example").option("--force", "Overwrite existing files instead of skipping them", false).option("--yes", "Non-interactive: scaffold defaults without prompts (for CI)", false).action(async (options, command) => {
36238
- const verbose = command.optsWithGlobals().verbose === true;
36239
- const [{ initCommand: initCommand2 }, { NonTtyError: NonTtyError2 }] = await Promise.all([
36240
- Promise.resolve().then(() => (init_init(), init_exports)),
36241
- Promise.resolve().then(() => (init_errors(), errors_exports))
36242
- ]);
36243
- try {
36244
- await initCommand2({ cwd: process.cwd(), force: options.force, yes: options.yes });
36245
- } catch (err) {
36246
- if (err instanceof NonTtyError2) {
36247
- process.stderr.write(err.message + "\n");
36248
- process.exit(1);
36636
+ program.command("init").description("Scaffold plune.yaml (interactive), an example dataset, and .env.example").option("--force", "Overwrite existing files instead of skipping them", false).option("--yes", "Non-interactive: scaffold defaults without prompts (for CI)", false).option(
36637
+ "--from-openai-eval <eval.json>",
36638
+ "Build plune.yaml from an exported OpenAI eval (the answer of GET /v1/evals/{eval_id}) and print what each grader became"
36639
+ ).option("--run <run.json>", "With --from-openai-eval: one run of that eval, for the prompt and the model").option("--data <rows.jsonl>", 'With --from-openai-eval: the test data, one {"item": {...}} per line').action(
36640
+ async (options, command) => {
36641
+ const verbose = command.optsWithGlobals().verbose === true;
36642
+ const [{ initCommand: initCommand2, initFromOpenAiEval: initFromOpenAiEval2 }, { NonTtyError: NonTtyError2 }] = await Promise.all([
36643
+ Promise.resolve().then(() => (init_init(), init_exports)),
36644
+ Promise.resolve().then(() => (init_errors(), errors_exports))
36645
+ ]);
36646
+ if (options.fromOpenaiEval === void 0 && (options.run !== void 0 || options.data !== void 0)) {
36647
+ process.stderr.write("--run and --data need --from-openai-eval <eval.json>\n");
36648
+ process.exit(2);
36249
36649
  return;
36250
36650
  }
36251
- failUnexpected(err, verbose);
36651
+ try {
36652
+ if (options.fromOpenaiEval !== void 0) {
36653
+ await initFromOpenAiEval2({
36654
+ cwd: process.cwd(),
36655
+ force: options.force,
36656
+ evalPath: options.fromOpenaiEval,
36657
+ ...options.run !== void 0 ? { runPath: options.run } : {},
36658
+ ...options.data !== void 0 ? { dataPath: options.data } : {}
36659
+ });
36660
+ return;
36661
+ }
36662
+ await initCommand2({ cwd: process.cwd(), force: options.force, yes: options.yes });
36663
+ } catch (err) {
36664
+ if (err instanceof Error && err.name === "OpenAiEvalImportError") {
36665
+ process.stderr.write(err.message + "\n");
36666
+ process.exit(2);
36667
+ return;
36668
+ }
36669
+ if (err instanceof NonTtyError2) {
36670
+ process.stderr.write(err.message + "\n");
36671
+ process.exit(1);
36672
+ return;
36673
+ }
36674
+ failUnexpected(err, verbose);
36675
+ }
36252
36676
  }
36253
- });
36677
+ );
36254
36678
  program.command("login").description("Save your Plune API token (get one in the dashboard: Account \u2192 API tokens)").option("--token <token>", "API token (omit to paste it / pipe it via stdin)").option(
36255
36679
  "--skip-verify",
36256
36680
  "Save without checking the token against the API (offline setup)",
@@ -36559,13 +36983,13 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36559
36983
  "Send a Markdown document of test cases back to Plune (POST /v1/test-cases/markdown)"
36560
36984
  ).option("--dry-run", "Show what would change and write nothing", false).action(async (file, options, command) => {
36561
36985
  const verbose = command.optsWithGlobals().verbose === true;
36562
- const { handlePush: handlePush2, formatReport: formatReport3, reportCasesFailure: reportCasesFailure2 } = await Promise.resolve().then(() => (init_cases(), cases_exports));
36986
+ const { handlePush: handlePush2, formatReport: formatReport4, reportCasesFailure: reportCasesFailure2 } = await Promise.resolve().then(() => (init_cases(), cases_exports));
36563
36987
  try {
36564
36988
  const report = await handlePush2({
36565
36989
  ...file !== void 0 ? { file } : {},
36566
36990
  dryRun: options.dryRun
36567
36991
  });
36568
- process.stdout.write(formatReport3(report));
36992
+ process.stdout.write(formatReport4(report));
36569
36993
  if (report.refused.length > 0) process.exitCode = 4;
36570
36994
  } catch (err) {
36571
36995
  const code = reportCasesFailure2(err, (s) => process.stderr.write(s));
@@ -36586,13 +37010,13 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36586
37010
  (value2, previous = []) => [...previous, value2]
36587
37011
  ).option("--key-column <header>", "Table: the column holding the requirement key").option("--title-column <header>", "Table: the column holding the title").option("--text-column <header>", "Table: one text column; the title is its first line (not with --title-column)").option("--description-column <header>", "Table: the description column").option("--priority-column <header>", "Table: the priority column").option("--category-column <header>", "Table: the category column").option("--type-column <header>", "Table: the type column").option("--status-column <header>", "Table: the status column (draft, active or done)").option("--criteria-column <header>", "Table: the acceptance criteria column").option("--map-priority <pairs>", 'Rename priority values, e.g. "Critical=Must-have,High=Should-have"').option("--map-category <pairs>", 'Table: rename category values, e.g. "Quality=non-functional"').option("--sections <heading|n>", "Read the section with this heading or number (from the list)").option("--unit <unit>", "Sections: bullets or subheadings (default: sub-headings if it has any)").option("--key-prefix <text>", "Sections: text a bullet or sub-heading starts with that carries its key").option("--priority-from <source>", "Sections: subheading \u2014 bullets take their sub-heading as priority").option("--type <type>", "What a row without a type becomes: user_story, feature or epic").option("--project <id>", "The project (default: PLUNE_PROJECT, else the only project of the account)").option("--yes", "Write it. Without it the import is a dry run", false).option("--json", "Print the platform\u2019s answer as JSON", false).action(async (file, options, command) => {
36588
37012
  const verbose = command.optsWithGlobals().verbose === true;
36589
- const { handleRequirementsImport: handleRequirementsImport2, formatDiscover: formatDiscover2, formatReport: formatReport3, reportRequirementsImportFailure: reportRequirementsImportFailure2 } = await Promise.resolve().then(() => (init_requirements_import(), requirements_import_exports));
37013
+ const { handleRequirementsImport: handleRequirementsImport2, formatDiscover: formatDiscover2, formatReport: formatReport4, reportRequirementsImportFailure: reportRequirementsImportFailure2 } = await Promise.resolve().then(() => (init_requirements_import(), requirements_import_exports));
36590
37014
  try {
36591
37015
  const res = await handleRequirementsImport2({ file, ...options });
36592
37016
  if (options.json === true) {
36593
37017
  process.stdout.write(JSON.stringify(res.step === "discover" ? res.result : res.report, null, 2) + "\n");
36594
37018
  } else {
36595
- process.stdout.write(res.step === "discover" ? formatDiscover2(file, res.result) : formatReport3(res.report));
37019
+ process.stdout.write(res.step === "discover" ? formatDiscover2(file, res.result) : formatReport4(res.report));
36596
37020
  }
36597
37021
  } catch (err) {
36598
37022
  const code = reportRequirementsImportFailure2(err, (s) => process.stderr.write(s));