@ancha-labs/cli 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/ancha.mjs +485 -258
- package/lib/assets/docs/cloud.md +3 -3
- package/lib/assets/docs/run.md +7 -1
- package/lib/assets/harbor/companion.mjs +257 -195
- package/lib/assets/ui/app.js +28 -18
- package/lib/assets/ui/style.css +2 -0
- package/lib/mcp-entry.mjs +74 -12
- package/lib/worker.mjs +332 -210
- package/lib/world-server.mjs +257 -195
- package/package.json +1 -1
package/lib/ancha.mjs
CHANGED
|
@@ -26,9 +26,9 @@ var __commonJS = (cb, mod) => function __require3() {
|
|
|
26
26
|
throw mod = 0, e;
|
|
27
27
|
}
|
|
28
28
|
};
|
|
29
|
-
var __export = (target5,
|
|
30
|
-
for (var name5 in
|
|
31
|
-
__defProp(target5, name5, { get:
|
|
29
|
+
var __export = (target5, all8) => {
|
|
30
|
+
for (var name5 in all8)
|
|
31
|
+
__defProp(target5, name5, { get: all8[name5], enumerable: true });
|
|
32
32
|
};
|
|
33
33
|
var __copyProps = (to, from, except, desc) => {
|
|
34
34
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
@@ -3548,6 +3548,160 @@ var init_errors = __esm({
|
|
|
3548
3548
|
}
|
|
3549
3549
|
});
|
|
3550
3550
|
|
|
3551
|
+
// packages/core/src/execution-support.ts
|
|
3552
|
+
function executionSupports(path6, feature) {
|
|
3553
|
+
return EXECUTION_SUPPORT[feature]?.[path6] === true;
|
|
3554
|
+
}
|
|
3555
|
+
function rejectUnsupportedExecution(inputs2) {
|
|
3556
|
+
if (!inputs2.length) return;
|
|
3557
|
+
throw new AnchaError("CONFIG_INVALID", "Unsupported by managed/cloud execution:\n" + inputs2.map(({ file: file3, field: field4 }) => `${file3 ? file3 + ": " : ""}${field4}`).join("\n"), {
|
|
3558
|
+
hint: "Run locally with ancha run --on local, or use local/container execution in CI. Managed tasks must explicitly select a saved world; scene/test import is not equivalent."
|
|
3559
|
+
});
|
|
3560
|
+
}
|
|
3561
|
+
function unsupportedCloudDocument(file3, input2, contract = "import") {
|
|
3562
|
+
if (!input2 || typeof input2 !== "object" || Array.isArray(input2)) return [{ file: file3, field: "document (expected a scene or test mapping)" }];
|
|
3563
|
+
const doc = input2, test3 = doc.version === 2;
|
|
3564
|
+
const issues = [];
|
|
3565
|
+
for (const key3 of Object.keys(doc)) {
|
|
3566
|
+
if (["version", "generated", "checks", "start"].includes(key3)) continue;
|
|
3567
|
+
const feature = key3 === "timeout" ? `${test3 ? "test" : "scene"}.timeout` : key3 === "world" && test3 && contract === "managed-task" && typeof doc.world === "string" ? "managed.world-reference" : key3;
|
|
3568
|
+
if (!executionSupports("managed", feature)) issues.push({ file: file3, field: key3 });
|
|
3569
|
+
}
|
|
3570
|
+
if (doc.start && typeof doc.start === "object") for (const key3 of Object.keys(doc.start)) {
|
|
3571
|
+
if (!executionSupports("managed", `start.${key3}`)) issues.push({ file: file3, field: `start.${key3}` });
|
|
3572
|
+
}
|
|
3573
|
+
if (Array.isArray(doc.checks)) doc.checks.forEach((check4, index) => {
|
|
3574
|
+
if (!check4 || typeof check4 !== "object") {
|
|
3575
|
+
issues.push({ file: file3, field: `checks[${index}]` });
|
|
3576
|
+
return;
|
|
3577
|
+
}
|
|
3578
|
+
const keys5 = Object.keys(check4).filter((key3) => key3 !== "id");
|
|
3579
|
+
for (const key3 of keys5) {
|
|
3580
|
+
const kind = ["state", "trace", "judge"].includes(key3) ? key3 : "process";
|
|
3581
|
+
if (!executionSupports("managed", `checks.${kind}`)) issues.push({ file: file3, field: `checks[${index}].${key3}` });
|
|
3582
|
+
}
|
|
3583
|
+
});
|
|
3584
|
+
const format2 = test3 ? contract === "managed-task" ? "input.managed-task" : "input.test" : "input.scene";
|
|
3585
|
+
if (!executionSupports("managed", format2)) issues.push({ file: file3, field: format2 });
|
|
3586
|
+
return issues;
|
|
3587
|
+
}
|
|
3588
|
+
var all, sceneOnly, EXECUTION_SUPPORT;
|
|
3589
|
+
var init_execution_support = __esm({
|
|
3590
|
+
"packages/core/src/execution-support.ts"() {
|
|
3591
|
+
"use strict";
|
|
3592
|
+
init_errors();
|
|
3593
|
+
all = { local: true, container: true, managed: true };
|
|
3594
|
+
sceneOnly = { local: true, container: true, managed: false };
|
|
3595
|
+
EXECUTION_SUPPORT = {
|
|
3596
|
+
"input.scene": { ...sceneOnly, reason: "scene worlds cannot be imported without changing their semantics" },
|
|
3597
|
+
"input.test": { ...sceneOnly, reason: "local test worlds cannot be equated with saved managed worlds" },
|
|
3598
|
+
"input.managed-task": { local: false, container: false, managed: true, reason: "explicit saved-world tasks use runs start or the console" },
|
|
3599
|
+
"managed.world-reference": { local: false, container: false, managed: true, reason: "an explicit reference to an existing managed world, not an imported local world" },
|
|
3600
|
+
"id": all,
|
|
3601
|
+
"title": all,
|
|
3602
|
+
"task": sceneOnly,
|
|
3603
|
+
"start.task": all,
|
|
3604
|
+
"attempts": all,
|
|
3605
|
+
"twins": sceneOnly,
|
|
3606
|
+
"world": sceneOnly,
|
|
3607
|
+
"start_time": sceneOnly,
|
|
3608
|
+
"time_scale": sceneOnly,
|
|
3609
|
+
"seed": sceneOnly,
|
|
3610
|
+
"world_rules": sceneOnly,
|
|
3611
|
+
"people": sceneOnly,
|
|
3612
|
+
"until": sceneOnly,
|
|
3613
|
+
"deadline": sceneOnly,
|
|
3614
|
+
"start.message": sceneOnly,
|
|
3615
|
+
"pass": sceneOnly,
|
|
3616
|
+
"scene.timeout": sceneOnly,
|
|
3617
|
+
"test.timeout": all,
|
|
3618
|
+
"checks.state": all,
|
|
3619
|
+
"checks.trace": all,
|
|
3620
|
+
"checks.process": all,
|
|
3621
|
+
"checks.judge": sceneOnly,
|
|
3622
|
+
"agent.input.command": all,
|
|
3623
|
+
"agent.input.per_event": sceneOnly,
|
|
3624
|
+
"agent.input.events": { local: true, container: false, managed: false },
|
|
3625
|
+
"agent.input.http": all,
|
|
3626
|
+
"agent.endpoint": { local: true, container: false, managed: false },
|
|
3627
|
+
"agent.slack_transport.feed": sceneOnly,
|
|
3628
|
+
"agent.slack_transport.http": { local: true, container: false, managed: false },
|
|
3629
|
+
"agent.slack_transport.socket": { local: true, container: false, managed: false },
|
|
3630
|
+
"agent.env": sceneOnly,
|
|
3631
|
+
"agent.pass_env": sceneOnly,
|
|
3632
|
+
"agent.execution": sceneOnly,
|
|
3633
|
+
"judge": sceneOnly,
|
|
3634
|
+
"min_pass_rate": sceneOnly,
|
|
3635
|
+
"--agent": all,
|
|
3636
|
+
"--trials": all,
|
|
3637
|
+
"--parallel": all,
|
|
3638
|
+
"--idempotency-key": all,
|
|
3639
|
+
"--on": all,
|
|
3640
|
+
"--json": all,
|
|
3641
|
+
"--agent-url": { local: true, container: false, managed: false },
|
|
3642
|
+
"--compare": sceneOnly,
|
|
3643
|
+
"--min-pass-rate": sceneOnly,
|
|
3644
|
+
"--strict": sceneOnly,
|
|
3645
|
+
"--seed": sceneOnly,
|
|
3646
|
+
"--out": sceneOnly,
|
|
3647
|
+
"--detach": sceneOnly,
|
|
3648
|
+
"--pass-env": sceneOnly,
|
|
3649
|
+
"--inherit-env": sceneOnly,
|
|
3650
|
+
"--upload": sceneOnly,
|
|
3651
|
+
"--upload-required": sceneOnly
|
|
3652
|
+
};
|
|
3653
|
+
}
|
|
3654
|
+
});
|
|
3655
|
+
|
|
3656
|
+
// packages/core/src/verdict.ts
|
|
3657
|
+
function countTrials(requested2, outcomes) {
|
|
3658
|
+
const count3 = (kind) => outcomes.filter((outcome4) => outcome4 === kind).length;
|
|
3659
|
+
const passed = count3("passed"), failed = count3("failed"), invalid30 = count3("invalid"), skipped = count3("skipped");
|
|
3660
|
+
const counts = { requested: requested2, completed: passed + failed + invalid30 + skipped, valid: passed + failed, passed, invalid: invalid30, skipped };
|
|
3661
|
+
assertTrialCounts(counts);
|
|
3662
|
+
return counts;
|
|
3663
|
+
}
|
|
3664
|
+
function assertTrialCounts(counts) {
|
|
3665
|
+
if (!counts || !["requested", "completed", "valid", "passed", "invalid", "skipped"].every((key3) => Number.isSafeInteger(counts[key3]) && counts[key3] >= 0) || counts.completed > counts.requested || counts.valid + counts.invalid + counts.skipped !== counts.completed || counts.passed > counts.valid) {
|
|
3666
|
+
throw new Error("Invalid requested trial counts; rerun the evaluation and save a fresh baseline.");
|
|
3667
|
+
}
|
|
3668
|
+
}
|
|
3669
|
+
function allTrialsPassed(counts) {
|
|
3670
|
+
return counts.requested > 0 && counts.completed === counts.requested && counts.valid === counts.requested && counts.passed === counts.requested && counts.invalid === 0 && counts.skipped === 0;
|
|
3671
|
+
}
|
|
3672
|
+
function minimumPassingTrials(requested2, rate) {
|
|
3673
|
+
if (!Number.isSafeInteger(requested2) || requested2 < 0 || !Number.isFinite(rate) || rate < 0 || rate > 1) throw new Error("Invalid requested trial count or minimum pass rate.");
|
|
3674
|
+
const [mantissa, exponent = "0"] = rate.toString().split("e");
|
|
3675
|
+
const [whole2, fractional = ""] = mantissa.split(".");
|
|
3676
|
+
const scale = fractional.length - Number(exponent);
|
|
3677
|
+
const numerator = BigInt(whole2 + fractional) * (scale < 0 ? 10n ** BigInt(-scale) : 1n);
|
|
3678
|
+
const denominator = scale > 0 ? 10n ** BigInt(scale) : 1n;
|
|
3679
|
+
return Number((BigInt(requested2) * numerator + denominator - 1n) / denominator);
|
|
3680
|
+
}
|
|
3681
|
+
function meetsPassRate(counts, rate) {
|
|
3682
|
+
assertTrialCounts(counts);
|
|
3683
|
+
return counts.requested > 0 && counts.passed >= minimumPassingTrials(counts.requested, rate);
|
|
3684
|
+
}
|
|
3685
|
+
function trialOutcome(trial) {
|
|
3686
|
+
if (trial.valid === false || trial.exit === "invalid" || trial.outcome === "invalid") return "invalid";
|
|
3687
|
+
if (trial.outcome === "skipped" || trial.outcome === "xfailed") return "skipped";
|
|
3688
|
+
return trial.passed === true ? "passed" : "failed";
|
|
3689
|
+
}
|
|
3690
|
+
function verifiedCounts(summary, scene2) {
|
|
3691
|
+
if (summary.verdictVersion !== VERDICT_VERSION || !scene2.counts) throw new Error("Incompatible baseline/report verdict version or requested trial counts; rerun and save a fresh baseline.");
|
|
3692
|
+
const counts = scene2.counts;
|
|
3693
|
+
assertTrialCounts(counts);
|
|
3694
|
+
if (counts.passed !== scene2.passed || counts.completed !== scene2.trials || counts.invalid !== (scene2.invalidTrials ?? 0)) throw new Error("Inconsistent baseline/report trial counts; rerun and save a fresh baseline.");
|
|
3695
|
+
return counts;
|
|
3696
|
+
}
|
|
3697
|
+
var VERDICT_VERSION;
|
|
3698
|
+
var init_verdict = __esm({
|
|
3699
|
+
"packages/core/src/verdict.ts"() {
|
|
3700
|
+
"use strict";
|
|
3701
|
+
VERDICT_VERSION = 2;
|
|
3702
|
+
}
|
|
3703
|
+
});
|
|
3704
|
+
|
|
3551
3705
|
// packages/core/src/agent-environment.ts
|
|
3552
3706
|
function isPrivateAgentEnvironmentName(name5) {
|
|
3553
3707
|
return /^(?:ANCHA_(?:PEOPLE_|RESULTS_|CONSOLE_|CONTROL_|WORKSPACE_)|GATEWAY_|SIDECAR_|TENANT_)/i.test(name5) || /^(?:ANCHA_API_KEY|ANCHA_SERVER_URL|ANCHA_CREDENTIALS_FILE|OPENROUTER_MANAGEMENT_KEY|OPENROUTER_PROVISIONING_KEY)$/i.test(name5);
|
|
@@ -27680,15 +27834,15 @@ var init_notion = __esm({
|
|
|
27680
27834
|
databases: external_exports.array(database).max(200).default([])
|
|
27681
27835
|
}).superRefine((seed40, ctx) => {
|
|
27682
27836
|
const issue5 = (path6, message5) => ctx.addIssue({ code: "custom", path: path6, message: message5 });
|
|
27683
|
-
const users4 = /* @__PURE__ */ new Set(), pages = /* @__PURE__ */ new Set(),
|
|
27837
|
+
const users4 = /* @__PURE__ */ new Set(), pages = /* @__PURE__ */ new Set(), all8 = /* @__PURE__ */ new Set();
|
|
27684
27838
|
seed40.users.forEach((u, i) => {
|
|
27685
27839
|
if (users4.has(u.ref)) issue5(["users", i, "ref"], "duplicate user ref");
|
|
27686
27840
|
users4.add(u.ref);
|
|
27687
27841
|
});
|
|
27688
27842
|
const declare = (r, path6) => {
|
|
27689
27843
|
if (r === void 0) return;
|
|
27690
|
-
if (
|
|
27691
|
-
|
|
27844
|
+
if (all8.has(r) || users4.has(r)) issue5(path6, `duplicate ref ${r}`);
|
|
27845
|
+
all8.add(r);
|
|
27692
27846
|
};
|
|
27693
27847
|
seed40.pages.forEach((p2, i) => {
|
|
27694
27848
|
declare(p2.ref, ["pages", i, "ref"]);
|
|
@@ -33001,12 +33155,12 @@ function airtableSeedRecords(seed40) {
|
|
|
33001
33155
|
}
|
|
33002
33156
|
function airtableDataView(state3) {
|
|
33003
33157
|
const raw3 = state3 && typeof state3 === "object" ? state3 : {}, tables = [];
|
|
33004
|
-
const
|
|
33005
|
-
for (const { base: base3, entry: entry3 } of
|
|
33158
|
+
const all8 = rows26(raw3.bases).flatMap((base3) => rows26(base3.tables).map((entry3) => ({ base: String(base3.name ?? ""), entry: entry3 })));
|
|
33159
|
+
for (const { base: base3, entry: entry3 } of all8) {
|
|
33006
33160
|
const columns = rows26(entry3.fields).filter((item2) => !["multipleRecordLinks", "count", "multipleLookupValues", "rollup", "createdTime", "lastModifiedTime", "autoNumber"].includes(item2.type)).slice(0, 5).map((item2) => String(item2.name));
|
|
33007
33161
|
const records3 = rows26(entry3.records).filter((item2) => !item2.deleted);
|
|
33008
33162
|
if (!columns.length || !records3.length) continue;
|
|
33009
|
-
const title =
|
|
33163
|
+
const title = all8.filter((other) => other.entry.name === entry3.name).length > 1 ? `${entry3.name} (${base3})` : String(entry3.name);
|
|
33010
33164
|
tables.push({ title, columns, rows: records3.slice(0, 200).map((item2) => Object.fromEntries(columns.map((column) => [column, show((item2.fields ?? {})[column])]))), total: records3.length });
|
|
33011
33165
|
}
|
|
33012
33166
|
return { tables, conversations: [] };
|
|
@@ -43616,8 +43770,8 @@ var init_connections = __esm({
|
|
|
43616
43770
|
function toolDataView(tool, raw3) {
|
|
43617
43771
|
const state3 = object3(raw3), tables = [], conversations = [];
|
|
43618
43772
|
const add = (title, items, project11) => {
|
|
43619
|
-
const
|
|
43620
|
-
if (rows33.length) tables.push({ title, columns: Object.keys(rows33[0]), rows: rows33, total:
|
|
43773
|
+
const all8 = list(items), rows33 = all8.slice(0, 200).map(project11);
|
|
43774
|
+
if (rows33.length) tables.push({ title, columns: Object.keys(rows33[0]), rows: rows33, total: all8.length });
|
|
43621
43775
|
};
|
|
43622
43776
|
if (tool === "slack") {
|
|
43623
43777
|
const who2 = (id12) => list(state3.users).find((u) => u.id === id12)?.real_name ?? list(state3.users).find((u) => u.id === id12)?.name ?? id12;
|
|
@@ -43883,6 +44037,8 @@ var init_src = __esm({
|
|
|
43883
44037
|
"packages/core/src/index.ts"() {
|
|
43884
44038
|
"use strict";
|
|
43885
44039
|
init_errors();
|
|
44040
|
+
init_execution_support();
|
|
44041
|
+
init_verdict();
|
|
43886
44042
|
init_agent_environment();
|
|
43887
44043
|
init_relay();
|
|
43888
44044
|
init_duration();
|
|
@@ -96280,7 +96436,8 @@ function validateHarborBatchSetup(agent, resolvedAgent, configuration) {
|
|
|
96280
96436
|
if (resolvedAgent.mode === "endpoint") throw new AnchaError("CONFIG_INVALID", "Managed playgrounds require a local start command.");
|
|
96281
96437
|
if (Object.keys(resolvedAgent.env).some((key3) => key3 === "ANCHA_CONNECTION_MANIFEST" || /^ANCHA_(?:TASK|ENV_ID|ATTEMPT_ID|CASE_ID|TRIAL|STATE_DIR|WORLD_SEED|AGENT_PORT)$/.test(key3))) throw new AnchaError("CONFIG_INVALID", "Agent environment mappings cannot override managed task, world, or attempt identities.");
|
|
96282
96438
|
const input2 = agent.taskInput ?? resolvedAgent.taskInput;
|
|
96283
|
-
if (!input2
|
|
96439
|
+
if (!input2) throw new AnchaError("CONFIG_INVALID", "Declare command or HTTP task input for this agent.");
|
|
96440
|
+
if (!executionSupports("managed", `agent.input.${input2.kind}`)) throw new AnchaError("CONFIG_INVALID", `Event task input ${input2.kind} is not supported by managed/Harbor execution. Use command or HTTP input, or run per_event locally or in CI.`);
|
|
96284
96441
|
parseTaskInput(input2);
|
|
96285
96442
|
if (input2.kind === "http" && !/\$(?:ANCHA_AGENT_PORT\b|\{ANCHA_AGENT_PORT\})/.test(resolvedAgent.command)) throw new AnchaError("CONFIG_INVALID", "The HTTP agent command must use $ANCHA_AGENT_PORT.");
|
|
96286
96443
|
if (compileSandboxConfiguration(configuration).scene.twins.includes("google-ads")) throw new AnchaError("CONFIG_INVALID", "Google Ads is not qualified for managed playgrounds yet. Its gRPC transport needs separate integration.");
|
|
@@ -96371,7 +96528,7 @@ async function executeHarborBatch(input2) {
|
|
|
96371
96528
|
if (resolvedAgent.mode === "endpoint") throw new AnchaError("CONFIG_INVALID", "Managed playgrounds require a local start command.");
|
|
96372
96529
|
validateHarborBatchSetup(entry3.agent, resolvedAgent, entry3.configuration);
|
|
96373
96530
|
const taskInput = entry3.agent.taskInput ?? resolvedAgent.taskInput;
|
|
96374
|
-
if (!taskInput || taskInput.kind
|
|
96531
|
+
if (!taskInput || !executionSupports("managed", `agent.input.${taskInput.kind}`)) throw new AnchaError("CONFIG_INVALID", "Choose command or HTTP task input; events and per_event are unsupported.");
|
|
96375
96532
|
const policy = policyFor(entry3.agent, resolvedAgent);
|
|
96376
96533
|
const inherited = entries2?.length ? entry3.inheritedEnv ?? {} : entry3.inheritedEnv ?? input2.inheritedEnv ?? process.env;
|
|
96377
96534
|
const inheritedValues = Object.fromEntries(policy.env.flatMap((key3) => inherited[key3] === void 0 ? [] : [[key3, inherited[key3]]]));
|
|
@@ -96767,11 +96924,11 @@ var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
|
96767
96924
|
var __getProtoOf2 = Object.getPrototypeOf;
|
|
96768
96925
|
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
96769
96926
|
var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
96770
|
-
var __exportAll = (
|
|
96927
|
+
var __exportAll = (all8, symbols) => {
|
|
96771
96928
|
let target5 = {};
|
|
96772
|
-
for (var name5 in
|
|
96929
|
+
for (var name5 in all8) {
|
|
96773
96930
|
__defProp2(target5, name5, {
|
|
96774
|
-
get:
|
|
96931
|
+
get: all8[name5],
|
|
96775
96932
|
enumerable: true
|
|
96776
96933
|
});
|
|
96777
96934
|
}
|
|
@@ -114784,9 +114941,9 @@ function inspectPredicate(env2, predicate, atMs) {
|
|
|
114784
114941
|
const expected = predicateWords(predicate);
|
|
114785
114942
|
const outcome4 = (passed, actual, explanation = actual) => ({ passed, expected, actual, explanation });
|
|
114786
114943
|
if ("all" in predicate || "any" in predicate) {
|
|
114787
|
-
const
|
|
114788
|
-
const children2 = (
|
|
114789
|
-
return outcome4(
|
|
114944
|
+
const all8 = "all" in predicate;
|
|
114945
|
+
const children2 = (all8 ? predicate.all : predicate.any).map((child2) => inspectPredicate(env2, child2, atMs));
|
|
114946
|
+
return outcome4(all8 ? children2.every((child2) => child2.passed) : children2.some((child2) => child2.passed), children2.map((child2) => child2.actual).join("; "));
|
|
114790
114947
|
}
|
|
114791
114948
|
if ("not" in predicate) {
|
|
114792
114949
|
const child2 = inspectPredicate(env2, predicate.not, atMs);
|
|
@@ -119155,10 +119312,10 @@ var bufferToFormData = (arrayBuffer, contentType) => {
|
|
|
119155
119312
|
var MAX_NESTED_OBJECTS = 1e4;
|
|
119156
119313
|
var isRawRequest = (request2) => "headers" in request2;
|
|
119157
119314
|
var parseBody = async (request2, options3 = /* @__PURE__ */ Object.create(null)) => {
|
|
119158
|
-
const { all:
|
|
119315
|
+
const { all: all8 = false, dot = false } = options3;
|
|
119159
119316
|
const mediaType2 = (isRawRequest(request2) ? request2.headers : request2.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();
|
|
119160
119317
|
if (mediaType2 === "multipart/form-data" || mediaType2 === "application/x-www-form-urlencoded") return parseFormData(request2, {
|
|
119161
|
-
all:
|
|
119318
|
+
all: all8,
|
|
119162
119319
|
dot
|
|
119163
119320
|
});
|
|
119164
119321
|
return {};
|
|
@@ -121067,8 +121224,8 @@ function properties(type, record23) {
|
|
|
121067
121224
|
function project3(ctx, type, record23, selected2, historyFields, associationObjects) {
|
|
121068
121225
|
const names3 = selected2 ?? defaultProperties[type];
|
|
121069
121226
|
for (const name5 of [...names3, ...historyFields ?? []]) checkProperty(type, name5);
|
|
121070
|
-
const
|
|
121071
|
-
const output2 = { id: record23.id, properties: Object.fromEntries(keys5.filter((key3) =>
|
|
121227
|
+
const all8 = properties(type, record23), keys5 = [.../* @__PURE__ */ new Set([...names3, "hs_object_id", "createdate", type === "contacts" ? "lastmodifieddate" : "hs_lastmodifieddate"])];
|
|
121228
|
+
const output2 = { id: record23.id, properties: Object.fromEntries(keys5.filter((key3) => all8[key3] !== void 0).map((key3) => [key3, all8[key3]])), createdAt: record23.createdAt, updatedAt: record23.updatedAt, archived: record23.archived, ...record23.archived && { archivedAt: record23.archivedAt } };
|
|
121072
121229
|
if (historyFields?.length) {
|
|
121073
121230
|
const versions2 = ctx.store.db.prepare("SELECT data,operation FROM hubspot_versions WHERE type=? AND id=? ORDER BY ordinal").all(type, record23.id).map((row) => ({ ...row, record: JSON.parse(row.data) }));
|
|
121074
121231
|
output2.propertiesWithHistory = Object.fromEntries(historyFields.map((name5) => {
|
|
@@ -121484,9 +121641,9 @@ function dispatch(ctx, method2, url3, body6) {
|
|
|
121484
121641
|
permission3(ctx, type2);
|
|
121485
121642
|
queryParams(url3, ["archived"]);
|
|
121486
121643
|
if (boolean5(url3.searchParams.get("archived"))) unsupported3("archived pipelines");
|
|
121487
|
-
const
|
|
121488
|
-
if (!match2[2]) return { status: 200, body: { results:
|
|
121489
|
-
const pipeline =
|
|
121644
|
+
const all8 = config2(ctx).pipelines;
|
|
121645
|
+
if (!match2[2]) return { status: 200, body: { results: all8.map((p2) => ({ ...p2, archived: false })) } };
|
|
121646
|
+
const pipeline = all8.find((p2) => p2.id === decodeURIComponent(match2[2]));
|
|
121490
121647
|
if (!pipeline) throw new HubError(404, "OBJECT_NOT_FOUND", "Pipeline not found.");
|
|
121491
121648
|
if (path6.includes("/stages")) {
|
|
121492
121649
|
if (!match2[3]) return { status: 200, body: { results: pipeline.stages.map((stage2) => ({ ...stage2, createdAt: pipeline.createdAt, updatedAt: pipeline.updatedAt, archived: false })) } };
|
|
@@ -121922,7 +122079,7 @@ function initializeCatalogIntegrations(env2) {
|
|
|
121922
122079
|
}
|
|
121923
122080
|
function reconcileCatalogIntegrations(env2) {
|
|
121924
122081
|
if (!hasTable5(env2, "world_catalog_cursor")) return { activity: false };
|
|
121925
|
-
const
|
|
122082
|
+
const all8 = entries(env2), before = env2.events.tail;
|
|
121926
122083
|
let cursor4 = env2.store.db.prepare("SELECT cursor FROM world_catalog_cursor WHERE id = 1").get().cursor;
|
|
121927
122084
|
let activity2 = false;
|
|
121928
122085
|
scan: for (let batch3 = env2.events.list(cursor4, 100); batch3.length; batch3 = env2.events.list(cursor4, 100)) {
|
|
@@ -121934,7 +122091,7 @@ function reconcileCatalogIntegrations(env2) {
|
|
|
121934
122091
|
}
|
|
121935
122092
|
cursor4 = event3.cursor;
|
|
121936
122093
|
const view3 = catalogEvent(event3);
|
|
121937
|
-
for (const entry3 of
|
|
122094
|
+
for (const entry3 of all8) {
|
|
121938
122095
|
if (!matches(entry3.integration, view3)) continue;
|
|
121939
122096
|
const delay = entry3.integration.delay === void 0 ? 0 : parseDuration(entry3.integration.delay);
|
|
121940
122097
|
if (delay > 0) env2.scheduler.enqueue({ atMs: env2.clock.elapsedMs() + delay, kind: "integration.catalog", payload: { integration: entry3.ordinal, event: event3.cursor } });
|
|
@@ -132540,11 +132697,11 @@ function listPermissions(call2) {
|
|
|
132540
132697
|
const pageSize2 = integerParameter(params9, "pageSize", 100, 1, 100);
|
|
132541
132698
|
const binding2 = JSON.stringify(["permissions", file3.id]);
|
|
132542
132699
|
const offset16 = readPageToken(params9.get("pageToken"), binding2);
|
|
132543
|
-
const
|
|
132700
|
+
const all8 = effectivePermissions(call2.ctx, file3);
|
|
132544
132701
|
return json8(project8({
|
|
132545
132702
|
kind: "drive#permissionList",
|
|
132546
|
-
...offset16 + pageSize2 <
|
|
132547
|
-
permissions:
|
|
132703
|
+
...offset16 + pageSize2 < all8.length && { nextPageToken: pageToken(offset16 + pageSize2, binding2) },
|
|
132704
|
+
permissions: all8.slice(offset16, offset16 + pageSize2).map((entry3) => permissionResource(call2.ctx, entry3.grant))
|
|
132548
132705
|
}, mask(params9, "kind,nextPageToken,permissions(kind,id,type,role,allowFileDiscovery)", ["kind", "nextPageToken", "permissions"], { permissions: PERMISSION_FIELDS })));
|
|
132549
132706
|
}
|
|
132550
132707
|
function getPermission(call2) {
|
|
@@ -133286,10 +133443,10 @@ function leaves(part) {
|
|
|
133286
133443
|
return part.parts.length ? part.parts.flatMap(leaves) : [part];
|
|
133287
133444
|
}
|
|
133288
133445
|
function bodyText(root2) {
|
|
133289
|
-
const
|
|
133290
|
-
const plain4 =
|
|
133446
|
+
const all8 = leaves(root2).filter((p2) => !isAttachment(p2));
|
|
133447
|
+
const plain4 = all8.filter((p2) => p2.mimeType === "text/plain");
|
|
133291
133448
|
if (plain4.length) return plain4.map(partText).join("\n");
|
|
133292
|
-
return
|
|
133449
|
+
return all8.filter((p2) => p2.mimeType === "text/html").map((p2) => htmlToText(partText(p2))).join("\n");
|
|
133293
133450
|
}
|
|
133294
133451
|
function htmlToText(html2) {
|
|
133295
133452
|
return html2.replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gi, " ").replace(/<br\s*\/?>|<\/(p|div|li|h\d)>/gi, "\n").replace(/<[^>]+>/g, " ").replace(/ /g, " ").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
|
@@ -133991,9 +134148,9 @@ function searchFor(r) {
|
|
|
133991
134148
|
function filterFor(r, labelIds = []) {
|
|
133992
134149
|
const search9 = searchFor(r), mailbox2 = r.caller.mailbox.address;
|
|
133993
134150
|
for (const id12 of labelIds) if (!getLabel2(r.ctx, mailbox2, id12)) invalid12(`Invalid label: ${id12}`);
|
|
133994
|
-
const
|
|
133995
|
-
const trashOk =
|
|
133996
|
-
const spamOk =
|
|
134151
|
+
const all8 = bool2(r.query, "includeSpamTrash");
|
|
134152
|
+
const trashOk = all8 || search9.includesTrash || labelIds.includes("TRASH");
|
|
134153
|
+
const spamOk = all8 || search9.includesSpam || labelIds.includes("SPAM");
|
|
133997
134154
|
return (row) => {
|
|
133998
134155
|
const ids2 = labelIdsOf(r.ctx, mailbox2, row.id);
|
|
133999
134156
|
if (!trashOk && ids2.includes("TRASH")) return false;
|
|
@@ -135041,12 +135198,12 @@ function listBuckets(call2) {
|
|
|
135041
135198
|
const limit2 = max === void 0 ? 1e4 : Number(max);
|
|
135042
135199
|
if (!Number.isInteger(limit2) || limit2 < 1 || limit2 > 1e4) throw new S3Error("InvalidArgument", "Argument max-buckets must be an integer between 1 and 10000", { ArgumentName: "max-buckets", ArgumentValue: max ?? "" });
|
|
135043
135200
|
const after = token2 === void 0 ? "" : Buffer.from(token2, "base64url").toString("utf8");
|
|
135044
|
-
const
|
|
135045
|
-
const page15 =
|
|
135201
|
+
const all8 = call2.ctx.store.db.prepare("SELECT * FROM s3_buckets ORDER BY name").all().filter((bucket2) => bucket2.name.startsWith(prefix2) && (region === void 0 || bucket2.region === region) && bucket2.name > after);
|
|
135202
|
+
const page15 = all8.slice(0, limit2);
|
|
135046
135203
|
return xml(call2, node3("ListAllMyBucketsResult", [
|
|
135047
135204
|
owner(call2.ctx),
|
|
135048
135205
|
node3("Buckets", page15.map((bucket2) => node3("Bucket", [el("Name", bucket2.name), el("CreationDate", iso3(bucket2.created_ms)), el("BucketRegion", bucket2.region)]))),
|
|
135049
|
-
...
|
|
135206
|
+
...all8.length > limit2 ? [el("ContinuationToken", Buffer.from(page15.at(-1).name).toString("base64url"))] : [],
|
|
135050
135207
|
...prefix2 ? [el("Prefix", prefix2)] : []
|
|
135051
135208
|
], true));
|
|
135052
135209
|
}
|
|
@@ -135685,7 +135842,7 @@ function migrate16(db2) {
|
|
|
135685
135842
|
db2.exec(SCHEMA7);
|
|
135686
135843
|
}
|
|
135687
135844
|
var one = (ctx, sql, ...args) => ctx.store.db.prepare(sql).get(...args);
|
|
135688
|
-
var
|
|
135845
|
+
var all2 = (ctx, sql, ...args) => ctx.store.db.prepare(sql).all(...args);
|
|
135689
135846
|
var org = (ctx) => one(ctx, "SELECT * FROM linear_org");
|
|
135690
135847
|
var userById = (ctx, id12) => one(ctx, "SELECT * FROM linear_users WHERE id = ?", id12);
|
|
135691
135848
|
var teamById = (ctx, id12) => one(ctx, "SELECT * FROM linear_teams WHERE id = ?", id12);
|
|
@@ -135694,17 +135851,17 @@ var labelById = (ctx, id12) => one(ctx, "SELECT * FROM linear_labels WHERE id =
|
|
|
135694
135851
|
var projectById = (ctx, id12) => one(ctx, "SELECT * FROM linear_projects WHERE id = ?", id12);
|
|
135695
135852
|
var issueById = (ctx, id12) => one(ctx, "SELECT * FROM linear_issues WHERE id = ?", id12);
|
|
135696
135853
|
var commentById = (ctx, id12) => one(ctx, "SELECT * FROM linear_comments WHERE id = ?", id12);
|
|
135697
|
-
var allUsers = (ctx) =>
|
|
135698
|
-
var allTeams = (ctx) =>
|
|
135699
|
-
var allStates = (ctx) =>
|
|
135700
|
-
var allLabels = (ctx) =>
|
|
135701
|
-
var allProjects = (ctx) =>
|
|
135702
|
-
var allIssues = (ctx) =>
|
|
135703
|
-
var allComments = (ctx) =>
|
|
135704
|
-
var teamMemberIds = (ctx, teamId) =>
|
|
135705
|
-
var userTeamIds = (ctx, userId) =>
|
|
135706
|
-
var issueLabelIds = (ctx, issueId) =>
|
|
135707
|
-
var projectTeamIds = (ctx, projectId) =>
|
|
135854
|
+
var allUsers = (ctx) => all2(ctx, "SELECT * FROM linear_users ORDER BY rowid");
|
|
135855
|
+
var allTeams = (ctx) => all2(ctx, "SELECT * FROM linear_teams ORDER BY rowid");
|
|
135856
|
+
var allStates = (ctx) => all2(ctx, "SELECT * FROM linear_states ORDER BY rowid");
|
|
135857
|
+
var allLabels = (ctx) => all2(ctx, "SELECT * FROM linear_labels ORDER BY rowid");
|
|
135858
|
+
var allProjects = (ctx) => all2(ctx, "SELECT * FROM linear_projects ORDER BY rowid");
|
|
135859
|
+
var allIssues = (ctx) => all2(ctx, "SELECT * FROM linear_issues ORDER BY rowid");
|
|
135860
|
+
var allComments = (ctx) => all2(ctx, "SELECT * FROM linear_comments ORDER BY rowid");
|
|
135861
|
+
var teamMemberIds = (ctx, teamId) => all2(ctx, "SELECT user_id FROM linear_team_members WHERE team_id = ? ORDER BY rowid", teamId).map((r) => r.user_id);
|
|
135862
|
+
var userTeamIds = (ctx, userId) => all2(ctx, "SELECT team_id FROM linear_team_members WHERE user_id = ? ORDER BY rowid", userId).map((r) => r.team_id);
|
|
135863
|
+
var issueLabelIds = (ctx, issueId) => all2(ctx, "SELECT label_id FROM linear_issue_labels WHERE issue_id = ? ORDER BY rowid", issueId).map((r) => r.label_id);
|
|
135864
|
+
var projectTeamIds = (ctx, projectId) => all2(ctx, "SELECT team_id FROM linear_project_teams WHERE project_id = ? ORDER BY rowid", projectId).map((r) => r.team_id);
|
|
135708
135865
|
function uuid5(ctx) {
|
|
135709
135866
|
const hex5 = ctx.ids.hex(32).split("");
|
|
135710
135867
|
hex5[12] = "4";
|
|
@@ -135749,7 +135906,7 @@ init_src();
|
|
|
135749
135906
|
var scalar = (comparator, column) => ({ kind: "scalar", comparator, get: (_, row) => row[column] });
|
|
135750
135907
|
var ts = (column) => scalar("date", column);
|
|
135751
135908
|
var db = (r) => r.ctx.store.db;
|
|
135752
|
-
var
|
|
135909
|
+
var all3 = (r, sql, ...args) => db(r).prepare(sql).all(...args);
|
|
135753
135910
|
var SPECS = {
|
|
135754
135911
|
Issue: {
|
|
135755
135912
|
id: scalar("id", "id"),
|
|
@@ -135772,10 +135929,10 @@ ${row.description ?? ""}` },
|
|
|
135772
135929
|
assignee: { kind: "one", type: "User", get: (r, row) => row.assignee_id ? userById(r.ctx, row.assignee_id) : void 0 },
|
|
135773
135930
|
creator: { kind: "one", type: "User", get: (r, row) => row.creator_id ? userById(r.ctx, row.creator_id) : void 0 },
|
|
135774
135931
|
project: { kind: "one", type: "Project", get: (r, row) => row.project_id ? projectById(r.ctx, row.project_id) : void 0 },
|
|
135775
|
-
parent: { kind: "one", type: "Issue", get: (r, row) => row.parent_id ?
|
|
135932
|
+
parent: { kind: "one", type: "Issue", get: (r, row) => row.parent_id ? all3(r, "SELECT * FROM linear_issues WHERE id = ?", row.parent_id)[0] : void 0 },
|
|
135776
135933
|
labels: { kind: "many", type: "IssueLabel", get: (r, row) => issueLabelIds(r.ctx, row.id).map((id12) => labelById(r.ctx, id12)) },
|
|
135777
|
-
children: { kind: "many", type: "Issue", get: (r, row) =>
|
|
135778
|
-
comments: { kind: "many", type: "Comment", get: (r, row) =>
|
|
135934
|
+
children: { kind: "many", type: "Issue", get: (r, row) => all3(r, "SELECT * FROM linear_issues WHERE parent_id = ? ORDER BY rowid", row.id) },
|
|
135935
|
+
comments: { kind: "many", type: "Comment", get: (r, row) => all3(r, "SELECT * FROM linear_comments WHERE issue_id = ? ORDER BY rowid", row.id) }
|
|
135779
135936
|
},
|
|
135780
135937
|
Team: {
|
|
135781
135938
|
id: scalar("id", "id"),
|
|
@@ -135786,7 +135943,7 @@ ${row.description ?? ""}` },
|
|
|
135786
135943
|
createdAt: ts("created_at"),
|
|
135787
135944
|
updatedAt: ts("updated_at"),
|
|
135788
135945
|
members: { kind: "many", type: "User", get: (r, row) => teamMemberIds(r.ctx, row.id).map((id12) => userById(r.ctx, id12)) },
|
|
135789
|
-
issues: { kind: "many", type: "Issue", get: (r, row) =>
|
|
135946
|
+
issues: { kind: "many", type: "Issue", get: (r, row) => all3(r, "SELECT * FROM linear_issues WHERE team_id = ? ORDER BY rowid", row.id) }
|
|
135790
135947
|
},
|
|
135791
135948
|
User: {
|
|
135792
135949
|
id: scalar("id", "id"),
|
|
@@ -135799,7 +135956,7 @@ ${row.description ?? ""}` },
|
|
|
135799
135956
|
app: { kind: "scalar", comparator: "boolean", get: () => false },
|
|
135800
135957
|
createdAt: ts("created_at"),
|
|
135801
135958
|
updatedAt: ts("updated_at"),
|
|
135802
|
-
assignedIssues: { kind: "many", type: "Issue", get: (r, row) =>
|
|
135959
|
+
assignedIssues: { kind: "many", type: "Issue", get: (r, row) => all3(r, "SELECT * FROM linear_issues WHERE assignee_id = ? ORDER BY rowid", row.id) }
|
|
135803
135960
|
},
|
|
135804
135961
|
WorkflowState: {
|
|
135805
135962
|
id: scalar("id", "id"),
|
|
@@ -135810,7 +135967,7 @@ ${row.description ?? ""}` },
|
|
|
135810
135967
|
createdAt: ts("created_at"),
|
|
135811
135968
|
updatedAt: ts("updated_at"),
|
|
135812
135969
|
team: { kind: "one", type: "Team", get: (r, row) => teamById(r.ctx, row.team_id) },
|
|
135813
|
-
issues: { kind: "many", type: "Issue", get: (r, row) =>
|
|
135970
|
+
issues: { kind: "many", type: "Issue", get: (r, row) => all3(r, "SELECT * FROM linear_issues WHERE state_id = ? ORDER BY rowid", row.id) }
|
|
135814
135971
|
},
|
|
135815
135972
|
IssueLabel: {
|
|
135816
135973
|
id: scalar("id", "id"),
|
|
@@ -135826,9 +135983,9 @@ ${row.description ?? ""}` },
|
|
|
135826
135983
|
body: scalar("string", "body"),
|
|
135827
135984
|
createdAt: ts("created_at"),
|
|
135828
135985
|
updatedAt: ts("updated_at"),
|
|
135829
|
-
issue: { kind: "one", type: "Issue", get: (r, row) =>
|
|
135986
|
+
issue: { kind: "one", type: "Issue", get: (r, row) => all3(r, "SELECT * FROM linear_issues WHERE id = ?", row.issue_id)[0] },
|
|
135830
135987
|
user: { kind: "one", type: "User", get: (r, row) => userById(r.ctx, row.user_id) },
|
|
135831
|
-
parent: { kind: "one", type: "Comment", get: (r, row) => row.parent_id ?
|
|
135988
|
+
parent: { kind: "one", type: "Comment", get: (r, row) => row.parent_id ? all3(r, "SELECT * FROM linear_comments WHERE id = ?", row.parent_id)[0] : void 0 }
|
|
135832
135989
|
},
|
|
135833
135990
|
Project: {
|
|
135834
135991
|
id: scalar("id", "id"),
|
|
@@ -135845,7 +136002,7 @@ ${row.description ?? ""}` },
|
|
|
135845
136002
|
searchableContent: { kind: "scalar", comparator: "content", get: (_, row) => `${row.name}
|
|
135846
136003
|
${row.description ?? ""}` },
|
|
135847
136004
|
lead: { kind: "one", type: "User", get: (r, row) => row.lead_id ? userById(r.ctx, row.lead_id) : void 0 },
|
|
135848
|
-
issues: { kind: "many", type: "Issue", get: (r, row) =>
|
|
136005
|
+
issues: { kind: "many", type: "Issue", get: (r, row) => all3(r, "SELECT * FROM linear_issues WHERE project_id = ? ORDER BY rowid", row.id) }
|
|
135849
136006
|
}
|
|
135850
136007
|
};
|
|
135851
136008
|
function dateValue2(r, value4) {
|
|
@@ -136728,8 +136885,8 @@ function seed17(ctx) {
|
|
|
136728
136885
|
states.set(s.name.toLowerCase(), stateId);
|
|
136729
136886
|
db2.prepare("INSERT INTO linear_states (id, team_id, name, type, color, position, description, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(stateId, id12, s.name, s.type, s.color ?? "#bec2c8", position, ("description" in s ? s.description : void 0) ?? null, workspaceCreated, workspaceCreated);
|
|
136730
136887
|
});
|
|
136731
|
-
const
|
|
136732
|
-
const initial = t.default_state ?? (
|
|
136888
|
+
const all8 = t.states ?? LINEAR_DEFAULT_STATES;
|
|
136889
|
+
const initial = t.default_state ?? (all8.find((s) => s.type === "backlog") ?? all8.find((s) => s.type === "unstarted")).name;
|
|
136733
136890
|
db2.prepare("UPDATE linear_teams SET default_state_id = ? WHERE id = ?").run(states.get(initial.toLowerCase()), id12);
|
|
136734
136891
|
for (const l of t.labels) {
|
|
136735
136892
|
const labelId = uuid5(ctx);
|
|
@@ -137959,7 +138116,7 @@ function save6(ctx, value4) {
|
|
|
137959
138116
|
db2.prepare("INSERT OR REPLACE INTO stripe_objects (id, type, seq, created, customer, json) VALUES (?, ?, ?, ?, ?, ?)").run(value4.id, value4.object, seq2, typeof value4.created === "number" ? value4.created : 0, customer3, JSON.stringify(value4));
|
|
137960
138117
|
return value4;
|
|
137961
138118
|
}
|
|
137962
|
-
function
|
|
138119
|
+
function all4(ctx, type) {
|
|
137963
138120
|
return ctx.store.db.prepare("SELECT json FROM stripe_objects WHERE type = ? ORDER BY created DESC, seq DESC").all(type).map((r) => JSON.parse(r.json));
|
|
137964
138121
|
}
|
|
137965
138122
|
var BASE622 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
@@ -139279,7 +139436,7 @@ function markPaid(ctx, inv, at3, amount3 = inv.amount_remaining, offStripe = fal
|
|
|
139279
139436
|
const sub2 = inv.parent?.subscription_details?.subscription ? load(ctx, inv.parent.subscription_details.subscription) : void 0;
|
|
139280
139437
|
if (sub2 && (sub2.status === "past_due" || sub2.status === "unpaid" || sub2.status === "incomplete") && !openInvoices(ctx, sub2.id).some((i) => i.id !== inv.id)) save6(ctx, { ...sub2, status: "active" });
|
|
139281
139438
|
}
|
|
139282
|
-
var openInvoices = (ctx, subscription2) =>
|
|
139439
|
+
var openInvoices = (ctx, subscription2) => all4(ctx, "invoice").filter((i) => i.status === "open" && i.parent?.subscription_details?.subscription === subscription2);
|
|
139283
139440
|
function pay(ctx, inv, o) {
|
|
139284
139441
|
if (inv.status === "paid") invalid13("Invoice is already paid");
|
|
139285
139442
|
if (inv.status === "void") invalid13("You cannot pay a void invoice.");
|
|
@@ -139313,7 +139470,7 @@ function voidInvoice(ctx, inv) {
|
|
|
139313
139470
|
if (inv.status === "void") invalid13("This invoice is already void.", void 0, "invoice_not_editable");
|
|
139314
139471
|
const at3 = nowSeconds(ctx);
|
|
139315
139472
|
Object.assign(inv, { status: "void", amount_remaining: 0, next_payment_attempt: null, auto_advance: false, status_transitions: { ...inv.status_transitions, voided_at: at3 } });
|
|
139316
|
-
for (const item2 of
|
|
139473
|
+
for (const item2 of all4(ctx, "invoiceitem").filter((i) => i.invoice === inv.id)) save6(ctx, item2);
|
|
139317
139474
|
return save6(ctx, inv);
|
|
139318
139475
|
}
|
|
139319
139476
|
function prorate(ctx, sub2, item2, oldPrice, oldQuantity, newPrice, newQuantity) {
|
|
@@ -139400,7 +139557,7 @@ function searchCustomers(ctx, params9, present2) {
|
|
|
139400
139557
|
const limit2 = int2(params9.limit, "limit") ?? 10;
|
|
139401
139558
|
if (limit2 < 1 || limit2 > 100) invalid13("Invalid limit: must be between 1 and 100.", "limit");
|
|
139402
139559
|
const { clauses: tests, or } = clauses(query11);
|
|
139403
|
-
const matches7 =
|
|
139560
|
+
const matches7 = all4(ctx, "customer").filter((c) => !c.deleted && (or ? tests.some((t) => t(c)) : tests.every((t) => t(c))));
|
|
139404
139561
|
const token2 = str(params9.page, "page");
|
|
139405
139562
|
const offset16 = token2 === void 0 ? 0 : Number(/^page_(\d+)$/.exec(token2)?.[1] ?? NaN);
|
|
139406
139563
|
if (!Number.isSafeInteger(offset16)) invalid13(`Invalid page: ${token2}`, "page");
|
|
@@ -139474,7 +139631,7 @@ function customerFields(r, c) {
|
|
|
139474
139631
|
function presentCustomer(ctx, c) {
|
|
139475
139632
|
if (c.deleted) return deletedStub(c);
|
|
139476
139633
|
const now10 = nowSeconds(ctx);
|
|
139477
|
-
return { ...c, delinquent:
|
|
139634
|
+
return { ...c, delinquent: all4(ctx, "invoice").some((i) => i.customer === c.id && i.status === "open" && (i.due_date !== null && i.due_date < now10 || i.attempt_count > 0)) };
|
|
139478
139635
|
}
|
|
139479
139636
|
var read4 = (path6, supported3, run6, notes6) => ({ method: "GET", path: path6, supported: supported3, run: run6, coverage: notes6 ? { status: "partial", notes: notes6 } : { status: "supported" } });
|
|
139480
139637
|
var write3 = (method2, path6, supported3, run6, notes6) => ({ method: method2, path: path6, supported: supported3, run: run6, coverage: notes6 ? { status: "partial", notes: notes6 } : { status: "supported" } });
|
|
@@ -139488,7 +139645,7 @@ var stripeRoutes = [
|
|
|
139488
139645
|
}, "invoice_settings supports default_payment_method only; addresses, shipping, tax ids and cash balances are gaps"),
|
|
139489
139646
|
read4("/v1/customers", ["email", "created", ...PAGE], (r) => {
|
|
139490
139647
|
const email10 = str(r.params.email, "email", 512);
|
|
139491
|
-
const items = filterCreated(
|
|
139648
|
+
const items = filterCreated(all4(r.ctx, "customer").filter((c) => !c.deleted && (email10 === void 0 || c.email === email10)), r.params);
|
|
139492
139649
|
const result = page7(items, r.params, "/v1/customers", "customer");
|
|
139493
139650
|
return { ...result, data: result.data.map((c) => presentCustomer(r.ctx, c)) };
|
|
139494
139651
|
}),
|
|
@@ -139501,7 +139658,7 @@ var stripeRoutes = [
|
|
|
139501
139658
|
}),
|
|
139502
139659
|
write3("DELETE", "/v1/customers/:id", [], (r) => {
|
|
139503
139660
|
const c = liveCustomer(r.ctx, r.id, "id");
|
|
139504
|
-
for (const sub2 of
|
|
139661
|
+
for (const sub2 of all4(r.ctx, "subscription").filter((s) => s.customer === c.id && s.status !== "canceled")) {
|
|
139505
139662
|
const at3 = nowSeconds(r.ctx);
|
|
139506
139663
|
save6(r.ctx, { ...sub2, status: "canceled", canceled_at: at3, ended_at: at3, cancellation_details: { ...sub2.cancellation_details, reason: "cancellation_requested" } });
|
|
139507
139664
|
}
|
|
@@ -139511,20 +139668,20 @@ var stripeRoutes = [
|
|
|
139511
139668
|
/* ----------------------------- products and prices ---------------------------- */
|
|
139512
139669
|
read4("/v1/products", ["active", "ids", "created", ...PAGE], (r) => {
|
|
139513
139670
|
const active3 = bool3(r.params.active, "active"), ids2 = list10(r.params.ids, "ids")?.map((v, i) => str(v, `ids[${i}]`));
|
|
139514
|
-
return page7(filterCreated(
|
|
139671
|
+
return page7(filterCreated(all4(r.ctx, "product").filter((p2) => (active3 === void 0 || p2.active === active3) && (!ids2 || ids2.includes(p2.id))), r.params), r.params, "/v1/products", "product");
|
|
139515
139672
|
}),
|
|
139516
139673
|
read4("/v1/products/:id", [], (r) => find4(r.ctx, "product", r.id)),
|
|
139517
139674
|
read4("/v1/prices", ["product", "active", "type", "currency", "lookup_keys", "created", ...PAGE], (r) => {
|
|
139518
139675
|
const product2 = str(r.params.product, "product"), active3 = bool3(r.params.active, "active"), type = oneOf(r.params.type, "type", ["one_time", "recurring"]);
|
|
139519
139676
|
const currency = str(r.params.currency, "currency")?.toLowerCase(), keys5 = list10(r.params.lookup_keys, "lookup_keys")?.map((v, i) => str(v, `lookup_keys[${i}]`));
|
|
139520
|
-
return page7(filterCreated(
|
|
139677
|
+
return page7(filterCreated(all4(r.ctx, "price").filter((p2) => (!product2 || p2.product === product2) && (active3 === void 0 || p2.active === active3) && (!type || p2.type === type) && (!currency || p2.currency === currency) && (!keys5 || keys5.includes(p2.lookup_key))), r.params), r.params, "/v1/prices", "price");
|
|
139521
139678
|
}),
|
|
139522
139679
|
read4("/v1/prices/:id", [], (r) => find4(r.ctx, "price", r.id)),
|
|
139523
139680
|
/* --------------------------------- subscriptions ------------------------------- */
|
|
139524
139681
|
read4("/v1/subscriptions", ["customer", "price", "status", "created", ...PAGE], (r) => {
|
|
139525
139682
|
const customer3 = str(r.params.customer, "customer"), priceId = str(r.params.price, "price");
|
|
139526
139683
|
const status5 = oneOf(r.params.status, "status", ["active", "all", "canceled", "ended", "incomplete", "incomplete_expired", "past_due", "paused", "trialing", "unpaid"]);
|
|
139527
|
-
const items =
|
|
139684
|
+
const items = all4(r.ctx, "subscription").filter((s) => (!customer3 || s.customer === customer3) && (!priceId || s.items.data.some((i) => i.price.id === priceId)) && (status5 === "all" || (status5 === void 0 ? s.status !== "canceled" && s.status !== "incomplete_expired" : status5 === "ended" ? s.status === "canceled" : s.status === status5)));
|
|
139528
139685
|
return page7(filterCreated(items, r.params), r.params, "/v1/subscriptions", "subscription");
|
|
139529
139686
|
}, "without status, canceled subscriptions are left out, as Stripe does"),
|
|
139530
139687
|
read4("/v1/subscriptions/:id", [], (r) => find4(r.ctx, "subscription", r.id)),
|
|
@@ -139607,7 +139764,7 @@ var stripeRoutes = [
|
|
|
139607
139764
|
read4("/v1/invoices", ["customer", "subscription", "status", "collection_method", "created", ...PAGE], (r) => {
|
|
139608
139765
|
const customer3 = str(r.params.customer, "customer"), subscription2 = str(r.params.subscription, "subscription");
|
|
139609
139766
|
const status5 = oneOf(r.params.status, "status", ["draft", "open", "paid", "uncollectible", "void"]), method2 = oneOf(r.params.collection_method, "collection_method", ["charge_automatically", "send_invoice"]);
|
|
139610
|
-
return page7(filterCreated(
|
|
139767
|
+
return page7(filterCreated(all4(r.ctx, "invoice").filter((i) => (!customer3 || i.customer === customer3) && (!subscription2 || i.parent?.subscription_details?.subscription === subscription2) && (!status5 || i.status === status5) && (!method2 || i.collection_method === method2)), r.params), r.params, "/v1/invoices", "invoice");
|
|
139611
139768
|
}),
|
|
139612
139769
|
read4("/v1/invoices/:id", [], (r) => find4(r.ctx, "invoice", r.id)),
|
|
139613
139770
|
write3("POST", "/v1/invoices", ["customer", "auto_advance", "collection_method", "days_until_due", "due_date", "description", "footer", "custom_fields", "metadata", "currency", "pending_invoice_items_behavior", "subscription"], (r) => {
|
|
@@ -139639,7 +139796,7 @@ var stripeRoutes = [
|
|
|
139639
139796
|
period: { start: now10, end: now10 }
|
|
139640
139797
|
});
|
|
139641
139798
|
save6(r.ctx, inv);
|
|
139642
|
-
if (behavior === "include") for (const item2 of
|
|
139799
|
+
if (behavior === "include") for (const item2 of all4(r.ctx, "invoiceitem").filter((i) => i.customer === c.id && i.invoice === null && (!sub2 || i.parent?.subscription_details?.subscription === sub2.id)).reverse()) addLine(r.ctx, inv, item2);
|
|
139643
139800
|
return save6(r.ctx, recalc(inv));
|
|
139644
139801
|
}, "pending invoice items are included only with pending_invoice_items_behavior=include, the default for new API versions"),
|
|
139645
139802
|
write3("POST", "/v1/invoices/:id", ["description", "footer", "custom_fields", "metadata", "auto_advance", "days_until_due", "due_date"], (r) => {
|
|
@@ -139715,7 +139872,7 @@ var stripeRoutes = [
|
|
|
139715
139872
|
read4("/v1/invoiceitems", ["customer", "invoice", "pending", "created", ...PAGE], (r) => {
|
|
139716
139873
|
const customer3 = str(r.params.customer, "customer"), invoiceId = str(r.params.invoice, "invoice"), pending = bool3(r.params.pending, "pending");
|
|
139717
139874
|
return page7(
|
|
139718
|
-
filterCreated(
|
|
139875
|
+
filterCreated(all4(r.ctx, "invoiceitem").filter((i) => (!customer3 || i.customer === customer3) && (!invoiceId || i.invoice === invoiceId) && (pending === void 0 || i.invoice === null === pending)), r.params, "date"),
|
|
139719
139876
|
r.params,
|
|
139720
139877
|
"/v1/invoiceitems",
|
|
139721
139878
|
"invoiceitem"
|
|
@@ -139755,7 +139912,7 @@ var stripeRoutes = [
|
|
|
139755
139912
|
}, "card payments with a saved payment method or a test token such as pm_card_visa; pm_card_chargeDeclined* tokens decline; 3D Secure, manual capture and other methods are gaps"),
|
|
139756
139913
|
read4("/v1/payment_intents", ["customer", "created", ...PAGE], (r) => {
|
|
139757
139914
|
const customer3 = str(r.params.customer, "customer");
|
|
139758
|
-
return page7(filterCreated(
|
|
139915
|
+
return page7(filterCreated(all4(r.ctx, "payment_intent").filter((pi) => !customer3 || pi.customer === customer3), r.params), r.params, "/v1/payment_intents", "payment_intent");
|
|
139759
139916
|
}),
|
|
139760
139917
|
read4("/v1/payment_intents/:id", ["client_secret"], (r) => find4(r.ctx, "payment_intent", r.id)),
|
|
139761
139918
|
write3("POST", "/v1/payment_intents/:id/confirm", ["payment_method", "off_session", "receipt_email"], (r) => {
|
|
@@ -139778,7 +139935,7 @@ var stripeRoutes = [
|
|
|
139778
139935
|
/* -------------------------------- charges, refunds ------------------------------- */
|
|
139779
139936
|
read4("/v1/charges", ["customer", "payment_intent", "created", ...PAGE], (r) => {
|
|
139780
139937
|
const customer3 = str(r.params.customer, "customer"), intent = str(r.params.payment_intent, "payment_intent");
|
|
139781
|
-
return page7(filterCreated(
|
|
139938
|
+
return page7(filterCreated(all4(r.ctx, "charge").filter((ch) => (!customer3 || ch.customer === customer3) && (!intent || ch.payment_intent === intent)), r.params), r.params, "/v1/charges", "charge");
|
|
139782
139939
|
}),
|
|
139783
139940
|
read4("/v1/charges/:id", [], (r) => find4(r.ctx, "charge", r.id)),
|
|
139784
139941
|
write3("POST", "/v1/refunds", ["charge", "payment_intent", "amount", "reason", "metadata"], (r) => {
|
|
@@ -139796,7 +139953,7 @@ var stripeRoutes = [
|
|
|
139796
139953
|
}, "card refunds settle at once (status succeeded)"),
|
|
139797
139954
|
read4("/v1/refunds", ["charge", "payment_intent", "created", ...PAGE], (r) => {
|
|
139798
139955
|
const chargeId = str(r.params.charge, "charge"), intent = str(r.params.payment_intent, "payment_intent");
|
|
139799
|
-
return page7(filterCreated(
|
|
139956
|
+
return page7(filterCreated(all4(r.ctx, "refund").filter((re) => (!chargeId || re.charge === chargeId) && (!intent || re.payment_intent === intent)), r.params), r.params, "/v1/refunds", "refund");
|
|
139800
139957
|
}),
|
|
139801
139958
|
read4("/v1/refunds/:id", [], (r) => find4(r.ctx, "refund", r.id)),
|
|
139802
139959
|
read4("/v1/balance", [], (r) => load(r.ctx, "__balance"), "available and pending card funds; payouts and fees are not modeled")
|
|
@@ -139965,7 +140122,7 @@ function seed19(ctx) {
|
|
|
139965
140122
|
save6(ctx, row);
|
|
139966
140123
|
}
|
|
139967
140124
|
}
|
|
139968
|
-
if (sub2) save6(ctx, { ...load(ctx, sub2.id), latest_invoice:
|
|
140125
|
+
if (sub2) save6(ctx, { ...load(ctx, sub2.id), latest_invoice: all4(ctx, "invoice").find((i) => i.parent?.subscription_details?.subscription === sub2.id)?.id ?? null });
|
|
139969
140126
|
}
|
|
139970
140127
|
for (const p2 of data5.payments) {
|
|
139971
140128
|
const cus = p2.customer ? load(ctx, customers.get(p2.customer).id) : null, t = at3(p2.created);
|
|
@@ -139989,7 +140146,7 @@ function credentials18(ctx) {
|
|
|
139989
140146
|
|
|
139990
140147
|
// packages/server/src/twins/stripe/state.ts
|
|
139991
140148
|
function dumpState18(ctx) {
|
|
139992
|
-
const of = (type) => present(
|
|
140149
|
+
const of = (type) => present(all4(ctx, type).reverse());
|
|
139993
140150
|
return {
|
|
139994
140151
|
balance: present(load(ctx, "__balance")),
|
|
139995
140152
|
customers: of("customer"),
|
|
@@ -140623,8 +140780,8 @@ var flagUser = (column, value4) => (call2) => {
|
|
|
140623
140780
|
function userMemberships(call2) {
|
|
140624
140781
|
const query11 = params7(call2, ["limit", "offset"]);
|
|
140625
140782
|
const user8 = userFor2(call2);
|
|
140626
|
-
const
|
|
140627
|
-
return respond3(call2, 200, { data: list11(
|
|
140783
|
+
const all8 = call2.ctx.store.db.prepare("SELECT * FROM clerk_memberships WHERE user_id = ? ORDER BY created_ms, id").all(user8.id);
|
|
140784
|
+
return respond3(call2, 200, { data: list11(all8, query11).map((member4) => membershipJson(call2.ctx, member4)), total_count: all8.length });
|
|
140628
140785
|
}
|
|
140629
140786
|
function orgFor(call2) {
|
|
140630
140787
|
const org5 = getOrg(call2.ctx, call2.ids[0]);
|
|
@@ -143014,7 +143171,7 @@ function migrate22(db2) {
|
|
|
143014
143171
|
db2.exec(SCHEMA13);
|
|
143015
143172
|
}
|
|
143016
143173
|
var one2 = (ctx, sql, ...args) => ctx.store.db.prepare(sql).get(...args);
|
|
143017
|
-
var
|
|
143174
|
+
var all5 = (ctx, sql, ...args) => ctx.store.db.prepare(sql).all(...args);
|
|
143018
143175
|
var run2 = (ctx, sql, ...args) => ctx.store.db.prepare(sql).run(...args);
|
|
143019
143176
|
function uuid9(ctx) {
|
|
143020
143177
|
const h = ctx.ids.hex(32).split("");
|
|
@@ -143240,7 +143397,7 @@ function primary(ctx, attr, data5) {
|
|
|
143240
143397
|
}
|
|
143241
143398
|
}
|
|
143242
143399
|
function currentValues(ctx, parentId, attributeId) {
|
|
143243
|
-
return
|
|
143400
|
+
return all5(ctx, "SELECT * FROM attio_values WHERE parent_id = ? AND attribute_id = ? AND active_until IS NULL ORDER BY id", parentId, attributeId);
|
|
143244
143401
|
}
|
|
143245
143402
|
function writeValues(ctx, parentId, attr, items, by2, replace, now10 = attioTime(ctx.clock.nowMs())) {
|
|
143246
143403
|
const current = currentValues(ctx, parentId, attr.id);
|
|
@@ -143316,7 +143473,7 @@ function findObject(ctx, key3) {
|
|
|
143316
143473
|
function findList(ctx, key3) {
|
|
143317
143474
|
return one2(ctx, "SELECT * FROM attio_lists WHERE api_slug = ? OR id = ?", key3, key3) ?? notFound9(`List with slug/ID "${key3}" not found.`);
|
|
143318
143475
|
}
|
|
143319
|
-
var attributesOf = (ctx, parentId) =>
|
|
143476
|
+
var attributesOf = (ctx, parentId) => all5(ctx, "SELECT * FROM attio_attributes WHERE parent_id = ? ORDER BY position", parentId);
|
|
143320
143477
|
var listParent = (list15) => `list:${list15.id}`;
|
|
143321
143478
|
function objectShape(ctx, o) {
|
|
143322
143479
|
return { id: { workspace_id: workspaceId(ctx), object_id: o.id }, api_slug: o.api_slug, singular_noun: o.singular_noun, plural_noun: o.plural_noun, created_at: o.created_at };
|
|
@@ -143346,7 +143503,7 @@ function memberShape(ctx, m) {
|
|
|
143346
143503
|
return { id: { workspace_id: workspaceId(ctx), workspace_member_id: m.id }, first_name: m.first_name, last_name: m.last_name, avatar_url: null, email_address: m.email, created_at: m.created_at, access_level: m.access_level };
|
|
143347
143504
|
}
|
|
143348
143505
|
function valuesOf(ctx, parentId, attributes2, computed) {
|
|
143349
|
-
const rows33 =
|
|
143506
|
+
const rows33 = all5(ctx, "SELECT * FROM attio_values WHERE parent_id = ? AND active_until IS NULL ORDER BY id", parentId);
|
|
143350
143507
|
return Object.fromEntries(attributes2.map((a) => [a.api_slug, computed(a) ?? rows33.filter((r) => r.attribute_id === a.id).map((r) => valueObject(ctx, a, r))]));
|
|
143351
143508
|
}
|
|
143352
143509
|
function recordShape(ctx, r) {
|
|
@@ -143364,7 +143521,7 @@ function recordShape(ctx, r) {
|
|
|
143364
143521
|
if (o.api_slug === "companies" && a.api_slug === "team") {
|
|
143365
143522
|
const people3 = one2(ctx, "SELECT * FROM attio_objects WHERE api_slug = 'people'");
|
|
143366
143523
|
const company = one2(ctx, "SELECT * FROM attio_attributes WHERE parent_id = ? AND api_slug = 'company'", people3.id);
|
|
143367
|
-
return
|
|
143524
|
+
return all5(ctx, "SELECT * FROM attio_values WHERE attribute_id = ? AND active_until IS NULL AND json_extract(data, '$.target_record_id') = ? ORDER BY id", company.id, r.id).map((v) => ({ active_from: v.active_from, active_until: null, created_by_actor: JSON.parse(v.created_by), target_object: "people", target_record_id: v.parent_id, attribute_type: "record-reference" }));
|
|
143368
143525
|
}
|
|
143369
143526
|
return void 0;
|
|
143370
143527
|
})
|
|
@@ -143432,7 +143589,7 @@ function writeAll(r, parentId, attributes2, values2, mode, objectSlug) {
|
|
|
143432
143589
|
const items = list15.map((v) => parseValue(r.ctx, attr, v));
|
|
143433
143590
|
if (attr.is_unique) for (const item2 of items) {
|
|
143434
143591
|
const key4 = primary(r.ctx, attr, item2);
|
|
143435
|
-
const clash =
|
|
143592
|
+
const clash = all5(r.ctx, "SELECT * FROM attio_values WHERE attribute_id = ? AND active_until IS NULL AND parent_id != ?", attr.id, parentId).find((v) => primary(r.ctx, attr, JSON.parse(v.data)) === key4);
|
|
143436
143593
|
if (clash) invalid17(`A record with the value "${String(key4)}" for the unique attribute "${attr.api_slug}" already exists.`, "uniqueness_conflict");
|
|
143437
143594
|
}
|
|
143438
143595
|
writeValues(r.ctx, parentId, attr, items, tokenActor(r), mode !== "append" || !attr.is_multiselect);
|
|
@@ -143484,7 +143641,7 @@ function query8(r, rows33, attributes2) {
|
|
|
143484
143641
|
const { limit: limit2, offset: offset16 } = limitOffset(r.body);
|
|
143485
143642
|
return kept.slice(offset16, offset16 + limit2);
|
|
143486
143643
|
}
|
|
143487
|
-
var records = (r, object16) =>
|
|
143644
|
+
var records = (r, object16) => all5(r.ctx, "SELECT * FROM attio_records WHERE object_id = ? ORDER BY created_at, rowid", object16.id);
|
|
143488
143645
|
function memberRef(r, value4) {
|
|
143489
143646
|
const key3 = value4?.referenced_actor_id ?? value4?.workspace_member_email_address;
|
|
143490
143647
|
const m = typeof key3 === "string" ? one2(r.ctx, "SELECT * FROM attio_members WHERE id = ? OR lower(email) = lower(?)", key3, key3) : void 0;
|
|
@@ -143526,7 +143683,7 @@ var attioRoutes = [
|
|
|
143526
143683
|
workspace_logo_url: null
|
|
143527
143684
|
};
|
|
143528
143685
|
} },
|
|
143529
|
-
{ method: "GET", path: "/v2/objects", coverage: { status: "supported" }, run: (r) => ({ data:
|
|
143686
|
+
{ method: "GET", path: "/v2/objects", coverage: { status: "supported" }, run: (r) => ({ data: all5(r.ctx, "SELECT * FROM attio_objects ORDER BY rowid").map((o) => objectShape(r.ctx, o)) }) },
|
|
143530
143687
|
{ method: "GET", path: "/v2/objects/:object", coverage: { status: "supported" }, run: (r) => ({ data: objectShape(r.ctx, findObject(r.ctx, r.param("object"))) }) },
|
|
143531
143688
|
{ method: "GET", path: "/v2/:target/:identifier/attributes", query: { known: ["limit", "offset", "show_archived"], supported: ["limit", "offset", "show_archived"] }, coverage: { status: "supported" }, run: (r) => {
|
|
143532
143689
|
const target5 = r.param("target");
|
|
@@ -143567,7 +143724,7 @@ var attioRoutes = [
|
|
|
143567
143724
|
const given = (r.data.values ?? {})[attr.api_slug] ?? (r.data.values ?? {})[attr.id];
|
|
143568
143725
|
if (given === void 0) invalid17(`The values must include the matching attribute "${attr.api_slug}".`, "missing_value");
|
|
143569
143726
|
const wanted = (Array.isArray(given) ? given : [given]).map((v) => primary(r.ctx, attr, parseValue(r.ctx, attr, v)));
|
|
143570
|
-
const owners = new Set(
|
|
143727
|
+
const owners = new Set(all5(r.ctx, "SELECT * FROM attio_values WHERE attribute_id = ? AND active_until IS NULL", attr.id).filter((v) => wanted.includes(primary(r.ctx, attr, JSON.parse(v.data)))).map((v) => v.parent_id));
|
|
143571
143728
|
if (owners.size > 1) invalid17("More than one record matches the given value.", "multiple_match_results");
|
|
143572
143729
|
if (!owners.size) return { data: recordShape(r.ctx, createRecord3(r, object16, r.data.values)) };
|
|
143573
143730
|
const id12 = [...owners][0];
|
|
@@ -143600,7 +143757,7 @@ var attioRoutes = [
|
|
|
143600
143757
|
},
|
|
143601
143758
|
{ method: "DELETE", path: RECORD_PATH, coverage: { status: "supported" }, run: (r) => {
|
|
143602
143759
|
const rec = findRecord(r, findObject(r.ctx, r.param("object")));
|
|
143603
|
-
for (const e of
|
|
143760
|
+
for (const e of all5(r.ctx, "SELECT * FROM attio_entries WHERE record_id = ?", rec.id)) {
|
|
143604
143761
|
run2(r.ctx, "DELETE FROM attio_values WHERE parent_id = ?", e.id);
|
|
143605
143762
|
run2(r.ctx, "DELETE FROM attio_entries WHERE id = ?", e.id);
|
|
143606
143763
|
}
|
|
@@ -143617,7 +143774,7 @@ var attioRoutes = [
|
|
|
143617
143774
|
const object16 = findObject(r.ctx, r.param("object")), rec = findRecord(r, object16);
|
|
143618
143775
|
const attr = attributesOf(r.ctx, object16.id).find((a) => a.api_slug === r.param("attribute") || a.id === r.param("attribute")) ?? notFound9(`Attribute with slug/ID "${r.param("attribute")}" not found.`);
|
|
143619
143776
|
const historic = r.query.get("show_historic") === "true";
|
|
143620
|
-
const rows33 =
|
|
143777
|
+
const rows33 = all5(r.ctx, `SELECT * FROM attio_values WHERE parent_id = ? AND attribute_id = ? ${historic ? "" : "AND active_until IS NULL"} ORDER BY id`, rec.id, attr.id);
|
|
143621
143778
|
const { limit: limit2, offset: offset16 } = limitOffset({ limit: r.query.get("limit") ?? void 0, offset: r.query.get("offset") ?? void 0 });
|
|
143622
143779
|
return { data: rows33.slice(offset16, offset16 + limit2).map((v) => valueObject(r.ctx, attr, v)) };
|
|
143623
143780
|
}
|
|
@@ -143629,11 +143786,11 @@ var attioRoutes = [
|
|
|
143629
143786
|
coverage: { status: "supported" },
|
|
143630
143787
|
run: (r) => {
|
|
143631
143788
|
const rec = findRecord(r, findObject(r.ctx, r.param("object")));
|
|
143632
|
-
return { data:
|
|
143789
|
+
return { data: all5(r.ctx, "SELECT e.*, l.api_slug FROM attio_entries e JOIN attio_lists l ON l.id = e.list_id WHERE e.record_id = ? ORDER BY e.created_at", rec.id).map((e) => ({ list_id: e.list_id, list_api_slug: e.api_slug, entry_id: e.id, created_at: e.created_at })) };
|
|
143633
143790
|
}
|
|
143634
143791
|
},
|
|
143635
143792
|
/* ------------------------------------ lists ------------------------------------ */
|
|
143636
|
-
{ method: "GET", path: "/v2/lists", coverage: { status: "supported" }, run: (r) => ({ data:
|
|
143793
|
+
{ method: "GET", path: "/v2/lists", coverage: { status: "supported" }, run: (r) => ({ data: all5(r.ctx, "SELECT * FROM attio_lists ORDER BY rowid").map((l) => listShape(r.ctx, l)) }) },
|
|
143637
143794
|
{ method: "GET", path: "/v2/lists/:list", coverage: { status: "supported" }, run: (r) => ({ data: listShape(r.ctx, findList(r.ctx, r.param("list"))) }) },
|
|
143638
143795
|
{
|
|
143639
143796
|
method: "POST",
|
|
@@ -143641,7 +143798,7 @@ var attioRoutes = [
|
|
|
143641
143798
|
coverage: { status: "partial", notes: "filters and sorts on the list's own attributes" },
|
|
143642
143799
|
run: (r) => {
|
|
143643
143800
|
const list15 = findList(r.ctx, r.param("list"));
|
|
143644
|
-
return { data: query8(r,
|
|
143801
|
+
return { data: query8(r, all5(r.ctx, "SELECT * FROM attio_entries WHERE list_id = ? ORDER BY created_at, rowid", list15.id), attributesOf(r.ctx, listParent(list15))).map((e) => entryShape(r.ctx, e)) };
|
|
143645
143802
|
}
|
|
143646
143803
|
},
|
|
143647
143804
|
{
|
|
@@ -143680,7 +143837,7 @@ var attioRoutes = [
|
|
|
143680
143837
|
return {};
|
|
143681
143838
|
} },
|
|
143682
143839
|
/* ------------------------------- members, notes, tasks ----------------------------- */
|
|
143683
|
-
{ method: "GET", path: "/v2/workspace_members", coverage: { status: "supported" }, run: (r) => ({ data:
|
|
143840
|
+
{ method: "GET", path: "/v2/workspace_members", coverage: { status: "supported" }, run: (r) => ({ data: all5(r.ctx, "SELECT * FROM attio_members ORDER BY rowid").map((m) => memberShape(r.ctx, m)) }) },
|
|
143684
143841
|
{
|
|
143685
143842
|
method: "GET",
|
|
143686
143843
|
path: "/v2/workspace_members/:id",
|
|
@@ -143695,7 +143852,7 @@ var attioRoutes = [
|
|
|
143695
143852
|
run: (r) => {
|
|
143696
143853
|
const object16 = r.query.get("parent_object"), record23 = r.query.get("parent_record_id");
|
|
143697
143854
|
const objectSlug = object16 ? findObject(r.ctx, object16).api_slug : void 0;
|
|
143698
|
-
const notes6 =
|
|
143855
|
+
const notes6 = all5(r.ctx, "SELECT * FROM attio_notes ORDER BY created_at, rowid").filter((n) => (!objectSlug || n.parent_object === objectSlug) && (!record23 || n.parent_record_id === record23));
|
|
143699
143856
|
const { limit: limit2, offset: offset16 } = limitOffset({ limit: r.query.get("limit") ?? void 0, offset: r.query.get("offset") ?? void 0 }, 10);
|
|
143700
143857
|
return { data: notes6.slice(offset16, offset16 + limit2).map((n) => noteShape2(r.ctx, n)) };
|
|
143701
143858
|
}
|
|
@@ -143747,7 +143904,7 @@ var attioRoutes = [
|
|
|
143747
143904
|
const linkedObject = q.get("linked_object") ? findObject(r.ctx, q.get("linked_object")).id : void 0;
|
|
143748
143905
|
const assignee = q.get("assignee") ? one2(r.ctx, "SELECT * FROM attio_members WHERE id = ? OR lower(email) = lower(?)", q.get("assignee"), q.get("assignee"))?.id ?? "__none__" : void 0;
|
|
143749
143906
|
const done = q.get("is_completed");
|
|
143750
|
-
let tasks =
|
|
143907
|
+
let tasks = all5(r.ctx, "SELECT * FROM attio_tasks ORDER BY created_at, rowid").filter((t) => {
|
|
143751
143908
|
const linked = JSON.parse(t.linked);
|
|
143752
143909
|
return (!linkedObject || linked.some((l) => l.target_object_id === linkedObject)) && (!q.get("linked_record_id") || linked.some((l) => l.target_record_id === q.get("linked_record_id"))) && (!assignee || JSON.parse(t.assignees).some((a) => a.referenced_actor_id === assignee)) && (done === null || String(!!t.is_completed) === done);
|
|
143753
143910
|
});
|
|
@@ -143924,7 +144081,7 @@ function seed23(ctx) {
|
|
|
143924
144081
|
run2(ctx, "INSERT INTO attio_records (id, object_id, created_at, created_by) VALUES (?, ?, ?, ?)", id12, objectIds.get(slug11), at3(r.created), JSON.stringify(actor(members4.get(data5.agent))));
|
|
143925
144082
|
}
|
|
143926
144083
|
const write4 = (parentId, parent2, values2, when12, by2) => {
|
|
143927
|
-
const attributes2 =
|
|
144084
|
+
const attributes2 = all5(ctx, "SELECT * FROM attio_attributes WHERE parent_id = ? ORDER BY position", parent2);
|
|
143928
144085
|
for (const [slug11, raw3] of Object.entries(values2)) {
|
|
143929
144086
|
const attr = attributes2.find((a) => a.api_slug === slug11);
|
|
143930
144087
|
if (!attr) throw new AnchaError("SCENE_INVALID", `seed.attio: no attribute "${slug11}"`);
|
|
@@ -143982,9 +144139,9 @@ function credentials22(ctx) {
|
|
|
143982
144139
|
function dumpState22(ctx) {
|
|
143983
144140
|
const flat2 = (parentId, attributes2) => Object.fromEntries(attributes2.map((a) => [
|
|
143984
144141
|
a.api_slug,
|
|
143985
|
-
|
|
144142
|
+
all5(ctx, "SELECT * FROM attio_values WHERE parent_id = ? AND attribute_id = ? AND active_until IS NULL ORDER BY id", parentId, a.id).map((v) => primary(ctx, a, JSON.parse(v.data)))
|
|
143986
144143
|
]).filter(([, v]) => v.length));
|
|
143987
|
-
const objects =
|
|
144144
|
+
const objects = all5(ctx, "SELECT * FROM attio_objects ORDER BY rowid");
|
|
143988
144145
|
const name5 = (recordId) => {
|
|
143989
144146
|
const r = one2(ctx, "SELECT * FROM attio_records WHERE id = ?", recordId);
|
|
143990
144147
|
if (!r) return recordId;
|
|
@@ -143996,18 +144153,18 @@ function dumpState22(ctx) {
|
|
|
143996
144153
|
return m ? `${m.first_name} ${m.last_name}`.trim() : id12;
|
|
143997
144154
|
};
|
|
143998
144155
|
return {
|
|
143999
|
-
members:
|
|
144156
|
+
members: all5(ctx, "SELECT id, first_name, last_name, email, access_level FROM attio_members ORDER BY rowid"),
|
|
144000
144157
|
objects: objects.map((o) => ({ id: o.id, api_slug: o.api_slug, attributes: attributesOf(ctx, o.id).map((a) => ({ api_slug: a.api_slug, type: a.type })) })),
|
|
144001
|
-
records:
|
|
144002
|
-
lists:
|
|
144158
|
+
records: all5(ctx, "SELECT * FROM attio_records ORDER BY created_at, rowid").map((r) => ({ id: r.id, object: objects.find((o) => o.id === r.object_id).api_slug, created_at: r.created_at, values: flat2(r.id, attributesOf(ctx, r.object_id)) })),
|
|
144159
|
+
lists: all5(ctx, "SELECT * FROM attio_lists ORDER BY rowid").map((l) => ({
|
|
144003
144160
|
id: l.id,
|
|
144004
144161
|
api_slug: l.api_slug,
|
|
144005
144162
|
name: l.name,
|
|
144006
144163
|
parent_object: l.parent_object,
|
|
144007
|
-
entries:
|
|
144164
|
+
entries: all5(ctx, "SELECT * FROM attio_entries WHERE list_id = ? ORDER BY created_at, rowid", l.id).map((e) => ({ id: e.id, record_id: e.record_id, record: name5(e.record_id), values: flat2(e.id, attributesOf(ctx, listParent(l))) }))
|
|
144008
144165
|
})),
|
|
144009
|
-
notes:
|
|
144010
|
-
tasks:
|
|
144166
|
+
notes: all5(ctx, "SELECT * FROM attio_notes ORDER BY created_at, rowid").map((n) => ({ ...noteShape2(ctx, n), parent_label: name5(n.parent_record_id), author: member4(JSON.parse(n.created_by).id) })),
|
|
144167
|
+
tasks: all5(ctx, "SELECT * FROM attio_tasks ORDER BY created_at, rowid").map((t) => taskShape(ctx, t))
|
|
144011
144168
|
};
|
|
144012
144169
|
}
|
|
144013
144170
|
|
|
@@ -144291,7 +144448,7 @@ function listing(ctx, cursor4) {
|
|
|
144291
144448
|
}
|
|
144292
144449
|
function page9(ctx, cursor4) {
|
|
144293
144450
|
if (cursor4.o >= 0) {
|
|
144294
|
-
const
|
|
144451
|
+
const all8 = listing(ctx, cursor4), slice = all8.slice(cursor4.o, cursor4.o + cursor4.l), more = cursor4.o + cursor4.l < all8.length;
|
|
144295
144452
|
return json15({ entries: slice, cursor: encodeCursor3(more ? { ...cursor4, o: cursor4.o + cursor4.l } : { ...cursor4, o: -1 }), has_more: more });
|
|
144296
144453
|
}
|
|
144297
144454
|
const changed = ctx.store.db.prepare("SELECT path_lower, MAX(seq) AS seq FROM dbx_changes WHERE seq > ? GROUP BY path_lower ORDER BY MAX(seq)").all(cursor4.s).map((row) => row.path_lower).filter((key3) => cursor4.p === "" ? cursor4.r || !key3.slice(1).includes("/") : key3.startsWith(`${cursor4.p}/`) && (cursor4.r || !key3.slice(cursor4.p.length + 1).includes("/")));
|
|
@@ -146330,15 +146487,15 @@ function search6(call2, query11) {
|
|
|
146330
146487
|
odata(call2, ["$top", "$skiptoken", "$orderby"]);
|
|
146331
146488
|
const tokens2 = query11.toLowerCase().split(/\s+/).filter(Boolean);
|
|
146332
146489
|
if (!tokens2.length) throw invalid19("The search query is empty.");
|
|
146333
|
-
const scope3 = target3(call2),
|
|
146490
|
+
const scope3 = target3(call2), all8 = [];
|
|
146334
146491
|
const visit3 = (node5) => {
|
|
146335
146492
|
for (const child2 of childrenOf2(call2.ctx, node5.id)) {
|
|
146336
|
-
|
|
146493
|
+
all8.push(child2);
|
|
146337
146494
|
if (child2.kind === "folder") visit3(child2);
|
|
146338
146495
|
}
|
|
146339
146496
|
};
|
|
146340
146497
|
visit3(scope3);
|
|
146341
|
-
const matches7 =
|
|
146498
|
+
const matches7 = all8.filter((item2) => {
|
|
146342
146499
|
const text24 = `${item2.name}
|
|
146343
146500
|
${textOf2(item2) ?? ""}`.toLowerCase();
|
|
146344
146501
|
return tokens2.every((token2) => text24.includes(token2));
|
|
@@ -146599,7 +146756,7 @@ function save8(ctx, kind, doc, parent2 = null) {
|
|
|
146599
146756
|
ctx.store.db.prepare("INSERT INTO shopify_objects (gid, kind, num, parent, json) VALUES (?, ?, ?, ?, ?) ON CONFLICT (gid) DO UPDATE SET json = excluded.json").run(doc.gid, kind, numOf(doc.gid) ?? 0, parent2, JSON.stringify(doc));
|
|
146600
146757
|
return doc;
|
|
146601
146758
|
}
|
|
146602
|
-
function
|
|
146759
|
+
function all6(ctx, kind) {
|
|
146603
146760
|
return ctx.store.db.prepare("SELECT json FROM shopify_objects WHERE kind = ? ORDER BY num").all(kind).map((r) => JSON.parse(r.json));
|
|
146604
146761
|
}
|
|
146605
146762
|
function childrenOf3(ctx, parent2, kind) {
|
|
@@ -146673,7 +146830,7 @@ function level2(ctx, item2, location) {
|
|
|
146673
146830
|
}
|
|
146674
146831
|
function committed(ctx, item2, location) {
|
|
146675
146832
|
let n = 0;
|
|
146676
|
-
for (const fo of
|
|
146833
|
+
for (const fo of all6(ctx, "FulfillmentOrder")) {
|
|
146677
146834
|
if (fo.location !== location) continue;
|
|
146678
146835
|
const order4 = load3(ctx, fo.order);
|
|
146679
146836
|
if (order4.cancelled_ms !== null) continue;
|
|
@@ -146947,7 +147104,7 @@ function connection2(items, args, key3, shape5) {
|
|
|
146947
147104
|
var byNum = (d) => ({ id: numOf(d.gid) });
|
|
146948
147105
|
var pathOf3 = (path6) => path6 ? [...pathOf3(path6.prev), path6.key] : [];
|
|
146949
147106
|
var firstOf = (items, n) => typeof n === "number" ? items.slice(0, Math.max(0, n)) : items;
|
|
146950
|
-
var currencyOf = (ctx) =>
|
|
147107
|
+
var currencyOf = (ctx) => all6(ctx, "Shop")[0].currency;
|
|
146951
147108
|
var bag = (ctx, c) => {
|
|
146952
147109
|
const m = { amount: decimal2(c), currencyCode: currencyOf(ctx) };
|
|
146953
147110
|
return { shopMoney: m, presentmentMoney: m };
|
|
@@ -147047,7 +147204,7 @@ function distance(ms2) {
|
|
|
147047
147204
|
return years === 1 ? "about 1 year" : `about ${years} years`;
|
|
147048
147205
|
}
|
|
147049
147206
|
function shopShape(req) {
|
|
147050
|
-
const s =
|
|
147207
|
+
const s = all6(req.ctx, "Shop")[0], host = `${s.domain}.myshopify.com`;
|
|
147051
147208
|
return {
|
|
147052
147209
|
__typename: "Shop",
|
|
147053
147210
|
id: s.gid,
|
|
@@ -147074,7 +147231,7 @@ function shopShape(req) {
|
|
|
147074
147231
|
};
|
|
147075
147232
|
}
|
|
147076
147233
|
function locationShape(req, l) {
|
|
147077
|
-
const primary3 =
|
|
147234
|
+
const primary3 = all6(req.ctx, "Location")[0].gid === l.gid, a = l.address, country = a.country_code ?? "US";
|
|
147078
147235
|
return {
|
|
147079
147236
|
__typename: "Location",
|
|
147080
147237
|
id: l.gid,
|
|
@@ -147154,7 +147311,7 @@ function itemShape(req, item2) {
|
|
|
147154
147311
|
};
|
|
147155
147312
|
}
|
|
147156
147313
|
function variantStock(req, v) {
|
|
147157
|
-
const levels3 = levelsOf(req.ctx, { item: v.item }), locations = new Map(
|
|
147314
|
+
const levels3 = levelsOf(req.ctx, { item: v.item }), locations = new Map(all6(req.ctx, "Location").map((l) => [l.gid, l]));
|
|
147158
147315
|
const active3 = levels3.filter((l) => locations.get(l.location)?.active);
|
|
147159
147316
|
return { available: active3.reduce((n, l) => n + l.available, 0), online: active3.filter((l) => locations.get(l.location).fulfills_online_orders).reduce((n, l) => n + Math.max(0, l.available), 0) };
|
|
147160
147317
|
}
|
|
@@ -147209,7 +147366,7 @@ function productShape(req, p2) {
|
|
|
147209
147366
|
const variants = () => childrenOf3(req.ctx, p2.gid, "ProductVariant");
|
|
147210
147367
|
const tracked2 = () => variants().filter((v) => load3(req.ctx, v.item).tracked);
|
|
147211
147368
|
const prices = () => variants().map((v) => v.price_cents);
|
|
147212
|
-
const host = `${
|
|
147369
|
+
const host = `${all6(req.ctx, "Shop")[0].domain}.myshopify.com`;
|
|
147213
147370
|
return {
|
|
147214
147371
|
__typename: "Product",
|
|
147215
147372
|
id: p2.gid,
|
|
@@ -147253,7 +147410,7 @@ function productShape(req, p2) {
|
|
|
147253
147410
|
};
|
|
147254
147411
|
}
|
|
147255
147412
|
function customerShape(req, c) {
|
|
147256
|
-
const orders = () =>
|
|
147413
|
+
const orders = () => all6(req.ctx, "Order").filter((o) => o.customer === c.gid);
|
|
147257
147414
|
const name5 = [c.first_name, c.last_name].filter(Boolean).join(" ");
|
|
147258
147415
|
return {
|
|
147259
147416
|
__typename: "Customer",
|
|
@@ -147291,7 +147448,7 @@ function orderShape(req, o) {
|
|
|
147291
147448
|
let cached2;
|
|
147292
147449
|
const facts = () => cached2 ??= orderFacts(req.ctx, o);
|
|
147293
147450
|
const sm = (pick5) => () => bag(req.ctx, pick5(facts()));
|
|
147294
|
-
const shop =
|
|
147451
|
+
const shop = all6(req.ctx, "Shop")[0];
|
|
147295
147452
|
const fos = () => childrenOf3(req.ctx, o.gid, "FulfillmentOrder");
|
|
147296
147453
|
return {
|
|
147297
147454
|
__typename: "Order",
|
|
@@ -147662,7 +147819,7 @@ function ordersConnection(req, orders, args, path6) {
|
|
|
147662
147819
|
function productsConnection(req, args, path6) {
|
|
147663
147820
|
const variants = (p2) => childrenOf3(req.ctx, p2.gid, "ProductVariant");
|
|
147664
147821
|
const inventory = (p2) => variants(p2).filter((v) => load3(req.ctx, v.item).tracked).reduce((n, v) => n + variantStock(req, v).available, 0);
|
|
147665
|
-
let found = filter3(req, "products",
|
|
147822
|
+
let found = filter3(req, "products", all6(req.ctx, "Product"), args, path6, {
|
|
147666
147823
|
default: { text: (p2) => [p2.title, p2.vendor, p2.product_type, p2.handle, ...p2.tags, ...variants(p2).map((v) => v.sku)] },
|
|
147667
147824
|
id: { number: num2 },
|
|
147668
147825
|
title: { text: (p2) => [p2.title], words: true },
|
|
@@ -147700,7 +147857,7 @@ function productsConnection(req, args, path6) {
|
|
|
147700
147857
|
}
|
|
147701
147858
|
function variantsConnection(req, args, path6) {
|
|
147702
147859
|
const product2 = (v) => load3(req.ctx, v.product);
|
|
147703
|
-
const found = filter3(req, "productVariants",
|
|
147860
|
+
const found = filter3(req, "productVariants", all6(req.ctx, "ProductVariant"), args, path6, {
|
|
147704
147861
|
default: { text: (v) => [product2(v).title, variantTitle(v), v.sku, v.barcode] },
|
|
147705
147862
|
id: { number: num2 },
|
|
147706
147863
|
sku: { text: (v) => [v.sku] },
|
|
@@ -147729,9 +147886,9 @@ function variantsConnection(req, args, path6) {
|
|
|
147729
147886
|
return connection2(items, args, (v) => ({ id: num2(v), value: key3(v) }), (v) => variantShape(req, v));
|
|
147730
147887
|
}
|
|
147731
147888
|
function customersConnection(req, args, path6) {
|
|
147732
|
-
const orders = (c) =>
|
|
147889
|
+
const orders = (c) => all6(req.ctx, "Order").filter((o) => o.customer === c.gid);
|
|
147733
147890
|
const fullName = (c) => [c.first_name, c.last_name].filter(Boolean).join(" ");
|
|
147734
|
-
const found = filter3(req, "customers",
|
|
147891
|
+
const found = filter3(req, "customers", all6(req.ctx, "Customer"), args, path6, {
|
|
147735
147892
|
default: { text: (c) => [fullName(c), c.email, c.phone, c.address?.company ?? null, ...c.tags] },
|
|
147736
147893
|
id: { number: num2 },
|
|
147737
147894
|
email: { text: (c) => [c.email] },
|
|
@@ -147758,7 +147915,7 @@ function customersConnection(req, args, path6) {
|
|
|
147758
147915
|
return connection2(items, args, (c) => ({ id: num2(c), value: key3(c) }), (c) => customerShape(req, c));
|
|
147759
147916
|
}
|
|
147760
147917
|
function locationsConnection(req, args, path6) {
|
|
147761
|
-
const found = filter3(req, "locations",
|
|
147918
|
+
const found = filter3(req, "locations", all6(req.ctx, "Location").filter((l) => args.includeInactive || l.active), args, path6, {
|
|
147762
147919
|
default: { text: (l) => [l.name, l.address.city, l.address.address1, l.address.zip] },
|
|
147763
147920
|
id: { number: num2 },
|
|
147764
147921
|
location_id: { number: num2 },
|
|
@@ -147808,7 +147965,7 @@ function queryRoot(req) {
|
|
|
147808
147965
|
};
|
|
147809
147966
|
return {
|
|
147810
147967
|
shop: () => shopShape(req),
|
|
147811
|
-
orders: (args, _r, info) => ordersConnection(req,
|
|
147968
|
+
orders: (args, _r, info) => ordersConnection(req, all6(ctx, "Order"), args, pathOf3(info.path)),
|
|
147812
147969
|
order: one7("Order", orderShape),
|
|
147813
147970
|
products: (args, _r, info) => productsConnection(req, args, pathOf3(info.path)),
|
|
147814
147971
|
product: one7("Product", productShape),
|
|
@@ -147819,7 +147976,7 @@ function queryRoot(req) {
|
|
|
147819
147976
|
locations: (args, _r, info) => locationsConnection(req, args, pathOf3(info.path)),
|
|
147820
147977
|
// Without an id, Shopify returns the primary location.
|
|
147821
147978
|
location: ({ id: id12 }) => {
|
|
147822
|
-
const d = id12 === void 0 || id12 === null ?
|
|
147979
|
+
const d = id12 === void 0 || id12 === null ? all6(ctx, "Location")[0] : loadKind(ctx, "Location", checkId(id12));
|
|
147823
147980
|
return d ? locationShape(req, d) : null;
|
|
147824
147981
|
},
|
|
147825
147982
|
inventoryItem: one7("InventoryItem", itemShape),
|
|
@@ -148010,7 +148167,7 @@ function mutationRoot(req) {
|
|
|
148010
148167
|
}
|
|
148011
148168
|
if (data5.handle !== void 0 && data5.handle !== null) {
|
|
148012
148169
|
const handle30 = slug8(data5.handle);
|
|
148013
|
-
if (
|
|
148170
|
+
if (all6(ctx, "Product").some((x) => x.gid !== p2.gid && x.handle === handle30)) errors3.push({ field: ["handle"], message: `Handle '${handle30}' already in use. Please provide a new handle.` });
|
|
148014
148171
|
else next2.handle = handle30;
|
|
148015
148172
|
}
|
|
148016
148173
|
if (errors3.length) return { product: null, userErrors: errors3 };
|
|
@@ -148067,7 +148224,7 @@ function refundCreate(req, input2) {
|
|
|
148067
148224
|
const found = orderOrError(req, input2.orderId, ["orderId"]);
|
|
148068
148225
|
if ("errors" in found) return fail7(found.errors);
|
|
148069
148226
|
const o = found.order, facts = orderFacts(ctx, o);
|
|
148070
|
-
if (input2.currency && input2.currency !==
|
|
148227
|
+
if (input2.currency && input2.currency !== all6(ctx, "Shop")[0].currency) gap4("refunds in a presentment currency");
|
|
148071
148228
|
const errors3 = [];
|
|
148072
148229
|
const items = [];
|
|
148073
148230
|
(input2.refundLineItems ?? []).forEach((i, n) => {
|
|
@@ -148273,7 +148430,7 @@ function customerWrite(req, input2, create2) {
|
|
|
148273
148430
|
updated_ms: at3
|
|
148274
148431
|
};
|
|
148275
148432
|
const errors3 = [];
|
|
148276
|
-
const others =
|
|
148433
|
+
const others = all6(ctx, "Customer").filter((x) => x.gid !== c.gid);
|
|
148277
148434
|
if (input2.email !== void 0) {
|
|
148278
148435
|
if (input2.email !== null && !EMAIL17.test(input2.email)) errors3.push({ field: ["email"], message: "Email is invalid" });
|
|
148279
148436
|
else if (input2.email !== null && others.some((x) => x.email?.toLowerCase() === input2.email.toLowerCase())) errors3.push({ field: ["email"], message: "Email has already been taken" });
|
|
@@ -148686,13 +148843,13 @@ function credentials26(ctx) {
|
|
|
148686
148843
|
var when9 = (ms2) => ms2 === null ? null : iso8(ms2);
|
|
148687
148844
|
var oneLine = (a) => a ? [a.company, a.address1, a.address2, a.city, [a.province_code, a.zip].filter(Boolean).join(" "), a.country_code].filter(Boolean).join(", ") : null;
|
|
148688
148845
|
function dumpState26(ctx) {
|
|
148689
|
-
const shop =
|
|
148846
|
+
const shop = all6(ctx, "Shop")[0], locations = all6(ctx, "Location");
|
|
148690
148847
|
const locationName = (id12) => id12 ? locations.find((l) => l.gid === id12)?.name ?? null : null;
|
|
148691
148848
|
const sku = (lineId) => load3(ctx, lineId)?.sku ?? null;
|
|
148692
148849
|
return {
|
|
148693
148850
|
shop: { name: shop.name, domain: `${shop.domain}.myshopify.com`, email: shop.email, currency: shop.currency },
|
|
148694
148851
|
locations: locations.map((l) => ({ id: l.gid, name: l.name, city: l.address.city, active: l.active, fulfills_online_orders: l.fulfills_online_orders })),
|
|
148695
|
-
products:
|
|
148852
|
+
products: all6(ctx, "Product").map((p2) => ({
|
|
148696
148853
|
id: p2.gid,
|
|
148697
148854
|
title: p2.title,
|
|
148698
148855
|
handle: p2.handle,
|
|
@@ -148719,7 +148876,7 @@ function dumpState26(ctx) {
|
|
|
148719
148876
|
};
|
|
148720
148877
|
})
|
|
148721
148878
|
})),
|
|
148722
|
-
customers:
|
|
148879
|
+
customers: all6(ctx, "Customer").map((c) => ({
|
|
148723
148880
|
id: c.gid,
|
|
148724
148881
|
name: [c.first_name, c.last_name].filter(Boolean).join(" ") || null,
|
|
148725
148882
|
email: c.email,
|
|
@@ -148728,9 +148885,9 @@ function dumpState26(ctx) {
|
|
|
148728
148885
|
note: c.note,
|
|
148729
148886
|
state: c.state,
|
|
148730
148887
|
accepts_marketing: c.accepts_marketing,
|
|
148731
|
-
orders:
|
|
148888
|
+
orders: all6(ctx, "Order").filter((o) => o.customer === c.gid).length
|
|
148732
148889
|
})),
|
|
148733
|
-
orders:
|
|
148890
|
+
orders: all6(ctx, "Order").map((o) => {
|
|
148734
148891
|
const f = orderFacts(ctx, o), customer3 = o.customer ? load3(ctx, o.customer) : void 0;
|
|
148735
148892
|
return {
|
|
148736
148893
|
id: o.gid,
|
|
@@ -148786,7 +148943,7 @@ function dumpState26(ctx) {
|
|
|
148786
148943
|
transactions: f.transactions.map((t) => ({ id: t.gid, kind: t.kind, status: t.status, gateway: t.gateway, amount: decimal2(t.cents), created_at: iso8(t.created_ms), error_code: t.error_code }))
|
|
148787
148944
|
};
|
|
148788
148945
|
}),
|
|
148789
|
-
inventory_adjustments:
|
|
148946
|
+
inventory_adjustments: all6(ctx, "InventoryAdjustmentGroup").map((g) => ({
|
|
148790
148947
|
id: g.gid,
|
|
148791
148948
|
reason: g.reason,
|
|
148792
148949
|
reference: g.reference,
|
|
@@ -150963,14 +151120,14 @@ var billingRoutes = [
|
|
|
150963
151120
|
path: "/v1/catalogs/products",
|
|
150964
151121
|
coverage: { status: "supported" },
|
|
150965
151122
|
run: (r) => {
|
|
150966
|
-
const { size, n, total } = page11(r, 20),
|
|
150967
|
-
return { products:
|
|
151123
|
+
const { size, n, total } = page11(r, 20), all8 = allOf2(r.ctx, "product");
|
|
151124
|
+
return { products: all8.slice((n - 1) * size, n * size).map((p2) => ({
|
|
150968
151125
|
id: p2.id,
|
|
150969
151126
|
name: p2.name,
|
|
150970
151127
|
description: p2.description ?? void 0,
|
|
150971
151128
|
create_time: iso10(p2.create_ms),
|
|
150972
151129
|
links: [link4(`${r.base}/v1/catalogs/products/${p2.id}`, "self")]
|
|
150973
|
-
})), ...total && { total_items:
|
|
151130
|
+
})), ...total && { total_items: all8.length, total_pages: Math.ceil(all8.length / size) }, links: [] };
|
|
150974
151131
|
}
|
|
150975
151132
|
},
|
|
150976
151133
|
{
|
|
@@ -150997,10 +151154,10 @@ var billingRoutes = [
|
|
|
150997
151154
|
coverage: { status: "supported" },
|
|
150998
151155
|
run: (r) => {
|
|
150999
151156
|
const { size, n, total } = page11(r, 20), ids2 = r.query.get("plan_ids")?.split(",").filter(Boolean), product2 = r.query.get("product_id");
|
|
151000
|
-
const
|
|
151157
|
+
const all8 = allOf2(r.ctx, "plan").filter((p2) => (!product2 || p2.product_id === product2) && (!ids2 || ids2.includes(p2.id)));
|
|
151001
151158
|
return {
|
|
151002
|
-
plans:
|
|
151003
|
-
...total && { total_items:
|
|
151159
|
+
plans: all8.slice((n - 1) * size, n * size).map((p2) => planShape(r, p2, false)),
|
|
151160
|
+
...total && { total_items: all8.length, total_pages: Math.ceil(all8.length / size) },
|
|
151004
151161
|
links: [link4(`${r.base}/v1/billing/plans?page_size=${size}&page=${n}`, "self")]
|
|
151005
151162
|
};
|
|
151006
151163
|
}
|
|
@@ -151070,8 +151227,8 @@ var billingRoutes = [
|
|
|
151070
151227
|
run: (r) => {
|
|
151071
151228
|
const { size, n } = page11(r, 20), plans = r.query.get("plan_ids")?.split(",").filter(Boolean), statuses2 = r.query.get("statuses")?.split(",").filter(Boolean);
|
|
151072
151229
|
for (const key3 of ["created_after", "created_before", "status_updated_after", "status_updated_before", "filter", "customer_ids"]) if (r.query.get(key3)) unsupported23(`the ${key3} filter on subscriptions`);
|
|
151073
|
-
const
|
|
151074
|
-
return { subscriptions:
|
|
151230
|
+
const all8 = allOf2(r.ctx, "subscription").filter((s) => (!plans || plans.includes(s.plan_id)) && (!statuses2 || statuses2.includes(s.status)));
|
|
151231
|
+
return { subscriptions: all8.slice((n - 1) * size, n * size).map((s) => subscriptionShape(r, s)), total_items: all8.length, total_pages: Math.ceil(all8.length / size), links: [] };
|
|
151075
151232
|
}
|
|
151076
151233
|
},
|
|
151077
151234
|
{ method: "GET", path: "/v1/billing/subscriptions/:id", coverage: { status: "supported" }, run: (r) => subscriptionShape(r, subscriptionOr404(r)) },
|
|
@@ -154828,7 +154985,7 @@ function load5(ctx, kind, id12) {
|
|
|
154828
154985
|
const row = ctx.store.db.prepare("SELECT json FROM intercom_objects WHERE kind = ? AND id = ?").get(kind, id12);
|
|
154829
154986
|
return row && JSON.parse(row.json);
|
|
154830
154987
|
}
|
|
154831
|
-
function
|
|
154988
|
+
function all7(ctx, kind) {
|
|
154832
154989
|
return ctx.store.db.prepare("SELECT json FROM intercom_objects WHERE kind = ? ORDER BY seq").all(kind).map((r) => JSON.parse(r.json));
|
|
154833
154990
|
}
|
|
154834
154991
|
function save10(ctx, kind, doc) {
|
|
@@ -154952,7 +155109,7 @@ function byPage(items, r, dflt, key3, body6) {
|
|
|
154952
155109
|
}
|
|
154953
155110
|
var numeric2 = (id12) => id12 === null ? null : Number(id12);
|
|
154954
155111
|
function adminShape(r, a) {
|
|
154955
|
-
const teams =
|
|
155112
|
+
const teams = all7(r.ctx, "team").filter((t) => t.admin_ids.includes(a.id)).map((t) => Number(t.id));
|
|
154956
155113
|
return {
|
|
154957
155114
|
type: "admin",
|
|
154958
155115
|
id: a.id,
|
|
@@ -154982,7 +155139,7 @@ var tagRef = (r, t) => {
|
|
|
154982
155139
|
};
|
|
154983
155140
|
function contactShape2(r, c) {
|
|
154984
155141
|
const list15 = (type, ids2, path6) => ({ type: "list", data: ids2.map((id12) => ({ type, id: id12, url: `/${type === "company" ? "companies" : `${type}s`}/${id12}` })), url: `/contacts/${c.id}/${path6}`, total_count: ids2.length, has_more: false });
|
|
154985
|
-
const notes6 =
|
|
155142
|
+
const notes6 = all7(r.ctx, "note").filter((n) => n.contact_id === c.id).map((n) => n.id);
|
|
154986
155143
|
return {
|
|
154987
155144
|
type: "contact",
|
|
154988
155145
|
id: c.id,
|
|
@@ -155041,7 +155198,7 @@ function contactShape2(r, c) {
|
|
|
155041
155198
|
};
|
|
155042
155199
|
}
|
|
155043
155200
|
function companyShape(r, co) {
|
|
155044
|
-
const users4 =
|
|
155201
|
+
const users4 = all7(r.ctx, "contact").filter((c) => c.companies.includes(co.id)).length;
|
|
155045
155202
|
return {
|
|
155046
155203
|
type: "company",
|
|
155047
155204
|
id: co.id,
|
|
@@ -155309,9 +155466,9 @@ function applyContact(r, c, b) {
|
|
|
155309
155466
|
}
|
|
155310
155467
|
}
|
|
155311
155468
|
function conflictOnEmail(r, c) {
|
|
155312
|
-
const dup = c.email &&
|
|
155469
|
+
const dup = c.email && all7(r.ctx, "contact").find((x) => x.id !== c.id && x.role === "user" && c.role === "user" && x.email?.toLowerCase() === c.email.toLowerCase());
|
|
155313
155470
|
if (dup) fail3(409, "conflict", `A contact matching those details already exists with id=${dup.id}`);
|
|
155314
|
-
const ext = c.external_id &&
|
|
155471
|
+
const ext = c.external_id && all7(r.ctx, "contact").find((x) => x.id !== c.id && x.external_id === c.external_id);
|
|
155315
155472
|
if (ext) fail3(409, "conflict", `A contact matching those details already exists with id=${ext.id}`);
|
|
155316
155473
|
}
|
|
155317
155474
|
function tagOn(r, doc, tagId, adminId) {
|
|
@@ -155333,7 +155490,7 @@ var intercomRoutes = [
|
|
|
155333
155490
|
return { ...adminShape(r, r.me), app: { type: "app", id_code: w.id, name: w.name, created_at: w.created_at, secure: false, identity_verification: false, timezone: "America/Los_Angeles", region: "US" } };
|
|
155334
155491
|
}
|
|
155335
155492
|
},
|
|
155336
|
-
{ method: "GET", path: "/admins", coverage: { status: "supported" }, run: (r) => ({ type: "admin.list", admins:
|
|
155493
|
+
{ method: "GET", path: "/admins", coverage: { status: "supported" }, run: (r) => ({ type: "admin.list", admins: all7(r.ctx, "admin").map((a) => adminShape(r, a)) }) },
|
|
155337
155494
|
{ method: "GET", path: "/admins/:id", coverage: { status: "supported" }, run: (r) => adminShape(r, load5(r.ctx, "admin", r.param("id")) ?? notFound15("Admin")) },
|
|
155338
155495
|
{
|
|
155339
155496
|
method: "PUT",
|
|
@@ -155345,7 +155502,7 @@ var intercomRoutes = [
|
|
|
155345
155502
|
return adminShape(r, save10(r.ctx, "admin", { ...a, away: r.body.away_mode_enabled, reassign: !!r.body.away_mode_reassign }));
|
|
155346
155503
|
}
|
|
155347
155504
|
},
|
|
155348
|
-
{ method: "GET", path: "/teams", coverage: { status: "supported" }, run: (r) => ({ type: "team.list", teams:
|
|
155505
|
+
{ method: "GET", path: "/teams", coverage: { status: "supported" }, run: (r) => ({ type: "team.list", teams: all7(r.ctx, "team").map((t) => ({ type: "team", id: t.id, name: t.name, admin_ids: t.admin_ids.map(Number), admin_priority_level: {} })) }) },
|
|
155349
155506
|
{
|
|
155350
155507
|
method: "GET",
|
|
155351
155508
|
path: "/teams/:id",
|
|
@@ -155356,7 +155513,7 @@ var intercomRoutes = [
|
|
|
155356
155513
|
}
|
|
155357
155514
|
},
|
|
155358
155515
|
{ method: "GET", path: "/contacts", coverage: { status: "supported" }, run: (r) => {
|
|
155359
|
-
const l = listOf("list", "data",
|
|
155516
|
+
const l = listOf("list", "data", all7(r.ctx, "contact").filter((c) => !c.archived), r);
|
|
155360
155517
|
return { ...l, data: l.data.map((c) => contactShape2(r, c)) };
|
|
155361
155518
|
} },
|
|
155362
155519
|
{
|
|
@@ -155365,7 +155522,7 @@ var intercomRoutes = [
|
|
|
155365
155522
|
coverage: { status: "partial", notes: "common contact fields, tags, companies and custom attributes; segments and device fields are gaps" },
|
|
155366
155523
|
run: (r) => {
|
|
155367
155524
|
const ok = matcher(contactFields(r), CONTACT_DOCUMENTED, r.body.query, "contacts");
|
|
155368
|
-
const l = listOf("list", "data",
|
|
155525
|
+
const l = listOf("list", "data", all7(r.ctx, "contact").filter((c) => !c.archived && ok(c)), r, 50, r.body);
|
|
155369
155526
|
return { ...l, data: l.data.map((c) => contactShape2(r, c)) };
|
|
155370
155527
|
}
|
|
155371
155528
|
},
|
|
@@ -155406,7 +155563,7 @@ var intercomRoutes = [
|
|
|
155406
155563
|
method: "GET",
|
|
155407
155564
|
path: "/contacts/find_by_external_id/:id",
|
|
155408
155565
|
coverage: { status: "supported" },
|
|
155409
|
-
run: (r) => contactShape2(r,
|
|
155566
|
+
run: (r) => contactShape2(r, all7(r.ctx, "contact").find((c) => c.external_id === r.param("id")) ?? notFound15("User"))
|
|
155410
155567
|
},
|
|
155411
155568
|
{ method: "GET", path: "/contacts/:id", coverage: { status: "supported" }, run: (r) => contactShape2(r, contactOr404(r)) },
|
|
155412
155569
|
{
|
|
@@ -155483,7 +155640,7 @@ var intercomRoutes = [
|
|
|
155483
155640
|
coverage: { status: "supported" },
|
|
155484
155641
|
run: (r) => {
|
|
155485
155642
|
const c = contactOr404(r);
|
|
155486
|
-
const l = byPage(
|
|
155643
|
+
const l = byPage(all7(r.ctx, "note").filter((n) => n.contact_id === c.id).reverse(), r, 50, "data");
|
|
155487
155644
|
return { ...l, data: l.data.map((n) => noteShape3(r, n)) };
|
|
155488
155645
|
}
|
|
155489
155646
|
},
|
|
@@ -155536,13 +155693,13 @@ var intercomRoutes = [
|
|
|
155536
155693
|
run: (r) => {
|
|
155537
155694
|
const id12 = r.query.get("company_id"), name5 = r.query.get("name");
|
|
155538
155695
|
for (const key3 of ["segment_id", "tag_id"]) if (r.query.get(key3)) unsupported26(`listing companies by ${key3}`);
|
|
155539
|
-
if (id12 || name5) return companyShape(r,
|
|
155540
|
-
const l = byPage(
|
|
155696
|
+
if (id12 || name5) return companyShape(r, all7(r.ctx, "company").find((co) => id12 && co.company_id === id12 || name5 && co.name.toLowerCase() === name5.toLowerCase()) ?? notFound15("Company"));
|
|
155697
|
+
const l = byPage(all7(r.ctx, "company"), r, 15, "data");
|
|
155541
155698
|
return { ...l, data: l.data.map((co) => companyShape(r, co)) };
|
|
155542
155699
|
}
|
|
155543
155700
|
},
|
|
155544
155701
|
{ method: "POST", path: "/companies/list", coverage: { status: "supported" }, run: (r) => {
|
|
155545
|
-
const l = byPage(
|
|
155702
|
+
const l = byPage(all7(r.ctx, "company"), r, 15, "data", { page: r.body.page ?? r.query.get("page") ?? 1, per_page: r.body.per_page ?? r.query.get("per_page") ?? 15 });
|
|
155546
155703
|
return { ...l, data: l.data.map((co) => companyShape(r, co)) };
|
|
155547
155704
|
} },
|
|
155548
155705
|
{
|
|
@@ -155552,7 +155709,7 @@ var intercomRoutes = [
|
|
|
155552
155709
|
run: (r) => {
|
|
155553
155710
|
const b = r.body;
|
|
155554
155711
|
if (!b.company_id && !b.name) fail3(400, "parameter_invalid", "company_id or name is required");
|
|
155555
|
-
const at3 = now8(r), existing2 =
|
|
155712
|
+
const at3 = now8(r), existing2 = all7(r.ctx, "company").find((co2) => co2.company_id === (b.company_id ?? b.name));
|
|
155556
155713
|
const co = existing2 ?? { id: r.ctx.ids.hex(24), company_id: b.company_id ?? b.name, name: b.name ?? b.company_id, plan: null, plan_id: null, size: null, website: null, industry: null, monthly_spend: 0, custom_attributes: {}, created_at: b.remote_created_at ?? at3, updated_at: at3 };
|
|
155557
155714
|
for (const key3 of ["name", "size", "website", "industry", "monthly_spend"]) if (b[key3] !== void 0) co[key3] = b[key3];
|
|
155558
155715
|
if (b.plan !== void 0) {
|
|
@@ -155584,7 +155741,7 @@ var intercomRoutes = [
|
|
|
155584
155741
|
coverage: { status: "supported" },
|
|
155585
155742
|
run: (r) => {
|
|
155586
155743
|
const co = load5(r.ctx, "company", r.param("id")) ?? notFound15("Company");
|
|
155587
|
-
const l = listOf("list", "data",
|
|
155744
|
+
const l = listOf("list", "data", all7(r.ctx, "contact").filter((c) => c.companies.includes(co.id)), r);
|
|
155588
155745
|
return { ...l, data: l.data.map((c) => contactShape2(r, c)) };
|
|
155589
155746
|
}
|
|
155590
155747
|
},
|
|
@@ -155593,7 +155750,7 @@ var intercomRoutes = [
|
|
|
155593
155750
|
path: "/conversations",
|
|
155594
155751
|
coverage: { status: "supported", notes: "newest activity first" },
|
|
155595
155752
|
run: (r) => {
|
|
155596
|
-
const l = listOf("conversation.list", "conversations",
|
|
155753
|
+
const l = listOf("conversation.list", "conversations", all7(r.ctx, "conversation").sort((a, b) => b.updated_at - a.updated_at), r, 20);
|
|
155597
155754
|
return { ...l, conversations: l.conversations.map((c) => conversationShape(r, c, false)) };
|
|
155598
155755
|
}
|
|
155599
155756
|
},
|
|
@@ -155603,7 +155760,7 @@ var intercomRoutes = [
|
|
|
155603
155760
|
coverage: { status: "partial", notes: "state, assignment, tags, contacts, source and timestamps; ratings, AI agent and statistics fields are gaps" },
|
|
155604
155761
|
run: (r) => {
|
|
155605
155762
|
const ok = matcher(conversationFields(), CONVERSATION_DOCUMENTED, r.body.query, "conversations");
|
|
155606
|
-
const l = listOf("conversation.list", "conversations",
|
|
155763
|
+
const l = listOf("conversation.list", "conversations", all7(r.ctx, "conversation").filter(ok).sort((a, b) => b.updated_at - a.updated_at), r, 20, r.body);
|
|
155607
155764
|
return { ...l, conversations: l.conversations.map((c) => conversationShape(r, c, false)) };
|
|
155608
155765
|
}
|
|
155609
155766
|
},
|
|
@@ -155674,7 +155831,7 @@ var intercomRoutes = [
|
|
|
155674
155831
|
}
|
|
155675
155832
|
} else if (b.type === "user") {
|
|
155676
155833
|
if (b.message_type !== "comment") fail3(400, "parameter_invalid", "a contact can only reply with a comment");
|
|
155677
|
-
const contact = load5(r.ctx, "contact", String(b.intercom_user_id ?? "")) ??
|
|
155834
|
+
const contact = load5(r.ctx, "contact", String(b.intercom_user_id ?? "")) ?? all7(r.ctx, "contact").find((c) => b.user_id && c.external_id === b.user_id || b.email && c.email?.toLowerCase() === String(b.email).toLowerCase());
|
|
155678
155835
|
if (!contact || contact.id !== conv.contact_id) fail3(404, "not_found", "User Not Found");
|
|
155679
155836
|
addPart(r, conv, { type: "comment", body: html(b.body), author: { type: "user", id: contact.id } });
|
|
155680
155837
|
if (conv.state !== "open") {
|
|
@@ -155755,7 +155912,7 @@ var intercomRoutes = [
|
|
|
155755
155912
|
return { type: "tag", id: tag3.id, name: tag3.name };
|
|
155756
155913
|
}
|
|
155757
155914
|
},
|
|
155758
|
-
{ method: "GET", path: "/tags", coverage: { status: "supported" }, run: (r) => ({ type: "list", data:
|
|
155915
|
+
{ method: "GET", path: "/tags", coverage: { status: "supported" }, run: (r) => ({ type: "list", data: all7(r.ctx, "tag").map((t) => ({ type: "tag", id: t.id, name: t.name })) }) },
|
|
155759
155916
|
{
|
|
155760
155917
|
method: "POST",
|
|
155761
155918
|
path: "/tags",
|
|
@@ -155769,7 +155926,7 @@ var intercomRoutes = [
|
|
|
155769
155926
|
save10(r.ctx, "tag", { ...t2, name: b.name });
|
|
155770
155927
|
return { type: "tag", id: t2.id, name: b.name };
|
|
155771
155928
|
}
|
|
155772
|
-
const existing2 =
|
|
155929
|
+
const existing2 = all7(r.ctx, "tag").find((t2) => t2.name.toLowerCase() === b.name.toLowerCase());
|
|
155773
155930
|
const t = existing2 ?? save10(r.ctx, "tag", { id: nextId5(r.ctx, "tag"), name: b.name });
|
|
155774
155931
|
return { type: "tag", id: t.id, name: t.name };
|
|
155775
155932
|
}
|
|
@@ -155784,14 +155941,14 @@ var intercomRoutes = [
|
|
|
155784
155941
|
coverage: { status: "supported" },
|
|
155785
155942
|
run: (r) => {
|
|
155786
155943
|
const t = load5(r.ctx, "tag", r.param("id")) ?? notFound15("Tag");
|
|
155787
|
-
const used = [...
|
|
155944
|
+
const used = [...all7(r.ctx, "contact"), ...all7(r.ctx, "conversation")].some((x) => x.tags.some((y) => y.id === t.id));
|
|
155788
155945
|
if (used) fail3(400, "tag_has_dependent_objects", "Unable to delete Tag with dependent objects.");
|
|
155789
155946
|
remove3(r.ctx, "tag", t.id);
|
|
155790
155947
|
return void 0;
|
|
155791
155948
|
}
|
|
155792
155949
|
},
|
|
155793
155950
|
{ method: "GET", path: "/articles", coverage: { status: "supported" }, run: (r) => {
|
|
155794
|
-
const l = byPage(
|
|
155951
|
+
const l = byPage(all7(r.ctx, "article"), r, 50, "data");
|
|
155795
155952
|
return { ...l, data: l.data.map((a) => articleShape(r, a)) };
|
|
155796
155953
|
} },
|
|
155797
155954
|
{
|
|
@@ -155801,7 +155958,7 @@ var intercomRoutes = [
|
|
|
155801
155958
|
run: (r) => {
|
|
155802
155959
|
const words4 = (r.query.get("phrase") ?? "").toLowerCase().split(/\W+/).filter(Boolean), state3 = r.query.get("state");
|
|
155803
155960
|
if (r.query.get("help_center_id")) unsupported26("searching one help center of several");
|
|
155804
|
-
const found =
|
|
155961
|
+
const found = all7(r.ctx, "article").filter((a) => (!state3 || state3 === "all" || a.state === state3) && words4.every((w) => `${a.title} ${a.description} ${plain3(a.body)}`.toLowerCase().includes(w)));
|
|
155805
155962
|
return { type: "list", total_count: found.length, data: { articles: found.map((a) => articleShape(r, a)), highlights: [] }, pages: { type: "pages", page: 1, per_page: Math.max(found.length, 1), total_pages: 1 } };
|
|
155806
155963
|
}
|
|
155807
155964
|
},
|
|
@@ -155978,11 +156135,11 @@ function dumpState31(ctx) {
|
|
|
155978
156135
|
const contact = (id12) => load5(ctx, "contact", id12);
|
|
155979
156136
|
return {
|
|
155980
156137
|
workspace: workspace(ctx).name,
|
|
155981
|
-
admins:
|
|
155982
|
-
teams:
|
|
155983
|
-
tags:
|
|
155984
|
-
companies:
|
|
155985
|
-
contacts:
|
|
156138
|
+
admins: all7(ctx, "admin").map((a) => ({ id: a.id, name: a.name, email: a.email, away: a.away })),
|
|
156139
|
+
teams: all7(ctx, "team").map((t) => ({ id: t.id, name: t.name, members: t.admin_ids.map(admin) })),
|
|
156140
|
+
tags: all7(ctx, "tag").map((t) => t.name),
|
|
156141
|
+
companies: all7(ctx, "company").map((co) => ({ id: co.id, name: co.name, company_id: co.company_id, plan: co.plan })),
|
|
156142
|
+
contacts: all7(ctx, "contact").map((c) => ({
|
|
155986
156143
|
id: c.id,
|
|
155987
156144
|
name: c.name,
|
|
155988
156145
|
email: c.email,
|
|
@@ -155994,9 +156151,9 @@ function dumpState31(ctx) {
|
|
|
155994
156151
|
companies: c.companies.map((id12) => load5(ctx, "company", id12)?.name ?? null),
|
|
155995
156152
|
tags: c.tags.map(tag3),
|
|
155996
156153
|
custom_attributes: c.custom_attributes,
|
|
155997
|
-
notes:
|
|
156154
|
+
notes: all7(ctx, "note").filter((n) => n.contact_id === c.id).map((n) => ({ author: admin(n.author), body: plain3(n.body), created_at: iso13(n.created_at) }))
|
|
155998
156155
|
})),
|
|
155999
|
-
conversations:
|
|
156156
|
+
conversations: all7(ctx, "conversation").map((v) => ({
|
|
156000
156157
|
id: v.id,
|
|
156001
156158
|
contact: contact(v.contact_id)?.name ?? null,
|
|
156002
156159
|
contact_email: contact(v.contact_id)?.email ?? null,
|
|
@@ -156020,7 +156177,7 @@ function dumpState31(ctx) {
|
|
|
156020
156177
|
...p2.assigned_to && { assigned_to: p2.assigned_to.type === "admin" ? admin(p2.assigned_to.id) : load5(ctx, "team", p2.assigned_to.id)?.name ?? null }
|
|
156021
156178
|
}))
|
|
156022
156179
|
})),
|
|
156023
|
-
articles:
|
|
156180
|
+
articles: all7(ctx, "article").map((a) => ({ id: a.id, title: a.title, state: a.state }))
|
|
156024
156181
|
};
|
|
156025
156182
|
}
|
|
156026
156183
|
|
|
@@ -156521,9 +156678,9 @@ function macroJson(ctx, macro2) {
|
|
|
156521
156678
|
};
|
|
156522
156679
|
}
|
|
156523
156680
|
function viewJson(ctx, view3) {
|
|
156524
|
-
const
|
|
156681
|
+
const all8 = [{ field: "status", operator: "less_than", value: "solved" }], statuses2 = JSON.parse(view3.statuses);
|
|
156525
156682
|
const conditions = [
|
|
156526
|
-
...statuses2.join() === "new,open,pending,hold" ?
|
|
156683
|
+
...statuses2.join() === "new,open,pending,hold" ? all8 : statuses2.map((status5) => ({ field: "status", operator: "is", value: status5 })),
|
|
156527
156684
|
...view3.assignee === "none" ? [{ field: "assignee_id", operator: "is", value: null }] : view3.assignee === "me" ? [{ field: "assignee_id", operator: "is", value: "current_user" }] : [],
|
|
156528
156685
|
...view3.group_id === null ? [] : [{ field: "group_id", operator: "is", value: String(view3.group_id) }]
|
|
156529
156686
|
];
|
|
@@ -159763,9 +159920,9 @@ function permissionsIn(ctx, userId, channel3) {
|
|
|
159763
159920
|
if (ctx.store.meta.get("discord.owner") === userId) return ALL;
|
|
159764
159921
|
const member4 = getMember(ctx, userId);
|
|
159765
159922
|
if (!member4) return 0n;
|
|
159766
|
-
const
|
|
159923
|
+
const all8 = roles(ctx), mine = new Set(JSON.parse(member4.roles)), everyone = guildId(ctx);
|
|
159767
159924
|
let permissions = 0n;
|
|
159768
|
-
for (const role3 of
|
|
159925
|
+
for (const role3 of all8) if (role3.id === everyone || mine.has(role3.id)) permissions |= BigInt(role3.permissions);
|
|
159769
159926
|
if (permissions & BITS.ADMINISTRATOR) return ALL;
|
|
159770
159927
|
const target5 = channel3?.type === PUBLIC_THREAD ? getChannel(ctx, channel3.parent_id) : channel3;
|
|
159771
159928
|
if (!target5 || target5.type === DM) return permissions;
|
|
@@ -160096,8 +160253,8 @@ function members3(call2) {
|
|
|
160096
160253
|
guildFor(call2);
|
|
160097
160254
|
const params9 = call2.url.searchParams, limit2 = Number(params9.get("limit") ?? 1), after = params9.get("after") ?? "0";
|
|
160098
160255
|
if (!Number.isInteger(limit2) || limit2 < 1 || limit2 > 1e3) throw invalidForm("limit", "NUMBER_TYPE_MAX", "int value should be between 1 and 1000");
|
|
160099
|
-
const
|
|
160100
|
-
return json27(
|
|
160256
|
+
const all8 = call2.ctx.store.db.prepare("SELECT * FROM dc_members").all().sort((a, b) => BigInt(a.user_id) < BigInt(b.user_id) ? -1 : 1);
|
|
160257
|
+
return json27(all8.filter((member4) => BigInt(member4.user_id) > BigInt(after)).slice(0, limit2).map((member4) => memberJson(call2.ctx, member4)));
|
|
160101
160258
|
}
|
|
160102
160259
|
function member2(call2) {
|
|
160103
160260
|
guildFor(call2);
|
|
@@ -160121,15 +160278,15 @@ function listMessages2(call2) {
|
|
|
160121
160278
|
const anchors = ["before", "after", "around"].filter((name5) => params9.has(name5));
|
|
160122
160279
|
if (anchors.length > 1) throw invalidForm(anchors[1], "BASE_TYPE_BAD_ARGUMENT", "Only one of before, after or around may be given");
|
|
160123
160280
|
if (!canRead(call2, channel3)) return json27([]);
|
|
160124
|
-
const
|
|
160281
|
+
const all8 = call2.ctx.store.db.prepare("SELECT * FROM dc_messages WHERE channel_id = ? AND deleted_ms IS NULL").all(channel3.id).sort((a, b) => BigInt(b.id) > BigInt(a.id) ? 1 : -1);
|
|
160125
160282
|
const at3 = (name5) => BigInt(params9.get(name5));
|
|
160126
160283
|
let page15;
|
|
160127
|
-
if (params9.has("before")) page15 =
|
|
160128
|
-
else if (params9.has("after")) page15 =
|
|
160284
|
+
if (params9.has("before")) page15 = all8.filter((row) => BigInt(row.id) < at3("before")).slice(0, limit2);
|
|
160285
|
+
else if (params9.has("after")) page15 = all8.filter((row) => BigInt(row.id) > at3("after")).slice(-limit2);
|
|
160129
160286
|
else if (params9.has("around")) {
|
|
160130
|
-
const older =
|
|
160287
|
+
const older = all8.filter((row) => BigInt(row.id) <= at3("around")).slice(0, Math.ceil(limit2 / 2)), newer = all8.filter((row) => BigInt(row.id) > at3("around")).slice(-Math.floor(limit2 / 2));
|
|
160131
160288
|
page15 = [...newer, ...older];
|
|
160132
|
-
} else page15 =
|
|
160289
|
+
} else page15 = all8.slice(0, limit2);
|
|
160133
160290
|
return json27(page15.map((row) => messageJson2(call2.ctx, row)));
|
|
160134
160291
|
}
|
|
160135
160292
|
function showMessage(call2) {
|
|
@@ -162531,8 +162688,8 @@ var AirtableBase = class _AirtableBase {
|
|
|
162531
162688
|
}
|
|
162532
162689
|
/** A table by id or name, as the URL gives it. */
|
|
162533
162690
|
table(ref20) {
|
|
162534
|
-
const
|
|
162535
|
-
const found =
|
|
162691
|
+
const all8 = this.tables();
|
|
162692
|
+
const found = all8.find((item2) => item2.id === ref20) ?? all8.find((item2) => item2.name === ref20) ?? all8.find((item2) => item2.name.toLowerCase() === ref20.toLowerCase());
|
|
162536
162693
|
if (!found) throw modelNotFound();
|
|
162537
162694
|
return found;
|
|
162538
162695
|
}
|
|
@@ -162546,8 +162703,8 @@ var AirtableBase = class _AirtableBase {
|
|
|
162546
162703
|
}
|
|
162547
162704
|
/** A field by id or exact name; `loose` also matches names regardless of case (as formulas do). */
|
|
162548
162705
|
field(tableId, ref20, loose = false) {
|
|
162549
|
-
const
|
|
162550
|
-
return
|
|
162706
|
+
const all8 = this.fields(tableId);
|
|
162707
|
+
return all8.find((item2) => item2.id === ref20) ?? all8.find((item2) => item2.name === ref20) ?? (loose ? all8.find((item2) => item2.name.toLowerCase() === ref20.toLowerCase()) : void 0);
|
|
162551
162708
|
}
|
|
162552
162709
|
fieldById(id12) {
|
|
162553
162710
|
for (const table3 of this.tables()) {
|
|
@@ -162932,13 +163089,13 @@ var AirtableBase = class _AirtableBase {
|
|
|
162932
163089
|
}
|
|
162933
163090
|
}
|
|
162934
163091
|
#person(value4, typecast, bad3) {
|
|
162935
|
-
const
|
|
163092
|
+
const all8 = this.users(), lower4 = (text24) => String(text24).trim().toLowerCase();
|
|
162936
163093
|
let found;
|
|
162937
163094
|
if (value4 && typeof value4 === "object" && !Array.isArray(value4)) {
|
|
162938
163095
|
const ref20 = value4;
|
|
162939
|
-
found = ref20.id !== void 0 ?
|
|
163096
|
+
found = ref20.id !== void 0 ? all8.find((item2) => item2.id === ref20.id) : ref20.email !== void 0 ? all8.find((item2) => item2.email.toLowerCase() === lower4(ref20.email)) : void 0;
|
|
162940
163097
|
} else if (typeof value4 === "string") {
|
|
162941
|
-
found =
|
|
163098
|
+
found = all8.find((item2) => item2.id === value4) ?? all8.find((item2) => item2.email.toLowerCase() === lower4(value4)) ?? (typecast ? all8.find((item2) => item2.name.toLowerCase() === lower4(value4)) : void 0);
|
|
162942
163099
|
}
|
|
162943
163100
|
if (!found) throw bad3();
|
|
162944
163101
|
return found.id;
|
|
@@ -163280,11 +163437,11 @@ function commentsOf3(call2, writing) {
|
|
|
163280
163437
|
var liveComments = (ctx, recordId) => ctx.store.db.prepare("SELECT * FROM at_comments WHERE record_id = ? AND deleted_ms IS NULL ORDER BY created_ms DESC, id DESC").all(recordId);
|
|
163281
163438
|
function listComments3(call2) {
|
|
163282
163439
|
const { model: model2, record: record23 } = commentsOf3(call2, false), pageSize2 = whole(call2.url.searchParams.get("pageSize") ?? void 0, "pageSize", 1, 100) ?? 100;
|
|
163283
|
-
const
|
|
163284
|
-
const from = offset16 === null ? 0 :
|
|
163440
|
+
const all8 = liveComments(call2.ctx, record23.id), offset16 = call2.url.searchParams.get("offset");
|
|
163441
|
+
const from = offset16 === null ? 0 : all8.findIndex((row) => row.id === offset16);
|
|
163285
163442
|
if (from < 0) throw new AirtableError(422, "LIST_RECORDS_ITERATOR_NOT_AVAILABLE");
|
|
163286
|
-
const page15 =
|
|
163287
|
-
return json29({ comments: page15.map((row) => commentJson2(model2, row)), offset:
|
|
163443
|
+
const page15 = all8.slice(from, from + pageSize2);
|
|
163444
|
+
return json29({ comments: page15.map((row) => commentJson2(model2, row)), offset: all8[from + pageSize2]?.id ?? null });
|
|
163288
163445
|
}
|
|
163289
163446
|
function commentText(body6) {
|
|
163290
163447
|
if (typeof body6.text !== "string" || !body6.text.trim()) throw invalidRequest("Invalid request: text is required");
|
|
@@ -166665,7 +166822,7 @@ JSON: {"files": [{"repo": "${legend.repos.keys().next().value}", "path": "src/ex
|
|
|
166665
166822
|
check(value4) {
|
|
166666
166823
|
const parsed3 = FilesSchema.safeParse(value4);
|
|
166667
166824
|
if (!parsed3.success) return { errors: zodErrors(parsed3.error) };
|
|
166668
|
-
const files2 = parsed3.data.files.filter((file3, i,
|
|
166825
|
+
const files2 = parsed3.data.files.filter((file3, i, all8) => legend.repos.has(file3.repo) && all8.findIndex((other) => other.repo === file3.repo && other.path === file3.path) === i);
|
|
166669
166826
|
const missing6 = [...legend.repos.keys()].filter((name5) => !files2.some((file3) => file3.repo === name5));
|
|
166670
166827
|
if (missing6.length) return { errors: [
|
|
166671
166828
|
...parsed3.data.files.flatMap((file3, i) => legend.repos.has(file3.repo) ? [] : [`files[${i}].repo: ${JSON.stringify(file3.repo)} is not a repository; use one of ${oneOf2(legend.repos.keys())}`]),
|
|
@@ -168958,6 +169115,7 @@ import { basename as basename5, dirname as dirname5, join as join6, resolve as r
|
|
|
168958
169115
|
init_src();
|
|
168959
169116
|
|
|
168960
169117
|
// backend/src/report.ts
|
|
169118
|
+
init_src();
|
|
168961
169119
|
var MAX_FAILURES_PER_SCENE = 20;
|
|
168962
169120
|
var DEFAULT_RUNS_DIR = ".ancha/runs";
|
|
168963
169121
|
var exitedCleanly = (t) => t.exit === "done" || t.exit === "idle" || t.exit === "exited" && t.exitCode === 0;
|
|
@@ -168987,13 +169145,15 @@ function traceExcerpt(trace, evidence) {
|
|
|
168987
169145
|
return trace.filter((e) => wanted.has(e.seq)).map(excerptOf);
|
|
168988
169146
|
}
|
|
168989
169147
|
var trialIssues = (t) => t.harnessIssues ?? collectHarnessIssues(t.trace, t.checks);
|
|
168990
|
-
var trialValid = (t) => !trialIssues(t).some((i) => i.owner === "harness");
|
|
168991
|
-
|
|
169148
|
+
var trialValid = (t) => t.valid !== false && t.exit !== "invalid" && !trialIssues(t).some((i) => i.owner === "harness");
|
|
169149
|
+
var outcomeOf2 = (t) => trialOutcome({ ...t, valid: trialValid(t), outcome: t.checks.some((check4) => check4.required && check4.status === "skipped") ? "skipped" : t.outcome });
|
|
169150
|
+
function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
|
|
169151
|
+
const counts = countTrials(requestedTrials, trials.map(outcomeOf2));
|
|
168992
169152
|
const checks = {};
|
|
168993
169153
|
const failures = [];
|
|
168994
169154
|
const agentIssues = [];
|
|
168995
169155
|
const harnessIssues = [];
|
|
168996
|
-
|
|
169156
|
+
const invalidTrials = counts.invalid;
|
|
168997
169157
|
let skippedJudges = 0;
|
|
168998
169158
|
const warnings = [];
|
|
168999
169159
|
const gaps2 = /* @__PURE__ */ new Map();
|
|
@@ -169001,7 +169161,6 @@ function summarizeScene(sceneId, trials) {
|
|
|
169001
169161
|
let totalMs = 0;
|
|
169002
169162
|
for (const t of trials) {
|
|
169003
169163
|
totalMs += t.realMs;
|
|
169004
|
-
if (!trialValid(t)) invalidTrials++;
|
|
169005
169164
|
for (const issue5 of trialIssues(t)) {
|
|
169006
169165
|
if (harnessIssues.length < MAX_FAILURES_PER_SCENE) harnessIssues.push({ ...issue5, sceneId, trial: t.trial });
|
|
169007
169166
|
}
|
|
@@ -169041,13 +169200,14 @@ function summarizeScene(sceneId, trials) {
|
|
|
169041
169200
|
}
|
|
169042
169201
|
}
|
|
169043
169202
|
}
|
|
169044
|
-
const passed =
|
|
169203
|
+
const passed = counts.passed;
|
|
169045
169204
|
return {
|
|
169046
169205
|
sceneId,
|
|
169206
|
+
counts,
|
|
169047
169207
|
trials: trials.length,
|
|
169048
169208
|
passed,
|
|
169049
|
-
passRate:
|
|
169050
|
-
passAllK:
|
|
169209
|
+
passRate: counts.requested === 0 ? 0 : round4(passed / counts.requested),
|
|
169210
|
+
passAllK: allTrialsPassed(counts),
|
|
169051
169211
|
checks,
|
|
169052
169212
|
agentIssues,
|
|
169053
169213
|
harnessIssues,
|
|
@@ -169058,18 +169218,19 @@ function summarizeScene(sceneId, trials) {
|
|
|
169058
169218
|
coverageGaps: [...gaps2.values()],
|
|
169059
169219
|
meanRealMs: trials.length === 0 ? 0 : Math.round(totalMs / trials.length),
|
|
169060
169220
|
agentCalls: agentCalls2,
|
|
169061
|
-
trialsDetail: trials.map((t) => ({ trial: t.trial, passed: t
|
|
169221
|
+
trialsDetail: trials.map((t) => ({ trial: t.trial, passed: outcomeOf2(t) === "passed", valid: trialValid(t), ...outcomeOf2(t) === "skipped" ? { outcome: "skipped" } : t.outcome ? { outcome: t.outcome } : {}, ...t.checks.some((c) => c.status === "skipped") && { skippedJudges: t.checks.filter((c) => c.status === "skipped").length }, exit: t.exit, exitCode: t.exitCode, realMs: t.realMs, ...t.simMs !== void 0 && { simMs: t.simMs }, ...t.playOut !== void 0 && { playOut: t.playOut }, ...t.sessionId !== void 0 && { sessionId: t.sessionId }, dir: t.dir }))
|
|
169062
169222
|
};
|
|
169063
169223
|
}
|
|
169064
169224
|
function summarize(run6, agent, minPassRate) {
|
|
169065
|
-
const scenes = [...run6.results].map(([sceneId, value4]) => ({ ...summarizeScene(sceneId, value4.trials), ...value4.case && { scenarioId: value4.scene.id, case: value4.case } }));
|
|
169225
|
+
const scenes = [...run6.results].map(([sceneId, value4]) => ({ ...summarizeScene(sceneId, value4.trials, value4.requestedTrials), ...value4.case && { scenarioId: value4.scene.id, case: value4.case } }));
|
|
169066
169226
|
return {
|
|
169227
|
+
verdictVersion: VERDICT_VERSION,
|
|
169067
169228
|
runId: run6.runId,
|
|
169068
169229
|
startedAt: run6.startedAt,
|
|
169069
169230
|
finishedAt: run6.finishedAt,
|
|
169070
169231
|
agent,
|
|
169071
169232
|
minPassRate,
|
|
169072
|
-
verdict: scenes.every((s) => s.invalidTrials === 0 && s.
|
|
169233
|
+
verdict: scenes.every((s) => s.invalidTrials === 0 && meetsPassRate(s.counts, minPassRate)) ? "pass" : "fail",
|
|
169073
169234
|
scenes,
|
|
169074
169235
|
...[...run6.results.values()].some((value4) => value4.case) && { caseFingerprints: Object.fromEntries([...run6.results].flatMap(([id12, value4]) => value4.case ? [[id12, value4.case.fingerprint]] : [])) },
|
|
169075
169236
|
sceneFingerprints: Object.fromEntries([...run6.results].map(([id12, { scene: scene2 }]) => [id12, sceneFingerprint(scene2)])),
|
|
@@ -169136,10 +169297,10 @@ function renderSummaryText(s, opts = {}) {
|
|
|
169136
169297
|
if (s.pytest) lines.push(`pytest ${s.pytest.nodeId}: ${s.pytest.outcome}${s.pytest.invalid ? " [invalid]" : !s.pytest.graded ? " (ungraded)" : ""}`);
|
|
169137
169298
|
for (const scene2 of s.scenes) {
|
|
169138
169299
|
const invalid30 = scene2.invalidTrials ?? 0;
|
|
169139
|
-
const ok = invalid30 === 0 && scene2.
|
|
169300
|
+
const ok = invalid30 === 0 && !!scene2.counts && meetsPassRate(scene2.counts, s.minPassRate);
|
|
169140
169301
|
const excluded3 = scene2.trialsDetail.filter((trial) => trial.outcome === "skipped" || trial.outcome === "xfailed").length;
|
|
169141
169302
|
if (s.pytest && !s.pytest.graded) lines.push(`\u2014 ${scene2.sceneId} ungraded${excluded3 ? ` (${excluded3} excluded)` : ""}${invalid30 ? " [invalid]" : ""}`);
|
|
169142
|
-
else lines.push(`${ok ? "\u2713" : "\u2717"} ${scene2.sceneId} ${scene2.passed}/${scene2.
|
|
169303
|
+
else lines.push(`${ok ? "\u2713" : "\u2717"} ${scene2.sceneId} ${scene2.passed}/${scene2.counts?.requested ?? scene2.trials} (${pct(scene2.passRate)}%)${invalid30 > 0 ? " [invalid]" : ""}${excluded3 ? ` (${excluded3} excluded)` : ""}`);
|
|
169143
169304
|
if (invalid30 > 0) lines.push(` \u2717 harness failure: ${invalid30}/${scene2.trials} trials invalid`);
|
|
169144
169305
|
if ((scene2.skippedJudges ?? 0) > 0) lines.push(` judge grading skipped: ${scene2.skippedJudges} check(s)`);
|
|
169145
169306
|
for (const warning of scene2.warnings ?? []) lines.push(` warning: trial ${warning.trial} ${warning.check}: ${warning.message.replaceAll("\n", "\n ")}`);
|
|
@@ -169420,6 +169581,7 @@ async function loadRunSummary(cwd, ref20, out) {
|
|
|
169420
169581
|
}
|
|
169421
169582
|
|
|
169422
169583
|
// packages/cli/src/report-html.ts
|
|
169584
|
+
init_src();
|
|
169423
169585
|
var escape9 = (value4) => String(value4 ?? "").replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
169424
169586
|
var pct2 = (rate) => `${Math.round(rate * 1e3) / 10}%`;
|
|
169425
169587
|
var ms = (value4) => value4 < 1e3 ? `${value4}ms` : `${(value4 / 1e3).toFixed(1)}s`;
|
|
@@ -169454,15 +169616,16 @@ function renderHtmlReport(input2) {
|
|
|
169454
169616
|
const pytest = summary.pytest ? `<p>pytest <code>${escape9(summary.pytest.nodeId)}</code> \xB7 ${escape9(summary.pytest.outcome)}</p><p class="muted">${escape9(summary.pytest.excluded)} excluded invocation(s) \xB7 ${summary.pytest.phases.map((phase) => `${escape9(phase.when)} ${escape9(phase.outcome)}${phase.errorCode ? ` (${escape9(phase.errorCode)})` : ""}`).join(" \xB7 ")}</p>` : "";
|
|
169455
169617
|
const rows33 = summary.scenes.map((scene2) => {
|
|
169456
169618
|
const change = summary.comparison?.scenes.find((item2) => item2.sceneId === scene2.sceneId);
|
|
169457
|
-
const evaluated =
|
|
169619
|
+
const evaluated = scene2.counts?.requested ?? scene2.trials;
|
|
169620
|
+
const valid2 = scene2.counts?.valid ?? scene2.trialsDetail.filter((trial) => trial.valid !== false && trial.outcome !== "skipped" && trial.outcome !== "xfailed").length;
|
|
169458
169621
|
const excluded3 = scene2.trialsDetail.filter((trial) => trial.outcome === "skipped" || trial.outcome === "xfailed").length;
|
|
169459
|
-
return `<tr><th scope="row">${escape9(scene2.sceneId)}<span class="scene-note">${escape9(
|
|
169622
|
+
return `<tr><th scope="row">${escape9(scene2.sceneId)}<span class="scene-note">${escape9(evaluated)} requested \xB7 ${escape9(valid2)} valid \xB7 ${escape9(scene2.invalidTrials)} invalid \xB7 ${escape9(scene2.counts?.skipped ?? excluded3)} skipped \xB7 ${escape9(scene2.skippedJudges)} judge(s) skipped</span></th><td>${trialMatrix(scene2)}</td><td class="numeric">${escape9(scene2.passed)} / ${escape9(evaluated)}<strong>${summary.pytest && evaluated === 0 ? "Not graded" : pct2(scene2.passRate)}</strong></td><td>${!scene2.counts ? "Unverified" : allTrialsPassed(scene2.counts) ? "Yes" : "No"}<span class="scene-note">All ${escape9(evaluated)} requested trials</span></td><td class="numeric">${ms(scene2.meanRealMs)}<span class="scene-note">${escape9(scene2.agentCalls)} agent call(s)</span></td><td class="${change && change.delta < 0 ? "negative" : ""}">${change ? `${delta(change.delta)}<span class="scene-note">${pct2(change.before)} \u2192 ${pct2(change.after)}${change.beforeTrials === void 0 || change.afterTrials === void 0 ? "" : `<br>${escape9(change.beforeTrials)} \u2192 ${escape9(change.afterTrials)} trials`}</span>` : "\u2014"}</td></tr>`;
|
|
169460
169623
|
}).join("");
|
|
169461
169624
|
const comparison2 = summary.comparison === void 0 ? "" : `<aside class="comparison"><strong>${summary.comparison.regressed ? "Regression detected" : "No per-scene regression"}</strong><span>Compared with <code>${escape9(summary.comparison.baselineRunId)}</code>. Every scene must meet the threshold and avoid a pass-rate decrease. Trial counts may differ between runs.</span></aside>`;
|
|
169462
169625
|
return `<!doctype html>
|
|
169463
169626
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><title>Ancha \xB7 ${escape9(summary.runId)}</title><style>
|
|
169464
169627
|
:root{color-scheme:light;--ink:#14283F;--page:#F5F8FC;--surface:#FFFFFF;--pass:#087F74;--failure:#AB3D2E;--muted:#64748B;--line:#dbe3ed}*{box-sizing:border-box}body{margin:0;background:var(--page);color:var(--ink);font:15px/1.55 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}main{max-width:1320px;margin:auto;padding:36px 32px 64px}header{border-top:5px solid var(--ink);padding-top:18px}.eyebrow{font:700 12px/1.4 system-ui,sans-serif;letter-spacing:.13em;text-transform:uppercase;display:flex;justify-content:space-between;gap:20px}.eyebrow code{letter-spacing:0;text-transform:none;font-weight:400}h1,h2{font-family:"Avenir Next","Trebuchet MS",sans-serif}h1{font-size:34px;letter-spacing:-.035em;line-height:1.15;margin:24px 0 8px}h2{font-size:21px;line-height:1.3;margin:0 0 16px}h3,h4,p{margin:12px 0}h4{font-size:14px}code,pre,.numeric,.path{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}code{font-size:.88em;overflow-wrap:anywhere}.identity{display:grid;grid-template-columns:1fr auto;gap:20px;margin-bottom:24px}.identity p{margin:5px 0}.muted,.scene-note{color:var(--muted)}.pass-text{color:var(--pass)}.negative,.fail-text{color:var(--failure)}.comparison{border-left:4px solid var(--ink);background:#eaf0f7;padding:14px 18px;margin:22px 0 28px;display:grid;gap:4px}.legend{display:flex;flex-wrap:wrap;gap:10px 24px;font-size:12px;margin:12px 0 20px}.legend b{font-size:16px;margin-right:5px}.scroll{overflow-x:auto}.reliability{min-width:860px}table{width:100%;border-collapse:collapse;background:var(--surface)}th,td{padding:17px 16px;text-align:left;vertical-align:middle;border-bottom:1px solid var(--line)}thead th{font-size:11px;letter-spacing:.07em;text-transform:uppercase;background:#eaf0f7;color:var(--ink)}tbody th{font-weight:600}td strong{display:block;font-size:12px}.scene-note{display:block;font:400 12px/1.5 system-ui,sans-serif;margin-top:5px}.matrix{display:flex;flex-wrap:wrap;gap:5px;min-width:180px;max-width:470px}.trial{width:35px;height:40px;display:inline-flex;position:relative;align-items:center;justify-content:center;border:1px solid var(--line);font-size:22px;font-weight:700;border-radius:3px;padding-bottom:8px}.trial-number{position:absolute;bottom:1px;left:0;right:0;font:9px/1.1 ui-monospace,monospace;text-align:center}.passed{color:var(--pass);background:#e5f3f0}.failed{color:var(--failure);background:#f9e9e5}.invalid{color:var(--ink);background:#e5ebf3}.skipped,.unverified{color:#6b5200;background:#fff5d9}.skip-mark{position:absolute;right:1px;top:-3px;font-size:12px;color:#6b5200}section{margin-top:38px}.section-intro{color:var(--muted);margin:-6px 0 18px}details{background:var(--surface);border:1px solid var(--line);border-radius:4px;margin:10px 0}summary{cursor:pointer;padding:15px 18px;font-weight:600}summary:hover{background:#f0f4f9}summary:focus-visible{outline:3px solid var(--pass);outline-offset:3px}.scene-evidence>summary .muted{font-size:12px;font-weight:400;margin-left:20px}.detail-body{padding:0 18px 18px}.failure{border-left:3px solid var(--failure)}.issue{border-left:3px solid var(--failure);padding:8px 14px;margin:16px 0;background:#f9eeeb}.issue.invalid{border-left-color:var(--ink);background:#eaf0f7}dl{margin:16px 0}dt{font-size:11px;text-transform:uppercase;font-weight:700;letter-spacing:.07em;margin-top:14px}dd{margin:4px 0 0}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:var(--page);border:1px solid var(--line);padding:12px;font-size:12px;line-height:1.65;margin:4px 0}.path{font-size:12px;overflow-wrap:anywhere}.checks{font-size:12px}.checks th,.checks td{padding:10px}.checks caption{text-align:left;font-weight:700;padding:12px 0}ul{padding-left:22px}li{margin:8px 0}footer{border-top:1px solid var(--line);margin-top:38px;padding-top:18px;font-size:12px;color:var(--muted)}@media(max-width:700px){main{padding:24px 16px}.eyebrow,.identity{display:block}.eyebrow code{display:block;margin-top:6px}h1{font-size:29px}.scene-evidence>summary .muted{display:block;margin-left:0}}@media print{body{background:white}main{padding:0;max-width:none}details{break-inside:avoid}.scroll{overflow:visible}.reliability{min-width:0}th,td{padding:10px 7px}summary{padding:10px}footer{margin-top:20px}}
|
|
169465
|
-
</style></head><body><main><header><div class="eyebrow"><span>Ancha / Incident evaluation</span><code>${escape9(summary.runId)}</code></div><h1 class="${invalid30 > 0 || ungraded ? "" : summary.verdict === "pass" ? "pass-text" : "fail-text"}">${verdict}</h1><div class="identity"><div>${pytest}<p>Agent <code>${escape9(summary.agent)}</code></p><p class="muted">Minimum pass rate ${pct2(summary.minPassRate)} \xB7 ${escape9(invalid30)} invalid trial(s) \xB7 ${escape9(skipped)} judge(s) skipped</p></div><div class="muted"><p>Completed <code>${escape9(summary.finishedAt)}</code></p><p>Started <code>${escape9(summary.startedAt)}</code></p></div></div></header>${comparison2}<section aria-labelledby="reliability-title"><h2 id="reliability-title">Scene reliability</h2><p class="section-intro">Each cell is one actual trial.
|
|
169628
|
+
</style></head><body><main><header><div class="eyebrow"><span>Ancha / Incident evaluation</span><code>${escape9(summary.runId)}</code></div><h1 class="${invalid30 > 0 || ungraded ? "" : summary.verdict === "pass" ? "pass-text" : "fail-text"}">${verdict}</h1><div class="identity"><div>${pytest}<p>Agent <code>${escape9(summary.agent)}</code></p><p class="muted">Minimum pass rate ${pct2(summary.minPassRate)} \xB7 ${escape9(invalid30)} invalid trial(s) \xB7 ${escape9(skipped)} judge(s) skipped</p></div><div class="muted"><p>Completed <code>${escape9(summary.finishedAt)}</code></p><p>Started <code>${escape9(summary.startedAt)}</code></p></div></div></header>${comparison2}<section aria-labelledby="reliability-title"><h2 id="reliability-title">Scene reliability</h2><p class="section-intro">Each cell is one actual trial. Invalid and skipped trials never count as passed; all requested trials remain in the denominator.</p><div class="legend"><span class="pass-text"><b>\u2713</b> Passed</span><span class="fail-text"><b>\xD7</b> Failed</span><span><b>!</b> Invalid harness</span><span><b>\u25C7</b> Skipped grading</span><span><b>?</b> Legacy validity unverified</span></div><div class="scroll"><table class="reliability"><thead><tr><th scope="col">Scene</th><th scope="col">Trial outcomes</th><th scope="col">Passed / requested</th><th scope="col">Pass all k</th><th scope="col">Mean real duration</th><th scope="col">Change</th></tr></thead><tbody>${rows33}</tbody></table></div></section><section aria-labelledby="evidence-title"><h2 id="evidence-title">Failures and evidence</h2><p class="section-intro">Expand a scene to inspect check outcomes, expected and actual results, trace excerpts, process output and coverage gaps.</p>${summary.scenes.map((scene2) => sceneEvidence(scene2, !!summary.pytest)).join("")}</section><footer>Local run evidence. Agent identity above describes its provenance; this report does not certify a live AI run. ${summary.pytest ? "Pytest outcomes grade each invocation; observed world checks are separate evidence." : summary.sceneFingerprints === void 0 ? "Legacy summary: scene fingerprints are unverified; comparison requires a fresh run." : "Scene fingerprints recorded; comparisons require matching scene content and criteria."}<details><summary>Scene fingerprints</summary>${pre(JSON.stringify(summary.sceneFingerprints ?? {}, null, 2))}</details></footer></main></body></html>`;
|
|
169466
169629
|
}
|
|
169467
169630
|
|
|
169468
169631
|
// backend/src/playgrounds/model.ts
|
|
@@ -170877,7 +171040,8 @@ function gradeAttempt(results) {
|
|
|
170877
171040
|
...r.error !== void 0 && { error: clip4(r.error, 600) },
|
|
170878
171041
|
required: r.required !== false
|
|
170879
171042
|
}));
|
|
170880
|
-
|
|
171043
|
+
const skipped = results.some((r) => r && r.required !== false && r.status === "skipped");
|
|
171044
|
+
return { outcome: skipped ? "skipped" : checks.every((c) => c.passed || !c.required) ? "passed" : "failed", checks: checks.map(({ required: _required, ...c }) => c) };
|
|
170881
171045
|
}
|
|
170882
171046
|
var keyName = /(?:api.?key|token|secret|password|authorization|cookie|credential)/i;
|
|
170883
171047
|
var obviousCredential = /\bsk-(?:or-v1-)?[a-zA-Z0-9_-]{16,}|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/;
|
|
@@ -170899,17 +171063,20 @@ function privateInput(value4, privateValues) {
|
|
|
170899
171063
|
if (obviousCredential.test(text24) || privateValues.some((secret) => secret.length >= 8 && text24.includes(secret))) throw new AnchaError("USAGE", "keep credentials in the agent runtime environment; do not put them in tasks or tool datasets");
|
|
170900
171064
|
}
|
|
170901
171065
|
function summarizeRun(run6) {
|
|
170902
|
-
const
|
|
170903
|
-
const
|
|
171066
|
+
const requested2 = run6.tasks.reduce((sum4, task2) => sum4 + task2.attempts, 0);
|
|
171067
|
+
const counts = countTrials(requested2, run6.attempts.map((attempt) => !isTerminal(attempt.status) ? "pending" : attempt.outcome ?? (attempt.status === "error" ? "invalid" : "skipped")));
|
|
171068
|
+
const { passed, invalid: invalid30 } = counts, failed = counts.valid - passed;
|
|
170904
171069
|
const graded = run6.tasks.some((task2) => task2.checks?.length);
|
|
170905
171070
|
return {
|
|
171071
|
+
verdictVersion: VERDICT_VERSION,
|
|
171072
|
+
counts,
|
|
170906
171073
|
graded,
|
|
170907
171074
|
attempts: run6.attempts.length,
|
|
170908
171075
|
passed,
|
|
170909
171076
|
failed,
|
|
170910
171077
|
invalid: invalid30,
|
|
170911
|
-
pass_rate:
|
|
170912
|
-
pass_all_k: graded &&
|
|
171078
|
+
pass_rate: graded && requested2 > 0 ? passed / requested2 : null,
|
|
171079
|
+
pass_all_k: graded && allTrialsPassed(counts)
|
|
170913
171080
|
};
|
|
170914
171081
|
}
|
|
170915
171082
|
var withSummary = (run6) => ({ ...run6, summary: summarizeRun(run6) });
|
|
@@ -196528,7 +196695,7 @@ async function executeRun(opts) {
|
|
|
196528
196695
|
const frozen = cases.map((item2) => {
|
|
196529
196696
|
const value4 = { id: item2.id, scenarioId: item2.scene.id, seed: seedOf(item2), compiledFingerprint: sceneFingerprint(item2.scene), identity: item2.identity ?? {} };
|
|
196530
196697
|
const record23 = { ...value4, fingerprint: sceneFingerprint(value4) };
|
|
196531
|
-
results.set(item2.id, { scene: item2.scene, trials: [], ...explicitCases && { case: record23 } });
|
|
196698
|
+
results.set(item2.id, { scene: item2.scene, trials: [], requestedTrials: trials, ...explicitCases && { case: record23 } });
|
|
196532
196699
|
return record23;
|
|
196533
196700
|
});
|
|
196534
196701
|
let finished = 0;
|
|
@@ -196697,6 +196864,18 @@ init_src();
|
|
|
196697
196864
|
import { readFile as readFile17 } from "node:fs/promises";
|
|
196698
196865
|
import { basename as basename9, resolve as resolve19 } from "node:path";
|
|
196699
196866
|
async function runOnCloud(ctx, serverUrl3, run6) {
|
|
196867
|
+
const issues = [];
|
|
196868
|
+
if (!executionSupports("managed", `agent.input.${run6.taskInput ?? "command"}`)) issues.push({ field: `agent.input.${run6.taskInput}` });
|
|
196869
|
+
for (const file3 of run6.files) {
|
|
196870
|
+
let doc;
|
|
196871
|
+
try {
|
|
196872
|
+
doc = (0, import_yaml7.parse)(await readFile17(resolve19(ctx.io.cwd, file3), "utf8"));
|
|
196873
|
+
} catch {
|
|
196874
|
+
throw new AnchaError("CONFIG_INVALID", `${file3}: cannot read a valid scene/test document`, { hint: "Check the file, then run locally or in CI." });
|
|
196875
|
+
}
|
|
196876
|
+
issues.push(...unsupportedCloudDocument(file3, doc));
|
|
196877
|
+
}
|
|
196878
|
+
rejectUnsupportedExecution(issues);
|
|
196700
196879
|
let server = serverUrl3;
|
|
196701
196880
|
try {
|
|
196702
196881
|
server = normalizeServerUrl(serverUrl3);
|
|
@@ -196780,6 +196959,14 @@ function validateTrialCounts(scene2) {
|
|
|
196780
196959
|
if (!Number.isFinite(scene2.passRate) || scene2.passRate < 0 || scene2.passRate > 1) throw new AnchaError("USAGE", `invalid pass rate for scene ${scene2.sceneId}`);
|
|
196781
196960
|
}
|
|
196782
196961
|
function assertComparableSummaries(current, baseline) {
|
|
196962
|
+
try {
|
|
196963
|
+
for (const scene2 of baseline.scenes) {
|
|
196964
|
+
const counts = verifiedCounts(baseline, scene2);
|
|
196965
|
+
if (counts.invalid || counts.skipped || counts.completed !== counts.requested) throw new Error("The baseline contains invalid harness, skipped or unfinished trials; rerun and save a fresh baseline.");
|
|
196966
|
+
}
|
|
196967
|
+
} catch (error64) {
|
|
196968
|
+
throw new AnchaError("USAGE", error64 instanceof Error ? error64.message : "Incompatible baseline counts", { hint: "Rerun the reference evaluation and save a fresh baseline with this CLI." });
|
|
196969
|
+
}
|
|
196783
196970
|
if (current.runId === baseline.runId) throw new AnchaError("USAGE", "a run cannot be compared with itself");
|
|
196784
196971
|
const ids2 = (s) => s.scenes.map((scene2) => scene2.sceneId).sort();
|
|
196785
196972
|
const currentIds = ids2(current), baselineIds = ids2(baseline);
|
|
@@ -196811,8 +196998,14 @@ function compareSummaries(current, baseline) {
|
|
|
196811
196998
|
const droppedChecks = [];
|
|
196812
196999
|
const scenes = current.scenes.map((scene2) => {
|
|
196813
197000
|
const beforeScene = baseline.scenes.find((s) => s.sceneId === scene2.sceneId);
|
|
197001
|
+
try {
|
|
197002
|
+
verifiedCounts(current, scene2);
|
|
197003
|
+
} catch (error64) {
|
|
197004
|
+
throw new AnchaError("USAGE", error64 instanceof Error ? error64.message : "Incompatible current counts");
|
|
197005
|
+
}
|
|
196814
197006
|
validateTrialCounts(scene2);
|
|
196815
|
-
const
|
|
197007
|
+
const beforeTrials = beforeScene.counts.requested, afterTrials = scene2.counts.requested;
|
|
197008
|
+
const { numerator, denominator } = rateChange(beforeScene.passed, beforeTrials, scene2.passed, afterTrials);
|
|
196816
197009
|
if (numerator < 0n) regressed = true;
|
|
196817
197010
|
const checks = [];
|
|
196818
197011
|
for (const [check4, after] of Object.entries(scene2.checks)) {
|
|
@@ -196828,7 +197021,7 @@ function compareSummaries(current, baseline) {
|
|
|
196828
197021
|
droppedChecks.push(delta2);
|
|
196829
197022
|
}
|
|
196830
197023
|
}
|
|
196831
|
-
return { sceneId: scene2.sceneId, before: beforeScene.passed /
|
|
197024
|
+
return { sceneId: scene2.sceneId, before: beforeScene.passed / beforeTrials, after: scene2.passed / afterTrials, delta: Number(numerator) / Number(denominator), beforeTrials, afterTrials, ...checks.length > 0 && { checks } };
|
|
196832
197025
|
});
|
|
196833
197026
|
return { baselineRunId: baseline.runId, regressed, droppedChecks, scenes };
|
|
196834
197027
|
}
|
|
@@ -196912,12 +197105,28 @@ async function interruptible(ctx, fn) {
|
|
|
196912
197105
|
}
|
|
196913
197106
|
}
|
|
196914
197107
|
function registerRun(program2, ctx) {
|
|
196915
|
-
program2.command("run").description("run an agent against scenes N times and summarize how often it passes (starts its own server unless one is configured)").argument("[scenes...]", "scene YAML files (default: the globs in scenes: of ancha.yaml)").option("--agent <cmd>", "shell command that runs the agent (default: agent.command in ancha.yaml)").option("--agent-url <url>", "endpoint URL (overrides agent.url; requires endpoint setup/start configuration)").option("-n, --trials <n>", "trials per scene (default: trials in ancha.yaml, else 5)").option("--parallel <n>", "trials running at once (default: parallel in ancha.yaml, else command 2 / endpoint 1)").option("--min-pass-rate <r>", "fraction of trials that must pass, 0 to 1 (default: min_pass_rate in ancha.yaml, else 1)").option("--seed <seed>", "seed for ids and randomness").option("--out <dir>", "where run directories go (default: .ancha/runs)").option("--strict", "exit 4 if the agent hit an endpoint Ancha does not implement").option("--detach", "continue in a private worker after this command exits; observe with status/wait").option("--compare <reference>", "compare against a completed run id or saved baseline; any per-scene decrease fails").option("--pass-env <name>", "give the agent this variable from this shell (repeatable); it otherwise gets only a base set (PATH, HOME, locale\u2026) plus Ancha's and the tools' variables", (name5, names3) => [...names3, name5], []).option("--inherit-env", "give the agent this shell's whole environment, including any real credentials (the behavior before 0.1.2)").option("--on <target>", "where the agent runs: local (a process on this computer), docker (a sealed container; needs agent.execution with an image in ancha.yaml) or cloud (
|
|
197108
|
+
program2.command("run").description("run an agent against scenes N times and summarize how often it passes (starts its own server unless one is configured)").argument("[scenes...]", "scene YAML files (default: the globs in scenes: of ancha.yaml)").option("--agent <cmd>", "shell command that runs the agent (default: agent.command in ancha.yaml)").option("--agent-url <url>", "endpoint URL (overrides agent.url; requires endpoint setup/start configuration)").option("-n, --trials <n>", "trials per scene (default: trials in ancha.yaml, else 5)").option("--parallel <n>", "trials running at once (default: parallel in ancha.yaml, else command 2 / endpoint 1)").option("--min-pass-rate <r>", "fraction of trials that must pass, 0 to 1 (default: min_pass_rate in ancha.yaml, else 1)").option("--seed <seed>", "seed for ids and randomness").option("--out <dir>", "where run directories go (default: .ancha/runs)").option("--strict", "exit 4 if the agent hit an endpoint Ancha does not implement").option("--detach", "continue in a private worker after this command exits; observe with status/wait").option("--compare <reference>", "compare against a completed run id or saved baseline; any per-scene decrease fails").option("--pass-env <name>", "give the agent this variable from this shell (repeatable); it otherwise gets only a base set (PATH, HOME, locale\u2026) plus Ancha's and the tools' variables", (name5, names3) => [...names3, name5], []).option("--inherit-env", "give the agent this shell's whole environment, including any real credentials (the behavior before 0.1.2)").option("--on <target>", "where the agent runs: local (a process on this computer), docker (a sealed container; needs agent.execution with an image in ancha.yaml) or cloud (scene/test import is currently unsupported; use local/CI or an explicit saved-world task via runs start). Default: what ancha.yaml says").option("--idempotency-key <key>", "retry safely: the same key and the same run definition return the original run instead of starting another").option("--upload", "send the finished run to your workspace, where the console shows it (also ANCHA_UPLOAD=1); a failed upload is a warning").option("--upload-required", "like --upload, but a failed upload fails the command").action(async (sceneArgs, opts, command) => {
|
|
196916
197109
|
const { cwd } = ctx.io;
|
|
196917
197110
|
if (opts.agent === void 0 && opts.agentUrl === void 0 && ctx.globals().config === void 0 && !await access4(resolve21(cwd, "ancha.yaml")).then(() => true, () => false)) {
|
|
196918
197111
|
throw new AnchaError("USAGE", "no ancha.yaml here", { hint: 'run `ancha init` in your agent\'s project, or pass --agent "<command>"' });
|
|
196919
197112
|
}
|
|
196920
197113
|
const config9 = await ctx.loadConfig();
|
|
197114
|
+
if (opts.on === "cloud") {
|
|
197115
|
+
const issues = command.options.flatMap((option3) => {
|
|
197116
|
+
const key3 = option3.attributeName();
|
|
197117
|
+
return command.getOptionValueSource(key3) === "cli" && !executionSupports("managed", option3.long ?? "") ? [{ field: option3.long ?? key3 }] : [];
|
|
197118
|
+
});
|
|
197119
|
+
const configFile = ctx.globals().config ?? "ancha.yaml";
|
|
197120
|
+
for (const key3 of ["env", "passEnv", "execution", "slackTransport"]) if (config9.agent?.[key3] !== void 0) {
|
|
197121
|
+
const field4 = `agent.${key3 === "passEnv" ? "pass_env" : key3 === "slackTransport" ? "slack_transport" : key3}`;
|
|
197122
|
+
if (!executionSupports("managed", field4)) issues.push({ field: `${configFile}: ${field4}` });
|
|
197123
|
+
}
|
|
197124
|
+
if (config9.judge !== void 0) issues.push({ field: `${configFile}: judge` });
|
|
197125
|
+
if (config9.min_pass_rate !== 1) issues.push({ field: `${configFile}: min_pass_rate` });
|
|
197126
|
+
const input3 = config9.agent?.input ?? "command";
|
|
197127
|
+
if (!executionSupports("managed", `agent.input.${input3}`)) issues.push({ field: `${configFile}: agent.input.${input3}` });
|
|
197128
|
+
rejectUnsupportedExecution(issues);
|
|
197129
|
+
}
|
|
196921
197130
|
const trials = opts.trials === void 0 ? config9.trials : positiveInt("--trials", opts.trials);
|
|
196922
197131
|
const uploading = opts.upload === true || opts.uploadRequired === true || ctx.io.env.ANCHA_UPLOAD === "1";
|
|
196923
197132
|
if (opts.on === "cloud" && uploading) throw new AnchaError("USAGE", "--on cloud runs already live in the workspace", { hint: "leave out --upload" });
|
|
@@ -196928,7 +197137,7 @@ function registerRun(program2, ctx) {
|
|
|
196928
197137
|
const agent2 = resolveRunAgent(config9, cwd, { ...opts.agent !== void 0 && { agent: opts.agent } }).agent;
|
|
196929
197138
|
if (agent2.mode === "endpoint") throw new AnchaError("USAGE", "--on cloud runs agents started by a command for now", { hint: "set agent.command in ancha.yaml, or use --on local" });
|
|
196930
197139
|
const files2 = sceneArgs.length > 0 ? sceneArgs : (await glob3(config9.scenes, { cwd, absolute: true, onlyFiles: true })).sort().map((path6) => relative7(cwd, path6));
|
|
196931
|
-
ctx.exitCode = await runOnCloud(ctx, choice5.url, { files: files2, name: basename10(cwd), command: agent2.command, taskInput: agent2.taskInput?.kind === "per_event" ? "
|
|
197140
|
+
ctx.exitCode = await runOnCloud(ctx, choice5.url, { files: files2, name: basename10(cwd), command: agent2.command, taskInput: agent2.taskInput?.kind === "per_event" ? "per_event" : "command", ...opts.trials !== void 0 && { attempts: trials }, ...opts.parallel !== void 0 && { concurrency: positiveInt("--parallel", opts.parallel) }, ...opts.idempotencyKey !== void 0 && { idempotencyKey: opts.idempotencyKey } });
|
|
196932
197141
|
return;
|
|
196933
197142
|
}
|
|
196934
197143
|
const resolved = resolveRunAgent(config9, cwd, { ...opts.agent !== void 0 && { agent: opts.agent }, ...opts.agentUrl !== void 0 && { agentUrl: opts.agentUrl }, ...opts.parallel !== void 0 && { parallel: positiveInt("--parallel", opts.parallel) } });
|
|
@@ -200793,17 +201002,19 @@ var CliRuns = class {
|
|
|
200793
201002
|
const summary = await this.summary(id12);
|
|
200794
201003
|
if (!summary) return void 0;
|
|
200795
201004
|
const recorded = await this.recordedScenes(id12);
|
|
200796
|
-
const tasks = summary.scenes.map((scene2) => ({ id: scene2.sceneId, title: summary.pytest?.nodeId ?? scene2.sceneId, prompt: opening2(recorded.get(scene2.sceneId)) }));
|
|
201005
|
+
const tasks = summary.scenes.map((scene2) => ({ id: scene2.sceneId, title: summary.pytest?.nodeId ?? scene2.sceneId, prompt: opening2(recorded.get(scene2.sceneId)), attempts: scene2.counts?.requested ?? scene2.trials }));
|
|
200797
201006
|
const attempts = [];
|
|
200798
201007
|
for (const scene2 of summary.scenes) for (const trial of scene2.trialsDetail) {
|
|
200799
201008
|
const excluded3 = trial.outcome === "skipped" || trial.outcome === "xfailed";
|
|
200800
|
-
const outcome4 = trial.valid === false ? "invalid" : excluded3 ?
|
|
201009
|
+
const outcome4 = trial.valid === false ? "invalid" : excluded3 ? "skipped" : trial.passed ? "passed" : "failed";
|
|
200801
201010
|
const attempt = { id: `${scene2.sceneId}.${trial.trial}`, taskId: scene2.sceneId, number: trial.trial, status: "completed", queuedAt: summary.startedAt, toolCalls: 0, ...outcome4 && { outcome: outcome4 }, ...summary.source === "pytest" && trial.outcome && { pytestOutcome: trial.outcome }, ...outcome4 === "invalid" && { invalidReason: "harness" }, ...Number.isFinite(trial.realMs) && { durationMs: trial.realMs } };
|
|
200802
201011
|
if (detail2) Object.assign(attempt, await this.attemptDetail(id12, scene2.sceneId, trial.trial));
|
|
200803
201012
|
attempts.push(attempt);
|
|
200804
201013
|
}
|
|
200805
201014
|
const world5 = recorded.get(summary.scenes[0]?.sceneId ?? "") ?? [...recorded.values()][0];
|
|
200806
201015
|
const graded = attempts.filter((a) => a.outcome === "passed" || a.outcome === "failed"), passed = graded.filter((a) => a.outcome === "passed").length;
|
|
201016
|
+
const counts = summary.verdictVersion === 2 && summary.scenes.every((scene2) => scene2.counts) ? summary.scenes.reduce((total, scene2) => Object.fromEntries(Object.keys(total).map((key3) => [key3, total[key3] + scene2.counts[key3]])), { requested: 0, completed: 0, valid: 0, passed: 0, invalid: 0, skipped: 0 }) : void 0;
|
|
201017
|
+
const requested2 = counts?.requested ?? attempts.length;
|
|
200807
201018
|
return {
|
|
200808
201019
|
schemaVersion: 1,
|
|
200809
201020
|
id: id12,
|
|
@@ -200821,7 +201032,7 @@ var CliRuns = class {
|
|
|
200821
201032
|
configuration: { preset: { title: String(world5?.title ?? ""), datasets: (Array.isArray(world5?.twins) ? world5.twins : []).map((tool) => ({ tool: String(tool) })) } },
|
|
200822
201033
|
tasks,
|
|
200823
201034
|
attempts,
|
|
200824
|
-
summary: { graded: summary.pytest?.graded ?? true, attempts: attempts.length, passed, failed: graded.length - passed, invalid: attempts.filter((a) => a.outcome === "invalid").length, pass_rate: graded
|
|
201035
|
+
summary: { ...counts && { verdictVersion: 2, counts }, graded: summary.pytest?.graded ?? true, attempts: attempts.length, passed, failed: graded.length - passed, invalid: attempts.filter((a) => a.outcome === "invalid").length, pass_rate: requested2 && (summary.pytest?.graded ?? true) ? passed / requested2 : null, pass_all_k: counts ? allTrialsPassed(counts) : false, ...summary.pytest && { excluded: summary.pytest.excluded } },
|
|
200825
201036
|
// Where the agent ran: in a container (`--on docker`), else wherever this reader's runs come from.
|
|
200826
201037
|
origin: { source: "cli", target: summary.target === "docker" ? "docker" : this.target, ...await this.files.origin?.(id12), ...summary.source === "pytest" && { source: "pytest", target: "local", ...summary.workspace && { workspace: summary.workspace } } }
|
|
200827
201038
|
};
|
|
@@ -201683,8 +201894,8 @@ async function startConsole(opts) {
|
|
|
201683
201894
|
throw new AnchaError("USAGE", error64.message);
|
|
201684
201895
|
}
|
|
201685
201896
|
const listed = await playgrounds.list(q.agentId), runs = await withQueue(listed.runs, q.agentId ? void 0 : listed.runs);
|
|
201686
|
-
const
|
|
201687
|
-
return send2(res, { ...listed, runs: include.full ?
|
|
201897
|
+
const all8 = include.cli && !q.agentId ? [...runs, ...await cliRuns.list()].sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt))) : runs;
|
|
201898
|
+
return send2(res, { ...listed, runs: include.full ? all8 : all8.map(listRun) });
|
|
201688
201899
|
}
|
|
201689
201900
|
return send2(res, await playgrounds.start(data5));
|
|
201690
201901
|
}
|
|
@@ -202330,11 +202541,11 @@ var __getOwnPropNames3 = Object.getOwnPropertyNames;
|
|
|
202330
202541
|
var __getProtoOf3 = Object.getPrototypeOf;
|
|
202331
202542
|
var __hasOwnProp3 = Object.prototype.hasOwnProperty;
|
|
202332
202543
|
var __commonJSMin2 = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
202333
|
-
var __exportAll2 = (
|
|
202544
|
+
var __exportAll2 = (all8, symbols) => {
|
|
202334
202545
|
let target5 = {};
|
|
202335
|
-
for (var name5 in
|
|
202546
|
+
for (var name5 in all8) {
|
|
202336
202547
|
__defProp3(target5, name5, {
|
|
202337
|
-
get:
|
|
202548
|
+
get: all8[name5],
|
|
202338
202549
|
enumerable: true
|
|
202339
202550
|
});
|
|
202340
202551
|
}
|
|
@@ -218929,20 +219140,20 @@ function startWorldServer(cwd, controlToken) {
|
|
|
218929
219140
|
async function recordWorld(cwd, envId, record23) {
|
|
218930
219141
|
await mkdir22(dir(cwd), { recursive: true });
|
|
218931
219142
|
const path6 = join47(dir(cwd), ENVS_FILE);
|
|
218932
|
-
const
|
|
218933
|
-
for (const [id12, entry3] of Object.entries(
|
|
218934
|
-
|
|
218935
|
-
await writePrivate(path6,
|
|
219143
|
+
const all8 = await readJson(path6) ?? {};
|
|
219144
|
+
for (const [id12, entry3] of Object.entries(all8)) if (Date.now() - Date.parse(entry3.createdAt) > 864e5) delete all8[id12];
|
|
219145
|
+
all8[envId] = record23;
|
|
219146
|
+
await writePrivate(path6, all8);
|
|
218936
219147
|
}
|
|
218937
219148
|
async function worldRecord(cwd, envId) {
|
|
218938
219149
|
return (await readJson(join47(dir(cwd), ENVS_FILE)))?.[envId];
|
|
218939
219150
|
}
|
|
218940
219151
|
async function forgetWorld(cwd, envId) {
|
|
218941
219152
|
const path6 = join47(dir(cwd), ENVS_FILE);
|
|
218942
|
-
const
|
|
218943
|
-
if (
|
|
218944
|
-
delete
|
|
218945
|
-
await writePrivate(path6,
|
|
219153
|
+
const all8 = await readJson(path6);
|
|
219154
|
+
if (all8?.[envId] === void 0) return;
|
|
219155
|
+
delete all8[envId];
|
|
219156
|
+
await writePrivate(path6, all8);
|
|
218946
219157
|
}
|
|
218947
219158
|
|
|
218948
219159
|
// packages/cli/src/commands/lifecycle.ts
|
|
@@ -219095,7 +219306,7 @@ function registerWorldLifecycle(world5, ctx) {
|
|
|
219095
219306
|
});
|
|
219096
219307
|
}
|
|
219097
219308
|
function registerCheck(program2, ctx) {
|
|
219098
|
-
program2.command("check").description("grade a live world from ancha world up: the same checks and exit codes as ancha run (1 when a required check fails)").requiredOption("--env <id>", "world id from ancha world up").option("--test <file>", "test or scene file whose checks to apply (default: the scene the world started from)").option("--scene <file>", "same as --test").option("--check <json>", "a check to apply instead, as one JSON object (repeatable); each is required", (value4,
|
|
219309
|
+
program2.command("check").description("grade a live world from ancha world up: the same checks and exit codes as ancha run (1 when a required check fails)").requiredOption("--env <id>", "world id from ancha world up").option("--test <file>", "test or scene file whose checks to apply (default: the scene the world started from)").option("--scene <file>", "same as --test").option("--check <json>", "a check to apply instead, as one JSON object (repeatable); each is required", (value4, all8) => [...all8, value4], []).action(async (opts) => {
|
|
219099
219310
|
if (opts.test !== void 0 && opts.scene !== void 0) throw new AnchaError("USAGE", "choose --test or --scene");
|
|
219100
219311
|
const inline = opts.check.map((text24) => {
|
|
219101
219312
|
let value4;
|
|
@@ -219340,6 +219551,7 @@ var schema2 = external_exports.strictObject({
|
|
|
219340
219551
|
finishedAt: instant,
|
|
219341
219552
|
outcome: external_exports.enum(["passed", "failed", "skipped", "xfailed", "xpassed", "error"]),
|
|
219342
219553
|
minPassRate: external_exports.number().min(0).max(1),
|
|
219554
|
+
requestedTrials: external_exports.number().int().min(1).max(1e4).optional(),
|
|
219343
219555
|
phases: external_exports.array(external_exports.strictObject({ when: external_exports.enum(["setup", "call", "teardown"]), outcome: external_exports.enum(["passed", "failed", "skipped"]), durationMs: external_exports.number().nonnegative(), errorCode: code2.optional() })).max(3),
|
|
219344
219556
|
attempts: external_exports.array(external_exports.strictObject({
|
|
219345
219557
|
number: external_exports.number().int().min(1).max(99999),
|
|
@@ -219376,7 +219588,7 @@ function validatePytestRecord(input2) {
|
|
|
219376
219588
|
const parsed3 = schema2.safeParse(input2);
|
|
219377
219589
|
if (!parsed3.success) throw invalid29();
|
|
219378
219590
|
const record23 = parsed3.data;
|
|
219379
|
-
if (Date.parse(record23.finishedAt) < Date.parse(record23.startedAt) || new Set(record23.phases.map((phase) => phase.when)).size !== record23.phases.length || new Set(record23.attempts.map((attempt) => attempt.number)).size !== record23.attempts.length || record23.attempts.some((attempt) => Date.parse(attempt.finishedAt) < Date.parse(attempt.startedAt) || Date.parse(attempt.startedAt) < Date.parse(record23.startedAt) || Date.parse(attempt.finishedAt) > Date.parse(record23.finishedAt))) throw invalid29();
|
|
219591
|
+
if (Date.parse(record23.finishedAt) < Date.parse(record23.startedAt) || new Set(record23.phases.map((phase) => phase.when)).size !== record23.phases.length || record23.requestedTrials !== void 0 && (record23.attempts.length > record23.requestedTrials || record23.attempts.some((attempt) => attempt.number > record23.requestedTrials)) || new Set(record23.attempts.map((attempt) => attempt.number)).size !== record23.attempts.length || record23.attempts.some((attempt) => Date.parse(attempt.finishedAt) < Date.parse(attempt.startedAt) || Date.parse(attempt.startedAt) < Date.parse(record23.startedAt) || Date.parse(attempt.finishedAt) > Date.parse(record23.finishedAt))) throw invalid29();
|
|
219380
219592
|
for (const attempt of record23.attempts) for (const world5 of attempt.worlds) if (world5.capture) {
|
|
219381
219593
|
const observation = world5.capture.observation;
|
|
219382
219594
|
if (!observation.state || typeof observation.state !== "object" || Array.isArray(observation.state) || !Array.isArray(observation.trace)) throw invalid29();
|
|
@@ -219401,12 +219613,14 @@ function artifacts(record23, runDir) {
|
|
|
219401
219613
|
const graded = attempts.filter((attempt) => !excluded2(attempt.outcome) && attempt.outcome !== "invalid");
|
|
219402
219614
|
const passed = graded.filter((attempt) => passing(attempt.outcome)).length;
|
|
219403
219615
|
const invalidCount = attempts.filter((attempt) => attempt.outcome === "invalid").length;
|
|
219616
|
+
const counts = countTrials(record23.requestedTrials ?? attempts.length, attempts.map((attempt) => attempt.outcome === "invalid" ? "invalid" : excluded2(attempt.outcome) ? "skipped" : passing(attempt.outcome) ? "passed" : "failed"));
|
|
219404
219617
|
const scene2 = {
|
|
219405
219618
|
sceneId,
|
|
219619
|
+
...record23.requestedTrials !== void 0 && { counts },
|
|
219406
219620
|
trials: attempts.length,
|
|
219407
219621
|
passed,
|
|
219408
|
-
passRate:
|
|
219409
|
-
passAllK:
|
|
219622
|
+
passRate: counts.requested ? passed / counts.requested : 0,
|
|
219623
|
+
passAllK: record23.requestedTrials !== void 0 && allTrialsPassed(counts),
|
|
219410
219624
|
checks: { pytest: { passed, total: graded.length, required: true } },
|
|
219411
219625
|
skippedJudges: 0,
|
|
219412
219626
|
warnings: [],
|
|
@@ -219457,12 +219671,13 @@ function artifacts(record23, runDir) {
|
|
|
219457
219671
|
const sceneDefinition = definitions3.find((item2) => item2.definition.scene)?.definition.scene;
|
|
219458
219672
|
const workspaces = [...new Set(record23.attempts.flatMap((attempt) => attempt.worlds.map((world5) => world5.capture?.workspace ?? world5.workspace).filter((workspace3) => workspace3 !== void 0)))];
|
|
219459
219673
|
const summary = {
|
|
219674
|
+
...record23.requestedTrials !== void 0 && { verdictVersion: VERDICT_VERSION },
|
|
219460
219675
|
runId: record23.runId,
|
|
219461
219676
|
startedAt: record23.startedAt,
|
|
219462
219677
|
finishedAt: record23.finishedAt,
|
|
219463
219678
|
agent: "pytest",
|
|
219464
219679
|
minPassRate: record23.minPassRate,
|
|
219465
|
-
verdict: invalidCount || record23.outcome === "failed" ||
|
|
219680
|
+
verdict: invalidCount || record23.outcome === "failed" || !meetsPassRate(counts, record23.minPassRate) ? "fail" : "pass",
|
|
219466
219681
|
scenes: [scene2],
|
|
219467
219682
|
source: "pytest",
|
|
219468
219683
|
target: "local",
|
|
@@ -219935,6 +220150,7 @@ var runFinished = {
|
|
|
219935
220150
|
type: "object",
|
|
219936
220151
|
required: ["runId", "startedAt", "finishedAt", "agent", "minPassRate", "verdict", "scenes"],
|
|
219937
220152
|
properties: {
|
|
220153
|
+
verdictVersion: { const: 2, description: "Requested-count verdict semantics. Absent on historical reports." },
|
|
219938
220154
|
runId: string7,
|
|
219939
220155
|
startedAt: string7,
|
|
219940
220156
|
finishedAt: string7,
|
|
@@ -219949,6 +220165,7 @@ var runFinished = {
|
|
|
219949
220165
|
passed: { type: "integer" },
|
|
219950
220166
|
passRate: { type: "number" },
|
|
219951
220167
|
passAllK: { type: "boolean" },
|
|
220168
|
+
counts: { type: "object", required: ["requested", "completed", "valid", "passed", "invalid", "skipped"], properties: Object.fromEntries(["requested", "completed", "valid", "passed", "invalid", "skipped"].map((key3) => [key3, { type: "integer", minimum: 0 }])) },
|
|
219952
220169
|
checks: { type: "object", additionalProperties: check3 },
|
|
219953
220170
|
failures: { type: "array", items: failure4 },
|
|
219954
220171
|
coverageGaps: { type: "array", items: coverageGap },
|
|
@@ -220062,9 +220279,9 @@ function schemas2() {
|
|
|
220062
220279
|
}
|
|
220063
220280
|
function registerSchema(program2, ctx) {
|
|
220064
220281
|
program2.command("schema").description("print JSON Schema for configuration, test and pytest recording files and JSON command outputs").argument("[kind]", "one of: ancha, world, test, scene, run_started, run_finished, explain, replay_finished, world_up, world_capture, world_record, pytest_record, check, error (default: all)").action((kind) => {
|
|
220065
|
-
const
|
|
220066
|
-
if (kind !== void 0 && !(kind in
|
|
220067
|
-
const result = kind === void 0 ? { version: SCHEMA_VERSION, kinds: Object.keys(
|
|
220282
|
+
const all8 = schemas2();
|
|
220283
|
+
if (kind !== void 0 && !(kind in all8)) throw new AnchaError("USAGE", `unknown schema: ${kind}`, { hint: `available: ${Object.keys(all8).join(", ")}` });
|
|
220284
|
+
const result = kind === void 0 ? { version: SCHEMA_VERSION, kinds: Object.keys(all8), schemas: all8 } : { version: SCHEMA_VERSION, kind, schema: all8[kind] };
|
|
220068
220285
|
ctx.out.result(result, () => JSON.stringify(result, null, 2));
|
|
220069
220286
|
});
|
|
220070
220287
|
}
|
|
@@ -220090,10 +220307,11 @@ function brief(run6, queue) {
|
|
|
220090
220307
|
};
|
|
220091
220308
|
}
|
|
220092
220309
|
var grade = (run6) => {
|
|
220093
|
-
const attempts = run6.summary?.graded ? `${run6.summary.passed} of ${run6.summary.
|
|
220310
|
+
const attempts = run6.summary?.graded ? `${run6.summary.passed} of ${run6.summary.counts?.requested ?? run6.summary.attempts} passed${run6.summary.invalid ? `, ${run6.summary.invalid} invalid` : ""}${run6.summary.counts?.skipped ? `, ${run6.summary.counts.skipped} skipped` : ""}` : "ungraded";
|
|
220094
220311
|
return run6.pytest ? `pytest ${run6.pytest.outcome}${run6.pytest.invalid ? " [invalid]" : ""}; ${attempts}` : attempts;
|
|
220095
220312
|
};
|
|
220096
|
-
|
|
220313
|
+
var ManagedTaskFields = TestFileSchema.pick({ id: true, title: true, start: true, checks: true, attempts: true, timeout: true }).extend({ id: TestFileSchema.shape.id.max(80) }).partial();
|
|
220314
|
+
async function testTask(ctx, file3, worldOverride) {
|
|
220097
220315
|
const path6 = resolve37(ctx.io.cwd, file3);
|
|
220098
220316
|
let doc;
|
|
220099
220317
|
try {
|
|
@@ -220102,6 +220320,11 @@ async function testTask(ctx, file3) {
|
|
|
220102
220320
|
throw new AnchaError("CONFIG_INVALID", `cannot read ${file3}: ${error64 instanceof Error ? error64.message.split("\n")[0] : String(error64)}`, { hint: "pass a test file (version 2) or a scene file" });
|
|
220103
220321
|
}
|
|
220104
220322
|
if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw new AnchaError("CONFIG_INVALID", `${file3} is not a test`, { hint: "pass a test file (version 2) or a scene file" });
|
|
220323
|
+
const unsupported34 = unsupportedCloudDocument(file3, doc, "managed-task");
|
|
220324
|
+
if (doc.world === void 0 && worldOverride === void 0) unsupported34.push({ file: file3, field: "world (explicit saved-world reference required)" });
|
|
220325
|
+
rejectUnsupportedExecution(unsupported34);
|
|
220326
|
+
const fields11 = ManagedTaskFields.safeParse({ id: doc.id, title: doc.title, start: doc.start, checks: doc.checks, attempts: doc.attempts, timeout: doc.timeout });
|
|
220327
|
+
if (!fields11.success) throw new AnchaError("CONFIG_INVALID", fields11.error.issues.map((issue5) => `${file3}: ${issue5.path.join(".")}: invalid managed task field`).join("\n"), { hint: "Use valid test field types; run locally or in CI for unsupported scene semantics." });
|
|
220105
220328
|
const v22 = doc.version === 2, start = v22 && typeof doc.start === "object" && doc.start !== null ? doc.start : {};
|
|
220106
220329
|
const prompt = v22 ? start.task : doc.task;
|
|
220107
220330
|
if (typeof prompt !== "string" || !prompt.trim()) {
|
|
@@ -220111,7 +220334,7 @@ async function testTask(ctx, file3) {
|
|
|
220111
220334
|
const pass = Array.isArray(doc.pass) ? new Set(doc.pass.map(String)) : void 0;
|
|
220112
220335
|
const checks = Array.isArray(doc.checks) ? doc.checks.filter((check4) => pass === void 0 || pass.has(String(check4.id))) : [];
|
|
220113
220336
|
const timeoutMs = v22 && typeof doc.timeout === "string" ? parseDuration(doc.timeout) : void 0;
|
|
220114
|
-
return { task: { id: id12, prompt, ...typeof doc.attempts === "number" && { attempts: doc.attempts }, ...timeoutMs !== void 0 && { timeoutMs }, ...checks.length > 0 && { checks } }, world: typeof doc.world === "string" ? doc.world : void 0 };
|
|
220337
|
+
return { task: { id: id12, prompt, ...typeof doc.title === "string" && { title: doc.title }, ...typeof doc.attempts === "number" && { attempts: doc.attempts }, ...timeoutMs !== void 0 && { timeoutMs }, ...checks.length > 0 && { checks } }, world: typeof doc.world === "string" ? doc.world : void 0 };
|
|
220115
220338
|
}
|
|
220116
220339
|
async function follow(ctx, first, get4, link6, wait) {
|
|
220117
220340
|
ctx.out.event({ event: "run_started", runId: first.id, attempts: first.attempts.length, ...link6 !== void 0 && { url: link6 } });
|
|
@@ -220132,7 +220355,11 @@ async function follow(ctx, first, get4, link6, wait) {
|
|
|
220132
220355
|
await new Promise((done) => setTimeout(done, 2e3));
|
|
220133
220356
|
run6 = await get4();
|
|
220134
220357
|
}
|
|
220135
|
-
|
|
220358
|
+
const invalid30 = (run6.summary?.invalid ?? 0) > 0 || run6.attempts.some((attempt) => attempt.outcome === "invalid");
|
|
220359
|
+
const counts = run6.summary?.counts;
|
|
220360
|
+
const incomplete = counts && counts.completed < counts.requested;
|
|
220361
|
+
const failed = (run6.summary?.failed ?? 0) > 0 || (counts?.skipped ?? 0) > 0 && run6.summary?.graded || incomplete;
|
|
220362
|
+
ctx.exitCode = run6.status === "error" || invalid30 ? 3 : run6.status === "stopped" ? 2 : failed ? 1 : 0;
|
|
220136
220363
|
ctx.out.event({ event: "run_finished", runId: run6.id, status: run6.status, ...run6.summary !== void 0 && { summary: run6.summary }, ...link6 !== void 0 && { url: link6 }, next: [`ancha explain ${run6.id} --json`] });
|
|
220137
220364
|
}
|
|
220138
220365
|
function registerRuns(program2, ctx) {
|
|
@@ -220146,8 +220373,8 @@ function registerRuns(program2, ctx) {
|
|
|
220146
220373
|
});
|
|
220147
220374
|
ctx.out.result(result, () => result.runs.length ? formatTable(result.runs.map((run6) => [run6.id, run6.name, run6.status, grade(run6), run6.queue ? `queued #${run6.queue.position}` : run6.createdAt])) : "No runs yet.");
|
|
220148
220375
|
});
|
|
220149
|
-
runs.command("start").description("run a test with a saved agent in fresh worlds; in a hosted workspace its console runs it, so a dropped connection doesn't stop it").requiredOption("--agent <id>", "saved agent (ancha agent list)").requiredOption("--test <file>", "
|
|
220150
|
-
const { task: task2, world: world5 } = await testTask(ctx, options3.test);
|
|
220376
|
+
runs.command("start").description("run a test with a saved agent in fresh worlds; in a hosted workspace its console runs it, so a dropped connection doesn't stop it").requiredOption("--agent <id>", "saved agent (ancha agent list)").requiredOption("--test <file>", "managed task file (version 2, start.task and an explicit saved world; unsupported scene fields are rejected)").option("--world <id-or-name>", "saved world to run in (default: the test's world)").option("-n, --attempts <n>", "attempts (default: the test's attempts, else 1)").option("--concurrency <n>", "attempts at once", "1").option("--idempotency-key <key>", "retry safely: the same key and definition return the original run").option("--commit <sha>", "the git commit of the code this run tests (ancha run --on cloud sets it; here, the folder's own)").option("--dirty", "that code had uncommitted changes").option("--no-wait", "return once the run is accepted (hosted workspace only)").action(async (options3) => {
|
|
220377
|
+
const { task: task2, world: world5 } = await testTask(ctx, options3.test, options3.world);
|
|
220151
220378
|
const attempts = options3.attempts !== void 0 ? positiveInt("--attempts", options3.attempts) : task2.attempts ?? 1;
|
|
220152
220379
|
const worldRef = options3.world ?? world5;
|
|
220153
220380
|
const consoleUrl = ctx.io.env.ANCHA_CONSOLE_URL;
|