@ancha-labs/cli 0.4.0 → 0.4.2

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
@@ -100287,7 +100287,7 @@ function readTools(cx, header4, records3, { examples: examples2 = [] } = {}) {
100287
100287
  }
100288
100288
  if (reads2.length) cx.ask("tools.pure", `Which of these tools only compute from their arguments, reading and changing nothing (a calculator, a formatter): ${reads2.join(", ")}? A test runs those itself when production never made the call.`, ["none", "all", reads2.join(",")], 0, { type: "text" });
100289
100289
  if (names3.length) {
100290
- cx.ask("tools.mcp", `Which of these tools does your agent reach over MCP: ${names3.join(", ")}? A test serves those at {{tools.mcp_url}}; the others the agent wraps.`, ["none", "all", names3.join(",")], 0, { type: "text" });
100290
+ cx.ask("tools.mcp", `Which of these tools does your agent reach over MCP: ${names3.join(", ")}? A test serves those at {{tools.mcp_url}}. The others are the agent's own functions: the test answers them when the agent wraps them (wrapTools from @ancha-labs/tools, ancha.wrap_tools in Python).`, ["none", "all", names3.join(",")], 0, { type: "text" });
100291
100291
  if (mcp.size) cx.note("answered", "tools.mcp", `your answer: ${[...mcp].join(", ")} over MCP`);
100292
100292
  }
100293
100293
  const cut = calls2.filter((r) => r.truncated).length;
@@ -123276,8 +123276,8 @@ async function handleApiCall(c) {
123276
123276
  const args = await readArgs(c.req.raw);
123277
123277
  ctx.signal?.throwIfAborted();
123278
123278
  if (name5 === "apps.connections.open" && c.req.method !== "POST") throw new SlackError("method_not_supported");
123279
- const access7 = reads.has(name5) ? withRead : withMutation;
123280
- const body6 = access7(ctx, () => {
123279
+ const access8 = reads.has(name5) ? withRead : withMutation;
123280
+ const body6 = access8(ctx, () => {
123281
123281
  const caller2 = authenticate(ctx, tokenOf(c.req.raw, args), name5 === "apps.connections.open");
123282
123282
  return method2(ctx, args, caller2);
123283
123283
  });
@@ -127993,8 +127993,8 @@ function handle(route11) {
127993
127993
  }
127994
127994
  }
127995
127995
  try {
127996
- const access7 = route11.read ? withRead : withMutation;
127997
- const result = access7(ctx, () => {
127996
+ const access8 = route11.read ? withRead : withMutation;
127997
+ const result = access8(ctx, () => {
127998
127998
  const caller2 = authenticate2(c, route11.scopes);
127999
127999
  const query11 = readQuery(c, route11.query ?? []);
128000
128000
  if (bodyError) throw bodyError;
@@ -131793,9 +131793,9 @@ function authenticate4(c, write4) {
131793
131793
  if (write4 && principal.readOnly) throw new AdsError2(403, "This credential cannot modify the account", "permission_denied");
131794
131794
  return { account: account8, seed: seed40, readOnly: principal.readOnly };
131795
131795
  }
131796
- function consumeQuota(ctx, access7, route11) {
131797
- const bucket2 = Math.floor(ctx.clock.elapsedMs() / 6e4), limits = access7.seed.limits;
131798
- const scopes3 = [{ name: access7.account.id, limit: limits.perAccountPerMinute }, { name: `${access7.account.id}:${route11}`, limit: limits.perEndpointPerMinute }];
131796
+ function consumeQuota(ctx, access8, route11) {
131797
+ const bucket2 = Math.floor(ctx.clock.elapsedMs() / 6e4), limits = access8.seed.limits;
131798
+ const scopes3 = [{ name: access8.account.id, limit: limits.perAccountPerMinute }, { name: `${access8.account.id}:${route11}`, limit: limits.perEndpointPerMinute }];
131799
131799
  for (const scope3 of scopes3) {
131800
131800
  const row = ctx.store.db.prepare("SELECT bucket,count FROM chatgpt_ads_quota WHERE scope=?").get(scope3.name);
131801
131801
  if (row?.bucket === bucket2 && row.count >= scope3.limit) throw new AdsError2(429, "Advertiser API request rate exceeded", "rate_limit_exceeded");
@@ -131815,10 +131815,10 @@ function handle2(route11) {
131815
131815
  }
131816
131816
  return withMutation(c.env.ctx, () => {
131817
131817
  try {
131818
- const access7 = authenticate4(c, route11.write ?? route11.method === "POST");
131819
- consumeQuota(c.env.ctx, access7, `${route11.method} ${route11.path}`);
131818
+ const access8 = authenticate4(c, route11.write ?? route11.method === "POST");
131819
+ consumeQuota(c.env.ctx, access8, `${route11.method} ${route11.path}`);
131820
131820
  if (parseError) throw parseError;
131821
- return withRead(c.env.ctx, () => new Response(JSON.stringify(route11.run(c, body6, access7)), { headers: { "content-type": "application/json; charset=utf-8" } }));
131821
+ return withRead(c.env.ctx, () => new Response(JSON.stringify(route11.run(c, body6, access8)), { headers: { "content-type": "application/json; charset=utf-8" } }));
131822
131822
  } catch (error64) {
131823
131823
  if (!(error64 instanceof AdsError2)) throw error64;
131824
131824
  return new Response(JSON.stringify({ error: { message: error64.message, type: error64.status === 401 ? "authentication_error" : error64.status === 429 ? "rate_limit_error" : "invalid_request_error", code: error64.code, param: error64.param } }), { status: error64.status, headers: { "content-type": "application/json; charset=utf-8", ...error64.status === 501 ? { [GAP_HEADER]: "1" } : {} } });
@@ -131826,8 +131826,8 @@ function handle2(route11) {
131826
131826
  });
131827
131827
  };
131828
131828
  }
131829
- function find(access7, kind, id12) {
131830
- const row = access7.seed[kind].find((item2) => item2.id === id12 && item2.accountId === access7.account.id);
131829
+ function find(access8, kind, id12) {
131830
+ const row = access8.seed[kind].find((item2) => item2.id === id12 && item2.accountId === access8.account.id);
131831
131831
  if (!row) throw new AdsError2(404, "Resource not found", "resource_not_found");
131832
131832
  return row;
131833
131833
  }
@@ -131852,15 +131852,15 @@ function canonical3(value5) {
131852
131852
  if (value5 && typeof value5 === "object") return `{${Object.entries(value5).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical3(v)}`).join(",")}}`;
131853
131853
  return JSON.stringify(value5);
131854
131854
  }
131855
- function idempotency(c, access7, kind, body6) {
131855
+ function idempotency(c, access8, kind, body6) {
131856
131856
  const key3 = c.req.header("idempotency-key");
131857
131857
  if (key3 === void 0) return { existing: void 0, remember: (_id) => {
131858
131858
  } };
131859
131859
  if (key3.length > 255 || !key3.trim()) invalid8("Idempotency-Key requires 1\u2013255 characters and non-whitespace");
131860
131860
  const fingerprint = createHash13("sha256").update(canonical3(body6)).digest("hex");
131861
- const prior = c.env.ctx.store.db.prepare("SELECT fingerprint,resource_id FROM chatgpt_ads_idempotency WHERE account_id=? AND kind=? AND key=?").get(access7.account.id, kind, key3);
131861
+ const prior = c.env.ctx.store.db.prepare("SELECT fingerprint,resource_id FROM chatgpt_ads_idempotency WHERE account_id=? AND kind=? AND key=?").get(access8.account.id, kind, key3);
131862
131862
  if (prior && prior.fingerprint !== fingerprint) throw new AdsError2(409, "Idempotency-Key was used with different input", "idempotency_conflict");
131863
- return { existing: prior ? find(access7, kind, prior.resource_id) : void 0, remember: (id12) => c.env.ctx.store.db.prepare("INSERT INTO chatgpt_ads_idempotency VALUES (?,?,?,?,?)").run(access7.account.id, kind, key3, fingerprint, id12) };
131863
+ return { existing: prior ? find(access8, kind, prior.resource_id) : void 0, remember: (id12) => c.env.ctx.store.db.prepare("INSERT INTO chatgpt_ads_idempotency VALUES (?,?,?,?,?)").run(access8.account.id, kind, key3, fingerprint, id12) };
131864
131864
  }
131865
131865
 
131866
131866
  // packages/server/src/twins/chatgpt-ads/routes.ts
@@ -131876,40 +131876,40 @@ function targeting2(value5, previous) {
131876
131876
  const parsed3 = parse5(ChatGPTAdsTargetingSchema, body6);
131877
131877
  return { ...parsed3, ...!Object.hasOwn(body6, "platforms") && previous?.platforms !== void 0 ? { platforms: previous.platforms } : {} };
131878
131878
  }
131879
- function bidding(value5, campaign2, access7) {
131879
+ function bidding(value5, campaign2, access8) {
131880
131880
  const body6 = object6(value5, "bidding_config");
131881
131881
  keys(body6, ["billing_event_type", "strategy", "max_bid_micros"], "bidding_config");
131882
131882
  if (body6.strategy === "maximize_conversions") unsupported5("conversion bidding");
131883
131883
  const bid = parse5(ChatGPTAdsBiddingSchema, body6), billing = campaign2.bidding_type === "clicks" ? "click" : "impression";
131884
131884
  if (bid.billing_event_type !== billing) invalid8("Bidding must match the campaign billing event", "bidding_config");
131885
- if (billing === "impression" && !access7.account.impressionBiddingEnabled) throw new AdsError2(403, "Account is not eligible for impression bidding", "permission_denied");
131885
+ if (billing === "impression" && !access8.account.impressionBiddingEnabled) throw new AdsError2(403, "Account is not eligible for impression bidding", "permission_denied");
131886
131886
  const strategy = bid.strategy ?? (bid.max_bid_micros !== void 0 ? "fixed_bid" : "maximize_clicks");
131887
131887
  if (strategy === "fixed_bid" && bid.max_bid_micros === void 0) invalid8("Fixed bid requires max_bid_micros");
131888
131888
  if (strategy === "maximize_clicks" && (billing !== "click" || bid.max_bid_micros !== void 0)) invalid8("Maximize clicks requires click billing and no fixed bid");
131889
131889
  return { ...bid, strategy };
131890
131890
  }
131891
- function creative(value5, access7, creating) {
131891
+ function creative(value5, access8, creating) {
131892
131892
  const body6 = object6(value5, "creative");
131893
131893
  keys(body6, ["type", "title", "body", "target_url", "file_id", "price"], "creative");
131894
131894
  if (body6.type !== void 0 && body6.type !== "chat_card") unsupported5(`creative type ${String(body6.type)}`);
131895
131895
  const parsed3 = parse5(ChatGPTAdsCreativeSchema, body6);
131896
131896
  if (creating && parsed3.title.length < 3) invalid8("New creative title must have at least 3 characters", "creative.title");
131897
- const file3 = access7.seed.files.find((f) => f.id === parsed3.file_id && f.accountId === access7.account.id);
131897
+ const file3 = access8.seed.files.find((f) => f.id === parsed3.file_id && f.accountId === access8.account.id);
131898
131898
  if (!file3) invalid8("Creative file is not available to this account", "creative.file_id");
131899
131899
  if (file3.width < 640 || file3.height < 640) invalid8("Creative image must be at least 640 by 640", "creative.file_id");
131900
131900
  return parsed3;
131901
131901
  }
131902
- function parent(access7, kind, value5) {
131902
+ function parent(access8, kind, value5) {
131903
131903
  if (kind === "campaigns") return void 0;
131904
- const row = find(access7, kind === "adGroups" ? "campaigns" : "adGroups", text15(value5[kind === "adGroups" ? "campaign_id" : "ad_group_id"], "parent id", 200));
131904
+ const row = find(access8, kind === "adGroups" ? "campaigns" : "adGroups", text15(value5[kind === "adGroups" ? "campaign_id" : "ad_group_id"], "parent id", 200));
131905
131905
  if (row.status === "archived") invalid8("Cannot create a child of an archived resource");
131906
- if (kind === "ads" && find(access7, "campaigns", row.campaign_id).status === "archived") invalid8("Cannot create an ad in an archived campaign");
131906
+ if (kind === "ads" && find(access8, "campaigns", row.campaign_id).status === "archived") invalid8("Cannot create an ad in an archived campaign");
131907
131907
  return row;
131908
131908
  }
131909
131909
  function validateSeed(seed40) {
131910
131910
  return parse5(ChatGPTAdsSeedSchema, seed40);
131911
131911
  }
131912
- function mutate2(c, access7, kind, input2, existing2) {
131912
+ function mutate2(c, access8, kind, input2, existing2) {
131913
131913
  const body6 = object6(input2), creating = !existing2;
131914
131914
  keys(body6, creating ? createFields[kind] : updateFields[kind], kind);
131915
131915
  if (creating && !["active", "paused"].includes(body6.status)) invalid8("Create status must be active or paused", "status");
@@ -131919,29 +131919,29 @@ function mutate2(c, access7, kind, input2, existing2) {
131919
131919
  if (!creating && Object.keys(body6).length === 0) invalid8("Update must specify a field");
131920
131920
  if (existing2?.status === "archived") invalid8("Archived resources cannot be changed");
131921
131921
  if (kind === "campaigns" && body6.bidding_type !== void 0 && !["impressions", "clicks"].includes(body6.bidding_type)) unsupported5("conversion campaign bidding");
131922
- const ancestor = creating ? parent(access7, kind, body6) : void 0;
131922
+ const ancestor = creating ? parent(access8, kind, body6) : void 0;
131923
131923
  const timestamp3 = now(c.env.ctx), prefix2 = collections2.find((x) => x.kind === kind).prefix;
131924
131924
  let provisional = `${prefix2}_validation`;
131925
- while (access7.seed[kind].some((x) => x.id === provisional)) provisional += "x";
131926
- let candidate = creating ? { id: provisional, accountId: access7.account.id, created_at: timestamp3, updated_at: timestamp3, ...body6 } : { ...existing2, ...body6, updated_at: timestamp3 };
131925
+ while (access8.seed[kind].some((x) => x.id === provisional)) provisional += "x";
131926
+ let candidate = creating ? { id: provisional, accountId: access8.account.id, created_at: timestamp3, updated_at: timestamp3, ...body6 } : { ...existing2, ...body6, updated_at: timestamp3 };
131927
131927
  if (kind === "campaigns") {
131928
131928
  if (creating && body6.bidding_type === void 0) candidate.bidding_type = "impressions";
131929
131929
  if (Object.hasOwn(body6, "targeting")) candidate.targeting = targeting2(body6.targeting, existing2?.targeting);
131930
131930
  if (body6.budget !== void 0) keys(object6(body6.budget, "budget"), ["daily_spend_limit_micros", "lifetime_spend_limit_micros"], "budget");
131931
131931
  if (candidate.end_time !== void 0 && candidate.end_time !== null && Number(candidate.end_time) <= Number(candidate.start_time ?? timestamp3)) invalid8("end_time must follow start_time");
131932
131932
  } else if (kind === "adGroups") {
131933
- if (body6.bidding_config !== void 0) candidate.bidding_config = bidding(body6.bidding_config, ancestor ?? find(access7, "campaigns", existing2.campaign_id), access7);
131933
+ if (body6.bidding_config !== void 0) candidate.bidding_config = bidding(body6.bidding_config, ancestor ?? find(access8, "campaigns", existing2.campaign_id), access8);
131934
131934
  } else {
131935
- if (body6.creative !== void 0) candidate.creative = creative(body6.creative, access7, creating);
131935
+ if (body6.creative !== void 0) candidate.creative = creative(body6.creative, access8, creating);
131936
131936
  if (creating || body6.creative !== void 0) {
131937
- const policy = access7.account.newAdReview;
131937
+ const policy = access8.account.newAdReview;
131938
131938
  candidate = { ...candidate, review: { status: "in_review" }, reviewAfterMs: c.env.ctx.clock.elapsedMs() + policy.delayMs, reviewOutcome: policy.outcome, reviewReason: policy.reason };
131939
131939
  }
131940
131940
  }
131941
- const rows33 = [...access7.seed[kind]];
131941
+ const rows33 = [...access8.seed[kind]];
131942
131942
  if (creating) rows33.push(candidate);
131943
131943
  else rows33[rows33.findIndex((x) => x.id === existing2.id)] = candidate;
131944
- const seed40 = validateSeed({ ...access7.seed, [kind]: rows33 });
131944
+ const seed40 = validateSeed({ ...access8.seed, [kind]: rows33 });
131945
131945
  const result = seed40[kind].find((x) => x.id === candidate.id);
131946
131946
  if (creating) {
131947
131947
  let id12;
@@ -131953,7 +131953,7 @@ function mutate2(c, access7, kind, input2, existing2) {
131953
131953
  save3(c.env.ctx, seed40);
131954
131954
  return { seed: seed40, item: result };
131955
131955
  }
131956
- function list6(c, access7, kind) {
131956
+ function list6(c, access8, kind) {
131957
131957
  const parentKey = kind === "adGroups" ? "campaign_id" : kind === "ads" ? "ad_group_id" : void 0;
131958
131958
  const query11 = params3(c, ["include", "name", "limit", "after", "before", "order", ...parentKey ? [parentKey] : []], ["include"]), issues = includes2(query11);
131959
131959
  if (query11.order !== void 0 && !["asc", "desc"].includes(query11.order)) invalid8("order must be asc or desc");
@@ -131961,42 +131961,42 @@ function list6(c, access7, kind) {
131961
131961
  const name5 = text15(query11.name, "name");
131962
131962
  if (name5.length < 3 || !name5.trim()) invalid8("name must have at least three characters");
131963
131963
  }
131964
- if (parentKey && query11[parentKey] !== void 0) find(access7, kind === "adGroups" ? "campaigns" : "adGroups", text15(query11[parentKey], parentKey, 200));
131965
- const rows33 = access7.seed[kind].filter((row) => row.accountId === access7.account.id && (query11.name === void 0 || row.name === query11.name) && (!parentKey || query11[parentKey] === void 0 || row[parentKey] === query11[parentKey]));
131964
+ if (parentKey && query11[parentKey] !== void 0) find(access8, kind === "adGroups" ? "campaigns" : "adGroups", text15(query11[parentKey], parentKey, 200));
131965
+ const rows33 = access8.seed[kind].filter((row) => row.accountId === access8.account.id && (query11.name === void 0 || row.name === query11.name) && (!parentKey || query11[parentKey] === void 0 || row[parentKey] === query11[parentKey]));
131966
131966
  rows33.sort((a, b) => (a.created_at - b.created_at || a.id.localeCompare(b.id)) * (query11.order === "asc" ? 1 : -1));
131967
131967
  const page15 = pagination(rows33, query11);
131968
- return { ...page15, data: page15.data.map((row) => project5(c.env.ctx, access7.seed, kind, row, issues)) };
131968
+ return { ...page15, data: page15.data.map((row) => project5(c.env.ctx, access8.seed, kind, row, issues)) };
131969
131969
  }
131970
- var catalogRoutes = [{ method: "GET", path: "/v1/ad_account", notes: "Account-scoped identity and seeded account/brand/integrity review.", run: (c, _body, access7) => {
131970
+ var catalogRoutes = [{ method: "GET", path: "/v1/ad_account", notes: "Account-scoped identity and seeded account/brand/integrity review.", run: (c, _body, access8) => {
131971
131971
  params3(c, []);
131972
- return accountView(access7.account);
131972
+ return accountView(access8.account);
131973
131973
  } }];
131974
131974
  for (const { kind, path: path6 } of collections2) {
131975
131975
  catalogRoutes.push(
131976
- { method: "GET", path: `/v1/${path6}`, notes: "Account/parent-scoped list, exact local name filter, native forward/backward ID cursors and optional serving issues.", run: (c, _b, access7) => list6(c, access7, kind) },
131977
- { method: "POST", path: `/v1/${path6}`, body: true, notes: "Native bounded create with account/parent/file eligibility and deterministic idempotency. Creative review is seeded local policy.", run: (c, body6, access7) => {
131976
+ { method: "GET", path: `/v1/${path6}`, notes: "Account/parent-scoped list, exact local name filter, native forward/backward ID cursors and optional serving issues.", run: (c, _b, access8) => list6(c, access8, kind) },
131977
+ { method: "POST", path: `/v1/${path6}`, body: true, notes: "Native bounded create with account/parent/file eligibility and deterministic idempotency. Creative review is seeded local policy.", run: (c, body6, access8) => {
131978
131978
  params3(c, []);
131979
- const retry = idempotency(c, access7, kind, body6);
131980
- if (retry.existing) return project5(c.env.ctx, access7.seed, kind, retry.existing);
131981
- const result = mutate2(c, access7, kind, body6);
131979
+ const retry = idempotency(c, access8, kind, body6);
131980
+ if (retry.existing) return project5(c.env.ctx, access8.seed, kind, retry.existing);
131981
+ const result = mutate2(c, access8, kind, body6);
131982
131982
  retry.remember(result.item.id);
131983
131983
  return project5(c.env.ctx, result.seed, kind, result.item);
131984
131984
  } },
131985
- { method: "GET", path: `/v1/${path6}/:id`, notes: "Account-scoped object read with optional serving issues; no hidden parent IDs added to native response.", run: (c, _body, access7) => {
131985
+ { method: "GET", path: `/v1/${path6}/:id`, notes: "Account-scoped object read with optional serving issues; no hidden parent IDs added to native response.", run: (c, _body, access8) => {
131986
131986
  const query11 = params3(c, ["include"], ["include"]);
131987
- return project5(c.env.ctx, access7.seed, kind, find(access7, kind, c.req.param("id")), includes2(query11));
131987
+ return project5(c.env.ctx, access8.seed, kind, find(access8, kind, c.req.param("id")), includes2(query11));
131988
131988
  } },
131989
- { method: "POST", path: `/v1/${path6}/:id`, body: true, notes: "Bounded native update; budgets replace, omitted targeting platforms persist, archived objects cannot change.", run: (c, body6, access7) => {
131989
+ { method: "POST", path: `/v1/${path6}/:id`, body: true, notes: "Bounded native update; budgets replace, omitted targeting platforms persist, archived objects cannot change.", run: (c, body6, access8) => {
131990
131990
  params3(c, []);
131991
- const result = mutate2(c, access7, kind, body6, find(access7, kind, c.req.param("id")));
131991
+ const result = mutate2(c, access8, kind, body6, find(access8, kind, c.req.param("id")));
131992
131992
  return project5(c.env.ctx, result.seed, kind, result.item);
131993
131993
  } }
131994
131994
  );
131995
- for (const [action, status5] of [["activate", "active"], ["pause", "paused"], ["archive", "archived"]]) catalogRoutes.push({ method: "POST", path: `/v1/${path6}/:id/${action}`, notes: "Native local status action, preserving child statuses; archive is irreversible.", run: (c, _body, access7) => {
131995
+ for (const [action, status5] of [["activate", "active"], ["pause", "paused"], ["archive", "archived"]]) catalogRoutes.push({ method: "POST", path: `/v1/${path6}/:id/${action}`, notes: "Native local status action, preserving child statuses; archive is irreversible.", run: (c, _body, access8) => {
131996
131996
  params3(c, []);
131997
- const existing2 = find(access7, kind, c.req.param("id"));
131998
- if (existing2.status === status5) return project5(c.env.ctx, access7.seed, kind, existing2);
131999
- const result = mutate2(c, access7, kind, { status: status5 }, existing2);
131997
+ const existing2 = find(access8, kind, c.req.param("id"));
131998
+ if (existing2.status === status5) return project5(c.env.ctx, access8.seed, kind, existing2);
131999
+ const result = mutate2(c, access8, kind, { status: status5 }, existing2);
132000
132000
  return project5(c.env.ctx, result.seed, kind, result.item);
132001
132001
  } });
132002
132002
  }
@@ -132022,7 +132022,7 @@ function bound(value5, field4) {
132022
132022
  if (typeof value5 !== "number" || !Number.isSafeInteger(value5)) invalid8(`Invalid ${field4}`);
132023
132023
  return value5;
132024
132024
  }
132025
- function report(c, access7, scope3) {
132025
+ function report(c, access8, scope3) {
132026
132026
  const query11 = params3(c, ["time_granularity", "aggregation_level", "limit", "after", "before", "time_ranges", "fields", "filters", "sort"], ["time_ranges", "fields", "filters", "sort"]);
132027
132027
  const granularity = query11.time_granularity ?? "daily";
132028
132028
  if (!["none", "daily"].includes(granularity)) unsupported5(`insights time_granularity ${String(granularity)}`);
@@ -132030,8 +132030,8 @@ function report(c, access7, scope3) {
132030
132030
  if (!levels.includes(requested2)) invalid8("Invalid aggregation_level");
132031
132031
  const level3 = requested2;
132032
132032
  if (levels.indexOf(level3) < levels.indexOf(scope3)) invalid8("Aggregation must be at or below the endpoint scope");
132033
- const scopeId = scope3 === "ad_account" ? access7.account.id : c.req.param("id");
132034
- if (scope3 !== "ad_account") find(access7, scope3 === "campaign" ? "campaigns" : scope3 === "ad_group" ? "adGroups" : "ads", scopeId);
132033
+ const scopeId = scope3 === "ad_account" ? access8.account.id : c.req.param("id");
132034
+ if (scope3 !== "ad_account") find(access8, scope3 === "campaign" ? "campaigns" : scope3 === "ad_group" ? "adGroups" : "ads", scopeId);
132035
132035
  const at3 = now(c.env.ctx), earliest = at3 - 5 * 366 * 86400, ranges2 = array2(query11.time_ranges);
132036
132036
  if (ranges2.length > 1) invalid8("Exactly one time range is supported");
132037
132037
  let start = Math.ceil(earliest / 3600) * 3600, end = Math.floor(at3 / 3600) * 3600;
@@ -132080,16 +132080,16 @@ function report(c, access7, scope3) {
132080
132080
  if (!["asc", "desc"].includes(s.direction)) invalid8("Sort direction must be asc or desc");
132081
132081
  return { key: key3, direction: s.direction };
132082
132082
  });
132083
- const ads = new Map(access7.seed.ads.filter((x) => x.accountId === access7.account.id).map((x) => [x.id, x])), groups = new Map(access7.seed.adGroups.map((x) => [x.id, x])), campaigns = new Map(access7.seed.campaigns.map((x) => [x.id, x]));
132083
+ const ads = new Map(access8.seed.ads.filter((x) => x.accountId === access8.account.id).map((x) => [x.id, x])), groups = new Map(access8.seed.adGroups.map((x) => [x.id, x])), campaigns = new Map(access8.seed.campaigns.map((x) => [x.id, x]));
132084
132084
  const totals2 = /* @__PURE__ */ new Map();
132085
- for (const observation of access7.seed.insights) {
132085
+ for (const observation of access8.seed.insights) {
132086
132086
  if (observation.availableAfterMs > c.env.ctx.clock.elapsedMs() || observation.start_time < start || observation.end_time > end || observation.end_time > at3) continue;
132087
132087
  const ad = ads.get(observation.adId);
132088
132088
  if (!ad) continue;
132089
132089
  const group5 = groups.get(ad.ad_group_id), campaign2 = campaigns.get(group5.campaign_id);
132090
- const entities = { ad_account: access7.account, campaign: campaign2, ad_group: group5, ad };
132090
+ const entities = { ad_account: access8.account, campaign: campaign2, ad_group: group5, ad };
132091
132091
  if (entities[scope3].id !== scopeId) continue;
132092
- const bucket2 = granularity === "daily" ? dayBounds(observation.start_time, access7.account.timezone) : void 0;
132092
+ const bucket2 = granularity === "daily" ? dayBounds(observation.start_time, access8.account.timezone) : void 0;
132093
132093
  const from = bucket2 ? Math.max(start, bucket2.start) : start, to = bucket2 ? Math.min(end, bucket2.end) : end;
132094
132094
  const id12 = `start=${from}:end=${to}:entity_id=${entities[level3].id}`;
132095
132095
  let total = totals2.get(id12);
@@ -132123,7 +132123,7 @@ function report(c, access7, scope3) {
132123
132123
  return a.start_time - b.start_time || a.id.localeCompare(b.id);
132124
132124
  });
132125
132125
  const page15 = pagination(rows33, query11, 20, 2e3);
132126
- return { ...page15, timezone: access7.account.timezone, count: page15.data.length, data: page15.data.map(({ id: id12, start_time, end_time, values: values2 }) => {
132126
+ return { ...page15, timezone: access8.account.timezone, count: page15.data.length, data: page15.data.map(({ id: id12, start_time, end_time, values: values2 }) => {
132127
132127
  const row = { id: id12, start_time, end_time };
132128
132128
  for (const name5 of fields11) {
132129
132129
  const [entity, key3] = name5.split("."), wire2 = name5 === "metadata.readable_time" ? "readable_time" : metrics.includes(key3) ? key3 : `${entity}_${key3}`;
@@ -132132,7 +132132,7 @@ function report(c, access7, scope3) {
132132
132132
  return row;
132133
132133
  }) };
132134
132134
  }
132135
- var insightsRoutes = levels.map((scope3) => ({ method: "GET", path: scope3 === "ad_account" ? "/v1/ad_account/insights" : `/v1/${scope3 === "campaign" ? "campaigns" : scope3 === "ad_group" ? "ad_groups" : "ads"}/:id/insights`, notes: "Seeded historical hourly delivery, none/daily account-timezone grouping, native field/filter/sort/cursor subset. No live auction, attribution or cross-level repeated metrics.", run: (c, _body, access7) => report(c, access7, scope3) }));
132135
+ var insightsRoutes = levels.map((scope3) => ({ method: "GET", path: scope3 === "ad_account" ? "/v1/ad_account/insights" : `/v1/${scope3 === "campaign" ? "campaigns" : scope3 === "ad_group" ? "ad_groups" : "ads"}/:id/insights`, notes: "Seeded historical hourly delivery, none/daily account-timezone grouping, native field/filter/sort/cursor subset. No live auction, attribution or cross-level repeated metrics.", run: (c, _body, access8) => report(c, access8, scope3) }));
132136
132136
 
132137
132137
  // packages/server/src/twins/chatgpt-ads/index.ts
132138
132138
  var chatGPTAdsRoutes = [...catalogRoutes, ...insightsRoutes];
@@ -135546,8 +135546,8 @@ function visible2(ctx, type, record23) {
135546
135546
  return true;
135547
135547
  }
135548
135548
  function permission5(ctx, write4 = false) {
135549
- const access7 = config4(ctx).access;
135550
- if (!access7.read || write4 && !access7.write) throw new SalesforceError(403, "INSUFFICIENT_ACCESS_OR_READONLY", "The session does not have permission for this operation.");
135549
+ const access8 = config4(ctx).access;
135550
+ if (!access8.read || write4 && !access8.write) throw new SalesforceError(403, "INSUFFICIENT_ACCESS_OR_READONLY", "The session does not have permission for this operation.");
135551
135551
  }
135552
135552
  function getRecord2(ctx, type, id12) {
135553
135553
  permission5(ctx);
@@ -135636,8 +135636,8 @@ function deleteRecord(ctx, type, id12) {
135636
135636
  history2(ctx, type, id12, "delete", prior, null);
135637
135637
  }
135638
135638
  function dumpState9(ctx) {
135639
- const { org: org5, access: access7 } = config4(ctx);
135640
- return { org: org5, access: access7, ...Object.fromEntries(salesforceObjectNames.map((type) => [salesforceCollections[type], rows29(ctx, type)])), history: ctx.store.db.prepare("SELECT * FROM salesforce_history ORDER BY ordinal").all().map((row) => ({ ordinal: row.ordinal, object: row.type, id: row.id, operation: row.operation, at: row.at, before: row.before_json ? JSON.parse(row.before_json) : null, after: row.after_json ? JSON.parse(row.after_json) : null })) };
135639
+ const { org: org5, access: access8 } = config4(ctx);
135640
+ return { org: org5, access: access8, ...Object.fromEntries(salesforceObjectNames.map((type) => [salesforceCollections[type], rows29(ctx, type)])), history: ctx.store.db.prepare("SELECT * FROM salesforce_history ORDER BY ordinal").all().map((row) => ({ ordinal: row.ordinal, object: row.type, id: row.id, operation: row.operation, at: row.at, before: row.before_json ? JSON.parse(row.before_json) : null, after: row.after_json ? JSON.parse(row.after_json) : null })) };
135641
135641
  }
135642
135642
 
135643
135643
  // packages/server/src/twins/salesforce/query.ts
@@ -137887,8 +137887,8 @@ function visibleParents(ctx, caller2, file3) {
137887
137887
  const parent2 = getFile(ctx, file3.parent);
137888
137888
  return parent2 && accessTo(ctx, caller2, parent2).role !== null ? [parent2.id] : [];
137889
137889
  }
137890
- function fileResource(ctx, caller2, file3, access7 = accessTo(ctx, caller2, file3)) {
137891
- const role3 = access7.role ?? "reader", editor = isEditorFile(file3), folder = isFolder(file3), binary = !editor && !folder;
137890
+ function fileResource(ctx, caller2, file3, access8 = accessTo(ctx, caller2, file3)) {
137891
+ const role3 = access8.role ?? "reader", editor = isEditorFile(file3), folder = isFolder(file3), binary = !editor && !folder;
137892
137892
  const trash2 = trashedBy(ctx, file3), granted = effectivePermissions(ctx, file3), caps = capabilities(file3, role3);
137893
137893
  const properties2 = JSON.parse(file3.properties), appProperties = JSON.parse(file3.app_properties);
137894
137894
  const extension2 = binary && /\.([A-Za-z0-9]+)$/.exec(file3.original_filename ?? file3.name)?.[1];
@@ -137920,7 +137920,7 @@ function fileResource(ctx, caller2, file3, access7 = accessTo(ctx, caller2, file
137920
137920
  modifiedTime: iso(file3.modified_ms),
137921
137921
  ...file3.modified_by === caller2.email && { modifiedByMeTime: iso(file3.modified_ms) },
137922
137922
  modifiedByMe: file3.modified_by === caller2.email,
137923
- ...access7.direct && file3.owner !== caller2.email && { sharedWithMeTime: iso(access7.direct.created_ms), sharingUser: userResource(ctx, caller2, file3.owner) },
137923
+ ...access8.direct && file3.owner !== caller2.email && { sharedWithMeTime: iso(access8.direct.created_ms), sharingUser: userResource(ctx, caller2, file3.owner) },
137924
137924
  owners: [userResource(ctx, caller2, file3.owner)],
137925
137925
  lastModifyingUser: userResource(ctx, caller2, file3.modified_by),
137926
137926
  shared: granted.length > 1,
@@ -137949,7 +137949,7 @@ function fileResource(ctx, caller2, file3, access7 = accessTo(ctx, caller2, file
137949
137949
  function headRevision(ctx, fileId) {
137950
137950
  return ctx.store.db.prepare("SELECT id FROM gdrive_revisions WHERE file_id = ? ORDER BY rowid DESC LIMIT 1").get(fileId)?.id;
137951
137951
  }
137952
- function searchable(ctx, caller2, file3, access7) {
137952
+ function searchable(ctx, caller2, file3, access8) {
137953
137953
  const granted = effectivePermissions(ctx, file3);
137954
137954
  const people3 = (min) => granted.filter((entry3) => (entry3.grant.type === "user" || entry3.grant.type === "group") && RANK2[entry3.grant.role] >= RANK2[min]).map((entry3) => entry3.grant.email);
137955
137955
  const anyone = granted.find((entry3) => entry3.grant.type === "anyone"), domain2 = granted.find((entry3) => entry3.grant.type === "domain");
@@ -137970,7 +137970,7 @@ ${text24}`,
137970
137970
  owners: [file3.owner],
137971
137971
  writers: people3("writer"),
137972
137972
  readers: people3("reader"),
137973
- sharedWithMe: access7.direct !== null && file3.owner !== caller2.email,
137973
+ sharedWithMe: access8.direct !== null && file3.owner !== caller2.email,
137974
137974
  visibility: anyone ? anyone.grant.allow_discovery ? "anyoneCanFind" : "anyoneWithLink" : domain2 ? domain2.grant.allow_discovery ? "domainCanFind" : "domainWithLink" : "limited"
137975
137975
  };
137976
137976
  }
@@ -138038,10 +138038,10 @@ function resolve4(ctx, caller2, id12, minimum = "reader") {
138038
138038
  if (id12 === "root" || id12 === caller2.root) return { file: rootFolder(ctx, caller2), access: { role: "owner", listed: true, direct: null } };
138039
138039
  throw notFound3(id12);
138040
138040
  }
138041
- const access7 = accessTo(ctx, caller2, file3);
138042
- if (access7.role === null) throw notFound3(id12);
138043
- if (RANK2[access7.role] < RANK2[minimum]) throw forbidden();
138044
- return { file: file3, access: access7 };
138041
+ const access8 = accessTo(ctx, caller2, file3);
138042
+ if (access8.role === null) throw notFound3(id12);
138043
+ if (RANK2[access8.role] < RANK2[minimum]) throw forbidden();
138044
+ return { file: file3, access: access8 };
138045
138045
  }
138046
138046
  function rootFolder(ctx, caller2) {
138047
138047
  const user8 = getUser4(ctx, caller2.email);
@@ -138074,9 +138074,9 @@ function rootFolder(ctx, caller2) {
138074
138074
  var isRoot = (caller2, file3) => file3.id === caller2.root;
138075
138075
  function writableParent(ctx, caller2, id12) {
138076
138076
  if (id12 === "root" || id12 === caller2.root) return null;
138077
- const { file: file3, access: access7 } = resolve4(ctx, caller2, id12);
138077
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, id12);
138078
138078
  if (!isFolder(file3)) throw new DriveError(400, "invalid", "The specified parent is not a folder.", { name: "parents" });
138079
- if (RANK2[access7.role] < RANK2.writer) throw forbidden();
138079
+ if (RANK2[access8.role] < RANK2.writer) throw forbidden();
138080
138080
  return file3.id;
138081
138081
  }
138082
138082
  function parentList(value5) {
@@ -138266,10 +138266,10 @@ function listFiles(call3) {
138266
138266
  const offset16 = readPageToken(params9.get("pageToken"), binding2);
138267
138267
  const matches7 = [];
138268
138268
  for (const file3 of allFiles(ctx)) {
138269
- const access7 = accessTo(ctx, caller2, file3);
138270
- if (access7.role === null || !access7.listed) continue;
138269
+ const access8 = accessTo(ctx, caller2, file3);
138270
+ if (access8.role === null || !access8.listed) continue;
138271
138271
  if (corpora === "domain" && !effectivePermissions(ctx, file3).some((entry3) => entry3.grant.type === "domain" && entry3.grant.domain === caller2.domain)) continue;
138272
- if (predicate(searchable(ctx, caller2, file3, access7))) matches7.push({ file: file3, access: access7 });
138272
+ if (predicate(searchable(ctx, caller2, file3, access8))) matches7.push({ file: file3, access: access8 });
138273
138273
  }
138274
138274
  matches7.sort((a, b) => order4(a.file, b.file));
138275
138275
  const page15 = matches7.slice(offset16, offset16 + pageSize2);
@@ -138277,18 +138277,18 @@ function listFiles(call3) {
138277
138277
  kind: "drive#fileList",
138278
138278
  incompleteSearch: false,
138279
138279
  ...offset16 + pageSize2 < matches7.length && { nextPageToken: pageToken(offset16 + pageSize2, binding2) },
138280
- files: page15.map(({ file: file3, access: access7 }) => fileResource(ctx, caller2, file3, access7))
138280
+ files: page15.map(({ file: file3, access: access8 }) => fileResource(ctx, caller2, file3, access8))
138281
138281
  }, selection));
138282
138282
  }
138283
138283
  function getFileRoute(call3) {
138284
138284
  const params9 = parameters(call3.url, []);
138285
- const { file: file3, access: access7 } = resolve4(call3.ctx, call3.caller, call3.ids[0]);
138285
+ const { file: file3, access: access8 } = resolve4(call3.ctx, call3.caller, call3.ids[0]);
138286
138286
  if (params9.get("alt") === "media") {
138287
138287
  if (isFolder(file3) || isEditorFile(file3)) throw new DriveError(403, "fileNotDownloadable", "Only files with binary content can be downloaded. Use Export with Docs Editors files.", { name: "alt" });
138288
- if (file3.copy_requires_writer === 1 && RANK2[access7.role] < RANK2.writer) throw new DriveError(403, "cannotDownloadFile", "The user does not have sufficient permissions to download this file.");
138288
+ if (file3.copy_requires_writer === 1 && RANK2[access8.role] < RANK2.writer) throw new DriveError(403, "cannotDownloadFile", "The user does not have sufficient permissions to download this file.");
138289
138289
  return new Response(new Uint8Array(file3.content ?? Buffer.alloc(0)), { status: 200, headers: { "content-type": file3.mime_type, "content-length": String(file3.content?.length ?? 0) } });
138290
138290
  }
138291
- return json9(project8(fileResource(call3.ctx, call3.caller, file3, access7), fileMask(params9)));
138291
+ return json9(project8(fileResource(call3.ctx, call3.caller, file3, access8), fileMask(params9)));
138292
138292
  }
138293
138293
  function createFile(call3, media, metadata7 = jsonBody2(call3.body)) {
138294
138294
  const { ctx, caller: caller2 } = call3;
@@ -138349,9 +138349,9 @@ function updateFile(call3, media, metadata7 = jsonBody2(call3.body)) {
138349
138349
  const params9 = parameters(call3.url, ["addParents", "removeParents"]);
138350
138350
  fileBody(metadata7, UPDATE_WRITABLE);
138351
138351
  if (metadata7.contentHints !== void 0) unsupported11("contentHints");
138352
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0]);
138352
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
138353
138353
  if (isRoot(caller2, file3)) throw forbidden();
138354
- const role3 = access7.role, editor = RANK2[role3] >= RANK2.writer;
138354
+ const role3 = access8.role, editor = RANK2[role3] >= RANK2.writer;
138355
138355
  const next2 = { ...file3 };
138356
138356
  let edited = false;
138357
138357
  const edit = () => {
@@ -138469,8 +138469,8 @@ function remove(ctx, caller2, file3) {
138469
138469
  }
138470
138470
  function deleteFile(call3) {
138471
138471
  parameters(call3.url, []);
138472
- const { file: file3, access: access7 } = resolve4(call3.ctx, call3.caller, call3.ids[0]);
138473
- if (access7.role !== "owner" || isRoot(call3.caller, file3)) throw forbidden();
138472
+ const { file: file3, access: access8 } = resolve4(call3.ctx, call3.caller, call3.ids[0]);
138473
+ if (access8.role !== "owner" || isRoot(call3.caller, file3)) throw forbidden();
138474
138474
  remove(call3.ctx, call3.caller, file3);
138475
138475
  return new Response(null, { status: 204 });
138476
138476
  }
@@ -138488,8 +138488,8 @@ function copyFile(call3) {
138488
138488
  const metadata7 = jsonBody2(call3.body);
138489
138489
  fileBody(metadata7, COPY_WRITABLE);
138490
138490
  if (metadata7.contentHints !== void 0) unsupported11("contentHints");
138491
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0]);
138492
- if (isFolder(file3) || file3.copy_requires_writer === 1 && RANK2[access7.role] < RANK2.writer) throw new DriveError(403, "cannotCopyFile", "This file cannot be copied by the user.");
138491
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
138492
+ if (isFolder(file3) || file3.copy_requires_writer === 1 && RANK2[access8.role] < RANK2.writer) throw new DriveError(403, "cannotCopyFile", "This file cannot be copied by the user.");
138493
138493
  const mimeType = stringField(metadata7, "mimeType", 255);
138494
138494
  if (mimeType !== void 0 && mimeType !== file3.mime_type) unsupported11("converting a file while copying it");
138495
138495
  const parents = parentList(metadata7.parents);
@@ -138585,10 +138585,10 @@ function emailAddress(body6) {
138585
138585
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email10)) throw new DriveError(400, "invalid", "Invalid email address.", { name: "permission.emailAddress" });
138586
138586
  return email10;
138587
138587
  }
138588
- function transferOwnership(call3, file3, access7, email10, params9) {
138588
+ function transferOwnership(call3, file3, access8, email10, params9) {
138589
138589
  const { ctx, caller: caller2 } = call3;
138590
138590
  if (!booleanParameter(params9, "transferOwnership", false)) throw new DriveError(403, "forbidden", "The transferOwnership parameter must be enabled when the permission role is 'owner'.");
138591
- if (access7.role !== "owner") throw forbidden();
138591
+ if (access8.role !== "owner") throw forbidden();
138592
138592
  if (email10 === file3.owner) throw new DriveError(403, "invalidSharingRequest", 'Bad Request. User message: "The owner already has access."');
138593
138593
  if (email10.split("@")[1] !== file3.owner.split("@")[1]) {
138594
138594
  throw new DriveError(400, "ownershipChangeAcrossDomainNotPermitted", `Bad Request. User message: "Sorry, cannot transfer ownership to ${email10}. Ownership can only be transferred to another user in the same organization as the current owner."`);
@@ -138635,15 +138635,15 @@ function createPermission(call3) {
138635
138635
  if (key3 === "expirationTime" || key3 === "view" || key3 === "pendingOwner" || key3 === "inheritedPermissionsDisabled") unsupported11(`permission field ${key3}`);
138636
138636
  if (!["type", "role", "emailAddress", "domain", "allowFileDiscovery"].includes(key3)) throw new DriveError(403, "fieldNotWritable", "The resource body includes fields which are not directly writable.");
138637
138637
  }
138638
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0]);
138639
- if (isRoot(caller2, file3) || !canShare(file3, access7.role)) throw forbidden();
138638
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
138639
+ if (isRoot(caller2, file3) || !canShare(file3, access8.role)) throw forbidden();
138640
138640
  const type = body6.type, role3 = body6.role;
138641
138641
  if (type === void 0) throw new DriveError(400, "required", "Permission type field required", { name: "permission.type" });
138642
138642
  if (role3 === void 0) throw new DriveError(400, "required", "Permission role field required", { name: "permission.role" });
138643
138643
  if (!["user", "group", "domain", "anyone"].includes(String(type))) throw new DriveError(400, "invalid", "Invalid permission type.", { name: "permission.type" });
138644
138644
  if (role3 === "owner") {
138645
138645
  if (type !== "user") unsupported11(`the owner role for a ${String(type)} permission`);
138646
- return transferOwnership(call3, file3, access7, emailAddress(body6), params9);
138646
+ return transferOwnership(call3, file3, access8, emailAddress(body6), params9);
138647
138647
  }
138648
138648
  if (role3 === "organizer" || role3 === "fileOrganizer") throw new DriveError(403, "invalidSharingRequest", 'Bad Request. User message: "Organizer roles only apply to shared drives."');
138649
138649
  if (!["reader", "commenter", "writer"].includes(String(role3))) throw new DriveError(400, "invalid", "Invalid permission role.", { name: "permission.role" });
@@ -138682,15 +138682,15 @@ function updatePermission(call3) {
138682
138682
  if (key3 === "expirationTime" || key3 === "view" || key3 === "pendingOwner") unsupported11(`permission field ${key3}`);
138683
138683
  if (key3 !== "role" && key3 !== "allowFileDiscovery") throw new DriveError(403, "fieldNotWritable", "The resource body includes fields which are not directly writable.");
138684
138684
  }
138685
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0]);
138686
- if (!canShare(file3, access7.role)) throw forbidden();
138685
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
138686
+ if (!canShare(file3, access8.role)) throw forbidden();
138687
138687
  const entry3 = findGrant(ctx, file3, call3.ids[1]);
138688
138688
  if (entry3.grant.role === "owner") throw new DriveError(403, "cannotModifyOwnerPermission", "The owner of a file cannot be changed with this request.");
138689
138689
  if (entry3.inherited) unsupported11("changing a permission inherited from a parent folder");
138690
138690
  const role3 = body6.role === void 0 ? entry3.grant.role : body6.role;
138691
138691
  if (role3 === "owner") {
138692
138692
  if (entry3.grant.type !== "user") unsupported11(`the owner role for a ${entry3.grant.type} permission`);
138693
- return transferOwnership(call3, file3, access7, entry3.grant.email, params9);
138693
+ return transferOwnership(call3, file3, access8, entry3.grant.email, params9);
138694
138694
  }
138695
138695
  if (!["reader", "commenter", "writer"].includes(String(role3))) throw new DriveError(400, "invalid", "Invalid permission role.", { name: "permission.role" });
138696
138696
  ctx.store.db.prepare("UPDATE gdrive_permissions SET role = ? WHERE file_id = ? AND id = ?").run(role3, file3.id, entry3.grant.id);
@@ -138701,10 +138701,10 @@ function deletePermission(call3) {
138701
138701
  const { ctx, caller: caller2 } = call3;
138702
138702
  const params9 = parameters(call3.url, ["useDomainAdminAccess", "enforceExpansiveAccess"]);
138703
138703
  if (booleanParameter(params9, "useDomainAdminAccess", false)) unsupported11("useDomainAdminAccess");
138704
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0]);
138704
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
138705
138705
  const entry3 = findGrant(ctx, file3, call3.ids[1]);
138706
138706
  const self2 = entry3.grant.email === caller2.email;
138707
- if (!self2 && !canShare(file3, access7.role)) throw forbidden();
138707
+ if (!self2 && !canShare(file3, access8.role)) throw forbidden();
138708
138708
  if (entry3.grant.role === "owner") throw new DriveError(403, "cannotRemoveOwner", "The owner of a file cannot be removed.");
138709
138709
  if (entry3.inherited) unsupported11("removing a permission inherited from a parent folder");
138710
138710
  ctx.store.db.prepare("DELETE FROM gdrive_permissions WHERE file_id = ? AND id = ?").run(file3.id, entry3.grant.id);
@@ -138788,9 +138788,9 @@ function updateComment(call3) {
138788
138788
  function deleteComment(call3) {
138789
138789
  const { ctx, caller: caller2 } = call3;
138790
138790
  parameters(call3.url, []);
138791
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0], "commenter");
138791
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0], "commenter");
138792
138792
  const comment8 = getComment(ctx, file3, call3.ids[1], false);
138793
- if (comment8.author !== caller2.email && access7.role !== "owner") throw new DriveError(403, "insufficientPermissions", "The user does not have sufficient permissions for this comment.");
138793
+ if (comment8.author !== caller2.email && access8.role !== "owner") throw new DriveError(403, "insufficientPermissions", "The user does not have sufficient permissions for this comment.");
138794
138794
  ctx.store.db.prepare("UPDATE gdrive_comments SET deleted = 1, modified_ms = ? WHERE id = ?").run(ctx.clock.nowMs(), comment8.id);
138795
138795
  return new Response(null, { status: 204 });
138796
138796
  }
@@ -138865,8 +138865,8 @@ function listChanges(call3) {
138865
138865
  const file3 = row.removed ? void 0 : getFile(ctx, row.file_id);
138866
138866
  let change = null;
138867
138867
  if (file3) {
138868
- const access7 = accessTo(ctx, caller2, file3);
138869
- if (access7.role !== null && access7.listed && (!myDrive || file3.owner === caller2.email)) change = { file: fileResource(ctx, caller2, file3, access7), removed: false };
138868
+ const access8 = accessTo(ctx, caller2, file3);
138869
+ if (access8.role !== null && access8.listed && (!myDrive || file3.owner === caller2.email)) change = { file: fileResource(ctx, caller2, file3, access8), removed: false };
138870
138870
  } else if (includeRemoved && row.owner === caller2.email) change = { removed: true };
138871
138871
  if (!change) continue;
138872
138872
  if (visible5.length === pageSize2) {
@@ -138933,8 +138933,8 @@ async function handle7(c) {
138933
138933
  try {
138934
138934
  const body6 = method2 === "GET" || method2 === "DELETE" ? void 0 : new Uint8Array(await c.req.arrayBuffer());
138935
138935
  const ids2 = (route11.pattern.exec(url3.pathname) ?? []).slice(1).map((value5) => decodeURIComponent(value5));
138936
- const access7 = route11.write ? withMutation : withRead;
138937
- return access7(ctx, () => {
138936
+ const access8 = route11.write ? withMutation : withRead;
138937
+ return access8(ctx, () => {
138938
138938
  const token2 = tokenOf2(c, url3);
138939
138939
  const caller2 = callerFor(ctx, token2);
138940
138940
  if (!caller2) {
@@ -150142,10 +150142,10 @@ function linkSettings(call3, settings) {
150142
150142
  if (!["public", "team", "no_one"].includes(audience)) unsupported19(`shared link audience ${audience}`);
150143
150143
  out.audience = audience;
150144
150144
  }
150145
- const access7 = tag3(value5.access);
150146
- if (access7 !== void 0) {
150147
- if (!["viewer", "editor", "max"].includes(access7)) throw new DropboxError(400, `Error in call to API function "${call3.route}": settings.access: unknown tag '${access7}'`);
150148
- out.access = access7 === "max" ? "editor" : access7;
150145
+ const access8 = tag3(value5.access);
150146
+ if (access8 !== void 0) {
150147
+ if (!["viewer", "editor", "max"].includes(access8)) throw new DropboxError(400, `Error in call to API function "${call3.route}": settings.access: unknown tag '${access8}'`);
150148
+ out.access = access8 === "max" ? "editor" : access8;
150149
150149
  }
150150
150150
  if (value5.expires !== void 0) {
150151
150151
  const at3 = Date.parse(String(value5.expires));
@@ -150254,10 +150254,10 @@ function addMembers(call3) {
150254
150254
  }
150255
150255
  const email10 = String(member4.email ?? "").trim().toLowerCase();
150256
150256
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email10)) throw endpoint("bad_member/invalid_email", { ".tag": "bad_member", bad_member: { ".tag": "invalid_email", invalid_email: email10 } });
150257
- const access7 = typeof raw3.access_level === "string" ? raw3.access_level : raw3.access_level?.[".tag"] ?? "viewer";
150258
- if (!["editor", "viewer", "viewer_no_comment"].includes(access7)) throw new DropboxError(400, `Error in call to API function "sharing/add_folder_member": access_level: unknown tag '${access7}'`);
150257
+ const access8 = typeof raw3.access_level === "string" ? raw3.access_level : raw3.access_level?.[".tag"] ?? "viewer";
150258
+ if (!["editor", "viewer", "viewer_no_comment"].includes(access8)) throw new DropboxError(400, `Error in call to API function "sharing/add_folder_member": access_level: unknown tag '${access8}'`);
150259
150259
  if (email10 === account5(call3.ctx).email) throw endpoint("bad_member/cant_share_with_self", { ".tag": "bad_member", bad_member: { ".tag": "cant_share_with_self" } });
150260
- call3.ctx.store.db.prepare("INSERT OR REPLACE INTO dbx_members (shared_folder_id, email, access, added_ms) VALUES (?, ?, ?, ?)").run(folder.shared_folder_id, email10, access7, now10);
150260
+ call3.ctx.store.db.prepare("INSERT OR REPLACE INTO dbx_members (shared_folder_id, email, access, added_ms) VALUES (?, ?, ?, ?)").run(folder.shared_folder_id, email10, access8, now10);
150261
150261
  }
150262
150262
  return json15(null);
150263
150263
  }
@@ -157128,11 +157128,11 @@ async function token(c) {
157128
157128
  if (!known2) return Response.json({ error: "invalid_client", error_description: "Client Authentication failed" }, { status: 401 });
157129
157129
  const grant = form.get("grant_type");
157130
157130
  if (grant !== "client_credentials") return Response.json({ error: "unsupported_grant_type", error_description: grant ? "unsupported grant_type" : "Grant Type is NULL" }, { status: 400 });
157131
- const now10 = ctx.clock.nowMs(), access7 = `A21AA${ctx.secrets.alnumUpper(92)}`;
157132
- ctx.store.db.prepare("INSERT INTO paypal_tokens (token, expires_ms) VALUES (?, ?)").run(access7, now10 + 324e5);
157131
+ const now10 = ctx.clock.nowMs(), access8 = `A21AA${ctx.secrets.alnumUpper(92)}`;
157132
+ ctx.store.db.prepare("INSERT INTO paypal_tokens (token, expires_ms) VALUES (?, ?)").run(access8, now10 + 324e5);
157133
157133
  return Response.json({
157134
157134
  scope: "https://uri.paypal.com/services/payments/payment https://uri.paypal.com/services/payments/refund https://uri.paypal.com/services/subscriptions https://uri.paypal.com/services/reporting/search/read",
157135
- access_token: access7,
157135
+ access_token: access8,
157136
157136
  token_type: "Bearer",
157137
157137
  app_id: "APP-80W284485P519543T",
157138
157138
  expires_in: 32400,
@@ -177678,9 +177678,9 @@ function writeTar(entries2, mtimeMs) {
177678
177678
  }
177679
177679
 
177680
177680
  // packages/cli/src/run-upload.ts
177681
- async function uploadWorkspace(ctx) {
177681
+ async function uploadWorkspace(ctx, missing6 = { message: "--upload needs a workspace", hint: "run ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY" }) {
177682
177682
  const url3 = ctx.globals().local ? (await ctx.loadConfig()).server?.url || ctx.io.env.ANCHA_SERVER_URL || await defaultServerUrl(ctx.io.env) : (await serverChoice(ctx)).url;
177683
- if (url3 === void 0) throw new AnchaError("USAGE", "--upload needs a workspace", { hint: "run ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY" });
177683
+ if (url3 === void 0) throw new AnchaError("USAGE", missing6.message, { hint: missing6.hint });
177684
177684
  try {
177685
177685
  return normalizeServerUrl(url3);
177686
177686
  } catch {
@@ -177730,57 +177730,13 @@ function httpUrl2(value5) {
177730
177730
  }
177731
177731
 
177732
177732
  // packages/cli/src/reproduction.ts
177733
- import { readFile as readFile17 } from "node:fs/promises";
177734
- import { dirname as dirname10, join as join21, resolve as resolve18 } from "node:path";
177735
- async function reproductionOf(summary, scenePaths, cwd, runDir) {
177736
- const out = [];
177737
- const answers = runDir === void 0 ? [] : await toolAnswers(runDir, summary, {});
177738
- for (const scene2 of summary.scenes) {
177739
- const path6 = scenePaths[scene2.sceneId];
177740
- if (path6 === void 0) continue;
177741
- const production3 = await readFile17(join21(dirname10(resolve18(cwd, path6)), "production.json"), "utf8").then((text24) => JSON.parse(text24), () => void 0);
177742
- if (production3?.checks === void 0) continue;
177743
- const checks = Object.entries(production3.checks).flatMap(([check4, result]) => {
177744
- const here = scene2.checks[check4];
177745
- return here === void 0 ? [] : [{ check: check4, production: result, failed: here.total - here.passed, total: here.total }];
177746
- });
177747
- const failedThere = checks.filter((c) => c.production === "failed");
177748
- const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : "matches";
177749
- const added = Object.keys(scene2.checks).filter((check4) => !(check4 in production3.checks));
177750
- const counts = {};
177751
- for (const a of answers.filter((x) => x.scene === scene2.sceneId)) for (const [source, n] of Object.entries(a.counts)) counts[source] = (counts[source] ?? 0) + n;
177752
- out.push({ sceneId: scene2.sceneId, ...production3.trace !== void 0 && { trace: production3.trace }, verdict, checks, added, ...Object.keys(counts).length && { answers: counts } });
177753
- }
177754
- return out;
177755
- }
177756
- var SAY = {
177757
- reproduced: "production's failure happens here too",
177758
- partly: "production's failure happens here in part",
177759
- "not-reproduced": "production's failure did not happen here: the agent is fixed, or the world differs from production (see questions.json next to the scene)",
177760
- matches: "this run matches production, which passed these checks",
177761
- differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)"
177762
- };
177763
- function renderReproduction(reproductions) {
177764
- return reproductions.map((r) => {
177765
- const width = Math.max(...r.checks.map((c) => c.check.length));
177766
- const rows33 = r.checks.map((c) => ` ${c.check.padEnd(width)} ${c.production} in production \xB7 ${c.total === 0 ? "not run" : `failed ${c.failed}/${c.total} here`}`);
177767
- const also = r.verdict !== "differs" ? r.checks.filter((c) => c.production === "passed" && c.failed > 0).map((c) => c.check) : [];
177768
- return [
177769
- `compared with production${r.trace === void 0 ? "" : ` (trace ${r.trace.slice(0, 12)})`}: ${r.sceneId}`,
177770
- ...rows33,
177771
- `=> ${SAY[r.verdict]}`,
177772
- ...also.length > 0 ? [` also failing here, though production passed: ${also.join(", ")}`] : [],
177773
- ...r.added.length > 0 ? [` checks added after saving, with no production result: ${r.added.join(", ")}`] : [],
177774
- // How much of the run stood on production's own answers (TRACE_PLAN_V2 §8.6).
177775
- ...r.answers ? [` answers to the agent's tools: ${["replayed", "replayed-elsewhere", "twin", "ran", "simulated", "failed"].filter((s) => r.answers[s]).map((s) => `${r.answers[s]} ${s}`).join(", ")}${r.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : []
177776
- ].join("\n");
177777
- }).join("\n\n");
177778
- }
177733
+ import { readFile as readFile18 } from "node:fs/promises";
177734
+ import { dirname as dirname11, join as join22, resolve as resolve18 } from "node:path";
177779
177735
 
177780
177736
  // backend/src/production.ts
177781
177737
  import { createHash as createHash57 } from "node:crypto";
177782
- import { readFile as readFile18, writeFile as writeFile10 } from "node:fs/promises";
177783
- import { dirname as dirname11, join as join22 } from "node:path";
177738
+ import { readFile as readFile17, writeFile as writeFile10 } from "node:fs/promises";
177739
+ import { dirname as dirname10, join as join21 } from "node:path";
177784
177740
 
177785
177741
  // node_modules/.pnpm/openai@7.43.0_@aws-sdk+credential-provider-node@3.972.91_@smithy+signature-v4@5.7.5_undici@8.12.3_ws@8.22.0_zod@4.6.7/node_modules/openai/internal/tslib.mjs
177786
177742
  function __classPrivateFieldSet(receiver, state3, value5, kind, f) {
@@ -201285,13 +201241,17 @@ function productionTrace(lines) {
201285
201241
  if (invocation?.output !== void 0) entries2.push({ seq: ++seq2, tSim: "", tReal: 0, source: "agent", service: "agent", method: "POST", path: "/done", status: 200, request: { output: invocation.output } });
201286
201242
  return entries2;
201287
201243
  }
201244
+ async function productionRecord(dir2) {
201245
+ const text24 = await readFile17(join21(dir2, "production.jsonl"), "utf8").catch(() => void 0);
201246
+ return text24 === void 0 ? void 0 : productionTrace(text24.split("\n").filter(Boolean).map((line2) => JSON.parse(line2)));
201247
+ }
201288
201248
  async function completeProduction(scenePath, scene2, judge) {
201289
- const dir2 = dirname11(scenePath);
201290
- const text24 = await readFile18(join22(dir2, "production.jsonl"), "utf8").catch(() => void 0);
201249
+ const dir2 = dirname10(scenePath);
201250
+ const text24 = await readFile17(join21(dir2, "production.jsonl"), "utf8").catch(() => void 0);
201291
201251
  if (text24 === void 0) return [];
201292
201252
  const lines = text24.split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
201293
- const file3 = join22(dir2, "production.json");
201294
- const known2 = await readFile18(file3, "utf8").then((t) => JSON.parse(t), () => ({}));
201253
+ const file3 = join21(dir2, "production.json");
201254
+ const known2 = await readFile17(file3, "utf8").then((t) => JSON.parse(t), () => ({}));
201295
201255
  const checks = { ...known2.checks }, signatures = { ...known2.signatures };
201296
201256
  const sign2 = (check4) => createHash57("sha256").update(JSON.stringify(check4)).digest("hex").slice(0, 12);
201297
201257
  const missing6 = scene2.checks.filter((check4) => checks[check4.id] === void 0 || checks[check4.id] === "unknown" || signatures[check4.id] !== void 0 && signatures[check4.id] !== sign2(check4));
@@ -201320,6 +201280,80 @@ async function completeProduction(scenePath, scene2, judge) {
201320
201280
  return missing6.map((check4) => check4.id);
201321
201281
  }
201322
201282
 
201283
+ // packages/cli/src/reproduction.ts
201284
+ async function reproductionOf(summary, scenePaths, cwd, runDir, scenes = []) {
201285
+ const out = [];
201286
+ const answers = runDir === void 0 ? [] : await toolAnswers(runDir, summary, {});
201287
+ for (const scene2 of summary.scenes) {
201288
+ const path6 = scenePaths[scene2.sceneId];
201289
+ if (path6 === void 0) continue;
201290
+ const production3 = await readFile18(join22(dirname11(resolve18(cwd, path6)), "production.json"), "utf8").then((text24) => JSON.parse(text24), () => void 0);
201291
+ if (production3?.checks === void 0) continue;
201292
+ const checks = Object.entries(production3.checks).flatMap(([check4, result]) => {
201293
+ const here = scene2.checks[check4];
201294
+ return here === void 0 ? [] : [{ check: check4, production: result, failed: here.total - here.passed, total: here.total }];
201295
+ });
201296
+ const failedThere = checks.filter((c) => c.production === "failed");
201297
+ const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : checks.some((c) => c.production === "passed") ? "matches" : "unknown";
201298
+ const added = Object.keys(scene2.checks).filter((check4) => !(check4 in production3.checks));
201299
+ const counts = {};
201300
+ for (const a of answers.filter((x) => x.scene === scene2.sceneId)) for (const [source, n] of Object.entries(a.counts)) counts[source] = (counts[source] ?? 0) + n;
201301
+ const defined = scenes.find((s) => s.id === scene2.sceneId);
201302
+ const writes2 = defined === void 0 || runDir === void 0 || !writeTools(defined).size ? void 0 : await writesOf(defined, dirname11(resolve18(cwd, path6)), runDir, scene2);
201303
+ out.push({ sceneId: scene2.sceneId, ...production3.trace !== void 0 && { trace: production3.trace }, verdict, checks, added, ...Object.keys(counts).length && { answers: counts }, ...writes2 !== void 0 && { writes: writes2 } });
201304
+ }
201305
+ return out;
201306
+ }
201307
+ async function writesOf(scene2, dir2, runDir, ran) {
201308
+ const record23 = await productionRecord(dir2);
201309
+ if (record23 === void 0) return void 0;
201310
+ const made = /* @__PURE__ */ new Map(), here = /* @__PURE__ */ new Map();
201311
+ for (const action of actionsOf(scene2, record23)) made.set(action.tool, (made.get(action.tool) ?? 0) + 1);
201312
+ const trials = (ran.trialsDetail ?? []).filter((t) => t.valid !== false);
201313
+ for (const { trial } of trials) {
201314
+ const text24 = await readFile18(join22(runDir, `trial-${ran.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
201315
+ const trace = text24.split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
201316
+ for (const tool of new Set(actionsOf(scene2, trace).map((action) => action.tool))) here.set(tool, (here.get(tool) ?? 0) + 1);
201317
+ }
201318
+ const tools2 = [...made.keys(), ...[...here.keys()].filter((tool) => !made.has(tool)).sort()];
201319
+ return { of: trials.length, tools: tools2.map((tool) => ({ tool, production: made.get(tool) ?? 0, trials: here.get(tool) ?? 0 })) };
201320
+ }
201321
+ function renderWrites(writes2) {
201322
+ const of = `${writes2.of} ${writes2.of === 1 ? "trial" : "trials"}`;
201323
+ if (!writes2.tools.length) return [` writes compared with production: none in production, none in this run's ${of}`];
201324
+ const called = (n) => n === 0 ? "not called" : n === 1 ? "called" : `called ${n} times`;
201325
+ const width = Math.max(...writes2.tools.map((w) => w.tool.length)), said = Math.max(...writes2.tools.map((w) => called(w.production).length));
201326
+ return [" writes compared with production:", ...writes2.tools.map((w) => ` ${w.tool.padEnd(width)} production: ${called(w.production).padEnd(said)} this run: ${w.trials} of ${of}`)];
201327
+ }
201328
+ var SAY = {
201329
+ reproduced: "production's failure happens here too",
201330
+ partly: "production's failure happens here in part",
201331
+ "not-reproduced": "production's failure did not happen here: the agent is fixed, or the world differs from production (see questions.json next to the scene)",
201332
+ matches: "this run matches production, which passed these checks",
201333
+ differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)",
201334
+ unknown: "set OPENROUTER_API_KEY and run again: a model grades these checks on production's record and on this run"
201335
+ };
201336
+ function renderReproduction(reproductions) {
201337
+ return reproductions.map((r) => {
201338
+ const width = Math.max(...r.checks.map((c) => c.check.length));
201339
+ const rows33 = r.checks.map((c) => ` ${c.check.padEnd(width)} ${c.production} in production \xB7 ${c.total === 0 ? "not run" : `failed ${c.failed}/${c.total} here`}`);
201340
+ const also = r.verdict !== "differs" ? r.checks.filter((c) => c.production === "passed" && c.failed > 0).map((c) => c.check) : [];
201341
+ return [
201342
+ `compared with production${r.trace === void 0 ? "" : ` (trace ${r.trace.slice(0, 12)})`}: ${r.sceneId}`,
201343
+ ...rows33,
201344
+ `=> ${SAY[r.verdict]}`,
201345
+ ...also.length > 0 ? [` also failing here, though production passed: ${also.join(", ")}`] : [],
201346
+ // A failure here on a check production is not graded on yet is neither a match nor a regression: say how to grade both.
201347
+ ...r.verdict !== "unknown" && r.checks.some((c) => c.production === "unknown" && c.failed > 0) ? [` set OPENROUTER_API_KEY to grade ${r.checks.filter((c) => c.production === "unknown" && c.failed > 0).map((c) => c.check).join(", ")} on production's record and here`] : [],
201348
+ ...r.added.length > 0 ? [` checks added after saving, with no production result: ${r.added.join(", ")}`] : [],
201349
+ // How much of the run stood on production's own answers (TRACE_PLAN_V2 §8.6).
201350
+ ...r.answers ? [` answers to the agent's tools: ${["replayed", "replayed-elsewhere", "twin", "ran", "simulated", "failed"].filter((s) => r.answers[s]).map((s) => `${r.answers[s]} ${s}`).join(", ")}${r.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : [],
201351
+ // What the agent changed, next to what production changed: an answer that needs no model (SPEC-020 R1).
201352
+ ...r.writes !== void 0 && r.writes.of > 0 ? renderWrites(r.writes) : []
201353
+ ].join("\n");
201354
+ }).join("\n\n");
201355
+ }
201356
+
201323
201357
  // backend/src/runner/run.ts
201324
201358
  init_src();
201325
201359
  import { randomInt } from "node:crypto";
@@ -202787,7 +202821,7 @@ async function interruptible(ctx, fn) {
202787
202821
  }
202788
202822
  }
202789
202823
  function registerRun(program2, ctx) {
202790
- program2.command("run").description("run an agent against scenes N times and summarize how often it passes (starts its own server unless one is configured)").argument("[scenes...]", "scene YAML files (default: the globs in scenes: of ancha.yaml)").option("--agent <cmd>", "shell command that runs the agent (default: agent.command in ancha.yaml)").option("--agent-url <url>", "endpoint URL (overrides agent.url; requires endpoint setup/start configuration)").option("-n, --trials <n>", "trials per scene (default: trials in ancha.yaml, else 5)").option("--parallel <n>", "trials running at once (default: parallel in ancha.yaml, else command 2 / endpoint 1)").option("--min-pass-rate <r>", "fraction of trials that must pass, 0 to 1 (default: min_pass_rate in ancha.yaml, else 1)").option("--seed <seed>", "seed for ids and randomness").option("--out <dir>", "where run directories go (default: .ancha/runs)").option("--strict", "exit 4 if the agent hit an endpoint Ancha does not implement").option("--detach", "continue in a private worker after this command exits; observe with status/wait").option("--compare <reference>", "compare against a completed run id or saved baseline; any per-scene decrease fails").option("--pass-env <name>", "give the agent this variable from this shell (repeatable); it otherwise gets only a base set (PATH, HOME, locale\u2026) plus Ancha's and the tools' variables", (name5, names3) => [...names3, name5], []).option("--inherit-env", "give the agent this shell's whole environment, including any real credentials (the behavior before 0.1.2)").option("--on <target>", "where the agent runs: local (a process on this computer), docker (a sealed container; needs agent.execution with an image in ancha.yaml) or cloud (scene/test import is currently unsupported; use local/CI or an explicit saved-world task via runs start). Default: what ancha.yaml says").option("--idempotency-key <key>", "retry safely: the same key and the same run definition return the original run instead of starting another").option("--upload", "send the finished run to your workspace, where the console shows it (also ANCHA_UPLOAD=1); a failed upload is a warning").option("--upload-required", "like --upload, but a failed upload fails the command").option("--dry-run", "check ancha.yaml and every scene, print what would run, and stop: no server, no agent, no trial").option("--allow-unwrapped <tools>", "in a test made from a trace, let the agent call these tools for real instead of stopping because it does not wrap them (comma-separated, repeatable)", (value5, all8 = []) => [...all8, ...value5.split(",").map((s) => s.trim()).filter(Boolean)]).action(async (sceneArgs, opts, command) => {
202824
+ program2.command("run").description("run an agent against scenes N times and summarize how often it passes (starts its own server unless one is configured)").argument("[scenes...]", "scene YAML files (default: the globs in scenes: of ancha.yaml)").option("--agent <cmd>", "shell command that runs the agent (default: agent.command in ancha.yaml)").option("--agent-url <url>", "endpoint URL (overrides agent.url; requires endpoint setup/start configuration)").option("-n, --trials <n>", "trials per scene (default: trials in ancha.yaml, else 5)").option("--parallel <n>", "trials running at once (default: parallel in ancha.yaml, else command 2 / endpoint 1)").option("--min-pass-rate <r>", "fraction of trials that must pass, 0 to 1 (default: min_pass_rate in ancha.yaml, else 1)").option("--seed <seed>", "seed for ids and randomness").option("--out <dir>", "where run directories go (default: .ancha/runs)").option("--strict", "exit 4 if the agent hit an endpoint Ancha does not implement").option("--detach", "continue in a private worker after this command exits; observe with status/wait").option("--compare <reference>", "compare against a completed run id or saved baseline; any per-scene decrease fails").option("--pass-env <name>", "give the agent this variable from this shell (repeatable); it otherwise gets only a base set (PATH, HOME, locale\u2026) plus Ancha's and the tools' variables", (name5, names3) => [...names3, name5], []).option("--inherit-env", "give the agent this shell's whole environment, including any real credentials (the behavior before 0.1.2)").option("--on <target>", "where the agent runs: local (a process on this computer) or docker (a sealed container; needs agent.execution with an image in ancha.yaml). Default: what ancha.yaml says. To run in your workspace, start a saved world's task with ancha runs start").option("--idempotency-key <key>", "retry safely: the same key and the same run definition return the original run instead of starting another").option("--upload", "send the finished run to your workspace, where the console shows it (also ANCHA_UPLOAD=1); a failed upload is a warning").option("--upload-required", "like --upload, but a failed upload fails the command").option("--dry-run", "check ancha.yaml and every scene, print what would run, and stop: no server, no agent, no trial").option("--allow-unwrapped <tools>", "in a test made from a trace, let the agent call these tools for real instead of stopping because it does not wrap them (comma-separated, repeatable)", (value5, all8 = []) => [...all8, ...value5.split(",").map((s) => s.trim()).filter(Boolean)]).action(async (sceneArgs, opts, command) => {
202791
202825
  const { cwd } = ctx.io;
202792
202826
  if (opts.agent === void 0 && opts.agentUrl === void 0 && ctx.globals().config === void 0 && !await access4(resolve23(cwd, "ancha.yaml")).then(() => true, () => false)) {
202793
202827
  throw new AnchaError("USAGE", "no ancha.yaml here", { hint: 'run `ancha init` in your agent\'s project, or pass --agent "<command>"' });
@@ -202866,9 +202900,9 @@ function registerRun(program2, ctx) {
202866
202900
  const workspace3 = workspaceOf(choice4.url, cwd);
202867
202901
  let relay;
202868
202902
  if (serverUrl3 === void 0 && scenes.some((scene2) => (scene2.people?.length ?? 0) > 0 || Object.keys(scene2.tools ?? {}).length > 0)) {
202869
- const access7 = await modelAccess(ctx.io.env);
202870
- if (access7.kind === "relay") {
202871
- relay = { baseUrl: access7.baseUrl, apiKey: access7.apiKey };
202903
+ const access8 = await modelAccess(ctx.io.env);
202904
+ if (access8.kind === "relay") {
202905
+ relay = { baseUrl: access8.baseUrl, apiKey: access8.apiKey };
202872
202906
  ctx.out.info(RELAY_NOTICE);
202873
202907
  }
202874
202908
  }
@@ -203027,7 +203061,7 @@ async function executePreparedRun(ctx, input2, initial, ready2) {
203027
203061
  const upload3 = await uploadFinished(ctx, input2, summary.runId);
203028
203062
  await writer.finish({ state: "finished", exitCode: ctx.exitCode, ...upload3 !== void 0 && { upload: keptUpload(upload3, summary.runId) } });
203029
203063
  if (ctx.exitCode === EXIT_STRICT_GAP) ctx.out.info("--strict: the agent hit an endpoint Ancha does not implement (see coverage gaps)");
203030
- emitFinished(ctx, summary, input2.out, upload3, input2.uploadHint, await reproductionOf(summary, input2.scenePaths, ctx.io.cwd, join31(resolve23(ctx.io.cwd, input2.out ?? DEFAULT_RUNS_DIR), summary.runId)));
203064
+ emitFinished(ctx, summary, input2.out, upload3, input2.uploadHint, await reproductionOf(summary, input2.scenePaths, ctx.io.cwd, join31(resolve23(ctx.io.cwd, input2.out ?? DEFAULT_RUNS_DIR), summary.runId), input2.scenes));
203031
203065
  } catch (error64) {
203032
203066
  const code4 = toErrorJson(error64).code;
203033
203067
  const interrupted2 = error64 instanceof AnchaError && error64.code === "USAGE" && error64.message === "run interrupted";
@@ -203511,9 +203545,9 @@ function registerReplay(program2, ctx) {
203511
203545
  let relay;
203512
203546
  let canAnswer = choice4.url !== void 0;
203513
203547
  if (choice4.url === void 0 && hasPeople) {
203514
- const access7 = await modelAccess(ctx.io.env);
203515
- canAnswer = access7.kind !== "none";
203516
- if (access7.kind === "relay") relay = { baseUrl: access7.baseUrl, apiKey: access7.apiKey };
203548
+ const access8 = await modelAccess(ctx.io.env);
203549
+ canAnswer = access8.kind !== "none";
203550
+ if (access8.kind === "relay") relay = { baseUrl: access8.baseUrl, apiKey: access8.apiKey };
203517
203551
  }
203518
203552
  if (opts.people === "live" && hasPeople && !canAnswer) {
203519
203553
  throw new AnchaError("USAGE", "people can't answer live here: there is no model for them", { hint: "run ancha login, set OPENROUTER_API_KEY, or replay with --people strict" });
@@ -203783,12 +203817,12 @@ function registerSimulate(sceneCommand, ctx) {
203783
203817
  }
203784
203818
 
203785
203819
  // packages/cli/src/kit/init.ts
203786
- var import_yaml13 = __toESM(require_dist(), 1);
203787
- init_src();
203788
203820
  import { constants as constants5 } from "node:fs";
203789
203821
  import { lstat as lstat6, mkdir as mkdir18, open as open5, readFile as readFile31, rm as rm9, writeFile as writeFile18 } from "node:fs/promises";
203790
203822
  import { join as join42 } from "node:path";
203791
203823
  import { Writable } from "node:stream";
203824
+ var import_yaml13 = __toESM(require_dist(), 1);
203825
+ init_src();
203792
203826
 
203793
203827
  // packages/cli/src/kit/seeds.ts
203794
203828
  var import_yaml9 = __toESM(require_dist(), 1);
@@ -204577,11 +204611,11 @@ import { dirname as dirname15, join as join40, relative as relative9, resolve as
204577
204611
  async function model(ctx) {
204578
204612
  const env2 = ctx.io.env;
204579
204613
  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" };
204580
- const access7 = await modelAccess(env2);
204581
- if (access7.kind === "own") return { client: gen_exports.openRouterClient({ apiKey: access7.apiKey }), credit: "own" };
204582
- if (access7.kind === "relay") {
204614
+ const access8 = await modelAccess(env2);
204615
+ if (access8.kind === "own") return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey }), credit: "own" };
204616
+ if (access8.kind === "relay") {
204583
204617
  ctx.out.info(RELAY_NOTICE);
204584
- return { client: gen_exports.openRouterClient({ apiKey: access7.apiKey, baseUrl: access7.baseUrl, relay: true }), credit: "workspace" };
204618
+ return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey, baseUrl: access8.baseUrl, relay: true }), credit: "workspace" };
204585
204619
  }
204586
204620
  throw new AnchaError("CONFIG_INVALID", "world gen needs a model key", { hint: "set OPENROUTER_API_KEY, or log in to your workspace with ancha login, then run the same command again" });
204587
204621
  }
@@ -204903,11 +204937,11 @@ ${(0, import_yaml11.stringify)(sorted2, { lineWidth: 0 })}`;
204903
204937
  async function draftingModel(ctx) {
204904
204938
  const env2 = ctx.io.env;
204905
204939
  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" };
204906
- const access7 = await modelAccess(env2);
204907
- if (access7.kind === "own") return { client: gen_exports.openRouterClient({ apiKey: access7.apiKey }), credit: "own" };
204908
- if (access7.kind === "relay") {
204940
+ const access8 = await modelAccess(env2);
204941
+ if (access8.kind === "own") return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey }), credit: "own" };
204942
+ if (access8.kind === "relay") {
204909
204943
  ctx.out.info(RELAY_NOTICE);
204910
- return { client: gen_exports.openRouterClient({ apiKey: access7.apiKey, baseUrl: access7.baseUrl, relay: true }), credit: "workspace" };
204944
+ return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey, baseUrl: access8.baseUrl, relay: true }), credit: "workspace" };
204911
204945
  }
204912
204946
  throw new AnchaError("CONFIG_INVALID", "test new needs a model key", { hint: "set OPENROUTER_API_KEY, or log in to your workspace with ancha login, then run the same command again" });
204913
204947
  }
@@ -205022,7 +205056,7 @@ function registerTestNew(tests, ctx) {
205022
205056
  init_src();
205023
205057
  init_assets();
205024
205058
  import { readFile as readFile30 } from "node:fs/promises";
205025
- var DOC_TOPICS = ["setup", "apps", "run", "explain", "compare", "scenes", "integrations", "cloud", "playgrounds", "cli-quickstart", "tools"];
205059
+ var DOC_TOPICS = ["setup", "apps", "run", "traces", "explain", "compare", "scenes", "integrations", "cloud", "playgrounds", "cli-quickstart", "tools"];
205026
205060
  async function loadDoc(topic = "setup") {
205027
205061
  if (!DOC_TOPICS.includes(topic)) throw new AnchaError("USAGE", `unknown docs topic: ${topic}`, { hint: `available topics: ${DOC_TOPICS.join(", ")}` });
205028
205062
  return { topics: [...DOC_TOPICS], topic, markdown: await readFile30(new URL(`docs/${topic}.md`, assetRoot()), "utf8") };
@@ -205158,7 +205192,7 @@ async function addExampleSeeds(file3, twins) {
205158
205192
  return { added, skipped };
205159
205193
  }
205160
205194
  function registerKit(program2, ctx) {
205161
- program2.command("init").description("set up agent tests in this project: ancha.yaml, a starter scene for the tools it uses, coding-agent instructions; installs and runs nothing").option("--agent <command>", "the command that starts your agent (default: package.json scripts.start, a Procfile, pyproject.toml [project.scripts] or the Dockerfile CMD)").option("--template <template>", "starter or incidents", "starter").option("--intent <description>", "also generate a world (company, people, tool history) from this description and draft a first test with people for it (uses a model)").option("--idempotency-key <key>", "with --intent: return the first world and test for a repeated request instead of generating again").action(async (opts) => {
205195
+ program2.command("init").description("set up agent tests in this project: ancha.yaml, a starter scene for the tools it uses, coding-agent instructions; installs and runs nothing").option("--agent <command>", "the command that starts your agent (default: package.json scripts.start, a Procfile, pyproject.toml [project.scripts] or the Dockerfile CMD)").option("--template <template>", "starter or incidents", "starter").option("--intent <description>", "also generate a world (company, people, tool history) from this description and draft a first test with people for it (uses a model)").option("--idempotency-key <key>", "with --intent: return the first world and test for a repeated request instead of generating again").action(async (opts, command) => {
205162
205196
  if (opts.template !== "starter" && opts.template !== "incidents") throw new AnchaError("USAGE", `unknown template: ${opts.template}`, { hint: "available templates: starter, incidents" });
205163
205197
  if (opts.intent !== void 0 && !(ctx.io.env.ANCHA_PEOPLE_BASE_URL && ctx.io.env.ANCHA_PEOPLE_API_KEY) && (await modelAccess(ctx.io.env)).kind === "none") {
205164
205198
  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" });
@@ -205167,7 +205201,9 @@ function registerKit(program2, ctx) {
205167
205201
  const used = detection.sdks;
205168
205202
  const twins = used.length > 0 ? [...used] : [...STARTER_TWINS];
205169
205203
  const unchecked = twins.filter((twin) => !hasAccessCheck(twin));
205170
- const templates = opts.template === "starter" ? (await starterPack("starter", `Reach ${twins.map(toolName).join(", ")}`, twins)).filter((file3) => ["scene.yaml", "oracle.mjs", "null.mjs"].includes(file3.relativePath)) : await templateFiles(opts.template);
205204
+ const existing2 = opts.template === "starter" && command.getOptionValueSource("template") !== "cli" ? (await glob3("scenes/**/scene.yaml", { cwd: ctx.io.cwd, onlyFiles: true, followSymbolicLinks: false })).sort() : [];
205205
+ const starter = opts.template === "starter" && existing2.length === 0;
205206
+ const templates = existing2.length > 0 ? [] : opts.template === "starter" ? (await starterPack("starter", `Reach ${twins.map(toolName).join(", ")}`, twins)).filter((file3) => ["scene.yaml", "oracle.mjs", "null.mjs"].includes(file3.relativePath)) : await templateFiles(opts.template);
205171
205207
  const files2 = [
205172
205208
  { relativePath: "ancha.yaml", content: `${detection.agent === null ? "# Set agent.command to the command that starts your agent.\n" : (0, import_yaml13.stringify)({ agent: { command: detection.agent } })}scenes: [scenes/**/scene.yaml${opts.intent !== void 0 ? ", ancha/tests/*.yaml" : ""}]
205173
205209
  trials: 1
@@ -205201,14 +205237,15 @@ min_pass_rate: 1
205201
205237
  result.created.push(...world5.files, test3.file, test3.record);
205202
205238
  }
205203
205239
  const next2 = detection.agent === null ? ["set agent.command in ancha.yaml", "ancha run"] : generated ? [`ancha run ${generated.test.file} --json`] : ["ancha run"];
205204
- const output2 = { ...result, updated, detection, template: opts.template, ...opts.template === "starter" && { tools: twins, ...unchecked.length > 0 && { unchecked } }, ...generated, next: next2 };
205240
+ const output2 = { ...result, updated, detection, template: opts.template, ...starter && { tools: twins, ...unchecked.length > 0 && { unchecked } }, ...existing2.length > 0 && { scenes: existing2 }, ...generated, next: next2 };
205205
205241
  const agent = detection.agent === null ? "no start command found (package.json scripts.start, Procfile, pyproject.toml, Dockerfile)" : `${detection.agent}${detection.agentSource === "explicit" ? "" : ` (from ${detection.agentSource})`}`;
205206
205242
  const names3 = (list16) => list16.map(toolName).join(", ");
205207
205243
  ctx.out.result(output2, () => [
205208
205244
  `Created ${result.created.length} files; updated ${updated.length}; preserved ${result.skipped.length}.`,
205209
205245
  `agent: ${agent}`,
205210
- ...opts.template === "starter" ? [`starter: ${names3(twins)}${used.length > 0 ? "" : " (no tool SDK recognized in the dependencies)"}`] : [],
205211
- ...opts.template === "starter" && unchecked.length > 0 ? [` ${names3(unchecked)}: seeded; no access check, since ${unchecked.length === 1 ? "its" : "their"} requests need signing or a token exchange; add checks of your own`] : [],
205246
+ ...starter ? [`starter: ${names3(twins)}${used.length > 0 ? "" : " (no tool SDK recognized in the dependencies)"}`] : [],
205247
+ ...existing2.length > 0 ? [`scenes: ${existing2.length} already in scenes/ (${existing2.slice(0, 2).join(", ")}${existing2.length > 2 ? ", \u2026" : ""})${result.created.includes("ancha.yaml") ? "; ancha.yaml runs them" : ""}; ancha init --template starter adds the starter scene`] : [],
205248
+ ...starter && unchecked.length > 0 ? [` ${names3(unchecked)}: seeded; no access check, since ${unchecked.length === 1 ? "its" : "their"} requests need signing or a token exchange; add checks of your own`] : [],
205212
205249
  ...generated ? [`world: ${generated.world.file} (people: ${generated.world.people.join(", ") || "none"})`] : [],
205213
205250
  ...notGenerated?.added.length ? [` world gen populates ${gen_exports.GENERATED_TOOLS.join(", ")}; ${names3(notGenerated.added)} got ${notGenerated.added.length === 1 ? "its" : "their"} example data instead (ancha twins seed <tool> shows the fields)`] : [],
205214
205251
  ...notGenerated?.skipped.length ? [` ${names3(notGenerated.skipped)}: not in the world (the example data clashes with it); add a seed by hand (ancha twins seed <tool>)`] : [],
@@ -226290,7 +226327,7 @@ function registerRuns(program2, ctx) {
226290
226327
 
226291
226328
  // packages/cli/src/commands/traces.ts
226292
226329
  import { createHash as createHash68 } from "node:crypto";
226293
- import { readFile as readFile40, mkdir as mkdir26, writeFile as writeFile27 } from "node:fs/promises";
226330
+ import { access as access7, readFile as readFile40, mkdir as mkdir26, writeFile as writeFile27 } from "node:fs/promises";
226294
226331
  import { basename as basename12, dirname as dirname17, join as join55, relative as relative12, resolve as resolve40 } from "node:path";
226295
226332
  var import_yaml16 = __toESM(require_dist(), 1);
226296
226333
  init_src();
@@ -226489,8 +226526,8 @@ function workspaceError(status5, body6, path6) {
226489
226526
  function notInWorkspace(error64) {
226490
226527
  return error64 instanceof WorkspaceError && error64.status === 404 && !error64.noTraces;
226491
226528
  }
226492
- async function workspaceApi(ctx) {
226493
- const workspace3 = await uploadWorkspace(ctx);
226529
+ async function workspaceApi(ctx, hint = "run ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY") {
226530
+ const workspace3 = await uploadWorkspace(ctx, { message: "not logged in to a workspace", hint });
226494
226531
  const key3 = await apiKeyFor(workspace3, ctx.io.env);
226495
226532
  if (key3 === void 0) throw authError(workspace3, { keySent: false });
226496
226533
  const origin = new URL(workspace3).origin;
@@ -226648,6 +226685,14 @@ async function report6(ctx, world5, written) {
226648
226685
  ].join("\n")
226649
226686
  );
226650
226687
  }
226688
+ async function nextLines(ctx, paths2, dest) {
226689
+ const folder = relative12(ctx.io.cwd, resolve40(ctx.io.cwd, dest)) || ".", where2 = paths2.length === 1 ? relative12(ctx.io.cwd, paths2[0]) : `${folder}/*/scene.yaml`;
226690
+ const configured = ctx.globals().config !== void 0 || await access7(resolve40(ctx.io.cwd, "ancha.yaml")).then(() => true, () => false);
226691
+ if (!configured) return [`next: ancha init (it writes ancha.yaml; set agent.command to the command that starts your agent), then ancha run ${where2}`];
226692
+ const globs = await ctx.loadConfig().then((config9) => config9.scenes, () => void 0);
226693
+ const found = globs === void 0 ? void 0 : new Set(await glob3(globs, { cwd: ctx.io.cwd, absolute: true, onlyFiles: true }));
226694
+ return [`next: ancha run ${where2}`, ...!found || paths2.every((path6) => found.has(path6)) ? [] : [`note: scenes: in ancha.yaml does not include ${where2}; add ${folder}/**/scene.yaml to run them with the rest`]];
226695
+ }
226651
226696
  var when12 = (iso19) => iso19 ? `${new Date(iso19).toISOString().replace("T", " ").slice(0, 16)} UTC` : "-";
226652
226697
  var plural5 = (n, one7, many = `${one7}s`) => `${n} ${n === 1 ? one7 : many}`;
226653
226698
  function production2(trace) {
@@ -226759,7 +226804,7 @@ function registerTraces(program2, ctx) {
226759
226804
  ctx.out.result(made.result, () => made.text);
226760
226805
  return;
226761
226806
  }
226762
- const api3 = await workspaceApi(ctx);
226807
+ const api3 = await workspaceApi(ctx, `ancha import --offline ${options3.from ? `--from ${options3.from} ` : ""}${trace} makes the tests on this computer; ancha login sends traces to your workspace`);
226763
226808
  const { traces: imported } = await api3(`/v1/imports?name=${encodeURIComponent(source.name)}`, { method: "POST", headers: { "content-type": options3.from ? "application/json" : "application/x-ndjson" }, body: source.text });
226764
226809
  for (const { id: id12 } of imported) {
226765
226810
  const changes = await guard(ctx, resolve40(ctx.io.cwd, options3.dest, `trace-${id12.slice(0, 8)}`), options3.force);
@@ -226951,6 +226996,7 @@ async function importLocally(ctx, source, options3) {
226951
226996
  " the test has them only if the app makes them when it starts, or the start script or an app_calls entry does (ancha docs apps)"
226952
226997
  );
226953
226998
  }
226999
+ lines2.push(...await nextLines(ctx, [path6], options3.dest));
226954
227000
  return { result: { scene: relative12(ctx.io.cwd, path6), summary: m.made.summary, questions: m.made.questions, setup: setup2 }, text: lines2.join("\n") };
226955
227001
  }
226956
227002
  const questions = [...new Map(made.flatMap((m) => m.made.questions).reverse().map((q) => [q.id, q])).values()].reverse();
@@ -226965,6 +227011,7 @@ async function importLocally(ctx, source, options3) {
226965
227011
  ];
226966
227012
  const setups = made.filter((m) => m.made.setup.length).length;
226967
227013
  if (setups) lines.push(` warning: in ${plural5(setups, "test")}, calls came before the first event the test replays, the app's own setup (provenance.json lists them; ancha docs apps)`);
227014
+ lines.push(...await nextLines(ctx, paths2, options3.dest));
226968
227015
  return { result: { scenes: made.map((m, i) => ({ scene: relative12(ctx.io.cwd, paths2[i]), conversation: m.conversation.id, traces: m.conversation.traces, summary: m.made.summary, setup: setupOf(m) })), questions, skipped }, text: lines.join("\n") };
226969
227016
  }
226970
227017
 
@@ -226974,15 +227021,16 @@ function processIO() {
226974
227021
  return { stdout: process.stdout, stderr: process.stderr, cwd: process.cwd(), env: process.env };
226975
227022
  }
226976
227023
  var HELP_GROUPS = {
226977
- "Start:": ["init", "run", "explain", "baseline", "docs"],
227024
+ "Start:": ["init", "import", "run", "explain", "baseline", "docs"],
226978
227025
  "Cloud:": ["login", "whoami", "secrets", "traces"],
226979
- "Inspect:": ["world", "test", "twins", "connect", "doctor", "schema"],
227026
+ "Inspect:": ["world", "test", "twins", "connect", "doctor"],
226980
227027
  "More:": ["completion"]
226981
227028
  };
226982
- var ADVANCED = /* @__PURE__ */ new Set(["agent", "serve", "ui", "scene", "env", "sandbox", "mcp", "execution", "playground", "status", "wait", "logs", "report", "check", "runs", "attempt", "replay", "import", "pull", "logout"]);
227029
+ var ADVANCED = /* @__PURE__ */ new Set(["agent", "serve", "ui", "scene", "env", "sandbox", "mcp", "execution", "playground", "status", "wait", "logs", "report", "check", "runs", "attempt", "replay", "pull", "schema", "logout"]);
226983
227030
  var START = [
226984
227031
  "Ancha: simulation playgrounds for agents. Start here:",
226985
227032
  " ancha init set up this project: ancha.yaml, a starter scene, coding-agent instructions",
227033
+ " ancha import --offline <trace file> turn production traces into tests on this computer, one per conversation",
226986
227034
  " ancha run run your agent against fresh worlds and grade it",
226987
227035
  " ancha explain latest why it failed: each check, expected vs actual, the calls behind it",
226988
227036
  " ancha login use your hosted workspace at app.ancha.io (one browser approval)",