@ancha-labs/cli 0.4.26 → 0.4.27

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/worker.mjs CHANGED
@@ -422,9 +422,9 @@ function floatSafeRemainder(val, step2) {
422
422
  return 0;
423
423
  return ratio - roundedRatio;
424
424
  }
425
- function defineLazy(object19, key4, getter2) {
425
+ function defineLazy(object20, key4, getter2) {
426
426
  let value4 = void 0;
427
- Object.defineProperty(object19, key4, {
427
+ Object.defineProperty(object20, key4, {
428
428
  get() {
429
429
  if (value4 === EVALUATING) {
430
430
  return void 0;
@@ -436,7 +436,7 @@ function defineLazy(object19, key4, getter2) {
436
436
  return value4;
437
437
  },
438
438
  set(v) {
439
- Object.defineProperty(object19, key4, {
439
+ Object.defineProperty(object20, key4, {
440
440
  value: v
441
441
  // configurable: true,
442
442
  });
@@ -16098,8 +16098,8 @@ function foldObjects(members4) {
16098
16098
  }
16099
16099
  const properties3 = {};
16100
16100
  const required4 = /* @__PURE__ */ new Set();
16101
- for (const object19 of objects) {
16102
- for (const key4 in object19.properties) {
16101
+ for (const object20 of objects) {
16102
+ for (const key4 in object20.properties) {
16103
16103
  if (Object.prototype.hasOwnProperty.call(properties3, key4))
16104
16104
  continue;
16105
16105
  const parts3 = [];
@@ -16113,18 +16113,18 @@ function foldObjects(members4) {
16113
16113
  const merged = parts3.length === 1 ? parts3[0] : foldObjects(parts3) ?? { allOf: parts3 };
16114
16114
  assignProp(properties3, key4, merged);
16115
16115
  }
16116
- for (const key4 of object19.required ?? [])
16116
+ for (const key4 of object20.required ?? [])
16117
16117
  required4.add(key4);
16118
16118
  }
16119
16119
  const folded = { type: "object", properties: properties3 };
16120
16120
  if (required4.size)
16121
16121
  folded.required = [...required4];
16122
- if (objects.every((object19) => object19.additionalProperties === false)) {
16122
+ if (objects.every((object20) => object20.additionalProperties === false)) {
16123
16123
  folded.additionalProperties = false;
16124
16124
  } else {
16125
16125
  const constraints = [];
16126
- for (const object19 of objects) {
16127
- const constraint = undeclaredConstraint(object19);
16126
+ for (const object20 of objects) {
16127
+ const constraint = undeclaredConstraint(object20);
16128
16128
  if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))
16129
16129
  constraints.push(constraint);
16130
16130
  }
@@ -22274,8 +22274,8 @@ var init_hubspot = __esm({
22274
22274
  const plural6 = { company: "companies", contact: "contacts", deal: "deals" };
22275
22275
  seed43.webhooks?.subscriptions.forEach((subscription2, index) => {
22276
22276
  const [type, property4] = subscription2.split(":");
22277
- const object19 = plural6[type.split(".")[0]];
22278
- if (property4 !== void 0 && !(property4 in hubspotPropertySchemas[object19].shape)) issue8(["webhooks", "subscriptions", index], `${property4} is not a ${object19.slice(0, -1)} property`);
22277
+ const object20 = plural6[type.split(".")[0]];
22278
+ if (property4 !== void 0 && !(property4 in hubspotPropertySchemas[object20].shape)) issue8(["webhooks", "subscriptions", index], `${property4} is not a ${object20.slice(0, -1)} property`);
22279
22279
  if (seed43.webhooks.subscriptions.indexOf(subscription2) !== index) issue8(["webhooks", "subscriptions", index], "duplicate subscription");
22280
22280
  });
22281
22281
  });
@@ -24734,7 +24734,7 @@ var init_notion = __esm({
24734
24734
 
24735
24735
  // packages/core/src/tools/attio.ts
24736
24736
  function attioSeedRecords(seed43) {
24737
- return ["people", "companies", "deals"].flatMap((object19) => seed43.records[object19].map((r2) => ({ collection: object19, id: r2.ref, label: String(r2.values.name ?? r2.ref) })));
24737
+ return ["people", "companies", "deals"].flatMap((object20) => seed43.records[object20].map((r2) => ({ collection: object20, id: r2.ref, label: String(r2.values.name ?? r2.ref) })));
24738
24738
  }
24739
24739
  var ATTIO_ATTRIBUTE_TYPES, EMAIL5, ref11, slug, when4, attribute, values, ATTIO_STANDARD_ATTRIBUTES, STANDARD_LOOKUPS, AttioSeedSchema, attioStarterSeed;
24740
24740
  var init_attio = __esm({
@@ -24832,9 +24832,9 @@ var init_attio = __esm({
24832
24832
  const members4 = new Set(seed43.members.map((m) => m.ref));
24833
24833
  if (!members4.has(seed43.agent)) issue8(["agent"], "agent must be the ref of a member");
24834
24834
  const recordObject = /* @__PURE__ */ new Map();
24835
- for (const object19 of ["people", "companies", "deals"]) seed43.records[object19].forEach((r2, i) => {
24836
- if (recordObject.has(r2.ref)) issue8(["records", object19, i, "ref"], "duplicate record ref");
24837
- recordObject.set(r2.ref, object19);
24835
+ for (const object20 of ["people", "companies", "deals"]) seed43.records[object20].forEach((r2, i) => {
24836
+ if (recordObject.has(r2.ref)) issue8(["records", object20, i, "ref"], "duplicate record ref");
24837
+ recordObject.set(r2.ref, object20);
24838
24838
  });
24839
24839
  const lists = /* @__PURE__ */ new Set();
24840
24840
  const emails = new Set(seed43.members.map((m) => m.email.toLowerCase()));
@@ -24855,9 +24855,9 @@ var init_attio = __esm({
24855
24855
  }
24856
24856
  }
24857
24857
  };
24858
- for (const object19 of ["people", "companies", "deals"]) {
24859
- const standard2 = { ...Object.fromEntries(ATTIO_STANDARD_ATTRIBUTES[object19].map((slug10) => [slug10, {}])), ...STANDARD_LOOKUPS[object19], ...object19 === "deals" && { stage: { options: seed43.deal_stages } } };
24860
- seed43.records[object19].forEach((r2, i) => named4(r2.values, seed43.attributes[object19] ?? [], standard2, ["records", object19, i, "values"]));
24858
+ for (const object20 of ["people", "companies", "deals"]) {
24859
+ const standard2 = { ...Object.fromEntries(ATTIO_STANDARD_ATTRIBUTES[object20].map((slug10) => [slug10, {}])), ...STANDARD_LOOKUPS[object20], ...object20 === "deals" && { stage: { options: seed43.deal_stages } } };
24860
+ seed43.records[object20].forEach((r2, i) => named4(r2.values, seed43.attributes[object20] ?? [], standard2, ["records", object20, i, "values"]));
24861
24861
  }
24862
24862
  seed43.lists.forEach((l, i) => {
24863
24863
  if (lists.has(l.api_slug)) issue8(["lists", i, "api_slug"], "duplicate list slug");
@@ -32140,7 +32140,7 @@ function validateRefs(scene2) {
32140
32140
  for (const field6 of ["charge", "payment_intent"]) localUse(`stripe.refunds.${field6}`, c.state["stripe.refunds"][field6], field6, stripeRefs(field6));
32141
32141
  }
32142
32142
  if ("stripe.balance" in c.state) localUse("stripe.balance.customer", c.state["stripe.balance"].customer, "customer", stripeRefs("customer"));
32143
- if ("stripe.unchanged" in c.state) c.state["stripe.unchanged"].objects.forEach((object19, n2) => localUse(`stripe.unchanged.objects[${n2}].id`, object19.id, object19.type, stripeRefs(object19.type)));
32143
+ if ("stripe.unchanged" in c.state) c.state["stripe.unchanged"].objects.forEach((object20, n2) => localUse(`stripe.unchanged.objects[${n2}].id`, object20.id, object20.type, stripeRefs(object20.type)));
32144
32144
  if ("okta.user" in c.state && c.state["okta.user"].startsWith("$")) use(`${p2}.okta.user`, c.state["okta.user"], "user", "okta");
32145
32145
  });
32146
32146
  const selector2 = (value4, p2) => {
@@ -42342,6 +42342,67 @@ var init_function_tool_observation = __esm({
42342
42342
  }
42343
42343
  });
42344
42344
 
42345
+ // packages/core/src/function-tool-view.ts
42346
+ function functionCallFields(entry2) {
42347
+ const response5 = object3(entry2.response);
42348
+ return { args: object3(entry2.request).args, result: response5.result, error_type: response5.error_type ?? object3(response5.error).type };
42349
+ }
42350
+ function projectFunctionTools(trace, state3, names5 = []) {
42351
+ const observation = functionToolObservationSchema.safeParse(object3(object3(state3).tools).observation);
42352
+ const calls2 = [], seen = /* @__PURE__ */ new Set();
42353
+ for (const entry2 of projectToolCalls(trace)) {
42354
+ if (entry2.source !== "agent" || entry2.service !== "tools" || !entry2.path.startsWith("/tools/")) continue;
42355
+ const response5 = object3(entry2.response), fields11 = functionCallFields(entry2);
42356
+ const call_id = typeof response5.call_id === "string" ? response5.call_id : void 0;
42357
+ if (call_id && seen.has(call_id)) continue;
42358
+ if (call_id) seen.add(call_id);
42359
+ let tool = entry2.path.slice("/tools/".length);
42360
+ try {
42361
+ tool = decodeURIComponent(tool);
42362
+ } catch {
42363
+ }
42364
+ const unconfirmed = response5.execution_status === "unknown" || response5.execution_status === "pending";
42365
+ const failed = response5.execution_status === "failed" || response5.error != null || response5.source === "failed" || (entry2.status ?? 0) >= 400 || entry2.gap || entry2.issue;
42366
+ const complete = response5.execution_status === "succeeded" || Object.hasOwn(response5, "result") || response5.result_kind === "undefined";
42367
+ const outcome3 = unconfirmed ? response5.execution_status === "pending" || observation.success && !observation.data.complete ? "pending" : "unknown" : failed ? "failed" : complete ? "succeeded" : "unknown";
42368
+ calls2.push({
42369
+ tool,
42370
+ ...call_id && { call_id },
42371
+ seq: entry2.seq,
42372
+ evidence: [entry2.seq, ...entry2.completion ? [entry2.completion.seq] : []],
42373
+ ...fields11.args !== void 0 && { args: fields11.args },
42374
+ ...Object.hasOwn(response5, "result") && { result: fields11.result },
42375
+ ...response5.error !== void 0 && { error: response5.error },
42376
+ ...typeof fields11.error_type === "string" && { error_type: fields11.error_type },
42377
+ outcome: outcome3,
42378
+ source: typeof response5.source === "string" ? response5.source : "unknown",
42379
+ ...entry2.completion && { completion: entry2.completion }
42380
+ });
42381
+ }
42382
+ const known2 = observation.success ? observation.data : void 0;
42383
+ return { calls: calls2, tools: [.../* @__PURE__ */ new Set([...names5, ...known2?.required ?? [], ...known2?.registered ?? [], ...known2?.tools.map((t) => t.name) ?? [], ...calls2.map((c) => c.tool)])].sort().map((name5) => {
42384
+ const own2 = calls2.filter((c) => c.tool === name5), captured = known2?.tools.find((t) => t.name === name5);
42385
+ return {
42386
+ name: name5,
42387
+ registered: known2 ? known2.registered.includes(name5) : null,
42388
+ protocol_version: known2?.protocol_version ?? null,
42389
+ complete: known2?.complete ?? null,
42390
+ called: own2.length || captured?.called || (known2 ? 0 : null),
42391
+ completed: own2.length ? own2.filter((c) => c.outcome === "succeeded" || c.outcome === "failed").length : captured?.completed ?? (known2 ? 0 : null),
42392
+ pending: own2.length ? own2.filter((c) => c.outcome === "pending" || c.outcome === "unknown").length : captured?.pending ?? (known2 ? 0 : null)
42393
+ };
42394
+ }) };
42395
+ }
42396
+ var object3;
42397
+ var init_function_tool_view = __esm({
42398
+ "packages/core/src/function-tool-view.ts"() {
42399
+ "use strict";
42400
+ init_tool_call_trace();
42401
+ init_function_tool_observation();
42402
+ object3 = (value4) => value4 !== null && typeof value4 === "object" && !Array.isArray(value4) ? value4 : {};
42403
+ }
42404
+ });
42405
+
42345
42406
  // packages/core/src/index.ts
42346
42407
  var init_src = __esm({
42347
42408
  "packages/core/src/index.ts"() {
@@ -42419,6 +42480,7 @@ var init_src = __esm({
42419
42480
  init_tool_call_trace();
42420
42481
  init_tool_completion();
42421
42482
  init_function_tool_observation();
42483
+ init_function_tool_view();
42422
42484
  }
42423
42485
  });
42424
42486
 
@@ -42427,19 +42489,19 @@ function business(entry2) {
42427
42489
  if (entry2.source !== "agent" || isAgentAnswer(entry2)) return false;
42428
42490
  if (/(?:^|\/)(?:health|healthz|ready|readiness|oauth2?|authorize|token|metadata-catalog)(?:\/|$)/i.test(entry2.path)) return false;
42429
42491
  if (entry2.service === "slack" && /\/(?:auth|api)\.test$/.test(entry2.path)) return false;
42430
- if (entry2.path.includes("/mcp")) return object3(entry2.request).method === "tools/call";
42492
+ if (entry2.path.includes("/mcp")) return object4(entry2.request).method === "tools/call";
42431
42493
  return true;
42432
42494
  }
42433
42495
  function successful(entry2) {
42434
- const response5 = object3(entry2.response);
42435
- return !entry2.gap && !entry2.issue && entry2.status !== void 0 && entry2.status >= 200 && entry2.status < 300 && response5.ok !== false && !response5.error && !object3(response5.result).isError && !["unknown", "pending", "failed"].includes(String(response5.execution_status));
42496
+ const response5 = object4(entry2.response);
42497
+ return !entry2.gap && !entry2.issue && entry2.status !== void 0 && entry2.status >= 200 && entry2.status < 300 && response5.ok !== false && !response5.error && !object4(response5.result).isError && !["unknown", "pending", "failed"].includes(String(response5.execution_status));
42436
42498
  }
42437
42499
  function attemptToolDiagnostics(scene2, trial) {
42438
42500
  const entries3 = projectToolCalls(trial.trace).filter(business);
42439
42501
  const tools = [.../* @__PURE__ */ new Set([...scene2.twins ?? [], ...entries3.map((e) => e.service).filter((s2) => typeof s2 === "string" && s2 !== "" && s2 !== "agent" && s2 !== "world")])];
42440
42502
  const toolCalls = tools.map((tool) => {
42441
42503
  const calls2 = entries3.filter((e) => e.service === tool);
42442
- const writes3 = tool === "netsuite" ? calls2.filter((e) => successful(e) && (/\/services\/rest\/record\/v1\//.test(e.path) && ["POST", "PATCH", "PUT", "DELETE"].includes(e.method) || e.path.includes("/mcp") && NETSUITE_WRITES.has(String(object3(object3(e.request).params).name)))).length : void 0;
42504
+ const writes3 = tool === "netsuite" ? calls2.filter((e) => successful(e) && (/\/services\/rest\/record\/v1\//.test(e.path) && ["POST", "PATCH", "PUT", "DELETE"].includes(e.method) || e.path.includes("/mcp") && NETSUITE_WRITES.has(String(object4(object4(e.request).params).name)))).length : void 0;
42443
42505
  return { tool, calls: calls2.length, successful: calls2.filter(successful).length, ...writes3 !== void 0 && { writes: writes3 } };
42444
42506
  });
42445
42507
  const failed = trial.checks.filter((c) => c.required && !c.passed && c.status !== "skipped" && !c.error);
@@ -42463,7 +42525,7 @@ function toolDiagnosticLines(attempt) {
42463
42525
  ...(attempt.unreachedChecks?.length ?? 0) > 0 ? [`business checks not reached: ${attempt.unreachedChecks.join(", ")}`] : []
42464
42526
  ];
42465
42527
  }
42466
- var count2, ToolDiagnosisSchema, AttemptToolDiagnosticsSchema, toolAccessFix, toolTitle, NETSUITE_WRITES, object3;
42528
+ var count2, ToolDiagnosisSchema, AttemptToolDiagnosticsSchema, toolAccessFix, toolTitle, NETSUITE_WRITES, object4;
42467
42529
  var init_attempt_tool_diagnostics = __esm({
42468
42530
  "backend/src/attempt-tool-diagnostics.ts"() {
42469
42531
  "use strict";
@@ -42480,7 +42542,7 @@ var init_attempt_tool_diagnostics = __esm({
42480
42542
  toolAccessFix = (tool) => `configure the native SDK using ancha connect ${tool}; health and process exit do not prove agent access`;
42481
42543
  toolTitle = (tool) => TOOL_DESCRIPTORS.find((t) => t.name === tool)?.title ?? tool;
42482
42544
  NETSUITE_WRITES = /* @__PURE__ */ new Set(["ns_createRecord", "ns_transformRecord", "ns_updateRecord", "ns_executeRecordAction", "ns_attachFile", "ns_detachFile"]);
42483
- object3 = (value4) => value4 !== null && typeof value4 === "object" ? value4 : {};
42545
+ object4 = (value4) => value4 !== null && typeof value4 === "object" ? value4 : {};
42484
42546
  }
42485
42547
  });
42486
42548
 
@@ -42506,22 +42568,25 @@ var init_scenes = __esm({
42506
42568
  });
42507
42569
 
42508
42570
  // backend/src/actions.ts
42571
+ import { readFile } from "node:fs/promises";
42572
+ import { join } from "node:path";
42509
42573
  function actionsOf(scene2, trace) {
42510
42574
  const writes3 = writeTools(scene2);
42511
- return projectToolCalls(trace).flatMap((entry2) => {
42512
- if (entry2.service !== "tools" || entry2.source !== "agent" || !entry2.path.startsWith("/tools/")) return [];
42513
- const tool = decodeURIComponent(entry2.path.slice("/tools/".length));
42514
- if (!writes3.has(tool)) return [];
42515
- const response5 = entry2.response ?? {};
42516
- return [{ tool, args: entry2.request?.args ?? {}, source: typeof response5.source === "string" ? response5.source : "unknown", ...response5.execution_status && { execution_status: response5.execution_status }, ...typeof response5.error === "string" && { error: response5.error } }];
42517
- });
42575
+ const entries3 = new Map(projectToolCalls(trace).map((e) => [e.seq, e]));
42576
+ return projectFunctionTools(trace).calls.filter((call2) => writes3.has(call2.tool)).map((call2) => ({
42577
+ tool: call2.tool,
42578
+ args: call2.args ?? {},
42579
+ source: call2.source,
42580
+ functionCall: call2,
42581
+ ...entries3.get(call2.seq)?.response?.execution_status && { execution_status: entries3.get(call2.seq).response.execution_status },
42582
+ ...typeof call2.error === "string" && { error: call2.error }
42583
+ }));
42518
42584
  }
42519
42585
  function answersOf(trace) {
42520
42586
  const answers = {};
42521
- for (const entry2 of projectToolCalls(trace)) {
42522
- if (entry2.service !== "tools" || entry2.source !== "agent" || !entry2.path.startsWith("/tools/")) continue;
42523
- const source = entry2.response?.source;
42524
- if (typeof source === "string") answers[source] = (answers[source] ?? 0) + 1;
42587
+ const sourced = new Set(projectToolCalls(trace).filter((entry2) => typeof entry2.response?.source === "string").map((entry2) => entry2.seq));
42588
+ for (const call2 of projectFunctionTools(trace).calls) {
42589
+ if (sourced.has(call2.seq)) answers[call2.source] = (answers[call2.source] ?? 0) + 1;
42525
42590
  }
42526
42591
  return answers;
42527
42592
  }
@@ -42564,6 +42629,10 @@ function actionLabel(action) {
42564
42629
  const args = canonicalJson(action.args);
42565
42630
  return `${action.tool} ${args.length > 120 ? `${args.slice(0, 117)}...` : args}`;
42566
42631
  }
42632
+ async function savedFunctionTools(dir, trace, names5 = []) {
42633
+ const state3 = await readFile(join(dir, "state.json"), "utf8").then((text25) => JSON.parse(text25)).catch(() => void 0);
42634
+ return projectFunctionTools(trace, state3, names5);
42635
+ }
42567
42636
  var writeTools, keyOf;
42568
42637
  var init_actions = __esm({
42569
42638
  "backend/src/actions.ts"() {
@@ -42796,11 +42865,11 @@ var init_config = __esm({
42796
42865
 
42797
42866
  // backend/src/agent-input.ts
42798
42867
  import { rename, writeFile } from "node:fs/promises";
42799
- import { join } from "node:path";
42868
+ import { join as join2 } from "node:path";
42800
42869
  function sceneTaskInput(scene2, configured) {
42801
42870
  return scene2.agent_input ? { kind: scene2.agent_input } : configured;
42802
42871
  }
42803
- function object4(value4, fields11) {
42872
+ function object5(value4, fields11) {
42804
42873
  if (!value4 || typeof value4 !== "object" || Array.isArray(value4) || Object.keys(value4).some((key4) => !fields11.includes(key4))) throw new AnchaError("USAGE", "invalid task input fields");
42805
42874
  }
42806
42875
  function path2(value4) {
@@ -42810,7 +42879,7 @@ function field2(value4) {
42810
42879
  if (typeof value4 !== "string" || !/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(value4) || ["constructor", "prototype"].includes(value4)) throw new AnchaError("USAGE", "HTTP task fields must be simple JSON field names");
42811
42880
  }
42812
42881
  function parseTaskInput(raw3) {
42813
- object4(raw3, ["kind", "path", "readyPath", "messageField", "responseField", "conversation", "startupTimeoutMs", "responseTimeoutMs"]);
42882
+ object5(raw3, ["kind", "path", "readyPath", "messageField", "responseField", "conversation", "startupTimeoutMs", "responseTimeoutMs"]);
42814
42883
  if (raw3.kind === "command" || raw3.kind === "events" || raw3.kind === "per_event" || raw3.kind === "stdin") {
42815
42884
  if (Object.keys(raw3).length !== 1) throw new AnchaError("USAGE", "HTTP settings require the HTTP task input method");
42816
42885
  return { kind: raw3.kind };
@@ -42821,7 +42890,7 @@ function parseTaskInput(raw3) {
42821
42890
  field2(raw3.messageField);
42822
42891
  if (raw3.responseField !== void 0) field2(raw3.responseField);
42823
42892
  if (raw3.conversation !== void 0) {
42824
- object4(raw3.conversation, ["path", "idField", "body"]);
42893
+ object5(raw3.conversation, ["path", "idField", "body"]);
42825
42894
  path2(raw3.conversation.path);
42826
42895
  field2(raw3.conversation.idField);
42827
42896
  if (raw3.conversation.idField === raw3.messageField) throw new AnchaError("USAGE", "conversation and message fields must differ");
@@ -42845,9 +42914,9 @@ function parseTaskInput(raw3) {
42845
42914
  return structuredClone(raw3);
42846
42915
  }
42847
42916
  async function writeTaskDelivery(dir, value4) {
42848
- const temporary = join(dir, ".task-input.tmp");
42917
+ const temporary = join2(dir, ".task-input.tmp");
42849
42918
  await writeFile(temporary, JSON.stringify(value4) + "\n", { mode: 384 });
42850
- await rename(temporary, join(dir, "task-input.json"));
42919
+ await rename(temporary, join2(dir, "task-input.json"));
42851
42920
  }
42852
42921
  function availableTaskDelivery(input5) {
42853
42922
  return {
@@ -43713,8 +43782,8 @@ var init_agent_fix = __esm({
43713
43782
  });
43714
43783
 
43715
43784
  // backend/src/report.ts
43716
- import { readFile, writeFile as writeFile2 } from "node:fs/promises";
43717
- import { basename, dirname, join as join2, relative as relative2, resolve } from "node:path";
43785
+ import { readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
43786
+ import { basename, dirname, join as join3, relative as relative2, resolve } from "node:path";
43718
43787
  function okFalseError(response5) {
43719
43788
  if (typeof response5 !== "object" || response5 === null || response5.ok !== false) return void 0;
43720
43789
  const error64 = response5.error;
@@ -43724,6 +43793,7 @@ function excerptOf(entry2) {
43724
43793
  const response5 = entry2.response;
43725
43794
  const error64 = entry2.service === "tools" && typeof response5?.error === "string" ? response5.error : okFalseError(entry2.response);
43726
43795
  return {
43796
+ ...projectFunctionTools([entry2]).calls[0] && { functionCall: projectFunctionTools([entry2]).calls[0] },
43727
43797
  seq: entry2.seq,
43728
43798
  source: entry2.source,
43729
43799
  method: entry2.method,
@@ -43763,7 +43833,7 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
43763
43833
  }
43764
43834
  const exit = t.exit === "invalid" && t.originalExit === "spawn_failed" ? "spawn_failed" : t.exit;
43765
43835
  if (!t.passed && exit !== "invalid" && !exitedCleanly({ exit, exitCode: t.exitCode }) && agentIssues.length < MAX_FAILURES_PER_SCENE) {
43766
- agentIssues.push({ sceneId, trial: t.trial, exit, exitCode: t.exitCode, realMs: t.realMs, log: join2(t.dir, "agent.log"), logTail: t.logTail, ...t.invocations !== void 0 && { invocations: t.invocations } });
43836
+ agentIssues.push({ sceneId, trial: t.trial, exit, exitCode: t.exitCode, realMs: t.realMs, log: join3(t.dir, "agent.log"), logTail: t.logTail, ...t.invocations !== void 0 && { invocations: t.invocations } });
43767
43837
  }
43768
43838
  const valid = trialValid(t);
43769
43839
  for (const c of t.checks) {
@@ -43790,7 +43860,9 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
43790
43860
  });
43791
43861
  }
43792
43862
  }
43863
+ const logicalSeqs = new Set(projectFunctionTools(t.trace).calls.map((c) => c.seq));
43793
43864
  for (const e of projectToolCalls(t.trace)) {
43865
+ if (e.source === "agent" && e.service === "tools" && e.path.startsWith("/tools/") && !logicalSeqs.has(e.seq)) continue;
43794
43866
  if (e.source === "agent" && !isAgentAnswer(e)) agentCalls2++;
43795
43867
  if (e.gap === true) {
43796
43868
  const key4 = JSON.stringify([e.service, e.method, e.path]);
@@ -43835,7 +43907,11 @@ function summarize(run4, agent, minPassRate, options4 = {}) {
43835
43907
  const summary = summarizeScene(sceneId, value4.trials, value4.requestedTrials);
43836
43908
  return {
43837
43909
  ...summary,
43838
- trialsDetail: summary.trialsDetail.map((detail3, i) => ({ ...detail3, ...attemptToolDiagnostics(value4.scene, value4.trials[i]) })),
43910
+ failures: summary.failures.map((f2) => ({ ...f2, ...value4.scene.checks?.some((c) => c.id === f2.check && "tool_call" in c) && { kind: "tool_call" } })),
43911
+ trialsDetail: summary.trialsDetail.map((detail3, i) => {
43912
+ const functionTools = value4.trials[i].functionTools ?? projectFunctionTools(value4.trials[i].trace, void 0, Object.keys(value4.scene.tools ?? {}));
43913
+ return { ...detail3, ...attemptToolDiagnostics(value4.scene, value4.trials[i]), ...functionTools.tools.length && { functionTools } };
43914
+ }),
43839
43915
  ...value4.case && { scenarioId: value4.scene.id, case: value4.case }
43840
43916
  };
43841
43917
  });
@@ -43953,9 +44029,9 @@ function neverRanNextLine(n2, retry) {
43953
44029
  return `next: ${n2.fix === void 0 ? "fix what its log says" : "make the fix above"}, then ${retry.join(", then ")}`;
43954
44030
  }
43955
44031
  async function writeSummary(run4, summary) {
43956
- await writeFile2(join2(run4.dir, "summary.json"), `${JSON.stringify(summary, null, 2)}
44032
+ await writeFile2(join3(run4.dir, "summary.json"), `${JSON.stringify(summary, null, 2)}
43957
44033
  `);
43958
- await writeFile2(join2(dirname(run4.dir), "latest"), `${run4.runId}
44034
+ await writeFile2(join3(dirname(run4.dir), "latest"), `${run4.runId}
43959
44035
  `);
43960
44036
  }
43961
44037
  function formatRateDelta(value4) {
@@ -44122,8 +44198,8 @@ var init_run_store = __esm({
44122
44198
 
44123
44199
  // backend/src/runner/run-state.ts
44124
44200
  import { randomBytes } from "node:crypto";
44125
- import { mkdir, readFile as readFile2, rename as rename2, stat, writeFile as writeFile3 } from "node:fs/promises";
44126
- import { join as join3 } from "node:path";
44201
+ import { mkdir, readFile as readFile3, rename as rename2, stat, writeFile as writeFile3 } from "node:fs/promises";
44202
+ import { join as join4 } from "node:path";
44127
44203
  function validateRunId(runId) {
44128
44204
  if (runId.length > 128 || !/^run_[A-Za-z0-9_-]+$/.test(runId)) throw new AnchaError("USAGE", "invalid run id", { hint: "use the run id returned by run" });
44129
44205
  }
@@ -44173,7 +44249,7 @@ var init_run_state = __esm({
44173
44249
  "use strict";
44174
44250
  init_src();
44175
44251
  init_run_store();
44176
- pathOf2 = (outDir, runId) => join3(outDir, ".status", `${runId}.json`);
44252
+ pathOf2 = (outDir, runId) => join4(outDir, ".status", `${runId}.json`);
44177
44253
  }
44178
44254
  });
44179
44255
 
@@ -62649,8 +62725,8 @@ var init_context = __esm({
62649
62725
  * })
62650
62726
  * ```
62651
62727
  */
62652
- json = (object19, arg, headers) => {
62653
- return this.#newResponse(JSON.stringify(object19), arg, setDefaultContentType("application/json", headers));
62728
+ json = (object20, arg, headers) => {
62729
+ return this.#newResponse(JSON.stringify(object20), arg, setDefaultContentType("application/json", headers));
62654
62730
  };
62655
62731
  html = (html2, arg, headers) => {
62656
62732
  const res = (html3) => this.#newResponse(html3, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
@@ -64139,11 +64215,11 @@ function argumentError(schema, args) {
64139
64215
  if (errors2.every((error64) => error64 !== void 0)) return errors2[0];
64140
64216
  }
64141
64217
  if (value4 !== null && typeof value4 === "object" && !Array.isArray(value4)) {
64142
- const object19 = value4;
64143
- for (const name5 of rule.required ?? []) if (!Object.hasOwn(object19, name5)) return `Missing required argument: ${[...path6, name5].join(".")}`;
64218
+ const object20 = value4;
64219
+ for (const name5 of rule.required ?? []) if (!Object.hasOwn(object20, name5)) return `Missing required argument: ${[...path6, name5].join(".")}`;
64144
64220
  const properties3 = rule.properties ?? {};
64145
64221
  const patterns = Object.entries(rule.patternProperties ?? {}).map(([pattern, child2]) => ({ pattern: new RegExp(pattern), child: child2 }));
64146
- for (const [name5, child2] of Object.entries(object19)) {
64222
+ for (const [name5, child2] of Object.entries(object20)) {
64147
64223
  const children3 = patterns.filter((p2) => p2.pattern.test(name5)).map((p2) => p2.child);
64148
64224
  if (Object.hasOwn(properties3, name5)) children3.unshift(properties3[name5]);
64149
64225
  if (!children3.length) {
@@ -66428,13 +66504,13 @@ var require_inspect = __commonJS({
66428
66504
  function isJSONable(value4) {
66429
66505
  return typeof value4.toJSON === "function";
66430
66506
  }
66431
- function formatObject(object19, seenValues) {
66432
- const entries3 = Object.entries(object19);
66507
+ function formatObject(object20, seenValues) {
66508
+ const entries3 = Object.entries(object20);
66433
66509
  if (entries3.length === 0) {
66434
66510
  return "{}";
66435
66511
  }
66436
66512
  if (seenValues.length > MAX_RECURSIVE_DEPTH) {
66437
- return "[" + getObjectTag(object19) + "]";
66513
+ return "[" + getObjectTag(object20) + "]";
66438
66514
  }
66439
66515
  const properties3 = entries3.map(
66440
66516
  ([key4, value4]) => key4 + ": " + formatValue(value4, seenValues)
@@ -66461,10 +66537,10 @@ var require_inspect = __commonJS({
66461
66537
  }
66462
66538
  return "[" + items.join(", ") + "]";
66463
66539
  }
66464
- function getObjectTag(object19) {
66465
- const tag3 = Object.prototype.toString.call(object19).replace(/^\[object /, "").replace(/]$/, "");
66466
- if (tag3 === "Object" && typeof object19.constructor === "function") {
66467
- const name5 = object19.constructor.name;
66540
+ function getObjectTag(object20) {
66541
+ const tag3 = Object.prototype.toString.call(object20).replace(/^\[object /, "").replace(/]$/, "");
66542
+ if (tag3 === "Object" && typeof object20.constructor === "function") {
66543
+ const name5 = object20.constructor.name;
66468
66544
  if (typeof name5 === "string" && name5 !== "") {
66469
66545
  return name5;
66470
66546
  }
@@ -68862,16 +68938,16 @@ var require_printer = __commonJS({
68862
68938
  },
68863
68939
  // Document
68864
68940
  Document: {
68865
- leave: (node5) => join22(node5.definitions, "\n\n")
68941
+ leave: (node5) => join23(node5.definitions, "\n\n")
68866
68942
  },
68867
68943
  OperationDefinition: {
68868
68944
  leave(node5) {
68869
- const varDefs = hasMultilineItems(node5.variableDefinitions) ? wrap("(\n", join22(node5.variableDefinitions, "\n"), "\n)") : wrap("(", join22(node5.variableDefinitions, ", "), ")");
68870
- const prefix2 = wrap("", node5.description, "\n") + join22(
68945
+ const varDefs = hasMultilineItems(node5.variableDefinitions) ? wrap("(\n", join23(node5.variableDefinitions, "\n"), "\n)") : wrap("(", join23(node5.variableDefinitions, ", "), ")");
68946
+ const prefix2 = wrap("", node5.description, "\n") + join23(
68871
68947
  [
68872
68948
  node5.operation,
68873
- join22([node5.name, varDefs]),
68874
- join22(node5.directives, " ")
68949
+ join23([node5.name, varDefs]),
68950
+ join23(node5.directives, " ")
68875
68951
  ],
68876
68952
  " "
68877
68953
  );
@@ -68879,7 +68955,7 @@ var require_printer = __commonJS({
68879
68955
  }
68880
68956
  },
68881
68957
  VariableDefinition: {
68882
- leave: ({ variable, type, defaultValue, directives, description: description2 }) => wrap("", description2, "\n") + variable + ": " + type + wrap(" = ", defaultValue) + wrap(" ", join22(directives, " "))
68958
+ leave: ({ variable, type, defaultValue, directives, description: description2 }) => wrap("", description2, "\n") + variable + ": " + type + wrap(" = ", defaultValue) + wrap(" ", join23(directives, " "))
68883
68959
  },
68884
68960
  SelectionSet: {
68885
68961
  leave: ({ selections: selections2 }) => block2(selections2)
@@ -68887,11 +68963,11 @@ var require_printer = __commonJS({
68887
68963
  Field: {
68888
68964
  leave({ alias, name: name5, arguments: args, directives, selectionSet }) {
68889
68965
  const prefix2 = wrap("", alias, ": ") + name5;
68890
- let argsLine = prefix2 + wrap("(", join22(args, ", "), ")");
68966
+ let argsLine = prefix2 + wrap("(", join23(args, ", "), ")");
68891
68967
  if (argsLine.length > MAX_LINE_LENGTH) {
68892
- argsLine = prefix2 + wrap("(\n", indent(join22(args, "\n")), "\n)");
68968
+ argsLine = prefix2 + wrap("(\n", indent(join23(args, "\n")), "\n)");
68893
68969
  }
68894
- return join22([argsLine, join22(directives, " "), selectionSet], " ");
68970
+ return join23([argsLine, join23(directives, " "), selectionSet], " ");
68895
68971
  }
68896
68972
  },
68897
68973
  Argument: {
@@ -68899,14 +68975,14 @@ var require_printer = __commonJS({
68899
68975
  },
68900
68976
  // Fragments
68901
68977
  FragmentSpread: {
68902
- leave: ({ name: name5, directives }) => "..." + name5 + wrap(" ", join22(directives, " "))
68978
+ leave: ({ name: name5, directives }) => "..." + name5 + wrap(" ", join23(directives, " "))
68903
68979
  },
68904
68980
  InlineFragment: {
68905
- leave: ({ typeCondition, directives, selectionSet }) => join22(
68981
+ leave: ({ typeCondition, directives, selectionSet }) => join23(
68906
68982
  [
68907
68983
  "...",
68908
68984
  wrap("on ", typeCondition),
68909
- join22(directives, " "),
68985
+ join23(directives, " "),
68910
68986
  selectionSet
68911
68987
  ],
68912
68988
  " "
@@ -68922,7 +68998,7 @@ var require_printer = __commonJS({
68922
68998
  description: description2
68923
68999
  }) => wrap("", description2, "\n") + // Note: fragment variable definitions are experimental and may be changed
68924
69000
  // or removed in the future.
68925
- `fragment ${name5}${wrap("(", join22(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap("", join22(directives, " "), " ")}` + selectionSet
69001
+ `fragment ${name5}${wrap("(", join23(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap("", join23(directives, " "), " ")}` + selectionSet
68926
69002
  },
68927
69003
  // Value
68928
69004
  IntValue: {
@@ -68944,17 +69020,17 @@ var require_printer = __commonJS({
68944
69020
  leave: ({ value: value4 }) => value4
68945
69021
  },
68946
69022
  ListValue: {
68947
- leave: ({ values: values2 }) => "[" + join22(values2, ", ") + "]"
69023
+ leave: ({ values: values2 }) => "[" + join23(values2, ", ") + "]"
68948
69024
  },
68949
69025
  ObjectValue: {
68950
- leave: ({ fields: fields11 }) => "{" + join22(fields11, ", ") + "}"
69026
+ leave: ({ fields: fields11 }) => "{" + join23(fields11, ", ") + "}"
68951
69027
  },
68952
69028
  ObjectField: {
68953
69029
  leave: ({ name: name5, value: value4 }) => name5 + ": " + value4
68954
69030
  },
68955
69031
  // Directive
68956
69032
  Directive: {
68957
- leave: ({ name: name5, arguments: args }) => "@" + name5 + wrap("(", join22(args, ", "), ")")
69033
+ leave: ({ name: name5, arguments: args }) => "@" + name5 + wrap("(", join23(args, ", "), ")")
68958
69034
  },
68959
69035
  // Type
68960
69036
  NamedType: {
@@ -68968,61 +69044,61 @@ var require_printer = __commonJS({
68968
69044
  },
68969
69045
  // Type System Definitions
68970
69046
  SchemaDefinition: {
68971
- leave: ({ description: description2, directives, operationTypes }) => wrap("", description2, "\n") + join22(["schema", join22(directives, " "), block2(operationTypes)], " ")
69047
+ leave: ({ description: description2, directives, operationTypes }) => wrap("", description2, "\n") + join23(["schema", join23(directives, " "), block2(operationTypes)], " ")
68972
69048
  },
68973
69049
  OperationTypeDefinition: {
68974
69050
  leave: ({ operation, type }) => operation + ": " + type
68975
69051
  },
68976
69052
  ScalarTypeDefinition: {
68977
- leave: ({ description: description2, name: name5, directives }) => wrap("", description2, "\n") + join22(["scalar", name5, join22(directives, " ")], " ")
69053
+ leave: ({ description: description2, name: name5, directives }) => wrap("", description2, "\n") + join23(["scalar", name5, join23(directives, " ")], " ")
68978
69054
  },
68979
69055
  ObjectTypeDefinition: {
68980
- leave: ({ description: description2, name: name5, interfaces, directives, fields: fields11 }) => wrap("", description2, "\n") + join22(
69056
+ leave: ({ description: description2, name: name5, interfaces, directives, fields: fields11 }) => wrap("", description2, "\n") + join23(
68981
69057
  [
68982
69058
  "type",
68983
69059
  name5,
68984
- wrap("implements ", join22(interfaces, " & ")),
68985
- join22(directives, " "),
69060
+ wrap("implements ", join23(interfaces, " & ")),
69061
+ join23(directives, " "),
68986
69062
  block2(fields11)
68987
69063
  ],
68988
69064
  " "
68989
69065
  )
68990
69066
  },
68991
69067
  FieldDefinition: {
68992
- leave: ({ description: description2, name: name5, arguments: args, type, directives }) => wrap("", description2, "\n") + name5 + (hasMultilineItems(args) ? wrap("(\n", indent(join22(args, "\n")), "\n)") : wrap("(", join22(args, ", "), ")")) + ": " + type + wrap(" ", join22(directives, " "))
69068
+ leave: ({ description: description2, name: name5, arguments: args, type, directives }) => wrap("", description2, "\n") + name5 + (hasMultilineItems(args) ? wrap("(\n", indent(join23(args, "\n")), "\n)") : wrap("(", join23(args, ", "), ")")) + ": " + type + wrap(" ", join23(directives, " "))
68993
69069
  },
68994
69070
  InputValueDefinition: {
68995
- leave: ({ description: description2, name: name5, type, defaultValue, directives }) => wrap("", description2, "\n") + join22(
68996
- [name5 + ": " + type, wrap("= ", defaultValue), join22(directives, " ")],
69071
+ leave: ({ description: description2, name: name5, type, defaultValue, directives }) => wrap("", description2, "\n") + join23(
69072
+ [name5 + ": " + type, wrap("= ", defaultValue), join23(directives, " ")],
68997
69073
  " "
68998
69074
  )
68999
69075
  },
69000
69076
  InterfaceTypeDefinition: {
69001
- leave: ({ description: description2, name: name5, interfaces, directives, fields: fields11 }) => wrap("", description2, "\n") + join22(
69077
+ leave: ({ description: description2, name: name5, interfaces, directives, fields: fields11 }) => wrap("", description2, "\n") + join23(
69002
69078
  [
69003
69079
  "interface",
69004
69080
  name5,
69005
- wrap("implements ", join22(interfaces, " & ")),
69006
- join22(directives, " "),
69081
+ wrap("implements ", join23(interfaces, " & ")),
69082
+ join23(directives, " "),
69007
69083
  block2(fields11)
69008
69084
  ],
69009
69085
  " "
69010
69086
  )
69011
69087
  },
69012
69088
  UnionTypeDefinition: {
69013
- leave: ({ description: description2, name: name5, directives, types }) => wrap("", description2, "\n") + join22(
69014
- ["union", name5, join22(directives, " "), wrap("= ", join22(types, " | "))],
69089
+ leave: ({ description: description2, name: name5, directives, types }) => wrap("", description2, "\n") + join23(
69090
+ ["union", name5, join23(directives, " "), wrap("= ", join23(types, " | "))],
69015
69091
  " "
69016
69092
  )
69017
69093
  },
69018
69094
  EnumTypeDefinition: {
69019
- leave: ({ description: description2, name: name5, directives, values: values2 }) => wrap("", description2, "\n") + join22(["enum", name5, join22(directives, " "), block2(values2)], " ")
69095
+ leave: ({ description: description2, name: name5, directives, values: values2 }) => wrap("", description2, "\n") + join23(["enum", name5, join23(directives, " "), block2(values2)], " ")
69020
69096
  },
69021
69097
  EnumValueDefinition: {
69022
- leave: ({ description: description2, name: name5, directives }) => wrap("", description2, "\n") + join22([name5, join22(directives, " ")], " ")
69098
+ leave: ({ description: description2, name: name5, directives }) => wrap("", description2, "\n") + join23([name5, join23(directives, " ")], " ")
69023
69099
  },
69024
69100
  InputObjectTypeDefinition: {
69025
- leave: ({ description: description2, name: name5, directives, fields: fields11 }) => wrap("", description2, "\n") + join22(["input", name5, join22(directives, " "), block2(fields11)], " ")
69101
+ leave: ({ description: description2, name: name5, directives, fields: fields11 }) => wrap("", description2, "\n") + join23(["input", name5, join23(directives, " "), block2(fields11)], " ")
69026
69102
  },
69027
69103
  DirectiveDefinition: {
69028
69104
  leave: ({
@@ -69032,84 +69108,84 @@ var require_printer = __commonJS({
69032
69108
  directives,
69033
69109
  repeatable,
69034
69110
  locations
69035
- }) => wrap("", description2, "\n") + "directive @" + name5 + (hasMultilineItems(args) ? wrap("(\n", indent(join22(args, "\n")), "\n)") : wrap("(", join22(args, ", "), ")")) + wrap(" ", join22(directives, " ")) + (repeatable ? " repeatable" : "") + " on " + join22(locations, " | ")
69111
+ }) => wrap("", description2, "\n") + "directive @" + name5 + (hasMultilineItems(args) ? wrap("(\n", indent(join23(args, "\n")), "\n)") : wrap("(", join23(args, ", "), ")")) + wrap(" ", join23(directives, " ")) + (repeatable ? " repeatable" : "") + " on " + join23(locations, " | ")
69036
69112
  },
69037
69113
  SchemaExtension: {
69038
- leave: ({ directives, operationTypes }) => join22(
69039
- ["extend schema", join22(directives, " "), block2(operationTypes)],
69114
+ leave: ({ directives, operationTypes }) => join23(
69115
+ ["extend schema", join23(directives, " "), block2(operationTypes)],
69040
69116
  " "
69041
69117
  )
69042
69118
  },
69043
69119
  ScalarTypeExtension: {
69044
- leave: ({ name: name5, directives }) => join22(["extend scalar", name5, join22(directives, " ")], " ")
69120
+ leave: ({ name: name5, directives }) => join23(["extend scalar", name5, join23(directives, " ")], " ")
69045
69121
  },
69046
69122
  ObjectTypeExtension: {
69047
- leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join22(
69123
+ leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join23(
69048
69124
  [
69049
69125
  "extend type",
69050
69126
  name5,
69051
- wrap("implements ", join22(interfaces, " & ")),
69052
- join22(directives, " "),
69127
+ wrap("implements ", join23(interfaces, " & ")),
69128
+ join23(directives, " "),
69053
69129
  block2(fields11)
69054
69130
  ],
69055
69131
  " "
69056
69132
  )
69057
69133
  },
69058
69134
  InterfaceTypeExtension: {
69059
- leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join22(
69135
+ leave: ({ name: name5, interfaces, directives, fields: fields11 }) => join23(
69060
69136
  [
69061
69137
  "extend interface",
69062
69138
  name5,
69063
- wrap("implements ", join22(interfaces, " & ")),
69064
- join22(directives, " "),
69139
+ wrap("implements ", join23(interfaces, " & ")),
69140
+ join23(directives, " "),
69065
69141
  block2(fields11)
69066
69142
  ],
69067
69143
  " "
69068
69144
  )
69069
69145
  },
69070
69146
  UnionTypeExtension: {
69071
- leave: ({ name: name5, directives, types }) => join22(
69147
+ leave: ({ name: name5, directives, types }) => join23(
69072
69148
  [
69073
69149
  "extend union",
69074
69150
  name5,
69075
- join22(directives, " "),
69076
- wrap("= ", join22(types, " | "))
69151
+ join23(directives, " "),
69152
+ wrap("= ", join23(types, " | "))
69077
69153
  ],
69078
69154
  " "
69079
69155
  )
69080
69156
  },
69081
69157
  EnumTypeExtension: {
69082
- leave: ({ name: name5, directives, values: values2 }) => join22(["extend enum", name5, join22(directives, " "), block2(values2)], " ")
69158
+ leave: ({ name: name5, directives, values: values2 }) => join23(["extend enum", name5, join23(directives, " "), block2(values2)], " ")
69083
69159
  },
69084
69160
  InputObjectTypeExtension: {
69085
- leave: ({ name: name5, directives, fields: fields11 }) => join22(["extend input", name5, join22(directives, " "), block2(fields11)], " ")
69161
+ leave: ({ name: name5, directives, fields: fields11 }) => join23(["extend input", name5, join23(directives, " "), block2(fields11)], " ")
69086
69162
  },
69087
69163
  DirectiveExtension: {
69088
- leave: ({ name: name5, directives }) => join22(["extend directive @" + name5, join22(directives, " ")], " ")
69164
+ leave: ({ name: name5, directives }) => join23(["extend directive @" + name5, join23(directives, " ")], " ")
69089
69165
  },
69090
69166
  // Schema Coordinates
69091
69167
  TypeCoordinate: {
69092
69168
  leave: ({ name: name5 }) => name5
69093
69169
  },
69094
69170
  MemberCoordinate: {
69095
- leave: ({ name: name5, memberName }) => join22([name5, wrap(".", memberName)])
69171
+ leave: ({ name: name5, memberName }) => join23([name5, wrap(".", memberName)])
69096
69172
  },
69097
69173
  ArgumentCoordinate: {
69098
- leave: ({ name: name5, fieldName, argumentName }) => join22([name5, wrap(".", fieldName), wrap("(", argumentName, ":)")])
69174
+ leave: ({ name: name5, fieldName, argumentName }) => join23([name5, wrap(".", fieldName), wrap("(", argumentName, ":)")])
69099
69175
  },
69100
69176
  DirectiveCoordinate: {
69101
- leave: ({ name: name5 }) => join22(["@", name5])
69177
+ leave: ({ name: name5 }) => join23(["@", name5])
69102
69178
  },
69103
69179
  DirectiveArgumentCoordinate: {
69104
- leave: ({ name: name5, argumentName }) => join22(["@", name5, wrap("(", argumentName, ":)")])
69180
+ leave: ({ name: name5, argumentName }) => join23(["@", name5, wrap("(", argumentName, ":)")])
69105
69181
  }
69106
69182
  };
69107
- function join22(maybeArray, separator = "") {
69183
+ function join23(maybeArray, separator = "") {
69108
69184
  var _maybeArray$filter$jo;
69109
69185
  return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter((x) => x).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : "";
69110
69186
  }
69111
69187
  function block2(array3) {
69112
- return wrap("{\n", indent(join22(array3, "\n")), "\n}");
69188
+ return wrap("{\n", indent(join23(array3, "\n")), "\n}");
69113
69189
  }
69114
69190
  function wrap(start2, maybeString, end = "") {
69115
69191
  return maybeString != null && maybeString !== "" ? start2 + maybeString + end : "";
@@ -78669,10 +78745,10 @@ var require_promiseForObject = __commonJS({
78669
78745
  value: true
78670
78746
  });
78671
78747
  exports.promiseForObject = promiseForObject;
78672
- function promiseForObject(object19) {
78673
- return Promise.all(Object.values(object19)).then((resolvedValues) => {
78748
+ function promiseForObject(object20) {
78749
+ return Promise.all(Object.values(object20)).then((resolvedValues) => {
78674
78750
  const resolvedObject = /* @__PURE__ */ Object.create(null);
78675
- for (const [i, key4] of Object.keys(object19).entries()) {
78751
+ for (const [i, key4] of Object.keys(object20).entries()) {
78676
78752
  resolvedObject[key4] = resolvedValues[i];
78677
78753
  }
78678
78754
  return resolvedObject;
@@ -86483,7 +86559,7 @@ function toolValueDifferences(have, want, path6, subset) {
86483
86559
  ...want.flatMap((value4, index) => toolValueDifferences(have[index], value4, `${path6}[${index}]`, false))
86484
86560
  ];
86485
86561
  }
86486
- const desired = object5(want), actual = object5(have);
86562
+ const desired = object6(want), actual = object6(have);
86487
86563
  if (desired && actual) return [
86488
86564
  ...Object.entries(desired).flatMap(([key4, value4]) => Object.hasOwn(actual, key4) ? toolValueDifferences(actual[key4], value4, `${path6}.${key4}`, subset) : [`${path6}.${key4}: expected ${jsonValue(value4)}, got (missing)`]),
86489
86565
  ...!subset ? Object.keys(actual).filter((key4) => !Object.hasOwn(desired, key4)).map((key4) => `${path6}.${key4}: unexpected ${jsonValue(actual[key4])}`) : []
@@ -86495,11 +86571,12 @@ function evaluateToolCall(check3, trace) {
86495
86571
  const status5 = check3.status ?? "succeeded", count5 = check3.count ?? { gte: 1 };
86496
86572
  const expected = `${check3.name}: status ${status5}; count ${JSON.stringify(count5)}` + (check3.args ? `; args ${JSON.stringify(check3.args)}` : "") + (check3.result ? `; result ${JSON.stringify(check3.result)}` : "") + (check3.error ? `; error.type ${JSON.stringify(check3.error.type)}` : "");
86497
86573
  const candidates = calls2.map((entry2) => {
86498
- const response5 = object5(entry2.response), request2 = object5(entry2.request);
86574
+ const response5 = object6(entry2.response), request2 = object6(entry2.request);
86499
86575
  const functionCall = entry2.service === "tools" && entry2.path === `/tools/${check3.name}`;
86500
- const params10 = object5(request2?.params);
86501
- const args = functionCall ? request2?.args : entry2.method === "MCP" ? request2?.args ?? request2?.arguments : params10?.arguments;
86502
- const result = functionCall || entry2.method === "POST" ? response5?.result : entry2.response;
86576
+ const params10 = object6(request2?.params);
86577
+ const fields11 = functionCallFields(entry2);
86578
+ const args = functionCall ? fields11.args : entry2.method === "MCP" ? request2?.args ?? request2?.arguments : params10?.arguments;
86579
+ const result = functionCall ? fields11.result : entry2.method === "POST" ? response5?.result : entry2.response;
86503
86580
  const unconfirmed = response5?.execution_status === "unknown" || response5?.execution_status === "pending";
86504
86581
  if (unconfirmed) throw new AnchaError("USAGE", `${check3.name} (seq ${entry2.seq}): completion missing. ${functionWiringMessage([check3.name])} Await the wrapped call and its completion report before finishing the task.`);
86505
86582
  const actualStatus = response5?.execution_status === "failed" || failure2(entry2) !== void 0 || response5?.isError === true || response5?.error != null ? "failed" : "succeeded";
@@ -86516,14 +86593,14 @@ function evaluateToolCall(check3, trace) {
86516
86593
  }
86517
86594
  differences2.push(...toolValueDifferences(value4, predicate.equals !== void 0 ? predicate.equals : predicate.contains, field6, predicate.contains !== void 0));
86518
86595
  }
86519
- const errorType = response5?.error_type ?? object5(response5?.error)?.type;
86596
+ const errorType = functionCall ? fields11.error_type : response5?.error_type ?? object6(response5?.error)?.type;
86520
86597
  if (check3.error && errorType !== check3.error.type) differences2.push(`error.type: expected ${jsonValue(check3.error.type)}, got ${jsonValue(errorType)}`);
86521
86598
  return { entry: entry2, differences: differences2, actualStatus };
86522
86599
  });
86523
86600
  const matched = candidates.filter((call2) => call2.differences.length === 0);
86524
86601
  const passed = (count5.eq === void 0 || matched.length === count5.eq) && (count5.gte === void 0 || matched.length >= count5.gte) && (count5.lte === void 0 || matched.length <= count5.lte);
86525
86602
  const closest = [...candidates].sort((a, b) => a.differences.length - b.differences.length || a.entry.seq - b.entry.seq)[0];
86526
- const detail3 = closest ? `closest call ${check3.name} (seq ${closest.entry.seq}${closest.entry.completion ? `, completion seq ${closest.entry.completion.seq}` : ""}${object5(closest.entry.response)?.source ? `, ${object5(closest.entry.response).source}` : ""}): ${list3(closest.differences) || `status ${closest.actualStatus}; all call predicates match`}` : `no call named ${check3.name}`;
86603
+ const detail3 = closest ? `closest call ${check3.name} (seq ${closest.entry.seq}${closest.entry.completion ? `, completion seq ${closest.entry.completion.seq}` : ""}${object6(closest.entry.response)?.source ? `, ${object6(closest.entry.response).source}` : ""}): ${list3(closest.differences) || `status ${closest.actualStatus}; all call predicates match`}` : `no call named ${check3.name}`;
86527
86604
  const actual = `${check3.name}: count ${matched.length} matching of ${calls2.length} named call(s); ${detail3}`;
86528
86605
  return {
86529
86606
  passed,
@@ -86762,12 +86839,13 @@ function evaluateChecks(env, checks2 = env.scene.checks) {
86762
86839
  };
86763
86840
  });
86764
86841
  }
86765
- var import_graphql, LIST_LIMIT, PATTERN_HINT, seqs, unique2, describe3, quoted2, asList, object5, jsonValue, ANSWER_QUOTE, sceneTools;
86842
+ var import_graphql, LIST_LIMIT, PATTERN_HINT, seqs, unique2, describe3, quoted2, asList, object6, jsonValue, ANSWER_QUOTE, sceneTools;
86766
86843
  var init_checks5 = __esm({
86767
86844
  "packages/server/src/checks.ts"() {
86768
86845
  "use strict";
86769
86846
  init_src();
86770
86847
  init_src();
86848
+ init_src();
86771
86849
  init_agent_tools();
86772
86850
  import_graphql = __toESM(require_graphql2(), 1);
86773
86851
  init_checks4();
@@ -86786,7 +86864,7 @@ var init_checks5 = __esm({
86786
86864
  };
86787
86865
  quoted2 = (patterns) => patterns.map((p2) => `"${p2}"`).join(", ");
86788
86866
  asList = (v) => v === void 0 ? [] : Array.isArray(v) ? v : [v];
86789
- object5 = (value4) => value4 !== null && typeof value4 === "object" && !Array.isArray(value4) ? value4 : void 0;
86867
+ object6 = (value4) => value4 !== null && typeof value4 === "object" && !Array.isArray(value4) ? value4 : void 0;
86790
86868
  jsonValue = (value4) => value4 === void 0 ? "(missing)" : JSON.stringify(value4);
86791
86869
  ANSWER_QUOTE = 300;
86792
86870
  sceneTools = (env) => new Set(Object.keys(env.scene.tools ?? {}));
@@ -88085,13 +88163,13 @@ function githubEvent(ctx, type, payload2, additionalLinks = []) {
88085
88163
  const body6 = structuredClone({ ...payload2, sender: payload2.sender ?? userShape(githubEventContext(ctx), botUser(ctx)) });
88086
88164
  const apiLinks = [];
88087
88165
  const fields11 = (pointer2, keys7) => {
88088
- let object19 = body6;
88166
+ let object20 = body6;
88089
88167
  for (const key4 of pointer2.slice(1).split("/")) {
88090
- if (!object19 || typeof object19 !== "object") return;
88091
- object19 = object19[key4];
88168
+ if (!object20 || typeof object20 !== "object") return;
88169
+ object20 = object20[key4];
88092
88170
  }
88093
- if (!object19 || typeof object19 !== "object") return;
88094
- const resource2 = object19;
88171
+ if (!object20 || typeof object20 !== "object") return;
88172
+ const resource2 = object20;
88095
88173
  for (const key4 of keys7) {
88096
88174
  const value4 = resource2[key4];
88097
88175
  if (typeof value4 !== "string" || !(value4.startsWith(`${semanticOrigin}/`) || value4.startsWith("/"))) continue;
@@ -89509,12 +89587,12 @@ var init_incidents = __esm({
89509
89587
  });
89510
89588
 
89511
89589
  // packages/server/src/twins/pagerduty/ingest.ts
89512
- function object6(value4) {
89590
+ function object7(value4) {
89513
89591
  return value4 !== null && typeof value4 === "object" && !Array.isArray(value4);
89514
89592
  }
89515
89593
  function ingestEvent(ctx, input5) {
89516
89594
  return withMutation(ctx, () => {
89517
- if (!object6(input5)) invalid4("Event must be an object");
89595
+ if (!object7(input5)) invalid4("Event must be an object");
89518
89596
  for (const key5 of Object.keys(input5)) if (!["routing_key", "event_action", "dedup_key", "payload"].includes(key5)) unsupported2(`Events ${key5}`);
89519
89597
  if (typeof input5.routing_key !== "string") invalid4("routing_key is required");
89520
89598
  const service = ctx.store.db.prepare("SELECT * FROM pagerduty_services WHERE routing_key = ?").get(input5.routing_key);
@@ -89523,11 +89601,11 @@ function ingestEvent(ctx, input5) {
89523
89601
  if (input5.dedup_key !== void 0 && (typeof input5.dedup_key !== "string" || !input5.dedup_key.length || input5.dedup_key.length > 255)) invalid4("dedup_key must be 1 to 255 characters");
89524
89602
  if (input5.event_action !== "trigger" && input5.dedup_key === void 0) invalid4("dedup_key is required");
89525
89603
  if (input5.payload !== void 0) {
89526
- if (!object6(input5.payload)) invalid4("payload must be an object");
89604
+ if (!object7(input5.payload)) invalid4("payload must be an object");
89527
89605
  for (const key5 of Object.keys(input5.payload)) if (!["summary", "source", "severity", "timestamp", "component", "group", "class", "custom_details"].includes(key5)) unsupported2(`Events payload.${key5}`);
89528
89606
  for (const key5 of ["component", "group", "class"]) if (input5.payload[key5] !== void 0 && typeof input5.payload[key5] !== "string") invalid4(`Invalid payload.${key5}`);
89529
89607
  if (input5.payload.timestamp !== void 0 && (!/^\d{4}-\d\d-\d\dT/.test(input5.payload.timestamp) || !Number.isFinite(Date.parse(input5.payload.timestamp)))) invalid4("Invalid payload.timestamp");
89530
- if (input5.payload.custom_details !== void 0 && !object6(input5.payload.custom_details)) invalid4("Invalid payload.custom_details");
89608
+ if (input5.payload.custom_details !== void 0 && !object7(input5.payload.custom_details)) invalid4("Invalid payload.custom_details");
89531
89609
  }
89532
89610
  if (input5.event_action === "trigger") {
89533
89611
  const p2 = input5.payload;
@@ -90052,11 +90130,11 @@ function replaceLink(message7, link6, url4) {
90052
90130
  for (const [index, key4] of keys7.entries()) {
90053
90131
  if (typeof target5 !== "object" || target5 === null || !Object.hasOwn(target5, key4) || Array.isArray(target5) && !/^(0|[1-9]\d*)$/.test(key4))
90054
90132
  throw new AnchaError("INTERNAL", "Missing Slack message API link field");
90055
- const object19 = target5;
90133
+ const object20 = target5;
90056
90134
  if (index === keys7.length - 1) {
90057
- if (object19[key4] !== link6.path) throw new AnchaError("INTERNAL", "Slack message API link does not match its semantic path");
90058
- Object.defineProperty(object19, key4, { value: url4, enumerable: true, configurable: true, writable: true });
90059
- } else target5 = object19[key4];
90135
+ if (object20[key4] !== link6.path) throw new AnchaError("INTERNAL", "Slack message API link does not match its semantic path");
90136
+ Object.defineProperty(object20, key4, { value: url4, enumerable: true, configurable: true, writable: true });
90137
+ } else target5 = object20[key4];
90060
90138
  }
90061
90139
  }
90062
90140
  function persistMessageLinks(ctx, row2, links3 = []) {
@@ -90771,7 +90849,7 @@ var init_issues = __esm({
90771
90849
  function emitWebhooks(ctx, type, prior, next2) {
90772
90850
  const seed43 = ctx.scene.seed.hubspot, webhooks = seed43?.webhooks;
90773
90851
  if (!seed43 || !webhooks?.subscriptions.length) return;
90774
- const object19 = SINGULAR[type];
90852
+ const object20 = SINGULAR[type];
90775
90853
  webhooks.subscriptions.forEach((subscription2, index) => {
90776
90854
  const [subscriptionType, propertyName] = subscription2.split(":");
90777
90855
  const event3 = () => ({
@@ -90785,8 +90863,8 @@ function emitWebhooks(ctx, type, prior, next2) {
90785
90863
  objectId: Number(next2.id),
90786
90864
  changeSource: "API"
90787
90865
  });
90788
- if (subscriptionType === `${object19}.creation` && prior === void 0) ctx.events.append({ service: "hubspot", type: subscriptionType, payload: [event3()] });
90789
- if (subscriptionType === `${object19}.propertyChange` && propertyName !== void 0) {
90866
+ if (subscriptionType === `${object20}.creation` && prior === void 0) ctx.events.append({ service: "hubspot", type: subscriptionType, payload: [event3()] });
90867
+ if (subscriptionType === `${object20}.propertyChange` && propertyName !== void 0) {
90790
90868
  const value4 = next2.properties[propertyName];
90791
90869
  if (value4 !== void 0 && value4 !== "" && value4 !== prior?.properties[propertyName]) ctx.events.append({ service: "hubspot", type: subscriptionType, payload: [{ ...event3(), propertyName, propertyValue: value4 }] });
90792
90870
  }
@@ -92174,7 +92252,7 @@ function handleMutation(handler, status5 = 200, applicationKey = true) {
92174
92252
  }
92175
92253
  };
92176
92254
  }
92177
- function object7(value4, field6) {
92255
+ function object8(value4, field6) {
92178
92256
  if (value4 === null || typeof value4 !== "object" || Array.isArray(value4)) throw new DatadogError(400, `Invalid ${field6}: expected object`);
92179
92257
  return value4;
92180
92258
  }
@@ -95936,7 +96014,7 @@ function fields4(value4, allowed2) {
95936
96014
  if (!allowed2.includes(key4))
95937
96015
  gap(`field ${key4}`);
95938
96016
  }
95939
- function object8(value4) {
96017
+ function object9(value4) {
95940
96018
  if (!value4 || typeof value4 !== "object" || Array.isArray(value4))
95941
96019
  invalid7("Expected an object");
95942
96020
  return value4;
@@ -96188,7 +96266,7 @@ function search2(ctx, body6, customer3, stream = false) {
96188
96266
  if (body6.summaryRowSetting && !["UNSPECIFIED", "NO_SUMMARY_ROW"].includes(body6.summaryRowSetting))
96189
96267
  gap("summaryRowSetting");
96190
96268
  if (body6.searchSettings) {
96191
- fields4(object8(body6.searchSettings), ["returnTotalResultsCount"]);
96269
+ fields4(object9(body6.searchSettings), ["returnTotalResultsCount"]);
96192
96270
  if (body6.searchSettings.returnTotalResultsCount !== void 0 && typeof body6.searchSettings.returnTotalResultsCount !== "boolean")
96193
96271
  invalid7("returnTotalResultsCount must be boolean");
96194
96272
  }
@@ -96353,7 +96431,7 @@ function updatePaths(mask2) {
96353
96431
  invalid7("update_mask is required");
96354
96432
  return mask2.split(",").map((p2) => p2.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`));
96355
96433
  }
96356
- const obj = object8(mask2);
96434
+ const obj = object9(mask2);
96357
96435
  fields4(obj, ["paths"]);
96358
96436
  if (!Array.isArray(obj.paths) || !obj.paths.length || obj.paths.some((p2) => typeof p2 !== "string"))
96359
96437
  invalid7("update_mask.paths must contain field paths");
@@ -96383,7 +96461,7 @@ function validateRelationships(ctx, kind, record13, cid) {
96383
96461
  throw new AdsError(3, "fieldError", "INVALID_VALUE", "end_date_time must not precede start_date_time");
96384
96462
  }
96385
96463
  function oneOperation(ctx, kind, cid, raw3, returnResource) {
96386
- const op = object8(raw3);
96464
+ const op = object9(raw3);
96387
96465
  fields4(op, ["create", "update", "remove", "updateMask"]);
96388
96466
  const types = ["create", "update", "remove"].filter((k) => op[k] !== void 0);
96389
96467
  if (types.length !== 1)
@@ -96392,7 +96470,7 @@ function oneOperation(ctx, kind, cid, raw3, returnResource) {
96392
96470
  invalid7("update_mask is only valid with update");
96393
96471
  let record13;
96394
96472
  if (op.create !== void 0) {
96395
- const input5 = object8(op.create);
96473
+ const input5 = object9(op.create);
96396
96474
  for (const k of ["resourceName", "id", "criterionId", "policySummary", "type"]) {
96397
96475
  if (input5[k] !== void 0 && !(k === "type" && kind === "adGroups"))
96398
96476
  throw new AdsError(3, "fieldError", "VALUE_MUST_BE_UNSET", `${k} must not be set on create`);
@@ -96409,7 +96487,7 @@ function oneOperation(ctx, kind, cid, raw3, returnResource) {
96409
96487
  if (kind === "ads") {
96410
96488
  if (input5.ad?.id !== void 0 || input5.ad?.resourceName !== void 0 || input5.ad?.type !== void 0)
96411
96489
  throw new AdsError(3, "fieldError", "VALUE_MUST_BE_UNSET", "Ad id, resource_name and type are assigned on create");
96412
- record13.ad = { ...object8(input5.ad), id: id14, resourceName: `customers/${cid}/ads/${id14}`, type: "RESPONSIVE_SEARCH_AD" };
96490
+ record13.ad = { ...object9(input5.ad), id: id14, resourceName: `customers/${cid}/ads/${id14}`, type: "RESPONSIVE_SEARCH_AD" };
96413
96491
  record13.policySummary = { reviewStatus: "REVIEW_IN_PROGRESS", approvalStatus: "UNKNOWN" };
96414
96492
  }
96415
96493
  if (kind === "criteria")
@@ -96417,7 +96495,7 @@ function oneOperation(ctx, kind, cid, raw3, returnResource) {
96417
96495
  if (kind === "budgets")
96418
96496
  record13.status = "ENABLED";
96419
96497
  } else {
96420
- const input5 = op.update === void 0 ? void 0 : object8(op.update), name5 = parseName(op.remove ?? input5?.resourceName, cid, kind);
96498
+ const input5 = op.update === void 0 ? void 0 : object9(op.update), name5 = parseName(op.remove ?? input5?.resourceName, cid, kind);
96421
96499
  const old = get(ctx, kind, name5);
96422
96500
  if (!old)
96423
96501
  throw new AdsError(3, "mutateError", "RESOURCE_NOT_FOUND", "Resource does not exist");
@@ -96508,7 +96586,7 @@ function execute2(ctx, method2, raw3, headers) {
96508
96586
  const write4 = method2.startsWith("Mutate");
96509
96587
  return (write4 ? withMutation : withRead)(ctx, () => {
96510
96588
  authenticate4(ctx, headers);
96511
- const body6 = object8(raw3);
96589
+ const body6 = object9(raw3);
96512
96590
  if (method2 === "ListAccessibleCustomers") {
96513
96591
  fields4(body6, []);
96514
96592
  return { resourceNames: config3(ctx).access.directCustomerIds.map((id14) => `customers/${id14}`) };
@@ -96815,9 +96893,9 @@ var require_lodash = __commonJS({
96815
96893
  function asciiWords(string7) {
96816
96894
  return string7.match(reAsciiWord) || [];
96817
96895
  }
96818
- function basePropertyOf(object19) {
96896
+ function basePropertyOf(object20) {
96819
96897
  return function(key4) {
96820
- return object19 == null ? void 0 : object19[key4];
96898
+ return object20 == null ? void 0 : object20[key4];
96821
96899
  };
96822
96900
  }
96823
96901
  var deburrLetter = basePropertyOf(deburredLetters);
@@ -99634,32 +99712,32 @@ var require_namespace = __commonJS({
99634
99712
  return this.nested[name5].values;
99635
99713
  throw Error("no such enum: " + name5);
99636
99714
  };
99637
- Namespace.prototype.add = function add(object19) {
99638
- if (!(object19 instanceof Field && object19.extend !== void 0 || object19 instanceof Type || object19 instanceof OneOf || object19 instanceof Enum || object19 instanceof Service || object19 instanceof Namespace))
99715
+ Namespace.prototype.add = function add(object20) {
99716
+ if (!(object20 instanceof Field && object20.extend !== void 0 || object20 instanceof Type || object20 instanceof OneOf || object20 instanceof Enum || object20 instanceof Service || object20 instanceof Namespace))
99639
99717
  throw TypeError("object must be a valid nested object");
99640
- if (object19.name === "__proto__")
99718
+ if (object20.name === "__proto__")
99641
99719
  return this;
99642
99720
  if (!this.nested)
99643
99721
  this.nested = {};
99644
99722
  else {
99645
- var prev = this.get(object19.name);
99723
+ var prev = this.get(object20.name);
99646
99724
  if (prev) {
99647
- if (prev instanceof Namespace && object19 instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {
99725
+ if (prev instanceof Namespace && object20 instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {
99648
99726
  var nested = prev.nestedArray;
99649
99727
  for (var i = 0; i < nested.length; ++i)
99650
- object19.add(nested[i]);
99728
+ object20.add(nested[i]);
99651
99729
  this.remove(prev);
99652
99730
  if (!this.nested)
99653
99731
  this.nested = {};
99654
- object19.setOptions(prev.options, true);
99732
+ object20.setOptions(prev.options, true);
99655
99733
  } else
99656
- throw Error("duplicate name '" + object19.name + "' in " + this);
99734
+ throw Error("duplicate name '" + object20.name + "' in " + this);
99657
99735
  }
99658
99736
  }
99659
- this.nested[object19.name] = object19;
99737
+ this.nested[object20.name] = object20;
99660
99738
  if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) {
99661
- if (!object19._edition) {
99662
- object19._edition = object19._defaultEdition;
99739
+ if (!object20._edition) {
99740
+ object20._edition = object20._defaultEdition;
99663
99741
  }
99664
99742
  }
99665
99743
  this._needsRecursiveFeatureResolution = true;
@@ -99669,18 +99747,18 @@ var require_namespace = __commonJS({
99669
99747
  parent2._needsRecursiveFeatureResolution = true;
99670
99748
  parent2._needsRecursiveResolve = true;
99671
99749
  }
99672
- object19.onAdd(this);
99750
+ object20.onAdd(this);
99673
99751
  return clearCache(this);
99674
99752
  };
99675
- Namespace.prototype.remove = function remove5(object19) {
99676
- if (!(object19 instanceof ReflectionObject))
99753
+ Namespace.prototype.remove = function remove5(object20) {
99754
+ if (!(object20 instanceof ReflectionObject))
99677
99755
  throw TypeError("object must be a ReflectionObject");
99678
- if (object19.parent !== this)
99679
- throw Error(object19 + " is not a member of " + this);
99680
- delete this.nested[object19.name];
99756
+ if (object20.parent !== this)
99757
+ throw Error(object20 + " is not a member of " + this);
99758
+ delete this.nested[object20.name];
99681
99759
  if (!Object.keys(this.nested).length)
99682
99760
  this.nested = void 0;
99683
- object19.onRemove(this);
99761
+ object20.onRemove(this);
99684
99762
  return clearCache(this);
99685
99763
  };
99686
99764
  Namespace.prototype.define = function define2(path6, json33) {
@@ -100018,27 +100096,27 @@ var require_service2 = __commonJS({
100018
100096
  });
100019
100097
  return this;
100020
100098
  };
100021
- Service.prototype.add = function add(object19) {
100022
- if (this.get(object19.name))
100023
- throw Error("duplicate name '" + object19.name + "' in " + this);
100024
- if (object19 instanceof Method) {
100025
- if (object19.name === "__proto__")
100099
+ Service.prototype.add = function add(object20) {
100100
+ if (this.get(object20.name))
100101
+ throw Error("duplicate name '" + object20.name + "' in " + this);
100102
+ if (object20 instanceof Method) {
100103
+ if (object20.name === "__proto__")
100026
100104
  return this;
100027
- this.methods[object19.name] = object19;
100028
- object19.parent = this;
100105
+ this.methods[object20.name] = object20;
100106
+ object20.parent = this;
100029
100107
  return clearCache(this);
100030
100108
  }
100031
- return Namespace.prototype.add.call(this, object19);
100109
+ return Namespace.prototype.add.call(this, object20);
100032
100110
  };
100033
- Service.prototype.remove = function remove5(object19) {
100034
- if (object19 instanceof Method) {
100035
- if (this.methods[object19.name] !== object19)
100036
- throw Error(object19 + " is not a member of " + this);
100037
- delete this.methods[object19.name];
100038
- object19.parent = null;
100111
+ Service.prototype.remove = function remove5(object20) {
100112
+ if (object20 instanceof Method) {
100113
+ if (this.methods[object20.name] !== object20)
100114
+ throw Error(object20 + " is not a member of " + this);
100115
+ delete this.methods[object20.name];
100116
+ object20.parent = null;
100039
100117
  return clearCache(this);
100040
100118
  }
100041
- return Namespace.prototype.remove.call(this, object19);
100119
+ return Namespace.prototype.remove.call(this, object20);
100042
100120
  };
100043
100121
  Service.prototype.create = function create3(rpcImpl, requestDelimited, responseDelimited) {
100044
100122
  var rpcService = new rpc2.Service(rpcImpl, requestDelimited, responseDelimited);
@@ -100089,8 +100167,8 @@ var require_message = __commonJS({
100089
100167
  Message.verify = function verify4(message7) {
100090
100168
  return this.$type.verify(message7);
100091
100169
  };
100092
- Message.fromObject = function fromObject(object19) {
100093
- return this.$type.fromObject(object19);
100170
+ Message.fromObject = function fromObject(object20) {
100171
+ return this.$type.fromObject(object20);
100094
100172
  };
100095
100173
  Message.toObject = function toObject(message7, options4) {
100096
100174
  return this.$type.toObject(message7, options4);
@@ -100476,26 +100554,26 @@ var require_wrappers = __commonJS({
100476
100554
  var Message = require_message();
100477
100555
  var util = require_minimal();
100478
100556
  wrappers[".google.protobuf.Any"] = {
100479
- fromObject: function(object19, depth) {
100557
+ fromObject: function(object20, depth) {
100480
100558
  if (depth === void 0)
100481
100559
  depth = 0;
100482
100560
  if (depth > util.recursionLimit)
100483
100561
  throw Error("max depth exceeded");
100484
- if (object19 && object19["@type"]) {
100485
- var name5 = object19["@type"].substring(object19["@type"].lastIndexOf("/") + 1);
100562
+ if (object20 && object20["@type"]) {
100563
+ var name5 = object20["@type"].substring(object20["@type"].lastIndexOf("/") + 1);
100486
100564
  var type = this.lookup(name5);
100487
100565
  if (type) {
100488
- var type_url = object19["@type"].charAt(0) === "." ? object19["@type"].slice(1) : object19["@type"];
100566
+ var type_url = object20["@type"].charAt(0) === "." ? object20["@type"].slice(1) : object20["@type"];
100489
100567
  if (type_url.indexOf("/") === -1) {
100490
100568
  type_url = "/" + type_url;
100491
100569
  }
100492
100570
  return this.create({
100493
100571
  type_url,
100494
- value: type.encode(type.fromObject(object19, depth + 1)).finish()
100572
+ value: type.encode(type.fromObject(object20, depth + 1)).finish()
100495
100573
  });
100496
100574
  }
100497
100575
  }
100498
- return this.fromObject(object19, depth);
100576
+ return this.fromObject(object20, depth);
100499
100577
  },
100500
100578
  toObject: function(message7, options4, depth) {
100501
100579
  if (depth === void 0)
@@ -100513,14 +100591,14 @@ var require_wrappers = __commonJS({
100513
100591
  message7 = type.decode(message7.value, void 0, void 0, depth + 1);
100514
100592
  }
100515
100593
  if (!(message7 instanceof this.ctor) && message7 instanceof Message) {
100516
- var object19 = message7.$type.toObject(message7, options4, depth + 1);
100594
+ var object20 = message7.$type.toObject(message7, options4, depth + 1);
100517
100595
  var messageName = message7.$type.fullName[0] === "." ? message7.$type.fullName.slice(1) : message7.$type.fullName;
100518
100596
  if (prefix2 === "") {
100519
100597
  prefix2 = googleApi;
100520
100598
  }
100521
100599
  name5 = prefix2 + messageName;
100522
- object19["@type"] = name5;
100523
- return object19;
100600
+ object20["@type"] = name5;
100601
+ return object20;
100524
100602
  }
100525
100603
  return this.toObject(message7, options4, depth);
100526
100604
  }
@@ -100750,59 +100828,59 @@ var require_type2 = __commonJS({
100750
100828
  return this.nested[name5];
100751
100829
  return null;
100752
100830
  };
100753
- Type.prototype.add = function add(object19) {
100754
- if (this.get(object19.name))
100755
- throw Error("duplicate name '" + object19.name + "' in " + this);
100756
- if (object19 instanceof Field && object19.extend === void 0) {
100831
+ Type.prototype.add = function add(object20) {
100832
+ if (this.get(object20.name))
100833
+ throw Error("duplicate name '" + object20.name + "' in " + this);
100834
+ if (object20 instanceof Field && object20.extend === void 0) {
100757
100835
  if (this._fieldsById ? (
100758
100836
  /* istanbul ignore next */
100759
- this._fieldsById[object19.id]
100760
- ) : this.fieldsById[object19.id])
100761
- throw Error("duplicate id " + object19.id + " in " + this);
100762
- if (this.isReservedId(object19.id))
100763
- throw Error("id " + object19.id + " is reserved in " + this);
100764
- if (this.isReservedName(object19.name) || object19.name.charAt(0) === "$")
100765
- throw Error("name '" + object19.name + "' is reserved in " + this);
100766
- if (object19.name === "__proto__")
100837
+ this._fieldsById[object20.id]
100838
+ ) : this.fieldsById[object20.id])
100839
+ throw Error("duplicate id " + object20.id + " in " + this);
100840
+ if (this.isReservedId(object20.id))
100841
+ throw Error("id " + object20.id + " is reserved in " + this);
100842
+ if (this.isReservedName(object20.name) || object20.name.charAt(0) === "$")
100843
+ throw Error("name '" + object20.name + "' is reserved in " + this);
100844
+ if (object20.name === "__proto__")
100767
100845
  return this;
100768
- if (object19.parent)
100769
- object19.parent.remove(object19);
100770
- this.fields[object19.name] = object19;
100771
- object19.message = this;
100772
- object19.onAdd(this);
100846
+ if (object20.parent)
100847
+ object20.parent.remove(object20);
100848
+ this.fields[object20.name] = object20;
100849
+ object20.message = this;
100850
+ object20.onAdd(this);
100773
100851
  return clearCache(this);
100774
100852
  }
100775
- if (object19 instanceof OneOf) {
100776
- if (object19.name.charAt(0) === "$")
100777
- throw Error("name '" + object19.name + "' is reserved in " + this);
100778
- if (object19.name === "__proto__")
100853
+ if (object20 instanceof OneOf) {
100854
+ if (object20.name.charAt(0) === "$")
100855
+ throw Error("name '" + object20.name + "' is reserved in " + this);
100856
+ if (object20.name === "__proto__")
100779
100857
  return this;
100780
100858
  if (!this.oneofs)
100781
100859
  this.oneofs = {};
100782
- this.oneofs[object19.name] = object19;
100783
- object19.onAdd(this);
100860
+ this.oneofs[object20.name] = object20;
100861
+ object20.onAdd(this);
100784
100862
  return clearCache(this);
100785
100863
  }
100786
- return Namespace.prototype.add.call(this, object19);
100864
+ return Namespace.prototype.add.call(this, object20);
100787
100865
  };
100788
- Type.prototype.remove = function remove5(object19) {
100789
- if (object19 instanceof Field && object19.extend === void 0) {
100790
- if (!this.fields || this.fields[object19.name] !== object19)
100791
- throw Error(object19 + " is not a member of " + this);
100792
- delete this.fields[object19.name];
100793
- object19.parent = null;
100794
- object19.onRemove(this);
100866
+ Type.prototype.remove = function remove5(object20) {
100867
+ if (object20 instanceof Field && object20.extend === void 0) {
100868
+ if (!this.fields || this.fields[object20.name] !== object20)
100869
+ throw Error(object20 + " is not a member of " + this);
100870
+ delete this.fields[object20.name];
100871
+ object20.parent = null;
100872
+ object20.onRemove(this);
100795
100873
  return clearCache(this);
100796
100874
  }
100797
- if (object19 instanceof OneOf) {
100798
- if (!this.oneofs || this.oneofs[object19.name] !== object19)
100799
- throw Error(object19 + " is not a member of " + this);
100800
- delete this.oneofs[object19.name];
100801
- object19.parent = null;
100802
- object19.onRemove(this);
100875
+ if (object20 instanceof OneOf) {
100876
+ if (!this.oneofs || this.oneofs[object20.name] !== object20)
100877
+ throw Error(object20 + " is not a member of " + this);
100878
+ delete this.oneofs[object20.name];
100879
+ object20.parent = null;
100880
+ object20.onRemove(this);
100803
100881
  return clearCache(this);
100804
100882
  }
100805
- return Namespace.prototype.remove.call(this, object19);
100883
+ return Namespace.prototype.remove.call(this, object20);
100806
100884
  };
100807
100885
  Type.prototype.isReservedId = function isReservedId(id14) {
100808
100886
  return Namespace.isReservedId(this.reserved, id14);
@@ -100867,8 +100945,8 @@ var require_type2 = __commonJS({
100867
100945
  Type.prototype.verify = function verify_setup(message7, depth) {
100868
100946
  return this.setup().verify(message7, depth);
100869
100947
  };
100870
- Type.prototype.fromObject = function fromObject(object19, depth) {
100871
- return this.setup().fromObject(object19, depth);
100948
+ Type.prototype.fromObject = function fromObject(object20, depth) {
100949
+ return this.setup().fromObject(object20, depth);
100872
100950
  };
100873
100951
  Type.prototype.toObject = function toObject(message7, options4) {
100874
100952
  return this.setup().toObject.apply(this, arguments);
@@ -101069,65 +101147,65 @@ var require_root = __commonJS({
101069
101147
  }
101070
101148
  return false;
101071
101149
  }
101072
- Root.prototype._handleAdd = function _handleAdd(object19) {
101073
- if (object19 instanceof Field) {
101150
+ Root.prototype._handleAdd = function _handleAdd(object20) {
101151
+ if (object20 instanceof Field) {
101074
101152
  if (
101075
101153
  /* an extension field (implies not part of a oneof) */
101076
- object19.extend !== void 0 && /* not already handled */
101077
- !object19.extensionField
101154
+ object20.extend !== void 0 && /* not already handled */
101155
+ !object20.extensionField
101078
101156
  ) {
101079
- if (!tryHandleExtension(this, object19))
101080
- this.deferred.push(object19);
101081
- }
101082
- } else if (object19 instanceof Enum) {
101083
- if (exposeRe.test(object19.name))
101084
- object19.parent[object19.name] = object19.values;
101085
- } else if (!(object19 instanceof OneOf)) {
101086
- if (object19 instanceof Type)
101157
+ if (!tryHandleExtension(this, object20))
101158
+ this.deferred.push(object20);
101159
+ }
101160
+ } else if (object20 instanceof Enum) {
101161
+ if (exposeRe.test(object20.name))
101162
+ object20.parent[object20.name] = object20.values;
101163
+ } else if (!(object20 instanceof OneOf)) {
101164
+ if (object20 instanceof Type)
101087
101165
  for (var i = 0; i < this.deferred.length; )
101088
101166
  if (tryHandleExtension(this, this.deferred[i]))
101089
101167
  this.deferred.splice(i, 1);
101090
101168
  else
101091
101169
  ++i;
101092
101170
  for (var j = 0; j < /* initializes */
101093
- object19.nestedArray.length; ++j)
101094
- this._handleAdd(object19._nestedArray[j]);
101095
- if (exposeRe.test(object19.name))
101096
- object19.parent[object19.name] = object19;
101171
+ object20.nestedArray.length; ++j)
101172
+ this._handleAdd(object20._nestedArray[j]);
101173
+ if (exposeRe.test(object20.name))
101174
+ object20.parent[object20.name] = object20;
101097
101175
  }
101098
- if (object19 instanceof Type || object19 instanceof Enum || object19 instanceof Field) {
101099
- this._fullyQualifiedObjects[object19.fullName] = object19;
101176
+ if (object20 instanceof Type || object20 instanceof Enum || object20 instanceof Field) {
101177
+ this._fullyQualifiedObjects[object20.fullName] = object20;
101100
101178
  }
101101
101179
  };
101102
- Root.prototype._handleRemove = function _handleRemove(object19) {
101103
- if (object19 instanceof Field) {
101180
+ Root.prototype._handleRemove = function _handleRemove(object20) {
101181
+ if (object20 instanceof Field) {
101104
101182
  if (
101105
101183
  /* an extension field */
101106
- object19.extend !== void 0
101184
+ object20.extend !== void 0
101107
101185
  ) {
101108
101186
  if (
101109
101187
  /* already handled */
101110
- object19.extensionField
101188
+ object20.extensionField
101111
101189
  ) {
101112
- object19.extensionField.parent.remove(object19.extensionField);
101113
- object19.extensionField = null;
101190
+ object20.extensionField.parent.remove(object20.extensionField);
101191
+ object20.extensionField = null;
101114
101192
  } else {
101115
- var index = this.deferred.indexOf(object19);
101193
+ var index = this.deferred.indexOf(object20);
101116
101194
  if (index > -1)
101117
101195
  this.deferred.splice(index, 1);
101118
101196
  }
101119
101197
  }
101120
- } else if (object19 instanceof Enum) {
101121
- if (exposeRe.test(object19.name))
101122
- delete object19.parent[object19.name];
101123
- } else if (object19 instanceof Namespace) {
101198
+ } else if (object20 instanceof Enum) {
101199
+ if (exposeRe.test(object20.name))
101200
+ delete object20.parent[object20.name];
101201
+ } else if (object20 instanceof Namespace) {
101124
101202
  for (var i = 0; i < /* initializes */
101125
- object19.nestedArray.length; ++i)
101126
- this._handleRemove(object19._nestedArray[i]);
101127
- if (exposeRe.test(object19.name))
101128
- delete object19.parent[object19.name];
101203
+ object20.nestedArray.length; ++i)
101204
+ this._handleRemove(object20._nestedArray[i]);
101205
+ if (exposeRe.test(object20.name))
101206
+ delete object20.parent[object20.name];
101129
101207
  }
101130
- delete this._fullyQualifiedObjects[object19.fullName];
101208
+ delete this._fullyQualifiedObjects[object20.fullName];
101131
101209
  };
101132
101210
  Root._configure = function(Type_, parse_, common_) {
101133
101211
  Type = Type_;
@@ -101158,23 +101236,23 @@ var require_util2 = __commonJS({
101158
101236
  throw Error("max depth exceeded");
101159
101237
  return depth;
101160
101238
  };
101161
- util.toArray = function toArray(object19) {
101162
- if (object19) {
101163
- var keys7 = Object.keys(object19), array3 = new Array(keys7.length), index = 0;
101239
+ util.toArray = function toArray(object20) {
101240
+ if (object20) {
101241
+ var keys7 = Object.keys(object20), array3 = new Array(keys7.length), index = 0;
101164
101242
  while (index < keys7.length)
101165
- array3[index] = object19[keys7[index++]];
101243
+ array3[index] = object20[keys7[index++]];
101166
101244
  return array3;
101167
101245
  }
101168
101246
  return [];
101169
101247
  };
101170
101248
  util.toObject = function toObject(array3) {
101171
- var object19 = {}, index = 0;
101249
+ var object20 = {}, index = 0;
101172
101250
  while (index < array3.length) {
101173
101251
  var key4 = array3[index++], val = array3[index++];
101174
101252
  if (val !== void 0)
101175
- object19[key4] = val;
101253
+ object20[key4] = val;
101176
101254
  }
101177
- return object19;
101255
+ return object20;
101178
101256
  };
101179
101257
  util.isReserved = function isReserved(name5) {
101180
101258
  return reservedRe.test(name5);
@@ -101215,14 +101293,14 @@ var require_util2 = __commonJS({
101215
101293
  return type;
101216
101294
  };
101217
101295
  var decorateEnumIndex = 0;
101218
- util.decorateEnum = function decorateEnum(object19) {
101219
- if (object19.$type)
101220
- return object19.$type;
101296
+ util.decorateEnum = function decorateEnum(object20) {
101297
+ if (object20.$type)
101298
+ return object20.$type;
101221
101299
  if (!Enum)
101222
101300
  Enum = require_enum2();
101223
- var enm = new Enum("Enum" + decorateEnumIndex++, object19);
101301
+ var enm = new Enum("Enum" + decorateEnumIndex++, object20);
101224
101302
  util.decorateRoot.add(enm);
101225
- Object.defineProperty(object19, "$type", { value: enm, enumerable: false });
101303
+ Object.defineProperty(object20, "$type", { value: enm, enumerable: false });
101226
101304
  return enm;
101227
101305
  };
101228
101306
  util.setProperty = function setProperty(dst, path6, value4, ifNotSet) {
@@ -121560,7 +121638,7 @@ function invalid8(message7, param4 = null) {
121560
121638
  function unsupported6(message7) {
121561
121639
  throw new AdsError2(501, `ancha: not implemented: ${message7}`, "unsupported_operation");
121562
121640
  }
121563
- function object9(value4, field6 = "body") {
121641
+ function object10(value4, field6 = "body") {
121564
121642
  if (!value4 || typeof value4 !== "object" || Array.isArray(value4)) invalid8(`${field6} must be an object`, field6);
121565
121643
  return value4;
121566
121644
  }
@@ -121706,15 +121784,15 @@ var init_request7 = __esm({
121706
121784
  // packages/server/src/twins/chatgpt-ads/routes.ts
121707
121785
  function targeting2(value4, previous) {
121708
121786
  if (value4 === null) return {};
121709
- const body6 = object9(value4, "targeting");
121787
+ const body6 = object10(value4, "targeting");
121710
121788
  keys3(body6, ["locations", "platforms"], "targeting");
121711
- if (body6.locations !== void 0) keys3(object9(body6.locations, "locations"), ["countries"], "targeting.locations");
121712
- if (body6.platforms !== void 0 && body6.platforms !== null) keys3(object9(body6.platforms, "platforms"), ["included"], "targeting.platforms");
121789
+ if (body6.locations !== void 0) keys3(object10(body6.locations, "locations"), ["countries"], "targeting.locations");
121790
+ if (body6.platforms !== void 0 && body6.platforms !== null) keys3(object10(body6.platforms, "platforms"), ["included"], "targeting.platforms");
121713
121791
  const parsed3 = parse5(ChatGPTAdsTargetingSchema, body6);
121714
121792
  return { ...parsed3, ...!Object.hasOwn(body6, "platforms") && previous?.platforms !== void 0 ? { platforms: previous.platforms } : {} };
121715
121793
  }
121716
121794
  function bidding(value4, campaign2, access5) {
121717
- const body6 = object9(value4, "bidding_config");
121795
+ const body6 = object10(value4, "bidding_config");
121718
121796
  keys3(body6, ["billing_event_type", "strategy", "max_bid_micros"], "bidding_config");
121719
121797
  if (body6.strategy === "maximize_conversions") unsupported6("conversion bidding");
121720
121798
  const bid = parse5(ChatGPTAdsBiddingSchema, body6), billing = campaign2.bidding_type === "clicks" ? "click" : "impression";
@@ -121726,7 +121804,7 @@ function bidding(value4, campaign2, access5) {
121726
121804
  return { ...bid, strategy };
121727
121805
  }
121728
121806
  function creative(value4, access5, creating) {
121729
- const body6 = object9(value4, "creative");
121807
+ const body6 = object10(value4, "creative");
121730
121808
  keys3(body6, ["type", "title", "body", "target_url", "file_id", "price"], "creative");
121731
121809
  if (body6.type !== void 0 && body6.type !== "chat_card") unsupported6(`creative type ${String(body6.type)}`);
121732
121810
  const parsed3 = parse5(ChatGPTAdsCreativeSchema, body6);
@@ -121747,7 +121825,7 @@ function validateSeed(seed43) {
121747
121825
  return parse5(ChatGPTAdsSeedSchema, seed43);
121748
121826
  }
121749
121827
  function mutate2(c, access5, kind, input5, existing2) {
121750
- const body6 = object9(input5), creating = !existing2;
121828
+ const body6 = object10(input5), creating = !existing2;
121751
121829
  keys3(body6, creating ? createFields[kind] : updateFields[kind], kind);
121752
121830
  if (creating && !["active", "paused"].includes(body6.status)) invalid8("Create status must be active or paused", "status");
121753
121831
  if (creating) {
@@ -121764,7 +121842,7 @@ function mutate2(c, access5, kind, input5, existing2) {
121764
121842
  if (kind === "campaigns") {
121765
121843
  if (creating && body6.bidding_type === void 0) candidate.bidding_type = "impressions";
121766
121844
  if (Object.hasOwn(body6, "targeting")) candidate.targeting = targeting2(body6.targeting, existing2?.targeting);
121767
- if (body6.budget !== void 0) keys3(object9(body6.budget, "budget"), ["daily_spend_limit_micros", "lifetime_spend_limit_micros"], "budget");
121845
+ if (body6.budget !== void 0) keys3(object10(body6.budget, "budget"), ["daily_spend_limit_micros", "lifetime_spend_limit_micros"], "budget");
121768
121846
  if (candidate.end_time !== void 0 && candidate.end_time !== null && Number(candidate.end_time) <= Number(candidate.start_time ?? timestamp4)) invalid8("end_time must follow start_time");
121769
121847
  } else if (kind === "adGroups") {
121770
121848
  if (body6.bidding_config !== void 0) candidate.bidding_config = bidding(body6.bidding_config, ancestor ?? find(access5, "campaigns", existing2.campaign_id), access5);
@@ -121853,7 +121931,7 @@ var init_routes = __esm({
121853
121931
  // packages/server/src/twins/chatgpt-ads/insights.ts
121854
121932
  function json7(value4, field6) {
121855
121933
  try {
121856
- return object9(JSON.parse(value4), field6);
121934
+ return object10(JSON.parse(value4), field6);
121857
121935
  } catch (error64) {
121858
121936
  if (error64 instanceof SyntaxError) invalid8(`Invalid JSON in ${field6}`);
121859
121937
  throw error64;
@@ -122047,7 +122125,7 @@ function invalid9(message7) {
122047
122125
  function unsupported7(message7) {
122048
122126
  throw new GA4Error(501, "UNIMPLEMENTED", `ancha: not implemented: ${message7}`);
122049
122127
  }
122050
- function object10(value4, field6) {
122128
+ function object11(value4, field6) {
122051
122129
  if (!value4 || typeof value4 !== "object" || Array.isArray(value4)) invalid9(`${field6} must be an object`);
122052
122130
  return value4;
122053
122131
  }
@@ -122165,7 +122243,7 @@ function selectedFields(raw3, kind, required4 = false) {
122165
122243
  if (raw3 === void 0 && !required4) return [];
122166
122244
  if (!Array.isArray(raw3) || raw3.length > (kind === "dimensions" ? 9 : 10) || required4 && !raw3.length) invalid9(`Invalid ${kind} count`);
122167
122245
  const fields11 = raw3.map((entry2, index) => {
122168
- const item2 = object10(entry2, `${kind}[${index}]`);
122246
+ const item2 = object11(entry2, `${kind}[${index}]`);
122169
122247
  keys4(item2, kind === "dimensions" ? ["name", "dimensionExpression"] : ["name", "expression", "invisible"], kind);
122170
122248
  if (item2.dimensionExpression !== void 0 || item2.expression !== void 0 || item2.invisible === true) unsupported7(`${kind} expressions or invisible metrics`);
122171
122249
  if (item2.invisible !== void 0 && typeof item2.invisible !== "boolean") invalid9("Invalid invisible");
@@ -122258,7 +122336,7 @@ var init_fields = __esm({
122258
122336
 
122259
122337
  // packages/server/src/twins/ga4/filter.ts
122260
122338
  function numeric(value4) {
122261
- const item2 = object10(value4, "NumericValue");
122339
+ const item2 = object11(value4, "NumericValue");
122262
122340
  keys4(item2, ["int64Value", "doubleValue"], "NumericValue");
122263
122341
  if (Object.keys(item2).length !== 1) invalid9("NumericValue must contain exactly one value");
122264
122342
  if (item2.int64Value !== void 0) {
@@ -122275,7 +122353,7 @@ function compileFilter(raw3, kind) {
122275
122353
  let count5 = 0;
122276
122354
  const compile2 = (raw4, depth) => {
122277
122355
  if (depth > 8 || ++count5 > 100) invalid9("Filter exceeds supported depth/node limit");
122278
- const expr = object10(raw4, "FilterExpression");
122356
+ const expr = object11(raw4, "FilterExpression");
122279
122357
  keys4(expr, ["andGroup", "orGroup", "notExpression", "filter"], "FilterExpression");
122280
122358
  if (Object.keys(expr).length !== 1) invalid9("FilterExpression requires exactly one expression");
122281
122359
  if (expr.notExpression !== void 0) {
@@ -122283,18 +122361,18 @@ function compileFilter(raw3, kind) {
122283
122361
  return (read6) => !child2(read6);
122284
122362
  }
122285
122363
  for (const op2 of ["andGroup", "orGroup"]) if (expr[op2] !== void 0) {
122286
- const group5 = object10(expr[op2], op2);
122364
+ const group5 = object11(expr[op2], op2);
122287
122365
  keys4(group5, ["expressions"], op2);
122288
122366
  if (!Array.isArray(group5.expressions) || !group5.expressions.length || group5.expressions.length > 20) invalid9("Invalid filter group");
122289
122367
  const children3 = group5.expressions.map((child2) => compile2(child2, depth + 1));
122290
122368
  return op2 === "andGroup" ? (read6) => children3.every((fn) => fn(read6)) : (read6) => children3.some((fn) => fn(read6));
122291
122369
  }
122292
- const filter4 = object10(expr.filter, "filter");
122370
+ const filter4 = object11(expr.filter, "filter");
122293
122371
  keys4(filter4, ["fieldName", "stringFilter", "inListFilter", "numericFilter", "betweenFilter", "emptyFilter"], "filter");
122294
122372
  const field6 = kind === "dimension" ? dimensionName(filter4.fieldName) : metricName(filter4.fieldName);
122295
122373
  const operators = Object.keys(filter4).filter((key4) => key4 !== "fieldName");
122296
122374
  if (operators.length !== 1) invalid9("Filter requires one operator");
122297
- const op = operators[0], value4 = object10(filter4[op], op);
122375
+ const op = operators[0], value4 = object11(filter4[op], op);
122298
122376
  if (op === "stringFilter") {
122299
122377
  if (kind === "metric") invalid9("stringFilter requires a dimension");
122300
122378
  keys4(value4, ["matchType", "value", "caseSensitive"], "stringFilter");
@@ -122367,7 +122445,7 @@ function date9(value4, property4, ctx) {
122367
122445
  function ranges(raw3, property4, ctx) {
122368
122446
  if (!Array.isArray(raw3) || raw3.length < 1 || raw3.length > 4) invalid9("One to four dateRanges are required");
122369
122447
  const result = raw3.map((entry2, i) => {
122370
- const value4 = object10(entry2, "dateRanges");
122448
+ const value4 = object11(entry2, "dateRanges");
122371
122449
  keys4(value4, ["startDate", "endDate", "name"], "dateRanges");
122372
122450
  const start2 = date9(value4.startDate, property4, ctx), end = date9(value4.endDate, property4, ctx);
122373
122451
  if (end < start2) invalid9("startDate must not be after endDate");
@@ -122390,13 +122468,13 @@ function ordering(raw3, dims, mets) {
122390
122468
  if (raw3 === void 0) raw3 = [];
122391
122469
  if (!Array.isArray(raw3) || raw3.length > 20) invalid9("Invalid orderBys");
122392
122470
  const comparisons = raw3.map((entry2) => {
122393
- const value4 = object10(entry2, "orderBys");
122471
+ const value4 = object11(entry2, "orderBys");
122394
122472
  keys4(value4, ["dimension", "metric", "pivot", "desc"], "orderBys");
122395
122473
  if (value4.pivot !== void 0) unsupported7("pivot order");
122396
122474
  if (value4.dimension === void 0 === (value4.metric === void 0)) invalid9("Specify one dimension or metric order");
122397
122475
  const sign3 = bool2(value4.desc, "orderBys.desc") ? -1 : 1;
122398
122476
  if (value4.dimension !== void 0) {
122399
- const order7 = object10(value4.dimension, "dimension order");
122477
+ const order7 = object11(value4.dimension, "dimension order");
122400
122478
  keys4(order7, ["dimensionName", "orderType"], "dimension order");
122401
122479
  const name5 = order7.dimensionName === "dateRange" ? "dateRange" : dimensionName(order7.dimensionName), index2 = dims.indexOf(name5);
122402
122480
  if (index2 < 0) invalid9("Ordered dimension must be selected");
@@ -122411,7 +122489,7 @@ function ordering(raw3, dims, mets) {
122411
122489
  return sign3 * lexical(type === "CASE_INSENSITIVE_ALPHANUMERIC" ? left.toLowerCase() : left, type === "CASE_INSENSITIVE_ALPHANUMERIC" ? right.toLowerCase() : right);
122412
122490
  };
122413
122491
  }
122414
- const order6 = object10(value4.metric, "metric order");
122492
+ const order6 = object11(value4.metric, "metric order");
122415
122493
  keys4(order6, ["metricName"], "metric order");
122416
122494
  const index = mets.indexOf(metricName(order6.metricName));
122417
122495
  if (index < 0) invalid9("Ordered metric must be selected");
@@ -122426,7 +122504,7 @@ function ordering(raw3, dims, mets) {
122426
122504
  };
122427
122505
  }
122428
122506
  function report2(ctx, property4, raw3, batch3 = false) {
122429
- const value4 = object10(raw3, "RunReportRequest");
122507
+ const value4 = object11(raw3, "RunReportRequest");
122430
122508
  keys4(value4, ["property", "dimensions", "metrics", "dateRanges", "dimensionFilter", "metricFilter", "offset", "limit", "metricAggregations", "orderBys", "currencyCode", "keepEmptyRows", "returnPropertyQuota", "cohortSpec", "comparisons"], "RunReportRequest");
122431
122509
  if (value4.property !== void 0 && (!batch3 || value4.property !== `properties/${property4.id}`)) invalid9("Property must be specified in the path and match the batch");
122432
122510
  if (value4.cohortSpec !== void 0 || value4.comparisons !== void 0) unsupported7("cohorts or comparisons");
@@ -122516,14 +122594,14 @@ var init_ga42 = __esm({
122516
122594
  return { ...result.response, ...result.returnQuota ? { propertyQuota: used } : {} };
122517
122595
  } },
122518
122596
  { method: "POST", path: "/v1beta/properties/:property{[0-9]+:batchRunReports}", notes: "One to five reports for one property; prevalidate all reports before local quota debit.", run: (c, body6) => {
122519
- const p2 = property2(c, c.req.param("property").split(":")[0]), value4 = object10(body6, "BatchRunReportsRequest");
122597
+ const p2 = property2(c, c.req.param("property").split(":")[0]), value4 = object11(body6, "BatchRunReportsRequest");
122520
122598
  keys4(value4, ["requests"], "BatchRunReportsRequest");
122521
122599
  if (!Array.isArray(value4.requests) || !value4.requests.length || value4.requests.length > 5) invalid9("Batch requires one to five report requests");
122522
122600
  const results = value4.requests.map((request2) => report2(c.env.ctx, p2, request2, true)), used = quota(c.env.ctx, p2.id, results.length);
122523
122601
  return { kind: "analyticsData#batchRunReports", reports: results.map((result) => ({ ...result.response, ...result.returnQuota ? { propertyQuota: used } : {} })) };
122524
122602
  } },
122525
122603
  { method: "POST", path: "/v1beta/properties/:property{[0-9]+:checkCompatibility}", notes: "Compatibility only within the supported metadata subset; all supported combinations are compatible. Unknown fields expose gaps.", run: (c, body6) => {
122526
- const p2 = property2(c, c.req.param("property").split(":")[0]), value4 = object10(body6, "CheckCompatibilityRequest");
122604
+ const p2 = property2(c, c.req.param("property").split(":")[0]), value4 = object11(body6, "CheckCompatibilityRequest");
122527
122605
  keys4(value4, ["dimensions", "metrics", "dimensionFilter", "metricFilter", "compatibilityFilter"], "CheckCompatibilityRequest");
122528
122606
  selectedFields(value4.dimensions, "dimensions");
122529
122607
  selectedFields(value4.metrics, "metrics");
@@ -124298,13 +124376,13 @@ function target(ctx, value4) {
124298
124376
  function parse7(c, body6, version5, old) {
124299
124377
  query4(c, []);
124300
124378
  const ctx = c.env.ctx, now11 = ctx.clock.now().getTime();
124301
- let attrs = object7(body6, "body");
124379
+ let attrs = object8(body6, "body");
124302
124380
  if (version5 === 2) {
124303
124381
  keys2(attrs, ["data"], "body");
124304
- const data5 = object7(attrs.data, "data");
124382
+ const data5 = object8(attrs.data, "data");
124305
124383
  keys2(data5, ["type", "id", "attributes"], "data");
124306
124384
  if (data5.type !== "downtime" || (old ? data5.id !== old.uuid : data5.id !== void 0)) throw new DatadogError(400, "Invalid downtime type or id");
124307
- attrs = object7(data5.attributes, "attributes");
124385
+ attrs = object8(data5.attributes, "attributes");
124308
124386
  }
124309
124387
  keys2(attrs, version5 === 1 ? ["scope", "monitor_id", "monitor_tags", "start", "end", "message", "timezone", "mute_first_recovery_notification", "notify_end_types", "notify_end_states"] : ["scope", "monitor_identifier", "schedule", "message", "display_timezone", "mute_first_recovery_notification", "notify_end_types", "notify_end_states"], "downtime");
124310
124388
  if (!old && attrs.scope === void 0) throw new DatadogError(400, "scope is required");
@@ -124319,7 +124397,7 @@ function parse7(c, body6, version5, old) {
124319
124397
  monitorId = null;
124320
124398
  }
124321
124399
  } else if (attrs.monitor_identifier !== void 0) {
124322
- const identifier4 = object7(attrs.monitor_identifier, "monitor_identifier");
124400
+ const identifier4 = object8(attrs.monitor_identifier, "monitor_identifier");
124323
124401
  keys2(identifier4, ["monitor_id", "monitor_tags"], "monitor_identifier");
124324
124402
  if (Object.keys(identifier4).length !== 1) throw new DatadogError(400, "Specify exactly one monitor identifier");
124325
124403
  if (identifier4.monitor_id !== void 0) monitorId = target(ctx, identifier4.monitor_id);
@@ -124329,7 +124407,7 @@ function parse7(c, body6, version5, old) {
124329
124407
  monitorId = null;
124330
124408
  }
124331
124409
  } else if (!old && version5 === 2) throw new DatadogError(400, "monitor_identifier is required");
124332
- const schedule3 = version5 === 1 ? attrs : attrs.schedule === void 0 ? {} : object7(attrs.schedule, "schedule");
124410
+ const schedule3 = version5 === 1 ? attrs : attrs.schedule === void 0 ? {} : object8(attrs.schedule, "schedule");
124333
124411
  if (version5 === 2) keys2(schedule3, ["start", "end"], "schedule");
124334
124412
  const start2 = schedule3.start === void 0 ? old?.start ?? now11 : timestamp2(schedule3.start, version5, "start");
124335
124413
  if (schedule3.end === void 0 && !old) unsupported4("indefinite downtime; provide a finite end");
@@ -124742,7 +124820,7 @@ function listEvents(c) {
124742
124820
  }
124743
124821
  function createEvent(c, input5) {
124744
124822
  query4(c, []);
124745
- const body6 = object7(input5, "event");
124823
+ const body6 = object8(input5, "event");
124746
124824
  const title2 = string5(body6.title, "title"), text25 = string5(body6.text, "text");
124747
124825
  if (text25.length > 4e3) throw new DatadogError(400, "Event text exceeds 4000 characters");
124748
124826
  const now11 = c.env.ctx.clock.nowMs();
@@ -124777,10 +124855,10 @@ function find2(c, id14) {
124777
124855
  return row2;
124778
124856
  }
124779
124857
  function attributes(input5, create3, id14) {
124780
- const body6 = object7(input5, "body"), data5 = object7(body6.data, "data");
124858
+ const body6 = object8(input5, "body"), data5 = object8(body6.data, "data");
124781
124859
  if (data5.type !== "incidents") throw new DatadogError(400, "Invalid data.type: expected incidents");
124782
124860
  if (!create3 && incidentId(data5.id) !== id14) throw new DatadogError(400, "Incident id does not match URL");
124783
- const attrs = object7(data5.attributes === void 0 && !create3 ? {} : data5.attributes, "data.attributes");
124861
+ const attrs = object8(data5.attributes === void 0 && !create3 ? {} : data5.attributes, "data.attributes");
124784
124862
  const title2 = attrs.title === void 0 && !create3 ? void 0 : string5(attrs.title, "title");
124785
124863
  if ((create3 || attrs.customer_impacted !== void 0) && typeof attrs.customer_impacted !== "boolean") throw new DatadogError(400, "Invalid customer_impacted: expected boolean");
124786
124864
  if (attrs.customer_impact_scope !== void 0 && typeof attrs.customer_impact_scope !== "string") throw new DatadogError(400, "Invalid customer_impact_scope");
@@ -124788,9 +124866,9 @@ function attributes(input5, create3, id14) {
124788
124866
  if ("state" in attrs || "severity" in attrs || "status" in attrs) throw new DatadogError(400, "Incident state and severity belong in attributes.fields");
124789
124867
  let state3, severity;
124790
124868
  if (attrs.fields !== void 0) {
124791
- const fields11 = object7(attrs.fields, "fields");
124869
+ const fields11 = object8(attrs.fields, "fields");
124792
124870
  for (const [name5, value4] of Object.entries(fields11)) {
124793
- const field6 = object7(value4, `fields.${name5}`);
124871
+ const field6 = object8(value4, `fields.${name5}`);
124794
124872
  if (name5 !== "state" && name5 !== "severity") unsupported4(`incident field ${name5}`);
124795
124873
  if (typeof field6.value !== "string") throw new DatadogError(400, `Invalid fields.${name5}.value`);
124796
124874
  if (field6.type !== void 0 && field6.type !== "dropdown") {
@@ -124943,10 +125021,10 @@ async function searchLogs(c) {
124943
125021
  }
124944
125022
  function listLogs(c, input5) {
124945
125023
  query4(c, []);
124946
- const body6 = object7(input5, "logs search");
124947
- const filter4 = body6.filter === void 0 ? {} : object7(body6.filter, "filter");
124948
- const page18 = body6.page === void 0 ? {} : object7(body6.page, "page");
124949
- const options4 = body6.options === void 0 ? {} : object7(body6.options, "options");
125024
+ const body6 = object8(input5, "logs search");
125025
+ const filter4 = body6.filter === void 0 ? {} : object8(body6.filter, "filter");
125026
+ const page18 = body6.page === void 0 ? {} : object8(body6.page, "page");
125027
+ const options4 = body6.options === void 0 ? {} : object8(body6.options, "options");
124950
125028
  const from = filter4.from === void 0 ? "now-15m" : string5(filter4.from, "filter.from");
124951
125029
  const to = filter4.to === void 0 ? "now" : string5(filter4.to, "filter.to");
124952
125030
  const source = filter4.query === void 0 ? "*" : string5(filter4.query, "filter.query");
@@ -127473,7 +127551,7 @@ function errorBody2(e) {
127473
127551
  function errorResponse3(e) {
127474
127552
  return json8(errorBody2(e), e.status, e.gap ? { [GAP_HEADER]: "1" } : {});
127475
127553
  }
127476
- function object11(input5) {
127554
+ function object12(input5) {
127477
127555
  if (!input5 || typeof input5 !== "object" || Array.isArray(input5)) invalid12("Expected an object");
127478
127556
  return input5;
127479
127557
  }
@@ -127676,11 +127754,11 @@ function create(ctx, kind, account9, body6) {
127676
127754
  }
127677
127755
  function update3(ctx, kind, account9, id14, body6) {
127678
127756
  access(ctx, account9, true);
127679
- const row2 = find3(ctx, kind, id14, account9), original2 = value2(row2), root3 = object11(body6);
127757
+ const row2 = find3(ctx, kind, id14, account9), original2 = value2(row2), root3 = object12(body6);
127680
127758
  fields6(root3, ["patch"]);
127681
- const patch = object11(root3.patch);
127759
+ const patch = object12(root3.patch);
127682
127760
  fields6(patch, ["$set"]);
127683
- const changes = object11(patch.$set);
127761
+ const changes = object12(patch.$set);
127684
127762
  fields6(changes, mutable[kind]);
127685
127763
  if (!Object.keys(changes).length) invalid12("patch.$set must not be empty");
127686
127764
  if ((original2.status === "CANCELED" || original2.intendedStatus === "CANCELED") && (changes.status || changes.intendedStatus)) invalid12("Cannot reactivate a canceled entity");
@@ -127745,7 +127823,7 @@ function collectionWrite(kind, c, body6) {
127745
127823
  const op = method(c, ["CREATE", "BATCH_CREATE"]);
127746
127824
  if (op === "BATCH_CREATE") {
127747
127825
  if (kind === "creatives") gap3("creative batch create");
127748
- const b = object11(body6);
127826
+ const b = object12(body6);
127749
127827
  fields6(b, ["elements"]);
127750
127828
  if (!Array.isArray(b.elements) || !b.elements.length || b.elements.length > 100) invalid12("elements must contain 1..100 objects");
127751
127829
  let hasGap = false;
@@ -127974,7 +128052,7 @@ import { createHash as createHash18, createHmac as createHmac2, timingSafeEqual
127974
128052
  function unsupported9(message7) {
127975
128053
  throw new GongError(501, `ancha: not implemented: ${message7}`);
127976
128054
  }
127977
- function object12(value4, field6) {
128055
+ function object13(value4, field6) {
127978
128056
  if (!value4 || typeof value4 !== "object" || Array.isArray(value4)) throw new GongError(400, `Invalid ${field6}: expected object`);
127979
128057
  return value4;
127980
128058
  }
@@ -128108,7 +128186,7 @@ var init_request10 = __esm({
128108
128186
 
128109
128187
  // packages/server/src/twins/gong/routes.ts
128110
128188
  function filter2(raw3, mode) {
128111
- const value4 = object12(raw3, "filter");
128189
+ const value4 = object13(raw3, "filter");
128112
128190
  keys5(value4, ["fromDateTime", "toDateTime", "workspaceId", ...mode === "basic" ? [] : ["callIds"], ...mode === "extensive" ? ["primaryUserIds"] : []], "filter");
128113
128191
  if (mode === "basic" && (value4.fromDateTime === void 0 || value4.toDateTime === void 0)) throw new GongError(400, "fromDateTime and toDateTime are required");
128114
128192
  const parsed3 = {
@@ -128132,20 +128210,20 @@ function nonempty(values2) {
128132
128210
  return values2;
128133
128211
  }
128134
128212
  function selector(raw3) {
128135
- const value4 = raw3 === void 0 ? {} : object12(raw3, "contentSelector");
128213
+ const value4 = raw3 === void 0 ? {} : object13(raw3, "contentSelector");
128136
128214
  keys5(value4, ["context", "contextTiming", "exposedFields"], "contentSelector");
128137
128215
  const context3 = value4.context === void 0 ? "None" : value4.context;
128138
128216
  if (!["None", "Basic", "Extended"].includes(context3)) throw new GongError(400, "Invalid contentSelector.context");
128139
128217
  const timing = value4.contextTiming === void 0 ? ["Now"] : value4.contextTiming;
128140
128218
  if (!Array.isArray(timing) || timing.length < 1 || timing.length > 2 || timing.some((v) => !["Now", "TimeOfCall"].includes(v)) || new Set(timing).size !== timing.length) throw new GongError(400, "Invalid contentSelector.contextTiming");
128141
128219
  if (value4.contextTiming !== void 0 && context3 !== "Extended") throw new GongError(400, "contextTiming requires Extended context");
128142
- const exposed = value4.exposedFields === void 0 ? {} : object12(value4.exposedFields, "contentSelector.exposedFields");
128220
+ const exposed = value4.exposedFields === void 0 ? {} : object13(value4.exposedFields, "contentSelector.exposedFields");
128143
128221
  keys5(exposed, ["parties", "content", "interaction", "collaboration", "media"], "contentSelector.exposedFields");
128144
128222
  for (const name5 of ["parties", "media"]) if (exposed[name5] !== void 0 && typeof exposed[name5] !== "boolean") throw new GongError(400, `Invalid exposedFields.${name5}`);
128145
128223
  if (exposed.media === true) unsupported9("contentSelector.exposedFields.media");
128146
128224
  const unsupportedFields = { content: ["structure", "topics", "trackers", "trackerOccurrences", "pointsOfInterest", "brief", "outline", "highlights", "callOutcome", "keyPoints"], interaction: ["speakers", "video", "personInteractionStats", "questions"], collaboration: ["publicComments"] };
128147
128225
  for (const [name5, allowed2] of Object.entries(unsupportedFields)) if (exposed[name5] !== void 0) {
128148
- const fields11 = object12(exposed[name5], `exposedFields.${name5}`);
128226
+ const fields11 = object13(exposed[name5], `exposedFields.${name5}`);
128149
128227
  keys5(fields11, allowed2, `exposedFields.${name5}`);
128150
128228
  for (const [field6, requested2] of Object.entries(fields11)) {
128151
128229
  if (typeof requested2 !== "boolean") throw new GongError(400, `Invalid exposedFields.${name5}.${field6}`);
@@ -128175,7 +128253,7 @@ function extensive(call2, selected2) {
128175
128253
  }
128176
128254
  function post2(c, raw3, allowed2) {
128177
128255
  query7(c, []);
128178
- const value4 = object12(raw3, "body");
128256
+ const value4 = object13(raw3, "body");
128179
128257
  keys5(value4, allowed2, "body");
128180
128258
  return value4;
128181
128259
  }
@@ -136611,8 +136689,8 @@ import { createHash as createHash29 } from "node:crypto";
136611
136689
  function invalid15(message7, param4, code2) {
136612
136690
  throw new StripeError(400, "invalid_request_error", message7, { ...code2 && { code: code2, doc_url: docs(code2) }, ...param4 && { param: param4 } });
136613
136691
  }
136614
- function missing2(object19, id14, param4 = "id", detail3 = "") {
136615
- throw new StripeError(404, "invalid_request_error", `No such ${object19}: '${id14}'${detail3}`, { code: "resource_missing", doc_url: docs("resource_missing"), param: param4 });
136692
+ function missing2(object20, id14, param4 = "id", detail3 = "") {
136693
+ throw new StripeError(404, "invalid_request_error", `No such ${object20}: '${id14}'${detail3}`, { code: "resource_missing", doc_url: docs("resource_missing"), param: param4 });
136616
136694
  }
136617
136695
  function unsupported14(what) {
136618
136696
  throw new StripeError(501, "api_error", `ancha: not implemented: ${what}`, {}, true);
@@ -136638,7 +136716,7 @@ function oneOf(value4, param4, values2) {
136638
136716
  if (typeof value4 !== "string" || !values2.includes(value4)) invalid15(`Invalid ${param4}: must be one of ${values2.slice(0, -1).join(", ")}, or ${values2[values2.length - 1]}`, param4);
136639
136717
  return value4;
136640
136718
  }
136641
- function object13(value4, param4, allowed2) {
136719
+ function object14(value4, param4, allowed2) {
136642
136720
  if (value4 === void 0 || value4 === "") return void 0;
136643
136721
  if (typeof value4 !== "object" || Array.isArray(value4)) invalid15(`Invalid object: ${param4}`, param4);
136644
136722
  for (const key4 of Object.keys(value4)) if (!allowed2.includes(key4)) unsupported14(`parameter ${param4}[${key4}]`);
@@ -136671,7 +136749,7 @@ function range(value4, param4) {
136671
136749
  const n2 = int2(value4, param4);
136672
136750
  return (x) => x === n2;
136673
136751
  }
136674
- const bounds = object13(value4, param4, ["gt", "gte", "lt", "lte"]);
136752
+ const bounds = object14(value4, param4, ["gt", "gte", "lt", "lte"]);
136675
136753
  const b = Object.fromEntries(Object.entries(bounds).map(([k, v]) => [k, int2(v, `${param4}[${k}]`)]));
136676
136754
  return (x) => (b.gt === void 0 || x > b.gt) && (b.gte === void 0 || x >= b.gte) && (b.lt === void 0 || x < b.lt) && (b.lte === void 0 || x <= b.lte);
136677
136755
  }
@@ -137632,11 +137710,11 @@ function clauses(query10, resource2) {
137632
137710
  if (pos < query10.length && !/\s/.test(query10[pos])) invalid15(`Invalid search query: ${query10}`, "query");
137633
137711
  while (pos < query10.length && /\s/.test(query10[pos])) pos++;
137634
137712
  if (pos === query10.length) break;
137635
- const join22 = /^(AND|OR)\b/.exec(query10.slice(pos));
137636
- joins.add(join22?.[1] ?? "AND");
137713
+ const join23 = /^(AND|OR)\b/.exec(query10.slice(pos));
137714
+ joins.add(join23?.[1] ?? "AND");
137637
137715
  if (joins.size > 1) invalid15("Search queries cannot mix AND and OR.", "query");
137638
- if (join22) {
137639
- pos += join22[0].length;
137716
+ if (join23) {
137717
+ pos += join23[0].length;
137640
137718
  if (!query10.slice(pos).trim()) invalid15(`Invalid search query: ${query10}`, "query");
137641
137719
  }
137642
137720
  }
@@ -137704,7 +137782,7 @@ function customFields(value4) {
137704
137782
  if (value4 === void 0) return void 0;
137705
137783
  if (value4 === "") return null;
137706
137784
  const fields11 = list10(value4, "custom_fields").map((f2, i) => {
137707
- const field6 = object13(f2, `custom_fields[${i}]`, ["name", "value"]);
137785
+ const field6 = object14(f2, `custom_fields[${i}]`, ["name", "value"]);
137708
137786
  const name5 = str(field6.name, `custom_fields[${i}][name]`, 40), v = str(field6.value, `custom_fields[${i}][value]`, 140);
137709
137787
  if (!name5 || !v) invalid15("Each custom field needs a name and a value.", `custom_fields[${i}]`);
137710
137788
  return { name: name5, value: v };
@@ -137728,7 +137806,7 @@ function customerFields(r2, c) {
137728
137806
  }
137729
137807
  if ("preferred_locales" in p2) c.preferred_locales = (list10(p2.preferred_locales, "preferred_locales") ?? []).map((l, i) => str(l, `preferred_locales[${i}]`));
137730
137808
  c.metadata = mergeMetadata(c.metadata, p2.metadata);
137731
- const settings = object13(p2.invoice_settings, "invoice_settings", ["default_payment_method"]);
137809
+ const settings = object14(p2.invoice_settings, "invoice_settings", ["default_payment_method"]);
137732
137810
  if (p2.payment_method !== void 0) {
137733
137811
  const pm = resolvePaymentMethod(r2.ctx, str(p2.payment_method, "payment_method"), c);
137734
137812
  save6(r2.ctx, { ...pm, customer: c.id });
@@ -137822,7 +137900,7 @@ var init_routes9 = __esm({
137822
137900
  if (proration === "always_invoice") unsupported14("proration_behavior=always_invoice");
137823
137901
  sub2.metadata = mergeMetadata(sub2.metadata, r2.params.metadata);
137824
137902
  if ("description" in r2.params) sub2.description = str(r2.params.description, "description", 500) || null;
137825
- const details = object13(r2.params.cancellation_details, "cancellation_details", ["comment", "feedback"]);
137903
+ const details = object14(r2.params.cancellation_details, "cancellation_details", ["comment", "feedback"]);
137826
137904
  if (details) sub2.cancellation_details = {
137827
137905
  ...sub2.cancellation_details,
137828
137906
  ...details.comment !== void 0 && { comment: str(details.comment, "cancellation_details[comment]") || null },
@@ -137834,7 +137912,7 @@ var init_routes9 = __esm({
137834
137912
  if (changes) {
137835
137913
  const now11 = nowSeconds(r2.ctx);
137836
137914
  changes.forEach((value4, i) => {
137837
- const change3 = object13(value4, `items[${i}]`, ["id", "price", "quantity", "deleted", "metadata"]);
137915
+ const change3 = object14(value4, `items[${i}]`, ["id", "price", "quantity", "deleted", "metadata"]);
137838
137916
  const id14 = str(change3.id, `items[${i}][id]`), priceId = str(change3.price, `items[${i}][price]`), quantity = int2(change3.quantity, `items[${i}][quantity]`), remove5 = bool3(change3.deleted, `items[${i}][deleted]`);
137839
137917
  if (quantity !== void 0 && quantity < 0) invalid15("Invalid quantity: must be greater than or equal to 0", `items[${i}][quantity]`);
137840
137918
  const newPrice = priceId ? find4(r2.ctx, "price", priceId) : void 0;
@@ -137876,7 +137954,7 @@ var init_routes9 = __esm({
137876
137954
  if (sub2.status === "canceled") invalid15("A canceled subscription can only update its cancellation_details and metadata.");
137877
137955
  if (bool3(r2.params.invoice_now, "invoice_now")) unsupported14("cancel with invoice_now=true");
137878
137956
  if (bool3(r2.params.prorate, "prorate")) unsupported14("cancel with prorate=true");
137879
- const details = object13(r2.params.cancellation_details, "cancellation_details", ["comment", "feedback"]);
137957
+ const details = object14(r2.params.cancellation_details, "cancellation_details", ["comment", "feedback"]);
137880
137958
  const at3 = nowSeconds(r2.ctx);
137881
137959
  Object.assign(sub2, {
137882
137960
  status: "canceled",
@@ -137964,7 +138042,7 @@ var init_routes9 = __esm({
137964
138042
  const p2 = r2.params;
137965
138043
  if (p2.customer === void 0) invalid15("Missing required param: customer.", "customer", "parameter_missing");
137966
138044
  const c = liveCustomer(r2.ctx, str(p2.customer, "customer"));
137967
- const pricing = object13(p2.pricing, "pricing", ["price"]);
138045
+ const pricing = object14(p2.pricing, "pricing", ["price"]);
137968
138046
  const price3 = pricing?.price !== void 0 ? find4(r2.ctx, "price", str(pricing.price, "pricing[price]")) : null;
137969
138047
  const amount3 = int2(p2.amount, "amount"), quantity = int2(p2.quantity, "quantity") ?? 1;
137970
138048
  if (price3 && amount3 !== void 0) invalid15("You may only specify one of these parameters: amount, pricing[price].", "amount");
@@ -137975,7 +138053,7 @@ var init_routes9 = __esm({
137975
138053
  const inv = p2.invoice !== void 0 ? find4(r2.ctx, "invoice", str(p2.invoice, "invoice")) : null;
137976
138054
  if (inv && inv.customer !== c.id) invalid15(`The invoice ${inv.id} belongs to a different customer.`, "invoice");
137977
138055
  if (inv && inv.status !== "draft") invalid15(`You can only add invoice items to draft invoices; ${inv.id} is ${inv.status}.`, "invoice", "invoice_not_editable");
137978
- const periodValue = object13(p2.period, "period", ["start", "end"]);
138056
+ const periodValue = object14(p2.period, "period", ["start", "end"]);
137979
138057
  const now11 = nowSeconds(r2.ctx), period2 = periodValue ? { start: int2(periodValue.start, "period[start]"), end: int2(periodValue.end, "period[end]") } : { start: now11, end: now11 };
137980
138058
  const item2 = save6(r2.ctx, invoiceItem(r2.ctx, {
137981
138059
  customer: c.id,
@@ -138016,7 +138094,7 @@ var init_routes9 = __esm({
138016
138094
  const c = p2.customer !== void 0 ? liveCustomer(r2.ctx, str(p2.customer, "customer")) : null;
138017
138095
  const types = list10(p2.payment_method_types, "payment_method_types")?.map((t, i) => str(t, `payment_method_types[${i}]`));
138018
138096
  if (types && types.some((t) => t !== "card")) unsupported14(`payment_method_types other than card (${types.join(", ")})`);
138019
- const auto = object13(p2.automatic_payment_methods, "automatic_payment_methods", ["enabled", "allow_redirects"]);
138097
+ const auto = object14(p2.automatic_payment_methods, "automatic_payment_methods", ["enabled", "allow_redirects"]);
138020
138098
  bool3(p2.off_session, "off_session");
138021
138099
  const pm = p2.payment_method !== void 0 ? resolvePaymentMethod(r2.ctx, str(p2.payment_method, "payment_method"), c) : void 0;
138022
138100
  const pi = save6(r2.ctx, paymentIntent(r2.ctx, {
@@ -138526,11 +138604,11 @@ function balance(ctx, args) {
138526
138604
  function unchanged(ctx, args) {
138527
138605
  const baseline = account5(ctx).__baseline;
138528
138606
  if (baseline === void 0) throw new AnchaError("USAGE", "Stripe seed baseline is absent from this checkpoint", { hint: "create a fresh world to evaluate stripe.unchanged" });
138529
- const changes = args.objects.flatMap((object19) => {
138530
- const row2 = resolve5(ctx, object19.type, object19.id);
138607
+ const changes = args.objects.flatMap((object20) => {
138608
+ const row2 = resolve5(ctx, object20.type, object20.id);
138531
138609
  const before = row2 && baseline?.[row2.id];
138532
138610
  const reason2 = !row2 ? "object absent" : !before ? "seed baseline absent" : !isDeepStrictEqual(present(row2), before) ? "object changed" : void 0;
138533
- return reason2 ? [{ ...object19, reason: reason2 }] : [];
138611
+ return reason2 ? [{ ...object20, reason: reason2 }] : [];
138534
138612
  });
138535
138613
  return checkOutcome(changes.length === 0, `objects unchanged from seed: ${JSON.stringify(args.objects)}`, changes.length ? JSON.stringify(changes) : "all named objects equal their seed state");
138536
138614
  }
@@ -142140,14 +142218,14 @@ function writeAll(r2, parentId, attributes2, values2, mode, objectSlug) {
142140
142218
  if (attr.is_required && !currentValues(r2.ctx, parentId, attr.id).length) invalid19(`Required value for attribute with slug "${attr.api_slug}" was not provided.`, "missing_value");
142141
142219
  }
142142
142220
  }
142143
- function findRecord(r2, object19) {
142221
+ function findRecord(r2, object20) {
142144
142222
  const id14 = r2.param("record_id");
142145
- return one2(r2.ctx, "SELECT * FROM attio_records WHERE id = ? AND object_id = ?", id14, object19.id) ?? notFound9(`Record with ID "${id14}" not found.`);
142223
+ return one2(r2.ctx, "SELECT * FROM attio_records WHERE id = ? AND object_id = ?", id14, object20.id) ?? notFound9(`Record with ID "${id14}" not found.`);
142146
142224
  }
142147
- function createRecord3(r2, object19, values2) {
142225
+ function createRecord3(r2, object20, values2) {
142148
142226
  const id14 = uuid9(r2.ctx);
142149
- run2(r2.ctx, "INSERT INTO attio_records (id, object_id, created_at, created_by) VALUES (?, ?, ?, ?)", id14, object19.id, now5(r2.ctx), JSON.stringify(tokenActor(r2)));
142150
- writeAll(r2, id14, attributesOf(r2.ctx, object19.id), values2, "create", object19.api_slug);
142227
+ run2(r2.ctx, "INSERT INTO attio_records (id, object_id, created_at, created_by) VALUES (?, ?, ?, ?)", id14, object20.id, now5(r2.ctx), JSON.stringify(tokenActor(r2)));
142228
+ writeAll(r2, id14, attributesOf(r2.ctx, object20.id), values2, "create", object20.api_slug);
142151
142229
  return one2(r2.ctx, "SELECT * FROM attio_records WHERE id = ?", id14);
142152
142230
  }
142153
142231
  function query8(r2, rows8, attributes2) {
@@ -142192,10 +142270,10 @@ function memberRef(r2, value4) {
142192
142270
  function linkedRecords(r2, value4) {
142193
142271
  if (!Array.isArray(value4)) invalid19("linked_records must be an array.");
142194
142272
  return value4.map((l) => {
142195
- const object19 = findObject(r2.ctx, String(l?.target_object));
142273
+ const object20 = findObject(r2.ctx, String(l?.target_object));
142196
142274
  if (!l.target_record_id) unsupported18("linking tasks to records by a matching attribute");
142197
- const record13 = one2(r2.ctx, "SELECT * FROM attio_records WHERE id = ? AND object_id = ?", l.target_record_id, object19.id) ?? notFound9(`Record with ID "${l.target_record_id}" not found.`);
142198
- return { target_object_id: object19.id, target_record_id: record13.id };
142275
+ const record13 = one2(r2.ctx, "SELECT * FROM attio_records WHERE id = ? AND object_id = ?", l.target_record_id, object20.id) ?? notFound9(`Record with ID "${l.target_record_id}" not found.`);
142276
+ return { target_object_id: object20.id, target_record_id: record13.id };
142199
142277
  });
142200
142278
  }
142201
142279
  var now5, tokenActor, records, deadline, RECORD_PATH, attioRoutes;
@@ -142208,7 +142286,7 @@ var init_routes13 = __esm({
142208
142286
  init_values();
142209
142287
  now5 = (ctx) => attioTime(ctx.clock.nowMs());
142210
142288
  tokenActor = (r2) => ({ type: "api-token", id: r2.ctx.store.meta.get("attio.token_id") });
142211
- records = (r2, object19) => all5(r2.ctx, "SELECT * FROM attio_records WHERE object_id = ? ORDER BY created_at, rowid", object19.id);
142289
+ records = (r2, object20) => all5(r2.ctx, "SELECT * FROM attio_records WHERE object_id = ? ORDER BY created_at, rowid", object20.id);
142212
142290
  deadline = (value4) => {
142213
142291
  if (value4 === null) return null;
142214
142292
  if (typeof value4 !== "string" || !Number.isFinite(Date.parse(value4))) invalid19("deadline_at must be an ISO 8601 timestamp or null.");
@@ -142249,8 +142327,8 @@ var init_routes13 = __esm({
142249
142327
  path: "/v2/objects/:object/records/query",
142250
142328
  coverage: { status: "partial", notes: "filter shorthand, operators, value properties, $and/$or/$not; sorts by attribute; path filters through references are gaps" },
142251
142329
  run: (r2) => {
142252
- const object19 = findObject(r2.ctx, r2.param("object"));
142253
- return { data: query8(r2, records(r2, object19), attributesOf(r2.ctx, object19.id)).map((rec) => recordShape(r2.ctx, rec)) };
142330
+ const object20 = findObject(r2.ctx, r2.param("object"));
142331
+ return { data: query8(r2, records(r2, object20), attributesOf(r2.ctx, object20.id)).map((rec) => recordShape(r2.ctx, rec)) };
142254
142332
  }
142255
142333
  },
142256
142334
  {
@@ -142267,10 +142345,10 @@ var init_routes13 = __esm({
142267
142345
  data: { known: ["values"], supported: ["values"] },
142268
142346
  coverage: { status: "partial", notes: "assert by a unique attribute: updates the match (appending to multiselect values) or creates a record" },
142269
142347
  run: (r2) => {
142270
- const object19 = findObject(r2.ctx, r2.param("object"));
142348
+ const object20 = findObject(r2.ctx, r2.param("object"));
142271
142349
  const slug10 = r2.query.get("matching_attribute");
142272
142350
  if (!slug10) invalid19("The matching_attribute query parameter is required.", "missing_value");
142273
- const attr = attributesOf(r2.ctx, object19.id).find((a) => a.api_slug === slug10 || a.id === slug10);
142351
+ const attr = attributesOf(r2.ctx, object20.id).find((a) => a.api_slug === slug10 || a.id === slug10);
142274
142352
  if (!attr) invalid19(`Cannot find attribute with slug/ID "${slug10}".`, "value_not_found");
142275
142353
  if (!attr.is_unique) invalid19(`Attribute with slug "${attr.api_slug}" is not unique and cannot be used to match records.`);
142276
142354
  const given2 = (r2.data.values ?? {})[attr.api_slug] ?? (r2.data.values ?? {})[attr.id];
@@ -142278,9 +142356,9 @@ var init_routes13 = __esm({
142278
142356
  const wanted = (Array.isArray(given2) ? given2 : [given2]).map((v) => primary(r2.ctx, attr, parseValue(r2.ctx, attr, v)));
142279
142357
  const owners = new Set(all5(r2.ctx, "SELECT * FROM attio_values WHERE attribute_id = ? AND active_until IS NULL", attr.id).filter((v) => wanted.includes(primary(r2.ctx, attr, JSON.parse(v.data)))).map((v) => v.parent_id));
142280
142358
  if (owners.size > 1) invalid19("More than one record matches the given value.", "multiple_match_results");
142281
- if (!owners.size) return { data: recordShape(r2.ctx, createRecord3(r2, object19, r2.data.values)) };
142359
+ if (!owners.size) return { data: recordShape(r2.ctx, createRecord3(r2, object20, r2.data.values)) };
142282
142360
  const id14 = [...owners][0];
142283
- writeAll(r2, id14, attributesOf(r2.ctx, object19.id), r2.data.values, "append", object19.api_slug);
142361
+ writeAll(r2, id14, attributesOf(r2.ctx, object20.id), r2.data.values, "append", object20.api_slug);
142284
142362
  return { data: recordShape(r2.ctx, one2(r2.ctx, "SELECT * FROM attio_records WHERE id = ?", id14)) };
142285
142363
  }
142286
142364
  },
@@ -142291,8 +142369,8 @@ var init_routes13 = __esm({
142291
142369
  data: { known: ["values"], supported: ["values"] },
142292
142370
  coverage: { status: "supported", notes: "multiselect values are added to" },
142293
142371
  run: (r2) => {
142294
- const object19 = findObject(r2.ctx, r2.param("object")), rec = findRecord(r2, object19);
142295
- writeAll(r2, rec.id, attributesOf(r2.ctx, object19.id), r2.data.values, "append", object19.api_slug);
142372
+ const object20 = findObject(r2.ctx, r2.param("object")), rec = findRecord(r2, object20);
142373
+ writeAll(r2, rec.id, attributesOf(r2.ctx, object20.id), r2.data.values, "append", object20.api_slug);
142296
142374
  return { data: recordShape(r2.ctx, rec) };
142297
142375
  }
142298
142376
  },
@@ -142302,8 +142380,8 @@ var init_routes13 = __esm({
142302
142380
  data: { known: ["values"], supported: ["values"] },
142303
142381
  coverage: { status: "supported", notes: "multiselect values are replaced" },
142304
142382
  run: (r2) => {
142305
- const object19 = findObject(r2.ctx, r2.param("object")), rec = findRecord(r2, object19);
142306
- writeAll(r2, rec.id, attributesOf(r2.ctx, object19.id), r2.data.values, "replace", object19.api_slug);
142383
+ const object20 = findObject(r2.ctx, r2.param("object")), rec = findRecord(r2, object20);
142384
+ writeAll(r2, rec.id, attributesOf(r2.ctx, object20.id), r2.data.values, "replace", object20.api_slug);
142307
142385
  return { data: recordShape(r2.ctx, rec) };
142308
142386
  }
142309
142387
  },
@@ -142323,8 +142401,8 @@ var init_routes13 = __esm({
142323
142401
  query: { known: ["show_historic", "limit", "offset"], supported: ["show_historic", "limit", "offset"] },
142324
142402
  coverage: { status: "supported" },
142325
142403
  run: (r2) => {
142326
- const object19 = findObject(r2.ctx, r2.param("object")), rec = findRecord(r2, object19);
142327
- const attr = attributesOf(r2.ctx, object19.id).find((a) => a.api_slug === r2.param("attribute") || a.id === r2.param("attribute")) ?? notFound9(`Attribute with slug/ID "${r2.param("attribute")}" not found.`);
142404
+ const object20 = findObject(r2.ctx, r2.param("object")), rec = findRecord(r2, object20);
142405
+ const attr = attributesOf(r2.ctx, object20.id).find((a) => a.api_slug === r2.param("attribute") || a.id === r2.param("attribute")) ?? notFound9(`Attribute with slug/ID "${r2.param("attribute")}" not found.`);
142328
142406
  const historic = r2.query.get("show_historic") === "true";
142329
142407
  const rows8 = all5(r2.ctx, `SELECT * FROM attio_values WHERE parent_id = ? AND attribute_id = ? ${historic ? "" : "AND active_until IS NULL"} ORDER BY id`, rec.id, attr.id);
142330
142408
  const { limit: limit2, offset: offset17 } = limitOffset({ limit: r2.query.get("limit") ?? void 0, offset: r2.query.get("offset") ?? void 0 });
@@ -142360,9 +142438,9 @@ var init_routes13 = __esm({
142360
142438
  coverage: { status: "supported" },
142361
142439
  run: (r2) => {
142362
142440
  const list16 = findList(r2.ctx, r2.param("list"));
142363
- const object19 = findObject(r2.ctx, String(r2.data.parent_object ?? list16.parent_object));
142364
- if (object19.api_slug !== list16.parent_object) invalid19(`The list "${list16.api_slug}" holds ${list16.parent_object} records, not ${object19.api_slug}.`);
142365
- const rec = one2(r2.ctx, "SELECT * FROM attio_records WHERE id = ? AND object_id = ?", r2.data.parent_record_id, object19.id) ?? notFound9(`Record with ID "${r2.data.parent_record_id}" not found.`);
142441
+ const object20 = findObject(r2.ctx, String(r2.data.parent_object ?? list16.parent_object));
142442
+ if (object20.api_slug !== list16.parent_object) invalid19(`The list "${list16.api_slug}" holds ${list16.parent_object} records, not ${object20.api_slug}.`);
142443
+ const rec = one2(r2.ctx, "SELECT * FROM attio_records WHERE id = ? AND object_id = ?", r2.data.parent_record_id, object20.id) ?? notFound9(`Record with ID "${r2.data.parent_record_id}" not found.`);
142366
142444
  const id14 = uuid9(r2.ctx);
142367
142445
  run2(r2.ctx, "INSERT INTO attio_entries (id, list_id, record_id, created_at) VALUES (?, ?, ?, ?)", id14, list16.id, rec.id, now5(r2.ctx));
142368
142446
  writeAll(r2, id14, attributesOf(r2.ctx, listParent(list16)), r2.data.entry_values ?? {}, "create");
@@ -142402,8 +142480,8 @@ var init_routes13 = __esm({
142402
142480
  query: { known: ["limit", "offset", "parent_object", "parent_record_id"], supported: ["limit", "offset", "parent_object", "parent_record_id"] },
142403
142481
  coverage: { status: "supported" },
142404
142482
  run: (r2) => {
142405
- const object19 = r2.query.get("parent_object"), record13 = r2.query.get("parent_record_id");
142406
- const objectSlug = object19 ? findObject(r2.ctx, object19).api_slug : void 0;
142483
+ const object20 = r2.query.get("parent_object"), record13 = r2.query.get("parent_record_id");
142484
+ const objectSlug = object20 ? findObject(r2.ctx, object20).api_slug : void 0;
142407
142485
  const notes6 = all5(r2.ctx, "SELECT * FROM attio_notes ORDER BY created_at, rowid").filter((n2) => (!objectSlug || n2.parent_object === objectSlug) && (!record13 || n2.parent_record_id === record13));
142408
142486
  const { limit: limit2, offset: offset17 } = limitOffset({ limit: r2.query.get("limit") ?? void 0, offset: r2.query.get("offset") ?? void 0 }, 10);
142409
142487
  return { data: notes6.slice(offset17, offset17 + limit2).map((n2) => noteShape2(r2.ctx, n2)) };
@@ -142418,14 +142496,14 @@ var init_routes13 = __esm({
142418
142496
  const d = r2.data;
142419
142497
  for (const key4 of ["parent_object", "parent_record_id", "title", "format", "content"]) if (typeof d[key4] !== "string") invalid19(`Body payload validation error: "data.${key4}" is required.`, "missing_value");
142420
142498
  if (d.format !== "plaintext" && d.format !== "markdown") invalid19('format must be "plaintext" or "markdown".');
142421
- const object19 = findObject(r2.ctx, d.parent_object);
142422
- if (!one2(r2.ctx, "SELECT 1 FROM attio_records WHERE id = ? AND object_id = ?", d.parent_record_id, object19.id)) notFound9(`Record with ID "${d.parent_record_id}" not found.`);
142499
+ const object20 = findObject(r2.ctx, d.parent_object);
142500
+ if (!one2(r2.ctx, "SELECT 1 FROM attio_records WHERE id = ? AND object_id = ?", d.parent_record_id, object20.id)) notFound9(`Record with ID "${d.parent_record_id}" not found.`);
142423
142501
  const id14 = uuid9(r2.ctx);
142424
142502
  run2(
142425
142503
  r2.ctx,
142426
142504
  "INSERT INTO attio_notes (id, parent_object, parent_record_id, title, content, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
142427
142505
  id14,
142428
- object19.api_slug,
142506
+ object20.api_slug,
142429
142507
  d.parent_record_id,
142430
142508
  d.title,
142431
142509
  d.content,
@@ -145695,7 +145773,7 @@ function send(ctx, mail, draft2, keep = true) {
145695
145773
  }
145696
145774
  function responseDraft(ctx, mail, original2, action, body6) {
145697
145775
  if (body6.comment !== void 0 && (typeof body6.comment !== "string" || body6.message?.body !== void 0)) throw invalid22("Specify either comment or message.body, but not both.");
145698
- if (body6.message !== void 0 && !object14(body6.message)) throw invalid22("message must be an object.");
145776
+ if (body6.message !== void 0 && !object15(body6.message)) throw invalid22("message must be an object.");
145699
145777
  if (body6.toRecipients !== void 0 && !OutlookMessageInputSchema.shape.toRecipients.safeParse(body6.toRecipients).success) throw invalid22("Invalid toRecipients.");
145700
145778
  if (Object.keys(body6).some((k) => !["comment", "message", "toRecipients"].includes(k))) throw invalid22("Invalid message action parameter.");
145701
145779
  const content2 = input3(body6.message ?? {}, mail), forwarding = action.toLowerCase().includes("forward"), all9 = action.toLowerCase().includes("replyall");
@@ -145745,7 +145823,7 @@ function attachmentRoute(ctx, mail, m, tail, method2, url4, headers, body6) {
145745
145823
  }
145746
145824
  if (tail[0] === "createUploadSession" && method2 === "POST") {
145747
145825
  const item2 = body6.AttachmentItem;
145748
- if (!object14(item2) || item2.attachmentType !== "file" || typeof item2.name !== "string" || !Number.isInteger(item2.size) || item2.size < 3 * 1024 * 1024 || item2.size > 150 * 1024 * 1024) throw invalid22("AttachmentItem must describe a file between 3 MB and 150 MB.");
145826
+ if (!object15(item2) || item2.attachmentType !== "file" || typeof item2.name !== "string" || !Number.isInteger(item2.size) || item2.size < 3 * 1024 * 1024 || item2.size > 150 * 1024 * 1024) throw invalid22("AttachmentItem must describe a file between 3 MB and 150 MB.");
145749
145827
  const id14 = ctx.secrets.hex(64), expiry = ctx.clock.nowMs() + 60 * 60 * 1e3;
145750
145828
  ctx.store.db.prepare("INSERT INTO outlook_uploads VALUES (?, ?, ?, ?, ?)").run(id14, mail, m.id, JSON.stringify({ ...item2, expiry }), Buffer.alloc(0));
145751
145829
  return json18({ "@odata.context": context2("microsoft.graph.uploadSession"), uploadUrl: `${ctx.serviceUrl}/upload/${id14}`, expirationDateTime: new Date(expiry).toISOString(), nextExpectedRanges: ["0-"] }, 201);
@@ -145848,7 +145926,7 @@ function route4(ctx, method2, url4, headers, body6, auth = "delegated") {
145848
145926
  const mail = user8.email, resource2 = `users('${user8.id}')`;
145849
145927
  if (!parts3.length && method2 === "GET") return json18({ "@odata.context": context2("users/$entity"), ...project9({ id: user8.id, displayName: user8.name, mail, userPrincipalName: mail, jobTitle: null }, url4, headers) });
145850
145928
  if (parts3[0] === "sendMail" && method2 === "POST") {
145851
- if (!object14(body6.message) || body6.saveToSentItems !== void 0 && typeof body6.saveToSentItems !== "boolean") throw invalid22("A message and a boolean saveToSentItems value are required.");
145929
+ if (!object15(body6.message) || body6.saveToSentItems !== void 0 && typeof body6.saveToSentItems !== "boolean") throw invalid22("A message and a boolean saveToSentItems value are required.");
145852
145930
  const m2 = create2(ctx, mail, input3(body6.message, mail));
145853
145931
  save8(ctx, mail, m2);
145854
145932
  send(ctx, mail, m2, body6.saveToSentItems !== false);
@@ -145958,7 +146036,7 @@ function route4(ctx, method2, url4, headers, body6, auth = "delegated") {
145958
146036
  }
145959
146037
  unsupported21(`${method2} ${url4.pathname}`);
145960
146038
  }
145961
- var requireFolder, object14;
146039
+ var requireFolder, object15;
145962
146040
  var init_routes17 = __esm({
145963
146041
  "packages/server/src/twins/outlook/routes.ts"() {
145964
146042
  "use strict";
@@ -145971,7 +146049,7 @@ var init_routes17 = __esm({
145971
146049
  if (!f2) throw missing4();
145972
146050
  return f2;
145973
146051
  };
145974
- object14 = (value4) => !!value4 && typeof value4 === "object" && !Array.isArray(value4);
146052
+ object15 = (value4) => !!value4 && typeof value4 === "object" && !Array.isArray(value4);
145975
146053
  }
145976
146054
  });
145977
146055
 
@@ -149248,22 +149326,22 @@ function jsonParameter(value4, field6) {
149248
149326
  }
149249
149327
  function metadataOf(value4, prefix2 = "") {
149250
149328
  if (value4 === void 0 || value4 === null || value4 === "") return {};
149251
- const object19 = jsonParameter(value4, `${prefix2}metadata`);
149252
- if (!isObject3(object19)) throw invalid23(`${prefix2}metadata must be an object`);
149253
- const entries3 = Object.entries(object19);
149329
+ const object20 = jsonParameter(value4, `${prefix2}metadata`);
149330
+ if (!isObject3(object20)) throw invalid23(`${prefix2}metadata must be an object`);
149331
+ const entries3 = Object.entries(object20);
149254
149332
  if (entries3.length > 20) throw invalid23(`${prefix2}metadata must have less than or equal to 20 keys`);
149255
149333
  for (const [key4, item2] of entries3) {
149256
149334
  if (key4.length > 40 || /["\\]/.test(key4)) throw invalid23(`${prefix2}metadata keys must be at most 40 characters and cannot contain " or \\`);
149257
149335
  if (typeof item2 !== "string" || item2.length > 500 || /["\\]/.test(item2)) throw invalid23(`${prefix2}metadata.${key4} must be a string of at most 500 characters without " or \\`);
149258
149336
  }
149259
- return object19;
149337
+ return object20;
149260
149338
  }
149261
149339
  function mergeVariablesOf(value4) {
149262
149340
  if (value4 === void 0 || value4 === null || value4 === "") return null;
149263
- const object19 = jsonParameter(value4, "merge_variables");
149264
- if (!isObject3(object19)) throw invalid23("merge_variables must be an object");
149265
- if (JSON.stringify(object19).length > 25e3) throw invalid23("merge_variables must be at most 25,000 characters");
149266
- return object19;
149341
+ const object20 = jsonParameter(value4, "merge_variables");
149342
+ if (!isObject3(object20)) throw invalid23("merge_variables must be an object");
149343
+ if (JSON.stringify(object20).length > 25e3) throw invalid23("merge_variables must be at most 25,000 characters");
149344
+ return object20;
149267
149345
  }
149268
149346
  function addressInput(body6, prefix2 = "") {
149269
149347
  allowed(body6, ADDRESS_FIELDS, [], prefix2);
@@ -149324,9 +149402,9 @@ function addressFor(call2, field6, required4) {
149324
149402
  }
149325
149403
  function rangeOf2(value4, field6) {
149326
149404
  if (value4 === void 0) return () => true;
149327
- const object19 = jsonParameter(value4, field6);
149328
- if (!isObject3(object19)) throw invalid23(`${field6} must be an object with gt, gte, lt or lte`);
149329
- const tests = Object.entries(object19).map(([operator2, raw3]) => {
149405
+ const object20 = jsonParameter(value4, field6);
149406
+ if (!isObject3(object20)) throw invalid23(`${field6} must be an object with gt, gte, lt or lte`);
149407
+ const tests = Object.entries(object20).map(([operator2, raw3]) => {
149330
149408
  if (!["gt", "gte", "lt", "lte"].includes(operator2)) throw invalid23(`${field6}.${operator2} is not allowed`);
149331
149409
  const ms = typeof raw3 === "string" ? Date.parse(raw3) : Number.NaN;
149332
149410
  if (Number.isNaN(ms)) throw invalid23(`${field6}.${operator2} must be a valid ISO 8601 date`);
@@ -150188,37 +150266,37 @@ function decimal3(v, field6) {
150188
150266
  return n2;
150189
150267
  }
150190
150268
  function money10(v, currency, field6) {
150191
- const m = object15(v, field6);
150269
+ const m = object16(v, field6);
150192
150270
  keys6(m, ["currency_code", "value"], field6);
150193
150271
  if (m.currency_code !== currency) refused("CURRENCY_MISMATCH", "Currency must match the invoice currency.", `${field6}/currency_code`);
150194
150272
  return decimal3(m.value, `${field6}/value`);
150195
150273
  }
150196
150274
  function invoiceFrom(ctx, body6) {
150197
- const b = object15(body6, "/");
150275
+ const b = object16(body6, "/");
150198
150276
  keys6(b, ["detail", "invoicer", "primary_recipients", "items", "configuration"], "invoice");
150199
- const detail3 = object15(b.detail, "/detail");
150277
+ const detail3 = object16(b.detail, "/detail");
150200
150278
  keys6(detail3, ["currency_code", "invoice_number", "reference", "note", "terms_and_conditions", "memo"], "/detail");
150201
150279
  const currency = detail3.currency_code;
150202
150280
  if (!["USD", "EUR", "GBP", "CAD", "AUD"].includes(currency)) unsupported23(`invoice currency ${String(currency)}`);
150203
150281
  for (const key4 of ["invoice_number", "reference", "note", "terms_and_conditions", "memo"]) if (detail3[key4] !== void 0) text22(detail3[key4], `/detail/${key4}`, key4 === "invoice_number" ? 25 : 4e3);
150204
150282
  if (detail3.invoice_number && allOf2(ctx, "invoice").some((i) => i.detail.invoice_number === detail3.invoice_number)) refused("DUPLICATE_INVOICE_NUMBER", "Invoice number must be unique.", "/detail/invoice_number");
150205
150283
  if (b.configuration !== void 0) {
150206
- const c = object15(b.configuration, "/configuration");
150284
+ const c = object16(b.configuration, "/configuration");
150207
150285
  keys6(c, ["tax_calculated_after_discount", "tax_inclusive"], "/configuration");
150208
150286
  if (c.tax_calculated_after_discount !== void 0 && c.tax_calculated_after_discount !== true) unsupported23("configuration.tax_calculated_after_discount=false");
150209
150287
  if (c.tax_inclusive !== void 0 && c.tax_inclusive !== false) unsupported23("configuration.tax_inclusive=true");
150210
150288
  }
150211
150289
  const contact = (v, field6) => {
150212
- const c = object15(v, field6);
150290
+ const c = object16(v, field6);
150213
150291
  keys6(c, ["name", "email_address", "address", "business_name"], field6);
150214
150292
  if (c.email_address !== void 0 && (typeof c.email_address !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(c.email_address))) invalid24({ field: `${field6}/email_address`, issue: "INVALID_PARAMETER_VALUE", description: "Invalid email address." });
150215
150293
  if (c.name !== void 0) {
150216
- const n2 = object15(c.name, `${field6}/name`);
150294
+ const n2 = object16(c.name, `${field6}/name`);
150217
150295
  keys6(n2, ["given_name", "surname", "full_name"], `${field6}/name`);
150218
150296
  for (const [k, v3] of Object.entries(n2)) text22(v3, `${field6}/name/${k}`, 300);
150219
150297
  }
150220
150298
  if (c.address !== void 0) {
150221
- const a = object15(c.address, `${field6}/address`);
150299
+ const a = object16(c.address, `${field6}/address`);
150222
150300
  keys6(a, ["address_line_1", "address_line_2", "admin_area_1", "admin_area_2", "postal_code", "country_code"], `${field6}/address`);
150223
150301
  for (const [k, v3] of Object.entries(a)) text22(v3, `${field6}/address/${k}`, 300);
150224
150302
  }
@@ -150228,21 +150306,21 @@ function invoiceFrom(ctx, body6) {
150228
150306
  const invoicer = b.invoicer === void 0 ? void 0 : contact(b.invoicer, "/invoicer");
150229
150307
  if (!Array.isArray(b.primary_recipients) || b.primary_recipients.length !== 1) invalid24({ field: "/primary_recipients", issue: "INVALID_ARRAY_SIZE", description: "Supply one primary recipient." });
150230
150308
  const recipients2 = b.primary_recipients.map((raw3) => {
150231
- const r2 = object15(raw3, "/primary_recipients");
150309
+ const r2 = object16(raw3, "/primary_recipients");
150232
150310
  keys6(r2, ["billing_info"], "/primary_recipients");
150233
150311
  const billing = contact(r2.billing_info, "/primary_recipients/billing_info");
150234
150312
  return { billing_info: billing };
150235
150313
  });
150236
150314
  if (!Array.isArray(b.items) || b.items.length === 0 || b.items.length > 100) invalid24({ field: "/items", issue: "INVALID_ARRAY_SIZE", description: "Supply 1 to 100 items." });
150237
150315
  const items = b.items.map((raw3, index) => {
150238
- const path6 = `/items/${index}`, i = object15(raw3, path6);
150316
+ const path6 = `/items/${index}`, i = object16(raw3, path6);
150239
150317
  keys6(i, ["name", "description", "quantity", "unit_amount", "tax", "discount", "unit_of_measure"], path6);
150240
150318
  const name5 = text22(i.name, `${path6}/name`, 200), quantity = decimal3(i.quantity, `${path6}/quantity`);
150241
150319
  if (quantity <= 0 || quantity > 1e6) invalid24({ field: `${path6}/quantity`, issue: "INVALID_PARAMETER_VALUE", description: "Quantity must be positive and at most 10000." });
150242
150320
  const unit = money10(i.unit_amount, currency, `${path6}/unit_amount`), line2 = rounded(unit, quantity, 100);
150243
150321
  let discount = 0, tax = 0;
150244
150322
  if (i.discount !== void 0) {
150245
- const d = object15(i.discount, `${path6}/discount`);
150323
+ const d = object16(i.discount, `${path6}/discount`);
150246
150324
  keys6(d, ["percent", "amount"], `${path6}/discount`);
150247
150325
  if (d.percent === void 0 === (d.amount === void 0)) invalid24({ field: `${path6}/discount`, issue: "INVALID_PARAMETER_VALUE", description: "Supply a discount percent or amount." });
150248
150326
  if (d.percent !== void 0) {
@@ -150253,7 +150331,7 @@ function invoiceFrom(ctx, body6) {
150253
150331
  if (discount > line2) refused("INVALID_DISCOUNT", "Discount cannot exceed the item amount.");
150254
150332
  }
150255
150333
  if (i.tax !== void 0) {
150256
- const t = object15(i.tax, `${path6}/tax`);
150334
+ const t = object16(i.tax, `${path6}/tax`);
150257
150335
  keys6(t, ["name", "percent"], `${path6}/tax`);
150258
150336
  text22(t.name, `${path6}/tax/name`, 100);
150259
150337
  const percent = decimal3(t.percent, `${path6}/tax/percent`);
@@ -150308,13 +150386,13 @@ function invoiceShape(i, base4) {
150308
150386
  links: [{ href: `${base4}/v2/invoicing/invoices/${i.id}`, rel: "self", method: "GET" }]
150309
150387
  };
150310
150388
  }
150311
- var object15, rounded, get4, invoiceRoutes;
150389
+ var object16, rounded, get4, invoiceRoutes;
150312
150390
  var init_invoices = __esm({
150313
150391
  "packages/server/src/twins/paypal/invoices.ts"() {
150314
150392
  "use strict";
150315
150393
  init_db26();
150316
150394
  init_request18();
150317
- object15 = (v, field6) => {
150395
+ object16 = (v, field6) => {
150318
150396
  if (!v || typeof v !== "object" || Array.isArray(v)) invalid24({ field: field6, issue: "INVALID_PARAMETER_SYNTAX", description: "Expected an object.", location: "body" });
150319
150397
  return v;
150320
150398
  };
@@ -150340,7 +150418,7 @@ var init_invoices = __esm({
150340
150418
  return { items: all9.slice((page18 - 1) * size2, page18 * size2).map((i) => invoiceShape(i, r2.base)), ...r2.query.get("total_required") === "true" && { total_items: all9.length, total_pages: Math.ceil(all9.length / size2) } };
150341
150419
  } },
150342
150420
  { method: "POST", path: "/v2/invoicing/invoices/:id/send", coverage: { status: "partial", notes: "Send a draft invoice to its billing recipient" }, run: (r2) => {
150343
- const b = object15(r2.body, "/");
150421
+ const b = object16(r2.body, "/");
150344
150422
  keys6(b, ["send_to_recipient", "send_to_invoicer"], "/send");
150345
150423
  for (const [k, v] of Object.entries(b)) if (typeof v !== "boolean") invalid24({ field: `/${k}`, issue: "INVALID_PARAMETER_VALUE", description: "Expected a boolean." });
150346
150424
  if (b.send_to_recipient === false) unsupported23("send_to_recipient=false");
@@ -164764,10 +164842,10 @@ ${stream}endstream`);
164764
164842
  objects[0] = "<< /Type /Catalog /Pages 2 0 R >>";
164765
164843
  objects[1] = `<< /Type /Pages /Kids [${kids.join(" ")}] /Count ${pages.length} >>`;
164766
164844
  let pdf = "%PDF-1.4\n", offsets = [0];
164767
- objects.forEach((object19, i) => {
164845
+ objects.forEach((object20, i) => {
164768
164846
  offsets.push(Buffer.byteLength(pdf));
164769
164847
  pdf += `${i + 1} 0 obj
164770
- ${object19}
164848
+ ${object20}
164771
164849
  endobj
164772
164850
  `;
164773
164851
  });
@@ -166743,19 +166821,19 @@ function dayOf(raw3) {
166743
166821
  const match3 = /^(\d{4}-\d{2}-\d{2})(?:T([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d)(?:\.\d{1,9})?)?(?:Z|[+-](?:[01]\d|2[0-3]):?[0-5]\d)?)?$/.exec(raw3);
166744
166822
  return match3 && isDay2(match3[1]) ? match3[1] : void 0;
166745
166823
  }
166746
- function object16(value4, path6) {
166824
+ function object17(value4, path6) {
166747
166825
  if (value4 && typeof value4 === "object" && !Array.isArray(value4)) return value4;
166748
166826
  if (path6 !== void 0) throw malformed(path6, value4);
166749
166827
  throw new NetsuiteError(400, "INVALID_CONTENT", "The request body must be a JSON object.");
166750
166828
  }
166751
166829
  function entries2(raw3, path6) {
166752
166830
  if (raw3 === null) return [];
166753
- const list16 = object16(raw3, path6).items;
166831
+ const list16 = object17(raw3, path6).items;
166754
166832
  if (!Array.isArray(list16)) throw malformed(`${path6}.items`, list16);
166755
- return list16.map((entry2, index) => object16(entry2, `${path6}.items[${index}]`));
166833
+ return list16.map((entry2, index) => object17(entry2, `${path6}.items[${index}]`));
166756
166834
  }
166757
166835
  function refId(ctx, target5, raw3, path6) {
166758
- const ref22 = object16(raw3, path6);
166836
+ const ref22 = object17(raw3, path6);
166759
166837
  if (ref22.id !== void 0) {
166760
166838
  const id14 = typeof ref22.id === "number" ? ref22.id : typeof ref22.id === "string" && /^\d{1,10}$/.test(ref22.id) ? Number(ref22.id) : Number.NaN;
166761
166839
  if (!Number.isSafeInteger(id14) || id14 <= 0) throw malformed(path6, ref22.id);
@@ -166770,7 +166848,7 @@ function refId(ctx, target5, raw3, path6) {
166770
166848
  throw malformed(path6, raw3);
166771
166849
  }
166772
166850
  function address7(raw3, path6, strict, warnings2) {
166773
- const given2 = object16(raw3, path6), out = {};
166851
+ const given2 = object17(raw3, path6), out = {};
166774
166852
  for (const [key4, value4] of Object.entries(given2)) {
166775
166853
  if (key4 === "links" || key4 === "addrText" || key4 === "refName") continue;
166776
166854
  if (!ADDRESS_KEYS.includes(key4)) {
@@ -167816,7 +167894,7 @@ function orderStatusChange(ctx, prior, current, requested2) {
167816
167894
  }
167817
167895
  function save12(ctx, type, id14, body6, opts = {}) {
167818
167896
  if (isBanking(type)) return saveBanking(ctx, type, id14, body6);
167819
- const input5 = object16(body6), kept = keptFields(ctx, type), given2 = /* @__PURE__ */ new Map();
167897
+ const input5 = object17(body6), kept = keptFields(ctx, type), given2 = /* @__PURE__ */ new Map();
167820
167898
  const declared = new Set(customFieldsFor(ctx, type).map((f2) => f2.id));
167821
167899
  for (const [name5, value4] of Object.entries(input5)) if (kept.has(name5) && !Object.hasOwn(FIELDS3[type], name5) && !declared.has(name5)) given2.set(name5, value4);
167822
167900
  const saved = saveModeled(ctx, type, id14, given2.size ? without(input5, ...given2.keys()) : input5, opts);
@@ -167863,7 +167941,7 @@ function picks(ctx, order6, body6, sublist, column, zeroQuantity = false) {
167863
167941
  });
167864
167942
  }
167865
167943
  function transform2(ctx, source, id14, targetName, raw3, base4 = {}) {
167866
- const body6 = object16(raw3), target5 = netsuiteRecordTypes.find((known2) => known2.toLowerCase() === targetName.toLowerCase());
167944
+ const body6 = object17(raw3), target5 = netsuiteRecordTypes.find((known2) => known2.toLowerCase() === targetName.toLowerCase());
167867
167945
  if (!target5 || !(TRANSFORMS[source] ?? []).includes(target5)) throw gap6(`transforming a ${source} into a ${targetName}`);
167868
167946
  const opts = { ...base4, replace: void 0, replaceSelected: void 0 };
167869
167947
  const make = (type, fields11, origin) => ({ type, id: saveTransaction(ctx, type, void 0, fields11, { ...opts, ...origin && { origin } }) });
@@ -168383,15 +168461,15 @@ function match2(ctx, bankIds, gl, source) {
168383
168461
  function saveBanking(ctx, type, id14, body6) {
168384
168462
  if (type !== "transactionMatch" || id14 !== void 0) throw new NetsuiteError(405, "METHOD_NOT_ALLOWED", "Transaction matches are created once; imported bank data and suggestions are read-only.");
168385
168463
  bankPermission(ctx, 2);
168386
- const input5 = object16(body6);
168464
+ const input5 = object17(body6);
168387
168465
  for (const key4 of Object.keys(input5)) if (!["importedTransactionMatch", "generalLedgerTransactionMatch"].includes(key4)) throw new NetsuiteError(403, "INSUFFICIENT_PERMISSION", `The field ${key4} is read-only.`);
168388
168466
  const list16 = (name5) => {
168389
- const items = object16(input5[name5]).items;
168467
+ const items = object17(input5[name5]).items;
168390
168468
  if (!Array.isArray(items) || !items.length || items.length > 500) throw userError(`Provide ${name5}.items.`);
168391
- return items.map((item2) => object16(item2));
168469
+ return items.map((item2) => object17(item2));
168392
168470
  };
168393
168471
  const ref22 = (v) => {
168394
- const n2 = Number(object16(v).id);
168472
+ const n2 = Number(object17(v).id);
168395
168473
  if (!Number.isSafeInteger(n2) || n2 <= 0) throw userError("Provide a valid internal ID.");
168396
168474
  return n2;
168397
168475
  };
@@ -168413,7 +168491,7 @@ function bankingActions(ctx, id14) {
168413
168491
  function bankAction(ctx, id14, action, body6) {
168414
168492
  if (!["accept", "reject"].includes(action)) throw userError("Choose accept or reject.");
168415
168493
  bankPermission(ctx, action === "accept" ? 2 : 3);
168416
- if (Object.keys(object16(body6 ?? {})).length) throw userError("This action takes the record ID only.");
168494
+ if (Object.keys(object17(body6 ?? {})).length) throw userError("This action takes the record ID only.");
168417
168495
  const s2 = suggestion(ctx, id14), db3 = sql(ctx);
168418
168496
  if (s2.status !== "pending") throw userError("This suggestion has already been accepted or rejected.");
168419
168497
  if (action === "reject") {
@@ -170993,16 +171071,16 @@ var init_suiteql = __esm({
170993
171071
  block(q, parent2, limit2 = -1, comparisonType) {
170994
171072
  const scope2 = { relations: [], parent: parent2, correlations: [] };
170995
171073
  let from = q.from ? this.source(q.from, scope2) : sql2("");
170996
- for (const join22 of q.joins) {
170997
- const source = this.source(join22.source, scope2);
170998
- if (!join22.on) {
170999
- from = sql2(from, JOINS[join22.kind], source);
171074
+ for (const join23 of q.joins) {
171075
+ const source = this.source(join23.source, scope2);
171076
+ if (!join23.on) {
171077
+ from = sql2(from, JOINS[join23.kind], source);
171000
171078
  continue;
171001
171079
  }
171002
- if (hasWindow(join22.on)) invalid28("Analytic functions are not allowed in JOIN conditions.");
171003
- const on = this.expr(join22.on, scope2);
171004
- if (on.aggregate || hasRownum(join22.on)) invalid28("JOIN conditions cannot contain aggregate functions or ROWNUM.");
171005
- from = sql2(from, JOINS[join22.kind], source, " ON ", on);
171080
+ if (hasWindow(join23.on)) invalid28("Analytic functions are not allowed in JOIN conditions.");
171081
+ const on = this.expr(join23.on, scope2);
171082
+ if (on.aggregate || hasRownum(join23.on)) invalid28("JOIN conditions cannot contain aggregate functions or ROWNUM.");
171083
+ from = sql2(from, JOINS[join23.kind], source, " ON ", on);
171006
171084
  }
171007
171085
  for (const e of [q.where, ...q.group, q.having]) if (e && hasWindow(e)) invalid28("Analytic functions are only allowed in the select list and ORDER BY.");
171008
171086
  const split = this.rownumFilter(q.where), usesRownum = expressions(q).some(hasRownum);
@@ -172967,13 +173045,13 @@ var init_reports = __esm({
172967
173045
 
172968
173046
  // packages/server/src/twins/netsuite/searches.ts
172969
173047
  function joined(ctx, type, name5, error64, plan4) {
172970
- const [join22, column, ...rest2] = name5.split("."), spec = JOINS2[type]?.[join22];
173048
+ const [join23, column, ...rest2] = name5.split("."), spec = JOINS2[type]?.[join23];
172971
173049
  if (!spec || !column || rest2.length) throw error64(name5);
172972
- const target5 = FIELDS4[spec.type], alias = `j_${join22}`, original2 = target5.from.split(" ")[1];
173050
+ const target5 = FIELDS4[spec.type], alias = `j_${join23}`, original2 = target5.from.split(" ")[1];
172973
173051
  const replace = (s2) => s2.replace(new RegExp(`\\b${original2}\\.`, "g"), `${alias}.`).replace(/\btl\./g, `${alias}_line.`);
172974
- if (!plan4.joins.has(join22)) {
172975
- const on = type === spec.type || type === "customer" && join22 === "contact" || type === "contact" && join22 === "customer" ? spec.on : spec.on.replace(new RegExp(`\\b${original2}\\.`, "g"), `${alias}.`);
172976
- plan4.joins.set(join22, `${spec.via ? spec.via + " " : ""}LEFT JOIN ${spec.type} ${alias} ON ${on}${spec.type === "transaction" ? ` LEFT JOIN transactionline ${alias}_line ON ${alias}_line.transaction = ${alias}.id AND ${alias}_line.mainline = 'T'` : ""}`);
173052
+ if (!plan4.joins.has(join23)) {
173053
+ const on = type === spec.type || type === "customer" && join23 === "contact" || type === "contact" && join23 === "customer" ? spec.on : spec.on.replace(new RegExp(`\\b${original2}\\.`, "g"), `${alias}.`);
173054
+ plan4.joins.set(join23, `${spec.via ? spec.via + " " : ""}LEFT JOIN ${spec.type} ${alias} ON ${on}${spec.type === "transaction" ? ` LEFT JOIN transactionline ${alias}_line ON ${alias}_line.transaction = ${alias}.id AND ${alias}_line.mainline = 'T'` : ""}`);
172977
173055
  }
172978
173056
  const found = field5(ctx, spec.type, column, error64, { joins: /* @__PURE__ */ new Map() });
172979
173057
  return { ...found, sql: replace(found.sql), ...found.text && { text: replace(found.text) } };
@@ -173153,9 +173231,9 @@ function expression2(ctx, type, filters, params10, plan4) {
173153
173231
  if (!filters.length) return "";
173154
173232
  if (filters.every((entry2) => entry2 && typeof entry2 === "object" && !Array.isArray(entry2))) {
173155
173233
  return filters.map((entry2) => {
173156
- const { name: name5, operator: operator2, values: values2, join: join22, formula, summary } = entry2;
173157
- if (join22 !== void 0 && typeof join22 !== "string") throw badExpression();
173158
- return term(ctx, type, [join22 ? `${join22}.${name5}` : name5, operator2, ...Array.isArray(values2) ? values2 : values2 === void 0 ? [] : [values2]], params10, plan4, summary, formula);
173234
+ const { name: name5, operator: operator2, values: values2, join: join23, formula, summary } = entry2;
173235
+ if (join23 !== void 0 && typeof join23 !== "string") throw badExpression();
173236
+ return term(ctx, type, [join23 ? `${join23}.${name5}` : name5, operator2, ...Array.isArray(values2) ? values2 : values2 === void 0 ? [] : [values2]], params10, plan4, summary, formula);
173159
173237
  }).join(" AND ");
173160
173238
  }
173161
173239
  if (typeof filters[0] === "string" && typeof filters[1] === "string" && !["AND", "OR", "NOT"].includes(String(filters[0]).toUpperCase())) return term(ctx, type, filters, params10, plan4);
@@ -173740,20 +173818,20 @@ async function mcpEndpoint(ctx, method2, text25, base4, serve3, caller2, headers
173740
173818
  }
173741
173819
  if (Array.isArray(message7)) return rpcError(null, -32600, "Invalid Request: send one JSON-RPC message per request.", 400);
173742
173820
  if (!message7 || typeof message7 !== "object" || message7.jsonrpc !== "2.0") return rpcError(null, -32600, "Invalid Request", 400);
173743
- const object19 = (value4) => !!value4 && typeof value4 === "object" && !Array.isArray(value4);
173821
+ const object20 = (value4) => !!value4 && typeof value4 === "object" && !Array.isArray(value4);
173744
173822
  if (message7.id !== void 0 && typeof message7.id !== "string" && !(typeof message7.id === "number" && Number.isInteger(message7.id))) return rpcError(null, -32600, "Invalid Request", 400);
173745
173823
  if (message7.method === void 0) {
173746
- const hasResult = object19(message7.result), hasError = object19(message7.error) && Number.isInteger(message7.error.code) && typeof message7.error.message === "string";
173824
+ const hasResult = object20(message7.result), hasError = object20(message7.error) && Number.isInteger(message7.error.code) && typeof message7.error.message === "string";
173747
173825
  if (message7.id !== void 0 && (hasResult && message7.error === void 0 || hasError && message7.result === void 0)) return { status: 202, headers: {}, body: null };
173748
173826
  return rpcError(null, -32600, "Invalid Request", 400);
173749
173827
  }
173750
173828
  if (typeof message7.method !== "string" || message7.result !== void 0 || message7.error !== void 0) return rpcError(null, -32600, "Invalid Request", 400);
173751
- if (message7.params !== void 0 && !object19(message7.params)) return rpcError(message7.id, -32602, "Invalid params", 400);
173829
+ if (message7.params !== void 0 && !object20(message7.params)) return rpcError(message7.id, -32602, "Invalid params", 400);
173752
173830
  if (message7.id === void 0) return { status: 202, headers: {}, body: null };
173753
173831
  const id14 = message7.id, params10 = message7.params ?? {};
173754
173832
  switch (message7.method) {
173755
173833
  case "initialize": {
173756
- if (typeof params10.protocolVersion !== "string" || !object19(params10.capabilities) || !object19(params10.clientInfo) || typeof params10.clientInfo.name !== "string" || typeof params10.clientInfo.version !== "string") return rpcError(id14, -32602, "initialize requires protocolVersion, capabilities and clientInfo.");
173834
+ if (typeof params10.protocolVersion !== "string" || !object20(params10.capabilities) || !object20(params10.clientInfo) || typeof params10.clientInfo.name !== "string" || typeof params10.clientInfo.version !== "string") return rpcError(id14, -32602, "initialize requires protocolVersion, capabilities and clientInfo.");
173757
173835
  const asked = params10.protocolVersion;
173758
173836
  return reply4(id14, {
173759
173837
  protocolVersion: PROTOCOLS.includes(asked) ? asked : PROTOCOLS[0],
@@ -175273,7 +175351,7 @@ function records2(ctx, method2, url4, segments3, body6, opts) {
175273
175351
  async function suiteql(ctx, url4, body6, prefer) {
175274
175352
  if (!/(^|[\s,;])transient($|[\s,;])/i.test(prefer ?? "")) throw new NetsuiteError(400, "INVALID_PARAMETER", "Invalid search query. SuiteQL requests need the header Prefer: transient.", { header: "Prefer" });
175275
175353
  params9(url4, ["limit", "offset"]);
175276
- const window5 = paging(url4), { q, params: values2 } = object16(body6);
175354
+ const window5 = paging(url4), { q, params: values2 } = object17(body6);
175277
175355
  if (typeof q !== "string" || q.trim() === "") throw new NetsuiteError(400, "INVALID_PARAMETER", 'Invalid search query. Send the query as {"q": "SELECT ..."}.', "q");
175278
175356
  if (values2 !== void 0 && (!Array.isArray(values2) || values2.length > 1e3)) throw new NetsuiteError(400, "INVALID_PARAMETER", "Invalid search query. Send params as an array of values for the ? markers.", "params");
175279
175357
  try {
@@ -175623,13 +175701,13 @@ function materializeEvent(event3, info, transportNowMs, targetUrl) {
175623
175701
  for (const [index, key4] of keys7.entries()) {
175624
175702
  if (typeof target5 !== "object" || target5 === null || !Object.hasOwn(target5, key4)) throw new AnchaError("INTERNAL", `event pointer does not exist: ${pointer2}`);
175625
175703
  if (Array.isArray(target5) && !/^(0|[1-9]\d*)$/.test(key4)) throw new AnchaError("INTERNAL", `invalid event array pointer: ${pointer2}`);
175626
- const object19 = target5;
175704
+ const object20 = target5;
175627
175705
  if (index === keys7.length - 1) {
175628
- if (typeof object19[key4] !== "string") throw new AnchaError("INTERNAL", `event URL is not a string: ${pointer2}`);
175706
+ if (typeof object20[key4] !== "string") throw new AnchaError("INTERNAL", `event URL is not a string: ${pointer2}`);
175629
175707
  const targetService = linkService === void 0 ? service : info.services[linkService];
175630
175708
  if (!targetService) throw new AnchaError("INTERNAL", `missing ${linkService} service for event API link`);
175631
- Object.defineProperty(object19, key4, { value: targetService.url.replace(/\/$/, "") + path6, enumerable: true, configurable: true, writable: true });
175632
- } else target5 = object19[key4];
175709
+ Object.defineProperty(object20, key4, { value: targetService.url.replace(/\/$/, "") + path6, enumerable: true, configurable: true, writable: true });
175710
+ } else target5 = object20[key4];
175633
175711
  }
175634
175712
  }
175635
175713
  body6 = JSON.stringify(payload2);
@@ -180432,7 +180510,7 @@ var init_sessions = __esm({
180432
180510
  });
180433
180511
 
180434
180512
  // packages/server/src/control/inspection-routes.ts
180435
- function object17(value4) {
180513
+ function object18(value4) {
180436
180514
  if (!value4 || typeof value4 !== "object" || Array.isArray(value4)) return bad3("expected a JSON object");
180437
180515
  return value4;
180438
180516
  }
@@ -180511,7 +180589,7 @@ function inspectionRoutes(opts) {
180511
180589
  return c.json(observe(env, revisions.get(env) ?? null));
180512
180590
  });
180513
180591
  routes2.post("/envs/:id/inspect", async (c) => {
180514
- const body6 = object17(await c.req.json().catch(() => bad3("invalid JSON")));
180592
+ const body6 = object18(await c.req.json().catch(() => bad3("invalid JSON")));
180515
180593
  only3(body6, []);
180516
180594
  const env = opts.manager.get(c.req.param("id"));
180517
180595
  return c.json(await env.serialize(() => {
@@ -180524,7 +180602,7 @@ function inspectionRoutes(opts) {
180524
180602
  }));
180525
180603
  });
180526
180604
  routes2.post("/envs/:id/inspect/advance", async (c) => {
180527
- const body6 = object17(await c.req.json().catch(() => bad3("invalid JSON")));
180605
+ const body6 = object18(await c.req.json().catch(() => bad3("invalid JSON")));
180528
180606
  only3(body6, ["revision", "untilMs"]);
180529
180607
  const env = opts.manager.get(c.req.param("id"));
180530
180608
  return c.json(await env.serialize(() => {
@@ -180536,7 +180614,7 @@ function inspectionRoutes(opts) {
180536
180614
  }));
180537
180615
  });
180538
180616
  routes2.post("/envs/:id/inspect/reset", async (c) => {
180539
- const body6 = object17(await c.req.json().catch(() => bad3("invalid JSON")));
180617
+ const body6 = object18(await c.req.json().catch(() => bad3("invalid JSON")));
180540
180618
  only3(body6, ["revision"]);
180541
180619
  const env = opts.manager.get(c.req.param("id"));
180542
180620
  return c.json(await env.serialize(async () => {
@@ -180550,12 +180628,12 @@ function inspectionRoutes(opts) {
180550
180628
  }));
180551
180629
  });
180552
180630
  routes2.post("/envs/:id/inspect/action", async (c) => {
180553
- const body6 = object17(await c.req.json().catch(() => bad3("invalid JSON")));
180631
+ const body6 = object18(await c.req.json().catch(() => bad3("invalid JSON")));
180554
180632
  only3(body6, ["revision", "action"]);
180555
180633
  const env = opts.manager.get(c.req.param("id"));
180556
180634
  return c.json(await env.serialize(async () => {
180557
180635
  const revision = owned2(env, body6.revision);
180558
- const action = object17(body6.action);
180636
+ const action = object18(body6.action);
180559
180637
  const info = envInfo(env, opts.publicUrl(), opts.port());
180560
180638
  let service, path6, method2, payload2;
180561
180639
  switch (action.kind) {
@@ -180693,7 +180771,7 @@ var init_simulation_routes = __esm({
180693
180771
 
180694
180772
  // packages/server/src/control/session-routes.ts
180695
180773
  import { isAbsolute as isAbsolute2 } from "node:path";
180696
- function object18(value4) {
180774
+ function object19(value4) {
180697
180775
  if (typeof value4 !== "object" || value4 === null || Array.isArray(value4)) throw new AnchaError("USAGE", "request must be a JSON object");
180698
180776
  return value4;
180699
180777
  }
@@ -180701,7 +180779,7 @@ function fields10(value4, allowed2) {
180701
180779
  if (Object.keys(value4).some((key4) => !allowed2.includes(key4))) throw new AnchaError("USAGE", "unknown request field");
180702
180780
  }
180703
180781
  function parseOptions(value4) {
180704
- const input5 = object18(value4);
180782
+ const input5 = object19(value4);
180705
180783
  fields10(input5, ["mode", "idleMs", "delivery", "slackTransport", "clientOrigin", "setupCalls", "clockFile"]);
180706
180784
  if (input5.clockFile !== void 0 && (typeof input5.clockFile !== "string" || !isAbsolute2(input5.clockFile) || !input5.clockFile.endsWith("/clock.json") || input5.clockFile.includes("\0"))) {
180707
180785
  throw new AnchaError("USAGE", "clockFile must be an absolute path ending in /clock.json");
@@ -180720,7 +180798,7 @@ function parseOptions(value4) {
180720
180798
  if (input5.idleMs !== void 0 && (typeof input5.idleMs !== "number" || !Number.isFinite(input5.idleMs) || input5.idleMs < 0)) throw new AnchaError("USAGE", "idleMs must be non-negative simulated milliseconds");
180721
180799
  if (input5.slackTransport !== void 0 && (typeof input5.slackTransport !== "string" || !["feed", "http", "socket"].includes(input5.slackTransport))) throw new AnchaError("USAGE", "invalid Slack transport");
180722
180800
  if (input5.delivery !== void 0) {
180723
- const delivery = object18(input5.delivery);
180801
+ const delivery = object19(input5.delivery);
180724
180802
  fields10(delivery, [...SUPPORTED_TWINS, "app"]);
180725
180803
  for (const url4 of Object.values(delivery)) {
180726
180804
  try {
@@ -180733,7 +180811,7 @@ function parseOptions(value4) {
180733
180811
  return input5;
180734
180812
  }
180735
180813
  function parseStartOptions(value4) {
180736
- const input5 = object18(value4);
180814
+ const input5 = object19(value4);
180737
180815
  fields10(input5, ["delivery", "timeoutMs"]);
180738
180816
  if (input5.timeoutMs !== void 0 && (typeof input5.timeoutMs !== "number" || !Number.isSafeInteger(input5.timeoutMs) || input5.timeoutMs <= 0 || input5.timeoutMs > 2147483647)) throw new AnchaError("USAGE", "timeoutMs must be positive real milliseconds (at most 2147483647)");
180739
180817
  if (input5.delivery !== void 0) parseOptions({ mode: "endpoint", delivery: input5.delivery });
@@ -180745,7 +180823,7 @@ function sessionRoutes(opts, sessions) {
180745
180823
  app2.post("/envs/:id/trials", async (c) => {
180746
180824
  let input5;
180747
180825
  try {
180748
- input5 = object18(await c.req.json());
180826
+ input5 = object19(await c.req.json());
180749
180827
  } catch {
180750
180828
  throw new AnchaError("USAGE", "request must be a JSON object");
180751
180829
  }
@@ -180768,7 +180846,7 @@ function sessionRoutes(opts, sessions) {
180768
180846
  app2.post("/envs/:id/trials/:sid/answer", async (c) => {
180769
180847
  let input5;
180770
180848
  try {
180771
- input5 = object18(await c.req.json());
180849
+ input5 = object19(await c.req.json());
180772
180850
  } catch {
180773
180851
  throw new AnchaError("USAGE", "request must be a JSON object");
180774
180852
  }
@@ -180783,7 +180861,7 @@ function sessionRoutes(opts, sessions) {
180783
180861
  app2.post("/envs/:id/trials/:sid/agent", async (c) => {
180784
180862
  let input5;
180785
180863
  try {
180786
- input5 = object18(await c.req.json());
180864
+ input5 = object19(await c.req.json());
180787
180865
  } catch {
180788
180866
  throw new AnchaError("USAGE", "request must be a JSON object");
180789
180867
  }
@@ -182505,13 +182583,13 @@ var init_http = __esm({
182505
182583
  });
182506
182584
 
182507
182585
  // backend/src/credentials.ts
182508
- import { chmod, mkdir as mkdir2, readFile as readFile3, writeFile as writeFile4 } from "node:fs/promises";
182509
- import { dirname as dirname2, join as join4 } from "node:path";
182586
+ import { chmod, mkdir as mkdir2, readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
182587
+ import { dirname as dirname2, join as join5 } from "node:path";
182510
182588
  function credentialsPath(env = process.env) {
182511
182589
  if (env.ANCHA_CREDENTIALS_FILE) return env.ANCHA_CREDENTIALS_FILE;
182512
182590
  const home = env.HOME || (process.platform === "win32" ? env.USERPROFILE : void 0);
182513
- const base4 = env.XDG_CONFIG_HOME || (home ? join4(home, ".config") : "");
182514
- return base4 ? join4(base4, "ancha", "credentials.json") : "";
182591
+ const base4 = env.XDG_CONFIG_HOME || (home ? join5(home, ".config") : "");
182592
+ return base4 ? join5(base4, "ancha", "credentials.json") : "";
182515
182593
  }
182516
182594
  function normalizeServerUrl(value4) {
182517
182595
  const url4 = new URL(value4);
@@ -182530,7 +182608,7 @@ async function readCredentials(env = process.env) {
182530
182608
  const path6 = credentialsPath(env);
182531
182609
  if (!path6) return { version: 1, servers: {} };
182532
182610
  try {
182533
- const parsed3 = JSON.parse(await readFile3(path6, "utf8"));
182611
+ const parsed3 = JSON.parse(await readFile4(path6, "utf8"));
182534
182612
  return { version: 1, ...parsed3.default !== void 0 && { default: parsed3.default }, servers: parsed3.servers ?? {} };
182535
182613
  } catch (e) {
182536
182614
  if (e.code === "ENOENT") return { version: 1, servers: {} };
@@ -182802,8 +182880,8 @@ var init_backend = __esm({
182802
182880
 
182803
182881
  // backend/src/run-bundle.ts
182804
182882
  import { createHash as createHash54 } from "node:crypto";
182805
- import { readdir, readFile as readFile4 } from "node:fs/promises";
182806
- import { join as join5 } from "node:path";
182883
+ import { readdir, readFile as readFile5 } from "node:fs/promises";
182884
+ import { join as join6 } from "node:path";
182807
182885
  import { gunzipSync as gunzipSync2, gzipSync } from "node:zlib";
182808
182886
  function bundleSource(env) {
182809
182887
  return env.CI === "true" || env.GITHUB_ACTIONS ? "ci" : "cli";
@@ -182812,7 +182890,7 @@ async function bundleSecrets(options4) {
182812
182890
  const base4 = new Set(BASE_ENV);
182813
182891
  const names5 = options4.inheritEnv ? Object.keys(options4.env).filter((name5) => !base4.has(name5) && !name5.startsWith("LC_")) : [...options4.passEnv ?? []];
182814
182892
  const values2 = names5.map((name5) => options4.env[name5]);
182815
- const file3 = await readFile4(join5(options4.cwd, ".ancha/openrouter.env"), "utf8").catch(() => "");
182893
+ const file3 = await readFile5(join6(options4.cwd, ".ancha/openrouter.env"), "utf8").catch(() => "");
182816
182894
  for (const line2 of file3.split(/\r?\n/)) {
182817
182895
  const match3 = /^\s*(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=\s*(.*?)\s*$/.exec(line2);
182818
182896
  if (match3) values2.push(match3[1].replace(/^(['"])(.*)\1$/, "$2"));
@@ -182846,7 +182924,7 @@ async function runFiles(runDir, source) {
182846
182924
  const root3 = await readdir(runDir, { withFileTypes: true });
182847
182925
  const paths2 = ["summary.json", "inputs.json", "reproduction.json", "cloud.json"].filter((name5) => allowedFor(source, name5) && root3.some((entry2) => entry2.isFile() && entry2.name === name5));
182848
182926
  for (const dir of root3.filter((entry2) => entry2.isDirectory()).map((entry2) => entry2.name).sort()) {
182849
- for (const file3 of (await readdir(join5(runDir, dir), { withFileTypes: true })).filter((entry2) => entry2.isFile()).map((entry2) => entry2.name).sort()) {
182927
+ for (const file3 of (await readdir(join6(runDir, dir), { withFileTypes: true })).filter((entry2) => entry2.isFile()).map((entry2) => entry2.name).sort()) {
182850
182928
  if (allowedFor(source, `${dir}/${file3}`)) paths2.push(`${dir}/${file3}`);
182851
182929
  }
182852
182930
  }
@@ -182860,7 +182938,7 @@ async function packRun(options4) {
182860
182938
  if (paths2.length + 1 > most) throw tooBig(`run ${options4.runId} has ${paths2.length} files to upload; a run bundle holds at most ${most - 1} besides its manifest`);
182861
182939
  const entries3 = [], omitted = [];
182862
182940
  for (const path6 of paths2) {
182863
- let data5 = redact(await readFile4(join5(options4.runDir, path6)), options4.secrets);
182941
+ let data5 = redact(await readFile5(join6(options4.runDir, path6)), options4.secrets);
182864
182942
  const cap = capFor(path6, options4.inputsBytes);
182865
182943
  if (data5.length > cap) {
182866
182944
  if (path6.endsWith("/agent.log")) data5 = logTail(data5, cap);
@@ -184986,13 +185064,13 @@ var init_utils2 = __esm({
184986
185064
  function is_non_nullish_primitive(v) {
184987
185065
  return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint";
184988
185066
  }
184989
- function inner_stringify(object19, prefix2, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter4, sort, allowDots, serializeDate, format2, formatter, encodeValuesOnly, charset, sideChannel) {
184990
- let obj = object19;
185067
+ function inner_stringify(object20, prefix2, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter4, sort, allowDots, serializeDate, format2, formatter, encodeValuesOnly, charset, sideChannel) {
185068
+ let obj = object20;
184991
185069
  let tmp_sc = sideChannel;
184992
185070
  let step2 = 0;
184993
185071
  let find_flag = false;
184994
185072
  while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) {
184995
- const pos = tmp_sc.get(object19);
185073
+ const pos = tmp_sc.get(object20);
184996
185074
  step2 += 1;
184997
185075
  if (pos !== void 0) {
184998
185076
  if (pos === step2) {
@@ -185078,7 +185156,7 @@ function inner_stringify(object19, prefix2, generateArrayPrefix, commaRoundTrip,
185078
185156
  } else {
185079
185157
  key_prefix = adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]");
185080
185158
  }
185081
- sideChannel.set(object19, step2);
185159
+ sideChannel.set(object20, step2);
185082
185160
  const valueSideChannel = new WeakMap([[sentinel, sideChannel]]);
185083
185161
  push_to_array(values2, inner_stringify(
185084
185162
  value4,
@@ -185171,8 +185249,8 @@ function normalize_stringify_options(opts = defaults2) {
185171
185249
  strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling
185172
185250
  };
185173
185251
  }
185174
- function stringify2(object19, opts = {}) {
185175
- let obj = object19;
185252
+ function stringify2(object20, opts = {}) {
185253
+ let obj = object20;
185176
185254
  const options4 = normalize_stringify_options(opts);
185177
185255
  let obj_keys;
185178
185256
  let filter4;
@@ -197563,8 +197641,8 @@ function parseAgentResult(result, format2) {
197563
197641
  throw new AgentOutputParseError(result);
197564
197642
  }
197565
197643
  }
197566
- function ownJSONValue(object19, key4) {
197567
- const descriptor2 = object19 && Object.getOwnPropertyDescriptor(object19, key4);
197644
+ function ownJSONValue(object20, key4) {
197645
+ const descriptor2 = object20 && Object.getOwnPropertyDescriptor(object20, key4);
197568
197646
  return descriptor2?.enumerable && "value" in descriptor2 ? descriptor2.value : void 0;
197569
197647
  }
197570
197648
  function agentFormatParser(format2) {
@@ -197582,17 +197660,17 @@ function agentFormatParser(format2) {
197582
197660
  const parse15 = descriptor2.value;
197583
197661
  return { type: "json_schema", schema, $parseRaw: (text25) => parse15.call(format2, text25) };
197584
197662
  }
197585
- function snapshotJSONProperty(object19, key4, capture3 = (value4) => value4) {
197586
- const descriptor2 = Object.getOwnPropertyDescriptor(object19, key4);
197663
+ function snapshotJSONProperty(object20, key4, capture3 = (value4) => value4) {
197664
+ const descriptor2 = Object.getOwnPropertyDescriptor(object20, key4);
197587
197665
  if (!descriptor2?.enumerable) {
197588
- return object19;
197666
+ return object20;
197589
197667
  }
197590
- const value4 = capture3(object19[key4]);
197668
+ const value4 = capture3(object20[key4]);
197591
197669
  if ("value" in descriptor2 && value4 === descriptor2.value) {
197592
- return object19;
197670
+ return object20;
197593
197671
  }
197594
- return Object.create(Object.getPrototypeOf(object19), {
197595
- ...Object.getOwnPropertyDescriptors(object19),
197672
+ return Object.create(Object.getPrototypeOf(object20), {
197673
+ ...Object.getOwnPropertyDescriptors(object20),
197596
197674
  [key4]: { value: value4, enumerable: true, configurable: descriptor2.configurable, writable: true }
197597
197675
  });
197598
197676
  }
@@ -208817,9 +208895,7 @@ var init_judge = __esm({
208817
208895
  }
208818
208896
  });
208819
208897
 
208820
- // backend/src/production.ts
208821
- import { readFile as readFile6, writeFile as writeFile5 } from "node:fs/promises";
208822
- import { dirname as dirname3, join as join7 } from "node:path";
208898
+ // backend/src/production-trace.ts
208823
208899
  function productionTrace(lines) {
208824
208900
  let seq2 = 0;
208825
208901
  const entries3 = [];
@@ -208836,14 +208912,24 @@ function productionTrace(lines) {
208836
208912
  path: `/tools/${line2.tool}`,
208837
208913
  status: 200,
208838
208914
  request: { ...line2.args !== void 0 && { args: line2.args } },
208839
- response: { ...line2.error !== void 0 ? { source: "replayed", error: line2.error } : { source: "replayed", ...line2.result !== void 0 && { result: line2.result } }, ...line2.capture && { capture: line2.capture.result, ...line2.capture.result !== "complete" && { execution_status: "unknown" } } }
208915
+ response: { ...line2.call_id && { call_id: line2.call_id }, ...line2.error_type && { error_type: line2.error_type }, ...line2.error !== void 0 ? { source: "replayed", error: line2.error } : { source: "replayed", ...line2.result !== void 0 && { result: line2.result } }, ...line2.capture && { capture: line2.capture.result, ...line2.capture.result !== "complete" && { execution_status: "unknown" } } }
208840
208916
  });
208841
208917
  }
208842
208918
  if (invocation?.output !== void 0) entries3.push({ seq: ++seq2, tSim: "", tReal: 0, source: "agent", service: "agent", method: "POST", path: "/done", status: 200, request: { output: invocation.output } });
208843
208919
  return entries3;
208844
208920
  }
208921
+ var init_production_trace = __esm({
208922
+ "backend/src/production-trace.ts"() {
208923
+ "use strict";
208924
+ init_src();
208925
+ }
208926
+ });
208927
+
208928
+ // backend/src/production.ts
208929
+ import { readFile as readFile7, writeFile as writeFile5 } from "node:fs/promises";
208930
+ import { dirname as dirname3, join as join8 } from "node:path";
208845
208931
  async function productionRecord(dir) {
208846
- const text25 = await readFile6(join7(dir, "production.jsonl"), "utf8").catch(() => void 0);
208932
+ const text25 = await readFile7(join8(dir, "production.jsonl"), "utf8").catch(() => void 0);
208847
208933
  return text25 === void 0 ? void 0 : productionTrace(text25.split("\n").filter(Boolean).map((line2) => JSON.parse(line2)));
208848
208934
  }
208849
208935
  var init_production = __esm({
@@ -208853,19 +208939,21 @@ var init_production = __esm({
208853
208939
  init_src2();
208854
208940
  init_production_state();
208855
208941
  init_judge();
208942
+ init_production_trace();
208943
+ init_production_trace();
208856
208944
  }
208857
208945
  });
208858
208946
 
208859
208947
  // backend/src/production-comparison.ts
208860
- import { readFile as readFile7 } from "node:fs/promises";
208861
- import { dirname as dirname4, join as join8, resolve as resolve8 } from "node:path";
208948
+ import { readFile as readFile8 } from "node:fs/promises";
208949
+ import { dirname as dirname4, join as join9, resolve as resolve8 } from "node:path";
208862
208950
  async function reproductionOf(summary, scenePaths, cwd, runDir, scenes = [], productionFiles = {}) {
208863
208951
  const out = [];
208864
208952
  for (const scene2 of summary.scenes) {
208865
208953
  const path6 = scenePaths[scene2.sceneId];
208866
208954
  if (path6 === void 0) continue;
208867
- const file3 = Object.hasOwn(productionFiles, scene2.sceneId) ? productionFiles[scene2.sceneId] : join8(dirname4(resolve8(cwd, path6)), "production.json");
208868
- const production2 = await readFile7(file3, "utf8").then((text25) => JSON.parse(text25), () => void 0);
208955
+ const file3 = Object.hasOwn(productionFiles, scene2.sceneId) ? productionFiles[scene2.sceneId] : join9(dirname4(resolve8(cwd, path6)), "production.json");
208956
+ const production2 = await readFile8(file3, "utf8").then((text25) => JSON.parse(text25), () => void 0);
208869
208957
  if (production2?.checks === void 0) continue;
208870
208958
  const checks2 = Object.entries(production2.checks).flatMap(([check3, result]) => {
208871
208959
  const here = scene2.checks[check3];
@@ -208919,7 +209007,7 @@ async function reproductionOf(summary, scenePaths, cwd, runDir, scenes = [], pro
208919
209007
  async function answerSources(runDir, scene2) {
208920
209008
  const counts2 = {};
208921
209009
  for (const { trial } of scene2.trialsDetail) {
208922
- const text25 = await readFile7(join8(runDir, `trial-${scene2.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
209010
+ const text25 = await readFile8(join9(runDir, `trial-${scene2.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
208923
209011
  for (const entry2 of text25.split("\n").filter(Boolean).map((line2) => JSON.parse(line2))) {
208924
209012
  const source = entry2.service === "tools" && entry2.path?.startsWith("/tools/") ? entry2.response?.source : void 0;
208925
209013
  if (source) counts2[source] = (counts2[source] ?? 0) + 1;
@@ -208934,7 +209022,7 @@ async function writesOf(scene2, dir, runDir, ran) {
208934
209022
  for (const action of actionsOf(scene2, record13)) made.set(action.tool, (made.get(action.tool) ?? 0) + 1);
208935
209023
  const trials = (ran.trialsDetail ?? []).filter((t) => t.valid !== false);
208936
209024
  for (const { trial } of trials) {
208937
- const text25 = await readFile7(join8(runDir, `trial-${ran.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
209025
+ const text25 = await readFile8(join9(runDir, `trial-${ran.sceneId}-${trial}`, "trace.jsonl"), "utf8").catch(() => "");
208938
209026
  const trace = text25.split("\n").filter(Boolean).map((line2) => JSON.parse(line2));
208939
209027
  for (const tool of new Set(actionsOf(scene2, trace).map((action) => action.tool))) here.set(tool, (here.get(tool) ?? 0) + 1);
208940
209028
  }
@@ -209037,7 +209125,7 @@ import { spawn } from "node:child_process";
209037
209125
  import { randomUUID as randomUUID4 } from "node:crypto";
209038
209126
  import { closeSync as closeSync2, fstatSync as fstatSync2, openSync as openSync2, readSync, unlinkSync, writeSync } from "node:fs";
209039
209127
  import { tmpdir } from "node:os";
209040
- import { join as join9 } from "node:path";
209128
+ import { join as join10 } from "node:path";
209041
209129
  import { StringDecoder } from "node:string_decoder";
209042
209130
  import { setTimeout as sleep5 } from "node:timers/promises";
209043
209131
  function signalGroup(pid, signal) {
@@ -209060,7 +209148,7 @@ function groupAlive(pid) {
209060
209148
  }
209061
209149
  function outputCopy(logFd) {
209062
209150
  const open4 = () => {
209063
- const path6 = join9(tmpdir(), `ancha-output-${randomUUID4()}`), fd = openSync2(path6, "wx+", 384);
209151
+ const path6 = join10(tmpdir(), `ancha-output-${randomUUID4()}`), fd = openSync2(path6, "wx+", 384);
209064
209152
  try {
209065
209153
  unlinkSync(path6);
209066
209154
  } catch {
@@ -209229,7 +209317,7 @@ var init_contained_env = __esm({
209229
209317
  // backend/src/execution/source.ts
209230
209318
  import { constants as constants5 } from "node:fs";
209231
209319
  import { chmod as chmod2, lstat, mkdir as mkdir3, open as open2, readdir as readdir2, realpath } from "node:fs/promises";
209232
- import { basename as basename4, dirname as dirname5, isAbsolute as isAbsolute3, join as join10, relative as relative4, resolve as resolve9, sep, win32 } from "node:path";
209320
+ import { basename as basename4, dirname as dirname5, isAbsolute as isAbsolute3, join as join11, relative as relative4, resolve as resolve9, sep, win32 } from "node:path";
209233
209321
  function invalid31(message7) {
209234
209322
  return new AnchaError("CONFIG_INVALID", `Cannot stage agent source: ${message7}`, {
209235
209323
  hint: "Select only source files or directories. Put Linux dependencies in the runtime image and pass credentials explicitly."
@@ -209290,7 +209378,7 @@ async function stageProject(sourceRoot, selections2, destination, options4 = {})
209290
209378
  if (destinationEntry && (!destinationEntry.isDirectory() || destinationEntry.isSymbolicLink())) {
209291
209379
  throw invalid31("staging destination must be a real empty directory");
209292
209380
  }
209293
- const target5 = destinationEntry ? await realpath(requestedDestination) : join10(await realpath(dirname5(requestedDestination)), basename4(requestedDestination));
209381
+ const target5 = destinationEntry ? await realpath(requestedDestination) : join11(await realpath(dirname5(requestedDestination)), basename4(requestedDestination));
209294
209382
  if (within(source, target5) || within(target5, source)) throw invalid31("staging destination must be separate from the project directory");
209295
209383
  if (destinationEntry && (await readdir2(target5)).length > 0) throw invalid31("staging destination must be empty");
209296
209384
  if (!destinationEntry) await mkdir3(target5, { mode: 493 });
@@ -209302,7 +209390,7 @@ async function stageProject(sourceRoot, selections2, destination, options4 = {})
209302
209390
  const parts3 = relative4(target5, path6).split(sep).filter(Boolean);
209303
209391
  let current = target5;
209304
209392
  for (const part of parts3) {
209305
- current = join10(current, part);
209393
+ current = join11(current, part);
209306
209394
  try {
209307
209395
  await mkdir3(current, { mode: 493 });
209308
209396
  } catch (error64) {
@@ -209325,7 +209413,7 @@ async function stageProject(sourceRoot, selections2, destination, options4 = {})
209325
209413
  const entries3 = await readdir2(path6);
209326
209414
  if (path6 !== source && entries3.includes("scene.yaml")) return;
209327
209415
  for (const entry2 of entries3.sort()) {
209328
- if (!excluded(entry2) && !definitionFile(source, path6, entry2, entries3) && !excludedPaths.has(join10(path6, entry2))) await copy(join10(path6, entry2));
209416
+ if (!excluded(entry2) && !definitionFile(source, path6, entry2, entries3) && !excludedPaths.has(join11(path6, entry2))) await copy(join11(path6, entry2));
209329
209417
  }
209330
209418
  return;
209331
209419
  }
@@ -209340,7 +209428,7 @@ async function stageProject(sourceRoot, selections2, destination, options4 = {})
209340
209428
  const opened = await input5.stat();
209341
209429
  if (!sameFile(stat3, opened) || !opened.isFile() || opened.nlink !== 1 || opened.size !== stat3.size) throw invalid31(`source changed while opening: ${name5}`);
209342
209430
  await sourceStat(path6);
209343
- const outputPath = join10(target5, name5);
209431
+ const outputPath = join11(target5, name5);
209344
209432
  await destinationDirectory(dirname5(outputPath));
209345
209433
  const output2 = await open2(outputPath, constants5.O_WRONLY | constants5.O_CREAT | constants5.O_EXCL | constants5.O_NOFOLLOW, 384);
209346
209434
  try {
@@ -209733,7 +209821,7 @@ import { randomUUID as randomUUID5 } from "node:crypto";
209733
209821
  import { writeSync as writeSync2 } from "node:fs";
209734
209822
  import { copyFile as copyFile2, mkdir as mkdir4, mkdtemp, rm, writeFile as writeFile6 } from "node:fs/promises";
209735
209823
  import { tmpdir as tmpdir2 } from "node:os";
209736
- import { join as join11 } from "node:path";
209824
+ import { join as join12 } from "node:path";
209737
209825
  import { promisify as promisify2 } from "node:util";
209738
209826
  function dockerEnvironment() {
209739
209827
  return Object.fromEntries(["PATH", "HOME", "DOCKER_CONFIG", "XDG_RUNTIME_DIR", "TMPDIR"].flatMap((key4) => process.env[key4] ? [[key4, process.env[key4]]] : []));
@@ -209829,7 +209917,7 @@ async function startContainedAgent(command, opts) {
209829
209917
  const relayImage = await inspectImage(RELAY_IMAGE, context3, opts.signal);
209830
209918
  const id14 = `ancha-${randomUUID5()}`;
209831
209919
  const agentName2 = `${id14}-agent`, relayName = `${id14}-relay`, volume = `${id14}-source`, helperName = `${id14}-copy`;
209832
- const temporary = await mkdtemp(join11(tmpdir2(), "ancha-source-"));
209920
+ const temporary = await mkdtemp(join12(tmpdir2(), "ancha-source-"));
209833
209921
  const startup2 = AbortSignal.any([AbortSignal.timeout(9e4), ...opts.signal ? [opts.signal] : [], ...opts.startupSignal ? [opts.startupSignal] : []]);
209834
209922
  let gateway;
209835
209923
  let relay;
@@ -209880,23 +209968,23 @@ async function startContainedAgent(command, opts) {
209880
209968
  });
209881
209969
  };
209882
209970
  try {
209883
- const source = await stageProject(opts.agent.cwd, policy.files, join11(temporary, "project"), { ...opts.agent.privatePaths && { exclude: opts.agent.privatePaths } });
209971
+ const source = await stageProject(opts.agent.cwd, policy.files, join12(temporary, "project"), { ...opts.agent.privatePaths && { exclude: opts.agent.privatePaths } });
209884
209972
  const records3 = opts.runtime?.attempt?.records;
209885
209973
  if (records3 !== void 0) {
209886
- await mkdir4(join11(temporary, "project", ".ancha-records"), { recursive: true });
209887
- await copyFile2(records3, join11(temporary, "project", CONTAINER_RECORDS));
209974
+ await mkdir4(join12(temporary, "project", ".ancha-records"), { recursive: true });
209975
+ await copyFile2(records3, join12(temporary, "project", CONTAINER_RECORDS));
209888
209976
  }
209889
209977
  const withTask = opts.agent.mode !== "endpoint";
209890
209978
  if (withTask) {
209891
- await mkdir4(join11(temporary, "project", ".ancha-task"), { recursive: true });
209892
- await writeFile6(join11(temporary, "project", CONTAINER_TASK), agentTask(opts.scene, opts.runtime));
209979
+ await mkdir4(join12(temporary, "project", ".ancha-task"), { recursive: true });
209980
+ await writeFile6(join12(temporary, "project", CONTAINER_TASK), agentTask(opts.scene, opts.runtime));
209893
209981
  }
209894
209982
  startup2.throwIfAborted();
209895
209983
  createdVolume = true;
209896
209984
  await run4(["volume", "create", "--label", `${LABEL2}=true`, volume]);
209897
209985
  containers.add(helperName);
209898
209986
  await run4(["create", "--name", helperName, "--label", `${LABEL2}=true`, "--network", "none", "--cap-drop", "ALL", "--security-opt", "no-new-privileges=true", "--mount", `type=volume,source=${volume},target=/workspace`, "--entrypoint", "/bin/sh", relayImage.id, "-c", "find /workspace -type d -exec chmod 755 {} +; find /workspace -type f -exec chmod a+r {} +; ln -s /opt/ancha/node_modules /workspace/node_modules"]);
209899
- await run4(["cp", join11(temporary, "project") + "/.", `${helperName}:/workspace`]);
209987
+ await run4(["cp", join12(temporary, "project") + "/.", `${helperName}:/workspace`]);
209900
209988
  await run4(["start", "-a", helperName]);
209901
209989
  await run4(["rm", helperName]);
209902
209990
  containers.delete(helperName);
@@ -209987,7 +210075,7 @@ async function startContainedAgent(command, opts) {
209987
210075
  const input5 = `exec /usr/bin/env -i ${names5.map((name5) => quote2(`${name5}=${values2[name5] ?? ""}`)).join(" ")} /bin/sh -c ${quote2(command)}${stdin}
209988
210076
  `;
209989
210077
  if (Buffer.byteLength(input5) > 262144 || input5.includes("\0")) throw new AnchaError("CONFIG_INVALID", "Container launch environment and command exceed the supported size or contain a NUL byte");
209990
- await writeFile6(join11(opts.dir, "execution.json"), JSON.stringify({ ...executionDescription({ ...opts.agent, execution: policy }), context: context3, imageId: image2.id, source, container: agentName2 }, null, 2) + "\n", { mode: 384 });
210078
+ await writeFile6(join12(opts.dir, "execution.json"), JSON.stringify({ ...executionDescription({ ...opts.agent, execution: policy }), context: context3, imageId: image2.id, source, container: agentName2 }, null, 2) + "\n", { mode: 384 });
209991
210079
  child2 = spawn2("docker", ["--context", context3, "exec", "-i", agentName2, "/bin/sh"], {
209992
210080
  env: dockerEnvironment(),
209993
210081
  stdio: ["pipe", "pipe", "pipe"]
@@ -210089,11 +210177,11 @@ var init_docker = __esm({
210089
210177
  // backend/src/execution/python-environment.ts
210090
210178
  import { constants as constants6 } from "node:fs";
210091
210179
  import { access as access3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
210092
- import { join as join12 } from "node:path";
210180
+ import { join as join13 } from "node:path";
210093
210181
  async function pythonEnvironment(cwd, pathPrepend, values2) {
210094
- const venv = join12(cwd, ".venv"), bin = join12(venv, "bin");
210095
- if ((await stat2(join12(venv, "pyvenv.cfg")).catch(() => void 0))?.isFile()) {
210096
- const executable = await access3(join12(bin, "python"), constants6.X_OK).then(() => true, () => false);
210182
+ const venv = join13(cwd, ".venv"), bin = join13(venv, "bin");
210183
+ if ((await stat2(join13(venv, "pyvenv.cfg")).catch(() => void 0))?.isFile()) {
210184
+ const executable = await access3(join13(bin, "python"), constants6.X_OK).then(() => true, () => false);
210097
210185
  if (!pathPrepend.includes(bin) || !executable) {
210098
210186
  throw new AnchaError("CONFIG_INVALID", "The prepared .venv Python interpreter cannot be executed. Check agent.install.");
210099
210187
  }
@@ -210103,7 +210191,7 @@ async function pythonEnvironment(cwd, pathPrepend, values2) {
210103
210191
  values2.VIRTUAL_ENV = venv;
210104
210192
  }
210105
210193
  const root3 = await realpath2(cwd);
210106
- const src = join12(cwd, "src"), actual = await realpath2(src).catch(() => void 0);
210194
+ const src = join13(cwd, "src"), actual = await realpath2(src).catch(() => void 0);
210107
210195
  if (actual !== void 0 && actual.startsWith(`${root3}/`) && (await stat2(src)).isDirectory()) {
210108
210196
  values2.PYTHONPATH = [src, cwd, ...values2.PYTHONPATH ? values2.PYTHONPATH.split(":") : []].filter((path6, index, paths2) => paths2.indexOf(path6) === index).join(":");
210109
210197
  }
@@ -210119,7 +210207,7 @@ var init_python_environment = __esm({
210119
210207
  import { execFile as execFile3, spawn as spawn3 } from "node:child_process";
210120
210208
  import { writeSync as writeSync3 } from "node:fs";
210121
210209
  import { chmod as chmod3, chown, copyFile as copyFile3, mkdir as mkdir5, mkdtemp as mkdtemp2, writeFile as writeFile7 } from "node:fs/promises";
210122
- import { dirname as dirname6, join as join13 } from "node:path";
210210
+ import { dirname as dirname6, join as join14 } from "node:path";
210123
210211
  import { StringDecoder as StringDecoder3 } from "node:string_decoder";
210124
210212
  import { setTimeout as sleep6 } from "node:timers/promises";
210125
210213
  import { promisify as promisify3 } from "node:util";
@@ -210158,9 +210246,9 @@ async function ownedPaths(descriptor2, unsafe) {
210158
210246
  let pending = directories.get(descriptor2);
210159
210247
  if (!pending) {
210160
210248
  pending = (async () => {
210161
- const root3 = await mkdtemp2(join13(dirname6(descriptor2.agentDir), ".ancha-runtime-"));
210249
+ const root3 = await mkdtemp2(join14(dirname6(descriptor2.agentDir), ".ancha-runtime-"));
210162
210250
  await chmod3(root3, 457);
210163
- const paths2 = { root: root3, home: join13(root3, "home"), tmp: join13(root3, "tmp"), state: join13(root3, "state") };
210251
+ const paths2 = { root: root3, home: join14(root3, "home"), tmp: join14(root3, "tmp"), state: join14(root3, "state") };
210164
210252
  for (const path6 of [paths2.home, paths2.tmp, paths2.state]) {
210165
210253
  await mkdir5(path6, { mode: 448 });
210166
210254
  if (!unsafe) await chown(path6, descriptor2.uid, descriptor2.gid);
@@ -210250,16 +210338,16 @@ async function startVmAgent(command, opts, deps = {}) {
210250
210338
  const paths2 = await ownedPaths(descriptor2, unsafe);
210251
210339
  let records3;
210252
210340
  if (opts.runtime?.attempt?.records !== void 0) {
210253
- const directory = await mkdtemp2(join13(paths2.root, "records-"));
210254
- records3 = join13(directory, "records.jsonl");
210341
+ const directory = await mkdtemp2(join14(paths2.root, "records-"));
210342
+ records3 = join14(directory, "records.jsonl");
210255
210343
  await copyFile3(opts.runtime.attempt.records, records3);
210256
210344
  await chmod3(records3, 292);
210257
210345
  await chmod3(directory, 457);
210258
210346
  }
210259
210347
  let taskFile;
210260
210348
  if (opts.agent.mode !== "endpoint") {
210261
- const directory = await mkdtemp2(join13(paths2.root, "task-"));
210262
- taskFile = join13(directory, "task.txt");
210349
+ const directory = await mkdtemp2(join14(paths2.root, "task-"));
210350
+ taskFile = join14(directory, "task.txt");
210263
210351
  await writeFile7(taskFile, agentTask(opts.scene, opts.runtime), { mode: 292 });
210264
210352
  await chmod3(taskFile, 292);
210265
210353
  await chmod3(directory, 457);
@@ -210285,12 +210373,12 @@ async function startVmAgent(command, opts, deps = {}) {
210285
210373
  paths: { ...paths2, path: [...descriptor2.pathPrepend, VM_PATH].join(":") }
210286
210374
  });
210287
210375
  await pythonEnvironment(descriptor2.agentDir, descriptor2.pathPrepend, values2);
210288
- Object.assign(values2, { XDG_CONFIG_HOME: join13(paths2.home, ".config"), XDG_CACHE_HOME: join13(paths2.home, ".cache"), XDG_DATA_HOME: join13(paths2.home, ".local/share"), LANG: "C.UTF-8", TZ: "UTC" });
210376
+ Object.assign(values2, { XDG_CONFIG_HOME: join14(paths2.home, ".config"), XDG_CACHE_HOME: join14(paths2.home, ".cache"), XDG_DATA_HOME: join14(paths2.home, ".local/share"), LANG: "C.UTF-8", TZ: "UTC" });
210289
210377
  if (Object.entries(values2).some(([name5, value4]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name5) || value4?.includes("\0")) || Buffer.byteLength(JSON.stringify(values2)) + Buffer.byteLength(command) > 262144) {
210290
210378
  throw new AnchaError("CONFIG_INVALID", "Agent launch environment and command must fit within 256 KiB and contain valid variable names.");
210291
210379
  }
210292
210380
  await mkdir5(opts.dir, { recursive: true });
210293
- await writeFile7(join13(opts.dir, "execution.json"), JSON.stringify({ mode: "vm", runtime: runtime2, contained: !unsafe, network: unsafe ? "local-test" : "loopback-with-scoped-gateway", project: "prepared-copy", scratch: "fresh-per-attempt", credentials: "explicit-only", modelHosts, uid: descriptor2.uid, gid: descriptor2.gid, pids: 1024 }, null, 2) + "\n", { mode: 384 });
210381
+ await writeFile7(join14(opts.dir, "execution.json"), JSON.stringify({ mode: "vm", runtime: runtime2, contained: !unsafe, network: unsafe ? "local-test" : "loopback-with-scoped-gateway", project: "prepared-copy", scratch: "fresh-per-attempt", credentials: "explicit-only", modelHosts, uid: descriptor2.uid, gid: descriptor2.gid, pids: 1024 }, null, 2) + "\n", { mode: 384 });
210294
210382
  opts.signal?.throwIfAborted();
210295
210383
  opts.startupSignal?.throwIfAborted();
210296
210384
  const protectedValues = [
@@ -210499,7 +210587,7 @@ var init_run_inputs = __esm({
210499
210587
 
210500
210588
  // backend/src/runner/artifacts.ts
210501
210589
  import { open as open3, writeFile as writeFile9 } from "node:fs/promises";
210502
- import { join as join14 } from "node:path";
210590
+ import { join as join15 } from "node:path";
210503
210591
  async function logTail2(path6) {
210504
210592
  const file3 = await open3(path6, "r");
210505
210593
  try {
@@ -210536,24 +210624,24 @@ async function captureTrial(backend, envId, sessionId, dir, scene2, judge = {},
210536
210624
  const capture3 = await evaluateJudges(scene2, frozen, judge);
210537
210625
  onCaptured?.(capture3);
210538
210626
  await Promise.all([
210539
- writeFile9(join14(dir, "trace.jsonl"), capture3.trace.map((e) => `${JSON.stringify(e)}
210627
+ writeFile9(join15(dir, "trace.jsonl"), capture3.trace.map((e) => `${JSON.stringify(e)}
210540
210628
  `).join("")),
210541
210629
  // A large world's record tables stay out: the change log and small parts are kept (run-inputs.ts).
210542
- writeFile9(join14(dir, "state.json"), `${JSON.stringify(keptState(capture3.state), null, 2)}
210630
+ writeFile9(join15(dir, "state.json"), `${JSON.stringify(keptState(capture3.state), null, 2)}
210543
210631
  `),
210544
- writeFile9(join14(dir, "checks.json"), `${JSON.stringify(capture3.checks, null, 2)}
210632
+ writeFile9(join15(dir, "checks.json"), `${JSON.stringify(capture3.checks, null, 2)}
210545
210633
  `),
210546
210634
  // Every people-model call, in order: who, what kind, which model, hashes, tokens, cost and the answer. No credentials.
210547
- ...capture3.people?.length ? [writeFile9(join14(dir, "people.jsonl"), capture3.people.map((record13) => `${JSON.stringify(record13)}
210635
+ ...capture3.people?.length ? [writeFile9(join15(dir, "people.jsonl"), capture3.people.map((record13) => `${JSON.stringify(record13)}
210548
210636
  `).join(""))] : [],
210549
210637
  // A replay: how many answers came from the recording, how many live, and where it first diverged.
210550
- ...capture3.peopleReplay ? [writeFile9(join14(dir, "people-replay.json"), `${JSON.stringify(capture3.peopleReplay, null, 2)}
210638
+ ...capture3.peopleReplay ? [writeFile9(join15(dir, "people-replay.json"), `${JSON.stringify(capture3.peopleReplay, null, 2)}
210551
210639
  `)] : [],
210552
210640
  // What passed between the agent and people, for the console; fact ids only, never values.
210553
- ...capture3.peopleTimeline ? [writeFile9(join14(dir, "people-timeline.json"), `${JSON.stringify(capture3.peopleTimeline, null, 2)}
210641
+ ...capture3.peopleTimeline ? [writeFile9(join15(dir, "people-timeline.json"), `${JSON.stringify(capture3.peopleTimeline, null, 2)}
210554
210642
  `)] : [],
210555
210643
  // Why each failed check failed, from the world's records (explain v2).
210556
- ...capture3.explanations?.length ? [writeFile9(join14(dir, "explain.json"), `${JSON.stringify(capture3.explanations, null, 2)}
210644
+ ...capture3.explanations?.length ? [writeFile9(join15(dir, "explain.json"), `${JSON.stringify(capture3.explanations, null, 2)}
210557
210645
  `)] : []
210558
210646
  ]);
210559
210647
  return capture3;
@@ -210598,7 +210686,7 @@ var init_budget = __esm({
210598
210686
  import { closeSync as closeSync3, openSync as openSync3, writeSync as writeSync4 } from "node:fs";
210599
210687
  import { mkdir as mkdir6 } from "node:fs/promises";
210600
210688
  import { createServer as createServer3 } from "node:net";
210601
- import { join as join15, resolve as resolve11 } from "node:path";
210689
+ import { join as join16, resolve as resolve11 } from "node:path";
210602
210690
  import { setTimeout as sleep7 } from "node:timers/promises";
210603
210691
  function deadline2(ms) {
210604
210692
  const controller = new AbortController();
@@ -210715,7 +210803,7 @@ async function runEndpointTrial(spec) {
210715
210803
  const session2 = await backend.prepareTrial(env.id, { mode: "endpoint", idleMs: agent.idleMs, slackTransport: agent.slackTransport ?? "http", ...agent.setupCalls && { setupCalls: true }, ...clockFile && { clockFile }, ...agent.execution?.mode === "container" && { clientOrigin: "http://127.0.0.1:18991" } });
210716
210804
  const runtime2 = { ...port && { port: managedAppPort(agent.url, port.port, agentTemplateVars(env.id, env.services, scene2.task ?? "", trial, session2)) }, ...spec.attempt && { attempt: spec.attempt } };
210717
210805
  const vars = agentTemplateVars(env.id, env.services, scene2.task ?? "", trial, session2, runtime2, env.mcp);
210718
- const logFd = openSync3(join15(dir, "agent.log"), "w");
210806
+ const logFd = openSync3(join16(dir, "agent.log"), "w");
210719
210807
  const startedAt = performance.now();
210720
210808
  const startup2 = deadline2(agent.startupTimeoutMs);
210721
210809
  const bootstrapCancellation = new AbortController();
@@ -210785,7 +210873,7 @@ async function runEndpointTrial(spec) {
210785
210873
  }
210786
210874
  } catch (error64) {
210787
210875
  const cause = error64 instanceof Error ? error64.message : String(error64);
210788
- const reported = !started2 && !signal?.aborted && !(error64 instanceof AnchaError) ? new AnchaError("AGENT_UNREACHABLE", `endpoint startup failed: ${cause}`, { hint: `Check agent.start, ready_url and setup_url; see ${join15(dir, "agent.log")}`, cause: error64 }) : error64;
210876
+ const reported = !started2 && !signal?.aborted && !(error64 instanceof AnchaError) ? new AnchaError("AGENT_UNREACHABLE", `endpoint startup failed: ${cause}`, { hint: `Check agent.start, ready_url and setup_url; see ${join16(dir, "agent.log")}`, cause: error64 }) : error64;
210789
210877
  writeSync4(logFd, `ancha: ${reported instanceof Error ? reported.message : String(reported)}
210790
210878
  `);
210791
210879
  failure5 = { error: reported };
@@ -210822,7 +210910,7 @@ async function runEndpointTrial(spec) {
210822
210910
  valid: !harnessIssues.some((issue8) => issue8.owner === "harness"),
210823
210911
  harnessIssues,
210824
210912
  passed: checks2.every((check3) => !check3.required || check3.passed),
210825
- logTail: result.exit === "done" || result.exit === "idle" || result.exit === "exited" && result.exitCode === 0 ? [] : await logTail2(join15(dir, "agent.log"))
210913
+ logTail: result.exit === "done" || result.exit === "idle" || result.exit === "exited" && result.exitCode === 0 ? [] : await logTail2(join16(dir, "agent.log"))
210826
210914
  };
210827
210915
  } finally {
210828
210916
  if (port && !released) await port.release();
@@ -210848,7 +210936,7 @@ var init_endpoint = __esm({
210848
210936
  import { closeSync as closeSync4, openSync as openSync4 } from "node:fs";
210849
210937
  import { mkdir as mkdir7 } from "node:fs/promises";
210850
210938
  import { createServer as createServer4 } from "node:net";
210851
- import { join as join16 } from "node:path";
210939
+ import { join as join17 } from "node:path";
210852
210940
  import { setTimeout as sleep8 } from "node:timers/promises";
210853
210941
  async function reserve(used) {
210854
210942
  const held = [];
@@ -210907,7 +210995,7 @@ async function runHttpTaskTrial(spec) {
210907
210995
  };
210908
210996
  await record13({});
210909
210997
  spec.onPrepared?.();
210910
- const started2 = performance.now(), logFd = openSync4(join16(dir, "agent.log"), "w");
210998
+ const started2 = performance.now(), logFd = openSync4(join17(dir, "agent.log"), "w");
210911
210999
  let child2;
210912
211000
  let port;
210913
211001
  let released = false, ready3 = false, timedOut = false;
@@ -211049,7 +211137,7 @@ async function runHttpTaskTrial(spec) {
211049
211137
  harnessIssues: issues,
211050
211138
  valid: !issues.some((issue8) => issue8.owner === "harness"),
211051
211139
  passed: capture3.checks.every((check3) => !check3.required || check3.passed),
211052
- logTail: failure5 ? await logTail2(join16(dir, "agent.log")) : [],
211140
+ logTail: failure5 ? await logTail2(join17(dir, "agent.log")) : [],
211053
211141
  dir,
211054
211142
  taskDelivery: delivery
211055
211143
  };
@@ -211073,7 +211161,7 @@ var init_http_task = __esm({
211073
211161
  // backend/src/runner/per-event.ts
211074
211162
  import { closeSync as closeSync5, openSync as openSync5, writeSync as writeSync5 } from "node:fs";
211075
211163
  import { mkdir as mkdir8 } from "node:fs/promises";
211076
- import { join as join17 } from "node:path";
211164
+ import { join as join18 } from "node:path";
211077
211165
  async function runPerEventTrial(spec) {
211078
211166
  const { backend, env, scene: scene2, agent, trial, dir, signal, inheritedEnv = process.env } = spec;
211079
211167
  signal?.throwIfAborted();
@@ -211083,7 +211171,7 @@ async function runPerEventTrial(spec) {
211083
211171
  const session2 = await backend.prepareTrial(env.id, { mode: "command", slackTransport: agent.slackTransport ?? "feed", ...agent.execution?.mode === "container" && { clientOrigin: "http://127.0.0.1:18991" } });
211084
211172
  spec.onPrepared?.();
211085
211173
  signal?.throwIfAborted();
211086
- const logFd = openSync5(join17(dir, "agent.log"), "w");
211174
+ const logFd = openSync5(join18(dir, "agent.log"), "w");
211087
211175
  const startedAt = performance.now();
211088
211176
  let timedOut = false, spawnFailed = false, started2 = false, firstFailure, invocations = 0, failedInvocations = 0;
211089
211177
  let failure5;
@@ -211178,7 +211266,7 @@ async function runPerEventTrial(spec) {
211178
211266
  simMs,
211179
211267
  checks: checks2,
211180
211268
  invocations: { total: invocations, failed: failedInvocations },
211181
- logTail: exit === "exited" && failedInvocations === 0 ? [] : await logTail2(join17(dir, "agent.log")),
211269
+ logTail: exit === "exited" && failedInvocations === 0 ? [] : await logTail2(join18(dir, "agent.log")),
211182
211270
  passed: failedInvocations === 0 && checks2.every((c) => !c.required || c.passed),
211183
211271
  trace,
211184
211272
  dir,
@@ -211230,7 +211318,7 @@ var init_agent_outcome = __esm({
211230
211318
  import { setTimeout as sleep9 } from "node:timers/promises";
211231
211319
  import { closeSync as closeSync6, openSync as openSync6, writeSync as writeSync6 } from "node:fs";
211232
211320
  import { mkdir as mkdir9 } from "node:fs/promises";
211233
- import { join as join18 } from "node:path";
211321
+ import { join as join19 } from "node:path";
211234
211322
  function answersFrom(agent, source) {
211235
211323
  const mode = agent.answer ?? "auto";
211236
211324
  return mode === "auto" || mode === "stdout" && source === "stdout";
@@ -211275,7 +211363,7 @@ async function runTrial(spec) {
211275
211363
  const session2 = await backend.prepareTrial(env.id, { mode: "command", slackTransport: agent.slackTransport ?? "feed", ...idleMs !== void 0 && { idleMs }, ...agent.execution?.mode === "container" && { clientOrigin: "http://127.0.0.1:18991" } });
211276
211364
  spec.onPrepared?.();
211277
211365
  signal?.throwIfAborted();
211278
- const logFd = openSync6(join18(dir, "agent.log"), "w");
211366
+ const logFd = openSync6(join19(dir, "agent.log"), "w");
211279
211367
  const startedAt = performance.now();
211280
211368
  let modelRequests = 0, modelActivityVersion = 0;
211281
211369
  let failure5;
@@ -211408,7 +211496,7 @@ async function runTrial(spec) {
211408
211496
  ...playOut !== void 0 && playOut.toMs > playOut.fromMs && { playOut },
211409
211497
  checks: checks2,
211410
211498
  ...output2?.modelReplies?.length && { modelReplies: output2.modelReplies },
211411
- logTail: exit === "idle" || exit === "done" || exit === "exited" && exitCode === 0 ? [] : await logTail2(join18(dir, "agent.log")),
211499
+ logTail: exit === "idle" || exit === "done" || exit === "exited" && exitCode === 0 ? [] : await logTail2(join19(dir, "agent.log")),
211412
211500
  // An agent that exits non-zero or dies by a signal on its own fails its trial whatever the checks say, as a per_event
211413
211501
  // invocation does: an agent that crashed before its first call would otherwise pass every not_called check.
211414
211502
  passed: checks2.every((c) => !c.required || c.passed) && !(exit === "exited" && exitCode !== 0),
@@ -211442,11 +211530,11 @@ var init_trial = __esm({
211442
211530
 
211443
211531
  // backend/src/runner/invalid-trial.ts
211444
211532
  import { mkdir as mkdir10 } from "node:fs/promises";
211445
- import { join as join19 } from "node:path";
211533
+ import { join as join20 } from "node:path";
211446
211534
  async function invalidTrial(options4) {
211447
211535
  const { scene: scene2, trial, dir, startedAt, error: error64, service = "world", envId, sessionId, capture: capture3 } = options4;
211448
211536
  await mkdir10(dir, { recursive: true });
211449
- const tail = await logTail2(join19(dir, "agent.log")).catch((failure5) => {
211537
+ const tail = await logTail2(join20(dir, "agent.log")).catch((failure5) => {
211450
211538
  if (failure5?.code === "ENOENT") return [];
211451
211539
  throw failure5;
211452
211540
  });
@@ -211482,8 +211570,8 @@ var init_invalid_trial = __esm({
211482
211570
 
211483
211571
  // backend/src/runner/run.ts
211484
211572
  import { createHash as createHash56, randomInt } from "node:crypto";
211485
- import { access as access4, mkdir as mkdir11, readFile as readFile8, writeFile as writeFile10 } from "node:fs/promises";
211486
- import { dirname as dirname7, join as join20, relative as relative5, resolve as resolve12 } from "node:path";
211573
+ import { access as access4, mkdir as mkdir11, readFile as readFile9, writeFile as writeFile10 } from "node:fs/promises";
211574
+ import { dirname as dirname7, join as join21, relative as relative5, resolve as resolve12 } from "node:path";
211487
211575
  function interrupted(dir) {
211488
211576
  return new AnchaError("USAGE", "run interrupted", dir === void 0 ? {} : { hint: `partial results in ${dir}` });
211489
211577
  }
@@ -211497,7 +211585,7 @@ async function recordsFor(scenePath, root3 = process.cwd()) {
211497
211585
  if (scenePath === void 0) return void 0;
211498
211586
  const top = resolve12(root3);
211499
211587
  for (let dir = dirname7(resolve12(top, scenePath)); ; dir = dirname7(dir)) {
211500
- const file3 = join20(dir, "records.jsonl");
211588
+ const file3 = join21(dir, "records.jsonl");
211501
211589
  if (await access4(file3).then(() => true, () => false)) return file3;
211502
211590
  if (dir === top || relative5(top, dir).startsWith("..") || dirname7(dir) === dir) return void 0;
211503
211591
  }
@@ -211640,13 +211728,13 @@ async function executeRun(opts) {
211640
211728
  const stopped = () => halt.spawnFailure !== void 0 || halt.crash !== void 0 || signal?.aborted === true;
211641
211729
  const startedAt = /* @__PURE__ */ new Date();
211642
211730
  const runId = opts.runId ?? newRunId(startedAt);
211643
- const dir = join20(outDir, runId);
211731
+ const dir = join21(outDir, runId);
211644
211732
  let next2 = 0;
211645
211733
  const total2 = cases.length * trials;
211646
211734
  try {
211647
211735
  await mkdir11(outDir, { recursive: true });
211648
211736
  await mkdir11(dir);
211649
- await writeFile10(join20(dir, "inputs.json"), `${JSON.stringify({
211737
+ await writeFile10(join21(dir, "inputs.json"), `${JSON.stringify({
211650
211738
  schemaVersion: 1,
211651
211739
  cases: sharedSeeds(frozen.map((value4, index) => ({ ...value4, scene: cases[index].scene }))),
211652
211740
  // A world's seed once (run-inputs.ts). Names only, never values: what a later `ancha runs upload` redacts (hosting spec §3.1).
@@ -211658,7 +211746,7 @@ async function executeRun(opts) {
211658
211746
  for (const [index, item2] of cases.entries()) {
211659
211747
  const source = await recordsFor(pathOf6(item2), opts.root);
211660
211748
  if (source === void 0) continue;
211661
- const text25 = await readFile8(source), copy = join20(dir, "records", `${index}.jsonl`);
211749
+ const text25 = await readFile9(source), copy = join21(dir, "records", `${index}.jsonl`);
211662
211750
  await mkdir11(dirname7(copy), { recursive: true });
211663
211751
  await writeFile10(copy, text25, { flag: "wx", mode: 384 });
211664
211752
  kept.set(item2.id, copy);
@@ -211670,7 +211758,7 @@ async function executeRun(opts) {
211670
211758
  const index = next2++;
211671
211759
  const item2 = cases[index % cases.length];
211672
211760
  const trial = Math.floor(index / cases.length) + 1 + trialOffset;
211673
- const trialDir = join20(dir, `trial-${item2.id}-${trial}`);
211761
+ const trialDir = join21(dir, `trial-${item2.id}-${trial}`);
211674
211762
  const records3 = kept.get(item2.id);
211675
211763
  const attempt = { id: `${runId}/${item2.id}/${trial}`, caseId: item2.id, stateDir: resolve12(trialDir, "agent-state"), seed: seedOf(item2), ...records3 !== void 0 && { records: records3 }, ...opts.recordsDiagnostic && { recordsDiagnostic: { ...opts.recordsDiagnostic, attempt: trial } } };
211676
211764
  const startedAt2 = performance.now();
@@ -211740,6 +211828,7 @@ async function executeRun(opts) {
211740
211828
  }
211741
211829
  result.caseId = item2.id;
211742
211830
  result.attemptId = attempt.id;
211831
+ if (Object.keys(item2.scene.tools ?? {}).length) result.functionTools = await savedFunctionTools(result.dir, result.trace, Object.keys(item2.scene.tools ?? {}));
211743
211832
  if (writeTools(item2.scene).size) result.actions = actionsOf(item2.scene, result.trace);
211744
211833
  if (Object.keys(item2.scene.tools ?? {}).length) result.answers = answersOf(result.trace);
211745
211834
  if (result.exit !== "invalid") {
@@ -211748,7 +211837,7 @@ async function executeRun(opts) {
211748
211837
  }
211749
211838
  finished++;
211750
211839
  results.get(item2.id).trials.push(result);
211751
- await writeFile10(join20(trialDir, "result.json"), `${JSON.stringify({ ...result, trace: void 0 }, null, 2)}
211840
+ await writeFile10(join21(trialDir, "result.json"), `${JSON.stringify({ ...result, trace: void 0 }, null, 2)}
211752
211841
  `, { flag: "wx", mode: 384 });
211753
211842
  onEvent?.({
211754
211843
  event: "trial_finished",
@@ -211778,7 +211867,7 @@ async function executeRun(opts) {
211778
211867
  if (halt.crash !== void 0) throw halt.crash.error;
211779
211868
  if (halt.spawnFailure !== void 0) {
211780
211869
  throw new AnchaError("AGENT_SPAWN_FAILED", `agent command failed to start: ${agent.mode === "endpoint" ? agent.start : agent.command}`, {
211781
- hint: `check agent.command in ancha.yaml or --agent; see ${join20(halt.spawnFailure.dir, "agent.log")}`
211870
+ hint: `check agent.command in ancha.yaml or --agent; see ${join21(halt.spawnFailure.dir, "agent.log")}`
211782
211871
  });
211783
211872
  }
211784
211873
  if (signal?.aborted && finished < scenes.length * trials) throw interrupted(dir);
@@ -211984,7 +212073,7 @@ init_src();
211984
212073
 
211985
212074
  // packages/cli/src/commands/run.ts
211986
212075
  import { appendFileSync } from "node:fs";
211987
- import { dirname as dirname8, join as join21, relative as relative6, resolve as resolve14 } from "node:path";
212076
+ import { dirname as dirname8, join as join22, relative as relative6, resolve as resolve14 } from "node:path";
211988
212077
  init_src();
211989
212078
  init_run_state();
211990
212079
 
@@ -212006,8 +212095,8 @@ init_credentials();
212006
212095
  init_run_metadata();
212007
212096
  init_src();
212008
212097
  init_credentials();
212009
- import { readFile as readFile5 } from "node:fs/promises";
212010
- import { basename as basename2, join as join6 } from "node:path";
212098
+ import { readFile as readFile6 } from "node:fs/promises";
212099
+ import { basename as basename2, join as join7 } from "node:path";
212011
212100
 
212012
212101
  // packages/cli/src/git-state.ts
212013
212102
  import { execFile } from "node:child_process";
@@ -212036,7 +212125,7 @@ var CLI_VERSION = JSON.parse(readFileSync3(new URL("../package.json", import.met
212036
212125
 
212037
212126
  // packages/cli/src/run-upload.ts
212038
212127
  async function uploadRun(ctx, workspace3, run4) {
212039
- const summary = JSON.parse(await readFile5(join6(run4.runDir, "summary.json"), "utf8").catch(() => "{}"));
212128
+ const summary = JSON.parse(await readFile6(join7(run4.runDir, "summary.json"), "utf8").catch(() => "{}"));
212040
212129
  if (summary.source === "pytest") throw new AnchaError("USAGE", "pytest run upload is not supported; records remain local");
212041
212130
  const key4 = await apiKeyFor(workspace3, ctx.io.env);
212042
212131
  if (key4 === void 0 && !isLoopbackUrl(workspace3)) throw authError2(workspace3, { keySent: false });
@@ -212522,7 +212611,7 @@ ${uploadHintLine(summary.runId, uploadHint, { out: opts.out })}` : ""}`);
212522
212611
  async function uploadFinished(ctx, input5, runId) {
212523
212612
  if (input5.upload === void 0) return void 0;
212524
212613
  try {
212525
- return await uploadRun(ctx, input5.upload.workspace, { runId, runDir: join21(input5.outDir, runId), ...input5.agent.passEnv !== void 0 && { passEnv: input5.agent.passEnv }, ...input5.agent.inheritEnv && { inheritEnv: true } });
212614
+ return await uploadRun(ctx, input5.upload.workspace, { runId, runDir: join22(input5.outDir, runId), ...input5.agent.passEnv !== void 0 && { passEnv: input5.agent.passEnv }, ...input5.agent.inheritEnv && { inheritEnv: true } });
212526
212615
  } catch (error64) {
212527
212616
  const json33 = toErrorJson(error64);
212528
212617
  if (input5.upload.required) {
@@ -212547,7 +212636,7 @@ async function executePreparedRun(ctx, input5, initial, ready3) {
212547
212636
  const backend = await openBackend({ ...input5.serverUrl !== void 0 && { serverUrl: input5.serverUrl }, ...input5.peopleRelay !== void 0 && { peopleRelay: input5.peopleRelay } });
212548
212637
  try {
212549
212638
  const where2 = { ...input5.workspace !== void 0 && { workspace: input5.workspace }, target: input5.agent.execution?.mode === "container" ? "docker" : "local", ...input5.peopleRelay !== void 0 && { modelCredit: "workspace" } };
212550
- const log2 = join21(input5.outDir, initial.runId, "events.ndjson");
212639
+ const log2 = join22(input5.outDir, initial.runId, "events.ndjson");
212551
212640
  const run4 = await executeRun({
212552
212641
  ...input5,
212553
212642
  root: ctx.io.cwd,