@ancha-labs/cli 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/ancha.mjs CHANGED
@@ -19388,13 +19388,13 @@ function _promise(Class2, innerType) {
19388
19388
  }
19389
19389
  // @__NO_SIDE_EFFECTS__
19390
19390
  function _custom(Class2, fn, _params) {
19391
- const norm = normalizeParams(_params);
19392
- norm.abort ?? (norm.abort = true);
19391
+ const norm2 = normalizeParams(_params);
19392
+ norm2.abort ?? (norm2.abort = true);
19393
19393
  const schema3 = new Class2({
19394
19394
  type: "custom",
19395
19395
  check: "custom",
19396
19396
  fn,
19397
- ...norm
19397
+ ...norm2
19398
19398
  });
19399
19399
  return schema3;
19400
19400
  }
@@ -32193,10 +32193,10 @@ function tokenize(text24) {
32193
32193
  return out;
32194
32194
  }
32195
32195
  function parseFormula(text24) {
32196
- const tokens2 = tokenize(text24);
32196
+ const tokens3 = tokenize(text24);
32197
32197
  let at3 = 0;
32198
32198
  const isOp = (value5) => {
32199
- const token2 = tokens2[at3];
32199
+ const token2 = tokens3[at3];
32200
32200
  return token2.kind === "op" && token2.value === value5;
32201
32201
  };
32202
32202
  const expect = (value5) => {
@@ -32206,14 +32206,14 @@ function parseFormula(text24) {
32206
32206
  const level3 = (ops, next2) => () => {
32207
32207
  let left = next2();
32208
32208
  for (; ; ) {
32209
- const token2 = tokens2[at3];
32209
+ const token2 = tokens3[at3];
32210
32210
  if (token2.kind !== "op" || !ops.includes(token2.value)) return left;
32211
32211
  at3++;
32212
32212
  left = { type: "binary", op: token2.value, left, right: next2() };
32213
32213
  }
32214
32214
  };
32215
32215
  const primary3 = () => {
32216
- const token2 = tokens2[at3++];
32216
+ const token2 = tokens3[at3++];
32217
32217
  if (token2.kind === "num") return { type: "number", value: token2.value };
32218
32218
  if (token2.kind === "str") return { type: "text", value: token2.value };
32219
32219
  if (token2.kind === "field") return { type: "field", name: token2.value };
@@ -32238,14 +32238,14 @@ function parseFormula(text24) {
32238
32238
  };
32239
32239
  const unary = () => {
32240
32240
  if (isOp("-") || isOp("+")) {
32241
- const op = tokens2[at3++].value;
32241
+ const op = tokens3[at3++].value;
32242
32242
  return { type: "unary", op, arg: unary() };
32243
32243
  }
32244
32244
  return primary3();
32245
32245
  };
32246
32246
  const comparison2 = level3(["=", "!=", "<", ">", "<=", ">="], level3(["&"], level3(["+", "-"], level3(["*", "/"], unary))));
32247
32247
  const node5 = comparison2();
32248
- if (tokens2[at3].kind !== "end") throw new FormulaSyntaxError("unexpected text after the formula");
32248
+ if (tokens3[at3].kind !== "end") throw new FormulaSyntaxError("unexpected text after the formula");
32249
32249
  return node5;
32250
32250
  }
32251
32251
  function formulaFieldNames(node5) {
@@ -33674,6 +33674,8 @@ var init_schema2 = __esm({
33674
33674
  allow_unwrapped: external_exports.literal(true).optional(),
33675
33675
  /** Changes something (a refund, an email): an unrecorded call is never answered by invention unless set to simulate. */
33676
33676
  write: external_exports.boolean().optional(),
33677
+ /** Only computes from its arguments (a calculator): a call production never made runs the tool itself, for real. */
33678
+ pure: external_exports.literal(true).optional(),
33677
33679
  description: external_exports.string().optional(),
33678
33680
  schema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
33679
33681
  });
@@ -38500,7 +38502,7 @@ ${pointer2}
38500
38502
  var require_resolve_props = __commonJS({
38501
38503
  "node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/dist/compose/resolve-props.js"(exports) {
38502
38504
  "use strict";
38503
- function resolveProps(tokens2, { flow, indicator, next: next2, offset: offset16, onError, parentIndent, startOnNewline }) {
38505
+ function resolveProps(tokens3, { flow, indicator, next: next2, offset: offset16, onError, parentIndent, startOnNewline }) {
38504
38506
  let spaceBefore = false;
38505
38507
  let atNewline = startOnNewline;
38506
38508
  let hasSpace = startOnNewline;
@@ -38515,7 +38517,7 @@ var require_resolve_props = __commonJS({
38515
38517
  let comma = null;
38516
38518
  let found = null;
38517
38519
  let start = null;
38518
- for (const token2 of tokens2) {
38520
+ for (const token2 of tokens3) {
38519
38521
  if (reqSpace) {
38520
38522
  if (token2.type !== "space" && token2.type !== "newline" && token2.type !== "comma")
38521
38523
  onError(token2.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
@@ -38606,7 +38608,7 @@ var require_resolve_props = __commonJS({
38606
38608
  hasSpace = false;
38607
38609
  }
38608
38610
  }
38609
- const last = tokens2[tokens2.length - 1];
38611
+ const last = tokens3[tokens3.length - 1];
38610
38612
  const end = last ? last.offset + last.source.length : offset16;
38611
38613
  if (reqSpace && next2 && next2.type !== "space" && next2.type !== "newline" && next2.type !== "comma" && (next2.type !== "scalar" || next2.source !== "")) {
38612
38614
  onError(next2.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
@@ -39946,8 +39948,8 @@ ${cb}` : comment8;
39946
39948
  * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
39947
39949
  * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
39948
39950
  */
39949
- *compose(tokens2, forceDoc = false, endOffset = -1) {
39950
- for (const token2 of tokens2)
39951
+ *compose(tokens3, forceDoc = false, endOffset = -1) {
39952
+ for (const token2 of tokens3)
39951
39953
  yield* this.next(token2);
39952
39954
  yield* this.end(forceDoc, endOffset);
39953
39955
  }
@@ -42219,6 +42221,7 @@ function toolIssues(scene2) {
42219
42221
  else if (!scene2.twins.includes(tool.twin)) issues.push({ path: `${path6}.twin`, message: `twin ${tool.twin} is not listed in twins`, hint: `add ${tool.twin} to twins, e.g. twins: [${tool.twin}]` });
42220
42222
  }
42221
42223
  if (tool.unrecorded === "twin" && tool.twin === void 0) issues.push({ path: `${path6}.unrecorded`, message: "unrecorded: twin needs the twin that answers", hint: `set ${path6}.twin, e.g. twin: slack` });
42224
+ if (tool.pure && tool.write) issues.push({ path: `${path6}.pure`, message: "a tool that changes something is not pure", hint: `remove ${path6}.pure, or ${path6}.write if it only computes from its arguments` });
42222
42225
  if (tool.observations !== void 0 && tool.recorded === void 0) {
42223
42226
  issues.push({ path: `${path6}.observations`, message: `${tool.observations} was not read`, hint: "load the scene from its file (ancha run, ancha scene validate), which reads the recorded calls next to it" });
42224
42227
  }
@@ -51041,9 +51044,9 @@ var require_parse = __commonJS({
51041
51044
  if (isOption) {
51042
51045
  isOption = false;
51043
51046
  if (token3.includes(".") && !token3.includes("(")) {
51044
- var tokens2 = token3.split(".");
51045
- option3 = tokens2[0] + ".";
51046
- token3 = tokens2[1];
51047
+ var tokens3 = token3.split(".");
51048
+ option3 = tokens3[0] + ".";
51049
+ token3 = tokens3[1];
51047
51050
  continue;
51048
51051
  }
51049
51052
  option3 = token3;
@@ -93436,7 +93439,7 @@ var require_scan = __commonJS({
93436
93439
  const length = input2.length - 1;
93437
93440
  const scanToEnd = opts.parts === true || opts.tokens === true || opts.scanToEnd === true;
93438
93441
  const slashes = [];
93439
- const tokens2 = [];
93442
+ const tokens3 = [];
93440
93443
  const parts3 = [];
93441
93444
  let str4 = input2;
93442
93445
  let index = -1;
@@ -93520,7 +93523,7 @@ var require_scan = __commonJS({
93520
93523
  }
93521
93524
  if (code4 === CHAR_FORWARD_SLASH) {
93522
93525
  slashes.push(index);
93523
- tokens2.push(token2);
93526
+ tokens3.push(token2);
93524
93527
  token2 = { value: "", depth: 0, isGlob: false };
93525
93528
  if (finished === true) continue;
93526
93529
  if (prev === CHAR_DOT && index === start + 1) {
@@ -93682,9 +93685,9 @@ var require_scan = __commonJS({
93682
93685
  if (opts.tokens === true) {
93683
93686
  state3.maxDepth = 0;
93684
93687
  if (!isPathSeparator(code4)) {
93685
- tokens2.push(token2);
93688
+ tokens3.push(token2);
93686
93689
  }
93687
- state3.tokens = tokens2;
93690
+ state3.tokens = tokens3;
93688
93691
  }
93689
93692
  if (opts.parts === true || opts.tokens === true) {
93690
93693
  let prevIndex;
@@ -93694,13 +93697,13 @@ var require_scan = __commonJS({
93694
93697
  const value6 = input2.slice(n2, i);
93695
93698
  if (opts.tokens) {
93696
93699
  if (idx === 0 && start !== 0) {
93697
- tokens2[idx].isPrefix = true;
93698
- tokens2[idx].value = prefix2;
93700
+ tokens3[idx].isPrefix = true;
93701
+ tokens3[idx].value = prefix2;
93699
93702
  } else {
93700
- tokens2[idx].value = value6;
93703
+ tokens3[idx].value = value6;
93701
93704
  }
93702
- depth(tokens2[idx]);
93703
- state3.maxDepth += tokens2[idx].depth;
93705
+ depth(tokens3[idx]);
93706
+ state3.maxDepth += tokens3[idx].depth;
93704
93707
  }
93705
93708
  if (i >= start) {
93706
93709
  parts3.push(value6);
@@ -93711,9 +93714,9 @@ var require_scan = __commonJS({
93711
93714
  const value5 = input2.slice(n);
93712
93715
  parts3.push(value5);
93713
93716
  if (opts.tokens && prevIndex && prevIndex + 1 < input2.length) {
93714
- tokens2[tokens2.length - 1].value = value5;
93715
- depth(tokens2[tokens2.length - 1]);
93716
- state3.maxDepth += tokens2[tokens2.length - 1].depth;
93717
+ tokens3[tokens3.length - 1].value = value5;
93718
+ depth(tokens3[tokens3.length - 1]);
93719
+ state3.maxDepth += tokens3[tokens3.length - 1].depth;
93717
93720
  }
93718
93721
  state3.slashes = slashes;
93719
93722
  state3.parts = parts3;
@@ -93989,7 +93992,7 @@ var require_parse2 = __commonJS({
93989
93992
  throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
93990
93993
  }
93991
93994
  const bos = { type: "bos", value: "", output: opts.prepend || "" };
93992
- const tokens2 = [bos];
93995
+ const tokens3 = [bos];
93993
93996
  const capture4 = opts.capture ? "" : "?:";
93994
93997
  const PLATFORM_CHARS = constants7.globChars(opts.windows);
93995
93998
  const EXTGLOB_CHARS = constants7.extglobChars(PLATFORM_CHARS);
@@ -94034,7 +94037,7 @@ var require_parse2 = __commonJS({
94034
94037
  parens: 0,
94035
94038
  quotes: 0,
94036
94039
  globstar: false,
94037
- tokens: tokens2
94040
+ tokens: tokens3
94038
94041
  };
94039
94042
  input2 = utils.removePrefix(input2, state3);
94040
94043
  len = input2.length;
@@ -94099,7 +94102,7 @@ var require_parse2 = __commonJS({
94099
94102
  return;
94100
94103
  }
94101
94104
  tok.prev = prev;
94102
- tokens2.push(tok);
94105
+ tokens3.push(tok);
94103
94106
  prev = tok;
94104
94107
  };
94105
94108
  const extglobOpen = (type, value6) => {
@@ -94108,7 +94111,7 @@ var require_parse2 = __commonJS({
94108
94111
  token2.parens = state3.parens;
94109
94112
  token2.output = state3.output;
94110
94113
  token2.startIndex = state3.index;
94111
- token2.tokensIndex = tokens2.length;
94114
+ token2.tokensIndex = tokens3.length;
94112
94115
  const output2 = (opts.capture ? "(" : "") + token2.open;
94113
94116
  increment("parens");
94114
94117
  push({ type, value: value6, output: state3.output ? "" : ONE_CHAR });
@@ -94121,14 +94124,14 @@ var require_parse2 = __commonJS({
94121
94124
  const analysis = analyzeRepeatedExtglob(body6, opts);
94122
94125
  if ((token2.type === "plus" || token2.type === "star") && analysis.risky) {
94123
94126
  const safeOutput = analysis.safeOutput ? (token2.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : void 0;
94124
- const open9 = tokens2[token2.tokensIndex];
94127
+ const open9 = tokens3[token2.tokensIndex];
94125
94128
  open9.type = "text";
94126
94129
  open9.value = literal2;
94127
94130
  open9.output = safeOutput || utils.escapeRegex(literal2);
94128
- for (let i = token2.tokensIndex + 1; i < tokens2.length; i++) {
94129
- tokens2[i].value = "";
94130
- tokens2[i].output = "";
94131
- delete tokens2[i].suffix;
94131
+ for (let i = token2.tokensIndex + 1; i < tokens3.length; i++) {
94132
+ tokens3[i].value = "";
94133
+ tokens3[i].output = "";
94134
+ delete tokens3[i].suffix;
94132
94135
  }
94133
94136
  state3.output = token2.output + open9.output;
94134
94137
  state3.backtrack = true;
@@ -94251,7 +94254,7 @@ var require_parse2 = __commonJS({
94251
94254
  prev.value = pre2 + posix2;
94252
94255
  state3.backtrack = true;
94253
94256
  advance();
94254
- if (!bos.output && tokens2.indexOf(prev) === 1) {
94257
+ if (!bos.output && tokens3.indexOf(prev) === 1) {
94255
94258
  bos.output = ONE_CHAR;
94256
94259
  }
94257
94260
  continue;
@@ -94369,10 +94372,10 @@ var require_parse2 = __commonJS({
94369
94372
  }
94370
94373
  let output2 = ")";
94371
94374
  if (brace.dots === true) {
94372
- const arr = tokens2.slice();
94375
+ const arr = tokens3.slice();
94373
94376
  const range2 = [];
94374
94377
  for (let i = arr.length - 1; i >= 0; i--) {
94375
- tokens2.pop();
94378
+ tokens3.pop();
94376
94379
  if (arr[i].type === "brace") {
94377
94380
  break;
94378
94381
  }
@@ -94420,7 +94423,7 @@ var require_parse2 = __commonJS({
94420
94423
  state3.start = state3.index + 1;
94421
94424
  state3.consumed = "";
94422
94425
  state3.output = "";
94423
- tokens2.pop();
94426
+ tokens3.pop();
94424
94427
  prev = bos;
94425
94428
  continue;
94426
94429
  }
@@ -97784,7 +97787,7 @@ function proposeChecks(cx, { slack: slack2, datadog: datadog2, pagerduty }) {
97784
97787
  add({ id: `healthy-${m.ref.replace(/_/g, "-")}`, state: { "datadog.monitor": `$${m.ref}`, is: "OK" } }, `${m.name} is back to OK`, last ? verdict(last.state === "OK") : "unknown");
97785
97788
  }
97786
97789
  if (!cx.checks.length && !cx.seed.slack && cx.seed.gmail) add({ id: "no-trash", trace: { not_called: "POST /gmail/v1/users/*/messages/*/trash" } }, "nothing the trace suggests; a harmless default", verdict(!cx.calls("gmail", (c) => /\/trash$/.test(c.path)).length));
97787
- if (!cx.checks.length) add({ id: "no-deletes", trace: { not_called: "* /api/chat.delete" } }, "nothing the trace suggests; a harmless default", verdict(!cx.calls("slack", (c) => c.path === "/api/chat.delete").length));
97790
+ if (!cx.checks.length && cx.seed.slack) add({ id: "no-deletes", trace: { not_called: "* /api/chat.delete" } }, "nothing the trace suggests; a harmless default", verdict(!cx.calls("slack", (c) => c.path === "/api/chat.delete").length));
97788
97791
  }
97789
97792
  var DEFAULT_TASK, isPayload, seconds3;
97790
97793
  var init_infer = __esm({
@@ -100236,7 +100239,7 @@ function readTools(cx, header4, records3, { examples: examples2 = [] } = {}) {
100236
100239
  const at3 = (t) => duration10(Date.parse(t) - start);
100237
100240
  const definitions3 = /* @__PURE__ */ new Map();
100238
100241
  for (const r of records3) if (r.kind === "llm") for (const d of r.tools ?? []) definitions3.set(d.name, d);
100239
- const names3 = [...new Set(calls2.map((r) => r.name))];
100242
+ const names3 = [.../* @__PURE__ */ new Set([...calls2.map((r) => r.name), ...examples2.map((e) => e.tool)])];
100240
100243
  const mcp = mcpTools(cx.answers["tools.mcp"], names3);
100241
100244
  const linked = /* @__PURE__ */ new Map();
100242
100245
  for (const name5 of names3) {
@@ -100269,21 +100272,27 @@ function readTools(cx, header4, records3, { examples: examples2 = [] } = {}) {
100269
100272
  };
100270
100273
  const errors3 = own2.filter((r) => r.error !== void 0).length, cut2 = own2.filter((r) => r.truncated).length;
100271
100274
  cx.note("observed", `tools.${name5}`, `${own2.length} recorded ${own2.length === 1 ? "call" : "calls"}${errors3 ? `, ${errors3} with an error` : ""}${cut2 ? `, ${cut2} cut by the tracing SDK` : ""}${definition3 ? "; its description and arguments from the trace" : ""}`, own2.map((r) => r.id));
100272
- if (write4) cx.note("inferred", `tools.${name5}.write`, "its name says it changes something, so a call production never made fails instead of being invented");
100275
+ if (write4) cx.note("inferred", `tools.${name5}.write`, "its name says it changes something, so each trial counts its calls");
100273
100276
  }
100274
- const writes2 = names3.filter(isWrite), simulated = mcpTools(cx.answers["tools.simulate_writes"], writes2);
100275
- for (const name5 of simulated) {
100276
- tools2[name5].unrecorded = "simulate";
100277
- cx.note("answered", `tools.${name5}.unrecorded`, "your answer: a call production never made is simulated");
100277
+ const writes2 = names3.filter(isWrite), answer = cx.answers["tools.simulate_writes"], simulated = mcpTools(answer ?? "all", writes2);
100278
+ for (const name5 of writes2) {
100279
+ if (simulated.has(name5)) tools2[name5].unrecorded = "simulate";
100280
+ cx.note(answer === void 0 ? "inferred" : "answered", `tools.${name5}.unrecorded`, `${answer === void 0 ? "" : "your answer: "}a call production never made ${simulated.has(name5) ? "is simulated; nothing executes" : "fails"}`);
100278
100281
  }
100279
- if (writes2.length) cx.ask("tools.simulate_writes", `Which of these writes may the test simulate when the agent makes one production never made: ${writes2.join(", ")}? The others fail, so a test never invents a write's success.`, ["none", "all", writes2.join(",")], 0, { type: "text" });
100282
+ if (writes2.length) cx.ask("tools.simulate_writes", `Which of these writes may the test simulate when the agent makes one production never made: ${writes2.join(", ")}? A simulated write executes nothing and the trial counts it; the others fail.`, ["all", "none", writes2.join(",")], 0, { type: "text" });
100283
+ const reads2 = names3.filter((name5) => !isWrite(name5)), pure = mcpTools(cx.answers["tools.pure"], reads2);
100284
+ for (const name5 of pure) {
100285
+ tools2[name5].pure = true;
100286
+ cx.note("answered", `tools.${name5}.pure`, "your answer: it only computes from its arguments, so a call production never made runs the tool itself");
100287
+ }
100288
+ if (reads2.length) cx.ask("tools.pure", `Which of these tools only compute from their arguments, reading and changing nothing (a calculator, a formatter): ${reads2.join(", ")}? A test runs those itself when production never made the call.`, ["none", "all", reads2.join(",")], 0, { type: "text" });
100280
100289
  if (names3.length) {
100281
- cx.ask("tools.mcp", `Which of these tools does your agent reach over MCP: ${names3.join(", ")}? A test serves those at {{tools.mcp_url}}; the others the agent wraps.`, ["none", "all", names3.join(",")], 0, { type: "text" });
100290
+ cx.ask("tools.mcp", `Which of these tools does your agent reach over MCP: ${names3.join(", ")}? A test serves those at {{tools.mcp_url}}. The others are the agent's own functions: the test answers them when the agent wraps them (wrapTools from @ancha-labs/tools, ancha.wrap_tools in Python).`, ["none", "all", names3.join(",")], 0, { type: "text" });
100282
100291
  if (mcp.size) cx.note("answered", "tools.mcp", `your answer: ${[...mcp].join(", ")} over MCP`);
100283
100292
  }
100284
100293
  const cut = calls2.filter((r) => r.truncated).length;
100285
100294
  if (cut) cx.ask("tools.truncated", `${cut} recorded ${cut === 1 ? "result was" : "results were"} cut by the tracing SDK's length limit. Should the test replay ${cut === 1 ? "it" : "them"} as cut?`, ["replay as cut", "fail those calls"], 0);
100286
- const messages4 = header4?.input?.messages ?? [];
100295
+ const messages4 = header4?.input?.messages ?? (records3.find((r) => r.kind === "llm" && Array.isArray(r.input))?.input ?? []).map((m) => ({ role: m.role, content: m.content ?? m.text ?? null }));
100287
100296
  const task2 = typeof cx.answers.task === "string" && cx.answers.task.trim() ? cx.answers.task.trim() : [...messages4].reverse().find((m) => m.role === "user" && m.content)?.content;
100288
100297
  const trigger = { ...task2 && { task: task2 }, ...(messages4.length || header4?.user) && { input: { messages: messages4, ...header4?.user && { user: header4.user } } } };
100289
100298
  if (messages4.length) cx.note("observed", "trigger", `the invocation's input: ${messages4.length} ${messages4.length === 1 ? "message" : "messages"}${header4?.user ? ", and the user it served" : ""}`);
@@ -100387,7 +100396,10 @@ var init_tools = __esm({
100387
100396
  "grant",
100388
100397
  "revoke",
100389
100398
  "disable",
100390
- "enable"
100399
+ "enable",
100400
+ "trigger",
100401
+ "reset",
100402
+ "escalate"
100391
100403
  ]);
100392
100404
  duration10 = (ms3) => {
100393
100405
  ms3 = Math.max(0, Math.round(ms3));
@@ -100401,6 +100413,161 @@ var init_tools = __esm({
100401
100413
  }
100402
100414
  });
100403
100415
 
100416
+ // cloud/rebuild/person.mjs
100417
+ function customerFacts(facts, transcript3, world5 = []) {
100418
+ const kept = [], dropped = [];
100419
+ for (const fact2 of facts) {
100420
+ const value5 = norm(fact2.value);
100421
+ const first = value5.length >= 3 && exactLike(fact2) ? transcript3.find((line2) => norm(line2.content).includes(value5)) : void 0;
100422
+ const at3 = Date.parse(first?.t ?? ""), key3 = tokens2(fact2.value);
100423
+ const read6 = first?.role === "assistant" && key3.trim().length >= 3 && world5.some((answer) => (!Number.isFinite(at3) || !Number.isFinite(Date.parse(answer.t ?? "")) || Date.parse(answer.t) <= at3) && tokens2(answer.text).includes(key3));
100424
+ (first?.role === "assistant" && !read6 ? dropped : kept).push(fact2);
100425
+ }
100426
+ return { kept, dropped };
100427
+ }
100428
+ function agentValuesInGoal(goal, values2) {
100429
+ const text24 = norm(goal);
100430
+ return values2.map(String).filter((value5) => norm(value5).length >= 3 && text24.includes(norm(value5)));
100431
+ }
100432
+ function goalWithout(goal, values2) {
100433
+ const named3 = (sentence) => values2.some((value5) => norm(sentence).includes(norm(value5)));
100434
+ const left = String(goal ?? "").split(/(?<=[.!?])\s+/).filter((sentence) => !named3(sentence));
100435
+ return left.join(" ").trim();
100436
+ }
100437
+ function personByRule(transcript3) {
100438
+ const users4 = transcript3.filter((line2) => line2.role === "user");
100439
+ const facts = [];
100440
+ transcript3.forEach((line2, i) => {
100441
+ if (line2.role !== "user" || line2 === users4[0]) return;
100442
+ const before = transcript3.slice(0, i).reverse().find((l) => l.role === "assistant");
100443
+ facts.push({
100444
+ id: `said_${facts.length + 2}`,
100445
+ value: line2.content,
100446
+ match: "semantic",
100447
+ about: before ? `what to answer when the agent says: ${before.content.replace(/\s+/g, " ").trim().slice(0, 240)}` : "what to say after your first message"
100448
+ });
100449
+ });
100450
+ const emails = [...new Set(users4.flatMap((line2) => line2.content.match(EMAIL19) ?? []))];
100451
+ emails.forEach((email10, i) => facts.push({ id: `email_${i + 1}`, value: email10, about: "an email address you gave", match: "exact" }));
100452
+ return {
100453
+ goal: `Get the agent to sort out what you asked in your first message: ${users4[0]?.content ?? ""}`,
100454
+ facts,
100455
+ style: "like your first message; answer what the agent asks, don't volunteer more"
100456
+ };
100457
+ }
100458
+ function placePerson(cx, person4, { agent, opener, userTurns }) {
100459
+ const name5 = String(person4.name ?? "").trim() || "Customer", bot = String(agent ?? "").trim() || "Agent";
100460
+ cx.seed.slack = {
100461
+ bot: "$slack_bot",
100462
+ users: [{ ref: "slack_bot", name: slug12(bot, "-") || "agent", real_name: bot, is_bot: true }, { ref: "slack_customer", name: slug12(name5, ".") || "customer", real_name: name5 }],
100463
+ channels: [{ ref: "slack_help", name: "help", is_private: true, members: ["$slack_bot", "$slack_customer"] }]
100464
+ };
100465
+ (cx.rules.actors ??= []).push({ at: "0s", "slack.post": { ref: "opening", channel: "$slack_help", user: "$slack_customer", text: `<$user.slack_bot> ${opener}` } });
100466
+ const ids2 = /* @__PURE__ */ new Set(), knows = [];
100467
+ for (const fact2 of person4.facts ?? []) {
100468
+ if (!String(fact2.value ?? "").trim() || !String(fact2.about ?? "").trim()) continue;
100469
+ let id12 = String(fact2.id ?? "fact").replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+|_+$/g, "") || "fact";
100470
+ while (ids2.has(id12)) id12 += "_2";
100471
+ ids2.add(id12);
100472
+ knows.push({ id: id12, value: String(fact2.value), about: String(fact2.about), match: fact2.match ?? (fact2.exact ? "exact" : "semantic") });
100473
+ }
100474
+ const style = String(person4.style ?? "").trim().replace(/\.$/, "") || "brief";
100475
+ return [{
100476
+ ref: "customer",
100477
+ name: name5,
100478
+ role: `a user of ${bot}, writing to it`,
100479
+ goal: String(person4.goal ?? "").trim() || `Get the agent to sort out what you asked in your first message: ${opener}`,
100480
+ style: `${style}. Never make up information you were not given: asked for something you don't know, say you don't have it. An id, a name or a number you give is exactly the one you know.`,
100481
+ accounts: { slack: "$slack_customer" },
100482
+ listens: ["dm", "mentions", "threads"],
100483
+ replies_after: "1s..3s",
100484
+ budget: Math.min(64, Math.max(12, 2 * userTurns)),
100485
+ can: ["slack.post"],
100486
+ ...knows.length && { knows }
100487
+ }];
100488
+ }
100489
+ var EMAIL19, norm, exactLike, tokens2, slug12;
100490
+ var init_person = __esm({
100491
+ "cloud/rebuild/person.mjs"() {
100492
+ "use strict";
100493
+ EMAIL19 = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g;
100494
+ norm = (text24) => String(text24 ?? "").toLowerCase().replace(/\s+/g, " ").trim();
100495
+ exactLike = (fact2) => fact2.exact === true || fact2.match === "exact" || /[\d$€£¥]/.test(String(fact2.value ?? ""));
100496
+ tokens2 = (text24) => ` ${String(text24 ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
100497
+ slug12 = (text24, sep4) => String(text24 ?? "").toLowerCase().replace(/[^a-z0-9]+/g, sep4).replace(new RegExp(`^\\${sep4}+|\\${sep4}+$`, "g"), "");
100498
+ }
100499
+ });
100500
+
100501
+ // cloud/rebuild/conversations.mjs
100502
+ function userMessages(lines) {
100503
+ const input2 = headerOf2(lines).input?.messages ?? lines.find((l) => l.kind === "llm" && Array.isArray(l.input))?.input ?? [];
100504
+ return input2.filter((m) => m.role === "user").map((m) => String(m.content ?? m.text ?? ""));
100505
+ }
100506
+ function messagesOf(lines) {
100507
+ const input2 = headerOf2(lines).input?.messages ?? lines.find((l) => l.kind === "llm" && Array.isArray(l.input))?.input ?? [];
100508
+ return input2.map((m) => ({ role: m.role, content: String(m.content ?? m.text ?? "").trim() })).filter((m) => (m.role === "user" || m.role === "assistant") && m.content);
100509
+ }
100510
+ function answerOf(lines) {
100511
+ const output2 = headerOf2(lines).output;
100512
+ if (typeof output2 === "string" && output2.trim()) return output2.trim();
100513
+ return lines.filter((l) => l.kind === "llm" && typeof l.output === "string" && l.output.trim()).at(-1)?.output.trim();
100514
+ }
100515
+ function transcriptOf(turns) {
100516
+ const transcript3 = [];
100517
+ for (const turn of turns) {
100518
+ const said = transcript3.filter((l) => l.role === "user").map((l) => l.content);
100519
+ let messages4 = messagesOf(turn.lines);
100520
+ const users4 = messages4.filter((m) => m.role === "user").map((m) => m.content);
100521
+ if (said.length && said.every((u, i) => users4[i] === u)) {
100522
+ let seen = 0, at3 = 0;
100523
+ while (at3 < messages4.length && seen < said.length) {
100524
+ if (messages4[at3].role === "user") seen++;
100525
+ at3++;
100526
+ }
100527
+ messages4 = messages4.slice(at3);
100528
+ }
100529
+ const t = headerOf2(turn.lines).started_at;
100530
+ for (const m of messages4) if (!(m.role === "assistant" && transcript3.at(-1)?.role === "assistant")) transcript3.push({ ...m, ...t && { t } });
100531
+ const answer = answerOf(turn.lines), last = turn.lines.filter((l) => l.t).at(-1)?.t ?? t;
100532
+ if (answer && !(transcript3.at(-1)?.role === "assistant" && transcript3.at(-1).content === answer)) transcript3.push({ role: "assistant", content: answer, ...last && { t: last } });
100533
+ }
100534
+ return transcript3;
100535
+ }
100536
+ function conversationsOf(docs2) {
100537
+ const episodes = /* @__PURE__ */ new Map();
100538
+ for (const { traceId, lines } of docs2) episodes.set(traceId, episodes.has(traceId) ? mergeIr(episodes.get(traceId), lines) : lines);
100539
+ const traces = [...episodes].map(([id12, lines]) => ({ id: id12, lines, start: startOf(lines), session: headerOf2(lines).session, users: userMessages(lines) })).sort((a, b) => a.start - b.start);
100540
+ const conversations = [], sessions = /* @__PURE__ */ new Map();
100541
+ for (const trace of traces) {
100542
+ if (trace.session !== void 0) {
100543
+ const known2 = sessions.get(trace.session);
100544
+ if (known2) known2.turns.push(trace);
100545
+ else {
100546
+ const c = { id: String(trace.session), turns: [trace] };
100547
+ sessions.set(trace.session, c);
100548
+ conversations.push(c);
100549
+ }
100550
+ continue;
100551
+ }
100552
+ const prior = trace.users.length > 1 && conversations.find((c) => {
100553
+ const last = c.turns.at(-1);
100554
+ return last.session === void 0 && last.users.length === trace.users.length - 1 && last.users.every((u, i) => u === trace.users[i]);
100555
+ });
100556
+ if (prior) prior.turns.push(trace);
100557
+ else conversations.push({ id: String(trace.id), turns: [trace] });
100558
+ }
100559
+ return conversations.map((c) => ({ id: c.id, traces: c.turns.map((t) => t.id), lines: c.turns.map((t) => t.lines).reduce((merged, next2) => mergeIr(merged, next2)), transcript: transcriptOf(c.turns) }));
100560
+ }
100561
+ var headerOf2, startOf;
100562
+ var init_conversations = __esm({
100563
+ "cloud/rebuild/conversations.mjs"() {
100564
+ "use strict";
100565
+ init_ir();
100566
+ headerOf2 = (lines) => lines.find((l) => l.ir) ?? {};
100567
+ startOf = (lines) => Date.parse(headerOf2(lines).started_at ?? lines.find((l) => l.t)?.t ?? 0) || 0;
100568
+ }
100569
+ });
100570
+
100404
100571
  // cloud/rebuild/adapters/messages.mjs
100405
100572
  function feedbackStatus(value5) {
100406
100573
  return value5 === false || value5 === 0 ? "error" : value5 === true || value5 === 1 ? "ok" : "unknown";
@@ -100690,6 +100857,12 @@ function toolOf(a, span2) {
100690
100857
  if (looksCut(text24) || looksCut(resultText)) record23.truncated = true;
100691
100858
  return record23;
100692
100859
  }
100860
+ function outputOf(a) {
100861
+ const listed = parse18(a["gen_ai.output.messages"]);
100862
+ if (Array.isArray(listed)) return lastAnswer(conversation2(listed).messages) || void 0;
100863
+ const text24 = a["llm.output_messages.0.message.content"] ?? a["gen_ai.completion.0.content"] ?? a["ai.response.text"];
100864
+ return typeof text24 === "string" && text24.trim() ? text24 : void 0;
100865
+ }
100693
100866
  function inputOf(a, span2) {
100694
100867
  const event3 = span2.events?.find((e) => e.name === "gen_ai.content.prompt")?.attributes?.find((x) => x.key === "gen_ai.prompt")?.value;
100695
100868
  let messages4 = parse18(a["gen_ai.input.messages"] ?? a["gen_ai.prompt"] ?? a["ai.prompt.messages"] ?? value4(event3));
@@ -100778,7 +100951,7 @@ function traceToIr3(traceId, { agent, environment: environment3, spans }, { offs
100778
100951
  invocationIsRoot = isRoot3;
100779
100952
  }
100780
100953
  } else if (kind === "llm") {
100781
- const input2 = inputOf(a, span2), tools2 = toolDefinitions(a);
100954
+ const input2 = inputOf(a, span2), tools2 = toolDefinitions(a), output2 = outputOf(a);
100782
100955
  records3.push({
100783
100956
  kind: "llm",
100784
100957
  id: span2.spanId,
@@ -100786,6 +100959,7 @@ function traceToIr3(traceId, { agent, environment: environment3, spans }, { offs
100786
100959
  model: a["gen_ai.request.model"] ?? a["llm.model_name"] ?? a["ai.model.id"],
100787
100960
  usage: { input: a["gen_ai.usage.input_tokens"] ?? a["llm.token_count.prompt"] ?? a["ai.usage.promptTokens"], output: a["gen_ai.usage.output_tokens"] ?? a["llm.token_count.completion"] ?? a["ai.usage.completionTokens"] },
100788
100961
  ...input2 && { input: input2 },
100962
+ ...output2 && { output: output2 },
100789
100963
  ...tools2 && { tools: tools2 }
100790
100964
  });
100791
100965
  }
@@ -101023,10 +101197,14 @@ var init_answers = __esm({
101023
101197
  var rebuild_exports = {};
101024
101198
  __export(rebuild_exports, {
101025
101199
  REBUILT: () => REBUILT,
101200
+ agentValuesInGoal: () => agentValuesInGoal,
101026
101201
  answerErrors: () => answerErrors,
101027
101202
  callKey: () => callKey,
101203
+ conversationsOf: () => conversationsOf,
101204
+ customerFacts: () => customerFacts,
101028
101205
  decodeOtlpProto: () => decodeOtlpProto,
101029
101206
  fileToIr: () => fileToIr,
101207
+ goalWithout: () => goalWithout,
101030
101208
  intakeOf: () => intakeOf,
101031
101209
  isWrite: () => isWrite,
101032
101210
  itemsOf: () => itemsOf,
@@ -101035,6 +101213,7 @@ __export(rebuild_exports, {
101035
101213
  mergeIr: () => mergeIr,
101036
101214
  otlpToIr: () => otlpToIr,
101037
101215
  parseIr: () => parseIr,
101216
+ personByRule: () => personByRule,
101038
101217
  readTools: () => readTools,
101039
101218
  rebuild: () => rebuild,
101040
101219
  sceneFiles: () => sceneFiles,
@@ -101043,11 +101222,11 @@ __export(rebuild_exports, {
101043
101222
  spansByTrace: () => spansByTrace,
101044
101223
  traceToIr: () => traceToIr3
101045
101224
  });
101046
- function rebuild(ir, { id: id12 = "rebuilt-from-trace", title, task: task2, answers = {}, expect, examples: examples2 } = {}) {
101225
+ function rebuild(ir, { id: id12 = "rebuilt-from-trace", title, task: task2, answers = {}, expect, examples: examples2, customer: customer3 } = {}) {
101047
101226
  const { header: header4, records: records3 } = typeof ir === "string" ? parseIr(ir) : { header: ir.find((l) => l.ir), records: ir.filter((l) => !l.ir) };
101048
101227
  const cx = createContext(itemsOf(records3));
101049
101228
  cx.answers = answers ?? {};
101050
- const own2 = records3.some((r) => r.kind === "tool") || header4?.input?.messages?.length ? readTools(cx, header4, records3, { examples: examplesOf(examples2, Date.parse(header4?.started_at ?? records3.find((r) => r.t)?.t ?? 0)) }) : void 0;
101229
+ const own2 = records3.some((r) => r.kind === "tool") || header4?.input?.messages?.length ? readTools(cx, header4, records3, { examples: examplesOf(examples2, Date.parse(header4?.started_at ?? records3.find((r) => r.t)?.t ?? 0), valuesOf2(records3.filter((r) => r.kind === "tool").map((r) => r.args))) }) : void 0;
101051
101230
  if (!cx.items.length && !own2) throw Object.assign(new Error("the trace has no tool calls, API calls or webhooks Ancha can read, and no input"), { code: "NO_CALLS" });
101052
101231
  task2 ??= own2?.trigger.task ?? inferTask(cx, records3);
101053
101232
  const slack2 = readSlack(cx), github2 = readGitHub(cx), datadog2 = readDatadog(cx), pagerduty = readPagerDuty(cx);
@@ -101071,24 +101250,31 @@ function rebuild(ir, { id: id12 = "rebuilt-from-trace", title, task: task2, answ
101071
101250
  for (const service of read6) if (!cx.seed[service]) cx.note("missing", `seed.${service}`, `calls to ${service} were seen, but Ancha cannot rebuild ${service} yet`);
101072
101251
  linkTwins(cx, own2);
101073
101252
  proposeToolChecks(cx, own2, { expect });
101253
+ const users4 = customer3?.transcript.filter((line2) => line2.role === "user") ?? [];
101254
+ const people3 = customer3 && !cx.seed.slack ? placePerson(cx, customer3.person, { agent: header4?.agent, opener: users4[0]?.content ?? task2, userTurns: users4.length }) : void 0;
101255
+ if (people3) {
101256
+ const left = (customer3.dropped?.length ? `; left out because the agent said it first: ${customer3.dropped.join("; ")}` : "") + (customer3.rewrote?.length ? `; the goal written again without ${customer3.rewrote.join("; ")}` : "");
101257
+ cx.note("inferred", "people.customer", customer3.by === "rule" ? `from the customer's lines without a model: the first is the goal, each later one a fact${left}` : `the customer's goal and ${(people3[0].knows ?? []).length} facts, written down from their lines by ${customer3.by}${left}`);
101258
+ } else if (customer3) cx.note("missing", "people.customer", "production talked to the customer on Slack, where the test does not place them yet");
101074
101259
  const lastMs = Math.max(0, ...[...cx.rules.actors ?? [], ...cx.rules.app_calls ?? []].filter((r) => "at" in r).map((r) => parseMs(r.at)));
101075
101260
  const long = lastMs > 10 * 6e4;
101076
101261
  const firstMs = Math.min(...[...cx.rules.actors ?? [], ...cx.rules.app_calls ?? []].filter((r) => "at" in r).map((r) => parseMs(r.at)));
101077
101262
  const setup2 = cx.rules.app_calls?.length ? cx.items.filter((i) => i.kind === "call" && i.ms - cx.start < firstMs).map(callKey) : [];
101078
101263
  const tools2 = own2 && Object.keys(own2.tools).length ? own2.tools : void 0;
101264
+ const start = people3 ? {} : { task: task2, ...own2 && Object.keys(own2.trigger).length && { trigger: own2.trigger } };
101079
101265
  const scene2 = {
101080
101266
  id: id12,
101081
101267
  title: title ?? `Rebuilt from trace ${header4?.trace_id ?? ""}`.trim(),
101082
101268
  twins: Object.keys(cx.seed),
101083
101269
  start_time: new Date(cx.items.length ? cx.start : own2.startMs).toISOString(),
101084
101270
  time_scale: 1,
101085
- timeout: long ? cx.dur(lastMs + 36e5) : "10m",
101271
+ timeout: long ? cx.dur(lastMs + 36e5) : people3 ? "30m" : "10m",
101086
101272
  ...long && { skip_idle: true },
101087
- task: task2,
101088
- ...own2 && Object.keys(own2.trigger).length && { trigger: own2.trigger },
101273
+ ...start,
101089
101274
  ...tools2 && { tools: tools2 },
101090
101275
  seed: cx.seed,
101091
101276
  ...Object.keys(cx.rules).length && { world_rules: cx.rules },
101277
+ ...people3 && { people: people3 },
101092
101278
  checks: cx.checks,
101093
101279
  pass: cx.checks.map((c) => c.id)
101094
101280
  };
@@ -101103,7 +101289,27 @@ function rebuild(ir, { id: id12 = "rebuilt-from-trace", title, task: task2, answ
101103
101289
  summary: { trace: header4?.trace_id, agent: header4?.agent, records: records3.length, observed: count3("observed"), inferred: count3("inferred"), missing: count3("missing"), questions: cx.questions.length, production: cx.production }
101104
101290
  };
101105
101291
  }
101106
- function examplesOf(traces = [], startOfThisTrace) {
101292
+ function valuesOf2(value5, into = /* @__PURE__ */ new Set()) {
101293
+ if (typeof value5 === "string") {
101294
+ if (value5.length >= 3 && value5.length <= 200) into.add(value5);
101295
+ } else if (typeof value5 === "number") {
101296
+ if (Math.abs(value5) >= 100) into.add(String(value5));
101297
+ } else if (Array.isArray(value5)) for (const v of value5) valuesOf2(v, into);
101298
+ else if (value5 && typeof value5 === "object") for (const v of Object.values(value5)) valuesOf2(v, into);
101299
+ return into;
101300
+ }
101301
+ function examplesOf(traces = [], startOfThisTrace, near = /* @__PURE__ */ new Set()) {
101302
+ const byTool = /* @__PURE__ */ new Map();
101303
+ for (const e of allExamples(traces, startOfThisTrace)) {
101304
+ const calls2 = byTool.get(e.tool) ?? /* @__PURE__ */ new Map(), key3 = JSON.stringify(e.args);
101305
+ calls2.delete(key3);
101306
+ calls2.set(key3, e);
101307
+ byTool.set(e.tool, calls2);
101308
+ }
101309
+ const shared = (e) => [...valuesOf2(e.args)].filter((v) => near.has(v)).length;
101310
+ return [...byTool.values()].flatMap((calls2) => [...calls2.values()].map((e, i) => ({ e, i, score: shared(e) })).sort((a, b) => b.score - a.score || b.i - a.i).slice(0, EXAMPLES_PER_TOOL).sort((a, b) => a.i - b.i).map(({ e }) => e));
101311
+ }
101312
+ function allExamples(traces, startOfThisTrace) {
101107
101313
  return traces.flatMap((lines) => {
101108
101314
  const header4 = lines.find((l) => l.ir), start = Date.parse(header4?.started_at ?? lines.find((l) => l.t)?.t ?? 0);
101109
101315
  const at3 = (t) => {
@@ -101122,7 +101328,7 @@ function parseMs(text24) {
101122
101328
  const m = /^(-?)(?:(\d+)s)?(?:(\d+)ms)?$/.exec(String(text24));
101123
101329
  return m ? (m[1] ? -1 : 1) * (Number(m[2] ?? 0) * 1e3 + Number(m[3] ?? 0)) : 0;
101124
101330
  }
101125
- var ISO_TIME;
101331
+ var EXAMPLES_PER_TOOL, ISO_TIME;
101126
101332
  var init_rebuild = __esm({
101127
101333
  "cloud/rebuild/index.mjs"() {
101128
101334
  "use strict";
@@ -101138,7 +101344,10 @@ var init_rebuild = __esm({
101138
101344
  init_maps();
101139
101345
  init_intake();
101140
101346
  init_tools();
101347
+ init_person();
101141
101348
  init_ir();
101349
+ init_conversations();
101350
+ init_person();
101142
101351
  init_file2();
101143
101352
  init_langfuse();
101144
101353
  init_langsmith();
@@ -101147,6 +101356,7 @@ var init_rebuild = __esm({
101147
101356
  init_intake();
101148
101357
  init_answers();
101149
101358
  init_tools();
101359
+ EXAMPLES_PER_TOOL = 30;
101150
101360
  ISO_TIME = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})/g;
101151
101361
  }
101152
101362
  });
@@ -114312,7 +114522,7 @@ var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
114312
114522
  function isLeapYear(year) {
114313
114523
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
114314
114524
  }
114315
- const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
114525
+ const DATE2 = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
114316
114526
  const DAYS2 = [
114317
114527
  0,
114318
114528
  31,
@@ -114329,7 +114539,7 @@ var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => {
114329
114539
  31
114330
114540
  ];
114331
114541
  function date10(str4) {
114332
- const matches7 = DATE.exec(str4);
114542
+ const matches7 = DATE2.exec(str4);
114333
114543
  if (!matches7) return false;
114334
114544
  const year = +matches7[1];
114335
114545
  const month = +matches7[2];
@@ -123066,8 +123276,8 @@ async function handleApiCall(c) {
123066
123276
  const args = await readArgs(c.req.raw);
123067
123277
  ctx.signal?.throwIfAborted();
123068
123278
  if (name5 === "apps.connections.open" && c.req.method !== "POST") throw new SlackError("method_not_supported");
123069
- const access7 = reads.has(name5) ? withRead : withMutation;
123070
- const body6 = access7(ctx, () => {
123279
+ const access8 = reads.has(name5) ? withRead : withMutation;
123280
+ const body6 = access8(ctx, () => {
123071
123281
  const caller2 = authenticate(ctx, tokenOf(c.req.raw, args), name5 === "apps.connections.open");
123072
123282
  return method2(ctx, args, caller2);
123073
123283
  });
@@ -125162,10 +125372,10 @@ var Node = class Node2 {
125162
125372
  #index;
125163
125373
  #varIndex;
125164
125374
  #children = createNullObject();
125165
- insert(tokens2, index, paramMap, context2, isStatic) {
125375
+ insert(tokens3, index, paramMap, context2, isStatic) {
125166
125376
  let node5 = this;
125167
- for (let i = 0, len = tokens2.length; i < len; i++) {
125168
- const token2 = tokens2[i];
125377
+ for (let i = 0, len = tokens3.length; i < len; i++) {
125378
+ const token2 = tokens3[i];
125169
125379
  const pattern = token2.length === 1 ? token2 === "*" ? i === len - 1 ? [
125170
125380
  "",
125171
125381
  "",
@@ -125250,15 +125460,15 @@ var Trie = class {
125250
125460
  });
125251
125461
  if (!replaced2) break;
125252
125462
  }
125253
- const tokens2 = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
125463
+ const tokens3 = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
125254
125464
  for (let i = groups.length - 1; i >= 0; i--) {
125255
125465
  const [mark] = groups[i];
125256
- for (let j = tokens2.length - 1; j >= 0; j--) if (tokens2[j].indexOf(mark) !== -1) {
125257
- tokens2[j] = tokens2[j].replace(mark, groups[i][1]);
125466
+ for (let j = tokens3.length - 1; j >= 0; j--) if (tokens3[j].indexOf(mark) !== -1) {
125467
+ tokens3[j] = tokens3[j].replace(mark, groups[i][1]);
125258
125468
  break;
125259
125469
  }
125260
125470
  }
125261
- this.#root.insert(tokens2, this.#index, paramAssoc, this.#context, false);
125471
+ this.#root.insert(tokens3, this.#index, paramAssoc, this.#context, false);
125262
125472
  this.paths[path6] = [this.#index++, paramAssoc];
125263
125473
  }
125264
125474
  buildRegExp() {
@@ -127347,7 +127557,7 @@ function decodeQuotedPrintable(text24) {
127347
127557
  return Buffer.from(bytes3);
127348
127558
  }
127349
127559
  function parseHeaderParams(value5) {
127350
- const tokens2 = [];
127560
+ const tokens3 = [];
127351
127561
  let current = "", quoted3 = false;
127352
127562
  for (let i = 0; i < value5.length; i++) {
127353
127563
  const ch = value5[i];
@@ -127360,16 +127570,16 @@ function parseHeaderParams(value5) {
127360
127570
  continue;
127361
127571
  }
127362
127572
  if (ch === ";" && !quoted3) {
127363
- tokens2.push(current);
127573
+ tokens3.push(current);
127364
127574
  current = "";
127365
127575
  continue;
127366
127576
  }
127367
127577
  current += ch;
127368
127578
  }
127369
- tokens2.push(current);
127579
+ tokens3.push(current);
127370
127580
  const params9 = {};
127371
127581
  const extended2 = {};
127372
- for (const token2 of tokens2.slice(1)) {
127582
+ for (const token2 of tokens3.slice(1)) {
127373
127583
  const eq = token2.indexOf("=");
127374
127584
  if (eq < 1) continue;
127375
127585
  const key3 = token2.slice(0, eq).trim().toLowerCase(), val = token2.slice(eq + 1).trim();
@@ -127397,7 +127607,7 @@ function parseHeaderParams(value5) {
127397
127607
  });
127398
127608
  params9[name5] = decodeCharset(Buffer.concat(bytes3), charset);
127399
127609
  }
127400
- return { value: tokens2[0].trim(), params: params9 };
127610
+ return { value: tokens3[0].trim(), params: params9 };
127401
127611
  }
127402
127612
  function splitHeaders(block2) {
127403
127613
  const headers = [];
@@ -127783,8 +127993,8 @@ function handle(route11) {
127783
127993
  }
127784
127994
  }
127785
127995
  try {
127786
- const access7 = route11.read ? withRead : withMutation;
127787
- const result = access7(ctx, () => {
127996
+ const access8 = route11.read ? withRead : withMutation;
127997
+ const result = access8(ctx, () => {
127788
127998
  const caller2 = authenticate2(c, route11.scopes);
127789
127999
  const query11 = readQuery(c, route11.query ?? []);
127790
128000
  if (bodyError) throw bodyError;
@@ -129495,7 +129705,7 @@ function readWorldSnapshot(bytes3) {
129495
129705
  init_src();
129496
129706
 
129497
129707
  // packages/server/src/agent-tools/simulate.ts
129498
- var SYSTEM = `You stand in for one tool of an AI agent's application, in a test made from a production trace. Production recorded some calls to this tool. Answer the new call exactly as the real tool would at this point: consistent with what production recorded and with the writes the agent already made in this test, in the same shape as production's results (the same top-level fields, with values of the same types). The call happens at time.now: a time the tool reports for this call (when a reading was taken, when something was posted) is time.now. When time has passed since production's last answer, answer as the tool would by then: what changes over time (a status, a measurement) moves on the way the recorded answers, the writes and the tool's calls in other production runs imply; those runs' times are already on this run's timeline. Invent nothing the tool would not know. If the real tool would fail on this call (an unknown id, invalid arguments), answer with its error instead. Reply with JSON: {"result_json": "<the result as a JSON string>"} or {"error": "<the error message>"}.`;
129708
+ var SYSTEM = `You stand in for one tool of an AI agent's application, in a test made from a production trace. Production recorded some calls to this tool. Answer the new call exactly as the real tool would at this point: consistent with what production recorded, with the calls the agent already made in this test and their answers (calls_in_this_test, writes included), and with the records that mention this call's values (records_that_mention_these_values: what other tools answered about the same thing), in the same shape as production's results (the same top-level fields, with values of the same types). The call happens at time.now: a time the tool reports for this call (when a reading was taken, when something was posted) is time.now. When time has passed since production's last answer, answer as the tool would by then: what changes over time (a status, a measurement) moves on the way the recorded answers, the writes and the tool's calls in other production runs imply; those runs' times are already on this run's timeline. Invent nothing the tool would not know. If the real tool would fail on this call (an unknown id, invalid arguments), answer with its error instead. Reply with JSON: {"result_json": "<the result as a JSON string>"} or {"error": "<the error message>"}.`;
129499
129709
  var SCHEMA5 = { name: "tool_answer", schema: { type: "object", additionalProperties: false, properties: { result_json: { type: "string" }, error: { type: "string" } } } };
129500
129710
  function shape(value5) {
129501
129711
  if (Array.isArray(value5)) return `[${value5.length ? shape(value5[0]) : ""}]`;
@@ -129517,12 +129727,15 @@ function sameShape(result, recorded2) {
129517
129727
  async function simulate(model2, request2, signal) {
129518
129728
  const recorded2 = (request2.tool?.recorded ?? []).map((o) => ({ args: o.args, at: o.at, ...o.error !== void 0 ? { error: o.error } : { result: o.result } }));
129519
129729
  const results = recorded2.filter((o) => "result" in o).map((o) => o.result);
129730
+ const known2 = results.length ? results : (request2.tool?.examples ?? []).filter((o) => o.error === void 0 && o.result !== void 0).map((o) => o.result);
129731
+ const text24 = known2.length > 0 && known2.every((r) => typeof r === "string");
129520
129732
  const user8 = JSON.stringify({
129521
129733
  tool: { name: request2.name, ...request2.tool?.description && { description: request2.tool.description }, ...request2.tool?.schema && { arguments: request2.tool.schema }, ...request2.tool?.write && { changes_something: true } },
129522
129734
  production_recorded: recorded2.slice(-20),
129523
129735
  ...request2.tool?.examples?.length && { other_production_runs_of_this_agent: request2.tool.examples.slice(-30) },
129524
- ...results.length && { result_shape: shape(results[0]) },
129525
- writes_in_this_test: request2.writes.slice(-20),
129736
+ ...known2.length && { result_shape: shape(known2[0]) },
129737
+ calls_in_this_test: request2.calls.slice(-30),
129738
+ ...request2.records?.length && { records_that_mention_these_values: request2.records },
129526
129739
  call: { arguments: request2.args, ...request2.repeat && { production_made_this_exact_call: request2.repeat.recorded, this_is_call_number: request2.repeat.call } },
129527
129740
  // Time moves on as the agent waits: a status read later may say what a real one would say by then.
129528
129741
  ...request2.time && { time: {
@@ -129530,7 +129743,7 @@ async function simulate(model2, request2, signal) {
129530
129743
  ...request2.time.now_ms > request2.time.last_recorded_ms && { seconds_since_productions_last_answer: Math.round((request2.time.now_ms - request2.time.last_recorded_ms) / 1e3) }
129531
129744
  } }
129532
129745
  });
129533
- let inputTokens = 0, outputTokens = 0, costUsd = 0, model_, feedback = "";
129746
+ let inputTokens = 0, outputTokens = 0, costUsd = 0, model_, feedback = "", last = "";
129534
129747
  for (let attempt = 0; attempt < 2; attempt++) {
129535
129748
  const answer = await model2.complete({ kind: "simulate", person: request2.name, system: SYSTEM, user: feedback ? `${user8}
129536
129749
 
@@ -129540,18 +129753,23 @@ ${feedback}` : user8, schema: SCHEMA5, temperature: 0, maxTokens: 1200 }, signal
129540
129753
  costUsd += answer.costUsd;
129541
129754
  model_ = answer.model;
129542
129755
  const out = answer.output;
129756
+ last = JSON.stringify(out ?? null).slice(0, 200);
129543
129757
  if (typeof out?.error === "string" && out.error && out.result_json === void 0) return { error: out.error, inputTokens, outputTokens, costUsd, model: model_ };
129544
129758
  let result;
129545
129759
  try {
129546
129760
  result = JSON.parse(String(out?.result_json));
129547
129761
  } catch {
129548
- feedback = "Your result_json was not valid JSON. Answer again.";
129549
- continue;
129762
+ if (!text24 || typeof out?.result_json !== "string") {
129763
+ feedback = "Your result_json was not valid JSON. Answer again.";
129764
+ continue;
129765
+ }
129766
+ result = out.result_json;
129550
129767
  }
129551
- if (sameShape(result, results)) return { result, inputTokens, outputTokens, costUsd, model: model_ };
129552
- feedback = `Your result has the shape ${shape(result)}, but production's results have the shape ${shape(results[0])}. Answer again in that shape.`;
129768
+ if (text24 && typeof result !== "string" && typeof out?.result_json === "string") result = out.result_json;
129769
+ if (sameShape(result, known2)) return { result, inputTokens, outputTokens, costUsd, model: model_ };
129770
+ feedback = `Your result has the shape ${shape(result)}, but production's results have the shape ${shape(known2[0])}. Answer again in that shape.`;
129553
129771
  }
129554
- throw new PeopleModelError(`the simulated answer to ${request2.name} did not have the shape of production's results`);
129772
+ throw new PeopleModelError(`the simulated answer to ${request2.name} did not have the shape of production's results (the model's last answer: ${last})`);
129555
129773
  }
129556
129774
 
129557
129775
  // packages/server/src/agent-tools/index.ts
@@ -129580,6 +129798,29 @@ var getState = (ctx, k) => ctx.store.db.prepare("SELECT v FROM agent_tool_state
129580
129798
  var setState = (ctx, k, v) => ctx.store.db.prepare("INSERT INTO agent_tool_state (k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v=excluded.v").run(k, v);
129581
129799
  var SIMULATION_LIMIT = () => Number(process.env.ANCHA_SIMULATE_MAX ?? 30);
129582
129800
  var simulationOn = (ctx) => process.env.ANCHA_SIMULATE !== "0" && ctx.model !== void 0;
129801
+ var ID_LIKE = /^(?=.*[\d@])[A-Za-z0-9][\w.:@#/+-]{3,63}$/;
129802
+ var DATE = /^\d{4}-\d{2}-\d{2}/;
129803
+ function idValues(value5, out = /* @__PURE__ */ new Set()) {
129804
+ if (Array.isArray(value5)) for (const v of value5) idValues(v, out);
129805
+ else if (value5 && typeof value5 === "object") for (const v of Object.values(value5)) idValues(v, out);
129806
+ else if ((typeof value5 === "string" || typeof value5 === "number" && Number.isInteger(value5)) && ID_LIKE.test(String(value5)) && !DATE.test(String(value5))) out.add(String(value5));
129807
+ return out;
129808
+ }
129809
+ var RECORDS_SHOWN = 20;
129810
+ function recordsMentioning(ctx, name5, args) {
129811
+ const ids2 = [...idValues(args)].map((id12) => new RegExp(`(^|[^A-Za-z0-9])${id12.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}([^A-Za-z0-9]|$)`));
129812
+ if (!ids2.length) return [];
129813
+ const records3 = [];
129814
+ const add = (tool, o, here) => {
129815
+ const answer = o.error !== void 0 ? { error: o.error } : { result: o.result };
129816
+ const text24 = JSON.stringify([o.args, answer]);
129817
+ if (ids2.some((id12) => id12.test(text24))) records3.push({ tool, args: o.args ?? {}, ...answer, conversation: here ? "this one" : o.trace ?? "another" });
129818
+ };
129819
+ const others = Object.entries(ctx.scene.tools ?? {}).filter(([tool]) => tool !== name5);
129820
+ for (const [tool] of others) for (const o of recorded(ctx, tool)) add(tool, o, true);
129821
+ for (const [tool, t] of others) for (const o of [...t.examples ?? []].reverse()) add(tool, o, false);
129822
+ return records3.slice(0, RECORDS_SHOWN);
129823
+ }
129583
129824
  function keepUp(ctx) {
129584
129825
  const behind = withRead(ctx, () => Number(getState(ctx, "reached") ?? 0)) - ctx.clock.elapsedMs();
129585
129826
  if (behind > 0) ctx.clock.advance(behind);
@@ -129607,13 +129848,19 @@ function decide(ctx, name5, args) {
129607
129848
  setState(ctx, "reached", String(Math.max(reached, o.endMs)));
129608
129849
  return o.error !== void 0 ? { source: "replayed", error: o.error, ...o.raw !== void 0 && { raw: o.raw, wrap: o.wrap } } : { source: "replayed", result: o.result, ...o.raw !== void 0 && { raw: o.raw, wrap: o.wrap } };
129609
129850
  }
129851
+ if (!same2.length && !tool?.write) {
129852
+ const elsewhere = [...tool?.examples ?? []].reverse().find((o) => o.error === void 0 && o.result !== void 0 && canonical2(o.args) === key3);
129853
+ if (elsewhere) return { source: "replayed-elsewhere", result: elsewhere.result };
129854
+ }
129610
129855
  if (tool?.twin !== void 0 || policy === "twin") return { source: "twin", passthrough: true };
129856
+ if (tool?.pure) return { source: "ran", passthrough: true };
129611
129857
  const repeat = same2.length ? { recorded: same2.length, call: n + 1 } : void 0;
129612
129858
  const last = same2.at(-1) ?? recorded(ctx, name5).at(-1), took = last ? last.endMs - last.atMs : 0;
129613
129859
  if (policy === "simulate" && simulationOn(ctx)) {
129614
129860
  if (Number(getState(ctx, "simulated") ?? 0) >= SIMULATION_LIMIT()) return { source: "failed", error: `Ancha has no recorded answer for this call, and this test reached its limit of ${SIMULATION_LIMIT()} simulated answers` };
129615
129861
  const lastRecordedMs = Math.max(0, ...recorded(ctx, name5).map((o) => o.endMs));
129616
- return { simulate: { name: name5, tool, args, ...repeat && { repeat }, time: { now_ms: Math.max(reached, ctx.clock.elapsedMs()), last_recorded_ms: lastRecordedMs, start: ctx.scene.start_time } }, cacheKey: callKey2, reached, took };
129862
+ const records3 = recordsMentioning(ctx, name5, args);
129863
+ return { simulate: { name: name5, tool, args, ...repeat && { repeat }, ...records3.length && { records: records3 }, time: { now_ms: Math.max(reached, ctx.clock.elapsedMs()), last_recorded_ms: lastRecordedMs, start: ctx.scene.start_time } }, cacheKey: callKey2, reached, took };
129617
129864
  }
129618
129865
  if (repeat && !tool?.write) {
129619
129866
  const o = same2.at(-1);
@@ -129623,14 +129870,14 @@ function decide(ctx, name5, args) {
129623
129870
  const unsimulated = policy === "simulate" && !simulationOn(ctx) ? process.env.ANCHA_SIMULATE === "0" ? "; simulation is off (ANCHA_SIMULATE=0)" : "; there is no model to simulate one with (set OPENROUTER_API_KEY)" : "";
129624
129871
  return { source: "failed", error: `Ancha has no recorded answer for this call: ${why}${unsimulated}` };
129625
129872
  }
129626
- function noteWrite(ctx, name5, args, a) {
129627
- if (!ctx.scene.tools?.[name5]?.write || a.passthrough) return;
129628
- const writes2 = JSON.parse(getState(ctx, "writes") ?? "[]");
129629
- writes2.push({ tool: name5, args, ...a.error !== void 0 ? { error: a.error } : { result: a.result } });
129630
- setState(ctx, "writes", JSON.stringify(writes2.slice(-50)));
129873
+ function noteCall(ctx, name5, args, a) {
129874
+ if (a.passthrough) return;
129875
+ const calls2 = JSON.parse(getState(ctx, "calls") ?? "[]");
129876
+ calls2.push({ tool: name5, args, ...ctx.scene.tools?.[name5]?.write && { changes_something: true }, ...a.error !== void 0 ? { error: a.error } : { result: a.result } });
129877
+ setState(ctx, "calls", JSON.stringify(calls2.slice(-50)));
129631
129878
  }
129632
129879
  function toolsToWrap(ctx) {
129633
- return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => t.twin === void 0 && !t.mcp && !t.allow_unwrapped).map(([name5]) => name5).sort();
129880
+ return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => t.twin === void 0 && !t.mcp && !t.pure && !t.allow_unwrapped).map(([name5]) => name5).sort();
129634
129881
  }
129635
129882
  function registration(ctx, names3) {
129636
129883
  const before = JSON.parse(getState(ctx, "wrapped") ?? "[]");
@@ -129678,14 +129925,14 @@ function agentToolsService() {
129678
129925
  const ctx = c.env.ctx, args = body6.args ?? {};
129679
129926
  const decision2 = withMutation(ctx, () => decide(ctx, name5, args));
129680
129927
  if (!("simulate" in decision2)) {
129681
- withMutation(ctx, () => noteWrite(ctx, name5, args, decision2));
129928
+ withMutation(ctx, () => noteCall(ctx, name5, args, decision2));
129682
129929
  keepUp(ctx);
129683
129930
  return c.json(decision2);
129684
129931
  }
129685
129932
  let answered;
129686
129933
  try {
129687
- const writes2 = withRead(ctx, () => JSON.parse(getState(ctx, "writes") ?? "[]"));
129688
- const sim = await simulate(ctx.model, { ...decision2.simulate, writes: writes2 }, c.req.raw.signal);
129934
+ const calls2 = withRead(ctx, () => JSON.parse(getState(ctx, "calls") ?? "[]"));
129935
+ const sim = await simulate(ctx.model, { ...decision2.simulate, calls: calls2 }, c.req.raw.signal);
129689
129936
  answered = { source: "simulated", ...sim.error !== void 0 ? { error: sim.error } : { result: sim.result }, cost_usd: Math.round(sim.costUsd * 1e6) / 1e6 };
129690
129937
  } catch (error64) {
129691
129938
  answered = { source: "failed", error: `Ancha has no recorded answer for this call and could not simulate one: ${error64 instanceof Error ? error64.message : String(error64)}` };
@@ -129697,11 +129944,11 @@ function agentToolsService() {
129697
129944
  setState(ctx, `sim:${decision2.cacheKey}`, JSON.stringify({ answer: { ...answered, cost_usd: void 0 }, reached: now10 }));
129698
129945
  setState(ctx, "simulated", String(Number(getState(ctx, "simulated") ?? 0) + 1));
129699
129946
  }
129700
- noteWrite(ctx, name5, args, answered);
129947
+ noteCall(ctx, name5, args, answered);
129701
129948
  return answered;
129702
129949
  });
129703
129950
  keepUp(ctx);
129704
- return c.json(answer);
129951
+ return answer.source === "failed" ? c.json(answer, 200, { [SETUP_ISSUE_HEADER]: "1" }) : c.json(answer);
129705
129952
  });
129706
129953
  app2.all("*", (c) => c.json({ error: `not a route of Ancha's tool service: ${c.req.method} ${new URL(c.req.url).pathname}` }, 404));
129707
129954
  return {
@@ -130540,7 +130787,7 @@ var definitions2 = {
130540
130787
  function parse4(source) {
130541
130788
  if (source.length > 2e4)
130542
130789
  invalid7("Query too long");
130543
- const tokens2 = [];
130790
+ const tokens3 = [];
130544
130791
  let pos = 0;
130545
130792
  const scanner = /\s*(?:([A-Za-z_][A-Za-z_0-9.]*)|(-?\d+(?:\.\d+)?)|('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")|(>=|<=|!=|=|>|<|,|\(|\)))/y;
130546
130793
  while (pos < source.length) {
@@ -130551,14 +130798,14 @@ function parse4(source) {
130551
130798
  break;
130552
130799
  gap(`GAQL syntax near ${source.slice(pos, pos + 30)}`);
130553
130800
  }
130554
- tokens2.push(m[1] ?? m[2] ?? m[3] ?? m[4]);
130801
+ tokens3.push(m[1] ?? m[2] ?? m[3] ?? m[4]);
130555
130802
  pos = scanner.lastIndex;
130556
130803
  }
130557
130804
  let i = 0;
130558
- const peek = () => tokens2[i]?.toUpperCase(), take2 = () => {
130559
- if (i >= tokens2.length)
130805
+ const peek = () => tokens3[i]?.toUpperCase(), take2 = () => {
130806
+ if (i >= tokens3.length)
130560
130807
  invalid7("Unexpected end of query");
130561
- return tokens2[i++];
130808
+ return tokens3[i++];
130562
130809
  }, expect = (s) => {
130563
130810
  if (take2().toUpperCase() !== s)
130564
130811
  invalid7(`Expected ${s}`);
@@ -130637,8 +130884,8 @@ function parse4(source) {
130637
130884
  invalid7("LIMIT must be 1..100000");
130638
130885
  limit2 = Number(n);
130639
130886
  }
130640
- if (i !== tokens2.length)
130641
- gap(`GAQL clause ${tokens2.slice(i).join(" ")}`);
130887
+ if (i !== tokens3.length)
130888
+ gap(`GAQL clause ${tokens3.slice(i).join(" ")}`);
130642
130889
  const joins = { customer: [], customer_client: [], campaign_budget: ["customer"], campaign: ["customer", "campaign_budget", "metrics", "segments"], ad_group: ["customer", "campaign", "campaign_budget"], ad_group_ad: ["customer", "ad_group", "campaign", "campaign_budget"], ad_group_criterion: ["customer", "ad_group", "campaign", "campaign_budget"] };
130643
130890
  for (const f of [...select3, ...where2.map((p2) => p2.field), ...order4.map((o) => o.field)]) {
130644
130891
  const [prefix2, ...path6] = f.split(".");
@@ -131546,9 +131793,9 @@ function authenticate4(c, write4) {
131546
131793
  if (write4 && principal.readOnly) throw new AdsError2(403, "This credential cannot modify the account", "permission_denied");
131547
131794
  return { account: account8, seed: seed40, readOnly: principal.readOnly };
131548
131795
  }
131549
- function consumeQuota(ctx, access7, route11) {
131550
- const bucket2 = Math.floor(ctx.clock.elapsedMs() / 6e4), limits = access7.seed.limits;
131551
- const scopes3 = [{ name: access7.account.id, limit: limits.perAccountPerMinute }, { name: `${access7.account.id}:${route11}`, limit: limits.perEndpointPerMinute }];
131796
+ function consumeQuota(ctx, access8, route11) {
131797
+ const bucket2 = Math.floor(ctx.clock.elapsedMs() / 6e4), limits = access8.seed.limits;
131798
+ const scopes3 = [{ name: access8.account.id, limit: limits.perAccountPerMinute }, { name: `${access8.account.id}:${route11}`, limit: limits.perEndpointPerMinute }];
131552
131799
  for (const scope3 of scopes3) {
131553
131800
  const row = ctx.store.db.prepare("SELECT bucket,count FROM chatgpt_ads_quota WHERE scope=?").get(scope3.name);
131554
131801
  if (row?.bucket === bucket2 && row.count >= scope3.limit) throw new AdsError2(429, "Advertiser API request rate exceeded", "rate_limit_exceeded");
@@ -131568,10 +131815,10 @@ function handle2(route11) {
131568
131815
  }
131569
131816
  return withMutation(c.env.ctx, () => {
131570
131817
  try {
131571
- const access7 = authenticate4(c, route11.write ?? route11.method === "POST");
131572
- consumeQuota(c.env.ctx, access7, `${route11.method} ${route11.path}`);
131818
+ const access8 = authenticate4(c, route11.write ?? route11.method === "POST");
131819
+ consumeQuota(c.env.ctx, access8, `${route11.method} ${route11.path}`);
131573
131820
  if (parseError) throw parseError;
131574
- return withRead(c.env.ctx, () => new Response(JSON.stringify(route11.run(c, body6, access7)), { headers: { "content-type": "application/json; charset=utf-8" } }));
131821
+ return withRead(c.env.ctx, () => new Response(JSON.stringify(route11.run(c, body6, access8)), { headers: { "content-type": "application/json; charset=utf-8" } }));
131575
131822
  } catch (error64) {
131576
131823
  if (!(error64 instanceof AdsError2)) throw error64;
131577
131824
  return new Response(JSON.stringify({ error: { message: error64.message, type: error64.status === 401 ? "authentication_error" : error64.status === 429 ? "rate_limit_error" : "invalid_request_error", code: error64.code, param: error64.param } }), { status: error64.status, headers: { "content-type": "application/json; charset=utf-8", ...error64.status === 501 ? { [GAP_HEADER]: "1" } : {} } });
@@ -131579,8 +131826,8 @@ function handle2(route11) {
131579
131826
  });
131580
131827
  };
131581
131828
  }
131582
- function find(access7, kind, id12) {
131583
- const row = access7.seed[kind].find((item2) => item2.id === id12 && item2.accountId === access7.account.id);
131829
+ function find(access8, kind, id12) {
131830
+ const row = access8.seed[kind].find((item2) => item2.id === id12 && item2.accountId === access8.account.id);
131584
131831
  if (!row) throw new AdsError2(404, "Resource not found", "resource_not_found");
131585
131832
  return row;
131586
131833
  }
@@ -131605,15 +131852,15 @@ function canonical3(value5) {
131605
131852
  if (value5 && typeof value5 === "object") return `{${Object.entries(value5).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical3(v)}`).join(",")}}`;
131606
131853
  return JSON.stringify(value5);
131607
131854
  }
131608
- function idempotency(c, access7, kind, body6) {
131855
+ function idempotency(c, access8, kind, body6) {
131609
131856
  const key3 = c.req.header("idempotency-key");
131610
131857
  if (key3 === void 0) return { existing: void 0, remember: (_id) => {
131611
131858
  } };
131612
131859
  if (key3.length > 255 || !key3.trim()) invalid8("Idempotency-Key requires 1\u2013255 characters and non-whitespace");
131613
131860
  const fingerprint = createHash13("sha256").update(canonical3(body6)).digest("hex");
131614
- const prior = c.env.ctx.store.db.prepare("SELECT fingerprint,resource_id FROM chatgpt_ads_idempotency WHERE account_id=? AND kind=? AND key=?").get(access7.account.id, kind, key3);
131861
+ const prior = c.env.ctx.store.db.prepare("SELECT fingerprint,resource_id FROM chatgpt_ads_idempotency WHERE account_id=? AND kind=? AND key=?").get(access8.account.id, kind, key3);
131615
131862
  if (prior && prior.fingerprint !== fingerprint) throw new AdsError2(409, "Idempotency-Key was used with different input", "idempotency_conflict");
131616
- return { existing: prior ? find(access7, kind, prior.resource_id) : void 0, remember: (id12) => c.env.ctx.store.db.prepare("INSERT INTO chatgpt_ads_idempotency VALUES (?,?,?,?,?)").run(access7.account.id, kind, key3, fingerprint, id12) };
131863
+ return { existing: prior ? find(access8, kind, prior.resource_id) : void 0, remember: (id12) => c.env.ctx.store.db.prepare("INSERT INTO chatgpt_ads_idempotency VALUES (?,?,?,?,?)").run(access8.account.id, kind, key3, fingerprint, id12) };
131617
131864
  }
131618
131865
 
131619
131866
  // packages/server/src/twins/chatgpt-ads/routes.ts
@@ -131629,40 +131876,40 @@ function targeting2(value5, previous) {
131629
131876
  const parsed3 = parse5(ChatGPTAdsTargetingSchema, body6);
131630
131877
  return { ...parsed3, ...!Object.hasOwn(body6, "platforms") && previous?.platforms !== void 0 ? { platforms: previous.platforms } : {} };
131631
131878
  }
131632
- function bidding(value5, campaign2, access7) {
131879
+ function bidding(value5, campaign2, access8) {
131633
131880
  const body6 = object6(value5, "bidding_config");
131634
131881
  keys(body6, ["billing_event_type", "strategy", "max_bid_micros"], "bidding_config");
131635
131882
  if (body6.strategy === "maximize_conversions") unsupported5("conversion bidding");
131636
131883
  const bid = parse5(ChatGPTAdsBiddingSchema, body6), billing = campaign2.bidding_type === "clicks" ? "click" : "impression";
131637
131884
  if (bid.billing_event_type !== billing) invalid8("Bidding must match the campaign billing event", "bidding_config");
131638
- if (billing === "impression" && !access7.account.impressionBiddingEnabled) throw new AdsError2(403, "Account is not eligible for impression bidding", "permission_denied");
131885
+ if (billing === "impression" && !access8.account.impressionBiddingEnabled) throw new AdsError2(403, "Account is not eligible for impression bidding", "permission_denied");
131639
131886
  const strategy = bid.strategy ?? (bid.max_bid_micros !== void 0 ? "fixed_bid" : "maximize_clicks");
131640
131887
  if (strategy === "fixed_bid" && bid.max_bid_micros === void 0) invalid8("Fixed bid requires max_bid_micros");
131641
131888
  if (strategy === "maximize_clicks" && (billing !== "click" || bid.max_bid_micros !== void 0)) invalid8("Maximize clicks requires click billing and no fixed bid");
131642
131889
  return { ...bid, strategy };
131643
131890
  }
131644
- function creative(value5, access7, creating) {
131891
+ function creative(value5, access8, creating) {
131645
131892
  const body6 = object6(value5, "creative");
131646
131893
  keys(body6, ["type", "title", "body", "target_url", "file_id", "price"], "creative");
131647
131894
  if (body6.type !== void 0 && body6.type !== "chat_card") unsupported5(`creative type ${String(body6.type)}`);
131648
131895
  const parsed3 = parse5(ChatGPTAdsCreativeSchema, body6);
131649
131896
  if (creating && parsed3.title.length < 3) invalid8("New creative title must have at least 3 characters", "creative.title");
131650
- const file3 = access7.seed.files.find((f) => f.id === parsed3.file_id && f.accountId === access7.account.id);
131897
+ const file3 = access8.seed.files.find((f) => f.id === parsed3.file_id && f.accountId === access8.account.id);
131651
131898
  if (!file3) invalid8("Creative file is not available to this account", "creative.file_id");
131652
131899
  if (file3.width < 640 || file3.height < 640) invalid8("Creative image must be at least 640 by 640", "creative.file_id");
131653
131900
  return parsed3;
131654
131901
  }
131655
- function parent(access7, kind, value5) {
131902
+ function parent(access8, kind, value5) {
131656
131903
  if (kind === "campaigns") return void 0;
131657
- const row = find(access7, kind === "adGroups" ? "campaigns" : "adGroups", text15(value5[kind === "adGroups" ? "campaign_id" : "ad_group_id"], "parent id", 200));
131904
+ const row = find(access8, kind === "adGroups" ? "campaigns" : "adGroups", text15(value5[kind === "adGroups" ? "campaign_id" : "ad_group_id"], "parent id", 200));
131658
131905
  if (row.status === "archived") invalid8("Cannot create a child of an archived resource");
131659
- if (kind === "ads" && find(access7, "campaigns", row.campaign_id).status === "archived") invalid8("Cannot create an ad in an archived campaign");
131906
+ if (kind === "ads" && find(access8, "campaigns", row.campaign_id).status === "archived") invalid8("Cannot create an ad in an archived campaign");
131660
131907
  return row;
131661
131908
  }
131662
131909
  function validateSeed(seed40) {
131663
131910
  return parse5(ChatGPTAdsSeedSchema, seed40);
131664
131911
  }
131665
- function mutate2(c, access7, kind, input2, existing2) {
131912
+ function mutate2(c, access8, kind, input2, existing2) {
131666
131913
  const body6 = object6(input2), creating = !existing2;
131667
131914
  keys(body6, creating ? createFields[kind] : updateFields[kind], kind);
131668
131915
  if (creating && !["active", "paused"].includes(body6.status)) invalid8("Create status must be active or paused", "status");
@@ -131672,29 +131919,29 @@ function mutate2(c, access7, kind, input2, existing2) {
131672
131919
  if (!creating && Object.keys(body6).length === 0) invalid8("Update must specify a field");
131673
131920
  if (existing2?.status === "archived") invalid8("Archived resources cannot be changed");
131674
131921
  if (kind === "campaigns" && body6.bidding_type !== void 0 && !["impressions", "clicks"].includes(body6.bidding_type)) unsupported5("conversion campaign bidding");
131675
- const ancestor = creating ? parent(access7, kind, body6) : void 0;
131922
+ const ancestor = creating ? parent(access8, kind, body6) : void 0;
131676
131923
  const timestamp3 = now(c.env.ctx), prefix2 = collections2.find((x) => x.kind === kind).prefix;
131677
131924
  let provisional = `${prefix2}_validation`;
131678
- while (access7.seed[kind].some((x) => x.id === provisional)) provisional += "x";
131679
- let candidate = creating ? { id: provisional, accountId: access7.account.id, created_at: timestamp3, updated_at: timestamp3, ...body6 } : { ...existing2, ...body6, updated_at: timestamp3 };
131925
+ while (access8.seed[kind].some((x) => x.id === provisional)) provisional += "x";
131926
+ let candidate = creating ? { id: provisional, accountId: access8.account.id, created_at: timestamp3, updated_at: timestamp3, ...body6 } : { ...existing2, ...body6, updated_at: timestamp3 };
131680
131927
  if (kind === "campaigns") {
131681
131928
  if (creating && body6.bidding_type === void 0) candidate.bidding_type = "impressions";
131682
131929
  if (Object.hasOwn(body6, "targeting")) candidate.targeting = targeting2(body6.targeting, existing2?.targeting);
131683
131930
  if (body6.budget !== void 0) keys(object6(body6.budget, "budget"), ["daily_spend_limit_micros", "lifetime_spend_limit_micros"], "budget");
131684
131931
  if (candidate.end_time !== void 0 && candidate.end_time !== null && Number(candidate.end_time) <= Number(candidate.start_time ?? timestamp3)) invalid8("end_time must follow start_time");
131685
131932
  } else if (kind === "adGroups") {
131686
- if (body6.bidding_config !== void 0) candidate.bidding_config = bidding(body6.bidding_config, ancestor ?? find(access7, "campaigns", existing2.campaign_id), access7);
131933
+ if (body6.bidding_config !== void 0) candidate.bidding_config = bidding(body6.bidding_config, ancestor ?? find(access8, "campaigns", existing2.campaign_id), access8);
131687
131934
  } else {
131688
- if (body6.creative !== void 0) candidate.creative = creative(body6.creative, access7, creating);
131935
+ if (body6.creative !== void 0) candidate.creative = creative(body6.creative, access8, creating);
131689
131936
  if (creating || body6.creative !== void 0) {
131690
- const policy = access7.account.newAdReview;
131937
+ const policy = access8.account.newAdReview;
131691
131938
  candidate = { ...candidate, review: { status: "in_review" }, reviewAfterMs: c.env.ctx.clock.elapsedMs() + policy.delayMs, reviewOutcome: policy.outcome, reviewReason: policy.reason };
131692
131939
  }
131693
131940
  }
131694
- const rows33 = [...access7.seed[kind]];
131941
+ const rows33 = [...access8.seed[kind]];
131695
131942
  if (creating) rows33.push(candidate);
131696
131943
  else rows33[rows33.findIndex((x) => x.id === existing2.id)] = candidate;
131697
- const seed40 = validateSeed({ ...access7.seed, [kind]: rows33 });
131944
+ const seed40 = validateSeed({ ...access8.seed, [kind]: rows33 });
131698
131945
  const result = seed40[kind].find((x) => x.id === candidate.id);
131699
131946
  if (creating) {
131700
131947
  let id12;
@@ -131706,7 +131953,7 @@ function mutate2(c, access7, kind, input2, existing2) {
131706
131953
  save3(c.env.ctx, seed40);
131707
131954
  return { seed: seed40, item: result };
131708
131955
  }
131709
- function list6(c, access7, kind) {
131956
+ function list6(c, access8, kind) {
131710
131957
  const parentKey = kind === "adGroups" ? "campaign_id" : kind === "ads" ? "ad_group_id" : void 0;
131711
131958
  const query11 = params3(c, ["include", "name", "limit", "after", "before", "order", ...parentKey ? [parentKey] : []], ["include"]), issues = includes2(query11);
131712
131959
  if (query11.order !== void 0 && !["asc", "desc"].includes(query11.order)) invalid8("order must be asc or desc");
@@ -131714,42 +131961,42 @@ function list6(c, access7, kind) {
131714
131961
  const name5 = text15(query11.name, "name");
131715
131962
  if (name5.length < 3 || !name5.trim()) invalid8("name must have at least three characters");
131716
131963
  }
131717
- if (parentKey && query11[parentKey] !== void 0) find(access7, kind === "adGroups" ? "campaigns" : "adGroups", text15(query11[parentKey], parentKey, 200));
131718
- const rows33 = access7.seed[kind].filter((row) => row.accountId === access7.account.id && (query11.name === void 0 || row.name === query11.name) && (!parentKey || query11[parentKey] === void 0 || row[parentKey] === query11[parentKey]));
131964
+ if (parentKey && query11[parentKey] !== void 0) find(access8, kind === "adGroups" ? "campaigns" : "adGroups", text15(query11[parentKey], parentKey, 200));
131965
+ const rows33 = access8.seed[kind].filter((row) => row.accountId === access8.account.id && (query11.name === void 0 || row.name === query11.name) && (!parentKey || query11[parentKey] === void 0 || row[parentKey] === query11[parentKey]));
131719
131966
  rows33.sort((a, b) => (a.created_at - b.created_at || a.id.localeCompare(b.id)) * (query11.order === "asc" ? 1 : -1));
131720
131967
  const page15 = pagination(rows33, query11);
131721
- return { ...page15, data: page15.data.map((row) => project5(c.env.ctx, access7.seed, kind, row, issues)) };
131968
+ return { ...page15, data: page15.data.map((row) => project5(c.env.ctx, access8.seed, kind, row, issues)) };
131722
131969
  }
131723
- var catalogRoutes = [{ method: "GET", path: "/v1/ad_account", notes: "Account-scoped identity and seeded account/brand/integrity review.", run: (c, _body, access7) => {
131970
+ var catalogRoutes = [{ method: "GET", path: "/v1/ad_account", notes: "Account-scoped identity and seeded account/brand/integrity review.", run: (c, _body, access8) => {
131724
131971
  params3(c, []);
131725
- return accountView(access7.account);
131972
+ return accountView(access8.account);
131726
131973
  } }];
131727
131974
  for (const { kind, path: path6 } of collections2) {
131728
131975
  catalogRoutes.push(
131729
- { method: "GET", path: `/v1/${path6}`, notes: "Account/parent-scoped list, exact local name filter, native forward/backward ID cursors and optional serving issues.", run: (c, _b, access7) => list6(c, access7, kind) },
131730
- { method: "POST", path: `/v1/${path6}`, body: true, notes: "Native bounded create with account/parent/file eligibility and deterministic idempotency. Creative review is seeded local policy.", run: (c, body6, access7) => {
131976
+ { method: "GET", path: `/v1/${path6}`, notes: "Account/parent-scoped list, exact local name filter, native forward/backward ID cursors and optional serving issues.", run: (c, _b, access8) => list6(c, access8, kind) },
131977
+ { method: "POST", path: `/v1/${path6}`, body: true, notes: "Native bounded create with account/parent/file eligibility and deterministic idempotency. Creative review is seeded local policy.", run: (c, body6, access8) => {
131731
131978
  params3(c, []);
131732
- const retry = idempotency(c, access7, kind, body6);
131733
- if (retry.existing) return project5(c.env.ctx, access7.seed, kind, retry.existing);
131734
- const result = mutate2(c, access7, kind, body6);
131979
+ const retry = idempotency(c, access8, kind, body6);
131980
+ if (retry.existing) return project5(c.env.ctx, access8.seed, kind, retry.existing);
131981
+ const result = mutate2(c, access8, kind, body6);
131735
131982
  retry.remember(result.item.id);
131736
131983
  return project5(c.env.ctx, result.seed, kind, result.item);
131737
131984
  } },
131738
- { method: "GET", path: `/v1/${path6}/:id`, notes: "Account-scoped object read with optional serving issues; no hidden parent IDs added to native response.", run: (c, _body, access7) => {
131985
+ { method: "GET", path: `/v1/${path6}/:id`, notes: "Account-scoped object read with optional serving issues; no hidden parent IDs added to native response.", run: (c, _body, access8) => {
131739
131986
  const query11 = params3(c, ["include"], ["include"]);
131740
- return project5(c.env.ctx, access7.seed, kind, find(access7, kind, c.req.param("id")), includes2(query11));
131987
+ return project5(c.env.ctx, access8.seed, kind, find(access8, kind, c.req.param("id")), includes2(query11));
131741
131988
  } },
131742
- { method: "POST", path: `/v1/${path6}/:id`, body: true, notes: "Bounded native update; budgets replace, omitted targeting platforms persist, archived objects cannot change.", run: (c, body6, access7) => {
131989
+ { method: "POST", path: `/v1/${path6}/:id`, body: true, notes: "Bounded native update; budgets replace, omitted targeting platforms persist, archived objects cannot change.", run: (c, body6, access8) => {
131743
131990
  params3(c, []);
131744
- const result = mutate2(c, access7, kind, body6, find(access7, kind, c.req.param("id")));
131991
+ const result = mutate2(c, access8, kind, body6, find(access8, kind, c.req.param("id")));
131745
131992
  return project5(c.env.ctx, result.seed, kind, result.item);
131746
131993
  } }
131747
131994
  );
131748
- for (const [action, status5] of [["activate", "active"], ["pause", "paused"], ["archive", "archived"]]) catalogRoutes.push({ method: "POST", path: `/v1/${path6}/:id/${action}`, notes: "Native local status action, preserving child statuses; archive is irreversible.", run: (c, _body, access7) => {
131995
+ for (const [action, status5] of [["activate", "active"], ["pause", "paused"], ["archive", "archived"]]) catalogRoutes.push({ method: "POST", path: `/v1/${path6}/:id/${action}`, notes: "Native local status action, preserving child statuses; archive is irreversible.", run: (c, _body, access8) => {
131749
131996
  params3(c, []);
131750
- const existing2 = find(access7, kind, c.req.param("id"));
131751
- if (existing2.status === status5) return project5(c.env.ctx, access7.seed, kind, existing2);
131752
- const result = mutate2(c, access7, kind, { status: status5 }, existing2);
131997
+ const existing2 = find(access8, kind, c.req.param("id"));
131998
+ if (existing2.status === status5) return project5(c.env.ctx, access8.seed, kind, existing2);
131999
+ const result = mutate2(c, access8, kind, { status: status5 }, existing2);
131753
132000
  return project5(c.env.ctx, result.seed, kind, result.item);
131754
132001
  } });
131755
132002
  }
@@ -131775,7 +132022,7 @@ function bound(value5, field4) {
131775
132022
  if (typeof value5 !== "number" || !Number.isSafeInteger(value5)) invalid8(`Invalid ${field4}`);
131776
132023
  return value5;
131777
132024
  }
131778
- function report(c, access7, scope3) {
132025
+ function report(c, access8, scope3) {
131779
132026
  const query11 = params3(c, ["time_granularity", "aggregation_level", "limit", "after", "before", "time_ranges", "fields", "filters", "sort"], ["time_ranges", "fields", "filters", "sort"]);
131780
132027
  const granularity = query11.time_granularity ?? "daily";
131781
132028
  if (!["none", "daily"].includes(granularity)) unsupported5(`insights time_granularity ${String(granularity)}`);
@@ -131783,8 +132030,8 @@ function report(c, access7, scope3) {
131783
132030
  if (!levels.includes(requested2)) invalid8("Invalid aggregation_level");
131784
132031
  const level3 = requested2;
131785
132032
  if (levels.indexOf(level3) < levels.indexOf(scope3)) invalid8("Aggregation must be at or below the endpoint scope");
131786
- const scopeId = scope3 === "ad_account" ? access7.account.id : c.req.param("id");
131787
- if (scope3 !== "ad_account") find(access7, scope3 === "campaign" ? "campaigns" : scope3 === "ad_group" ? "adGroups" : "ads", scopeId);
132033
+ const scopeId = scope3 === "ad_account" ? access8.account.id : c.req.param("id");
132034
+ if (scope3 !== "ad_account") find(access8, scope3 === "campaign" ? "campaigns" : scope3 === "ad_group" ? "adGroups" : "ads", scopeId);
131788
132035
  const at3 = now(c.env.ctx), earliest = at3 - 5 * 366 * 86400, ranges2 = array2(query11.time_ranges);
131789
132036
  if (ranges2.length > 1) invalid8("Exactly one time range is supported");
131790
132037
  let start = Math.ceil(earliest / 3600) * 3600, end = Math.floor(at3 / 3600) * 3600;
@@ -131833,16 +132080,16 @@ function report(c, access7, scope3) {
131833
132080
  if (!["asc", "desc"].includes(s.direction)) invalid8("Sort direction must be asc or desc");
131834
132081
  return { key: key3, direction: s.direction };
131835
132082
  });
131836
- const ads = new Map(access7.seed.ads.filter((x) => x.accountId === access7.account.id).map((x) => [x.id, x])), groups = new Map(access7.seed.adGroups.map((x) => [x.id, x])), campaigns = new Map(access7.seed.campaigns.map((x) => [x.id, x]));
132083
+ const ads = new Map(access8.seed.ads.filter((x) => x.accountId === access8.account.id).map((x) => [x.id, x])), groups = new Map(access8.seed.adGroups.map((x) => [x.id, x])), campaigns = new Map(access8.seed.campaigns.map((x) => [x.id, x]));
131837
132084
  const totals2 = /* @__PURE__ */ new Map();
131838
- for (const observation of access7.seed.insights) {
132085
+ for (const observation of access8.seed.insights) {
131839
132086
  if (observation.availableAfterMs > c.env.ctx.clock.elapsedMs() || observation.start_time < start || observation.end_time > end || observation.end_time > at3) continue;
131840
132087
  const ad = ads.get(observation.adId);
131841
132088
  if (!ad) continue;
131842
132089
  const group5 = groups.get(ad.ad_group_id), campaign2 = campaigns.get(group5.campaign_id);
131843
- const entities = { ad_account: access7.account, campaign: campaign2, ad_group: group5, ad };
132090
+ const entities = { ad_account: access8.account, campaign: campaign2, ad_group: group5, ad };
131844
132091
  if (entities[scope3].id !== scopeId) continue;
131845
- const bucket2 = granularity === "daily" ? dayBounds(observation.start_time, access7.account.timezone) : void 0;
132092
+ const bucket2 = granularity === "daily" ? dayBounds(observation.start_time, access8.account.timezone) : void 0;
131846
132093
  const from = bucket2 ? Math.max(start, bucket2.start) : start, to = bucket2 ? Math.min(end, bucket2.end) : end;
131847
132094
  const id12 = `start=${from}:end=${to}:entity_id=${entities[level3].id}`;
131848
132095
  let total = totals2.get(id12);
@@ -131876,7 +132123,7 @@ function report(c, access7, scope3) {
131876
132123
  return a.start_time - b.start_time || a.id.localeCompare(b.id);
131877
132124
  });
131878
132125
  const page15 = pagination(rows33, query11, 20, 2e3);
131879
- return { ...page15, timezone: access7.account.timezone, count: page15.data.length, data: page15.data.map(({ id: id12, start_time, end_time, values: values2 }) => {
132126
+ return { ...page15, timezone: access8.account.timezone, count: page15.data.length, data: page15.data.map(({ id: id12, start_time, end_time, values: values2 }) => {
131880
132127
  const row = { id: id12, start_time, end_time };
131881
132128
  for (const name5 of fields11) {
131882
132129
  const [entity, key3] = name5.split("."), wire2 = name5 === "metadata.readable_time" ? "readable_time" : metrics.includes(key3) ? key3 : `${entity}_${key3}`;
@@ -131885,7 +132132,7 @@ function report(c, access7, scope3) {
131885
132132
  return row;
131886
132133
  }) };
131887
132134
  }
131888
- var insightsRoutes = levels.map((scope3) => ({ method: "GET", path: scope3 === "ad_account" ? "/v1/ad_account/insights" : `/v1/${scope3 === "campaign" ? "campaigns" : scope3 === "ad_group" ? "ad_groups" : "ads"}/:id/insights`, notes: "Seeded historical hourly delivery, none/daily account-timezone grouping, native field/filter/sort/cursor subset. No live auction, attribution or cross-level repeated metrics.", run: (c, _body, access7) => report(c, access7, scope3) }));
132135
+ var insightsRoutes = levels.map((scope3) => ({ method: "GET", path: scope3 === "ad_account" ? "/v1/ad_account/insights" : `/v1/${scope3 === "campaign" ? "campaigns" : scope3 === "ad_group" ? "ad_groups" : "ads"}/:id/insights`, notes: "Seeded historical hourly delivery, none/daily account-timezone grouping, native field/filter/sort/cursor subset. No live auction, attribution or cross-level repeated metrics.", run: (c, _body, access8) => report(c, access8, scope3) }));
131889
132136
 
131890
132137
  // packages/server/src/twins/chatgpt-ads/index.ts
131891
132138
  var chatGPTAdsRoutes = [...catalogRoutes, ...insightsRoutes];
@@ -135299,8 +135546,8 @@ function visible2(ctx, type, record23) {
135299
135546
  return true;
135300
135547
  }
135301
135548
  function permission5(ctx, write4 = false) {
135302
- const access7 = config4(ctx).access;
135303
- if (!access7.read || write4 && !access7.write) throw new SalesforceError(403, "INSUFFICIENT_ACCESS_OR_READONLY", "The session does not have permission for this operation.");
135549
+ const access8 = config4(ctx).access;
135550
+ if (!access8.read || write4 && !access8.write) throw new SalesforceError(403, "INSUFFICIENT_ACCESS_OR_READONLY", "The session does not have permission for this operation.");
135304
135551
  }
135305
135552
  function getRecord2(ctx, type, id12) {
135306
135553
  permission5(ctx);
@@ -135389,34 +135636,34 @@ function deleteRecord(ctx, type, id12) {
135389
135636
  history2(ctx, type, id12, "delete", prior, null);
135390
135637
  }
135391
135638
  function dumpState9(ctx) {
135392
- const { org: org5, access: access7 } = config4(ctx);
135393
- return { org: org5, access: access7, ...Object.fromEntries(salesforceObjectNames.map((type) => [salesforceCollections[type], rows29(ctx, type)])), history: ctx.store.db.prepare("SELECT * FROM salesforce_history ORDER BY ordinal").all().map((row) => ({ ordinal: row.ordinal, object: row.type, id: row.id, operation: row.operation, at: row.at, before: row.before_json ? JSON.parse(row.before_json) : null, after: row.after_json ? JSON.parse(row.after_json) : null })) };
135639
+ const { org: org5, access: access8 } = config4(ctx);
135640
+ return { org: org5, access: access8, ...Object.fromEntries(salesforceObjectNames.map((type) => [salesforceCollections[type], rows29(ctx, type)])), history: ctx.store.db.prepare("SELECT * FROM salesforce_history ORDER BY ordinal").all().map((row) => ({ ordinal: row.ordinal, object: row.type, id: row.id, operation: row.operation, at: row.at, before: row.before_json ? JSON.parse(row.before_json) : null, after: row.after_json ? JSON.parse(row.after_json) : null })) };
135394
135641
  }
135395
135642
 
135396
135643
  // packages/server/src/twins/salesforce/query.ts
135397
135644
  function tokenize3(q) {
135398
135645
  if (!q || q.length > 2e4) throw new SalesforceError(400, "MALFORMED_QUERY", "Query must contain 1\u201320,000 characters.");
135399
135646
  const pattern = /\s*(?:('(?:\\.|[^'\\])*')|(\d{4}-\d{2}-\d{2}(?![T\d-]))|([A-Za-z_][A-Za-z0-9_]*)|(-?\d+(?:\.\d+)?)|(>=|<=|!=|=|>|<)|([(),]))/gy;
135400
- const tokens2 = [];
135647
+ const tokens3 = [];
135401
135648
  let position = 0;
135402
135649
  while (position < q.trimEnd().length) {
135403
135650
  pattern.lastIndex = position;
135404
135651
  const match2 = pattern.exec(q);
135405
135652
  if (!match2) unsupported8("SOQL expression outside the documented subset", "MALFORMED_QUERY");
135406
135653
  const raw3 = match2[1] ?? match2[2] ?? match2[3] ?? match2[4] ?? match2[5] ?? match2[6];
135407
- tokens2.push(match2[1] ? { raw: raw3, value: raw3.slice(1, -1).replace(/\\(['\\])/g, "$1"), literal: true } : match2[2] ? { raw: raw3, value: raw3, literal: true } : match2[4] ? { raw: raw3, value: Number(raw3), literal: true } : { raw: raw3 });
135654
+ tokens3.push(match2[1] ? { raw: raw3, value: raw3.slice(1, -1).replace(/\\(['\\])/g, "$1"), literal: true } : match2[2] ? { raw: raw3, value: raw3, literal: true } : match2[4] ? { raw: raw3, value: Number(raw3), literal: true } : { raw: raw3 });
135408
135655
  position = pattern.lastIndex;
135409
- if (tokens2.length > 500) unsupported8("SOQL expression exceeds the 500-token subset", "MALFORMED_QUERY");
135656
+ if (tokens3.length > 500) unsupported8("SOQL expression exceeds the 500-token subset", "MALFORMED_QUERY");
135410
135657
  }
135411
- return tokens2;
135658
+ return tokens3;
135412
135659
  }
135413
135660
  function executeQuery(ctx, q) {
135414
135661
  permission5(ctx);
135415
- const tokens2 = tokenize3(q);
135662
+ const tokens3 = tokenize3(q);
135416
135663
  let at3 = 0;
135417
- const peek = (word) => tokens2[at3]?.raw.toUpperCase() === word;
135664
+ const peek = (word) => tokens3[at3]?.raw.toUpperCase() === word;
135418
135665
  const take2 = () => {
135419
- const token2 = tokens2[at3++];
135666
+ const token2 = tokens3[at3++];
135420
135667
  if (!token2) throw new SalesforceError(400, "MALFORMED_QUERY", "Incomplete query.");
135421
135668
  return token2;
135422
135669
  };
@@ -135507,7 +135754,7 @@ function executeQuery(ctx, q) {
135507
135754
  at3++;
135508
135755
  offset16 = integer13(2e3);
135509
135756
  }
135510
- if (at3 !== tokens2.length) unsupported8(`SOQL ${tokens2[at3].raw}; relationships, aggregation, OR and additional clauses are outside this subset`, "MALFORMED_QUERY");
135757
+ if (at3 !== tokens3.length) unsupported8(`SOQL ${tokens3[at3].raw}; relationships, aggregation, OR and additional clauses are outside this subset`, "MALFORMED_QUERY");
135511
135758
  let result = rows29(ctx, type).filter((record23) => visible2(ctx, type, record23)).map((record23) => project6(type, record23)).filter((record23) => predicates.every((test3) => test3(record23)));
135512
135759
  if (order4) result.sort((a, b) => {
135513
135760
  const left = a[order4] ?? null, right = b[order4] ?? null;
@@ -137301,7 +137548,7 @@ init_src();
137301
137548
 
137302
137549
  // packages/server/src/twins/google-drive/query.ts
137303
137550
  function tokenize4(source) {
137304
- const tokens2 = [];
137551
+ const tokens3 = [];
137305
137552
  let at3 = 0;
137306
137553
  while (at3 < source.length) {
137307
137554
  const char = source[at3];
@@ -137310,7 +137557,7 @@ function tokenize4(source) {
137310
137557
  continue;
137311
137558
  }
137312
137559
  if (char === "(" || char === ")") {
137313
- tokens2.push({ kind: "paren", value: char });
137560
+ tokens3.push({ kind: "paren", value: char });
137314
137561
  at3++;
137315
137562
  continue;
137316
137563
  }
@@ -137333,25 +137580,25 @@ function tokenize4(source) {
137333
137580
  value5 += next2;
137334
137581
  at3++;
137335
137582
  }
137336
- tokens2.push({ kind: "string", value: value5 });
137583
+ tokens3.push({ kind: "string", value: value5 });
137337
137584
  continue;
137338
137585
  }
137339
137586
  const op = /^(?:!=|<=|>=|=|<|>)/.exec(source.slice(at3));
137340
137587
  if (op) {
137341
- tokens2.push({ kind: "op", value: op[0] });
137588
+ tokens3.push({ kind: "op", value: op[0] });
137342
137589
  at3 += op[0].length;
137343
137590
  continue;
137344
137591
  }
137345
137592
  const word = /^[A-Za-z_][A-Za-z0-9_.]*/.exec(source.slice(at3));
137346
137593
  if (word) {
137347
- tokens2.push({ kind: "word", value: word[0] });
137594
+ tokens3.push({ kind: "word", value: word[0] });
137348
137595
  at3 += word[0].length;
137349
137596
  continue;
137350
137597
  }
137351
137598
  if (char === "{" || char === "}") unsupported11("properties and appProperties search with has");
137352
137599
  throw invalid12("q");
137353
137600
  }
137354
- return tokens2;
137601
+ return tokens3;
137355
137602
  }
137356
137603
  function namePrefix(name5, value5) {
137357
137604
  if (!value5) return true;
@@ -137393,12 +137640,12 @@ function compare3(left, op, right) {
137393
137640
  }
137394
137641
  }
137395
137642
  function parseQuery(source, aliases) {
137396
- const tokens2 = tokenize4(source);
137643
+ const tokens3 = tokenize4(source);
137397
137644
  let at3 = 0;
137398
- const peek = () => tokens2[at3];
137645
+ const peek = () => tokens3[at3];
137399
137646
  const isWord = (token2, value5) => token2?.kind === "word" && token2.value.toLowerCase() === value5;
137400
137647
  const expect = () => {
137401
- const token2 = tokens2[at3++];
137648
+ const token2 = tokens3[at3++];
137402
137649
  if (!token2) throw invalid12("q");
137403
137650
  return token2;
137404
137651
  };
@@ -137535,9 +137782,9 @@ function parseQuery(source, aliases) {
137535
137782
  throw invalid12("q");
137536
137783
  }
137537
137784
  };
137538
- if (!tokens2.length) return () => true;
137785
+ if (!tokens3.length) return () => true;
137539
137786
  const predicate = or();
137540
- if (at3 !== tokens2.length) throw invalid12("q");
137787
+ if (at3 !== tokens3.length) throw invalid12("q");
137541
137788
  return predicate;
137542
137789
  }
137543
137790
 
@@ -137640,8 +137887,8 @@ function visibleParents(ctx, caller2, file3) {
137640
137887
  const parent2 = getFile(ctx, file3.parent);
137641
137888
  return parent2 && accessTo(ctx, caller2, parent2).role !== null ? [parent2.id] : [];
137642
137889
  }
137643
- function fileResource(ctx, caller2, file3, access7 = accessTo(ctx, caller2, file3)) {
137644
- const role3 = access7.role ?? "reader", editor = isEditorFile(file3), folder = isFolder(file3), binary = !editor && !folder;
137890
+ function fileResource(ctx, caller2, file3, access8 = accessTo(ctx, caller2, file3)) {
137891
+ const role3 = access8.role ?? "reader", editor = isEditorFile(file3), folder = isFolder(file3), binary = !editor && !folder;
137645
137892
  const trash2 = trashedBy(ctx, file3), granted = effectivePermissions(ctx, file3), caps = capabilities(file3, role3);
137646
137893
  const properties2 = JSON.parse(file3.properties), appProperties = JSON.parse(file3.app_properties);
137647
137894
  const extension2 = binary && /\.([A-Za-z0-9]+)$/.exec(file3.original_filename ?? file3.name)?.[1];
@@ -137673,7 +137920,7 @@ function fileResource(ctx, caller2, file3, access7 = accessTo(ctx, caller2, file
137673
137920
  modifiedTime: iso(file3.modified_ms),
137674
137921
  ...file3.modified_by === caller2.email && { modifiedByMeTime: iso(file3.modified_ms) },
137675
137922
  modifiedByMe: file3.modified_by === caller2.email,
137676
- ...access7.direct && file3.owner !== caller2.email && { sharedWithMeTime: iso(access7.direct.created_ms), sharingUser: userResource(ctx, caller2, file3.owner) },
137923
+ ...access8.direct && file3.owner !== caller2.email && { sharedWithMeTime: iso(access8.direct.created_ms), sharingUser: userResource(ctx, caller2, file3.owner) },
137677
137924
  owners: [userResource(ctx, caller2, file3.owner)],
137678
137925
  lastModifyingUser: userResource(ctx, caller2, file3.modified_by),
137679
137926
  shared: granted.length > 1,
@@ -137702,7 +137949,7 @@ function fileResource(ctx, caller2, file3, access7 = accessTo(ctx, caller2, file
137702
137949
  function headRevision(ctx, fileId) {
137703
137950
  return ctx.store.db.prepare("SELECT id FROM gdrive_revisions WHERE file_id = ? ORDER BY rowid DESC LIMIT 1").get(fileId)?.id;
137704
137951
  }
137705
- function searchable(ctx, caller2, file3, access7) {
137952
+ function searchable(ctx, caller2, file3, access8) {
137706
137953
  const granted = effectivePermissions(ctx, file3);
137707
137954
  const people3 = (min) => granted.filter((entry3) => (entry3.grant.type === "user" || entry3.grant.type === "group") && RANK2[entry3.grant.role] >= RANK2[min]).map((entry3) => entry3.grant.email);
137708
137955
  const anyone = granted.find((entry3) => entry3.grant.type === "anyone"), domain2 = granted.find((entry3) => entry3.grant.type === "domain");
@@ -137723,7 +137970,7 @@ ${text24}`,
137723
137970
  owners: [file3.owner],
137724
137971
  writers: people3("writer"),
137725
137972
  readers: people3("reader"),
137726
- sharedWithMe: access7.direct !== null && file3.owner !== caller2.email,
137973
+ sharedWithMe: access8.direct !== null && file3.owner !== caller2.email,
137727
137974
  visibility: anyone ? anyone.grant.allow_discovery ? "anyoneCanFind" : "anyoneWithLink" : domain2 ? domain2.grant.allow_discovery ? "domainCanFind" : "domainWithLink" : "limited"
137728
137975
  };
137729
137976
  }
@@ -137791,10 +138038,10 @@ function resolve4(ctx, caller2, id12, minimum = "reader") {
137791
138038
  if (id12 === "root" || id12 === caller2.root) return { file: rootFolder(ctx, caller2), access: { role: "owner", listed: true, direct: null } };
137792
138039
  throw notFound3(id12);
137793
138040
  }
137794
- const access7 = accessTo(ctx, caller2, file3);
137795
- if (access7.role === null) throw notFound3(id12);
137796
- if (RANK2[access7.role] < RANK2[minimum]) throw forbidden();
137797
- return { file: file3, access: access7 };
138041
+ const access8 = accessTo(ctx, caller2, file3);
138042
+ if (access8.role === null) throw notFound3(id12);
138043
+ if (RANK2[access8.role] < RANK2[minimum]) throw forbidden();
138044
+ return { file: file3, access: access8 };
137798
138045
  }
137799
138046
  function rootFolder(ctx, caller2) {
137800
138047
  const user8 = getUser4(ctx, caller2.email);
@@ -137827,9 +138074,9 @@ function rootFolder(ctx, caller2) {
137827
138074
  var isRoot = (caller2, file3) => file3.id === caller2.root;
137828
138075
  function writableParent(ctx, caller2, id12) {
137829
138076
  if (id12 === "root" || id12 === caller2.root) return null;
137830
- const { file: file3, access: access7 } = resolve4(ctx, caller2, id12);
138077
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, id12);
137831
138078
  if (!isFolder(file3)) throw new DriveError(400, "invalid", "The specified parent is not a folder.", { name: "parents" });
137832
- if (RANK2[access7.role] < RANK2.writer) throw forbidden();
138079
+ if (RANK2[access8.role] < RANK2.writer) throw forbidden();
137833
138080
  return file3.id;
137834
138081
  }
137835
138082
  function parentList(value5) {
@@ -138019,10 +138266,10 @@ function listFiles(call3) {
138019
138266
  const offset16 = readPageToken(params9.get("pageToken"), binding2);
138020
138267
  const matches7 = [];
138021
138268
  for (const file3 of allFiles(ctx)) {
138022
- const access7 = accessTo(ctx, caller2, file3);
138023
- if (access7.role === null || !access7.listed) continue;
138269
+ const access8 = accessTo(ctx, caller2, file3);
138270
+ if (access8.role === null || !access8.listed) continue;
138024
138271
  if (corpora === "domain" && !effectivePermissions(ctx, file3).some((entry3) => entry3.grant.type === "domain" && entry3.grant.domain === caller2.domain)) continue;
138025
- if (predicate(searchable(ctx, caller2, file3, access7))) matches7.push({ file: file3, access: access7 });
138272
+ if (predicate(searchable(ctx, caller2, file3, access8))) matches7.push({ file: file3, access: access8 });
138026
138273
  }
138027
138274
  matches7.sort((a, b) => order4(a.file, b.file));
138028
138275
  const page15 = matches7.slice(offset16, offset16 + pageSize2);
@@ -138030,18 +138277,18 @@ function listFiles(call3) {
138030
138277
  kind: "drive#fileList",
138031
138278
  incompleteSearch: false,
138032
138279
  ...offset16 + pageSize2 < matches7.length && { nextPageToken: pageToken(offset16 + pageSize2, binding2) },
138033
- files: page15.map(({ file: file3, access: access7 }) => fileResource(ctx, caller2, file3, access7))
138280
+ files: page15.map(({ file: file3, access: access8 }) => fileResource(ctx, caller2, file3, access8))
138034
138281
  }, selection));
138035
138282
  }
138036
138283
  function getFileRoute(call3) {
138037
138284
  const params9 = parameters(call3.url, []);
138038
- const { file: file3, access: access7 } = resolve4(call3.ctx, call3.caller, call3.ids[0]);
138285
+ const { file: file3, access: access8 } = resolve4(call3.ctx, call3.caller, call3.ids[0]);
138039
138286
  if (params9.get("alt") === "media") {
138040
138287
  if (isFolder(file3) || isEditorFile(file3)) throw new DriveError(403, "fileNotDownloadable", "Only files with binary content can be downloaded. Use Export with Docs Editors files.", { name: "alt" });
138041
- if (file3.copy_requires_writer === 1 && RANK2[access7.role] < RANK2.writer) throw new DriveError(403, "cannotDownloadFile", "The user does not have sufficient permissions to download this file.");
138288
+ if (file3.copy_requires_writer === 1 && RANK2[access8.role] < RANK2.writer) throw new DriveError(403, "cannotDownloadFile", "The user does not have sufficient permissions to download this file.");
138042
138289
  return new Response(new Uint8Array(file3.content ?? Buffer.alloc(0)), { status: 200, headers: { "content-type": file3.mime_type, "content-length": String(file3.content?.length ?? 0) } });
138043
138290
  }
138044
- return json9(project8(fileResource(call3.ctx, call3.caller, file3, access7), fileMask(params9)));
138291
+ return json9(project8(fileResource(call3.ctx, call3.caller, file3, access8), fileMask(params9)));
138045
138292
  }
138046
138293
  function createFile(call3, media, metadata7 = jsonBody2(call3.body)) {
138047
138294
  const { ctx, caller: caller2 } = call3;
@@ -138102,9 +138349,9 @@ function updateFile(call3, media, metadata7 = jsonBody2(call3.body)) {
138102
138349
  const params9 = parameters(call3.url, ["addParents", "removeParents"]);
138103
138350
  fileBody(metadata7, UPDATE_WRITABLE);
138104
138351
  if (metadata7.contentHints !== void 0) unsupported11("contentHints");
138105
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0]);
138352
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
138106
138353
  if (isRoot(caller2, file3)) throw forbidden();
138107
- const role3 = access7.role, editor = RANK2[role3] >= RANK2.writer;
138354
+ const role3 = access8.role, editor = RANK2[role3] >= RANK2.writer;
138108
138355
  const next2 = { ...file3 };
138109
138356
  let edited = false;
138110
138357
  const edit = () => {
@@ -138222,8 +138469,8 @@ function remove(ctx, caller2, file3) {
138222
138469
  }
138223
138470
  function deleteFile(call3) {
138224
138471
  parameters(call3.url, []);
138225
- const { file: file3, access: access7 } = resolve4(call3.ctx, call3.caller, call3.ids[0]);
138226
- if (access7.role !== "owner" || isRoot(call3.caller, file3)) throw forbidden();
138472
+ const { file: file3, access: access8 } = resolve4(call3.ctx, call3.caller, call3.ids[0]);
138473
+ if (access8.role !== "owner" || isRoot(call3.caller, file3)) throw forbidden();
138227
138474
  remove(call3.ctx, call3.caller, file3);
138228
138475
  return new Response(null, { status: 204 });
138229
138476
  }
@@ -138241,8 +138488,8 @@ function copyFile(call3) {
138241
138488
  const metadata7 = jsonBody2(call3.body);
138242
138489
  fileBody(metadata7, COPY_WRITABLE);
138243
138490
  if (metadata7.contentHints !== void 0) unsupported11("contentHints");
138244
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0]);
138245
- if (isFolder(file3) || file3.copy_requires_writer === 1 && RANK2[access7.role] < RANK2.writer) throw new DriveError(403, "cannotCopyFile", "This file cannot be copied by the user.");
138491
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
138492
+ if (isFolder(file3) || file3.copy_requires_writer === 1 && RANK2[access8.role] < RANK2.writer) throw new DriveError(403, "cannotCopyFile", "This file cannot be copied by the user.");
138246
138493
  const mimeType = stringField(metadata7, "mimeType", 255);
138247
138494
  if (mimeType !== void 0 && mimeType !== file3.mime_type) unsupported11("converting a file while copying it");
138248
138495
  const parents = parentList(metadata7.parents);
@@ -138338,10 +138585,10 @@ function emailAddress(body6) {
138338
138585
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email10)) throw new DriveError(400, "invalid", "Invalid email address.", { name: "permission.emailAddress" });
138339
138586
  return email10;
138340
138587
  }
138341
- function transferOwnership(call3, file3, access7, email10, params9) {
138588
+ function transferOwnership(call3, file3, access8, email10, params9) {
138342
138589
  const { ctx, caller: caller2 } = call3;
138343
138590
  if (!booleanParameter(params9, "transferOwnership", false)) throw new DriveError(403, "forbidden", "The transferOwnership parameter must be enabled when the permission role is 'owner'.");
138344
- if (access7.role !== "owner") throw forbidden();
138591
+ if (access8.role !== "owner") throw forbidden();
138345
138592
  if (email10 === file3.owner) throw new DriveError(403, "invalidSharingRequest", 'Bad Request. User message: "The owner already has access."');
138346
138593
  if (email10.split("@")[1] !== file3.owner.split("@")[1]) {
138347
138594
  throw new DriveError(400, "ownershipChangeAcrossDomainNotPermitted", `Bad Request. User message: "Sorry, cannot transfer ownership to ${email10}. Ownership can only be transferred to another user in the same organization as the current owner."`);
@@ -138388,15 +138635,15 @@ function createPermission(call3) {
138388
138635
  if (key3 === "expirationTime" || key3 === "view" || key3 === "pendingOwner" || key3 === "inheritedPermissionsDisabled") unsupported11(`permission field ${key3}`);
138389
138636
  if (!["type", "role", "emailAddress", "domain", "allowFileDiscovery"].includes(key3)) throw new DriveError(403, "fieldNotWritable", "The resource body includes fields which are not directly writable.");
138390
138637
  }
138391
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0]);
138392
- if (isRoot(caller2, file3) || !canShare(file3, access7.role)) throw forbidden();
138638
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
138639
+ if (isRoot(caller2, file3) || !canShare(file3, access8.role)) throw forbidden();
138393
138640
  const type = body6.type, role3 = body6.role;
138394
138641
  if (type === void 0) throw new DriveError(400, "required", "Permission type field required", { name: "permission.type" });
138395
138642
  if (role3 === void 0) throw new DriveError(400, "required", "Permission role field required", { name: "permission.role" });
138396
138643
  if (!["user", "group", "domain", "anyone"].includes(String(type))) throw new DriveError(400, "invalid", "Invalid permission type.", { name: "permission.type" });
138397
138644
  if (role3 === "owner") {
138398
138645
  if (type !== "user") unsupported11(`the owner role for a ${String(type)} permission`);
138399
- return transferOwnership(call3, file3, access7, emailAddress(body6), params9);
138646
+ return transferOwnership(call3, file3, access8, emailAddress(body6), params9);
138400
138647
  }
138401
138648
  if (role3 === "organizer" || role3 === "fileOrganizer") throw new DriveError(403, "invalidSharingRequest", 'Bad Request. User message: "Organizer roles only apply to shared drives."');
138402
138649
  if (!["reader", "commenter", "writer"].includes(String(role3))) throw new DriveError(400, "invalid", "Invalid permission role.", { name: "permission.role" });
@@ -138435,15 +138682,15 @@ function updatePermission(call3) {
138435
138682
  if (key3 === "expirationTime" || key3 === "view" || key3 === "pendingOwner") unsupported11(`permission field ${key3}`);
138436
138683
  if (key3 !== "role" && key3 !== "allowFileDiscovery") throw new DriveError(403, "fieldNotWritable", "The resource body includes fields which are not directly writable.");
138437
138684
  }
138438
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0]);
138439
- if (!canShare(file3, access7.role)) throw forbidden();
138685
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
138686
+ if (!canShare(file3, access8.role)) throw forbidden();
138440
138687
  const entry3 = findGrant(ctx, file3, call3.ids[1]);
138441
138688
  if (entry3.grant.role === "owner") throw new DriveError(403, "cannotModifyOwnerPermission", "The owner of a file cannot be changed with this request.");
138442
138689
  if (entry3.inherited) unsupported11("changing a permission inherited from a parent folder");
138443
138690
  const role3 = body6.role === void 0 ? entry3.grant.role : body6.role;
138444
138691
  if (role3 === "owner") {
138445
138692
  if (entry3.grant.type !== "user") unsupported11(`the owner role for a ${entry3.grant.type} permission`);
138446
- return transferOwnership(call3, file3, access7, entry3.grant.email, params9);
138693
+ return transferOwnership(call3, file3, access8, entry3.grant.email, params9);
138447
138694
  }
138448
138695
  if (!["reader", "commenter", "writer"].includes(String(role3))) throw new DriveError(400, "invalid", "Invalid permission role.", { name: "permission.role" });
138449
138696
  ctx.store.db.prepare("UPDATE gdrive_permissions SET role = ? WHERE file_id = ? AND id = ?").run(role3, file3.id, entry3.grant.id);
@@ -138454,10 +138701,10 @@ function deletePermission(call3) {
138454
138701
  const { ctx, caller: caller2 } = call3;
138455
138702
  const params9 = parameters(call3.url, ["useDomainAdminAccess", "enforceExpansiveAccess"]);
138456
138703
  if (booleanParameter(params9, "useDomainAdminAccess", false)) unsupported11("useDomainAdminAccess");
138457
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0]);
138704
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0]);
138458
138705
  const entry3 = findGrant(ctx, file3, call3.ids[1]);
138459
138706
  const self2 = entry3.grant.email === caller2.email;
138460
- if (!self2 && !canShare(file3, access7.role)) throw forbidden();
138707
+ if (!self2 && !canShare(file3, access8.role)) throw forbidden();
138461
138708
  if (entry3.grant.role === "owner") throw new DriveError(403, "cannotRemoveOwner", "The owner of a file cannot be removed.");
138462
138709
  if (entry3.inherited) unsupported11("removing a permission inherited from a parent folder");
138463
138710
  ctx.store.db.prepare("DELETE FROM gdrive_permissions WHERE file_id = ? AND id = ?").run(file3.id, entry3.grant.id);
@@ -138541,9 +138788,9 @@ function updateComment(call3) {
138541
138788
  function deleteComment(call3) {
138542
138789
  const { ctx, caller: caller2 } = call3;
138543
138790
  parameters(call3.url, []);
138544
- const { file: file3, access: access7 } = resolve4(ctx, caller2, call3.ids[0], "commenter");
138791
+ const { file: file3, access: access8 } = resolve4(ctx, caller2, call3.ids[0], "commenter");
138545
138792
  const comment8 = getComment(ctx, file3, call3.ids[1], false);
138546
- if (comment8.author !== caller2.email && access7.role !== "owner") throw new DriveError(403, "insufficientPermissions", "The user does not have sufficient permissions for this comment.");
138793
+ if (comment8.author !== caller2.email && access8.role !== "owner") throw new DriveError(403, "insufficientPermissions", "The user does not have sufficient permissions for this comment.");
138547
138794
  ctx.store.db.prepare("UPDATE gdrive_comments SET deleted = 1, modified_ms = ? WHERE id = ?").run(ctx.clock.nowMs(), comment8.id);
138548
138795
  return new Response(null, { status: 204 });
138549
138796
  }
@@ -138618,8 +138865,8 @@ function listChanges(call3) {
138618
138865
  const file3 = row.removed ? void 0 : getFile(ctx, row.file_id);
138619
138866
  let change = null;
138620
138867
  if (file3) {
138621
- const access7 = accessTo(ctx, caller2, file3);
138622
- if (access7.role !== null && access7.listed && (!myDrive || file3.owner === caller2.email)) change = { file: fileResource(ctx, caller2, file3, access7), removed: false };
138868
+ const access8 = accessTo(ctx, caller2, file3);
138869
+ if (access8.role !== null && access8.listed && (!myDrive || file3.owner === caller2.email)) change = { file: fileResource(ctx, caller2, file3, access8), removed: false };
138623
138870
  } else if (includeRemoved && row.owner === caller2.email) change = { removed: true };
138624
138871
  if (!change) continue;
138625
138872
  if (visible5.length === pageSize2) {
@@ -138686,8 +138933,8 @@ async function handle7(c) {
138686
138933
  try {
138687
138934
  const body6 = method2 === "GET" || method2 === "DELETE" ? void 0 : new Uint8Array(await c.req.arrayBuffer());
138688
138935
  const ids2 = (route11.pattern.exec(url3.pathname) ?? []).slice(1).map((value5) => decodeURIComponent(value5));
138689
- const access7 = route11.write ? withMutation : withRead;
138690
- return access7(ctx, () => {
138936
+ const access8 = route11.write ? withMutation : withRead;
138937
+ return access8(ctx, () => {
138691
138938
  const token2 = tokenOf2(c, url3);
138692
138939
  const caller2 = callerFor(ctx, token2);
138693
138940
  if (!caller2) {
@@ -138805,7 +139052,7 @@ init_src();
138805
139052
 
138806
139053
  // packages/server/src/twins/gmail/search.ts
138807
139054
  function tokenize5(q) {
138808
- const tokens2 = [];
139055
+ const tokens3 = [];
138809
139056
  let i = 0;
138810
139057
  while (i < q.length) {
138811
139058
  const ch = q[i];
@@ -138814,39 +139061,39 @@ function tokenize5(q) {
138814
139061
  continue;
138815
139062
  }
138816
139063
  if (ch === "(") {
138817
- tokens2.push({ type: "open", value: ch });
139064
+ tokens3.push({ type: "open", value: ch });
138818
139065
  i++;
138819
139066
  continue;
138820
139067
  }
138821
139068
  if (ch === ")") {
138822
- tokens2.push({ type: "close", value: ch });
139069
+ tokens3.push({ type: "close", value: ch });
138823
139070
  i++;
138824
139071
  continue;
138825
139072
  }
138826
139073
  if (ch === "{") {
138827
- tokens2.push({ type: "openBrace", value: ch });
139074
+ tokens3.push({ type: "openBrace", value: ch });
138828
139075
  i++;
138829
139076
  continue;
138830
139077
  }
138831
139078
  if (ch === "}") {
138832
- tokens2.push({ type: "closeBrace", value: ch });
139079
+ tokens3.push({ type: "closeBrace", value: ch });
138833
139080
  i++;
138834
139081
  continue;
138835
139082
  }
138836
139083
  if (ch === "|") {
138837
- tokens2.push({ type: "or", value: ch });
139084
+ tokens3.push({ type: "or", value: ch });
138838
139085
  i++;
138839
139086
  continue;
138840
139087
  }
138841
139088
  if (ch === "-" && i + 1 < q.length && !/\s/.test(q[i + 1])) {
138842
- tokens2.push({ type: "minus", value: ch });
139089
+ tokens3.push({ type: "minus", value: ch });
138843
139090
  i++;
138844
139091
  continue;
138845
139092
  }
138846
139093
  if (ch === '"') {
138847
139094
  const end = q.indexOf('"', i + 1);
138848
139095
  const value5 = end < 0 ? q.slice(i + 1) : q.slice(i + 1, end);
138849
- tokens2.push({ type: "phrase", value: value5 });
139096
+ tokens3.push({ type: "phrase", value: value5 });
138850
139097
  i = end < 0 ? q.length : end + 1;
138851
139098
  continue;
138852
139099
  }
@@ -138867,13 +139114,13 @@ function tokenize5(q) {
138867
139114
  value5 = end < 0 ? q.slice(i + 1) : q.slice(i + 1, end);
138868
139115
  i = end < 0 ? q.length : end + 1;
138869
139116
  }
138870
- tokens2.push({ type: "op", op, value: value5 });
139117
+ tokens3.push({ type: "op", op, value: value5 });
138871
139118
  continue;
138872
139119
  }
138873
- if (word === "OR") tokens2.push({ type: "or", value: word });
138874
- else if (word !== "AND") tokens2.push({ type: "word", value: word });
139120
+ if (word === "OR") tokens3.push({ type: "or", value: word });
139121
+ else if (word !== "AND") tokens3.push({ type: "word", value: word });
138875
139122
  }
138876
- return tokens2;
139123
+ return tokens3;
138877
139124
  }
138878
139125
  var WORD = /[\p{L}\p{N}]+/gu;
138879
139126
  var words = (text24) => text24.toLowerCase().match(WORD) ?? [];
@@ -138917,10 +139164,10 @@ function bytes2(value5) {
138917
139164
  return Number(m[1]) * (m[2].toLowerCase() === "k" ? 1024 : m[2].toLowerCase() === "m" ? 1024 * 1024 : 1);
138918
139165
  }
138919
139166
  function labelByName(env2, value5) {
138920
- const norm = (s) => s.toLowerCase().replace(/[\s/-]+/g, "-");
139167
+ const norm2 = (s) => s.toLowerCase().replace(/[\s/-]+/g, "-");
138921
139168
  const system = SYSTEM_IN[value5.toLowerCase()] ?? CATEGORIES[value5.toLowerCase().replace(/^category[-_]/, "")];
138922
139169
  if (system) return system;
138923
- return env2.labels.find((l) => norm(l.name) === norm(value5) || l.id.toLowerCase() === value5.toLowerCase())?.id;
139170
+ return env2.labels.find((l) => norm2(l.name) === norm2(value5) || l.id.toLowerCase() === value5.toLowerCase())?.id;
138924
139171
  }
138925
139172
  function operator(op, value5) {
138926
139173
  const test3 = (fn, extra = {}) => ({ kind: "test", test: fn, ...extra });
@@ -139010,13 +139257,13 @@ function operator(op, value5) {
139010
139257
  return unsupported4(`Gmail search operator ${op}:`);
139011
139258
  }
139012
139259
  }
139013
- function parse7(tokens2) {
139260
+ function parse7(tokens3) {
139014
139261
  let i = 0;
139015
139262
  const sequence = (until) => {
139016
139263
  const items = [];
139017
- while (i < tokens2.length && tokens2[i].type !== until) {
139264
+ while (i < tokens3.length && tokens3[i].type !== until) {
139018
139265
  let item2 = unary();
139019
- while (tokens2[i]?.type === "or") {
139266
+ while (tokens3[i]?.type === "or") {
139020
139267
  i++;
139021
139268
  const next2 = unary();
139022
139269
  item2 = { kind: "or", items: [item2, next2] };
@@ -139026,7 +139273,7 @@ function parse7(tokens2) {
139026
139273
  return items;
139027
139274
  };
139028
139275
  const unary = () => {
139029
- const token2 = tokens2[i++];
139276
+ const token2 = tokens3[i++];
139030
139277
  if (!token2) return { kind: "and", items: [] };
139031
139278
  switch (token2.type) {
139032
139279
  case "minus":
@@ -141197,26 +141444,26 @@ function compare4(r, kind, value5, comparator, coordinate2) {
141197
141444
  if (op === "null") return (value5 === null || value5 === void 0) === want;
141198
141445
  if (value5 === null || value5 === void 0) return op === "neq" || op === "nin" || op.startsWith("not");
141199
141446
  if (kind === "date" || kind === "day") {
141200
- const norm = (v) => kind === "date" ? dateValue2(r, v) : dayValue(r, v);
141447
+ const norm2 = (v) => kind === "date" ? dateValue2(r, v) : dayValue(r, v);
141201
141448
  const have = kind === "date" ? Date.parse(String(value5)) : String(value5);
141202
- const list16 = (v) => v.map(norm);
141449
+ const list16 = (v) => v.map(norm2);
141203
141450
  switch (op) {
141204
141451
  case "eq":
141205
- return have === norm(want);
141452
+ return have === norm2(want);
141206
141453
  case "neq":
141207
- return have !== norm(want);
141454
+ return have !== norm2(want);
141208
141455
  case "in":
141209
141456
  return list16(want).includes(have);
141210
141457
  case "nin":
141211
141458
  return !list16(want).includes(have);
141212
141459
  case "lt":
141213
- return have < norm(want);
141460
+ return have < norm2(want);
141214
141461
  case "lte":
141215
- return have <= norm(want);
141462
+ return have <= norm2(want);
141216
141463
  case "gt":
141217
- return have > norm(want);
141464
+ return have > norm2(want);
141218
141465
  case "gte":
141219
- return have >= norm(want);
141466
+ return have >= norm2(want);
141220
141467
  }
141221
141468
  }
141222
141469
  if (kind === "number") {
@@ -142401,7 +142648,7 @@ import { createHash as createHash24 } from "node:crypto";
142401
142648
  var FilterError = class extends Error {
142402
142649
  };
142403
142650
  function tokenize6(source) {
142404
- const tokens2 = [];
142651
+ const tokens3 = [];
142405
142652
  let at3 = 0;
142406
142653
  while (at3 < source.length) {
142407
142654
  const char = source[at3];
@@ -142410,7 +142657,7 @@ function tokenize6(source) {
142410
142657
  continue;
142411
142658
  }
142412
142659
  if (char === "(" || char === ")") {
142413
- tokens2.push({ kind: "paren", value: char });
142660
+ tokens3.push({ kind: "paren", value: char });
142414
142661
  at3++;
142415
142662
  continue;
142416
142663
  }
@@ -142430,21 +142677,21 @@ function tokenize6(source) {
142430
142677
  }
142431
142678
  value5 += source[at3++];
142432
142679
  }
142433
- tokens2.push({ kind: "string", value: value5 });
142680
+ tokens3.push({ kind: "string", value: value5 });
142434
142681
  continue;
142435
142682
  }
142436
142683
  const number7 = /^-?\d+(?:\.\d+)?/.exec(source.slice(at3));
142437
142684
  if (number7) {
142438
- tokens2.push({ kind: "number", value: number7[0] });
142685
+ tokens3.push({ kind: "number", value: number7[0] });
142439
142686
  at3 += number7[0].length;
142440
142687
  continue;
142441
142688
  }
142442
142689
  const word = /^[A-Za-z_][A-Za-z0-9_.$]*/.exec(source.slice(at3));
142443
142690
  if (!word) throw new FilterError(`unexpected ${char}`);
142444
- tokens2.push({ kind: "word", value: word[0] });
142691
+ tokens3.push({ kind: "word", value: word[0] });
142445
142692
  at3 += word[0].length;
142446
142693
  }
142447
- return tokens2;
142694
+ return tokens3;
142448
142695
  }
142449
142696
  var OPERATORS = /* @__PURE__ */ new Set(["eq", "ne", "sw", "co", "ew", "gt", "ge", "lt", "le", "pr"]);
142450
142697
  function compare5(actual, op, expected) {
@@ -142479,9 +142726,9 @@ function compare5(actual, op, expected) {
142479
142726
  }
142480
142727
  }
142481
142728
  function parseFilter(source, attributes2) {
142482
- const tokens2 = tokenize6(source);
142729
+ const tokens3 = tokenize6(source);
142483
142730
  let at3 = 0;
142484
- const keyword = (value5) => tokens2[at3]?.kind === "word" && tokens2[at3].value.toLowerCase() === value5;
142731
+ const keyword = (value5) => tokens3[at3]?.kind === "word" && tokens3[at3].value.toLowerCase() === value5;
142485
142732
  const or = () => {
142486
142733
  const terms = [and()];
142487
142734
  while (keyword("or")) {
@@ -142504,21 +142751,21 @@ function parseFilter(source, attributes2) {
142504
142751
  const inner = unary();
142505
142752
  return (lookup6) => !inner(lookup6);
142506
142753
  }
142507
- if (tokens2[at3]?.kind === "paren" && tokens2[at3].value === "(") {
142754
+ if (tokens3[at3]?.kind === "paren" && tokens3[at3].value === "(") {
142508
142755
  at3++;
142509
142756
  const inner = or();
142510
- if (tokens2[at3]?.kind !== "paren" || tokens2[at3].value !== ")") throw new FilterError("missing )");
142757
+ if (tokens3[at3]?.kind !== "paren" || tokens3[at3].value !== ")") throw new FilterError("missing )");
142511
142758
  at3++;
142512
142759
  return inner;
142513
142760
  }
142514
- const path6 = tokens2[at3++];
142761
+ const path6 = tokens3[at3++];
142515
142762
  if (!path6 || path6.kind !== "word") throw new FilterError("expected an attribute");
142516
142763
  if (attributes2 && !attributes2(path6.value)) throw new FilterError(`unsupported attribute ${path6.value}`);
142517
- const operator2 = tokens2[at3++];
142764
+ const operator2 = tokens3[at3++];
142518
142765
  if (!operator2 || operator2.kind !== "word" || !OPERATORS.has(operator2.value.toLowerCase())) throw new FilterError("expected an operator");
142519
142766
  const op = operator2.value.toLowerCase();
142520
142767
  if (op === "pr") return (lookup6) => compare5(lookup6(path6.value), "pr", null);
142521
- const value5 = tokens2[at3++];
142768
+ const value5 = tokens3[at3++];
142522
142769
  if (!value5) throw new FilterError("expected a value");
142523
142770
  let expected;
142524
142771
  if (value5.kind === "string") expected = value5.value;
@@ -142527,9 +142774,9 @@ function parseFilter(source, attributes2) {
142527
142774
  else throw new FilterError("expected a value");
142528
142775
  return (lookup6) => compare5(lookup6(path6.value), op, expected);
142529
142776
  };
142530
- if (!tokens2.length) throw new FilterError("empty expression");
142777
+ if (!tokens3.length) throw new FilterError("empty expression");
142531
142778
  const expression2 = or();
142532
- if (at3 !== tokens2.length) throw new FilterError("unexpected trailing input");
142779
+ if (at3 !== tokens3.length) throw new FilterError("unexpected trailing input");
142533
142780
  return expression2;
142534
142781
  }
142535
142782
  function lookupIn(value5) {
@@ -144683,12 +144930,12 @@ function refundCharge(ctx, ch, amount3, reason2, metadata7, at3 = nowSeconds(ctx
144683
144930
  var FIELDS2 = ["email", "name", "phone", "created"];
144684
144931
  function clauses(query11) {
144685
144932
  const token2 = /\s*(-?(?:metadata\[(?:"[^"]*"|'[^']*')\]|[a-z_]+)\s*(?:>=|<=|:|~|>|<)\s*(?:"[^"]*"|'[^']*'|[^\s"']+)|AND|OR)\s*/y;
144686
- const tokens2 = [];
144687
- for (let m; token2.lastIndex < query11.length && (m = token2.exec(query11)); ) tokens2.push(m[1]);
144688
- if (!tokens2.length || token2.lastIndex < query11.length) invalid13(`Invalid search query: ${query11}`, "query");
144689
- const joins = tokens2.filter((t) => t === "AND" || t === "OR");
144933
+ const tokens3 = [];
144934
+ for (let m; token2.lastIndex < query11.length && (m = token2.exec(query11)); ) tokens3.push(m[1]);
144935
+ if (!tokens3.length || token2.lastIndex < query11.length) invalid13(`Invalid search query: ${query11}`, "query");
144936
+ const joins = tokens3.filter((t) => t === "AND" || t === "OR");
144690
144937
  if (new Set(joins).size > 1) invalid13("Search queries cannot mix AND and OR.", "query");
144691
- const parsed3 = tokens2.filter((t) => t !== "AND" && t !== "OR").map((token3) => {
144938
+ const parsed3 = tokens3.filter((t) => t !== "AND" && t !== "OR").map((token3) => {
144692
144939
  const m = /^(-?)(metadata\[(?:"([^"]*)"|'([^']*)')\]|[a-z_]+)\s*(>=|<=|:|~|>|<)\s*(?:"([^"]*)"|'([^']*)'|(\S+))$/.exec(token3);
144693
144940
  if (!m) invalid13(`Invalid search query: ${token3}`, "query");
144694
144941
  const [, negate, field4, mk1, mk2, op, v1, v22, v3] = m;
@@ -145951,11 +146198,11 @@ function orgFor(call3) {
145951
146198
  return org5;
145952
146199
  }
145953
146200
  var slugify2 = (name5) => name5.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "organization";
145954
- function checkSlug(ctx, slug12, except) {
145955
- if (typeof slug12 !== "string" || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug12) || slug12.length > 100) throw new ClerkError(422, "form_param_format_invalid", "is invalid", "slug must contain only lowercase letters, digits and dashes", { param_name: "slug" });
145956
- const owner3 = getOrg(ctx, slug12);
146201
+ function checkSlug(ctx, slug13, except) {
146202
+ if (typeof slug13 !== "string" || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug13) || slug13.length > 100) throw new ClerkError(422, "form_param_format_invalid", "is invalid", "slug must contain only lowercase letters, digits and dashes", { param_name: "slug" });
146203
+ const owner3 = getOrg(ctx, slug13);
145957
146204
  if (owner3 && owner3.id !== except) throw taken("slug", "slug");
145958
- return slug12;
146205
+ return slug13;
145959
146206
  }
145960
146207
  function seats(value5) {
145961
146208
  if (value5 === void 0) return void 0;
@@ -145986,14 +146233,14 @@ function createOrg(call3) {
145986
146233
  const body6 = fields7(call3, ["name", "slug", "created_by", "max_allowed_memberships", "public_metadata", "private_metadata"], ["role_set_key"]);
145987
146234
  const name5 = text18(body6.name, "name");
145988
146235
  if (!name5?.trim()) throw missing3("name");
145989
- const slug12 = checkSlug(ctx, body6.slug ?? slugify2(name5));
146236
+ const slug13 = checkSlug(ctx, body6.slug ?? slugify2(name5));
145990
146237
  const creator = body6.created_by === void 0 ? void 0 : getUser6(ctx, String(body6.created_by));
145991
146238
  if (body6.created_by !== void 0 && !creator) throw new ClerkError(422, "form_param_value_invalid", "is invalid", "created_by must be an existing user", { param_name: "created_by" });
145992
146239
  const now10 = ctx.clock.nowMs();
145993
146240
  const org5 = {
145994
146241
  id: newId2(ctx.ids, "org"),
145995
146242
  name: name5,
145996
- slug: slug12,
146243
+ slug: slug13,
145997
146244
  max_members: seats(body6.max_allowed_memberships) ?? 0,
145998
146245
  admin_delete_enabled: 1,
145999
146246
  public_metadata: JSON.stringify(json11(body6.public_metadata, "public_metadata") ?? {}),
@@ -146002,7 +146249,7 @@ function createOrg(call3) {
146002
146249
  created_ms: now10,
146003
146250
  updated_ms: now10
146004
146251
  };
146005
- ctx.store.db.prepare("INSERT INTO clerk_orgs (id, name, slug, max_members, public_metadata, private_metadata, created_by, created_ms, updated_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(org5.id, name5, slug12, org5.max_members, org5.public_metadata, org5.private_metadata, org5.created_by, now10, now10);
146252
+ ctx.store.db.prepare("INSERT INTO clerk_orgs (id, name, slug, max_members, public_metadata, private_metadata, created_by, created_ms, updated_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(org5.id, name5, slug13, org5.max_members, org5.public_metadata, org5.private_metadata, org5.created_by, now10, now10);
146006
146253
  if (creator) ctx.store.db.prepare("INSERT INTO clerk_memberships (id, org_id, user_id, role, created_ms, updated_ms) VALUES (?, ?, ?, ?, ?, ?)").run(newId2(ctx.ids, "orgmem"), org5.id, creator.id, "org:admin", now10, now10);
146007
146254
  return respond3(call3, 200, orgJson(ctx, org5));
146008
146255
  }
@@ -148878,10 +149125,10 @@ var attioRoutes = [
148878
149125
  coverage: { status: "partial", notes: "assert by a unique attribute: updates the match (appending to multiselect values) or creates a record" },
148879
149126
  run: (r) => {
148880
149127
  const object16 = findObject(r.ctx, r.param("object"));
148881
- const slug12 = r.query.get("matching_attribute");
148882
- if (!slug12) invalid17("The matching_attribute query parameter is required.", "missing_value");
148883
- const attr = attributesOf(r.ctx, object16.id).find((a) => a.api_slug === slug12 || a.id === slug12);
148884
- if (!attr) invalid17(`Cannot find attribute with slug/ID "${slug12}".`, "value_not_found");
149128
+ const slug13 = r.query.get("matching_attribute");
149129
+ if (!slug13) invalid17("The matching_attribute query parameter is required.", "missing_value");
149130
+ const attr = attributesOf(r.ctx, object16.id).find((a) => a.api_slug === slug13 || a.id === slug13);
149131
+ if (!attr) invalid17(`Cannot find attribute with slug/ID "${slug13}".`, "value_not_found");
148885
149132
  if (!attr.is_unique) invalid17(`Attribute with slug "${attr.api_slug}" is not unique and cannot be used to match records.`);
148886
149133
  const given = (r.data.values ?? {})[attr.api_slug] ?? (r.data.values ?? {})[attr.id];
148887
149134
  if (given === void 0) invalid17(`The values must include the matching attribute "${attr.api_slug}".`, "missing_value");
@@ -149202,13 +149449,13 @@ function seed23(ctx) {
149202
149449
  run2(ctx, "INSERT INTO attio_members (id, ref, first_name, last_name, email, access_level, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)", id12, m.ref, m.first_name, m.last_name, m.email, m.access_level, created2);
149203
149450
  }
149204
149451
  run2(ctx, "INSERT INTO attio_tokens (token, member_id) VALUES (?, ?)", ctx.secrets.hex(64), members4.get(data5.agent));
149205
- const used = (slug12) => [...new Set(data5.records.companies.flatMap((r) => {
149206
- const v = r.values[slug12];
149452
+ const used = (slug13) => [...new Set(data5.records.companies.flatMap((r) => {
149453
+ const v = r.values[slug13];
149207
149454
  return Array.isArray(v) ? v.map(String) : typeof v === "string" ? [v] : [];
149208
149455
  }))];
149209
149456
  const objects = standard(data5.deal_stages, [.../* @__PURE__ */ new Set([...used("categories"), "B2B", "B2C", "SaaS", "Retail"])]);
149210
149457
  const objectIds = /* @__PURE__ */ new Map();
149211
- for (const slug12 of Object.keys(objects)) objectIds.set(slug12, uuid9(ctx));
149458
+ for (const slug13 of Object.keys(objects)) objectIds.set(slug13, uuid9(ctx));
149212
149459
  const addAttributes = (parentId, specs) => specs.forEach((spec, position) => {
149213
149460
  const id12 = uuid9(ctx);
149214
149461
  const config9 = { currency: { default_currency_code: spec.currency ?? null, display_type: spec.currency ? "symbol" : null }, record_reference: { allowed_object_ids: spec.target ? [objectIds.get(spec.target)] : null } };
@@ -149231,28 +149478,28 @@ function seed23(ctx) {
149231
149478
  );
149232
149479
  (spec.options ?? []).forEach((title, i) => run2(ctx, "INSERT INTO attio_options (id, attribute_id, title, position) VALUES (?, ?, ?, ?)", uuid9(ctx), id12, title, i));
149233
149480
  });
149234
- for (const [slug12, o] of Object.entries(objects)) {
149235
- run2(ctx, "INSERT INTO attio_objects (id, api_slug, singular_noun, plural_noun, created_at) VALUES (?, ?, ?, ?, ?)", objectIds.get(slug12), slug12, o.singular, o.plural, created2);
149236
- addAttributes(objectIds.get(slug12), [...o.attributes, ...(data5.attributes[slug12] ?? []).map((a) => ({ ...a, target: a.target }))]);
149481
+ for (const [slug13, o] of Object.entries(objects)) {
149482
+ run2(ctx, "INSERT INTO attio_objects (id, api_slug, singular_noun, plural_noun, created_at) VALUES (?, ?, ?, ?, ?)", objectIds.get(slug13), slug13, o.singular, o.plural, created2);
149483
+ addAttributes(objectIds.get(slug13), [...o.attributes, ...(data5.attributes[slug13] ?? []).map((a) => ({ ...a, target: a.target }))]);
149237
149484
  }
149238
149485
  const records3 = /* @__PURE__ */ new Map();
149239
149486
  const order4 = ["companies", "people", "deals"];
149240
- for (const slug12 of order4) for (const r of data5.records[slug12]) {
149487
+ for (const slug13 of order4) for (const r of data5.records[slug13]) {
149241
149488
  const id12 = uuid9(ctx);
149242
149489
  records3.set(r.ref, id12);
149243
- run2(ctx, "INSERT INTO attio_records (id, object_id, created_at, created_by) VALUES (?, ?, ?, ?)", id12, objectIds.get(slug12), at3(r.created), JSON.stringify(actor(members4.get(data5.agent))));
149490
+ run2(ctx, "INSERT INTO attio_records (id, object_id, created_at, created_by) VALUES (?, ?, ?, ?)", id12, objectIds.get(slug13), at3(r.created), JSON.stringify(actor(members4.get(data5.agent))));
149244
149491
  }
149245
149492
  const write4 = (parentId, parent2, values2, when13, by2) => {
149246
149493
  const attributes2 = all5(ctx, "SELECT * FROM attio_attributes WHERE parent_id = ? ORDER BY position", parent2);
149247
- for (const [slug12, raw3] of Object.entries(values2)) {
149248
- const attr = attributes2.find((a) => a.api_slug === slug12);
149249
- if (!attr) throw new AnchaError("SCENE_INVALID", `seed.attio: no attribute "${slug12}"`);
149494
+ for (const [slug13, raw3] of Object.entries(values2)) {
149495
+ const attr = attributes2.find((a) => a.api_slug === slug13);
149496
+ if (!attr) throw new AnchaError("SCENE_INVALID", `seed.attio: no attribute "${slug13}"`);
149250
149497
  const list16 = raw3 === null ? [] : Array.isArray(raw3) ? raw3 : [raw3];
149251
149498
  const items = list16.map((v) => parseValue(ctx, attr, attr.type === "record-reference" ? { target_record_id: records3.get(String(v)) ?? String(v) } : attr.type === "actor-reference" ? members4.get(String(v)) ?? String(v) : v));
149252
149499
  writeValues(ctx, parentId, attr, items, actor(by2), true, when13);
149253
149500
  }
149254
149501
  };
149255
- for (const slug12 of order4) for (const r of data5.records[slug12]) write4(records3.get(r.ref), objectIds.get(slug12), r.values, at3(r.created), members4.get(data5.agent));
149502
+ for (const slug13 of order4) for (const r of data5.records[slug13]) write4(records3.get(r.ref), objectIds.get(slug13), r.values, at3(r.created), members4.get(data5.agent));
149256
149503
  for (const l of data5.lists) {
149257
149504
  const id12 = uuid9(ctx);
149258
149505
  run2(ctx, "INSERT INTO attio_lists (id, api_slug, name, parent_object, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?)", id12, l.api_slug, l.name, l.parent_object, members4.get(data5.agent), at3(l.created));
@@ -149263,7 +149510,7 @@ function seed23(ctx) {
149263
149510
  write4(entryId, `list:${id12}`, e.values, at3(e.created), members4.get(data5.agent));
149264
149511
  }
149265
149512
  }
149266
- const objectOf = (ref20) => order4.find((slug12) => data5.records[slug12].some((r) => r.ref === ref20));
149513
+ const objectOf = (ref20) => order4.find((slug13) => data5.records[slug13].some((r) => r.ref === ref20));
149267
149514
  for (const n of data5.notes) {
149268
149515
  run2(
149269
149516
  ctx,
@@ -149812,13 +150059,13 @@ function serveTemporary(ctx, token2) {
149812
150059
  return new Response(new Uint8Array(revision2.content), { status: 200, headers: { "content-type": "application/octet-stream" } });
149813
150060
  }
149814
150061
  function searchPage(call3, cursor4) {
149815
- const tokens2 = cursor4.q.toLowerCase().split(/\s+/).filter(Boolean);
150062
+ const tokens3 = cursor4.q.toLowerCase().split(/\s+/).filter(Boolean);
149816
150063
  const words4 = (value5) => value5.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
149817
150064
  const candidates = cursor4.s === "deleted" ? call3.ctx.store.db.prepare("SELECT * FROM dbx_deleted ORDER BY path_lower").all().filter((row) => !getEntry(call3.ctx, row.path_lower)).map((row) => ({ key: row.path_lower, name: nameOf3(row.path_display), text: "", value: deletedMetadata(row) })) : childrenOf(call3.ctx, cursor4.p, true).map((entry3) => ({ key: entry3.path_lower, name: nameOf3(entry3.path_display), text: entry3.kind === "file" && /\.(txt|csv|md|json|html|xml|pdf)$/i.test(entry3.path_lower) ? (entry3.content ?? Buffer.alloc(0)).toString("utf8") : "", value: metadata6(call3.ctx, entry3) }));
149818
150065
  const matches7 = candidates.filter((item2) => (cursor4.p === "" || item2.key.startsWith(`${cursor4.p}/`)) && (!cursor4.x || cursor4.x.some((ext) => item2.key.endsWith(`.${ext.toLowerCase()}`)))).flatMap((item2) => {
149819
150066
  const nameWords = words4(item2.name);
149820
- const byName = tokens2.every((token2) => nameWords.some((word) => word.startsWith(token2)));
149821
- const byContent = !cursor4.f && tokens2.every((token2) => item2.text.toLowerCase().includes(token2));
150067
+ const byName = tokens3.every((token2) => nameWords.some((word) => word.startsWith(token2)));
150068
+ const byContent = !cursor4.f && tokens3.every((token2) => item2.text.toLowerCase().includes(token2));
149822
150069
  if (!byName && !byContent) return [];
149823
150070
  return [{ match_type: { ".tag": byName && byContent ? "filename_and_content" : byName ? "filename" : "file_content" }, metadata: { ".tag": "metadata", metadata: item2.value } }];
149824
150071
  });
@@ -149895,10 +150142,10 @@ function linkSettings(call3, settings) {
149895
150142
  if (!["public", "team", "no_one"].includes(audience)) unsupported19(`shared link audience ${audience}`);
149896
150143
  out.audience = audience;
149897
150144
  }
149898
- const access7 = tag3(value5.access);
149899
- if (access7 !== void 0) {
149900
- if (!["viewer", "editor", "max"].includes(access7)) throw new DropboxError(400, `Error in call to API function "${call3.route}": settings.access: unknown tag '${access7}'`);
149901
- out.access = access7 === "max" ? "editor" : access7;
150145
+ const access8 = tag3(value5.access);
150146
+ if (access8 !== void 0) {
150147
+ if (!["viewer", "editor", "max"].includes(access8)) throw new DropboxError(400, `Error in call to API function "${call3.route}": settings.access: unknown tag '${access8}'`);
150148
+ out.access = access8 === "max" ? "editor" : access8;
149902
150149
  }
149903
150150
  if (value5.expires !== void 0) {
149904
150151
  const at3 = Date.parse(String(value5.expires));
@@ -150007,10 +150254,10 @@ function addMembers(call3) {
150007
150254
  }
150008
150255
  const email10 = String(member4.email ?? "").trim().toLowerCase();
150009
150256
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email10)) throw endpoint("bad_member/invalid_email", { ".tag": "bad_member", bad_member: { ".tag": "invalid_email", invalid_email: email10 } });
150010
- const access7 = typeof raw3.access_level === "string" ? raw3.access_level : raw3.access_level?.[".tag"] ?? "viewer";
150011
- if (!["editor", "viewer", "viewer_no_comment"].includes(access7)) throw new DropboxError(400, `Error in call to API function "sharing/add_folder_member": access_level: unknown tag '${access7}'`);
150257
+ const access8 = typeof raw3.access_level === "string" ? raw3.access_level : raw3.access_level?.[".tag"] ?? "viewer";
150258
+ if (!["editor", "viewer", "viewer_no_comment"].includes(access8)) throw new DropboxError(400, `Error in call to API function "sharing/add_folder_member": access_level: unknown tag '${access8}'`);
150012
150259
  if (email10 === account5(call3.ctx).email) throw endpoint("bad_member/cant_share_with_self", { ".tag": "bad_member", bad_member: { ".tag": "cant_share_with_self" } });
150013
- call3.ctx.store.db.prepare("INSERT OR REPLACE INTO dbx_members (shared_folder_id, email, access, added_ms) VALUES (?, ?, ?, ?)").run(folder.shared_folder_id, email10, access7, now10);
150260
+ call3.ctx.store.db.prepare("INSERT OR REPLACE INTO dbx_members (shared_folder_id, email, access, added_ms) VALUES (?, ?, ?, ?)").run(folder.shared_folder_id, email10, access8, now10);
150014
150261
  }
150015
150262
  return json15(null);
150016
150263
  }
@@ -151647,8 +151894,8 @@ function restoreVersion(call3, id12) {
151647
151894
  }
151648
151895
  function search6(call3, query11) {
151649
151896
  odata(call3, ["$top", "$skiptoken", "$orderby"]);
151650
- const tokens2 = query11.toLowerCase().split(/\s+/).filter(Boolean);
151651
- if (!tokens2.length) throw invalid19("The search query is empty.");
151897
+ const tokens3 = query11.toLowerCase().split(/\s+/).filter(Boolean);
151898
+ if (!tokens3.length) throw invalid19("The search query is empty.");
151652
151899
  const scope3 = target3(call3), all8 = [];
151653
151900
  const visit3 = (node5) => {
151654
151901
  for (const child2 of childrenOf2(call3.ctx, node5.id)) {
@@ -151660,7 +151907,7 @@ function search6(call3, query11) {
151660
151907
  const matches7 = all8.filter((item2) => {
151661
151908
  const text24 = `${item2.name}
151662
151909
  ${textOf2(item2) ?? ""}`.toLowerCase();
151663
- return tokens2.every((token2) => text24.includes(token2));
151910
+ return tokens3.every((token2) => text24.includes(token2));
151664
151911
  });
151665
151912
  const response5 = collection(call3, "Collection(driveItem)", matches7);
151666
151913
  return response5;
@@ -156881,11 +157128,11 @@ async function token(c) {
156881
157128
  if (!known2) return Response.json({ error: "invalid_client", error_description: "Client Authentication failed" }, { status: 401 });
156882
157129
  const grant = form.get("grant_type");
156883
157130
  if (grant !== "client_credentials") return Response.json({ error: "unsupported_grant_type", error_description: grant ? "unsupported grant_type" : "Grant Type is NULL" }, { status: 400 });
156884
- const now10 = ctx.clock.nowMs(), access7 = `A21AA${ctx.secrets.alnumUpper(92)}`;
156885
- ctx.store.db.prepare("INSERT INTO paypal_tokens (token, expires_ms) VALUES (?, ?)").run(access7, now10 + 324e5);
157131
+ const now10 = ctx.clock.nowMs(), access8 = `A21AA${ctx.secrets.alnumUpper(92)}`;
157132
+ ctx.store.db.prepare("INSERT INTO paypal_tokens (token, expires_ms) VALUES (?, ?)").run(access8, now10 + 324e5);
156886
157133
  return Response.json({
156887
157134
  scope: "https://uri.paypal.com/services/payments/payment https://uri.paypal.com/services/payments/refund https://uri.paypal.com/services/subscriptions https://uri.paypal.com/services/reporting/search/read",
156888
- access_token: access7,
157135
+ access_token: access8,
156889
157136
  token_type: "Bearer",
156890
157137
  app_id: "APP-80W284485P519543T",
156891
157138
  expires_in: 32400,
@@ -158982,7 +159229,7 @@ function credentials29(ctx) {
158982
159229
  var iso11 = (ms3) => ms3 === null ? null : new Date(ms3).toISOString();
158983
159230
  function dumpState29(ctx) {
158984
159231
  const people3 = users2(ctx), name5 = (id12) => id12 === null ? null : people3.find((u) => u.account_id === id12)?.name ?? null;
158985
- const issues = rows31(ctx, "jira_issues"), keyOf2 = (id12) => issues.find((i) => i.id === id12)?.key ?? null;
159232
+ const issues = rows31(ctx, "jira_issues"), keyOf3 = (id12) => issues.find((i) => i.id === id12)?.key ?? null;
158986
159233
  const sprints = rows31(ctx, "jira_sprints");
158987
159234
  return {
158988
159235
  site: `${site(ctx).name}.atlassian.net`,
@@ -159002,7 +159249,7 @@ function dumpState29(ctx) {
159002
159249
  assignee: name5(i.assignee),
159003
159250
  reporter: name5(i.reporter),
159004
159251
  labels: i.labels,
159005
- parent: i.parent_id === null ? null : keyOf2(i.parent_id),
159252
+ parent: i.parent_id === null ? null : keyOf3(i.parent_id),
159006
159253
  sprints: i.sprint_ids.map((id12) => sprints.find((s) => s.id === id12)?.name),
159007
159254
  story_points: i.story_points,
159008
159255
  due: i.due,
@@ -159012,7 +159259,7 @@ function dumpState29(ctx) {
159012
159259
  watchers: i.watchers.map(name5),
159013
159260
  links: links(ctx).filter((l) => l.outward === i.id || l.inward === i.id).map((l) => {
159014
159261
  const t = LINK_TYPES.find((x) => x.name === l.type);
159015
- return l.outward === i.id ? `${t.outward} ${keyOf2(l.inward)}` : `${t.inward} ${keyOf2(l.outward)}`;
159262
+ return l.outward === i.id ? `${t.outward} ${keyOf3(l.inward)}` : `${t.inward} ${keyOf3(l.outward)}`;
159016
159263
  }),
159017
159264
  comments: rows31(ctx, "jira_comments", "WHERE issue_id = ?", i.id).map((c) => ({ author: name5(c.author), body: adfToText(c.body), created: iso11(c.created_ms) }))
159018
159265
  }))
@@ -161914,7 +162161,7 @@ function paginate7(call3, key3, items, render2, sideload = () => ({})) {
161914
162161
  var PRIORITY_RANK = { low: 1, normal: 2, high: 3, urgent: 4 };
161915
162162
  function sortTickets(ctx, tickets, field4, descending) {
161916
162163
  const name5 = (id12) => id12 === null ? "" : getUser7(ctx, id12)?.name ?? "";
161917
- const keyOf2 = {
162164
+ const keyOf3 = {
161918
162165
  id: (ticket2) => ticket2.id,
161919
162166
  created_at: (ticket2) => ticket2.created_ms,
161920
162167
  updated_at: (ticket2) => ticket2.updated_ms,
@@ -161928,7 +162175,7 @@ function sortTickets(ctx, tickets, field4, descending) {
161928
162175
  group: (ticket2) => ticket2.group_id ?? 0,
161929
162176
  ticket_type: (ticket2) => ticket2.type ?? ""
161930
162177
  };
161931
- const key3 = keyOf2[field4];
162178
+ const key3 = keyOf3[field4];
161932
162179
  if (!key3) throw badRequest(`cannot sort by ${field4}`);
161933
162180
  return [...tickets].sort((a, b) => {
161934
162181
  const x = key3(a), y = key3(b);
@@ -165859,10 +166106,10 @@ function handle28(route11) {
165859
166106
  all: (name5) => url3.searchParams.getAll(name5).filter((v) => v !== "")
165860
166107
  };
165861
166108
  const run6 = () => {
165862
- const slug12 = c.req.param("org");
165863
- if (slug12 !== void 0) {
166109
+ const slug13 = c.req.param("org");
166110
+ if (slug13 !== void 0) {
165864
166111
  const o = org4(ctx);
165865
- if (decodeURIComponent(slug12) !== o.slug && decodeURIComponent(slug12) !== o.id) notFound19();
166112
+ if (decodeURIComponent(slug13) !== o.slug && decodeURIComponent(slug13) !== o.id) notFound19();
165866
166113
  }
165867
166114
  return route11.run(r);
165868
166115
  };
@@ -166910,7 +167157,7 @@ function listReleases(r, projects) {
166910
167157
  var KEY = /^(!?)([a-zA-Z_][\w.-]*(?:\[[^\]]+\])?):(.*)$/s;
166911
167158
  var unquote2 = (v) => v.length >= 2 && v.startsWith('"') && v.endsWith('"') ? v.slice(1, -1).replace(/\\"/g, '"') : v;
166912
167159
  function parseSearch2(query11, where2) {
166913
- const tokens2 = [];
167160
+ const tokens3 = [];
166914
167161
  for (let i = 0; i < query11.length; ) {
166915
167162
  if (/\s/.test(query11[i])) {
166916
167163
  i++;
@@ -166925,11 +167172,11 @@ function parseSearch2(query11, where2) {
166925
167172
  else if (!quoted3 && depth <= 0 && /\s/.test(ch)) break;
166926
167173
  }
166927
167174
  if (quoted3) fail5(400, `Error parsing search query: Missing closing quote in ${query11.slice(i, j)}`);
166928
- tokens2.push(query11.slice(i, j));
167175
+ tokens3.push(query11.slice(i, j));
166929
167176
  i = j;
166930
167177
  }
166931
167178
  const filters = [], text24 = [];
166932
- for (const token2 of tokens2) {
167179
+ for (const token2 of tokens3) {
166933
167180
  if (token2 === "OR" || token2 === "AND") {
166934
167181
  if (where2 === "issues") fail5(400, 'Error parsing search query: Boolean statements containing "OR" or "AND" are not supported in this search');
166935
167182
  unsupported32("OR and AND in the events query");
@@ -168341,8 +168588,8 @@ function formulaJson(value5) {
168341
168588
  return { error: "#ERROR!" };
168342
168589
  }
168343
168590
  function sameCells(a, b) {
168344
- const norm = (cells) => JSON.stringify(Object.keys(cells).sort().map((key3) => [key3, cells[key3]]));
168345
- return norm(a) === norm(b);
168591
+ const norm2 = (cells) => JSON.stringify(Object.keys(cells).sort().map((key3) => [key3, cells[key3]]));
168592
+ return norm2(a) === norm2(b);
168346
168593
  }
168347
168594
 
168348
168595
  // packages/server/src/twins/airtable/routes.ts
@@ -168553,8 +168800,8 @@ function updateRecords(call3, replace) {
168553
168800
  return json29({ records: rows33.map((row) => model2.recordJson(row, { byId: byId2 })), ...merge3 && { createdRecords: created2, updatedRecords: updated } });
168554
168801
  }
168555
168802
  function sameValue(stored, wanted) {
168556
- const norm = (value5) => JSON.stringify(Array.isArray(value5) ? value5.map(String).sort() : value5 ?? null);
168557
- return norm(stored) === norm(wanted);
168803
+ const norm2 = (value5) => JSON.stringify(Array.isArray(value5) ? value5.map(String).sort() : value5 ?? null);
168804
+ return norm2(stored) === norm2(wanted);
168558
168805
  }
168559
168806
  function updateRecord3(call3, replace) {
168560
168807
  const { model: model2, table: table3 } = writable3(call3, false), body6 = call3.body;
@@ -172605,10 +172852,10 @@ ${lastErrors.slice(0, 20).join("\n")}`, {
172605
172852
  var DEFAULT_START_TIME = "2026-11-03T16:00:00Z";
172606
172853
  var GENERATOR = "ancha world gen";
172607
172854
  function slugify4(text24, max = 48) {
172608
- const slug12 = text24.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "world";
172609
- if (slug12.length <= max) return slug12;
172610
- const cut = slug12.slice(0, max + 1).lastIndexOf("-");
172611
- return slug12.slice(0, cut > 20 ? cut : max);
172855
+ const slug13 = text24.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "world";
172856
+ if (slug13.length <= max) return slug13;
172857
+ const cut = slug13.slice(0, max + 1).lastIndexOf("-");
172858
+ return slug13.slice(0, cut > 20 ? cut : max);
172612
172859
  }
172613
172860
  var hours = (days, hour2 = 0) => `-${days * 24 + hour2}h`;
172614
172861
  function assembleWorld(input2) {
@@ -174327,6 +174574,68 @@ import { basename as basename5, dirname as dirname6, join as join7, resolve as r
174327
174574
  // backend/src/harness-issues.ts
174328
174575
  init_src();
174329
174576
 
174577
+ // backend/src/actions.ts
174578
+ var writeTools = (scene2) => new Set(Object.entries(scene2.tools ?? {}).filter(([, tool]) => tool.write).map(([name5]) => name5));
174579
+ function actionsOf(scene2, trace) {
174580
+ const writes2 = writeTools(scene2);
174581
+ return trace.flatMap((entry3) => {
174582
+ if (entry3.service !== "tools" || entry3.source !== "agent" || !entry3.path.startsWith("/tools/")) return [];
174583
+ const tool = decodeURIComponent(entry3.path.slice("/tools/".length));
174584
+ if (!writes2.has(tool)) return [];
174585
+ const response5 = entry3.response ?? {};
174586
+ return [{ tool, args: entry3.request?.args ?? {}, source: typeof response5.source === "string" ? response5.source : "unknown", ...typeof response5.error === "string" && { error: response5.error } }];
174587
+ });
174588
+ }
174589
+ function answersOf(trace) {
174590
+ const answers = {};
174591
+ for (const entry3 of trace) {
174592
+ if (entry3.service !== "tools" || entry3.source !== "agent" || !entry3.path.startsWith("/tools/")) continue;
174593
+ const source = entry3.response?.source;
174594
+ if (typeof source === "string") answers[source] = (answers[source] ?? 0) + 1;
174595
+ }
174596
+ return answers;
174597
+ }
174598
+ function answerCounts(trials) {
174599
+ const counted2 = trials.filter((trial) => trial.answers !== void 0);
174600
+ if (!counted2.length) return void 0;
174601
+ const bySource = {};
174602
+ for (const trial of counted2) for (const [source, n] of Object.entries(trial.answers)) bySource[source] = (bySource[source] ?? 0) + n;
174603
+ return { of: counted2.length, simulatedIn: counted2.filter((trial) => (trial.answers.simulated ?? 0) > 0).length, bySource };
174604
+ }
174605
+ function canonicalJson2(value5) {
174606
+ if (Array.isArray(value5)) return `[${value5.map(canonicalJson2).join(",")}]`;
174607
+ if (value5 && typeof value5 === "object") return `{${Object.keys(value5).sort().map((key3) => `${JSON.stringify(key3)}:${canonicalJson2(value5[key3])}`).join(",")}}`;
174608
+ return JSON.stringify(value5 ?? null);
174609
+ }
174610
+ var keyOf = (action) => `${action.tool} ${canonicalJson2(action.args)}`;
174611
+ function actionCounts(trials) {
174612
+ const counted2 = trials.filter((trial) => trial.actions !== void 0);
174613
+ if (!counted2.length) return void 0;
174614
+ const made = /* @__PURE__ */ new Map();
174615
+ for (const trial of counted2) {
174616
+ for (const key3 of new Set(trial.actions.map(keyOf))) {
174617
+ const action = trial.actions.find((a) => keyOf(a) === key3);
174618
+ const entry3 = made.get(key3) ?? { tool: action.tool, args: action.args, trials: 0 };
174619
+ entry3.trials++;
174620
+ made.set(key3, entry3);
174621
+ }
174622
+ }
174623
+ return { of: counted2.length, made: [...made.values()].sort((a, b) => b.trials - a.trials || a.tool.localeCompare(b.tool)) };
174624
+ }
174625
+ function actionChanges(before, after) {
174626
+ if (!before?.of || !after?.of) return [];
174627
+ const was = new Map(before.made.map((a) => [keyOf(a), a])), now10 = new Map(after.made.map((a) => [keyOf(a), a]));
174628
+ const share = (c) => c.trials / c.of;
174629
+ return [.../* @__PURE__ */ new Set([...was.keys(), ...now10.keys()])].map((key3) => {
174630
+ const action = now10.get(key3) ?? was.get(key3);
174631
+ return { tool: action.tool, args: action.args, before: { trials: was.get(key3)?.trials ?? 0, of: before.of }, after: { trials: now10.get(key3)?.trials ?? 0, of: after.of } };
174632
+ }).filter((c) => c.before.trials * c.after.of !== c.after.trials * c.before.of).sort((a, b) => Math.abs(share(b.after) - share(b.before)) - Math.abs(share(a.after) - share(a.before)) || a.tool.localeCompare(b.tool));
174633
+ }
174634
+ function actionLabel(action) {
174635
+ const args = canonicalJson2(action.args);
174636
+ return `${action.tool} ${args.length > 120 ? `${args.slice(0, 117)}...` : args}`;
174637
+ }
174638
+
174330
174639
  // backend/src/report.ts
174331
174640
  init_src();
174332
174641
  var MAX_FAILURES_PER_SCENE = 20;
@@ -174378,7 +174687,7 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
174378
174687
  if (harnessIssues.length < MAX_FAILURES_PER_SCENE) harnessIssues.push({ ...issue5, sceneId, trial: t.trial });
174379
174688
  }
174380
174689
  if (!t.passed && t.exit !== "invalid" && !exitedCleanly(t) && agentIssues.length < MAX_FAILURES_PER_SCENE) {
174381
- agentIssues.push({ sceneId, trial: t.trial, exit: t.exit, exitCode: t.exitCode, realMs: t.realMs, log: join7(t.dir, "agent.log"), logTail: t.logTail });
174690
+ agentIssues.push({ sceneId, trial: t.trial, exit: t.exit, exitCode: t.exitCode, realMs: t.realMs, log: join7(t.dir, "agent.log"), logTail: t.logTail, ...t.invocations !== void 0 && { invocations: t.invocations } });
174382
174691
  }
174383
174692
  for (const c of t.checks) {
174384
174693
  const tally = checks[c.id] ??= { passed: 0, total: 0, required: c.required };
@@ -174414,6 +174723,7 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
174414
174723
  }
174415
174724
  }
174416
174725
  const passed = counts.passed;
174726
+ const actions = actionCounts(trials.filter(trialValid)), answers = answerCounts(trials.filter(trialValid));
174417
174727
  return {
174418
174728
  sceneId,
174419
174729
  counts,
@@ -174431,6 +174741,8 @@ function summarizeScene(sceneId, trials, requestedTrials = trials.length) {
174431
174741
  coverageGaps: [...gaps2.values()],
174432
174742
  meanRealMs: trials.length === 0 ? 0 : Math.round(totalMs / trials.length),
174433
174743
  agentCalls: agentCalls2,
174744
+ ...actions !== void 0 && { actions },
174745
+ ...answers !== void 0 && { answers },
174434
174746
  trialsDetail: trials.map((t) => ({ trial: t.trial, passed: outcomeOf2(t) === "passed", valid: trialValid(t), ...outcomeOf2(t) === "skipped" ? { outcome: "skipped" } : t.outcome ? { outcome: t.outcome } : {}, ...t.checks.some((c) => c.status === "skipped") && { skippedJudges: t.checks.filter((c) => c.status === "skipped").length }, exit: t.exit, exitCode: t.exitCode, realMs: t.realMs, ...t.simMs !== void 0 && { simMs: t.simMs }, ...t.playOut !== void 0 && { playOut: t.playOut }, ...t.sessionId !== void 0 && { sessionId: t.sessionId }, dir: t.dir }))
174435
174747
  };
174436
174748
  }
@@ -174490,6 +174802,8 @@ function formatRateDelta(value5) {
174490
174802
  return `${value5 > 0 ? "+" : value5 < 0 ? "-" : ""}${rounded === 0 && magnitude > 0 ? magnitude.toPrecision(3) : rounded} pp`;
174491
174803
  }
174492
174804
  var SUMMARY_GAPS_SHOWN = 10;
174805
+ var SUMMARY_ACTIONS_SHOWN = 8;
174806
+ var ANSWER_SOURCES = [["replayed", "replayed"], ["replayed-elsewhere", "replayed from another conversation"], ["twin", "by twins"], ["ran", "ran the tool itself"], ["simulated", "simulated"], ["failed", "failed"]];
174493
174807
  var duration8 = (ms3) => ms3 < 1e3 ? `${ms3}ms` : `${(ms3 / 1e3).toFixed(1)}s`;
174494
174808
  function howItEnded(i) {
174495
174809
  switch (i.exit) {
@@ -174497,8 +174811,10 @@ function howItEnded(i) {
174497
174811
  return `timed out after ${duration8(i.realMs)} and was killed`;
174498
174812
  case "spawn_failed":
174499
174813
  return i.exitCode === null ? "could not be started" : `failed to start (exit code ${i.exitCode})`;
174500
- default:
174501
- return i.exitCode === null ? `was killed by a signal after ${duration8(i.realMs)}` : `exited with code ${i.exitCode} after ${duration8(i.realMs)}`;
174814
+ default: {
174815
+ const when13 = i.invocations?.failed ? `on ${i.invocations.failed} of ${i.invocations.total} events` : `after ${duration8(i.realMs)}`;
174816
+ return i.exitCode === null ? `was killed by a signal ${when13}` : `exited with code ${i.exitCode} ${when13}`;
174817
+ }
174502
174818
  }
174503
174819
  }
174504
174820
  var shellWord = (dir2) => /^[\w./@%+=:,-]+$/.test(dir2) ? dir2 : `'${dir2.replaceAll("'", `'\\''`)}'`;
@@ -174543,6 +174859,17 @@ function renderSummaryText(s, opts = {}) {
174543
174859
  if (scene2.coverageGaps.length > SUMMARY_GAPS_SHOWN) {
174544
174860
  lines.push(` \u2026 ${scene2.coverageGaps.length - SUMMARY_GAPS_SHOWN} more coverage gap(s)`);
174545
174861
  }
174862
+ if (scene2.answers !== void 0) {
174863
+ const { of, simulatedIn, bySource } = scene2.answers;
174864
+ const named3 = ANSWER_SOURCES.filter(([source]) => bySource[source]).map(([source, label5]) => `${bySource[source]} ${label5}`);
174865
+ if (named3.length) lines.push(` tool answers: ${named3.join(", ")}; ${simulatedIn}/${of} verdicts rest on simulated answers`);
174866
+ }
174867
+ if (scene2.actions !== void 0) {
174868
+ const { of, made } = scene2.actions, trials = `${of} valid ${of === 1 ? "trial" : "trials"}`;
174869
+ lines.push(made.length ? ` writes, in how many of ${trials}:` : ` writes: none in ${trials}`);
174870
+ for (const action of made.slice(0, SUMMARY_ACTIONS_SHOWN)) lines.push(` ${action.trials}/${of} ${actionLabel(action)}`);
174871
+ if (made.length > SUMMARY_ACTIONS_SHOWN) lines.push(` \u2026 ${made.length - SUMMARY_ACTIONS_SHOWN} more`);
174872
+ }
174546
174873
  }
174547
174874
  lines.push("");
174548
174875
  if (s.comparison !== void 0) {
@@ -174552,6 +174879,8 @@ function renderSummaryText(s, opts = {}) {
174552
174879
  for (const scene2 of s.comparison.scenes) {
174553
174880
  lines.push(` ${scene2.sceneId}: ${pct(scene2.before)}% \u2192 ${pct(scene2.after)}% (${formatRateDelta(scene2.delta)})${scene2.beforeTrials === void 0 || scene2.afterTrials === void 0 ? "" : `; ${scene2.beforeTrials} \u2192 ${scene2.afterTrials} trials`}`);
174554
174881
  for (const check4 of (scene2.checks ?? []).filter((c) => c.delta > 0 || !c.required)) lines.push(` ${check4.delta > 0 ? "improved" : "optional, dropped"}: ${check4.check} ${counts(check4)}`);
174882
+ for (const action of (scene2.actions ?? []).slice(0, SUMMARY_ACTIONS_SHOWN)) lines.push(` write: ${actionLabel(action)} ${action.before.trials}/${action.before.of} \u2192 ${action.after.trials}/${action.after.of} trials`);
174883
+ if ((scene2.actions ?? []).length > SUMMARY_ACTIONS_SHOWN) lines.push(` \u2026 ${scene2.actions.length - SUMMARY_ACTIONS_SHOWN} more changed writes`);
174555
174884
  }
174556
174885
  }
174557
174886
  lines.push(`${s.pytest && !s.pytest.graded && !s.pytest.invalid ? s.pytest.outcome + " (ungraded)" : s.verdict} (minimum pass rate ${pct(s.minPassRate)}%) run ${s.runId}`);
@@ -177349,9 +177678,9 @@ function writeTar(entries2, mtimeMs) {
177349
177678
  }
177350
177679
 
177351
177680
  // packages/cli/src/run-upload.ts
177352
- async function uploadWorkspace(ctx) {
177681
+ async function uploadWorkspace(ctx, missing6 = { message: "--upload needs a workspace", hint: "run ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY" }) {
177353
177682
  const url3 = ctx.globals().local ? (await ctx.loadConfig()).server?.url || ctx.io.env.ANCHA_SERVER_URL || await defaultServerUrl(ctx.io.env) : (await serverChoice(ctx)).url;
177354
- if (url3 === void 0) throw new AnchaError("USAGE", "--upload needs a workspace", { hint: "run ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY" });
177683
+ if (url3 === void 0) throw new AnchaError("USAGE", missing6.message, { hint: missing6.hint });
177355
177684
  try {
177356
177685
  return normalizeServerUrl(url3);
177357
177686
  } catch {
@@ -177416,7 +177745,7 @@ async function reproductionOf(summary, scenePaths, cwd, runDir) {
177416
177745
  return here === void 0 ? [] : [{ check: check4, production: result, failed: here.total - here.passed, total: here.total }];
177417
177746
  });
177418
177747
  const failedThere = checks.filter((c) => c.production === "failed");
177419
- const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : "matches";
177748
+ const verdict = failedThere.length > 0 ? failedThere.every((c) => c.failed * 2 > c.total) ? "reproduced" : failedThere.some((c) => c.failed > 0) ? "partly" : "not-reproduced" : checks.some((c) => c.production === "passed" && c.failed > 0) ? "differs" : checks.some((c) => c.production === "passed") ? "matches" : "unknown";
177420
177749
  const added = Object.keys(scene2.checks).filter((check4) => !(check4 in production3.checks));
177421
177750
  const counts = {};
177422
177751
  for (const a of answers.filter((x) => x.scene === scene2.sceneId)) for (const [source, n] of Object.entries(a.counts)) counts[source] = (counts[source] ?? 0) + n;
@@ -177429,7 +177758,8 @@ var SAY = {
177429
177758
  partly: "production's failure happens here in part",
177430
177759
  "not-reproduced": "production's failure did not happen here: the agent is fixed, or the world differs from production (see questions.json next to the scene)",
177431
177760
  matches: "this run matches production, which passed these checks",
177432
- differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)"
177761
+ differs: "checks production passed failed here: a regression, or the world differs from production (see questions.json)",
177762
+ unknown: "set OPENROUTER_API_KEY and run again: a model grades these checks on production's record and on this run"
177433
177763
  };
177434
177764
  function renderReproduction(reproductions) {
177435
177765
  return reproductions.map((r) => {
@@ -177441,9 +177771,11 @@ function renderReproduction(reproductions) {
177441
177771
  ...rows33,
177442
177772
  `=> ${SAY[r.verdict]}`,
177443
177773
  ...also.length > 0 ? [` also failing here, though production passed: ${also.join(", ")}`] : [],
177774
+ // A failure here on a check production is not graded on yet is neither a match nor a regression: say how to grade both.
177775
+ ...r.verdict !== "unknown" && r.checks.some((c) => c.production === "unknown" && c.failed > 0) ? [` set OPENROUTER_API_KEY to grade ${r.checks.filter((c) => c.production === "unknown" && c.failed > 0).map((c) => c.check).join(", ")} on production's record and here`] : [],
177444
177776
  ...r.added.length > 0 ? [` checks added after saving, with no production result: ${r.added.join(", ")}`] : [],
177445
177777
  // How much of the run stood on production's own answers (TRACE_PLAN_V2 §8.6).
177446
- ...r.answers ? [` answers to the agent's tools: ${["replayed", "twin", "simulated", "failed"].filter((s) => r.answers[s]).map((s) => `${r.answers[s]} ${s}`).join(", ")}${r.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : []
177778
+ ...r.answers ? [` answers to the agent's tools: ${["replayed", "replayed-elsewhere", "twin", "ran", "simulated", "failed"].filter((s) => r.answers[s]).map((s) => `${r.answers[s]} ${s}`).join(", ")}${r.answers.simulated ? "; simulated answers took the agent where production never went (ancha explain lists them)" : ""}`] : []
177447
177779
  ].join("\n");
177448
177780
  }).join("\n\n");
177449
177781
  }
@@ -200740,11 +201072,11 @@ _a6 = brand_privateBedrockClient;
200740
201072
 
200741
201073
  // backend/src/judge/openrouter.ts
200742
201074
  var DEFAULT_JUDGE_MODEL = "anthropic/claude-haiku-5.5";
200743
- async function requestGrade(apiKey, model2, rubric, evidence, signal) {
201075
+ async function requestGrade(apiKey, model2, rubric, evidence, signal, baseUrl = "https://openrouter.ai/api/v1") {
200744
201076
  signal?.throwIfAborted();
200745
201077
  const client = new OpenAI({
200746
201078
  apiKey,
200747
- baseURL: "https://openrouter.ai/api/v1",
201079
+ baseURL: baseUrl,
200748
201080
  adminAPIKey: null,
200749
201081
  organization: null,
200750
201082
  project: null,
@@ -200893,7 +201225,7 @@ async function evaluateJudges(scene2, capture4, options3) {
200893
201225
  continue;
200894
201226
  }
200895
201227
  try {
200896
- const response5 = await requestGrade(key3, model2, check4.judge.replaceAll(key3, "[redacted]"), evidence.json, options3.signal);
201228
+ const response5 = await requestGrade(key3, model2, check4.judge.replaceAll(key3, "[redacted]"), evidence.json, options3.signal, options3.baseUrl);
200897
201229
  options3.signal?.throwIfAborted();
200898
201230
  const choice4 = response5.choices[0];
200899
201231
  if (response5.choices.length !== 1 || choice4?.finish_reason !== "stop" || choice4.message.refusal || typeof choice4.message.content !== "string") throw new Error("missing, refused or truncated structured grade");
@@ -201647,7 +201979,7 @@ async function runPerEventTrial(spec) {
201647
201979
  signal?.throwIfAborted();
201648
201980
  const logFd = openSync3(join26(dir2, "agent.log"), "w");
201649
201981
  const startedAt = performance.now();
201650
- let timedOut = false, spawnFailed = false, firstFailure = null, invocations = 0;
201982
+ let timedOut = false, spawnFailed = false, firstFailure, invocations = 0, failedInvocations = 0;
201651
201983
  let failure5;
201652
201984
  try {
201653
201985
  await backend.startTrial(env2.id, session.id);
@@ -201685,8 +202017,9 @@ async function runPerEventTrial(spec) {
201685
202017
  spawnFailed = true;
201686
202018
  writeSync3(logFd, `ancha: could not start the agent: ${outcome4.error.message}
201687
202019
  `);
201688
- } else if (outcome4.kind === "exit" && outcome4.code !== 0) {
201689
- firstFailure ??= outcome4.code;
202020
+ } else if (outcome4.kind === "exit" && outcome4.code !== 0 && !timedOut) {
202021
+ failedInvocations++;
202022
+ if (firstFailure === void 0) firstFailure = outcome4.code;
201690
202023
  if (outcome4.code === EXIT_COMMAND_NOT_FOUND) spawnFailed = true;
201691
202024
  }
201692
202025
  } finally {
@@ -201721,7 +202054,7 @@ async function runPerEventTrial(spec) {
201721
202054
  if (failure5 !== void 0) throw failure5.error;
201722
202055
  signal?.throwIfAborted();
201723
202056
  const exit = spawnFailed ? "spawn_failed" : timedOut ? "timeout" : "exited";
201724
- const exitCode = spawnFailed ? EXIT_COMMAND_NOT_FOUND : firstFailure ?? 0;
202057
+ const exitCode = spawnFailed ? EXIT_COMMAND_NOT_FOUND : firstFailure === void 0 ? 0 : firstFailure;
201725
202058
  return {
201726
202059
  valid: !harnessIssues.some((issue5) => issue5.owner === "harness"),
201727
202060
  harnessIssues,
@@ -201734,8 +202067,9 @@ async function runPerEventTrial(spec) {
201734
202067
  realMs,
201735
202068
  simMs,
201736
202069
  checks,
201737
- logTail: exit === "exited" && exitCode === 0 ? [] : await logTail2(join26(dir2, "agent.log")),
201738
- passed: checks.every((c) => !c.required || c.passed),
202070
+ invocations: { total: invocations, failed: failedInvocations },
202071
+ logTail: exit === "exited" && failedInvocations === 0 ? [] : await logTail2(join26(dir2, "agent.log")),
202072
+ passed: failedInvocations === 0 && checks.every((c) => !c.required || c.passed),
201739
202073
  trace,
201740
202074
  dir: dir2,
201741
202075
  taskDelivery
@@ -202139,6 +202473,8 @@ async function executeRun(opts) {
202139
202473
  }
202140
202474
  result.caseId = item2.id;
202141
202475
  result.attemptId = attempt.id;
202476
+ if (writeTools(item2.scene).size) result.actions = actionsOf(item2.scene, result.trace);
202477
+ if (Object.keys(item2.scene.tools ?? {}).length) result.answers = answersOf(result.trace);
202142
202478
  if (result.exit !== "invalid") {
202143
202479
  if (!observedAgentExit && result.exit === "spawn_failed") halt.spawnFailure = result;
202144
202480
  observedAgentExit = true;
@@ -202369,7 +202705,8 @@ function compareSummaries(current, baseline) {
202369
202705
  droppedChecks.push(delta2);
202370
202706
  }
202371
202707
  }
202372
- return { sceneId: scene2.sceneId, before: beforeScene.passed / beforeTrials, after: scene2.passed / afterTrials, delta: Number(numerator) / Number(denominator), beforeTrials, afterTrials, ...checks.length > 0 && { checks } };
202708
+ const actions = actionChanges(beforeScene.actions, scene2.actions);
202709
+ return { sceneId: scene2.sceneId, before: beforeScene.passed / beforeTrials, after: scene2.passed / afterTrials, delta: Number(numerator) / Number(denominator), beforeTrials, afterTrials, ...checks.length > 0 && { checks }, ...actions.length > 0 && { actions } };
202373
202710
  });
202374
202711
  return { baselineRunId: baseline.runId, regressed, droppedChecks, scenes };
202375
202712
  }
@@ -202453,7 +202790,7 @@ async function interruptible(ctx, fn) {
202453
202790
  }
202454
202791
  }
202455
202792
  function registerRun(program2, ctx) {
202456
- program2.command("run").description("run an agent against scenes N times and summarize how often it passes (starts its own server unless one is configured)").argument("[scenes...]", "scene YAML files (default: the globs in scenes: of ancha.yaml)").option("--agent <cmd>", "shell command that runs the agent (default: agent.command in ancha.yaml)").option("--agent-url <url>", "endpoint URL (overrides agent.url; requires endpoint setup/start configuration)").option("-n, --trials <n>", "trials per scene (default: trials in ancha.yaml, else 5)").option("--parallel <n>", "trials running at once (default: parallel in ancha.yaml, else command 2 / endpoint 1)").option("--min-pass-rate <r>", "fraction of trials that must pass, 0 to 1 (default: min_pass_rate in ancha.yaml, else 1)").option("--seed <seed>", "seed for ids and randomness").option("--out <dir>", "where run directories go (default: .ancha/runs)").option("--strict", "exit 4 if the agent hit an endpoint Ancha does not implement").option("--detach", "continue in a private worker after this command exits; observe with status/wait").option("--compare <reference>", "compare against a completed run id or saved baseline; any per-scene decrease fails").option("--pass-env <name>", "give the agent this variable from this shell (repeatable); it otherwise gets only a base set (PATH, HOME, locale\u2026) plus Ancha's and the tools' variables", (name5, names3) => [...names3, name5], []).option("--inherit-env", "give the agent this shell's whole environment, including any real credentials (the behavior before 0.1.2)").option("--on <target>", "where the agent runs: local (a process on this computer), docker (a sealed container; needs agent.execution with an image in ancha.yaml) or cloud (scene/test import is currently unsupported; use local/CI or an explicit saved-world task via runs start). Default: what ancha.yaml says").option("--idempotency-key <key>", "retry safely: the same key and the same run definition return the original run instead of starting another").option("--upload", "send the finished run to your workspace, where the console shows it (also ANCHA_UPLOAD=1); a failed upload is a warning").option("--upload-required", "like --upload, but a failed upload fails the command").option("--dry-run", "check ancha.yaml and every scene, print what would run, and stop: no server, no agent, no trial").option("--allow-unwrapped <tools>", "in a test made from a trace, let the agent call these tools for real instead of stopping because it does not wrap them (comma-separated, repeatable)", (value5, all8 = []) => [...all8, ...value5.split(",").map((s) => s.trim()).filter(Boolean)]).action(async (sceneArgs, opts, command) => {
202793
+ program2.command("run").description("run an agent against scenes N times and summarize how often it passes (starts its own server unless one is configured)").argument("[scenes...]", "scene YAML files (default: the globs in scenes: of ancha.yaml)").option("--agent <cmd>", "shell command that runs the agent (default: agent.command in ancha.yaml)").option("--agent-url <url>", "endpoint URL (overrides agent.url; requires endpoint setup/start configuration)").option("-n, --trials <n>", "trials per scene (default: trials in ancha.yaml, else 5)").option("--parallel <n>", "trials running at once (default: parallel in ancha.yaml, else command 2 / endpoint 1)").option("--min-pass-rate <r>", "fraction of trials that must pass, 0 to 1 (default: min_pass_rate in ancha.yaml, else 1)").option("--seed <seed>", "seed for ids and randomness").option("--out <dir>", "where run directories go (default: .ancha/runs)").option("--strict", "exit 4 if the agent hit an endpoint Ancha does not implement").option("--detach", "continue in a private worker after this command exits; observe with status/wait").option("--compare <reference>", "compare against a completed run id or saved baseline; any per-scene decrease fails").option("--pass-env <name>", "give the agent this variable from this shell (repeatable); it otherwise gets only a base set (PATH, HOME, locale\u2026) plus Ancha's and the tools' variables", (name5, names3) => [...names3, name5], []).option("--inherit-env", "give the agent this shell's whole environment, including any real credentials (the behavior before 0.1.2)").option("--on <target>", "where the agent runs: local (a process on this computer) or docker (a sealed container; needs agent.execution with an image in ancha.yaml). Default: what ancha.yaml says. To run in your workspace, start a saved world's task with ancha runs start").option("--idempotency-key <key>", "retry safely: the same key and the same run definition return the original run instead of starting another").option("--upload", "send the finished run to your workspace, where the console shows it (also ANCHA_UPLOAD=1); a failed upload is a warning").option("--upload-required", "like --upload, but a failed upload fails the command").option("--dry-run", "check ancha.yaml and every scene, print what would run, and stop: no server, no agent, no trial").option("--allow-unwrapped <tools>", "in a test made from a trace, let the agent call these tools for real instead of stopping because it does not wrap them (comma-separated, repeatable)", (value5, all8 = []) => [...all8, ...value5.split(",").map((s) => s.trim()).filter(Boolean)]).action(async (sceneArgs, opts, command) => {
202457
202794
  const { cwd } = ctx.io;
202458
202795
  if (opts.agent === void 0 && opts.agentUrl === void 0 && ctx.globals().config === void 0 && !await access4(resolve23(cwd, "ancha.yaml")).then(() => true, () => false)) {
202459
202796
  throw new AnchaError("USAGE", "no ancha.yaml here", { hint: 'run `ancha init` in your agent\'s project, or pass --agent "<command>"' });
@@ -202532,9 +202869,9 @@ function registerRun(program2, ctx) {
202532
202869
  const workspace3 = workspaceOf(choice4.url, cwd);
202533
202870
  let relay;
202534
202871
  if (serverUrl3 === void 0 && scenes.some((scene2) => (scene2.people?.length ?? 0) > 0 || Object.keys(scene2.tools ?? {}).length > 0)) {
202535
- const access7 = await modelAccess(ctx.io.env);
202536
- if (access7.kind === "relay") {
202537
- relay = { baseUrl: access7.baseUrl, apiKey: access7.apiKey };
202872
+ const access8 = await modelAccess(ctx.io.env);
202873
+ if (access8.kind === "relay") {
202874
+ relay = { baseUrl: access8.baseUrl, apiKey: access8.apiKey };
202538
202875
  ctx.out.info(RELAY_NOTICE);
202539
202876
  }
202540
202877
  }
@@ -202544,7 +202881,11 @@ function registerRun(program2, ctx) {
202544
202881
  trials,
202545
202882
  parallel,
202546
202883
  minPassRate,
202547
- judge: { ...ctx.io.env.OPENROUTER_API_KEY !== void 0 && { apiKey: ctx.io.env.OPENROUTER_API_KEY }, ...config9.judge?.model !== void 0 && { model: config9.judge.model } },
202884
+ judge: {
202885
+ ...ctx.io.env.OPENROUTER_API_KEY !== void 0 && { apiKey: ctx.io.env.OPENROUTER_API_KEY },
202886
+ ...config9.judge?.model !== void 0 && { model: config9.judge.model },
202887
+ ...ctx.io.env.ANCHA_JUDGE_BASE_URL !== void 0 && { baseUrl: ctx.io.env.ANCHA_JUDGE_BASE_URL }
202888
+ },
202548
202889
  ...opts.seed !== void 0 && { seed: opts.seed },
202549
202890
  ...opts.out !== void 0 && { out: opts.out },
202550
202891
  ...opts.strict !== void 0 && { strict: opts.strict },
@@ -203173,9 +203514,9 @@ function registerReplay(program2, ctx) {
203173
203514
  let relay;
203174
203515
  let canAnswer = choice4.url !== void 0;
203175
203516
  if (choice4.url === void 0 && hasPeople) {
203176
- const access7 = await modelAccess(ctx.io.env);
203177
- canAnswer = access7.kind !== "none";
203178
- if (access7.kind === "relay") relay = { baseUrl: access7.baseUrl, apiKey: access7.apiKey };
203517
+ const access8 = await modelAccess(ctx.io.env);
203518
+ canAnswer = access8.kind !== "none";
203519
+ if (access8.kind === "relay") relay = { baseUrl: access8.baseUrl, apiKey: access8.apiKey };
203179
203520
  }
203180
203521
  if (opts.people === "live" && hasPeople && !canAnswer) {
203181
203522
  throw new AnchaError("USAGE", "people can't answer live here: there is no model for them", { hint: "run ancha login, set OPENROUTER_API_KEY, or replay with --people strict" });
@@ -203202,7 +203543,11 @@ function registerReplay(program2, ctx) {
203202
203543
  runId: state3.runId,
203203
203544
  signal,
203204
203545
  inheritedEnv: ctx.io.env,
203205
- judge: { ...ctx.io.env.OPENROUTER_API_KEY !== void 0 && { apiKey: ctx.io.env.OPENROUTER_API_KEY }, ...config9.judge?.model !== void 0 && { model: config9.judge.model } },
203546
+ judge: {
203547
+ ...ctx.io.env.OPENROUTER_API_KEY !== void 0 && { apiKey: ctx.io.env.OPENROUTER_API_KEY },
203548
+ ...config9.judge?.model !== void 0 && { model: config9.judge.model },
203549
+ ...ctx.io.env.ANCHA_JUDGE_BASE_URL !== void 0 && { baseUrl: ctx.io.env.ANCHA_JUDGE_BASE_URL }
203550
+ },
203206
203551
  onEvent: (event3) => {
203207
203552
  if (event3.event === "trial_finished") writer.trialFinished();
203208
203553
  const shown = event3.event === "run_started" ? { ...event3, replayOf: attempt.id, ...where2 } : event3;
@@ -203400,7 +203745,11 @@ function registerSimulate(sceneCommand, ctx) {
203400
203745
  trials: 1,
203401
203746
  parallel: 1,
203402
203747
  seed: seed40,
203403
- judge: { ...ctx.io.env.OPENROUTER_API_KEY !== void 0 && { apiKey: ctx.io.env.OPENROUTER_API_KEY }, ...config9.judge?.model !== void 0 && { model: config9.judge.model } },
203748
+ judge: {
203749
+ ...ctx.io.env.OPENROUTER_API_KEY !== void 0 && { apiKey: ctx.io.env.OPENROUTER_API_KEY },
203750
+ ...config9.judge?.model !== void 0 && { model: config9.judge.model },
203751
+ ...ctx.io.env.ANCHA_JUDGE_BASE_URL !== void 0 && { baseUrl: ctx.io.env.ANCHA_JUDGE_BASE_URL }
203752
+ },
203404
203753
  outDir: resolve29(ctx.io.cwd, DEFAULT_RUNS_DIR),
203405
203754
  inheritedEnv: ctx.io.env,
203406
203755
  signal,
@@ -204231,11 +204580,11 @@ import { dirname as dirname15, join as join40, relative as relative9, resolve as
204231
204580
  async function model(ctx) {
204232
204581
  const env2 = ctx.io.env;
204233
204582
  if (env2.ANCHA_PEOPLE_BASE_URL && env2.ANCHA_PEOPLE_API_KEY) return { client: gen_exports.openRouterClient({ apiKey: env2.ANCHA_PEOPLE_API_KEY, baseUrl: env2.ANCHA_PEOPLE_BASE_URL, relay: true }), credit: "own" };
204234
- const access7 = await modelAccess(env2);
204235
- if (access7.kind === "own") return { client: gen_exports.openRouterClient({ apiKey: access7.apiKey }), credit: "own" };
204236
- if (access7.kind === "relay") {
204583
+ const access8 = await modelAccess(env2);
204584
+ if (access8.kind === "own") return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey }), credit: "own" };
204585
+ if (access8.kind === "relay") {
204237
204586
  ctx.out.info(RELAY_NOTICE);
204238
- return { client: gen_exports.openRouterClient({ apiKey: access7.apiKey, baseUrl: access7.baseUrl, relay: true }), credit: "workspace" };
204587
+ return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey, baseUrl: access8.baseUrl, relay: true }), credit: "workspace" };
204239
204588
  }
204240
204589
  throw new AnchaError("CONFIG_INVALID", "world gen needs a model key", { hint: "set OPENROUTER_API_KEY, or log in to your workspace with ancha login, then run the same command again" });
204241
204590
  }
@@ -204557,11 +204906,11 @@ ${(0, import_yaml11.stringify)(sorted2, { lineWidth: 0 })}`;
204557
204906
  async function draftingModel(ctx) {
204558
204907
  const env2 = ctx.io.env;
204559
204908
  if (env2.ANCHA_PEOPLE_BASE_URL && env2.ANCHA_PEOPLE_API_KEY) return { client: gen_exports.openRouterClient({ apiKey: env2.ANCHA_PEOPLE_API_KEY, baseUrl: env2.ANCHA_PEOPLE_BASE_URL, relay: true }), credit: "own" };
204560
- const access7 = await modelAccess(env2);
204561
- if (access7.kind === "own") return { client: gen_exports.openRouterClient({ apiKey: access7.apiKey }), credit: "own" };
204562
- if (access7.kind === "relay") {
204909
+ const access8 = await modelAccess(env2);
204910
+ if (access8.kind === "own") return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey }), credit: "own" };
204911
+ if (access8.kind === "relay") {
204563
204912
  ctx.out.info(RELAY_NOTICE);
204564
- return { client: gen_exports.openRouterClient({ apiKey: access7.apiKey, baseUrl: access7.baseUrl, relay: true }), credit: "workspace" };
204913
+ return { client: gen_exports.openRouterClient({ apiKey: access8.apiKey, baseUrl: access8.baseUrl, relay: true }), credit: "workspace" };
204565
204914
  }
204566
204915
  throw new AnchaError("CONFIG_INVALID", "test new needs a model key", { hint: "set OPENROUTER_API_KEY, or log in to your workspace with ancha login, then run the same command again" });
204567
204916
  }
@@ -219853,7 +220202,7 @@ var require_formats2 = /* @__PURE__ */ __commonJSMin2(((exports) => {
219853
220202
  function isLeapYear(year) {
219854
220203
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
219855
220204
  }
219856
- const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
220205
+ const DATE2 = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
219857
220206
  const DAYS2 = [
219858
220207
  0,
219859
220208
  31,
@@ -219870,7 +220219,7 @@ var require_formats2 = /* @__PURE__ */ __commonJSMin2(((exports) => {
219870
220219
  31
219871
220220
  ];
219872
220221
  function date10(str4) {
219873
- const matches7 = DATE.exec(str4);
220222
+ const matches7 = DATE2.exec(str4);
219874
220223
  if (!matches7) return false;
219875
220224
  const year = +matches7[1];
219876
220225
  const month = +matches7[2];
@@ -220651,22 +221000,22 @@ async function authInternal(provider, { serverUrl: serverUrl3, authorizationCode
220651
221000
  }, infoCtx);
220652
221001
  return "AUTHORIZED";
220653
221002
  }
220654
- let tokens2 = discardIfIssuerMismatch(await provider.tokens(infoCtx), issuer);
220655
- if (tokens2 && tokens2.issuer === void 0) {
220656
- tokens2 = {
220657
- ...tokens2,
221003
+ let tokens3 = discardIfIssuerMismatch(await provider.tokens(infoCtx), issuer);
221004
+ if (tokens3 && tokens3.issuer === void 0) {
221005
+ tokens3 = {
221006
+ ...tokens3,
220658
221007
  issuer
220659
221008
  };
220660
- await provider.saveTokens(tokens2, infoCtx);
221009
+ await provider.saveTokens(tokens3, infoCtx);
220661
221010
  }
220662
- if (tokens2?.refresh_token && !forceReauthorization) {
220663
- const refreshScope = await provider.scopeForRefresh?.(tokens2);
221011
+ if (tokens3?.refresh_token && !forceReauthorization) {
221012
+ const refreshScope = await provider.scopeForRefresh?.(tokens3);
220664
221013
  let newTokens;
220665
221014
  try {
220666
221015
  newTokens = await refreshAuthorization(authorizationServerUrl, {
220667
221016
  metadata: metadata7,
220668
221017
  clientInformation,
220669
- refreshToken: tokens2.refresh_token,
221018
+ refreshToken: tokens3.refresh_token,
220670
221019
  scope: refreshScope,
220671
221020
  resource: resource2,
220672
221021
  addClientAuthentication: provider.addClientAuthentication,
@@ -220961,7 +221310,7 @@ async function refreshAuthorization(authorizationServerUrl, { metadata: metadata
220961
221310
  refresh_token: refreshToken
220962
221311
  });
220963
221312
  if (scope3) tokenRequestParams.set("scope", scope3);
220964
- const tokens2 = await executeTokenRequest(authorizationServerUrl, {
221313
+ const tokens3 = await executeTokenRequest(authorizationServerUrl, {
220965
221314
  metadata: metadata7,
220966
221315
  tokenRequestParams,
220967
221316
  clientInformation,
@@ -220972,8 +221321,8 @@ async function refreshAuthorization(authorizationServerUrl, { metadata: metadata
220972
221321
  });
220973
221322
  return {
220974
221323
  refresh_token: refreshToken,
220975
- ...tokens2,
220976
- ...scope3 && !tokens2.scope && { scope: scope3 }
221324
+ ...tokens3,
221325
+ ...scope3 && !tokens3.scope && { scope: scope3 }
220977
221326
  };
220978
221327
  }
220979
221328
  async function fetchToken(provider, authorizationServerUrl, { metadata: metadata7, resource: resource2, authorizationCode, iss, scope: scope3, fetchFn } = {}) {
@@ -221052,10 +221401,10 @@ var InMemoryResponseCacheStore = class {
221052
221401
  return this._entries.size;
221053
221402
  }
221054
221403
  get(key3) {
221055
- return this._entries.get(keyOf(key3));
221404
+ return this._entries.get(keyOf2(key3));
221056
221405
  }
221057
221406
  set(key3, entry3) {
221058
- const k = keyOf(key3);
221407
+ const k = keyOf2(key3);
221059
221408
  const exempt = CAP_EXEMPT_METHODS.has(key3.method);
221060
221409
  const isNew = !this._entries.has(k);
221061
221410
  if (!exempt && isNew && this._maxEntries > 0 && this._cappedSize >= this._maxEntries) {
@@ -221074,7 +221423,7 @@ var InMemoryResponseCacheStore = class {
221074
221423
  return stamp5;
221075
221424
  }
221076
221425
  delete(key3) {
221077
- if (this._entries.delete(keyOf(key3)) && !CAP_EXEMPT_METHODS.has(key3.method)) this._cappedSize--;
221426
+ if (this._entries.delete(keyOf2(key3)) && !CAP_EXEMPT_METHODS.has(key3.method)) this._cappedSize--;
221078
221427
  }
221079
221428
  evict(method2) {
221080
221429
  const prefix2 = `${method2}\0`;
@@ -221089,7 +221438,7 @@ var InMemoryResponseCacheStore = class {
221089
221438
  this._cappedSize = 0;
221090
221439
  }
221091
221440
  };
221092
- function keyOf(key3) {
221441
+ function keyOf2(key3) {
221093
221442
  return `${key3.method}\0${JSON.stringify([key3.partition ?? "", key3.params ?? ""])}`;
221094
221443
  }
221095
221444
  function genKey(method2, params9) {
@@ -223648,13 +223997,13 @@ var withDpopFromProvider = (provider) => withDpop(async () => {
223648
223997
  throw markAuthSeamEscape(error64);
223649
223998
  }
223650
223999
  }, async () => {
223651
- let tokens2;
224000
+ let tokens3;
223652
224001
  try {
223653
- tokens2 = await provider.tokens();
224002
+ tokens3 = await provider.tokens();
223654
224003
  } catch (error64) {
223655
224004
  throw markAuthSeamEscape(error64);
223656
224005
  }
223657
- return tokens2?.token_type?.toLowerCase() === "dpop" ? tokens2.access_token : void 0;
224006
+ return tokens3?.token_type?.toLowerCase() === "dpop" ? tokens3.access_token : void 0;
223658
224007
  });
223659
224008
  var SseError = class extends Error {
223660
224009
  static {
@@ -223803,10 +224152,10 @@ var StreamableHTTPClientTransport = class {
223803
224152
  text: challenge.text
223804
224153
  });
223805
224154
  if (challenge.resourceMetadataUrl) this._resourceMetadataUrl = challenge.resourceMetadataUrl;
223806
- const tokens2 = await this._oauthProvider.tokens();
223807
- const unionScope = computeScopeUnion(this._scope, tokens2?.scope, challenge.scope);
224155
+ const tokens3 = await this._oauthProvider.tokens();
224156
+ const unionScope = computeScopeUnion(this._scope, tokens3?.scope, challenge.scope);
223808
224157
  this._scope = unionScope;
223809
- const forceReauthorization = isStrictScopeSuperset(unionScope, tokens2?.scope);
224158
+ const forceReauthorization = isStrictScopeSuperset(unionScope, tokens3?.scope);
223810
224159
  return auth(this._oauthProvider, {
223811
224160
  serverUrl: this._url,
223812
224161
  resourceMetadataUrl: this._resourceMetadataUrl,
@@ -225600,6 +225949,11 @@ var runFinished = {
225600
225949
  invalidTrials: { type: "integer" },
225601
225950
  agentIssues: { type: "array" },
225602
225951
  harnessIssues: { type: "array" },
225952
+ actions: {
225953
+ type: "object",
225954
+ description: "present when the scene has tools that change something: each distinct call to one (tool and arguments) and in how many of the `of` valid trials the agent made it",
225955
+ properties: { of: { type: "integer" }, made: { type: "array", items: { type: "object", properties: { tool: string7, args: {}, trials: { type: "integer" } } } } }
225956
+ },
225603
225957
  trialsDetail: { type: "array", items: { type: "object", properties: {
225604
225958
  trial: { type: "integer" },
225605
225959
  passed: { type: "boolean" },
@@ -225939,7 +226293,7 @@ function registerRuns(program2, ctx) {
225939
226293
 
225940
226294
  // packages/cli/src/commands/traces.ts
225941
226295
  import { createHash as createHash68 } from "node:crypto";
225942
- import { readFile as readFile40, mkdir as mkdir26, writeFile as writeFile27 } from "node:fs/promises";
226296
+ import { access as access7, readFile as readFile40, mkdir as mkdir26, writeFile as writeFile27 } from "node:fs/promises";
225943
226297
  import { basename as basename12, dirname as dirname17, join as join55, relative as relative12, resolve as resolve40 } from "node:path";
225944
226298
  var import_yaml16 = __toESM(require_dist(), 1);
225945
226299
  init_src();
@@ -226029,6 +226383,79 @@ async function fetchTrace(source, ref20, env2, f = fetch) {
226029
226383
  return source === "langfuse" ? fromLangfuse(id12, env2, f) : fromLangsmith(id12, env2, f);
226030
226384
  }
226031
226385
 
226386
+ // packages/cli/src/import-people.ts
226387
+ var DEFAULT_IMPORT_MODEL = "openai/gpt-4.1-mini";
226388
+ var EXTRACT = `You read a conversation between a CUSTOMER and an AGENT and write down what the CUSTOMER knows and wants, so that
226389
+ someone else can play the same customer in a new conversation with a different agent. Use only what the customer wrote.
226390
+ The agent's lines are context: they show what the customer was answering. Leave out everything only the agent said or
226391
+ produced (what it looked up, its offers, prices, the ids and options it proposed, what its rules allow), even when the
226392
+ customer went along with it. When the customer picked one of the options the agent offered, record what they picked
226393
+ and why, if they said why.
226394
+
226395
+ Answer in JSON:
226396
+ {"name": "the customer's full name as they gave it, or null",
226397
+ "goal": "one paragraph in the second person ('You want ...'): what they came for, and every condition, preference or
226398
+ limit they stated: what they will and won't accept, how they want it done, what to do if told no",
226399
+ "facts": [{"id": "snake_case", "value": "the fact as they would say it", "about": "what a question must ask about to
226400
+ get it", "exact": true for an id, a name, a number, a date or an amount}],
226401
+ "style": "how they write, in a few words"}
226402
+ One fact per item: an account, order or booking id, a name, an email, a date, a choice they made and why. Include what
226403
+ the first message says. Leave out anything the customer didn't say.`;
226404
+ var REWRITE = `A goal for someone who plays a customer in a test names things the customer only knew because the agent said
226405
+ them in the old conversation (its offers, amounts, ids, flights or dates it found). Write the goal again without them.
226406
+ Where the customer accepted or picked one of them, say what they wanted in their own terms (a criterion, a preference)
226407
+ if the goal gives one; otherwise leave that part out. Keep every other condition, limit and preference as it is, in
226408
+ the second person. Answer in JSON: {"goal": "..."}`;
226409
+ async function rewriteGoal(goal, values2, options3) {
226410
+ const client = new OpenAI({
226411
+ apiKey: options3.apiKey,
226412
+ baseURL: options3.baseUrl ?? "https://openrouter.ai/api/v1",
226413
+ adminAPIKey: null,
226414
+ organization: null,
226415
+ project: null,
226416
+ webhookSecret: null,
226417
+ maxRetries: 2,
226418
+ timeout: 12e4,
226419
+ logLevel: "off"
226420
+ });
226421
+ const response5 = await client.chat.completions.create({
226422
+ model: options3.model,
226423
+ temperature: 0,
226424
+ store: false,
226425
+ response_format: { type: "json_object" },
226426
+ messages: [{ role: "system", content: REWRITE }, { role: "user", content: `GOAL: ${goal}
226427
+ ONLY THE AGENT SAID: ${values2.join("; ")}` }]
226428
+ }, { ...options3.signal !== void 0 && { signal: options3.signal } });
226429
+ const rewritten = JSON.parse(response5.choices[0]?.message?.content ?? "").goal;
226430
+ if (typeof rewritten !== "string" || !rewritten.trim()) throw new Error("the model did not answer with a goal");
226431
+ return rewritten.trim();
226432
+ }
226433
+ async function extractPerson(transcript3, options3) {
226434
+ const client = new OpenAI({
226435
+ apiKey: options3.apiKey,
226436
+ baseURL: options3.baseUrl ?? "https://openrouter.ai/api/v1",
226437
+ adminAPIKey: null,
226438
+ organization: null,
226439
+ project: null,
226440
+ webhookSecret: null,
226441
+ maxRetries: 2,
226442
+ timeout: 12e4,
226443
+ logLevel: "off"
226444
+ });
226445
+ const lines = transcript3.map((line2) => `${line2.role === "user" ? "CUSTOMER" : "AGENT"}: ${line2.content.replace(/\s+/g, " ").trim()}`).join("\n");
226446
+ const response5 = await client.chat.completions.create({
226447
+ model: options3.model,
226448
+ temperature: 0,
226449
+ store: false,
226450
+ response_format: { type: "json_object" },
226451
+ messages: [{ role: "system", content: EXTRACT }, { role: "user", content: lines }]
226452
+ }, { ...options3.signal !== void 0 && { signal: options3.signal } });
226453
+ const parsed3 = JSON.parse(response5.choices[0]?.message?.content ?? "");
226454
+ if (!parsed3 || typeof parsed3 !== "object" || Array.isArray(parsed3)) throw new Error("the model did not answer with a JSON object");
226455
+ const person4 = parsed3;
226456
+ return { ...person4, facts: Array.isArray(person4.facts) ? person4.facts.filter((fact2) => fact2 && typeof fact2 === "object") : [] };
226457
+ }
226458
+
226032
226459
  // packages/cli/src/commands/traces.ts
226033
226460
  function agentToolLines(intake) {
226034
226461
  const tools2 = (intake.agentTools ?? []).map((t) => {
@@ -226042,7 +226469,7 @@ function agentToolLines(intake) {
226042
226469
  function toolLines(scene2) {
226043
226470
  const tools2 = Object.entries(scene2.tools ?? {});
226044
226471
  if (!tools2.length) return [];
226045
- const unrecorded = (t) => t.twin ? `otherwise the ${t.twin} twin` : t.unrecorded === "simulate" || !t.write && t.unrecorded !== "fail" ? "otherwise simulated" : "otherwise fails";
226472
+ const unrecorded = (t) => t.twin ? `otherwise the ${t.twin} twin` : t.pure ? "otherwise runs itself" : t.unrecorded === "simulate" || !t.write && t.unrecorded !== "fail" ? "otherwise simulated" : "otherwise fails";
226046
226473
  return [
226047
226474
  " tools (production's answers replayed; observations.jsonl holds them):",
226048
226475
  ...tools2.map(([name5, t]) => ` ${name5}: ${plural5(t.recorded?.length ?? 0, "recorded call")}${t.write ? ", changes something" : ""}${t.mcp ? ", over MCP" : ""}; ${unrecorded(t)}`),
@@ -226065,8 +226492,8 @@ function workspaceError(status5, body6, path6) {
226065
226492
  function notInWorkspace(error64) {
226066
226493
  return error64 instanceof WorkspaceError && error64.status === 404 && !error64.noTraces;
226067
226494
  }
226068
- async function workspaceApi(ctx) {
226069
- const workspace3 = await uploadWorkspace(ctx);
226495
+ async function workspaceApi(ctx, hint = "run ancha login, or set ANCHA_SERVER_URL and ANCHA_API_KEY") {
226496
+ const workspace3 = await uploadWorkspace(ctx, { message: "not logged in to a workspace", hint });
226070
226497
  const key3 = await apiKeyFor(workspace3, ctx.io.env);
226071
226498
  if (key3 === void 0) throw authError(workspace3, { keySent: false });
226072
226499
  const origin = new URL(workspace3).origin;
@@ -226224,6 +226651,14 @@ async function report6(ctx, world5, written) {
226224
226651
  ].join("\n")
226225
226652
  );
226226
226653
  }
226654
+ async function nextLines(ctx, paths2, dest) {
226655
+ const folder = relative12(ctx.io.cwd, resolve40(ctx.io.cwd, dest)) || ".", where2 = paths2.length === 1 ? relative12(ctx.io.cwd, paths2[0]) : `${folder}/*/scene.yaml`;
226656
+ const configured = ctx.globals().config !== void 0 || await access7(resolve40(ctx.io.cwd, "ancha.yaml")).then(() => true, () => false);
226657
+ if (!configured) return [`next: ancha init (it writes ancha.yaml; set agent.command to the command that starts your agent), then ancha run ${where2}`];
226658
+ const globs = await ctx.loadConfig().then((config9) => config9.scenes, () => void 0);
226659
+ const found = globs === void 0 ? void 0 : new Set(await glob3(globs, { cwd: ctx.io.cwd, absolute: true, onlyFiles: true }));
226660
+ return [`next: ancha run ${where2}`, ...!found || paths2.every((path6) => found.has(path6)) ? [] : [`note: scenes: in ancha.yaml does not include ${where2}; add ${folder}/**/scene.yaml to run them with the rest`]];
226661
+ }
226227
226662
  var when12 = (iso19) => iso19 ? `${new Date(iso19).toISOString().replace("T", " ").slice(0, 16)} UTC` : "-";
226228
226663
  var plural5 = (n, one7, many = `${one7}s`) => `${n} ${n === 1 ? one7 : many}`;
226229
226664
  function production2(trace) {
@@ -226328,14 +226763,14 @@ function registerTraces(program2, ctx) {
226328
226763
  ].join("\n");
226329
226764
  });
226330
226765
  });
226331
- program2.command("import").argument("<trace>", "a trace file (Ancha Trace IR, OTLP JSON, a Langfuse or LangSmith export), or with --from the trace's id or URL").option("--from <tool>", `fetch the trace from ${TRACE_SOURCES.join(" or ")} with the keys in this shell (LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_HOST; LANGSMITH_API_KEY, LANGSMITH_ENDPOINT); they never leave this computer`).option("--dest <dir>", "where the tests go", "scenes/from-traces").option("--force", "overwrite a scene.yaml already here even if it has changes besides checks you added").option("--offline", "turn the trace into a test on this computer; nothing is uploaded").option("--answer <question=value>", "with --offline: answer one of the test's questions; repeat for more", (value5, all8) => [...all8, value5], []).option("--expect <what went wrong>", "say in a sentence what the agent did wrong in production; the test gets a check for it").option("--examples <file>", "with --offline: another trace of the same agent, whose tool calls show simulation how the tools behave; repeat for more", (value5, all8) => [...all8, value5], []).description("send a production trace to your workspace and save the test it makes (or, with --offline, make it here); writes the test here").action(async (trace, options3) => {
226766
+ program2.command("import").argument("<trace>", "a trace file (Ancha Trace IR, OTLP JSON, a Langfuse or LangSmith export), or with --from the trace's id or URL").option("--from <tool>", `fetch the trace from ${TRACE_SOURCES.join(" or ")} with the keys in this shell (LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_HOST; LANGSMITH_API_KEY, LANGSMITH_ENDPOINT); they never leave this computer`).option("--dest <dir>", "where the tests go", "scenes/from-traces").option("--force", "overwrite a scene.yaml already here even if it has changes besides checks you added").option("--offline", "turn the trace into a test on this computer; nothing is uploaded").option("--answer <question=value>", "with --offline: answer one of the test's questions; repeat for more", (value5, all8) => [...all8, value5], []).option("--expect <what went wrong>", "say in a sentence what the agent did wrong in production; the test gets a check for it").option("--examples <file>", "with --offline: another trace of the same agent, whose tool calls show simulation how the tools behave; repeat for more", (value5, all8) => [...all8, value5], []).option("--conversation <id>", "with --offline: only this conversation of the file (its session id, or the id of one of its traces)").description("send a production trace to your workspace and save the test it makes (or, with --offline, make it here: one test per conversation in the file); writes the test here").action(async (trace, options3) => {
226332
226767
  const source = await traceSource(ctx, trace, options3.from);
226333
226768
  if (options3.offline) {
226334
226769
  const made = await importLocally(ctx, source, options3);
226335
226770
  ctx.out.result(made.result, () => made.text);
226336
226771
  return;
226337
226772
  }
226338
- const api3 = await workspaceApi(ctx);
226773
+ const api3 = await workspaceApi(ctx, `ancha import --offline ${options3.from ? `--from ${options3.from} ` : ""}${trace} makes the tests on this computer; ancha login sends traces to your workspace`);
226339
226774
  const { traces: imported } = await api3(`/v1/imports?name=${encodeURIComponent(source.name)}`, { method: "POST", headers: { "content-type": options3.from ? "application/json" : "application/x-ndjson" }, body: source.text });
226340
226775
  for (const { id: id12 } of imported) {
226341
226776
  const changes = await guard(ctx, resolve40(ctx.io.cwd, options3.dest, `trace-${id12.slice(0, 8)}`), options3.force);
@@ -226391,6 +226826,51 @@ async function traceTextLines(text24, name5) {
226391
226826
  }
226392
226827
  return docs2.map((doc) => doc.lines).reduce((merged, next2) => mergeIr2(merged, next2));
226393
226828
  }
226829
+ async function traceConversations(text24, name5) {
226830
+ const { fileToIr: fileToIr2, conversationsOf: conversationsOf2 } = await Promise.resolve().then(() => (init_rebuild(), rebuild_exports));
226831
+ try {
226832
+ return conversationsOf2(fileToIr2(text24, name5));
226833
+ } catch (error64) {
226834
+ throw new AnchaError("USAGE", `${name5}: ${error64 instanceof Error ? error64.message : String(error64)}`);
226835
+ }
226836
+ }
226837
+ async function customersOf(ctx, conversations) {
226838
+ const { agentValuesInGoal: agentValuesInGoal2, customerFacts: customerFacts2, goalWithout: goalWithout2, personByRule: personByRule2 } = await Promise.resolve().then(() => (init_rebuild(), rebuild_exports));
226839
+ const apiKey = ctx.io.env.OPENROUTER_API_KEY, model2 = ctx.io.env.ANCHA_IMPORT_MODEL || DEFAULT_IMPORT_MODEL;
226840
+ let failed = 0;
226841
+ const one7 = async ({ transcript: transcript3, lines }) => {
226842
+ if (transcript3.filter((line2) => line2.role === "user").length < 2) return void 0;
226843
+ if (apiKey) {
226844
+ try {
226845
+ const route11 = { apiKey, model: model2, ...ctx.io.env.ANCHA_JUDGE_BASE_URL && { baseUrl: ctx.io.env.ANCHA_JUDGE_BASE_URL } };
226846
+ const person4 = await extractPerson(transcript3, route11);
226847
+ const world5 = lines.filter((l) => l.kind === "tool" && l.result !== void 0).map((l) => ({ t: typeof l.t === "string" ? l.t : void 0, text: typeof l.result === "string" ? l.result : JSON.stringify(l.result) }));
226848
+ const { kept, dropped } = customerFacts2(person4.facts ?? [], transcript3, world5), left = dropped.map((fact2) => String(fact2.value));
226849
+ let goal = String(person4.goal ?? ""), rewrote = agentValuesInGoal2(goal, left);
226850
+ if (rewrote.length) {
226851
+ goal = await rewriteGoal(goal, rewrote, route11).catch(() => goal);
226852
+ const still = agentValuesInGoal2(goal, rewrote);
226853
+ if (still.length) goal = goalWithout2(goal, still) || goal;
226854
+ rewrote = rewrote.filter((value5) => !agentValuesInGoal2(goal, [value5]).length);
226855
+ }
226856
+ return { person: { ...person4, goal, facts: kept }, transcript: transcript3, by: model2, dropped: left, rewrote };
226857
+ } catch {
226858
+ failed++;
226859
+ }
226860
+ }
226861
+ return { person: personByRule2(transcript3), transcript: transcript3, by: "rule", dropped: [], rewrote: [] };
226862
+ };
226863
+ const people3 = new Array(conversations.length);
226864
+ let next2 = 0;
226865
+ await Promise.all(Array.from({ length: Math.min(8, conversations.length) }, async () => {
226866
+ while (next2 < conversations.length) {
226867
+ const i = next2++;
226868
+ people3[i] = await one7(conversations[i]);
226869
+ }
226870
+ }));
226871
+ return { people: people3, model: apiKey ? model2 : void 0, failed };
226872
+ }
226873
+ var conversationSlug = (id12) => /^[0-9a-f]{16,}$/i.test(id12) ? id12.slice(0, 8).toLowerCase() : id12.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "conversation";
226394
226874
  async function traceFileItems(ctx, file3) {
226395
226875
  const { itemsOf: itemsOf2 } = await Promise.resolve().then(() => (init_rebuild(), rebuild_exports));
226396
226876
  return itemsOf2((await traceFileLines(ctx, file3)).lines);
@@ -226408,51 +226888,97 @@ function diffCalls(production3, attempt) {
226408
226888
  };
226409
226889
  }
226410
226890
  async function importLocally(ctx, source, options3) {
226411
- const { text: text24 } = source, lines = await traceTextLines(text24, source.name);
226891
+ const { text: text24 } = source, all8 = await traceConversations(text24, source.name);
226412
226892
  const { rebuild: rebuild2, sceneFiles: sceneFiles2 } = await Promise.resolve().then(() => (init_rebuild(), rebuild_exports));
226413
226893
  const answers = Object.fromEntries(options3.answer.map((pair) => {
226414
226894
  const at3 = pair.indexOf("=");
226415
226895
  if (at3 < 1) throw new AnchaError("USAGE", `--answer needs question=value, got ${pair}`);
226416
226896
  return [pair.slice(0, at3), pair.slice(at3 + 1)];
226417
226897
  }));
226418
- const id12 = `trace-${createHash68("sha256").update(text24).digest("hex").slice(0, 8)}`;
226419
- let made;
226420
- const examples2 = await Promise.all((options3.examples ?? []).map(async (file3) => (await traceFileLines(ctx, file3)).lines));
226421
- try {
226422
- made = rebuild2(lines, { id: id12, answers, ...options3.expect && { expect: options3.expect }, ...examples2.length && { examples: examples2 } });
226423
- } catch (error64) {
226424
- if (error64.code === "NO_CALLS") throw new AnchaError("USAGE", error64.message, { hint: "an import needs the agent's tool calls with their results (turn on your tracing SDK's content capture), the API calls it made, or at least the invocation's input" });
226425
- throw error64;
226426
- }
226427
- const setup2 = [...made.setup.reduce((all8, call3) => all8.set(call3, (all8.get(call3) ?? 0) + 1), /* @__PURE__ */ new Map())].map(([call3, count3]) => ({ call: call3, count: count3 }));
226428
- const dir2 = resolve40(ctx.io.cwd, options3.dest, id12), path6 = join55(dir2, "scene.yaml");
226429
- if (!options3.force && await readFile40(path6, "utf8").then(() => true, () => false)) throw new AnchaError("USAGE", `${relative12(ctx.io.cwd, path6)} exists; --force replaces it`);
226430
- await mkdir26(dir2, { recursive: true });
226431
- const files2 = sceneFiles2(made.scene);
226432
- await writeFile27(path6, (0, import_yaml16.stringify)(files2.scene, { lineWidth: 0 }));
226433
- if (files2.observations !== void 0) await writeFile27(join55(dir2, "observations.jsonl"), files2.observations);
226434
- if (made.record) await writeFile27(join55(dir2, "production.jsonl"), productionLines(made.record));
226435
- if (made.production !== void 0 && Object.keys(made.production).length) await writeFile27(join55(dir2, "production.json"), `${JSON.stringify({ trace: made.summary.trace, checks: made.production }, null, 2)}
226898
+ const picked = options3.conversation === void 0 ? all8 : all8.filter((c) => c.id === options3.conversation || c.traces.includes(options3.conversation));
226899
+ if (!picked.length) throw new AnchaError("USAGE", `no conversation ${options3.conversation} in ${source.label}`, { hint: `its conversations: ${all8.slice(0, 10).map((c) => c.id).join(", ")}${all8.length > 10 ? `, and ${all8.length - 10} more` : ""}` });
226900
+ const base3 = `trace-${createHash68("sha256").update(text24).digest("hex").slice(0, 8)}`, ids2 = /* @__PURE__ */ new Set();
226901
+ const idOf2 = (c) => {
226902
+ if (all8.length === 1) return base3;
226903
+ let id12 = `${base3}-${conversationSlug(c.id)}`;
226904
+ for (let n = 2; ids2.has(id12); n++) id12 = `${base3}-${conversationSlug(c.id)}-${n}`;
226905
+ ids2.add(id12);
226906
+ return id12;
226907
+ };
226908
+ const named3 = new Map(all8.map((c) => [c, idOf2(c)]));
226909
+ const files2 = await Promise.all((options3.examples ?? []).map(async (file3) => (await traceFileLines(ctx, file3)).lines));
226910
+ const customers = await customersOf(ctx, picked);
226911
+ const made = [], skipped = [];
226912
+ for (const [i, conversation3] of picked.entries()) {
226913
+ const examples2 = [...all8.filter((c) => c !== conversation3).map((c) => c.lines), ...files2], customer3 = customers.people[i];
226914
+ try {
226915
+ made.push({ conversation: conversation3, id: named3.get(conversation3), made: rebuild2(conversation3.lines, { id: named3.get(conversation3), answers, ...options3.expect && { expect: options3.expect }, ...examples2.length && { examples: examples2 }, ...customer3 && { customer: customer3 } }) });
226916
+ } catch (error64) {
226917
+ if (error64.code !== "NO_CALLS") throw error64;
226918
+ if (picked.length === 1) throw new AnchaError("USAGE", error64.message, { hint: "an import needs the agent's tool calls with their results (turn on your tracing SDK's content capture), the API calls it made, or at least the invocation's input" });
226919
+ skipped.push(conversation3.id);
226920
+ }
226921
+ }
226922
+ const paths2 = made.map((m) => join55(resolve40(ctx.io.cwd, options3.dest, m.id), "scene.yaml"));
226923
+ if (!options3.force) {
226924
+ for (const path6 of paths2) if (await readFile40(path6, "utf8").then(() => true, () => false)) throw new AnchaError("USAGE", `${relative12(ctx.io.cwd, path6)} exists; --force replaces it`);
226925
+ }
226926
+ for (const [i, m] of made.entries()) {
226927
+ const path6 = paths2[i], dir2 = dirname17(path6);
226928
+ await mkdir26(dir2, { recursive: true });
226929
+ const files3 = sceneFiles2(m.made.scene);
226930
+ await writeFile27(path6, (0, import_yaml16.stringify)(files3.scene, { lineWidth: 0 }));
226931
+ if (files3.observations !== void 0) await writeFile27(join55(dir2, "observations.jsonl"), files3.observations);
226932
+ if (m.made.record) await writeFile27(join55(dir2, "production.jsonl"), productionLines(m.made.record));
226933
+ if (m.made.production !== void 0 && Object.keys(m.made.production).length) await writeFile27(join55(dir2, "production.json"), `${JSON.stringify({ trace: m.made.summary.trace, checks: m.made.production }, null, 2)}
226436
226934
  `);
226437
- await writeFile27(join55(dir2, "provenance.json"), `${JSON.stringify({ summary: made.summary, provenance: made.provenance, questions: made.questions }, null, 2)}
226935
+ await writeFile27(join55(dir2, "provenance.json"), `${JSON.stringify({ summary: m.made.summary, provenance: m.made.provenance, questions: m.made.questions, ...all8.length > 1 && { conversation: { id: m.conversation.id, traces: m.conversation.traces } } }, null, 2)}
226438
226936
  `);
226439
- await loadSceneFile(path6);
226440
- const lines2 = [
226441
- `wrote ${relative12(ctx.io.cwd, path6)} from ${source.label}, on this computer (nothing was uploaded)`,
226442
- ` ${made.summary.observed} observed, ${made.summary.inferred} inferred, ${made.summary.missing} missing; provenance in provenance.json`,
226443
- ...toolLines(made.scene)
226937
+ await loadSceneFile(path6);
226938
+ }
226939
+ const setupOf = (m) => [...m.made.setup.reduce((all9, call3) => all9.set(call3, (all9.get(call3) ?? 0) + 1), /* @__PURE__ */ new Map())].map(([call3, count3]) => ({ call: call3, count: count3 }));
226940
+ const questionLines = (questions2) => questions2.length ? [
226941
+ " questions (answer with --answer <id>=<value>, then import again with --force; a default repeats what production did, so answer the ones about what went wrong):",
226942
+ ...questions2.flatMap((q) => [` ${q.id}: ${q.question}`, ` ${q.answer === void 0 ? `default: ${q.default}` : `answered: ${q.answer}`}`])
226943
+ ] : [];
226944
+ const placed = made.filter((m) => m.made.scene.people?.length).length;
226945
+ const dropped = customers.people.reduce((n, c) => n + (c?.dropped?.length ?? 0), 0);
226946
+ const customerLines = !placed ? [] : [
226947
+ customers.model ? ` the customer: written down by ${customers.model} from their lines${placed > 1 ? ` (${placed} conversations)` : ""}; their lines went to that model with your OPENROUTER_API_KEY${dropped ? `; ${plural5(dropped, "fact")} the agent said first left out` : ""}${customers.failed ? `; ${customers.failed} without it, as below (the model failed)` : ""}` : ` the customer${placed > 1 ? `s of ${placed} conversations` : ""}: their first message is the goal and each later one a fact (no OPENROUTER_API_KEY; with one, a model writes down their goal and facts: import again with --force)`,
226948
+ " they write to your agent in a private Slack channel: run it with input: per_event (in Python, ancha.chat(reply) does the Slack part)"
226444
226949
  ];
226445
- if (made.questions.length) {
226446
- lines2.push(" questions (answer with --answer <id>=<value>, then import again with --force; a default repeats what production did, so answer the ones about what went wrong):");
226447
- for (const q of made.questions) lines2.push(` ${q.id}: ${q.question}`, ` ${q.answer === void 0 ? `default: ${q.default}` : `answered: ${q.answer}`}`);
226448
- }
226449
- if (setup2.length) {
226450
- lines2.push(
226451
- ` warning: ${plural5(made.setup.length, "call")} came before the first event the test replays, the app's own setup: ${setup2.map((c) => `${c.call}${c.count > 1 ? ` \xD7${c.count}` : ""}`).join(", ")}`,
226452
- " the test has them only if the app makes them when it starts, or the start script or an app_calls entry does (ancha docs apps)"
226453
- );
226950
+ if (all8.length === 1) {
226951
+ const [m] = made, setup2 = setupOf(m), path6 = paths2[0];
226952
+ const lines2 = [
226953
+ `wrote ${relative12(ctx.io.cwd, path6)} from ${source.label}, on this computer (nothing was uploaded)`,
226954
+ ` ${m.made.summary.observed} observed, ${m.made.summary.inferred} inferred, ${m.made.summary.missing} missing; provenance in provenance.json`,
226955
+ ...toolLines(m.made.scene),
226956
+ ...customerLines,
226957
+ ...questionLines(m.made.questions)
226958
+ ];
226959
+ if (setup2.length) {
226960
+ lines2.push(
226961
+ ` warning: ${plural5(m.made.setup.length, "call")} came before the first event the test replays, the app's own setup: ${setup2.map((c) => `${c.call}${c.count > 1 ? ` \xD7${c.count}` : ""}`).join(", ")}`,
226962
+ " the test has them only if the app makes them when it starts, or the start script or an app_calls entry does (ancha docs apps)"
226963
+ );
226964
+ }
226965
+ lines2.push(...await nextLines(ctx, [path6], options3.dest));
226966
+ return { result: { scene: relative12(ctx.io.cwd, path6), summary: m.made.summary, questions: m.made.questions, setup: setup2 }, text: lines2.join("\n") };
226454
226967
  }
226455
- return { result: { scene: relative12(ctx.io.cwd, path6), summary: made.summary, questions: made.questions, setup: setup2 }, text: lines2.join("\n") };
226968
+ const questions = [...new Map(made.flatMap((m) => m.made.questions).reverse().map((q) => [q.id, q])).values()].reverse();
226969
+ const recorded2 = (m) => Object.values(m.made.scene.tools ?? {}).reduce((n, t) => n + (t.recorded?.length ?? 0), 0);
226970
+ const lines = [
226971
+ `wrote ${plural5(made.length, "test")} from ${source.label}, one per conversation, on this computer (nothing was uploaded)`,
226972
+ ...made.map((m, i) => ` ${relative12(ctx.io.cwd, paths2[i])} ${plural5(m.conversation.traces.length, "turn")}, ${plural5(recorded2(m), "recorded call")} (conversation ${m.conversation.id})`),
226973
+ ...skipped.length ? [` skipped ${plural5(skipped.length, "conversation")} with no tool calls, API calls or input: ${skipped.join(", ")}`] : [],
226974
+ ...made.length > 1 ? [" each test replays its own conversation's calls; the other conversations' calls show simulation how the tools behave"] : [],
226975
+ ...customerLines,
226976
+ ...questionLines(questions)
226977
+ ];
226978
+ const setups = made.filter((m) => m.made.setup.length).length;
226979
+ if (setups) lines.push(` warning: in ${plural5(setups, "test")}, calls came before the first event the test replays, the app's own setup (provenance.json lists them; ancha docs apps)`);
226980
+ lines.push(...await nextLines(ctx, paths2, options3.dest));
226981
+ return { result: { scenes: made.map((m, i) => ({ scene: relative12(ctx.io.cwd, paths2[i]), conversation: m.conversation.id, traces: m.conversation.traces, summary: m.made.summary, setup: setupOf(m) })), questions, skipped }, text: lines.join("\n") };
226456
226982
  }
226457
226983
 
226458
226984
  // packages/cli/src/main.ts
@@ -226461,15 +226987,16 @@ function processIO() {
226461
226987
  return { stdout: process.stdout, stderr: process.stderr, cwd: process.cwd(), env: process.env };
226462
226988
  }
226463
226989
  var HELP_GROUPS = {
226464
- "Start:": ["init", "run", "explain", "baseline", "docs"],
226990
+ "Start:": ["init", "import", "run", "explain", "baseline", "docs"],
226465
226991
  "Cloud:": ["login", "whoami", "secrets", "traces"],
226466
- "Inspect:": ["world", "test", "twins", "connect", "doctor", "schema"],
226992
+ "Inspect:": ["world", "test", "twins", "connect", "doctor"],
226467
226993
  "More:": ["completion"]
226468
226994
  };
226469
- var ADVANCED = /* @__PURE__ */ new Set(["agent", "serve", "ui", "scene", "env", "sandbox", "mcp", "execution", "playground", "status", "wait", "logs", "report", "check", "runs", "attempt", "replay", "import", "pull", "logout"]);
226995
+ var ADVANCED = /* @__PURE__ */ new Set(["agent", "serve", "ui", "scene", "env", "sandbox", "mcp", "execution", "playground", "status", "wait", "logs", "report", "check", "runs", "attempt", "replay", "pull", "schema", "logout"]);
226470
226996
  var START = [
226471
226997
  "Ancha: simulation playgrounds for agents. Start here:",
226472
226998
  " ancha init set up this project: ancha.yaml, a starter scene, coding-agent instructions",
226999
+ " ancha import --offline <trace file> turn production traces into tests on this computer, one per conversation",
226473
227000
  " ancha run run your agent against fresh worlds and grade it",
226474
227001
  " ancha explain latest why it failed: each check, expected vs actual, the calls behind it",
226475
227002
  " ancha login use your hosted workspace at app.ancha.io (one browser approval)",