@ancha-labs/cli 0.4.47 → 0.4.48

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
@@ -181022,10 +181022,10 @@ function commentJson2(model2, row2) {
181022
181022
  ...Object.keys(mentioned).length && { mentioned }
181023
181023
  };
181024
181024
  }
181025
- function commentsOf3(call4, writing) {
181026
- need(call4.ctx, writing ? "data.recordComments:write" : "data.recordComments:read");
181025
+ function commentsOf3(call4, writing2) {
181026
+ need(call4.ctx, writing2 ? "data.recordComments:write" : "data.recordComments:read");
181027
181027
  const model2 = AirtableBase.find(call4.ctx, call4.ids[0]), table6 = model2.table(call4.ids[1]);
181028
- if (writing) atLeast(model2, "comment");
181028
+ if (writing2) atLeast(model2, "comment");
181029
181029
  return { model: model2, record: recordIn(model2, table6, call4.ids[2]) };
181030
181030
  }
181031
181031
  function listComments3(call4) {
@@ -251675,7 +251675,7 @@ function withOwnNext(onboarding) {
251675
251675
  const testsAdded = onboarding.checks.testsAdded ?? { done: traces?.done === true, traceId: traces?.traceId ?? null, runId: null, at: traces?.at ?? null };
251676
251676
  const checks2 = { ...onboarding.checks, testsAdded };
251677
251677
  const open17 = CHECKS.find(([key5]) => !checks2[key5].done)?.[0];
251678
- return { ...onboarding, checks: checks2, nextCommand: NEXT_COMMANDS[open17 ?? "done"] };
251678
+ return { ...onboarding, checks: checks2, nextCommand: open17 === "testsAdded" && traces?.done && traces.traceId ? `ancha pull ${traces.traceId}` : NEXT_COMMANDS[open17 ?? "done"] };
251679
251679
  }
251680
251680
  var checkLine = (done, [, doneLabel, title2]) => `${done ? "\u2713" : "\u25CB"} ${done ? doneLabel : title2}`;
251681
251681
  async function listsTests(ctx) {
@@ -251964,7 +251964,7 @@ function eventLine(event3, all9) {
251964
251964
  case "phase":
251965
251965
  return all9 ? `${attemptOf(event3)}: ${text27(data7.phase)}` : void 0;
251966
251966
  case "log":
251967
- return all9 ? `${event3.attemptId === null ? "" : `${attemptOf(event3)}: `}${text27(data7.line ?? data7.text ?? data7.message)}` : void 0;
251967
+ return data7.source === "machine_wait" ? `waiting for a machine: ${text27(data7.reason)}; retrying` : all9 ? `${event3.attemptId === null ? "" : `${attemptOf(event3)}: `}${text27(data7.line ?? data7.text ?? data7.message)}` : void 0;
251968
251968
  default:
251969
251969
  return all9 ? `${event3.type.replace(/_/g, " ")}${data7.state ? `: ${text27(data7.state)}` : ""}` : void 0;
251970
251970
  }
@@ -252020,7 +252020,7 @@ function projectTestDirectoryReader(cwd, cloud) {
252020
252020
  function finishedText(ws, detail3, includeNext = true) {
252021
252021
  const { job, summary } = detail3;
252022
252022
  const counts2 = summary?.counts ?? job.counts;
252023
- const never2 = cloudNeverRan(detail3);
252023
+ const never2 = ["install", "create", "start"].includes(job.error?.step ?? "") ? void 0 : cloudNeverRan(detail3);
252024
252024
  if (never2 !== void 0 && summary !== null) {
252025
252025
  const head2 = summary.graded !== true && counts2.completedAttempts === 0 ? "INVALID (no attempts graded)" : job.state === "completed" ? summary.verdict.toUpperCase() : job.state.toUpperCase();
252026
252026
  const folded = neverRanChecksLine(never2, job.id);
@@ -252062,7 +252062,11 @@ function finishedText(ws, detail3, includeNext = true) {
252062
252062
  const counts3 = job.counts;
252063
252063
  if (counts3 !== void 0) lines2.push(`Cases: ${counts3.cases} \xB7 attempts: ${counts3.requestedAttempts} requested, ${counts3.completedAttempts} completed, ${counts3.invalidAttempts} invalid${counts3.skippedAttempts ? `, ${counts3.skippedAttempts} skipped` : ""}${counts3.cancelledAttempts ? `, ${counts3.cancelledAttempts} cancelled` : ""}`);
252064
252064
  }
252065
- if (job.error !== null && job.error !== void 0) lines2.push(`${job.error.step ? `${job.error.step}: ` : ""}${job.error.message}`, errorAction(toErrorJson(serverError(400, { error: job.error }, { message: "The job failed." }))));
252065
+ if (job.error !== null && job.error !== void 0) lines2.push(
252066
+ `${job.error.step ? `${job.error.step}: ` : ""}${job.error.message}`,
252067
+ ...job.error.step === "install" && job.error.stderr ? job.error.stderr.trim().split("\n").slice(-10).map((line2) => ` ${line2}`) : [],
252068
+ errorAction(toErrorJson(serverError(400, { error: job.error }, { message: "The job failed." })))
252069
+ );
252066
252070
  lines2.push(`Result: ${resultUrl(ws, detail3)}`);
252067
252071
  if (includeNext && job.kind === "run") {
252068
252072
  const ungraded = summary?.verdict === "ungraded";
@@ -256050,8 +256054,10 @@ next: ancha wait ${job.id}`);
256050
256054
  return followToEnd(ctx, ws, job.id, signal);
256051
256055
  }
256052
256056
  async function connectOnCloud(ctx, ws, check4, signal) {
256057
+ const key5 = submissionKey(check4.idempotencyKey);
256053
256058
  const { bundle } = await cloudBundle(ctx, { kind: "connect", tests: [], options: { attempts: 1, concurrency: 1, seed: null, strict: false, minPassRate: check4.minPassRate, allowUnwrapped: [], agentCommand: check4.agentCommand } });
256054
- const submitted = await submit2(ws, bundle, submissionKey(void 0), signal, {});
256059
+ const submitted = await submit2(ws, bundle, key5, signal, {});
256060
+ if (submitted.replayed && check4.idempotencyKey !== void 0) ctx.out.info(`${submitted.job.id}: already submitted with this --idempotency-key`);
256055
256061
  const logTail3 = [];
256056
256062
  const agentLogTail = [];
256057
256063
  await followJob(ws, submitted.job.id, { signal, onEvent: (event3) => {
@@ -257039,7 +257045,7 @@ async function uploadAgent(ctx, opts, command = "ancha agent upload") {
257039
257045
  const configured = config12.agent?.mode === "endpoint" ? void 0 : config12.agent;
257040
257046
  const task2 = await taskCheck(ctx, typeof opts.agent === "string" ? { command: opts.agent, ...configured?.env && { env: configured.env } } : configured);
257041
257047
  if (task2?.status === "warning") ctx.out.info(`${task2.message}: ${task2.fix} (${task2.hint})`);
257042
- const { detail: detail3, agent, agentAction: agentAction2, bundle, logTail: logTail3, url: url4 } = await interruptible(ctx, (signal) => connectOnCloud(ctx, ws, { agentCommand: typeof opts.agent === "string" ? opts.agent : null, minPassRate: config12.min_pass_rate }, signal));
257048
+ const { detail: detail3, agent, agentAction: agentAction2, bundle, logTail: logTail3, url: url4 } = await interruptible(ctx, (signal) => connectOnCloud(ctx, ws, { agentCommand: typeof opts.agent === "string" ? opts.agent : null, minPassRate: config12.min_pass_rate, ...opts.idempotencyKey !== void 0 && { idempotencyKey: opts.idempotencyKey } }, signal));
257043
257049
  const checks2 = [
257044
257050
  { name: "workspace", status: "pass", message: `running in the workspace ${ws.server}` },
257045
257051
  { name: "bundle", status: "pass", message: `${bundle.files} files, ${(bundle.bytes / 1024 / 1024).toFixed(1)} MiB; project ${bundle.projectHash.slice(0, 12)}` },
@@ -257444,7 +257450,7 @@ function loginRunLine(ctx) {
257444
257450
  const apiKey = Boolean(ctx.io.env.ANCHA_API_KEY);
257445
257451
  return apiKey || inCi(ctx.io.env) ? `${apiKey ? "With ANCHA_API_KEY set" : "In CI"}, ancha run runs where ancha.yaml says; ancha run --on cloud runs in this workspace.` : "ancha run runs your tests in this workspace; ancha run --on local runs them on this computer.";
257446
257452
  }
257447
- async function json38(url4, init = {}, fetchImpl = fetch) {
257453
+ async function json38(url4, init = {}, fetchImpl = fetch, transient = false) {
257448
257454
  let res;
257449
257455
  let text31;
257450
257456
  try {
@@ -257454,10 +257460,16 @@ async function json38(url4, init = {}, fetchImpl = fetch) {
257454
257460
  });
257455
257461
  throw authError(new URL(url4).origin, { status: 401, keySent: Boolean(new Headers(init.headers).get("authorization")) });
257456
257462
  }
257463
+ if (transient && [429, 502, 503, 504].includes(res.status)) {
257464
+ void res.body?.cancel().catch(() => {
257465
+ });
257466
+ throw Object.assign(new AnchaError("SERVER_UNREACHABLE", `cannot reach ${new URL(url4).origin}`, { hint: "run ancha login again" }), { retryAfter: res.headers.get("retry-after") });
257467
+ }
257457
257468
  text31 = await res.text();
257458
257469
  } catch (e) {
257459
257470
  if (e instanceof AnchaError) throw e;
257460
- throw new AnchaError("SERVER_UNREACHABLE", `cannot reach ${new URL(url4).origin}`, { hint: "check the address and your network, then run ancha login again", cause: e });
257471
+ const error65 = new AnchaError("SERVER_UNREACHABLE", `cannot reach ${new URL(url4).origin}`, { hint: "check the address and your network, then run ancha login again", cause: e });
257472
+ throw transient ? Object.assign(error65, { retryAfter: null }) : error65;
257461
257473
  }
257462
257474
  let body8;
257463
257475
  try {
@@ -257467,7 +257479,14 @@ async function json38(url4, init = {}, fetchImpl = fetch) {
257467
257479
  }
257468
257480
  if (!res.ok) {
257469
257481
  const message8 = body8 && typeof body8 === "object" && typeof body8.error === "string" ? body8.error : `HTTP ${res.status}`;
257470
- throw new AnchaError("INTERNAL", `${new URL(url4).origin}: ${message8}`);
257482
+ if (!transient || res.status === 403) throw new AnchaError("INTERNAL", `${new URL(url4).origin}: ${message8}`);
257483
+ const contract = body8 && typeof body8 === "object" && typeof body8.error === "object" ? body8 : void 0;
257484
+ const error65 = serverError(res.status, contract, { message: `${new URL(url4).origin}: ${message8}`, code: "INTERNAL" });
257485
+ if (res.status === 500) {
257486
+ error65.code = "INTERNAL";
257487
+ error65.kind = "ours";
257488
+ }
257489
+ throw error65;
257471
257490
  }
257472
257491
  if (body8 === void 0) throw new AnchaError("INTERNAL", `${new URL(url4).origin} sent a malformed response`);
257473
257492
  return body8;
@@ -257485,12 +257504,34 @@ function openBrowser(url4) {
257485
257504
  }
257486
257505
  }
257487
257506
  var sleep12 = (ms2, signal) => new Promise((resolve63) => {
257488
- const timer = setTimeout(resolve63, ms2);
257489
- signal?.addEventListener("abort", () => {
257507
+ const done = () => {
257490
257508
  clearTimeout(timer);
257509
+ signal?.removeEventListener("abort", done);
257491
257510
  resolve63();
257492
- }, { once: true });
257511
+ };
257512
+ const timer = setTimeout(done, ms2);
257513
+ if (signal?.aborted) done();
257514
+ else signal?.addEventListener("abort", done, { once: true });
257493
257515
  });
257516
+ async function loginJson(url4, init, fetchImpl, signal, deadline3 = Infinity) {
257517
+ for (let failures = 0; ; failures++) {
257518
+ if (signal?.aborted) throw new AnchaError("USAGE", "login interrupted");
257519
+ try {
257520
+ const timeout = AbortSignal.timeout(Math.max(1, Math.min(2e4, deadline3 > Date.now() ? deadline3 - Date.now() : 2e4)));
257521
+ return await json38(url4, { ...init, signal: signal ? AbortSignal.any([signal, timeout]) : timeout }, fetchImpl, true);
257522
+ } catch (error65) {
257523
+ if (signal?.aborted) throw new AnchaError("USAGE", "login interrupted");
257524
+ if (!(error65 instanceof AnchaError) || !("retryAfter" in error65)) throw error65;
257525
+ const unavailable3 = () => new AnchaError("SERVER_UNREACHABLE", error65.message, { kind: "retry", hint: "run ancha login again", cause: error65 });
257526
+ if (failures >= 5 || Date.now() >= deadline3) throw unavailable3();
257527
+ const after = error65.retryAfter;
257528
+ const delay = after && /^\d+(?:\.\d+)?$/.test(after.trim()) ? Number(after) * 1e3 : after ? Date.parse(after) - Date.now() : NaN;
257529
+ await sleep12(Math.min(deadline3 - Date.now(), Number.isFinite(delay) ? Math.max(0, Math.min(3e4, delay)) : 4e3 + Math.random() * 2e3), signal);
257530
+ if (Date.now() >= deadline3) throw unavailable3();
257531
+ }
257532
+ }
257533
+ }
257534
+ var SAVE_REASONS = { EACCES: "permission denied", EPERM: "operation not permitted", EROFS: "read-only file system", ENOSPC: "no space left on device", EISDIR: "is a directory", ENOTDIR: "not a directory" };
257494
257535
  var RESUME_HINT = "If this command stops before you approve, run ancha login again: it finishes this sign-in.";
257495
257536
  var pendingPath = (env2) => {
257496
257537
  const path9 = credentialsPath(env2);
@@ -257538,10 +257579,10 @@ function registerLogin(program2, ctx, deps = {}) {
257538
257579
  }
257539
257580
  const env2 = ctx.io.env, signal = ctx.io.abort;
257540
257581
  if (!credentialsPath(env2)) throw new AnchaError("USAGE", "set HOME or ANCHA_CREDENTIALS_FILE to save a sign-in");
257541
- const poll = (deviceCode) => json38(`${base6}/cli/poll?device_code=${encodeURIComponent(deviceCode)}`, {}, deps.fetch);
257582
+ const poll = (deviceCode, deadline4) => loginJson(`${base6}/cli/poll?device_code=${encodeURIComponent(deviceCode)}`, {}, deps.fetch, signal, deadline4);
257542
257583
  let pending = await readPending(env2, base6), resumed = false;
257543
257584
  if (pending) {
257544
- const first2 = await poll(pending.deviceCode);
257585
+ const first2 = await poll(pending.deviceCode, Date.parse(pending.expiresAt));
257545
257586
  if (first2.status === "approved") return finish2(first2, pending.deviceCode);
257546
257587
  if (first2.status === "pending" && Date.parse(pending.expiresAt) - Date.now() > 15e3) resumed = true;
257547
257588
  else {
@@ -257551,7 +257592,7 @@ function registerLogin(program2, ctx, deps = {}) {
257551
257592
  }
257552
257593
  let saved = resumed;
257553
257594
  if (!pending) {
257554
- const start2 = await json38(`${base6}/cli/device`, { method: "POST", body: JSON.stringify({ name: hostname4() }) }, deps.fetch);
257595
+ const start2 = await loginJson(`${base6}/cli/device`, { method: "POST", body: JSON.stringify({ name: hostname4() }) }, deps.fetch, signal);
257555
257596
  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() };
257556
257597
  saved = await writePending(env2, pending);
257557
257598
  }
@@ -257565,9 +257606,9 @@ function registerLogin(program2, ctx, deps = {}) {
257565
257606
  const deadline3 = Date.parse(pending.expiresAt);
257566
257607
  const interval = Math.max(2, Math.min(15, pending.interval || 3)) * 1e3;
257567
257608
  while (Date.now() < deadline3 && !signal?.aborted) {
257568
- await sleep12(interval, signal);
257569
- if (signal?.aborted) break;
257570
- const result = await poll(pending.deviceCode);
257609
+ await sleep12(Math.min(interval, deadline3 - Date.now()), signal);
257610
+ if (signal?.aborted || Date.now() >= deadline3) break;
257611
+ const result = await poll(pending.deviceCode, Date.parse(pending.expiresAt));
257571
257612
  if (result.status === "pending") continue;
257572
257613
  if (result.status === "denied") {
257573
257614
  await dropPending(env2, pending.deviceCode);
@@ -257586,10 +257627,17 @@ function registerLogin(program2, ctx, deps = {}) {
257586
257627
  throw new AnchaError("INTERNAL", `${base6} approved the sign-in without a key`);
257587
257628
  }
257588
257629
  const serverUrl3 = normalizeServerUrl(approved.serverUrl);
257589
- const file3 = await readCredentials(env2);
257590
- file3.servers[serverUrl3] = { apiKey: approved.apiKey, ...approved.email && { email: approved.email }, savedAt: (/* @__PURE__ */ new Date()).toISOString(), minted: "device" };
257591
- file3.default = serverUrl3;
257592
- const path9 = await writeCredentials(file3, env2);
257630
+ let path9;
257631
+ try {
257632
+ const file3 = await readCredentials(env2);
257633
+ file3.servers[serverUrl3] = { apiKey: approved.apiKey, ...approved.email && { email: approved.email }, savedAt: (/* @__PURE__ */ new Date()).toISOString(), minted: "device" };
257634
+ file3.default = serverUrl3;
257635
+ path9 = await writeCredentials(file3, env2);
257636
+ } catch (error65) {
257637
+ const reason2 = SAVE_REASONS[error65.code ?? ""];
257638
+ if (!reason2) throw error65;
257639
+ throw new AnchaError("CONFIG_INVALID", `cannot save the sign-in to ${credentialsPath(env2)}: ${reason2}`, { kind: "fix", hint: "make the folder writable, or set ANCHA_CREDENTIALS_FILE to a file you can write", cause: error65 });
257640
+ }
257593
257641
  await dropPending(env2, deviceCode);
257594
257642
  let onboarding = null, unread2;
257595
257643
  try {
@@ -258581,7 +258629,7 @@ init_scenes();
258581
258629
 
258582
258630
  // packages/cli/src/kit/init.ts
258583
258631
  import { constants as constants12 } from "node:fs";
258584
- import { lstat as lstat10, mkdir as mkdir26, open as open11, readFile as readFile43, rm as rm13, writeFile as writeFile27 } from "node:fs/promises";
258632
+ import { lstat as lstat10, mkdir as mkdir26, open as fsOpen, readFile as readFile43, rm as rm13, writeFile as fsWriteFile } from "node:fs/promises";
258585
258633
  import { join as join58 } from "node:path";
258586
258634
  import { Writable } from "node:stream";
258587
258635
  var import_yaml18 = __toESM(require_dist(), 1);
@@ -260579,6 +260627,30 @@ ${doc.markdown}` : doc.markdown);
260579
260627
 
260580
260628
  // packages/cli/src/kit/init.ts
260581
260629
  var toolName = (twin) => TOOL_DESCRIPTORS.find((tool) => tool.name === twin)?.title ?? twin;
260630
+ var WRITE_REFUSALS = {
260631
+ EACCES: "permission denied",
260632
+ EPERM: "not permitted",
260633
+ EROFS: "the file system is read-only",
260634
+ ENOSPC: "the disk is full",
260635
+ EDQUOT: "the disk quota is used up",
260636
+ ENOTDIR: "part of the path is a file, not a folder",
260637
+ EISDIR: "it is a folder"
260638
+ };
260639
+ function initWriteError(error65, cwd) {
260640
+ const cause = error65;
260641
+ if (error65 instanceof AnchaError || !cause?.code || !Object.hasOwn(WRITE_REFUSALS, cause.code) || !/^(open|mkdir|write|writev|ftruncate|rename|unlink|rmdir|copyfile)$/.test(cause.syscall ?? "")) return error65;
260642
+ return new AnchaError("CONFIG_INVALID", `cannot write ${cause.path ?? cwd}: ${WRITE_REFUSALS[cause.code]}`, { kind: "fix", hint: "run ancha init in a folder you can write", cause });
260643
+ }
260644
+ async function writing(path9, fn) {
260645
+ try {
260646
+ return await fn();
260647
+ } catch (error65) {
260648
+ throw initWriteError(error65, path9);
260649
+ }
260650
+ }
260651
+ var applyScaffold2 = (cwd, files2) => writing(cwd, () => applyScaffold(cwd, files2));
260652
+ var open11 = (path9, flags) => writing(path9, () => fsOpen(path9, flags));
260653
+ var writeFile27 = (path9, content2) => writing(path9, () => fsWriteFile(path9, content2));
260582
260654
  function step2(ctx) {
260583
260655
  const io = { ...ctx.io, stdout: new Writable({ write(_chunk, _encoding, done) {
260584
260656
  done();
@@ -260603,7 +260675,7 @@ Read \`ancha docs tools\` for function checks and registration.
260603
260675
  original2 = await readFile43(target6, "utf8");
260604
260676
  } catch (error65) {
260605
260677
  if (error65.code !== "ENOENT") throw error65;
260606
- const result = await applyScaffold(cwd, [{ relativePath: "AGENTS.md", content: managed }]);
260678
+ const result = await applyScaffold2(cwd, [{ relativePath: "AGENTS.md", content: managed }]);
260607
260679
  return result.created.length ? "created" : "preserved";
260608
260680
  }
260609
260681
  if (original2.includes(BEGIN) || original2.includes(END)) {
@@ -260616,7 +260688,7 @@ Read \`ancha docs tools\` for function checks and registration.
260616
260688
  await preflightFiles(cwd, [{ relativePath: "AGENTS.md", content: "" }]);
260617
260689
  const handle31 = await open11(target6, constants12.O_WRONLY | constants12.O_APPEND | constants12.O_NOFOLLOW);
260618
260690
  try {
260619
- await handle31.writeFile(`${original2.endsWith("\n") ? "\n" : "\n\n"}${managed}`);
260691
+ await writing(target6, () => handle31.writeFile(`${original2.endsWith("\n") ? "\n" : "\n\n"}${managed}`));
260620
260692
  } finally {
260621
260693
  await handle31.close();
260622
260694
  }
@@ -260632,15 +260704,15 @@ async function ignoreAnchaDirectory(cwd) {
260632
260704
  original2 = await readFile43(target6, "utf8");
260633
260705
  } catch (error65) {
260634
260706
  if (error65.code !== "ENOENT") throw error65;
260635
- const result = await applyScaffold(cwd, [{ relativePath: ".gitignore", content: ".ancha/\n" }]);
260707
+ const result = await applyScaffold2(cwd, [{ relativePath: ".gitignore", content: ".ancha/\n" }]);
260636
260708
  return result.created.length ? "created" : "preserved";
260637
260709
  }
260638
260710
  if (ignoresAncha(original2)) return "preserved";
260639
260711
  await preflightFiles(cwd, [{ relativePath: ".gitignore", content: "" }]);
260640
260712
  const handle31 = await open11(target6, constants12.O_WRONLY | constants12.O_APPEND | constants12.O_NOFOLLOW);
260641
260713
  try {
260642
- await handle31.writeFile(`${original2 === "" || original2.endsWith("\n") ? "" : "\n"}.ancha/
260643
- `);
260714
+ await writing(target6, () => handle31.writeFile(`${original2 === "" || original2.endsWith("\n") ? "" : "\n"}.ancha/
260715
+ `));
260644
260716
  } finally {
260645
260717
  await handle31.close();
260646
260718
  }
@@ -260788,7 +260860,7 @@ async function rewrite(cwd, relativePath, content2) {
260788
260860
  await preflightFiles(cwd, [{ relativePath, content: "" }]);
260789
260861
  const handle31 = await open11(join58(cwd, relativePath), constants12.O_WRONLY | constants12.O_TRUNC | constants12.O_NOFOLLOW);
260790
260862
  try {
260791
- await handle31.writeFile(content2);
260863
+ await writing(join58(cwd, relativePath), () => handle31.writeFile(content2));
260792
260864
  } finally {
260793
260865
  await handle31.close();
260794
260866
  }
@@ -260923,7 +260995,7 @@ async function wireExistingConfig(cwd, fillMissing) {
260923
260995
  await preflightFiles(cwd, [{ relativePath: "ancha.yaml", content: "" }]);
260924
260996
  const handle31 = await open11(target6, constants12.O_WRONLY | constants12.O_TRUNC | constants12.O_NOFOLLOW);
260925
260997
  try {
260926
- await handle31.writeFile(next2);
260998
+ await writing(target6, () => handle31.writeFile(next2));
260927
260999
  } finally {
260928
261000
  await handle31.close();
260929
261001
  }
@@ -261001,7 +261073,7 @@ min_pass_rate: 1
261001
261073
  await rewrite(ctx.io.cwd, file3.relativePath, file3.content);
261002
261074
  updated.push(file3.relativePath);
261003
261075
  }
261004
- const result = await applyScaffold(ctx.io.cwd, files2.filter((file3) => !rewritten.includes(file3)));
261076
+ const result = await applyScaffold2(ctx.io.cwd, files2.filter((file3) => !rewritten.includes(file3)));
261005
261077
  const agents = await installAgents(ctx.io.cwd, detection.functionTools);
261006
261078
  let savedCommand;
261007
261079
  if (configured) {
@@ -261031,9 +261103,9 @@ min_pass_rate: 1
261031
261103
  const isGenerated = (twin) => gen_exports.GENERATED_TOOLS.includes(twin);
261032
261104
  const tools2 = twins.filter(isGenerated);
261033
261105
  const keyed2 = (suffix) => opts.idempotencyKey === void 0 ? {} : { idempotencyKey: `${opts.idempotencyKey}-${suffix}` };
261034
- const world5 = await worldGen(step2(ctx), opts.intent, { ...used.length > 0 && tools2.length > 0 && { tools: tools2.join(",") }, ...keyed2("world") });
261106
+ const world5 = await writing(ctx.io.cwd, () => worldGen(step2(ctx), opts.intent, { ...used.length > 0 && tools2.length > 0 && { tools: tools2.join(",") }, ...keyed2("world") }));
261035
261107
  notGenerated = await addExampleSeeds(join58(ctx.io.cwd, world5.world), used.filter((twin) => !isGenerated(twin)));
261036
- const test3 = await testNew(step2(ctx), opts.intent, { world: world5.id, ...keyed2("test") });
261108
+ const test3 = await writing(ctx.io.cwd, () => testNew(step2(ctx), opts.intent, { world: world5.id, ...keyed2("test") }));
261037
261109
  generated = { world: { id: world5.id, file: world5.world, people: world5.people, ...notGenerated.added.length > 0 && { exampleData: notGenerated.added } }, test: { id: test3.id, file: test3.file, checks: test3.checks }, ...(world5.modelCredit ?? test3.modelCredit) && { modelCredit: "workspace" } };
261038
261110
  result.created.push(...world5.files, test3.file, test3.record);
261039
261111
  }
@@ -261121,7 +261193,7 @@ function registerSceneNew(scene2, ctx) {
261121
261193
  throw new AnchaError("USAGE", `cannot create scene destination: ${prefix2}`, { hint: "choose another id and remove unsafe symlinks", cause });
261122
261194
  }
261123
261195
  try {
261124
- const result = await applyScaffold(ctx.io.cwd, planned);
261196
+ const result = await applyScaffold2(ctx.io.cwd, planned);
261125
261197
  ctx.out.result({ id: id15, twins, ...result }, () => `Created ${prefix2}/scene.yaml and oracle/null companions. Validate: ancha scene validate ${prefix2}/scene.yaml`);
261126
261198
  } catch (error65) {
261127
261199
  await rm13(target6, { recursive: true, force: true });
@@ -264360,10 +264432,14 @@ function traceRef(source, ref23) {
264360
264432
  async function call3(f2, url4, init, tool, keys7) {
264361
264433
  for (let attempt2 = 0; ; attempt2++) {
264362
264434
  let res;
264435
+ const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 3e4);
264363
264436
  try {
264364
- res = await f2(url4, init);
264437
+ const response6 = await f2(url4, { ...init, signal: controller.signal });
264438
+ res = new Response([204, 205, 304].includes(response6.status) ? null : await response6.arrayBuffer(), { status: response6.status, headers: response6.headers });
264365
264439
  } catch (error65) {
264366
- throw new AnchaError("SERVER_UNREACHABLE", `cannot reach ${tool} at ${new URL(url4).origin}`, { cause: error65, hint: "check the host in your environment and the network" });
264440
+ throw new AnchaError("SERVER_UNREACHABLE", `cannot reach ${tool} at ${new URL(url4).origin}`, { cause: error65, kind: "retry", hint: "check the host in your environment and the network; no workspace uploads have been confirmed by this command. Running the same command again is safe." });
264441
+ } finally {
264442
+ clearTimeout(timer);
264367
264443
  }
264368
264444
  if (res.status === 429 && attempt2 < 8) {
264369
264445
  await sleep14((Number(res.headers.get("retry-after")) || 2 ** attempt2) * 1e3);
@@ -264422,7 +264498,10 @@ async function fromLangsmith(traceId, env2, f2) {
264422
264498
  if (!runs.length) throw new AnchaError("USAGE", `LangSmith has no trace ${traceId} that this key can read`);
264423
264499
  const root3 = runs.find((r2) => !r2.parent_run_id) ?? runs[0];
264424
264500
  const thread4 = root3.thread_id ?? root3.extra?.metadata?.thread_id;
264425
- const turns = thread4 && root3.session_id ? await query12({ session: [root3.session_id], is_root: true, filter: `and(eq(metadata_key, "thread_id"), eq(metadata_value, ${JSON.stringify(String(thread4))}))` }).catch(() => [root3]) : [root3];
264501
+ const turns = thread4 && root3.session_id ? await query12({ session: [root3.session_id], is_root: true, filter: `and(eq(metadata_key, "thread_id"), eq(metadata_value, ${JSON.stringify(String(thread4))}))` }).catch((error65) => {
264502
+ if (error65 instanceof AnchaError && error65.code === "SERVER_UNREACHABLE") throw error65;
264503
+ return [root3];
264504
+ }) : [root3];
264426
264505
  const ids3 = [.../* @__PURE__ */ new Set([root3.id, ...turns.map((r2) => r2.id)])];
264427
264506
  const feedback = [];
264428
264507
  for (const id15 of ids3) feedback.push(...await call3(f2, `${api4}/feedback?${new URLSearchParams({ run: id15 })}`, { headers }, "LangSmith", "LANGSMITH_API_KEY"));
@@ -264828,24 +264907,51 @@ var WorkspaceError = class extends AnchaError {
264828
264907
  };
264829
264908
  function workspaceError(status6, body8, path9) {
264830
264909
  if (status6 === 404 && body8.error === void 0) return new WorkspaceError(404, "this workspace does not take traces", "ancha import --offline <trace file> makes the test on this computer; nothing is uploaded", true);
264831
- const error65 = serverError(status6, body8, { message: `${path9}: HTTP ${status6}`, code: "USAGE" });
264910
+ const contract = typeof body8.error === "string" ? { error: { message: body8.error, code: body8.code, kind: body8.kind, hint: body8.hint, reference: body8.reference } } : body8;
264911
+ const error65 = serverError(status6, contract, { message: `${path9}: HTTP ${status6}`, code: "USAGE" });
264912
+ if (status6 === 409 && error65.message === "this trace is still arriving; try again in a minute") error65.kind = "retry";
264832
264913
  return Object.assign(new WorkspaceError(status6, error65.message, error65.hint), { code: error65.code, kind: error65.kind, ...error65.reference && { reference: error65.reference } });
264833
264914
  }
264834
264915
  function notInWorkspace(error65) {
264835
264916
  return error65 instanceof WorkspaceError && error65.status === 404 && !error65.noTraces;
264836
264917
  }
264918
+ var traceRequestMs = (bytes4 = 0) => Math.min(3e5, 3e4 + Math.ceil(bytes4 / 65536) * 1e3);
264919
+ async function traceRequest(url4, init, receipt2 = () => "No workspace uploads have been confirmed by this command.") {
264920
+ const controller = new AbortController(), ms2 = traceRequestMs(new URL(url4).pathname === "/v1/imports" && typeof init.body === "string" ? Buffer.byteLength(init.body) : 0);
264921
+ const timer = setTimeout(() => controller.abort(), ms2);
264922
+ try {
264923
+ const res = await fetch(url4, { ...init, signal: controller.signal });
264924
+ const text31 = await res.text();
264925
+ let body8 = {};
264926
+ try {
264927
+ const parsed5 = JSON.parse(text31);
264928
+ if (parsed5 && typeof parsed5 === "object" && !Array.isArray(parsed5)) body8 = parsed5;
264929
+ } catch {
264930
+ }
264931
+ return { res, body: body8 };
264932
+ } catch (cause) {
264933
+ throw new AnchaError(
264934
+ "SERVER_UNREACHABLE",
264935
+ `The workspace did not answer. ${receipt2()} The interrupted request may have been saved. Running the same command again is safe.`,
264936
+ { kind: "retry", hint: "run the same command again; traces already in the workspace are reported as already imported", cause }
264937
+ );
264938
+ } finally {
264939
+ clearTimeout(timer);
264940
+ }
264941
+ }
264837
264942
  async function workspaceApi(ctx, hint = "run ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY") {
264838
264943
  const workspace4 = await uploadWorkspace(ctx, { message: "not logged in to a workspace", hint });
264839
264944
  const key5 = await apiKeyFor(workspace4, ctx.io.env);
264840
264945
  if (key5 === void 0) throw authError(workspace4, { keySent: false });
264841
264946
  const origin = new URL(workspace4).origin;
264947
+ const traces = /* @__PURE__ */ new Set(), tests = /* @__PURE__ */ new Set();
264948
+ const receipt2 = () => `Workspace receipts from this command: traces ${[...traces].join(", ") || "none confirmed"}; saved tests ${[...tests].join(", ") || "none confirmed"}.`;
264842
264949
  return async (path9, init = {}) => {
264843
- const res = await fetch(`${origin}${path9}`, { ...init, headers: { authorization: `Bearer ${key5}`, "x-ancha-trace-import": "1", ...init.headers } }).catch((cause) => {
264844
- throw new AnchaError("SERVER_UNREACHABLE", "The workspace did not answer.", { cause });
264845
- });
264846
- const body8 = await res.json().catch(() => ({}));
264950
+ const { res, body: body8 } = await traceRequest(`${origin}${path9}`, { ...init, headers: { authorization: `Bearer ${key5}`, "x-ancha-trace-import": "1", ...init.headers } }, receipt2);
264847
264951
  if (res.status === 401) throw serverError(res.status, body8, authError(workspace4, { keySent: true }));
264848
264952
  if (!res.ok) throw workspaceError(res.status, body8, path9);
264953
+ if (path9.startsWith("/v1/imports")) for (const trace2 of body8.traces ?? []) traces.add(trace2.id);
264954
+ if (init.method === "POST" && body8.world?.id) tests.add(body8.world.id);
264849
264955
  return body8;
264850
264956
  };
264851
264957
  }
@@ -265101,6 +265207,7 @@ async function nextLines(ctx, paths3, dest, connection4) {
265101
265207
  var testName = (id15) => /^trace-([0-9a-f]{8,})$/i.exec(id15.trim())?.[1];
265102
265208
  var AT_ONCE = 4;
265103
265209
  var MB4 = 1024 * 1024;
265210
+ var classifiedSkip = (skip, error65) => ({ code: error65?.code ?? "USAGE", kind: error65?.kind ?? "fix", ...skip });
265104
265211
  async function atOnce(items2, n2, fn) {
265105
265212
  const out = new Array(items2.length);
265106
265213
  let next2 = 0;
@@ -265130,14 +265237,15 @@ async function projectAgent(ctx) {
265130
265237
  return configured ? agentName(ctx.io.cwd) : void 0;
265131
265238
  }
265132
265239
  async function sendTraces(ctx, api4, units, name5, options5, maxBytes) {
265133
- const packed = packUploads(units, name5, maxBytes), skipped = [...packed.skipped], uploads = [];
265240
+ const packed = packUploads(units, name5, maxBytes), skipped = packed.skipped.map((s3) => classifiedSkip(s3)), uploads = [];
265134
265241
  const sent2 = [], fileOf = (unit) => units.find((u) => u.id === unit)?.files[0];
265135
265242
  const queue = [...packed.uploads];
265136
- let stop, first2;
265243
+ const alreadyImported = [];
265244
+ let stop, stopError, first2;
265137
265245
  for (let i = 0; i < queue.length; i++) {
265138
265246
  const upload6 = queue[i];
265139
265247
  if (stop) {
265140
- skipped.push(...upload6.ids.map((id15) => ({ trace: id15, file: fileOf(id15), reason: stop })));
265248
+ skipped.push(...upload6.ids.map((id15) => classifiedSkip({ trace: id15, file: fileOf(id15), reason: stop }, stopError)));
265141
265249
  continue;
265142
265250
  }
265143
265251
  const size2 = upload6.bytes >= MB4 / 10 ? `${(upload6.bytes / MB4).toFixed(1)} MB` : `${Math.max(1, Math.round(upload6.bytes / 1024))} KB`;
@@ -265154,17 +265262,21 @@ async function sendTraces(ctx, api4, units, name5, options5, maxBytes) {
265154
265262
  }
265155
265263
  if (![400, 413, 429].includes(error65.status)) throw error65;
265156
265264
  first2 ??= error65;
265157
- if (error65.status === 429) stop = `${error65.message} (the workspace takes 600 uploads an hour)`;
265158
- skipped.push(...upload6.ids.map((id15) => ({ trace: id15, file: fileOf(id15), reason: stop ?? error65.message })));
265265
+ if (error65.status === 429) {
265266
+ stop = `${error65.message} (the workspace takes 600 uploads an hour)`;
265267
+ stopError = error65;
265268
+ }
265269
+ skipped.push(...upload6.ids.map((id15) => classifiedSkip({ trace: id15, file: fileOf(id15), reason: stop ?? error65.message }, error65)));
265159
265270
  continue;
265160
265271
  }
265161
265272
  uploads.push(upload6);
265273
+ alreadyImported.push(...answer.traces.filter((t) => t.alreadyImported).map((t) => t.id));
265162
265274
  answer.traces.forEach((t, n2) => sent2.push({ id: t.id, file: fileOf(answer.traces.length === upload6.ids.length ? upload6.ids[n2] : upload6.ids.find((id15) => t.trace?.endsWith(`:${id15}`))) }));
265163
265275
  }
265164
265276
  if (sent2.length > 1) ctx.out.info(`making ${plural6(sent2.length, "test")}, ${AT_ONCE} at a time`);
265165
265277
  const answered = options5.expect !== void 0 || options5.answer.length > 0 || Boolean(options5.resetAnswers);
265166
265278
  const results = await atOnce(sent2, AT_ONCE, async ({ id: id15, file: file3 }) => {
265167
- const skip = (error65) => ({ skip: { trace: id15, ...file3 && { file: file3 }, reason: error65.message }, error: error65 });
265279
+ const skip = (error65) => ({ skip: classifiedSkip({ trace: id15, ...file3 && { file: file3 }, reason: error65.message }, error65), error: error65 });
265168
265280
  let changes;
265169
265281
  try {
265170
265282
  changes = await guard(ctx, resolve50(ctx.io.cwd, options5.dest, `trace-${id15.slice(0, 8)}`), options5.force);
@@ -265190,7 +265302,7 @@ async function sendTraces(ctx, api4, units, name5, options5, maxBytes) {
265190
265302
  skipped.push(r2.skip);
265191
265303
  first2 ??= r2.error;
265192
265304
  }
265193
- return { made: results.flatMap((r2) => r2.made ? [r2.made] : []), skipped, uploads, sent: sent2.length, files: options5.files, first: first2 };
265305
+ return { alreadyImported, made: results.flatMap((r2) => r2.made ? [r2.made] : []), skipped, uploads, sent: sent2.length, files: options5.files, first: first2 };
265194
265306
  }
265195
265307
  function outcomeOf3(world5) {
265196
265308
  const production3 = world5.summary?.production ?? {}, values3 = checksOf2(world5.scene).map((c) => production3[c.id] ?? "unknown");
@@ -265228,6 +265340,7 @@ async function uploadReport(ctx, done, from, dest) {
265228
265340
  ...m.written.kept.length && { kept: m.written.kept }
265229
265341
  })),
265230
265342
  skipped: done.skipped,
265343
+ alreadyImported: done.alreadyImported,
265231
265344
  questions: asking.length,
265232
265345
  uploads: done.uploads.map((u) => ({ format: u.format, traces: u.ids.length, files: u.files, bytes: u.bytes })),
265233
265346
  ...connection4 && { connection: connection4 },
@@ -265251,7 +265364,8 @@ async function uploadReport(ctx, done, from, dest) {
265251
265364
  });
265252
265365
  const short = (m) => m.world.name;
265253
265366
  return [
265254
- `Uploaded ${plural6(done.sent, "trace")} from ${from}: ${made}${done.skipped.length ? `; ${done.skipped.length} skipped` : ""}`,
265367
+ `Uploaded ${plural6(done.sent, "trace")} from ${from}: ${made}${done.skipped.length ? `; ${done.skipped.length} skipped (${ERROR_KINDS.map((kind2) => [kind2, done.skipped.filter((s3) => s3.kind === kind2).length]).filter(([, n2]) => n2).map(([kind2, n2]) => `${n2} ${kind2}`).join(", ")})` : ""}`,
265368
+ ...done.alreadyImported.map((id15) => ` already imported: trace ${id15}`),
265255
265369
  ...rows35.length ? formatTable(rows35).split("\n").map((line2) => ` ${line2}`) : [],
265256
265370
  // Each test's evidence under its name when there are several.
265257
265371
  ...tests.flatMap((m) => {
@@ -265269,10 +265383,12 @@ async function uploadReport(ctx, done, from, dest) {
265269
265383
  });
265270
265384
  }
265271
265385
  async function importJson(ctx, done) {
265272
- for (const s3 of done.skipped) if (s3.trace) ctx.out.event({ event: "trace_skipped", trace: s3.trace, reason: s3.reason });
265386
+ for (const s3 of done.skipped) if (s3.trace) ctx.out.event({ event: "trace_skipped", trace: s3.trace, reason: s3.reason, code: s3.code, kind: s3.kind });
265273
265387
  for (const { world: world5, written } of done.made) {
265274
265388
  const where3 = relative25(ctx.io.cwd, written.scene) || written.scene, connection4 = await connectionFor(ctx, [written.scene], where3);
265275
265389
  ctx.out.result({
265390
+ alreadyImported: done.alreadyImported,
265391
+ skipped: done.skipped,
265276
265392
  connection: connection4,
265277
265393
  world: world5.id,
265278
265394
  name: world5.name,
@@ -265475,10 +265591,10 @@ function registerTraces(program2, ctx) {
265475
265591
  }
265476
265592
  expectOne(options5.expect, units.length);
265477
265593
  const done = await sendTraces(ctx, api4, units, name5, { dest: options5.dest, ...options5.force && { force: true }, ...options5.expect !== void 0 && { expect: options5.expect }, answer: [], files: read7.length, agent: await projectAgent(ctx) });
265478
- done.skipped.unshift(...fetchSkipped, ...skipped);
265594
+ done.skipped.unshift(...[...fetchSkipped, ...skipped].map((s3) => classifiedSkip(s3)));
265479
265595
  if (!done.made.length) {
265480
265596
  if (done.skipped.length === 1 && done.first instanceof AnchaError) throw done.first;
265481
- throw new AnchaError("USAGE", `none of the ${plural6(done.sent || units.length, "trace")} made a test`, { hint: done.skipped.slice(0, 5).map((s3) => `${s3.trace ? `trace ${s3.trace.slice(0, 8)}` : s3.file}: ${s3.reason}`).join("; ") });
265597
+ throw new AnchaError("USAGE", `none of the ${plural6(done.sent || units.length, "trace")} made a test`, { kind: done.skipped.some((s3) => s3.kind === "ours") ? "ours" : done.skipped.every((s3) => s3.kind === "retry") ? "retry" : "fix", hint: done.skipped.slice(0, 5).map((s3) => `${s3.trace ? `trace ${s3.trace.slice(0, 8)}` : s3.file}: ${s3.reason}`).join("; ") });
265482
265598
  }
265483
265599
  await uploadReport(ctx, done, options5.from !== void 0 ? options5.from === "langfuse" ? "Langfuse" : "LangSmith" : read7.length === 1 ? read7[0] : plural6(read7.length, "file"), options5.dest);
265484
265600
  });
@@ -265497,6 +265613,7 @@ function registerTraces(program2, ctx) {
265497
265613
  if (!units.length) throw new AnchaError("USAGE", `${source.label}: ${skipped[0]?.reason ?? "it holds no traces"}`, { hint: "use Ancha Trace IR JSONL, OTLP JSON, or a Langfuse or LangSmith export; ancha docs traces" });
265498
265614
  expectOne(options5.expect, units.length);
265499
265615
  const done = await sendTraces(ctx, api4, units, source.name, { ...options5, files: 1, agent: await projectAgent(ctx) });
265616
+ done.skipped.unshift(...skipped.map((s3) => classifiedSkip(s3)));
265500
265617
  if (!done.made.length) throw done.first ?? new AnchaError("USAGE", `${source.label}: ${done.skipped[0]?.reason ?? "no trace made a test"}`);
265501
265618
  if (ctx.out.json) await importJson(ctx, done);
265502
265619
  else await uploadReport(ctx, done, source.label, options5.dest);
@@ -266077,8 +266194,8 @@ ${result.verification?.message ?? "Use ancha report or ancha explain to inspect
266077
266194
  function registerAgent(program2, ctx) {
266078
266195
  const registry2 = () => new AgentRegistry(ctx.io.cwd);
266079
266196
  const command = program2.command("agent").description("upload this project's agent to the cloud (agent upload), or save and test a local agent against automatically prepared tool worlds");
266080
- command.command("upload").description("install this project's agent in a cloud machine, as a cloud run does, and start it once with a task (also: ancha doctor --on cloud)").option("--agent <command>", "override the configured agent command").action(async (opts) => {
266081
- const result = await uploadAgent(ctx, { ...opts.agent !== void 0 && { agent: opts.agent }, timeout: "10s", on: "cloud" });
266197
+ command.command("upload").description("install this project's agent in a cloud machine, as a cloud run does, and start it once with a task (also: ancha doctor --on cloud)").option("--agent <command>", "override the configured agent command").option("--idempotency-key <key>", "retry safely: the same key and the same project return the upload the workspace accepted instead of starting another").action(async (opts) => {
266198
+ const result = await uploadAgent(ctx, { ...opts.agent !== void 0 && { agent: opts.agent }, ...opts.idempotencyKey !== void 0 && { idempotencyKey: opts.idempotencyKey }, timeout: "10s", on: "cloud" });
266082
266199
  ctx.exitCode = result.exitCode;
266083
266200
  ctx.out.result(result.report, () => renderUpload(result.report));
266084
266201
  });
@@ -18,7 +18,7 @@ Add `--json` to every command. Runs print NDJSON events that end with `run_finis
18
18
  <!-- ancha:first-steps -->
19
19
  1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.
20
20
  ```sh
21
- ancha --version || npm install -g @ancha-labs/cli
21
+ npm install -g @ancha-labs/cli
22
22
  ancha login
23
23
  ```
24
24
  2. **Set up the project.** Run it in the agent's project: it finds the command that starts the agent and how the agent takes its task, and writes both to `ancha.yaml`. It installs and runs nothing.
@@ -3,7 +3,7 @@
3
3
 
4
4
  1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.
5
5
  ```sh
6
- ancha --version || npm install -g @ancha-labs/cli
6
+ npm install -g @ancha-labs/cli
7
7
  ancha login
8
8
  ```
9
9
  2. **Set up the project.** Run it in the agent's project: it finds the command that starts the agent and how the agent takes its task, and writes both to `ancha.yaml`. It installs and runs nothing.
@@ -11,7 +11,7 @@ Without `--on`, a project with `ancha.yaml` (or `--config`) runs in the workspac
11
11
  <!-- ancha:first-steps -->
12
12
  1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.
13
13
  ```sh
14
- ancha --version || npm install -g @ancha-labs/cli
14
+ npm install -g @ancha-labs/cli
15
15
  ancha login
16
16
  ```
17
17
  2. **Set up the project.** Run it in the agent's project: it finds the command that starts the agent and how the agent takes its task, and writes both to `ancha.yaml`. It installs and runs nothing.
@@ -9,7 +9,7 @@ Requirements: Node 24 or newer. Install once with `npm install -g @ancha-labs/cl
9
9
  <!-- ancha:first-steps -->
10
10
  1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.
11
11
  ```sh
12
- ancha --version || npm install -g @ancha-labs/cli
12
+ npm install -g @ancha-labs/cli
13
13
  ancha login
14
14
  ```
15
15
  2. **Set up the project.** Run it in the agent's project: it finds the command that starts the agent and how the agent takes its task, and writes both to `ancha.yaml`. It installs and runs nothing.
@@ -22222,7 +22222,7 @@ function starterCount(tool, key, state) {
22222
22222
  }
22223
22223
 
22224
22224
  // frontend/src/generated/coding-agent-skill.ts
22225
- var codingAgentSkill = "---\nname: ancha\ndescription: Test, debug and fix an AI agent (a Slack bot, a support or on-call agent) against stateful replicas of the tools it uses, built from its production traces, and prove a fix with graded runs in the cloud. Use when asked to test an agent with Ancha, or in a repository that has ancha.yaml.\n---\n\n# Ancha\n\nAncha gives an AI agent the other side of its job: stateful replicas of the tools it uses (Slack, GitHub, Datadog, PagerDuty and more), seeded with one fictional company or rebuilt from a production trace, and checks that grade every attempt from the agent's calls and the world's end state. The verdict comes from the world, not from mocks you wrote yourself. `ancha run --on cloud` runs each attempt on a fresh machine of its own in Ancha's cloud.\n\n## Run the CLI\n\nBefore the CLI is installed, run every command as `npx -y @ancha-labs/cli <command>`. After `npm install -g @ancha-labs/cli` (Node 24 or newer), run `ancha <command>`. Never run `npx` with the bare name `ancha`: that npm name is not this package.\n\nAdd `--json` to every command. Runs print NDJSON events that end with `run_finished`; `ancha traces upload` prints the tests it made. `env list` and `sandbox list` return arrays; trace commands use the fields described in `ancha docs traces`. `ancha schema <kind> --json` prints the JSON Schema of `ancha.yaml`, test files (`scene.yaml`) and these outputs. If your command can time out, give `ancha run` an `--idempotency-key <key>`: running it again with the same key returns the same run instead of starting another.\n\n## First steps\n\n<!-- ancha:first-steps -->\n1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.\n ```sh\n ancha --version || npm install -g @ancha-labs/cli\n ancha login\n ```\n2. **Set up the project.** Run it in the agent's project: it finds the command that starts the agent and how the agent takes its task, and writes both to `ancha.yaml`. It installs and runs nothing.\n ```sh\n ancha init\n ```\n - To name the command yourself: `ancha init --agent \"<the command that starts your agent>\"`.\n - To name its tools yourself (NetSuite, Slack, ...): `ancha init --tools netsuite,slack`.\n - **Composio agents.** Init detects Python `composio` / `composio_client` and TypeScript `@composio/core`, and finds tools from explicit toolkit lists and tool slugs. It writes each available Composio route under `agent.routes` and adds `COMPOSIO_API_KEY` to `agent.pass_env`, preserving existing settings. The world of each test decides which routed tools answer there.\n - When init asks which tools the agent reaches through Composio, ask the user which tools they use. Set `agent.routes.<tool>: composio` for each routed tool (for example, `agent.routes.quickbooks: composio`) and add `COMPOSIO_API_KEY` to `agent.pass_env` in `ancha.yaml`. Configure the Composio client to read `COMPOSIO_BASE_URL` from the attempt environment.\n - For a routed agent with no tests or traces, init writes a starter test that reads from each routed tool, plus the QuickBooks examples when the agent uses QuickBooks. Routed tests run in the cloud: with `COMPOSIO_API_KEY` in your shell, the steps below store it, upload the agent and run the tests.\n3. **Point the agent at Ancha's tools.** In a test, the agent calls Ancha instead of production:\n - Its clients for Slack, GitHub and the other tools Ancha replicates take the URLs and credentials Ancha supplies: `ancha connect <tool>` prints the settings.\n - Its own functions: wrap them with `wrapTools` from `@ancha-labs/tools` (`ancha.wrap_tools` in Python), or serve them over MCP.\n4. **Store the key it needs.** The agent's own model key, read from your shell, never from an argument: it is stored in your workspace and named under `agent.pass_env` in `ancha.yaml`, so the agent gets it in every cloud attempt.\n ```sh\n ancha secrets set ANTHROPIC_API_KEY\n ```\n5. **Upload your agent.** A fresh machine in the cloud installs the project's dependencies and starts the agent once with a task. It says the agent is ready, or shows the end of its log.\n ```sh\n ancha agent upload\n ```\n - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.\n6. **Without production traces.** For an agent that calls NetSuite directly, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests: 10 read tasks and 15 write workflows. For an agent that uses QuickBooks, it writes Pellmont Building Services' 2025 books and two tests: `pellmont-duplicates` reports the duplicate vendors, the invoices and bills entered twice and the money at stake without changing the books, and `pellmont-approved-merge` merges the three duplicate vendor pairs as approved and changes nothing else.\n - Variants: once `pellmont-duplicates` passes, `ancha test vary ancha/tests/pellmont-duplicates.yaml` writes ten variants of it, each changing one thing in the books with the expected findings recalculated; run them with the command it prints.\n - Your data: `ancha world import netsuite <your exports> --id <id>` reads REST record JSON, SuiteQL results and saved search CSV into `ancha/worlds/<id>.yaml`; check it with `ancha world validate`. To write the seed yourself, `ancha twins seed netsuite` lists its fields.\n - Your evals: `ancha test import <file>` (JSONL, JSON, CSV or YAML with a question and an expected answer) writes tests for the only world in `ancha/worlds/`, or the one `--world <id>` names; with none, `ancha init --on local --template starter` adds one.\n - One test from a sentence: `ancha test new \"<sentence>\" --world <id>`.\n7. **Upload traces.** A file or a folder of traces, runs that went fine and runs that failed: each trace becomes a test, in `scenes/from-traces/` and in your workspace.\n ```sh\n ancha traces upload ./traces\n ```\n - From Langfuse or LangSmith, with your keys on this computer: `ancha traces upload --from langfuse --limit 50`, or `--from langsmith`.\n - A trace of a run that went wrong can say what went wrong: `ancha traces upload <trace file> --expect \"<what went wrong>\"`, or for a test already made, `ancha pull <test id> --expect \"<what went wrong>\"`.\n - Traces your agent already sent to your workspace: `ancha traces`, then `ancha pull <trace id>`.\n - A test lists what one trace cannot settle: answer with `ancha pull <test id> --answer <question>=<answer>`.\n - A check marked `(optional)` is graded and shown, and the required checks decide the test; `ancha pull <test id> --answer checks.success=\"<end state>\"` makes completing the request decide it too.\n8. **Run your tests.** Every test, each attempt on a fresh machine. The run grades each attempt check by check and ends with the link to its result.\n ```sh\n ancha run\n ```\n - Your agent and its worlds run in the cloud, each attempt on a fresh machine of its own; a run keeps going when your laptop closes, and its results land in Runs.\n - `--attempts <n>` sets how many attempts each test gets, `--concurrency <n>` how many run at once.\n - `ancha wait <run id>` follows a run again from any terminal; `ancha explain <run id>` shows why a check failed.\n - `ancha status` shows which of these steps your workspace has done.\n9. **Fix the agent and keep the test.** Keep the failing run as the reference, fix the agent, and run again: exit 0 means every required check passes and nothing regressed.\n ```sh\n ancha baseline save before --from <run id>\n ancha run --compare before\n ```\n - Commit `scenes/from-traces/` so every run, in CI too, keeps it fixed.\n10. **Run it on this computer.** While you develop, `ancha run --on local` runs the agent and its worlds on this computer, with the same checks.\n ```sh\n ancha run --on local --attempts 1\n ```\n - Here the agent gets the keys in `agent.pass_env` from your shell, and model-graded checks need `OPENROUTER_API_KEY`.\n<!-- /ancha:first-steps -->\n\n## Cloud runs\n\n- `ancha run --on cloud` sends the project as one bundle: the agent's files, without hidden directories, dependencies or credential-like files, and its tests with their worlds and checks, which stay with the grader and never reach the agent. Each attempt's machine installs the dependencies, runs the agent and grades it with the same engine as a run on this computer. `--attempts <n>` sets the attempts per test, `--concurrency <n>` how many run at once.\n- The agent gets the workspace's secrets for the names in `agent.pass_env`, and its network reaches its tools and its model providers. Model-graded checks and the people in a world run on the workspace's model credit.\n- The `run_finished` event carries `url` (the result in the workspace) and `summary`, with `counts` of the attempts: requested, completed, invalid, skipped and cancelled. Interrupting the command stops the following, never the run: `ancha wait <run id>` follows it again, and `--detach` returns once the run is accepted.\n- `ancha explain <run id> --json` shows each failed check: what was expected, what happened, and the calls and world events behind it. Read it before guessing from the code; many bugs only show up with the world's data and timing.\n- When every attempt ended before the agent did anything (it exited within seconds without a call, or its command could not start), the run, `ancha wait` and `ancha explain` say that first: \"Your agent didn't run\", the end of its log once, and the likely fix read from it, such as the `agent.env` line that gives the agent its task under the name it reads. `agentNeverRan` in the JSON carries the same. Make that fix first: the failed checks follow from it, and `ancha explain <run id> --all` lists them.\n- `ancha status --json` shows the workspace's three steps (agent uploaded, tests added, tests run in the cloud) and the next command. In CI, `ANCHA_SERVER_URL` and `ANCHA_API_KEY` replace the login. More: `ancha docs cloud`.\n\n## An app, not a command\n\nIf the AI feature lives inside an app (a web app or API server with its database, workers and scheduled jobs), don't wrap it in `agent.command`. Ancha starts the app once per attempt with `agent.start`, waits for `agent.ready_url`, delivers the tools' events to `agent.url`, and a scene's `world_rules.app_calls` call the app's own routes, such as its cron jobs, at a time. Read `ancha docs apps` before writing `ancha.yaml`. The start script gives the app a clean database, cache and seed every attempt: a new world has new URLs and tokens, and stale rows or sync cursors make an app silently do nothing.\n\n## More from production traces\n\n`ancha traces upload <file or folder> --json` sends the traces to the workspace, which rebuilds each one's world and checks, and writes each test to `scenes/from-traces/<name>/scene.yaml`: runs that went fine and runs that failed. `--from langfuse` or `--from langsmith` takes the newest traces there instead (`--limit`, `--since`), with the keys in this shell. For one trace of a failure, `--expect \"<what went wrong>\"` adds a check for it. A test lists the questions one trace cannot settle, each with the default it uses. Ask the user for the answers; don't guess them. Pass them with `ancha pull <test id> --answer <question>=<value>`. `ancha import --offline <trace file> --json` makes the tests on this computer instead, one per conversation, and uploads nothing; there, `--answer` and `--force` go on the import.\n\nA test from a run that failed should fail the same way production did. If it doesn't, run it on this computer: `ancha traces diff <trace file> latest` shows the calls production made and the attempt didn't, and the import also lists the app's own setup calls, which the start script or an `app_call` has to make.\n\nIf the user's workspace takes traces (their agents send them to it), each trace becomes a test there: `ancha pull --all --json` writes every test that is turned on (`--agent <name>` for one agent's), `ancha traces --failed --json` lists the ones where production failed a check, `ancha traces show <id> --json` previews the test, and `ancha pull <id> --json` writes one, with `--answer` for its questions. Checks you add to a pulled `scene.yaml` stay when you pull a newer version; any other edit stops the pull. More: `ancha docs traces`.\n\n## Other tests\n\nThe starter test `ancha init` writes when `scenes/` holds no tests only proves that the agent reaches each tool. For the agent's real job beyond its traces, `ancha test new \"<the test in one sentence>\" --json` drafts a test with people for the project's world (`ancha init --intent \"<company and scenario>\"` makes the world and a first test). Review its checks before you run it. To write a seed yourself, `ancha twins seed <tool> --json` prints the tool's fields, an example that validates as written, and the checks a test can make on it. More: `ancha docs scenes`.\n\n## The rule\n\nFix the agent, not the tests or their checks. `ancha.yaml` says how to start the agent and give it its task and keys: change it for that, never to make a check pass. The exception is a check that is wrong for the real API, such as a method the official SDK never sends. Then don't quietly edit it: tell the user, show the evidence (the call from `ancha explain`, the vendor's documentation), and change it only with their agreement.\n\nNever give the agent under test the tests, checks, seeds or reference companions (`oracle.mjs`, `null.mjs`), and never point it at a real SaaS API.\n\n## What the agent gets\n\nEach attempt gives the agent its tools as environment variables, with fake credentials that only work against the replicas:\n\n- Slack: `SLACK_API_URL` (ends in `/api/`), `SLACK_BOT_TOKEN`\n- GitHub: `GITHUB_API_URL`, `GITHUB_TOKEN`\n- Datadog: `DATADOG_API_URL`, `DD_API_KEY`, `DD_APP_KEY`\n- PagerDuty: `PAGERDUTY_API_URL`, `PAGERDUTY_API_TOKEN`, `PAGERDUTY_FROM_EMAIL`, `PAGERDUTY_ROUTING_KEY`\n- the same pattern for the other tools in the world; `ANCHA_TASK` carries a command-line task, and `ANCHA_TASK_FILE` names a file holding it. An agent that reads its task under another name gets it with `agent.env: { MY_TASK: \"{{task}}\" }` (`{{task_file}}` for the file); `ancha init` writes that line when it finds the name.\n\n`ancha connect <tool> --lang ts|py` prints the SDK settings. `ancha twins coverage <tool>` lists the endpoints each replica implements.\n\nGoogle clients (`googleapis`, `@googleapis/*`) take the replica's URL in each call's options: `drive.files.list(params, { rootUrl: process.env.GOOGLE_DRIVE_API_URL + '/' })`. A `rootUrl` set on the client keeps only the host; Ancha still routes those calls by their token, but the client sends file uploads to www.googleapis.com.\n\nThe agent's own keys are the names in `agent.pass_env` in `ancha.yaml`, such as `agent.pass_env: [OPENAI_API_KEY]`, and `agent.env` sets fixed values, such as the path of a key file. In the cloud each name comes from the workspace's secrets (`ancha secrets set NAME`). `ancha run --on local` starts the agent on this computer instead, with this computer's network and those names from this shell (or `--pass-env NAME`); `--on docker` seals it in a container (`agent.execution: { mode: container, image: node:24-slim }`, which needs Docker). An agent without its model key stops at its first model call.\n\n## When something fails\n\n- Exit 1: a check failed or the comparison regressed (a single check's drop counts, see `comparison.droppedChecks`). Run `ancha explain <run id> --json`.\n- Exit 2: usage, config, test file or authentication error, or a cancelled cloud run. `AUTH_INVALID` means `ancha login` again or a valid `ANCHA_API_KEY`; `CONFIG_INVALID` naming a workspace secret means `ancha secrets set NAME`. Read the `hint`.\n- Exit 3: infrastructure, or an attempt the harness couldn't run or grade. It counts as invalid, never as a failed check, so it's not the agent's fault; run again, and `ancha agent upload --json` if it repeats.\n- Exit 4, only with `--strict`: an endpoint coverage error or a verdict using simulated tool answers. The summary names the tests, trials and evaluated checks using those answers. `ancha explain` lists endpoint errors; `ancha twins coverage <tool>` shows the endpoint inventory.\n\nRead the error's stable `code` and `message`, then follow its `hint` when provided. More: `ancha docs`, `ancha docs <topic>` for setup, run, traces, explain, compare, scenes, integrations, cloud and playgrounds, and https://docs.ancha.io/coding-agents.\n\nTell the user what you ran, where it ran, the pass rate, the evidence and the result link. Never claim a fix until `ancha run --compare` exits 0.\n";
22225
+ var codingAgentSkill = "---\nname: ancha\ndescription: Test, debug and fix an AI agent (a Slack bot, a support or on-call agent) against stateful replicas of the tools it uses, built from its production traces, and prove a fix with graded runs in the cloud. Use when asked to test an agent with Ancha, or in a repository that has ancha.yaml.\n---\n\n# Ancha\n\nAncha gives an AI agent the other side of its job: stateful replicas of the tools it uses (Slack, GitHub, Datadog, PagerDuty and more), seeded with one fictional company or rebuilt from a production trace, and checks that grade every attempt from the agent's calls and the world's end state. The verdict comes from the world, not from mocks you wrote yourself. `ancha run --on cloud` runs each attempt on a fresh machine of its own in Ancha's cloud.\n\n## Run the CLI\n\nBefore the CLI is installed, run every command as `npx -y @ancha-labs/cli <command>`. After `npm install -g @ancha-labs/cli` (Node 24 or newer), run `ancha <command>`. Never run `npx` with the bare name `ancha`: that npm name is not this package.\n\nAdd `--json` to every command. Runs print NDJSON events that end with `run_finished`; `ancha traces upload` prints the tests it made. `env list` and `sandbox list` return arrays; trace commands use the fields described in `ancha docs traces`. `ancha schema <kind> --json` prints the JSON Schema of `ancha.yaml`, test files (`scene.yaml`) and these outputs. If your command can time out, give `ancha run` an `--idempotency-key <key>`: running it again with the same key returns the same run instead of starting another.\n\n## First steps\n\n<!-- ancha:first-steps -->\n1. **Install the CLI and sign in.** It needs Node 24 or newer. Approve this computer in the browser, once.\n ```sh\n npm install -g @ancha-labs/cli\n ancha login\n ```\n2. **Set up the project.** Run it in the agent's project: it finds the command that starts the agent and how the agent takes its task, and writes both to `ancha.yaml`. It installs and runs nothing.\n ```sh\n ancha init\n ```\n - To name the command yourself: `ancha init --agent \"<the command that starts your agent>\"`.\n - To name its tools yourself (NetSuite, Slack, ...): `ancha init --tools netsuite,slack`.\n - **Composio agents.** Init detects Python `composio` / `composio_client` and TypeScript `@composio/core`, and finds tools from explicit toolkit lists and tool slugs. It writes each available Composio route under `agent.routes` and adds `COMPOSIO_API_KEY` to `agent.pass_env`, preserving existing settings. The world of each test decides which routed tools answer there.\n - When init asks which tools the agent reaches through Composio, ask the user which tools they use. Set `agent.routes.<tool>: composio` for each routed tool (for example, `agent.routes.quickbooks: composio`) and add `COMPOSIO_API_KEY` to `agent.pass_env` in `ancha.yaml`. Configure the Composio client to read `COMPOSIO_BASE_URL` from the attempt environment.\n - For a routed agent with no tests or traces, init writes a starter test that reads from each routed tool, plus the QuickBooks examples when the agent uses QuickBooks. Routed tests run in the cloud: with `COMPOSIO_API_KEY` in your shell, the steps below store it, upload the agent and run the tests.\n3. **Point the agent at Ancha's tools.** In a test, the agent calls Ancha instead of production:\n - Its clients for Slack, GitHub and the other tools Ancha replicates take the URLs and credentials Ancha supplies: `ancha connect <tool>` prints the settings.\n - Its own functions: wrap them with `wrapTools` from `@ancha-labs/tools` (`ancha.wrap_tools` in Python), or serve them over MCP.\n4. **Store the key it needs.** The agent's own model key, read from your shell, never from an argument: it is stored in your workspace and named under `agent.pass_env` in `ancha.yaml`, so the agent gets it in every cloud attempt.\n ```sh\n ancha secrets set ANTHROPIC_API_KEY\n ```\n5. **Upload your agent.** A fresh machine in the cloud installs the project's dependencies and starts the agent once with a task. It says the agent is ready, or shows the end of its log.\n ```sh\n ancha agent upload\n ```\n - The install follows the project's own manifests and lockfiles; `agent.install` in `ancha.yaml` sets the command instead.\n6. **Without production traces.** For an agent that calls NetSuite directly, `ancha init` writes a NetSuite world of a private-equity portfolio company (four subsidiaries, two currencies, thousands of transactions) and 25 tests: 10 read tasks and 15 write workflows. For an agent that uses QuickBooks, it writes Pellmont Building Services' 2025 books and two tests: `pellmont-duplicates` reports the duplicate vendors, the invoices and bills entered twice and the money at stake without changing the books, and `pellmont-approved-merge` merges the three duplicate vendor pairs as approved and changes nothing else.\n - Variants: once `pellmont-duplicates` passes, `ancha test vary ancha/tests/pellmont-duplicates.yaml` writes ten variants of it, each changing one thing in the books with the expected findings recalculated; run them with the command it prints.\n - Your data: `ancha world import netsuite <your exports> --id <id>` reads REST record JSON, SuiteQL results and saved search CSV into `ancha/worlds/<id>.yaml`; check it with `ancha world validate`. To write the seed yourself, `ancha twins seed netsuite` lists its fields.\n - Your evals: `ancha test import <file>` (JSONL, JSON, CSV or YAML with a question and an expected answer) writes tests for the only world in `ancha/worlds/`, or the one `--world <id>` names; with none, `ancha init --on local --template starter` adds one.\n - One test from a sentence: `ancha test new \"<sentence>\" --world <id>`.\n7. **Upload traces.** A file or a folder of traces, runs that went fine and runs that failed: each trace becomes a test, in `scenes/from-traces/` and in your workspace.\n ```sh\n ancha traces upload ./traces\n ```\n - From Langfuse or LangSmith, with your keys on this computer: `ancha traces upload --from langfuse --limit 50`, or `--from langsmith`.\n - A trace of a run that went wrong can say what went wrong: `ancha traces upload <trace file> --expect \"<what went wrong>\"`, or for a test already made, `ancha pull <test id> --expect \"<what went wrong>\"`.\n - Traces your agent already sent to your workspace: `ancha traces`, then `ancha pull <trace id>`.\n - A test lists what one trace cannot settle: answer with `ancha pull <test id> --answer <question>=<answer>`.\n - A check marked `(optional)` is graded and shown, and the required checks decide the test; `ancha pull <test id> --answer checks.success=\"<end state>\"` makes completing the request decide it too.\n8. **Run your tests.** Every test, each attempt on a fresh machine. The run grades each attempt check by check and ends with the link to its result.\n ```sh\n ancha run\n ```\n - Your agent and its worlds run in the cloud, each attempt on a fresh machine of its own; a run keeps going when your laptop closes, and its results land in Runs.\n - `--attempts <n>` sets how many attempts each test gets, `--concurrency <n>` how many run at once.\n - `ancha wait <run id>` follows a run again from any terminal; `ancha explain <run id>` shows why a check failed.\n - `ancha status` shows which of these steps your workspace has done.\n9. **Fix the agent and keep the test.** Keep the failing run as the reference, fix the agent, and run again: exit 0 means every required check passes and nothing regressed.\n ```sh\n ancha baseline save before --from <run id>\n ancha run --compare before\n ```\n - Commit `scenes/from-traces/` so every run, in CI too, keeps it fixed.\n10. **Run it on this computer.** While you develop, `ancha run --on local` runs the agent and its worlds on this computer, with the same checks.\n ```sh\n ancha run --on local --attempts 1\n ```\n - Here the agent gets the keys in `agent.pass_env` from your shell, and model-graded checks need `OPENROUTER_API_KEY`.\n<!-- /ancha:first-steps -->\n\n## Cloud runs\n\n- `ancha run --on cloud` sends the project as one bundle: the agent's files, without hidden directories, dependencies or credential-like files, and its tests with their worlds and checks, which stay with the grader and never reach the agent. Each attempt's machine installs the dependencies, runs the agent and grades it with the same engine as a run on this computer. `--attempts <n>` sets the attempts per test, `--concurrency <n>` how many run at once.\n- The agent gets the workspace's secrets for the names in `agent.pass_env`, and its network reaches its tools and its model providers. Model-graded checks and the people in a world run on the workspace's model credit.\n- The `run_finished` event carries `url` (the result in the workspace) and `summary`, with `counts` of the attempts: requested, completed, invalid, skipped and cancelled. Interrupting the command stops the following, never the run: `ancha wait <run id>` follows it again, and `--detach` returns once the run is accepted.\n- `ancha explain <run id> --json` shows each failed check: what was expected, what happened, and the calls and world events behind it. Read it before guessing from the code; many bugs only show up with the world's data and timing.\n- When every attempt ended before the agent did anything (it exited within seconds without a call, or its command could not start), the run, `ancha wait` and `ancha explain` say that first: \"Your agent didn't run\", the end of its log once, and the likely fix read from it, such as the `agent.env` line that gives the agent its task under the name it reads. `agentNeverRan` in the JSON carries the same. Make that fix first: the failed checks follow from it, and `ancha explain <run id> --all` lists them.\n- `ancha status --json` shows the workspace's three steps (agent uploaded, tests added, tests run in the cloud) and the next command. In CI, `ANCHA_SERVER_URL` and `ANCHA_API_KEY` replace the login. More: `ancha docs cloud`.\n\n## An app, not a command\n\nIf the AI feature lives inside an app (a web app or API server with its database, workers and scheduled jobs), don't wrap it in `agent.command`. Ancha starts the app once per attempt with `agent.start`, waits for `agent.ready_url`, delivers the tools' events to `agent.url`, and a scene's `world_rules.app_calls` call the app's own routes, such as its cron jobs, at a time. Read `ancha docs apps` before writing `ancha.yaml`. The start script gives the app a clean database, cache and seed every attempt: a new world has new URLs and tokens, and stale rows or sync cursors make an app silently do nothing.\n\n## More from production traces\n\n`ancha traces upload <file or folder> --json` sends the traces to the workspace, which rebuilds each one's world and checks, and writes each test to `scenes/from-traces/<name>/scene.yaml`: runs that went fine and runs that failed. `--from langfuse` or `--from langsmith` takes the newest traces there instead (`--limit`, `--since`), with the keys in this shell. For one trace of a failure, `--expect \"<what went wrong>\"` adds a check for it. A test lists the questions one trace cannot settle, each with the default it uses. Ask the user for the answers; don't guess them. Pass them with `ancha pull <test id> --answer <question>=<value>`. `ancha import --offline <trace file> --json` makes the tests on this computer instead, one per conversation, and uploads nothing; there, `--answer` and `--force` go on the import.\n\nA test from a run that failed should fail the same way production did. If it doesn't, run it on this computer: `ancha traces diff <trace file> latest` shows the calls production made and the attempt didn't, and the import also lists the app's own setup calls, which the start script or an `app_call` has to make.\n\nIf the user's workspace takes traces (their agents send them to it), each trace becomes a test there: `ancha pull --all --json` writes every test that is turned on (`--agent <name>` for one agent's), `ancha traces --failed --json` lists the ones where production failed a check, `ancha traces show <id> --json` previews the test, and `ancha pull <id> --json` writes one, with `--answer` for its questions. Checks you add to a pulled `scene.yaml` stay when you pull a newer version; any other edit stops the pull. More: `ancha docs traces`.\n\n## Other tests\n\nThe starter test `ancha init` writes when `scenes/` holds no tests only proves that the agent reaches each tool. For the agent's real job beyond its traces, `ancha test new \"<the test in one sentence>\" --json` drafts a test with people for the project's world (`ancha init --intent \"<company and scenario>\"` makes the world and a first test). Review its checks before you run it. To write a seed yourself, `ancha twins seed <tool> --json` prints the tool's fields, an example that validates as written, and the checks a test can make on it. More: `ancha docs scenes`.\n\n## The rule\n\nFix the agent, not the tests or their checks. `ancha.yaml` says how to start the agent and give it its task and keys: change it for that, never to make a check pass. The exception is a check that is wrong for the real API, such as a method the official SDK never sends. Then don't quietly edit it: tell the user, show the evidence (the call from `ancha explain`, the vendor's documentation), and change it only with their agreement.\n\nNever give the agent under test the tests, checks, seeds or reference companions (`oracle.mjs`, `null.mjs`), and never point it at a real SaaS API.\n\n## What the agent gets\n\nEach attempt gives the agent its tools as environment variables, with fake credentials that only work against the replicas:\n\n- Slack: `SLACK_API_URL` (ends in `/api/`), `SLACK_BOT_TOKEN`\n- GitHub: `GITHUB_API_URL`, `GITHUB_TOKEN`\n- Datadog: `DATADOG_API_URL`, `DD_API_KEY`, `DD_APP_KEY`\n- PagerDuty: `PAGERDUTY_API_URL`, `PAGERDUTY_API_TOKEN`, `PAGERDUTY_FROM_EMAIL`, `PAGERDUTY_ROUTING_KEY`\n- the same pattern for the other tools in the world; `ANCHA_TASK` carries a command-line task, and `ANCHA_TASK_FILE` names a file holding it. An agent that reads its task under another name gets it with `agent.env: { MY_TASK: \"{{task}}\" }` (`{{task_file}}` for the file); `ancha init` writes that line when it finds the name.\n\n`ancha connect <tool> --lang ts|py` prints the SDK settings. `ancha twins coverage <tool>` lists the endpoints each replica implements.\n\nGoogle clients (`googleapis`, `@googleapis/*`) take the replica's URL in each call's options: `drive.files.list(params, { rootUrl: process.env.GOOGLE_DRIVE_API_URL + '/' })`. A `rootUrl` set on the client keeps only the host; Ancha still routes those calls by their token, but the client sends file uploads to www.googleapis.com.\n\nThe agent's own keys are the names in `agent.pass_env` in `ancha.yaml`, such as `agent.pass_env: [OPENAI_API_KEY]`, and `agent.env` sets fixed values, such as the path of a key file. In the cloud each name comes from the workspace's secrets (`ancha secrets set NAME`). `ancha run --on local` starts the agent on this computer instead, with this computer's network and those names from this shell (or `--pass-env NAME`); `--on docker` seals it in a container (`agent.execution: { mode: container, image: node:24-slim }`, which needs Docker). An agent without its model key stops at its first model call.\n\n## When something fails\n\n- Exit 1: a check failed or the comparison regressed (a single check's drop counts, see `comparison.droppedChecks`). Run `ancha explain <run id> --json`.\n- Exit 2: usage, config, test file or authentication error, or a cancelled cloud run. `AUTH_INVALID` means `ancha login` again or a valid `ANCHA_API_KEY`; `CONFIG_INVALID` naming a workspace secret means `ancha secrets set NAME`. Read the `hint`.\n- Exit 3: infrastructure, or an attempt the harness couldn't run or grade. It counts as invalid, never as a failed check, so it's not the agent's fault; run again, and `ancha agent upload --json` if it repeats.\n- Exit 4, only with `--strict`: an endpoint coverage error or a verdict using simulated tool answers. The summary names the tests, trials and evaluated checks using those answers. `ancha explain` lists endpoint errors; `ancha twins coverage <tool>` shows the endpoint inventory.\n\nRead the error's stable `code` and `message`, then follow its `hint` when provided. More: `ancha docs`, `ancha docs <topic>` for setup, run, traces, explain, compare, scenes, integrations, cloud and playgrounds, and https://docs.ancha.io/coding-agents.\n\nTell the user what you ran, where it ran, the pass rate, the evidence and the result link. Never claim a fix until `ancha run --compare` exits 0.\n";
22226
22226
 
22227
22227
  // frontend/src/workspace-pages.ts
22228
22228
  var startSentence = "Set up Ancha for this agent: read https://app.ancha.io/llms.txt and follow its first steps.";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ancha-labs/cli",
3
- "version": "0.4.47",
3
+ "version": "0.4.48",
4
4
  "type": "module",
5
5
  "description": "Simulation playgrounds for agents: run your agent against stateful replicas of Slack, GitHub, Datadog and more, each attempt on a fresh cloud machine in your app.ancha.io workspace, or on your computer.",
6
6
  "bugs": {