@ancha-labs/cli 0.4.46 → 0.4.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ancha.mjs +1 -1
- package/lib/ancha.mjs +662 -377
- package/lib/assets/SKILL.md +1 -1
- package/lib/assets/agents-section.md +1 -1
- package/lib/assets/docs/cloud.md +1 -1
- package/lib/assets/docs/setup.md +1 -1
- package/lib/assets/harbor/companion.mjs +23 -2
- package/lib/assets/ui/app.js +1 -1
- package/lib/mcp-entry.mjs +20 -0
- package/lib/worker.mjs +66 -14
- package/lib/world-server.mjs +23 -2
- package/package.json +1 -1
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
|
|
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(
|
|
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 ||
|
|
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 &&
|
|
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 ||
|
|
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/${
|
|
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(
|
|
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),
|
|
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 (!
|
|
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,
|
|
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) !==
|
|
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
|
|
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 ===
|
|
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 !==
|
|
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
|
|
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 ===
|
|
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,
|
|
37777
|
+
const visit4 = (value6, owner6, path9) => {
|
|
37753
37778
|
if (Array.isArray(value6)) {
|
|
37754
|
-
value6.forEach((v, i) => visit4(v,
|
|
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" &&
|
|
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" &&
|
|
37769
|
-
visit4(v,
|
|
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
|
|
38748
|
-
if (decl && !decl.path.startsWith(`seed.${
|
|
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
|
|
39291
|
-
if (!
|
|
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 =
|
|
39320
|
+
const fact2 = owner6.knows?.find((f2) => f2.id === id15);
|
|
39296
39321
|
if (fact2) return fact2;
|
|
39297
39322
|
add(
|
|
39298
39323
|
path9,
|
|
39299
|
-
|
|
39300
|
-
`${who2}'s facts: ${listed2((
|
|
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
|
|
39412
|
-
const decision2 =
|
|
39413
|
-
if (
|
|
39414
|
-
if (decision2 && option4 !== void 0 && !decision2.options.includes(option4)) add(`${path9}[2]`, `${option4} is not an option of ${
|
|
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
|
|
47125
|
-
if (
|
|
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
|
|
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,
|
|
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:
|
|
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 = [],
|
|
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:
|
|
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,
|
|
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
|
|
66763
|
-
return Response.json(
|
|
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:
|
|
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:
|
|
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(
|
|
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:
|
|
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(
|
|
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:
|
|
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:
|
|
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"),
|
|
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,
|
|
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
|
|
97208
|
-
if (
|
|
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 [
|
|
99666
|
-
if (!ctx.store.db.prepare("SELECT 1 FROM github_users WHERE login = ?").get(
|
|
99667
|
-
ctx.store.db.prepare("INSERT INTO github_organizations (id,login) VALUES (?,?)").run(resourceId(ctx),
|
|
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,
|
|
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
|
|
99862
|
-
const labels2 = body8[
|
|
99863
|
-
if (Array.isArray(labels2)) labels2.forEach((_, i) => fields13(`/${
|
|
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(":"),
|
|
104470
|
-
if (
|
|
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
|
|
106014
|
-
if (
|
|
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
|
|
107924
|
-
if (account9 !== null &&
|
|
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 };
|
|
@@ -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
|
|
108402
|
-
for (const type of types) emitEvent(ctx, type, current, { previous: type.endsWith(".updated") && before ? changed : void 0, account:
|
|
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
|
|
109377
|
-
const accountId4 =
|
|
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) => (
|
|
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,
|
|
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,
|
|
137211
|
-
if (
|
|
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
|
|
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:
|
|
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:
|
|
139068
|
-
const row2 = ctx.store.db.prepare("SELECT * FROM github_repos WHERE owner = ? COLLATE NOCASE AND name = ? COLLATE NOCASE").get(
|
|
139069
|
-
if (!row2) throw new import_graphql3.GraphQLError(`Could not resolve to a Repository with the name '${
|
|
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
|
|
141535
|
-
if (
|
|
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,
|
|
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:
|
|
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:
|
|
145362
|
+
canMoveItemOutOfDrive: owner6,
|
|
145338
145363
|
canMoveItemWithinDrive: editor,
|
|
145339
145364
|
canReadLabels: false,
|
|
145340
145365
|
canReadRevisions: editor,
|
|
145341
145366
|
canRemoveChildren: folder2 && editor,
|
|
145342
|
-
canRemoveMyDriveParent:
|
|
145367
|
+
canRemoveMyDriveParent: owner6,
|
|
145343
145368
|
canRename: editor,
|
|
145344
|
-
canShare:
|
|
145345
|
-
canTrash:
|
|
145346
|
-
canUntrash:
|
|
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
|
|
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 ??
|
|
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
|
|
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,
|
|
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
|
|
154065
|
-
if (
|
|
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
|
|
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 =
|
|
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 =
|
|
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
|
|
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 =
|
|
168364
|
+
const prior = owner6.get(i);
|
|
168340
168365
|
if (prior === void 0 || assign(prior, seen)) {
|
|
168341
|
-
|
|
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
|
|
179007
|
-
if (
|
|
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;
|
|
@@ -180997,10 +181022,10 @@ function commentJson2(model2, row2) {
|
|
|
180997
181022
|
...Object.keys(mentioned).length && { mentioned }
|
|
180998
181023
|
};
|
|
180999
181024
|
}
|
|
181000
|
-
function commentsOf3(call4,
|
|
181001
|
-
need(call4.ctx,
|
|
181025
|
+
function commentsOf3(call4, writing2) {
|
|
181026
|
+
need(call4.ctx, writing2 ? "data.recordComments:write" : "data.recordComments:read");
|
|
181002
181027
|
const model2 = AirtableBase.find(call4.ctx, call4.ids[0]), table6 = model2.table(call4.ids[1]);
|
|
181003
|
-
if (
|
|
181028
|
+
if (writing2) atLeast(model2, "comment");
|
|
181004
181029
|
return { model: model2, record: recordIn(model2, table6, call4.ids[2]) };
|
|
181005
181030
|
}
|
|
181006
181031
|
function listComments3(call4) {
|
|
@@ -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),
|
|
183274
|
-
const stored = db3.prepare("SELECT fields FROM ns_extra WHERE owner=? AND id=?").get(
|
|
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(
|
|
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),
|
|
183649
|
-
const fields13 = json35(db3.prepare("SELECT fields FROM ns_extra WHERE owner = ? AND id = ?").get(
|
|
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(
|
|
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, "",
|
|
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
|
|
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(
|
|
183683
|
-
notes7.note(record32.type, "",
|
|
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,
|
|
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:
|
|
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
|
|
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 :
|
|
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 :
|
|
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 =
|
|
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") ??
|
|
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")) && (
|
|
184675
|
-
if ((placed2 || has4("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 ?
|
|
184706
|
-
location: segmentRef(ctx, "location", keep2("location", prior?.location ?? (creating ?
|
|
184707
|
-
class: segmentRef(ctx, "classification", keep2("class", prior?.class ?? (creating ?
|
|
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,
|
|
186848
|
-
return { ...bound2(column3.value, column3.type), column: column3, owner:
|
|
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((
|
|
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
|
|
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,
|
|
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}/${
|
|
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,
|
|
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:
|
|
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
|
|
205424
|
-
|
|
205448
|
+
const owner6 = subscription2;
|
|
205449
|
+
owner6.callbacks.add(reference3);
|
|
205425
205450
|
return () => {
|
|
205426
|
-
|
|
205451
|
+
owner6.callbacks.delete(reference3);
|
|
205427
205452
|
registry2.unregister(reference3);
|
|
205428
|
-
if (
|
|
205429
|
-
if (subscriptions2.get(signal) ===
|
|
205453
|
+
if (owner6.callbacks.size === 0) {
|
|
205454
|
+
if (subscriptions2.get(signal) === owner6) {
|
|
205430
205455
|
subscriptions2.delete(signal);
|
|
205431
205456
|
}
|
|
205432
|
-
signal.removeEventListener("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(
|
|
205464
|
+
function retainRequestAbortCallback(owner6, abort, requestSignal) {
|
|
205440
205465
|
if (typeof weakGlobals.WeakRef === "function" && finalizer && !requestSignal.aborted) {
|
|
205441
|
-
let callbacks = callbackOwners.get(
|
|
205466
|
+
let callbacks = callbackOwners.get(owner6);
|
|
205442
205467
|
if (!callbacks) {
|
|
205443
205468
|
callbacks = /* @__PURE__ */ new Set();
|
|
205444
|
-
callbackOwners.set(
|
|
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
|
|
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(
|
|
210091
|
+
affected.add(owner6);
|
|
210067
210092
|
}
|
|
210068
210093
|
}
|
|
210069
210094
|
return affected;
|
|
210070
210095
|
}
|
|
210071
|
-
function updateBufferedLedgerMembershipChanges(
|
|
210072
|
-
for (const identity7 of
|
|
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 (!
|
|
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
|
|
210103
|
-
const 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(
|
|
210130
|
+
if (!next2 || !updateBufferedLedgerMembershipChanges(owner6, next2, graph, records6, changes, work)) {
|
|
210106
210131
|
return void 0;
|
|
210107
210132
|
}
|
|
210108
|
-
memberships2.set(
|
|
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 [
|
|
210148
|
-
for (const identity7 of
|
|
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(
|
|
210175
|
+
records6.get(identity7)?.owners.delete(owner6);
|
|
210151
210176
|
}
|
|
210152
210177
|
}
|
|
210153
210178
|
for (const identity7 of next2) {
|
|
210154
|
-
if (!
|
|
210155
|
-
records6.get(identity7).owners.add(
|
|
210179
|
+
if (!owner6.identities.has(identity7)) {
|
|
210180
|
+
records6.get(identity7).owners.add(owner6);
|
|
210156
210181
|
}
|
|
210157
210182
|
}
|
|
210158
|
-
|
|
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
|
|
212033
|
-
const serializer = Object.getOwnPropertyDescriptor(
|
|
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
|
|
212237
|
+
const owner6 = ownSerializedParserObject(body8.tools, String(index));
|
|
212213
212238
|
const source = initial.tools?.[index];
|
|
212214
|
-
if (
|
|
212215
|
-
originalToolOwners.set(
|
|
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
|
|
212275
|
+
const owner6 = ownSerializedParserObject(holder, key5);
|
|
212251
212276
|
responseFrame = {
|
|
212252
|
-
source:
|
|
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
|
|
212282
|
-
const source =
|
|
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
|
|
222140
|
-
if (
|
|
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
|
|
222178
|
-
if (
|
|
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"),
|
|
230720
|
-
if (
|
|
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:
|
|
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
|
|
230733
|
-
if (!record25(
|
|
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:
|
|
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 {
|
|
@@ -232393,6 +232434,7 @@ var init_runtime3 = __esm({
|
|
|
232393
232434
|
concurrency: external_exports.number().int().positive(),
|
|
232394
232435
|
seed: text26.nullable(),
|
|
232395
232436
|
strict: external_exports.boolean(),
|
|
232437
|
+
simulatedAnswers: external_exports.enum(["allow", "fail"]).optional(),
|
|
232396
232438
|
minPassRate: external_exports.number().min(0).max(1),
|
|
232397
232439
|
allowUnwrapped: external_exports.array(text26),
|
|
232398
232440
|
agentCommand: text26.nullable(),
|
|
@@ -232807,7 +232849,7 @@ async function startIngressClient(options5) {
|
|
|
232807
232849
|
const toolkit = event3?.toolkit ?? (qb ? "quickbooks" : "netsuite");
|
|
232808
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 } });
|
|
232809
232851
|
};
|
|
232810
|
-
const issue9 = (code5, detail3, toolkit = qb ? "quickbooks" : "netsuite",
|
|
232852
|
+
const issue9 = (code5, detail3, toolkit = qb ? "quickbooks" : "netsuite", owner6 = "harness") => ({ kind: "world", owner: owner6, service: toolkit, code: code5, message: `${code5}: ${detail3}` });
|
|
232811
232853
|
const fail9 = () => {
|
|
232812
232854
|
if (failed2 || closed || options5.signal?.aborted) return;
|
|
232813
232855
|
failed2 = true;
|
|
@@ -235780,7 +235822,16 @@ function attemptOutcome(view3, ctx) {
|
|
|
235780
235822
|
return out({ code: "answered", level: "pass", message: ctx.check === "netsuite" ? answeredNetsuite(netsuite, answer.text) : `It took the task and answered ${quoted3(answer.text)}.` });
|
|
235781
235823
|
}
|
|
235782
235824
|
const model2 = view3.modelReplies?.find((reply6) => MODEL_REFUSALS.has(reply6.status));
|
|
235783
|
-
if (model2 !== void 0)
|
|
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
|
+
}
|
|
235784
235835
|
const refused2 = (entry3) => entry3.status === 401 || entry3.status === 403;
|
|
235785
235836
|
const turnedDown = used.length > 0 && used.every(refused2) ? used : data7.length > 0 && data7.every(refused2) ? data7 : [];
|
|
235786
235837
|
if (turnedDown.length > 0) {
|
|
@@ -235888,12 +235939,13 @@ async function recordAnswer(backend, envId, sessionId, output2, source, printed)
|
|
|
235888
235939
|
}
|
|
235889
235940
|
}
|
|
235890
235941
|
function modelKeyIssue(refusal4, given2) {
|
|
235942
|
+
const failure6 = modelFailure(refusal4.status);
|
|
235891
235943
|
return {
|
|
235892
235944
|
kind: "model",
|
|
235893
235945
|
owner: "harness",
|
|
235894
235946
|
service: refusal4.host,
|
|
235895
|
-
code:
|
|
235896
|
-
message: `${refusal4.host}
|
|
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.`}`
|
|
235897
235949
|
};
|
|
235898
235950
|
}
|
|
235899
235951
|
function recordStdout(backend, envId, sessionId, output2) {
|
|
@@ -236066,6 +236118,7 @@ var EXIT_COMMAND_NOT_FOUND2, unknownRoute18;
|
|
|
236066
236118
|
var init_trial = __esm({
|
|
236067
236119
|
"backend/src/runner/trial.ts"() {
|
|
236068
236120
|
"use strict";
|
|
236121
|
+
init_gateway();
|
|
236069
236122
|
init_routed_trial();
|
|
236070
236123
|
init_slack_app();
|
|
236071
236124
|
init_src();
|
|
@@ -237357,7 +237410,7 @@ async function readRunState(outDir, runId2) {
|
|
|
237357
237410
|
updatedAt: summary.finishedAt,
|
|
237358
237411
|
completedTrials,
|
|
237359
237412
|
totalTrials,
|
|
237360
|
-
...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 }
|
|
237361
237414
|
};
|
|
237362
237415
|
}
|
|
237363
237416
|
throw new AnchaError("INTERNAL", "cannot read run status", { cause: error65 });
|
|
@@ -237374,7 +237427,7 @@ async function readRunState(outDir, runId2) {
|
|
|
237374
237427
|
alive4 = error65.code !== "ESRCH";
|
|
237375
237428
|
}
|
|
237376
237429
|
if (!alive4 || Date.now() - Date.parse(state3.updatedAt) > 15e3) {
|
|
237377
|
-
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" } };
|
|
237378
237431
|
}
|
|
237379
237432
|
}
|
|
237380
237433
|
return state3;
|
|
@@ -241622,17 +241675,17 @@ function buildSeed(cx, { writes: writes3, state: state3, get: get8, listed: list
|
|
|
241622
241675
|
linesNote(s3, "one line carries its total");
|
|
241623
241676
|
}
|
|
241624
241677
|
}
|
|
241625
|
-
const
|
|
241678
|
+
const owner6 = party4(s3, kind2), from = s3.fields.createdFrom && get8(s3.fields.createdFrom), order6 = from && idOf4(from), orderType = purchase ? "purchaseOrder" : "salesOrder";
|
|
241626
241679
|
let linked2 = false;
|
|
241627
241680
|
if (type !== "creditMemo" && order6 && docs2.get(order6)?.type === orderType) {
|
|
241628
|
-
if (docs2.get(order6).owner ===
|
|
241681
|
+
if (docs2.get(order6).owner === owner6 && !docs2.get(order6).pending && !expenses.length && fitOrder(order6, lines2, "billed")) linked2 = true;
|
|
241629
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`);
|
|
241630
241683
|
}
|
|
241631
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;
|
|
241632
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`);
|
|
241633
241686
|
const row2 = {
|
|
241634
241687
|
...base6,
|
|
241635
|
-
[kind2]:
|
|
241688
|
+
[kind2]: owner6,
|
|
241636
241689
|
...type !== "creditMemo" && termsOf(s3) && { terms: termsOf(s3) },
|
|
241637
241690
|
...type !== "creditMemo" && dueOf(s3) && { dueDate: dueOf(s3) },
|
|
241638
241691
|
...approval && { approval },
|
|
@@ -241643,7 +241696,7 @@ function buildSeed(cx, { writes: writes3, state: state3, get: get8, listed: list
|
|
|
241643
241696
|
if (type === "creditMemo") row2.apply = [];
|
|
241644
241697
|
lists3[SEED_LIST[type]].push(row2);
|
|
241645
241698
|
const total6 = round2(totalOf(lines2, purchase) + sum6(expenses.map((e) => e.amount)));
|
|
241646
|
-
docs2.set(base6.id, { type, owner:
|
|
241699
|
+
docs2.set(base6.id, { type, owner: owner6, total: total6, open: total6, approved: approval === "approved", s: s3, row: row2 });
|
|
241647
241700
|
observed(s3, `${total6.toFixed(2)}${approval ? `, ${approval === "pending" ? "pending approval" : approval}` : ""}${linked2 ? `, from ${label7(from)}` : ""}`);
|
|
241648
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)}`);
|
|
241649
241702
|
}
|
|
@@ -241662,7 +241715,7 @@ function buildSeed(cx, { writes: writes3, state: state3, get: get8, listed: list
|
|
|
241662
241715
|
return out;
|
|
241663
241716
|
};
|
|
241664
241717
|
for (const [type, kind2] of [["customerPayment", "customer"], ["vendorPayment", "vendor"]]) for (const s3 of byType(type)) {
|
|
241665
|
-
const base6 = header4(s3),
|
|
241718
|
+
const base6 = header4(s3), owner6 = party4(s3, kind2), apply2 = applied(s3, SEED_LIST[type], { owner: owner6 });
|
|
241666
241719
|
const amount6 = money22(s3.fields.payment ?? s3.fields.total) ?? sum6(apply2.map((a) => a.amount));
|
|
241667
241720
|
const total6 = Math.max(amount6, sum6(apply2.map((a) => a.amount)));
|
|
241668
241721
|
if (!(total6 > 0)) {
|
|
@@ -241670,8 +241723,8 @@ function buildSeed(cx, { writes: writes3, state: state3, get: get8, listed: list
|
|
|
241670
241723
|
continue;
|
|
241671
241724
|
}
|
|
241672
241725
|
const acct = account9(s3.fields.account, type === "vendorPayment" ? "bank" : "funds");
|
|
241673
|
-
lists3[SEED_LIST[type]].push({ ...base6, [kind2]:
|
|
241674
|
-
docs2.set(base6.id, { type, owner:
|
|
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 });
|
|
241675
241728
|
observed(s3, `${total6.toFixed(2)}${apply2.length ? `, applied to ${apply2.map((a) => label7(docs2.get(a.doc).s)).join(", ")}` : ""}`);
|
|
241676
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`);
|
|
241677
241730
|
}
|
|
@@ -242947,11 +243000,11 @@ function startingState(check4, scene2) {
|
|
|
242947
243000
|
const args = check4["github.permission"], github3 = seed44.github;
|
|
242948
243001
|
const repo4 = github3.repos?.find((r2) => r2.ref === refName7(args.repo)), user9 = github3.users?.find((u) => u.ref === refName7(args.user));
|
|
242949
243002
|
if (!repo4 || !user9) return "unknown";
|
|
242950
|
-
const
|
|
242951
|
-
const member4 = github3.orgs?.find((o) => o.login.toLowerCase() ===
|
|
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);
|
|
242952
243005
|
const collaborator = repo4.collaborators?.find((c) => refName7(c.user) === user9.ref);
|
|
242953
243006
|
const direct = collaborator ? collaborator.permission ?? "write" : "none";
|
|
242954
|
-
const permission7 =
|
|
243007
|
+
const permission7 = owner6 === user9.login.toLowerCase() ? "admin" : direct === "none" && member4 ? "read" : direct;
|
|
242955
243008
|
return productionState(check4, scene2, [read7("github", `/repos/${repo4.name}/collaborators/${user9.login}/permission`, {}, { permission: permission7 })]);
|
|
242956
243009
|
}
|
|
242957
243010
|
if ("github.file_at" in check4 && seed44.github) {
|
|
@@ -243556,6 +243609,21 @@ function taskFixFromLog(lines2, agent) {
|
|
|
243556
243609
|
if (input5 === null) return void 0;
|
|
243557
243610
|
return { name: input5.name, via: input5.via, file: input5.file, yaml: taskWiring(input5, agent.command).yaml };
|
|
243558
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
|
+
}
|
|
243559
243627
|
async function probeVmConnection(descriptor3, deps = {}) {
|
|
243560
243628
|
if (descriptor3 !== attemptDescriptor() || descriptor3.role !== "connect") throw new AnchaError("CONFIG_INVALID", "A connection attempt descriptor is required.");
|
|
243561
243629
|
const probe = { kind: "command", passed: false, startedAt: null, readyAt: null, exitCode: null };
|
|
@@ -243656,7 +243724,7 @@ async function probeVmConnection(descriptor3, deps = {}) {
|
|
|
243656
243724
|
const text31 = await readFile25(join44(descriptor3.outDir, "agent.log"), "utf8").catch(() => "");
|
|
243657
243725
|
const tail = text31.trimEnd().split("\n").filter(Boolean).slice(-10);
|
|
243658
243726
|
if (tail.length) probe.logTail = tail;
|
|
243659
|
-
if (error65 instanceof AnchaError
|
|
243727
|
+
if (error65 instanceof AnchaError || !(error65 instanceof Error) || !["AbortError", "TimeoutError"].includes(error65.name)) throw connectionFailure(error65, descriptor3);
|
|
243660
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." };
|
|
243661
243729
|
} finally {
|
|
243662
243730
|
try {
|
|
@@ -243713,7 +243781,9 @@ async function runWithTask(descriptor3, agent, run7) {
|
|
|
243713
243781
|
realTimeouts: { [scene2.id]: limit2 }
|
|
243714
243782
|
});
|
|
243715
243783
|
trial = result.results.get(scene2.id)?.trials[0];
|
|
243716
|
-
} 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 });
|
|
243717
243787
|
} finally {
|
|
243718
243788
|
await backend?.close().catch(() => {
|
|
243719
243789
|
});
|
|
@@ -243722,7 +243792,7 @@ async function runWithTask(descriptor3, agent, run7) {
|
|
|
243722
243792
|
if (log3 !== void 0) writeSync7(run7.fd, log3);
|
|
243723
243793
|
probe.durationMs = trial?.realMs ?? 0;
|
|
243724
243794
|
probe.exitCode = trial?.exitCode ?? null;
|
|
243725
|
-
if (trial === void 0)
|
|
243795
|
+
if (trial === void 0) throw new AnchaError("INTERNAL", "The connection check ended without a trial result.");
|
|
243726
243796
|
probe.tools = probeToolCalls(twins, trial.trace);
|
|
243727
243797
|
const tail = trial.logTail, fix = taskFixFromLog(tail, { command, env: agent.env });
|
|
243728
243798
|
const text31 = log3?.toString("utf8") ?? tail.join("\n");
|
|
@@ -243732,12 +243802,9 @@ async function runWithTask(descriptor3, agent, run7) {
|
|
|
243732
243802
|
Object.assign(probe, { reason: route15.reason, logTail: tail.length > 0 ? tail : text31.trimEnd().split("\n").filter(Boolean).slice(-10) });
|
|
243733
243803
|
return { state: "failed", probe, message: route15.reason.message };
|
|
243734
243804
|
}
|
|
243735
|
-
const diagnosed = (code5) => code5
|
|
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");
|
|
243736
243806
|
const harnessIssue = trial.harnessIssues.some((issue9) => issue9.owner === "harness" && !diagnosed(issue9.code));
|
|
243737
|
-
if (harnessIssue || !trial.valid && !trial.harnessIssues.some((issue9) => diagnosed(issue9.code)))
|
|
243738
|
-
Object.assign(probe, { logTail: tail, ...fix !== void 0 && { fix } });
|
|
243739
|
-
return { state: "failed", probe, message: unfinished(trial) };
|
|
243740
|
-
}
|
|
243807
|
+
if (harnessIssue || !trial.valid && !trial.harnessIssues.some((issue9) => diagnosed(issue9.code))) throw connectionFailure(new AnchaError("INTERNAL", unfinished(trial)), descriptor3);
|
|
243741
243808
|
if (trial.exit === "spawn_failed" && agent.taskInput?.kind === "http") {
|
|
243742
243809
|
probe.logTail = tail;
|
|
243743
243810
|
return { state: "failed", probe, message: trial.taskDelivery?.message ?? "The agent did not pass its HTTP readiness check." };
|
|
@@ -243932,8 +243999,10 @@ function finalizeInput(value6) {
|
|
|
243932
243999
|
if (!TERMINAL.includes(item2.state)) wrong(`has attempt ${item2.id}, which has not ended`);
|
|
243933
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`);
|
|
243934
244001
|
if (item2.error !== null) {
|
|
243935
|
-
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"]);
|
|
243936
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`);
|
|
243937
244006
|
}
|
|
243938
244007
|
}
|
|
243939
244008
|
return value6;
|
|
@@ -245168,17 +245237,17 @@ function readAccess(cx, repos, loginRef) {
|
|
|
245168
245237
|
}
|
|
245169
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]);
|
|
245170
245239
|
for (const l of left) membership(l.org, l.login, "member", "inferred", l.span);
|
|
245171
|
-
for (const
|
|
245172
|
-
const unread2 = removed.filter((r2) => r2.full.startsWith(`${
|
|
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));
|
|
245173
245242
|
if (!unread2.length) continue;
|
|
245174
|
-
const id15 = `github.members.${
|
|
245243
|
+
const id15 = `github.members.${owner6}`, answer = cx.answers[id15];
|
|
245175
245244
|
const people4 = [...new Set(unread2.map((r2) => r2.login))].join(", "), where3 = [...new Set(unread2.map((r2) => r2.full))].join(", ");
|
|
245176
|
-
cx.ask(id15, `Who were members of the ${
|
|
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" });
|
|
245177
245246
|
if (typeof answer !== "string") continue;
|
|
245178
245247
|
const named5 = /^\s*none\s*$/i.test(answer) ? [] : answer.split(/[\s,]+/).filter(Boolean);
|
|
245179
|
-
for (const login2 of named5) membership(
|
|
245180
|
-
for (const r2 of unread2) if (!named5.some((n2) => n2.toLowerCase() === r2.login.toLowerCase())) membership(
|
|
245181
|
-
cx.note("answered", `seed.github.orgs.${
|
|
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"}`);
|
|
245182
245251
|
}
|
|
245183
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]);
|
|
245184
245253
|
const isMember3 = (org5, login2) => {
|
|
@@ -245490,8 +245559,8 @@ function readGoogleDrive(cx) {
|
|
|
245490
245559
|
}
|
|
245491
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] : []) {
|
|
245492
245561
|
if (!f2?.id) continue;
|
|
245493
|
-
const
|
|
245494
|
-
if (!had || before && !had.before) files2.set(f2.id, { ...had, ...f2, owner: before ?
|
|
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 });
|
|
245495
245564
|
}
|
|
245496
245565
|
const m = PERMISSIONS.exec(c.path);
|
|
245497
245566
|
if (!m) continue;
|
|
@@ -245947,12 +246016,12 @@ function proposeAccessChecks(cx, { okta, drive: drive2, pagerduty, github: githu
|
|
|
245947
246016
|
}
|
|
245948
246017
|
const removed = github3?.access?.removed ?? [], repos = (login2) => new Set(removed.filter((r2) => r2.login.toLowerCase() === login2.toLowerCase()).map((r2) => r2.full)).size;
|
|
245949
246018
|
for (const r2 of removed) {
|
|
245950
|
-
const repo4 = github3.repos.get(r2.full)?.ref,
|
|
246019
|
+
const repo4 = github3.repos.get(r2.full)?.ref, owner6 = r2.full.split("/")[0];
|
|
245951
246020
|
if (!repo4) continue;
|
|
245952
|
-
const member4 = github3.access.isMember(
|
|
246021
|
+
const member4 = github3.access.isMember(owner6, r2.login), left = github3.access.left.some((l) => l.org === owner6 && l.login.toLowerCase() === r2.login.toLowerCase());
|
|
245953
246022
|
add(
|
|
245954
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" } },
|
|
245955
|
-
`the agent removed ${r2.login}'s direct access to ${r2.full}${member4 && !left ? `; still a member of ${
|
|
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` : ""}`,
|
|
245956
246025
|
left || member4 === false ? "passed" : member4 ? "failed" : "unknown"
|
|
245957
246026
|
);
|
|
245958
246027
|
}
|
|
@@ -246057,9 +246126,9 @@ function invert(map2, items2, cx) {
|
|
|
246057
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)] });
|
|
246058
246127
|
continue;
|
|
246059
246128
|
}
|
|
246060
|
-
const
|
|
246061
|
-
if (pinOf(r2.collection))
|
|
246062
|
-
links4.push({ owner:
|
|
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)) });
|
|
246063
246132
|
}
|
|
246064
246133
|
}
|
|
246065
246134
|
const fill = (into, from) => {
|
|
@@ -250151,6 +250220,25 @@ async function configuredServerUrl(ctx) {
|
|
|
250151
250220
|
init_credentials();
|
|
250152
250221
|
init_backend();
|
|
250153
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
|
+
|
|
250154
250242
|
// packages/cli/src/hosted.ts
|
|
250155
250243
|
init_src();
|
|
250156
250244
|
init_credentials();
|
|
@@ -251150,8 +251238,8 @@ function namedFiles(path9, doc) {
|
|
|
251150
251238
|
const to = record27(tool) ? beside(path9, tool.observations) : void 0;
|
|
251151
251239
|
if (to !== void 0) named5.push({ field: `${field6}.${name5}.observations`, to, kind: "observations", role: "world" });
|
|
251152
251240
|
}
|
|
251153
|
-
const generated = (
|
|
251154
|
-
const to = record27(
|
|
251241
|
+
const generated = (owner6, field6) => {
|
|
251242
|
+
const to = record27(owner6) && record27(owner6.generated) ? beside(path9, owner6.generated.record) : void 0;
|
|
251155
251243
|
if (to !== void 0) named5.push({ field: field6, to, kind: "generated-record", role: "provenance" });
|
|
251156
251244
|
};
|
|
251157
251245
|
generated(doc, "generated.record");
|
|
@@ -251458,6 +251546,10 @@ init_report2();
|
|
|
251458
251546
|
|
|
251459
251547
|
// packages/cli/src/output.ts
|
|
251460
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
|
+
}
|
|
251461
251553
|
function terse(value6) {
|
|
251462
251554
|
if (typeof value6 === "string") return /^[^\s"]+$/.test(value6) ? value6 : JSON.stringify(value6);
|
|
251463
251555
|
return JSON.stringify(value6) ?? "undefined";
|
|
@@ -251554,7 +251646,7 @@ var Output = class {
|
|
|
251554
251646
|
`);
|
|
251555
251647
|
} else {
|
|
251556
251648
|
const lines2 = [`error[${err2.code}]: ${err2.message.replaceAll("\n", "\n ")}`];
|
|
251557
|
-
|
|
251649
|
+
lines2.push(errorAction(e instanceof AnchaError ? err2 : { ...err2, hint: "a bug in the Ancha CLI, not in your setup" }));
|
|
251558
251650
|
if (err2.docs !== void 0) lines2.push(`docs: ${err2.docs}`);
|
|
251559
251651
|
this.#io.stderr.write(`${lines2.join("\n")}
|
|
251560
251652
|
`);
|
|
@@ -251583,7 +251675,7 @@ function withOwnNext(onboarding) {
|
|
|
251583
251675
|
const testsAdded = onboarding.checks.testsAdded ?? { done: traces?.done === true, traceId: traces?.traceId ?? null, runId: null, at: traces?.at ?? null };
|
|
251584
251676
|
const checks2 = { ...onboarding.checks, testsAdded };
|
|
251585
251677
|
const open17 = CHECKS.find(([key5]) => !checks2[key5].done)?.[0];
|
|
251586
|
-
return { ...onboarding, checks: checks2, nextCommand: NEXT_COMMANDS[open17 ?? "done"] };
|
|
251678
|
+
return { ...onboarding, checks: checks2, nextCommand: open17 === "testsAdded" && traces?.done && traces.traceId ? `ancha pull ${traces.traceId}` : NEXT_COMMANDS[open17 ?? "done"] };
|
|
251587
251679
|
}
|
|
251588
251680
|
var checkLine = (done, [, doneLabel, title2]) => `${done ? "\u2713" : "\u25CB"} ${done ? doneLabel : title2}`;
|
|
251589
251681
|
async function listsTests(ctx) {
|
|
@@ -251631,15 +251723,12 @@ async function fetchOnboarding(ctx, target6) {
|
|
|
251631
251723
|
if (ctx.io.abort?.aborted) throw new AnchaError("USAGE", "interrupted");
|
|
251632
251724
|
throw new AnchaError("SERVER_UNREACHABLE", `cannot reach ${serverUrl3}`, { hint: "check your network, then run ancha status --on cloud", cause: e });
|
|
251633
251725
|
}
|
|
251634
|
-
if (res.status === 401 || res.status === 403) throw authError(serverUrl3, { status: res.status, keySent: true });
|
|
251635
251726
|
const body8 = await res.json().catch(() => void 0);
|
|
251636
251727
|
if (!res.ok) {
|
|
251637
|
-
|
|
251638
|
-
const
|
|
251639
|
-
|
|
251640
|
-
|
|
251641
|
-
const hint = typeof error65.hint === "string" ? error65.hint : busy ? "retry in a few seconds with ancha status --on cloud" : void 0;
|
|
251642
|
-
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;
|
|
251643
251732
|
}
|
|
251644
251733
|
if (!isOnboarding(body8)) throw new AnchaError("INTERNAL", `${serverUrl3} sent a malformed onboarding answer`);
|
|
251645
251734
|
return withOwnNext(body8);
|
|
@@ -251705,13 +251794,12 @@ function retryHint(response6) {
|
|
|
251705
251794
|
return `retry in ${seconds6 < 120 ? `${seconds6} seconds` : `${Math.ceil(seconds6 / 60)} minutes`}`;
|
|
251706
251795
|
}
|
|
251707
251796
|
async function refusal2(response6, server) {
|
|
251708
|
-
if (response6.status === 401) return authError(server, { status: 401, keySent: true });
|
|
251709
251797
|
const body8 = await response6.json().catch(() => void 0);
|
|
251710
|
-
const
|
|
251711
|
-
|
|
251712
|
-
|
|
251713
|
-
|
|
251714
|
-
|
|
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
|
+
});
|
|
251715
251803
|
}
|
|
251716
251804
|
async function call2(ws, method2, path9, options5 = {}) {
|
|
251717
251805
|
for (let attempt2 = 0; ; attempt2++) {
|
|
@@ -251756,6 +251844,7 @@ var getArchive = (ws, id15) => call2(ws, "GET", path8(id15, "/archive"), { retry
|
|
|
251756
251844
|
var getAttemptArtifact = (ws, id15, attemptId) => call2(ws, "GET", path8(id15, `/attempts/${encodeURIComponent(attemptId)}/artifact`), { retry: true, bytes: true });
|
|
251757
251845
|
var cancelJob = (ws, id15) => call2(ws, "POST", path8(id15, "/cancel"), { json: {}, retry: true });
|
|
251758
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 });
|
|
251759
251848
|
var getOnboarding = (ws) => call2(ws, "GET", "/_onboarding", { retry: true }).then(withOwnNext);
|
|
251760
251849
|
var listCloudAgents = (ws) => call2(ws, "GET", "/_agents", { retry: true });
|
|
251761
251850
|
var getCloudAgent = (ws, id15) => call2(ws, "GET", `/_agents/${encodeURIComponent(id15)}`, { retry: true });
|
|
@@ -251776,7 +251865,7 @@ async function cloudAgent(ctx, id15) {
|
|
|
251776
251865
|
function atStep(step3, error65, next2) {
|
|
251777
251866
|
if (!(error65 instanceof AnchaError)) return error65;
|
|
251778
251867
|
const named5 = error65.step ?? step3;
|
|
251779
|
-
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 });
|
|
251780
251869
|
}
|
|
251781
251870
|
function parseEvent(line2) {
|
|
251782
251871
|
const event3 = JSON.parse(line2);
|
|
@@ -251875,7 +251964,7 @@ function eventLine(event3, all9) {
|
|
|
251875
251964
|
case "phase":
|
|
251876
251965
|
return all9 ? `${attemptOf(event3)}: ${text27(data7.phase)}` : void 0;
|
|
251877
251966
|
case "log":
|
|
251878
|
-
return all9 ? `${event3.attemptId === null ? "" : `${attemptOf(event3)}: `}${text27(data7.line ?? data7.text ?? data7.message)}` : void 0;
|
|
251967
|
+
return data7.source === "machine_wait" ? `waiting for a machine: ${text27(data7.reason)}; retrying` : all9 ? `${event3.attemptId === null ? "" : `${attemptOf(event3)}: `}${text27(data7.line ?? data7.text ?? data7.message)}` : void 0;
|
|
251879
251968
|
default:
|
|
251880
251969
|
return all9 ? `${event3.type.replace(/_/g, " ")}${data7.state ? `: ${text27(data7.state)}` : ""}` : void 0;
|
|
251881
251970
|
}
|
|
@@ -251931,7 +252020,7 @@ function projectTestDirectoryReader(cwd, cloud) {
|
|
|
251931
252020
|
function finishedText(ws, detail3, includeNext = true) {
|
|
251932
252021
|
const { job, summary } = detail3;
|
|
251933
252022
|
const counts2 = summary?.counts ?? job.counts;
|
|
251934
|
-
const never2 = cloudNeverRan(detail3);
|
|
252023
|
+
const never2 = ["install", "create", "start"].includes(job.error?.step ?? "") ? void 0 : cloudNeverRan(detail3);
|
|
251935
252024
|
if (never2 !== void 0 && summary !== null) {
|
|
251936
252025
|
const head2 = summary.graded !== true && counts2.completedAttempts === 0 ? "INVALID (no attempts graded)" : job.state === "completed" ? summary.verdict.toUpperCase() : job.state.toUpperCase();
|
|
251937
252026
|
const folded = neverRanChecksLine(never2, job.id);
|
|
@@ -251973,7 +252062,11 @@ function finishedText(ws, detail3, includeNext = true) {
|
|
|
251973
252062
|
const counts3 = job.counts;
|
|
251974
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` : ""}`);
|
|
251975
252064
|
}
|
|
251976
|
-
if (job.error !== null && job.error !== void 0) lines2.push(
|
|
252065
|
+
if (job.error !== null && job.error !== void 0) lines2.push(
|
|
252066
|
+
`${job.error.step ? `${job.error.step}: ` : ""}${job.error.message}`,
|
|
252067
|
+
...job.error.step === "install" && job.error.stderr ? job.error.stderr.trim().split("\n").slice(-10).map((line2) => ` ${line2}`) : [],
|
|
252068
|
+
errorAction(toErrorJson(serverError(400, { error: job.error }, { message: "The job failed." })))
|
|
252069
|
+
);
|
|
251977
252070
|
lines2.push(`Result: ${resultUrl(ws, detail3)}`);
|
|
251978
252071
|
if (includeNext && job.kind === "run") {
|
|
251979
252072
|
const ungraded = summary?.verdict === "ungraded";
|
|
@@ -252132,7 +252225,6 @@ async function post5(server, key5, argv, files2) {
|
|
|
252132
252225
|
} catch (error65) {
|
|
252133
252226
|
throw new AnchaError("SERVER_UNREACHABLE", `${server} did not answer`, { hint: "check the network, then retry", cause: error65 });
|
|
252134
252227
|
}
|
|
252135
|
-
if (response6.status === 401) throw authError(server, { status: 401, keySent: true });
|
|
252136
252228
|
if (!response6.ok || response6.body === null) throw await refusal3(response6, server);
|
|
252137
252229
|
return response6.body;
|
|
252138
252230
|
}
|
|
@@ -252151,7 +252243,7 @@ async function ask(server, key5, argv) {
|
|
|
252151
252243
|
}
|
|
252152
252244
|
});
|
|
252153
252245
|
const failed2 = lines2.find((line2) => typeof line2 === "object" && line2 !== null && "error" in line2);
|
|
252154
|
-
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(" ")}
|
|
252246
|
+
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) });
|
|
252155
252247
|
return lines2;
|
|
252156
252248
|
}
|
|
252157
252249
|
async function refuseWhileConnecting(server, key5, agentId2, name5) {
|
|
@@ -252173,14 +252265,18 @@ function optionValue(args, name5) {
|
|
|
252173
252265
|
}
|
|
252174
252266
|
return void 0;
|
|
252175
252267
|
}
|
|
252268
|
+
function owner5(error65) {
|
|
252269
|
+
return { ...isErrorKind(error65?.kind) && { kind: error65.kind }, ...typeof error65?.reference === "string" && { reference: error65.reference } };
|
|
252270
|
+
}
|
|
252176
252271
|
async function refusal3(response6, server) {
|
|
252177
252272
|
const body8 = await response6.json().catch(() => void 0);
|
|
252273
|
+
if (response6.status === 401) return serverError(response6.status, body8, authError(server, { status: 401, keySent: true }));
|
|
252178
252274
|
const error65 = typeof body8?.error === "object" ? body8.error : { message: typeof body8?.error === "string" ? body8.error : void 0 };
|
|
252179
|
-
if (response6.status === 429) return new AnchaError("USAGE", error65.message ?? "too many commands for this key", { hint: error65.hint ?? retryHint(response6) });
|
|
252275
|
+
if (response6.status === 429) return new AnchaError("USAGE", error65.message ?? "too many commands for this key", { hint: error65.hint ?? retryHint(response6), kind: "retry" });
|
|
252180
252276
|
if (response6.status >= 500) {
|
|
252181
|
-
return new AnchaError("SERVER_UNREACHABLE", `${server} could not run the command: ${error65.message ?? `HTTP ${response6.status}`}`, { hint: "retry in a few seconds" });
|
|
252277
|
+
return new AnchaError("SERVER_UNREACHABLE", `${server} could not run the command: ${error65.message ?? `HTTP ${response6.status}`}`, { hint: "retry in a few seconds", ...owner5(error65) });
|
|
252182
252278
|
}
|
|
252183
|
-
return new AnchaError("USAGE", error65.message ?? `the workspace refused the command (HTTP ${response6.status})`, { hint: error65.hint ?? "run it on this computer with --local" });
|
|
252279
|
+
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) });
|
|
252184
252280
|
}
|
|
252185
252281
|
async function stream(ctx, body8, server) {
|
|
252186
252282
|
const decoder = new TextDecoder();
|
|
@@ -252257,7 +252353,7 @@ async function uploadProject(server, key5, name5, dir2) {
|
|
|
252257
252353
|
const error65 = typeof result.error === "object" && result.error !== null ? result.error : void 0;
|
|
252258
252354
|
if (!response6.ok && typeof error65?.message === "string") {
|
|
252259
252355
|
const hint = typeof error65.hint === "string" ? error65.hint : response6.status === 429 ? retryHint(response6) : void 0;
|
|
252260
|
-
throw new AnchaError(error65.code !== void 0 && isErrorCode(error65.code) ? error65.code : response6.status >= 500 ? "SERVER_UNREACHABLE" : "USAGE", error65.message, { ...hint !== void 0 && { hint } });
|
|
252356
|
+
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) });
|
|
252261
252357
|
}
|
|
252262
252358
|
const message8 = typeof result.error === "string" ? result.error : `HTTP ${response6.status}`;
|
|
252263
252359
|
if (response6.status >= 500) throw new AnchaError("SERVER_UNREACHABLE", `the workspace refused the upload: ${message8}`, { hint: "retry in a few seconds" });
|
|
@@ -253136,7 +253232,7 @@ function sameSeed(left, right) {
|
|
|
253136
253232
|
|
|
253137
253233
|
// backend/src/playgrounds/managed-seed.ts
|
|
253138
253234
|
async function inspectManagedSeed(service, rawOwner) {
|
|
253139
|
-
const
|
|
253235
|
+
const owner6 = seedOwner(rawOwner);
|
|
253140
253236
|
const [agents, worlds2, tests, runs] = await Promise.all([
|
|
253141
253237
|
service.registry.list(),
|
|
253142
253238
|
service.worlds({ includeArchived: true }),
|
|
@@ -253145,11 +253241,11 @@ async function inspectManagedSeed(service, rawOwner) {
|
|
|
253145
253241
|
]);
|
|
253146
253242
|
if ([agents, worlds2, tests, runs].some((result) => result.errors.length)) throw new AnchaError("CONFIG_INVALID", "unreadable workspace objects prevent a safe seed reset");
|
|
253147
253243
|
return {
|
|
253148
|
-
owner:
|
|
253149
|
-
agents: agents.agents.filter((item2) => item2.managedSeed?.owner ===
|
|
253150
|
-
worlds: worlds2.worlds.filter((item2) => item2.managedSeed?.owner ===
|
|
253151
|
-
tests: tests.tests.filter((item2) => item2.managedSeed?.owner ===
|
|
253152
|
-
runs: runs.runs.filter((item2) => item2.managedSeed?.owner ===
|
|
253244
|
+
owner: owner6,
|
|
253245
|
+
agents: agents.agents.filter((item2) => item2.managedSeed?.owner === owner6),
|
|
253246
|
+
worlds: worlds2.worlds.filter((item2) => item2.managedSeed?.owner === owner6),
|
|
253247
|
+
tests: tests.tests.filter((item2) => item2.managedSeed?.owner === owner6),
|
|
253248
|
+
runs: runs.runs.filter((item2) => item2.managedSeed?.owner === owner6)
|
|
253153
253249
|
};
|
|
253154
253250
|
}
|
|
253155
253251
|
async function resetManagedSeed(service, rawOwner) {
|
|
@@ -254198,9 +254294,9 @@ var PlaygroundStore = class {
|
|
|
254198
254294
|
async processOwner() {
|
|
254199
254295
|
return { pid: process.pid, birth: birth(process.pid) };
|
|
254200
254296
|
}
|
|
254201
|
-
processOwnerAlive(
|
|
254202
|
-
if (!
|
|
254203
|
-
return alive(
|
|
254297
|
+
processOwnerAlive(owner6) {
|
|
254298
|
+
if (!owner6 || typeof owner6 !== "object" || !Number.isSafeInteger(owner6.pid) || typeof owner6.birth !== "string" || !owner6.birth) return null;
|
|
254299
|
+
return alive(owner6);
|
|
254204
254300
|
}
|
|
254205
254301
|
async stagedRuns() {
|
|
254206
254302
|
await preflightFiles(this.workspace, [{ relativePath: `${BASE4}/runs/probe.json`, content: "" }]);
|
|
@@ -255329,7 +255425,7 @@ async function startDetached(request2) {
|
|
|
255329
255425
|
state: "failed",
|
|
255330
255426
|
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
255331
255427
|
exitCode: 3,
|
|
255332
|
-
error: { code: "INTERNAL", message: "detached worker startup failed" }
|
|
255428
|
+
error: { code: "INTERNAL", kind: "ours", message: "detached worker startup failed" }
|
|
255333
255429
|
});
|
|
255334
255430
|
throw new AnchaError("INTERNAL", "detached worker startup failed", { cause: error65 });
|
|
255335
255431
|
}
|
|
@@ -255395,13 +255491,11 @@ async function uploadRun(ctx, workspace4, run7) {
|
|
|
255395
255491
|
} catch (error65) {
|
|
255396
255492
|
throw new AnchaError("SERVER_UNREACHABLE", `${workspace4} did not answer the upload`, { hint: `check the network, then ancha runs upload ${run7.runId}`, cause: error65 });
|
|
255397
255493
|
}
|
|
255398
|
-
if (response6.status === 401) throw authError(workspace4, { status: 401, keySent: key5 !== void 0 });
|
|
255399
255494
|
if (!response6.ok) {
|
|
255400
255495
|
const body8 = await response6.json().catch(() => void 0);
|
|
255401
|
-
|
|
255496
|
+
if (response6.status === 401) throw serverError(response6.status, body8, authError(workspace4, { status: 401, keySent: key5 !== void 0 }));
|
|
255402
255497
|
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" });
|
|
255403
|
-
|
|
255404
|
-
throw new AnchaError(code5, error65.message ?? `the upload was refused (HTTP ${response6.status})`, { hint: error65.hint ?? `ancha runs upload ${run7.runId}` });
|
|
255498
|
+
throw serverError(response6.status, body8, { message: `the upload was refused (HTTP ${response6.status})`, hint: `ancha runs upload ${run7.runId}` });
|
|
255405
255499
|
}
|
|
255406
255500
|
const answer = await response6.json().catch(() => void 0);
|
|
255407
255501
|
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 } };
|
|
@@ -255960,8 +256054,10 @@ next: ancha wait ${job.id}`);
|
|
|
255960
256054
|
return followToEnd(ctx, ws, job.id, signal);
|
|
255961
256055
|
}
|
|
255962
256056
|
async function connectOnCloud(ctx, ws, check4, signal) {
|
|
256057
|
+
const key5 = submissionKey(check4.idempotencyKey);
|
|
255963
256058
|
const { bundle } = await cloudBundle(ctx, { kind: "connect", tests: [], options: { attempts: 1, concurrency: 1, seed: null, strict: false, minPassRate: check4.minPassRate, allowUnwrapped: [], agentCommand: check4.agentCommand } });
|
|
255964
|
-
const submitted = await submit2(ws, bundle,
|
|
256059
|
+
const submitted = await submit2(ws, bundle, key5, signal, {});
|
|
256060
|
+
if (submitted.replayed && check4.idempotencyKey !== void 0) ctx.out.info(`${submitted.job.id}: already submitted with this --idempotency-key`);
|
|
255965
256061
|
const logTail3 = [];
|
|
255966
256062
|
const agentLogTail = [];
|
|
255967
256063
|
await followJob(ws, submitted.job.id, { signal, onEvent: (event3) => {
|
|
@@ -256450,7 +256546,7 @@ async function replayRun(ctx, input5, runId2, detach) {
|
|
|
256450
256546
|
}
|
|
256451
256547
|
const summary = await loadRunSummary(ctx.io.cwd, runId2, input5.out);
|
|
256452
256548
|
ctx.exitCode = state3.exitCode ?? 3;
|
|
256453
|
-
if (state3.error) ctx.out.error(new AnchaError(state3.error.code, state3.error.message));
|
|
256549
|
+
if (state3.error) ctx.out.error(new AnchaError(state3.error.code, state3.error.message, state3.error));
|
|
256454
256550
|
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 } });
|
|
256455
256551
|
else ctx.out.result(summary, () => `replayed run ${runId2} (same --idempotency-key)
|
|
256456
256552
|
|
|
@@ -256492,7 +256588,7 @@ hint: ${json40.hint}` : ""}`);
|
|
|
256492
256588
|
}
|
|
256493
256589
|
function keptUpload(upload6, runId2) {
|
|
256494
256590
|
if (!("error" in upload6)) return upload6;
|
|
256495
|
-
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 } };
|
|
256591
|
+
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 } };
|
|
256496
256592
|
}
|
|
256497
256593
|
async function executePreparedRun(ctx, input5, initial, ready3) {
|
|
256498
256594
|
const writer = stateWriter(input5.outDir, initial);
|
|
@@ -256552,7 +256648,7 @@ async function executePreparedRun(ctx, input5, initial, ready3) {
|
|
|
256552
256648
|
await writer.finish({
|
|
256553
256649
|
state: interrupted2 ? "interrupted" : "failed",
|
|
256554
256650
|
exitCode: exitCodeFor(code5),
|
|
256555
|
-
error: { code: code5, message: interrupted2 ? "run interrupted" : `run failed (${code5}); partial artifacts may be available` }
|
|
256651
|
+
error: { kind: toErrorJson(error65).kind, code: code5, message: interrupted2 ? "run interrupted" : `run failed (${code5}); partial artifacts may be available` }
|
|
256556
256652
|
});
|
|
256557
256653
|
throw error65;
|
|
256558
256654
|
}
|
|
@@ -256624,9 +256720,9 @@ async function execute4(ctx, service, start2) {
|
|
|
256624
256720
|
function registerPlayground(program2, ctx) {
|
|
256625
256721
|
const command = program2.command("playground").description("choose tools and test agent tasks in fresh independent playgrounds");
|
|
256626
256722
|
const seed44 = command.command("seed").description("inspect or reset objects with explicit creation provenance");
|
|
256627
|
-
for (const action of ["inspect", "reset"]) seed44.command(action).argument("<owner>").action(async (
|
|
256723
|
+
for (const action of ["inspect", "reset"]) seed44.command(action).argument("<owner>").action(async (owner6) => {
|
|
256628
256724
|
const base6 = ctx.io.env.ANCHA_CONSOLE_URL;
|
|
256629
|
-
const result = base6 ? await (await consoleApi(base6)).call(`/api/managed-seeds/${encodeURIComponent(
|
|
256725
|
+
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));
|
|
256630
256726
|
const output2 = { workspace: base6 ?? `local:${ctx.io.cwd}`, ...result };
|
|
256631
256727
|
ctx.out.result(output2, () => JSON.stringify(output2, null, 2));
|
|
256632
256728
|
});
|
|
@@ -256924,19 +257020,36 @@ async function taskCheck(ctx, agent) {
|
|
|
256924
257020
|
hint: "or run ancha init, which adds it"
|
|
256925
257021
|
};
|
|
256926
257022
|
}
|
|
257023
|
+
async function uploadSecrets(ws, names8) {
|
|
257024
|
+
const wanted = [...new Set(names8)];
|
|
257025
|
+
if (!wanted.length) return { name: "secrets", status: "pass", message: "the agent passes no workspace secrets" };
|
|
257026
|
+
const saved = await getSecrets(ws), missing10 = wanted.filter((name5) => !saved.names.includes(name5));
|
|
257027
|
+
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") });
|
|
257028
|
+
let warning = false;
|
|
257029
|
+
const details = wanted.flatMap((name5) => {
|
|
257030
|
+
const secret = saved.secrets?.find((item2) => item2.name === name5), check4 = secret?.check;
|
|
257031
|
+
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";
|
|
257032
|
+
const notes7 = (secret?.issues ?? []).filter((issue9) => issue9.level !== "info" && issue9.message);
|
|
257033
|
+
if (notes7.length) warning = true;
|
|
257034
|
+
return [`${name5}${secret?.preview ? ` \xB7 ${secret.preview}` : ""} \xB7 ${status6}`, ...notes7.map((issue9) => ` ${issue9.message}${issue9.fix ? ` ${issue9.fix}` : ""}`)];
|
|
257035
|
+
});
|
|
257036
|
+
return { name: "secrets", status: warning ? "warning" : "pass", message: `${wanted.length} workspace secret${wanted.length === 1 ? "" : "s"} saved`, details };
|
|
257037
|
+
}
|
|
256927
257038
|
async function uploadAgent(ctx, opts, command = "ancha agent upload") {
|
|
256928
257039
|
if (opts.agent === false) throw new AnchaError("USAGE", `${command} checks the agent in a cloud machine`, { hint: "leave out --no-agent" });
|
|
256929
257040
|
const config12 = await ctx.loadConfig();
|
|
256930
257041
|
const refusal4 = cloudAgentRefusal(config12, typeof opts.agent === "string" ? opts.agent : void 0);
|
|
256931
257042
|
if (refusal4) throw refusal4;
|
|
256932
257043
|
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" });
|
|
257044
|
+
const secrets2 = await uploadSecrets(ws, [...config12.agent?.passEnv ?? [], ...config12.agent?.execution?.mode === "container" ? config12.agent.execution.env : []]);
|
|
256933
257045
|
const configured = config12.agent?.mode === "endpoint" ? void 0 : config12.agent;
|
|
256934
257046
|
const task2 = await taskCheck(ctx, typeof opts.agent === "string" ? { command: opts.agent, ...configured?.env && { env: configured.env } } : configured);
|
|
256935
257047
|
if (task2?.status === "warning") ctx.out.info(`${task2.message}: ${task2.fix} (${task2.hint})`);
|
|
256936
|
-
const { detail: detail3, agent, agentAction: agentAction2, bundle, logTail: logTail3, url: url4 } = await interruptible(ctx, (signal) => connectOnCloud(ctx, ws, { agentCommand: typeof opts.agent === "string" ? opts.agent : null, minPassRate: config12.min_pass_rate }, signal));
|
|
257048
|
+
const { detail: detail3, agent, agentAction: agentAction2, bundle, logTail: logTail3, url: url4 } = await interruptible(ctx, (signal) => connectOnCloud(ctx, ws, { agentCommand: typeof opts.agent === "string" ? opts.agent : null, minPassRate: config12.min_pass_rate, ...opts.idempotencyKey !== void 0 && { idempotencyKey: opts.idempotencyKey } }, signal));
|
|
256937
257049
|
const checks2 = [
|
|
256938
257050
|
{ name: "workspace", status: "pass", message: `running in the workspace ${ws.server}` },
|
|
256939
257051
|
{ name: "bundle", status: "pass", message: `${bundle.files} files, ${(bundle.bytes / 1024 / 1024).toFixed(1)} MiB; project ${bundle.projectHash.slice(0, 12)}` },
|
|
257052
|
+
secrets2,
|
|
256940
257053
|
...task2 ? [task2] : []
|
|
256941
257054
|
];
|
|
256942
257055
|
const reason2 = detail3.connection?.probe?.reason;
|
|
@@ -256945,7 +257058,7 @@ async function uploadAgent(ctx, opts, command = "ancha agent upload") {
|
|
|
256945
257058
|
checks2.push(...connectionChecks);
|
|
256946
257059
|
const onboarding = state3 === "failed" ? void 0 : await getOnboarding(ws).then((value6) => nextFromHere(ctx, value6)).then((next3) => human(next3.at(-1)), () => void 0);
|
|
256947
257060
|
const next2 = state3 === "failed" ? ["ancha agent upload"] : [onboarding === void 0 || /doctor --on cloud|agent upload/.test(onboarding) ? "ancha run" : onboarding];
|
|
256948
|
-
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 };
|
|
257061
|
+
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 };
|
|
256949
257062
|
}
|
|
256950
257063
|
function connectionReport(detail3, logTail3, readsAnswer = false) {
|
|
256951
257064
|
const checks2 = [];
|
|
@@ -256984,7 +257097,7 @@ function connectionReport(detail3, logTail3, readsAnswer = false) {
|
|
|
256984
257097
|
} else {
|
|
256985
257098
|
exitCode = detail3.job.exitCode !== null && detail3.job.exitCode !== 0 ? detail3.job.exitCode : 3;
|
|
256986
257099
|
const started = evidence3?.install.passed && evidence3.probe !== null && evidence3.probe.startedAt !== null && evidence3.probe.durationMs !== void 0 && evidence3.probe.kind !== "http";
|
|
256987
|
-
if (started) {
|
|
257100
|
+
if (started && detail3.job.error?.kind !== "ours") {
|
|
256988
257101
|
const ran = evidence3.probe;
|
|
256989
257102
|
const parsedTextTask = ran.reason?.code === "crashed" && ran.reason.message.includes("connection check's plain-text task");
|
|
256990
257103
|
fix = ran.fix === void 0 ? parsedTextTask ? ran.reason?.fix : void 0 : fixLine(ran.fix);
|
|
@@ -257006,6 +257119,8 @@ function connectionReport(detail3, logTail3, readsAnswer = false) {
|
|
|
257006
257119
|
checks2.push({
|
|
257007
257120
|
name: "agent",
|
|
257008
257121
|
status: "fail",
|
|
257122
|
+
...error65?.kind && { kind: error65.kind },
|
|
257123
|
+
...error65?.reference && { reference: error65.reference },
|
|
257009
257124
|
message: `the upload stopped at ${step3}: ${error65?.message ?? `the job ${detail3.job.state}`}`,
|
|
257010
257125
|
hint: human(error65?.hint ?? `${logTail3.length > 0 ? "the end of its log is above; " : ""}ancha runs show ${detail3.job.id} lists each step`),
|
|
257011
257126
|
...logTail3.length > 0 && { logTail: logTail3 }
|
|
@@ -257025,7 +257140,10 @@ function connectionReport(detail3, logTail3, readsAnswer = false) {
|
|
|
257025
257140
|
hint: "name them with ancha init --tools <tools> or the tests' twins"
|
|
257026
257141
|
});
|
|
257027
257142
|
}
|
|
257028
|
-
for (const check4 of checks2)
|
|
257143
|
+
for (const check4 of checks2) {
|
|
257144
|
+
if (check4.logTail) check4.logTail = connectionLogTail(check4.logTail);
|
|
257145
|
+
if (check4.status === "fail") Object.assign(check4, { kind: detail3.job.error?.kind ?? reason2?.kind ?? "fix", ...detail3.job.error?.reference && { reference: detail3.job.error.reference } });
|
|
257146
|
+
}
|
|
257029
257147
|
return { checks: checks2, state: state3, exitCode, evidence: evidence3 };
|
|
257030
257148
|
}
|
|
257031
257149
|
var doctorOnCloud = (ctx, opts) => uploadAgent(ctx, opts, "ancha doctor --on cloud");
|
|
@@ -257054,12 +257172,12 @@ function renderUpload(report10) {
|
|
|
257054
257172
|
for (const line2 of check4.details ?? []) lines2.push(` ${line2}`);
|
|
257055
257173
|
for (const line2 of check4.logTail ?? []) lines2.push(` ${line2}`);
|
|
257056
257174
|
if (check4.fix !== void 0 && check4.status === "warning") lines2.push(` ${check4.fix}${check4.hint ? ` (${check4.hint})` : ""}`);
|
|
257057
|
-
else if (check4.hint && check4.fix === void 0) lines2.push(` ${check4.hint}`);
|
|
257175
|
+
else if (check4.hint && check4.fix === void 0) lines2.push(` ${check4.kind ? `${check4.kind}: ` : ""}${check4.hint}${check4.reference ? ` (reference ${check4.reference})` : ""}`);
|
|
257058
257176
|
}
|
|
257059
257177
|
const failed2 = report10.checks.find((check4) => check4.status === "fail");
|
|
257060
257178
|
if (report10.ok && report10.cloud) lines2.push(`Agent uploaded: ${report10.cloud.url}`);
|
|
257061
257179
|
else if (report10.cloud) lines2.push(`Upload: ${report10.cloud.url}`);
|
|
257062
|
-
if (failed2?.fix !== void 0) lines2.push(
|
|
257180
|
+
if (failed2?.fix !== void 0) lines2.push(`${failed2.kind ?? "fix"}: ${failed2.fix}`, `then: ${report10.next[0]}`);
|
|
257063
257181
|
else if (report10.next.length > 0) lines2.push(`next: ${report10.next[0]}`);
|
|
257064
257182
|
return lines2.join("\n");
|
|
257065
257183
|
}
|
|
@@ -257332,7 +257450,7 @@ function loginRunLine(ctx) {
|
|
|
257332
257450
|
const apiKey = Boolean(ctx.io.env.ANCHA_API_KEY);
|
|
257333
257451
|
return apiKey || inCi(ctx.io.env) ? `${apiKey ? "With ANCHA_API_KEY set" : "In CI"}, ancha run runs where ancha.yaml says; ancha run --on cloud runs in this workspace.` : "ancha run runs your tests in this workspace; ancha run --on local runs them on this computer.";
|
|
257334
257452
|
}
|
|
257335
|
-
async function json38(url4, init = {}, fetchImpl = fetch) {
|
|
257453
|
+
async function json38(url4, init = {}, fetchImpl = fetch, transient = false) {
|
|
257336
257454
|
let res;
|
|
257337
257455
|
let text31;
|
|
257338
257456
|
try {
|
|
@@ -257342,10 +257460,16 @@ async function json38(url4, init = {}, fetchImpl = fetch) {
|
|
|
257342
257460
|
});
|
|
257343
257461
|
throw authError(new URL(url4).origin, { status: 401, keySent: Boolean(new Headers(init.headers).get("authorization")) });
|
|
257344
257462
|
}
|
|
257463
|
+
if (transient && [429, 502, 503, 504].includes(res.status)) {
|
|
257464
|
+
void res.body?.cancel().catch(() => {
|
|
257465
|
+
});
|
|
257466
|
+
throw Object.assign(new AnchaError("SERVER_UNREACHABLE", `cannot reach ${new URL(url4).origin}`, { hint: "run ancha login again" }), { retryAfter: res.headers.get("retry-after") });
|
|
257467
|
+
}
|
|
257345
257468
|
text31 = await res.text();
|
|
257346
257469
|
} catch (e) {
|
|
257347
257470
|
if (e instanceof AnchaError) throw e;
|
|
257348
|
-
|
|
257471
|
+
const error65 = new AnchaError("SERVER_UNREACHABLE", `cannot reach ${new URL(url4).origin}`, { hint: "check the address and your network, then run ancha login again", cause: e });
|
|
257472
|
+
throw transient ? Object.assign(error65, { retryAfter: null }) : error65;
|
|
257349
257473
|
}
|
|
257350
257474
|
let body8;
|
|
257351
257475
|
try {
|
|
@@ -257355,7 +257479,14 @@ async function json38(url4, init = {}, fetchImpl = fetch) {
|
|
|
257355
257479
|
}
|
|
257356
257480
|
if (!res.ok) {
|
|
257357
257481
|
const message8 = body8 && typeof body8 === "object" && typeof body8.error === "string" ? body8.error : `HTTP ${res.status}`;
|
|
257358
|
-
throw new AnchaError("INTERNAL", `${new URL(url4).origin}: ${message8}`);
|
|
257482
|
+
if (!transient || res.status === 403) throw new AnchaError("INTERNAL", `${new URL(url4).origin}: ${message8}`);
|
|
257483
|
+
const contract = body8 && typeof body8 === "object" && typeof body8.error === "object" ? body8 : void 0;
|
|
257484
|
+
const error65 = serverError(res.status, contract, { message: `${new URL(url4).origin}: ${message8}`, code: "INTERNAL" });
|
|
257485
|
+
if (res.status === 500) {
|
|
257486
|
+
error65.code = "INTERNAL";
|
|
257487
|
+
error65.kind = "ours";
|
|
257488
|
+
}
|
|
257489
|
+
throw error65;
|
|
257359
257490
|
}
|
|
257360
257491
|
if (body8 === void 0) throw new AnchaError("INTERNAL", `${new URL(url4).origin} sent a malformed response`);
|
|
257361
257492
|
return body8;
|
|
@@ -257373,12 +257504,34 @@ function openBrowser(url4) {
|
|
|
257373
257504
|
}
|
|
257374
257505
|
}
|
|
257375
257506
|
var sleep12 = (ms2, signal) => new Promise((resolve63) => {
|
|
257376
|
-
const
|
|
257377
|
-
signal?.addEventListener("abort", () => {
|
|
257507
|
+
const done = () => {
|
|
257378
257508
|
clearTimeout(timer);
|
|
257509
|
+
signal?.removeEventListener("abort", done);
|
|
257379
257510
|
resolve63();
|
|
257380
|
-
}
|
|
257511
|
+
};
|
|
257512
|
+
const timer = setTimeout(done, ms2);
|
|
257513
|
+
if (signal?.aborted) done();
|
|
257514
|
+
else signal?.addEventListener("abort", done, { once: true });
|
|
257381
257515
|
});
|
|
257516
|
+
async function loginJson(url4, init, fetchImpl, signal, deadline3 = Infinity) {
|
|
257517
|
+
for (let failures = 0; ; failures++) {
|
|
257518
|
+
if (signal?.aborted) throw new AnchaError("USAGE", "login interrupted");
|
|
257519
|
+
try {
|
|
257520
|
+
const timeout = AbortSignal.timeout(Math.max(1, Math.min(2e4, deadline3 > Date.now() ? deadline3 - Date.now() : 2e4)));
|
|
257521
|
+
return await json38(url4, { ...init, signal: signal ? AbortSignal.any([signal, timeout]) : timeout }, fetchImpl, true);
|
|
257522
|
+
} catch (error65) {
|
|
257523
|
+
if (signal?.aborted) throw new AnchaError("USAGE", "login interrupted");
|
|
257524
|
+
if (!(error65 instanceof AnchaError) || !("retryAfter" in error65)) throw error65;
|
|
257525
|
+
const unavailable3 = () => new AnchaError("SERVER_UNREACHABLE", error65.message, { kind: "retry", hint: "run ancha login again", cause: error65 });
|
|
257526
|
+
if (failures >= 5 || Date.now() >= deadline3) throw unavailable3();
|
|
257527
|
+
const after = error65.retryAfter;
|
|
257528
|
+
const delay = after && /^\d+(?:\.\d+)?$/.test(after.trim()) ? Number(after) * 1e3 : after ? Date.parse(after) - Date.now() : NaN;
|
|
257529
|
+
await sleep12(Math.min(deadline3 - Date.now(), Number.isFinite(delay) ? Math.max(0, Math.min(3e4, delay)) : 4e3 + Math.random() * 2e3), signal);
|
|
257530
|
+
if (Date.now() >= deadline3) throw unavailable3();
|
|
257531
|
+
}
|
|
257532
|
+
}
|
|
257533
|
+
}
|
|
257534
|
+
var SAVE_REASONS = { EACCES: "permission denied", EPERM: "operation not permitted", EROFS: "read-only file system", ENOSPC: "no space left on device", EISDIR: "is a directory", ENOTDIR: "not a directory" };
|
|
257382
257535
|
var RESUME_HINT = "If this command stops before you approve, run ancha login again: it finishes this sign-in.";
|
|
257383
257536
|
var pendingPath = (env2) => {
|
|
257384
257537
|
const path9 = credentialsPath(env2);
|
|
@@ -257426,10 +257579,10 @@ function registerLogin(program2, ctx, deps = {}) {
|
|
|
257426
257579
|
}
|
|
257427
257580
|
const env2 = ctx.io.env, signal = ctx.io.abort;
|
|
257428
257581
|
if (!credentialsPath(env2)) throw new AnchaError("USAGE", "set HOME or ANCHA_CREDENTIALS_FILE to save a sign-in");
|
|
257429
|
-
const poll = (deviceCode) =>
|
|
257582
|
+
const poll = (deviceCode, deadline4) => loginJson(`${base6}/cli/poll?device_code=${encodeURIComponent(deviceCode)}`, {}, deps.fetch, signal, deadline4);
|
|
257430
257583
|
let pending = await readPending(env2, base6), resumed = false;
|
|
257431
257584
|
if (pending) {
|
|
257432
|
-
const first2 = await poll(pending.deviceCode);
|
|
257585
|
+
const first2 = await poll(pending.deviceCode, Date.parse(pending.expiresAt));
|
|
257433
257586
|
if (first2.status === "approved") return finish2(first2, pending.deviceCode);
|
|
257434
257587
|
if (first2.status === "pending" && Date.parse(pending.expiresAt) - Date.now() > 15e3) resumed = true;
|
|
257435
257588
|
else {
|
|
@@ -257439,7 +257592,7 @@ function registerLogin(program2, ctx, deps = {}) {
|
|
|
257439
257592
|
}
|
|
257440
257593
|
let saved = resumed;
|
|
257441
257594
|
if (!pending) {
|
|
257442
|
-
const start2 = await
|
|
257595
|
+
const start2 = await loginJson(`${base6}/cli/device`, { method: "POST", body: JSON.stringify({ name: hostname4() }) }, deps.fetch, signal);
|
|
257443
257596
|
pending = { version: 1, server: base6, deviceCode: start2.device_code, userCode: start2.user_code, verificationUrl: start2.verification_url, interval: start2.interval, window: start2.expires_in, expiresAt: new Date(Date.now() + start2.expires_in * 1e3).toISOString() };
|
|
257444
257597
|
saved = await writePending(env2, pending);
|
|
257445
257598
|
}
|
|
@@ -257453,9 +257606,9 @@ function registerLogin(program2, ctx, deps = {}) {
|
|
|
257453
257606
|
const deadline3 = Date.parse(pending.expiresAt);
|
|
257454
257607
|
const interval = Math.max(2, Math.min(15, pending.interval || 3)) * 1e3;
|
|
257455
257608
|
while (Date.now() < deadline3 && !signal?.aborted) {
|
|
257456
|
-
await sleep12(interval, signal);
|
|
257457
|
-
if (signal?.aborted) break;
|
|
257458
|
-
const result = await poll(pending.deviceCode);
|
|
257609
|
+
await sleep12(Math.min(interval, deadline3 - Date.now()), signal);
|
|
257610
|
+
if (signal?.aborted || Date.now() >= deadline3) break;
|
|
257611
|
+
const result = await poll(pending.deviceCode, Date.parse(pending.expiresAt));
|
|
257459
257612
|
if (result.status === "pending") continue;
|
|
257460
257613
|
if (result.status === "denied") {
|
|
257461
257614
|
await dropPending(env2, pending.deviceCode);
|
|
@@ -257474,10 +257627,17 @@ function registerLogin(program2, ctx, deps = {}) {
|
|
|
257474
257627
|
throw new AnchaError("INTERNAL", `${base6} approved the sign-in without a key`);
|
|
257475
257628
|
}
|
|
257476
257629
|
const serverUrl3 = normalizeServerUrl(approved.serverUrl);
|
|
257477
|
-
|
|
257478
|
-
|
|
257479
|
-
|
|
257480
|
-
|
|
257630
|
+
let path9;
|
|
257631
|
+
try {
|
|
257632
|
+
const file3 = await readCredentials(env2);
|
|
257633
|
+
file3.servers[serverUrl3] = { apiKey: approved.apiKey, ...approved.email && { email: approved.email }, savedAt: (/* @__PURE__ */ new Date()).toISOString(), minted: "device" };
|
|
257634
|
+
file3.default = serverUrl3;
|
|
257635
|
+
path9 = await writeCredentials(file3, env2);
|
|
257636
|
+
} catch (error65) {
|
|
257637
|
+
const reason2 = SAVE_REASONS[error65.code ?? ""];
|
|
257638
|
+
if (!reason2) throw error65;
|
|
257639
|
+
throw new AnchaError("CONFIG_INVALID", `cannot save the sign-in to ${credentialsPath(env2)}: ${reason2}`, { kind: "fix", hint: "make the folder writable, or set ANCHA_CREDENTIALS_FILE to a file you can write", cause: error65 });
|
|
257640
|
+
}
|
|
257481
257641
|
await dropPending(env2, deviceCode);
|
|
257482
257642
|
let onboarding = null, unread2;
|
|
257483
257643
|
try {
|
|
@@ -258210,7 +258370,7 @@ ${renderReplay(value6)}`);
|
|
|
258210
258370
|
await writer.finish({
|
|
258211
258371
|
state: interrupted2 ? "interrupted" : "failed",
|
|
258212
258372
|
exitCode: exitCodeFor(code5),
|
|
258213
|
-
error: { code: code5, message: interrupted2 ? "run interrupted" : `run failed (${code5}); partial artifacts may be available` }
|
|
258373
|
+
error: { kind: toErrorJson(error65).kind, code: code5, message: interrupted2 ? "run interrupted" : `run failed (${code5}); partial artifacts may be available` }
|
|
258214
258374
|
});
|
|
258215
258375
|
throw error65;
|
|
258216
258376
|
}
|
|
@@ -258263,7 +258423,7 @@ ${state3.error.message}` : ""}`);
|
|
|
258263
258423
|
const state3 = await readRunState(resolve42(ctx.io.cwd, opts.out ?? DEFAULT_RUNS_DIR), id15);
|
|
258264
258424
|
if (terminal(state3)) {
|
|
258265
258425
|
if (state3.state === "finished") {
|
|
258266
|
-
if (state3.error) ctx.out.error(new AnchaError(state3.error.code, state3.error.message));
|
|
258426
|
+
if (state3.error) ctx.out.error(new AnchaError(state3.error.code, state3.error.message, state3.error));
|
|
258267
258427
|
emitFinished(ctx, await loadRunSummary(ctx.io.cwd, id15, opts.out), opts.out, state3.upload);
|
|
258268
258428
|
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 ? `
|
|
258269
258429
|
hint: ${state3.upload.error.hint}` : ""}`);
|
|
@@ -258310,7 +258470,7 @@ hint: ${state3.upload.error.hint}` : ""}`);
|
|
|
258310
258470
|
printed = complete.length;
|
|
258311
258471
|
if (!opts.follow || terminal(state3)) {
|
|
258312
258472
|
if (printed === 0) ctx.out.result({ runId: id15, events: [], message: "No events were recorded for this run." }, () => "No events were recorded for this run.");
|
|
258313
|
-
if (terminal(state3) && state3.exitCode === void 0 && state3.error) ctx.exitCode = ctx.out.error(new AnchaError(state3.error.code, state3.error.message));
|
|
258473
|
+
if (terminal(state3) && state3.exitCode === void 0 && state3.error) ctx.exitCode = ctx.out.error(new AnchaError(state3.error.code, state3.error.message, state3.error));
|
|
258314
258474
|
if (opts.follow) ctx.exitCode = state3.exitCode ?? 3;
|
|
258315
258475
|
return;
|
|
258316
258476
|
}
|
|
@@ -258469,7 +258629,7 @@ init_scenes();
|
|
|
258469
258629
|
|
|
258470
258630
|
// packages/cli/src/kit/init.ts
|
|
258471
258631
|
import { constants as constants12 } from "node:fs";
|
|
258472
|
-
import { lstat as lstat10, mkdir as mkdir26, open as
|
|
258632
|
+
import { lstat as lstat10, mkdir as mkdir26, open as fsOpen, readFile as readFile43, rm as rm13, writeFile as fsWriteFile } from "node:fs/promises";
|
|
258473
258633
|
import { join as join58 } from "node:path";
|
|
258474
258634
|
import { Writable } from "node:stream";
|
|
258475
258635
|
var import_yaml18 = __toESM(require_dist(), 1);
|
|
@@ -260201,9 +260361,9 @@ function normalizeDraft(draft2, world5) {
|
|
|
260201
260361
|
const fact2 = (value6) => {
|
|
260202
260362
|
if (typeof value6 !== "string") return value6;
|
|
260203
260363
|
const dot = value6.lastIndexOf(".");
|
|
260204
|
-
const
|
|
260364
|
+
const owner6 = dot < 0 ? void 0 : personOf(value6.slice(0, dot));
|
|
260205
260365
|
const id16 = canon(dot < 0 ? value6 : value6.slice(dot + 1));
|
|
260206
|
-
const owners =
|
|
260366
|
+
const owners = owner6 ? [owner6] : people4;
|
|
260207
260367
|
const found = owners.flatMap((candidate) => (candidate.knows ?? []).filter((item2) => canon(item2.id) === id16).map((item2) => `${candidate.ref}.${item2.id}`));
|
|
260208
260368
|
return found.length === 1 ? found[0] : value6;
|
|
260209
260369
|
};
|
|
@@ -260467,6 +260627,30 @@ ${doc.markdown}` : doc.markdown);
|
|
|
260467
260627
|
|
|
260468
260628
|
// packages/cli/src/kit/init.ts
|
|
260469
260629
|
var toolName = (twin) => TOOL_DESCRIPTORS.find((tool) => tool.name === twin)?.title ?? twin;
|
|
260630
|
+
var WRITE_REFUSALS = {
|
|
260631
|
+
EACCES: "permission denied",
|
|
260632
|
+
EPERM: "not permitted",
|
|
260633
|
+
EROFS: "the file system is read-only",
|
|
260634
|
+
ENOSPC: "the disk is full",
|
|
260635
|
+
EDQUOT: "the disk quota is used up",
|
|
260636
|
+
ENOTDIR: "part of the path is a file, not a folder",
|
|
260637
|
+
EISDIR: "it is a folder"
|
|
260638
|
+
};
|
|
260639
|
+
function initWriteError(error65, cwd) {
|
|
260640
|
+
const cause = error65;
|
|
260641
|
+
if (error65 instanceof AnchaError || !cause?.code || !Object.hasOwn(WRITE_REFUSALS, cause.code) || !/^(open|mkdir|write|writev|ftruncate|rename|unlink|rmdir|copyfile)$/.test(cause.syscall ?? "")) return error65;
|
|
260642
|
+
return new AnchaError("CONFIG_INVALID", `cannot write ${cause.path ?? cwd}: ${WRITE_REFUSALS[cause.code]}`, { kind: "fix", hint: "run ancha init in a folder you can write", cause });
|
|
260643
|
+
}
|
|
260644
|
+
async function writing(path9, fn) {
|
|
260645
|
+
try {
|
|
260646
|
+
return await fn();
|
|
260647
|
+
} catch (error65) {
|
|
260648
|
+
throw initWriteError(error65, path9);
|
|
260649
|
+
}
|
|
260650
|
+
}
|
|
260651
|
+
var applyScaffold2 = (cwd, files2) => writing(cwd, () => applyScaffold(cwd, files2));
|
|
260652
|
+
var open11 = (path9, flags) => writing(path9, () => fsOpen(path9, flags));
|
|
260653
|
+
var writeFile27 = (path9, content2) => writing(path9, () => fsWriteFile(path9, content2));
|
|
260470
260654
|
function step2(ctx) {
|
|
260471
260655
|
const io = { ...ctx.io, stdout: new Writable({ write(_chunk, _encoding, done) {
|
|
260472
260656
|
done();
|
|
@@ -260491,7 +260675,7 @@ Read \`ancha docs tools\` for function checks and registration.
|
|
|
260491
260675
|
original2 = await readFile43(target6, "utf8");
|
|
260492
260676
|
} catch (error65) {
|
|
260493
260677
|
if (error65.code !== "ENOENT") throw error65;
|
|
260494
|
-
const result = await
|
|
260678
|
+
const result = await applyScaffold2(cwd, [{ relativePath: "AGENTS.md", content: managed }]);
|
|
260495
260679
|
return result.created.length ? "created" : "preserved";
|
|
260496
260680
|
}
|
|
260497
260681
|
if (original2.includes(BEGIN) || original2.includes(END)) {
|
|
@@ -260504,7 +260688,7 @@ Read \`ancha docs tools\` for function checks and registration.
|
|
|
260504
260688
|
await preflightFiles(cwd, [{ relativePath: "AGENTS.md", content: "" }]);
|
|
260505
260689
|
const handle31 = await open11(target6, constants12.O_WRONLY | constants12.O_APPEND | constants12.O_NOFOLLOW);
|
|
260506
260690
|
try {
|
|
260507
|
-
await handle31.writeFile(`${original2.endsWith("\n") ? "\n" : "\n\n"}${managed}`);
|
|
260691
|
+
await writing(target6, () => handle31.writeFile(`${original2.endsWith("\n") ? "\n" : "\n\n"}${managed}`));
|
|
260508
260692
|
} finally {
|
|
260509
260693
|
await handle31.close();
|
|
260510
260694
|
}
|
|
@@ -260520,15 +260704,15 @@ async function ignoreAnchaDirectory(cwd) {
|
|
|
260520
260704
|
original2 = await readFile43(target6, "utf8");
|
|
260521
260705
|
} catch (error65) {
|
|
260522
260706
|
if (error65.code !== "ENOENT") throw error65;
|
|
260523
|
-
const result = await
|
|
260707
|
+
const result = await applyScaffold2(cwd, [{ relativePath: ".gitignore", content: ".ancha/\n" }]);
|
|
260524
260708
|
return result.created.length ? "created" : "preserved";
|
|
260525
260709
|
}
|
|
260526
260710
|
if (ignoresAncha(original2)) return "preserved";
|
|
260527
260711
|
await preflightFiles(cwd, [{ relativePath: ".gitignore", content: "" }]);
|
|
260528
260712
|
const handle31 = await open11(target6, constants12.O_WRONLY | constants12.O_APPEND | constants12.O_NOFOLLOW);
|
|
260529
260713
|
try {
|
|
260530
|
-
await handle31.writeFile(`${original2 === "" || original2.endsWith("\n") ? "" : "\n"}.ancha/
|
|
260531
|
-
`);
|
|
260714
|
+
await writing(target6, () => handle31.writeFile(`${original2 === "" || original2.endsWith("\n") ? "" : "\n"}.ancha/
|
|
260715
|
+
`));
|
|
260532
260716
|
} finally {
|
|
260533
260717
|
await handle31.close();
|
|
260534
260718
|
}
|
|
@@ -260676,7 +260860,7 @@ async function rewrite(cwd, relativePath, content2) {
|
|
|
260676
260860
|
await preflightFiles(cwd, [{ relativePath, content: "" }]);
|
|
260677
260861
|
const handle31 = await open11(join58(cwd, relativePath), constants12.O_WRONLY | constants12.O_TRUNC | constants12.O_NOFOLLOW);
|
|
260678
260862
|
try {
|
|
260679
|
-
await handle31.writeFile(content2);
|
|
260863
|
+
await writing(join58(cwd, relativePath), () => handle31.writeFile(content2));
|
|
260680
260864
|
} finally {
|
|
260681
260865
|
await handle31.close();
|
|
260682
260866
|
}
|
|
@@ -260811,7 +260995,7 @@ async function wireExistingConfig(cwd, fillMissing) {
|
|
|
260811
260995
|
await preflightFiles(cwd, [{ relativePath: "ancha.yaml", content: "" }]);
|
|
260812
260996
|
const handle31 = await open11(target6, constants12.O_WRONLY | constants12.O_TRUNC | constants12.O_NOFOLLOW);
|
|
260813
260997
|
try {
|
|
260814
|
-
await handle31.writeFile(next2);
|
|
260998
|
+
await writing(target6, () => handle31.writeFile(next2));
|
|
260815
260999
|
} finally {
|
|
260816
261000
|
await handle31.close();
|
|
260817
261001
|
}
|
|
@@ -260889,7 +261073,7 @@ min_pass_rate: 1
|
|
|
260889
261073
|
await rewrite(ctx.io.cwd, file3.relativePath, file3.content);
|
|
260890
261074
|
updated.push(file3.relativePath);
|
|
260891
261075
|
}
|
|
260892
|
-
const result = await
|
|
261076
|
+
const result = await applyScaffold2(ctx.io.cwd, files2.filter((file3) => !rewritten.includes(file3)));
|
|
260893
261077
|
const agents = await installAgents(ctx.io.cwd, detection.functionTools);
|
|
260894
261078
|
let savedCommand;
|
|
260895
261079
|
if (configured) {
|
|
@@ -260919,9 +261103,9 @@ min_pass_rate: 1
|
|
|
260919
261103
|
const isGenerated = (twin) => gen_exports.GENERATED_TOOLS.includes(twin);
|
|
260920
261104
|
const tools2 = twins.filter(isGenerated);
|
|
260921
261105
|
const keyed2 = (suffix) => opts.idempotencyKey === void 0 ? {} : { idempotencyKey: `${opts.idempotencyKey}-${suffix}` };
|
|
260922
|
-
const world5 = await worldGen(step2(ctx), opts.intent, { ...used.length > 0 && tools2.length > 0 && { tools: tools2.join(",") }, ...keyed2("world") });
|
|
261106
|
+
const world5 = await writing(ctx.io.cwd, () => worldGen(step2(ctx), opts.intent, { ...used.length > 0 && tools2.length > 0 && { tools: tools2.join(",") }, ...keyed2("world") }));
|
|
260923
261107
|
notGenerated = await addExampleSeeds(join58(ctx.io.cwd, world5.world), used.filter((twin) => !isGenerated(twin)));
|
|
260924
|
-
const test3 = await testNew(step2(ctx), opts.intent, { world: world5.id, ...keyed2("test") });
|
|
261108
|
+
const test3 = await writing(ctx.io.cwd, () => testNew(step2(ctx), opts.intent, { world: world5.id, ...keyed2("test") }));
|
|
260925
261109
|
generated = { world: { id: world5.id, file: world5.world, people: world5.people, ...notGenerated.added.length > 0 && { exampleData: notGenerated.added } }, test: { id: test3.id, file: test3.file, checks: test3.checks }, ...(world5.modelCredit ?? test3.modelCredit) && { modelCredit: "workspace" } };
|
|
260926
261110
|
result.created.push(...world5.files, test3.file, test3.record);
|
|
260927
261111
|
}
|
|
@@ -261009,7 +261193,7 @@ function registerSceneNew(scene2, ctx) {
|
|
|
261009
261193
|
throw new AnchaError("USAGE", `cannot create scene destination: ${prefix2}`, { hint: "choose another id and remove unsafe symlinks", cause });
|
|
261010
261194
|
}
|
|
261011
261195
|
try {
|
|
261012
|
-
const result = await
|
|
261196
|
+
const result = await applyScaffold2(ctx.io.cwd, planned);
|
|
261013
261197
|
ctx.out.result({ id: id15, twins, ...result }, () => `Created ${prefix2}/scene.yaml and oracle/null companions. Validate: ancha scene validate ${prefix2}/scene.yaml`);
|
|
261014
261198
|
} catch (error65) {
|
|
261015
261199
|
await rm13(target6, { recursive: true, force: true });
|
|
@@ -261587,10 +261771,10 @@ async function probeAgentConnection(agent, signal, progress2, inheritedEnv = pro
|
|
|
261587
261771
|
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.");
|
|
261588
261772
|
}
|
|
261589
261773
|
}
|
|
261590
|
-
async function cleanupAbandonedConnection(
|
|
261591
|
-
if (!Number.isSafeInteger(
|
|
261774
|
+
async function cleanupAbandonedConnection(owner6) {
|
|
261775
|
+
if (!Number.isSafeInteger(owner6) || owner6 <= 0) return;
|
|
261592
261776
|
try {
|
|
261593
|
-
process.kill(
|
|
261777
|
+
process.kill(owner6, 0);
|
|
261594
261778
|
return;
|
|
261595
261779
|
} catch {
|
|
261596
261780
|
}
|
|
@@ -261598,7 +261782,7 @@ async function cleanupAbandonedConnection(owner5) {
|
|
|
261598
261782
|
if (!runtime2.available || !runtime2.context) throw new Error("Runtime unavailable for cleanup");
|
|
261599
261783
|
const exec9 = promisify9(execFile10), env2 = Object.fromEntries(["PATH", "HOME", "TMPDIR"].flatMap((name5) => process.env[name5] ? [[name5, process.env[name5]]] : []));
|
|
261600
261784
|
const run7 = async (args) => (await exec9("docker", ["--context", runtime2.context, ...args], { env: env2, timeout: 15e3, maxBuffer: 1e5 })).stdout.trim();
|
|
261601
|
-
const filter4 = `label=dev.ancha.connection.owner=${
|
|
261785
|
+
const filter4 = `label=dev.ancha.connection.owner=${owner6}`;
|
|
261602
261786
|
const containers = (await run7(["ps", "-a", "--filter", filter4, "--format", "{{.Names}}"])).split("\n").filter((name5) => /^ancha-connect-[a-f0-9-]+(?:-copy|-check)?$/.test(name5));
|
|
261603
261787
|
for (const name5 of containers) await run7(["rm", "-f", name5]);
|
|
261604
261788
|
const volumes = (await run7(["volume", "ls", "--filter", filter4, "--format", "{{.Name}}"])).split("\n").filter((name5) => /^ancha-connect-[a-f0-9-]+-source$/.test(name5));
|
|
@@ -262146,7 +262330,7 @@ var ConsoleJobs = class {
|
|
|
262146
262330
|
await this.writeEvents(initial.runId, job.events).catch(() => {
|
|
262147
262331
|
});
|
|
262148
262332
|
const code5 = toErrorJson(error65).code;
|
|
262149
|
-
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(() => {
|
|
262333
|
+
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(() => {
|
|
262150
262334
|
});
|
|
262151
262335
|
} finally {
|
|
262152
262336
|
if (verification && registered) {
|
|
@@ -263758,11 +263942,11 @@ function registerBaseline(program2, ctx) {
|
|
|
263758
263942
|
|
|
263759
263943
|
// packages/cli/src/commands/connection.ts
|
|
263760
263944
|
async function connectThroughConsole(base6, agentId2) {
|
|
263761
|
-
const
|
|
263762
|
-
let operation = await
|
|
263945
|
+
const owner6 = await consoleApi(base6), path9 = `/api/agents/${encodeURIComponent(agentId2)}/connect`;
|
|
263946
|
+
let operation = await owner6.call(path9, {});
|
|
263763
263947
|
while (operation?.state === "queued" || operation?.state === "connecting") {
|
|
263764
263948
|
await new Promise((done) => setTimeout(done, 2e3));
|
|
263765
|
-
operation = await
|
|
263949
|
+
operation = await owner6.call(path9);
|
|
263766
263950
|
}
|
|
263767
263951
|
return operation;
|
|
263768
263952
|
}
|
|
@@ -264248,10 +264432,14 @@ function traceRef(source, ref23) {
|
|
|
264248
264432
|
async function call3(f2, url4, init, tool, keys7) {
|
|
264249
264433
|
for (let attempt2 = 0; ; attempt2++) {
|
|
264250
264434
|
let res;
|
|
264435
|
+
const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 3e4);
|
|
264251
264436
|
try {
|
|
264252
|
-
|
|
264437
|
+
const response6 = await f2(url4, { ...init, signal: controller.signal });
|
|
264438
|
+
res = new Response([204, 205, 304].includes(response6.status) ? null : await response6.arrayBuffer(), { status: response6.status, headers: response6.headers });
|
|
264253
264439
|
} catch (error65) {
|
|
264254
|
-
throw new AnchaError("SERVER_UNREACHABLE", `cannot reach ${tool} at ${new URL(url4).origin}`, { cause: error65, hint: "check the host in your environment and the network" });
|
|
264440
|
+
throw new AnchaError("SERVER_UNREACHABLE", `cannot reach ${tool} at ${new URL(url4).origin}`, { cause: error65, kind: "retry", hint: "check the host in your environment and the network; no workspace uploads have been confirmed by this command. Running the same command again is safe." });
|
|
264441
|
+
} finally {
|
|
264442
|
+
clearTimeout(timer);
|
|
264255
264443
|
}
|
|
264256
264444
|
if (res.status === 429 && attempt2 < 8) {
|
|
264257
264445
|
await sleep14((Number(res.headers.get("retry-after")) || 2 ** attempt2) * 1e3);
|
|
@@ -264310,7 +264498,10 @@ async function fromLangsmith(traceId, env2, f2) {
|
|
|
264310
264498
|
if (!runs.length) throw new AnchaError("USAGE", `LangSmith has no trace ${traceId} that this key can read`);
|
|
264311
264499
|
const root3 = runs.find((r2) => !r2.parent_run_id) ?? runs[0];
|
|
264312
264500
|
const thread4 = root3.thread_id ?? root3.extra?.metadata?.thread_id;
|
|
264313
|
-
const turns = thread4 && root3.session_id ? await query12({ session: [root3.session_id], is_root: true, filter: `and(eq(metadata_key, "thread_id"), eq(metadata_value, ${JSON.stringify(String(thread4))}))` }).catch(() =>
|
|
264501
|
+
const turns = thread4 && root3.session_id ? await query12({ session: [root3.session_id], is_root: true, filter: `and(eq(metadata_key, "thread_id"), eq(metadata_value, ${JSON.stringify(String(thread4))}))` }).catch((error65) => {
|
|
264502
|
+
if (error65 instanceof AnchaError && error65.code === "SERVER_UNREACHABLE") throw error65;
|
|
264503
|
+
return [root3];
|
|
264504
|
+
}) : [root3];
|
|
264314
264505
|
const ids3 = [.../* @__PURE__ */ new Set([root3.id, ...turns.map((r2) => r2.id)])];
|
|
264315
264506
|
const feedback = [];
|
|
264316
264507
|
for (const id15 of ids3) feedback.push(...await call3(f2, `${api4}/feedback?${new URLSearchParams({ run: id15 })}`, { headers }, "LangSmith", "LANGSMITH_API_KEY"));
|
|
@@ -264472,8 +264663,8 @@ function readTraceUnits(texts4, { fileToIr: fileToIr2, sourceOf: sourceOf2 }) {
|
|
|
264472
264663
|
}
|
|
264473
264664
|
}
|
|
264474
264665
|
for (const { file: file3, traces, f: f2 } of langsmithFeedback) {
|
|
264475
|
-
const
|
|
264476
|
-
for (const id15 of
|
|
264666
|
+
const owner6 = f2?.run_id === void 0 ? void 0 : runTrace.get(f2.run_id);
|
|
264667
|
+
for (const id15 of owner6 ? [owner6] : traces) {
|
|
264477
264668
|
const d = draft2("langsmith", id15, file3);
|
|
264478
264669
|
put4(d, "feedback", f2, f2?.id);
|
|
264479
264670
|
d.alone = true;
|
|
@@ -264716,21 +264907,51 @@ var WorkspaceError = class extends AnchaError {
|
|
|
264716
264907
|
};
|
|
264717
264908
|
function workspaceError(status6, body8, path9) {
|
|
264718
264909
|
if (status6 === 404 && body8.error === void 0) return new WorkspaceError(404, "this workspace does not take traces", "ancha import --offline <trace file> makes the test on this computer; nothing is uploaded", true);
|
|
264719
|
-
|
|
264910
|
+
const contract = typeof body8.error === "string" ? { error: { message: body8.error, code: body8.code, kind: body8.kind, hint: body8.hint, reference: body8.reference } } : body8;
|
|
264911
|
+
const error65 = serverError(status6, contract, { message: `${path9}: HTTP ${status6}`, code: "USAGE" });
|
|
264912
|
+
if (status6 === 409 && error65.message === "this trace is still arriving; try again in a minute") error65.kind = "retry";
|
|
264913
|
+
return Object.assign(new WorkspaceError(status6, error65.message, error65.hint), { code: error65.code, kind: error65.kind, ...error65.reference && { reference: error65.reference } });
|
|
264720
264914
|
}
|
|
264721
264915
|
function notInWorkspace(error65) {
|
|
264722
264916
|
return error65 instanceof WorkspaceError && error65.status === 404 && !error65.noTraces;
|
|
264723
264917
|
}
|
|
264918
|
+
var traceRequestMs = (bytes4 = 0) => Math.min(3e5, 3e4 + Math.ceil(bytes4 / 65536) * 1e3);
|
|
264919
|
+
async function traceRequest(url4, init, receipt2 = () => "No workspace uploads have been confirmed by this command.") {
|
|
264920
|
+
const controller = new AbortController(), ms2 = traceRequestMs(new URL(url4).pathname === "/v1/imports" && typeof init.body === "string" ? Buffer.byteLength(init.body) : 0);
|
|
264921
|
+
const timer = setTimeout(() => controller.abort(), ms2);
|
|
264922
|
+
try {
|
|
264923
|
+
const res = await fetch(url4, { ...init, signal: controller.signal });
|
|
264924
|
+
const text31 = await res.text();
|
|
264925
|
+
let body8 = {};
|
|
264926
|
+
try {
|
|
264927
|
+
const parsed5 = JSON.parse(text31);
|
|
264928
|
+
if (parsed5 && typeof parsed5 === "object" && !Array.isArray(parsed5)) body8 = parsed5;
|
|
264929
|
+
} catch {
|
|
264930
|
+
}
|
|
264931
|
+
return { res, body: body8 };
|
|
264932
|
+
} catch (cause) {
|
|
264933
|
+
throw new AnchaError(
|
|
264934
|
+
"SERVER_UNREACHABLE",
|
|
264935
|
+
`The workspace did not answer. ${receipt2()} The interrupted request may have been saved. Running the same command again is safe.`,
|
|
264936
|
+
{ kind: "retry", hint: "run the same command again; traces already in the workspace are reported as already imported", cause }
|
|
264937
|
+
);
|
|
264938
|
+
} finally {
|
|
264939
|
+
clearTimeout(timer);
|
|
264940
|
+
}
|
|
264941
|
+
}
|
|
264724
264942
|
async function workspaceApi(ctx, hint = "run ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY") {
|
|
264725
264943
|
const workspace4 = await uploadWorkspace(ctx, { message: "not logged in to a workspace", hint });
|
|
264726
264944
|
const key5 = await apiKeyFor(workspace4, ctx.io.env);
|
|
264727
264945
|
if (key5 === void 0) throw authError(workspace4, { keySent: false });
|
|
264728
264946
|
const origin = new URL(workspace4).origin;
|
|
264947
|
+
const traces = /* @__PURE__ */ new Set(), tests = /* @__PURE__ */ new Set();
|
|
264948
|
+
const receipt2 = () => `Workspace receipts from this command: traces ${[...traces].join(", ") || "none confirmed"}; saved tests ${[...tests].join(", ") || "none confirmed"}.`;
|
|
264729
264949
|
return async (path9, init = {}) => {
|
|
264730
|
-
const res = await
|
|
264731
|
-
|
|
264732
|
-
if (res.status === 401) throw authError(workspace4, { keySent: true });
|
|
264950
|
+
const { res, body: body8 } = await traceRequest(`${origin}${path9}`, { ...init, headers: { authorization: `Bearer ${key5}`, "x-ancha-trace-import": "1", ...init.headers } }, receipt2);
|
|
264951
|
+
if (res.status === 401) throw serverError(res.status, body8, authError(workspace4, { keySent: true }));
|
|
264733
264952
|
if (!res.ok) throw workspaceError(res.status, body8, path9);
|
|
264953
|
+
if (path9.startsWith("/v1/imports")) for (const trace2 of body8.traces ?? []) traces.add(trace2.id);
|
|
264954
|
+
if (init.method === "POST" && body8.world?.id) tests.add(body8.world.id);
|
|
264734
264955
|
return body8;
|
|
264735
264956
|
};
|
|
264736
264957
|
}
|
|
@@ -264986,6 +265207,7 @@ async function nextLines(ctx, paths3, dest, connection4) {
|
|
|
264986
265207
|
var testName = (id15) => /^trace-([0-9a-f]{8,})$/i.exec(id15.trim())?.[1];
|
|
264987
265208
|
var AT_ONCE = 4;
|
|
264988
265209
|
var MB4 = 1024 * 1024;
|
|
265210
|
+
var classifiedSkip = (skip, error65) => ({ code: error65?.code ?? "USAGE", kind: error65?.kind ?? "fix", ...skip });
|
|
264989
265211
|
async function atOnce(items2, n2, fn) {
|
|
264990
265212
|
const out = new Array(items2.length);
|
|
264991
265213
|
let next2 = 0;
|
|
@@ -265015,14 +265237,15 @@ async function projectAgent(ctx) {
|
|
|
265015
265237
|
return configured ? agentName(ctx.io.cwd) : void 0;
|
|
265016
265238
|
}
|
|
265017
265239
|
async function sendTraces(ctx, api4, units, name5, options5, maxBytes) {
|
|
265018
|
-
const packed = packUploads(units, name5, maxBytes), skipped =
|
|
265240
|
+
const packed = packUploads(units, name5, maxBytes), skipped = packed.skipped.map((s3) => classifiedSkip(s3)), uploads = [];
|
|
265019
265241
|
const sent2 = [], fileOf = (unit) => units.find((u) => u.id === unit)?.files[0];
|
|
265020
265242
|
const queue = [...packed.uploads];
|
|
265021
|
-
|
|
265243
|
+
const alreadyImported = [];
|
|
265244
|
+
let stop, stopError, first2;
|
|
265022
265245
|
for (let i = 0; i < queue.length; i++) {
|
|
265023
265246
|
const upload6 = queue[i];
|
|
265024
265247
|
if (stop) {
|
|
265025
|
-
skipped.push(...upload6.ids.map((id15) => ({ trace: id15, file: fileOf(id15), reason: stop })));
|
|
265248
|
+
skipped.push(...upload6.ids.map((id15) => classifiedSkip({ trace: id15, file: fileOf(id15), reason: stop }, stopError)));
|
|
265026
265249
|
continue;
|
|
265027
265250
|
}
|
|
265028
265251
|
const size2 = upload6.bytes >= MB4 / 10 ? `${(upload6.bytes / MB4).toFixed(1)} MB` : `${Math.max(1, Math.round(upload6.bytes / 1024))} KB`;
|
|
@@ -265039,17 +265262,21 @@ async function sendTraces(ctx, api4, units, name5, options5, maxBytes) {
|
|
|
265039
265262
|
}
|
|
265040
265263
|
if (![400, 413, 429].includes(error65.status)) throw error65;
|
|
265041
265264
|
first2 ??= error65;
|
|
265042
|
-
if (error65.status === 429)
|
|
265043
|
-
|
|
265265
|
+
if (error65.status === 429) {
|
|
265266
|
+
stop = `${error65.message} (the workspace takes 600 uploads an hour)`;
|
|
265267
|
+
stopError = error65;
|
|
265268
|
+
}
|
|
265269
|
+
skipped.push(...upload6.ids.map((id15) => classifiedSkip({ trace: id15, file: fileOf(id15), reason: stop ?? error65.message }, error65)));
|
|
265044
265270
|
continue;
|
|
265045
265271
|
}
|
|
265046
265272
|
uploads.push(upload6);
|
|
265273
|
+
alreadyImported.push(...answer.traces.filter((t) => t.alreadyImported).map((t) => t.id));
|
|
265047
265274
|
answer.traces.forEach((t, n2) => sent2.push({ id: t.id, file: fileOf(answer.traces.length === upload6.ids.length ? upload6.ids[n2] : upload6.ids.find((id15) => t.trace?.endsWith(`:${id15}`))) }));
|
|
265048
265275
|
}
|
|
265049
265276
|
if (sent2.length > 1) ctx.out.info(`making ${plural6(sent2.length, "test")}, ${AT_ONCE} at a time`);
|
|
265050
265277
|
const answered = options5.expect !== void 0 || options5.answer.length > 0 || Boolean(options5.resetAnswers);
|
|
265051
265278
|
const results = await atOnce(sent2, AT_ONCE, async ({ id: id15, file: file3 }) => {
|
|
265052
|
-
const skip = (error65) => ({ skip: { trace: id15, ...file3 && { file: file3 }, reason: error65.message }, error: error65 });
|
|
265279
|
+
const skip = (error65) => ({ skip: classifiedSkip({ trace: id15, ...file3 && { file: file3 }, reason: error65.message }, error65), error: error65 });
|
|
265053
265280
|
let changes;
|
|
265054
265281
|
try {
|
|
265055
265282
|
changes = await guard(ctx, resolve50(ctx.io.cwd, options5.dest, `trace-${id15.slice(0, 8)}`), options5.force);
|
|
@@ -265075,7 +265302,7 @@ async function sendTraces(ctx, api4, units, name5, options5, maxBytes) {
|
|
|
265075
265302
|
skipped.push(r2.skip);
|
|
265076
265303
|
first2 ??= r2.error;
|
|
265077
265304
|
}
|
|
265078
|
-
return { made: results.flatMap((r2) => r2.made ? [r2.made] : []), skipped, uploads, sent: sent2.length, files: options5.files, first: first2 };
|
|
265305
|
+
return { alreadyImported, made: results.flatMap((r2) => r2.made ? [r2.made] : []), skipped, uploads, sent: sent2.length, files: options5.files, first: first2 };
|
|
265079
265306
|
}
|
|
265080
265307
|
function outcomeOf3(world5) {
|
|
265081
265308
|
const production3 = world5.summary?.production ?? {}, values3 = checksOf2(world5.scene).map((c) => production3[c.id] ?? "unknown");
|
|
@@ -265113,6 +265340,7 @@ async function uploadReport(ctx, done, from, dest) {
|
|
|
265113
265340
|
...m.written.kept.length && { kept: m.written.kept }
|
|
265114
265341
|
})),
|
|
265115
265342
|
skipped: done.skipped,
|
|
265343
|
+
alreadyImported: done.alreadyImported,
|
|
265116
265344
|
questions: asking.length,
|
|
265117
265345
|
uploads: done.uploads.map((u) => ({ format: u.format, traces: u.ids.length, files: u.files, bytes: u.bytes })),
|
|
265118
265346
|
...connection4 && { connection: connection4 },
|
|
@@ -265136,7 +265364,8 @@ async function uploadReport(ctx, done, from, dest) {
|
|
|
265136
265364
|
});
|
|
265137
265365
|
const short = (m) => m.world.name;
|
|
265138
265366
|
return [
|
|
265139
|
-
`Uploaded ${plural6(done.sent, "trace")} from ${from}: ${made}${done.skipped.length ? `; ${done.skipped.length} skipped` : ""}`,
|
|
265367
|
+
`Uploaded ${plural6(done.sent, "trace")} from ${from}: ${made}${done.skipped.length ? `; ${done.skipped.length} skipped (${ERROR_KINDS.map((kind2) => [kind2, done.skipped.filter((s3) => s3.kind === kind2).length]).filter(([, n2]) => n2).map(([kind2, n2]) => `${n2} ${kind2}`).join(", ")})` : ""}`,
|
|
265368
|
+
...done.alreadyImported.map((id15) => ` already imported: trace ${id15}`),
|
|
265140
265369
|
...rows35.length ? formatTable(rows35).split("\n").map((line2) => ` ${line2}`) : [],
|
|
265141
265370
|
// Each test's evidence under its name when there are several.
|
|
265142
265371
|
...tests.flatMap((m) => {
|
|
@@ -265154,10 +265383,12 @@ async function uploadReport(ctx, done, from, dest) {
|
|
|
265154
265383
|
});
|
|
265155
265384
|
}
|
|
265156
265385
|
async function importJson(ctx, done) {
|
|
265157
|
-
for (const s3 of done.skipped) if (s3.trace) ctx.out.event({ event: "trace_skipped", trace: s3.trace, reason: s3.reason });
|
|
265386
|
+
for (const s3 of done.skipped) if (s3.trace) ctx.out.event({ event: "trace_skipped", trace: s3.trace, reason: s3.reason, code: s3.code, kind: s3.kind });
|
|
265158
265387
|
for (const { world: world5, written } of done.made) {
|
|
265159
265388
|
const where3 = relative25(ctx.io.cwd, written.scene) || written.scene, connection4 = await connectionFor(ctx, [written.scene], where3);
|
|
265160
265389
|
ctx.out.result({
|
|
265390
|
+
alreadyImported: done.alreadyImported,
|
|
265391
|
+
skipped: done.skipped,
|
|
265161
265392
|
connection: connection4,
|
|
265162
265393
|
world: world5.id,
|
|
265163
265394
|
name: world5.name,
|
|
@@ -265360,10 +265591,10 @@ function registerTraces(program2, ctx) {
|
|
|
265360
265591
|
}
|
|
265361
265592
|
expectOne(options5.expect, units.length);
|
|
265362
265593
|
const done = await sendTraces(ctx, api4, units, name5, { dest: options5.dest, ...options5.force && { force: true }, ...options5.expect !== void 0 && { expect: options5.expect }, answer: [], files: read7.length, agent: await projectAgent(ctx) });
|
|
265363
|
-
done.skipped.unshift(...fetchSkipped, ...skipped);
|
|
265594
|
+
done.skipped.unshift(...[...fetchSkipped, ...skipped].map((s3) => classifiedSkip(s3)));
|
|
265364
265595
|
if (!done.made.length) {
|
|
265365
265596
|
if (done.skipped.length === 1 && done.first instanceof AnchaError) throw done.first;
|
|
265366
|
-
throw new AnchaError("USAGE", `none of the ${plural6(done.sent || units.length, "trace")} made a test`, { hint: done.skipped.slice(0, 5).map((s3) => `${s3.trace ? `trace ${s3.trace.slice(0, 8)}` : s3.file}: ${s3.reason}`).join("; ") });
|
|
265597
|
+
throw new AnchaError("USAGE", `none of the ${plural6(done.sent || units.length, "trace")} made a test`, { kind: done.skipped.some((s3) => s3.kind === "ours") ? "ours" : done.skipped.every((s3) => s3.kind === "retry") ? "retry" : "fix", hint: done.skipped.slice(0, 5).map((s3) => `${s3.trace ? `trace ${s3.trace.slice(0, 8)}` : s3.file}: ${s3.reason}`).join("; ") });
|
|
265367
265598
|
}
|
|
265368
265599
|
await uploadReport(ctx, done, options5.from !== void 0 ? options5.from === "langfuse" ? "Langfuse" : "LangSmith" : read7.length === 1 ? read7[0] : plural6(read7.length, "file"), options5.dest);
|
|
265369
265600
|
});
|
|
@@ -265382,6 +265613,7 @@ function registerTraces(program2, ctx) {
|
|
|
265382
265613
|
if (!units.length) throw new AnchaError("USAGE", `${source.label}: ${skipped[0]?.reason ?? "it holds no traces"}`, { hint: "use Ancha Trace IR JSONL, OTLP JSON, or a Langfuse or LangSmith export; ancha docs traces" });
|
|
265383
265614
|
expectOne(options5.expect, units.length);
|
|
265384
265615
|
const done = await sendTraces(ctx, api4, units, source.name, { ...options5, files: 1, agent: await projectAgent(ctx) });
|
|
265616
|
+
done.skipped.unshift(...skipped.map((s3) => classifiedSkip(s3)));
|
|
265385
265617
|
if (!done.made.length) throw done.first ?? new AnchaError("USAGE", `${source.label}: ${done.skipped[0]?.reason ?? "no trace made a test"}`);
|
|
265386
265618
|
if (ctx.out.json) await importJson(ctx, done);
|
|
265387
265619
|
else await uploadReport(ctx, done, source.label, options5.dest);
|
|
@@ -265833,7 +266065,7 @@ async function workspaceAgents(ctx) {
|
|
|
265833
266065
|
if (!(error65 instanceof AnchaError)) throw error65;
|
|
265834
266066
|
unread2 = error65;
|
|
265835
266067
|
}
|
|
265836
|
-
ctx.out.result({ cloud, agents: saved, ...unread2 !== void 0 && { agentsError: { code: unread2.code, message: unread2.message } } }, () => [
|
|
266068
|
+
ctx.out.result({ cloud, agents: saved, ...unread2 !== void 0 && { agentsError: { code: unread2.code, kind: unread2.kind, message: unread2.message, ...unread2.reference && { reference: unread2.reference } } } }, () => [
|
|
265837
266069
|
...cloud.map((agent) => `${agent.id} ${agent.name} ${agent.state} cloud`),
|
|
265838
266070
|
...(saved ?? []).map((agent) => `${agent.id} ${agent.name} ${agent.verification?.status ?? "unverified"} ${executionLabel(agent.execution)}`),
|
|
265839
266071
|
...unread2 !== void 0 ? [`The agents saved in the workspace were not listed: ${unread2.message}`] : []
|
|
@@ -265962,8 +266194,8 @@ ${result.verification?.message ?? "Use ancha report or ancha explain to inspect
|
|
|
265962
266194
|
function registerAgent(program2, ctx) {
|
|
265963
266195
|
const registry2 = () => new AgentRegistry(ctx.io.cwd);
|
|
265964
266196
|
const command = program2.command("agent").description("upload this project's agent to the cloud (agent upload), or save and test a local agent against automatically prepared tool worlds");
|
|
265965
|
-
command.command("upload").description("install this project's agent in a cloud machine, as a cloud run does, and start it once with a task (also: ancha doctor --on cloud)").option("--agent <command>", "override the configured agent command").action(async (opts) => {
|
|
265966
|
-
const result = await uploadAgent(ctx, { ...opts.agent !== void 0 && { agent: opts.agent }, timeout: "10s", on: "cloud" });
|
|
266197
|
+
command.command("upload").description("install this project's agent in a cloud machine, as a cloud run does, and start it once with a task (also: ancha doctor --on cloud)").option("--agent <command>", "override the configured agent command").option("--idempotency-key <key>", "retry safely: the same key and the same project return the upload the workspace accepted instead of starting another").action(async (opts) => {
|
|
266198
|
+
const result = await uploadAgent(ctx, { ...opts.agent !== void 0 && { agent: opts.agent }, ...opts.idempotencyKey !== void 0 && { idempotencyKey: opts.idempotencyKey }, timeout: "10s", on: "cloud" });
|
|
265967
266199
|
ctx.exitCode = result.exitCode;
|
|
265968
266200
|
ctx.out.result(result.report, () => renderUpload(result.report));
|
|
265969
266201
|
});
|
|
@@ -284410,35 +284642,35 @@ function attach(raws, lines2, links4, notes7) {
|
|
|
284410
284642
|
const owners = new Map(raws.filter((raw3) => raw3.id !== void 0 && TRANSACTION_TYPES2.has(raw3.type)).map((raw3) => [raw3.id, raw3]));
|
|
284411
284643
|
const groups = /* @__PURE__ */ new Map();
|
|
284412
284644
|
const origins = /* @__PURE__ */ new Map();
|
|
284413
|
-
const origin = (
|
|
284645
|
+
const origin = (owner6, id15) => {
|
|
284414
284646
|
const source = idOf3(id15);
|
|
284415
284647
|
if (source === void 0 || !owners.has(source)) return;
|
|
284416
|
-
const set2 = origins.get(
|
|
284648
|
+
const set2 = origins.get(owner6) ?? /* @__PURE__ */ new Set();
|
|
284417
284649
|
set2.add(source);
|
|
284418
|
-
origins.set(
|
|
284650
|
+
origins.set(owner6, set2);
|
|
284419
284651
|
};
|
|
284420
284652
|
let orphans = 0, posted = 0, unlinked2 = 0;
|
|
284421
284653
|
for (const line2 of lines2) {
|
|
284422
|
-
const f2 = line2.fields,
|
|
284423
|
-
if (!
|
|
284654
|
+
const f2 = line2.fields, owner6 = owners.get(idOf3(f2.transaction) ?? 0);
|
|
284655
|
+
if (!owner6) {
|
|
284424
284656
|
orphans++;
|
|
284425
284657
|
continue;
|
|
284426
284658
|
}
|
|
284427
|
-
origin(
|
|
284659
|
+
origin(owner6, f2.createdfrom);
|
|
284428
284660
|
if (bool10(f2.mainline) === true) {
|
|
284429
|
-
for (const key5 of ["subsidiary", "department", "class", "location", "entity"]) if (!present2(
|
|
284661
|
+
for (const key5 of ["subsidiary", "department", "class", "location", "entity"]) if (!present2(owner6.fields[key5]) && present2(f2[key5])) owner6.fields[key5] = f2[key5];
|
|
284430
284662
|
continue;
|
|
284431
284663
|
}
|
|
284432
284664
|
if (bool10(f2.taxline) === true || bool10(f2.iscogs) === true) {
|
|
284433
284665
|
posted++;
|
|
284434
284666
|
continue;
|
|
284435
284667
|
}
|
|
284436
|
-
const group5 = groups.get(
|
|
284668
|
+
const group5 = groups.get(owner6);
|
|
284437
284669
|
if (group5) group5.push(f2);
|
|
284438
|
-
else groups.set(
|
|
284670
|
+
else groups.set(owner6, [f2]);
|
|
284439
284671
|
}
|
|
284440
|
-
for (const [
|
|
284441
|
-
const rate = positive4(
|
|
284672
|
+
for (const [owner6, rows35] of groups) {
|
|
284673
|
+
const rate = positive4(owner6.fields.exchangeRate) ?? 1;
|
|
284442
284674
|
const amount6 = (f2) => netsuiteNumber(f2.foreignamount) ?? (netsuiteNumber(f2.netamount) ?? 0) / rate;
|
|
284443
284675
|
const sign4 = Math.sign(rows35.reduce((sum6, f2) => sum6 + amount6(f2), 0)) || 1;
|
|
284444
284676
|
for (const f2 of rows35) {
|
|
@@ -284471,17 +284703,17 @@ function attach(raws, lines2, links4, notes7) {
|
|
|
284471
284703
|
...rest2
|
|
284472
284704
|
} = f2;
|
|
284473
284705
|
const closed = bool10(isclosed) === true ? { isClosed: true } : {};
|
|
284474
|
-
if (
|
|
284706
|
+
if (owner6.type === "journalEntry") {
|
|
284475
284707
|
const d = netsuiteNumber(debitforeignamount ?? debit), c = netsuiteNumber(creditforeignamount ?? credit), net = amount6(f2);
|
|
284476
|
-
(
|
|
284708
|
+
(owner6.sublists.line ??= []).push({
|
|
284477
284709
|
...rest2,
|
|
284478
284710
|
account: expenseaccount ?? account9,
|
|
284479
284711
|
...present2(entity5) && { entity: entity5 },
|
|
284480
284712
|
...d ? { debit: d } : c ? { credit: c } : net >= 0 ? { debit: net } : { credit: -net }
|
|
284481
284713
|
});
|
|
284482
284714
|
} else if (present2(f2.item)) {
|
|
284483
|
-
(
|
|
284484
|
-
} else (
|
|
284715
|
+
(owner6.sublists.item ??= []).push({ ...rest2, ...closed, amount: round23(amount6(f2) * sign4), ...present2(quantity) && { quantity: Math.abs(netsuiteNumber(quantity) ?? 1) } });
|
|
284716
|
+
} else (owner6.sublists.expense ??= []).push({ ...rest2, ...closed, account: expenseaccount ?? account9, amount: round23(amount6(f2) * sign4) });
|
|
284485
284717
|
}
|
|
284486
284718
|
}
|
|
284487
284719
|
for (const link9 of links4) {
|
|
@@ -284498,7 +284730,7 @@ function attach(raws, lines2, links4, notes7) {
|
|
|
284498
284730
|
(from.sublists.apply ??= []).push({ doc, amount: Math.abs(amount6) });
|
|
284499
284731
|
} else origin(from, doc);
|
|
284500
284732
|
}
|
|
284501
|
-
for (const [
|
|
284733
|
+
for (const [owner6, sources] of origins) if (!present2(owner6.fields.createdFrom) && sources.size === 1) owner6.fields.createdFrom = [...sources][0];
|
|
284502
284734
|
const noun = (n2, what) => n2 === 1 ? `1 ${what} names` : `${n2} ${what}s name`;
|
|
284503
284735
|
if (orphans) notes7.push(`${noun(orphans, "transaction line")} a transaction the export lacks; left out of the world`);
|
|
284504
284736
|
if (posted) notes7.push(`${posted} tax and cost-of-goods line${posted === 1 ? "" : "s"}: the twin posts its own`);
|
|
@@ -286008,6 +286240,28 @@ import { resolve as resolve61 } from "node:path";
|
|
|
286008
286240
|
init_credentials();
|
|
286009
286241
|
var NAME_RE2 = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
286010
286242
|
var DEFERRED_SYNC = "Saved in the workspace; the workspace machine picks it up when it starts.";
|
|
286243
|
+
function renderSecrets(secrets2) {
|
|
286244
|
+
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";
|
|
286245
|
+
const saved = (at6) => at6 ? `${at6.slice(0, 16).replace("T", " ")}Z` : "";
|
|
286246
|
+
const table6 = formatTable([["NAME", "STATUS", "SAVED", "LENGTH", "PREVIEW"], ...secrets2.map((s3) => [s3.name, status6(s3), saved(s3.savedAt), String(s3.length), s3.preview ?? ""])]);
|
|
286247
|
+
const notes7 = secrets2.flatMap((s3) => [
|
|
286248
|
+
...s3.check?.status === "unchecked" && s3.check.reason ? [`- ${s3.name} was saved without a check: ${s3.check.reason}.`] : [],
|
|
286249
|
+
...s3.issues.flatMap((i) => [`- ${i.message}`, ...i.fix && i.level !== "info" ? [` fix: ${i.fix}`] : []])
|
|
286250
|
+
]);
|
|
286251
|
+
return notes7.length ? `${table6}
|
|
286252
|
+
${notes7.join("\n")}` : table6;
|
|
286253
|
+
}
|
|
286254
|
+
function parseDotenv(text31) {
|
|
286255
|
+
const values3 = /* @__PURE__ */ new Map();
|
|
286256
|
+
for (const line2 of text31.replace(/^\uFEFF/, "").split(/\r?\n/)) {
|
|
286257
|
+
const match3 = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(line2);
|
|
286258
|
+
if (!match3) continue;
|
|
286259
|
+
const [, name5, raw3] = match3;
|
|
286260
|
+
const quoted4 = /^(["'])(.*)\1(?:\s+#.*)?$/.exec(raw3);
|
|
286261
|
+
values3.set(name5, !quoted4 ? raw3.replace(/\s+#.*$/, "") : quoted4[1] === "'" ? quoted4[2] : quoted4[2].replace(/\\([nrt"\\])/g, (_, c) => ({ n: "\n", r: "\r", t: " " })[c] ?? c));
|
|
286262
|
+
}
|
|
286263
|
+
return values3;
|
|
286264
|
+
}
|
|
286011
286265
|
async function nameInConfig(ctx, names8) {
|
|
286012
286266
|
const label7 = ctx.globals().config ?? "ancha.yaml", file3 = resolve61(ctx.io.cwd, label7);
|
|
286013
286267
|
const them = names8.length === 1 ? "it" : "them", list19 = names8.join(", ");
|
|
@@ -286033,6 +286287,15 @@ async function nameInConfig(ctx, names8) {
|
|
|
286033
286287
|
}
|
|
286034
286288
|
return { passEnv: { file: label7, added } };
|
|
286035
286289
|
}
|
|
286290
|
+
async function configuredNames(ctx) {
|
|
286291
|
+
const text31 = await readFile60(resolve61(ctx.io.cwd, ctx.globals().config ?? "ancha.yaml"), "utf8").catch(() => void 0);
|
|
286292
|
+
if (text31 === void 0) return [];
|
|
286293
|
+
const doc = (0, import_yaml23.parseDocument)(text31), listed2 = (path9) => {
|
|
286294
|
+
const node5 = doc.getIn(path9);
|
|
286295
|
+
return (0, import_yaml23.isSeq)(node5) ? node5.items.map((item2) => String((0, import_yaml23.isScalar)(item2) ? item2.value : item2)) : [];
|
|
286296
|
+
};
|
|
286297
|
+
return [.../* @__PURE__ */ new Set([...listed2(["agent", "pass_env"]), ...listed2(["agent", "execution", "env"])])].filter((name5) => NAME_RE2.test(name5));
|
|
286298
|
+
}
|
|
286036
286299
|
function registerSecrets(program2, ctx) {
|
|
286037
286300
|
async function target6() {
|
|
286038
286301
|
const url4 = await configuredServerUrl(ctx);
|
|
@@ -286056,40 +286319,55 @@ function registerSecrets(program2, ctx) {
|
|
|
286056
286319
|
data7 = JSON.parse(text31);
|
|
286057
286320
|
} catch {
|
|
286058
286321
|
}
|
|
286059
|
-
if (res.status === 401 || res.status === 403) throw authError(base6, { status: res.status, keySent: true });
|
|
286060
286322
|
if (!res.ok) {
|
|
286061
|
-
const
|
|
286062
|
-
|
|
286063
|
-
const code5 = error65 !== void 0 && isErrorCode(error65.code) ? error65.code : res.status >= 500 ? "SERVER_UNREACHABLE" : "INTERNAL";
|
|
286064
|
-
throw new AnchaError(code5, `${base6}: ${message8}`, { ...typeof error65?.hint === "string" && { hint: error65.hint } });
|
|
286323
|
+
const auth2 = res.status === 401 || res.status === 403 ? authError(base6, { status: res.status, keySent: true }) : void 0;
|
|
286324
|
+
throw serverError(res.status, data7, { message: auth2?.message ?? `${base6}: HTTP ${res.status}`, ...auth2?.hint && { hint: auth2.hint } });
|
|
286065
286325
|
}
|
|
286066
|
-
return { names: data7.names ?? [], ...data7.restarting !== void 0 && { restarting: data7.restarting }, ...data7.synced !== void 0 && { synced: data7.synced } };
|
|
286326
|
+
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 } };
|
|
286067
286327
|
}
|
|
286068
286328
|
const validName = (name5) => {
|
|
286069
286329
|
if (!NAME_RE2.test(name5)) throw new AnchaError("USAGE", "secret names are UPPER_SNAKE_CASE, up to 64 characters");
|
|
286070
286330
|
return name5;
|
|
286071
286331
|
};
|
|
286072
286332
|
const command = program2.command("secrets").description("variables your agents get in the hosted workspace (provider keys); values come from this shell, not arguments");
|
|
286073
|
-
|
|
286333
|
+
async function save14(values3, check4, lead, extra2 = {}) {
|
|
286334
|
+
const names8 = Object.keys(values3);
|
|
286335
|
+
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.`);
|
|
286336
|
+
const result = await call4("PUT", check4 ? "" : "?check=0", values3);
|
|
286337
|
+
const named5 = await nameInConfig(ctx, names8);
|
|
286338
|
+
const line2 = "passEnvHint" in named5 ? `
|
|
286339
|
+
note: ${named5.passEnvHint}` : named5.passEnv.added.length > 0 ? `
|
|
286340
|
+
${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.` : "";
|
|
286341
|
+
const table6 = result.secrets?.length ? `
|
|
286342
|
+
${renderSecrets(result.secrets)}` : "";
|
|
286343
|
+
ctx.out.result({ set: names8, ...extra2, ...result, ...named5 }, () => `${lead}Saved ${names8.join(", ")} in the workspace. Workspace variables: ${result.names.join(", ") || "none"}.${result.synced === false ? `
|
|
286344
|
+
${DEFERRED_SYNC}` : result.restarting ? " The workspace machine restarts its processes to pick them up." : ""}${table6}${line2}`);
|
|
286345
|
+
}
|
|
286346
|
+
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) => {
|
|
286074
286347
|
const values3 = {};
|
|
286075
286348
|
for (const name5 of names8) {
|
|
286076
286349
|
validName(name5);
|
|
286077
286350
|
const value6 = ctx.io.env[name5];
|
|
286078
286351
|
if (value6 === void 0) throw new AnchaError("USAGE", `${name5} is not set in this shell`, { hint: `export ${name5}=\u2026 then run the command again` });
|
|
286079
|
-
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.`);
|
|
286080
286352
|
values3[name5] = value6;
|
|
286081
286353
|
}
|
|
286082
|
-
|
|
286083
|
-
|
|
286084
|
-
|
|
286085
|
-
|
|
286086
|
-
|
|
286087
|
-
|
|
286088
|
-
|
|
286354
|
+
await save14(values3, opts.check, "");
|
|
286355
|
+
});
|
|
286356
|
+
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) => {
|
|
286357
|
+
const path9 = resolve61(ctx.io.cwd, file3);
|
|
286358
|
+
const text31 = await readFile60(path9, "utf8").catch(() => {
|
|
286359
|
+
throw new AnchaError("USAGE", `cannot read ${file3}`, { hint: "pass the dotenv file that holds the values, e.g. ancha secrets import .env" });
|
|
286360
|
+
});
|
|
286361
|
+
const names8 = given2.length ? given2.map(validName) : await configuredNames(ctx);
|
|
286362
|
+
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` });
|
|
286363
|
+
const values3 = parseDotenv(text31), found = names8.filter((name5) => values3.has(name5)), missing10 = names8.filter((name5) => !values3.has(name5));
|
|
286364
|
+
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(" ")}` });
|
|
286365
|
+
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(", ")}.` : ""}
|
|
286366
|
+
`, { file: file3, ...missing10.length && { missing: missing10 } });
|
|
286089
286367
|
});
|
|
286090
|
-
command.command("list").description("list
|
|
286368
|
+
command.command("list").description("list the workspace's variables: names, when saved, whether accepted, and what to fix (never values)").action(async () => {
|
|
286091
286369
|
const result = await call4("GET", "");
|
|
286092
|
-
ctx.out.result({ names: result.names }, () => result.names.length ?
|
|
286370
|
+
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"));
|
|
286093
286371
|
});
|
|
286094
286372
|
command.command("unset").argument("<name>").description("remove a variable from the workspace").action(async (name5) => {
|
|
286095
286373
|
const result = await call4("DELETE", `/${validName(name5)}`);
|
|
@@ -286194,7 +286472,14 @@ var error64 = {
|
|
|
286194
286472
|
title: "error",
|
|
286195
286473
|
type: "object",
|
|
286196
286474
|
required: ["error"],
|
|
286197
|
-
properties: { error: { type: "object", required: ["code", "message"], properties: {
|
|
286475
|
+
properties: { error: { type: "object", required: ["code", "kind", "message"], properties: {
|
|
286476
|
+
code: { enum: [...ERROR_CODES] },
|
|
286477
|
+
kind: { enum: [...ERROR_KINDS], description: "who acts next: fix (change the input), retry (run it again) or ours (Ancha's side)" },
|
|
286478
|
+
message: string10,
|
|
286479
|
+
hint: { ...string10, description: "the exact next command" },
|
|
286480
|
+
reference: { ...string10, description: "the request or job ID, on an error on Ancha's side" },
|
|
286481
|
+
docs: string10
|
|
286482
|
+
} } }
|
|
286198
286483
|
};
|
|
286199
286484
|
var runStarted = {
|
|
286200
286485
|
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
@@ -286549,8 +286834,8 @@ next page: ancha runs list --cursor ${page20.nextCursor}`}`);
|
|
|
286549
286834
|
return found.id;
|
|
286550
286835
|
};
|
|
286551
286836
|
if (consoleUrl) {
|
|
286552
|
-
const
|
|
286553
|
-
const api4 = { start: (body8) =>
|
|
286837
|
+
const owner6 = await consoleApi(consoleUrl);
|
|
286838
|
+
const api4 = { start: (body8) => owner6.call("/api/playgrounds", body8), get: (id15) => owner6.call(`/api/playgrounds/${encodeURIComponent(id15)}`) };
|
|
286554
286839
|
const worldId = await withService(ctx, (service) => resolveWorld(() => service.worlds()));
|
|
286555
286840
|
const run7 = await api4.start(definition3(worldId));
|
|
286556
286841
|
const workspace4 = ctx.io.env.ANCHA_WORKSPACE_URL;
|