@ancha-labs/cli 0.4.45 → 0.4.47

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
@@ -23885,6 +23885,9 @@ var init_zod = __esm({
23885
23885
  function isErrorCode(value6) {
23886
23886
  return typeof value6 === "string" && ERROR_CODES.includes(value6);
23887
23887
  }
23888
+ function isErrorKind(value6) {
23889
+ return typeof value6 === "string" && ERROR_KINDS.includes(value6);
23890
+ }
23888
23891
  function exitCodeFor(code5) {
23889
23892
  switch (code5) {
23890
23893
  case "CHECKS_FAILED":
@@ -23914,14 +23917,15 @@ function exitCodeFor(code5) {
23914
23917
  }
23915
23918
  function toErrorJson(e) {
23916
23919
  if (e instanceof AnchaError) {
23917
- const out = { code: e.code, message: e.message };
23920
+ const out = { code: e.code, kind: e.kind, message: e.message };
23921
+ if (e.reference !== void 0) out.reference = e.reference;
23918
23922
  if (e.hint !== void 0) out.hint = e.hint;
23919
23923
  if (e.docs !== void 0) out.docs = e.docs;
23920
23924
  return out;
23921
23925
  }
23922
- return { code: "INTERNAL", message: e instanceof Error ? e.message : String(e) };
23926
+ return { code: "INTERNAL", kind: "ours", message: e instanceof Error ? e.message : String(e) };
23923
23927
  }
23924
- var ERROR_CODES, AnchaError;
23928
+ var ERROR_CODES, ERROR_KINDS, KIND_OF, AnchaError;
23925
23929
  var init_errors3 = __esm({
23926
23930
  "packages/core/src/errors.ts"() {
23927
23931
  "use strict";
@@ -23941,14 +23945,35 @@ var init_errors3 = __esm({
23941
23945
  "UNIMPLEMENTED_ENDPOINT",
23942
23946
  "INTERNAL"
23943
23947
  ];
23948
+ ERROR_KINDS = ["fix", "retry", "ours"];
23949
+ KIND_OF = {
23950
+ USAGE: "fix",
23951
+ CONFIG_INVALID: "fix",
23952
+ SCENE_INVALID: "fix",
23953
+ AUTH_INVALID: "fix",
23954
+ AGENT_SPAWN_FAILED: "fix",
23955
+ AGENT_UNREACHABLE: "fix",
23956
+ ENV_NOT_FOUND: "fix",
23957
+ SESSION_UNAUTHORIZED: "fix",
23958
+ CHECKS_FAILED: "fix",
23959
+ SERVER_UNREACHABLE: "retry",
23960
+ SERVER_START_FAILED: "retry",
23961
+ SESSION_CONFLICT: "retry",
23962
+ UNIMPLEMENTED_ENDPOINT: "ours",
23963
+ INTERNAL: "ours"
23964
+ };
23944
23965
  AnchaError = class extends Error {
23945
23966
  code;
23967
+ kind;
23968
+ reference;
23946
23969
  hint;
23947
23970
  docs;
23948
23971
  constructor(code5, message8, opts = {}) {
23949
23972
  super(message8, opts.cause === void 0 ? void 0 : { cause: opts.cause });
23950
23973
  this.name = "AnchaError";
23951
23974
  this.code = code5;
23975
+ this.kind = opts.kind ?? KIND_OF[code5];
23976
+ if (opts.reference !== void 0) this.reference = opts.reference;
23952
23977
  if (opts.hint !== void 0) this.hint = opts.hint;
23953
23978
  if (opts.docs !== void 0) this.docs = opts.docs;
23954
23979
  }
@@ -26404,7 +26429,7 @@ var init_google_ads = __esm({
26404
26429
  const customers3 = new Map(s3.customers.map((c) => [c.id, c]));
26405
26430
  if (customers3.size !== s3.customers.length)
26406
26431
  fail9(["customers"], "duplicate customer IDs");
26407
- const owner5 = (name5) => name5.split("/")[1];
26432
+ const owner6 = (name5) => name5.split("/")[1];
26408
26433
  for (const [i, c] of s3.customers.entries()) {
26409
26434
  if (c.parentId && (!customers3.get(c.parentId)?.manager || c.parentId === c.id))
26410
26435
  fail9(["customers", i], "parent must be another seeded manager");
@@ -26430,7 +26455,7 @@ var init_google_ads = __esm({
26430
26455
  if (names8.has(r2.resourceName))
26431
26456
  fail9([key5, i], "duplicate resource name");
26432
26457
  names8.add(r2.resourceName);
26433
- if (!customers3.has(owner5(r2.resourceName)) || customers3.get(owner5(r2.resourceName))?.manager)
26458
+ if (!customers3.has(owner6(r2.resourceName)) || customers3.get(owner6(r2.resourceName))?.manager)
26434
26459
  fail9([key5, i], "resource owner must be a seeded client customer");
26435
26460
  const number7 = "id" in r2 ? r2.id : "criterionId" in r2 ? r2.criterionId : r2.ad.id;
26436
26461
  if (r2.resourceName.split("/").at(-1).split("~").at(-1) !== number7)
@@ -26439,22 +26464,22 @@ var init_google_ads = __esm({
26439
26464
  }
26440
26465
  for (const [i, c] of s3.campaigns.entries()) {
26441
26466
  const b = s3.budgets.find((b2) => b2.resourceName === c.campaignBudget);
26442
- if (!b || owner5(b.resourceName) !== owner5(c.resourceName))
26467
+ if (!b || owner6(b.resourceName) !== owner6(c.resourceName))
26443
26468
  fail9(["campaigns", i], "budget must exist in same customer");
26444
26469
  if (b && !b.explicitlyShared && s3.campaigns.filter((c2) => c2.campaignBudget === b.resourceName && c2.status !== "REMOVED").length > 1)
26445
26470
  fail9(["campaigns", i], "budget is not shared");
26446
26471
  }
26447
26472
  for (const [i, a] of s3.adGroups.entries())
26448
- if (!s3.campaigns.some((c) => c.resourceName === a.campaign && owner5(c.resourceName) === owner5(a.resourceName)))
26473
+ if (!s3.campaigns.some((c) => c.resourceName === a.campaign && owner6(c.resourceName) === owner6(a.resourceName)))
26449
26474
  fail9(["adGroups", i], "campaign must exist in same customer");
26450
26475
  for (const key5 of ["ads", "criteria"])
26451
26476
  for (const [i, a] of s3[key5].entries()) {
26452
26477
  const group5 = s3.adGroups.find((g) => g.resourceName === a.adGroup);
26453
- if (!group5 || owner5(group5.resourceName) !== owner5(a.resourceName) || a.resourceName.split("/").at(-1).split("~")[0] !== group5.id)
26478
+ if (!group5 || owner6(group5.resourceName) !== owner6(a.resourceName) || a.resourceName.split("/").at(-1).split("~")[0] !== group5.id)
26454
26479
  fail9([key5, i], "ad group relationship invalid");
26455
26480
  }
26456
26481
  for (const [i, a] of s3.ads.entries())
26457
- if (a.ad.resourceName !== `customers/${owner5(a.resourceName)}/ads/${a.ad.id}`)
26482
+ if (a.ad.resourceName !== `customers/${owner6(a.resourceName)}/ads/${a.ad.id}`)
26458
26483
  fail9(["ads", i], "ad resource name does not match owner and ID");
26459
26484
  for (const [i, r2] of s3.reports.entries()) {
26460
26485
  if (!s3.campaigns.some((c) => c.resourceName === r2.campaign))
@@ -26463,7 +26488,7 @@ var init_google_ads = __esm({
26463
26488
  fail9(["reports", i], "clicks exceed impressions");
26464
26489
  if (s3.reports.slice(0, i).some((p2) => p2.campaign === r2.campaign && p2.date === r2.date))
26465
26490
  fail9(["reports", i], "duplicate campaign/date report");
26466
- if (customers3.get(owner5(r2.campaign))?.testAccount && (BigInt(r2.impressions) || BigInt(r2.clicks) || BigInt(r2.costMicros) || r2.conversions))
26491
+ if (customers3.get(owner6(r2.campaign))?.testAccount && (BigInt(r2.impressions) || BigInt(r2.clicks) || BigInt(r2.costMicros) || r2.conversions))
26467
26492
  fail9(["reports", i], "test account has no serving metrics");
26468
26493
  }
26469
26494
  });
@@ -27560,11 +27585,11 @@ var init_gong = __esm({
27560
27585
  });
27561
27586
  const calls2 = /* @__PURE__ */ new Map();
27562
27587
  seed44.calls.forEach((c, i) => {
27563
- const m = c.metaData, w2 = workspaces.get(m.workspaceId), owner5 = users5.get(m.primaryUserId);
27588
+ const m = c.metaData, w2 = workspaces.get(m.workspaceId), owner6 = users5.get(m.primaryUserId);
27564
27589
  if (calls2.has(m.id)) issue9(["calls", i, "metaData", "id"], "duplicate call identity");
27565
27590
  calls2.set(m.id, c);
27566
27591
  if (!w2) issue9(["calls", i, "metaData", "workspaceId"], "unknown workspace");
27567
- if (!owner5 || owner5.accountId !== w2?.accountId || !owner5.workspaceIds.includes(m.workspaceId)) issue9(["calls", i, "metaData", "primaryUserId"], "call owner must belong to its workspace and account");
27592
+ if (!owner6 || owner6.accountId !== w2?.accountId || !owner6.workspaceIds.includes(m.workspaceId)) issue9(["calls", i, "metaData", "primaryUserId"], "call owner must belong to its workspace and account");
27568
27593
  if (c.recordingKind === "web-conference" && !m.scheduled) issue9(["calls", i, "metaData", "scheduled"], "web-conference calls require scheduled time");
27569
27594
  if (c.transcriptAvailableAfterMs < c.availableAfterMs) issue9(["calls", i, "transcriptAvailableAfterMs"], "transcript cannot be available before call metadata");
27570
27595
  const speakers = /* @__PURE__ */ new Set(), parties = /* @__PURE__ */ new Set();
@@ -36351,7 +36376,7 @@ function books(seed44, issue9, money24) {
36351
36376
  };
36352
36377
  for (const [index, f2] of seed44.itemFulfillments.entries()) ship("itemFulfillments", index, f2.salesOrder, f2.lines, "customer");
36353
36378
  for (const [index, r2] of seed44.itemReceipts.entries()) ship("itemReceipts", index, r2.purchaseOrder, r2.lines, "vendor");
36354
- const billFrom = (name5, index, order6, list19, who2, owner5) => {
36379
+ const billFrom = (name5, index, order6, list19, who2, owner6) => {
36355
36380
  const lines3 = orderLines.get(order6), kind2 = who2 === "customer" ? seed44.salesOrders : seed44.purchaseOrders, path9 = [name5, index, who2 === "customer" ? "salesOrder" : "purchaseOrder"];
36356
36381
  const label7 = who2 === "customer" ? "sales order" : "purchase order";
36357
36382
  if (!lines3 || !kind2.some((o) => o.id === order6)) {
@@ -36359,7 +36384,7 @@ function books(seed44, issue9, money24) {
36359
36384
  return;
36360
36385
  }
36361
36386
  const source = kind2.find((o) => o.id === order6);
36362
- if (("customer" in source ? source.customer : source.vendor) !== owner5) issue9(path9, `${label7} belongs to another ${who2}`);
36387
+ if (("customer" in source ? source.customer : source.vendor) !== owner6) issue9(path9, `${label7} belongs to another ${who2}`);
36363
36388
  if (source.pendingApproval) issue9(path9, `${label7} is pending approval`);
36364
36389
  for (const [i, line2] of list19.entries()) {
36365
36390
  if (!lines3.some((l) => l.item === line2.item)) {
@@ -36400,13 +36425,13 @@ function books(seed44, issue9, money24) {
36400
36425
  const applied = /* @__PURE__ */ new Map();
36401
36426
  const applies = (name5, docs2, label7) => {
36402
36427
  for (const [index, t] of seed44[name5].entries()) {
36403
- const owner5 = "vendor" in t ? t.vendor : t.customer, seen = /* @__PURE__ */ new Set();
36428
+ const owner6 = "vendor" in t ? t.vendor : t.customer, seen = /* @__PURE__ */ new Set();
36404
36429
  for (const [i, a] of t.apply.entries()) {
36405
36430
  const path9 = [name5, index, "apply", i, "doc"], doc = docs2.get(a.doc);
36406
36431
  const journal = seed44.journalEntries.find((j) => j.id === a.doc);
36407
36432
  if (journal) {
36408
36433
  const side = ["vendorPayments", "vendorCredits"].includes(name5) ? "AcctPay" : "AcctRec";
36409
- const candidates2 = journal.lines.map((l, i2) => ({ ...l, line: i2 + 1 })).filter((l) => l.entity === owner5 && accountById.get(l.account)?.type === side && (side === "AcctRec" ? l.debit ?? 0 : l.credit ?? 0) > 0);
36434
+ const candidates2 = journal.lines.map((l, i2) => ({ ...l, line: i2 + 1 })).filter((l) => l.entity === owner6 && accountById.get(l.account)?.type === side && (side === "AcctRec" ? l.debit ?? 0 : l.credit ?? 0) > 0);
36410
36435
  const line2 = a.line === void 0 ? void 0 : candidates2.find((l) => l.line === a.line);
36411
36436
  const key5 = `${a.doc}:${a.line === void 0 ? "auto" : line2?.line}`;
36412
36437
  if ((a.line === void 0 ? !candidates2.length : !line2) || seen.has(key5) || journal.approval === "pending") issue9(path9, "invalid journal application line");
@@ -36421,7 +36446,7 @@ function books(seed44, issue9, money24) {
36421
36446
  issue9(path9, `missing ${label7}`);
36422
36447
  continue;
36423
36448
  }
36424
- if (doc.owner !== owner5) issue9(path9, `${label7} belongs to another ${"vendor" in t ? "vendor" : "customer"}`);
36449
+ if (doc.owner !== owner6) issue9(path9, `${label7} belongs to another ${"vendor" in t ? "vendor" : "customer"}`);
36425
36450
  else sameBooks(t.id, a.doc, path9, label7, KIND[name5]);
36426
36451
  if (doc.approved === false) issue9(path9, `${label7} is not approved`);
36427
36452
  applied.set(a.doc, (applied.get(a.doc) ?? 0) + a.amount);
@@ -36490,7 +36515,7 @@ function books(seed44, issue9, money24) {
36490
36515
  for (const name5 of ["creditMemos", "vendorCredits", "customerPayments", "vendorPayments"]) for (const [index, t] of seed44[name5].entries()) {
36491
36516
  const extended2 = "credit" in t && t.credit.length > 0 || t.apply.some((a) => seed44.journalEntries.some((j) => j.id === a.doc) || a.line !== void 0 && a.line !== 0) || "arAcct" in t && t.arAcct !== void 0 || "apAcct" in t && t.apAcct !== void 0 || "amount" in t && t.amount === 0;
36492
36517
  if (!extended2) continue;
36493
- const owner5 = "customer" in t ? t.customer : t.vendor, control = "arAcct" in t ? t.arAcct : "apAcct" in t ? t.apAcct : void 0;
36518
+ const owner6 = "customer" in t ? t.customer : t.vendor, control = "arAcct" in t ? t.arAcct : "apAcct" in t ? t.apAcct : void 0;
36494
36519
  const acct = control ?? ("customer" in t ? ar : ap) ?? 0;
36495
36520
  if (control !== void 0) account9(control, [name5, index, "customer" in t ? "arAcct" : "apAcct"], ["customer" in t ? "AcctRec" : "AcctPay"]);
36496
36521
  let gross = 0, credit = 0;
@@ -36498,7 +36523,7 @@ function books(seed44, issue9, money24) {
36498
36523
  for (const [role3, list19] of [["debt", t.apply], ["credit", "credit" in t ? t.credit : []]]) {
36499
36524
  const seen = /* @__PURE__ */ new Set();
36500
36525
  for (const [i, a] of list19.entries()) {
36501
- const eligible = open17.filter((o) => o.doc === a.doc && o.owner === owner5 && o.account === acct && o.role === role3 && o.amount > 4e-3);
36526
+ const eligible = open17.filter((o) => o.doc === a.doc && o.owner === owner6 && o.account === acct && o.role === role3 && o.amount > 4e-3);
36502
36527
  const available2 = eligible.filter((o) => o.amount - (before.get(`${o.doc}:${o.line}`) ?? 0) > 4e-3);
36503
36528
  const item2 = a.line === void 0 && available2.length === 1 ? available2[0] : eligible.find((o) => o.line === (a.line ?? 0));
36504
36529
  const key5 = `${a.doc}:${item2?.line}`, path9 = [name5, index, role3 === "debt" ? "apply" : "credit", i];
@@ -37749,15 +37774,15 @@ var init_quickbooks = __esm({
37749
37774
  }
37750
37775
  }
37751
37776
  const targets = { EmployeeRef: "Employee", CustomerRef: "Customer", VendorRef: "Vendor", PrefVendorRef: "Vendor", ItemRef: "Item", ClassRef: "Class", DepartmentRef: "Department", SalesTermRef: "Term", TermRef: "Term", PaymentMethodRef: "PaymentMethod", DefaultTaxCodeRef: "TaxCode", TaxCodeRef: "TaxCode", TxnTaxCodeRef: "TaxCode", TaxRateRef: "TaxRate", DefaultARAccount: "Account", DefaultAPAccount: "Account" };
37752
- const visit4 = (value6, owner5, path9) => {
37777
+ const visit4 = (value6, owner6, path9) => {
37753
37778
  if (Array.isArray(value6)) {
37754
- value6.forEach((v, i) => visit4(v, owner5, [...path9, i]));
37779
+ value6.forEach((v, i) => visit4(v, owner6, [...path9, i]));
37755
37780
  return;
37756
37781
  }
37757
37782
  if (!value6 || typeof value6 !== "object") return;
37758
37783
  const object28 = value6;
37759
37784
  for (const [key5, v] of Object.entries(object28)) {
37760
- const type = key5 === "EntityRef" && owner5 === "Attachable" ? QUICKBOOKS_ENTITIES.find((t) => t.toLowerCase() === String(v?.type ?? "").toLowerCase()) : key5 === "ParentRef" ? owner5 : key5.includes("AccountRef") ? "Account" : targets[key5];
37785
+ const type = key5 === "EntityRef" && owner6 === "Attachable" ? QUICKBOOKS_ENTITIES.find((t) => t.toLowerCase() === String(v?.type ?? "").toLowerCase()) : key5 === "ParentRef" ? owner6 : key5.includes("AccountRef") ? "Account" : targets[key5];
37761
37786
  if (type && v && typeof v === "object" && typeof v.value === "string" && !(key5 === "TaxCodeRef" && ["TAX", "NON"].includes(v.value))) {
37762
37787
  const candidates2 = seed44.entities[type] ?? [];
37763
37788
  if (candidates2.every((r2) => typeof r2.Id === "string")) {
@@ -37765,8 +37790,8 @@ var init_quickbooks = __esm({
37765
37790
  if (!target6 || target6.Active === false) ctx.addIssue({ code: "custom", path: [...path9, key5], message: `${type} ${v.value} ${target6 ? "is inactive" : "does not exist"}.` });
37766
37791
  }
37767
37792
  }
37768
- if (key5 === "EntityRef" && owner5 === "Attachable" && !type) ctx.addIssue({ code: "custom", path: [...path9, key5, "type"], message: "Supply a recognized entity type." });
37769
- visit4(v, owner5, [...path9, key5]);
37793
+ if (key5 === "EntityRef" && owner6 === "Attachable" && !type) ctx.addIssue({ code: "custom", path: [...path9, key5, "type"], message: "Supply a recognized entity type." });
37794
+ visit4(v, owner6, [...path9, key5]);
37770
37795
  }
37771
37796
  };
37772
37797
  for (const [type, rows35] of Object.entries(seed44.entities)) rows35?.forEach((row2, i) => visit4(row2, type, ["entities", type, i]));
@@ -38744,8 +38769,8 @@ function validateRefs(scene2) {
38744
38769
  sceneMessageMatches(scene2, (match3, p2) => {
38745
38770
  if (match3.in !== void 0) {
38746
38771
  const decl = use(`${p2}.in`, match3.in, ["channel", "issue", "pull"]);
38747
- const owner5 = decl?.kind === "channel" ? "slack" : "github";
38748
- if (decl && !decl.path.startsWith(`seed.${owner5}.`) && !decl.path.startsWith("world_rules.")) issues.push({ path: `${p2}.in`, message: `${match3.in} is not a Slack channel or a GitHub issue or pull request`, hint: "messages are Slack messages and GitHub issues and comments" });
38772
+ const owner6 = decl?.kind === "channel" ? "slack" : "github";
38773
+ if (decl && !decl.path.startsWith(`seed.${owner6}.`) && !decl.path.startsWith("world_rules.")) issues.push({ path: `${p2}.in`, message: `${match3.in} is not a Slack channel or a GitHub issue or pull request`, hint: "messages are Slack messages and GitHub issues and comments" });
38749
38774
  }
38750
38775
  if (match3.in_thread_of !== void 0) use(`${p2}.in_thread_of`, match3.in_thread_of, "message");
38751
38776
  if (match3.from?.startsWith("$")) use(`${p2}.from`, match3.from, ["user", "person"]);
@@ -39287,17 +39312,17 @@ function peopleIssues(scene2) {
39287
39312
  };
39288
39313
  const item2 = (path9, ref23) => {
39289
39314
  const { person: who2, id: id15 } = splitPersonItem(ref23);
39290
- const owner5 = byName.get(who2);
39291
- if (!owner5) {
39315
+ const owner6 = byName.get(who2);
39316
+ if (!owner6) {
39292
39317
  add(path9, `unknown person ${who2} in ${ref23}`, `people: ${listed2(byName.keys())}`);
39293
39318
  return void 0;
39294
39319
  }
39295
- const fact2 = owner5.knows?.find((f2) => f2.id === id15);
39320
+ const fact2 = owner6.knows?.find((f2) => f2.id === id15);
39296
39321
  if (fact2) return fact2;
39297
39322
  add(
39298
39323
  path9,
39299
- owner5.decides?.some((d) => d.id === id15) ? `${ref23} is a decision, not a fact` : `${who2} has no fact ${id15}`,
39300
- `${who2}'s facts: ${listed2((owner5.knows ?? []).map((f2) => `${who2}.${f2.id}`))}`
39324
+ owner6.decides?.some((d) => d.id === id15) ? `${ref23} is a decision, not a fact` : `${who2} has no fact ${id15}`,
39325
+ `${who2}'s facts: ${listed2((owner6.knows ?? []).map((f2) => `${who2}.${f2.id}`))}`
39301
39326
  );
39302
39327
  return void 0;
39303
39328
  };
@@ -39408,10 +39433,10 @@ function peopleIssues(scene2) {
39408
39433
  facts.forEach((fact2, k) => item2(`${path9}[${k + 1}]`, fact2));
39409
39434
  };
39410
39435
  const decidedTuple = (path9, [who2, id15, option4]) => {
39411
- const owner5 = person5(`${path9}[0]`, who2);
39412
- const decision2 = owner5?.decides?.find((d) => d.id === id15);
39413
- if (owner5 && !decision2) add(`${path9}[1]`, `${owner5.ref} has no decision ${id15}`, `${owner5.ref}'s decisions: ${listed2((owner5.decides ?? []).map((d) => d.id))}`);
39414
- if (decision2 && option4 !== void 0 && !decision2.options.includes(option4)) add(`${path9}[2]`, `${option4} is not an option of ${owner5.ref}.${id15}`, `options: ${decision2.options.join(", ")}`);
39436
+ const owner6 = person5(`${path9}[0]`, who2);
39437
+ const decision2 = owner6?.decides?.find((d) => d.id === id15);
39438
+ if (owner6 && !decision2) add(`${path9}[1]`, `${owner6.ref} has no decision ${id15}`, `${owner6.ref}'s decisions: ${listed2((owner6.decides ?? []).map((d) => d.id))}`);
39439
+ if (decision2 && option4 !== void 0 && !decision2.options.includes(option4)) add(`${path9}[2]`, `${option4} is not an option of ${owner6.ref}.${id15}`, `options: ${decision2.options.join(", ")}`);
39415
39440
  };
39416
39441
  const revealed = (path9, facts) => facts.forEach((ref23, k) => {
39417
39442
  const found = item2(`${path9}[${k}]`, ref23);
@@ -47121,12 +47146,12 @@ function githubSeedIssues(scene2) {
47121
47146
  for (const r2 of github3?.repos ?? []) for (const c of r2.commits) owners.set(c.ref, r2.ref);
47122
47147
  const sameRepo = (path9, value6, repo4) => {
47123
47148
  const name5 = refName5(value6);
47124
- const owner5 = name5 === void 0 ? void 0 : owners.get(name5);
47125
- if (owner5 !== void 0 && owner5 !== repo4) {
47149
+ const owner6 = name5 === void 0 ? void 0 : owners.get(name5);
47150
+ if (owner6 !== void 0 && owner6 !== repo4) {
47126
47151
  issues.push({ path: path9, message: `${value6} must belong to the same repo ($${repo4})`, hint: "choose a commit declared in this repository" });
47127
47152
  return void 0;
47128
47153
  }
47129
- return owner5 === repo4 ? name5 : void 0;
47154
+ return owner6 === repo4 ? name5 : void 0;
47130
47155
  };
47131
47156
  const repoNames = /* @__PURE__ */ new Set();
47132
47157
  github3?.repos.forEach((r2, i) => {
@@ -49126,7 +49151,7 @@ function retireVendors(b) {
49126
49151
  const quiet = b.vendors.filter((v) => !v.inactive && v.kind === "service" && b.bills.some((x) => x.vendor.id === v.id) && b.bills.filter((x) => x.vendor.id === v.id).every((x) => x.open === 0 && x.approval === "approved" && x.day > 150));
49127
49152
  for (const v of quiet.slice(0, 3)) v.inactive = true;
49128
49153
  }
49129
- function plantJournals(b, owner5) {
49154
+ function plantJournals(b, owner6) {
49130
49155
  const entries4 = [
49131
49156
  [b.r.int(2, 8), "Accrue year-end bonus pool", "6000", "2150", SUB.holdings],
49132
49157
  [b.r.int(3, 12), "Reclass inbound freight to inventory", "1300", "6300", SUB.flow],
@@ -49147,7 +49172,7 @@ function plantJournals(b, owner5) {
49147
49172
  memo: memo4,
49148
49173
  subsidiary,
49149
49174
  approval: "pending",
49150
- custom: { custbody_approval_owner: owner5 },
49175
+ custom: { custbody_approval_owner: owner6 },
49151
49176
  lines: [{ account: account2(debit), debit: money10(amount6), department: 3 }, { account: account2(credit), credit: money10(amount6), department: 3 }]
49152
49177
  });
49153
49178
  }
@@ -49956,7 +49981,7 @@ function pay(b) {
49956
49981
  }
49957
49982
  }
49958
49983
  function journals(b) {
49959
- const entries4 = [], owner5 = b.employee("controller");
49984
+ const entries4 = [], owner6 = b.employee("controller");
49960
49985
  const add = (date11, memo4, subsidiary, lines2, more = {}) => entries4.push({
49961
49986
  id: 0,
49962
49987
  date: day7(date11),
@@ -49972,7 +49997,7 @@ function journals(b) {
49972
49997
  ...l.class !== void 0 && { class: l.class },
49973
49998
  ...l.memo && { memo: l.memo }
49974
49999
  })),
49975
- custom: { custbody_approval_owner: owner5 },
50000
+ custom: { custbody_approval_owner: owner6 },
49976
50001
  sort: date11
49977
50002
  });
49978
50003
  const m = b.size, perMonth = m.journalEntries >= 300, payrollEvery = m.journalEntries >= 600 ? 7 : perMonth ? 14 : 30;
@@ -50020,7 +50045,7 @@ function journals(b) {
50020
50045
  }
50021
50046
  entries4.sort((x, y) => y.sort - x.sort);
50022
50047
  b.seed.journalEntries.push(...entries4.map(({ sort: _, ...e }) => e));
50023
- plantJournals(b, owner5);
50048
+ plantJournals(b, owner6);
50024
50049
  }
50025
50050
  function intercompany(b) {
50026
50051
  const id15 = Math.max(...b.seed.accounts.map((a) => a.id)) + 1;
@@ -66759,8 +66784,8 @@ function buildWwwAuthenticateHeader(errorCode, description2, requiredScopes, res
66759
66784
  function bearerAuthChallengeResponse(error65, options5) {
66760
66785
  const { requiredScopes = [], resourceMetadataUrl } = options5 ?? {};
66761
66786
  if (!(error65 instanceof OAuthError)) {
66762
- const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error");
66763
- return Response.json(serverError.toResponseObject(), { status: 500 });
66787
+ const serverError2 = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error");
66788
+ return Response.json(serverError2.toResponseObject(), { status: 500 });
66764
66789
  }
66765
66790
  switch (error65.code) {
66766
66791
  case OAuthErrorCode.InvalidToken: {
@@ -70031,7 +70056,7 @@ function registerGithubRepositoryTools(server, api4) {
70031
70056
  fields: external_exports.array(external_exports.enum(["sha", "html_url", "commit", "author", "committer"])).optional()
70032
70057
  })
70033
70058
  }, (args, context3) => {
70034
- const { owner: owner5, repo: name5, perPage, fields: fields13, ...query12 } = args;
70059
+ const { owner: owner6, repo: name5, perPage, fields: fields13, ...query12 } = args;
70035
70060
  return invoke2(
70036
70061
  "GET",
70037
70062
  `${root(args)}/commits?${params({ ...query12, per_page: perPage })}`,
@@ -70194,17 +70219,17 @@ function githubMcpServer(info2, request2) {
70194
70219
  server.registerTool("github_repositories_list", { description: "List repositories visible to the mock authenticated user.", inputSchema: external_exports.strictObject(page4.shape) }, (args) => call4("GET", `user/repos?${new URLSearchParams(Object.entries(args).filter(([, v]) => v !== void 0).map(([k, v]) => [k, String(v)]))}`));
70195
70220
  server.registerTool("github_repository_get", { description: "Read one repository.", inputSchema: external_exports.strictObject(repo3) }, (args) => call4("GET", `repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}`));
70196
70221
  server.registerTool("github_issues_list", { description: "List repository issues. Pull requests may also appear in the native issues endpoint.", inputSchema: external_exports.strictObject({ ...repo3, ...page4.shape, state: external_exports.enum(["open", "closed", "all"]).optional() }) }, (args) => {
70197
- const { owner: owner5, repo: name5, ...query12 } = args;
70222
+ const { owner: owner6, repo: name5, ...query12 } = args;
70198
70223
  const params10 = new URLSearchParams(Object.entries(query12).filter(([, v]) => v !== void 0).map(([k, v]) => [k, String(v)]));
70199
- return call4("GET", `repos/${encodeURIComponent(owner5)}/${encodeURIComponent(name5)}/issues?${params10}`);
70224
+ return call4("GET", `repos/${encodeURIComponent(owner6)}/${encodeURIComponent(name5)}/issues?${params10}`);
70200
70225
  });
70201
70226
  server.registerTool("github_issue_get", { description: "Read one issue.", inputSchema: external_exports.strictObject({ ...repo3, issue_number: external_exports.number().int().min(1) }) }, (args) => call4("GET", `repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}/issues/${args.issue_number}`));
70202
70227
  server.registerTool("github_issue_create", { description: "Create an issue in a mock repository.", inputSchema: external_exports.strictObject({ ...repo3, title: external_exports.string().min(1).max(256), body: external_exports.string().max(65536).optional() }), annotations: { destructiveHint: false, openWorldHint: false } }, (args) => call4("POST", `repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}/issues`, { title: args.title, ...args.body === void 0 ? {} : { body: args.body } }));
70203
70228
  server.registerTool("github_issue_comment", { description: "Add a comment to an issue or pull request conversation.", inputSchema: external_exports.strictObject({ ...repo3, issue_number: external_exports.number().int().min(1), body: external_exports.string().min(1).max(65536) }) }, (args) => call4("POST", `repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}/issues/${args.issue_number}/comments`, { body: args.body }));
70204
70229
  server.registerTool("github_pulls_list", { description: "List pull requests in a repository.", inputSchema: external_exports.strictObject({ ...repo3, ...page4.shape, state: external_exports.enum(["open", "closed", "all"]).optional() }) }, (args) => {
70205
- const { owner: owner5, repo: name5, ...query12 } = args;
70230
+ const { owner: owner6, repo: name5, ...query12 } = args;
70206
70231
  const params10 = new URLSearchParams(Object.entries(query12).filter(([, v]) => v !== void 0).map(([k, v]) => [k, String(v)]));
70207
- return call4("GET", `repos/${encodeURIComponent(owner5)}/${encodeURIComponent(name5)}/pulls?${params10}`);
70232
+ return call4("GET", `repos/${encodeURIComponent(owner6)}/${encodeURIComponent(name5)}/pulls?${params10}`);
70208
70233
  });
70209
70234
  server.registerTool("github_pull_get", { description: "Read one pull request.", inputSchema: external_exports.strictObject({ ...repo3, pull_number: external_exports.number().int().min(1) }) }, (args) => call4("GET", `repos/${encodeURIComponent(args.owner)}/${encodeURIComponent(args.repo)}/pulls/${args.pull_number}`));
70210
70235
  registerGithubVendorTools(server, client2);
@@ -70266,7 +70291,7 @@ function registerGithubVendorTools(server, client2) {
70266
70291
  if (["milestone", "type", "duplicate_of", "parent_issue_number", "parent_owner", "parent_repo", "issue_fields"].some((key5) => args[key5] !== void 0)) return mcpCoverageGap("issue_write", "Milestones, issue types, parent issues and custom fields are not implemented");
70267
70292
  if (args.method === "create" && !args.title) return mcpJsonResult({ message: "title is required to create an issue" }, true);
70268
70293
  if (args.method === "update" && !args.issue_number) return mcpJsonResult({ message: "issue_number is required to update an issue" }, true);
70269
- const { method: method2, owner: owner5, repo: name5, issue_number, ...body8 } = args;
70294
+ const { method: method2, owner: owner6, repo: name5, issue_number, ...body8 } = args;
70270
70295
  return invoke2(method2 === "create" ? "POST" : "PATCH", `${root3(args)}/issues${method2 === "update" ? `/${issue_number}` : ""}`, body8, ctx.mcpReq.signal, (value6) => {
70271
70296
  const issue9 = { id: String(value6.id), url: value6.html_url };
70272
70297
  return { text: issue9, structured: { method: method2, issue: issue9 } };
@@ -70299,7 +70324,7 @@ function registerGithubVendorTools(server, client2) {
70299
70324
  return mcpJsonResult(result);
70300
70325
  });
70301
70326
  server.registerTool("list_pull_requests", { description: "List pull requests in a repository.", inputSchema: external_exports.strictObject({ ...repo3, ...vendorPage, state: external_exports.enum(["open", "closed", "all"]).optional(), head: external_exports.string().optional(), base: external_exports.string().optional(), sort: external_exports.enum(["created", "updated", "popularity", "long-running"]).optional(), direction: external_exports.enum(["asc", "desc"]).optional(), fields: pullFields }), annotations: { readOnlyHint: true } }, (args, ctx) => {
70302
- const { owner: owner5, repo: name5, fields: fields13, perPage, ...params10 } = args;
70327
+ const { owner: owner6, repo: name5, fields: fields13, perPage, ...params10 } = args;
70303
70328
  return invoke2("GET", `${root3(args)}/pulls?${query({ ...params10, per_page: perPage })}`, void 0, ctx.mcpReq.signal, (value6) => ({ text: value6.map((pull2) => select(minimalPull(pull2), fields13)) }));
70304
70329
  });
70305
70330
  server.registerTool("pull_request_read", { description: "Read a pull request or its comments.", inputSchema: external_exports.strictObject({ ...repo3, pullNumber: number6, method: external_exports.enum(["get", "get_diff", "get_status", "get_files", "get_commits", "get_review_comments", "get_reviews", "get_comments", "get_check_runs"]), ...vendorPage, after: external_exports.string().optional() }), annotations: { readOnlyHint: true } }, (args, ctx) => {
@@ -96167,7 +96192,7 @@ function seedStorage(ctx, id15, seed44, users5, startMs3) {
96167
96192
  }
96168
96193
  for (const object28 of seed44.objects) {
96169
96194
  const bytes4 = object28.text !== void 0 ? Buffer.from(object28.text, "utf8") : Buffer.from(object28.base64, "base64");
96170
- const sha2568 = createHash11("sha256").update(bytes4).digest("hex"), owner5 = object28.owner ? users5.get(object28.owner) : null;
96195
+ const sha2568 = createHash11("sha256").update(bytes4).digest("hex"), owner6 = object28.owner ? users5.get(object28.owner) : null;
96171
96196
  const contentType = object28.content_type ?? (object28.text !== void 0 ? "text/plain;charset=UTF-8" : "application/octet-stream");
96172
96197
  const metadata8 = {
96173
96198
  eTag: `"${createHash11("md5").update(bytes4).digest("hex")}"`,
@@ -96180,7 +96205,7 @@ function seedStorage(ctx, id15, seed44, users5, startMs3) {
96180
96205
  };
96181
96206
  const run7 = execute(id15, [{
96182
96207
  text: `insert into storage.objects (bucket_id, name, owner, owner_id, metadata, version) values ($1, $2, $3::uuid, $3::text, $4, $5) returning id`,
96183
- params: [object28.bucket, object28.path, owner5, JSON.stringify(metadata8), uuidFrom(ctx, `version:${object28.bucket}/${object28.path}`)]
96208
+ params: [object28.bucket, object28.path, owner6, JSON.stringify(metadata8), uuidFrom(ctx, `version:${object28.bucket}/${object28.path}`)]
96184
96209
  }], startMs3);
96185
96210
  if (run7.error) throw new AnchaError(
96186
96211
  "SCENE_INVALID",
@@ -97204,8 +97229,8 @@ function reaches(env2, message8, accounts2, listens, channels) {
97204
97229
  }
97205
97230
  function authorOf(message8, people4, bot) {
97206
97231
  const owns = (accounts2) => message8.tool === "slack" ? accounts2.slack === message8.authorId : message8.tool === "gmail" ? accounts2.gmail?.toLowerCase() === message8.authorId : accounts2.github?.id === message8.authorId;
97207
- const owner5 = people4.find(({ accounts: accounts2 }) => owns(accounts2));
97208
- if (owner5) return personName(owner5.person.ref);
97232
+ const owner6 = people4.find(({ accounts: accounts2 }) => owns(accounts2));
97233
+ if (owner6) return personName(owner6.person.ref);
97209
97234
  if (owns(bot)) return "agent";
97210
97235
  return `${message8.tool}:${message8.authorId}`;
97211
97236
  }
@@ -99662,12 +99687,12 @@ function seed3(ctx) {
99662
99687
  return id15;
99663
99688
  };
99664
99689
  for (const repo4 of github3.repos) {
99665
- const [owner5, name5] = repo4.name.split("/"), numbers3 = githubSeedNumbers(repo4);
99666
- if (!ctx.store.db.prepare("SELECT 1 FROM github_users WHERE login = ?").get(owner5) && !ctx.store.db.prepare("SELECT 1 FROM github_organizations WHERE login = ?").get(owner5)) {
99667
- ctx.store.db.prepare("INSERT INTO github_organizations (id,login) VALUES (?,?)").run(resourceId(ctx), owner5);
99690
+ const [owner6, name5] = repo4.name.split("/"), numbers3 = githubSeedNumbers(repo4);
99691
+ if (!ctx.store.db.prepare("SELECT 1 FROM github_users WHERE login = ?").get(owner6) && !ctx.store.db.prepare("SELECT 1 FROM github_organizations WHERE login = ?").get(owner6)) {
99692
+ ctx.store.db.prepare("INSERT INTO github_organizations (id,login) VALUES (?,?)").run(resourceId(ctx), owner6);
99668
99693
  }
99669
99694
  const repoId = resourceId(ctx);
99670
- ctx.store.db.prepare("INSERT INTO github_repos (id,ref,owner,name,full_name,default_branch,private,next_issue_number) VALUES (?,?,?,?,?,?,?,?)").run(repoId, repo4.ref, owner5, name5, repo4.name, repo4.default_branch, repo4.private ? 1 : 0, numbers3.next);
99695
+ ctx.store.db.prepare("INSERT INTO github_repos (id,ref,owner,name,full_name,default_branch,private,next_issue_number) VALUES (?,?,?,?,?,?,?,?)").run(repoId, repo4.ref, owner6, name5, repo4.name, repo4.default_branch, repo4.private ? 1 : 0, numbers3.next);
99671
99696
  ctx.refs.register(repo4.ref, "repo", "github", String(repoId));
99672
99697
  for (const collaborator of repo4.collaborators ?? []) {
99673
99698
  ctx.store.db.prepare("INSERT INTO github_collaborators (repo_id,user_id,permission) VALUES (?,?,?)").run(repoId, userForRef(ctx, collaborator.user).id, collaborator.permission);
@@ -99858,9 +99883,9 @@ function githubEvent(ctx, type, payload3, additionalLinks = []) {
99858
99883
  for (const link9 of ["self", "issue", "comments", "review_comments", "review_comment", "commits", "statuses"]) fields13(`/pull_request/_links/${link9}`, ["href"]);
99859
99884
  fields13("/issue", ["url", "repository_url", "labels_url", "comments_url", "events_url"]);
99860
99885
  user9("/issue/user");
99861
- for (const owner5 of ["issue", "pull_request"]) {
99862
- const labels2 = body8[owner5]?.labels;
99863
- if (Array.isArray(labels2)) labels2.forEach((_, i) => fields13(`/${owner5}/labels/${i}`, ["url"]));
99886
+ for (const owner6 of ["issue", "pull_request"]) {
99887
+ const labels2 = body8[owner6]?.labels;
99888
+ if (Array.isArray(labels2)) labels2.forEach((_, i) => fields13(`/${owner6}/labels/${i}`, ["url"]));
99864
99889
  }
99865
99890
  fields13("/label", ["url"]);
99866
99891
  fields13("/issue/pull_request", ["url", "diff_url", "patch_url"]);
@@ -104466,8 +104491,8 @@ var init_pulls = __esm({
104466
104491
  const issue9 = getIssue(ctx, repo4.id, p2.number);
104467
104492
  if (state3 !== "all" && issue9.state !== state3 || baseFilter !== void 0 && p2.base_ref !== baseFilter) return false;
104468
104493
  if (headFilter !== void 0) {
104469
- const split3 = headFilter.indexOf(":"), owner5 = split3 < 0 ? repo4.owner : headFilter.slice(0, split3), ref23 = split3 < 0 ? headFilter : headFilter.slice(split3 + 1);
104470
- if (owner5.toLowerCase() !== repo4.owner.toLowerCase() || p2.head_ref !== ref23) return false;
104494
+ const split3 = headFilter.indexOf(":"), owner6 = split3 < 0 ? repo4.owner : headFilter.slice(0, split3), ref23 = split3 < 0 ? headFilter : headFilter.slice(split3 + 1);
104495
+ if (owner6.toLowerCase() !== repo4.owner.toLowerCase() || p2.head_ref !== ref23) return false;
104471
104496
  }
104472
104497
  return true;
104473
104498
  }).sort((a, b) => {
@@ -106010,8 +106035,8 @@ ${issue9.body}` : "";
106010
106035
  }
106011
106036
  #authorFor(tool, id15) {
106012
106037
  const owns = (accounts2) => tool === "slack" ? accounts2.slack === id15 : tool === "gmail" ? accounts2.gmail?.toLowerCase() === id15.toLowerCase() : accounts2.github?.id === id15;
106013
- const owner5 = this.#everyone().find(({ accounts: accounts2 }) => owns(accounts2));
106014
- if (owner5) return owner5.person.ref;
106038
+ const owner6 = this.#everyone().find(({ accounts: accounts2 }) => owns(accounts2));
106039
+ if (owner6) return owner6.person.ref;
106015
106040
  if (owns(this.#botAccounts())) return "agent";
106016
106041
  return `${tool}:${id15}`;
106017
106042
  }
@@ -107920,8 +107945,8 @@ function expand(ctx, value6, paths3, account9 = null) {
107920
107945
  if (typeof target6 === "string") {
107921
107946
  const loaded = load2(ctx, target6);
107922
107947
  if (!loaded) unsupported8(`expanding ${parts3.slice(0, i + 1).join(".")}`);
107923
- const owner5 = loaded.object === "event" ? loaded.account ?? null : eventOwner(loaded);
107924
- if (account9 !== null && owner5 !== account9) missing2(loaded.object, target6, "expand");
107948
+ const owner6 = loaded.object === "event" ? loaded.account ?? null : eventOwner(loaded);
107949
+ if (account9 !== null && owner6 !== account9) missing2(loaded.object, target6, "expand");
107925
107950
  target6 = loaded;
107926
107951
  }
107927
107952
  return { ...node5, [key5]: i + 1 < parts3.length ? apply2(target6, i + 1) : target6 };
@@ -108101,10 +108126,10 @@ var init_connect_registry = __esm({
108101
108126
  });
108102
108127
 
108103
108128
  // packages/server/src/twins/stripe/connect.ts
108104
- function requestAccount(ctx, header4, routeKey) {
108129
+ function requestAccount(ctx, header4, routeKey2) {
108105
108130
  if (header4 === void 0) return null;
108106
108131
  const id15 = header4.trim();
108107
- if (!ACCOUNT_SCOPED.has(routeKey)) unsupported8(`the Stripe-Account header on ${routeKey}`);
108132
+ if (!ACCOUNT_SCOPED.has(routeKey2)) unsupported8(`the Stripe-Account header on ${routeKey2}`);
108108
108133
  const account9 = load2(ctx, id15);
108109
108134
  if (!account9 || account9.object !== "account" || account9.deleted) {
108110
108135
  throw new StripeError(403, "invalid_request_error", `The provided key does not have access to account '${id15}' (or that account does not exist). Application access may have been revoked.`, { code: "account_invalid" });
@@ -108398,8 +108423,8 @@ function recordChange(ctx, row2, before) {
108398
108423
  } else if (row2.object === "invoice" && row2.attempt_count > before.attempt_count && row2.status === "open") types = ["invoice.payment_failed"];
108399
108424
  else types = row2.object === "invoiceitem" ? [] : [`${prefix2}.updated`];
108400
108425
  const changed = previous ? Object.fromEntries(Object.keys(previous).filter((k) => JSON.stringify(previous[k]) !== JSON.stringify(current[k])).map((k) => [k, previous[k]])) : {};
108401
- const owner5 = eventOwner(row2);
108402
- for (const type of types) emitEvent(ctx, type, current, { previous: type.endsWith(".updated") && before ? changed : void 0, account: owner5 });
108426
+ const owner6 = eventOwner(row2);
108427
+ for (const type of types) emitEvent(ctx, type, current, { previous: type.endsWith(".updated") && before ? changed : void 0, account: owner6 });
108403
108428
  }
108404
108429
  function emitEvent(ctx, type, object28, o = {}) {
108405
108430
  const event3 = save3(ctx, {
@@ -109373,10 +109398,10 @@ function resolve3(ctx, type, value6) {
109373
109398
  return ref23 === void 0 ? void 0 : account3(ctx).__refs[type]?.[ref23];
109374
109399
  }
109375
109400
  function fundsCheck(ctx, args, fees) {
109376
- const owner5 = fees ? args.account : args.destination;
109377
- const accountId4 = owner5 === void 0 ? void 0 : resolve3(ctx, "account", owner5), charge2 = args.charge === void 0 ? void 0 : resolve3(ctx, "charge", args.charge);
109401
+ const owner6 = fees ? args.account : args.destination;
109402
+ const accountId4 = owner6 === void 0 ? void 0 : resolve3(ctx, "account", owner6), charge2 = args.charge === void 0 ? void 0 : resolve3(ctx, "charge", args.charge);
109378
109403
  const group5 = fees ? void 0 : args.transfer_group;
109379
- const rows35 = all2(ctx, fees ? "application_fee" : "transfer").filter((r2) => (owner5 === void 0 || accountId4 !== void 0 && r2[fees ? "account" : "destination"] === accountId4) && (args.charge === void 0 || charge2 !== void 0 && (fees ? r2.originating_transaction === charge2 || r2.charge === charge2 : r2.source_transaction === charge2)) && (group5 === void 0 || r2.transfer_group === group5) && (!args.after_start || r2.created >= Date.parse(ctx.scene.start_time) / 1e3));
109404
+ const rows35 = all2(ctx, fees ? "application_fee" : "transfer").filter((r2) => (owner6 === void 0 || accountId4 !== void 0 && r2[fees ? "account" : "destination"] === accountId4) && (args.charge === void 0 || charge2 !== void 0 && (fees ? r2.originating_transaction === charge2 || r2.charge === charge2 : r2.source_transaction === charge2)) && (group5 === void 0 || r2.transfer_group === group5) && (!args.after_start || r2.created >= Date.parse(ctx.scene.start_time) / 1e3));
109380
109405
  const returnedKey = fees ? "amount_refunded" : "amount_reversed";
109381
109406
  const totals2 = { count: rows35.length, amount: rows35.reduce((n2, r2) => n2 + r2.amount, 0), [returnedKey]: rows35.reduce((n2, r2) => n2 + r2[returnedKey], 0) };
109382
109407
  return checkOutcome(
@@ -111807,7 +111832,7 @@ var init_env = __esm({
111807
111832
  }
111808
111833
  #forget(id15) {
111809
111834
  this.#envs.delete(id15);
111810
- for (const [key5, owner5] of this.#tokens) if (owner5 === id15) this.#tokens.delete(key5);
111835
+ for (const [key5, owner6] of this.#tokens) if (owner6 === id15) this.#tokens.delete(key5);
111811
111836
  }
111812
111837
  #entry(id15) {
111813
111838
  const entry3 = this.#envs.get(id15);
@@ -137207,8 +137232,8 @@ async function startGoogleAdsGrpc(env2) {
137207
137232
  };
137208
137233
  for (const service of new Set(Object.values(rpcMethods))) {
137209
137234
  const handlers = {};
137210
- for (const [method2, owner5] of Object.entries(rpcMethods)) {
137211
- if (owner5 !== service)
137235
+ for (const [method2, owner6] of Object.entries(rpcMethods)) {
137236
+ if (owner6 !== service)
137212
137237
  continue;
137213
137238
  handlers[method2] = (call4, callback2) => {
137214
137239
  const id15 = String(call4.metadata.get("x-ancha-request")[0] ?? ""), a = active4.get(id15);
@@ -139003,12 +139028,12 @@ function issue4(ctx, repo4, row2) {
139003
139028
  }
139004
139029
  function repository2(ctx, row2) {
139005
139030
  const ownerUser = getUserByLogin(ctx, row2.owner), org5 = getOrganization(ctx, row2.owner);
139006
- const owner5 = ownerUser ? { ...actor(ctx, ownerUser.id), __typename: "User" } : { __typename: "Organization", id: nodeId2("Organization", org5.id), login: org5.login, url: `https://github.com/${org5.login}` };
139031
+ const owner6 = ownerUser ? { ...actor(ctx, ownerUser.id), __typename: "User" } : { __typename: "Organization", id: nodeId2("Organization", org5.id), login: org5.login, url: `https://github.com/${org5.login}` };
139007
139032
  return {
139008
139033
  id: nodeId2("Repository", row2.id),
139009
139034
  name: row2.name,
139010
139035
  nameWithOwner: row2.full_name,
139011
- owner: owner5,
139036
+ owner: owner6,
139012
139037
  url: `https://github.com/${row2.full_name}`,
139013
139038
  issue: ({ number: number7 }) => {
139014
139039
  const i = getIssue(ctx, row2.id, number7);
@@ -139064,9 +139089,9 @@ function handleGraphql(c) {
139064
139089
  const viewer = ctx.store.db.prepare("SELECT user_id FROM github_tokens WHERE token = ?").get(token5);
139065
139090
  const result = (0, import_graphql3.executeSync)({ schema: githubSchema, document: document2, variableValues: variables2, operationName, rootValue: {
139066
139091
  viewer: () => ({ ...actor(ctx, viewer.user_id), __typename: "User" }),
139067
- repository: ({ owner: owner5, name: name5 }) => {
139068
- const row2 = ctx.store.db.prepare("SELECT * FROM github_repos WHERE owner = ? COLLATE NOCASE AND name = ? COLLATE NOCASE").get(owner5, name5);
139069
- if (!row2) throw new import_graphql3.GraphQLError(`Could not resolve to a Repository with the name '${owner5}/${name5}'.`, { extensions: { type: "NOT_FOUND" } });
139092
+ repository: ({ owner: owner6, name: name5 }) => {
139093
+ const row2 = ctx.store.db.prepare("SELECT * FROM github_repos WHERE owner = ? COLLATE NOCASE AND name = ? COLLATE NOCASE").get(owner6, name5);
139094
+ if (!row2) throw new import_graphql3.GraphQLError(`Could not resolve to a Repository with the name '${owner6}/${name5}'.`, { extensions: { type: "NOT_FOUND" } });
139070
139095
  return repository2(ctx, row2);
139071
139096
  }
139072
139097
  } });
@@ -141531,8 +141556,8 @@ var init_state3 = __esm({
141531
141556
  function ownedRef(ctx, ref23, kind2) {
141532
141557
  const parsed5 = parseRef(ref23);
141533
141558
  const id15 = ctx.refs.resolve(ref23, kind2);
141534
- const owner5 = ctx.store.db.prepare("SELECT twin FROM _ancha_refs WHERE name = ?").get(parsed5.name);
141535
- if (owner5?.twin !== "pagerduty") throw new AnchaError("INTERNAL", `PagerDuty actor ${kind2} must belong to pagerduty`);
141559
+ const owner6 = ctx.store.db.prepare("SELECT twin FROM _ancha_refs WHERE name = ?").get(parsed5.name);
141560
+ if (owner6?.twin !== "pagerduty") throw new AnchaError("INTERNAL", `PagerDuty actor ${kind2} must belong to pagerduty`);
141536
141561
  return id15;
141537
141562
  }
141538
141563
  function changeStatus(ctx, args, status6) {
@@ -145317,7 +145342,7 @@ function permissionResource(ctx, grant) {
145317
145342
  };
145318
145343
  }
145319
145344
  function capabilities(file3, role3) {
145320
- const folder2 = isFolder(file3), editor = RANK2[role3] >= RANK2.writer, owner5 = role3 === "owner";
145345
+ const folder2 = isFolder(file3), editor = RANK2[role3] >= RANK2.writer, owner6 = role3 === "owner";
145321
145346
  const copyBlocked = file3.copy_requires_writer === 1 && !editor;
145322
145347
  return {
145323
145348
  canAcceptOwnership: false,
@@ -145328,22 +145353,22 @@ function capabilities(file3, role3) {
145328
145353
  canChangeViewersCanCopyContent: editor,
145329
145354
  canComment: RANK2[role3] >= RANK2.commenter,
145330
145355
  canCopy: !folder2 && !copyBlocked,
145331
- canDelete: owner5,
145356
+ canDelete: owner6,
145332
145357
  canDownload: !copyBlocked,
145333
145358
  canEdit: editor,
145334
145359
  canListChildren: folder2,
145335
145360
  canModifyContent: editor,
145336
145361
  canModifyLabels: false,
145337
- canMoveItemOutOfDrive: owner5,
145362
+ canMoveItemOutOfDrive: owner6,
145338
145363
  canMoveItemWithinDrive: editor,
145339
145364
  canReadLabels: false,
145340
145365
  canReadRevisions: editor,
145341
145366
  canRemoveChildren: folder2 && editor,
145342
- canRemoveMyDriveParent: owner5,
145367
+ canRemoveMyDriveParent: owner6,
145343
145368
  canRename: editor,
145344
- canShare: owner5 || editor && file3.writers_can_share === 1,
145345
- canTrash: owner5,
145346
- canUntrash: owner5
145369
+ canShare: owner6 || editor && file3.writers_can_share === 1,
145370
+ canTrash: owner6,
145371
+ canUntrash: owner6
145347
145372
  };
145348
145373
  }
145349
145374
  function visibleParents(ctx, caller2, file3) {
@@ -145418,7 +145443,7 @@ function searchable(ctx, caller2, file3, access16) {
145418
145443
  const people4 = (min) => granted.filter((entry3) => (entry3.grant.type === "user" || entry3.grant.type === "group") && RANK2[entry3.grant.role] >= RANK2[min]).map((entry3) => entry3.grant.email);
145419
145444
  const anyone = granted.find((entry3) => entry3.grant.type === "anyone"), domain2 = granted.find((entry3) => entry3.grant.type === "domain");
145420
145445
  const text31 = file3.content !== null && (isEditorFile(file3) || /^text\//.test(file3.mime_type)) ? file3.content.toString("utf8") : "";
145421
- const owner5 = getUser4(ctx, file3.owner);
145446
+ const owner6 = getUser4(ctx, file3.owner);
145422
145447
  return {
145423
145448
  name: file3.name,
145424
145449
  mimeType: file3.mime_type,
@@ -145430,7 +145455,7 @@ ${text31}`,
145430
145455
  createdMs: file3.created_ms,
145431
145456
  modifiedMs: file3.modified_ms,
145432
145457
  viewedMs: file3.viewed_ms,
145433
- parents: [file3.parent ?? owner5?.root_id ?? ""],
145458
+ parents: [file3.parent ?? owner6?.root_id ?? ""],
145434
145459
  owners: [file3.owner],
145435
145460
  writers: people4("writer"),
145436
145461
  readers: people4("reader"),
@@ -147601,7 +147626,7 @@ function seed16(ctx) {
147601
147626
  insertLabel.run(box.address, id15, label7.name, "user", label7.message_list_visibility, label7.label_list_visibility, label7.color?.text_color ?? null, label7.color?.background_color ?? null);
147602
147627
  });
147603
147628
  db3.prepare("UPDATE gmail_mailboxes SET next_label = ? WHERE address = ?").run(box.labels.length + 1, box.address);
147604
- const owner5 = { name: box.name, email: box.address };
147629
+ const owner6 = { name: box.name, email: box.address };
147605
147630
  const sent2 = /* @__PURE__ */ new Map();
147606
147631
  const build5 = (entry3, from) => {
147607
147632
  const parent3 = entry3.in_reply_to === void 0 ? void 0 : sent2.get(entry3.in_reply_to);
@@ -147636,7 +147661,7 @@ function seed16(ctx) {
147636
147661
  insertMessage2(ctx, box.address, raw3, { internalDate: at6(message8.at), labels: labels2, history: false });
147637
147662
  }
147638
147663
  for (const draft2 of box.drafts) {
147639
- const { raw: raw3 } = build5(draft2, owner5);
147664
+ const { raw: raw3 } = build5(draft2, owner6);
147640
147665
  const row2 = insertMessage2(ctx, box.address, raw3, { internalDate: at6(draft2.at), labels: ["DRAFT"], history: false });
147641
147666
  db3.prepare("INSERT INTO gmail_drafts (mailbox, id, message_id) VALUES (?, ?, ?)").run(box.address, newDraftId(ctx), row2.id);
147642
147667
  }
@@ -154061,8 +154086,8 @@ function orgFor(call4) {
154061
154086
  }
154062
154087
  function checkSlug(ctx, slug16, except) {
154063
154088
  if (typeof slug16 !== "string" || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug16) || slug16.length > 100) throw new ClerkError(422, "form_param_format_invalid", "is invalid", "slug must contain only lowercase letters, digits and dashes", { param_name: "slug" });
154064
- const owner5 = getOrg(ctx, slug16);
154065
- if (owner5 && owner5.id !== except) throw taken("slug", "slug");
154089
+ const owner6 = getOrg(ctx, slug16);
154090
+ if (owner6 && owner6.id !== except) throw taken("slug", "slug");
154066
154091
  return slug16;
154067
154092
  }
154068
154093
  function seats(value6) {
@@ -160836,11 +160861,11 @@ function seed27(ctx) {
160836
160861
  const earliest = Math.min(start2, ...input5.items.map((entry3) => at6(entry3.created)));
160837
160862
  db3.prepare("INSERT INTO ms_items (id, parent_id, name, name_lower, kind, created_ms, modified_ms, created_by, modified_by) VALUES (?, NULL, 'root', 'root', 'root', ?, ?, ?, ?)").run(rootId, earliest, earliest, input5.me, input5.me);
160838
160863
  const ids3 = /* @__PURE__ */ new Map([["", rootId]]);
160839
- const owner5 = (value6) => value6 ?? input5.me;
160864
+ const owner6 = (value6) => value6 ?? input5.me;
160840
160865
  for (const entry3 of input5.items) {
160841
160866
  const key5 = entry3.path.toLowerCase(), name5 = entry3.path.slice(entry3.path.lastIndexOf("/") + 1), id15 = seededItemId(key5), parent3 = ids3.get(key5.slice(0, key5.lastIndexOf("/")));
160842
160867
  ids3.set(key5, id15);
160843
- const created4 = at6(entry3.created), modified = at6(entry3.modified ?? entry3.created), createdBy = owner5(entry3.createdBy), modifiedBy = owner5(entry3.modifiedBy ?? entry3.createdBy);
160868
+ const created4 = at6(entry3.created), modified = at6(entry3.modified ?? entry3.created), createdBy = owner6(entry3.createdBy), modifiedBy = owner6(entry3.modifiedBy ?? entry3.createdBy);
160844
160869
  const render3 = (version6, when13, by2) => name5.toLowerCase().endsWith(".docx") ? buildDocx(version6.paragraphs ?? [], { title: name5.replace(/\.docx$/i, ""), creator: input5.users.find((user9) => user9.email === createdBy).displayName, modifiedBy: input5.users.find((user9) => user9.email === by2).displayName, createdMs: created4, modifiedMs: when13 }) : Buffer.from(version6.content ?? "", "utf8");
160845
160870
  const content2 = entry3.kind === "file" ? render3(entry3, modified, modifiedBy) : null;
160846
160871
  db3.prepare(`INSERT INTO ms_items (id, parent_id, name, name_lower, kind, mime_type, content, created_ms, modified_ms, created_by, modified_by, etag_version, ctag_version)
@@ -160861,7 +160886,7 @@ function seed27(ctx) {
160861
160886
  );
160862
160887
  if (entry3.kind === "file") {
160863
160888
  entry3.versions.forEach((version6, index) => {
160864
- const by2 = owner5(version6.modifiedBy ?? entry3.createdBy), when13 = at6(version6.modified);
160889
+ const by2 = owner6(version6.modifiedBy ?? entry3.createdBy), when13 = at6(version6.modified);
160865
160890
  db3.prepare("INSERT INTO ms_versions (item_id, seq, content, modified_ms, modified_by) VALUES (?, ?, ?, ?, ?)").run(id15, index + 1, render3(version6, when13, by2), when13, by2);
160866
160891
  });
160867
160892
  db3.prepare("INSERT INTO ms_versions (item_id, seq, content, modified_ms, modified_by) VALUES (?, ?, ?, ?, ?)").run(id15, entry3.versions.length + 1, content2, modified, modifiedBy);
@@ -168330,15 +168355,15 @@ var init_record_checks = __esm({
168330
168355
  // packages/server/src/twins/paypal/checks.ts
168331
168356
  function itemsMatch(items2, wants) {
168332
168357
  if (wants === void 0) return true;
168333
- const owner5 = /* @__PURE__ */ new Map();
168358
+ const owner6 = /* @__PURE__ */ new Map();
168334
168359
  const fits = (i, w2) => i.name === w2.name && (w2.quantity === void 0 || Number(i.quantity) === Number(w2.quantity)) && equalMoney(i.cents, w2.unit_amount) && equalMoney(i.tax_cents ?? 0, w2.tax) && (w2.tax_percent === void 0 || Number(i.tax?.percent) === Number(w2.tax_percent));
168335
168360
  const assign = (w2, seen) => {
168336
168361
  for (let i = 0; i < items2.length; i++) {
168337
168362
  if (seen.has(i) || !fits(items2[i], wants[w2])) continue;
168338
168363
  seen.add(i);
168339
- const prior = owner5.get(i);
168364
+ const prior = owner6.get(i);
168340
168365
  if (prior === void 0 || assign(prior, seen)) {
168341
- owner5.set(i, w2);
168366
+ owner6.set(i, w2);
168342
168367
  return true;
168343
168368
  }
168344
168369
  }
@@ -179003,8 +179028,8 @@ function capture2(ctx, raw3) {
179003
179028
  const now11 = ctx.clock.nowMs();
179004
179029
  let target6, projectId;
179005
179030
  if (a.issue !== void 0) {
179006
- const owner5 = ctx.store.db.prepare("SELECT twin FROM _ancha_refs WHERE name = ?").get(parseRef(a.issue).name);
179007
- if (owner5?.twin !== "sentry") throw new AnchaError("INTERNAL", `sentry.capture: ${a.issue} is not a Sentry issue`);
179031
+ const owner6 = ctx.store.db.prepare("SELECT twin FROM _ancha_refs WHERE name = ?").get(parseRef(a.issue).name);
179032
+ if (owner6?.twin !== "sentry") throw new AnchaError("INTERNAL", `sentry.capture: ${a.issue} is not a Sentry issue`);
179008
179033
  target6 = issue6(ctx, ctx.refs.resolve(a.issue, "issue"));
179009
179034
  if (!target6) return { outcome: "skipped", reason: "issue_deleted" };
179010
179035
  projectId = target6.project_id;
@@ -183270,8 +183295,8 @@ function auditValues(ctx, type, id15) {
183270
183295
  }).map(([key5, value6]) => [key5, valueText(value6)]));
183271
183296
  }
183272
183297
  function auditChange(ctx, type, id15, before, operation, seed44) {
183273
- const db3 = sql2(ctx), owner5 = AUDIT_OWNER + type;
183274
- const stored = db3.prepare("SELECT fields FROM ns_extra WHERE owner=? AND id=?").get(owner5, id15);
183298
+ const db3 = sql2(ctx), owner6 = AUDIT_OWNER + type;
183299
+ const stored = db3.prepare("SELECT fields FROM ns_extra WHERE owner=? AND id=?").get(owner6, id15);
183275
183300
  const audit2 = stored ? JSON.parse(stored.fields) : { notes: [] };
183276
183301
  const approval = seed44 && isTx(type) ? txRow(ctx, id15)?.approvalstatus : void 0;
183277
183302
  const after = operation === "delete" ? {} : seed44 ? { approvalStatus: approval == null ? null : { 1: "Pending Approval", 2: "Approved", 3: "Rejected" }[approval] ?? null } : auditValues(ctx, type, id15);
@@ -183301,7 +183326,7 @@ function auditChange(ctx, type, id15, before, operation, seed44) {
183301
183326
  const oldvalue = before?.[key5] ?? null, newvalue = after[key5] ?? null;
183302
183327
  if (oldvalue !== newvalue) append(fieldId(type, key5), oldvalue, newvalue, oldvalue === null ? 4 : newvalue === null ? 5 : 2);
183303
183328
  }
183304
- db3.prepare("INSERT INTO ns_extra(owner,id,fields) VALUES (?,?,?) ON CONFLICT(owner,id) DO UPDATE SET fields=excluded.fields").run(owner5, id15, JSON.stringify(audit2));
183329
+ db3.prepare("INSERT INTO ns_extra(owner,id,fields) VALUES (?,?,?) ON CONFLICT(owner,id) DO UPDATE SET fields=excluded.fields").run(owner6, id15, JSON.stringify(audit2));
183305
183330
  }
183306
183331
  var AUDIT_OWNER, valueText, fieldId;
183307
183332
  var init_audit = __esm({
@@ -183645,15 +183670,15 @@ function deletePlain(ctx, type, id15) {
183645
183670
  }
183646
183671
  function writeKept(ctx, type, id15, values3) {
183647
183672
  if (!values3.size) return;
183648
- const db3 = sql2(ctx), owner5 = extraOwner(type);
183649
- const fields13 = json35(db3.prepare("SELECT fields FROM ns_extra WHERE owner = ? AND id = ?").get(owner5, id15)?.fields);
183673
+ const db3 = sql2(ctx), owner6 = extraOwner(type);
183674
+ const fields13 = json35(db3.prepare("SELECT fields FROM ns_extra WHERE owner = ? AND id = ?").get(owner6, id15)?.fields);
183650
183675
  for (const [name5, value6] of values3) {
183651
183676
  if (value6 === null) delete fields13[name5];
183652
183677
  else fields13[name5] = value6;
183653
183678
  }
183654
- db3.prepare("INSERT INTO ns_extra (owner, id, fields) VALUES (?, ?, ?) ON CONFLICT (owner, id) DO UPDATE SET fields = excluded.fields").run(owner5, id15, JSON.stringify(fields13));
183679
+ db3.prepare("INSERT INTO ns_extra (owner, id, fields) VALUES (?, ?, ?) ON CONFLICT (owner, id) DO UPDATE SET fields = excluded.fields").run(owner6, id15, JSON.stringify(fields13));
183655
183680
  const notes7 = new FieldNotes(plainTypes(ctx));
183656
- notes7.note(type, "", owner5, Object.fromEntries(values3));
183681
+ notes7.note(type, "", owner6, Object.fromEntries(values3));
183657
183682
  notes7.write(ctx);
183658
183683
  }
183659
183684
  function placed(fields13, subsidiaries2) {
@@ -183677,10 +183702,10 @@ function seedKept(ctx, input5) {
183677
183702
  const extra2 = db3.prepare("INSERT INTO ns_extra (owner, id, fields) VALUES (?, ?, ?) ON CONFLICT (owner, id) DO UPDATE SET fields = excluded.fields");
183678
183703
  const misplaced = (custom3, prefix2) => Object.fromEntries(Object.entries(custom3 ?? {}).filter(([key5]) => prefix2 === void 0 || !key5.startsWith(prefix2)));
183679
183704
  for (const record32 of netsuiteModeledRecords(input5)) {
183680
- const owner5 = extraOwner(record32.type), kept = { ...misplaced(record32.custom, netsuiteCustomPrefix(record32.type)), ...record32.extra };
183705
+ const owner6 = extraOwner(record32.type), kept = { ...misplaced(record32.custom, netsuiteCustomPrefix(record32.type)), ...record32.extra };
183681
183706
  if (Object.keys(kept).length) {
183682
- extra2.run(owner5, record32.id, JSON.stringify(kept));
183683
- notes7.note(record32.type, "", owner5, kept);
183707
+ extra2.run(owner6, record32.id, JSON.stringify(kept));
183708
+ notes7.note(record32.type, "", owner6, kept);
183684
183709
  }
183685
183710
  for (const line2 of record32.lines) notes7.note(record32.type, line2.sublist, "transaction", { ...misplaced(line2.custom, "custcol"), ...line2.extra });
183686
183711
  }
@@ -183703,11 +183728,11 @@ var init_plain = __esm({
183703
183728
  constructor(plain9) {
183704
183729
  this.#plain = plain9;
183705
183730
  }
183706
- note(recordtype, sublist, owner5, values3) {
183731
+ note(recordtype, sublist, owner6, values3) {
183707
183732
  for (const [field6, value6] of Object.entries(values3 ?? {})) {
183708
183733
  const key5 = JSON.stringify([recordtype, sublist, field6]), prior = this.#fields.get(key5), kind2 = netsuiteValueKind(value6);
183709
183734
  const target6 = prior?.target ?? netsuiteReferenceTarget(field6, value6, this.#plain) ?? null;
183710
- this.#fields.set(key5, { recordtype, sublist, field: field6, owner: owner5, target: target6, kind: prior === void 0 ? kind2 ?? "" : prior.kind === "" ? kind2 ?? "" : netsuiteMergeKinds(prior.kind, kind2) });
183735
+ this.#fields.set(key5, { recordtype, sublist, field: field6, owner: owner6, target: target6, kind: prior === void 0 ? kind2 ?? "" : prior.kind === "" ? kind2 ?? "" : netsuiteMergeKinds(prior.kind, kind2) });
183711
183736
  }
183712
183737
  }
183713
183738
  /** Merges what was noted into the catalog the world already has. */
@@ -184566,9 +184591,9 @@ function saveTransaction(ctx, type, id15, body8, opts = {}) {
184566
184591
  if (linked2) throw userError(`The ${def.party.label.toLowerCase()} cannot be changed on a transaction that other transactions apply to or were created from.`, field6);
184567
184592
  }
184568
184593
  if (type === "customerDeposit" && createdfrom !== null && txRow(ctx, createdfrom)?.entity !== entity5) throw invalidValue2("salesOrder", createdfrom);
184569
- const owner5 = entity5 === null ? void 0 : entityRow(ctx, entity5);
184594
+ const owner6 = entity5 === null ? void 0 : entityRow(ctx, entity5);
184570
184595
  const trandate = keep2("tranDate", prior?.trandate ?? today(ctx)) ?? today(ctx);
184571
- const terms2 = "terms" in specs ? keep2("terms", prior ? prior.terms : owner5?.terms ?? null) : null;
184596
+ const terms2 = "terms" in specs ? keep2("terms", prior ? prior.terms : owner6?.terms ?? null) : null;
184572
184597
  let duedate = prior?.duedate ?? null;
184573
184598
  if ("dueDate" in specs) {
184574
184599
  if (has4("dueDate") || cleared(opts, "dueDate", fields13)) duedate = has4("dueDate") ? get8("dueDate") : null;
@@ -184591,7 +184616,7 @@ function saveTransaction(ctx, type, id15, body8, opts = {}) {
184591
184616
  postingperiod = p2.id;
184592
184617
  } else if (!prior || trandate !== prior.trandate || has4("postingPeriod")) postingperiod = periodFor(ctx, trandate)?.id ?? null;
184593
184618
  if (postingperiod === null) throw userError("No accounting period covers the transaction date.", "tranDate");
184594
- const salesrep = "salesRep" in specs ? keep2("salesRep", prior ? prior.salesrep : owner5?.salesrep ?? null) : null;
184619
+ const salesrep = "salesRep" in specs ? keep2("salesRep", prior ? prior.salesrep : owner6?.salesrep ?? null) : null;
184595
184620
  if (salesrep !== null && has4("salesRep") && !entityRow(ctx, salesrep)?.issalesrep) throw invalidValue2("salesRep", salesrep);
184596
184621
  const employee = "employee" in specs ? keep2("employee", prior?.employee ?? null) : null;
184597
184622
  let status6 = prior?.status ?? null, approvalstatus = prior?.approvalstatus ?? null;
@@ -184666,13 +184691,13 @@ function saveTransaction(ctx, type, id15, body8, opts = {}) {
184666
184691
  if (creating) status6 = "A";
184667
184692
  break;
184668
184693
  }
184669
- const fallbackCurrency = owner5?.kind === "customer" || owner5?.kind === "vendor" ? owner5.currency : firstList(ctx, "currency");
184694
+ const fallbackCurrency = owner6?.kind === "customer" || owner6?.kind === "vendor" ? owner6.currency : firstList(ctx, "currency");
184670
184695
  const currency = has4("currency") ? get8("currency") ?? fallbackCurrency : prior?.currency ?? fallbackCurrency;
184671
- const subsidiary = has4("subsidiary") ? get8("subsidiary") ?? owner5?.subsidiary ?? firstList(ctx, "subsidiary") : prior?.subsidiary ?? owner5?.subsidiary ?? firstList(ctx, "subsidiary");
184696
+ const subsidiary = has4("subsidiary") ? get8("subsidiary") ?? owner6?.subsidiary ?? firstList(ctx, "subsidiary") : prior?.subsidiary ?? owner6?.subsidiary ?? firstList(ctx, "subsidiary");
184672
184697
  const placed2 = !prior || entity5 !== prior.entity;
184673
184698
  if (prior && currency !== prior.currency) throw userError("The currency of a saved transaction cannot be changed.", "currency");
184674
- if ((placed2 || has4("currency")) && (owner5?.kind === "customer" || owner5?.kind === "vendor") && currency !== owner5.currency) throw invalidValue2("currency", currency);
184675
- if ((placed2 || has4("subsidiary")) && owner5 && subsidiary !== owner5.subsidiary) throw invalidValue2("subsidiary", subsidiary);
184699
+ if ((placed2 || has4("currency")) && (owner6?.kind === "customer" || owner6?.kind === "vendor") && currency !== owner6.currency) throw invalidValue2("currency", currency);
184700
+ if ((placed2 || has4("subsidiary")) && owner6 && subsidiary !== owner6.subsidiary) throw invalidValue2("subsidiary", subsidiary);
184676
184701
  if (currency === null || subsidiary === null) throw missing7(currency === null ? "Currency" : "Subsidiary");
184677
184702
  const exchangerate = keep2("exchangeRate", prior ? prior.exchangerate : null) ?? rateOn(ctx, currency, trandate);
184678
184703
  if (!(exchangerate > 0)) throw invalidValue2("exchangeRate", exchangerate);
@@ -184702,9 +184727,9 @@ function saveTransaction(ctx, type, id15, body8, opts = {}) {
184702
184727
  salesrep,
184703
184728
  employee,
184704
184729
  createdfrom,
184705
- department: segmentRef(ctx, "department", keep2("department", prior?.department ?? (creating ? owner5?.department ?? null : null)), "department"),
184706
- location: segmentRef(ctx, "location", keep2("location", prior?.location ?? (creating ? owner5?.location ?? null : null)), "location"),
184707
- class: segmentRef(ctx, "classification", keep2("class", prior?.class ?? (creating ? owner5?.class ?? null : null)), "class"),
184730
+ department: segmentRef(ctx, "department", keep2("department", prior?.department ?? (creating ? owner6?.department ?? null : null)), "department"),
184731
+ location: segmentRef(ctx, "location", keep2("location", prior?.location ?? (creating ? owner6?.location ?? null : null)), "location"),
184732
+ class: segmentRef(ctx, "classification", keep2("class", prior?.class ?? (creating ? owner6?.class ?? null : null)), "class"),
184708
184733
  extra: mergeExtra(prior?.extra, passthrough, custom3, creating, opts),
184709
184734
  lastmodifieddate: now11
184710
184735
  };
@@ -186844,12 +186869,12 @@ function separated(parts3, sep10 = ", ") {
186844
186869
  function bound2(value6, type, kids = [], aggregateRoot = false) {
186845
186870
  return { ...value6, type, children: kids, aggregateRoot, aggregate: aggregateRoot || kids.some((k) => k.aggregate) };
186846
186871
  }
186847
- function columnValue(column3, owner5) {
186848
- return { ...bound2(column3.value, column3.type), column: column3, owner: owner5 };
186872
+ function columnValue(column3, owner6) {
186873
+ return { ...bound2(column3.value, column3.type), column: column3, owner: owner6 };
186849
186874
  }
186850
186875
  function resolve8(scope3, name5, qualifier) {
186851
186876
  const owners = scope3.relations.filter((r2) => !qualifier || r2.alias === qualifier);
186852
- const found = owners.flatMap((owner5) => owner5.columns.filter((c) => c.name === name5).map((c) => columnValue(c, owner5)));
186877
+ const found = owners.flatMap((owner6) => owner6.columns.filter((c) => c.name === name5).map((c) => columnValue(c, owner6)));
186853
186878
  if (found.length > 1) invalid31(`Ambiguous column '${name5}'.`);
186854
186879
  if (found.length === 1) return found[0];
186855
186880
  if (scope3.parent && (!qualifier || !owners.length)) {
@@ -188036,7 +188061,7 @@ var init_suiteql = __esm({
188036
188061
  const qualifier = item2.expr.qualifier;
188037
188062
  const owners = scope3.relations.filter((r2) => !qualifier || r2.alias === qualifier);
188038
188063
  if (!owners.length) invalid31("Wildcard has no matching table.");
188039
- for (const owner5 of owners) for (const c of owner5.columns) selected3.push({ name: c.name, value: columnValue(c, owner5) });
188064
+ for (const owner6 of owners) for (const c of owner6.columns) selected3.push({ name: c.name, value: columnValue(c, owner6) });
188040
188065
  } else {
188041
188066
  const value6 = this.expr(item2.expr, scope3);
188042
188067
  const name5 = item2.alias ?? (item2.expr.kind === "column" ? item2.expr.name : `expr${selected3.length + 1}`);
@@ -189005,7 +189030,7 @@ var init_filter4 = __esm({
189005
189030
  });
189006
189031
 
189007
189032
  // packages/server/src/twins/netsuite/metadata.ts
189008
- function property3(base6, name5, spec, owner5) {
189033
+ function property3(base6, name5, spec, owner6) {
189009
189034
  const common4 = { title: title(name5, spec), ...!spec.write && { readOnly: true }, nullable: true };
189010
189035
  switch (spec.kind) {
189011
189036
  case "text":
@@ -189026,7 +189051,7 @@ function property3(base6, name5, spec, owner5) {
189026
189051
  refName: { title: "Reference Name", type: "string", readOnly: true }
189027
189052
  } };
189028
189053
  case "sublist":
189029
- return { ...common4, type: "object", $ref: `${base6}${CATALOG}/${owner5}-${name5}Collection` };
189054
+ return { ...common4, type: "object", $ref: `${base6}${CATALOG}/${owner6}-${name5}Collection` };
189030
189055
  case "address": {
189031
189056
  const properties3 = Object.fromEntries(["addressee", "attention", "addr1", "addr2", "addr3", "city", "state", "zip", "addrPhone"].map((key5) => [key5, { title: title(key5), type: "string", nullable: true }]));
189032
189057
  properties3.country = { title: "Country", type: "object", nullable: true };
@@ -199052,11 +199077,11 @@ var init_socket2 = __esm({
199052
199077
  this.#fail(pending, error65 instanceof Error ? error65.message : "Socket Mode encoding failed", "harness");
199053
199078
  }
199054
199079
  }
199055
- #fail(pending, message8, owner5 = "agent") {
199080
+ #fail(pending, message8, owner6 = "agent") {
199056
199081
  clearTimeout(pending.timer);
199057
199082
  this.#pending.delete(pending.event.id);
199058
199083
  this.#env.noteActivity();
199059
- this.#record("failed", pending.event, { kind: "delivery", owner: owner5, service: this.#codec.service, message: message8 });
199084
+ this.#record("failed", pending.event, { kind: "delivery", owner: owner6, service: this.#codec.service, message: message8 });
199060
199085
  }
199061
199086
  #record(note2, event3, issue9) {
199062
199087
  if (!this.#env.canRecordTransport(this.#signal)) return;
@@ -205420,28 +205445,28 @@ function subscribeWeakly(signal, reference3, registry2) {
205420
205445
  signal.addEventListener("abort", abort, { once: true });
205421
205446
  subscriptions2.set(signal, subscription2);
205422
205447
  }
205423
- const owner5 = subscription2;
205424
- owner5.callbacks.add(reference3);
205448
+ const owner6 = subscription2;
205449
+ owner6.callbacks.add(reference3);
205425
205450
  return () => {
205426
- owner5.callbacks.delete(reference3);
205451
+ owner6.callbacks.delete(reference3);
205427
205452
  registry2.unregister(reference3);
205428
- if (owner5.callbacks.size === 0) {
205429
- if (subscriptions2.get(signal) === owner5) {
205453
+ if (owner6.callbacks.size === 0) {
205454
+ if (subscriptions2.get(signal) === owner6) {
205430
205455
  subscriptions2.delete(signal);
205431
205456
  }
205432
- signal.removeEventListener("abort", owner5.abort);
205457
+ signal.removeEventListener("abort", owner6.abort);
205433
205458
  }
205434
205459
  };
205435
205460
  }
205436
205461
  function releaseOnAbort(signal, callbacks, abort) {
205437
205462
  signal.addEventListener("abort", () => callbacks.deref()?.delete(abort), { once: true });
205438
205463
  }
205439
- function retainRequestAbortCallback(owner5, abort, requestSignal) {
205464
+ function retainRequestAbortCallback(owner6, abort, requestSignal) {
205440
205465
  if (typeof weakGlobals.WeakRef === "function" && finalizer && !requestSignal.aborted) {
205441
- let callbacks = callbackOwners.get(owner5);
205466
+ let callbacks = callbackOwners.get(owner6);
205442
205467
  if (!callbacks) {
205443
205468
  callbacks = /* @__PURE__ */ new Set();
205444
- callbackOwners.set(owner5, callbacks);
205469
+ callbackOwners.set(owner6, callbacks);
205445
205470
  }
205446
205471
  callbacks.add(abort);
205447
205472
  releaseOnAbort(requestSignal, new weakGlobals.WeakRef(callbacks), abort);
@@ -210058,18 +210083,18 @@ function findBufferedLedgerAffectedOwners(entry3, graph, records6, changes, work
210058
210083
  if (!changedEdges) {
210059
210084
  continue;
210060
210085
  }
210061
- for (const owner5 of previous.owners) {
210086
+ for (const owner6 of previous.owners) {
210062
210087
  work.remaining -= 1;
210063
210088
  if (work.remaining < 0) {
210064
210089
  return void 0;
210065
210090
  }
210066
- affected.add(owner5);
210091
+ affected.add(owner6);
210067
210092
  }
210068
210093
  }
210069
210094
  return affected;
210070
210095
  }
210071
- function updateBufferedLedgerMembershipChanges(owner5, next2, graph, records6, changes, work) {
210072
- for (const identity7 of owner5.identities) {
210096
+ function updateBufferedLedgerMembershipChanges(owner6, next2, graph, records6, changes, work) {
210097
+ for (const identity7 of owner6.identities) {
210073
210098
  work.remaining -= 1;
210074
210099
  if (work.remaining < 0) {
210075
210100
  return false;
@@ -210087,7 +210112,7 @@ function updateBufferedLedgerMembershipChanges(owner5, next2, graph, records6, c
210087
210112
  if (work.remaining < 0) {
210088
210113
  return false;
210089
210114
  }
210090
- if (!owner5.identities.has(identity7)) {
210115
+ if (!owner6.identities.has(identity7)) {
210091
210116
  const update5 = getBufferedLedgerChange(identity7, graph, records6, changes);
210092
210117
  if (!update5) {
210093
210118
  return false;
@@ -210099,13 +210124,13 @@ function updateBufferedLedgerMembershipChanges(owner5, next2, graph, records6, c
210099
210124
  }
210100
210125
  function collectBufferedLedgerMemberships(entry3, graph, affected, records6, changes, work) {
210101
210126
  const memberships2 = /* @__PURE__ */ new Map();
210102
- for (const owner5 of affected) {
210103
- const roots = owner5 === entry3 ? graph.roots : owner5.roots;
210127
+ for (const owner6 of affected) {
210128
+ const roots = owner6 === entry3 ? graph.roots : owner6.roots;
210104
210129
  const next2 = collectBufferedLedgerIdentities(roots, graph.nodes, records6, work);
210105
- if (!next2 || !updateBufferedLedgerMembershipChanges(owner5, next2, graph, records6, changes, work)) {
210130
+ if (!next2 || !updateBufferedLedgerMembershipChanges(owner6, next2, graph, records6, changes, work)) {
210106
210131
  return void 0;
210107
210132
  }
210108
- memberships2.set(owner5, next2);
210133
+ memberships2.set(owner6, next2);
210109
210134
  }
210110
210135
  return memberships2;
210111
210136
  }
@@ -210144,18 +210169,18 @@ function applyBufferedLedgerChanges(records6, changes, memberships2) {
210144
210169
  });
210145
210170
  }
210146
210171
  }
210147
- for (const [owner5, next2] of memberships2) {
210148
- for (const identity7 of owner5.identities) {
210172
+ for (const [owner6, next2] of memberships2) {
210173
+ for (const identity7 of owner6.identities) {
210149
210174
  if (!next2.has(identity7)) {
210150
- records6.get(identity7)?.owners.delete(owner5);
210175
+ records6.get(identity7)?.owners.delete(owner6);
210151
210176
  }
210152
210177
  }
210153
210178
  for (const identity7 of next2) {
210154
- if (!owner5.identities.has(identity7)) {
210155
- records6.get(identity7).owners.add(owner5);
210179
+ if (!owner6.identities.has(identity7)) {
210180
+ records6.get(identity7).owners.add(owner6);
210156
210181
  }
210157
210182
  }
210158
- owner5.identities = next2;
210183
+ owner6.identities = next2;
210159
210184
  }
210160
210185
  for (const identity7 of changes.keys()) {
210161
210186
  if (records6.get(identity7)?.owners.size === 0) {
@@ -212029,8 +212054,8 @@ function canonicalSerializedParserSchema(value6, budget2) {
212029
212054
  if (array4 && prototype !== Array.prototype || !array4 && prototype !== null && prototype !== Object.prototype) {
212030
212055
  return UNSAFE_SERIALIZED_PARSER_VALUE;
212031
212056
  }
212032
- for (let owner5 = current; owner5 !== null; owner5 = Object.getPrototypeOf(owner5)) {
212033
- const serializer = Object.getOwnPropertyDescriptor(owner5, "toJSON");
212057
+ for (let owner6 = current; owner6 !== null; owner6 = Object.getPrototypeOf(owner6)) {
212058
+ const serializer = Object.getOwnPropertyDescriptor(owner6, "toJSON");
212034
212059
  if (!serializer) {
212035
212060
  continue;
212036
212061
  }
@@ -212209,10 +212234,10 @@ function observeSerializedChatCompletionParserParams(body8, initial, update5) {
212209
212234
  const originalSchemaSignatures = /* @__PURE__ */ new WeakMap();
212210
212235
  if (body8.tools) {
212211
212236
  for (let index = 0; index < body8.tools.length && index < MAX_STREAM_TOOL_CALLS; index += 1) {
212212
- const owner5 = ownSerializedParserObject(body8.tools, String(index));
212237
+ const owner6 = ownSerializedParserObject(body8.tools, String(index));
212213
212238
  const source = initial.tools?.[index];
212214
- if (owner5 && source) {
212215
- originalToolOwners.set(owner5, source);
212239
+ if (owner6 && source) {
212240
+ originalToolOwners.set(owner6, source);
212216
212241
  const originalFunction = ownSerializedParserObject(source, "function");
212217
212242
  if (originalFunction) {
212218
212243
  rememberSerializedParserSchema(originalSchemaSignatures, source, originalFunction, "parameters");
@@ -212247,9 +212272,9 @@ function observeSerializedChatCompletionParserParams(body8, initial, update5) {
212247
212272
  if (holder === root3 && key5 === "response_format") {
212248
212273
  if (typeof value6 === "object" && value6 !== null) {
212249
212274
  responseFormat = value6;
212250
- const owner5 = ownSerializedParserObject(holder, key5);
212275
+ const owner6 = ownSerializedParserObject(holder, key5);
212251
212276
  responseFrame = {
212252
- source: owner5 === body8.response_format ? initial.response_format : void 0,
212277
+ source: owner6 === body8.response_format ? initial.response_format : void 0,
212253
212278
  schemaMatches: false
212254
212279
  };
212255
212280
  }
@@ -212278,8 +212303,8 @@ function observeSerializedChatCompletionParserParams(body8, initial, update5) {
212278
212303
  if (!Number.isSafeInteger(index) || index < 0 || index >= MAX_STREAM_TOOL_CALLS || typeof value6 !== "object" || value6 === null) {
212279
212304
  return;
212280
212305
  }
212281
- const owner5 = actualToolOwners.get(index);
212282
- const source = owner5 ? originalToolOwners.get(owner5) : void 0;
212306
+ const owner6 = actualToolOwners.get(index);
212307
+ const source = owner6 ? originalToolOwners.get(owner6) : void 0;
212283
212308
  const frame2 = { source };
212284
212309
  frames[index] = frame2;
212285
212310
  toolFrames.set(value6, frame2);
@@ -222136,8 +222161,8 @@ var init_AssistantStream = __esm({
222136
222161
  if (typeof runStepID !== "string" || runStepID.length === 0) {
222137
222162
  throw new OpenAIError("Received assistant run-step event with an invalid run-step ID");
222138
222163
  }
222139
- const owner5 = __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").get(runStepID);
222140
- if (owner5 !== void 0 && owner5 !== canonicalID) {
222164
+ const owner6 = __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").get(runStepID);
222165
+ if (owner6 !== void 0 && owner6 !== canonicalID) {
222141
222166
  throw new OpenAIError(`Received run-step creation for run step "${runStepID}", which has already been created`);
222142
222167
  }
222143
222168
  __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").set(runStepID, canonicalID);
@@ -222174,8 +222199,8 @@ var init_AssistantStream = __esm({
222174
222199
  if (typeof messageID !== "string" || messageID.length === 0) {
222175
222200
  throw new OpenAIError("Received assistant message event with an invalid message ID");
222176
222201
  }
222177
- const owner5 = __classPrivateFieldGet(this, _AssistantStream_messageIDOwners, "f").get(messageID);
222178
- if (owner5 !== void 0 && owner5 !== canonicalID) {
222202
+ const owner6 = __classPrivateFieldGet(this, _AssistantStream_messageIDOwners, "f").get(messageID);
222203
+ if (owner6 !== void 0 && owner6 !== canonicalID) {
222179
222204
  throw new OpenAIError(`Received message creation for message "${messageID}", which has already been created`);
222180
222205
  }
222181
222206
  __classPrivateFieldGet(this, _AssistantStream_messageIDOwners, "f").set(messageID, canonicalID);
@@ -230716,23 +230741,23 @@ function sharedSeeds(cases) {
230716
230741
  if (!record25(item2.scene) || item2.scene.seed === void 0 || typeof item2.id !== "string") return item2;
230717
230742
  const text31 = JSON.stringify(item2.scene.seed);
230718
230743
  if (text31.length < SHARED_SEED_CHARS) return item2;
230719
- const key5 = createHash60("sha256").update(text31).digest("hex"), owner5 = owners.get(key5);
230720
- if (owner5 === void 0) {
230744
+ const key5 = createHash60("sha256").update(text31).digest("hex"), owner6 = owners.get(key5);
230745
+ if (owner6 === void 0) {
230721
230746
  owners.set(key5, item2.id);
230722
230747
  return item2;
230723
230748
  }
230724
230749
  const { seed: _, ...scene2 } = item2.scene;
230725
- return { ...item2, scene: scene2, seedOf: owner5 };
230750
+ return { ...item2, scene: scene2, seedOf: owner6 };
230726
230751
  });
230727
230752
  }
230728
230753
  function withSeeds(cases) {
230729
230754
  const byId3 = new Map(cases.map((item2) => [item2.id, item2]));
230730
230755
  return cases.map((item2) => {
230731
230756
  if (typeof item2.seedOf !== "string" || !record25(item2.scene)) return item2;
230732
- const owner5 = byId3.get(item2.seedOf)?.scene;
230733
- if (!record25(owner5) || owner5.seed === void 0) return item2;
230757
+ const owner6 = byId3.get(item2.seedOf)?.scene;
230758
+ if (!record25(owner6) || owner6.seed === void 0) return item2;
230734
230759
  const { seedOf: _, ...rest2 } = item2;
230735
- return { ...rest2, scene: { ...item2.scene, seed: owner5.seed } };
230760
+ return { ...rest2, scene: { ...item2.scene, seed: owner6.seed } };
230736
230761
  });
230737
230762
  }
230738
230763
  function keptState(state3) {
@@ -231147,7 +231172,7 @@ function validateSpec(spec) {
231147
231172
  function validateStoredBody(table6, v) {
231148
231173
  table6 = table6.replace(/^cloud_/, "");
231149
231174
  if (!CLOUD_TABLES.includes(table6)) reject2("Invalid cloud table.");
231150
- object24(v, ["version", ...BODY_FIELDS[table6], ...table6 === "agents" ? ["projectKey", "repository", "modelKeyNames"] : []], `${table6} body`);
231175
+ object24(v, ["version", ...BODY_FIELDS[table6], ...table6 === "agents" ? ["projectKey", "repository", "modelKeyNames", "secretNames"] : table6 === "secrets" ? ["savedAt", "trimmed", "check"] : []], `${table6} body`);
231151
231176
  if (v.version !== 1) reject2("Invalid stored body version.");
231152
231177
  for (const key5 of BODY_FIELDS[table6]) if (!(key5 in v)) reject2(`Missing ${table6}.${key5}.`);
231153
231178
  if (table6 === "bundles") {
@@ -231225,12 +231250,24 @@ function validateStoredBody(table6, v) {
231225
231250
  if (v.repository !== void 0 && !validRepository(v.repository)) reject2("Invalid repository.");
231226
231251
  if (v.modelKeyNames !== void 0 && (!Array.isArray(v.modelKeyNames) || v.modelKeyNames.length > MODEL_KEY_NAMES.length || new Set(v.modelKeyNames).size !== v.modelKeyNames.length || v.modelKeyNames.some((name5) => !MODEL_KEY_NAMES.includes(name5)))) reject2("Invalid model key names.");
231227
231252
  if (v.projectKey !== void 0 && (typeof v.projectKey !== "string" || v.projectKey.length !== 32 || !PROJECT_KEY.test(v.projectKey))) reject2("Invalid project key.");
231253
+ if (v.secretNames !== void 0 && (!Array.isArray(v.secretNames) || v.secretNames.length > 128 || new Set(v.secretNames).size !== v.secretNames.length || v.secretNames.some((name5) => typeof name5 !== "string" || !/^[A-Z_][A-Z0-9_]{0,63}$/.test(name5)))) reject2("Invalid secret names.");
231228
231254
  if (!["ready", "configured", "connected", "connecting", "failed"].includes(v.state)) reject2("Invalid agent state.");
231229
231255
  string9(v.name, "agent name");
231230
231256
  hash5(v.projectHash);
231231
231257
  hash5(v.bundleHash);
231232
231258
  date10(v.updatedAt, "agent updatedAt");
231233
231259
  }
231260
+ if (table6 === "secrets") {
231261
+ if (v.savedAt !== void 0) date10(v.savedAt, "secret savedAt");
231262
+ if (v.trimmed !== void 0 && v.trimmed !== true) reject2("Invalid secret trim.");
231263
+ if (v.check !== void 0) {
231264
+ object24(v.check, ["provider", "status", "httpStatus", "reason", "at"], "secret check");
231265
+ if (!["Composio", "OpenRouter", "OpenAI", "Anthropic"].includes(v.check.provider) || !["accepted", "refused", "unchecked"].includes(v.check.status)) reject2("Invalid secret check.");
231266
+ if (v.check.httpStatus !== void 0) integer13(v.check.httpStatus, 100, 599, "secret check status");
231267
+ if (v.check.reason !== void 0 && (typeof v.check.reason !== "string" || v.check.reason.length > 200)) reject2("Invalid secret check reason.");
231268
+ date10(v.check.at, "secret check time");
231269
+ }
231270
+ }
231234
231271
  if (["secrets", "model_keys"].includes(table6)) {
231235
231272
  integer13(v.revision, 1, Number.MAX_SAFE_INTEGER, "revision");
231236
231273
  if (v.sealed !== null) {
@@ -231342,10 +231379,11 @@ var init_jobs_contract = __esm({
231342
231379
  };
231343
231380
  errorBody7 = (v) => {
231344
231381
  if (v === null) return;
231345
- object24(v, ["code", "message", "hint", "step"], "error");
231382
+ object24(v, ["code", "message", "hint", "step", "kind", "reference", "stderr"], "error");
231383
+ if (v.kind !== void 0 && !["fix", "retry", "ours"].includes(v.kind)) reject2("Invalid error.kind.");
231346
231384
  string9(v.code, "error.code");
231347
231385
  string9(v.message, "error.message");
231348
- for (const k of ["hint", "step"]) if (v[k] !== void 0) string9(v[k], `error.${k}`);
231386
+ for (const k of ["hint", "step", "reference", "stderr"]) if (v[k] !== void 0) string9(v[k], `error.${k}`);
231349
231387
  };
231350
231388
  EDITED_TEST_MAX_BYTES = 64 * 1024;
231351
231389
  projection = (row2, fields13) => Object.fromEntries(fields13.map((k) => [k, (row2.body ?? row2)[k]]));
@@ -231773,6 +231811,9 @@ import { createServer, request } from "node:http";
231773
231811
  import { request as secureRequest } from "node:https";
231774
231812
  import { isIP as isIP3 } from "node:net";
231775
231813
  import { brotliDecompressSync, gunzipSync, inflateSync as inflateSync2 } from "node:zlib";
231814
+ function modelFailure(status6) {
231815
+ return status6 === 429 ? { code: "MODEL_RATE_LIMITED", kind: "retry", outcome: "The model provider rate-limited the key", did: "rate-limited the agent's model key", fix: "Wait a little, then run the same command again." } : status6 === 402 ? { code: "MODEL_CREDITS_EXHAUSTED", kind: "fix", outcome: "The model key is out of credits", did: "says the agent's model key is out of credits", fix: "Add credits in the model provider account, then run again." } : { code: "MODEL_KEY_REFUSED", kind: "fix", outcome: "The model key was refused", did: "refused the agent's model key", fix: void 0 };
231816
+ }
231776
231817
  function refusalMessage(body8, encoding) {
231777
231818
  let text31;
231778
231819
  try {
@@ -232034,135 +232075,145 @@ async function startIsolationGateway(options5) {
232034
232075
  headers.host = modelHost ?? new URL(exposedOrigin ?? upstream.origin).host;
232035
232076
  delete headers["x-ancha-client-origin"];
232036
232077
  if (transform3) headers["accept-encoding"] = "identity";
232037
- const target6 = (modelHost ? secureRequest : request)({
232038
- hostname: modelAddress?.address ?? upstream.hostname.replace(/^\[|\]$/g, ""),
232039
- port: modelHost ? 443 : upstream.port || 80,
232040
- path: targetPath,
232041
- method: req.method,
232042
- headers,
232043
- agent: false,
232044
- ...modelHost && { servername: modelHost, rejectUnauthorized: true, family: modelAddress.family }
232045
- }, (reply6) => {
232046
- const observe2 = (host, status6, message8) => {
232047
- try {
232048
- options5.onModelReply?.(host, status6, message8);
232049
- } catch {
232078
+ let target6;
232079
+ try {
232080
+ target6 = (modelHost ? secureRequest : request)({
232081
+ hostname: modelAddress?.address ?? upstream.hostname.replace(/^\[|\]$/g, ""),
232082
+ port: modelHost ? 443 : upstream.port || 80,
232083
+ path: targetPath,
232084
+ method: req.method,
232085
+ headers,
232086
+ agent: false,
232087
+ ...modelHost && { servername: modelHost, rejectUnauthorized: true, family: modelAddress.family }
232088
+ }, (reply6) => {
232089
+ if (!reply6.statusCode || reply6.statusCode < 100) {
232090
+ reply6.destroy();
232091
+ reject3(res, 502, "Tool connection failed.");
232092
+ return;
232050
232093
  }
232051
- };
232052
- if (!toolCall && modelHost !== void 0 && reply6.statusCode !== void 0) {
232053
- const host = modelHost, status6 = reply6.statusCode;
232054
- if (!MODEL_REFUSALS.has(status6)) observe2(host, status6);
232055
- else {
232094
+ const observe2 = (host, status6, message8) => {
232095
+ try {
232096
+ options5.onModelReply?.(host, status6, message8);
232097
+ } catch {
232098
+ }
232099
+ };
232100
+ if (!toolCall && modelHost !== void 0 && reply6.statusCode !== void 0) {
232101
+ const host = modelHost, status6 = reply6.statusCode;
232102
+ if (!MODEL_REFUSALS.has(status6)) observe2(host, status6);
232103
+ else {
232104
+ const chunks2 = [];
232105
+ let size3 = 0, told = false;
232106
+ const tell = () => {
232107
+ if (told) return;
232108
+ told = true;
232109
+ observe2(host, status6, size3 <= REFUSAL_BYTES ? refusalMessage(Buffer.concat(chunks2), reply6.headers["content-encoding"]?.toLowerCase()) : void 0);
232110
+ };
232111
+ reply6.on("data", (chunk) => {
232112
+ size3 += chunk.length;
232113
+ if (size3 <= REFUSAL_BYTES) chunks2.push(chunk);
232114
+ });
232115
+ reply6.once("end", tell);
232116
+ reply6.once("close", tell);
232117
+ }
232118
+ }
232119
+ if (reply6.statusCode && reply6.statusCode >= 300 && reply6.statusCode < 400) {
232120
+ reply6.destroy();
232121
+ reject3(res, 502, "Tool redirects are not allowed through the sandbox gateway.");
232122
+ return;
232123
+ }
232124
+ const responseHeaders = toolCall ? { "content-type": reply6.headers["content-type"] ?? "application/json" } : cleanHeaders(reply6.headers);
232125
+ if (toolCall?.via === "mcp" && typeof reply6.headers["mcp-session-id"] === "string" && /^[\x21-\x7e]{1,256}$/.test(reply6.headers["mcp-session-id"])) responseHeaders["mcp-session-id"] = reply6.headers["mcp-session-id"];
232126
+ const successful2 = reply6.statusCode !== void 0 && reply6.statusCode >= 200 && reply6.statusCode < 300;
232127
+ if (toolCall?.response === "session-delete" && successful2) route15.sessions.delete(toolCall.sessionId);
232128
+ if (toolCall && successful2 && (toolCall.response === "session-create" || toolCall.response === "session-get")) {
232056
232129
  const chunks2 = [];
232057
- let size3 = 0, told = false;
232058
- const tell = () => {
232059
- if (told) return;
232060
- told = true;
232061
- observe2(host, status6, size3 <= REFUSAL_BYTES ? refusalMessage(Buffer.concat(chunks2), reply6.headers["content-encoding"]?.toLowerCase()) : void 0);
232130
+ let size3 = 0, failed2 = false;
232131
+ const fail9 = () => {
232132
+ if (failed2) return;
232133
+ failed2 = true;
232134
+ reply6.destroy();
232135
+ if (!res.headersSent) reject3(res, 502, "Composio returned an invalid session response.");
232136
+ else res.destroy();
232062
232137
  };
232063
232138
  reply6.on("data", (chunk) => {
232064
232139
  size3 += chunk.length;
232065
- if (size3 <= REFUSAL_BYTES) chunks2.push(chunk);
232140
+ if (size3 > 1024 * 1024) fail9();
232141
+ else if (!failed2) chunks2.push(Buffer.from(chunk));
232142
+ });
232143
+ reply6.once("error", fail9);
232144
+ reply6.once("aborted", fail9);
232145
+ reply6.once("end", () => {
232146
+ if (failed2) return;
232147
+ try {
232148
+ const value6 = rewriteComposioSession(JSON.parse(Buffer.concat(chunks2).toString("utf8")), toolCall, route15, exposedOrigin);
232149
+ const body8 = JSON.stringify(value6);
232150
+ res.writeHead(reply6.statusCode, { "content-type": "application/json", "content-length": Buffer.byteLength(body8) });
232151
+ res.end(body8);
232152
+ } catch {
232153
+ fail9();
232154
+ }
232066
232155
  });
232067
- reply6.once("end", tell);
232068
- reply6.once("close", tell);
232156
+ return;
232069
232157
  }
232070
- }
232071
- if (reply6.statusCode && reply6.statusCode >= 300 && reply6.statusCode < 400) {
232072
- reply6.destroy();
232073
- reject3(res, 502, "Tool redirects are not allowed through the sandbox gateway.");
232074
- return;
232075
- }
232076
- const responseHeaders = toolCall ? { "content-type": reply6.headers["content-type"] ?? "application/json" } : cleanHeaders(reply6.headers);
232077
- if (toolCall?.via === "mcp" && typeof reply6.headers["mcp-session-id"] === "string" && /^[\x21-\x7e]{1,256}$/.test(reply6.headers["mcp-session-id"])) responseHeaders["mcp-session-id"] = reply6.headers["mcp-session-id"];
232078
- const successful2 = reply6.statusCode !== void 0 && reply6.statusCode >= 200 && reply6.statusCode < 300;
232079
- if (toolCall?.response === "session-delete" && successful2) route15.sessions.delete(toolCall.sessionId);
232080
- if (toolCall && successful2 && (toolCall.response === "session-create" || toolCall.response === "session-get")) {
232081
- const chunks2 = [];
232082
- let size3 = 0, failed2 = false;
232083
- const fail9 = () => {
232084
- if (failed2) return;
232085
- failed2 = true;
232086
- reply6.destroy();
232087
- if (!res.headersSent) reject3(res, 502, "Composio returned an invalid session response.");
232088
- else res.destroy();
232089
- };
232158
+ if (toolCall) {
232159
+ let received = 0;
232160
+ reply6.on("data", (chunk) => {
232161
+ received += chunk.length;
232162
+ if (received > BODY_LIMIT) {
232163
+ reply6.destroy();
232164
+ res.destroy();
232165
+ }
232166
+ });
232167
+ }
232168
+ if (!transform3) {
232169
+ res.writeHead(reply6.statusCode ?? 502, responseHeaders);
232170
+ reply6.pipe(res);
232171
+ reply6.on("error", () => res.destroy());
232172
+ return;
232173
+ }
232174
+ const chunks = [];
232175
+ let size2 = 0;
232090
232176
  reply6.on("data", (chunk) => {
232091
- size3 += chunk.length;
232092
- if (size3 > 1024 * 1024) fail9();
232093
- else if (!failed2) chunks2.push(Buffer.from(chunk));
232177
+ size2 += chunk.length;
232178
+ if (size2 > BODY_LIMIT) {
232179
+ reply6.destroy();
232180
+ reject3(res, 502, "Tool response exceeded the sandbox gateway limit.");
232181
+ } else chunks.push(chunk);
232182
+ });
232183
+ reply6.on("error", () => {
232184
+ if (!res.headersSent) reject3(res, 502, "Tool connection failed.");
232185
+ else res.destroy();
232094
232186
  });
232095
- reply6.once("error", fail9);
232096
- reply6.once("aborted", fail9);
232097
- reply6.once("end", () => {
232098
- if (failed2) return;
232187
+ reply6.on("end", () => {
232188
+ if (size2 > BODY_LIMIT) return;
232099
232189
  try {
232100
- const value6 = rewriteComposioSession(JSON.parse(Buffer.concat(chunks2).toString("utf8")), toolCall, route15, exposedOrigin);
232190
+ let value6 = JSON.parse(Buffer.concat(chunks).toString("utf8"));
232191
+ if (transform3 === "context" && reply6.statusCode === 200) {
232192
+ const connection4 = mapped(exposedOrigin ?? "");
232193
+ value6 = { ...value6, env: connection4.env, session: connection4.session };
232194
+ }
232195
+ if (transform3 === "socket" && reply6.statusCode === 200 && value6?.ok === true) {
232196
+ const grant = new URL(value6.url);
232197
+ const expected = loopbackOrigin(session2.eventsUrl);
232198
+ if (grant.protocol !== "ws:" || grant.hostname !== expected.hostname || grant.port !== expected.port || grant.search || grant.hash || grant.username || grant.password || !/^\/_ancha\/socket\/[a-f0-9]{64}$/.test(grant.pathname)) throw new Error("Invalid socket grant");
232199
+ for (const [path10, old] of socketGrants) if (old.expires <= Date.now()) socketGrants.delete(path10);
232200
+ if (socketGrants.size >= 128) throw new Error("Too many socket grants");
232201
+ socketGrants.set(grant.pathname, { url: grant, expires: Date.now() + 3e4 });
232202
+ value6 = { ...value6, url: (exposedOrigin ?? "").replace(/^http:/, "ws:") + grant.pathname };
232203
+ }
232101
232204
  const body8 = JSON.stringify(value6);
232102
- res.writeHead(reply6.statusCode, { "content-type": "application/json", "content-length": Buffer.byteLength(body8) });
232205
+ delete responseHeaders["content-encoding"];
232206
+ delete responseHeaders["content-length"];
232207
+ res.writeHead(reply6.statusCode ?? 502, { ...responseHeaders, "content-length": Buffer.byteLength(body8) });
232103
232208
  res.end(body8);
232104
232209
  } catch {
232105
- fail9();
232210
+ reject3(res, 502, "Tool context was not a valid bounded response.");
232106
232211
  }
232107
232212
  });
232108
- return;
232109
- }
232110
- if (toolCall) {
232111
- let received = 0;
232112
- reply6.on("data", (chunk) => {
232113
- received += chunk.length;
232114
- if (received > BODY_LIMIT) {
232115
- reply6.destroy();
232116
- res.destroy();
232117
- }
232118
- });
232119
- }
232120
- if (!transform3) {
232121
- res.writeHead(reply6.statusCode ?? 502, responseHeaders);
232122
- reply6.pipe(res);
232123
- reply6.on("error", () => res.destroy());
232124
- return;
232125
- }
232126
- const chunks = [];
232127
- let size2 = 0;
232128
- reply6.on("data", (chunk) => {
232129
- size2 += chunk.length;
232130
- if (size2 > BODY_LIMIT) {
232131
- reply6.destroy();
232132
- reject3(res, 502, "Tool response exceeded the sandbox gateway limit.");
232133
- } else chunks.push(chunk);
232134
- });
232135
- reply6.on("error", () => {
232136
- if (!res.headersSent) reject3(res, 502, "Tool connection failed.");
232137
- else res.destroy();
232138
- });
232139
- reply6.on("end", () => {
232140
- if (size2 > BODY_LIMIT) return;
232141
- try {
232142
- let value6 = JSON.parse(Buffer.concat(chunks).toString("utf8"));
232143
- if (transform3 === "context" && reply6.statusCode === 200) {
232144
- const connection4 = mapped(exposedOrigin ?? "");
232145
- value6 = { ...value6, env: connection4.env, session: connection4.session };
232146
- }
232147
- if (transform3 === "socket" && reply6.statusCode === 200 && value6?.ok === true) {
232148
- const grant = new URL(value6.url);
232149
- const expected = loopbackOrigin(session2.eventsUrl);
232150
- if (grant.protocol !== "ws:" || grant.hostname !== expected.hostname || grant.port !== expected.port || grant.search || grant.hash || grant.username || grant.password || !/^\/_ancha\/socket\/[a-f0-9]{64}$/.test(grant.pathname)) throw new Error("Invalid socket grant");
232151
- for (const [path10, old] of socketGrants) if (old.expires <= Date.now()) socketGrants.delete(path10);
232152
- if (socketGrants.size >= 128) throw new Error("Too many socket grants");
232153
- socketGrants.set(grant.pathname, { url: grant, expires: Date.now() + 3e4 });
232154
- value6 = { ...value6, url: (exposedOrigin ?? "").replace(/^http:/, "ws:") + grant.pathname };
232155
- }
232156
- const body8 = JSON.stringify(value6);
232157
- delete responseHeaders["content-encoding"];
232158
- delete responseHeaders["content-length"];
232159
- res.writeHead(reply6.statusCode ?? 502, { ...responseHeaders, "content-length": Buffer.byteLength(body8) });
232160
- res.end(body8);
232161
- } catch {
232162
- reject3(res, 502, "Tool context was not a valid bounded response.");
232163
- }
232164
232213
  });
232165
- });
232214
+ } catch {
232215
+ return reject3(res, 502, "Tool connection failed.");
232216
+ }
232166
232217
  upstreamRequests.add(target6);
232167
232218
  target6.once("close", () => upstreamRequests.delete(target6));
232168
232219
  target6.once("error", () => {
@@ -232383,6 +232434,7 @@ var init_runtime3 = __esm({
232383
232434
  concurrency: external_exports.number().int().positive(),
232384
232435
  seed: text26.nullable(),
232385
232436
  strict: external_exports.boolean(),
232437
+ simulatedAnswers: external_exports.enum(["allow", "fail"]).optional(),
232386
232438
  minPassRate: external_exports.number().min(0).max(1),
232387
232439
  allowUnwrapped: external_exports.array(text26),
232388
232440
  agentCommand: text26.nullable(),
@@ -232490,7 +232542,8 @@ function createComposioConnection(options5) {
232490
232542
  signal.removeEventListener("abort", abort);
232491
232543
  }
232492
232544
  }
232493
- const tag3 = (expiry, lease) => createHmac13("sha256", options5.apiKey).update(`ancha-route:${expiry}:${lease}`).digest("hex").slice(0, 16);
232545
+ const tag3 = (expiry, lease, key5 = options5.apiKey) => createHmac13("sha256", key5).update(`ancha-route:${expiry}:${lease}`).digest("hex").slice(0, 16);
232546
+ const signers = [options5.apiKey, ...options5.savedApiKey && options5.savedApiKey !== options5.apiKey ? [options5.savedApiKey] : []];
232494
232547
  async function sweep() {
232495
232548
  const signal = AbortSignal.timeout(5e3);
232496
232549
  let cursor4, deletions = 0;
@@ -232508,7 +232561,7 @@ function createComposioConnection(options5) {
232508
232561
  if (!config12.success || visited.has(config12.data.id)) continue;
232509
232562
  visited.add(config12.data.id);
232510
232563
  const match3 = /^ancha-route-(\d{10})-([a-z0-9]{12})-([a-f0-9]{16})$/.exec(config12.data.name);
232511
- if (!match3 || Number(match3[1]) * 1e3 >= Date.now() || !timingSafeEqual12(Buffer.from(match3[3]), Buffer.from(tag3(match3[1], match3[2])))) continue;
232564
+ if (!match3 || Number(match3[1]) * 1e3 >= Date.now() || !signers.some((key5) => timingSafeEqual12(Buffer.from(match3[3]), Buffer.from(tag3(match3[1], match3[2], key5))))) continue;
232512
232565
  const accounts2 = await call4(`/connected_accounts?${new URLSearchParams({ auth_config_ids: config12.data.id, limit: "50" })}`, "GET", void 0, signal);
232513
232566
  if (accounts2.status < 200 || accounts2.status >= 300) continue;
232514
232567
  const listed2 = pageSchema.safeParse(accounts2.data);
@@ -232660,6 +232713,77 @@ var init_composio_connection = __esm({
232660
232713
  }
232661
232714
  });
232662
232715
 
232716
+ // backend/src/execution/connection-route.ts
232717
+ function routedTools(routes2) {
232718
+ return ["quickbooks", "netsuite"].filter((tool) => routes2?.[tool] === "composio");
232719
+ }
232720
+ function routedProbeTask(routes2) {
232721
+ const systems = routedTools(routes2).map((tool) => tool === "netsuite" ? "NetSuite (NETSUITE_RUN_SUITEQL_QUERY)" : "QuickBooks (QUICKBOOKS_QUERY_ENTITIES)");
232722
+ return `Ancha connection check: read one customer in each of these systems and reply with their names: ${systems.join(", ")}. Change nothing.`;
232723
+ }
232724
+ function unusableRouteKey(value6) {
232725
+ const key5 = routeKey(value6);
232726
+ if (!key5 || /^[\x21-\x7e]+$/.test(key5)) return void 0;
232727
+ return /[\r\n]/.test(key5) ? "a line break" : /[ \t]/.test(key5) ? "a space or tab" : /[^\x00-\x7f]/.test(key5) ? "a character that is not plain ASCII, such as a curly quote" : "a control character";
232728
+ }
232729
+ function connectionRouteEvidence(routes2, summary, trace2, log3) {
232730
+ const tools2 = routedTools(routes2);
232731
+ if (!tools2.length) return { details: [] };
232732
+ const counts2 = tools2.map((tool) => ({ tool, route: summary?.[tool] }));
232733
+ const details = counts2.map(({ tool, route: route15 }) => `${tool === "netsuite" ? "NetSuite" : "QuickBooks"} via Composio: ${route15?.executions ?? 0} execution${route15?.executions === 1 ? "" : "s"}, ${route15?.reached ?? 0} reached the world, ${route15?.refused ?? 0} refused${route15?.via ? ` \xB7 via direct ${route15.via.direct} / session ${route15.via.session} / MCP ${route15.via.mcp}` : ""}`);
232734
+ if (routeKeyRejected(trace2)) return { details, reason: { ...ROUTE_KEY_REASON } };
232735
+ const refused2 = trace2.filter((entry3) => entry3.routeEvent?.leg === "platform" && entry3.routeEvent.op === "refused");
232736
+ for (const entry3 of refused2.slice(0, 5)) {
232737
+ const event3 = entry3.routeEvent;
232738
+ if (event3.leg !== "platform") continue;
232739
+ details.push(`refused: ${event3.method} ${event3.slug ?? "Composio call"}${event3.via ? ` via ${event3.via}` : ""} (${event3.reason ?? "REFUSED"})`);
232740
+ }
232741
+ const first2 = refused2[0];
232742
+ if (first2 || counts2.some(({ route: route15 }) => (route15?.refused ?? 0) > 0)) return { details, reason: {
232743
+ code: "refused",
232744
+ level: "fail",
232745
+ message: "The Composio route refused a call.",
232746
+ fix: first2?.issue?.message ?? "Use the tools declared in agent.routes through COMPOSIO_BASE_URL."
232747
+ } };
232748
+ const platformCalled = trace2.some((entry3) => entry3.routeEvent?.leg === "platform") || counts2.some(({ route: route15 }) => (route15?.executions ?? 0) > 0 || (route15?.sessions ?? 0) > 0);
232749
+ if (!platformCalled && /\b(?:backend|api)\.composio\.(?:dev|ai)\b/i.test(log3)) return { details, reason: {
232750
+ code: "outside_host",
232751
+ level: "fail",
232752
+ message: "The agent called Composio\u2019s own API host without reaching the Ancha gateway.",
232753
+ fix: "The Composio client pins its API URL. Configure the client to take its API URL from COMPOSIO_BASE_URL, then run ancha agent upload again."
232754
+ } };
232755
+ const missed = counts2.filter(({ route: route15 }) => (route15?.executions ?? 0) > (route15?.reached ?? 0));
232756
+ const issue9 = trace2.find((entry3) => entry3.issue?.code === "ROUTE_NOT_REACHED" || entry3.issue?.code === "ROUTE_ARGUMENTS")?.issue;
232757
+ if (missed.length) return { details, reason: {
232758
+ code: "unserved",
232759
+ level: "warning",
232760
+ message: `The check\u2019s Composio executions did not reach ${missed.map(({ tool }) => tool === "netsuite" ? "NetSuite" : "QuickBooks").join(" or ")}.`,
232761
+ fix: issue9?.code === "ROUTE_ARGUMENTS" ? "Send NETSUITE_RUN_SUITEQL_QUERY its SuiteQL query in q, with integer limit and offset when paging." : issue9?.message ?? "Run ancha agent upload again."
232762
+ } };
232763
+ if (counts2.some(({ route: route15 }) => !route15?.reached)) return { details };
232764
+ return { details, reason: { code: "answered", level: "pass", message: "The agent\u2019s Composio executions reached each routed world." } };
232765
+ }
232766
+ var ROUTE_KEY_REASON, routeKeyRejected, routeKey, unusableKeyReason;
232767
+ var init_connection_route = __esm({
232768
+ "backend/src/execution/connection-route.ts"() {
232769
+ "use strict";
232770
+ ROUTE_KEY_REASON = {
232771
+ code: "route_key",
232772
+ level: "fail",
232773
+ message: "Composio did not accept the workspace secret COMPOSIO_API_KEY: it answered 401 to the agent\u2019s call through the route.",
232774
+ fix: "Export the Composio project\u2019s API key as COMPOSIO_API_KEY, run ancha secrets set COMPOSIO_API_KEY, then run ancha agent upload again."
232775
+ };
232776
+ routeKeyRejected = (entries4) => entries4.some((entry3) => entry3.issue?.code === "ROUTE_KEY_REJECTED");
232777
+ routeKey = (value6) => value6?.trim() ?? "";
232778
+ unusableKeyReason = (what, next2 = "run ancha agent upload again") => ({
232779
+ code: "route_key",
232780
+ level: "fail",
232781
+ message: `The workspace secret COMPOSIO_API_KEY contains ${what}, which an API key cannot carry in a request header.`,
232782
+ fix: `Export the Composio project\u2019s API key as COMPOSIO_API_KEY without that character, run ancha secrets set COMPOSIO_API_KEY, then ${next2}.`
232783
+ });
232784
+ }
232785
+ });
232786
+
232663
232787
  // backend/src/execution/ingress-client.ts
232664
232788
  import { createHash as createHash61, randomBytes as randomBytes6 } from "node:crypto";
232665
232789
  function ingressPath(path9, realm) {
@@ -232696,7 +232820,10 @@ async function startIngressClient(options5) {
232696
232820
  for (const toolkit of ["quickbooks", "netsuite"]) if (toolkits[toolkit] && twins.includes(toolkit)) activeToolkits[toolkit] = "composio";
232697
232821
  const qb = !!activeToolkits.quickbooks;
232698
232822
  const connection4 = qb ? env2.services.quickbooks : { url: "http://127.0.0.1", token: "", accountId: "" };
232699
- if (!connection4 || qb && (!connection4.accountId || !connection4.token) || !descriptor3.secretValues.COMPOSIO_API_KEY) throw new AnchaError("CONFIG_INVALID", "Composio route credentials are required");
232823
+ const apiKey = routeKey(descriptor3.secretValues.COMPOSIO_API_KEY);
232824
+ if (!connection4 || qb && (!connection4.accountId || !connection4.token) || !apiKey) throw new AnchaError("CONFIG_INVALID", "Composio route credentials are required");
232825
+ const unusable = unusableRouteKey(apiKey);
232826
+ if (unusable) throw new AnchaError("CONFIG_INVALID", unusableKeyReason(unusable).message);
232700
232827
  const local2 = new URL(connection4.url);
232701
232828
  if (qb && (local2.protocol !== "http:" || local2.hostname !== "127.0.0.1" || local2.username || local2.password || local2.search || local2.hash || local2.pathname.replace(/\/$/, "") !== `/e/${env2.id}/quickbooks`)) throw new Error("QuickBooks route must target its local world");
232702
232829
  const ns = activeToolkits.netsuite ? env2.services.netsuite : void 0;
@@ -232722,7 +232849,7 @@ async function startIngressClient(options5) {
232722
232849
  const toolkit = event3?.toolkit ?? (qb ? "quickbooks" : "netsuite");
232723
232850
  records6.push({ seq: 0, source: "world", service: toolkit, method: event3?.leg === "platform" ? event3.method : "RELAY", path: `/_route/${toolkit}`, tSim: env2.startTime, tReal: Date.now(), status: status6, routeEvent: event3 && { ...event3, toolkit }, ...issue10 && { issue: issue10 } });
232724
232851
  };
232725
- const issue9 = (code5, detail3, toolkit = qb ? "quickbooks" : "netsuite", owner5 = "harness") => ({ kind: "world", owner: owner5, service: toolkit, code: code5, message: `${code5}: ${detail3}` });
232852
+ const issue9 = (code5, detail3, toolkit = qb ? "quickbooks" : "netsuite", owner6 = "harness") => ({ kind: "world", owner: owner6, service: toolkit, code: code5, message: `${code5}: ${detail3}` });
232726
232853
  const fail9 = () => {
232727
232854
  if (failed2 || closed || options5.signal?.aborted) return;
232728
232855
  failed2 = true;
@@ -232815,7 +232942,8 @@ async function startIngressClient(options5) {
232815
232942
  const user9 = `ancha-${hash6(descriptor3.attemptId)}`;
232816
232943
  const lifecycle2 = createComposioConnection({
232817
232944
  ...options5.composio,
232818
- apiKey: descriptor3.secretValues.COMPOSIO_API_KEY,
232945
+ apiKey,
232946
+ savedApiKey: descriptor3.secretValues.COMPOSIO_API_KEY,
232819
232947
  user: user9,
232820
232948
  publicUrl,
232821
232949
  token: connection4.token,
@@ -232841,14 +232969,14 @@ async function startIngressClient(options5) {
232841
232969
  publicUrl,
232842
232970
  token: connection4.token,
232843
232971
  realm: connection4.accountId,
232844
- apiKey: descriptor3.secretValues.COMPOSIO_API_KEY,
232972
+ apiKey,
232845
232973
  attemptId: descriptor3.attemptId,
232846
232974
  agentKey,
232847
232975
  user: user9,
232848
232976
  connection: () => !qb || closed || failed2 || signal.aborted || Date.now() >= expires ? Promise.reject(new ComposioConnectionError(503, "ROUTE_CLOSED")) : lifecycle2.connection(),
232849
232977
  sessions: sessions2,
232850
232978
  narrowed: (toolkits2) => {
232851
- for (const toolkit of toolkits2) if (![agentKey, descriptor3.secretValues.COMPOSIO_API_KEY, connection4.token, ns?.token, publicUrl].some((secret) => secret && toolkit.includes(secret))) narrowed.add(toolkit);
232979
+ for (const toolkit of toolkits2) if (![agentKey, apiKey, connection4.token, ns?.token, publicUrl].some((secret) => secret && toolkit.includes(secret))) narrowed.add(toolkit);
232852
232980
  },
232853
232981
  signal: failure6.signal,
232854
232982
  get failed() {
@@ -232924,6 +233052,7 @@ var init_ingress_client = __esm({
232924
233052
  init_src();
232925
233053
  init_composio();
232926
233054
  init_composio_connection();
233055
+ init_connection_route();
232927
233056
  headersSchema = external_exports.record(external_exports.string(), external_exports.string());
232928
233057
  requestSchema = external_exports.strictObject({ rid: external_exports.string().min(1).max(256), method: external_exports.enum(["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"]), path: external_exports.string().max(8192), query: external_exports.string().max(8192), headers: headersSchema, body_b64: external_exports.string().max(87384) });
232929
233058
  batchSchema = external_exports.strictObject({ requests: external_exports.array(requestSchema).max(8) });
@@ -232984,6 +233113,12 @@ async function runRoutedTrial(spec, run7) {
232984
233113
  if (!spec.agent.routes?.quickbooks && !spec.agent.routes?.netsuite) return run7(spec);
232985
233114
  const descriptor3 = attemptDescriptor();
232986
233115
  const startedAt = performance.now();
233116
+ const unusable = unusableRouteKey(descriptor3.secretValues.COMPOSIO_API_KEY);
233117
+ if (unusable) {
233118
+ const { message: message8, fix } = unusableKeyReason(unusable, "run again");
233119
+ const result = await invalidTrial({ scene: spec.scene, trial: spec.trial, dir: spec.dir, startedAt, envId: spec.env.id, service: spec.agent.routes.quickbooks ? "quickbooks" : "netsuite", error: { code: "ROUTE_KEY_REJECTED", message: `${message8} ${fix}` } });
233120
+ return { ...result, harnessIssues: result.harnessIssues.map((issue9) => ({ ...issue9, code: "ROUTE_KEY_REJECTED" })) };
233121
+ }
232987
233122
  let sessionId, captured;
232988
233123
  const route15 = await startIngressClient({
232989
233124
  routes: spec.agent.routes,
@@ -233048,6 +233183,7 @@ var init_routed_trial = __esm({
233048
233183
  init_invalid_trial();
233049
233184
  init_runtime3();
233050
233185
  init_ingress_client();
233186
+ init_connection_route();
233051
233187
  connections3 = /* @__PURE__ */ new WeakMap();
233052
233188
  captures = /* @__PURE__ */ new WeakMap();
233053
233189
  trialIngress = (env2) => connections3.get(env2);
@@ -235686,7 +235822,16 @@ function attemptOutcome(view3, ctx) {
235686
235822
  return out({ code: "answered", level: "pass", message: ctx.check === "netsuite" ? answeredNetsuite(netsuite, answer.text) : `It took the task and answered ${quoted3(answer.text)}.` });
235687
235823
  }
235688
235824
  const model2 = view3.modelReplies?.find((reply6) => MODEL_REFUSALS.has(reply6.status));
235689
- if (model2 !== void 0) return out({ code: "model_key", level: "fail", message: `The model key was refused: ${model2.host} answered ${model2.status}${model2.message ? ` (${model2.message})` : ""}.`, fix: `ancha secrets set ${modelKeyName(model2.host, ctx.given ?? [])}` });
235825
+ if (model2 !== void 0) {
235826
+ const failure6 = modelFailure(model2.status);
235827
+ return out({
235828
+ code: "model_key",
235829
+ kind: failure6.kind,
235830
+ level: "fail",
235831
+ message: `${failure6.outcome}: ${model2.host} answered ${model2.status}${model2.message ? ` (${model2.message})` : ""}.`,
235832
+ fix: failure6.fix ?? `ancha secrets set ${modelKeyName(model2.host, ctx.given ?? [])}`
235833
+ });
235834
+ }
235690
235835
  const refused2 = (entry3) => entry3.status === 401 || entry3.status === 403;
235691
235836
  const turnedDown = used.length > 0 && used.every(refused2) ? used : data7.length > 0 && data7.every(refused2) ? data7 : [];
235692
235837
  if (turnedDown.length > 0) {
@@ -235794,12 +235939,13 @@ async function recordAnswer(backend, envId, sessionId, output2, source, printed)
235794
235939
  }
235795
235940
  }
235796
235941
  function modelKeyIssue(refusal4, given2) {
235942
+ const failure6 = modelFailure(refusal4.status);
235797
235943
  return {
235798
235944
  kind: "model",
235799
235945
  owner: "harness",
235800
235946
  service: refusal4.host,
235801
- code: "MODEL_KEY_REFUSED",
235802
- message: `${refusal4.host} refused the agent's model key (${refusal4.status}${refusal4.message ? `: ${refusal4.message}` : ""}), so the attempt tested nothing. Give the agent a working ${modelKeyName(refusal4.host, given2)} and run again.`
235947
+ code: failure6.code,
235948
+ message: `${refusal4.host} ${failure6.did} (${refusal4.status}${refusal4.message ? `: ${refusal4.message}` : ""}), so the attempt tested nothing. ${failure6.fix ?? `Give the agent a working ${modelKeyName(refusal4.host, given2)} and run again.`}`
235803
235949
  };
235804
235950
  }
235805
235951
  function recordStdout(backend, envId, sessionId, output2) {
@@ -235972,6 +236118,7 @@ var EXIT_COMMAND_NOT_FOUND2, unknownRoute18;
235972
236118
  var init_trial = __esm({
235973
236119
  "backend/src/runner/trial.ts"() {
235974
236120
  "use strict";
236121
+ init_gateway();
235975
236122
  init_routed_trial();
235976
236123
  init_slack_app();
235977
236124
  init_src();
@@ -237263,7 +237410,7 @@ async function readRunState(outDir, runId2) {
237263
237410
  updatedAt: summary.finishedAt,
237264
237411
  completedTrials,
237265
237412
  totalTrials,
237266
- ...exitCode === void 0 ? { error: { code: "INTERNAL", message: "Run finished; exit code is unknown because the saved summary has no exitCode." } } : { exitCode }
237413
+ ...exitCode === void 0 ? { error: { code: "INTERNAL", kind: "ours", message: "Run finished; exit code is unknown because the saved summary has no exitCode." } } : { exitCode }
237267
237414
  };
237268
237415
  }
237269
237416
  throw new AnchaError("INTERNAL", "cannot read run status", { cause: error65 });
@@ -237280,7 +237427,7 @@ async function readRunState(outDir, runId2) {
237280
237427
  alive4 = error65.code !== "ESRCH";
237281
237428
  }
237282
237429
  if (!alive4 || Date.now() - Date.parse(state3.updatedAt) > 15e3) {
237283
- return { ...state3, state: "failed", exitCode: 3, error: { code: "INTERNAL", message: alive4 ? "run worker heartbeat expired; completion is unknown" : "run worker exited without a terminal status" } };
237430
+ return { ...state3, state: "failed", exitCode: 3, error: { code: "INTERNAL", kind: "ours", message: alive4 ? "run worker heartbeat expired; completion is unknown" : "run worker exited without a terminal status" } };
237284
237431
  }
237285
237432
  }
237286
237433
  return state3;
@@ -241528,17 +241675,17 @@ function buildSeed(cx, { writes: writes3, state: state3, get: get8, listed: list
241528
241675
  linesNote(s3, "one line carries its total");
241529
241676
  }
241530
241677
  }
241531
- const owner5 = party4(s3, kind2), from = s3.fields.createdFrom && get8(s3.fields.createdFrom), order6 = from && idOf4(from), orderType = purchase ? "purchaseOrder" : "salesOrder";
241678
+ const owner6 = party4(s3, kind2), from = s3.fields.createdFrom && get8(s3.fields.createdFrom), order6 = from && idOf4(from), orderType = purchase ? "purchaseOrder" : "salesOrder";
241532
241679
  let linked2 = false;
241533
241680
  if (type !== "creditMemo" && order6 && docs2.get(order6)?.type === orderType) {
241534
- if (docs2.get(order6).owner === owner5 && !docs2.get(order6).pending && !expenses.length && fitOrder(order6, lines2, "billed")) linked2 = true;
241681
+ if (docs2.get(order6).owner === owner6 && !docs2.get(order6).pending && !expenses.length && fitOrder(order6, lines2, "billed")) linked2 = true;
241535
241682
  else note2("inferred", `seed.netsuite.${SEED_LIST[type]}.${base6.id}.${orderType}`, `${label7(s3)} was made from ${label7(from)}, but its lines do not fit what the test's ${LABEL2[orderType].toLowerCase()} has left to bill, so it stands alone`);
241536
241683
  }
241537
241684
  const approval = purchase ? s3.fields.approval ?? (/pending approval/i.test(String(s3.fields.status ?? "")) ? "pending" : /rejected/i.test(String(s3.fields.status ?? "")) ? "rejected" : /open|paid/i.test(String(s3.fields.status ?? "")) || s3.fields.remaining < s3.fields.total ? "approved" : void 0) : void 0;
241538
241685
  if (purchase && approval === void 0) note2("missing", `seed.netsuite.vendorBills.${base6.id}.approval`, `${label7(s3)}: its approval never showed; it waits for approval, as new bills do`);
241539
241686
  const row2 = {
241540
241687
  ...base6,
241541
- [kind2]: owner5,
241688
+ [kind2]: owner6,
241542
241689
  ...type !== "creditMemo" && termsOf(s3) && { terms: termsOf(s3) },
241543
241690
  ...type !== "creditMemo" && dueOf(s3) && { dueDate: dueOf(s3) },
241544
241691
  ...approval && { approval },
@@ -241549,7 +241696,7 @@ function buildSeed(cx, { writes: writes3, state: state3, get: get8, listed: list
241549
241696
  if (type === "creditMemo") row2.apply = [];
241550
241697
  lists3[SEED_LIST[type]].push(row2);
241551
241698
  const total6 = round2(totalOf(lines2, purchase) + sum6(expenses.map((e) => e.amount)));
241552
- docs2.set(base6.id, { type, owner: owner5, total: total6, open: total6, approved: approval === "approved", s: s3, row: row2 });
241699
+ docs2.set(base6.id, { type, owner: owner6, total: total6, open: total6, approved: approval === "approved", s: s3, row: row2 });
241553
241700
  observed(s3, `${total6.toFixed(2)}${approval ? `, ${approval === "pending" ? "pending approval" : approval}` : ""}${linked2 ? `, from ${label7(from)}` : ""}`);
241554
241701
  if (s3.fields.total !== void 0 && Math.abs(money22(s3.fields.total) - total6) > 4e-3) note2("inferred", `seed.netsuite.${SEED_LIST[type]}.${base6.id}.total`, `${label7(s3)} totaled ${money22(s3.fields.total).toFixed(2)} in production; its lines here total ${total6.toFixed(2)}`);
241555
241702
  }
@@ -241568,7 +241715,7 @@ function buildSeed(cx, { writes: writes3, state: state3, get: get8, listed: list
241568
241715
  return out;
241569
241716
  };
241570
241717
  for (const [type, kind2] of [["customerPayment", "customer"], ["vendorPayment", "vendor"]]) for (const s3 of byType(type)) {
241571
- const base6 = header4(s3), owner5 = party4(s3, kind2), apply2 = applied(s3, SEED_LIST[type], { owner: owner5 });
241718
+ const base6 = header4(s3), owner6 = party4(s3, kind2), apply2 = applied(s3, SEED_LIST[type], { owner: owner6 });
241572
241719
  const amount6 = money22(s3.fields.payment ?? s3.fields.total) ?? sum6(apply2.map((a) => a.amount));
241573
241720
  const total6 = Math.max(amount6, sum6(apply2.map((a) => a.amount)));
241574
241721
  if (!(total6 > 0)) {
@@ -241576,8 +241723,8 @@ function buildSeed(cx, { writes: writes3, state: state3, get: get8, listed: list
241576
241723
  continue;
241577
241724
  }
241578
241725
  const acct = account9(s3.fields.account, type === "vendorPayment" ? "bank" : "funds");
241579
- lists3[SEED_LIST[type]].push({ ...base6, [kind2]: owner5, amount: total6, ...acct && { account: acct }, apply: apply2 });
241580
- docs2.set(base6.id, { type, owner: owner5, total: total6 });
241726
+ lists3[SEED_LIST[type]].push({ ...base6, [kind2]: owner6, amount: total6, ...acct && { account: acct }, apply: apply2 });
241727
+ docs2.set(base6.id, { type, owner: owner6, total: total6 });
241581
241728
  observed(s3, `${total6.toFixed(2)}${apply2.length ? `, applied to ${apply2.map((a) => label7(docs2.get(a.doc).s)).join(", ")}` : ""}`);
241582
241729
  if (amount6 < sum6(apply2.map((a) => a.amount))) note2("inferred", `seed.netsuite.${SEED_LIST[type]}.${base6.id}.amount`, `${label7(s3)}: its amount never showed; what it applied stands in`);
241583
241730
  }
@@ -242853,11 +243000,11 @@ function startingState(check4, scene2) {
242853
243000
  const args = check4["github.permission"], github3 = seed44.github;
242854
243001
  const repo4 = github3.repos?.find((r2) => r2.ref === refName7(args.repo)), user9 = github3.users?.find((u) => u.ref === refName7(args.user));
242855
243002
  if (!repo4 || !user9) return "unknown";
242856
- const owner5 = repo4.name.split("/")[0].toLowerCase();
242857
- const member4 = github3.orgs?.find((o) => o.login.toLowerCase() === owner5)?.members?.some((m) => refName7(m.user) === user9.ref);
243003
+ const owner6 = repo4.name.split("/")[0].toLowerCase();
243004
+ const member4 = github3.orgs?.find((o) => o.login.toLowerCase() === owner6)?.members?.some((m) => refName7(m.user) === user9.ref);
242858
243005
  const collaborator = repo4.collaborators?.find((c) => refName7(c.user) === user9.ref);
242859
243006
  const direct = collaborator ? collaborator.permission ?? "write" : "none";
242860
- const permission7 = owner5 === user9.login.toLowerCase() ? "admin" : direct === "none" && member4 ? "read" : direct;
243007
+ const permission7 = owner6 === user9.login.toLowerCase() ? "admin" : direct === "none" && member4 ? "read" : direct;
242861
243008
  return productionState(check4, scene2, [read7("github", `/repos/${repo4.name}/collaborators/${user9.login}/permission`, {}, { permission: permission7 })]);
242862
243009
  }
242863
243010
  if ("github.file_at" in check4 && seed44.github) {
@@ -243397,65 +243544,6 @@ var init_dependency_plan = __esm({
243397
243544
  }
243398
243545
  });
243399
243546
 
243400
- // backend/src/execution/connection-route.ts
243401
- function routedTools(routes2) {
243402
- return ["quickbooks", "netsuite"].filter((tool) => routes2?.[tool] === "composio");
243403
- }
243404
- function routedProbeTask(routes2) {
243405
- const systems = routedTools(routes2).map((tool) => tool === "netsuite" ? "NetSuite (NETSUITE_RUN_SUITEQL_QUERY)" : "QuickBooks (QUICKBOOKS_QUERY_ENTITIES)");
243406
- return `Ancha connection check: read one customer in each of these systems and reply with their names: ${systems.join(", ")}. Change nothing.`;
243407
- }
243408
- function connectionRouteEvidence(routes2, summary, trace2, log3) {
243409
- const tools2 = routedTools(routes2);
243410
- if (!tools2.length) return { details: [] };
243411
- const counts2 = tools2.map((tool) => ({ tool, route: summary?.[tool] }));
243412
- const details = counts2.map(({ tool, route: route15 }) => `${tool === "netsuite" ? "NetSuite" : "QuickBooks"} via Composio: ${route15?.executions ?? 0} execution${route15?.executions === 1 ? "" : "s"}, ${route15?.reached ?? 0} reached the world, ${route15?.refused ?? 0} refused${route15?.via ? ` \xB7 via direct ${route15.via.direct} / session ${route15.via.session} / MCP ${route15.via.mcp}` : ""}`);
243413
- if (routeKeyRejected(trace2)) return { details, reason: { ...ROUTE_KEY_REASON } };
243414
- const refused2 = trace2.filter((entry3) => entry3.routeEvent?.leg === "platform" && entry3.routeEvent.op === "refused");
243415
- for (const entry3 of refused2.slice(0, 5)) {
243416
- const event3 = entry3.routeEvent;
243417
- if (event3.leg !== "platform") continue;
243418
- details.push(`refused: ${event3.method} ${event3.slug ?? "Composio call"}${event3.via ? ` via ${event3.via}` : ""} (${event3.reason ?? "REFUSED"})`);
243419
- }
243420
- const first2 = refused2[0];
243421
- if (first2 || counts2.some(({ route: route15 }) => (route15?.refused ?? 0) > 0)) return { details, reason: {
243422
- code: "refused",
243423
- level: "fail",
243424
- message: "The Composio route refused a call.",
243425
- fix: first2?.issue?.message ?? "Use the tools declared in agent.routes through COMPOSIO_BASE_URL."
243426
- } };
243427
- const platformCalled = trace2.some((entry3) => entry3.routeEvent?.leg === "platform") || counts2.some(({ route: route15 }) => (route15?.executions ?? 0) > 0 || (route15?.sessions ?? 0) > 0);
243428
- if (!platformCalled && /\b(?:backend|api)\.composio\.(?:dev|ai)\b/i.test(log3)) return { details, reason: {
243429
- code: "outside_host",
243430
- level: "fail",
243431
- message: "The agent called Composio\u2019s own API host without reaching the Ancha gateway.",
243432
- fix: "The Composio client pins its API URL. Configure the client to take its API URL from COMPOSIO_BASE_URL, then run ancha agent upload again."
243433
- } };
243434
- const missed = counts2.filter(({ route: route15 }) => (route15?.executions ?? 0) > (route15?.reached ?? 0));
243435
- const issue9 = trace2.find((entry3) => entry3.issue?.code === "ROUTE_NOT_REACHED" || entry3.issue?.code === "ROUTE_ARGUMENTS")?.issue;
243436
- if (missed.length) return { details, reason: {
243437
- code: "unserved",
243438
- level: "warning",
243439
- message: `The check\u2019s Composio executions did not reach ${missed.map(({ tool }) => tool === "netsuite" ? "NetSuite" : "QuickBooks").join(" or ")}.`,
243440
- fix: issue9?.code === "ROUTE_ARGUMENTS" ? "Send NETSUITE_RUN_SUITEQL_QUERY its SuiteQL query in q, with integer limit and offset when paging." : issue9?.message ?? "Run ancha agent upload again."
243441
- } };
243442
- if (counts2.some(({ route: route15 }) => !route15?.reached)) return { details };
243443
- return { details, reason: { code: "answered", level: "pass", message: "The agent\u2019s Composio executions reached each routed world." } };
243444
- }
243445
- var ROUTE_KEY_REASON, routeKeyRejected;
243446
- var init_connection_route = __esm({
243447
- "backend/src/execution/connection-route.ts"() {
243448
- "use strict";
243449
- ROUTE_KEY_REASON = {
243450
- code: "route_key",
243451
- level: "fail",
243452
- message: "Composio did not accept the workspace secret COMPOSIO_API_KEY: it answered 401 to the agent\u2019s call through the route.",
243453
- fix: "Export the Composio project\u2019s API key as COMPOSIO_API_KEY, run ancha secrets set COMPOSIO_API_KEY, then run ancha agent upload again."
243454
- };
243455
- routeKeyRejected = (entries4) => entries4.some((entry3) => entry3.issue?.code === "ROUTE_KEY_REJECTED");
243456
- }
243457
- });
243458
-
243459
243547
  // backend/src/execution/vm-connection.ts
243460
243548
  var vm_connection_exports = {};
243461
243549
  __export(vm_connection_exports, {
@@ -243521,6 +243609,21 @@ function taskFixFromLog(lines2, agent) {
243521
243609
  if (input5 === null) return void 0;
243522
243610
  return { name: input5.name, via: input5.via, file: input5.file, yaml: taskWiring(input5, agent.command).yaml };
243523
243611
  }
243612
+ function connectionFailure(cause, descriptor3) {
243613
+ const error65 = toErrorJson(cause);
243614
+ const redact4 = (text31) => {
243615
+ for (const value6 of Object.values(descriptor3.secretValues).filter((value7) => value7.length > 0).sort((a, b) => b.length - a.length)) {
243616
+ for (const form2 of [value6, JSON.stringify(value6).slice(1, -1), encodeURIComponent(value6)]) text31 = text31.replaceAll(form2, "[redacted]");
243617
+ }
243618
+ return text31;
243619
+ };
243620
+ return new AnchaError(error65.code, redact4(error65.message), {
243621
+ kind: error65.kind,
243622
+ ...error65.hint && { hint: redact4(error65.hint) },
243623
+ ...error65.reference && { reference: error65.reference },
243624
+ cause
243625
+ });
243626
+ }
243524
243627
  async function probeVmConnection(descriptor3, deps = {}) {
243525
243628
  if (descriptor3 !== attemptDescriptor() || descriptor3.role !== "connect") throw new AnchaError("CONFIG_INVALID", "A connection attempt descriptor is required.");
243526
243629
  const probe = { kind: "command", passed: false, startedAt: null, readyAt: null, exitCode: null };
@@ -243530,6 +243633,11 @@ async function probeVmConnection(descriptor3, deps = {}) {
243530
243633
  const config12 = deps.agent ? void 0 : await loadConfig(descriptor3.projectDir, descriptor3.configPath);
243531
243634
  const agent = deps.agent ?? withLocalEnvironment(resolveRunAgent(config12, descriptor3.projectDir, { ...descriptor3.options.agentCommand !== null && { agent: descriptor3.options.agentCommand }, parallel: 1 }).agent, config12);
243532
243635
  if (agent.mode === "endpoint") assertVmEndpoint(agent);
243636
+ const unusable = routedTools(agent.routes).length ? unusableRouteKey(descriptor3.secretValues.COMPOSIO_API_KEY) : void 0;
243637
+ if (unusable) {
243638
+ probe.reason = unusableKeyReason(unusable);
243639
+ return { state: "failed", probe, message: probe.reason.message };
243640
+ }
243533
243641
  if (agent.slackTransport === "socket" || agent.mode === "endpoint" && agent.slackTransport === "http" && (!agent.readyUrl || config12?.agent?.slackTransport === "http" || deps.agent?.slackTransport === "http")) {
243534
243642
  return await probeSlackApp(descriptor3, agent, probe, deps);
243535
243643
  }
@@ -243616,7 +243724,7 @@ async function probeVmConnection(descriptor3, deps = {}) {
243616
243724
  const text31 = await readFile25(join44(descriptor3.outDir, "agent.log"), "utf8").catch(() => "");
243617
243725
  const tail = text31.trimEnd().split("\n").filter(Boolean).slice(-10);
243618
243726
  if (tail.length) probe.logTail = tail;
243619
- if (error65 instanceof AnchaError && error65.code === "CONFIG_INVALID") return { state: "failed", probe, message: `${error65.message}${error65.hint ? `; ${error65.hint}` : ""}` };
243727
+ if (error65 instanceof AnchaError || !(error65 instanceof Error) || !["AbortError", "TimeoutError"].includes(error65.name)) throw connectionFailure(error65, descriptor3);
243620
243728
  return { state: "failed", probe, message: probe.kind === "http" ? "The agent did not pass its HTTP readiness check. Check its command and runtime configuration." : "The agent executable could not be checked. Check its command and required environment variables." };
243621
243729
  } finally {
243622
243730
  try {
@@ -243673,7 +243781,9 @@ async function runWithTask(descriptor3, agent, run7) {
243673
243781
  realTimeouts: { [scene2.id]: limit2 }
243674
243782
  });
243675
243783
  trial = result.results.get(scene2.id)?.trials[0];
243676
- } catch {
243784
+ } catch (cause) {
243785
+ const error65 = connectionFailure(cause, descriptor3);
243786
+ throw new AnchaError(error65.code, `The connection check could not start: ${error65.message}`, { ...error65, cause });
243677
243787
  } finally {
243678
243788
  await backend?.close().catch(() => {
243679
243789
  });
@@ -243682,7 +243792,7 @@ async function runWithTask(descriptor3, agent, run7) {
243682
243792
  if (log3 !== void 0) writeSync7(run7.fd, log3);
243683
243793
  probe.durationMs = trial?.realMs ?? 0;
243684
243794
  probe.exitCode = trial?.exitCode ?? null;
243685
- if (trial === void 0) return { state: "failed", probe, message: "The connection check could not start." };
243795
+ if (trial === void 0) throw new AnchaError("INTERNAL", "The connection check ended without a trial result.");
243686
243796
  probe.tools = probeToolCalls(twins, trial.trace);
243687
243797
  const tail = trial.logTail, fix = taskFixFromLog(tail, { command, env: agent.env });
243688
243798
  const text31 = log3?.toString("utf8") ?? tail.join("\n");
@@ -243692,12 +243802,9 @@ async function runWithTask(descriptor3, agent, run7) {
243692
243802
  Object.assign(probe, { reason: route15.reason, logTail: tail.length > 0 ? tail : text31.trimEnd().split("\n").filter(Boolean).slice(-10) });
243693
243803
  return { state: "failed", probe, message: route15.reason.message };
243694
243804
  }
243695
- const diagnosed = (code5) => code5 === "MODEL_KEY_REFUSED" || routed && (code5 === "ROUTE_REFUSED" || code5 === "ROUTE_NOT_REACHED" || code5 === "ROUTE_KEY_REJECTED");
243805
+ const diagnosed = (code5) => ["MODEL_KEY_REFUSED", "MODEL_RATE_LIMITED", "MODEL_CREDITS_EXHAUSTED"].includes(code5 ?? "") || routed && (code5 === "ROUTE_REFUSED" || code5 === "ROUTE_NOT_REACHED" || code5 === "ROUTE_KEY_REJECTED");
243696
243806
  const harnessIssue = trial.harnessIssues.some((issue9) => issue9.owner === "harness" && !diagnosed(issue9.code));
243697
- if (harnessIssue || !trial.valid && !trial.harnessIssues.some((issue9) => diagnosed(issue9.code))) {
243698
- Object.assign(probe, { logTail: tail, ...fix !== void 0 && { fix } });
243699
- return { state: "failed", probe, message: unfinished(trial) };
243700
- }
243807
+ if (harnessIssue || !trial.valid && !trial.harnessIssues.some((issue9) => diagnosed(issue9.code))) throw connectionFailure(new AnchaError("INTERNAL", unfinished(trial)), descriptor3);
243701
243808
  if (trial.exit === "spawn_failed" && agent.taskInput?.kind === "http") {
243702
243809
  probe.logTail = tail;
243703
243810
  return { state: "failed", probe, message: trial.taskDelivery?.message ?? "The agent did not pass its HTTP readiness check." };
@@ -243892,8 +243999,10 @@ function finalizeInput(value6) {
243892
243999
  if (!TERMINAL.includes(item2.state)) wrong(`has attempt ${item2.id}, which has not ended`);
243893
244000
  if (item2.artifactHash !== null && (typeof item2.artifactHash !== "string" || !SHA256.test(item2.artifactHash))) wrong(`has attempt ${item2.id} with an artifact hash that is not one`);
243894
244001
  if (item2.error !== null) {
243895
- const error65 = fields13(item2.error, "attempts[].error", ["code", "message"], ["hint", "step"]);
244002
+ const error65 = fields13(item2.error, "attempts[].error", ["code", "message"], ["hint", "step", "kind", "reference", "stderr"]);
243896
244003
  if (typeof error65.code !== "string" || typeof error65.message !== "string") wrong(`has attempt ${item2.id} with an error that says nothing`);
244004
+ if (error65.kind !== void 0 && !["fix", "retry", "ours"].includes(error65.kind)) wrong(`has attempt ${item2.id} with an error kind that is not one`);
244005
+ if (error65.reference !== void 0 && typeof error65.reference !== "string" || error65.stderr !== void 0 && typeof error65.stderr !== "string") wrong(`has attempt ${item2.id} with an error reference or stderr that is not text`);
243897
244006
  }
243898
244007
  }
243899
244008
  return value6;
@@ -245128,17 +245237,17 @@ function readAccess(cx, repos, loginRef) {
245128
245237
  }
245129
245238
  for (const [full2, list19] of grants) for (const [login2, g] of list19) if (g.how === "observed") cx.note("observed", `seed.github.repos.${full2}.collaborators.${login2}`, `direct ${g.permission}`, [g.span]);
245130
245239
  for (const l of left) membership(l.org, l.login, "member", "inferred", l.span);
245131
- for (const owner5 of new Set(removed.map((r2) => r2.full.split("/")[0]))) {
245132
- const unread2 = removed.filter((r2) => r2.full.startsWith(`${owner5}/`) && !members4.get(owner5)?.has(r2.login));
245240
+ for (const owner6 of new Set(removed.map((r2) => r2.full.split("/")[0]))) {
245241
+ const unread2 = removed.filter((r2) => r2.full.startsWith(`${owner6}/`) && !members4.get(owner6)?.has(r2.login));
245133
245242
  if (!unread2.length) continue;
245134
- const id15 = `github.members.${owner5}`, answer = cx.answers[id15];
245243
+ const id15 = `github.members.${owner6}`, answer = cx.answers[id15];
245135
245244
  const people4 = [...new Set(unread2.map((r2) => r2.login))].join(", "), where3 = [...new Set(unread2.map((r2) => r2.full))].join(", ");
245136
- cx.ask(id15, `Who were members of the ${owner5} organization when the run started? A member reads every ${owner5} repository, so a member whose direct access the agent removed (${people4} on ${where3}) still reads it. The trace never shows the membership.`, ["none", "their logins, comma-separated"], 0, { type: "text" });
245245
+ cx.ask(id15, `Who were members of the ${owner6} organization when the run started? A member reads every ${owner6} repository, so a member whose direct access the agent removed (${people4} on ${where3}) still reads it. The trace never shows the membership.`, ["none", "their logins, comma-separated"], 0, { type: "text" });
245137
245246
  if (typeof answer !== "string") continue;
245138
245247
  const named5 = /^\s*none\s*$/i.test(answer) ? [] : answer.split(/[\s,]+/).filter(Boolean);
245139
- for (const login2 of named5) membership(owner5, login2, "member", "answered");
245140
- for (const r2 of unread2) if (!named5.some((n2) => n2.toLowerCase() === r2.login.toLowerCase())) membership(owner5, r2.login, false, "answered");
245141
- cx.note("answered", `seed.github.orgs.${owner5}.members`, `your answer: ${named5.length ? named5.join(", ") : "none"}`);
245248
+ for (const login2 of named5) membership(owner6, login2, "member", "answered");
245249
+ for (const r2 of unread2) if (!named5.some((n2) => n2.toLowerCase() === r2.login.toLowerCase())) membership(owner6, r2.login, false, "answered");
245250
+ cx.note("answered", `seed.github.orgs.${owner6}.members`, `your answer: ${named5.length ? named5.join(", ") : "none"}`);
245142
245251
  }
245143
245252
  for (const [org5, list19] of members4) for (const [login2, m] of list19) if (m.how === "observed") cx.note("observed", `seed.github.orgs.${org5}.members.${login2}`, m.member ? `member (${m.member})` : "not a member", [m.span]);
245144
245253
  const isMember3 = (org5, login2) => {
@@ -245450,8 +245559,8 @@ function readGoogleDrive(cx) {
245450
245559
  }
245451
245560
  for (const f2 of c.path === "/drive/v3/files" ? Array.isArray(c.response?.files) ? c.response.files : [] : FILE2.exec(c.path) && c.response?.id ? [c.response] : []) {
245452
245561
  if (!f2?.id) continue;
245453
- const owner5 = person5(f2.owners?.[0]?.emailAddress, f2.owners?.[0]?.displayName), before = c.ms < changedAt(f2.id), had = files2.get(f2.id);
245454
- if (!had || before && !had.before) files2.set(f2.id, { ...had, ...f2, owner: before ? owner5 : had?.owner, before, span: c.id });
245562
+ const owner6 = person5(f2.owners?.[0]?.emailAddress, f2.owners?.[0]?.displayName), before = c.ms < changedAt(f2.id), had = files2.get(f2.id);
245563
+ if (!had || before && !had.before) files2.set(f2.id, { ...had, ...f2, owner: before ? owner6 : had?.owner, before, span: c.id });
245455
245564
  }
245456
245565
  const m = PERMISSIONS.exec(c.path);
245457
245566
  if (!m) continue;
@@ -245907,12 +246016,12 @@ function proposeAccessChecks(cx, { okta, drive: drive2, pagerduty, github: githu
245907
246016
  }
245908
246017
  const removed = github3?.access?.removed ?? [], repos = (login2) => new Set(removed.filter((r2) => r2.login.toLowerCase() === login2.toLowerCase()).map((r2) => r2.full)).size;
245909
246018
  for (const r2 of removed) {
245910
- const repo4 = github3.repos.get(r2.full)?.ref, owner5 = r2.full.split("/")[0];
246019
+ const repo4 = github3.repos.get(r2.full)?.ref, owner6 = r2.full.split("/")[0];
245911
246020
  if (!repo4) continue;
245912
- const member4 = github3.access.isMember(owner5, r2.login), left = github3.access.left.some((l) => l.org === owner5 && l.login.toLowerCase() === r2.login.toLowerCase());
246021
+ const member4 = github3.access.isMember(owner6, r2.login), left = github3.access.left.some((l) => l.org === owner6 && l.login.toLowerCase() === r2.login.toLowerCase());
245913
246022
  add(
245914
246023
  { id: `github-access-ended-${slug16(r2.login)}${repos(r2.login) > 1 ? `-${slug16(r2.full.split("/")[1])}` : ""}`, state: { "github.permission": { repo: `$${repo4}`, user: `$${github3.access.refOf(r2.login)}` }, is: "none" } },
245915
- `the agent removed ${r2.login}'s direct access to ${r2.full}${member4 && !left ? `; still a member of ${owner5}, ${r2.login} kept read access in production` : ""}`,
246024
+ `the agent removed ${r2.login}'s direct access to ${r2.full}${member4 && !left ? `; still a member of ${owner6}, ${r2.login} kept read access in production` : ""}`,
245916
246025
  left || member4 === false ? "passed" : member4 ? "failed" : "unknown"
245917
246026
  );
245918
246027
  }
@@ -246017,9 +246126,9 @@ function invert(map2, items2, cx) {
246017
246126
  for (const t of touched.filter((t2) => t2.path === r2.path && t2.target.collection === r2.collection)) links4.push({ owner: t.target, ...r2, ids: [String(value6)] });
246018
246127
  continue;
246019
246128
  }
246020
- const owner5 = byId3(r2.collection, value6) ?? entity5(r2.collection, void 0, value6);
246021
- if (pinOf(r2.collection)) owner5.fields[pinOf(r2.collection)] ??= value6;
246022
- links4.push({ owner: owner5, ...r2, ids: [...expand3(item2.response, r2.field)].map(([, v]) => String(v)) });
246129
+ const owner6 = byId3(r2.collection, value6) ?? entity5(r2.collection, void 0, value6);
246130
+ if (pinOf(r2.collection)) owner6.fields[pinOf(r2.collection)] ??= value6;
246131
+ links4.push({ owner: owner6, ...r2, ids: [...expand3(item2.response, r2.field)].map(([, v]) => String(v)) });
246023
246132
  }
246024
246133
  }
246025
246134
  const fill = (into, from) => {
@@ -250111,6 +250220,25 @@ async function configuredServerUrl(ctx) {
250111
250220
  init_credentials();
250112
250221
  init_backend();
250113
250222
 
250223
+ // packages/cli/src/server-error.ts
250224
+ init_src();
250225
+ function serverError(status6, body8, fallback) {
250226
+ const value6 = body8 && typeof body8 === "object" ? body8.error : void 0;
250227
+ const error65 = value6 && typeof value6 === "object" ? value6 : {};
250228
+ const unauthorized = status6 === 401 && error65.code !== "AUTH_INVALID";
250229
+ const code5 = status6 === 401 ? "AUTH_INVALID" : isErrorCode(error65.code) ? error65.code : status6 === 403 ? "AUTH_INVALID" : status6 === 500 ? "INTERNAL" : status6 >= 502 && status6 <= 504 ? "SERVER_UNREACHABLE" : fallback.code ?? (status6 === 409 ? "SESSION_CONFLICT" : status6 === 422 ? "CONFIG_INVALID" : "USAGE");
250230
+ const opts = {};
250231
+ const hint = typeof error65.hint === "string" && !unauthorized ? error65.hint : fallback.hint ?? (typeof error65.hint === "string" ? error65.hint : void 0);
250232
+ if (hint !== void 0) opts.hint = hint;
250233
+ if (isErrorKind(error65.kind) && !unauthorized) opts.kind = error65.kind;
250234
+ else if (status6 === 429 || status6 >= 502 && status6 <= 504) opts.kind = "retry";
250235
+ else if (status6 === 500) opts.kind = "ours";
250236
+ if (typeof error65.reference === "string") opts.reference = error65.reference;
250237
+ const said = unauthorized ? void 0 : typeof error65.message === "string" ? error65.message : typeof value6 === "string" ? value6 : void 0;
250238
+ const result = new AnchaError(code5, said ?? fallback.message, opts);
250239
+ return typeof error65.step === "string" ? Object.assign(result, { step: error65.step }) : result;
250240
+ }
250241
+
250114
250242
  // packages/cli/src/hosted.ts
250115
250243
  init_src();
250116
250244
  init_credentials();
@@ -251110,8 +251238,8 @@ function namedFiles(path9, doc) {
251110
251238
  const to = record27(tool) ? beside(path9, tool.observations) : void 0;
251111
251239
  if (to !== void 0) named5.push({ field: `${field6}.${name5}.observations`, to, kind: "observations", role: "world" });
251112
251240
  }
251113
- const generated = (owner5, field6) => {
251114
- const to = record27(owner5) && record27(owner5.generated) ? beside(path9, owner5.generated.record) : void 0;
251241
+ const generated = (owner6, field6) => {
251242
+ const to = record27(owner6) && record27(owner6.generated) ? beside(path9, owner6.generated.record) : void 0;
251115
251243
  if (to !== void 0) named5.push({ field: field6, to, kind: "generated-record", role: "provenance" });
251116
251244
  };
251117
251245
  generated(doc, "generated.record");
@@ -251418,6 +251546,10 @@ init_report2();
251418
251546
 
251419
251547
  // packages/cli/src/output.ts
251420
251548
  init_src();
251549
+ function errorAction(error65) {
251550
+ const hint = error65.hint ?? (error65.kind === "retry" ? "nothing to change; run the same command again" : error65.kind === "ours" ? "this failed on Ancha's side, not in your setup" : "check the command and configuration, then run it again");
251551
+ return `${error65.kind}: ${hint.replaceAll("\n", "\n ")}${error65.reference ? ` (reference ${error65.reference})` : ""}`;
251552
+ }
251421
251553
  function terse(value6) {
251422
251554
  if (typeof value6 === "string") return /^[^\s"]+$/.test(value6) ? value6 : JSON.stringify(value6);
251423
251555
  return JSON.stringify(value6) ?? "undefined";
@@ -251514,7 +251646,7 @@ var Output = class {
251514
251646
  `);
251515
251647
  } else {
251516
251648
  const lines2 = [`error[${err2.code}]: ${err2.message.replaceAll("\n", "\n ")}`];
251517
- if (err2.hint !== void 0) lines2.push(`hint: ${err2.hint.replaceAll("\n", "\n ")}`);
251649
+ lines2.push(errorAction(e instanceof AnchaError ? err2 : { ...err2, hint: "a bug in the Ancha CLI, not in your setup" }));
251518
251650
  if (err2.docs !== void 0) lines2.push(`docs: ${err2.docs}`);
251519
251651
  this.#io.stderr.write(`${lines2.join("\n")}
251520
251652
  `);
@@ -251591,15 +251723,12 @@ async function fetchOnboarding(ctx, target6) {
251591
251723
  if (ctx.io.abort?.aborted) throw new AnchaError("USAGE", "interrupted");
251592
251724
  throw new AnchaError("SERVER_UNREACHABLE", `cannot reach ${serverUrl3}`, { hint: "check your network, then run ancha status --on cloud", cause: e });
251593
251725
  }
251594
- if (res.status === 401 || res.status === 403) throw authError(serverUrl3, { status: res.status, keySent: true });
251595
251726
  const body8 = await res.json().catch(() => void 0);
251596
251727
  if (!res.ok) {
251597
- const error65 = typeof body8?.error === "object" && body8.error !== null ? body8.error : { message: body8?.error };
251598
- const message8 = typeof error65.message === "string" ? error65.message : `HTTP ${res.status}`;
251599
- const busy = res.status >= 500 || res.status === 429;
251600
- const code5 = res.status >= 500 ? "SERVER_UNREACHABLE" : res.status === 429 ? "USAGE" : isErrorCode(error65.code) ? error65.code : "INTERNAL";
251601
- const hint = typeof error65.hint === "string" ? error65.hint : busy ? "retry in a few seconds with ancha status --on cloud" : void 0;
251602
- throw new AnchaError(code5, `${serverUrl3}/_onboarding: ${message8}`, hint === void 0 ? {} : { hint });
251728
+ if (res.status === 401 || res.status === 403) throw serverError(res.status, body8, authError(serverUrl3, { status: res.status, keySent: true }));
251729
+ const error65 = serverError(res.status, body8, { message: `HTTP ${res.status}`, code: "INTERNAL", ...res.status >= 500 || res.status === 429 ? { hint: "retry in a few seconds with ancha status --on cloud" } : {} });
251730
+ error65.message = `${serverUrl3}/_onboarding: ${error65.message}`;
251731
+ throw error65;
251603
251732
  }
251604
251733
  if (!isOnboarding(body8)) throw new AnchaError("INTERNAL", `${serverUrl3} sent a malformed onboarding answer`);
251605
251734
  return withOwnNext(body8);
@@ -251665,13 +251794,12 @@ function retryHint(response6) {
251665
251794
  return `retry in ${seconds6 < 120 ? `${seconds6} seconds` : `${Math.ceil(seconds6 / 60)} minutes`}`;
251666
251795
  }
251667
251796
  async function refusal2(response6, server) {
251668
- if (response6.status === 401) return authError(server, { status: 401, keySent: true });
251669
251797
  const body8 = await response6.json().catch(() => void 0);
251670
- const error65 = typeof body8?.error === "object" && body8.error !== null ? body8.error : { message: typeof body8?.error === "string" ? body8.error : void 0 };
251671
- const code5 = error65.code !== void 0 && isErrorCode(error65.code) ? error65.code : response6.status === 409 ? "SESSION_CONFLICT" : response6.status === 422 ? "CONFIG_INVALID" : response6.status >= 500 ? "SERVER_UNREACHABLE" : "USAGE";
251672
- const hint = error65.hint ?? (response6.status === 429 ? retryHint(response6) : response6.status >= 500 ? "retry in a few seconds" : void 0);
251673
- const refused2 = new AnchaError(code5, error65.message ?? `${server} answered HTTP ${response6.status}`, { ...hint !== void 0 && { hint } });
251674
- return typeof error65.step === "string" ? Object.assign(refused2, { step: error65.step }) : refused2;
251798
+ const fallback = response6.status === 401 ? authError(server, { status: 401, keySent: true }) : void 0;
251799
+ return serverError(response6.status, body8, {
251800
+ message: fallback?.message ?? `${server} answered HTTP ${response6.status}`,
251801
+ ...fallback?.hint ? { hint: fallback.hint } : response6.status === 429 ? { hint: retryHint(response6) } : response6.status >= 502 ? { hint: "retry in a few seconds" } : {}
251802
+ });
251675
251803
  }
251676
251804
  async function call2(ws, method2, path9, options5 = {}) {
251677
251805
  for (let attempt2 = 0; ; attempt2++) {
@@ -251716,6 +251844,7 @@ var getArchive = (ws, id15) => call2(ws, "GET", path8(id15, "/archive"), { retry
251716
251844
  var getAttemptArtifact = (ws, id15, attemptId) => call2(ws, "GET", path8(id15, `/attempts/${encodeURIComponent(attemptId)}/artifact`), { retry: true, bytes: true });
251717
251845
  var cancelJob = (ws, id15) => call2(ws, "POST", path8(id15, "/cancel"), { json: {}, retry: true });
251718
251846
  var listJobs = (ws, query12) => call2(ws, "GET", `/_jobs?${new URLSearchParams(Object.entries(query12).filter(([, value6]) => value6 !== void 0).map(([key5, value6]) => [key5, String(value6)]))}`, { retry: true });
251847
+ var getSecrets = (ws) => call2(ws, "GET", "/_secrets", { retry: true });
251719
251848
  var getOnboarding = (ws) => call2(ws, "GET", "/_onboarding", { retry: true }).then(withOwnNext);
251720
251849
  var listCloudAgents = (ws) => call2(ws, "GET", "/_agents", { retry: true });
251721
251850
  var getCloudAgent = (ws, id15) => call2(ws, "GET", `/_agents/${encodeURIComponent(id15)}`, { retry: true });
@@ -251736,7 +251865,7 @@ async function cloudAgent(ctx, id15) {
251736
251865
  function atStep(step3, error65, next2) {
251737
251866
  if (!(error65 instanceof AnchaError)) return error65;
251738
251867
  const named5 = error65.step ?? step3;
251739
- return new AnchaError(error65.code, `${named5}: ${error65.message}`, { hint: error65.code === "SERVER_UNREACHABLE" || error65.hint === void 0 ? next2 : error65.hint, cause: error65 });
251868
+ return new AnchaError(error65.code, `${named5}: ${error65.message}`, { hint: error65.kind === "ours" ? error65.hint ?? "this failed on Ancha's side, not in your setup" : error65.code === "SERVER_UNREACHABLE" || error65.hint === void 0 ? next2 : error65.hint, kind: error65.kind, ...error65.reference && { reference: error65.reference }, cause: error65 });
251740
251869
  }
251741
251870
  function parseEvent(line2) {
251742
251871
  const event3 = JSON.parse(line2);
@@ -251933,7 +252062,7 @@ function finishedText(ws, detail3, includeNext = true) {
251933
252062
  const counts3 = job.counts;
251934
252063
  if (counts3 !== void 0) lines2.push(`Cases: ${counts3.cases} \xB7 attempts: ${counts3.requestedAttempts} requested, ${counts3.completedAttempts} completed, ${counts3.invalidAttempts} invalid${counts3.skippedAttempts ? `, ${counts3.skippedAttempts} skipped` : ""}${counts3.cancelledAttempts ? `, ${counts3.cancelledAttempts} cancelled` : ""}`);
251935
252064
  }
251936
- if (job.error !== null && job.error !== void 0) lines2.push(`${job.error.step ? `${job.error.step}: ` : ""}${job.error.message}`, ...job.error.hint ? [`hint: ${job.error.hint}`] : []);
252065
+ if (job.error !== null && job.error !== void 0) lines2.push(`${job.error.step ? `${job.error.step}: ` : ""}${job.error.message}`, errorAction(toErrorJson(serverError(400, { error: job.error }, { message: "The job failed." }))));
251937
252066
  lines2.push(`Result: ${resultUrl(ws, detail3)}`);
251938
252067
  if (includeNext && job.kind === "run") {
251939
252068
  const ungraded = summary?.verdict === "ungraded";
@@ -252092,7 +252221,6 @@ async function post5(server, key5, argv, files2) {
252092
252221
  } catch (error65) {
252093
252222
  throw new AnchaError("SERVER_UNREACHABLE", `${server} did not answer`, { hint: "check the network, then retry", cause: error65 });
252094
252223
  }
252095
- if (response6.status === 401) throw authError(server, { status: 401, keySent: true });
252096
252224
  if (!response6.ok || response6.body === null) throw await refusal3(response6, server);
252097
252225
  return response6.body;
252098
252226
  }
@@ -252111,7 +252239,7 @@ async function ask(server, key5, argv) {
252111
252239
  }
252112
252240
  });
252113
252241
  const failed2 = lines2.find((line2) => typeof line2 === "object" && line2 !== null && "error" in line2);
252114
- if (failed2?.error) throw new AnchaError(failed2.error.code === "SESSION_CONFLICT" || failed2.error.code === "CONFIG_INVALID" ? failed2.error.code : "USAGE", `the workspace answered: ${failed2.error.message ?? "an error"}`, { hint: failed2.error.hint ?? `ancha ${argv.slice(0, 2).join(" ")}` });
252242
+ if (failed2?.error) throw new AnchaError(failed2.error.code === "SESSION_CONFLICT" || failed2.error.code === "CONFIG_INVALID" ? failed2.error.code : "USAGE", `the workspace answered: ${failed2.error.message ?? "an error"}`, { hint: failed2.error.hint ?? `ancha ${argv.slice(0, 2).join(" ")}`, ...owner5(failed2.error) });
252115
252243
  return lines2;
252116
252244
  }
252117
252245
  async function refuseWhileConnecting(server, key5, agentId2, name5) {
@@ -252133,14 +252261,18 @@ function optionValue(args, name5) {
252133
252261
  }
252134
252262
  return void 0;
252135
252263
  }
252264
+ function owner5(error65) {
252265
+ return { ...isErrorKind(error65?.kind) && { kind: error65.kind }, ...typeof error65?.reference === "string" && { reference: error65.reference } };
252266
+ }
252136
252267
  async function refusal3(response6, server) {
252137
252268
  const body8 = await response6.json().catch(() => void 0);
252269
+ if (response6.status === 401) return serverError(response6.status, body8, authError(server, { status: 401, keySent: true }));
252138
252270
  const error65 = typeof body8?.error === "object" ? body8.error : { message: typeof body8?.error === "string" ? body8.error : void 0 };
252139
- if (response6.status === 429) return new AnchaError("USAGE", error65.message ?? "too many commands for this key", { hint: error65.hint ?? retryHint(response6) });
252271
+ if (response6.status === 429) return new AnchaError("USAGE", error65.message ?? "too many commands for this key", { hint: error65.hint ?? retryHint(response6), kind: "retry" });
252140
252272
  if (response6.status >= 500) {
252141
- return new AnchaError("SERVER_UNREACHABLE", `${server} could not run the command: ${error65.message ?? `HTTP ${response6.status}`}`, { hint: "retry in a few seconds" });
252273
+ return new AnchaError("SERVER_UNREACHABLE", `${server} could not run the command: ${error65.message ?? `HTTP ${response6.status}`}`, { hint: "retry in a few seconds", ...owner5(error65) });
252142
252274
  }
252143
- return new AnchaError("USAGE", error65.message ?? `the workspace refused the command (HTTP ${response6.status})`, { hint: error65.hint ?? "run it on this computer with --local" });
252275
+ return new AnchaError("USAGE", error65.message ?? `the workspace refused the command (HTTP ${response6.status})`, { hint: error65.hint ?? "run it on this computer with --local", ...owner5(error65) });
252144
252276
  }
252145
252277
  async function stream(ctx, body8, server) {
252146
252278
  const decoder = new TextDecoder();
@@ -252217,7 +252349,7 @@ async function uploadProject(server, key5, name5, dir2) {
252217
252349
  const error65 = typeof result.error === "object" && result.error !== null ? result.error : void 0;
252218
252350
  if (!response6.ok && typeof error65?.message === "string") {
252219
252351
  const hint = typeof error65.hint === "string" ? error65.hint : response6.status === 429 ? retryHint(response6) : void 0;
252220
- throw new AnchaError(error65.code !== void 0 && isErrorCode(error65.code) ? error65.code : response6.status >= 500 ? "SERVER_UNREACHABLE" : "USAGE", error65.message, { ...hint !== void 0 && { hint } });
252352
+ throw new AnchaError(error65.code !== void 0 && isErrorCode(error65.code) ? error65.code : response6.status >= 500 ? "SERVER_UNREACHABLE" : "USAGE", error65.message, { ...hint !== void 0 && { hint }, ...owner5(error65) });
252221
252353
  }
252222
252354
  const message8 = typeof result.error === "string" ? result.error : `HTTP ${response6.status}`;
252223
252355
  if (response6.status >= 500) throw new AnchaError("SERVER_UNREACHABLE", `the workspace refused the upload: ${message8}`, { hint: "retry in a few seconds" });
@@ -253096,7 +253228,7 @@ function sameSeed(left, right) {
253096
253228
 
253097
253229
  // backend/src/playgrounds/managed-seed.ts
253098
253230
  async function inspectManagedSeed(service, rawOwner) {
253099
- const owner5 = seedOwner(rawOwner);
253231
+ const owner6 = seedOwner(rawOwner);
253100
253232
  const [agents, worlds2, tests, runs] = await Promise.all([
253101
253233
  service.registry.list(),
253102
253234
  service.worlds({ includeArchived: true }),
@@ -253105,11 +253237,11 @@ async function inspectManagedSeed(service, rawOwner) {
253105
253237
  ]);
253106
253238
  if ([agents, worlds2, tests, runs].some((result) => result.errors.length)) throw new AnchaError("CONFIG_INVALID", "unreadable workspace objects prevent a safe seed reset");
253107
253239
  return {
253108
- owner: owner5,
253109
- agents: agents.agents.filter((item2) => item2.managedSeed?.owner === owner5),
253110
- worlds: worlds2.worlds.filter((item2) => item2.managedSeed?.owner === owner5),
253111
- tests: tests.tests.filter((item2) => item2.managedSeed?.owner === owner5),
253112
- runs: runs.runs.filter((item2) => item2.managedSeed?.owner === owner5)
253240
+ owner: owner6,
253241
+ agents: agents.agents.filter((item2) => item2.managedSeed?.owner === owner6),
253242
+ worlds: worlds2.worlds.filter((item2) => item2.managedSeed?.owner === owner6),
253243
+ tests: tests.tests.filter((item2) => item2.managedSeed?.owner === owner6),
253244
+ runs: runs.runs.filter((item2) => item2.managedSeed?.owner === owner6)
253113
253245
  };
253114
253246
  }
253115
253247
  async function resetManagedSeed(service, rawOwner) {
@@ -254158,9 +254290,9 @@ var PlaygroundStore = class {
254158
254290
  async processOwner() {
254159
254291
  return { pid: process.pid, birth: birth(process.pid) };
254160
254292
  }
254161
- processOwnerAlive(owner5) {
254162
- if (!owner5 || typeof owner5 !== "object" || !Number.isSafeInteger(owner5.pid) || typeof owner5.birth !== "string" || !owner5.birth) return null;
254163
- return alive(owner5);
254293
+ processOwnerAlive(owner6) {
254294
+ if (!owner6 || typeof owner6 !== "object" || !Number.isSafeInteger(owner6.pid) || typeof owner6.birth !== "string" || !owner6.birth) return null;
254295
+ return alive(owner6);
254164
254296
  }
254165
254297
  async stagedRuns() {
254166
254298
  await preflightFiles(this.workspace, [{ relativePath: `${BASE4}/runs/probe.json`, content: "" }]);
@@ -255289,7 +255421,7 @@ async function startDetached(request2) {
255289
255421
  state: "failed",
255290
255422
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
255291
255423
  exitCode: 3,
255292
- error: { code: "INTERNAL", message: "detached worker startup failed" }
255424
+ error: { code: "INTERNAL", kind: "ours", message: "detached worker startup failed" }
255293
255425
  });
255294
255426
  throw new AnchaError("INTERNAL", "detached worker startup failed", { cause: error65 });
255295
255427
  }
@@ -255355,13 +255487,11 @@ async function uploadRun(ctx, workspace4, run7) {
255355
255487
  } catch (error65) {
255356
255488
  throw new AnchaError("SERVER_UNREACHABLE", `${workspace4} did not answer the upload`, { hint: `check the network, then ancha runs upload ${run7.runId}`, cause: error65 });
255357
255489
  }
255358
- if (response6.status === 401) throw authError(workspace4, { status: 401, keySent: key5 !== void 0 });
255359
255490
  if (!response6.ok) {
255360
255491
  const body8 = await response6.json().catch(() => void 0);
255361
- const error65 = typeof body8?.error === "object" ? body8.error : { message: typeof body8?.error === "string" ? body8.error : void 0 };
255492
+ if (response6.status === 401) throw serverError(response6.status, body8, authError(workspace4, { status: 401, keySent: key5 !== void 0 }));
255362
255493
  if (response6.status === 404) throw new AnchaError("USAGE", `${workspace4} doesn't take run uploads`, { hint: "upload to your hosted workspace: ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY" });
255363
- const code5 = response6.status >= 500 ? "SERVER_UNREACHABLE" : error65.code !== void 0 && isErrorCode(error65.code) ? error65.code : "USAGE";
255364
- throw new AnchaError(code5, error65.message ?? `the upload was refused (HTTP ${response6.status})`, { hint: error65.hint ?? `ancha runs upload ${run7.runId}` });
255494
+ throw serverError(response6.status, body8, { message: `the upload was refused (HTTP ${response6.status})`, hint: `ancha runs upload ${run7.runId}` });
255365
255495
  }
255366
255496
  const answer = await response6.json().catch(() => void 0);
255367
255497
  return { ...runNumberOf(answer?.runNumber) && { runNumber: runNumberOf(answer?.runNumber) }, url: httpUrl4(answer?.url) ?? `${new URL(workspace4).origin}/runs/${encodeURIComponent(run7.runId)}`, bytes: archive.length, files: manifest2.files.length, ...answer?.replaced === true && { replaced: true } };
@@ -256410,7 +256540,7 @@ async function replayRun(ctx, input5, runId2, detach) {
256410
256540
  }
256411
256541
  const summary = await loadRunSummary(ctx.io.cwd, runId2, input5.out);
256412
256542
  ctx.exitCode = state3.exitCode ?? 3;
256413
- if (state3.error) ctx.out.error(new AnchaError(state3.error.code, state3.error.message));
256543
+ if (state3.error) ctx.out.error(new AnchaError(state3.error.code, state3.error.message, state3.error));
256414
256544
  if (ctx.out.json) ctx.out.event({ event: "run_finished", summary, next: nextAfterRun(summary, { out: nonDefaultOut(ctx.io.cwd, input5.out) }), replayed: true, ...state3.upload !== void 0 && { upload: state3.upload } });
256415
256545
  else ctx.out.result(summary, () => `replayed run ${runId2} (same --idempotency-key)
256416
256546
 
@@ -256452,7 +256582,7 @@ hint: ${json40.hint}` : ""}`);
256452
256582
  }
256453
256583
  function keptUpload(upload6, runId2) {
256454
256584
  if (!("error" in upload6)) return upload6;
256455
- return { error: { code: upload6.error.code, message: `the run finished, but its upload failed (${upload6.error.code})`, hint: `ancha runs upload ${runId2} tries again and says why` }, ...upload6.required && { required: true } };
256585
+ return { error: { kind: upload6.error.kind, ...upload6.error.reference && { reference: upload6.error.reference }, code: upload6.error.code, message: `the run finished, but its upload failed (${upload6.error.code})`, hint: `ancha runs upload ${runId2} tries again and says why` }, ...upload6.required && { required: true } };
256456
256586
  }
256457
256587
  async function executePreparedRun(ctx, input5, initial, ready3) {
256458
256588
  const writer = stateWriter(input5.outDir, initial);
@@ -256512,7 +256642,7 @@ async function executePreparedRun(ctx, input5, initial, ready3) {
256512
256642
  await writer.finish({
256513
256643
  state: interrupted2 ? "interrupted" : "failed",
256514
256644
  exitCode: exitCodeFor(code5),
256515
- error: { code: code5, message: interrupted2 ? "run interrupted" : `run failed (${code5}); partial artifacts may be available` }
256645
+ error: { kind: toErrorJson(error65).kind, code: code5, message: interrupted2 ? "run interrupted" : `run failed (${code5}); partial artifacts may be available` }
256516
256646
  });
256517
256647
  throw error65;
256518
256648
  }
@@ -256584,9 +256714,9 @@ async function execute4(ctx, service, start2) {
256584
256714
  function registerPlayground(program2, ctx) {
256585
256715
  const command = program2.command("playground").description("choose tools and test agent tasks in fresh independent playgrounds");
256586
256716
  const seed44 = command.command("seed").description("inspect or reset objects with explicit creation provenance");
256587
- for (const action of ["inspect", "reset"]) seed44.command(action).argument("<owner>").action(async (owner5) => {
256717
+ for (const action of ["inspect", "reset"]) seed44.command(action).argument("<owner>").action(async (owner6) => {
256588
256718
  const base6 = ctx.io.env.ANCHA_CONSOLE_URL;
256589
- const result = base6 ? await (await consoleApi(base6)).call(`/api/managed-seeds/${encodeURIComponent(owner5)}${action === "reset" ? "/reset" : ""}`, action === "reset" ? {} : void 0) : await withService(ctx, (service) => action === "reset" ? resetManagedSeed(service, owner5) : inspectManagedSeed(service, owner5));
256719
+ const result = base6 ? await (await consoleApi(base6)).call(`/api/managed-seeds/${encodeURIComponent(owner6)}${action === "reset" ? "/reset" : ""}`, action === "reset" ? {} : void 0) : await withService(ctx, (service) => action === "reset" ? resetManagedSeed(service, owner6) : inspectManagedSeed(service, owner6));
256590
256720
  const output2 = { workspace: base6 ?? `local:${ctx.io.cwd}`, ...result };
256591
256721
  ctx.out.result(output2, () => JSON.stringify(output2, null, 2));
256592
256722
  });
@@ -256884,12 +257014,28 @@ async function taskCheck(ctx, agent) {
256884
257014
  hint: "or run ancha init, which adds it"
256885
257015
  };
256886
257016
  }
257017
+ async function uploadSecrets(ws, names8) {
257018
+ const wanted = [...new Set(names8)];
257019
+ if (!wanted.length) return { name: "secrets", status: "pass", message: "the agent passes no workspace secrets" };
257020
+ const saved = await getSecrets(ws), missing10 = wanted.filter((name5) => !saved.names.includes(name5));
257021
+ if (missing10.length) throw new AnchaError("CONFIG_INVALID", `Workspace secrets are missing: ${missing10.join(", ")}. The project has not been bundled.`, { hint: missing10.map((name5) => `ancha secrets set ${name5}`).join("\n") });
257022
+ let warning = false;
257023
+ const details = wanted.flatMap((name5) => {
257024
+ const secret = saved.secrets?.find((item2) => item2.name === name5), check4 = secret?.check;
257025
+ const status6 = check4?.status === "accepted" ? `accepted by ${check4.provider}` : check4?.status === "refused" ? `refused by ${check4.provider}` : check4?.status === "unchecked" ? `unchecked${check4.reason ? ` (${check4.reason})` : ""}` : "saved";
257026
+ const notes7 = (secret?.issues ?? []).filter((issue9) => issue9.level !== "info" && issue9.message);
257027
+ if (notes7.length) warning = true;
257028
+ return [`${name5}${secret?.preview ? ` \xB7 ${secret.preview}` : ""} \xB7 ${status6}`, ...notes7.map((issue9) => ` ${issue9.message}${issue9.fix ? ` ${issue9.fix}` : ""}`)];
257029
+ });
257030
+ return { name: "secrets", status: warning ? "warning" : "pass", message: `${wanted.length} workspace secret${wanted.length === 1 ? "" : "s"} saved`, details };
257031
+ }
256887
257032
  async function uploadAgent(ctx, opts, command = "ancha agent upload") {
256888
257033
  if (opts.agent === false) throw new AnchaError("USAGE", `${command} checks the agent in a cloud machine`, { hint: "leave out --no-agent" });
256889
257034
  const config12 = await ctx.loadConfig();
256890
257035
  const refusal4 = cloudAgentRefusal(config12, typeof opts.agent === "string" ? opts.agent : void 0);
256891
257036
  if (refusal4) throw refusal4;
256892
257037
  const ws = await cloudWorkspace(ctx, { code: "USAGE", message: `${command === "ancha agent upload" ? "agent upload" : "--on cloud"} needs a workspace`, hint: "run ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY" });
257038
+ const secrets2 = await uploadSecrets(ws, [...config12.agent?.passEnv ?? [], ...config12.agent?.execution?.mode === "container" ? config12.agent.execution.env : []]);
256893
257039
  const configured = config12.agent?.mode === "endpoint" ? void 0 : config12.agent;
256894
257040
  const task2 = await taskCheck(ctx, typeof opts.agent === "string" ? { command: opts.agent, ...configured?.env && { env: configured.env } } : configured);
256895
257041
  if (task2?.status === "warning") ctx.out.info(`${task2.message}: ${task2.fix} (${task2.hint})`);
@@ -256897,6 +257043,7 @@ async function uploadAgent(ctx, opts, command = "ancha agent upload") {
256897
257043
  const checks2 = [
256898
257044
  { name: "workspace", status: "pass", message: `running in the workspace ${ws.server}` },
256899
257045
  { name: "bundle", status: "pass", message: `${bundle.files} files, ${(bundle.bytes / 1024 / 1024).toFixed(1)} MiB; project ${bundle.projectHash.slice(0, 12)}` },
257046
+ secrets2,
256900
257047
  ...task2 ? [task2] : []
256901
257048
  ];
256902
257049
  const reason2 = detail3.connection?.probe?.reason;
@@ -256905,7 +257052,7 @@ async function uploadAgent(ctx, opts, command = "ancha agent upload") {
256905
257052
  checks2.push(...connectionChecks);
256906
257053
  const onboarding = state3 === "failed" ? void 0 : await getOnboarding(ws).then((value6) => nextFromHere(ctx, value6)).then((next3) => human(next3.at(-1)), () => void 0);
256907
257054
  const next2 = state3 === "failed" ? ["ancha agent upload"] : [onboarding === void 0 || /doctor --on cloud|agent upload/.test(onboarding) ? "ancha run" : onboarding];
256908
- return { report: { ok: state3 !== "failed", checks: checks2, next: next2, cloud: { jobId: detail3.job.id, url: url4, state: state3, ...agentAction2 !== void 0 && { agentAction: agentAction2 }, ...agent !== void 0 && { agent }, connection: evidence3 } }, exitCode };
257055
+ return { report: { ok: state3 !== "failed", ...state3 === "failed" && detail3.job.error && { error: toErrorJson(serverError(400, { error: detail3.job.error }, { message: "The upload failed." })) }, checks: checks2, next: next2, cloud: { jobId: detail3.job.id, url: url4, state: state3, ...agentAction2 !== void 0 && { agentAction: agentAction2 }, ...agent !== void 0 && { agent }, connection: evidence3 } }, exitCode };
256909
257056
  }
256910
257057
  function connectionReport(detail3, logTail3, readsAnswer = false) {
256911
257058
  const checks2 = [];
@@ -256944,7 +257091,7 @@ function connectionReport(detail3, logTail3, readsAnswer = false) {
256944
257091
  } else {
256945
257092
  exitCode = detail3.job.exitCode !== null && detail3.job.exitCode !== 0 ? detail3.job.exitCode : 3;
256946
257093
  const started = evidence3?.install.passed && evidence3.probe !== null && evidence3.probe.startedAt !== null && evidence3.probe.durationMs !== void 0 && evidence3.probe.kind !== "http";
256947
- if (started) {
257094
+ if (started && detail3.job.error?.kind !== "ours") {
256948
257095
  const ran = evidence3.probe;
256949
257096
  const parsedTextTask = ran.reason?.code === "crashed" && ran.reason.message.includes("connection check's plain-text task");
256950
257097
  fix = ran.fix === void 0 ? parsedTextTask ? ran.reason?.fix : void 0 : fixLine(ran.fix);
@@ -256966,6 +257113,8 @@ function connectionReport(detail3, logTail3, readsAnswer = false) {
256966
257113
  checks2.push({
256967
257114
  name: "agent",
256968
257115
  status: "fail",
257116
+ ...error65?.kind && { kind: error65.kind },
257117
+ ...error65?.reference && { reference: error65.reference },
256969
257118
  message: `the upload stopped at ${step3}: ${error65?.message ?? `the job ${detail3.job.state}`}`,
256970
257119
  hint: human(error65?.hint ?? `${logTail3.length > 0 ? "the end of its log is above; " : ""}ancha runs show ${detail3.job.id} lists each step`),
256971
257120
  ...logTail3.length > 0 && { logTail: logTail3 }
@@ -256985,7 +257134,10 @@ function connectionReport(detail3, logTail3, readsAnswer = false) {
256985
257134
  hint: "name them with ancha init --tools <tools> or the tests' twins"
256986
257135
  });
256987
257136
  }
256988
- for (const check4 of checks2) if (check4.logTail) check4.logTail = connectionLogTail(check4.logTail);
257137
+ for (const check4 of checks2) {
257138
+ if (check4.logTail) check4.logTail = connectionLogTail(check4.logTail);
257139
+ if (check4.status === "fail") Object.assign(check4, { kind: detail3.job.error?.kind ?? reason2?.kind ?? "fix", ...detail3.job.error?.reference && { reference: detail3.job.error.reference } });
257140
+ }
256989
257141
  return { checks: checks2, state: state3, exitCode, evidence: evidence3 };
256990
257142
  }
256991
257143
  var doctorOnCloud = (ctx, opts) => uploadAgent(ctx, opts, "ancha doctor --on cloud");
@@ -257014,12 +257166,12 @@ function renderUpload(report10) {
257014
257166
  for (const line2 of check4.details ?? []) lines2.push(` ${line2}`);
257015
257167
  for (const line2 of check4.logTail ?? []) lines2.push(` ${line2}`);
257016
257168
  if (check4.fix !== void 0 && check4.status === "warning") lines2.push(` ${check4.fix}${check4.hint ? ` (${check4.hint})` : ""}`);
257017
- else if (check4.hint && check4.fix === void 0) lines2.push(` ${check4.hint}`);
257169
+ else if (check4.hint && check4.fix === void 0) lines2.push(` ${check4.kind ? `${check4.kind}: ` : ""}${check4.hint}${check4.reference ? ` (reference ${check4.reference})` : ""}`);
257018
257170
  }
257019
257171
  const failed2 = report10.checks.find((check4) => check4.status === "fail");
257020
257172
  if (report10.ok && report10.cloud) lines2.push(`Agent uploaded: ${report10.cloud.url}`);
257021
257173
  else if (report10.cloud) lines2.push(`Upload: ${report10.cloud.url}`);
257022
- if (failed2?.fix !== void 0) lines2.push(`fix: ${failed2.fix}`, `then: ${report10.next[0]}`);
257174
+ if (failed2?.fix !== void 0) lines2.push(`${failed2.kind ?? "fix"}: ${failed2.fix}`, `then: ${report10.next[0]}`);
257023
257175
  else if (report10.next.length > 0) lines2.push(`next: ${report10.next[0]}`);
257024
257176
  return lines2.join("\n");
257025
257177
  }
@@ -258170,7 +258322,7 @@ ${renderReplay(value6)}`);
258170
258322
  await writer.finish({
258171
258323
  state: interrupted2 ? "interrupted" : "failed",
258172
258324
  exitCode: exitCodeFor(code5),
258173
- error: { code: code5, message: interrupted2 ? "run interrupted" : `run failed (${code5}); partial artifacts may be available` }
258325
+ error: { kind: toErrorJson(error65).kind, code: code5, message: interrupted2 ? "run interrupted" : `run failed (${code5}); partial artifacts may be available` }
258174
258326
  });
258175
258327
  throw error65;
258176
258328
  }
@@ -258223,7 +258375,7 @@ ${state3.error.message}` : ""}`);
258223
258375
  const state3 = await readRunState(resolve42(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), id15);
258224
258376
  if (terminal(state3)) {
258225
258377
  if (state3.state === "finished") {
258226
- if (state3.error) ctx.out.error(new AnchaError(state3.error.code, state3.error.message));
258378
+ if (state3.error) ctx.out.error(new AnchaError(state3.error.code, state3.error.message, state3.error));
258227
258379
  emitFinished(ctx, await loadRunSummary(ctx.io.cwd, id15, opts.out), opts.out, state3.upload);
258228
258380
  if (!ctx.out.json && state3.upload !== void 0 && "error" in state3.upload) ctx.out.info(`${state3.upload.required ? "error" : "warning"}: ${state3.upload.error.message}${state3.upload.error.hint !== void 0 ? `
258229
258381
  hint: ${state3.upload.error.hint}` : ""}`);
@@ -258270,7 +258422,7 @@ hint: ${state3.upload.error.hint}` : ""}`);
258270
258422
  printed = complete.length;
258271
258423
  if (!opts.follow || terminal(state3)) {
258272
258424
  if (printed === 0) ctx.out.result({ runId: id15, events: [], message: "No events were recorded for this run." }, () => "No events were recorded for this run.");
258273
- if (terminal(state3) && state3.exitCode === void 0 && state3.error) ctx.exitCode = ctx.out.error(new AnchaError(state3.error.code, state3.error.message));
258425
+ if (terminal(state3) && state3.exitCode === void 0 && state3.error) ctx.exitCode = ctx.out.error(new AnchaError(state3.error.code, state3.error.message, state3.error));
258274
258426
  if (opts.follow) ctx.exitCode = state3.exitCode ?? 3;
258275
258427
  return;
258276
258428
  }
@@ -260161,9 +260313,9 @@ function normalizeDraft(draft2, world5) {
260161
260313
  const fact2 = (value6) => {
260162
260314
  if (typeof value6 !== "string") return value6;
260163
260315
  const dot = value6.lastIndexOf(".");
260164
- const owner5 = dot < 0 ? void 0 : personOf(value6.slice(0, dot));
260316
+ const owner6 = dot < 0 ? void 0 : personOf(value6.slice(0, dot));
260165
260317
  const id16 = canon(dot < 0 ? value6 : value6.slice(dot + 1));
260166
- const owners = owner5 ? [owner5] : people4;
260318
+ const owners = owner6 ? [owner6] : people4;
260167
260319
  const found = owners.flatMap((candidate) => (candidate.knows ?? []).filter((item2) => canon(item2.id) === id16).map((item2) => `${candidate.ref}.${item2.id}`));
260168
260320
  return found.length === 1 ? found[0] : value6;
260169
260321
  };
@@ -261547,10 +261699,10 @@ async function probeAgentConnection(agent, signal, progress2, inheritedEnv = pro
261547
261699
  if (failures.length) throw new AnchaError("INTERNAL", "The connection check finished but its temporary playground could not be fully removed. Check the local container runtime before retrying.");
261548
261700
  }
261549
261701
  }
261550
- async function cleanupAbandonedConnection(owner5) {
261551
- if (!Number.isSafeInteger(owner5) || owner5 <= 0) return;
261702
+ async function cleanupAbandonedConnection(owner6) {
261703
+ if (!Number.isSafeInteger(owner6) || owner6 <= 0) return;
261552
261704
  try {
261553
- process.kill(owner5, 0);
261705
+ process.kill(owner6, 0);
261554
261706
  return;
261555
261707
  } catch {
261556
261708
  }
@@ -261558,7 +261710,7 @@ async function cleanupAbandonedConnection(owner5) {
261558
261710
  if (!runtime2.available || !runtime2.context) throw new Error("Runtime unavailable for cleanup");
261559
261711
  const exec9 = promisify9(execFile10), env2 = Object.fromEntries(["PATH", "HOME", "TMPDIR"].flatMap((name5) => process.env[name5] ? [[name5, process.env[name5]]] : []));
261560
261712
  const run7 = async (args) => (await exec9("docker", ["--context", runtime2.context, ...args], { env: env2, timeout: 15e3, maxBuffer: 1e5 })).stdout.trim();
261561
- const filter4 = `label=dev.ancha.connection.owner=${owner5}`;
261713
+ const filter4 = `label=dev.ancha.connection.owner=${owner6}`;
261562
261714
  const containers = (await run7(["ps", "-a", "--filter", filter4, "--format", "{{.Names}}"])).split("\n").filter((name5) => /^ancha-connect-[a-f0-9-]+(?:-copy|-check)?$/.test(name5));
261563
261715
  for (const name5 of containers) await run7(["rm", "-f", name5]);
261564
261716
  const volumes = (await run7(["volume", "ls", "--filter", filter4, "--format", "{{.Name}}"])).split("\n").filter((name5) => /^ancha-connect-[a-f0-9-]+-source$/.test(name5));
@@ -262106,7 +262258,7 @@ var ConsoleJobs = class {
262106
262258
  await this.writeEvents(initial.runId, job.events).catch(() => {
262107
262259
  });
262108
262260
  const code5 = toErrorJson(error65).code;
262109
- await writer.finish({ state: controller.signal.aborted ? "interrupted" : "failed", exitCode: controller.signal.aborted ? 2 : exitCodeFor(code5), error: { code: code5, message: controller.signal.aborted ? "Run interrupted" : `Run failed (${code5}); partial artifacts may remain on disk` } }).catch(() => {
262261
+ await writer.finish({ state: controller.signal.aborted ? "interrupted" : "failed", exitCode: controller.signal.aborted ? 2 : exitCodeFor(code5), error: { kind: toErrorJson(error65).kind, code: code5, message: controller.signal.aborted ? "Run interrupted" : `Run failed (${code5}); partial artifacts may remain on disk` } }).catch(() => {
262110
262262
  });
262111
262263
  } finally {
262112
262264
  if (verification && registered) {
@@ -263718,11 +263870,11 @@ function registerBaseline(program2, ctx) {
263718
263870
 
263719
263871
  // packages/cli/src/commands/connection.ts
263720
263872
  async function connectThroughConsole(base6, agentId2) {
263721
- const owner5 = await consoleApi(base6), path9 = `/api/agents/${encodeURIComponent(agentId2)}/connect`;
263722
- let operation = await owner5.call(path9, {});
263873
+ const owner6 = await consoleApi(base6), path9 = `/api/agents/${encodeURIComponent(agentId2)}/connect`;
263874
+ let operation = await owner6.call(path9, {});
263723
263875
  while (operation?.state === "queued" || operation?.state === "connecting") {
263724
263876
  await new Promise((done) => setTimeout(done, 2e3));
263725
- operation = await owner5.call(path9);
263877
+ operation = await owner6.call(path9);
263726
263878
  }
263727
263879
  return operation;
263728
263880
  }
@@ -264432,8 +264584,8 @@ function readTraceUnits(texts4, { fileToIr: fileToIr2, sourceOf: sourceOf2 }) {
264432
264584
  }
264433
264585
  }
264434
264586
  for (const { file: file3, traces, f: f2 } of langsmithFeedback) {
264435
- const owner5 = f2?.run_id === void 0 ? void 0 : runTrace.get(f2.run_id);
264436
- for (const id15 of owner5 ? [owner5] : traces) {
264587
+ const owner6 = f2?.run_id === void 0 ? void 0 : runTrace.get(f2.run_id);
264588
+ for (const id15 of owner6 ? [owner6] : traces) {
264437
264589
  const d = draft2("langsmith", id15, file3);
264438
264590
  put4(d, "feedback", f2, f2?.id);
264439
264591
  d.alone = true;
@@ -264676,7 +264828,8 @@ var WorkspaceError = class extends AnchaError {
264676
264828
  };
264677
264829
  function workspaceError(status6, body8, path9) {
264678
264830
  if (status6 === 404 && body8.error === void 0) return new WorkspaceError(404, "this workspace does not take traces", "ancha import --offline <trace file> makes the test on this computer; nothing is uploaded", true);
264679
- return new WorkspaceError(status6, String(body8.error ?? `${path9}: HTTP ${status6}`));
264831
+ const error65 = serverError(status6, body8, { message: `${path9}: HTTP ${status6}`, code: "USAGE" });
264832
+ return Object.assign(new WorkspaceError(status6, error65.message, error65.hint), { code: error65.code, kind: error65.kind, ...error65.reference && { reference: error65.reference } });
264680
264833
  }
264681
264834
  function notInWorkspace(error65) {
264682
264835
  return error65 instanceof WorkspaceError && error65.status === 404 && !error65.noTraces;
@@ -264687,9 +264840,11 @@ async function workspaceApi(ctx, hint = "run ancha login, or set ANCHA_SERVER_UR
264687
264840
  if (key5 === void 0) throw authError(workspace4, { keySent: false });
264688
264841
  const origin = new URL(workspace4).origin;
264689
264842
  return async (path9, init = {}) => {
264690
- const res = await fetch(`${origin}${path9}`, { ...init, headers: { authorization: `Bearer ${key5}`, "x-ancha-trace-import": "1", ...init.headers } });
264843
+ const res = await fetch(`${origin}${path9}`, { ...init, headers: { authorization: `Bearer ${key5}`, "x-ancha-trace-import": "1", ...init.headers } }).catch((cause) => {
264844
+ throw new AnchaError("SERVER_UNREACHABLE", "The workspace did not answer.", { cause });
264845
+ });
264691
264846
  const body8 = await res.json().catch(() => ({}));
264692
- if (res.status === 401) throw authError(workspace4, { keySent: true });
264847
+ if (res.status === 401) throw serverError(res.status, body8, authError(workspace4, { keySent: true }));
264693
264848
  if (!res.ok) throw workspaceError(res.status, body8, path9);
264694
264849
  return body8;
264695
264850
  };
@@ -265793,7 +265948,7 @@ async function workspaceAgents(ctx) {
265793
265948
  if (!(error65 instanceof AnchaError)) throw error65;
265794
265949
  unread2 = error65;
265795
265950
  }
265796
- ctx.out.result({ cloud, agents: saved, ...unread2 !== void 0 && { agentsError: { code: unread2.code, message: unread2.message } } }, () => [
265951
+ ctx.out.result({ cloud, agents: saved, ...unread2 !== void 0 && { agentsError: { code: unread2.code, kind: unread2.kind, message: unread2.message, ...unread2.reference && { reference: unread2.reference } } } }, () => [
265797
265952
  ...cloud.map((agent) => `${agent.id} ${agent.name} ${agent.state} cloud`),
265798
265953
  ...(saved ?? []).map((agent) => `${agent.id} ${agent.name} ${agent.verification?.status ?? "unverified"} ${executionLabel(agent.execution)}`),
265799
265954
  ...unread2 !== void 0 ? [`The agents saved in the workspace were not listed: ${unread2.message}`] : []
@@ -284370,35 +284525,35 @@ function attach(raws, lines2, links4, notes7) {
284370
284525
  const owners = new Map(raws.filter((raw3) => raw3.id !== void 0 && TRANSACTION_TYPES2.has(raw3.type)).map((raw3) => [raw3.id, raw3]));
284371
284526
  const groups = /* @__PURE__ */ new Map();
284372
284527
  const origins = /* @__PURE__ */ new Map();
284373
- const origin = (owner5, id15) => {
284528
+ const origin = (owner6, id15) => {
284374
284529
  const source = idOf3(id15);
284375
284530
  if (source === void 0 || !owners.has(source)) return;
284376
- const set2 = origins.get(owner5) ?? /* @__PURE__ */ new Set();
284531
+ const set2 = origins.get(owner6) ?? /* @__PURE__ */ new Set();
284377
284532
  set2.add(source);
284378
- origins.set(owner5, set2);
284533
+ origins.set(owner6, set2);
284379
284534
  };
284380
284535
  let orphans = 0, posted = 0, unlinked2 = 0;
284381
284536
  for (const line2 of lines2) {
284382
- const f2 = line2.fields, owner5 = owners.get(idOf3(f2.transaction) ?? 0);
284383
- if (!owner5) {
284537
+ const f2 = line2.fields, owner6 = owners.get(idOf3(f2.transaction) ?? 0);
284538
+ if (!owner6) {
284384
284539
  orphans++;
284385
284540
  continue;
284386
284541
  }
284387
- origin(owner5, f2.createdfrom);
284542
+ origin(owner6, f2.createdfrom);
284388
284543
  if (bool10(f2.mainline) === true) {
284389
- for (const key5 of ["subsidiary", "department", "class", "location", "entity"]) if (!present2(owner5.fields[key5]) && present2(f2[key5])) owner5.fields[key5] = f2[key5];
284544
+ for (const key5 of ["subsidiary", "department", "class", "location", "entity"]) if (!present2(owner6.fields[key5]) && present2(f2[key5])) owner6.fields[key5] = f2[key5];
284390
284545
  continue;
284391
284546
  }
284392
284547
  if (bool10(f2.taxline) === true || bool10(f2.iscogs) === true) {
284393
284548
  posted++;
284394
284549
  continue;
284395
284550
  }
284396
- const group5 = groups.get(owner5);
284551
+ const group5 = groups.get(owner6);
284397
284552
  if (group5) group5.push(f2);
284398
- else groups.set(owner5, [f2]);
284553
+ else groups.set(owner6, [f2]);
284399
284554
  }
284400
- for (const [owner5, rows35] of groups) {
284401
- const rate = positive4(owner5.fields.exchangeRate) ?? 1;
284555
+ for (const [owner6, rows35] of groups) {
284556
+ const rate = positive4(owner6.fields.exchangeRate) ?? 1;
284402
284557
  const amount6 = (f2) => netsuiteNumber(f2.foreignamount) ?? (netsuiteNumber(f2.netamount) ?? 0) / rate;
284403
284558
  const sign4 = Math.sign(rows35.reduce((sum6, f2) => sum6 + amount6(f2), 0)) || 1;
284404
284559
  for (const f2 of rows35) {
@@ -284431,17 +284586,17 @@ function attach(raws, lines2, links4, notes7) {
284431
284586
  ...rest2
284432
284587
  } = f2;
284433
284588
  const closed = bool10(isclosed) === true ? { isClosed: true } : {};
284434
- if (owner5.type === "journalEntry") {
284589
+ if (owner6.type === "journalEntry") {
284435
284590
  const d = netsuiteNumber(debitforeignamount ?? debit), c = netsuiteNumber(creditforeignamount ?? credit), net = amount6(f2);
284436
- (owner5.sublists.line ??= []).push({
284591
+ (owner6.sublists.line ??= []).push({
284437
284592
  ...rest2,
284438
284593
  account: expenseaccount ?? account9,
284439
284594
  ...present2(entity5) && { entity: entity5 },
284440
284595
  ...d ? { debit: d } : c ? { credit: c } : net >= 0 ? { debit: net } : { credit: -net }
284441
284596
  });
284442
284597
  } else if (present2(f2.item)) {
284443
- (owner5.sublists.item ??= []).push({ ...rest2, ...closed, amount: round23(amount6(f2) * sign4), ...present2(quantity) && { quantity: Math.abs(netsuiteNumber(quantity) ?? 1) } });
284444
- } else (owner5.sublists.expense ??= []).push({ ...rest2, ...closed, account: expenseaccount ?? account9, amount: round23(amount6(f2) * sign4) });
284598
+ (owner6.sublists.item ??= []).push({ ...rest2, ...closed, amount: round23(amount6(f2) * sign4), ...present2(quantity) && { quantity: Math.abs(netsuiteNumber(quantity) ?? 1) } });
284599
+ } else (owner6.sublists.expense ??= []).push({ ...rest2, ...closed, account: expenseaccount ?? account9, amount: round23(amount6(f2) * sign4) });
284445
284600
  }
284446
284601
  }
284447
284602
  for (const link9 of links4) {
@@ -284458,7 +284613,7 @@ function attach(raws, lines2, links4, notes7) {
284458
284613
  (from.sublists.apply ??= []).push({ doc, amount: Math.abs(amount6) });
284459
284614
  } else origin(from, doc);
284460
284615
  }
284461
- for (const [owner5, sources] of origins) if (!present2(owner5.fields.createdFrom) && sources.size === 1) owner5.fields.createdFrom = [...sources][0];
284616
+ for (const [owner6, sources] of origins) if (!present2(owner6.fields.createdFrom) && sources.size === 1) owner6.fields.createdFrom = [...sources][0];
284462
284617
  const noun = (n2, what) => n2 === 1 ? `1 ${what} names` : `${n2} ${what}s name`;
284463
284618
  if (orphans) notes7.push(`${noun(orphans, "transaction line")} a transaction the export lacks; left out of the world`);
284464
284619
  if (posted) notes7.push(`${posted} tax and cost-of-goods line${posted === 1 ? "" : "s"}: the twin posts its own`);
@@ -285968,6 +286123,28 @@ import { resolve as resolve61 } from "node:path";
285968
286123
  init_credentials();
285969
286124
  var NAME_RE2 = /^[A-Z][A-Z0-9_]{0,63}$/;
285970
286125
  var DEFERRED_SYNC = "Saved in the workspace; the workspace machine picks it up when it starts.";
286126
+ function renderSecrets(secrets2) {
286127
+ const status6 = (s3) => s3.issues.some((i) => i.level === "fail") ? "fail" : s3.check?.status === "accepted" ? `accepted by ${s3.check.provider}` : s3.check?.status === "unchecked" ? "unchecked" : s3.issues.some((i) => i.level === "warn") ? "warn" : "ok";
286128
+ const saved = (at6) => at6 ? `${at6.slice(0, 16).replace("T", " ")}Z` : "";
286129
+ const table6 = formatTable([["NAME", "STATUS", "SAVED", "LENGTH", "PREVIEW"], ...secrets2.map((s3) => [s3.name, status6(s3), saved(s3.savedAt), String(s3.length), s3.preview ?? ""])]);
286130
+ const notes7 = secrets2.flatMap((s3) => [
286131
+ ...s3.check?.status === "unchecked" && s3.check.reason ? [`- ${s3.name} was saved without a check: ${s3.check.reason}.`] : [],
286132
+ ...s3.issues.flatMap((i) => [`- ${i.message}`, ...i.fix && i.level !== "info" ? [` fix: ${i.fix}`] : []])
286133
+ ]);
286134
+ return notes7.length ? `${table6}
286135
+ ${notes7.join("\n")}` : table6;
286136
+ }
286137
+ function parseDotenv(text31) {
286138
+ const values3 = /* @__PURE__ */ new Map();
286139
+ for (const line2 of text31.replace(/^\uFEFF/, "").split(/\r?\n/)) {
286140
+ const match3 = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line2);
286141
+ if (!match3) continue;
286142
+ const [, name5, raw3] = match3;
286143
+ const quoted4 = /^(["'])(.*)\1(?:\s+#.*)?$/.exec(raw3);
286144
+ values3.set(name5, !quoted4 ? raw3.replace(/\s+#.*$/, "") : quoted4[1] === "'" ? quoted4[2] : quoted4[2].replace(/\\([nrt"\\])/g, (_, c) => ({ n: "\n", r: "\r", t: " " })[c] ?? c));
286145
+ }
286146
+ return values3;
286147
+ }
285971
286148
  async function nameInConfig(ctx, names8) {
285972
286149
  const label7 = ctx.globals().config ?? "ancha.yaml", file3 = resolve61(ctx.io.cwd, label7);
285973
286150
  const them = names8.length === 1 ? "it" : "them", list19 = names8.join(", ");
@@ -285993,6 +286170,15 @@ async function nameInConfig(ctx, names8) {
285993
286170
  }
285994
286171
  return { passEnv: { file: label7, added } };
285995
286172
  }
286173
+ async function configuredNames(ctx) {
286174
+ const text31 = await readFile60(resolve61(ctx.io.cwd, ctx.globals().config ?? "ancha.yaml"), "utf8").catch(() => void 0);
286175
+ if (text31 === void 0) return [];
286176
+ const doc = (0, import_yaml23.parseDocument)(text31), listed2 = (path9) => {
286177
+ const node5 = doc.getIn(path9);
286178
+ return (0, import_yaml23.isSeq)(node5) ? node5.items.map((item2) => String((0, import_yaml23.isScalar)(item2) ? item2.value : item2)) : [];
286179
+ };
286180
+ return [.../* @__PURE__ */ new Set([...listed2(["agent", "pass_env"]), ...listed2(["agent", "execution", "env"])])].filter((name5) => NAME_RE2.test(name5));
286181
+ }
285996
286182
  function registerSecrets(program2, ctx) {
285997
286183
  async function target6() {
285998
286184
  const url4 = await configuredServerUrl(ctx);
@@ -286016,40 +286202,55 @@ function registerSecrets(program2, ctx) {
286016
286202
  data7 = JSON.parse(text31);
286017
286203
  } catch {
286018
286204
  }
286019
- if (res.status === 401 || res.status === 403) throw authError(base6, { status: res.status, keySent: true });
286020
286205
  if (!res.ok) {
286021
- const error65 = typeof data7.error === "object" && data7.error !== null ? data7.error : void 0;
286022
- const message8 = typeof data7.error === "string" ? data7.error : error65 !== void 0 && "message" in error65 ? String(error65.message) : `HTTP ${res.status}`;
286023
- const code5 = error65 !== void 0 && isErrorCode(error65.code) ? error65.code : res.status >= 500 ? "SERVER_UNREACHABLE" : "INTERNAL";
286024
- throw new AnchaError(code5, `${base6}: ${message8}`, { ...typeof error65?.hint === "string" && { hint: error65.hint } });
286206
+ const auth2 = res.status === 401 || res.status === 403 ? authError(base6, { status: res.status, keySent: true }) : void 0;
286207
+ throw serverError(res.status, data7, { message: auth2?.message ?? `${base6}: HTTP ${res.status}`, ...auth2?.hint && { hint: auth2.hint } });
286025
286208
  }
286026
- return { names: data7.names ?? [], ...data7.restarting !== void 0 && { restarting: data7.restarting }, ...data7.synced !== void 0 && { synced: data7.synced } };
286209
+ return { names: data7.names ?? [], ...Array.isArray(data7.secrets) && { secrets: data7.secrets }, ...data7.restarting !== void 0 && { restarting: data7.restarting }, ...data7.synced !== void 0 && { synced: data7.synced } };
286027
286210
  }
286028
286211
  const validName = (name5) => {
286029
286212
  if (!NAME_RE2.test(name5)) throw new AnchaError("USAGE", "secret names are UPPER_SNAKE_CASE, up to 64 characters");
286030
286213
  return name5;
286031
286214
  };
286032
286215
  const command = program2.command("secrets").description("variables your agents get in the hosted workspace (provider keys); values come from this shell, not arguments");
286033
- command.command("set").argument("<names...>", "variable names to copy from this environment, e.g. OPENAI_API_KEY").description("copy variables from this shell into the workspace; run in the agent's project, it also names them under agent.pass_env in ancha.yaml, which is what an agent in the cloud gets").action(async (names8) => {
286216
+ async function save14(values3, check4, lead, extra2 = {}) {
286217
+ const names8 = Object.keys(values3);
286218
+ for (const [name5, value6] of Object.entries(values3)) if (value6.length < 8) throw new AnchaError("CONFIG_INVALID", `${name5} is shorter than 8 characters; a workspace secret has at least 8. Put short settings under agent.env in ancha.yaml.`);
286219
+ const result = await call4("PUT", check4 ? "" : "?check=0", values3);
286220
+ const named5 = await nameInConfig(ctx, names8);
286221
+ const line2 = "passEnvHint" in named5 ? `
286222
+ note: ${named5.passEnvHint}` : named5.passEnv.added.length > 0 ? `
286223
+ ${named5.passEnv.file}: agent.pass_env now names ${named5.passEnv.added.join(", ")}, so the agent gets ${named5.passEnv.added.length === 1 ? "it" : "them"} in cloud runs.` : "";
286224
+ const table6 = result.secrets?.length ? `
286225
+ ${renderSecrets(result.secrets)}` : "";
286226
+ ctx.out.result({ set: names8, ...extra2, ...result, ...named5 }, () => `${lead}Saved ${names8.join(", ")} in the workspace. Workspace variables: ${result.names.join(", ") || "none"}.${result.synced === false ? `
286227
+ ${DEFERRED_SYNC}` : result.restarting ? " The workspace machine restarts its processes to pick them up." : ""}${table6}${line2}`);
286228
+ }
286229
+ command.command("set").argument("<names...>", "variable names to copy from this environment, e.g. OPENAI_API_KEY").description("copy variables from this shell into the workspace; run in the agent's project, it also names them under agent.pass_env in ancha.yaml, which is what an agent in the cloud gets").option("--no-check", "save without asking Composio, OpenRouter, OpenAI or Anthropic whether they accept the key").action(async (names8, opts) => {
286034
286230
  const values3 = {};
286035
286231
  for (const name5 of names8) {
286036
286232
  validName(name5);
286037
286233
  const value6 = ctx.io.env[name5];
286038
286234
  if (value6 === void 0) throw new AnchaError("USAGE", `${name5} is not set in this shell`, { hint: `export ${name5}=\u2026 then run the command again` });
286039
- if (value6.length < 8) throw new AnchaError("CONFIG_INVALID", `${name5} is shorter than 8 characters; a workspace secret has at least 8. Put short settings under agent.env in ancha.yaml.`);
286040
286235
  values3[name5] = value6;
286041
286236
  }
286042
- const result = await call4("PUT", "", values3);
286043
- const named5 = await nameInConfig(ctx, names8);
286044
- const line2 = "passEnvHint" in named5 ? `
286045
- note: ${named5.passEnvHint}` : named5.passEnv.added.length > 0 ? `
286046
- ${named5.passEnv.file}: agent.pass_env now names ${named5.passEnv.added.join(", ")}, so the agent gets ${named5.passEnv.added.length === 1 ? "it" : "them"} in cloud runs.` : "";
286047
- ctx.out.result({ set: names8, ...result, ...named5 }, () => `Saved ${names8.join(", ")} in the workspace. Workspace variables: ${result.names.join(", ") || "none"}.${result.synced === false ? `
286048
- ${DEFERRED_SYNC}` : result.restarting ? " The workspace machine restarts its processes to pick them up." : ""}${line2}`);
286237
+ await save14(values3, opts.check, "");
286238
+ });
286239
+ command.command("import").argument("[file]", "dotenv file to read the values from", ".env").argument("[names...]", "variables to import (default: the ones ancha.yaml lists under agent.pass_env and agent.execution.env)").description("copy variables from a dotenv file into the workspace, checked as ancha secrets set checks them; never prints a value").option("--no-check", "save without asking Composio, OpenRouter, OpenAI or Anthropic whether they accept the key").action(async (file3, given2, opts) => {
286240
+ const path9 = resolve61(ctx.io.cwd, file3);
286241
+ const text31 = await readFile60(path9, "utf8").catch(() => {
286242
+ throw new AnchaError("USAGE", `cannot read ${file3}`, { hint: "pass the dotenv file that holds the values, e.g. ancha secrets import .env" });
286243
+ });
286244
+ const names8 = given2.length ? given2.map(validName) : await configuredNames(ctx);
286245
+ if (!names8.length) throw new AnchaError("USAGE", "no variables to import", { hint: `name them (ancha secrets import ${file3} OPENAI_API_KEY), or run in the agent's project, whose ancha.yaml lists them under agent.pass_env` });
286246
+ const values3 = parseDotenv(text31), found = names8.filter((name5) => values3.has(name5)), missing10 = names8.filter((name5) => !values3.has(name5));
286247
+ if (!found.length) throw new AnchaError("USAGE", `${file3} has none of ${names8.join(", ")}`, { hint: `add them to ${file3} as NAME=value lines, or export them and run ancha secrets set ${names8.join(" ")}` });
286248
+ await save14(Object.fromEntries(found.map((name5) => [name5, values3.get(name5)])), opts.check, `Read ${found.join(", ")} from ${file3}.${missing10.length ? ` Not in ${file3}: ${missing10.join(", ")}.` : ""}
286249
+ `, { file: file3, ...missing10.length && { missing: missing10 } });
286049
286250
  });
286050
- command.command("list").description("list variable names in the workspace (never values)").action(async () => {
286251
+ command.command("list").description("list the workspace's variables: names, when saved, whether accepted, and what to fix (never values)").action(async () => {
286051
286252
  const result = await call4("GET", "");
286052
- ctx.out.result({ names: result.names }, () => result.names.length ? result.names.join("\n") : "No variables set. Add one with ancha secrets set NAME.");
286253
+ ctx.out.result({ names: result.names, ...result.secrets && { secrets: result.secrets } }, () => !result.names.length ? "No variables set. Add one with ancha secrets set NAME." : result.secrets?.length ? renderSecrets(result.secrets) : result.names.join("\n"));
286053
286254
  });
286054
286255
  command.command("unset").argument("<name>").description("remove a variable from the workspace").action(async (name5) => {
286055
286256
  const result = await call4("DELETE", `/${validName(name5)}`);
@@ -286154,7 +286355,14 @@ var error64 = {
286154
286355
  title: "error",
286155
286356
  type: "object",
286156
286357
  required: ["error"],
286157
- properties: { error: { type: "object", required: ["code", "message"], properties: { code: { enum: [...ERROR_CODES] }, message: string10, hint: { ...string10, description: "the exact next command" }, docs: string10 } } }
286358
+ properties: { error: { type: "object", required: ["code", "kind", "message"], properties: {
286359
+ code: { enum: [...ERROR_CODES] },
286360
+ kind: { enum: [...ERROR_KINDS], description: "who acts next: fix (change the input), retry (run it again) or ours (Ancha's side)" },
286361
+ message: string10,
286362
+ hint: { ...string10, description: "the exact next command" },
286363
+ reference: { ...string10, description: "the request or job ID, on an error on Ancha's side" },
286364
+ docs: string10
286365
+ } } }
286158
286366
  };
286159
286367
  var runStarted = {
286160
286368
  $schema: "https://json-schema.org/draft/2020-12/schema",
@@ -286509,8 +286717,8 @@ next page: ancha runs list --cursor ${page20.nextCursor}`}`);
286509
286717
  return found.id;
286510
286718
  };
286511
286719
  if (consoleUrl) {
286512
- const owner5 = await consoleApi(consoleUrl);
286513
- const api4 = { start: (body8) => owner5.call("/api/playgrounds", body8), get: (id15) => owner5.call(`/api/playgrounds/${encodeURIComponent(id15)}`) };
286720
+ const owner6 = await consoleApi(consoleUrl);
286721
+ const api4 = { start: (body8) => owner6.call("/api/playgrounds", body8), get: (id15) => owner6.call(`/api/playgrounds/${encodeURIComponent(id15)}`) };
286514
286722
  const worldId = await withService(ctx, (service) => resolveWorld(() => service.worlds()));
286515
286723
  const run7 = await api4.start(definition3(worldId));
286516
286724
  const workspace4 = ctx.io.env.ANCHA_WORKSPACE_URL;