@ancha-labs/cli 0.3.0 → 0.4.0

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
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 the agent wraps.`, ["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];
@@ -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 = [];
@@ -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(".");
@@ -135397,26 +135644,26 @@ function dumpState9(ctx) {
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
 
@@ -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
  });
@@ -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;
@@ -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}`);
@@ -177443,7 +177772,7 @@ function renderReproduction(reproductions) {
177443
177772
  ...also.length > 0 ? [` also failing here, though production passed: ${also.join(", ")}`] : [],
177444
177773
  ...r.added.length > 0 ? [` checks added after saving, with no production result: ${r.added.join(", ")}`] : [],
177445
177774
  // 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)" : ""}`] : []
177775
+ ...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
177776
  ].join("\n");
177448
177777
  }).join("\n\n");
177449
177778
  }
@@ -200740,11 +201069,11 @@ _a6 = brand_privateBedrockClient;
200740
201069
 
200741
201070
  // backend/src/judge/openrouter.ts
200742
201071
  var DEFAULT_JUDGE_MODEL = "anthropic/claude-haiku-5.5";
200743
- async function requestGrade(apiKey, model2, rubric, evidence, signal) {
201072
+ async function requestGrade(apiKey, model2, rubric, evidence, signal, baseUrl = "https://openrouter.ai/api/v1") {
200744
201073
  signal?.throwIfAborted();
200745
201074
  const client = new OpenAI({
200746
201075
  apiKey,
200747
- baseURL: "https://openrouter.ai/api/v1",
201076
+ baseURL: baseUrl,
200748
201077
  adminAPIKey: null,
200749
201078
  organization: null,
200750
201079
  project: null,
@@ -200893,7 +201222,7 @@ async function evaluateJudges(scene2, capture4, options3) {
200893
201222
  continue;
200894
201223
  }
200895
201224
  try {
200896
- const response5 = await requestGrade(key3, model2, check4.judge.replaceAll(key3, "[redacted]"), evidence.json, options3.signal);
201225
+ const response5 = await requestGrade(key3, model2, check4.judge.replaceAll(key3, "[redacted]"), evidence.json, options3.signal, options3.baseUrl);
200897
201226
  options3.signal?.throwIfAborted();
200898
201227
  const choice4 = response5.choices[0];
200899
201228
  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 +201976,7 @@ async function runPerEventTrial(spec) {
201647
201976
  signal?.throwIfAborted();
201648
201977
  const logFd = openSync3(join26(dir2, "agent.log"), "w");
201649
201978
  const startedAt = performance.now();
201650
- let timedOut = false, spawnFailed = false, firstFailure = null, invocations = 0;
201979
+ let timedOut = false, spawnFailed = false, firstFailure, invocations = 0, failedInvocations = 0;
201651
201980
  let failure5;
201652
201981
  try {
201653
201982
  await backend.startTrial(env2.id, session.id);
@@ -201685,8 +202014,9 @@ async function runPerEventTrial(spec) {
201685
202014
  spawnFailed = true;
201686
202015
  writeSync3(logFd, `ancha: could not start the agent: ${outcome4.error.message}
201687
202016
  `);
201688
- } else if (outcome4.kind === "exit" && outcome4.code !== 0) {
201689
- firstFailure ??= outcome4.code;
202017
+ } else if (outcome4.kind === "exit" && outcome4.code !== 0 && !timedOut) {
202018
+ failedInvocations++;
202019
+ if (firstFailure === void 0) firstFailure = outcome4.code;
201690
202020
  if (outcome4.code === EXIT_COMMAND_NOT_FOUND) spawnFailed = true;
201691
202021
  }
201692
202022
  } finally {
@@ -201721,7 +202051,7 @@ async function runPerEventTrial(spec) {
201721
202051
  if (failure5 !== void 0) throw failure5.error;
201722
202052
  signal?.throwIfAborted();
201723
202053
  const exit = spawnFailed ? "spawn_failed" : timedOut ? "timeout" : "exited";
201724
- const exitCode = spawnFailed ? EXIT_COMMAND_NOT_FOUND : firstFailure ?? 0;
202054
+ const exitCode = spawnFailed ? EXIT_COMMAND_NOT_FOUND : firstFailure === void 0 ? 0 : firstFailure;
201725
202055
  return {
201726
202056
  valid: !harnessIssues.some((issue5) => issue5.owner === "harness"),
201727
202057
  harnessIssues,
@@ -201734,8 +202064,9 @@ async function runPerEventTrial(spec) {
201734
202064
  realMs,
201735
202065
  simMs,
201736
202066
  checks,
201737
- logTail: exit === "exited" && exitCode === 0 ? [] : await logTail2(join26(dir2, "agent.log")),
201738
- passed: checks.every((c) => !c.required || c.passed),
202067
+ invocations: { total: invocations, failed: failedInvocations },
202068
+ logTail: exit === "exited" && failedInvocations === 0 ? [] : await logTail2(join26(dir2, "agent.log")),
202069
+ passed: failedInvocations === 0 && checks.every((c) => !c.required || c.passed),
201739
202070
  trace,
201740
202071
  dir: dir2,
201741
202072
  taskDelivery
@@ -202139,6 +202470,8 @@ async function executeRun(opts) {
202139
202470
  }
202140
202471
  result.caseId = item2.id;
202141
202472
  result.attemptId = attempt.id;
202473
+ if (writeTools(item2.scene).size) result.actions = actionsOf(item2.scene, result.trace);
202474
+ if (Object.keys(item2.scene.tools ?? {}).length) result.answers = answersOf(result.trace);
202142
202475
  if (result.exit !== "invalid") {
202143
202476
  if (!observedAgentExit && result.exit === "spawn_failed") halt.spawnFailure = result;
202144
202477
  observedAgentExit = true;
@@ -202369,7 +202702,8 @@ function compareSummaries(current, baseline) {
202369
202702
  droppedChecks.push(delta2);
202370
202703
  }
202371
202704
  }
202372
- return { sceneId: scene2.sceneId, before: beforeScene.passed / beforeTrials, after: scene2.passed / afterTrials, delta: Number(numerator) / Number(denominator), beforeTrials, afterTrials, ...checks.length > 0 && { checks } };
202705
+ const actions = actionChanges(beforeScene.actions, scene2.actions);
202706
+ 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
202707
  });
202374
202708
  return { baselineRunId: baseline.runId, regressed, droppedChecks, scenes };
202375
202709
  }
@@ -202544,7 +202878,11 @@ function registerRun(program2, ctx) {
202544
202878
  trials,
202545
202879
  parallel,
202546
202880
  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 } },
202881
+ judge: {
202882
+ ...ctx.io.env.OPENROUTER_API_KEY !== void 0 && { apiKey: ctx.io.env.OPENROUTER_API_KEY },
202883
+ ...config9.judge?.model !== void 0 && { model: config9.judge.model },
202884
+ ...ctx.io.env.ANCHA_JUDGE_BASE_URL !== void 0 && { baseUrl: ctx.io.env.ANCHA_JUDGE_BASE_URL }
202885
+ },
202548
202886
  ...opts.seed !== void 0 && { seed: opts.seed },
202549
202887
  ...opts.out !== void 0 && { out: opts.out },
202550
202888
  ...opts.strict !== void 0 && { strict: opts.strict },
@@ -203202,7 +203540,11 @@ function registerReplay(program2, ctx) {
203202
203540
  runId: state3.runId,
203203
203541
  signal,
203204
203542
  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 } },
203543
+ judge: {
203544
+ ...ctx.io.env.OPENROUTER_API_KEY !== void 0 && { apiKey: ctx.io.env.OPENROUTER_API_KEY },
203545
+ ...config9.judge?.model !== void 0 && { model: config9.judge.model },
203546
+ ...ctx.io.env.ANCHA_JUDGE_BASE_URL !== void 0 && { baseUrl: ctx.io.env.ANCHA_JUDGE_BASE_URL }
203547
+ },
203206
203548
  onEvent: (event3) => {
203207
203549
  if (event3.event === "trial_finished") writer.trialFinished();
203208
203550
  const shown = event3.event === "run_started" ? { ...event3, replayOf: attempt.id, ...where2 } : event3;
@@ -203400,7 +203742,11 @@ function registerSimulate(sceneCommand, ctx) {
203400
203742
  trials: 1,
203401
203743
  parallel: 1,
203402
203744
  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 } },
203745
+ judge: {
203746
+ ...ctx.io.env.OPENROUTER_API_KEY !== void 0 && { apiKey: ctx.io.env.OPENROUTER_API_KEY },
203747
+ ...config9.judge?.model !== void 0 && { model: config9.judge.model },
203748
+ ...ctx.io.env.ANCHA_JUDGE_BASE_URL !== void 0 && { baseUrl: ctx.io.env.ANCHA_JUDGE_BASE_URL }
203749
+ },
203404
203750
  outDir: resolve29(ctx.io.cwd, DEFAULT_RUNS_DIR),
203405
203751
  inheritedEnv: ctx.io.env,
203406
203752
  signal,
@@ -219853,7 +220199,7 @@ var require_formats2 = /* @__PURE__ */ __commonJSMin2(((exports) => {
219853
220199
  function isLeapYear(year) {
219854
220200
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
219855
220201
  }
219856
- const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
220202
+ const DATE2 = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
219857
220203
  const DAYS2 = [
219858
220204
  0,
219859
220205
  31,
@@ -219870,7 +220216,7 @@ var require_formats2 = /* @__PURE__ */ __commonJSMin2(((exports) => {
219870
220216
  31
219871
220217
  ];
219872
220218
  function date10(str4) {
219873
- const matches7 = DATE.exec(str4);
220219
+ const matches7 = DATE2.exec(str4);
219874
220220
  if (!matches7) return false;
219875
220221
  const year = +matches7[1];
219876
220222
  const month = +matches7[2];
@@ -220651,22 +220997,22 @@ async function authInternal(provider, { serverUrl: serverUrl3, authorizationCode
220651
220997
  }, infoCtx);
220652
220998
  return "AUTHORIZED";
220653
220999
  }
220654
- let tokens2 = discardIfIssuerMismatch(await provider.tokens(infoCtx), issuer);
220655
- if (tokens2 && tokens2.issuer === void 0) {
220656
- tokens2 = {
220657
- ...tokens2,
221000
+ let tokens3 = discardIfIssuerMismatch(await provider.tokens(infoCtx), issuer);
221001
+ if (tokens3 && tokens3.issuer === void 0) {
221002
+ tokens3 = {
221003
+ ...tokens3,
220658
221004
  issuer
220659
221005
  };
220660
- await provider.saveTokens(tokens2, infoCtx);
221006
+ await provider.saveTokens(tokens3, infoCtx);
220661
221007
  }
220662
- if (tokens2?.refresh_token && !forceReauthorization) {
220663
- const refreshScope = await provider.scopeForRefresh?.(tokens2);
221008
+ if (tokens3?.refresh_token && !forceReauthorization) {
221009
+ const refreshScope = await provider.scopeForRefresh?.(tokens3);
220664
221010
  let newTokens;
220665
221011
  try {
220666
221012
  newTokens = await refreshAuthorization(authorizationServerUrl, {
220667
221013
  metadata: metadata7,
220668
221014
  clientInformation,
220669
- refreshToken: tokens2.refresh_token,
221015
+ refreshToken: tokens3.refresh_token,
220670
221016
  scope: refreshScope,
220671
221017
  resource: resource2,
220672
221018
  addClientAuthentication: provider.addClientAuthentication,
@@ -220961,7 +221307,7 @@ async function refreshAuthorization(authorizationServerUrl, { metadata: metadata
220961
221307
  refresh_token: refreshToken
220962
221308
  });
220963
221309
  if (scope3) tokenRequestParams.set("scope", scope3);
220964
- const tokens2 = await executeTokenRequest(authorizationServerUrl, {
221310
+ const tokens3 = await executeTokenRequest(authorizationServerUrl, {
220965
221311
  metadata: metadata7,
220966
221312
  tokenRequestParams,
220967
221313
  clientInformation,
@@ -220972,8 +221318,8 @@ async function refreshAuthorization(authorizationServerUrl, { metadata: metadata
220972
221318
  });
220973
221319
  return {
220974
221320
  refresh_token: refreshToken,
220975
- ...tokens2,
220976
- ...scope3 && !tokens2.scope && { scope: scope3 }
221321
+ ...tokens3,
221322
+ ...scope3 && !tokens3.scope && { scope: scope3 }
220977
221323
  };
220978
221324
  }
220979
221325
  async function fetchToken(provider, authorizationServerUrl, { metadata: metadata7, resource: resource2, authorizationCode, iss, scope: scope3, fetchFn } = {}) {
@@ -221052,10 +221398,10 @@ var InMemoryResponseCacheStore = class {
221052
221398
  return this._entries.size;
221053
221399
  }
221054
221400
  get(key3) {
221055
- return this._entries.get(keyOf(key3));
221401
+ return this._entries.get(keyOf2(key3));
221056
221402
  }
221057
221403
  set(key3, entry3) {
221058
- const k = keyOf(key3);
221404
+ const k = keyOf2(key3);
221059
221405
  const exempt = CAP_EXEMPT_METHODS.has(key3.method);
221060
221406
  const isNew = !this._entries.has(k);
221061
221407
  if (!exempt && isNew && this._maxEntries > 0 && this._cappedSize >= this._maxEntries) {
@@ -221074,7 +221420,7 @@ var InMemoryResponseCacheStore = class {
221074
221420
  return stamp5;
221075
221421
  }
221076
221422
  delete(key3) {
221077
- if (this._entries.delete(keyOf(key3)) && !CAP_EXEMPT_METHODS.has(key3.method)) this._cappedSize--;
221423
+ if (this._entries.delete(keyOf2(key3)) && !CAP_EXEMPT_METHODS.has(key3.method)) this._cappedSize--;
221078
221424
  }
221079
221425
  evict(method2) {
221080
221426
  const prefix2 = `${method2}\0`;
@@ -221089,7 +221435,7 @@ var InMemoryResponseCacheStore = class {
221089
221435
  this._cappedSize = 0;
221090
221436
  }
221091
221437
  };
221092
- function keyOf(key3) {
221438
+ function keyOf2(key3) {
221093
221439
  return `${key3.method}\0${JSON.stringify([key3.partition ?? "", key3.params ?? ""])}`;
221094
221440
  }
221095
221441
  function genKey(method2, params9) {
@@ -223648,13 +223994,13 @@ var withDpopFromProvider = (provider) => withDpop(async () => {
223648
223994
  throw markAuthSeamEscape(error64);
223649
223995
  }
223650
223996
  }, async () => {
223651
- let tokens2;
223997
+ let tokens3;
223652
223998
  try {
223653
- tokens2 = await provider.tokens();
223999
+ tokens3 = await provider.tokens();
223654
224000
  } catch (error64) {
223655
224001
  throw markAuthSeamEscape(error64);
223656
224002
  }
223657
- return tokens2?.token_type?.toLowerCase() === "dpop" ? tokens2.access_token : void 0;
224003
+ return tokens3?.token_type?.toLowerCase() === "dpop" ? tokens3.access_token : void 0;
223658
224004
  });
223659
224005
  var SseError = class extends Error {
223660
224006
  static {
@@ -223803,10 +224149,10 @@ var StreamableHTTPClientTransport = class {
223803
224149
  text: challenge.text
223804
224150
  });
223805
224151
  if (challenge.resourceMetadataUrl) this._resourceMetadataUrl = challenge.resourceMetadataUrl;
223806
- const tokens2 = await this._oauthProvider.tokens();
223807
- const unionScope = computeScopeUnion(this._scope, tokens2?.scope, challenge.scope);
224152
+ const tokens3 = await this._oauthProvider.tokens();
224153
+ const unionScope = computeScopeUnion(this._scope, tokens3?.scope, challenge.scope);
223808
224154
  this._scope = unionScope;
223809
- const forceReauthorization = isStrictScopeSuperset(unionScope, tokens2?.scope);
224155
+ const forceReauthorization = isStrictScopeSuperset(unionScope, tokens3?.scope);
223810
224156
  return auth(this._oauthProvider, {
223811
224157
  serverUrl: this._url,
223812
224158
  resourceMetadataUrl: this._resourceMetadataUrl,
@@ -225600,6 +225946,11 @@ var runFinished = {
225600
225946
  invalidTrials: { type: "integer" },
225601
225947
  agentIssues: { type: "array" },
225602
225948
  harnessIssues: { type: "array" },
225949
+ actions: {
225950
+ type: "object",
225951
+ 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",
225952
+ properties: { of: { type: "integer" }, made: { type: "array", items: { type: "object", properties: { tool: string7, args: {}, trials: { type: "integer" } } } } }
225953
+ },
225603
225954
  trialsDetail: { type: "array", items: { type: "object", properties: {
225604
225955
  trial: { type: "integer" },
225605
225956
  passed: { type: "boolean" },
@@ -226029,6 +226380,79 @@ async function fetchTrace(source, ref20, env2, f = fetch) {
226029
226380
  return source === "langfuse" ? fromLangfuse(id12, env2, f) : fromLangsmith(id12, env2, f);
226030
226381
  }
226031
226382
 
226383
+ // packages/cli/src/import-people.ts
226384
+ var DEFAULT_IMPORT_MODEL = "openai/gpt-4.1-mini";
226385
+ var EXTRACT = `You read a conversation between a CUSTOMER and an AGENT and write down what the CUSTOMER knows and wants, so that
226386
+ someone else can play the same customer in a new conversation with a different agent. Use only what the customer wrote.
226387
+ The agent's lines are context: they show what the customer was answering. Leave out everything only the agent said or
226388
+ produced (what it looked up, its offers, prices, the ids and options it proposed, what its rules allow), even when the
226389
+ customer went along with it. When the customer picked one of the options the agent offered, record what they picked
226390
+ and why, if they said why.
226391
+
226392
+ Answer in JSON:
226393
+ {"name": "the customer's full name as they gave it, or null",
226394
+ "goal": "one paragraph in the second person ('You want ...'): what they came for, and every condition, preference or
226395
+ limit they stated: what they will and won't accept, how they want it done, what to do if told no",
226396
+ "facts": [{"id": "snake_case", "value": "the fact as they would say it", "about": "what a question must ask about to
226397
+ get it", "exact": true for an id, a name, a number, a date or an amount}],
226398
+ "style": "how they write, in a few words"}
226399
+ One fact per item: an account, order or booking id, a name, an email, a date, a choice they made and why. Include what
226400
+ the first message says. Leave out anything the customer didn't say.`;
226401
+ var REWRITE = `A goal for someone who plays a customer in a test names things the customer only knew because the agent said
226402
+ them in the old conversation (its offers, amounts, ids, flights or dates it found). Write the goal again without them.
226403
+ Where the customer accepted or picked one of them, say what they wanted in their own terms (a criterion, a preference)
226404
+ if the goal gives one; otherwise leave that part out. Keep every other condition, limit and preference as it is, in
226405
+ the second person. Answer in JSON: {"goal": "..."}`;
226406
+ async function rewriteGoal(goal, values2, options3) {
226407
+ const client = new OpenAI({
226408
+ apiKey: options3.apiKey,
226409
+ baseURL: options3.baseUrl ?? "https://openrouter.ai/api/v1",
226410
+ adminAPIKey: null,
226411
+ organization: null,
226412
+ project: null,
226413
+ webhookSecret: null,
226414
+ maxRetries: 2,
226415
+ timeout: 12e4,
226416
+ logLevel: "off"
226417
+ });
226418
+ const response5 = await client.chat.completions.create({
226419
+ model: options3.model,
226420
+ temperature: 0,
226421
+ store: false,
226422
+ response_format: { type: "json_object" },
226423
+ messages: [{ role: "system", content: REWRITE }, { role: "user", content: `GOAL: ${goal}
226424
+ ONLY THE AGENT SAID: ${values2.join("; ")}` }]
226425
+ }, { ...options3.signal !== void 0 && { signal: options3.signal } });
226426
+ const rewritten = JSON.parse(response5.choices[0]?.message?.content ?? "").goal;
226427
+ if (typeof rewritten !== "string" || !rewritten.trim()) throw new Error("the model did not answer with a goal");
226428
+ return rewritten.trim();
226429
+ }
226430
+ async function extractPerson(transcript3, options3) {
226431
+ const client = new OpenAI({
226432
+ apiKey: options3.apiKey,
226433
+ baseURL: options3.baseUrl ?? "https://openrouter.ai/api/v1",
226434
+ adminAPIKey: null,
226435
+ organization: null,
226436
+ project: null,
226437
+ webhookSecret: null,
226438
+ maxRetries: 2,
226439
+ timeout: 12e4,
226440
+ logLevel: "off"
226441
+ });
226442
+ const lines = transcript3.map((line2) => `${line2.role === "user" ? "CUSTOMER" : "AGENT"}: ${line2.content.replace(/\s+/g, " ").trim()}`).join("\n");
226443
+ const response5 = await client.chat.completions.create({
226444
+ model: options3.model,
226445
+ temperature: 0,
226446
+ store: false,
226447
+ response_format: { type: "json_object" },
226448
+ messages: [{ role: "system", content: EXTRACT }, { role: "user", content: lines }]
226449
+ }, { ...options3.signal !== void 0 && { signal: options3.signal } });
226450
+ const parsed3 = JSON.parse(response5.choices[0]?.message?.content ?? "");
226451
+ if (!parsed3 || typeof parsed3 !== "object" || Array.isArray(parsed3)) throw new Error("the model did not answer with a JSON object");
226452
+ const person4 = parsed3;
226453
+ return { ...person4, facts: Array.isArray(person4.facts) ? person4.facts.filter((fact2) => fact2 && typeof fact2 === "object") : [] };
226454
+ }
226455
+
226032
226456
  // packages/cli/src/commands/traces.ts
226033
226457
  function agentToolLines(intake) {
226034
226458
  const tools2 = (intake.agentTools ?? []).map((t) => {
@@ -226042,7 +226466,7 @@ function agentToolLines(intake) {
226042
226466
  function toolLines(scene2) {
226043
226467
  const tools2 = Object.entries(scene2.tools ?? {});
226044
226468
  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";
226469
+ 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
226470
  return [
226047
226471
  " tools (production's answers replayed; observations.jsonl holds them):",
226048
226472
  ...tools2.map(([name5, t]) => ` ${name5}: ${plural5(t.recorded?.length ?? 0, "recorded call")}${t.write ? ", changes something" : ""}${t.mcp ? ", over MCP" : ""}; ${unrecorded(t)}`),
@@ -226328,7 +226752,7 @@ function registerTraces(program2, ctx) {
226328
226752
  ].join("\n");
226329
226753
  });
226330
226754
  });
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) => {
226755
+ 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
226756
  const source = await traceSource(ctx, trace, options3.from);
226333
226757
  if (options3.offline) {
226334
226758
  const made = await importLocally(ctx, source, options3);
@@ -226391,6 +226815,51 @@ async function traceTextLines(text24, name5) {
226391
226815
  }
226392
226816
  return docs2.map((doc) => doc.lines).reduce((merged, next2) => mergeIr2(merged, next2));
226393
226817
  }
226818
+ async function traceConversations(text24, name5) {
226819
+ const { fileToIr: fileToIr2, conversationsOf: conversationsOf2 } = await Promise.resolve().then(() => (init_rebuild(), rebuild_exports));
226820
+ try {
226821
+ return conversationsOf2(fileToIr2(text24, name5));
226822
+ } catch (error64) {
226823
+ throw new AnchaError("USAGE", `${name5}: ${error64 instanceof Error ? error64.message : String(error64)}`);
226824
+ }
226825
+ }
226826
+ async function customersOf(ctx, conversations) {
226827
+ const { agentValuesInGoal: agentValuesInGoal2, customerFacts: customerFacts2, goalWithout: goalWithout2, personByRule: personByRule2 } = await Promise.resolve().then(() => (init_rebuild(), rebuild_exports));
226828
+ const apiKey = ctx.io.env.OPENROUTER_API_KEY, model2 = ctx.io.env.ANCHA_IMPORT_MODEL || DEFAULT_IMPORT_MODEL;
226829
+ let failed = 0;
226830
+ const one7 = async ({ transcript: transcript3, lines }) => {
226831
+ if (transcript3.filter((line2) => line2.role === "user").length < 2) return void 0;
226832
+ if (apiKey) {
226833
+ try {
226834
+ const route11 = { apiKey, model: model2, ...ctx.io.env.ANCHA_JUDGE_BASE_URL && { baseUrl: ctx.io.env.ANCHA_JUDGE_BASE_URL } };
226835
+ const person4 = await extractPerson(transcript3, route11);
226836
+ 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) }));
226837
+ const { kept, dropped } = customerFacts2(person4.facts ?? [], transcript3, world5), left = dropped.map((fact2) => String(fact2.value));
226838
+ let goal = String(person4.goal ?? ""), rewrote = agentValuesInGoal2(goal, left);
226839
+ if (rewrote.length) {
226840
+ goal = await rewriteGoal(goal, rewrote, route11).catch(() => goal);
226841
+ const still = agentValuesInGoal2(goal, rewrote);
226842
+ if (still.length) goal = goalWithout2(goal, still) || goal;
226843
+ rewrote = rewrote.filter((value5) => !agentValuesInGoal2(goal, [value5]).length);
226844
+ }
226845
+ return { person: { ...person4, goal, facts: kept }, transcript: transcript3, by: model2, dropped: left, rewrote };
226846
+ } catch {
226847
+ failed++;
226848
+ }
226849
+ }
226850
+ return { person: personByRule2(transcript3), transcript: transcript3, by: "rule", dropped: [], rewrote: [] };
226851
+ };
226852
+ const people3 = new Array(conversations.length);
226853
+ let next2 = 0;
226854
+ await Promise.all(Array.from({ length: Math.min(8, conversations.length) }, async () => {
226855
+ while (next2 < conversations.length) {
226856
+ const i = next2++;
226857
+ people3[i] = await one7(conversations[i]);
226858
+ }
226859
+ }));
226860
+ return { people: people3, model: apiKey ? model2 : void 0, failed };
226861
+ }
226862
+ 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
226863
  async function traceFileItems(ctx, file3) {
226395
226864
  const { itemsOf: itemsOf2 } = await Promise.resolve().then(() => (init_rebuild(), rebuild_exports));
226396
226865
  return itemsOf2((await traceFileLines(ctx, file3)).lines);
@@ -226408,51 +226877,95 @@ function diffCalls(production3, attempt) {
226408
226877
  };
226409
226878
  }
226410
226879
  async function importLocally(ctx, source, options3) {
226411
- const { text: text24 } = source, lines = await traceTextLines(text24, source.name);
226880
+ const { text: text24 } = source, all8 = await traceConversations(text24, source.name);
226412
226881
  const { rebuild: rebuild2, sceneFiles: sceneFiles2 } = await Promise.resolve().then(() => (init_rebuild(), rebuild_exports));
226413
226882
  const answers = Object.fromEntries(options3.answer.map((pair) => {
226414
226883
  const at3 = pair.indexOf("=");
226415
226884
  if (at3 < 1) throw new AnchaError("USAGE", `--answer needs question=value, got ${pair}`);
226416
226885
  return [pair.slice(0, at3), pair.slice(at3 + 1)];
226417
226886
  }));
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)}
226887
+ const picked = options3.conversation === void 0 ? all8 : all8.filter((c) => c.id === options3.conversation || c.traces.includes(options3.conversation));
226888
+ 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` : ""}` });
226889
+ const base3 = `trace-${createHash68("sha256").update(text24).digest("hex").slice(0, 8)}`, ids2 = /* @__PURE__ */ new Set();
226890
+ const idOf2 = (c) => {
226891
+ if (all8.length === 1) return base3;
226892
+ let id12 = `${base3}-${conversationSlug(c.id)}`;
226893
+ for (let n = 2; ids2.has(id12); n++) id12 = `${base3}-${conversationSlug(c.id)}-${n}`;
226894
+ ids2.add(id12);
226895
+ return id12;
226896
+ };
226897
+ const named3 = new Map(all8.map((c) => [c, idOf2(c)]));
226898
+ const files2 = await Promise.all((options3.examples ?? []).map(async (file3) => (await traceFileLines(ctx, file3)).lines));
226899
+ const customers = await customersOf(ctx, picked);
226900
+ const made = [], skipped = [];
226901
+ for (const [i, conversation3] of picked.entries()) {
226902
+ const examples2 = [...all8.filter((c) => c !== conversation3).map((c) => c.lines), ...files2], customer3 = customers.people[i];
226903
+ try {
226904
+ 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 } }) });
226905
+ } catch (error64) {
226906
+ if (error64.code !== "NO_CALLS") throw error64;
226907
+ 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" });
226908
+ skipped.push(conversation3.id);
226909
+ }
226910
+ }
226911
+ const paths2 = made.map((m) => join55(resolve40(ctx.io.cwd, options3.dest, m.id), "scene.yaml"));
226912
+ if (!options3.force) {
226913
+ 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`);
226914
+ }
226915
+ for (const [i, m] of made.entries()) {
226916
+ const path6 = paths2[i], dir2 = dirname17(path6);
226917
+ await mkdir26(dir2, { recursive: true });
226918
+ const files3 = sceneFiles2(m.made.scene);
226919
+ await writeFile27(path6, (0, import_yaml16.stringify)(files3.scene, { lineWidth: 0 }));
226920
+ if (files3.observations !== void 0) await writeFile27(join55(dir2, "observations.jsonl"), files3.observations);
226921
+ if (m.made.record) await writeFile27(join55(dir2, "production.jsonl"), productionLines(m.made.record));
226922
+ 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
226923
  `);
226437
- await writeFile27(join55(dir2, "provenance.json"), `${JSON.stringify({ summary: made.summary, provenance: made.provenance, questions: made.questions }, null, 2)}
226924
+ 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
226925
  `);
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)
226926
+ await loadSceneFile(path6);
226927
+ }
226928
+ 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 }));
226929
+ const questionLines = (questions2) => questions2.length ? [
226930
+ " 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):",
226931
+ ...questions2.flatMap((q) => [` ${q.id}: ${q.question}`, ` ${q.answer === void 0 ? `default: ${q.default}` : `answered: ${q.answer}`}`])
226932
+ ] : [];
226933
+ const placed = made.filter((m) => m.made.scene.people?.length).length;
226934
+ const dropped = customers.people.reduce((n, c) => n + (c?.dropped?.length ?? 0), 0);
226935
+ const customerLines = !placed ? [] : [
226936
+ 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)`,
226937
+ " 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
226938
  ];
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
- );
226939
+ if (all8.length === 1) {
226940
+ const [m] = made, setup2 = setupOf(m), path6 = paths2[0];
226941
+ const lines2 = [
226942
+ `wrote ${relative12(ctx.io.cwd, path6)} from ${source.label}, on this computer (nothing was uploaded)`,
226943
+ ` ${m.made.summary.observed} observed, ${m.made.summary.inferred} inferred, ${m.made.summary.missing} missing; provenance in provenance.json`,
226944
+ ...toolLines(m.made.scene),
226945
+ ...customerLines,
226946
+ ...questionLines(m.made.questions)
226947
+ ];
226948
+ if (setup2.length) {
226949
+ lines2.push(
226950
+ ` 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(", ")}`,
226951
+ " 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)"
226952
+ );
226953
+ }
226954
+ return { result: { scene: relative12(ctx.io.cwd, path6), summary: m.made.summary, questions: m.made.questions, setup: setup2 }, text: lines2.join("\n") };
226454
226955
  }
226455
- return { result: { scene: relative12(ctx.io.cwd, path6), summary: made.summary, questions: made.questions, setup: setup2 }, text: lines2.join("\n") };
226956
+ const questions = [...new Map(made.flatMap((m) => m.made.questions).reverse().map((q) => [q.id, q])).values()].reverse();
226957
+ const recorded2 = (m) => Object.values(m.made.scene.tools ?? {}).reduce((n, t) => n + (t.recorded?.length ?? 0), 0);
226958
+ const lines = [
226959
+ `wrote ${plural5(made.length, "test")} from ${source.label}, one per conversation, on this computer (nothing was uploaded)`,
226960
+ ...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})`),
226961
+ ...skipped.length ? [` skipped ${plural5(skipped.length, "conversation")} with no tool calls, API calls or input: ${skipped.join(", ")}`] : [],
226962
+ ...made.length > 1 ? [" each test replays its own conversation's calls; the other conversations' calls show simulation how the tools behave"] : [],
226963
+ ...customerLines,
226964
+ ...questionLines(questions)
226965
+ ];
226966
+ const setups = made.filter((m) => m.made.setup.length).length;
226967
+ 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)`);
226968
+ 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
226969
  }
226457
226970
 
226458
226971
  // packages/cli/src/main.ts