@ancha-labs/cli 0.4.43 → 0.4.44

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/lib/ancha.mjs CHANGED
@@ -204933,8 +204933,8 @@ function invalid35(message8) {
204933
204933
  });
204934
204934
  }
204935
204935
  function excluded(name5) {
204936
- const lower5 = name5.toLowerCase();
204937
- return lower5.startsWith(".") || EXCLUDED_DIRECTORIES.has(lower5) || EXCLUDED_NAMES.has(lower5) || /\.(?:env|pem|key|p12|pfx|jks|keystore|pyc|pyo)$/.test(lower5);
204936
+ const lower5 = name5.toLowerCase(), held = lower5.replace(/\.pending$/, "");
204937
+ return lower5.startsWith(".") || EXCLUDED_DIRECTORIES.has(lower5) || EXCLUDED_NAMES.has(held) || /\.(?:env|pem|key|p12|pfx|jks|keystore|pyc|pyo)$/.test(held);
204938
204938
  }
204939
204939
  function within(root3, candidate) {
204940
204940
  const path9 = relative3(root3, candidate);
@@ -243406,7 +243406,7 @@ function connectionRouteEvidence(routes2, summary, trace2, log3) {
243406
243406
  const tools2 = routedTools(routes2);
243407
243407
  if (!tools2.length) return { details: [] };
243408
243408
  const counts2 = tools2.map((tool) => ({ tool, route: summary?.[tool] }));
243409
- const details = counts2.map(({ tool, route: route15 }) => `${tool === "netsuite" ? "NetSuite" : "QuickBooks"} via Composio: ${route15?.executions ?? 0} executions, ${route15?.reached ?? 0} reached the world, ${route15?.refused ?? 0} refused${route15?.via ? ` \xB7 via direct ${route15.via.direct} / session ${route15.via.session} / MCP ${route15.via.mcp}` : ""}`);
243409
+ const details = counts2.map(({ tool, route: route15 }) => `${tool === "netsuite" ? "NetSuite" : "QuickBooks"} via Composio: ${route15?.executions ?? 0} execution${route15?.executions === 1 ? "" : "s"}, ${route15?.reached ?? 0} reached the world, ${route15?.refused ?? 0} refused${route15?.via ? ` \xB7 via direct ${route15.via.direct} / session ${route15.via.session} / MCP ${route15.via.mcp}` : ""}`);
243410
243410
  const refused2 = trace2.filter((entry3) => entry3.routeEvent?.leg === "platform" && entry3.routeEvent.op === "refused");
243411
243411
  for (const entry3 of refused2.slice(0, 5)) {
243412
243412
  const event3 = entry3.routeEvent;
@@ -252281,7 +252281,7 @@ function registerEnv(program2, ctx) {
252281
252281
  // packages/cli/src/commands/explain.ts
252282
252282
  init_src();
252283
252283
  init_src();
252284
- import { readFile as readFile34, writeFile as writeFile23 } from "node:fs/promises";
252284
+ import { readFile as readFile35, writeFile as writeFile24 } from "node:fs/promises";
252285
252285
  import { join as join50, relative as relative19, resolve as resolve39 } from "node:path";
252286
252286
 
252287
252287
  // packages/cli/src/numbers.ts
@@ -257262,7 +257262,9 @@ init_run_bundle();
257262
257262
  // packages/cli/src/commands/login.ts
257263
257263
  init_src();
257264
257264
  import { spawn as spawn5 } from "node:child_process";
257265
+ import { chmod as chmod7, mkdir as mkdir23, readFile as readFile33, rm as rm12, writeFile as writeFile23 } from "node:fs/promises";
257265
257266
  import { hostname as hostname4 } from "node:os";
257267
+ import { dirname as dirname21 } from "node:path";
257266
257268
  init_credentials();
257267
257269
  init_backend();
257268
257270
  var DEFAULT_CLOUD_URL = "https://app.ancha.io";
@@ -257317,6 +257319,43 @@ var sleep12 = (ms2, signal) => new Promise((resolve63) => {
257317
257319
  resolve63();
257318
257320
  }, { once: true });
257319
257321
  });
257322
+ var RESUME_HINT = "If this command stops before you approve, run ancha login again: it finishes this sign-in.";
257323
+ var pendingPath = (env2) => {
257324
+ const path9 = credentialsPath(env2);
257325
+ return path9 ? `${path9}.pending` : "";
257326
+ };
257327
+ async function readPending(env2, server) {
257328
+ const path9 = pendingPath(env2);
257329
+ if (!path9) return null;
257330
+ try {
257331
+ const p2 = JSON.parse(await readFile33(path9, "utf8"));
257332
+ if (p2.version !== 1 || p2.server !== server || typeof p2.deviceCode !== "string" || typeof p2.userCode !== "string" || typeof p2.verificationUrl !== "string" || typeof p2.expiresAt !== "string") return null;
257333
+ return p2;
257334
+ } catch {
257335
+ return null;
257336
+ }
257337
+ }
257338
+ async function writePending(env2, pending) {
257339
+ const path9 = pendingPath(env2);
257340
+ if (!path9) return false;
257341
+ try {
257342
+ await mkdir23(dirname21(path9), { recursive: true, mode: 448 });
257343
+ await writeFile23(path9, JSON.stringify(pending) + "\n", { mode: 384 });
257344
+ await chmod7(path9, 384).catch(() => {
257345
+ });
257346
+ return true;
257347
+ } catch {
257348
+ return false;
257349
+ }
257350
+ }
257351
+ async function dropPending(env2, deviceCode) {
257352
+ const path9 = pendingPath(env2);
257353
+ if (!path9) return;
257354
+ try {
257355
+ if (JSON.parse(await readFile33(path9, "utf8")).deviceCode === deviceCode) await rm12(path9, { force: true });
257356
+ } catch {
257357
+ }
257358
+ }
257320
257359
  function registerLogin(program2, ctx, deps = {}) {
257321
257360
  program2.command("login").description("sign in to your hosted workspace from this computer: ancha run runs your tests there, and import, pull and traces use it").option("--url <url>", "hosted Ancha address", DEFAULT_CLOUD_URL).option("--no-browser", "print the approval link instead of opening a browser").action(async (opts) => {
257322
257361
  let base6;
@@ -257325,30 +257364,64 @@ function registerLogin(program2, ctx, deps = {}) {
257325
257364
  } catch {
257326
257365
  throw new AnchaError("USAGE", "invalid --url", { hint: `use an https address such as ${DEFAULT_CLOUD_URL}` });
257327
257366
  }
257328
- const start2 = await json38(`${base6}/cli/device`, { method: "POST", body: JSON.stringify({ name: hostname4() }) }, deps.fetch);
257329
- ctx.out.info(`Confirm this computer in your browser: ${start2.verification_url}`);
257330
- ctx.out.info(`Code: ${start2.user_code}`);
257331
- if (ctx.out.json) ctx.out.event({ event: "login_pending", verificationUrl: start2.verification_url, userCode: start2.user_code, expiresIn: start2.expires_in });
257332
- if (opts.browser) openBrowser(start2.verification_url);
257333
- const signal = ctx.io.abort;
257334
- const deadline3 = Date.now() + start2.expires_in * 1e3;
257335
- const interval = Math.max(2, Math.min(15, start2.interval || 3)) * 1e3;
257367
+ const env2 = ctx.io.env, signal = ctx.io.abort;
257368
+ if (!credentialsPath(env2)) throw new AnchaError("USAGE", "set HOME or ANCHA_CREDENTIALS_FILE to save a sign-in");
257369
+ const poll = (deviceCode) => json38(`${base6}/cli/poll?device_code=${encodeURIComponent(deviceCode)}`, {}, deps.fetch);
257370
+ let pending = await readPending(env2, base6), resumed = false;
257371
+ if (pending) {
257372
+ const first2 = await poll(pending.deviceCode);
257373
+ if (first2.status === "approved") return finish2(first2, pending.deviceCode);
257374
+ if (first2.status === "pending" && Date.parse(pending.expiresAt) - Date.now() > 15e3) resumed = true;
257375
+ else {
257376
+ await dropPending(env2, pending.deviceCode);
257377
+ pending = null;
257378
+ }
257379
+ }
257380
+ let saved = resumed;
257381
+ if (!pending) {
257382
+ const start2 = await json38(`${base6}/cli/device`, { method: "POST", body: JSON.stringify({ name: hostname4() }) }, deps.fetch);
257383
+ pending = { version: 1, server: base6, deviceCode: start2.device_code, userCode: start2.user_code, verificationUrl: start2.verification_url, interval: start2.interval, window: start2.expires_in, expiresAt: new Date(Date.now() + start2.expires_in * 1e3).toISOString() };
257384
+ saved = await writePending(env2, pending);
257385
+ }
257386
+ const expiresIn = Math.max(1, Math.round((Date.parse(pending.expiresAt) - Date.now()) / 1e3));
257387
+ if (resumed) ctx.out.info("Finishing the sign-in an earlier ancha login started on this computer.");
257388
+ ctx.out.info(`Confirm this computer in your browser: ${pending.verificationUrl}`);
257389
+ ctx.out.info(`Code: ${pending.userCode}`);
257390
+ if (saved) ctx.out.info(RESUME_HINT);
257391
+ if (ctx.out.json) ctx.out.event({ event: "login_pending", verificationUrl: pending.verificationUrl, userCode: pending.userCode, expiresIn, ...resumed && { resumed: true }, ...saved && { hint: RESUME_HINT } });
257392
+ if (opts.browser && !resumed) openBrowser(pending.verificationUrl);
257393
+ const deadline3 = Date.parse(pending.expiresAt);
257394
+ const interval = Math.max(2, Math.min(15, pending.interval || 3)) * 1e3;
257336
257395
  while (Date.now() < deadline3 && !signal?.aborted) {
257337
257396
  await sleep12(interval, signal);
257338
257397
  if (signal?.aborted) break;
257339
- const poll = await json38(`${base6}/cli/poll?device_code=${encodeURIComponent(start2.device_code)}`, {}, deps.fetch);
257340
- if (poll.status === "pending") continue;
257341
- if (poll.status === "denied") throw new AnchaError("USAGE", "sign-in was denied in the browser");
257342
- if (poll.status === "expired") break;
257343
- if (!poll.apiKey || !poll.serverUrl) throw new AnchaError("INTERNAL", `${base6} approved the sign-in without a key`);
257344
- const serverUrl3 = normalizeServerUrl(poll.serverUrl);
257345
- const file3 = await readCredentials(ctx.io.env);
257346
- file3.servers[serverUrl3] = { apiKey: poll.apiKey, ...poll.email && { email: poll.email }, savedAt: (/* @__PURE__ */ new Date()).toISOString(), minted: "device" };
257398
+ const result = await poll(pending.deviceCode);
257399
+ if (result.status === "pending") continue;
257400
+ if (result.status === "denied") {
257401
+ await dropPending(env2, pending.deviceCode);
257402
+ throw new AnchaError("USAGE", "sign-in was denied in the browser");
257403
+ }
257404
+ if (result.status === "expired") break;
257405
+ return finish2(result, pending.deviceCode);
257406
+ }
257407
+ if (signal?.aborted) throw new AnchaError("USAGE", "login interrupted");
257408
+ await dropPending(env2, pending.deviceCode);
257409
+ const minutes = Math.max(1, Math.round((pending.window || expiresIn) / 60));
257410
+ throw new AnchaError("USAGE", "the approval link expired", { hint: `run ancha login again and approve within ${minutes} minute${minutes === 1 ? "" : "s"}` });
257411
+ async function finish2(approved, deviceCode) {
257412
+ if (!approved.apiKey || !approved.serverUrl) {
257413
+ await dropPending(env2, deviceCode);
257414
+ throw new AnchaError("INTERNAL", `${base6} approved the sign-in without a key`);
257415
+ }
257416
+ const serverUrl3 = normalizeServerUrl(approved.serverUrl);
257417
+ const file3 = await readCredentials(env2);
257418
+ file3.servers[serverUrl3] = { apiKey: approved.apiKey, ...approved.email && { email: approved.email }, savedAt: (/* @__PURE__ */ new Date()).toISOString(), minted: "device" };
257347
257419
  file3.default = serverUrl3;
257348
- const path9 = await writeCredentials(file3, ctx.io.env);
257420
+ const path9 = await writeCredentials(file3, env2);
257421
+ await dropPending(env2, deviceCode);
257349
257422
  let onboarding = null, unread2;
257350
257423
  try {
257351
- onboarding = await fetchOnboarding(ctx, { serverUrl: serverUrl3, apiKey: poll.apiKey });
257424
+ onboarding = await fetchOnboarding(ctx, { serverUrl: serverUrl3, apiKey: approved.apiKey });
257352
257425
  } catch (e) {
257353
257426
  unread2 = toErrorJson(e);
257354
257427
  }
@@ -257356,20 +257429,16 @@ function registerLogin(program2, ctx, deps = {}) {
257356
257429
  const { source } = await serverChoice(ctx).catch(() => ({ source: "login" }));
257357
257430
  const runLine = source === "config" || source === "env" ? `${SERVER_SOURCE_LABEL[source]} chooses the server here, so ancha run keeps the target in ancha.yaml.` : loginRunLine(ctx);
257358
257431
  ctx.out.result(
257359
- { serverUrl: serverUrl3, ...poll.email && { email: poll.email }, credentials: path9, onboarding, ...next2 && { next: next2 }, ...unread2 && { onboardingError: unread2 } },
257432
+ { serverUrl: serverUrl3, ...approved.email && { email: approved.email }, credentials: path9, onboarding, ...next2 && { next: next2 }, ...unread2 && { onboardingError: unread2 } },
257360
257433
  () => [
257361
- `Signed in${poll.email ? ` as ${poll.email}` : ""}.`,
257434
+ `Signed in${approved.email ? ` as ${approved.email}` : ""}.`,
257362
257435
  `Workspace: ${serverUrl3}`,
257363
257436
  `Saved to ${path9}. ${runLine}`,
257364
257437
  onboarding ? `
257365
257438
  ${renderOnboarding(onboarding, next2 ?? void 0)}` : `The onboarding checks could not be read: ${unread2?.message.replace(/\.$/, "")}. ancha status --on cloud shows them.`
257366
257439
  ].join("\n")
257367
257440
  );
257368
- return;
257369
257441
  }
257370
- if (signal?.aborted) throw new AnchaError("USAGE", "login interrupted");
257371
- const minutes = Math.max(1, Math.round(start2.expires_in / 60));
257372
- throw new AnchaError("USAGE", "the approval link expired", { hint: `run ancha login again and approve within ${minutes} minute${minutes === 1 ? "" : "s"}` });
257373
257442
  });
257374
257443
  program2.command("logout").description("sign out of a hosted Ancha and revoke the key that sign-in created").option("--url <url>", "hosted world server to forget (default: the saved default)").action(async (opts) => {
257375
257444
  const file3 = await readCredentials(ctx.io.env);
@@ -257437,11 +257506,11 @@ ${worlds2 === "local" ? loginRunLine(ctx) : "This server override keeps the agen
257437
257506
  // packages/cli/src/kit/trace-connection.ts
257438
257507
  var import_yaml10 = __toESM(require_dist(), 1);
257439
257508
  init_src();
257440
- import { readFile as readFile33 } from "node:fs/promises";
257509
+ import { readFile as readFile34 } from "node:fs/promises";
257441
257510
  import { relative as relative18 } from "node:path";
257442
257511
  init_detect();
257443
257512
  async function traceConnection(cwd, paths3, configured, target6, recordsAdapter, cloud = false) {
257444
- const scenes = await Promise.all(paths3.map(async (path9) => ({ path: relative18(cwd, path9), scene: (0, import_yaml10.parse)(await readFile33(path9, "utf8")) })));
257513
+ const scenes = await Promise.all(paths3.map(async (path9) => ({ path: relative18(cwd, path9), scene: (0, import_yaml10.parse)(await readFile34(path9, "utf8")) })));
257445
257514
  const tools2 = [...new Set(scenes.flatMap(({ scene: scene2 }) => (scene2.twins ?? []).filter((name5) => !(name5 === "slack" && scene2.agent_input === "per_event" && scene2.people?.length))))].map((name5) => ({
257446
257515
  name: name5,
257447
257516
  env: connectionGuide(name5, "ts").env,
@@ -257514,8 +257583,8 @@ async function toolAnswers(runDir, summary, filter4) {
257514
257583
  const out = [];
257515
257584
  for (const scene2 of summary.scenes) for (const { trial } of scene2.trialsDetail) {
257516
257585
  if (filter4.scene !== void 0 && filter4.scene !== scene2.sceneId || filter4.trial !== void 0 && filter4.trial !== trial) continue;
257517
- const text31 = await readFile34(join50(runDir, `trial-${scene2.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
257518
- const state3 = await readFile34(join50(runDir, `trial-${scene2.sceneId}-${trial}`, "state.json"), "utf8").then(JSON.parse).catch(() => void 0);
257586
+ const text31 = await readFile35(join50(runDir, `trial-${scene2.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
257587
+ const state3 = await readFile35(join50(runDir, `trial-${scene2.sceneId}-${trial}`, "state.json"), "utf8").then(JSON.parse).catch(() => void 0);
257519
257588
  const trace2 = text31.split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
257520
257589
  const functionTools = projectFunctionTools(trace2, state3);
257521
257590
  const logical = new Map(functionTools.calls.map((c) => [c.seq, c]));
@@ -257553,7 +257622,7 @@ function invalidSetupNext(summary, out, readDirectory) {
257553
257622
  })];
257554
257623
  }
257555
257624
  async function trialOutcomes(runDir, summary, filter4) {
257556
- const inputs2 = await readFile34(join50(runDir, "inputs.json"), "utf8").then((text31) => JSON.parse(text31), () => ({ cases: [] }));
257625
+ const inputs2 = await readFile35(join50(runDir, "inputs.json"), "utf8").then((text31) => JSON.parse(text31), () => ({ cases: [] }));
257557
257626
  const out = [];
257558
257627
  for (const scene2 of summary.scenes) {
257559
257628
  if (filter4.scene !== void 0 && filter4.scene !== scene2.sceneId) continue;
@@ -257562,15 +257631,15 @@ async function trialOutcomes(runDir, summary, filter4) {
257562
257631
  for (const detail3 of scene2.trialsDetail) {
257563
257632
  if (detail3.passed || detail3.outcome === "skipped" || detail3.outcome === "xfailed" || filter4.trial !== void 0 && filter4.trial !== detail3.trial) continue;
257564
257633
  const dir2 = join50(runDir, `trial-${scene2.sceneId}-${detail3.trial}`);
257565
- const trace2 = (await readFile34(join50(dir2, "trace.jsonl"), "utf8").catch(() => "")).split("\n").filter(Boolean).flatMap((line2) => {
257634
+ const trace2 = (await readFile35(join50(dir2, "trace.jsonl"), "utf8").catch(() => "")).split("\n").filter(Boolean).flatMap((line2) => {
257566
257635
  try {
257567
257636
  return [JSON.parse(line2)];
257568
257637
  } catch {
257569
257638
  return [];
257570
257639
  }
257571
257640
  });
257572
- const result = await readFile34(join50(dir2, "result.json"), "utf8").then((text31) => JSON.parse(text31), () => ({}));
257573
- const log3 = (await readFile34(join50(dir2, "agent.log"), "utf8").catch(() => "")).slice(-1e6);
257641
+ const result = await readFile35(join50(dir2, "result.json"), "utf8").then((text31) => JSON.parse(text31), () => ({}));
257642
+ const log3 = (await readFile35(join50(dir2, "agent.log"), "utf8").catch(() => "")).slice(-1e6);
257574
257643
  const { reason: reason2, calls: calls2 } = attemptOutcome(
257575
257644
  { exit: detail3.exit, exitCode: detail3.exitCode, realMs: detail3.realMs, trace: trace2, log: log3, ...result.logTail && { logTail: result.logTail }, modelReplies: result.modelReplies },
257576
257645
  { check: "test", answerChecked, target: "local" }
@@ -257781,7 +257850,7 @@ function registerExplain(program2, ctx) {
257781
257850
  const outcomes = await trialOutcomes(join50(resolve39(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), summary.runId), summary, filter4);
257782
257851
  const out = opts.out === void 0 ? "" : ` --out ${shellArgument(opts.out)}`;
257783
257852
  const baselinePath = join50(resolve39(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), "..", "baselines", "before.json");
257784
- const baselineText = await readFile34(baselinePath, "utf8").catch(() => void 0);
257853
+ const baselineText = await readFile35(baselinePath, "utf8").catch(() => void 0);
257785
257854
  const baseline = baselineText === void 0 ? void 0 : (() => {
257786
257855
  try {
257787
257856
  return normalizeSummary(JSON.parse(baselineText));
@@ -257835,7 +257904,7 @@ next: ${next2.join(", then ")}` : ""}`
257835
257904
  const runDir = join50(runsDir, summary.runId), path9 = join50(runDir, "report.html");
257836
257905
  const folder2 = relative19(ctx.io.cwd, runDir) || ".";
257837
257906
  const records6 = await readRunRecords(runDir, summary, { folder: folder2, secrets: await bundleSecrets({ cwd: ctx.io.cwd, env: ctx.io.env }) });
257838
- await writeFile23(path9, renderHtmlReport(reportData(summary, records6)));
257907
+ await writeFile24(path9, renderHtmlReport(reportData(summary, records6)));
257839
257908
  const opened = opts.open === true && openBrowser(path9);
257840
257909
  ctx.out.result({ runId: summary.runId, path: path9, ...opts.open && { opened } }, () => path9);
257841
257910
  return;
@@ -257856,7 +257925,7 @@ init_src();
257856
257925
  init_report2();
257857
257926
  init_run();
257858
257927
  init_run_inputs();
257859
- import { readdir as readdir9, readFile as readFile35 } from "node:fs/promises";
257928
+ import { readdir as readdir9, readFile as readFile36 } from "node:fs/promises";
257860
257929
  import { join as join51, resolve as resolve40 } from "node:path";
257861
257930
  var RUN_ID2 = /^[A-Za-z0-9_][\w.-]*$/;
257862
257931
  var TRIAL_DIR = /^trial-[a-z0-9][a-z0-9_-]*-[1-9]\d*$/;
@@ -257882,7 +257951,7 @@ async function loadReplayAttempt(cwd, ref23, out) {
257882
257951
  const trialDir = ref23.slice(slash + 1);
257883
257952
  if (runId2 === "latest") {
257884
257953
  try {
257885
- runId2 = (await readFile35(join51(runs, "latest"), "utf8")).trim();
257954
+ runId2 = (await readFile36(join51(runs, "latest"), "utf8")).trim();
257886
257955
  } catch (error65) {
257887
257956
  if (missing9(error65)) throw new AnchaError("USAGE", `no runs found in ${out ?? DEFAULT_RUNS_DIR}`, { hint: "run `ancha run` first", cause: error65 });
257888
257957
  throw error65;
@@ -257892,10 +257961,10 @@ async function loadReplayAttempt(cwd, ref23, out) {
257892
257961
  const runDir = join51(runs, runId2);
257893
257962
  let inputs2;
257894
257963
  try {
257895
- inputs2 = JSON.parse(await readFile35(join51(runDir, "inputs.json"), "utf8"));
257964
+ inputs2 = JSON.parse(await readFile36(join51(runDir, "inputs.json"), "utf8"));
257896
257965
  } catch (error65) {
257897
257966
  if (!missing9(error65)) throw error65;
257898
- const left = await readFile35(join51(runDir, "bundle.json"), "utf8").then((text31) => JSON.parse(text31).omitted?.find((item2) => item2.path === "inputs.json")).catch(() => void 0);
257967
+ const left = await readFile36(join51(runDir, "bundle.json"), "utf8").then((text31) => JSON.parse(text31).omitted?.find((item2) => item2.path === "inputs.json")).catch(() => void 0);
257899
257968
  const mb = (bytes4) => `${(bytes4 / (1024 * 1024)).toFixed(1)} MB`;
257900
257969
  if (left) throw new AnchaError("USAGE", `run ${runId2} came without its inputs.json (${mb(left.bytes)}, past the ${mb(left.cap)} its archive kept), so replay can't rebuild its worlds`, { hint: "a run started with ancha 0.4.14 or later keeps an inputs.json up to 12 MB: run the tests again, then replay the new run", cause: error65 });
257901
257970
  throw new AnchaError("USAGE", `unknown run ${JSON.stringify(runId2)}`, { hint: `see ${out ?? DEFAULT_RUNS_DIR}/`, cause: error65 });
@@ -257909,7 +257978,7 @@ async function loadReplayAttempt(cwd, ref23, out) {
257909
257978
  const dir2 = join51(runDir, trialDir);
257910
257979
  const read7 = async (name5, optional2 = false) => {
257911
257980
  try {
257912
- return await readFile35(join51(dir2, name5), "utf8");
257981
+ return await readFile36(join51(dir2, name5), "utf8");
257913
257982
  } catch (error65) {
257914
257983
  if (missing9(error65) && optional2) return "";
257915
257984
  if (missing9(error65)) throw new AnchaError("USAGE", `attempt ${runId2}/${trialDir} has no ${name5}`, { hint: "it may have been interrupted before its world was captured; replay a finished attempt", cause: error65 });
@@ -257946,7 +258015,7 @@ async function replayAttempt(attempt2, opts) {
257946
258015
  ...opts.onEvent !== void 0 && { onEvent: opts.onEvent }
257947
258016
  });
257948
258017
  const trial = run7.results.get(attempt2.caseId).trials[0];
257949
- const people4 = JSON.parse(await readFile35(join51(trial.dir, "people-replay.json"), "utf8").catch(() => "null")) ?? { replayed: 0, live: 0, divergence: null };
258018
+ const people4 = JSON.parse(await readFile36(join51(trial.dir, "people-replay.json"), "utf8").catch(() => "null")) ?? { replayed: 0, live: 0, divergence: null };
257950
258019
  const recorded2 = new Map(attempt2.checks.map((check4) => [check4.id, check4.passed]));
257951
258020
  return {
257952
258021
  replayOf: attempt2.id,
@@ -258093,7 +258162,7 @@ init_src();
258093
258162
  init_report2();
258094
258163
  init_run_store();
258095
258164
  init_run_state();
258096
- import { readFile as readFile36 } from "node:fs/promises";
258165
+ import { readFile as readFile37 } from "node:fs/promises";
258097
258166
  import { join as join53, resolve as resolve42 } from "node:path";
258098
258167
  import { setTimeout as sleep13 } from "node:timers/promises";
258099
258168
  function registerStatus(program2, ctx) {
@@ -258174,7 +258243,7 @@ hint: ${state3.upload.error.hint}` : ""}`);
258174
258243
  let printed = 0;
258175
258244
  for (; ; ) {
258176
258245
  const state3 = await readRunState(outDir, id15);
258177
- const lines2 = (await readFile36(log3, "utf8").catch(() => "")).split("\n");
258246
+ const lines2 = (await readFile37(log3, "utf8").catch(() => "")).split("\n");
258178
258247
  if (!terminal(state3)) lines2.pop();
258179
258248
  const complete = lines2.filter(Boolean);
258180
258249
  for (const line2 of complete.slice(printed)) ctx.out.event(JSON.parse(line2));
@@ -258200,8 +258269,8 @@ init_src();
258200
258269
  // packages/cli/src/commands/simulate.ts
258201
258270
  init_src();
258202
258271
  init_backend();
258203
- import { readFile as readFile37 } from "node:fs/promises";
258204
- import { dirname as dirname21, join as join55, resolve as resolve43 } from "node:path";
258272
+ import { readFile as readFile38 } from "node:fs/promises";
258273
+ import { dirname as dirname22, join as join55, resolve as resolve43 } from "node:path";
258205
258274
  init_config();
258206
258275
  init_report2();
258207
258276
  init_run();
@@ -258265,7 +258334,7 @@ function registerSimulate(sceneCommand, ctx) {
258265
258334
  const config12 = await ctx.loadConfig();
258266
258335
  let agent;
258267
258336
  if (mode !== "world") {
258268
- agent = withLocalEnvironment(resolveRunAgent(config12, ctx.io.cwd, { agent: await companionCommand(dirname21(resolve43(ctx.io.cwd, loaded.path)), mode), parallel: 1 }).agent, config12);
258337
+ agent = withLocalEnvironment(resolveRunAgent(config12, ctx.io.cwd, { agent: await companionCommand(dirname22(resolve43(ctx.io.cwd, loaded.path)), mode), parallel: 1 }).agent, config12);
258269
258338
  }
258270
258339
  const serverUrl3 = await configuredWorldServerUrl(ctx);
258271
258340
  const backend = await openBackend({ ...serverUrl3 !== void 0 && { serverUrl: serverUrl3 } });
@@ -258321,7 +258390,7 @@ function registerSimulate(sceneCommand, ctx) {
258321
258390
  timeline: trial.trace,
258322
258391
  checks: trial.checks,
258323
258392
  harnessIssues: trial.harnessIssues,
258324
- state: JSON.parse(await readFile37(join55(trial.dir, "state.json"), "utf8")),
258393
+ state: JSON.parse(await readFile38(join55(trial.dir, "state.json"), "utf8")),
258325
258394
  runId: run7.runId,
258326
258395
  dir: trial.dir
258327
258396
  };
@@ -258340,7 +258409,7 @@ init_scenes();
258340
258409
 
258341
258410
  // packages/cli/src/kit/init.ts
258342
258411
  import { constants as constants12 } from "node:fs";
258343
- import { lstat as lstat10, mkdir as mkdir25, open as open11, readFile as readFile42, rm as rm12, writeFile as writeFile26 } from "node:fs/promises";
258412
+ import { lstat as lstat10, mkdir as mkdir26, open as open11, readFile as readFile43, rm as rm13, writeFile as writeFile27 } from "node:fs/promises";
258344
258413
  import { join as join58 } from "node:path";
258345
258414
  import { Writable } from "node:stream";
258346
258415
  var import_yaml18 = __toESM(require_dist(), 1);
@@ -259629,10 +259698,10 @@ function netsuiteData(size2, options5 = {}) {
259629
259698
  // backend/src/kit/quickbooks-examples.ts
259630
259699
  var import_yaml14 = __toESM(require_dist(), 1);
259631
259700
  init_assets();
259632
- import { readFile as readFile38 } from "node:fs/promises";
259701
+ import { readFile as readFile39 } from "node:fs/promises";
259633
259702
  var QUICKBOOKS_EXAMPLES = { world: "pellmont-building-services", tests: ["pellmont-duplicates", "pellmont-approved-merge"] };
259634
259703
  async function quickbooksExamples() {
259635
- const read7 = (name5) => readFile38(new URL(`data/pellmont/${name5}.yaml`, assetRoot()), "utf8");
259704
+ const read7 = (name5) => readFile39(new URL(`data/pellmont/${name5}.yaml`, assetRoot()), "utf8");
259636
259705
  const world5 = `ancha/worlds/${QUICKBOOKS_EXAMPLES.world}.yaml`;
259637
259706
  const tests = await Promise.all(QUICKBOOKS_EXAMPLES.tests.map(async (id15) => {
259638
259707
  const content2 = await read7(id15);
@@ -259659,8 +259728,8 @@ var import_yaml15 = __toESM(require_dist(), 1);
259659
259728
  init_src();
259660
259729
  import { createHash as createHash75 } from "node:crypto";
259661
259730
  import { existsSync as existsSync2 } from "node:fs";
259662
- import { mkdir as mkdir23, readFile as readFile39, writeFile as writeFile24 } from "node:fs/promises";
259663
- import { dirname as dirname22, join as join56, relative as relative20, resolve as resolve45 } from "node:path";
259731
+ import { mkdir as mkdir24, readFile as readFile40, writeFile as writeFile25 } from "node:fs/promises";
259732
+ import { dirname as dirname23, join as join56, relative as relative20, resolve as resolve45 } from "node:path";
259664
259733
  async function model(ctx) {
259665
259734
  const env2 = ctx.io.env;
259666
259735
  if (env2.ANCHA_PEOPLE_BASE_URL && env2.ANCHA_PEOPLE_API_KEY) return { client: gen_exports.openRouterClient({ apiKey: env2.ANCHA_PEOPLE_API_KEY, baseUrl: env2.ANCHA_PEOPLE_BASE_URL, relay: true }), credit: "own" };
@@ -259690,14 +259759,14 @@ async function worldGenDataset(ctx, options5, description2) {
259690
259759
  if (!["s", "m", "l"].includes(size2)) throw new AnchaError("USAGE", `--size must be s, m or l, got ${JSON.stringify(options5.size)}`, { hint: "e.g. --size s" });
259691
259760
  const id15 = options5.id ?? `netsuite-pe-${size2}`;
259692
259761
  if (!/^[a-z0-9-]+$/.test(id15)) throw new AnchaError("USAGE", "--id must match [a-z0-9-]+", { hint: "e.g. --id portfolio-books" });
259693
- const outDir = resolve45(ctx.io.cwd, options5.out ?? "ancha/worlds"), worldPath = join56(outDir, `${id15}.yaml`), evalsPath = join56(dirname22(outDir), "evals", `${id15}.jsonl`);
259762
+ const outDir = resolve45(ctx.io.cwd, options5.out ?? "ancha/worlds"), worldPath = join56(outDir, `${id15}.yaml`), evalsPath = join56(dirname23(outDir), "evals", `${id15}.jsonl`);
259694
259763
  const taken2 = [worldPath, evalsPath].find((path9) => existsSync2(path9));
259695
259764
  if (taken2 && !options5.force) throw exists4(taken2, ctx);
259696
259765
  const { world: world5, evals, counts: counts2 } = generateNetsuitePe({ size: size2, id: id15, startTime: NETSUITE_PE_START_TIME });
259697
- await mkdir23(outDir, { recursive: true });
259698
- await mkdir23(dirname22(evalsPath), { recursive: true });
259699
- await writeFile24(worldPath, worldFileYaml(world5));
259700
- await writeFile24(evalsPath, netsuitePeJsonl(evals));
259766
+ await mkdir24(outDir, { recursive: true });
259767
+ await mkdir24(dirname23(evalsPath), { recursive: true });
259768
+ await writeFile25(worldPath, worldFileYaml(world5));
259769
+ await writeFile25(evalsPath, netsuitePeJsonl(evals));
259701
259770
  const rel = (path9) => relative20(ctx.io.cwd, path9) || ".";
259702
259771
  const result = {
259703
259772
  workspace: `local:${ctx.io.cwd}`,
@@ -259729,11 +259798,11 @@ async function worldGen(ctx, description2, options5) {
259729
259798
  const request2 = { description: description2, id: options5.id ?? null, tools: tools2 ?? null, size: size2, variants, from: options5.from ?? null };
259730
259799
  const keyFile = options5.idempotencyKey === void 0 ? void 0 : join56(ctx.io.cwd, ".ancha", "world-gen", `${createHash75("sha256").update(options5.idempotencyKey).digest("hex").slice(0, 32)}.json`);
259731
259800
  if (keyFile && existsSync2(keyFile)) {
259732
- const saved = JSON.parse(await readFile39(keyFile, "utf8"));
259801
+ const saved = JSON.parse(await readFile40(keyFile, "utf8"));
259733
259802
  if (JSON.stringify(saved.request) !== JSON.stringify(request2)) throw new AnchaError("USAGE", "this --idempotency-key was used with different arguments", { hint: "use a new key for a new request" });
259734
259803
  if (saved.result.files.every((file3) => existsSync2(resolve45(ctx.io.cwd, file3)))) return report5(ctx, { ...saved.result, reused: true });
259735
259804
  }
259736
- const from = options5.from === void 0 ? void 0 : parseWorldFile((0, import_yaml15.parse)(await readFile39(resolve45(ctx.io.cwd, options5.from), "utf8")));
259805
+ const from = options5.from === void 0 ? void 0 : parseWorldFile((0, import_yaml15.parse)(await readFile40(resolve45(ctx.io.cwd, options5.from), "utf8")));
259737
259806
  if (options5.id && !options5.force && existsSync2(join56(outDir, `${options5.id}.yaml`))) throw exists4(join56(outDir, `${options5.id}.yaml`), ctx);
259738
259807
  const { client: client2, credit } = await model(ctx);
259739
259808
  ctx.out.info(`generating a world from the description (size ${size2}${variants ? `, ${variants} variant${variants === 1 ? "" : "s"}` : ""})`);
@@ -259750,8 +259819,8 @@ async function worldGen(ctx, description2, options5) {
259750
259819
  const paths3 = Object.keys(generated.files).map((name5) => join56(outDir, name5));
259751
259820
  const taken2 = paths3.find((path9) => existsSync2(path9));
259752
259821
  if (taken2 && !options5.force) throw exists4(taken2, ctx);
259753
- await mkdir23(outDir, { recursive: true });
259754
- for (const [name5, text31] of Object.entries(generated.files)) await writeFile24(join56(outDir, name5), text31);
259822
+ await mkdir24(outDir, { recursive: true });
259823
+ for (const [name5, text31] of Object.entries(generated.files)) await writeFile25(join56(outDir, name5), text31);
259755
259824
  const rel = (path9) => relative20(ctx.io.cwd, path9) || ".";
259756
259825
  const worldPath = rel(join56(outDir, `${generated.world.id}.yaml`));
259757
259826
  const result = {
@@ -259771,8 +259840,8 @@ async function worldGen(ctx, description2, options5) {
259771
259840
  next: [`ancha test new "<the test in one sentence>" --world ${generated.world.id}`]
259772
259841
  };
259773
259842
  if (keyFile) {
259774
- await mkdir23(dirname22(keyFile), { recursive: true });
259775
- await writeFile24(keyFile, `${JSON.stringify({ request: request2, result }, null, 2)}
259843
+ await mkdir24(dirname23(keyFile), { recursive: true });
259844
+ await writeFile25(keyFile, `${JSON.stringify({ request: request2, result }, null, 2)}
259776
259845
  `);
259777
259846
  }
259778
259847
  return report5(ctx, result);
@@ -259793,7 +259862,7 @@ function report5(ctx, result) {
259793
259862
  var import_yaml17 = __toESM(require_dist(), 1);
259794
259863
  import { createHash as createHash77 } from "node:crypto";
259795
259864
  import { existsSync as existsSync3 } from "node:fs";
259796
- import { mkdir as mkdir24, readFile as readFile40, readdir as readdir10, writeFile as writeFile25 } from "node:fs/promises";
259865
+ import { mkdir as mkdir25, readFile as readFile41, readdir as readdir10, writeFile as writeFile26 } from "node:fs/promises";
259797
259866
  import { join as join57, relative as relative21, resolve as resolve46 } from "node:path";
259798
259867
  init_src();
259799
259868
 
@@ -260203,7 +260272,7 @@ async function chooseWorld(ctx, id15, command = 'ancha test new "<sentence>"') {
260203
260272
  const path9 = join57(dir2, `${chosen}.yaml`);
260204
260273
  if (!existsSync3(path9)) throw new AnchaError("USAGE", `no world ${chosen} in ancha/worlds`, { hint: ids3.length ? `worlds: ${ids3.join(", ")}` : noWorldHint });
260205
260274
  try {
260206
- return parseWorldFile((0, import_yaml17.parse)(await readFile40(path9, "utf8")));
260275
+ return parseWorldFile((0, import_yaml17.parse)(await readFile41(path9, "utf8")));
260207
260276
  } catch (error65) {
260208
260277
  throw new AnchaError("SCENE_INVALID", `ancha/worlds/${chosen}.yaml: ${error65 instanceof Error ? error65.message : String(error65)}`, { hint: "run `ancha schema world` for the world file format" });
260209
260278
  }
@@ -260238,7 +260307,7 @@ async function testNew(ctx, intent, options5) {
260238
260307
  const request2 = { intent, world: world5.id, id: options5.id ?? null, out: relative21(ctx.io.cwd, outDir) };
260239
260308
  const keyFile = options5.idempotencyKey === void 0 ? void 0 : join57(ctx.io.cwd, ".ancha", "test-new", `${createHash77("sha256").update(options5.idempotencyKey).digest("hex").slice(0, 32)}.json`);
260240
260309
  if (keyFile && existsSync3(keyFile)) {
260241
- const saved = JSON.parse(await readFile40(keyFile, "utf8"));
260310
+ const saved = JSON.parse(await readFile41(keyFile, "utf8"));
260242
260311
  if (JSON.stringify(saved.request) !== JSON.stringify(request2)) throw new AnchaError("USAGE", "this --idempotency-key was used with different arguments", { hint: "use a new key for a new request" });
260243
260312
  if ([saved.result.file, saved.result.record].every((file4) => existsSync3(resolve46(ctx.io.cwd, file4)))) return report6(ctx, { ...saved.result, reused: true });
260244
260313
  }
@@ -260248,13 +260317,13 @@ async function testNew(ctx, intent, options5) {
260248
260317
  const draft2 = await draftTest({ intent, world: world5, model: client2, ...options5.id && { id: options5.id }, onProgress: (line2) => ctx.out.info(` ${line2}`) });
260249
260318
  const path9 = join57(outDir, `${draft2.test.id}.yaml`), recordPath = join57(outDir, `${draft2.test.id}.gen.json`);
260250
260319
  if (existsSync3(path9) && !options5.force) throw exists5(ctx, path9);
260251
- const before = existsSync3(path9) ? await readFile40(path9, "utf8") : "";
260320
+ const before = existsSync3(path9) ? await readFile41(path9, "utf8") : "";
260252
260321
  const at6 = (/* @__PURE__ */ new Date()).toISOString();
260253
260322
  const yaml = testYaml2({ ...draft2.test, generated: { by: "ancha test new", at: at6, from: intent, record: `${draft2.test.id}.gen.json` } }, intent);
260254
260323
  const cost = Math.round(draft2.calls.reduce((sum6, call4) => sum6 + call4.costUsd, 0) * 1e6) / 1e6;
260255
- await mkdir24(outDir, { recursive: true });
260256
- await writeFile25(path9, yaml);
260257
- await writeFile25(recordPath, `${JSON.stringify({ generated: { by: "ancha test new", at: at6 }, request: { intent, world: world5.id }, prompt: draft2.prompt, calls: draft2.calls, cost_usd: cost }, null, 2)}
260324
+ await mkdir25(outDir, { recursive: true });
260325
+ await writeFile26(path9, yaml);
260326
+ await writeFile26(recordPath, `${JSON.stringify({ generated: { by: "ancha test new", at: at6 }, request: { intent, world: world5.id }, prompt: draft2.prompt, calls: draft2.calls, cost_usd: cost }, null, 2)}
260258
260327
  `);
260259
260328
  const file3 = relative21(ctx.io.cwd, path9);
260260
260329
  const people4 = [...new Set((draft2.test.checks ?? []).flatMap((check4) => JSON.stringify(check4).match(/"(?:to|from)":"([a-z][a-z0-9_-]*)"|\[\s*"([a-z][a-z0-9_-]*)"/g) ?? []).map((match3) => match3.replace(/^.*"([a-z][a-z0-9_-]*)"$/, "$1")))].filter((ref23) => (world5.people ?? []).some((person5) => person5.ref === ref23));
@@ -260273,8 +260342,8 @@ async function testNew(ctx, intent, options5) {
260273
260342
  ...credit === "workspace" && { modelCredit: "workspace" }
260274
260343
  };
260275
260344
  if (keyFile) {
260276
- await mkdir24(join57(ctx.io.cwd, ".ancha", "test-new"), { recursive: true });
260277
- await writeFile25(keyFile, `${JSON.stringify({ request: request2, result })}
260345
+ await mkdir25(join57(ctx.io.cwd, ".ancha", "test-new"), { recursive: true });
260346
+ await writeFile26(keyFile, `${JSON.stringify({ request: request2, result })}
260278
260347
  `);
260279
260348
  }
260280
260349
  return report6(ctx, result);
@@ -260321,11 +260390,11 @@ init_scenes();
260321
260390
  // packages/cli/src/kit/docs.ts
260322
260391
  init_src();
260323
260392
  init_assets();
260324
- import { readFile as readFile41 } from "node:fs/promises";
260393
+ import { readFile as readFile42 } from "node:fs/promises";
260325
260394
  var DOC_TOPICS = ["setup", "apps", "run", "traces", "explain", "compare", "tests", "scenes", "integrations", "cloud", "playgrounds", "cli-quickstart", "tools", "datasets", "company"];
260326
260395
  async function loadDoc(topic = "setup") {
260327
260396
  if (!DOC_TOPICS.includes(topic)) throw new AnchaError("USAGE", `unknown docs topic: ${topic}`, { hint: `available topics: ${DOC_TOPICS.join(", ")}` });
260328
- return { topics: [...DOC_TOPICS], topic, markdown: await readFile41(new URL(`docs/${topic === "tests" ? "scenes" : topic}.md`, assetRoot()), "utf8") };
260397
+ return { topics: [...DOC_TOPICS], topic, markdown: await readFile42(new URL(`docs/${topic === "tests" ? "scenes" : topic}.md`, assetRoot()), "utf8") };
260329
260398
  }
260330
260399
  function registerDocs(program2, ctx) {
260331
260400
  program2.command("docs").description("read the bundled documentation: setup, the run loop, checks, SDK settings and the hosted workspace").argument("[topic]", `available: ${DOC_TOPICS.join(", ")}`).action(async (topic) => {
@@ -260346,7 +260415,7 @@ function step2(ctx) {
260346
260415
  }
260347
260416
  var BEGIN = "<!-- ancha:begin -->";
260348
260417
  var END = "<!-- ancha:end -->";
260349
- var managedSection = () => readFile42(new URL("agents-section.md", assetRoot()), "utf8");
260418
+ var managedSection = () => readFile43(new URL("agents-section.md", assetRoot()), "utf8");
260350
260419
  async function installAgents(cwd, tools2) {
260351
260420
  const target6 = join58(cwd, "AGENTS.md");
260352
260421
  const base6 = await managedSection();
@@ -260359,7 +260428,7 @@ Read \`ancha docs tools\` for function checks and registration.
260359
260428
  const managed = base6.replace(END, wiring + END);
260360
260429
  let original2;
260361
260430
  try {
260362
- original2 = await readFile42(target6, "utf8");
260431
+ original2 = await readFile43(target6, "utf8");
260363
260432
  } catch (error65) {
260364
260433
  if (error65.code !== "ENOENT") throw error65;
260365
260434
  const result = await applyScaffold(cwd, [{ relativePath: "AGENTS.md", content: managed }]);
@@ -260388,7 +260457,7 @@ async function ignoreAnchaDirectory(cwd) {
260388
260457
  const target6 = join58(cwd, ".gitignore");
260389
260458
  let original2;
260390
260459
  try {
260391
- original2 = await readFile42(target6, "utf8");
260460
+ original2 = await readFile43(target6, "utf8");
260392
260461
  } catch (error65) {
260393
260462
  if (error65.code !== "ENOENT") throw error65;
260394
260463
  const result = await applyScaffold(cwd, [{ relativePath: ".gitignore", content: ".ancha/\n" }]);
@@ -260472,7 +260541,7 @@ ${twins.map((twin) => (routed.includes(twin) ? ROUTED_TASKS[twin] : void 0) ?? t
260472
260541
  }
260473
260542
  var STARTER_FILES = ["scene.yaml", "oracle.mjs", "null.mjs"];
260474
260543
  async function ownStarter(cwd) {
260475
- const read7 = (name5) => readFile42(join58(cwd, "scenes/starter", name5), "utf8").catch(() => void 0);
260544
+ const read7 = (name5) => readFile43(join58(cwd, "scenes/starter", name5), "utf8").catch(() => void 0);
260476
260545
  const scene2 = await read7("scene.yaml");
260477
260546
  if (scene2 === void 0) return void 0;
260478
260547
  let twins;
@@ -260503,7 +260572,7 @@ async function wireComposio(cwd, candidates2) {
260503
260572
  const added = [], pending = [];
260504
260573
  const result = { added, pending, passEnvAdded: false };
260505
260574
  if (!candidates2.length) return result;
260506
- const text31 = await readFile42(join58(cwd, "ancha.yaml"), "utf8");
260575
+ const text31 = await readFile43(join58(cwd, "ancha.yaml"), "utf8");
260507
260576
  let config12;
260508
260577
  try {
260509
260578
  config12 = parseConfigText(text31);
@@ -260553,7 +260622,7 @@ async function rewrite(cwd, relativePath, content2) {
260553
260622
  }
260554
260623
  }
260555
260624
  async function listTests(cwd, tests) {
260556
- const text31 = await readFile42(join58(cwd, "ancha.yaml"), "utf8");
260625
+ const text31 = await readFile43(join58(cwd, "ancha.yaml"), "utf8");
260557
260626
  let scenes;
260558
260627
  try {
260559
260628
  scenes = parseConfigText(text31).scenes;
@@ -260580,7 +260649,7 @@ async function listTests(cwd, tests) {
260580
260649
  return true;
260581
260650
  }
260582
260651
  async function addExampleSeeds(file3, twins) {
260583
- const doc = (0, import_yaml18.parseDocument)(await readFile42(file3, "utf8"));
260652
+ const doc = (0, import_yaml18.parseDocument)(await readFile43(file3, "utf8"));
260584
260653
  const added = [], skipped = [];
260585
260654
  for (const twin of twins) {
260586
260655
  if (doc.hasIn(["seed", twin])) continue;
@@ -260596,7 +260665,7 @@ async function addExampleSeeds(file3, twins) {
260596
260665
  doc.contents = before.contents;
260597
260666
  }
260598
260667
  }
260599
- if (added.length > 0) await writeFile26(file3, doc.toString({ lineWidth: 0 }));
260668
+ if (added.length > 0) await writeFile27(file3, doc.toString({ lineWidth: 0 }));
260600
260669
  return { added, skipped };
260601
260670
  }
260602
260671
  var where2 = (mark) => `${mark.source}:${mark.line}`;
@@ -260655,7 +260724,7 @@ async function wireExistingConfig(cwd, fillMissing) {
260655
260724
  const target6 = join58(cwd, "ancha.yaml");
260656
260725
  let text31;
260657
260726
  try {
260658
- text31 = await readFile42(target6, "utf8");
260727
+ text31 = await readFile43(target6, "utf8");
260659
260728
  } catch {
260660
260729
  return void 0;
260661
260730
  }
@@ -260698,7 +260767,7 @@ function registerKit(program2, ctx) {
260698
260767
  throw new AnchaError("CONFIG_INVALID", "init --intent needs a model key", { hint: "set OPENROUTER_API_KEY, or log in to your workspace with ancha login; or run ancha init without --intent" });
260699
260768
  }
260700
260769
  const detection = await detectProject(ctx.io.cwd, opts.agent);
260701
- const configText = await readFile42(join58(ctx.io.cwd, "ancha.yaml"), "utf8").catch(() => void 0);
260770
+ const configText = await readFile43(join58(ctx.io.cwd, "ancha.yaml"), "utf8").catch(() => void 0);
260702
260771
  const configured = configText !== void 0;
260703
260772
  let task2 = configured || detection.slackApp !== void 0 || detection.agent === null ? void 0 : await taskSetup(ctx.io.cwd, detection.agent, { command: detection.agent });
260704
260773
  const existingConfig = (() => {
@@ -260744,15 +260813,15 @@ min_pass_rate: 1
260744
260813
  ` },
260745
260814
  ...templates.map((file3) => ({ ...file3, relativePath: `scenes/${opts.template}/${file3.relativePath}` })),
260746
260815
  ...starterWorld ? [starterWorld] : [],
260747
- { relativePath: ".claude/skills/ancha/SKILL.md", content: await readFile42(new URL("SKILL.md", assetRoot()), "utf8") },
260816
+ { relativePath: ".claude/skills/ancha/SKILL.md", content: await readFile43(new URL("SKILL.md", assetRoot()), "utf8") },
260748
260817
  ...pe?.files ?? [],
260749
260818
  ...examples2?.files ?? []
260750
260819
  ];
260751
260820
  await preflightFiles(ctx.io.cwd, [...files2, { relativePath: "AGENTS.md", content: "" }, { relativePath: ".gitignore", content: "" }]);
260752
260821
  const updated = [];
260753
- const rewritten = own2 === void 0 ? [] : await Promise.all(files2.filter((file3) => file3.relativePath.startsWith("scenes/starter/")).map(async (file3) => await readFile42(join58(ctx.io.cwd, file3.relativePath), "utf8").catch(() => void 0) === file3.content ? void 0 : file3)).then((list19) => list19.filter((file3) => file3 !== void 0));
260822
+ const rewritten = own2 === void 0 ? [] : await Promise.all(files2.filter((file3) => file3.relativePath.startsWith("scenes/starter/")).map(async (file3) => await readFile43(join58(ctx.io.cwd, file3.relativePath), "utf8").catch(() => void 0) === file3.content ? void 0 : file3)).then((list19) => list19.filter((file3) => file3 !== void 0));
260754
260823
  if (starterWorld && own2 !== void 0) {
260755
- const before = await readFile42(join58(ctx.io.cwd, starterWorld.relativePath), "utf8").catch(() => void 0);
260824
+ const before = await readFile43(join58(ctx.io.cwd, starterWorld.relativePath), "utf8").catch(() => void 0);
260756
260825
  const previous = await loadSceneFile(join58(ctx.io.cwd, "scenes/starter/scene.yaml"));
260757
260826
  if (before === worldFileYaml(sceneWorld(previous)) && before !== starterWorld.content) rewritten.push(starterWorld);
260758
260827
  }
@@ -260798,7 +260867,7 @@ min_pass_rate: 1
260798
260867
  }
260799
260868
  const routeWiring = await wireComposio(ctx.io.cwd, routeTools);
260800
260869
  if (routeWiring.added.length && !result.created.includes("ancha.yaml") && !updated.includes("ancha.yaml")) updated.push("ancha.yaml");
260801
- const savedConfig = await readFile42(join58(ctx.io.cwd, "ancha.yaml"), "utf8").then((text31) => {
260870
+ const savedConfig = await readFile43(join58(ctx.io.cwd, "ancha.yaml"), "utf8").then((text31) => {
260802
260871
  try {
260803
260872
  return parseConfigText(text31);
260804
260873
  } catch {
@@ -260873,9 +260942,9 @@ function registerSceneNew(scene2, ctx) {
260873
260942
  } catch (error65) {
260874
260943
  if (error65.code !== "ENOENT") throw error65;
260875
260944
  }
260876
- await mkdir25(join58(ctx.io.cwd, "scenes"), { recursive: true });
260945
+ await mkdir26(join58(ctx.io.cwd, "scenes"), { recursive: true });
260877
260946
  try {
260878
- await mkdir25(target6);
260947
+ await mkdir26(target6);
260879
260948
  } catch (cause) {
260880
260949
  throw new AnchaError("USAGE", `cannot create scene destination: ${prefix2}`, { hint: "choose another id and remove unsafe symlinks", cause });
260881
260950
  }
@@ -260883,7 +260952,7 @@ function registerSceneNew(scene2, ctx) {
260883
260952
  const result = await applyScaffold(ctx.io.cwd, planned);
260884
260953
  ctx.out.result({ id: id15, twins, ...result }, () => `Created ${prefix2}/scene.yaml and oracle/null companions. Validate: ancha scene validate ${prefix2}/scene.yaml`);
260885
260954
  } catch (error65) {
260886
- await rm12(target6, { recursive: true, force: true });
260955
+ await rm13(target6, { recursive: true, force: true });
260887
260956
  throw error65;
260888
260957
  }
260889
260958
  });
@@ -261082,7 +261151,7 @@ async function suggestAgentProject(path9) {
261082
261151
  import { realpathSync as realpathSync3 } from "node:fs";
261083
261152
  init_src();
261084
261153
  import { randomUUID as randomUUID20 } from "node:crypto";
261085
- import { mkdir as mkdir28, rm as rm16, writeFile as writeFile29 } from "node:fs/promises";
261154
+ import { mkdir as mkdir29, rm as rm17, writeFile as writeFile30 } from "node:fs/promises";
261086
261155
  import { join as join62 } from "node:path";
261087
261156
  init_assets();
261088
261157
 
@@ -261090,7 +261159,7 @@ init_assets();
261090
261159
  init_src();
261091
261160
  import { execFile as execFile9 } from "node:child_process";
261092
261161
  import { createHash as createHash79, randomUUID as randomUUID18 } from "node:crypto";
261093
- import { mkdir as mkdir27, mkdtemp as mkdtemp10, readFile as readFile44, readdir as readdir12, rename as rename8, rm as rm14, writeFile as writeFile28 } from "node:fs/promises";
261162
+ import { mkdir as mkdir28, mkdtemp as mkdtemp10, readFile as readFile45, readdir as readdir12, rename as rename8, rm as rm15, writeFile as writeFile29 } from "node:fs/promises";
261094
261163
  import { tmpdir as tmpdir9 } from "node:os";
261095
261164
  import { join as join60 } from "node:path";
261096
261165
  init_detect();
@@ -261101,7 +261170,7 @@ init_policy();
261101
261170
 
261102
261171
  // backend/src/execution/runtime-cache.ts
261103
261172
  import { createHash as createHash78, randomUUID as randomUUID17 } from "node:crypto";
261104
- import { mkdir as mkdir26, readFile as readFile43, readdir as readdir11, realpath as realpath13, rename as rename7, rm as rm13, writeFile as writeFile27 } from "node:fs/promises";
261173
+ import { mkdir as mkdir27, readFile as readFile44, readdir as readdir11, realpath as realpath13, rename as rename7, rm as rm14, writeFile as writeFile28 } from "node:fs/promises";
261105
261174
  import { join as join59 } from "node:path";
261106
261175
  init_assets();
261107
261176
  async function runtimeCacheKey(source, project14, command, context3) {
@@ -261110,7 +261179,7 @@ async function runtimeCacheKey(source, project14, command, context3) {
261110
261179
  for (const entry3 of (await readdir11(path9, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
261111
261180
  const relative31 = prefix2 + entry3.name;
261112
261181
  if (entry3.isDirectory()) await visit4(join59(path9, entry3.name), relative31 + "/");
261113
- else hash10.update(relative31).update("\0").update(await readFile43(join59(path9, entry3.name))).update("\0");
261182
+ else hash10.update(relative31).update("\0").update(await readFile44(join59(path9, entry3.name))).update("\0");
261114
261183
  }
261115
261184
  }
261116
261185
  await visit4(source);
@@ -261132,17 +261201,17 @@ async function rememberRuntime(workspace4, key5, image2) {
261132
261201
  if (!/^sha256:[a-f0-9]{64}$/.test(image2)) throw new Error("Runtime must be pinned before caching");
261133
261202
  const path9 = cachePath(key5), temporary = `${path9}.${randomUUID17()}.tmp`;
261134
261203
  await preflightFiles(workspace4, [{ relativePath: path9, content: "" }, { relativePath: temporary, content: "" }]);
261135
- await mkdir26(join59(workspace4, ".ancha/agent-runtime-cache"), { recursive: true, mode: 448 });
261204
+ await mkdir27(join59(workspace4, ".ancha/agent-runtime-cache"), { recursive: true, mode: 448 });
261136
261205
  try {
261137
- await writeFile27(join59(workspace4, temporary), JSON.stringify({ version: 1, image: image2 }), { flag: "wx", mode: 384 });
261206
+ await writeFile28(join59(workspace4, temporary), JSON.stringify({ version: 1, image: image2 }), { flag: "wx", mode: 384 });
261138
261207
  await rename7(join59(workspace4, temporary), join59(workspace4, path9));
261139
261208
  } finally {
261140
- await rm13(join59(workspace4, temporary), { force: true });
261209
+ await rm14(join59(workspace4, temporary), { force: true });
261141
261210
  }
261142
261211
  }
261143
261212
 
261144
261213
  // backend/src/execution/prepare-agent.ts
261145
- var read6 = (directory, file3) => readFile44(join60(directory, file3), "utf8").catch((error65) => {
261214
+ var read6 = (directory, file3) => readFile45(join60(directory, file3), "utf8").catch((error65) => {
261146
261215
  if (error65.code === "ENOENT") return void 0;
261147
261216
  throw error65;
261148
261217
  });
@@ -261278,13 +261347,13 @@ async function prepareAgent(workspace4, agentId2, options5 = {}) {
261278
261347
  for (const entry3 of (await readdir12(path9, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
261279
261348
  const relative31 = prefix2 + entry3.name;
261280
261349
  if (entry3.isDirectory()) await hashTree(join60(path9, entry3.name), relative31 + "/");
261281
- else digest5.update(relative31).update("\0").update(await readFile44(join60(path9, entry3.name))).update("\0");
261350
+ else digest5.update(relative31).update("\0").update(await readFile45(join60(path9, entry3.name))).update("\0");
261282
261351
  }
261283
261352
  }
261284
261353
  await hashTree(source);
261285
261354
  const fingerprint = digest5.digest("hex"), cacheRelative = `.ancha/agent-images/${fingerprint}.json`;
261286
261355
  await preflightFiles(workspace4, [{ relativePath: cacheRelative, content: "" }]);
261287
- const cached3 = await readFile44(join60(workspace4, cacheRelative), "utf8").then((text31) => JSON.parse(text31)).catch(() => void 0);
261356
+ const cached3 = await readFile45(join60(workspace4, cacheRelative), "utf8").then((text31) => JSON.parse(text31)).catch(() => void 0);
261288
261357
  let cachedImage;
261289
261358
  if (cached3?.image && /^sha256:[a-f0-9]{64}$/.test(cached3.image)) {
261290
261359
  try {
@@ -261301,7 +261370,7 @@ async function prepareAgent(workspace4, agentId2, options5 = {}) {
261301
261370
  return { prepared: true, agent, runtime: plan4.kind, image: cachedImage.Id, reused: true, runtimeKey };
261302
261371
  }
261303
261372
  const dockerfile = join60(temporary, "Dockerfile");
261304
- await writeFile28(dockerfile, plan4.dockerfile, { mode: 384 });
261373
+ await writeFile29(dockerfile, plan4.dockerfile, { mode: 384 });
261305
261374
  options5.progress?.("Installing dependencies in an isolated runtime");
261306
261375
  tags4.add(plan4.custom ? baseTag : tag3);
261307
261376
  await runDocker(["build", "--tag", plan4.custom ? baseTag : tag3, "--file", dockerfile, source], runtime2.context, options5.signal);
@@ -261314,7 +261383,7 @@ async function prepareAgent(workspace4, agentId2, options5 = {}) {
261314
261383
  USER root
261315
261384
  RUN if [ -d ${quote3(nodeModules)} ] && [ ${quote3(nodeModules)} != '/opt/ancha/node_modules' ]; then mkdir -p /opt/ancha && cp -a ${quote3(nodeModules)} /opt/ancha/node_modules && chmod -R a+rX /opt/ancha/node_modules; fi
261316
261385
  `;
261317
- await writeFile28(dockerfile, wrapper, { mode: 384 });
261386
+ await writeFile29(dockerfile, wrapper, { mode: 384 });
261318
261387
  tags4.add(tag3);
261319
261388
  await runDocker(["build", "--tag", tag3, "--file", dockerfile, source], runtime2.context, options5.signal);
261320
261389
  image2 = inspect(await runDocker(["image", "inspect", tag3], runtime2.context, options5.signal));
@@ -261323,14 +261392,14 @@ RUN if [ -d ${quote3(nodeModules)} ] && [ ${quote3(nodeModules)} != '/opt/ancha/
261323
261392
  const previous = resolved.execution?.mode === "container" ? resolved.execution : void 0;
261324
261393
  const policy = parseExecutionPolicy({ memoryMb: 1024, ...previous ?? {}, mode: "container", preparation: "project", image: image2.Id });
261325
261394
  if (JSON.stringify(await registry2.saved(agentId2)) !== JSON.stringify(saved)) invalid39("Agent settings changed while connecting. Connect again with the new settings.");
261326
- await mkdir27(join60(workspace4, ".ancha/agent-images"), { recursive: true });
261395
+ await mkdir28(join60(workspace4, ".ancha/agent-images"), { recursive: true });
261327
261396
  const cacheTemp = cacheRelative + `.${randomUUID18()}.tmp`;
261328
261397
  await preflightFiles(workspace4, [{ relativePath: cacheRelative, content: "" }, { relativePath: cacheTemp, content: "" }]);
261329
261398
  try {
261330
- await writeFile28(join60(workspace4, cacheTemp), JSON.stringify({ image: image2.Id }), { flag: "wx", mode: 384 });
261399
+ await writeFile29(join60(workspace4, cacheTemp), JSON.stringify({ image: image2.Id }), { flag: "wx", mode: 384 });
261331
261400
  await rename8(join60(workspace4, cacheTemp), join60(workspace4, cacheRelative));
261332
261401
  } finally {
261333
- await rm14(join60(workspace4, cacheTemp), { force: true });
261402
+ await rm15(join60(workspace4, cacheTemp), { force: true });
261334
261403
  }
261335
261404
  checkSignal(options5.signal);
261336
261405
  if (JSON.stringify(await registry2.saved(agentId2)) !== JSON.stringify(saved)) invalid39("Agent settings changed while connecting. Connect again with the new settings.");
@@ -261340,7 +261409,7 @@ RUN if [ -d ${quote3(nodeModules)} ] && [ ${quote3(nodeModules)} != '/opt/ancha/
261340
261409
  } finally {
261341
261410
  for (const image2 of tags4) if (!success2 || image2 === baseTag) await runDocker(["image", "rm", image2], runtime2.context).catch(() => {
261342
261411
  });
261343
- await rm14(temporary, { recursive: true, force: true });
261412
+ await rm15(temporary, { recursive: true, force: true });
261344
261413
  }
261345
261414
  }
261346
261415
 
@@ -261352,7 +261421,7 @@ init_source();
261352
261421
  init_workspace();
261353
261422
  import { execFile as execFile10, spawn as spawn6 } from "node:child_process";
261354
261423
  import { randomUUID as randomUUID19 } from "node:crypto";
261355
- import { mkdtemp as mkdtemp11, rm as rm15 } from "node:fs/promises";
261424
+ import { mkdtemp as mkdtemp11, rm as rm16 } from "node:fs/promises";
261356
261425
  import { tmpdir as tmpdir10 } from "node:os";
261357
261426
  import { join as join61 } from "node:path";
261358
261427
  import { promisify as promisify9 } from "node:util";
@@ -261454,7 +261523,7 @@ async function probeAgentConnection(agent, signal, progress2, inheritedEnv = pro
261454
261523
  if (remaining) failures.push(name5);
261455
261524
  });
261456
261525
  for (const child3 of children3) child3.kill("SIGKILL");
261457
- await rm15(temporary, { recursive: true, force: true });
261526
+ await rm16(temporary, { recursive: true, force: true });
261458
261527
  if (failures.length) throw new AnchaError("INTERNAL", "The connection check finished but its temporary playground could not be fully removed. Check the local container runtime before retrying.");
261459
261528
  }
261460
261529
  }
@@ -261660,7 +261729,7 @@ var AgentConnectionService = class {
261660
261729
  const finished = (/* @__PURE__ */ new Date()).toISOString();
261661
261730
  Object.assign(value6, { state: "cancelled", phase: "finished", message: "Connect cancelled while queued.", finishedAt: finished, updatedAt: finished });
261662
261731
  delete value6.blockedBy;
261663
- await rm16(join62(this.workspace, request2), { force: true });
261732
+ await rm17(join62(this.workspace, request2), { force: true });
261664
261733
  await this.store.queueConnection(value6.agentId, value6);
261665
261734
  }
261666
261735
  async cancel(agentId2, operationId) {
@@ -261673,8 +261742,8 @@ var AgentConnectionService = class {
261673
261742
  } else if (value6.state === "connecting" || value6.state === "queued") {
261674
261743
  const request2 = `${this.path(agentId2)}.cancel`;
261675
261744
  await preflightFiles(this.workspace, [{ relativePath: request2, content: "" }]);
261676
- await mkdir28(join62(this.workspace, ".ancha/agent-connections"), { recursive: true, mode: 448 });
261677
- await writeFile29(join62(this.workspace, request2), operationId, { mode: 384 });
261745
+ await mkdir29(join62(this.workspace, ".ancha/agent-connections"), { recursive: true, mode: 448 });
261746
+ await writeFile30(join62(this.workspace, request2), operationId, { mode: 384 });
261678
261747
  }
261679
261748
  return this.status(agentId2);
261680
261749
  }
@@ -261739,7 +261808,7 @@ var AgentConnectionService = class {
261739
261808
  value6.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
261740
261809
  value6.updatedAt = value6.finishedAt;
261741
261810
  clearInterval(cancellation);
261742
- await rm16(join62(this.workspace, request2), { force: true });
261811
+ await rm17(join62(this.workspace, request2), { force: true });
261743
261812
  await writes3;
261744
261813
  await this.write(value6);
261745
261814
  }
@@ -261753,7 +261822,7 @@ init_backend();
261753
261822
  init_assets();
261754
261823
  import { createServer as createServer6 } from "node:http";
261755
261824
  import { randomBytes as randomBytes10 } from "node:crypto";
261756
- import { readFile as readFile45, realpath as realpath14, stat as stat15 } from "node:fs/promises";
261825
+ import { readFile as readFile46, realpath as realpath14, stat as stat15 } from "node:fs/promises";
261757
261826
  import { isAbsolute as isAbsolute12 } from "node:path";
261758
261827
  import { fileURLToPath as fileURLToPath7 } from "node:url";
261759
261828
 
@@ -261765,7 +261834,7 @@ init_run_state();
261765
261834
  init_report2();
261766
261835
  init_baselines();
261767
261836
  init_assets();
261768
- import { readdir as readdir13, stat as stat14, writeFile as writeFile30, rename as rename9, rm as rm17 } from "node:fs/promises";
261837
+ import { readdir as readdir13, stat as stat14, writeFile as writeFile31, rename as rename9, rm as rm18 } from "node:fs/promises";
261769
261838
  import { createHash as createHash81, randomBytes as randomBytes9 } from "node:crypto";
261770
261839
  import { join as join63 } from "node:path";
261771
261840
  import { fileURLToPath as fileURLToPath5 } from "node:url";
@@ -262260,10 +262329,10 @@ var ConsoleJobs = class {
262260
262329
  const target6 = `.ancha/console-runs/${runId2}.events.json`, temporary = `${target6}.${randomBytes9(8).toString("hex")}.tmp`;
262261
262330
  await preflightFiles(this.workspace, [{ relativePath: target6, content: "" }, { relativePath: temporary, content: "" }]);
262262
262331
  try {
262263
- await writeFile30(join63(this.workspace, temporary), JSON.stringify(publicData(events3, this.secrets)), { flag: "wx", mode: 384 });
262332
+ await writeFile31(join63(this.workspace, temporary), JSON.stringify(publicData(events3, this.secrets)), { flag: "wx", mode: 384 });
262264
262333
  await rename9(join63(this.workspace, temporary), join63(this.workspace, target6));
262265
262334
  } finally {
262266
- await rm17(join63(this.workspace, temporary), { force: true });
262335
+ await rm18(join63(this.workspace, temporary), { force: true });
262267
262336
  }
262268
262337
  }
262269
262338
  async savePublicAttempts(runId2, metadata8, events3, only5) {
@@ -262969,7 +263038,7 @@ init_world_data();
262969
263038
  init_src();
262970
263039
  init_assets();
262971
263040
  import { randomUUID as randomUUID21 } from "node:crypto";
262972
- import { readdir as readdir15, rm as rm18 } from "node:fs/promises";
263041
+ import { readdir as readdir15, rm as rm19 } from "node:fs/promises";
262973
263042
  import { join as join65 } from "node:path";
262974
263043
  var setupPattern = /^setup_[a-f0-9-]{36}$/;
262975
263044
  var runPattern = /^run_[A-Za-z0-9_-]{1,124}$/;
@@ -263067,7 +263136,7 @@ var SavedTestSetups = class {
263067
263136
  async remove(id15) {
263068
263137
  const relativePath = this.path(id15);
263069
263138
  await preflightFiles(this.workspace, [{ relativePath, content: "" }]);
263070
- await rm18(join65(this.workspace, relativePath));
263139
+ await rm19(join65(this.workspace, relativePath));
263071
263140
  return { removed: true };
263072
263141
  }
263073
263142
  };
@@ -263122,12 +263191,12 @@ async function startConsole(opts) {
263122
263191
  const files2 = /* @__PURE__ */ new Map();
263123
263192
  if (opts.assets !== false) {
263124
263193
  const assets = opts.assets ?? fileURLToPath7(new URL("ui/", assetRoot()));
263125
- const html4 = await readFile45(`${assets}/index.html`).catch(() => {
263194
+ const html4 = await readFile46(`${assets}/index.html`).catch(() => {
263126
263195
  throw new AnchaError("USAGE", "console assets are missing; reinstall Ancha with `npm install -g @ancha-labs/cli`");
263127
263196
  });
263128
263197
  files2.set("/", { body: html4, mime: "text/html; charset=utf-8" });
263129
- files2.set("/app.js", { body: await readFile45(`${assets}/app.js`), mime: "text/javascript; charset=utf-8" });
263130
- files2.set("/style.css", { body: await readFile45(`${assets}/style.css`), mime: "text/css; charset=utf-8" });
263198
+ files2.set("/app.js", { body: await readFile46(`${assets}/app.js`), mime: "text/javascript; charset=utf-8" });
263199
+ files2.set("/style.css", { body: await readFile46(`${assets}/style.css`), mime: "text/css; charset=utf-8" });
263131
263200
  }
263132
263201
  const backend = opts.backend ?? await openBackend();
263133
263202
  const catalog3 = new ScenarioCatalog(workspace4, opts.configPath);
@@ -263682,8 +263751,8 @@ function registerConnection(program2, ctx) {
263682
263751
  // packages/cli/src/commands/test-pull.ts
263683
263752
  init_src();
263684
263753
  import { createHash as createHash83, randomUUID as randomUUID22 } from "node:crypto";
263685
- import { lstat as lstat11, mkdir as mkdir29, readFile as readFile46, realpath as realpath15, rename as rename10, rm as rm19, writeFile as writeFile31 } from "node:fs/promises";
263686
- import { dirname as dirname23, join as join66 } from "node:path";
263754
+ import { lstat as lstat11, mkdir as mkdir30, readFile as readFile47, realpath as realpath15, rename as rename10, rm as rm20, writeFile as writeFile32 } from "node:fs/promises";
263755
+ import { dirname as dirname24, join as join66 } from "node:path";
263687
263756
  var hash8 = (text31) => createHash83("sha256").update(text31).digest("hex");
263688
263757
  var safePath4 = (path9) => typeof path9 === "string" && path9.length > 0 && path9.length <= 1024 && !path9.startsWith("/") && !/[\\\x00-\x1f\x7f:]/.test(path9) && path9.split("/").every((p2) => p2 && !p2.startsWith("."));
263689
263758
  async function writePulledTest(cwd, input5, force = false) {
@@ -263693,7 +263762,7 @@ async function writePulledTest(cwd, input5, force = false) {
263693
263762
  let parent3 = root3;
263694
263763
  for (const part of parts3.slice(0, -1)) {
263695
263764
  parent3 = join66(parent3, part);
263696
- await mkdir29(parent3).catch((e) => {
263765
+ await mkdir30(parent3).catch((e) => {
263697
263766
  if (e.code !== "EEXIST") throw e;
263698
263767
  });
263699
263768
  const info2 = await lstat11(parent3);
@@ -263707,18 +263776,18 @@ async function writePulledTest(cwd, input5, force = false) {
263707
263776
  });
263708
263777
  if (!info2) return null;
263709
263778
  if (!info2.isFile() || info2.isSymbolicLink()) throw new AnchaError("USAGE", "The test path must be a regular file.");
263710
- return readFile46(target6, "utf8");
263779
+ return readFile47(target6, "utf8");
263711
263780
  };
263712
263781
  const before = await current();
263713
263782
  if (!force && before !== null && before !== input5.yaml && hash8(before) !== input5.baseSha256 && hash8(before) !== input5.previousSha256)
263714
263783
  throw new AnchaError("SESSION_CONFLICT", `${input5.path} changed since this run's bundle.`, { hint: "Keep your local edits, or repeat ancha test pull with --force to replace the file." });
263715
- const temp = join66(dirname23(target6), `.ancha-pull-${randomUUID22()}`);
263784
+ const temp = join66(dirname24(target6), `.ancha-pull-${randomUUID22()}`);
263716
263785
  try {
263717
- await writeFile31(temp, input5.yaml, { flag: "wx", mode: 384 });
263786
+ await writeFile32(temp, input5.yaml, { flag: "wx", mode: 384 });
263718
263787
  if (await current() !== before) throw new AnchaError("SESSION_CONFLICT", `${input5.path} changed during the pull. Retry the command.`);
263719
263788
  await rename10(temp, target6);
263720
263789
  } finally {
263721
- await rm19(temp, { force: true });
263790
+ await rm20(temp, { force: true });
263722
263791
  }
263723
263792
  return input5.path;
263724
263793
  }
@@ -263740,8 +263809,8 @@ init_src();
263740
263809
  init_scenes();
263741
263810
  import { createHash as createHash84 } from "node:crypto";
263742
263811
  import { constants as constants13 } from "node:fs";
263743
- import { link as link8, lstat as lstat12, mkdir as mkdir30, mkdtemp as mkdtemp12, open as open13, readFile as readFile47, readdir as readdir16, rename as rename11, rm as rm20, rmdir, unlink as unlink2, writeFile as writeFile32 } from "node:fs/promises";
263744
- import { dirname as dirname24, join as join67, relative as relative22, resolve as resolve48 } from "node:path";
263812
+ import { link as link8, lstat as lstat12, mkdir as mkdir31, mkdtemp as mkdtemp12, open as open13, readFile as readFile48, readdir as readdir16, rename as rename11, rm as rm21, rmdir, unlink as unlink2, writeFile as writeFile33 } from "node:fs/promises";
263813
+ import { dirname as dirname25, join as join67, relative as relative22, resolve as resolve48 } from "node:path";
263745
263814
  var sha2567 = (bytes4) => createHash84("sha256").update(bytes4).digest("hex");
263746
263815
  var KEY_ORDER = ["version", "id", "title", "variant", "start", "attempts", "deadline", "timeout", "until", "checks", "pass", "world"];
263747
263816
  var ordered4 = (test3) => Object.fromEntries([...KEY_ORDER.filter((key5) => key5 in test3), ...Object.keys(test3).filter((key5) => !KEY_ORDER.includes(key5)).sort()].map((key5) => [key5, test3[key5]]));
@@ -263786,9 +263855,9 @@ async function checkBytes(path9, bytes4) {
263786
263855
  async function cleanupPublishedStage(path9) {
263787
263856
  const target6 = await lstat12(path9);
263788
263857
  if (target6.nlink === 1) return;
263789
- for (const entry3 of await readdir16(dirname24(path9), { withFileTypes: true })) {
263858
+ for (const entry3 of await readdir16(dirname25(path9), { withFileTypes: true })) {
263790
263859
  if (!entry3.isDirectory() || !/^\.vary-[a-zA-Z0-9]{6}$/.test(entry3.name)) continue;
263791
- const folder2 = join67(dirname24(path9), entry3.name), staged = join67(folder2, "test");
263860
+ const folder2 = join67(dirname25(path9), entry3.name), staged = join67(folder2, "test");
263792
263861
  const info2 = await lstat12(staged).catch((error65) => {
263793
263862
  if (error65.code === "ENOENT") return void 0;
263794
263863
  throw error65;
@@ -263807,10 +263876,10 @@ async function createExclusive(path9, bytes4) {
263807
263876
  await cleanupPublishedStage(path9);
263808
263877
  return "reused";
263809
263878
  }
263810
- const temp = await mkdtemp12(join67(dirname24(path9), ".vary-"));
263879
+ const temp = await mkdtemp12(join67(dirname25(path9), ".vary-"));
263811
263880
  try {
263812
263881
  const file3 = join67(temp, "test");
263813
- await writeFile32(file3, bytes4, { flag: "wx", mode: 384 });
263882
+ await writeFile33(file3, bytes4, { flag: "wx", mode: 384 });
263814
263883
  try {
263815
263884
  await link8(file3, path9);
263816
263885
  return "written";
@@ -263821,14 +263890,14 @@ async function createExclusive(path9, bytes4) {
263821
263890
  await cleanupPublishedStage(path9);
263822
263891
  return "reused";
263823
263892
  } finally {
263824
- await rm20(temp, { recursive: true, force: true });
263893
+ await rm21(temp, { recursive: true, force: true });
263825
263894
  }
263826
263895
  }
263827
263896
  async function atomicRecord(path9, bytes4, exclusive = false) {
263828
- const temp = await mkdtemp12(join67(dirname24(path9), ".vary-"));
263897
+ const temp = await mkdtemp12(join67(dirname25(path9), ".vary-"));
263829
263898
  const file3 = join67(temp, "record");
263830
263899
  try {
263831
- await writeFile32(file3, bytes4, { flag: "wx", mode: 384 });
263900
+ await writeFile33(file3, bytes4, { flag: "wx", mode: 384 });
263832
263901
  if (!exclusive) await rename11(file3, path9);
263833
263902
  else {
263834
263903
  try {
@@ -263839,7 +263908,7 @@ async function atomicRecord(path9, bytes4, exclusive = false) {
263839
263908
  }
263840
263909
  }
263841
263910
  } finally {
263842
- await rm20(temp, { recursive: true, force: true });
263911
+ await rm21(temp, { recursive: true, force: true });
263843
263912
  }
263844
263913
  }
263845
263914
  function prepare3(plan4, parent3, options5) {
@@ -263886,9 +263955,9 @@ async function mergeManifest(path9, next2) {
263886
263955
  const entries4 = /* @__PURE__ */ new Map();
263887
263956
  for (const entry3 of oldEntries) {
263888
263957
  if (!record31(entry3) || !Number.isInteger(entry3.ordinal) || entry3.ordinal < 1 || entries4.has(entry3.ordinal) || !safeFile(entry3.file) || !hex5(entry3.sha256)) throw conflict4(path9);
263889
- const bytes4 = await existing2(join67(dirname24(path9), entry3.file));
263958
+ const bytes4 = await existing2(join67(dirname25(path9), entry3.file));
263890
263959
  const replacement = newEntries.find((item2) => item2.ordinal === entry3.ordinal);
263891
- if (bytes4 === void 0 ? !replacement : sha2567(bytes4) !== entry3.sha256) throw conflict4(join67(dirname24(path9), entry3.file));
263960
+ if (bytes4 === void 0 ? !replacement : sha2567(bytes4) !== entry3.sha256) throw conflict4(join67(dirname25(path9), entry3.file));
263892
263961
  entries4.set(entry3.ordinal, entry3);
263893
263962
  }
263894
263963
  for (const entry3 of newEntries) {
@@ -263903,7 +263972,7 @@ async function varyTestFiles(cwd, path9, options5 = {}, dependencies = {}) {
263903
263972
  const source = resolve48(cwd, path9);
263904
263973
  let test3;
263905
263974
  try {
263906
- test3 = parseSceneYaml(await readFile47(source, "utf8"));
263975
+ test3 = parseSceneYaml(await readFile48(source, "utf8"));
263907
263976
  } catch {
263908
263977
  await loadSceneOrTest(cwd, source);
263909
263978
  throw invalid40(`${path9}: cannot parse the parent test`);
@@ -263914,9 +263983,9 @@ async function varyTestFiles(cwd, path9, options5 = {}, dependencies = {}) {
263914
263983
  path: relative22(cwd, source),
263915
263984
  test: test3,
263916
263985
  fingerprint: sceneFingerprint(loaded.scene),
263917
- ...loaded.world ? { world: parseSceneYaml(await readFile47(loaded.world, "utf8")) } : {}
263986
+ ...loaded.world ? { world: parseSceneYaml(await readFile48(loaded.world, "utf8")) } : {}
263918
263987
  };
263919
- const out = options5.out === void 0 ? dirname24(source) : resolve48(cwd, options5.out);
263988
+ const out = options5.out === void 0 ? dirname25(source) : resolve48(cwd, options5.out);
263920
263989
  const keyPath = options5.idempotencyKey === void 0 ? void 0 : join67(resolve48(cwd), ".ancha", "test-variation", `${sha2567(options5.idempotencyKey)}.json`);
263921
263990
  const inputHash = sceneFingerprint({ parent: parent3, options: resolved, out });
263922
263991
  const keyConflict = () => new AnchaError("USAGE", "this idempotency key is already bound to different inputs or options", { hint: "repeat the original request, or choose another --idempotency-key" });
@@ -263942,10 +264011,10 @@ async function varyTestFiles(cwd, path9, options5 = {}, dependencies = {}) {
263942
264011
  await mergeManifest(manifestPath, manifest2);
263943
264012
  if (!options5.dryRun) {
263944
264013
  if (keyPath) {
263945
- await mkdir30(dirname24(keyPath), { recursive: true });
264014
+ await mkdir31(dirname25(keyPath), { recursive: true });
263946
264015
  await atomicRecord(keyPath, keyBytes, true);
263947
264016
  }
263948
- await mkdir30(out, { recursive: true });
264017
+ await mkdir31(out, { recursive: true });
263949
264018
  }
263950
264019
  const variants = [];
263951
264020
  for (const item2 of prepared) {
@@ -264013,8 +264082,8 @@ init_trace_import();
264013
264082
  // packages/cli/src/commands/traces.ts
264014
264083
  init_trace_import();
264015
264084
  import { createHash as createHash85 } from "node:crypto";
264016
- import { access as access13, readFile as readFile50, mkdir as mkdir31, stat as stat17, writeFile as writeFile33 } from "node:fs/promises";
264017
- import { basename as basename15, dirname as dirname25, join as join69, relative as relative25, resolve as resolve50 } from "node:path";
264085
+ import { access as access13, readFile as readFile51, mkdir as mkdir32, stat as stat17, writeFile as writeFile34 } from "node:fs/promises";
264086
+ import { basename as basename15, dirname as dirname26, join as join69, relative as relative25, resolve as resolve50 } from "node:path";
264018
264087
  import { isDeepStrictEqual as isDeepStrictEqual7 } from "node:util";
264019
264088
  var import_yaml21 = __toESM(require_dist(), 1);
264020
264089
  init_src();
@@ -264023,7 +264092,7 @@ init_run_store();
264023
264092
 
264024
264093
  // backend/src/trace-ir.ts
264025
264094
  init_src();
264026
- import { readFile as readFile48 } from "node:fs/promises";
264095
+ import { readFile as readFile49 } from "node:fs/promises";
264027
264096
  import { join as join68 } from "node:path";
264028
264097
  var VENDOR_API_BASES2 = {
264029
264098
  slack: "https://slack.com",
@@ -264096,7 +264165,7 @@ function attemptToIr(entries4, traceId, agent, saved) {
264096
264165
  return [{ ir: "ancha.trace/v1", trace_id: traceId, ...agent !== void 0 && { agent }, source: "ancha-run", started_at: entries4[0]?.tSim ?? saved?.scene?.start_time, ...saved?.scene && { test: saved.scene, input: saved.scene.trigger?.input ?? { messages: [{ role: "user", content: saved.scene.task ?? saved.scene.trigger?.task ?? "" }] } }, ...output2?.output !== void 0 && { output: output2.output } }, ...records6];
264097
264166
  }
264098
264167
  async function readAttemptTrace(dir2) {
264099
- const text31 = (await readFile48(join68(dir2, "trace.jsonl"), "utf8")).trim();
264168
+ const text31 = (await readFile49(join68(dir2, "trace.jsonl"), "utf8")).trim();
264100
264169
  return text31 ? text31.split("\n").map((line2) => JSON.parse(line2)) : [];
264101
264170
  }
264102
264171
 
@@ -264219,7 +264288,7 @@ async function listTraces(source, { limit: limit2, since, name: name5 }, env2, f
264219
264288
  }
264220
264289
 
264221
264290
  // packages/cli/src/trace-files.ts
264222
- import { readFile as readFile49, stat as stat16 } from "node:fs/promises";
264291
+ import { readFile as readFile50, stat as stat16 } from "node:fs/promises";
264223
264292
  import { basename as basename14, relative as relative23, resolve as resolve49 } from "node:path";
264224
264293
  init_src();
264225
264294
  var MB3 = 1024 * 1024;
@@ -264248,7 +264317,7 @@ async function findTraceFiles(cwd, args) {
264248
264317
  return [...found].sort();
264249
264318
  }
264250
264319
  async function readTraceTexts(cwd, paths3) {
264251
- return Promise.all(paths3.map(async (path9) => ({ file: relative23(cwd, path9) || basename14(path9), name: basename14(path9), text: await readFile49(path9, "utf8").catch(() => void 0) })));
264320
+ return Promise.all(paths3.map(async (path9) => ({ file: relative23(cwd, path9) || basename14(path9), name: basename14(path9), text: await readFile50(path9, "utf8").catch(() => void 0) })));
264252
264321
  }
264253
264322
  function readTraceUnits(texts4, { fileToIr: fileToIr2, sourceOf: sourceOf2 }) {
264254
264323
  const drafts = /* @__PURE__ */ new Map(), skipped = [], read7 = [];
@@ -264710,7 +264779,7 @@ var importedCheckLines = (scene2, production3) => [
264710
264779
  ...importedChecks(scene2, production3).map((c) => ` ${c.id}: ${c.required ? "required" : "optional"}, ${c.production} in production`)
264711
264780
  ];
264712
264781
  async function localChanges(dir2) {
264713
- const text31 = await readFile50(join69(dir2, "scene.yaml"), "utf8").catch(() => void 0);
264782
+ const text31 = await readFile51(join69(dir2, "scene.yaml"), "utf8").catch(() => void 0);
264714
264783
  if (text31 === void 0) return void 0;
264715
264784
  const local2 = (() => {
264716
264785
  try {
@@ -264721,7 +264790,7 @@ async function localChanges(dir2) {
264721
264790
  })(), mark = MARK.exec(text31)?.[1];
264722
264791
  if (local2 === void 0 || mark === void 0) return { added: [], other: true };
264723
264792
  if (digest4(local2) === mark) return { added: [], other: false };
264724
- const production3 = await readFile50(join69(dir2, "production.json"), "utf8").then((t) => JSON.parse(t).checks, () => void 0);
264793
+ const production3 = await readFile51(join69(dir2, "production.json"), "utf8").then((t) => JSON.parse(t).checks, () => void 0);
264725
264794
  const added = production3 ? checksOf2(local2).filter((c) => !Object.hasOwn(production3, c.id)) : [];
264726
264795
  const addedIds = new Set(added.map((c) => c.id));
264727
264796
  const required6 = (Array.isArray(local2.pass) ? local2.pass : checksOf2(local2).map((c) => c.id)).filter((id15) => addedIds.has(id15));
@@ -264760,22 +264829,22 @@ function sceneToWrite(next2, changes) {
264760
264829
  }
264761
264830
  async function writeWorld(ctx, world5, dest, changes) {
264762
264831
  const dir2 = resolve50(ctx.io.cwd, dest, world5.name);
264763
- await mkdir31(dir2, { recursive: true });
264832
+ await mkdir32(dir2, { recursive: true });
264764
264833
  const { scene: content2, kept } = sceneToWrite(world5.scene, changes);
264765
264834
  const scene2 = join69(dir2, "scene.yaml");
264766
264835
  const { sceneFiles: sceneFiles2 } = await Promise.resolve().then(() => (init_rebuild(), rebuild_exports));
264767
264836
  const files2 = sceneFiles2(content2);
264768
- await writeFile33(scene2, `# Rebuilt by Ancha from a production trace (world ${world5.id}). Where each part came from: provenance.json.
264837
+ await writeFile34(scene2, `# Rebuilt by Ancha from a production trace (world ${world5.id}). Where each part came from: provenance.json.
264769
264838
  # ancha pull: ${world5.id} ${digest4(sceneFiles2(world5.scene).scene)}
264770
264839
  ${(0, import_yaml21.stringify)(files2.scene)}`);
264771
- if (files2.observations !== void 0) await writeFile33(join69(dir2, "observations.jsonl"), files2.observations);
264772
- if (world5.record) await writeFile33(join69(dir2, "production.jsonl"), productionLines(world5.record));
264773
- await writeFile33(join69(dir2, "provenance.json"), JSON.stringify(world5.provenance, null, 2) + "\n");
264774
- if (world5.summary?.candidates) await writeFile33(join69(dir2, "candidates.json"), JSON.stringify(world5.summary.candidates, null, 2) + "\n");
264775
- await writeFile33(join69(dir2, "questions.json"), JSON.stringify(world5.questions ?? [], null, 2) + "\n");
264840
+ if (files2.observations !== void 0) await writeFile34(join69(dir2, "observations.jsonl"), files2.observations);
264841
+ if (world5.record) await writeFile34(join69(dir2, "production.jsonl"), productionLines(world5.record));
264842
+ await writeFile34(join69(dir2, "provenance.json"), JSON.stringify(world5.provenance, null, 2) + "\n");
264843
+ if (world5.summary?.candidates) await writeFile34(join69(dir2, "candidates.json"), JSON.stringify(world5.summary.candidates, null, 2) + "\n");
264844
+ await writeFile34(join69(dir2, "questions.json"), JSON.stringify(world5.questions ?? [], null, 2) + "\n");
264776
264845
  if (world5.summary?.production !== void 0) {
264777
264846
  const checks2 = { ...Object.fromEntries(checksOf2(world5.scene).map((c) => [c.id, "unknown"])), ...world5.summary.production };
264778
- await writeFile33(join69(dir2, "production.json"), JSON.stringify({ trace: world5.summary.trace, checks: checks2, signatures: Object.fromEntries(checksOf2(world5.scene).map((c) => [c.id, productionSignature(c)])) }, null, 2) + "\n");
264847
+ await writeFile34(join69(dir2, "production.json"), JSON.stringify({ trace: world5.summary.trace, checks: checks2, signatures: Object.fromEntries(checksOf2(world5.scene).map((c) => [c.id, productionSignature(c)])) }, null, 2) + "\n");
264779
264848
  }
264780
264849
  await loadSceneFile(scene2);
264781
264850
  return { dir: dir2, scene: scene2, kept };
@@ -264797,7 +264866,7 @@ async function report7(ctx, world5, written) {
264797
264866
  ...open17.length ? [` answer: ancha pull ${world5.id.slice(0, 8)} --answer <question>=<value>; ancha traces show ${world5.id.slice(0, 8)} says how for each`] : [],
264798
264867
  ...traceConnectionLines(connection4),
264799
264868
  `next: ${connection4.commands.init ? `${connection4.commands.init}, then ` : ""}${connection4.commands.run}`,
264800
- ...seen ? [] : [`note: scenes: in ancha.yaml does not include ${where3}; add ${relative25(ctx.io.cwd, dirname25(written.dir)) || "."}/**/scene.yaml to run it with the rest`]
264869
+ ...seen ? [] : [`note: scenes: in ancha.yaml does not include ${where3}; add ${relative25(ctx.io.cwd, dirname26(written.dir)) || "."}/**/scene.yaml to run it with the rest`]
264801
264870
  ].join("\n")
264802
264871
  );
264803
264872
  }
@@ -265291,7 +265360,7 @@ function registerTraces(program2, ctx) {
265291
265360
  });
265292
265361
  }
265293
265362
  async function traceSource(ctx, trace2, from) {
265294
- if (!from) return { text: await readFile50(resolve50(ctx.io.cwd, trace2), "utf8").catch(() => {
265363
+ if (!from) return { text: await readFile51(resolve50(ctx.io.cwd, trace2), "utf8").catch(() => {
265295
265364
  throw new AnchaError("USAGE", `cannot read ${trace2}`, { hint: "pass the path of a trace file: ancha import --offline <trace.jsonl>" });
265296
265365
  }), name: basename15(trace2), label: basename15(trace2) };
265297
265366
  const doc = await fetchTrace(from, trace2, ctx.io.env);
@@ -265299,7 +265368,7 @@ async function traceSource(ctx, trace2, from) {
265299
265368
  return { text: JSON.stringify(doc), name: `${from}-${id15}`.slice(0, 80), label: `${from === "langfuse" ? "Langfuse" : "LangSmith"} trace ${id15}` };
265300
265369
  }
265301
265370
  async function traceFileLines(ctx, file3) {
265302
- const text31 = await readFile50(resolve50(ctx.io.cwd, file3), "utf8").catch(() => {
265371
+ const text31 = await readFile51(resolve50(ctx.io.cwd, file3), "utf8").catch(() => {
265303
265372
  throw new AnchaError("USAGE", `cannot read ${file3}`, { hint: "pass the path of a trace file: ancha traces diff <trace.jsonl> latest" });
265304
265373
  });
265305
265374
  return { text: text31, lines: await traceTextLines(text31, basename15(file3)) };
@@ -265372,9 +265441,9 @@ async function writeRecords(ctx, conversations, dest) {
265372
265441
  const seen = conversations.flatMap((c) => recordsOf2(toolCallsOf(c.lines), { conversation: c.id }));
265373
265442
  if (!seen.length) return void 0;
265374
265443
  const path9 = resolve50(ctx.io.cwd, dest, "records.jsonl");
265375
- const merged = mergeRecords2(readRecordLines2(await readFile50(path9, "utf8").catch(() => "")), seen);
265376
- await mkdir31(dirname25(path9), { recursive: true });
265377
- await writeFile33(path9, recordLines2(merged));
265444
+ const merged = mergeRecords2(readRecordLines2(await readFile51(path9, "utf8").catch(() => "")), seen);
265445
+ await mkdir32(dirname26(path9), { recursive: true });
265446
+ await writeFile34(path9, recordLines2(merged));
265378
265447
  const types = merged.reduce((all9, r2) => all9.set(r2.type, (all9.get(r2.type) ?? 0) + 1), /* @__PURE__ */ new Map());
265379
265448
  return { path: relative25(ctx.io.cwd, path9), count: merged.length, types: Object.fromEntries(types) };
265380
265449
  }
@@ -265386,7 +265455,7 @@ async function importLocally(ctx, source, options5) {
265386
265455
  const { text: text31 } = source, all9 = await traceConversations(text31, source.name);
265387
265456
  const { sceneFiles: sceneFiles2 } = await Promise.resolve().then(() => (init_trace_import(), trace_import_exports));
265388
265457
  const rebuild3 = rebuildTraceImport;
265389
- const checks2 = options5.checks ? readImportChecks(await readFile50(resolve50(ctx.io.cwd, options5.checks), "utf8").catch(() => {
265458
+ const checks2 = options5.checks ? readImportChecks(await readFile51(resolve50(ctx.io.cwd, options5.checks), "utf8").catch(() => {
265390
265459
  throw new AnchaError("USAGE", `cannot read checks file ${options5.checks}`);
265391
265460
  })) : void 0;
265392
265461
  const picked = options5.conversation === void 0 ? all9 : all9.filter((c) => c.id === options5.conversation || c.traces.includes(options5.conversation));
@@ -265405,7 +265474,7 @@ async function importLocally(ctx, source, options5) {
265405
265474
  const made = [], skipped = [];
265406
265475
  for (const [i, conversation3] of picked.entries()) {
265407
265476
  const examples2 = [...all9.filter((c) => c !== conversation3).map((c) => c.lines), ...files2], customer3 = customers3.people[i];
265408
- const earlier2 = options5.resetAnswers ? {} : await readFile50(resolve50(ctx.io.cwd, options5.dest, named5.get(conversation3), "answers.json"), "utf8").then((text32) => JSON.parse(text32), () => ({}));
265477
+ const earlier2 = options5.resetAnswers ? {} : await readFile51(resolve50(ctx.io.cwd, options5.dest, named5.get(conversation3), "answers.json"), "utf8").then((text32) => JSON.parse(text32), () => ({}));
265409
265478
  try {
265410
265479
  const preview = rebuild3(conversation3.lines, { id: named5.get(conversation3), withRecords: true, examples: examples2, useReportedResults: options5.useReportedResults });
265411
265480
  const answers = { ...answersFor(preview.questions, earlier2, options5.answer), ...options5.expect && { "checks.expect": options5.expect } };
@@ -265418,22 +265487,22 @@ async function importLocally(ctx, source, options5) {
265418
265487
  }
265419
265488
  const paths3 = made.map((m) => join69(resolve50(ctx.io.cwd, options5.dest, m.id), "scene.yaml"));
265420
265489
  if (!options5.force) {
265421
- for (const path9 of paths3) if (await readFile50(path9, "utf8").then(() => true, () => false)) throw new AnchaError("USAGE", `${relative25(ctx.io.cwd, path9)} exists; --force replaces it`);
265490
+ for (const path9 of paths3) if (await readFile51(path9, "utf8").then(() => true, () => false)) throw new AnchaError("USAGE", `${relative25(ctx.io.cwd, path9)} exists; --force replaces it`);
265422
265491
  }
265423
265492
  for (const [i, m] of made.entries()) {
265424
- const path9 = paths3[i], dir2 = dirname25(path9);
265425
- await mkdir31(dir2, { recursive: true });
265493
+ const path9 = paths3[i], dir2 = dirname26(path9);
265494
+ await mkdir32(dir2, { recursive: true });
265426
265495
  const files3 = sceneFiles2(m.made.scene);
265427
- await writeFile33(path9, (0, import_yaml21.stringify)(files3.scene, { lineWidth: 0 }));
265428
- await writeFile33(join69(dir2, "candidates.json"), JSON.stringify(m.made.candidates, null, 2) + "\n");
265429
- await writeFile33(join69(dir2, "answers.json"), JSON.stringify(m.answers, null, 2) + "\n");
265430
- if (files3.observations !== void 0) await writeFile33(join69(dir2, "observations.jsonl"), files3.observations);
265431
- if (m.made.record) await writeFile33(join69(dir2, "production.jsonl"), productionLines(m.made.record));
265432
- if (m.made.production !== void 0) await writeFile33(join69(dir2, "production.json"), `${JSON.stringify({ trace: m.made.summary.trace, checks: { ...Object.fromEntries(checksOf2(m.made.scene).map((c) => [c.id, "unknown"])), ...m.made.production }, signatures: Object.fromEntries(checksOf2(m.made.scene).map((c) => [c.id, productionSignature(c)])) }, null, 2)}
265496
+ await writeFile34(path9, (0, import_yaml21.stringify)(files3.scene, { lineWidth: 0 }));
265497
+ await writeFile34(join69(dir2, "candidates.json"), JSON.stringify(m.made.candidates, null, 2) + "\n");
265498
+ await writeFile34(join69(dir2, "answers.json"), JSON.stringify(m.answers, null, 2) + "\n");
265499
+ if (files3.observations !== void 0) await writeFile34(join69(dir2, "observations.jsonl"), files3.observations);
265500
+ if (m.made.record) await writeFile34(join69(dir2, "production.jsonl"), productionLines(m.made.record));
265501
+ if (m.made.production !== void 0) await writeFile34(join69(dir2, "production.json"), `${JSON.stringify({ trace: m.made.summary.trace, checks: { ...Object.fromEntries(checksOf2(m.made.scene).map((c) => [c.id, "unknown"])), ...m.made.production }, signatures: Object.fromEntries(checksOf2(m.made.scene).map((c) => [c.id, productionSignature(c)])) }, null, 2)}
265433
265502
  `);
265434
- await writeFile33(join69(dir2, "provenance.json"), `${JSON.stringify({ summary: m.made.summary, evidence: m.made.evidence, candidates: m.made.candidates, provenance: m.made.provenance, questions: m.made.questions, ...all9.length > 1 && { conversation: { id: m.conversation.id, traces: m.conversation.traces } } }, null, 2)}
265503
+ await writeFile34(join69(dir2, "provenance.json"), `${JSON.stringify({ summary: m.made.summary, evidence: m.made.evidence, candidates: m.made.candidates, provenance: m.made.provenance, questions: m.made.questions, ...all9.length > 1 && { conversation: { id: m.conversation.id, traces: m.conversation.traces } } }, null, 2)}
265435
265504
  `);
265436
- await writeFile33(join69(dir2, "questions.json"), `${JSON.stringify(m.made.questions, null, 2)}
265505
+ await writeFile34(join69(dir2, "questions.json"), `${JSON.stringify(m.made.questions, null, 2)}
265437
265506
  `);
265438
265507
  await loadSceneFile(path9);
265439
265508
  }
@@ -265508,8 +265577,8 @@ function evidenceLines2(made) {
265508
265577
 
265509
265578
  // packages/cli/src/commands/test-import.ts
265510
265579
  import { existsSync as existsSync4 } from "node:fs";
265511
- import { access as access14, mkdir as mkdir32, readFile as readFile51, writeFile as writeFile34 } from "node:fs/promises";
265512
- import { basename as basename16, dirname as dirname26, extname as extname2, isAbsolute as isAbsolute13, relative as relative26, resolve as resolve51 } from "node:path";
265580
+ import { access as access14, mkdir as mkdir33, readFile as readFile52, writeFile as writeFile35 } from "node:fs/promises";
265581
+ import { basename as basename16, dirname as dirname27, extname as extname2, isAbsolute as isAbsolute13, relative as relative26, resolve as resolve51 } from "node:path";
265513
265582
  init_src();
265514
265583
  init_detect();
265515
265584
  init_function_tools();
@@ -265542,7 +265611,7 @@ async function testImport(ctx, file3, options5) {
265542
265611
  }
265543
265612
  let text31, encoding;
265544
265613
  try {
265545
- ({ text: text31, encoding } = decodeEvalText(await readFile51(path9)));
265614
+ ({ text: text31, encoding } = decodeEvalText(await readFile52(path9)));
265546
265615
  } catch (error65) {
265547
265616
  throw new AnchaError("USAGE", `cannot read ${file3}: ${error65.code === "ENOENT" ? "no such file" : error65 instanceof Error ? error65.message : String(error65)}`, { hint: "ancha test import <evals file> --world <id>" });
265548
265617
  }
@@ -265576,11 +265645,11 @@ ${skipped.slice(0, 10).map((s3) => `item ${s3.item}: ${s3.reason}`).join("\n")}`
265576
265645
  const tests = [];
265577
265646
  for (const test3 of imported2.tests) {
265578
265647
  const target6 = resolve51(ctx.io.cwd, test3.path);
265579
- const before = existsSync4(target6) ? await readFile51(target6, "utf8") : void 0;
265648
+ const before = existsSync4(target6) ? await readFile52(target6, "utf8") : void 0;
265580
265649
  const status6 = before === void 0 ? "written" : before === test3.yaml ? "unchanged" : !editedSinceImport(before) ? "updated" : options5.force ? "written" : "kept";
265581
265650
  if (status6 === "written" || status6 === "updated") {
265582
- await mkdir32(dirname26(target6), { recursive: true });
265583
- await writeFile34(target6, test3.yaml);
265651
+ await mkdir33(dirname27(target6), { recursive: true });
265652
+ await writeFile35(target6, test3.yaml);
265584
265653
  }
265585
265654
  tests.push({ id: String(test3.scene.id), file: relative26(ctx.io.cwd, target6), checks: test3.scene.checks.map(kind), status: status6 });
265586
265655
  }
@@ -265628,7 +265697,7 @@ function registerTestImport(tests, ctx) {
265628
265697
  }
265629
265698
 
265630
265699
  // packages/cli/src/commands/test-files.ts
265631
- import { readFile as readFile52, stat as stat18 } from "node:fs/promises";
265700
+ import { readFile as readFile53, stat as stat18 } from "node:fs/promises";
265632
265701
  import { basename as basename17, relative as relative27, resolve as resolve52 } from "node:path";
265633
265702
  init_src();
265634
265703
  init_scenes();
@@ -265650,7 +265719,7 @@ async function showTestFile(ctx, ref23) {
265650
265719
  const matches11 = [];
265651
265720
  for (const file3 of await projectTestFiles(ctx)) {
265652
265721
  try {
265653
- const doc2 = parseSceneYaml(await readFile52(resolve52(ctx.io.cwd, file3), "utf8"));
265722
+ const doc2 = parseSceneYaml(await readFile53(resolve52(ctx.io.cwd, file3), "utf8"));
265654
265723
  if (doc2 && typeof doc2 === "object" && "id" in doc2 && doc2.id === ref23) matches11.push(file3);
265655
265724
  } catch {
265656
265725
  }
@@ -265661,7 +265730,7 @@ async function showTestFile(ctx, ref23) {
265661
265730
  path9 = matches11[0];
265662
265731
  }
265663
265732
  const [{ scene: scene2, world: worldPath }] = await loadScenes(ctx.io.cwd, [path9]);
265664
- const doc = parseSceneYaml(await readFile52(resolve52(ctx.io.cwd, path9), "utf8"));
265733
+ const doc = parseSceneYaml(await readFile53(resolve52(ctx.io.cwd, path9), "utf8"));
265665
265734
  const world5 = {
265666
265735
  ...worldPath !== void 0 && { id: basename17(worldPath, ".yaml"), path: relative27(ctx.io.cwd, worldPath) },
265667
265736
  tools: scene2.twins
@@ -265944,7 +266013,7 @@ Run again with ancha test run ${saved.id}`);
265944
266013
  // packages/cli/src/commands/sandbox.ts
265945
266014
  var import_yaml22 = __toESM(require_dist(), 1);
265946
266015
  init_src();
265947
- import { readFile as readFile53 } from "node:fs/promises";
266016
+ import { readFile as readFile54 } from "node:fs/promises";
265948
266017
  import { resolve as resolve54 } from "node:path";
265949
266018
  init_backend();
265950
266019
  function tools(value6) {
@@ -265991,7 +266060,7 @@ Use --json to export this configuration.`);
265991
266060
  if ([opts.tools, opts.preset, opts.definition].filter(Boolean).length > 1) throw new AnchaError("USAGE", "choose --tools, --preset or --definition");
265992
266061
  let input5;
265993
266062
  if (opts.definition) {
265994
- const doc = (0, import_yaml22.parseDocument)(await readFile53(resolve54(ctx.io.cwd, opts.definition), "utf8"));
266063
+ const doc = (0, import_yaml22.parseDocument)(await readFile54(resolve54(ctx.io.cwd, opts.definition), "utf8"));
265995
266064
  if (doc.errors.length) throw new AnchaError("CONFIG_INVALID", doc.errors.map((error65) => error65.message).join("; "));
265996
266065
  input5 = doc.toJS({ maxAliasCount: 100 });
265997
266066
  if (opts.name && input5 && typeof input5 === "object" && !Array.isArray(input5)) input5 = { ...input5, name: opts.name };
@@ -282594,7 +282663,7 @@ init_src();
282594
282663
  init_backend();
282595
282664
  import { fork as fork2 } from "node:child_process";
282596
282665
  import { randomBytes as randomBytes11 } from "node:crypto";
282597
- import { mkdir as mkdir33, open as open14, readFile as readFile54, rename as rename12, rm as rm21, stat as stat19, writeFile as writeFile35 } from "node:fs/promises";
282666
+ import { mkdir as mkdir34, open as open14, readFile as readFile55, rename as rename12, rm as rm22, stat as stat19, writeFile as writeFile36 } from "node:fs/promises";
282598
282667
  import { createRequire as createRequire6 } from "node:module";
282599
282668
  import { join as join70 } from "node:path";
282600
282669
  var WORLD_SERVER_IDLE_MS = 10 * 6e4;
@@ -282604,13 +282673,13 @@ var LOCK_FILE = "world-server.lock";
282604
282673
  var dir = (cwd) => join70(cwd, ".ancha");
282605
282674
  async function writePrivate(path9, value6) {
282606
282675
  const temporary = `${path9}.${process.pid}.tmp`;
282607
- await writeFile35(temporary, `${JSON.stringify(value6, null, 2)}
282676
+ await writeFile36(temporary, `${JSON.stringify(value6, null, 2)}
282608
282677
  `, { mode: 384 });
282609
282678
  await rename12(temporary, path9);
282610
282679
  }
282611
282680
  async function readJson2(path9) {
282612
282681
  try {
282613
- return JSON.parse(await readFile54(path9, "utf8"));
282682
+ return JSON.parse(await readFile55(path9, "utf8"));
282614
282683
  } catch {
282615
282684
  return void 0;
282616
282685
  }
@@ -282638,7 +282707,7 @@ async function withLock(cwd, work) {
282638
282707
  if (error65.code !== "EEXIST") throw error65;
282639
282708
  const age2 = Date.now() - await stat19(path9).then((s3) => s3.mtimeMs, () => Date.now());
282640
282709
  if (age2 > 3e4) {
282641
- await rm21(path9, { force: true });
282710
+ await rm22(path9, { force: true });
282642
282711
  continue;
282643
282712
  }
282644
282713
  if (attempt2 > 150) throw new AnchaError("SESSION_CONFLICT", "another ancha world up is starting the local world server", { hint: "retry in a few seconds" });
@@ -282648,11 +282717,11 @@ async function withLock(cwd, work) {
282648
282717
  try {
282649
282718
  return await work();
282650
282719
  } finally {
282651
- await rm21(path9, { force: true });
282720
+ await rm22(path9, { force: true });
282652
282721
  }
282653
282722
  }
282654
282723
  async function localWorldServer(cwd) {
282655
- await mkdir33(dir(cwd), { recursive: true });
282724
+ await mkdir34(dir(cwd), { recursive: true });
282656
282725
  const path9 = join70(dir(cwd), SERVER_FILE);
282657
282726
  const current = await readJson2(path9);
282658
282727
  if (current?.version === CLI_VERSION && await alive3(current)) return current;
@@ -282710,7 +282779,7 @@ function startWorldServer(cwd, controlToken) {
282710
282779
  });
282711
282780
  }
282712
282781
  async function recordWorld(cwd, envId, record32) {
282713
- await mkdir33(dir(cwd), { recursive: true });
282782
+ await mkdir34(dir(cwd), { recursive: true });
282714
282783
  const path9 = join70(dir(cwd), ENVS_FILE);
282715
282784
  const all9 = await readJson2(path9) ?? {};
282716
282785
  for (const [id15, entry3] of Object.entries(all9)) if (Date.now() - Date.parse(entry3.createdAt) > 864e5) delete all9[id15];
@@ -283057,7 +283126,7 @@ init_docker();
283057
283126
  init_world_image();
283058
283127
  import { execFile as execFile12, spawn as spawn7 } from "node:child_process";
283059
283128
  import { promisify as promisify11 } from "node:util";
283060
- import { access as access15, chmod as chmod7, copyFile as copyFile5, mkdir as mkdir34, writeFile as writeFile36 } from "node:fs/promises";
283129
+ import { access as access15, chmod as chmod8, copyFile as copyFile5, mkdir as mkdir35, writeFile as writeFile37 } from "node:fs/promises";
283061
283130
  import { join as join71 } from "node:path";
283062
283131
  var exec7 = promisify11(execFile12);
283063
283132
  var VERSION3 = "0.25.0";
@@ -283101,7 +283170,7 @@ async function preparePlaygroundRuntime(workspace4, progress2 = () => {
283101
283170
  "image/Dockerfile"
283102
283171
  ].map((path9) => ({ relativePath: `.ancha/harbor-runtime/${path9}`, content: "" })));
283103
283172
  const runtime2 = join71(workspace4, ".ancha/harbor-runtime");
283104
- await mkdir34(runtime2, { recursive: true, mode: 448 });
283173
+ await mkdir35(runtime2, { recursive: true, mode: 448 });
283105
283174
  const python = join71(runtime2, ".venv/bin/python");
283106
283175
  if (!await exists6(python)) {
283107
283176
  progress2("Preparing the local execution runtime");
@@ -283137,22 +283206,22 @@ async function preparePlaygroundRuntime(workspace4, progress2 = () => {
283137
283206
  if (!await exists6(plugin)) {
283138
283207
  const qualified3 = join71(workspace4, ".ancha/harbor-spike/docker-config/cli-plugins/docker-compose");
283139
283208
  if (!await exists6(qualified3)) throw new AnchaError("AGENT_UNREACHABLE", "Docker Compose is needed for local execution.", { hint: "Install the Docker Compose plugin, then run ancha execution prepare again." });
283140
- await mkdir34(join71(runtime2, "docker-config/cli-plugins"), { recursive: true, mode: 448 });
283209
+ await mkdir35(join71(runtime2, "docker-config/cli-plugins"), { recursive: true, mode: 448 });
283141
283210
  await copyFile5(qualified3, plugin);
283142
- await chmod7(plugin, 448);
283211
+ await chmod8(plugin, 448);
283143
283212
  }
283144
283213
  }
283145
283214
  progress2("Preparing the seeded tools");
283146
283215
  const imageDir = join71(runtime2, "image");
283147
- await mkdir34(imageDir, { recursive: true, mode: 448 });
283216
+ await mkdir35(imageDir, { recursive: true, mode: 448 });
283148
283217
  const companion = await packagedCompanion(), worker = await packagedSuiteqlWorker();
283149
283218
  const image2 = worldImageTag(companion, worker);
283150
- await writeFile36(join71(imageDir, "companion.mjs"), companion);
283151
- await writeFile36(join71(imageDir, "suiteql-worker.mjs"), worker);
283152
- await writeFile36(join71(imageDir, "package.json"), WORLD_PACKAGE_JSON);
283153
- await writeFile36(join71(imageDir, "Dockerfile"), WORLD_DOCKERFILE);
283219
+ await writeFile37(join71(imageDir, "companion.mjs"), companion);
283220
+ await writeFile37(join71(imageDir, "suiteql-worker.mjs"), worker);
283221
+ await writeFile37(join71(imageDir, "package.json"), WORLD_PACKAGE_JSON);
283222
+ await writeFile37(join71(imageDir, "Dockerfile"), WORLD_DOCKERFILE);
283154
283223
  await run6("docker", ["--context", docker3.context, "build", "--tag", image2, imageDir]);
283155
- await writeFile36(join71(runtime2, "setup.json"), JSON.stringify({ harbor: VERSION3, image: image2, preparedAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n", { mode: 384 });
283224
+ await writeFile37(join71(runtime2, "setup.json"), JSON.stringify({ harbor: VERSION3, image: image2, preparedAt: (/* @__PURE__ */ new Date()).toISOString() }) + "\n", { mode: 384 });
283156
283225
  return { available: true, message: "Local playgrounds are ready.", worldImage: image2 };
283157
283226
  }
283158
283227
 
@@ -283190,8 +283259,8 @@ init_src();
283190
283259
  // packages/cli/src/commands/world-company.ts
283191
283260
  init_src();
283192
283261
  import { constants as constants14 } from "node:fs";
283193
- import { lstat as lstat13, mkdir as mkdir35, open as open15, readFile as readFile55, rm as rm22 } from "node:fs/promises";
283194
- import { dirname as dirname27, join as join72, resolve as resolve56 } from "node:path";
283262
+ import { lstat as lstat13, mkdir as mkdir36, open as open15, readFile as readFile56, rm as rm23 } from "node:fs/promises";
283263
+ import { dirname as dirname28, join as join72, resolve as resolve56 } from "node:path";
283195
283264
 
283196
283265
  // backend/src/company/fetch.ts
283197
283266
  init_src();
@@ -283450,7 +283519,7 @@ async function writeCompanyFiles(cwd, files2, force) {
283450
283519
  try {
283451
283520
  const stat22 = await lstat13(target6);
283452
283521
  if (stat22.isFile() && !force) throw new AnchaError("USAGE", `${file3.relativePath} already exists`, { hint: "pass --force to overwrite generated files" });
283453
- previous.set(target6, await readFile55(target6));
283522
+ previous.set(target6, await readFile56(target6));
283454
283523
  } catch (error65) {
283455
283524
  if (error65.code !== "ENOENT") throw error65;
283456
283525
  previous.set(target6, void 0);
@@ -283459,7 +283528,7 @@ async function writeCompanyFiles(cwd, files2, force) {
283459
283528
  if (!force) {
283460
283529
  const result = await applyScaffold(cwd, files2);
283461
283530
  if (result.skipped.length) {
283462
- await Promise.all(result.created.map((file3) => rm22(join72(cwd, file3), { force: true })));
283531
+ await Promise.all(result.created.map((file3) => rm23(join72(cwd, file3), { force: true })));
283463
283532
  throw new AnchaError("USAGE", "a generated target appeared while writing; retry with --force");
283464
283533
  }
283465
283534
  return;
@@ -283468,7 +283537,7 @@ async function writeCompanyFiles(cwd, files2, force) {
283468
283537
  try {
283469
283538
  for (const file3 of files2) {
283470
283539
  const target6 = join72(cwd, file3.relativePath);
283471
- await mkdir35(dirname27(target6), { recursive: true });
283540
+ await mkdir36(dirname28(target6), { recursive: true });
283472
283541
  await preflightFiles(cwd, [file3]);
283473
283542
  const exists7 = previous.get(target6) !== void 0;
283474
283543
  const handle31 = await open15(target6, constants14.O_WRONLY | constants14.O_NOFOLLOW | (exists7 ? 0 : constants14.O_CREAT | constants14.O_EXCL), 420);
@@ -283483,7 +283552,7 @@ async function writeCompanyFiles(cwd, files2, force) {
283483
283552
  } catch (error65) {
283484
283553
  for (const target6 of written.reverse()) {
283485
283554
  const original2 = previous.get(target6);
283486
- if (original2 === void 0) await rm22(target6, { force: true });
283555
+ if (original2 === void 0) await rm23(target6, { force: true });
283487
283556
  else {
283488
283557
  const handle31 = await open15(target6, constants14.O_WRONLY | constants14.O_NOFOLLOW);
283489
283558
  try {
@@ -283506,7 +283575,7 @@ async function worldCompany(ctx, url4, options5, deps = {}) {
283506
283575
  let source = null, fetched = [], modelCredit = null;
283507
283576
  if (options5.profile) {
283508
283577
  try {
283509
- profile2 = parseCompanyProfile(JSON.parse(await readFile55(resolve56(ctx.io.cwd, options5.profile), "utf8")));
283578
+ profile2 = parseCompanyProfile(JSON.parse(await readFile56(resolve56(ctx.io.cwd, options5.profile), "utf8")));
283510
283579
  } catch {
283511
283580
  throw new AnchaError("CONFIG_INVALID", "company profile file must contain a valid version 1 profile", { hint: "see ancha docs company" });
283512
283581
  }
@@ -283590,7 +283659,7 @@ function registerWorldFrom(command, ctx) {
283590
283659
  // packages/cli/src/commands/world-import.ts
283591
283660
  init_src();
283592
283661
  import { existsSync as existsSync5 } from "node:fs";
283593
- import { mkdir as mkdir36, readdir as readdir17, readFile as readFile57, stat as stat20, writeFile as writeFile37 } from "node:fs/promises";
283662
+ import { mkdir as mkdir37, readdir as readdir17, readFile as readFile58, stat as stat20, writeFile as writeFile38 } from "node:fs/promises";
283594
283663
  import { extname as extname3, join as join73, relative as relative29, resolve as resolve58 } from "node:path";
283595
283664
 
283596
283665
  // backend/src/kit/netsuite-import.ts
@@ -284082,7 +284151,7 @@ function realmOf(href2) {
284082
284151
  const m = href2 === void 0 ? null : /^https?:\/\/(\d{4,10})(?:[-_]sb(\d{1,2}))?\.suitetalk\.api\.netsuite\.com/i.exec(href2);
284083
284152
  return m ? `${m[1]}${m[2] ? `_SB${m[2]}` : ""}` : void 0;
284084
284153
  }
284085
- function readFile56(file3, type, notes7) {
284154
+ function readFile57(file3, type, notes7) {
284086
284155
  const text31 = file3.text.replace(/^/, ""), start2 = text31.trimStart();
284087
284156
  if (!/^[[{]/.test(start2)) return readCsv2(file3.path, text31, type, notes7);
284088
284157
  let values3;
@@ -285308,7 +285377,7 @@ function importNetsuite(files2, options5) {
285308
285377
  const notes7 = [], problems = [], read7 = [], type = options5.type === void 0 ? void 0 : canonical11(options5.type);
285309
285378
  let raws = [];
285310
285379
  for (const file3 of files2) {
285311
- let rows35 = readFile56(file3, type, notes7).map((raw3) => ({ ...raw3, type: rowType(raw3) }));
285380
+ let rows35 = readFile57(file3, type, notes7).map((raw3) => ({ ...raw3, type: rowType(raw3) }));
285312
285381
  const untyped = rows35.filter((raw3) => raw3.type === "record" || raw3.type === TRANSACTION || raw3.type === ENTITY2);
285313
285382
  if (untyped.length) problems.push(`${file3.path}: ${untyped.length === 1 ? "a record" : `${untyped.length} records`} with no record type: name the file after its type (customers.csv, invoice.json) or pass --type`);
285314
285383
  rows35 = rows35.filter((raw3) => !untyped.includes(raw3));
@@ -285479,7 +285548,7 @@ async function worldImportNetsuite(ctx, paths3, options5) {
285479
285548
  if (existsSync5(worldPath) && !options5.force) throw new AnchaError("USAGE", `${rel(worldPath)} already exists`, { hint: "pass --force to overwrite it, or choose another --id" });
285480
285549
  const names8 = [...new Set((await Promise.all(paths3.map((path9) => exportFiles(ctx.io.cwd, path9)))).flat())];
285481
285550
  if (!names8.length) throw new AnchaError("USAGE", `no export files in ${paths3.join(", ")}`, { hint: "NetSuite exports are .json (REST records, SuiteQL results) and .csv (saved searches)" });
285482
- const files2 = await Promise.all(names8.map(async (name5) => ({ path: rel(name5), text: decodeEvalText(await readFile57(name5)).text })));
285551
+ const files2 = await Promise.all(names8.map(async (name5) => ({ path: rel(name5), text: decodeEvalText(await readFile58(name5)).text })));
285483
285552
  const imported2 = importNetsuite(files2, {
285484
285553
  id: options5.id,
285485
285554
  now: (/* @__PURE__ */ new Date()).toISOString(),
@@ -285487,8 +285556,8 @@ async function worldImportNetsuite(ctx, paths3, options5) {
285487
285556
  ...options5.type !== void 0 && { type: options5.type },
285488
285557
  ...options5.start !== void 0 && { start: options5.start }
285489
285558
  });
285490
- await mkdir36(outDir, { recursive: true });
285491
- await writeFile37(worldPath, worldFileYaml(imported2.world));
285559
+ await mkdir37(outDir, { recursive: true });
285560
+ await writeFile38(worldPath, worldFileYaml(imported2.world));
285492
285561
  const { coverage: coverage4, problems } = imported2, plain9 = imported2.plainable.filter((type) => !NETSUITE_IMPORT_MODELED.includes(type));
285493
285562
  if (problems.length) ctx.exitCode = 1;
285494
285563
  const again = [
@@ -285570,8 +285639,8 @@ init_privacy();
285570
285639
  init_assets();
285571
285640
  init_report2();
285572
285641
  import { createHash as createHash87, randomBytes as randomBytes12 } from "node:crypto";
285573
- import { lstat as lstat14, mkdir as mkdir37, mkdtemp as mkdtemp13, readFile as readFile58, rename as rename13, rm as rm23, writeFile as writeFile38 } from "node:fs/promises";
285574
- import { dirname as dirname28, join as join74, resolve as resolve59 } from "node:path";
285642
+ import { lstat as lstat14, mkdir as mkdir38, mkdtemp as mkdtemp13, readFile as readFile59, rename as rename13, rm as rm24, writeFile as writeFile39 } from "node:fs/promises";
285643
+ import { dirname as dirname29, join as join74, resolve as resolve59 } from "node:path";
285575
285644
  var object27 = external_exports.record(external_exports.string(), external_exports.unknown());
285576
285645
  var instant = external_exports.string().max(80).refine((value6) => /^\d{4}-\d\d-\d\dT.+(?:Z|[+-]\d\d:\d\d)$/.test(value6) && Number.isFinite(Date.parse(value6)));
285577
285646
  var code3 = external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/);
@@ -285738,7 +285807,7 @@ async function recordPytestRun(cwd, input5, env2 = {}) {
285738
285807
  const exists7 = async () => {
285739
285808
  await preflightFiles(cwd, [{ relativePath: `${relative31}/record.json`, content: "" }]);
285740
285809
  const completed = async () => {
285741
- const text31 = await readFile58(join74(runDir, "record.json"), "utf8");
285810
+ const text31 = await readFile59(join74(runDir, "record.json"), "utf8");
285742
285811
  let previous;
285743
285812
  try {
285744
285813
  previous = JSON.parse(text31);
@@ -285770,13 +285839,13 @@ async function recordPytestRun(cwd, input5, env2 = {}) {
285770
285839
  if (await exists7()) return result;
285771
285840
  const files2 = artifacts(cleaned, runDir);
285772
285841
  files2.set("record.json", json39({ version: 1, fingerprint }));
285773
- await mkdir37(outDir, { recursive: true, mode: 448 });
285842
+ await mkdir38(outDir, { recursive: true, mode: 448 });
285774
285843
  await preflightFiles(cwd, [{ relativePath: `${relative31}/summary.json`, content: "" }]);
285775
285844
  const staging = await mkdtemp13(join74(outDir, ".pytest-"));
285776
285845
  try {
285777
285846
  for (const [path9, content2] of files2) {
285778
- await mkdir37(dirname28(join74(staging, path9)), { recursive: true, mode: 448 });
285779
- await writeFile38(join74(staging, path9), content2, { flag: "wx", mode: 384 });
285847
+ await mkdir38(dirname29(join74(staging, path9)), { recursive: true, mode: 448 });
285848
+ await writeFile39(join74(staging, path9), content2, { flag: "wx", mode: 384 });
285780
285849
  }
285781
285850
  await preflightFiles(cwd, [{ relativePath: `${relative31}/summary.json`, content: "" }]);
285782
285851
  try {
@@ -285787,16 +285856,16 @@ async function recordPytestRun(cwd, input5, env2 = {}) {
285787
285856
  }
285788
285857
  const latest2 = join74(outDir, `.latest-pytest-${randomBytes12(8).toString("hex")}`);
285789
285858
  try {
285790
- await writeFile38(latest2, `${record32.runId}
285859
+ await writeFile39(latest2, `${record32.runId}
285791
285860
  `, { flag: "wx", mode: 384 });
285792
285861
  await preflightFiles(cwd, [{ relativePath: `${DEFAULT_RUNS_DIR}/latest`, content: "" }]);
285793
285862
  await rename13(latest2, join74(outDir, "latest"));
285794
285863
  } finally {
285795
- await rm23(latest2, { force: true });
285864
+ await rm24(latest2, { force: true });
285796
285865
  }
285797
285866
  return result;
285798
285867
  } finally {
285799
- await rm23(staging, { recursive: true, force: true });
285868
+ await rm24(staging, { recursive: true, force: true });
285800
285869
  }
285801
285870
  }
285802
285871
 
@@ -285874,7 +285943,7 @@ ${formatTable(value6.configuration.preset.datasets.map((data7) => [data7.tool, d
285874
285943
  // packages/cli/src/commands/secrets.ts
285875
285944
  var import_yaml23 = __toESM(require_dist(), 1);
285876
285945
  init_src();
285877
- import { readFile as readFile59, writeFile as writeFile39 } from "node:fs/promises";
285946
+ import { readFile as readFile60, writeFile as writeFile40 } from "node:fs/promises";
285878
285947
  import { resolve as resolve61 } from "node:path";
285879
285948
  init_credentials();
285880
285949
  var NAME_RE2 = /^[A-Z][A-Z0-9_]{0,63}$/;
@@ -285882,7 +285951,7 @@ var DEFERRED_SYNC = "Saved in the workspace; the workspace machine picks it up w
285882
285951
  async function nameInConfig(ctx, names8) {
285883
285952
  const label7 = ctx.globals().config ?? "ancha.yaml", file3 = resolve61(ctx.io.cwd, label7);
285884
285953
  const them = names8.length === 1 ? "it" : "them", list19 = names8.join(", ");
285885
- const text31 = await readFile59(file3, "utf8").catch(() => void 0);
285954
+ const text31 = await readFile60(file3, "utf8").catch(() => void 0);
285886
285955
  if (text31 === void 0) return { passEnvHint: `no ${label7} here: list ${list19} under agent.pass_env in the agent's ${label7} so its cloud runs get ${them}` };
285887
285956
  const doc = (0, import_yaml23.parseDocument)(text31);
285888
285957
  const listed2 = (path9) => {
@@ -285898,7 +285967,7 @@ async function nameInConfig(ctx, names8) {
285898
285967
  else for (const name5 of added) doc.addIn(["agent", "pass_env"], name5);
285899
285968
  const out = doc.toString({ lineWidth: 0, flowCollectionPadding: /\[ [^\]\n]*\S \]/.test(text31) });
285900
285969
  try {
285901
- await writeFile39(file3, out);
285970
+ await writeFile40(file3, out);
285902
285971
  } catch {
285903
285972
  return { passEnvHint: `${label7} could not be written: list ${added.join(", ")} under agent.pass_env so the agent's cloud runs get ${added.length === 1 ? "it" : "them"}` };
285904
285973
  }
@@ -286306,7 +286375,7 @@ import { randomUUID as randomUUID23 } from "node:crypto";
286306
286375
  init_run_metadata();
286307
286376
  var import_yaml24 = __toESM(require_dist(), 1);
286308
286377
  init_src();
286309
- import { mkdir as mkdir38, readFile as readFile60, stat as stat21, writeFile as writeFile40 } from "node:fs/promises";
286378
+ import { mkdir as mkdir39, readFile as readFile61, stat as stat21, writeFile as writeFile41 } from "node:fs/promises";
286310
286379
  import { basename as basename18, join as join75, relative as relative30, resolve as resolve62 } from "node:path";
286311
286380
  init_report2();
286312
286381
  init_run_store();
@@ -286337,7 +286406,7 @@ async function testTask(ctx, file3, worldOverride) {
286337
286406
  const path9 = resolve62(ctx.io.cwd, file3);
286338
286407
  let doc;
286339
286408
  try {
286340
- doc = (0, import_yaml24.parse)(await readFile60(path9, "utf8"));
286409
+ doc = (0, import_yaml24.parse)(await readFile61(path9, "utf8"));
286341
286410
  } catch (error65) {
286342
286411
  throw new AnchaError("CONFIG_INVALID", `cannot read ${file3}: ${error65 instanceof Error ? error65.message.split("\n")[0] : String(error65)}`, { hint: "pass a task file (version 2) or a test file (scene.yaml)" });
286343
286412
  }
@@ -286441,7 +286510,7 @@ next page: ancha runs list --cursor ${page20.nextCursor}`}`);
286441
286510
  const workspace4 = await uploadWorkspace(ctx);
286442
286511
  const summary = await loadRunSummary(ctx.io.cwd, ref23, options5.out);
286443
286512
  const runDir = join75(resolve62(ctx.io.cwd, options5.out ?? DEFAULT_RUNS_DIR), summary.runId);
286444
- const inputs2 = JSON.parse(await readFile60(join75(runDir, "inputs.json"), "utf8").catch(() => "{}"));
286513
+ const inputs2 = JSON.parse(await readFile61(join75(runDir, "inputs.json"), "utf8").catch(() => "{}"));
286445
286514
  const passEnv = inputs2.agentEnvironment?.passEnv ?? (await ctx.loadConfig().catch(() => void 0))?.agent?.passEnv ?? [];
286446
286515
  const inheritEnv = inputs2.agentEnvironment?.inheritEnv ?? summary.agentEnvironment?.inheritAll === true;
286447
286516
  const upload6 = await uploadRun(ctx, workspace4, { runId: summary.runId, runDir, passEnv, inheritEnv });
@@ -286462,14 +286531,14 @@ next page: ancha runs list --cursor ${page20.nextCursor}`}`);
286462
286531
  hint: `ancha report ${summary.runId}${options5.out === void 0 ? "" : ` --out ${shellWord(options5.out)}`} shows the saved result; export a run with captured world traces`
286463
286532
  });
286464
286533
  }
286465
- await mkdir38(dest, { recursive: true });
286466
- const inputs2 = await readFile60(join75(resolve62(ctx.io.cwd, options5.out ?? DEFAULT_RUNS_DIR), summary.runId, "inputs.json"), "utf8").then((text31) => JSON.parse(text31), () => ({}));
286534
+ await mkdir39(dest, { recursive: true });
286535
+ const inputs2 = await readFile61(join75(resolve62(ctx.io.cwd, options5.out ?? DEFAULT_RUNS_DIR), summary.runId, "inputs.json"), "utf8").then((text31) => JSON.parse(text31), () => ({}));
286467
286536
  const files2 = [], cases = withSeeds(inputs2.cases ?? []);
286468
286537
  for (const scene2 of summary.scenes) for (const trial of scene2.trialsDetail) {
286469
286538
  const dir2 = resolve62(ctx.io.cwd, trial.dir), name5 = basename18(dir2), file3 = join75(dest, `${name5}.ir.jsonl`);
286470
- await writeFile40(file3, attemptToIr(await readAttemptTrace(dir2), `${summary.runId}/${name5}`, summary.agent, {
286539
+ await writeFile41(file3, attemptToIr(await readAttemptTrace(dir2), `${summary.runId}/${name5}`, summary.agent, {
286471
286540
  scene: cases.find((c) => c.id === scene2.sceneId)?.scene,
286472
- checks: await readFile60(join75(dir2, "checks.json"), "utf8").then((text31) => JSON.parse(text31), () => void 0),
286541
+ checks: await readFile61(join75(dir2, "checks.json"), "utf8").then((text31) => JSON.parse(text31), () => void 0),
286473
286542
  outcome: trial.outcome ?? (trial.valid === false ? "invalid" : trial.passed ? "passed" : "failed"),
286474
286543
  exit: trial.exit,
286475
286544
  exitCode: trial.exitCode