@ancha-labs/cli 0.4.22 → 0.4.23

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
@@ -3630,10 +3630,10 @@ var init_execution_support = __esm({
3630
3630
  "agent.input.per_event": sceneOnly,
3631
3631
  "agent.input.events": localOnly,
3632
3632
  "agent.input.http": all,
3633
- "agent.endpoint": localOnly,
3633
+ "agent.endpoint": { ...localOnly, "cloud-vm": true },
3634
3634
  "agent.slack_transport.feed": sceneOnly,
3635
- "agent.slack_transport.http": localOnly,
3636
- "agent.slack_transport.socket": localOnly,
3635
+ "agent.slack_transport.http": { ...localOnly, "cloud-vm": true },
3636
+ "agent.slack_transport.socket": { ...localOnly, "cloud-vm": true },
3637
3637
  "agent.env": sceneOnly,
3638
3638
  "agent.pass_env": sceneOnly,
3639
3639
  "agent.execution": sceneOnly,
@@ -32601,10 +32601,10 @@ function tokenize(text30) {
32601
32601
  return out;
32602
32602
  }
32603
32603
  function parseFormula(text30) {
32604
- const tokens4 = tokenize(text30);
32604
+ const tokens5 = tokenize(text30);
32605
32605
  let at4 = 0;
32606
32606
  const isOp = (value5) => {
32607
- const token4 = tokens4[at4];
32607
+ const token4 = tokens5[at4];
32608
32608
  return token4.kind === "op" && token4.value === value5;
32609
32609
  };
32610
32610
  const expect = (value5) => {
@@ -32614,14 +32614,14 @@ function parseFormula(text30) {
32614
32614
  const level3 = (ops, next2) => () => {
32615
32615
  let left = next2();
32616
32616
  for (; ; ) {
32617
- const token4 = tokens4[at4];
32617
+ const token4 = tokens5[at4];
32618
32618
  if (token4.kind !== "op" || !ops.includes(token4.value)) return left;
32619
32619
  at4++;
32620
32620
  left = { type: "binary", op: token4.value, left, right: next2() };
32621
32621
  }
32622
32622
  };
32623
32623
  const primary3 = () => {
32624
- const token4 = tokens4[at4++];
32624
+ const token4 = tokens5[at4++];
32625
32625
  if (token4.kind === "num") return { type: "number", value: token4.value };
32626
32626
  if (token4.kind === "str") return { type: "text", value: token4.value };
32627
32627
  if (token4.kind === "field") return { type: "field", name: token4.value };
@@ -32646,14 +32646,14 @@ function parseFormula(text30) {
32646
32646
  };
32647
32647
  const unary = () => {
32648
32648
  if (isOp("-") || isOp("+")) {
32649
- const op2 = tokens4[at4++].value;
32649
+ const op2 = tokens5[at4++].value;
32650
32650
  return { type: "unary", op: op2, arg: unary() };
32651
32651
  }
32652
32652
  return primary3();
32653
32653
  };
32654
32654
  const comparison3 = level3(["=", "!=", "<", ">", "<=", ">="], level3(["&"], level3(["+", "-"], level3(["*", "/"], unary))));
32655
32655
  const node5 = comparison3();
32656
- if (tokens4[at4].kind !== "end") throw new FormulaSyntaxError("unexpected text after the formula");
32656
+ if (tokens5[at4].kind !== "end") throw new FormulaSyntaxError("unexpected text after the formula");
32657
32657
  return node5;
32658
32658
  }
32659
32659
  function formulaFieldNames(node5) {
@@ -32912,7 +32912,7 @@ function formatFormulaDate(ms2, format2) {
32912
32912
  return part;
32913
32913
  }
32914
32914
  };
32915
- return format2.replace(FORMAT_TOKENS, (part, literal3) => literal3 ?? token4(part));
32915
+ return format2.replace(FORMAT_TOKENS, (part, literal4) => literal4 ?? token4(part));
32916
32916
  }
32917
32917
  function parseWithFormat(text30, format2) {
32918
32918
  const parts3 = [];
@@ -35574,9 +35574,9 @@ function declarations(scene2) {
35574
35574
  const ref22 = "slack.post" in a ? a["slack.post"].ref : void 0;
35575
35575
  if (ref22 !== void 0) out.push({ name: ref22, kind: "message", path: `world_rules.actors[${i}].slack.post.ref` });
35576
35576
  });
35577
- const github2 = scene2.seed.github;
35578
- github2?.users?.forEach((u, i) => out.push({ name: u.ref, kind: "user", path: `seed.github.users[${i}].ref` }));
35579
- github2?.repos.forEach((r2, i) => {
35577
+ const github3 = scene2.seed.github;
35578
+ github3?.users?.forEach((u, i) => out.push({ name: u.ref, kind: "user", path: `seed.github.users[${i}].ref` }));
35579
+ github3?.repos.forEach((r2, i) => {
35580
35580
  const p2 = `seed.github.repos[${i}]`;
35581
35581
  out.push({ name: r2.ref, kind: "repo", path: `${p2}.ref` });
35582
35582
  r2.commits.forEach((c, j) => out.push({ name: c.ref, kind: "commit", path: `${p2}.commits[${j}].ref` }));
@@ -35708,9 +35708,9 @@ function validateRefs(scene2) {
35708
35708
  const decl = use(path7, value5, "user");
35709
35709
  if (decl && !/^seed\.(github|slack)\.users\[/.test(decl.path)) issues.push({ path: path7, message: `${value5} has no GitHub identity; use a GitHub or Slack seed user` });
35710
35710
  };
35711
- const github2 = scene2.seed.github;
35712
- if (github2?.bot !== void 0) useGitHubUser("seed.github.bot", github2.bot);
35713
- github2?.repos.forEach((r2, i) => {
35711
+ const github3 = scene2.seed.github;
35712
+ if (github3?.bot !== void 0) useGitHubUser("seed.github.bot", github3.bot);
35713
+ github3?.repos.forEach((r2, i) => {
35714
35714
  const p2 = `seed.github.repos[${i}]`;
35715
35715
  r2.commits.forEach((c, j) => {
35716
35716
  if (c.author !== void 0) useGitHubUser(`${p2}.commits[${j}].author`, c.author);
@@ -35742,7 +35742,7 @@ function validateRefs(scene2) {
35742
35742
  r2.check_runs?.forEach((c, j) => use(`${p2}.check_runs[${j}].commit`, c.commit, "commit"));
35743
35743
  r2.collaborators?.forEach((c, j) => useGitHubUser(`${p2}.collaborators[${j}].user`, c.user));
35744
35744
  });
35745
- github2?.orgs?.forEach((org5, i) => org5.members.forEach((member4, j) => useGitHubUser(`seed.github.orgs[${i}].members[${j}].user`, member4.user)));
35745
+ github3?.orgs?.forEach((org5, i) => org5.members.forEach((member4, j) => useGitHubUser(`seed.github.orgs[${i}].members[${j}].user`, member4.user)));
35746
35746
  scene2.world_rules?.pipelines?.forEach((p2, i) => use(`world_rules.pipelines[${i}].repo`, p2.repo, "repo"));
35747
35747
  scene2.world_rules?.actors?.forEach((a, i) => {
35748
35748
  const p2 = `world_rules.actors[${i}]`;
@@ -37860,9 +37860,9 @@ ${indent2}`) + "'";
37860
37860
  return quotedString(value5, ctx);
37861
37861
  }
37862
37862
  const indent2 = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value5) ? " " : "");
37863
- const literal3 = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.Scalar.BLOCK_FOLDED ? false : type === Scalar.Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value5, lineWidth, indent2.length);
37863
+ const literal4 = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.Scalar.BLOCK_FOLDED ? false : type === Scalar.Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value5, lineWidth, indent2.length);
37864
37864
  if (!value5)
37865
- return literal3 ? "|\n" : ">\n";
37865
+ return literal4 ? "|\n" : ">\n";
37866
37866
  let chomp;
37867
37867
  let endStart;
37868
37868
  for (endStart = value5.length; endStart > 0; --endStart) {
@@ -37911,7 +37911,7 @@ ${indent2}`) + "'";
37911
37911
  if (onComment)
37912
37912
  onComment();
37913
37913
  }
37914
- if (!literal3) {
37914
+ if (!literal4) {
37915
37915
  const foldedValue = value5.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent2}`);
37916
37916
  let literalFallback = false;
37917
37917
  const foldOptions = getFoldOptions(ctx, true);
@@ -40355,7 +40355,7 @@ ${pointer2}
40355
40355
  var require_resolve_props = __commonJS({
40356
40356
  "node_modules/.pnpm/yaml@2.9.1/node_modules/yaml/dist/compose/resolve-props.js"(exports) {
40357
40357
  "use strict";
40358
- function resolveProps(tokens4, { flow, indicator, next: next2, offset: offset18, onError, parentIndent, startOnNewline }) {
40358
+ function resolveProps(tokens5, { flow, indicator, next: next2, offset: offset18, onError, parentIndent, startOnNewline }) {
40359
40359
  let spaceBefore = false;
40360
40360
  let atNewline = startOnNewline;
40361
40361
  let hasSpace = startOnNewline;
@@ -40370,7 +40370,7 @@ var require_resolve_props = __commonJS({
40370
40370
  let comma = null;
40371
40371
  let found = null;
40372
40372
  let start2 = null;
40373
- for (const token4 of tokens4) {
40373
+ for (const token4 of tokens5) {
40374
40374
  if (reqSpace) {
40375
40375
  if (token4.type !== "space" && token4.type !== "newline" && token4.type !== "comma")
40376
40376
  onError(token4.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
@@ -40461,7 +40461,7 @@ var require_resolve_props = __commonJS({
40461
40461
  hasSpace = false;
40462
40462
  }
40463
40463
  }
40464
- const last = tokens4[tokens4.length - 1];
40464
+ const last = tokens5[tokens5.length - 1];
40465
40465
  const end = last ? last.offset + last.source.length : offset18;
40466
40466
  if (reqSpace && next2 && next2.type !== "space" && next2.type !== "newline" && next2.type !== "comma" && (next2.type !== "scalar" || next2.source !== "")) {
40467
40467
  onError(next2.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
@@ -41801,8 +41801,8 @@ ${cb}` : comment10;
41801
41801
  * @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.
41802
41802
  * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
41803
41803
  */
41804
- *compose(tokens4, forceDoc = false, endOffset = -1) {
41805
- for (const token4 of tokens4)
41804
+ *compose(tokens5, forceDoc = false, endOffset = -1) {
41805
+ for (const token4 of tokens5)
41806
41806
  yield* this.next(token4);
41807
41807
  yield* this.end(forceDoc, endOffset);
41808
41808
  }
@@ -44096,7 +44096,7 @@ function toolIssues(scene2) {
44096
44096
  }
44097
44097
  return issues;
44098
44098
  }
44099
- async function readObservations(doc, dir2) {
44099
+ async function readToolObservations(doc, dir2) {
44100
44100
  const tools2 = doc?.tools;
44101
44101
  if (!tools2 || typeof tools2 !== "object") return;
44102
44102
  const files2 = /* @__PURE__ */ new Map();
@@ -44220,7 +44220,7 @@ function validPath(value5) {
44220
44220
  return !value5.includes("\0") && !value5.split("/").some((p2) => p2 === "" || p2 === "." || p2 === "..");
44221
44221
  }
44222
44222
  function githubSeedIssues(scene2) {
44223
- const github2 = scene2.seed.github;
44223
+ const github3 = scene2.seed.github;
44224
44224
  const issues = [];
44225
44225
  const pathIssue = (path7, value5) => {
44226
44226
  if (!validPath(value5)) issues.push({ path: path7, message: "invalid path: use a relative path without empty, . or .. segments or NUL", hint: "use a path such as feature/fix or src/db.ts" });
@@ -44229,17 +44229,17 @@ function githubSeedIssues(scene2) {
44229
44229
  if (!validPath(value5)) pathIssue(path7, value5);
44230
44230
  else if (!validGitBranch(value5)) issues.push({ path: path7, message: "invalid Git branch name", hint: "use a literal Git branch name such as main or feature/fix" });
44231
44231
  };
44232
- if (!github2 && scene2.twins.includes("github")) {
44232
+ if (!github3 && scene2.twins.includes("github")) {
44233
44233
  issues.push({ path: "seed.github", message: "required when twins includes github", hint: "add a seed.github section with repos" });
44234
44234
  }
44235
44235
  const logins = /* @__PURE__ */ new Set();
44236
- github2?.users?.forEach((user8, i) => {
44236
+ github3?.users?.forEach((user8, i) => {
44237
44237
  const key4 = user8.login.toLowerCase();
44238
44238
  if (logins.has(key4)) issues.push({ path: `seed.github.users[${i}].login`, message: `duplicate GitHub login "${user8.login}" (case-insensitive)` });
44239
44239
  logins.add(key4);
44240
44240
  });
44241
44241
  const orgLogins = /* @__PURE__ */ new Set();
44242
- github2?.orgs?.forEach((org5, i) => {
44242
+ github3?.orgs?.forEach((org5, i) => {
44243
44243
  const key4 = org5.login.toLowerCase();
44244
44244
  if (orgLogins.has(key4)) issues.push({ path: `seed.github.orgs[${i}].login`, message: `duplicate organization "${org5.login}" (case-insensitive)` });
44245
44245
  if (logins.has(key4)) issues.push({ path: `seed.github.orgs[${i}].login`, message: `"${org5.login}" is a user login, not an organization` });
@@ -44252,7 +44252,7 @@ function githubSeedIssues(scene2) {
44252
44252
  members4.add(name5);
44253
44253
  });
44254
44254
  });
44255
- github2?.repos.forEach((r2, i) => {
44255
+ github3?.repos.forEach((r2, i) => {
44256
44256
  const seen = /* @__PURE__ */ new Set();
44257
44257
  r2.collaborators?.forEach((c, j) => {
44258
44258
  const name5 = refName5(c.user);
@@ -44262,7 +44262,7 @@ function githubSeedIssues(scene2) {
44262
44262
  });
44263
44263
  });
44264
44264
  const owners = /* @__PURE__ */ new Map();
44265
- for (const r2 of github2?.repos ?? []) for (const c of r2.commits) owners.set(c.ref, r2.ref);
44265
+ for (const r2 of github3?.repos ?? []) for (const c of r2.commits) owners.set(c.ref, r2.ref);
44266
44266
  const sameRepo = (path7, value5, repo4) => {
44267
44267
  const name5 = refName5(value5);
44268
44268
  const owner3 = name5 === void 0 ? void 0 : owners.get(name5);
@@ -44273,7 +44273,7 @@ function githubSeedIssues(scene2) {
44273
44273
  return owner3 === repo4 ? name5 : void 0;
44274
44274
  };
44275
44275
  const repoNames = /* @__PURE__ */ new Set();
44276
- github2?.repos.forEach((r2, i) => {
44276
+ github3?.repos.forEach((r2, i) => {
44277
44277
  const p2 = `seed.github.repos[${i}]`;
44278
44278
  if (repoNames.has(r2.name.toLowerCase())) issues.push({ path: `${p2}.name`, message: `duplicate repo name "${r2.name}" (case-insensitive)` });
44279
44279
  repoNames.add(r2.name.toLowerCase());
@@ -44617,7 +44617,7 @@ async function loadSceneFile(path7) {
44617
44617
  });
44618
44618
  }
44619
44619
  const doc = parseSceneYaml(text30);
44620
- await readObservations(doc, dirname(path7));
44620
+ await readToolObservations(doc, dirname(path7));
44621
44621
  return parseScene(doc);
44622
44622
  }
44623
44623
  function sceneJsonSchema() {
@@ -47578,7 +47578,7 @@ function testToSceneInput(test3, world5) {
47578
47578
  ...test3.deadline !== void 0 && { timeout: test3.deadline },
47579
47579
  ...test3.pass !== void 0 && { pass: test3.pass }
47580
47580
  });
47581
- return { ...input5, ...test3.until !== void 0 && { until: test3.until } };
47581
+ return { ...input5, ...test3.function_tools && { tools: test3.function_tools }, ...test3.until !== void 0 && { until: test3.until } };
47582
47582
  }
47583
47583
  function testPaths(text30, test3) {
47584
47584
  const field6 = (name5) => ({ channel: "in", user: "from" })[name5] ?? name5;
@@ -47634,6 +47634,7 @@ var init_test_file = __esm({
47634
47634
  };
47635
47635
  TestFileSchema = external_exports.strictObject({
47636
47636
  ...fields2,
47637
+ function_tools: SceneSchema.shape.tools,
47637
47638
  world: external_exports.union([WorldId, external_exports.record(external_exports.string(), external_exports.unknown())], { error: WORLD_ERROR }),
47638
47639
  until: external_exports.unknown().optional(),
47639
47640
  checks: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional(),
@@ -47641,6 +47642,7 @@ var init_test_file = __esm({
47641
47642
  });
47642
47643
  TestFileDocument = external_exports.strictObject({
47643
47644
  ...fields2,
47645
+ function_tools: SceneSchema.shape.tools,
47644
47646
  world: external_exports.union([WorldId, WorldBodySchema]).describe("A world file's id (ancha/worlds/<id>.yaml), or the world inline"),
47645
47647
  until: SceneSchema.shape.until,
47646
47648
  checks: SceneSchema.shape.checks.optional(),
@@ -49182,6 +49184,53 @@ var init_tool_completion = __esm({
49182
49184
  }
49183
49185
  });
49184
49186
 
49187
+ // packages/core/src/function-tool-observation.ts
49188
+ function requiredFunctionTools(scene2) {
49189
+ const names5 = Object.keys(scene2.tools ?? {}).filter((name5) => !scene2.tools[name5].mcp);
49190
+ const patterns = [];
49191
+ const visit4 = (value5) => {
49192
+ if (!value5 || typeof value5 !== "object") return;
49193
+ for (const [key4, item2] of Object.entries(value5)) {
49194
+ if (key4 === "called" || key4 === "not_called") patterns.push(...(Array.isArray(item2) ? item2 : [item2]).filter((p2) => typeof p2 === "string"));
49195
+ else visit4(item2);
49196
+ }
49197
+ };
49198
+ for (const check4 of scene2.checks) if (scene2.pass.includes(check4.id)) visit4(check4);
49199
+ return names5.filter((name5) => patterns.some((pattern) => {
49200
+ const p2 = pattern.trim();
49201
+ const bare = /^([A-Za-z_][\w.-]{0,127})(?:\s+\{.*\})?$/s.exec(p2);
49202
+ const [method2, path7] = p2.split(/\s+/);
49203
+ return p2 === "*" || bare?.[1] === name5 || (method2 === "POST" || method2 === "*") && (path7 === `/tools/${name5}` || path7 === "/tools/*");
49204
+ })).sort();
49205
+ }
49206
+ function functionWiringMessage(missing9) {
49207
+ return `Connect function tools: ${missing9.join(", ")}. Python: import ancha; pass ancha.wrap_tools([...]) to the framework and call ancha.entry(run). JavaScript: import { wrapTools, entry } from '@ancha-labs/tools'; pass wrapTools([...]) to the framework and call await entry(run). Register tools before the task starts.`;
49208
+ }
49209
+ function functionToolWiringIssues(observation) {
49210
+ return observation.missing.length ? [{ kind: "tools", owner: "harness", service: "tools", message: functionWiringMessage(observation.missing) }] : [];
49211
+ }
49212
+ var functionToolObservationSchema;
49213
+ var init_function_tool_observation = __esm({
49214
+ "packages/core/src/function-tool-observation.ts"() {
49215
+ "use strict";
49216
+ init_zod();
49217
+ functionToolObservationSchema = external_exports.strictObject({
49218
+ registered: external_exports.array(external_exports.string()),
49219
+ complete: external_exports.boolean(),
49220
+ protocol_version: external_exports.number().int().nonnegative().optional(),
49221
+ required: external_exports.array(external_exports.string()),
49222
+ missing: external_exports.array(external_exports.string()),
49223
+ tools: external_exports.array(external_exports.strictObject({
49224
+ name: external_exports.string(),
49225
+ registered: external_exports.boolean(),
49226
+ called: external_exports.number().int().nonnegative(),
49227
+ completed: external_exports.number().int().nonnegative(),
49228
+ pending: external_exports.number().int().nonnegative()
49229
+ }))
49230
+ });
49231
+ }
49232
+ });
49233
+
49185
49234
  // packages/core/src/index.ts
49186
49235
  var init_src = __esm({
49187
49236
  "packages/core/src/index.ts"() {
@@ -49258,6 +49307,7 @@ var init_src = __esm({
49258
49307
  init_carrier_portal();
49259
49308
  init_tool_call_trace();
49260
49309
  init_tool_completion();
49310
+ init_function_tool_observation();
49261
49311
  }
49262
49312
  });
49263
49313
 
@@ -49405,8 +49455,11 @@ function validate3(raw3, issues) {
49405
49455
  }
49406
49456
  }
49407
49457
  if (raw3.agent.command !== void 0) {
49408
- if (checkString(raw3.agent.command, "agent.command", issues) && agent.mode !== "endpoint") agent.command = raw3.agent.command;
49409
- for (const field6 of endpointFields) if (raw3.agent[field6] !== void 0) issues.push({ path: `agent.${field6}`, message: "conflicts with agent.command" });
49458
+ if (checkString(raw3.agent.command, "agent.command", issues)) {
49459
+ if (agent.mode === "endpoint" && raw3.agent.slack_transport === "http") agent.start = raw3.agent.command;
49460
+ else if (agent.mode !== "endpoint") agent.command = raw3.agent.command;
49461
+ }
49462
+ for (const field6 of endpointFields) if (raw3.agent[field6] !== void 0 && !(endpoint2 && raw3.agent.slack_transport === "http" && field6 !== "start")) issues.push({ path: `agent.${field6}`, message: "conflicts with agent.command" });
49410
49463
  }
49411
49464
  if (!endpoint2 && raw3.agent.command === void 0) {
49412
49465
  for (const field6 of endpointFields) if (raw3.agent[field6] !== void 0) issues.push({ path: `agent.${field6}`, message: "requires agent.url" });
@@ -49598,7 +49651,7 @@ function validateEndpointAgent(agent, parallel) {
49598
49651
  }
49599
49652
  if (agent.slackTransport === "socket") throw new AnchaError("CONFIG_INVALID", "endpoint mode cannot use slack_transport: socket; run a Socket bot with agent.command");
49600
49653
  if (agent.start !== void 0 && agent.setupUrl !== void 0) throw new AnchaError("CONFIG_INVALID", "agent.start conflicts with agent.setup_url");
49601
- if (agent.start !== void 0 && agent.readyUrl === void 0) throw new AnchaError("CONFIG_INVALID", "agent.ready_url is required with agent.start");
49654
+ if (agent.start !== void 0 && agent.readyUrl === void 0 && agent.slackTransport !== "http") throw new AnchaError("CONFIG_INVALID", "agent.ready_url is required with agent.start");
49602
49655
  if (agent.start === void 0 && agent.setupUrl === void 0) throw new AnchaError("CONFIG_INVALID", "agent.setup_url is required for an external endpoint");
49603
49656
  const vars = { ...URL_TEMPLATE_VARS, ...agent.start !== void 0 && { "agent.port": "34567" } };
49604
49657
  const url4 = renderAgentUrl(agent.url, { ...vars, service: "slack" });
@@ -49606,7 +49659,7 @@ function validateEndpointAgent(agent, parallel) {
49606
49659
  if (agent.setupUrl !== void 0) renderAgentUrl(agent.setupUrl, vars);
49607
49660
  if (agent.start !== void 0 && usesPort(agent.url) && !loopback(new URL(url4).hostname)) throw new AnchaError("CONFIG_INVALID", "managed dynamic agent URLs must use loopback hosts");
49608
49661
  if (agent.readyUrl !== void 0 && usesPort(agent.readyUrl) && !loopback(new URL(renderAgentUrl(agent.readyUrl, vars)).hostname)) throw new AnchaError("CONFIG_INVALID", "managed dynamic readiness URLs must use loopback hosts");
49609
- if (parallel > 1 && (agent.start === void 0 || !hasDynamicPort(agent.url, { ...vars, service: "slack" }) || agent.readyUrl === void 0 || !hasDynamicPort(agent.readyUrl, vars))) {
49662
+ if (parallel > 1 && (agent.start === void 0 || !hasDynamicPort(agent.url, { ...vars, service: "slack" }) || (agent.readyUrl === void 0 ? agent.slackTransport !== "http" : !hasDynamicPort(agent.readyUrl, vars)))) {
49610
49663
  throw new AnchaError("CONFIG_INVALID", "endpoint parallel > 1 requires agent.start and {{agent.port}} in both agent.url and agent.ready_url", { hint: "use parallel: 1 for fixed or external endpoints" });
49611
49664
  }
49612
49665
  }
@@ -68319,9 +68372,9 @@ function personAccounts(env2, person5) {
68319
68372
  const row2 = env2.store.db.prepare("SELECT id FROM slack_users WHERE ref = ?").get(slack2);
68320
68373
  if (row2) out.slack = row2.id;
68321
68374
  }
68322
- const github2 = person5.accounts.github === void 0 ? void 0 : refName6(person5.accounts.github);
68323
- if (github2 !== void 0 && hasTable3(env2, "github_users")) {
68324
- const row2 = env2.store.db.prepare("SELECT id, login FROM github_users WHERE ref = ?").get(github2);
68375
+ const github3 = person5.accounts.github === void 0 ? void 0 : refName6(person5.accounts.github);
68376
+ if (github3 !== void 0 && hasTable3(env2, "github_users")) {
68377
+ const row2 = env2.store.db.prepare("SELECT id, login FROM github_users WHERE ref = ?").get(github3);
68325
68378
  if (row2) out.github = { id: String(row2.id), login: row2.login };
68326
68379
  }
68327
68380
  if (person5.accounts.gmail !== void 0 && hasTable3(env2, "gmail_mailboxes")) {
@@ -70135,15 +70188,15 @@ function botUser(ctx) {
70135
70188
  return user8;
70136
70189
  }
70137
70190
  function seed2(ctx) {
70138
- const github2 = ctx.scene.seed.github;
70139
- if (!github2) throw new AnchaError("SCENE_INVALID", "seed.github: required when twins includes github");
70191
+ const github3 = ctx.scene.seed.github;
70192
+ if (!github3) throw new AnchaError("SCENE_INVALID", "seed.github: required when twins includes github");
70140
70193
  ctx.store.db.transaction(() => {
70141
70194
  const insertUser2 = (ref22, login2, name5, email11, bot2) => {
70142
70195
  const id14 = resourceId(ctx);
70143
70196
  ctx.store.db.prepare("INSERT INTO github_users (id,ref,login,name,email,is_bot) VALUES (?,?,?,?,?,?)").run(id14, ref22, login2, name5, email11 ?? null, bot2 ? 1 : 0);
70144
70197
  return id14;
70145
70198
  };
70146
- for (const u of github2.users ?? []) {
70199
+ for (const u of github3.users ?? []) {
70147
70200
  const id14 = insertUser2(u.ref, u.login, u.name ?? u.login, u.email, false);
70148
70201
  ctx.refs.register(u.ref, "user", "github", String(id14));
70149
70202
  }
@@ -70152,20 +70205,20 @@ function seed2(ctx) {
70152
70205
  insertUser2(u.ref, login2, u.real_name ?? u.name, u.email, u.is_bot ?? false);
70153
70206
  }
70154
70207
  let botId2;
70155
- if (github2.bot) botId2 = userForRef(ctx, github2.bot).id;
70208
+ if (github3.bot) botId2 = userForRef(ctx, github3.bot).id;
70156
70209
  else {
70157
70210
  const login2 = derivedLogin(ctx, "ancha-bot");
70158
70211
  botId2 = insertUser2(null, login2, "Ancha Bot", void 0, true);
70159
70212
  }
70160
70213
  ctx.store.meta.set("github:bot-user", String(botId2));
70161
70214
  const bot = botUser(ctx), at4 = ctx.clock.now().toISOString();
70162
- for (const org5 of github2.orgs ?? []) {
70215
+ for (const org5 of github3.orgs ?? []) {
70163
70216
  if (ctx.store.db.prepare("SELECT 1 FROM github_users WHERE login = ?").get(org5.login)) throw new AnchaError("SCENE_INVALID", `seed.github.orgs: ${org5.login} is a user login, not an organization`);
70164
70217
  if (!ctx.store.db.prepare("SELECT 1 FROM github_organizations WHERE login = ?").get(org5.login)) ctx.store.db.prepare("INSERT INTO github_organizations (id,login) VALUES (?,?)").run(resourceId(ctx), org5.login);
70165
70218
  const orgId = ctx.store.db.prepare("SELECT id FROM github_organizations WHERE login = ?").get(org5.login).id;
70166
70219
  for (const member4 of org5.members) ctx.store.db.prepare("INSERT INTO github_org_members (org_id,user_id,role) VALUES (?,?,?)").run(orgId, userForRef(ctx, member4.user).id, member4.role);
70167
70220
  }
70168
- for (const repo4 of github2.repos) {
70221
+ for (const repo4 of github3.repos) {
70169
70222
  const [owner3, name5] = repo4.name.split("/"), numbers2 = githubSeedNumbers(repo4);
70170
70223
  if (!ctx.store.db.prepare("SELECT 1 FROM github_users WHERE login = ?").get(owner3) && !ctx.store.db.prepare("SELECT 1 FROM github_organizations WHERE login = ?").get(owner3)) {
70171
70224
  ctx.store.db.prepare("INSERT INTO github_organizations (id,login) VALUES (?,?)").run(resourceId(ctx), owner3);
@@ -74410,10 +74463,10 @@ var init_node = __esm({
74410
74463
  #index;
74411
74464
  #varIndex;
74412
74465
  #children = createNullObject();
74413
- insert(tokens4, index, paramMap, context3, isStatic) {
74466
+ insert(tokens5, index, paramMap, context3, isStatic) {
74414
74467
  let node5 = this;
74415
- for (let i = 0, len = tokens4.length; i < len; i++) {
74416
- const token4 = tokens4[i];
74468
+ for (let i = 0, len = tokens5.length; i < len; i++) {
74469
+ const token4 = tokens5[i];
74417
74470
  const pattern = token4.length === 1 ? token4 === "*" ? i === len - 1 ? [
74418
74471
  "",
74419
74472
  "",
@@ -74505,15 +74558,15 @@ var init_trie = __esm({
74505
74558
  });
74506
74559
  if (!replaced3) break;
74507
74560
  }
74508
- const tokens4 = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
74561
+ const tokens5 = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
74509
74562
  for (let i = groups.length - 1; i >= 0; i--) {
74510
74563
  const [mark] = groups[i];
74511
- for (let j = tokens4.length - 1; j >= 0; j--) if (tokens4[j].indexOf(mark) !== -1) {
74512
- tokens4[j] = tokens4[j].replace(mark, groups[i][1]);
74564
+ for (let j = tokens5.length - 1; j >= 0; j--) if (tokens5[j].indexOf(mark) !== -1) {
74565
+ tokens5[j] = tokens5[j].replace(mark, groups[i][1]);
74513
74566
  break;
74514
74567
  }
74515
74568
  }
74516
- this.#root.insert(tokens4, this.#index, paramAssoc, this.#context, false);
74569
+ this.#root.insert(tokens5, this.#index, paramAssoc, this.#context, false);
74517
74570
  this.paths[path7] = [this.#index++, paramAssoc];
74518
74571
  }
74519
74572
  buildRegExp() {
@@ -75171,9 +75224,9 @@ function searchRows(ctx, type) {
75171
75224
  const versions2 = ctx.store.db.prepare("SELECT v.data FROM hubspot_versions v JOIN (SELECT id,MAX(ordinal) ordinal FROM hubspot_versions WHERE type=? AND visible_ms<=? GROUP BY id) latest ON v.ordinal=latest.ordinal ORDER BY v.ordinal").all(type, ctx.clock.nowMs());
75172
75225
  return versions2.map((v) => JSON.parse(v.data)).filter((record29) => !record29.archived && !rawRecord(ctx, type, record29.id)?.archived && visible(ctx, type, record29.id));
75173
75226
  }
75174
- function linkSpec(from, to, identifier4) {
75175
- const spec = hubspotAssociationTypes.find((type) => type.from === from && type.to === to && (String(type.id) === String(identifier4) || type.name === identifier4));
75176
- if (!spec) unsupported3(`association ${from} to ${to}, type ${identifier4}`);
75227
+ function linkSpec(from, to, identifier5) {
75228
+ const spec = hubspotAssociationTypes.find((type) => type.from === from && type.to === to && (String(type.id) === String(identifier5) || type.name === identifier5));
75229
+ if (!spec) unsupported3(`association ${from} to ${to}, type ${identifier5}`);
75177
75230
  return spec;
75178
75231
  }
75179
75232
  function writePair(ctx, from, fromId, to, toId, typeId) {
@@ -75197,8 +75250,8 @@ function associated(ctx, from, fromId, to) {
75197
75250
  return target5 && !target5.archived && visible(ctx, to, row2.to_id);
75198
75251
  }).map((row2) => ({ id: row2.to_id, type: linkSpec(from, to, row2.type_id).name }));
75199
75252
  }
75200
- function associate(ctx, from, fromId, to, toId, identifier4) {
75201
- const spec = linkSpec(from, to, identifier4);
75253
+ function associate(ctx, from, fromId, to, toId, identifier5) {
75254
+ const spec = linkSpec(from, to, identifier5);
75202
75255
  getRecord(ctx, from, fromId, false, void 0, "write");
75203
75256
  getRecord(ctx, to, toId);
75204
75257
  if ([1, 2, 5, 6].includes(spec.id)) {
@@ -75212,8 +75265,8 @@ function associate(ctx, from, fromId, to, toId, identifier4) {
75212
75265
  if (writeLink(ctx, from, fromId, to, toId, spec.id)) ctx.store.db.prepare("INSERT INTO hubspot_link_history(at,operation,data) VALUES(?,?,?)").run(ctx.clock.now().toISOString(), "associate", JSON.stringify({ from: { type: from, id: fromId }, to: { type: to, id: toId }, typeId: spec.id }));
75213
75266
  return { from: { id: fromId }, to: { id: toId }, type: spec.name };
75214
75267
  }
75215
- function disassociate(ctx, from, fromId, to, toId, identifier4) {
75216
- const spec = linkSpec(from, to, identifier4);
75268
+ function disassociate(ctx, from, fromId, to, toId, identifier5) {
75269
+ const spec = linkSpec(from, to, identifier5);
75217
75270
  getRecord(ctx, from, fromId, false, void 0, "write");
75218
75271
  getRecord(ctx, to, toId);
75219
75272
  const ids2 = [spec.id];
@@ -76798,7 +76851,7 @@ function decodeQuotedPrintable(text30) {
76798
76851
  return Buffer.from(bytes3);
76799
76852
  }
76800
76853
  function parseHeaderParams(value5) {
76801
- const tokens4 = [];
76854
+ const tokens5 = [];
76802
76855
  let current = "", quoted4 = false;
76803
76856
  for (let i = 0; i < value5.length; i++) {
76804
76857
  const ch = value5[i];
@@ -76811,16 +76864,16 @@ function parseHeaderParams(value5) {
76811
76864
  continue;
76812
76865
  }
76813
76866
  if (ch === ";" && !quoted4) {
76814
- tokens4.push(current);
76867
+ tokens5.push(current);
76815
76868
  current = "";
76816
76869
  continue;
76817
76870
  }
76818
76871
  current += ch;
76819
76872
  }
76820
- tokens4.push(current);
76873
+ tokens5.push(current);
76821
76874
  const params10 = {};
76822
76875
  const extended2 = {};
76823
- for (const token4 of tokens4.slice(1)) {
76876
+ for (const token4 of tokens5.slice(1)) {
76824
76877
  const eq = token4.indexOf("=");
76825
76878
  if (eq < 1) continue;
76826
76879
  const key4 = token4.slice(0, eq).trim().toLowerCase(), val = token4.slice(eq + 1).trim();
@@ -76848,7 +76901,7 @@ function parseHeaderParams(value5) {
76848
76901
  });
76849
76902
  params10[name5] = decodeCharset(Buffer.concat(bytes3), charset);
76850
76903
  }
76851
- return { value: tokens4[0].trim(), params: params10 };
76904
+ return { value: tokens5[0].trim(), params: params10 };
76852
76905
  }
76853
76906
  function splitHeaders(block2) {
76854
76907
  const headers = [];
@@ -77636,7 +77689,7 @@ function socketPost(socketPath) {
77636
77689
  function httpPeopleModel(options4) {
77637
77690
  const models = options4.models ?? DEFAULT_PEOPLE_MODELS;
77638
77691
  const post5 = options4.post ?? (options4.socketPath !== void 0 ? socketPost(options4.socketPath) : fetchPost);
77639
- const sleep15 = options4.sleep ?? defaultSleep;
77692
+ const sleep16 = options4.sleep ?? defaultSleep;
77640
77693
  const url4 = `${options4.baseUrl.replace(/\/+$/, "")}/chat/completions`;
77641
77694
  return {
77642
77695
  async complete(request2, signal) {
@@ -77663,7 +77716,7 @@ function httpPeopleModel(options4) {
77663
77716
  } catch (error65) {
77664
77717
  if (signal.aborted) throw error65;
77665
77718
  if (!options4.relay && options4.socketPath === void 0 && attempt < MAX_RETRIES) {
77666
- await sleep15(1e3 * (attempt + 1), signal);
77719
+ await sleep16(1e3 * (attempt + 1), signal);
77667
77720
  continue;
77668
77721
  }
77669
77722
  if (options4.relay || options4.socketPath !== void 0) {
@@ -77673,7 +77726,7 @@ function httpPeopleModel(options4) {
77673
77726
  }
77674
77727
  if ((response5.status === 429 || response5.status === 503 && response5.headers["retry-after"] !== void 0) && attempt < MAX_RETRIES) {
77675
77728
  const after = Number(response5.headers["retry-after"]);
77676
- await sleep15(Math.min(MAX_RETRY_WAIT_MS, Number.isFinite(after) && after > 0 ? after * 1e3 : 2e3 * (attempt + 1)), signal);
77729
+ await sleep16(Math.min(MAX_RETRY_WAIT_MS, Number.isFinite(after) && after > 0 ? after * 1e3 : 2e3 * (attempt + 1)), signal);
77677
77730
  continue;
77678
77731
  }
77679
77732
  let json35;
@@ -78356,8 +78409,8 @@ var init_engine = __esm({
78356
78409
  return;
78357
78410
  }
78358
78411
  const [repoId, number7] = place2.slice("github:".length).split("#").map(Number);
78359
- const github2 = this.#everyone().find((entry3) => entry3.person.ref === ref22)?.accounts.github;
78360
- const merged = mergePull(env2.ctxFor("github"), repoId, number7, {}, github2 === void 0 ? void 0 : Number(github2.id));
78412
+ const github3 = this.#everyone().find((entry3) => entry3.person.ref === ref22)?.accounts.github;
78413
+ const merged = mergePull(env2.ctxFor("github"), repoId, number7, {}, github3 === void 0 ? void 0 : Number(github3.id));
78361
78414
  env2.trace.record({ source: "world", service: "github", method: "ACTION", path: "people.merge", request: { person: ref22, repo: repoId, number: number7 }, response: { sha: merged.sha } });
78362
78415
  });
78363
78416
  return;
@@ -79424,6 +79477,13 @@ function decide(ctx, name5, args) {
79424
79477
  ctx.store.db.prepare("INSERT INTO agent_tool_calls (key, n) VALUES (?, 1) ON CONFLICT(key) DO UPDATE SET n=n+1").run(callKey2);
79425
79478
  const policy = tool?.unrecorded ?? (tool?.write ? "fail" : "simulate");
79426
79479
  const reached = Number(getState(ctx, "reached") ?? 0);
79480
+ let selected2 = Math.min(n2, same3.length - 1);
79481
+ for (let i = same3.length - 1; i > selected2; i--) if (same3[i].atMs <= reached) {
79482
+ selected2 = i;
79483
+ break;
79484
+ }
79485
+ const observation = same3[selected2];
79486
+ if (observation && observation.result === void 0 && observation.error === void 0) return { source: "failed", error: `Recorded call to ${name5} needs a result or error. Capture its outcome and import the trace again.` };
79427
79487
  const simulationKey = `${callKey2} revision:${getState(ctx, "revision") ?? "0"}${tool?.schema ? ` schema:${schemaFingerprint(tool.schema)}` : ""}`;
79428
79488
  if (policy === "run" && (tool?.write || getState(ctx, "run:changed") !== void 0 || n2 >= same3.length || same3[n2].atMs >= productionFirstWrite(ctx))) {
79429
79489
  if (tool?.write) {
@@ -79439,14 +79499,14 @@ function decide(ctx, name5, args) {
79439
79499
  index = i;
79440
79500
  break;
79441
79501
  }
79442
- const observation = n2 < same3.length ? same3[index] : void 0;
79443
- if (tool.write && observation?.error !== void 0) {
79444
- setState(ctx, "reached", String(Math.max(reached, observation.endMs)));
79445
- return { source: "replayed", error: observation.error, ...observation.raw !== void 0 && { raw: observation.raw, wrap: observation.wrap } };
79502
+ const observation2 = n2 < same3.length ? same3[index] : void 0;
79503
+ if (tool.write && observation2?.error !== void 0) {
79504
+ setState(ctx, "reached", String(Math.max(reached, observation2.endMs)));
79505
+ return { source: "replayed", error: observation2.error, ...observation2.raw !== void 0 && { raw: observation2.raw, wrap: observation2.wrap } };
79446
79506
  }
79447
- if (observation) setState(ctx, "reached", String(Math.max(reached, observation.endMs)));
79507
+ if (observation2) setState(ctx, "reached", String(Math.max(reached, observation2.endMs)));
79448
79508
  if (tool.write) setState(ctx, `twin:dirty:${linked2}`, "1");
79449
- return { source: "twin", passthrough: true, ...observation && { recording: observation } };
79509
+ return { source: "twin", passthrough: true, ...observation2 && { recording: observation2 } };
79450
79510
  }
79451
79511
  const cached3 = getState(ctx, `sim:${simulationKey}`);
79452
79512
  if (cached3 !== void 0) {
@@ -79499,7 +79559,28 @@ function noteCall(ctx, name5, args, a) {
79499
79559
  setState(ctx, "calls", JSON.stringify(calls2.slice(-50)));
79500
79560
  }
79501
79561
  function toolsToWrap(ctx) {
79502
- return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => !t.mcp && (!t.pure || t.twin !== void 0) && !t.allow_unwrapped).map(([name5]) => name5).sort();
79562
+ return [.../* @__PURE__ */ new Set([...requiredFunctionTools(ctx.scene), ...Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => !t.mcp && (!t.pure || t.twin !== void 0) && !t.allow_unwrapped).map(([name5]) => name5)])].sort();
79563
+ }
79564
+ function functionToolObservation(ctx) {
79565
+ const registered = JSON.parse(getState(ctx, "wrapped") ?? "[]");
79566
+ const required4 = toolsToWrap(ctx), calls2 = projectToolCalls(ctx.trace.list()).filter((e) => e.source === "agent" && e.service === "tools" && e.path.startsWith("/tools/"));
79567
+ const protocol = getState(ctx, "protocol");
79568
+ return {
79569
+ registered,
79570
+ complete: getState(ctx, "complete") === "1",
79571
+ ...protocol !== void 0 && { protocol_version: Number(protocol) },
79572
+ required: required4,
79573
+ missing: required4.filter((name5) => !registered.includes(name5)),
79574
+ tools: [.../* @__PURE__ */ new Set([...Object.keys(ctx.scene.tools ?? {}), ...registered])].sort().map((name5) => {
79575
+ const own2 = calls2.filter((e) => decodeURIComponent(e.path.slice("/tools/".length)) === name5);
79576
+ const pending = own2.filter((e) => e.response?.execution_status === "unknown").length;
79577
+ const completed = own2.filter((e) => {
79578
+ const r2 = e.response;
79579
+ return r2?.execution_status === "succeeded" || r2?.execution_status === "failed" || !r2?.passthrough && ["replayed", "replayed-elsewhere", "simulated", "validated"].includes(String(r2?.source)) && (r2?.result !== void 0 || r2?.error !== void 0);
79580
+ }).length;
79581
+ return { name: name5, registered: registered.includes(name5), called: own2.length, completed, pending };
79582
+ })
79583
+ };
79503
79584
  }
79504
79585
  function registration(ctx, names5) {
79505
79586
  const before = JSON.parse(getState(ctx, "wrapped") ?? "[]");
@@ -79532,7 +79613,7 @@ function agentToolsService() {
79532
79613
  ...t?.twin && { twin: t.twin },
79533
79614
  ...t?.write && { write: true }
79534
79615
  };
79535
- }), wrap: toolsToWrap(ctx) });
79616
+ }), wrap: toolsToWrap(ctx), observation: functionToolObservation(ctx) });
79536
79617
  }));
79537
79618
  app2.post("/register", bodyLimit({
79538
79619
  maxSize: TOOL_REGISTRATION_BYTES,
@@ -79556,11 +79637,15 @@ function agentToolsService() {
79556
79637
  }
79557
79638
  for (const d of definitions3.values()) setState(c.env.ctx, `definition:${d.name}`, JSON.stringify(d));
79558
79639
  const result = registration(c.env.ctx, [...definitions3.keys()]);
79559
- if (body7.complete) setState(c.env.ctx, "checked", "1");
79640
+ if (body7.protocol_version !== void 0) setState(c.env.ctx, "protocol", String(Math.min(body7.protocol_version, AGENT_TOOLS_PROTOCOL_VERSION)));
79641
+ if (body7.complete && !result.missing.length) {
79642
+ setState(c.env.ctx, "complete", "1");
79643
+ setState(c.env.ctx, "checked", "1");
79644
+ }
79560
79645
  return result;
79561
79646
  });
79562
79647
  const protocol_version = AGENT_TOOLS_PROTOCOL_VERSION;
79563
- if (body7.complete && missing9.length) return c.json({ protocol_version, error: unwrappedMessage(missing9, wrapped.length === 0), wrapped, missing: missing9, stop: true }, 409, { [SETUP_ISSUE_HEADER]: "1" });
79648
+ if (body7.complete && missing9.length) return c.json({ protocol_version, error: requiredFunctionTools(c.env.ctx.scene).some((name5) => missing9.includes(name5)) ? functionWiringMessage(missing9) : unwrappedMessage(missing9, wrapped.length === 0), wrapped, missing: missing9, stop: true }, 409, { [SETUP_ISSUE_HEADER]: "1" });
79564
79649
  return c.json({ protocol_version, wrapped, missing: missing9 });
79565
79650
  } catch (error65) {
79566
79651
  const message7 = error65 instanceof Error ? error65.message : String(error65);
@@ -79612,9 +79697,9 @@ function agentToolsService() {
79612
79697
  const body7 = await c.req.json().catch(() => ({}));
79613
79698
  const stop = withMutation(c.env.ctx, () => {
79614
79699
  if (getState(c.env.ctx, "checked")) return void 0;
79615
- setState(c.env.ctx, "checked", "1");
79616
79700
  const { wrapped, missing: missing9 } = registration(c.env.ctx, []);
79617
- return missing9.length ? { error: unwrappedMessage(missing9, wrapped.length === 0), wrapped, missing: missing9, stop: true } : void 0;
79701
+ if (!missing9.length) setState(c.env.ctx, "checked", "1");
79702
+ return missing9.length ? { error: requiredFunctionTools(c.env.ctx.scene).some((name6) => missing9.includes(name6)) ? functionWiringMessage(missing9) : unwrappedMessage(missing9, wrapped.length === 0), wrapped, missing: missing9, stop: true } : void 0;
79618
79703
  });
79619
79704
  if (stop) return c.json(stop, 409, { [SETUP_ISSUE_HEADER]: "1" });
79620
79705
  const ctx = c.env.ctx, args = body7.args ?? {};
@@ -79668,7 +79753,7 @@ function agentToolsService() {
79668
79753
  credentials: (ctx) => ({ token: `ancha-tools-${ctx.secrets.hex(32)}` }),
79669
79754
  actions: {},
79670
79755
  checks: {},
79671
- dumpState: (ctx) => ({ calls: ctx.store.db.prepare("SELECT key, n FROM agent_tool_calls ORDER BY key").all(), wrapped: JSON.parse(getState(ctx, "wrapped") ?? "[]"), definitions: ctx.store.db.prepare("SELECT k, v FROM agent_tool_state WHERE k LIKE 'definition:%' ORDER BY k").all() }),
79756
+ dumpState: (ctx) => ({ observation: functionToolObservation(ctx), calls: ctx.store.db.prepare("SELECT key, n FROM agent_tool_calls ORDER BY key").all(), wrapped: JSON.parse(getState(ctx, "wrapped") ?? "[]"), definitions: ctx.store.db.prepare("SELECT k, v FROM agent_tool_state WHERE k LIKE 'definition:%' ORDER BY k").all() }),
79672
79757
  coverage: []
79673
79758
  };
79674
79759
  }
@@ -79728,6 +79813,8 @@ var init_env = __esm({
79728
79813
  init_engine();
79729
79814
  init_world_snapshot();
79730
79815
  init_agent_tools();
79816
+ init_src();
79817
+ init_agent_tools();
79731
79818
  agentTools = agentToolsService();
79732
79819
  ENV_ID_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789";
79733
79820
  credentialsKey = (twin) => `credentials:${twin}`;
@@ -80212,7 +80299,7 @@ var init_env = __esm({
80212
80299
  trace,
80213
80300
  state: state3,
80214
80301
  simMs: this.clock.elapsedMs(),
80215
- harnessIssues: collectHarnessIssues(trace, checks2),
80302
+ harnessIssues: [...collectHarnessIssues(trace, checks2), ...Object.keys(this.scene.tools ?? {}).length > 0 ? functionToolWiringIssues(functionToolObservation(this.ctxFor("tools"))) : []],
80216
80303
  ...people4.length && { people: people4 },
80217
80304
  ...replay && { peopleReplay: { replayed: replay.replayed, live: replay.live, divergence: replay.divergence ?? null } },
80218
80305
  ...explanations.length && { explanations },
@@ -80590,7 +80677,7 @@ import { createHash as createHash15 } from "node:crypto";
80590
80677
  function parse4(source) {
80591
80678
  if (source.length > 2e4)
80592
80679
  invalid7("Query too long");
80593
- const tokens4 = [];
80680
+ const tokens5 = [];
80594
80681
  let pos = 0;
80595
80682
  const scanner = /\s*(?:([A-Za-z_][A-Za-z_0-9.]*)|(-?\d+(?:\.\d+)?)|('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")|(>=|<=|!=|=|>|<|,|\(|\)))/y;
80596
80683
  while (pos < source.length) {
@@ -80601,14 +80688,14 @@ function parse4(source) {
80601
80688
  break;
80602
80689
  gap(`GAQL syntax near ${source.slice(pos, pos + 30)}`);
80603
80690
  }
80604
- tokens4.push(m[1] ?? m[2] ?? m[3] ?? m[4]);
80691
+ tokens5.push(m[1] ?? m[2] ?? m[3] ?? m[4]);
80605
80692
  pos = scanner.lastIndex;
80606
80693
  }
80607
80694
  let i = 0;
80608
- const peek = () => tokens4[i]?.toUpperCase(), take2 = () => {
80609
- if (i >= tokens4.length)
80695
+ const peek = () => tokens5[i]?.toUpperCase(), take2 = () => {
80696
+ if (i >= tokens5.length)
80610
80697
  invalid7("Unexpected end of query");
80611
- return tokens4[i++];
80698
+ return tokens5[i++];
80612
80699
  }, expect = (s3) => {
80613
80700
  if (take2().toUpperCase() !== s3)
80614
80701
  invalid7(`Expected ${s3}`);
@@ -80619,7 +80706,7 @@ function parse4(source) {
80619
80706
  invalid7(`Invalid field ${t}`);
80620
80707
  return t;
80621
80708
  };
80622
- const literal3 = () => {
80709
+ const literal4 = () => {
80623
80710
  const t = take2();
80624
80711
  if (/^['"]/.test(t))
80625
80712
  return t.slice(1, -1).replace(/\\(['"\\])/g, "$1");
@@ -80644,18 +80731,18 @@ function parse4(source) {
80644
80731
  const f2 = field6(), op2 = take2().toUpperCase(), values2 = [];
80645
80732
  if (op2 === "IN") {
80646
80733
  expect("(");
80647
- values2.push(literal3());
80734
+ values2.push(literal4());
80648
80735
  while (peek() === ",") {
80649
80736
  take2();
80650
- values2.push(literal3());
80737
+ values2.push(literal4());
80651
80738
  }
80652
80739
  expect(")");
80653
80740
  } else if (op2 === "BETWEEN") {
80654
- values2.push(literal3());
80741
+ values2.push(literal4());
80655
80742
  expect("AND");
80656
- values2.push(literal3());
80743
+ values2.push(literal4());
80657
80744
  } else if (["=", "!=", ">", "<", ">=", "<=", "DURING"].includes(op2))
80658
- values2.push(literal3());
80745
+ values2.push(literal4());
80659
80746
  else
80660
80747
  gap(`GAQL operator ${op2}`);
80661
80748
  where3.push({ field: f2, op: op2, values: values2 });
@@ -80687,8 +80774,8 @@ function parse4(source) {
80687
80774
  invalid7("LIMIT must be 1..100000");
80688
80775
  limit2 = Number(n2);
80689
80776
  }
80690
- if (i !== tokens4.length)
80691
- gap(`GAQL clause ${tokens4.slice(i).join(" ")}`);
80777
+ if (i !== tokens5.length)
80778
+ gap(`GAQL clause ${tokens5.slice(i).join(" ")}`);
80692
80779
  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"] };
80693
80780
  for (const f2 of [...select4, ...where3.map((p2) => p2.field), ...order6.map((o) => o.field)]) {
80694
80781
  const [prefix2, ...path7] = f2.split(".");
@@ -87520,9 +87607,9 @@ var require_parse = __commonJS({
87520
87607
  if (isOption) {
87521
87608
  isOption = false;
87522
87609
  if (token5.includes(".") && !token5.includes("(")) {
87523
- var tokens4 = token5.split(".");
87524
- option4 = tokens4[0] + ".";
87525
- token5 = tokens4[1];
87610
+ var tokens5 = token5.split(".");
87611
+ option4 = tokens5[0] + ".";
87612
+ token5 = tokens5[1];
87526
87613
  continue;
87527
87614
  }
87528
87615
  option4 = token5;
@@ -129207,13 +129294,13 @@ function parse7(c, body7, version6, old) {
129207
129294
  monitorId = null;
129208
129295
  }
129209
129296
  } else if (attrs.monitor_identifier !== void 0) {
129210
- const identifier4 = object8(attrs.monitor_identifier, "monitor_identifier");
129211
- keys3(identifier4, ["monitor_id", "monitor_tags"], "monitor_identifier");
129212
- if (Object.keys(identifier4).length !== 1) throw new DatadogError(400, "Specify exactly one monitor identifier");
129213
- if (identifier4.monitor_id !== void 0) monitorId = target(ctx, identifier4.monitor_id);
129297
+ const identifier5 = object8(attrs.monitor_identifier, "monitor_identifier");
129298
+ keys3(identifier5, ["monitor_id", "monitor_tags"], "monitor_identifier");
129299
+ if (Object.keys(identifier5).length !== 1) throw new DatadogError(400, "Specify exactly one monitor identifier");
129300
+ if (identifier5.monitor_id !== void 0) monitorId = target(ctx, identifier5.monitor_id);
129214
129301
  else {
129215
- if (!Array.isArray(identifier4.monitor_tags) || identifier4.monitor_tags.some((t) => typeof t !== "string")) throw new DatadogError(400, "Invalid monitor_tags");
129216
- if (identifier4.monitor_tags.length !== 1 || identifier4.monitor_tags[0] !== "*") unsupported7("monitor tags");
129302
+ if (!Array.isArray(identifier5.monitor_tags) || identifier5.monitor_tags.some((t) => typeof t !== "string")) throw new DatadogError(400, "Invalid monitor_tags");
129303
+ if (identifier5.monitor_tags.length !== 1 || identifier5.monitor_tags[0] !== "*") unsupported7("monitor tags");
129217
129304
  monitorId = null;
129218
129305
  }
129219
129306
  } else if (!old && version6 === 2) throw new DatadogError(400, "monitor_identifier is required");
@@ -131883,26 +131970,26 @@ var init_store3 = __esm({
131883
131970
  function tokenize3(q2) {
131884
131971
  if (!q2 || q2.length > 2e4) throw new SalesforceError(400, "MALFORMED_QUERY", "Query must contain 1\u201320,000 characters.");
131885
131972
  const pattern = /\s*(?:('(?:\\.|[^'\\])*')|(\d{4}-\d{2}-\d{2}(?![T\d-]))|([A-Za-z_][A-Za-z0-9_]*)|(-?\d+(?:\.\d+)?)|(>=|<=|!=|=|>|<)|([(),]))/gy;
131886
- const tokens4 = [];
131973
+ const tokens5 = [];
131887
131974
  let position = 0;
131888
131975
  while (position < q2.trimEnd().length) {
131889
131976
  pattern.lastIndex = position;
131890
131977
  const match3 = pattern.exec(q2);
131891
131978
  if (!match3) unsupported8("SOQL expression outside the documented subset", "MALFORMED_QUERY");
131892
131979
  const raw3 = match3[1] ?? match3[2] ?? match3[3] ?? match3[4] ?? match3[5] ?? match3[6];
131893
- tokens4.push(match3[1] ? { raw: raw3, value: raw3.slice(1, -1).replace(/\\(['\\])/g, "$1"), literal: true } : match3[2] ? { raw: raw3, value: raw3, literal: true } : match3[4] ? { raw: raw3, value: Number(raw3), literal: true } : { raw: raw3 });
131980
+ tokens5.push(match3[1] ? { raw: raw3, value: raw3.slice(1, -1).replace(/\\(['\\])/g, "$1"), literal: true } : match3[2] ? { raw: raw3, value: raw3, literal: true } : match3[4] ? { raw: raw3, value: Number(raw3), literal: true } : { raw: raw3 });
131894
131981
  position = pattern.lastIndex;
131895
- if (tokens4.length > 500) unsupported8("SOQL expression exceeds the 500-token subset", "MALFORMED_QUERY");
131982
+ if (tokens5.length > 500) unsupported8("SOQL expression exceeds the 500-token subset", "MALFORMED_QUERY");
131896
131983
  }
131897
- return tokens4;
131984
+ return tokens5;
131898
131985
  }
131899
131986
  function executeQuery(ctx, q2) {
131900
131987
  permission5(ctx);
131901
- const tokens4 = tokenize3(q2);
131988
+ const tokens5 = tokenize3(q2);
131902
131989
  let at4 = 0;
131903
- const peek = (word2) => tokens4[at4]?.raw.toUpperCase() === word2;
131990
+ const peek = (word2) => tokens5[at4]?.raw.toUpperCase() === word2;
131904
131991
  const take2 = () => {
131905
- const token4 = tokens4[at4++];
131992
+ const token4 = tokens5[at4++];
131906
131993
  if (!token4) throw new SalesforceError(400, "MALFORMED_QUERY", "Incomplete query.");
131907
131994
  return token4;
131908
131995
  };
@@ -131910,19 +131997,19 @@ function executeQuery(ctx, q2) {
131910
131997
  if (!peek(word2)) unsupported8(`expected ${word2} in SOQL`, "MALFORMED_QUERY");
131911
131998
  at4++;
131912
131999
  };
131913
- const identifier4 = () => {
132000
+ const identifier5 = () => {
131914
132001
  const token4 = take2();
131915
132002
  if (token4.literal || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(token4.raw)) unsupported8("SOQL field or object expression", "MALFORMED_QUERY");
131916
132003
  return token4.raw;
131917
132004
  };
131918
132005
  expect("SELECT");
131919
- const names5 = [identifier4()];
132006
+ const names5 = [identifier5()];
131920
132007
  while (peek(",")) {
131921
132008
  at4++;
131922
- names5.push(identifier4());
132009
+ names5.push(identifier5());
131923
132010
  }
131924
132011
  expect("FROM");
131925
- const type = objectType2(identifier4()), selected2 = names5.map((name5) => canonicalField(type, name5));
132012
+ const type = objectType2(identifier5()), selected2 = names5.map((name5) => canonicalField(type, name5));
131926
132013
  if (new Set(selected2).size !== selected2.length) throw new SalesforceError(400, "MALFORMED_QUERY", "Duplicate selected field.");
131927
132014
  const value5 = () => {
131928
132015
  const token4 = take2();
@@ -131939,7 +132026,7 @@ function executeQuery(ctx, q2) {
131939
132026
  if (peek("WHERE")) {
131940
132027
  at4++;
131941
132028
  for (; ; ) {
131942
- const field6 = canonicalField(type, identifier4()), operator2 = take2().raw.toUpperCase();
132029
+ const field6 = canonicalField(type, identifier5()), operator2 = take2().raw.toUpperCase();
131943
132030
  if (operator2 === "IN") {
131944
132031
  expect("(");
131945
132032
  const values2 = [value5()];
@@ -131953,15 +132040,15 @@ function executeQuery(ctx, q2) {
131953
132040
  predicates.push((record29) => values2.some((item2) => normalize4(record29[field6]) === normalize4(item2)));
131954
132041
  } else {
131955
132042
  if (!["=", "!=", "<", "<=", ">", ">=", "LIKE"].includes(operator2)) unsupported8(`SOQL operator ${operator2}`, "MALFORMED_QUERY");
131956
- const literal3 = value5();
131957
- checkValue(field6, literal3);
131958
- if (typeof literal3 === "boolean" && !["=", "!="].includes(operator2)) throw new SalesforceError(400, "MALFORMED_QUERY", "Boolean fields only support equality comparisons.");
132043
+ const literal4 = value5();
132044
+ checkValue(field6, literal4);
132045
+ if (typeof literal4 === "boolean" && !["=", "!="].includes(operator2)) throw new SalesforceError(400, "MALFORMED_QUERY", "Boolean fields only support equality comparisons.");
131959
132046
  if (operator2 === "LIKE") {
131960
- if (typeof literal3 !== "string") throw new SalesforceError(400, "MALFORMED_QUERY", "LIKE needs a string.");
131961
- const regex3 = new RegExp("^" + literal3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/%/g, ".*").replace(/_/g, ".") + "$", "i");
132047
+ if (typeof literal4 !== "string") throw new SalesforceError(400, "MALFORMED_QUERY", "LIKE needs a string.");
132048
+ const regex3 = new RegExp("^" + literal4.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/%/g, ".*").replace(/_/g, ".") + "$", "i");
131962
132049
  predicates.push((record29) => typeof record29[field6] === "string" && regex3.test(record29[field6]));
131963
132050
  } else predicates.push((record29) => {
131964
- const left = normalize4(record29[field6] ?? null), right = normalize4(literal3);
132051
+ const left = normalize4(record29[field6] ?? null), right = normalize4(literal4);
131965
132052
  if (operator2 === "=") return left === right;
131966
132053
  if (operator2 === "!=") return left !== right;
131967
132054
  if (left === null || right === null || typeof left !== typeof right) return false;
@@ -131976,7 +132063,7 @@ function executeQuery(ctx, q2) {
131976
132063
  if (peek("ORDER")) {
131977
132064
  at4++;
131978
132065
  expect("BY");
131979
- order6 = canonicalField(type, identifier4());
132066
+ order6 = canonicalField(type, identifier5());
131980
132067
  if (peek("ASC") || peek("DESC")) descending = take2().raw.toUpperCase() === "DESC";
131981
132068
  }
131982
132069
  const integer14 = (max) => {
@@ -131993,7 +132080,7 @@ function executeQuery(ctx, q2) {
131993
132080
  at4++;
131994
132081
  offset18 = integer14(2e3);
131995
132082
  }
131996
- if (at4 !== tokens4.length) unsupported8(`SOQL ${tokens4[at4].raw}; relationships, aggregation, OR and additional clauses are outside this subset`, "MALFORMED_QUERY");
132083
+ if (at4 !== tokens5.length) unsupported8(`SOQL ${tokens5[at4].raw}; relationships, aggregation, OR and additional clauses are outside this subset`, "MALFORMED_QUERY");
131997
132084
  let result = rows29(ctx, type).filter((record29) => visible2(ctx, type, record29)).map((record29) => project6(type, record29)).filter((record29) => predicates.every((test3) => test3(record29)));
131998
132085
  if (order6) result.sort((a, b) => {
131999
132086
  const left = a[order6] ?? null, right = b[order6] ?? null;
@@ -133900,7 +133987,7 @@ var init_request11 = __esm({
133900
133987
 
133901
133988
  // packages/server/src/twins/google-drive/query.ts
133902
133989
  function tokenize4(source) {
133903
- const tokens4 = [];
133990
+ const tokens5 = [];
133904
133991
  let at4 = 0;
133905
133992
  while (at4 < source.length) {
133906
133993
  const char = source[at4];
@@ -133909,7 +133996,7 @@ function tokenize4(source) {
133909
133996
  continue;
133910
133997
  }
133911
133998
  if (char === "(" || char === ")") {
133912
- tokens4.push({ kind: "paren", value: char });
133999
+ tokens5.push({ kind: "paren", value: char });
133913
134000
  at4++;
133914
134001
  continue;
133915
134002
  }
@@ -133932,25 +134019,25 @@ function tokenize4(source) {
133932
134019
  value5 += next2;
133933
134020
  at4++;
133934
134021
  }
133935
- tokens4.push({ kind: "string", value: value5 });
134022
+ tokens5.push({ kind: "string", value: value5 });
133936
134023
  continue;
133937
134024
  }
133938
134025
  const op2 = /^(?:!=|<=|>=|=|<|>)/.exec(source.slice(at4));
133939
134026
  if (op2) {
133940
- tokens4.push({ kind: "op", value: op2[0] });
134027
+ tokens5.push({ kind: "op", value: op2[0] });
133941
134028
  at4 += op2[0].length;
133942
134029
  continue;
133943
134030
  }
133944
134031
  const word2 = /^[A-Za-z_][A-Za-z0-9_.]*/.exec(source.slice(at4));
133945
134032
  if (word2) {
133946
- tokens4.push({ kind: "word", value: word2[0] });
134033
+ tokens5.push({ kind: "word", value: word2[0] });
133947
134034
  at4 += word2[0].length;
133948
134035
  continue;
133949
134036
  }
133950
134037
  if (char === "{" || char === "}") unsupported11("properties and appProperties search with has");
133951
134038
  throw invalid14("q");
133952
134039
  }
133953
- return tokens4;
134040
+ return tokens5;
133954
134041
  }
133955
134042
  function namePrefix(name5, value5) {
133956
134043
  if (!value5) return true;
@@ -133992,16 +134079,16 @@ function compare3(left, op2, right) {
133992
134079
  }
133993
134080
  }
133994
134081
  function parseQuery(source, aliases) {
133995
- const tokens4 = tokenize4(source);
134082
+ const tokens5 = tokenize4(source);
133996
134083
  let at4 = 0;
133997
- const peek = () => tokens4[at4];
134084
+ const peek = () => tokens5[at4];
133998
134085
  const isWord = (token4, value5) => token4?.kind === "word" && token4.value.toLowerCase() === value5;
133999
134086
  const expect = () => {
134000
- const token4 = tokens4[at4++];
134087
+ const token4 = tokens5[at4++];
134001
134088
  if (!token4) throw invalid14("q");
134002
134089
  return token4;
134003
134090
  };
134004
- const literal3 = () => {
134091
+ const literal4 = () => {
134005
134092
  const token4 = expect();
134006
134093
  if (token4.kind !== "string") throw invalid14("q");
134007
134094
  return token4.value;
@@ -134088,17 +134175,17 @@ function parseQuery(source, aliases) {
134088
134175
  const op2 = contains3 ? "contains" : operator2.value;
134089
134176
  switch (field6) {
134090
134177
  case "name": {
134091
- const value5 = literal3();
134178
+ const value5 = literal4();
134092
134179
  if (op2 === "contains") return (file3) => namePrefix(file3.name, value5);
134093
134180
  return (file3) => equality(op2, file3.name, value5);
134094
134181
  }
134095
134182
  case "fullText": {
134096
134183
  if (op2 !== "contains") throw invalid14("q");
134097
- const value5 = literal3();
134184
+ const value5 = literal4();
134098
134185
  return (file3) => fullTextMatch(file3.fullText, value5);
134099
134186
  }
134100
134187
  case "mimeType": {
134101
- const value5 = literal3();
134188
+ const value5 = literal4();
134102
134189
  if (op2 === "contains") return (file3) => file3.mimeType.includes(value5);
134103
134190
  return (file3) => equality(op2, file3.mimeType, value5);
134104
134191
  }
@@ -134112,7 +134199,7 @@ function parseQuery(source, aliases) {
134112
134199
  case "modifiedTime":
134113
134200
  case "viewedByMeTime": {
134114
134201
  if (op2 === "contains") throw invalid14("q");
134115
- const value5 = time6(literal3());
134202
+ const value5 = time6(literal4());
134116
134203
  const read7 = (file3) => field6 === "createdTime" ? file3.createdMs : field6 === "modifiedTime" ? file3.modifiedMs : file3.viewedMs;
134117
134204
  return (file3) => {
134118
134205
  const actual = read7(file3);
@@ -134120,7 +134207,7 @@ function parseQuery(source, aliases) {
134120
134207
  };
134121
134208
  }
134122
134209
  case "visibility": {
134123
- const value5 = literal3();
134210
+ const value5 = literal4();
134124
134211
  if (!["anyoneCanFind", "anyoneWithLink", "domainCanFind", "domainWithLink", "limited"].includes(value5)) throw invalid14("q");
134125
134212
  return (file3) => equality(op2, file3.visibility, value5);
134126
134213
  }
@@ -134134,9 +134221,9 @@ function parseQuery(source, aliases) {
134134
134221
  throw invalid14("q");
134135
134222
  }
134136
134223
  };
134137
- if (!tokens4.length) return () => true;
134224
+ if (!tokens5.length) return () => true;
134138
134225
  const predicate = or();
134139
- if (at4 !== tokens4.length) throw invalid14("q");
134226
+ if (at4 !== tokens5.length) throw invalid14("q");
134140
134227
  return predicate;
134141
134228
  }
134142
134229
  var init_query4 = __esm({
@@ -135497,7 +135584,7 @@ var init_batch = __esm({
135497
135584
 
135498
135585
  // packages/server/src/twins/gmail/search.ts
135499
135586
  function tokenize5(q2) {
135500
- const tokens4 = [];
135587
+ const tokens5 = [];
135501
135588
  let i = 0;
135502
135589
  while (i < q2.length) {
135503
135590
  const ch = q2[i];
@@ -135506,39 +135593,39 @@ function tokenize5(q2) {
135506
135593
  continue;
135507
135594
  }
135508
135595
  if (ch === "(") {
135509
- tokens4.push({ type: "open", value: ch });
135596
+ tokens5.push({ type: "open", value: ch });
135510
135597
  i++;
135511
135598
  continue;
135512
135599
  }
135513
135600
  if (ch === ")") {
135514
- tokens4.push({ type: "close", value: ch });
135601
+ tokens5.push({ type: "close", value: ch });
135515
135602
  i++;
135516
135603
  continue;
135517
135604
  }
135518
135605
  if (ch === "{") {
135519
- tokens4.push({ type: "openBrace", value: ch });
135606
+ tokens5.push({ type: "openBrace", value: ch });
135520
135607
  i++;
135521
135608
  continue;
135522
135609
  }
135523
135610
  if (ch === "}") {
135524
- tokens4.push({ type: "closeBrace", value: ch });
135611
+ tokens5.push({ type: "closeBrace", value: ch });
135525
135612
  i++;
135526
135613
  continue;
135527
135614
  }
135528
135615
  if (ch === "|") {
135529
- tokens4.push({ type: "or", value: ch });
135616
+ tokens5.push({ type: "or", value: ch });
135530
135617
  i++;
135531
135618
  continue;
135532
135619
  }
135533
135620
  if (ch === "-" && i + 1 < q2.length && !/\s/.test(q2[i + 1])) {
135534
- tokens4.push({ type: "minus", value: ch });
135621
+ tokens5.push({ type: "minus", value: ch });
135535
135622
  i++;
135536
135623
  continue;
135537
135624
  }
135538
135625
  if (ch === '"') {
135539
135626
  const end = q2.indexOf('"', i + 1);
135540
135627
  const value5 = end < 0 ? q2.slice(i + 1) : q2.slice(i + 1, end);
135541
- tokens4.push({ type: "phrase", value: value5 });
135628
+ tokens5.push({ type: "phrase", value: value5 });
135542
135629
  i = end < 0 ? q2.length : end + 1;
135543
135630
  continue;
135544
135631
  }
@@ -135559,13 +135646,13 @@ function tokenize5(q2) {
135559
135646
  value5 = end < 0 ? q2.slice(i + 1) : q2.slice(i + 1, end);
135560
135647
  i = end < 0 ? q2.length : end + 1;
135561
135648
  }
135562
- tokens4.push({ type: "op", op: op2, value: value5 });
135649
+ tokens5.push({ type: "op", op: op2, value: value5 });
135563
135650
  continue;
135564
135651
  }
135565
- if (word2 === "OR") tokens4.push({ type: "or", value: word2 });
135566
- else if (word2 !== "AND") tokens4.push({ type: "word", value: word2 });
135652
+ if (word2 === "OR") tokens5.push({ type: "or", value: word2 });
135653
+ else if (word2 !== "AND") tokens5.push({ type: "word", value: word2 });
135567
135654
  }
135568
- return tokens4;
135655
+ return tokens5;
135569
135656
  }
135570
135657
  function containsWords(haystack, needle) {
135571
135658
  const want = words3(needle);
@@ -135697,13 +135784,13 @@ function operator(op2, value5) {
135697
135784
  return unsupported4(`Gmail search operator ${op2}:`);
135698
135785
  }
135699
135786
  }
135700
- function parse8(tokens4) {
135787
+ function parse8(tokens5) {
135701
135788
  let i = 0;
135702
135789
  const sequence = (until) => {
135703
135790
  const items2 = [];
135704
- while (i < tokens4.length && tokens4[i].type !== until) {
135791
+ while (i < tokens5.length && tokens5[i].type !== until) {
135705
135792
  let item2 = unary();
135706
- while (tokens4[i]?.type === "or") {
135793
+ while (tokens5[i]?.type === "or") {
135707
135794
  i++;
135708
135795
  const next2 = unary();
135709
135796
  item2 = { kind: "or", items: [item2, next2] };
@@ -135713,7 +135800,7 @@ function parse8(tokens4) {
135713
135800
  return items2;
135714
135801
  };
135715
135802
  const unary = () => {
135716
- const token4 = tokens4[i++];
135803
+ const token4 = tokens5[i++];
135717
135804
  if (!token4) return { kind: "and", items: [] };
135718
135805
  switch (token4.type) {
135719
135806
  case "minus":
@@ -139258,7 +139345,7 @@ var init_checks12 = __esm({
139258
139345
 
139259
139346
  // packages/server/src/twins/okta/filter.ts
139260
139347
  function tokenize6(source) {
139261
- const tokens4 = [];
139348
+ const tokens5 = [];
139262
139349
  let at4 = 0;
139263
139350
  while (at4 < source.length) {
139264
139351
  const char = source[at4];
@@ -139267,7 +139354,7 @@ function tokenize6(source) {
139267
139354
  continue;
139268
139355
  }
139269
139356
  if (char === "(" || char === ")") {
139270
- tokens4.push({ kind: "paren", value: char });
139357
+ tokens5.push({ kind: "paren", value: char });
139271
139358
  at4++;
139272
139359
  continue;
139273
139360
  }
@@ -139287,21 +139374,21 @@ function tokenize6(source) {
139287
139374
  }
139288
139375
  value5 += source[at4++];
139289
139376
  }
139290
- tokens4.push({ kind: "string", value: value5 });
139377
+ tokens5.push({ kind: "string", value: value5 });
139291
139378
  continue;
139292
139379
  }
139293
139380
  const number7 = /^-?\d+(?:\.\d+)?/.exec(source.slice(at4));
139294
139381
  if (number7) {
139295
- tokens4.push({ kind: "number", value: number7[0] });
139382
+ tokens5.push({ kind: "number", value: number7[0] });
139296
139383
  at4 += number7[0].length;
139297
139384
  continue;
139298
139385
  }
139299
139386
  const word2 = /^[A-Za-z_][A-Za-z0-9_.$]*/.exec(source.slice(at4));
139300
139387
  if (!word2) throw new FilterError(`unexpected ${char}`);
139301
- tokens4.push({ kind: "word", value: word2[0] });
139388
+ tokens5.push({ kind: "word", value: word2[0] });
139302
139389
  at4 += word2[0].length;
139303
139390
  }
139304
- return tokens4;
139391
+ return tokens5;
139305
139392
  }
139306
139393
  function compare5(actual, op2, expected) {
139307
139394
  if (op2 === "pr") return actual !== void 0 && actual !== null && actual !== "";
@@ -139335,9 +139422,9 @@ function compare5(actual, op2, expected) {
139335
139422
  }
139336
139423
  }
139337
139424
  function parseFilter(source, attributes2) {
139338
- const tokens4 = tokenize6(source);
139425
+ const tokens5 = tokenize6(source);
139339
139426
  let at4 = 0;
139340
- const keyword = (value5) => tokens4[at4]?.kind === "word" && tokens4[at4].value.toLowerCase() === value5;
139427
+ const keyword = (value5) => tokens5[at4]?.kind === "word" && tokens5[at4].value.toLowerCase() === value5;
139341
139428
  const or = () => {
139342
139429
  const terms = [and()];
139343
139430
  while (keyword("or")) {
@@ -139360,21 +139447,21 @@ function parseFilter(source, attributes2) {
139360
139447
  const inner2 = unary();
139361
139448
  return (lookup6) => !inner2(lookup6);
139362
139449
  }
139363
- if (tokens4[at4]?.kind === "paren" && tokens4[at4].value === "(") {
139450
+ if (tokens5[at4]?.kind === "paren" && tokens5[at4].value === "(") {
139364
139451
  at4++;
139365
139452
  const inner2 = or();
139366
- if (tokens4[at4]?.kind !== "paren" || tokens4[at4].value !== ")") throw new FilterError("missing )");
139453
+ if (tokens5[at4]?.kind !== "paren" || tokens5[at4].value !== ")") throw new FilterError("missing )");
139367
139454
  at4++;
139368
139455
  return inner2;
139369
139456
  }
139370
- const path7 = tokens4[at4++];
139457
+ const path7 = tokens5[at4++];
139371
139458
  if (!path7 || path7.kind !== "word") throw new FilterError("expected an attribute");
139372
139459
  if (attributes2 && !attributes2(path7.value)) throw new FilterError(`unsupported attribute ${path7.value}`);
139373
- const operator2 = tokens4[at4++];
139460
+ const operator2 = tokens5[at4++];
139374
139461
  if (!operator2 || operator2.kind !== "word" || !OPERATORS.has(operator2.value.toLowerCase())) throw new FilterError("expected an operator");
139375
139462
  const op2 = operator2.value.toLowerCase();
139376
139463
  if (op2 === "pr") return (lookup6) => compare5(lookup6(path7.value), "pr", null);
139377
- const value5 = tokens4[at4++];
139464
+ const value5 = tokens5[at4++];
139378
139465
  if (!value5) throw new FilterError("expected a value");
139379
139466
  let expected;
139380
139467
  if (value5.kind === "string") expected = value5.value;
@@ -139383,9 +139470,9 @@ function parseFilter(source, attributes2) {
139383
139470
  else throw new FilterError("expected a value");
139384
139471
  return (lookup6) => compare5(lookup6(path7.value), op2, expected);
139385
139472
  };
139386
- if (!tokens4.length) throw new FilterError("empty expression");
139473
+ if (!tokens5.length) throw new FilterError("empty expression");
139387
139474
  const expression3 = or();
139388
- if (at4 !== tokens4.length) throw new FilterError("unexpected trailing input");
139475
+ if (at4 !== tokens5.length) throw new FilterError("unexpected trailing input");
139389
139476
  return expression3;
139390
139477
  }
139391
139478
  function lookupIn(value5) {
@@ -141609,12 +141696,12 @@ var init_billing = __esm({
141609
141696
  // packages/server/src/twins/stripe/search.ts
141610
141697
  function clauses(query11) {
141611
141698
  const token4 = /\s*(-?(?:metadata\[(?:"[^"]*"|'[^']*')\]|[a-z_]+)\s*(?:>=|<=|:|~|>|<)\s*(?:"[^"]*"|'[^']*'|[^\s"']+)|AND|OR)\s*/y;
141612
- const tokens4 = [];
141613
- for (let m; token4.lastIndex < query11.length && (m = token4.exec(query11)); ) tokens4.push(m[1]);
141614
- if (!tokens4.length || token4.lastIndex < query11.length) invalid15(`Invalid search query: ${query11}`, "query");
141615
- const joins = tokens4.filter((t) => t === "AND" || t === "OR");
141699
+ const tokens5 = [];
141700
+ for (let m; token4.lastIndex < query11.length && (m = token4.exec(query11)); ) tokens5.push(m[1]);
141701
+ if (!tokens5.length || token4.lastIndex < query11.length) invalid15(`Invalid search query: ${query11}`, "query");
141702
+ const joins = tokens5.filter((t) => t === "AND" || t === "OR");
141616
141703
  if (new Set(joins).size > 1) invalid15("Search queries cannot mix AND and OR.", "query");
141617
- const parsed4 = tokens4.filter((t) => t !== "AND" && t !== "OR").map((token5) => {
141704
+ const parsed4 = tokens5.filter((t) => t !== "AND" && t !== "OR").map((token5) => {
141618
141705
  const m = /^(-?)(metadata\[(?:"([^"]*)"|'([^']*)')\]|[a-z_]+)\s*(>=|<=|:|~|>|<)\s*(?:"([^"]*)"|'([^']*)'|(\S+))$/.exec(token5);
141619
141706
  if (!m) invalid15(`Invalid search query: ${token5}`, "query");
141620
141707
  const [, negate, field6, mk1, mk2, op2, v1, v22, v3] = m;
@@ -146945,13 +147032,13 @@ function serveTemporary(ctx, token4) {
146945
147032
  return new Response(new Uint8Array(revision2.content), { status: 200, headers: { "content-type": "application/octet-stream" } });
146946
147033
  }
146947
147034
  function searchPage(call4, cursor4) {
146948
- const tokens4 = cursor4.q.toLowerCase().split(/\s+/).filter(Boolean);
147035
+ const tokens5 = cursor4.q.toLowerCase().split(/\s+/).filter(Boolean);
146949
147036
  const words9 = (value5) => value5.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
146950
147037
  const candidates = cursor4.s === "deleted" ? call4.ctx.store.db.prepare("SELECT * FROM dbx_deleted ORDER BY path_lower").all().filter((row2) => !getEntry(call4.ctx, row2.path_lower)).map((row2) => ({ key: row2.path_lower, name: nameOf3(row2.path_display), text: "", value: deletedMetadata(row2) })) : childrenOf(call4.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(call4.ctx, entry3) }));
146951
147038
  const matches9 = candidates.filter((item2) => (cursor4.p === "" || item2.key.startsWith(`${cursor4.p}/`)) && (!cursor4.x || cursor4.x.some((ext) => item2.key.endsWith(`.${ext.toLowerCase()}`)))).flatMap((item2) => {
146952
147039
  const nameWords = words9(item2.name);
146953
- const byName = tokens4.every((token4) => nameWords.some((word2) => word2.startsWith(token4)));
146954
- const byContent = !cursor4.f && tokens4.every((token4) => item2.text.toLowerCase().includes(token4));
147040
+ const byName = tokens5.every((token4) => nameWords.some((word2) => word2.startsWith(token4)));
147041
+ const byContent = !cursor4.f && tokens5.every((token4) => item2.text.toLowerCase().includes(token4));
146955
147042
  if (!byName && !byContent) return [];
146956
147043
  return [{ match_type: { ".tag": byName && byContent ? "filename_and_content" : byName ? "filename" : "file_content" }, metadata: { ".tag": "metadata", metadata: item2.value } }];
146957
147044
  });
@@ -148844,8 +148931,8 @@ function restoreVersion(call4, id14) {
148844
148931
  }
148845
148932
  function search6(call4, query11) {
148846
148933
  odata(call4, ["$top", "$skiptoken", "$orderby"]);
148847
- const tokens4 = query11.toLowerCase().split(/\s+/).filter(Boolean);
148848
- if (!tokens4.length) throw invalid21("The search query is empty.");
148934
+ const tokens5 = query11.toLowerCase().split(/\s+/).filter(Boolean);
148935
+ if (!tokens5.length) throw invalid21("The search query is empty.");
148849
148936
  const scope3 = target3(call4), all9 = [];
148850
148937
  const visit4 = (node5) => {
148851
148938
  for (const child2 of childrenOf2(call4.ctx, node5.id)) {
@@ -148857,7 +148944,7 @@ function search6(call4, query11) {
148857
148944
  const matches9 = all9.filter((item2) => {
148858
148945
  const text30 = `${item2.name}
148859
148946
  ${textOf2(item2) ?? ""}`.toLowerCase();
148860
- return tokens4.every((token4) => text30.includes(token4));
148947
+ return tokens5.every((token4) => text30.includes(token4));
148861
148948
  });
148862
148949
  const response5 = collection(call4, "Collection(driveItem)", matches9);
148863
148950
  return response5;
@@ -149147,19 +149234,19 @@ function project9(row2, url4, headers) {
149147
149234
  return result;
149148
149235
  }
149149
149236
  function filterPredicate(source) {
149150
- const tokens4 = [];
149237
+ const tokens5 = [];
149151
149238
  const re = /\s*(startswith|and\b|or\b|not\b|eq\b|ne\b|ge\b|gt\b|le\b|lt\b|true\b|false\b|null\b|'(?:[^']|'')*'|\d{4}-\d\d-\d\dT[\d:.]+(?:Z|[+-]\d\d:\d\d)|[A-Za-z][\w/]*|[(),])\s*/gy;
149152
149239
  let at4 = 0;
149153
149240
  while (at4 < source.length) {
149154
149241
  re.lastIndex = at4;
149155
149242
  const m = re.exec(source);
149156
149243
  if (!m) throw invalid22("Invalid filter clause.");
149157
- tokens4.push(m[1]);
149244
+ tokens5.push(m[1]);
149158
149245
  at4 = re.lastIndex;
149159
149246
  }
149160
149247
  let i = 0;
149161
149248
  const take2 = (want) => {
149162
- const v = tokens4[i++];
149249
+ const v = tokens5[i++];
149163
149250
  if (!v || want && v !== want) throw invalid22("Invalid filter clause.");
149164
149251
  return v;
149165
149252
  };
@@ -149178,18 +149265,18 @@ function filterPredicate(source) {
149178
149265
  return key4;
149179
149266
  };
149180
149267
  const atom2 = () => {
149181
- if (tokens4[i] === "(") {
149268
+ if (tokens5[i] === "(") {
149182
149269
  take2();
149183
149270
  const p2 = or();
149184
149271
  take2(")");
149185
149272
  return p2;
149186
149273
  }
149187
- if (tokens4[i] === "not") {
149274
+ if (tokens5[i] === "not") {
149188
149275
  take2();
149189
149276
  const p2 = atom2();
149190
149277
  return (r2) => !p2(r2);
149191
149278
  }
149192
- if (tokens4[i] === "startswith") {
149279
+ if (tokens5[i] === "startswith") {
149193
149280
  take2();
149194
149281
  take2("(");
149195
149282
  const key5 = property4();
@@ -149227,7 +149314,7 @@ function filterPredicate(source) {
149227
149314
  };
149228
149315
  const and = () => {
149229
149316
  let p2 = atom2();
149230
- while (tokens4[i] === "and") {
149317
+ while (tokens5[i] === "and") {
149231
149318
  take2();
149232
149319
  const a = p2, b = atom2();
149233
149320
  p2 = (r2) => a(r2) && b(r2);
@@ -149236,7 +149323,7 @@ function filterPredicate(source) {
149236
149323
  };
149237
149324
  const or = () => {
149238
149325
  let p2 = and();
149239
- while (tokens4[i] === "or") {
149326
+ while (tokens5[i] === "or") {
149240
149327
  take2();
149241
149328
  const a = p2, b = and();
149242
149329
  p2 = (r2) => a(r2) || b(r2);
@@ -149244,7 +149331,7 @@ function filterPredicate(source) {
149244
149331
  return p2;
149245
149332
  };
149246
149333
  const result = or();
149247
- if (i !== tokens4.length) throw invalid22("Invalid filter clause.");
149334
+ if (i !== tokens5.length) throw invalid22("Invalid filter clause.");
149248
149335
  return result;
149249
149336
  }
149250
149337
  function searchPredicate(source) {
@@ -151335,9 +151422,9 @@ function mutationRoot(req) {
151335
151422
  if (f2.status !== "SUCCESS") return { fulfillment: null, userErrors: [{ field: ["fulfillmentId"], message: "Tracking can only be updated on a successful fulfillment." }] };
151336
151423
  return { fulfillment: fulfillmentShape(req, save9(ctx, "Fulfillment", { ...f2, tracking: trackingFrom(trackingInfoInput), updated_ms: now6(req) }, f2.order)), userErrors: [] };
151337
151424
  },
151338
- productUpdate: ({ product: product2, input: input5, media: media2, identifier: identifier4 }) => {
151425
+ productUpdate: ({ product: product2, input: input5, media: media2, identifier: identifier5 }) => {
151339
151426
  if (media2?.length) gap5("productUpdate media");
151340
- if (identifier4) gap5("productUpdate identifier");
151427
+ if (identifier5) gap5("productUpdate identifier");
151341
151428
  const data5 = product2 ?? input5;
151342
151429
  if (!data5) return { product: null, userErrors: [{ field: ["product"], message: "Product input is required" }] };
151343
151430
  unmodeled(data5, [
@@ -155807,7 +155894,7 @@ function evaluate2(q2, w2) {
155807
155894
  if (abs) return localToUtc(Number(abs[1]), Number(abs[2]), Number(abs[3]), w2.timezone, Number(abs[4] ?? 0), Number(abs[5] ?? 0));
155808
155895
  throw new JqlError(`Date value '${v.text}' for field '${field6}' is invalid. Valid formats include: 'yyyy/MM/dd HH:mm', 'yyyy-MM-dd HH:mm', 'yyyy/MM/dd', 'yyyy-MM-dd', or a period format e.g. '-5d', '4w 2d'.`);
155809
155896
  };
155810
- const literal3 = (v, field6) => {
155897
+ const literal4 = (v, field6) => {
155811
155898
  if (v.kind === "literal") return v.text;
155812
155899
  if (v.kind === "func") throw new JqlError(`Function '${v.name}' is not supported for the field '${field6}'.`);
155813
155900
  return null;
@@ -155818,7 +155905,7 @@ function evaluate2(q2, w2) {
155818
155905
  return found2.id;
155819
155906
  };
155820
155907
  const one7 = (resolve59) => (v) => {
155821
- const t = literal3(v, "");
155908
+ const t = literal4(v, "");
155822
155909
  return t === null ? [] : [resolve59(t)];
155823
155910
  };
155824
155911
  const users5 = (field6, get7) => ({ kind: "set", get: (i) => get7(i).filter((x) => x !== null), resolve: (v) => {
@@ -155870,14 +155957,14 @@ function evaluate2(q2, w2) {
155870
155957
  if (n2 === "subtaskissuetypes") return w2.types.filter((t2) => t2.subtask).map((t2) => t2.name);
155871
155958
  throw new JqlError(`Function '${v.name}' is not supported for the field 'issuetype'.`);
155872
155959
  }
155873
- const t = literal3(v, "issuetype");
155960
+ const t = literal4(v, "issuetype");
155874
155961
  if (t === null) return [];
155875
155962
  const type = w2.types.find((x) => x.name.toLowerCase() === t.toLowerCase() || x.id === t || x.subtask && ["sub-task", "subtask"].includes(t.toLowerCase()));
155876
155963
  if (!type) throw new JqlError(`The value '${t}' does not exist for the field 'issuetype'.`);
155877
155964
  return [type.name];
155878
155965
  } },
155879
155966
  resolution: { kind: "set", get: (i) => i.resolution ? [i.resolution] : [], resolve: (v) => {
155880
- const t = literal3(v, "resolution");
155967
+ const t = literal4(v, "resolution");
155881
155968
  if (t === null) return [];
155882
155969
  if (t.toLowerCase() === "unresolved") return [UNRESOLVED];
155883
155970
  const r2 = ["Done", "Won't Do", "Duplicate", "Cannot Reproduce"].find((x) => x.toLowerCase() === t.toLowerCase());
@@ -155895,7 +155982,7 @@ function evaluate2(q2, w2) {
155895
155982
  if (!states) throw new JqlError(`Function '${v.name}' is not supported for the field 'sprint'.`);
155896
155983
  return w2.sprints.filter((s4) => states.includes(s4.state)).map((s4) => s4.id);
155897
155984
  }
155898
- const t = literal3(v, "sprint");
155985
+ const t = literal4(v, "sprint");
155899
155986
  if (t === null) return [];
155900
155987
  const s3 = w2.sprints.find((x) => String(x.id) === t || x.name.toLowerCase() === t.toLowerCase());
155901
155988
  if (!s3) throw new JqlError(`The value '${t}' does not exist for the field 'sprint'.`);
@@ -155946,7 +156033,7 @@ function evaluate2(q2, w2) {
155946
156033
  }
155947
156034
  if (f2.kind === "text") {
155948
156035
  if (op2 !== "~" && op2 !== "!~") throw new JqlError(`The operator '${op2}' is not supported by the '${node5.field}' field.`);
155949
- const raw3 = literal3(node5.values[0], node5.field) ?? "", hay = f2.get(i).toLowerCase();
156036
+ const raw3 = literal4(node5.values[0], node5.field) ?? "", hay = f2.get(i).toLowerCase();
155950
156037
  const phrase = /^".*"$/.exec(raw3.trim());
155951
156038
  const hit = phrase ? hay.includes(raw3.trim().slice(1, -1).toLowerCase()) : (() => {
155952
156039
  const have2 = words9(hay);
@@ -155957,11 +156044,11 @@ function evaluate2(q2, w2) {
155957
156044
  if (op2 === "~" || op2 === "!~") throw new JqlError(`The operator '${op2}' is not supported by the '${node5.field}' field.`);
155958
156045
  if (f2.kind === "date" || f2.kind === "number") {
155959
156046
  if (op2 === "in" || op2 === "not in") {
155960
- const have3 = f2.get(i), set2 = node5.values.map((v) => f2.kind === "date" ? dateOf2(v, node5.field) : Number(literal3(v, node5.field)));
156047
+ const have3 = f2.get(i), set2 = node5.values.map((v) => f2.kind === "date" ? dateOf2(v, node5.field) : Number(literal4(v, node5.field)));
155961
156048
  return have3 !== null && (op2 === "in" ? set2.includes(have3) : !set2.includes(have3));
155962
156049
  }
155963
- const have2 = f2.get(i), want = f2.kind === "date" ? dateOf2(node5.values[0], node5.field) : Number(literal3(node5.values[0], node5.field));
155964
- if (f2.kind === "number" && !Number.isFinite(want)) throw new JqlError(`The value '${literal3(node5.values[0], node5.field)}' is not a valid number for the field '${node5.field}'.`);
156050
+ const have2 = f2.get(i), want = f2.kind === "date" ? dateOf2(node5.values[0], node5.field) : Number(literal4(node5.values[0], node5.field));
156051
+ if (f2.kind === "number" && !Number.isFinite(want)) throw new JqlError(`The value '${literal4(node5.values[0], node5.field)}' is not a valid number for the field '${node5.field}'.`);
155965
156052
  if (have2 === null) return false;
155966
156053
  const day10 = f2.kind === "date" && node5.values[0].kind === "literal" && /^\d{4}[-/]\d{1,2}[-/]\d{1,2}$/.test(node5.values[0].text.trim());
155967
156054
  switch (op2) {
@@ -157182,9 +157269,9 @@ var init_routes19 = __esm({
157182
157269
  path: "/user/assignable/search",
157183
157270
  coverage: { status: "supported" },
157184
157271
  run: (r2) => {
157185
- const projectKey3 = r2.query.get("project"), issueKey = r2.query.get("issueKey");
157186
- if (!projectKey3 && !issueKey && !r2.query.get("issueId")) fail2(400, "One of the following parameters must be provided: issueKey, issueId, project.");
157187
- if (projectKey3 && !projectByKey(r2.ctx, projectKey3)) fail2(404, `No project could be found with key '${projectKey3}'.`);
157272
+ const projectKey2 = r2.query.get("project"), issueKey = r2.query.get("issueKey");
157273
+ if (!projectKey2 && !issueKey && !r2.query.get("issueId")) fail2(400, "One of the following parameters must be provided: issueKey, issueId, project.");
157274
+ if (projectKey2 && !projectByKey(r2.ctx, projectKey2)) fail2(404, `No project could be found with key '${projectKey2}'.`);
157188
157275
  if ((issueKey || r2.query.get("issueId")) && !issueByKey(r2.ctx, issueKey ?? r2.query.get("issueId"))) issueNotFound();
157189
157276
  const query11 = r2.query.get("query") ?? r2.query.get("username") ?? "";
157190
157277
  const start2 = Number(r2.query.get("startAt") ?? 0), max = Number(r2.query.get("maxResults") ?? 50);
@@ -165822,7 +165909,7 @@ var init_routes27 = __esm({
165822
165909
 
165823
165910
  // packages/server/src/twins/sentry/search.ts
165824
165911
  function parseSearch2(query11, where3) {
165825
- const tokens4 = [];
165912
+ const tokens5 = [];
165826
165913
  for (let i = 0; i < query11.length; ) {
165827
165914
  if (/\s/.test(query11[i])) {
165828
165915
  i++;
@@ -165837,11 +165924,11 @@ function parseSearch2(query11, where3) {
165837
165924
  else if (!quoted4 && depth <= 0 && /\s/.test(ch)) break;
165838
165925
  }
165839
165926
  if (quoted4) fail5(400, `Error parsing search query: Missing closing quote in ${query11.slice(i, j)}`);
165840
- tokens4.push(query11.slice(i, j));
165927
+ tokens5.push(query11.slice(i, j));
165841
165928
  i = j;
165842
165929
  }
165843
165930
  const filters = [], text30 = [];
165844
- for (const token4 of tokens4) {
165931
+ for (const token4 of tokens5) {
165845
165932
  if (token4 === "OR" || token4 === "AND") {
165846
165933
  if (where3 === "issues") fail5(400, 'Error parsing search query: Boolean statements containing "OR" or "AND" are not supported in this search');
165847
165934
  unsupported32("OR and AND in the events query");
@@ -173359,8 +173446,8 @@ function dateModel(model2) {
173359
173446
  if (model2[i] === '"') {
173360
173447
  const end = model2.indexOf('"', i + 1);
173361
173448
  if (end < 0) invalid28("Invalid date format model.");
173362
- const literal3 = model2.slice(i + 1, end);
173363
- parts3.push({ literal: literal3, original: literal3 });
173449
+ const literal4 = model2.slice(i + 1, end);
173450
+ parts3.push({ literal: literal4, original: literal4 });
173364
173451
  i = end + 1;
173365
173452
  continue;
173366
173453
  }
@@ -173376,16 +173463,16 @@ function dateModel(model2) {
173376
173463
  return parts3;
173377
173464
  }
173378
173465
  function parseDate2(value5, model2) {
173379
- const parts3 = dateModel(model2), tokens4 = [];
173466
+ const parts3 = dateModel(model2), tokens5 = [];
173380
173467
  const pattern = parts3.map((p2) => {
173381
173468
  if (!p2.token) return escapeRegex2(p2.literal);
173382
173469
  if (p2.token === "FM") return "";
173383
- tokens4.push(p2.token);
173470
+ tokens5.push(p2.token);
173384
173471
  return p2.token === "YYYY" ? "(\\d{4})" : ["MON", "MONTH"].includes(p2.token) ? "([A-Za-z]+)" : ["AM", "PM"].includes(p2.token) ? "(AM|PM)" : "(\\d{1,2})";
173385
173472
  }).join("");
173386
173473
  const match3 = new RegExp(`^${pattern}$`, "i").exec(value5.trim());
173387
173474
  if (!match3) invalid28("Invalid date value for the format model.");
173388
- const values2 = new Map(tokens4.map((t, i) => [t, match3[i + 1]]));
173475
+ const values2 = new Map(tokens5.map((t, i) => [t, match3[i + 1]]));
173389
173476
  if (!values2.has("YYYY") || !values2.has("DD") || !["MM", "MON", "MONTH"].some((t) => values2.has(t))) invalid28("TO_DATE requires year, month and day.", true);
173390
173477
  const month = values2.has("MM") ? Number(values2.get("MM")) : MONTHS3.findIndex((m) => values2.has("MON") ? m.slice(0, 3).toLowerCase() === values2.get("MON").toLowerCase() : m.toLowerCase() === values2.get("MONTH").toLowerCase()) + 1;
173391
173478
  const date11 = calendar3(Number(values2.get("YYYY")), month, Number(values2.get("DD")));
@@ -173397,7 +173484,7 @@ function parseDate2(value5, model2) {
173397
173484
  }
173398
173485
  if (hour2 > 23 || minute3 > 59 || second > 59) invalid28("Invalid time value.");
173399
173486
  date11.setUTCHours(hour2, minute3, second);
173400
- return tokens4.some((t) => t.startsWith("HH") || ["MI", "SS"].includes(t)) ? date11.toISOString() : date11.toISOString().slice(0, 10);
173487
+ return tokens5.some((t) => t.startsWith("HH") || ["MI", "SS"].includes(t)) ? date11.toISOString() : date11.toISOString().slice(0, 10);
173401
173488
  }
173402
173489
  function readDate(value5) {
173403
173490
  const text30 = String(value5);
@@ -174830,7 +174917,7 @@ var init_suiteql = __esm({
174830
174917
  const arg = math ? sql3("ns_suiteql_number(", args[0], ")") : args[0], fn = e.name === "median" ? "ns_suiteql_median" : e.name.toUpperCase();
174831
174918
  return bound2(sql3(fn, "(", e.distinct ? "DISTINCT " : "", arg, ")"), e.name === "count" ? "integer" : ["min", "max"].includes(e.name) ? args[0].type : "number", args, true);
174832
174919
  }
174833
- const literal3 = (b) => {
174920
+ const literal4 = (b) => {
174834
174921
  const value5 = b?.params[0];
174835
174922
  return b?.sql === "?" && typeof value5 === "string" ? value5 : void 0;
174836
174923
  };
@@ -174872,7 +174959,7 @@ var init_suiteql = __esm({
174872
174959
  case "concat":
174873
174960
  return this.concat(args[0], args[1]);
174874
174961
  case "builtin.hierarchy": {
174875
- const a = args[0], origin = a.column?.origin, mode = literal3(args[1]);
174962
+ const a = args[0], origin = a.column?.origin, mode = literal4(args[1]);
174876
174963
  const modes = ["DISPLAY", "DISPLAY_JOINED", "DISPLAY_SEPARATED", "IDENTIFIER", "IDENTIFIER_SEPARATED", "LEVEL", "SELF_DISPLAY", "SELF_IDENTIFIER"];
174877
174964
  if (!mode || !modes.includes(mode)) invalid28("BUILTIN.HIERARCHY requires a valid expansion type literal.");
174878
174965
  const table4 = origin && this.tables.find((t) => t.name === (origin.column.ref ?? (origin.column.name === "id" ? origin.table.name : "")));
@@ -174898,7 +174985,7 @@ var init_suiteql = __esm({
174898
174985
  case "builtin.consolidate":
174899
174986
  return args[0];
174900
174987
  case "builtin.relative_ranges": {
174901
- const range2 = literal3(args[0]), boundary = literal3(args[1]);
174988
+ const range2 = literal4(args[0]), boundary = literal4(args[1]);
174902
174989
  if (range2 === void 0 || boundary === void 0) invalid28("BUILTIN.RELATIVE_RANGES takes a range ID and START or END as literals.");
174903
174990
  return bound2(param3(relativeRange(range2, boundary, this.today)), "date");
174904
174991
  }
@@ -174906,8 +174993,8 @@ var init_suiteql = __esm({
174906
174993
  case "to_timestamp": {
174907
174994
  const type = e.name === "to_date" ? "date" : "datetime", format2 = args[1] ?? bound2(param3("MM/DD/YYYY"), "text");
174908
174995
  if (typeof format2.params[0] === "string" && format2.sql === "?") dateModel(format2.params[0]);
174909
- if (literal3(args[0]) !== void 0 && literal3(format2) !== void 0) {
174910
- const value5 = parseDate2(literal3(args[0]), literal3(format2));
174996
+ if (literal4(args[0]) !== void 0 && literal4(format2) !== void 0) {
174997
+ const value5 = parseDate2(literal4(args[0]), literal4(format2));
174911
174998
  return bound2(param3(type === "datetime" ? timestamp3(value5) : value5), type);
174912
174999
  }
174913
175000
  return make(`ns_suiteql_${e.name}`, type, [args[0], format2]);
@@ -174924,12 +175011,12 @@ var init_suiteql = __esm({
174924
175011
  }
174925
175012
  case "to_number": {
174926
175013
  if (!args[1]) return bound2(this.asNumber(args[0]), "number", [args[0]]);
174927
- if (literal3(args[1]) !== void 0) numberModel(literal3(args[1]));
175014
+ if (literal4(args[1]) !== void 0) numberModel(literal4(args[1]));
174928
175015
  return make("ns_suiteql_to_number", "number", [this.asText(args[0]), args[1]]);
174929
175016
  }
174930
175017
  case "trunc": {
174931
175018
  if (dated2(args[0].type)) {
174932
- const model2 = literal3(args[1]);
175019
+ const model2 = literal4(args[1]);
174933
175020
  if (model2 !== void 0) truncDate(this.today, model2);
174934
175021
  return make("ns_suiteql_trunc", model2 !== void 0 && /^(hh|hh12|hh24|mi)$/i.test(model2) ? "datetime" : "date");
174935
175022
  }
@@ -174969,8 +175056,8 @@ var init_suiteql = __esm({
174969
175056
  case "regexp_substr":
174970
175057
  case "regexp_instr":
174971
175058
  case "regexp_count": {
174972
- const match3 = literal3(args[{ regexp_like: 2, regexp_replace: 5, regexp_substr: 4, regexp_instr: 5, regexp_count: 3 }[e.name]]);
174973
- if (literal3(args[1]) !== void 0) regex2(literal3(args[1]), match3 ?? "");
175059
+ const match3 = literal4(args[{ regexp_like: 2, regexp_replace: 5, regexp_substr: 4, regexp_instr: 5, regexp_count: 3 }[e.name]]);
175060
+ if (literal4(args[1]) !== void 0) regex2(literal4(args[1]), match3 ?? "");
174974
175061
  return make(`ns_suiteql_${e.name}`, e.name === "regexp_like" ? "boolean" : ["regexp_instr", "regexp_count"].includes(e.name) ? "integer" : "text");
174975
175062
  }
174976
175063
  case "abs":
@@ -183129,6 +183216,9 @@ var init_socket2 = __esm({
183129
183216
  get pendingCount() {
183130
183217
  return this.#pending.size;
183131
183218
  }
183219
+ get connected() {
183220
+ return this.#live() && this.#socket?.readyState === import_websocket.default.OPEN;
183221
+ }
183132
183222
  isCurrent(env2) {
183133
183223
  return env2 === this.#env && this.#live();
183134
183224
  }
@@ -183687,6 +183777,7 @@ var init_sessions = __esm({
183687
183777
  pendingJobs,
183688
183778
  pendingBlockingJobs,
183689
183779
  pendingDeliveries,
183780
+ ...record29.socket && { socketConnected: record29.socket.connected },
183690
183781
  quiet: session2.state === "running" && quietNow(env2, record29.busy > 0),
183691
183782
  nextDueMs: nextDue,
183692
183783
  ...untilMs !== void 0 && { untilMs }
@@ -187326,7 +187417,7 @@ var require_scan = __commonJS({
187326
187417
  const length = input5.length - 1;
187327
187418
  const scanToEnd = opts.parts === true || opts.tokens === true || opts.scanToEnd === true;
187328
187419
  const slashes = [];
187329
- const tokens4 = [];
187420
+ const tokens5 = [];
187330
187421
  const parts3 = [];
187331
187422
  let str5 = input5;
187332
187423
  let index = -1;
@@ -187410,7 +187501,7 @@ var require_scan = __commonJS({
187410
187501
  }
187411
187502
  if (code5 === CHAR_FORWARD_SLASH) {
187412
187503
  slashes.push(index);
187413
- tokens4.push(token4);
187504
+ tokens5.push(token4);
187414
187505
  token4 = { value: "", depth: 0, isGlob: false };
187415
187506
  if (finished === true) continue;
187416
187507
  if (prev === CHAR_DOT && index === start2 + 1) {
@@ -187572,9 +187663,9 @@ var require_scan = __commonJS({
187572
187663
  if (opts.tokens === true) {
187573
187664
  state3.maxDepth = 0;
187574
187665
  if (!isPathSeparator(code5)) {
187575
- tokens4.push(token4);
187666
+ tokens5.push(token4);
187576
187667
  }
187577
- state3.tokens = tokens4;
187668
+ state3.tokens = tokens5;
187578
187669
  }
187579
187670
  if (opts.parts === true || opts.tokens === true) {
187580
187671
  let prevIndex;
@@ -187584,13 +187675,13 @@ var require_scan = __commonJS({
187584
187675
  const value6 = input5.slice(n3, i);
187585
187676
  if (opts.tokens) {
187586
187677
  if (idx === 0 && start2 !== 0) {
187587
- tokens4[idx].isPrefix = true;
187588
- tokens4[idx].value = prefix2;
187678
+ tokens5[idx].isPrefix = true;
187679
+ tokens5[idx].value = prefix2;
187589
187680
  } else {
187590
- tokens4[idx].value = value6;
187681
+ tokens5[idx].value = value6;
187591
187682
  }
187592
- depth(tokens4[idx]);
187593
- state3.maxDepth += tokens4[idx].depth;
187683
+ depth(tokens5[idx]);
187684
+ state3.maxDepth += tokens5[idx].depth;
187594
187685
  }
187595
187686
  if (i >= start2) {
187596
187687
  parts3.push(value6);
@@ -187601,9 +187692,9 @@ var require_scan = __commonJS({
187601
187692
  const value5 = input5.slice(n2);
187602
187693
  parts3.push(value5);
187603
187694
  if (opts.tokens && prevIndex && prevIndex + 1 < input5.length) {
187604
- tokens4[tokens4.length - 1].value = value5;
187605
- depth(tokens4[tokens4.length - 1]);
187606
- state3.maxDepth += tokens4[tokens4.length - 1].depth;
187695
+ tokens5[tokens5.length - 1].value = value5;
187696
+ depth(tokens5[tokens5.length - 1]);
187697
+ state3.maxDepth += tokens5[tokens5.length - 1].depth;
187607
187698
  }
187608
187699
  state3.slashes = slashes;
187609
187700
  state3.parts = parts3;
@@ -187852,9 +187943,9 @@ var require_parse2 = __commonJS({
187852
187943
  safeChars.push(...chars);
187853
187944
  continue;
187854
187945
  }
187855
- const literal3 = normalizeSimpleBranch(branch3);
187856
- if (literal3 && literal3.length === 1) {
187857
- safeChars.push(literal3);
187946
+ const literal4 = normalizeSimpleBranch(branch3);
187947
+ if (literal4 && literal4.length === 1) {
187948
+ safeChars.push(literal4);
187858
187949
  continue;
187859
187950
  }
187860
187951
  combinable = false;
@@ -187879,7 +187970,7 @@ var require_parse2 = __commonJS({
187879
187970
  throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
187880
187971
  }
187881
187972
  const bos = { type: "bos", value: "", output: opts.prepend || "" };
187882
- const tokens4 = [bos];
187973
+ const tokens5 = [bos];
187883
187974
  const capture4 = opts.capture ? "" : "?:";
187884
187975
  const PLATFORM_CHARS = constants14.globChars(opts.windows);
187885
187976
  const EXTGLOB_CHARS = constants14.extglobChars(PLATFORM_CHARS);
@@ -187924,7 +188015,7 @@ var require_parse2 = __commonJS({
187924
188015
  parens: 0,
187925
188016
  quotes: 0,
187926
188017
  globstar: false,
187927
- tokens: tokens4
188018
+ tokens: tokens5
187928
188019
  };
187929
188020
  input5 = utils.removePrefix(input5, state3);
187930
188021
  len = input5.length;
@@ -187989,7 +188080,7 @@ var require_parse2 = __commonJS({
187989
188080
  return;
187990
188081
  }
187991
188082
  tok.prev = prev;
187992
- tokens4.push(tok);
188083
+ tokens5.push(tok);
187993
188084
  prev = tok;
187994
188085
  };
187995
188086
  const extglobOpen = (type, value6) => {
@@ -187998,7 +188089,7 @@ var require_parse2 = __commonJS({
187998
188089
  token4.parens = state3.parens;
187999
188090
  token4.output = state3.output;
188000
188091
  token4.startIndex = state3.index;
188001
- token4.tokensIndex = tokens4.length;
188092
+ token4.tokensIndex = tokens5.length;
188002
188093
  const output2 = (opts.capture ? "(" : "") + token4.open;
188003
188094
  increment("parens");
188004
188095
  push({ type, value: value6, output: state3.output ? "" : ONE_CHAR });
@@ -188006,19 +188097,19 @@ var require_parse2 = __commonJS({
188006
188097
  extglobs.push(token4);
188007
188098
  };
188008
188099
  const extglobClose = (token4) => {
188009
- const literal3 = input5.slice(token4.startIndex, state3.index + 1);
188100
+ const literal4 = input5.slice(token4.startIndex, state3.index + 1);
188010
188101
  const body7 = input5.slice(token4.startIndex + 2, state3.index);
188011
188102
  const analysis = analyzeRepeatedExtglob(body7, opts);
188012
188103
  if ((token4.type === "plus" || token4.type === "star") && analysis.risky) {
188013
188104
  const safeOutput = analysis.safeOutput ? (token4.output ? "" : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput) : void 0;
188014
- const open14 = tokens4[token4.tokensIndex];
188105
+ const open14 = tokens5[token4.tokensIndex];
188015
188106
  open14.type = "text";
188016
- open14.value = literal3;
188017
- open14.output = safeOutput || utils.escapeRegex(literal3);
188018
- for (let i = token4.tokensIndex + 1; i < tokens4.length; i++) {
188019
- tokens4[i].value = "";
188020
- tokens4[i].output = "";
188021
- delete tokens4[i].suffix;
188107
+ open14.value = literal4;
188108
+ open14.output = safeOutput || utils.escapeRegex(literal4);
188109
+ for (let i = token4.tokensIndex + 1; i < tokens5.length; i++) {
188110
+ tokens5[i].value = "";
188111
+ tokens5[i].output = "";
188112
+ delete tokens5[i].suffix;
188022
188113
  }
188023
188114
  state3.output = token4.output + open14.output;
188024
188115
  state3.backtrack = true;
@@ -188141,7 +188232,7 @@ var require_parse2 = __commonJS({
188141
188232
  prev.value = pre + posix5;
188142
188233
  state3.backtrack = true;
188143
188234
  advance();
188144
- if (!bos.output && tokens4.indexOf(prev) === 1) {
188235
+ if (!bos.output && tokens5.indexOf(prev) === 1) {
188145
188236
  bos.output = ONE_CHAR;
188146
188237
  }
188147
188238
  continue;
@@ -188259,10 +188350,10 @@ var require_parse2 = __commonJS({
188259
188350
  }
188260
188351
  let output2 = ")";
188261
188352
  if (brace.dots === true) {
188262
- const arr = tokens4.slice();
188353
+ const arr = tokens5.slice();
188263
188354
  const range2 = [];
188264
188355
  for (let i = arr.length - 1; i >= 0; i--) {
188265
- tokens4.pop();
188356
+ tokens5.pop();
188266
188357
  if (arr[i].type === "brace") {
188267
188358
  break;
188268
188359
  }
@@ -188310,7 +188401,7 @@ var require_parse2 = __commonJS({
188310
188401
  state3.start = state3.index + 1;
188311
188402
  state3.consumed = "";
188312
188403
  state3.output = "";
188313
- tokens4.pop();
188404
+ tokens5.pop();
188314
188405
  prev = bos;
188315
188406
  continue;
188316
188407
  }
@@ -188946,6 +189037,115 @@ var init_source = __esm({
188946
189037
  }
188947
189038
  });
188948
189039
 
189040
+ // backend/src/runner/slack-app.ts
189041
+ import { createHmac as createHmac9 } from "node:crypto";
189042
+ import { setTimeout as sleep2 } from "node:timers/promises";
189043
+ function assertVmEndpoint(agent) {
189044
+ const hint = 'Set agent.start to the command that starts the agent and agent.url to its address on 127.0.0.1; map PORT under agent.env to "{{agent.port}}" for a dynamic port. A Slack app takes agent.command with slack_transport: http and its events URL, for example http://127.0.0.1:3000/slack/events. Or run it with --on local.';
189045
+ if (!agent.start) throw new AnchaError("CONFIG_INVALID", "Cloud runs start the agent inside its attempt machine, so an agent.url agent needs a start command.", { hint });
189046
+ for (const template3 of [agent.url, agent.readyUrl, agent.setupUrl]) {
189047
+ if (template3 === void 0) continue;
189048
+ const url4 = new URL(renderAgentUrl(template3, { "agent.port": "34567", "env.id": "attempt", service: "slack" }));
189049
+ if (url4.protocol !== "http:" || !["localhost", "127.0.0.1", "[::1]"].includes(url4.hostname)) {
189050
+ throw new AnchaError("CONFIG_INVALID", "Cloud runs reach the agent inside its attempt machine, so agent.url, ready_url and setup_url must be 127.0.0.1 or localhost addresses.", { hint });
189051
+ }
189052
+ }
189053
+ }
189054
+ function managedAppPort(template3, reserved, vars) {
189055
+ if (usesPort(template3)) return reserved;
189056
+ const url4 = new URL(renderAgentUrl(template3, { ...vars, service: "slack" }));
189057
+ return Number(url4.port) || (url4.protocol === "https:" ? 443 : 80);
189058
+ }
189059
+ async function waitSlackSocket(backend, envId, sessionId, child2, signal) {
189060
+ const stopped = new AbortController();
189061
+ void child2.exited.then(() => stopped.abort(), () => stopped.abort());
189062
+ const combined = AbortSignal.any([signal, stopped.signal]);
189063
+ try {
189064
+ for (; ; ) {
189065
+ combined.throwIfAborted();
189066
+ let cancel3;
189067
+ const aborted2 = new Promise((_, reject4) => {
189068
+ cancel3 = () => reject4(combined.reason);
189069
+ combined.addEventListener("abort", cancel3, { once: true });
189070
+ if (combined.aborted) cancel3();
189071
+ });
189072
+ try {
189073
+ if ((await Promise.race([backend.trialStatus(envId, sessionId), aborted2])).socketConnected === true) {
189074
+ combined.throwIfAborted();
189075
+ return;
189076
+ }
189077
+ } finally {
189078
+ combined.removeEventListener("abort", cancel3);
189079
+ }
189080
+ await sleep2(25, void 0, { signal: combined });
189081
+ }
189082
+ } catch (cause) {
189083
+ throw new AnchaError("AGENT_UNREACHABLE", "The Slack app did not open its Socket Mode connection.", { hint: slackSocketFix, cause });
189084
+ }
189085
+ }
189086
+ async function waitSlackHttp(url4, secret, sessionId, signal) {
189087
+ const challenge = createHmac9("sha256", secret).update(`readiness:${sessionId}`).digest("hex");
189088
+ const body7 = JSON.stringify({ type: "url_verification", challenge });
189089
+ try {
189090
+ for (; ; ) {
189091
+ signal.throwIfAborted();
189092
+ try {
189093
+ const timestamp4 = String(Math.floor(Date.now() / 1e3));
189094
+ const signature2 = "v0=" + createHmac9("sha256", secret).update(`v0:${timestamp4}:${body7}`).digest("hex");
189095
+ const response5 = await fetch(url4, {
189096
+ method: "POST",
189097
+ body: body7,
189098
+ redirect: "manual",
189099
+ signal: AbortSignal.any([signal, AbortSignal.timeout(500)]),
189100
+ headers: { "content-type": "application/json", "x-slack-request-timestamp": timestamp4, "x-slack-signature": signature2 }
189101
+ });
189102
+ const reader2 = response5.body?.getReader();
189103
+ const chunks = [];
189104
+ let bytes3 = 0;
189105
+ if (reader2) try {
189106
+ for (; ; ) {
189107
+ const { value: value5, done } = await reader2.read();
189108
+ if (done) break;
189109
+ bytes3 += value5.length;
189110
+ if (bytes3 > 65536) {
189111
+ await reader2.cancel();
189112
+ throw new Error("readiness response too large");
189113
+ }
189114
+ chunks.push(value5);
189115
+ }
189116
+ } finally {
189117
+ reader2.releaseLock();
189118
+ }
189119
+ const text30 = Buffer.concat(chunks).toString("utf8");
189120
+ let matches9 = text30 === challenge || new URLSearchParams(text30).get("challenge") === challenge;
189121
+ try {
189122
+ matches9 ||= JSON.parse(text30)?.challenge === challenge;
189123
+ } catch {
189124
+ }
189125
+ if (response5.ok && matches9) {
189126
+ signal.throwIfAborted();
189127
+ return;
189128
+ }
189129
+ } catch {
189130
+ signal.throwIfAborted();
189131
+ }
189132
+ await sleep2(25, void 0, { signal });
189133
+ }
189134
+ } catch (cause) {
189135
+ throw new AnchaError("AGENT_UNREACHABLE", "The Slack events URL did not answer its signed verification challenge.", { hint: slackHttpFix, cause });
189136
+ }
189137
+ }
189138
+ var slackSocketFix, slackHttpFix;
189139
+ var init_slack_app = __esm({
189140
+ "backend/src/runner/slack-app.ts"() {
189141
+ "use strict";
189142
+ init_src();
189143
+ init_config();
189144
+ slackSocketFix = 'Map the app token under agent.env: SLACK_APP_TOKEN: "{{slack.app_token}}" and the SDK API URL: SLACK_API_URL: "{{slack.url}}". Use the variable names your app reads.';
189145
+ slackHttpFix = 'Map the signing secret under agent.env: SLACK_SIGNING_SECRET: "{{slack.signing_secret}}". Set agent.url to the app events path and port; for a dynamic port map PORT: "{{agent.port}}" under agent.env.';
189146
+ }
189147
+ });
189148
+
188949
189149
  // backend/src/agent-input.ts
188950
189150
  import { rename, writeFile as writeFile2 } from "node:fs/promises";
188951
189151
  import { join as join5 } from "node:path";
@@ -189026,6 +189226,71 @@ var init_agent_input = __esm({
189026
189226
  }
189027
189227
  });
189028
189228
 
189229
+ // cloud/shared/run-metadata.mjs
189230
+ function runNumberOf(value5) {
189231
+ return Number.isSafeInteger(value5) && value5 > 0 ? value5 : void 0;
189232
+ }
189233
+ function runLabel(run6, fallback = run6.id ?? run6.runId ?? run6.run_id ?? "") {
189234
+ const number7 = runNumberOf(run6.runNumber ?? run6.summary?.runNumber);
189235
+ return number7 === void 0 ? fallback : `#${number7}`;
189236
+ }
189237
+ function numberReference(value5) {
189238
+ if (typeof value5 !== "string" || !/^#?[1-9]\d*$/.test(value5)) return void 0;
189239
+ return runNumberOf(Number(value5.replace(/^#/, "")));
189240
+ }
189241
+ function github2(value5) {
189242
+ if (!value5 || typeof value5 !== "object" || Array.isArray(value5) || Object.keys(value5).sort().join(",") !== "repository,runId,serverUrl") throw new Error("Invalid GitHub Actions context.");
189243
+ const { repository: repository3, runId: runId2, serverUrl: serverUrl3 } = value5;
189244
+ if (typeof repository3 !== "string" || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository3) || repository3.length > 201 || repository3.split("/").some((p2) => p2 === "." || p2 === "..") || typeof runId2 !== "string" || !/^[1-9]\d{0,19}$/.test(runId2)) throw new Error("Invalid GitHub Actions context.");
189245
+ let url4;
189246
+ try {
189247
+ url4 = new URL(serverUrl3);
189248
+ } catch {
189249
+ throw new Error("Invalid GitHub Actions server.");
189250
+ }
189251
+ if (typeof serverUrl3 !== "string" || serverUrl3.length > 2048 || url4.protocol !== "https:" || url4.username || url4.password || url4.search || url4.hash || url4.pathname !== "/") throw new Error("Invalid GitHub Actions server.");
189252
+ return { repository: repository3, runId: runId2, serverUrl: url4.origin };
189253
+ }
189254
+ function runContextHeader(env2) {
189255
+ if (env2.GITHUB_ACTIONS !== "true") return {};
189256
+ try {
189257
+ const context3 = github2({ repository: env2.GITHUB_REPOSITORY, runId: env2.GITHUB_RUN_ID, serverUrl: env2.GITHUB_SERVER_URL });
189258
+ return { "x-ancha-run-context": JSON.stringify(context3) };
189259
+ } catch {
189260
+ return {};
189261
+ }
189262
+ }
189263
+ function validateRunMetadata(value5) {
189264
+ if (!value5 || typeof value5 !== "object" || Array.isArray(value5) || Object.keys(value5).some((k) => !["runNumber", "startedBy"].includes(k))) throw new Error("Invalid run metadata.");
189265
+ if (value5.runNumber !== void 0 && runNumberOf(value5.runNumber) === void 0) throw new Error("Invalid run number.");
189266
+ if (value5.startedBy !== void 0) {
189267
+ const by2 = value5.startedBy;
189268
+ if (!by2 || typeof by2 !== "object" || Array.isArray(by2) || Object.keys(by2).some((k) => !["source", "email", "repository", "url"].includes(k)) || !["console", "cli", "github-actions"].includes(by2.source)) throw new Error("Invalid run starter.");
189269
+ if (by2.email !== void 0 && (typeof by2.email !== "string" || by2.email.length > 320 || /[\x00-\x1f\x7f]/.test(by2.email))) throw new Error("Invalid run starter email.");
189270
+ if (by2.source === "github-actions") {
189271
+ let u;
189272
+ try {
189273
+ u = new URL(by2.url);
189274
+ } catch {
189275
+ throw new Error("Invalid workflow URL.");
189276
+ }
189277
+ const match3 = /^\/(.+)\/actions\/runs\/(\d+)$/.exec(u.pathname);
189278
+ if (!match3 || match3[1] !== by2.repository || u.search || u.hash || u.username || u.password) throw new Error("Invalid workflow URL.");
189279
+ github2({ repository: by2.repository, runId: match3[2], serverUrl: u.origin });
189280
+ } else if (by2.repository !== void 0 || by2.url !== void 0) throw new Error("Invalid run starter context.");
189281
+ }
189282
+ return value5;
189283
+ }
189284
+ function starterLabel(by2) {
189285
+ if (!by2) return "";
189286
+ return [by2.email, by2.source === "github-actions" ? "GitHub Actions" : by2.source === "cli" ? "CLI" : "", by2.repository].filter(Boolean).join(" \xB7 ");
189287
+ }
189288
+ var init_run_metadata = __esm({
189289
+ "cloud/shared/run-metadata.mjs"() {
189290
+ "use strict";
189291
+ }
189292
+ });
189293
+
189029
189294
  // cloud/shared/jobs-contract.mjs
189030
189295
  var jobs_contract_exports = {};
189031
189296
  __export(jobs_contract_exports, {
@@ -189053,6 +189318,7 @@ __export(jobs_contract_exports, {
189053
189318
  HEARTBEAT_MS: () => HEARTBEAT_MS,
189054
189319
  JOB_KINDS: () => JOB_KINDS2,
189055
189320
  JOB_STATES: () => JOB_STATES,
189321
+ MODEL_KEY_NAMES: () => MODEL_KEY_NAMES,
189056
189322
  PROBE_OUTCOMES: () => PROBE_OUTCOMES,
189057
189323
  PROJECT_KEY: () => PROJECT_KEY,
189058
189324
  RUN_CLOUD_ID: () => RUN_CLOUD_ID,
@@ -189072,6 +189338,7 @@ __export(jobs_contract_exports, {
189072
189338
  projectJobDetail: () => projectJobDetail,
189073
189339
  reject: () => reject2,
189074
189340
  safeBundlePath: () => safeBundlePath,
189341
+ validRepository: () => validRepository,
189075
189342
  validateManifest: () => validateManifest,
189076
189343
  validateOptions: () => validateOptions,
189077
189344
  validateStoredBody: () => validateStoredBody
@@ -189097,6 +189364,11 @@ function object18(value5, fields11, label6) {
189097
189364
  function safeBundlePath(path7) {
189098
189365
  return typeof path7 === "string" && path7.length > 0 && path7.length <= 1024 && !/[\\\x00-\x1f\x7f:]/.test(path7) && path7.split("/").every((p2) => p2 && p2 !== "." && p2 !== "..");
189099
189366
  }
189367
+ function validRepository(value5) {
189368
+ if (typeof value5 !== "string" || value5.length > 200) return false;
189369
+ const match3 = /^([a-z0-9](?:[a-z0-9.-]*[a-z0-9])?)(?::([0-9]{1,5}))?\/([A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*)$/.exec(value5);
189370
+ return !!match3 && match3[1].split(".").every((label6) => label6.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label6)) && (!match3[2] || +match3[2] > 0 && +match3[2] <= 65535) && match3[3].split("/").every((part) => part !== "." && part !== "..");
189371
+ }
189100
189372
  function validateOptions(v) {
189101
189373
  object18(v, ["attempts", "concurrency", "seed", "strict", "minPassRate", "allowUnwrapped", "agentCommand", "baseline"], "options");
189102
189374
  integer11(v.attempts, 1, 1e4, "attempts");
@@ -189114,7 +189386,8 @@ function validateOptions(v) {
189114
189386
  return v;
189115
189387
  }
189116
189388
  function validateManifest(v) {
189117
- object18(v, ["version", "kind", "configPath", "agentName", "projectKey", "entrypoints", "options", "files", "references", "projectHash", "provenance"], "manifest");
189389
+ object18(v, ["version", "kind", "configPath", "agentName", "projectKey", "repository", "entrypoints", "options", "files", "references", "projectHash", "provenance"], "manifest");
189390
+ if (v.repository !== void 0 && !validRepository(v.repository)) reject2("Invalid repository.");
189118
189391
  if (v.version !== 1 || !JOB_KINDS2.includes(v.kind)) reject2("Invalid bundle version or kind.");
189119
189392
  if (v.projectKey !== void 0 && (typeof v.projectKey !== "string" || v.projectKey.length !== 32 || !PROJECT_KEY.test(v.projectKey))) reject2("Invalid project key.");
189120
189393
  string7(v.agentName, "agentName");
@@ -189187,7 +189460,7 @@ function validateSpec(spec) {
189187
189460
  function validateStoredBody(table4, v) {
189188
189461
  table4 = table4.replace(/^cloud_/, "");
189189
189462
  if (!CLOUD_TABLES.includes(table4)) reject2("Invalid cloud table.");
189190
- object18(v, ["version", ...BODY_FIELDS[table4], ...table4 === "agents" ? ["projectKey"] : []], `${table4} body`);
189463
+ object18(v, ["version", ...BODY_FIELDS[table4], ...table4 === "agents" ? ["projectKey", "repository", "modelKeyNames"] : []], `${table4} body`);
189191
189464
  if (v.version !== 1) reject2("Invalid stored body version.");
189192
189465
  for (const key4 of BODY_FIELDS[table4]) if (!(key4 in v)) reject2(`Missing ${table4}.${key4}.`);
189193
189466
  if (table4 === "bundles") {
@@ -189196,7 +189469,18 @@ function validateStoredBody(table4, v) {
189196
189469
  hash4(v.projectHash);
189197
189470
  }
189198
189471
  if (table4 === "jobs") {
189472
+ if (v.private?.runMetadata !== void 0) {
189473
+ try {
189474
+ validateRunMetadata(v.private.runMetadata);
189475
+ } catch {
189476
+ reject2("Invalid run metadata.");
189477
+ }
189478
+ }
189199
189479
  if (!JOB_KINDS2.includes(v.kind) || !JOB_STATES.includes(v.state) || !(v.kind === "run" ? RUN_CLOUD_ID : v.kind === "view" ? VIEW_CLOUD_ID : CONNECT_CLOUD_ID).test(v.id)) reject2("Invalid job.");
189480
+ if (v.private?.rerunOf !== void 0) {
189481
+ object18(v.private.rerunOf, ["runId", "mode"], "rerunOf");
189482
+ if (!RUN_CLOUD_ID.test(v.private?.rerunOf.runId) || !["again", "failed", "test"].includes(v.private?.rerunOf.mode)) reject2("Invalid rerun source.");
189483
+ }
189200
189484
  hash4(v.bundleHash);
189201
189485
  hash4(v.projectHash);
189202
189486
  hash4(v.requestHash);
@@ -189251,6 +189535,8 @@ function validateStoredBody(table4, v) {
189251
189535
  if (typeof v.private.cleanupPending !== "boolean") reject2("Invalid cleanup state.");
189252
189536
  }
189253
189537
  if (table4 === "agents") {
189538
+ if (v.repository !== void 0 && !validRepository(v.repository)) reject2("Invalid repository.");
189539
+ if (v.modelKeyNames !== void 0 && (!Array.isArray(v.modelKeyNames) || v.modelKeyNames.length > MODEL_KEY_NAMES.length || new Set(v.modelKeyNames).size !== v.modelKeyNames.length || v.modelKeyNames.some((name5) => !MODEL_KEY_NAMES.includes(name5)))) reject2("Invalid model key names.");
189254
189540
  if (v.projectKey !== void 0 && (typeof v.projectKey !== "string" || v.projectKey.length !== 32 || !PROJECT_KEY.test(v.projectKey))) reject2("Invalid project key.");
189255
189541
  if (!["ready", "configured", "connected", "connecting", "failed"].includes(v.state)) reject2("Invalid agent state.");
189256
189542
  string7(v.name, "agent name");
@@ -189274,11 +189560,11 @@ function validateStoredBody(table4, v) {
189274
189560
  return v;
189275
189561
  }
189276
189562
  function projectJob(row2) {
189277
- return { ...projection(row2, JOB_FIELDS), lastSeq: row2.last_seq ?? row2.body?.lastSeq ?? row2.lastSeq };
189563
+ return { ...projection(row2, JOB_FIELDS), ...(row2.body ?? row2).private?.runMetadata ?? {}, lastSeq: row2.last_seq ?? row2.body?.lastSeq ?? row2.lastSeq };
189278
189564
  }
189279
189565
  function projectJobDetail(row2) {
189280
189566
  const body7 = row2.body ?? row2;
189281
- return { ...projectJob(row2), imageDigest: imageDigestOf(body7.spec?.imageDigest), cliVersion: body7.private?.cliVersion ?? null };
189567
+ return { ...projectJob(row2), ...body7.private?.rerunOf !== void 0 && { rerunOf: body7.private?.rerunOf }, imageDigest: imageDigestOf(body7.spec?.imageDigest), cliVersion: body7.private?.cliVersion ?? null };
189282
189568
  }
189283
189569
  function projectAttempt(row2) {
189284
189570
  const body7 = row2.body ?? row2, m = body7.machine;
@@ -189289,10 +189575,11 @@ async function computeProjectHash(files2) {
189289
189575
  const digest4 = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonicalJson2(inventory)));
189290
189576
  return Array.from(new Uint8Array(digest4), (byte) => byte.toString(16).padStart(2, "0")).join("");
189291
189577
  }
189292
- var UUID2, RUN_CLOUD_ID, CONNECT_CLOUD_ID, VIEW_CLOUD_ID, ATTEMPT_CLOUD_ID, AGENT_CLOUD_ID, PROJECT_KEY, SHA256_HEX, CASE_ID, ATTEMPT_TOKEN_PREFIX, JOB_KINDS2, JOB_STATES, TERMINAL_JOB_STATES, ATTEMPT_ROLES, ATTEMPT_STATES, TERMINAL_ATTEMPT_STATES, ACTIVE_ATTEMPT_STATES, FILE_ROLES, EVALUATION_ROLES, AGENT_FILE_ROLES, MIB, BUNDLE_LIMITS, ARTIFACT_LIMITS, CLOUD_MODEL_HOSTS, DEFAULT_MODEL_HOSTS, PROBE_OUTCOMES, ANSWER_SOURCES, HEARTBEAT_MS, AGENT_UID, BUILD_UID, CLOUD_EXIT, CLOUD_TABLES, isTerminalJob, isTerminalAttempt, CloudError, reject2, string7, integer11, hash4, strings2, JOB_FIELDS, ATTEMPT_FIELDS, BODY_FIELDS, date10, errorBody7, projection, imageDigestOf, cliVersionOf;
189578
+ var UUID2, RUN_CLOUD_ID, CONNECT_CLOUD_ID, VIEW_CLOUD_ID, ATTEMPT_CLOUD_ID, AGENT_CLOUD_ID, PROJECT_KEY, SHA256_HEX, CASE_ID, ATTEMPT_TOKEN_PREFIX, JOB_KINDS2, JOB_STATES, TERMINAL_JOB_STATES, ATTEMPT_ROLES, ATTEMPT_STATES, TERMINAL_ATTEMPT_STATES, ACTIVE_ATTEMPT_STATES, FILE_ROLES, EVALUATION_ROLES, AGENT_FILE_ROLES, MIB, BUNDLE_LIMITS, ARTIFACT_LIMITS, CLOUD_MODEL_HOSTS, DEFAULT_MODEL_HOSTS, MODEL_KEY_NAMES, PROBE_OUTCOMES, ANSWER_SOURCES, HEARTBEAT_MS, AGENT_UID, BUILD_UID, CLOUD_EXIT, CLOUD_TABLES, isTerminalJob, isTerminalAttempt, CloudError, reject2, string7, integer11, hash4, strings2, JOB_FIELDS, ATTEMPT_FIELDS, BODY_FIELDS, date10, errorBody7, projection, imageDigestOf, cliVersionOf;
189293
189579
  var init_jobs_contract = __esm({
189294
189580
  "cloud/shared/jobs-contract.mjs"() {
189295
189581
  "use strict";
189582
+ init_run_metadata();
189296
189583
  UUID2 = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
189297
189584
  RUN_CLOUD_ID = new RegExp(`^run_cloud_${UUID2}$`);
189298
189585
  CONNECT_CLOUD_ID = new RegExp(`^connect_cloud_${UUID2}$`);
@@ -189318,6 +189605,7 @@ var init_jobs_contract = __esm({
189318
189605
  ARTIFACT_LIMITS = { compressedBytes: 50 * MIB, expandedBytes: 64 * MIB, entries: 32, largeFileBytes: 12 * MIB, fileBytes: 4 * MIB };
189319
189606
  CLOUD_MODEL_HOSTS = ["openrouter.ai", "api.openai.com", "api.anthropic.com", "generativelanguage.googleapis.com", "api.groq.com", "api.mistral.ai", "api.together.xyz", "api.fireworks.ai", "api.deepseek.com", "api.x.ai", "api.cohere.com"];
189320
189607
  DEFAULT_MODEL_HOSTS = ["openrouter.ai", "api.openai.com", "api.anthropic.com"];
189608
+ MODEL_KEY_NAMES = ["OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "GOOGLE_API_KEY", "OPENROUTER_API_KEY", "AZURE_OPENAI_API_KEY", "MISTRAL_API_KEY", "GROQ_API_KEY", "DEEPSEEK_API_KEY", "XAI_API_KEY", "COHERE_API_KEY", "TOGETHER_API_KEY", "FIREWORKS_API_KEY"];
189321
189609
  PROBE_OUTCOMES = ["answered", "refused", "outside_host", "unserved", "crashed", "idle", "no_answer", "wrong_answer", "model_key", "missing_secret"];
189322
189610
  ANSWER_SOURCES = ["done", "reply", "stdout"];
189323
189611
  HEARTBEAT_MS = 1e4;
@@ -189472,6 +189760,7 @@ async function startIsolationGateway(options4) {
189472
189760
  if (upstream.pathname !== path7 || upstream.search || upstream.hash) throw new Error("Invalid trial session route");
189473
189761
  sessionRoutes2.set(path7, { method: method2, upstream });
189474
189762
  }
189763
+ const socketGrants = /* @__PURE__ */ new Map();
189475
189764
  const modelHosts = new Set((options4.modelHosts ?? []).map(normalizeModelHost));
189476
189765
  const sockets = /* @__PURE__ */ new Set();
189477
189766
  const upstreamRequests = /* @__PURE__ */ new Set();
@@ -189529,7 +189818,9 @@ async function startIsolationGateway(options4) {
189529
189818
  upstream = route12.upstream;
189530
189819
  if (path7 === "/_ancha/context") transform3 = "context";
189531
189820
  }
189532
- if (req.method === "CONNECT" || req.method === "TRACE" || req.headers.upgrade || path7.endsWith("/apps.connections.open")) return reject3(res, 501, "This transport is not qualified for contained execution.");
189821
+ const socketOpen = decodeURIComponent(path7) === `/e/${env2.id}/slack/api/apps.connections.open`;
189822
+ if (req.method === "CONNECT" || req.method === "TRACE" || req.headers.upgrade || decodeURIComponent(path7).endsWith("/apps.connections.open") && !(socketOpen && options4.slackSocket && session2)) return reject3(res, 501, "This transport is not qualified for contained execution.");
189823
+ if (socketOpen && options4.slackSocket && session2) transform3 = "socket";
189533
189824
  const headers = cleanHeaders(req.headers);
189534
189825
  headers.host = modelHost ?? new URL(exposedOrigin ?? upstream.origin).host;
189535
189826
  delete headers["x-ancha-client-origin"];
@@ -189601,6 +189892,15 @@ async function startIsolationGateway(options4) {
189601
189892
  const connection4 = mapped(exposedOrigin ?? "");
189602
189893
  value5 = { ...value5, env: connection4.env, session: connection4.session };
189603
189894
  }
189895
+ if (transform3 === "socket" && reply5.statusCode === 200 && value5?.ok === true) {
189896
+ const grant = new URL(value5.url);
189897
+ const expected = loopbackOrigin(session2.eventsUrl);
189898
+ if (grant.protocol !== "ws:" || grant.hostname !== expected.hostname || grant.port !== expected.port || grant.search || grant.hash || grant.username || grant.password || !/^\/_ancha\/socket\/[a-f0-9]{64}$/.test(grant.pathname)) throw new Error("Invalid socket grant");
189899
+ for (const [path8, old] of socketGrants) if (old.expires <= Date.now()) socketGrants.delete(path8);
189900
+ if (socketGrants.size >= 128) throw new Error("Too many socket grants");
189901
+ socketGrants.set(grant.pathname, { url: grant, expires: Date.now() + 3e4 });
189902
+ value5 = { ...value5, url: (exposedOrigin ?? "").replace(/^http:/, "ws:") + grant.pathname };
189903
+ }
189604
189904
  const body7 = JSON.stringify(value5);
189605
189905
  delete responseHeaders["content-encoding"];
189606
189906
  delete responseHeaders["content-length"];
@@ -189641,7 +189941,52 @@ async function startIsolationGateway(options4) {
189641
189941
  });
189642
189942
  });
189643
189943
  server.on("clientError", (_error, socket) => socket.destroy());
189644
- server.on("upgrade", (_req, socket) => socket.end("HTTP/1.1 501 Not Implemented\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"));
189944
+ server.on("upgrade", (req, socket, head) => {
189945
+ const denied = () => {
189946
+ socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", () => socket.destroy());
189947
+ };
189948
+ const grant = socketGrants.get(req.url ?? "");
189949
+ if (closed || !options4.slackSocket || !grant || grant.expires <= Date.now() || req.method !== "GET" || req.headers.upgrade?.toLowerCase() !== "websocket") {
189950
+ denied();
189951
+ return;
189952
+ }
189953
+ socketGrants.delete(req.url);
189954
+ const headers = { host: grant.url.host, connection: "Upgrade", upgrade: "websocket" };
189955
+ for (const name5 of ["sec-websocket-key", "sec-websocket-version", "sec-websocket-protocol", "sec-websocket-extensions"]) if (req.headers[name5] !== void 0) headers[name5] = req.headers[name5];
189956
+ const target5 = request({ hostname: grant.url.hostname, port: grant.url.port || 80, path: grant.url.pathname, headers, agent: false });
189957
+ upstreamRequests.add(target5);
189958
+ target5.once("close", () => upstreamRequests.delete(target5));
189959
+ target5.once("error", () => socket.destroy());
189960
+ target5.once("response", (reply5) => {
189961
+ reply5.destroy();
189962
+ denied();
189963
+ });
189964
+ target5.setTimeout(1e4, () => target5.destroy());
189965
+ socket.once("close", () => target5.destroy());
189966
+ target5.once("upgrade", (reply5, peer, upstreamHead) => {
189967
+ target5.setTimeout(0);
189968
+ if (closed || socket.destroyed) {
189969
+ peer.destroy();
189970
+ return;
189971
+ }
189972
+ sockets.add(peer);
189973
+ peer.once("close", () => {
189974
+ sockets.delete(peer);
189975
+ socket.destroy();
189976
+ });
189977
+ peer.on("error", () => socket.destroy());
189978
+ socket.once("close", () => peer.destroy());
189979
+ socket.write(`HTTP/1.1 101 Switching Protocols\r
189980
+ ${Object.entries(reply5.headers).map(([name5, value5]) => `${name5}: ${value5}`).join("\r\n")}\r
189981
+ \r
189982
+ `);
189983
+ if (upstreamHead.length) socket.write(upstreamHead);
189984
+ if (head.length) peer.write(head);
189985
+ socket.pipe(peer);
189986
+ peer.pipe(socket);
189987
+ });
189988
+ target5.end();
189989
+ });
189645
189990
  server.on("connect", (_req, client2) => client2.end("HTTP/1.1 403 Rejected\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"));
189646
189991
  await new Promise((resolve59, rejectListen) => {
189647
189992
  server.once("error", rejectListen);
@@ -189657,6 +190002,7 @@ async function startIsolationGateway(options4) {
189657
190002
  let closing;
189658
190003
  const close = () => closing ??= (async () => {
189659
190004
  closed = true;
190005
+ socketGrants.clear();
189660
190006
  options4.signal?.removeEventListener("abort", abort);
189661
190007
  for (const target5 of upstreamRequests) target5.destroy();
189662
190008
  for (const socket of sockets) socket.destroy();
@@ -190086,7 +190432,7 @@ import { closeSync as closeSync2, fstatSync as fstatSync2, openSync as openSync2
190086
190432
  import { tmpdir } from "node:os";
190087
190433
  import { join as join6 } from "node:path";
190088
190434
  import { StringDecoder } from "node:string_decoder";
190089
- import { setTimeout as sleep2 } from "node:timers/promises";
190435
+ import { setTimeout as sleep3 } from "node:timers/promises";
190090
190436
  function signalGroup(pid, signal) {
190091
190437
  try {
190092
190438
  process.kill(-pid, signal);
@@ -190189,7 +190535,7 @@ function startAgentProcess(command, opts) {
190189
190535
  const exited = outcome4.then(async (result) => {
190190
190536
  try {
190191
190537
  if (pid !== void 0) {
190192
- while (terminating && groupAlive(pid) && performance.now() < graceEnds) await sleep2(GROUP_POLL_MS);
190538
+ while (terminating && groupAlive(pid) && performance.now() < graceEnds) await sleep3(GROUP_POLL_MS);
190193
190539
  }
190194
190540
  return result;
190195
190541
  } finally {
@@ -190674,8 +191020,8 @@ async function preflightExecution(agent, scenes = [], signal) {
190674
191020
  const descriptor3 = attemptDescriptor();
190675
191021
  explicitEnvironment(vmEnvironmentNames(agent), descriptor3.secretValues);
190676
191022
  vmModelHosts(descriptor3.modelHosts);
190677
- if (agent.mode === "endpoint" && agent.start === void 0) throw new AnchaError("CONFIG_INVALID", "Cloud HTTP agents require a start command.");
190678
- if (agent.slackTransport === "socket" || scenes.some((scene2) => scene2.twins.includes("google-ads"))) throw new AnchaError("CONFIG_INVALID", "Choose HTTP tool connections for this attempt runtime.");
191023
+ if (agent.mode === "endpoint") assertVmEndpoint(agent);
191024
+ if (scenes.some((scene2) => scene2.twins.includes("google-ads"))) throw new AnchaError("CONFIG_INVALID", "Choose HTTP tool connections for this attempt runtime.");
190679
191025
  return;
190680
191026
  }
190681
191027
  if (agent.execution === void 0) return;
@@ -190964,6 +191310,7 @@ var exec, RELAY_IMAGE, RELAY_PORT, LOG_LIMIT, LABEL, CONTAINER_RECORDS, CONTAINE
190964
191310
  var init_docker = __esm({
190965
191311
  "backend/src/execution/docker.ts"() {
190966
191312
  "use strict";
191313
+ init_slack_app();
190967
191314
  init_src();
190968
191315
  init_agent_env();
190969
191316
  init_agent_output();
@@ -191019,7 +191366,7 @@ import { writeSync as writeSync3 } from "node:fs";
191019
191366
  import { chmod as chmod3, chown, copyFile as copyFile3, mkdir as mkdir4, mkdtemp as mkdtemp2, writeFile as writeFile4 } from "node:fs/promises";
191020
191367
  import { dirname as dirname5, join as join9 } from "node:path";
191021
191368
  import { StringDecoder as StringDecoder3 } from "node:string_decoder";
191022
- import { setTimeout as sleep3 } from "node:timers/promises";
191369
+ import { setTimeout as sleep4 } from "node:timers/promises";
191023
191370
  import { promisify as promisify2 } from "node:util";
191024
191371
  async function sweepAgentUid(uid, run6 = async (file3, args) => {
191025
191372
  await exec2(file3, args, { env: { PATH: VM_PATH }, timeout: 1e3, maxBuffer: 65536 });
@@ -191043,12 +191390,12 @@ async function sweepAgentUid(uid, run6 = async (file3, args) => {
191043
191390
  };
191044
191391
  if (!await alive4()) return;
191045
191392
  await signal("TERM");
191046
- for (const grace2 = performance.now() + KILL_GRACE_MS2; performance.now() < grace2 && await alive4(); ) await sleep3(50);
191393
+ for (const grace2 = performance.now() + KILL_GRACE_MS2; performance.now() < grace2 && await alive4(); ) await sleep4(50);
191047
191394
  const deadline3 = performance.now() + 1e4;
191048
191395
  do {
191049
191396
  await signal("KILL");
191050
191397
  if (!await alive4()) return;
191051
- await sleep3(50);
191398
+ await sleep4(50);
191052
191399
  } while (performance.now() < deadline3);
191053
191400
  throw new AnchaError("INTERNAL", "Agent processes remained after the cleanup deadline.");
191054
191401
  }
@@ -191168,6 +191515,7 @@ async function startVmAgent(command, opts, deps = {}) {
191168
191515
  ...opts.session && { session: opts.session },
191169
191516
  modelHosts,
191170
191517
  port: unsafe ? 0 : 18991,
191518
+ slackSocket: opts.agent.slackTransport === "socket",
191171
191519
  onModelReply: (host, status5, message7) => replies.add(host, status5, message7)
191172
191520
  });
191173
191521
  const mapped = gateway.rewrite(unsafe ? gateway.url : VM_GATEWAY_ORIGIN);
@@ -191617,10 +191965,10 @@ var init_values2 = __esm({
191617
191965
  });
191618
191966
 
191619
191967
  // node_modules/.pnpm/openai@7.43.0_@aws-sdk+credential-provider-node@3.972.91_@smithy+signature-v4@5.7.5_undici@8.12.3_ws@8.22.0_zod@4.6.7/node_modules/openai/internal/utils/sleep.mjs
191620
- var sleep4;
191968
+ var sleep5;
191621
191969
  var init_sleep = __esm({
191622
191970
  "node_modules/.pnpm/openai@7.43.0_@aws-sdk+credential-provider-node@3.972.91_@smithy+signature-v4@5.7.5_undici@8.12.3_ws@8.22.0_zod@4.6.7/node_modules/openai/internal/utils/sleep.mjs"() {
191623
- sleep4 = (ms2, ...signals) => new Promise((resolve59, reject4) => {
191971
+ sleep5 = (ms2, ...signals) => new Promise((resolve59, reject4) => {
191624
191972
  const activeSignals = [...new Set(signals.filter((signal) => signal != null))];
191625
191973
  let timeout;
191626
191974
  let settled = false;
@@ -207630,7 +207978,7 @@ async function pollWithResponse(retrieve, intermediateStatuses, terminalStatuses
207630
207978
  }
207631
207979
  }
207632
207980
  const signal = options4 && Object.prototype.propertyIsEnumerable.call(options4, "signal") ? options4.signal : void 0;
207633
- await (signal ? sleepUntilAborted(sleepInterval, signal) : sleep4(sleepInterval));
207981
+ await (signal ? sleepUntilAborted(sleepInterval, signal) : sleep5(sleepInterval));
207634
207982
  } else if (terminalStatuses.includes(status5)) {
207635
207983
  return data5;
207636
207984
  }
@@ -209902,7 +210250,7 @@ async function waitForFileProcessing(resource2, id14, pollInterval, maxWait) {
209902
210250
  const start2 = performance.now();
209903
210251
  let file3 = await resource2.retrieve(id14);
209904
210252
  while (!file3.status || !terminalStates.has(file3.status)) {
209905
- await sleep4(pollInterval);
210253
+ await sleep5(pollInterval);
209906
210254
  file3 = await resource2.retrieve(id14);
209907
210255
  if (performance.now() - start2 > maxWait) {
209908
210256
  throw new APIConnectionTimeoutError({
@@ -215797,7 +216145,7 @@ var init_client = __esm({
215797
216145
  } else {
215798
216146
  const retrySignals = requestSignal === options4.signal ? [requestSignal] : [requestSignal, options4.signal];
215799
216147
  try {
215800
- await sleep4(timeoutMillis, ...retrySignals);
216148
+ await sleep5(timeoutMillis, ...retrySignals);
215801
216149
  } catch (error65) {
215802
216150
  const abortedSignal = retrySignals.find((signal) => signal?.aborted);
215803
216151
  if (abortedSignal) {
@@ -216514,7 +216862,7 @@ __export(relay_exports, {
216514
216862
  cloudModelAccess: () => cloudModelAccess,
216515
216863
  requestRelayGrade: () => requestRelayGrade
216516
216864
  });
216517
- import { setTimeout as sleep5 } from "node:timers/promises";
216865
+ import { setTimeout as sleep6 } from "node:timers/promises";
216518
216866
  function relayUrl(relay) {
216519
216867
  try {
216520
216868
  const url4 = new URL(relay.baseUrl);
@@ -216560,7 +216908,7 @@ async function requestRelayGrade(relay, model2, rubric, evidence2, signal) {
216560
216908
  const response5 = await relayPost(relay, body7, signal ? AbortSignal.any([signal, deadline3]) : deadline3);
216561
216909
  const after = Number(response5.headers["retry-after"]);
216562
216910
  if ((response5.status === 429 || response5.status === 503 && response5.headers["retry-after"] !== void 0) && attempt < RETRIES) {
216563
- await sleep5(Math.min(RETRY_WAIT_MS, response5.headers["retry-after"] !== void 0 && Number.isFinite(after) && after >= 0 ? after * 1e3 : 2e3 * (attempt + 1)), void 0, { signal });
216911
+ await sleep6(Math.min(RETRY_WAIT_MS, response5.headers["retry-after"] !== void 0 && Number.isFinite(after) && after >= 0 ? after * 1e3 : 2e3 * (attempt + 1)), void 0, { signal });
216564
216912
  continue;
216565
216913
  }
216566
216914
  let json35;
@@ -217130,7 +217478,7 @@ import { closeSync as closeSync3, openSync as openSync3, writeSync as writeSync4
217130
217478
  import { mkdir as mkdir5 } from "node:fs/promises";
217131
217479
  import { createServer as createServer3 } from "node:net";
217132
217480
  import { join as join11, resolve as resolve11 } from "node:path";
217133
- import { setTimeout as sleep6 } from "node:timers/promises";
217481
+ import { setTimeout as sleep7 } from "node:timers/promises";
217134
217482
  function deadline2(ms2) {
217135
217483
  const controller = new AbortController();
217136
217484
  const end = performance.now() + ms2;
@@ -217200,7 +217548,7 @@ async function ready2(url4, signal, expectedEnvId, headerOptional = false) {
217200
217548
  return;
217201
217549
  }
217202
217550
  }
217203
- await sleep6(25, void 0, { signal });
217551
+ await sleep7(25, void 0, { signal });
217204
217552
  }
217205
217553
  signal.throwIfAborted();
217206
217554
  }
@@ -217244,7 +217592,7 @@ async function runEndpointTrial(spec) {
217244
217592
  try {
217245
217593
  const clockFile = agent.clock === "node" ? resolve11(dir2, "clock.json") : void 0;
217246
217594
  const session2 = await backend.prepareTrial(env2.id, { mode: "endpoint", idleMs: agent.idleMs, slackTransport: agent.slackTransport ?? "http", ...agent.setupCalls && { setupCalls: true }, ...clockFile && { clockFile }, ...agent.execution?.mode === "container" && { clientOrigin: "http://127.0.0.1:18991" } });
217247
- const runtime2 = { ...port && { port: port.port }, ...spec.attempt && { attempt: spec.attempt } };
217595
+ const runtime2 = { ...port && { port: managedAppPort(agent.url, port.port, agentTemplateVars(env2.id, env2.services, scene2.task ?? "", trial, session2)) }, ...spec.attempt && { attempt: spec.attempt } };
217248
217596
  const vars = agentTemplateVars(env2.id, env2.services, scene2.task ?? "", trial, session2, runtime2, env2.mcp);
217249
217597
  const logFd = openSync3(join11(dir2, "agent.log"), "w");
217250
217598
  const startedAt = performance.now();
@@ -217269,10 +217617,12 @@ async function runEndpointTrial(spec) {
217269
217617
  } };
217270
217618
  child2 = await launchAgent(agent.start, { agent: clocked, env: env2, scene: scene2, session: session2, trial, inheritedEnv, runtime: runtime2, logFd, dir: dir2, ...signal && { signal }, startupSignal });
217271
217619
  }
217620
+ if (child2?.pid !== void 0) spec.onAgentStarted?.();
217272
217621
  const earlyExit = child2?.exited.then((outcome4) => {
217273
217622
  throw new Error(outcome4.kind === "error" ? `could not start agent: ${outcome4.error.message}` : `agent exited during startup (code ${outcome4.code})`);
217274
217623
  });
217275
217624
  const bootstrap = async () => {
217625
+ if (agent.start && !agent.readyUrl && agent.slackTransport === "http" && env2.services.slack) await waitSlackHttp(renderAgentUrl(agent.url, { ...vars, service: "slack" }), env2.services.slack.signingSecret, session2.id, startupSignal);
217276
217626
  if (agent.setupUrl !== void 0) await setup(renderAgentUrl(agent.setupUrl, vars), agentSetupPayload(env2, scene2, agent, trial, session2, runtime2), startupSignal);
217277
217627
  if (agent.readyUrl !== void 0) await ready2(renderAgentUrl(agent.readyUrl, vars), startupSignal, agent.start !== void 0 ? env2.id : void 0, usesPort(agent.readyUrl));
217278
217628
  startupSignal.throwIfAborted();
@@ -217295,7 +217645,7 @@ async function runEndpointTrial(spec) {
217295
217645
  if (typeof status5.untilMs === "number") return { exit: "done", exitCode: null };
217296
217646
  if (status5.simMs >= timeoutMs) return { exit: "timeout", exitCode: null };
217297
217647
  if (status5.done) return { exit: status5.idle ? "idle" : "done", exitCode: null };
217298
- await sleep6(20, void 0, { signal: observingSignal });
217648
+ await sleep7(20, void 0, { signal: observingSignal });
217299
217649
  status5 = await abortable(backend.trialStatus(env2.id, session2.id), observingSignal);
217300
217650
  }
217301
217651
  };
@@ -217361,6 +217711,7 @@ var CLOCK_PRELOAD;
217361
217711
  var init_endpoint = __esm({
217362
217712
  "backend/src/runner/endpoint.ts"() {
217363
217713
  "use strict";
217714
+ init_slack_app();
217364
217715
  init_agent_input();
217365
217716
  init_src();
217366
217717
  init_config();
@@ -217377,7 +217728,7 @@ import { closeSync as closeSync4, openSync as openSync4 } from "node:fs";
217377
217728
  import { mkdir as mkdir6 } from "node:fs/promises";
217378
217729
  import { createServer as createServer4 } from "node:net";
217379
217730
  import { join as join12 } from "node:path";
217380
- import { setTimeout as sleep7 } from "node:timers/promises";
217731
+ import { setTimeout as sleep8 } from "node:timers/promises";
217381
217732
  async function reserve(used) {
217382
217733
  const held = [];
217383
217734
  let chosen = false;
@@ -217465,7 +217816,7 @@ async function runHttpTaskTrial(spec) {
217465
217816
  } catch {
217466
217817
  startup.throwIfAborted();
217467
217818
  }
217468
- if (!ready3) await sleep7(25, void 0, { signal: startup });
217819
+ if (!ready3) await sleep8(25, void 0, { signal: startup });
217469
217820
  }
217470
217821
  spec.onAgentStarted?.();
217471
217822
  await record29({ state: agent.connectionOnly ? "check-only" : "ready", connection: "connected", message: agent.connectionOnly ? "HTTP readiness passed. No task request was sent during this connection check." : "HTTP readiness passed. Preparing the task request." });
@@ -217963,7 +218314,7 @@ var init_agent_outcome = __esm({
217963
218314
  });
217964
218315
 
217965
218316
  // backend/src/runner/trial.ts
217966
- import { setTimeout as sleep8 } from "node:timers/promises";
218317
+ import { setTimeout as sleep9 } from "node:timers/promises";
217967
218318
  import { closeSync as closeSync6, openSync as openSync6, writeSync as writeSync6 } from "node:fs";
217968
218319
  import { mkdir as mkdir8 } from "node:fs/promises";
217969
218320
  import { join as join14 } from "node:path";
@@ -218029,6 +218380,7 @@ async function runTrial(spec) {
218029
218380
  let failure6;
218030
218381
  try {
218031
218382
  if (child2.pid !== void 0) spec.onAgentStarted?.();
218383
+ if (agent.slackTransport === "socket") await waitSlackSocket(backend, env2.id, session2.id, child2, AbortSignal.any([AbortSignal.timeout(3e4), ...signal ? [signal] : []]));
218032
218384
  await backend.startTrial(env2.id, session2.id);
218033
218385
  signal?.throwIfAborted();
218034
218386
  const status5 = await backend.trialStatus(env2.id, session2.id);
@@ -218046,11 +218398,11 @@ async function runTrial(spec) {
218046
218398
  const simulatedDeadline = parseDuration(scene2.timeout);
218047
218399
  void (async () => {
218048
218400
  while (observing && completed === void 0 && !timedOut) {
218049
- await sleep8(100);
218401
+ await sleep9(100);
218050
218402
  if (!observing || completed !== void 0 || timedOut) return;
218051
218403
  const now11 = await backend.trialStatus(env2.id, session2.id);
218052
218404
  if (!observing || completed !== void 0 || timedOut) return;
218053
- if (typeof now11.untilMs === "number") {
218405
+ if (typeof now11.untilMs === "number" || agent.slackTransport === "socket" && now11.done) {
218054
218406
  untilReached = true;
218055
218407
  void child2.stop();
218056
218408
  return;
@@ -218131,6 +218483,7 @@ var EXIT_COMMAND_NOT_FOUND2, unknownRoute18;
218131
218483
  var init_trial = __esm({
218132
218484
  "backend/src/runner/trial.ts"() {
218133
218485
  "use strict";
218486
+ init_slack_app();
218134
218487
  init_src();
218135
218488
  init_launch();
218136
218489
  init_artifacts2();
@@ -218220,6 +218573,7 @@ async function loadSceneOrTest(cwd, path7) {
218220
218573
  }
218221
218574
  if (!version22) return { scene: await loadSceneFile(file3) };
218222
218575
  const test3 = parseTestFile(doc);
218576
+ if (test3.function_tools) await readToolObservations({ tools: test3.function_tools }, dirname6(file3));
218223
218577
  const realTimeoutMs = testRealTimeoutMs(test3);
218224
218578
  const limit2 = realTimeoutMs === void 0 ? {} : { realTimeoutMs };
218225
218579
  if (typeof test3.world !== "string") return { scene: testToScene(test3), ...limit2 };
@@ -218725,7 +219079,7 @@ function renderSummaryText(s3, opts = {}) {
218725
219079
  if (s3.comparison !== void 0) lines2.push(...comparisonLines(s3.comparison));
218726
219080
  if ((opts.reproduction ?? []).length > 0) lines2.push(renderReproduction(opts.reproduction, { neverRan: never2 !== void 0 }), "");
218727
219081
  const noneGraded = s3.scenes.length > 0 && s3.scenes.every((scene2) => scene2.trials > 0 && (scene2.invalidTrials ?? 0) >= scene2.trials);
218728
- lines2.push(`${s3.pytest && !s3.pytest.graded && !s3.pytest.invalid ? s3.pytest.outcome + " (ungraded)" : noneGraded ? "invalid (no trials graded)" : s3.verdict} (minimum pass rate ${pct(s3.minPassRate)}%) run ${s3.runId}`);
219082
+ lines2.push(`${s3.pytest && !s3.pytest.graded && !s3.pytest.invalid ? s3.pytest.outcome + " (ungraded)" : noneGraded ? "invalid (no trials graded)" : s3.verdict} (minimum pass rate ${pct(s3.minPassRate)}%) run ${s3.runNumber ? `#${s3.runNumber}` : s3.runId}`);
218729
219083
  const next2 = nextAfterRun(s3, opts);
218730
219084
  if (never2 !== void 0) lines2.push(neverRanNextLine(never2, next2));
218731
219085
  else if (next2.length > 0) lines2.push(`next: ${next2.join(", then ")}`);
@@ -219542,6 +219896,36 @@ var init_run = __esm({
219542
219896
  }
219543
219897
  });
219544
219898
 
219899
+ // backend/src/kit/slack-app.ts
219900
+ function slackAppInSource(body7, file3) {
219901
+ const python = file3.endsWith(".py");
219902
+ const code5 = body7.replace(python ? /^\s*#.*$/gm : /\/\*[\s\S]*?\*\/|^\s*\/\/.*$/gm, "");
219903
+ if (!(python ? /\bfrom\s+slack_bolt\s+import\s+.*\bApp\b/ : /["']@slack\/bolt["']/).test(code5) || !/\bApp\s*\(/.test(code5)) return;
219904
+ const socket = python ? /\bSocketModeHandler\s*\(/.test(code5) : /\bsocketMode\s*:\s*true\b/.test(code5);
219905
+ const start2 = /\.start\s*\(([^\n;]*)/.exec(code5)?.[1];
219906
+ const portOption = /\bport\s*:\s*(\d+)/.exec(code5)?.[1];
219907
+ const hasPort = /\bport\s*:/.test(code5);
219908
+ if (!socket && start2 === void 0 && !hasPort) return;
219909
+ const env2 = {};
219910
+ const variables2 = [...code5.matchAll(/(?:process\.env\.([A-Za-z_]\w*)|(?:os\.)?(?:environ(?:\.get)?|getenv)\s*[\[(]\s*["']([A-Za-z_]\w*)["'])/g)].map((match3) => match3[1] ?? match3[2]);
219911
+ for (const name5 of variables2) {
219912
+ const value5 = /SIGNING.*SECRET/i.test(name5) ? "slack.signing_secret" : /APP.*TOKEN|TOKEN.*APP/i.test(name5) ? "slack.app_token" : /(?:SLACK|BOT).*TOKEN/i.test(name5) ? "slack.token" : /SLACK.*(?:URL|BASE)/i.test(name5) ? "slack.url" : void 0;
219913
+ if (value5) env2[name5] = `{{${value5}}}`;
219914
+ }
219915
+ if (socket) return { file: file3, transport: "socket", env: env2 };
219916
+ const portVar = variables2.find((name5) => /(?:^|_)PORT$/.test(name5));
219917
+ const literal4 = /^(?:\s*port\s*=)?\s*(\d+)\b/.exec(start2 ?? "")?.[1] ?? portOption;
219918
+ const dynamic = portVar !== void 0 && literal4 === void 0;
219919
+ if (dynamic) env2[portVar] = "{{agent.port}}";
219920
+ const path7 = /\b(?:endpoints|path)\s*:\s*["'](\/[^"']*)["']/.exec(code5)?.[1] ?? "/slack/events";
219921
+ return { file: file3, transport: "http", url: `http://127.0.0.1:${dynamic ? "{{agent.port}}" : literal4 ?? "3000"}${path7}`, env: env2 };
219922
+ }
219923
+ var init_slack_app2 = __esm({
219924
+ "backend/src/kit/slack-app.ts"() {
219925
+ "use strict";
219926
+ }
219927
+ });
219928
+
219545
219929
  // backend/src/kit/project-files.ts
219546
219930
  import { constants as constants8 } from "node:fs";
219547
219931
  import { lstat as lstat3, open as open5, readdir as readdir3 } from "node:fs/promises";
@@ -219700,6 +220084,135 @@ var init_start_command = __esm({
219700
220084
  }
219701
220085
  });
219702
220086
 
220087
+ // backend/src/kit/function-tools.ts
220088
+ function tokens3(text30, python) {
220089
+ const pattern = python ? /#[^\n]*|"""[\s\S]*?"""|'''[\s\S]*?'''|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[A-Za-z_$][\w$]*|[^\s]/g : /\/\/[^\n]*|\/\*[\s\S]*?\*\/|`(?:\\.|[^`\\])*`|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[A-Za-z_$][\w$]*|[^\s]/g;
220090
+ const out = [];
220091
+ let line2 = 1, offset18 = 0;
220092
+ for (const match3 of text30.matchAll(pattern)) {
220093
+ line2 += text30.slice(offset18, match3.index).split("\n").length - 1;
220094
+ const value5 = match3[0];
220095
+ if (!(python ? /^(?:#|"""|''')/ : /^(?:\/\/|\/\*|`)/).test(value5)) out.push({ value: value5, line: line2 });
220096
+ line2 += value5.split("\n").length - 1;
220097
+ offset18 = match3.index + value5.length;
220098
+ }
220099
+ return out;
220100
+ }
220101
+ function functionToolsIn(text30, source) {
220102
+ if (!/tool|create_?react_?agent/i.test(text30)) return [];
220103
+ const python = source.endsWith(".py"), ts3 = tokens3(text30, python), v = ts3.map((t) => t.value);
220104
+ const result = /* @__PURE__ */ new Map();
220105
+ const add = (name5, symbol2, at4) => {
220106
+ if (name5 && /^[A-Za-z_][\w.-]{0,127}$/.test(name5)) result.set(name5, { name: name5, symbol: symbol2, source, line: ts3[at4].line, language: python ? "py" : "ts" });
220107
+ };
220108
+ const end = (start2) => {
220109
+ const stack = [], pairs = { "(": ")", "[": "]", "{": "}" };
220110
+ for (let i = start2; i < v.length; i++) {
220111
+ if (pairs[v[i]]) stack.push(pairs[v[i]]);
220112
+ else if (v[i] === stack.at(-1) && stack.pop() && !stack.length) return i;
220113
+ }
220114
+ return start2;
220115
+ };
220116
+ const aliases = /* @__PURE__ */ new Set(["tool", "function_tool", "wrapTool"]);
220117
+ for (let i = 0; i < v.length; i++) if (aliases.has(v[i]) && v[i + 1] === "as" && identifier4(v[i + 2])) aliases.add(v[i + 2]);
220118
+ const definitions3 = /* @__PURE__ */ new Map();
220119
+ for (let i = 0; i < v.length; i++) {
220120
+ if (python && v[i] === "@") {
220121
+ let decorator = i + 1;
220122
+ while (v[decorator + 1] === ".") decorator += 2;
220123
+ if (!aliases.has(v[decorator])) continue;
220124
+ const close2 = v[decorator + 1] === "(" ? end(decorator + 1) : decorator;
220125
+ let d = close2 + 1;
220126
+ while (v[d] === "@") {
220127
+ d++;
220128
+ while (d < v.length && v[d] !== "def" && v[d] !== "async") d++;
220129
+ }
220130
+ if (v[d] === "async") d++;
220131
+ if (v[d] !== "def") continue;
220132
+ const symbol3 = v[d + 1];
220133
+ const args2 = v.slice(decorator + 2, close2);
220134
+ const named6 = args2.findIndex((x) => x === "name" || x === "name_override");
220135
+ const name6 = literal2(args2[named6 >= 0 ? named6 + 2 : 0]) ?? symbol3;
220136
+ definitions3.set(symbol3, name6);
220137
+ add(name6, symbol3, i);
220138
+ }
220139
+ if (v[i] !== "=" || !identifier4(v[i - 1])) continue;
220140
+ const symbol2 = v[i - 1];
220141
+ let c = i + 1;
220142
+ while (v[c + 1] === ".") c += 2;
220143
+ if (!(aliases.has(v[c]) || v[c] === "StructuredTool" || v[c] === "from_function") || v[c + 1] !== "(") continue;
220144
+ const close = end(c + 1), args = v.slice(c + 2, close);
220145
+ const named5 = args.findIndex((x) => x === "name" || x === "name_override");
220146
+ const name5 = literal2(args[named5 + 2]) ?? (v[c] === "wrapTool" ? literal2(args[0]) : void 0) ?? symbol2;
220147
+ definitions3.set(symbol2, name5);
220148
+ add(name5, symbol2, i - 1);
220149
+ }
220150
+ const lists2 = /* @__PURE__ */ new Map();
220151
+ for (let i = 0; i < v.length; i++) if (identifier4(v[i]) && v[i + 1] === "=" && ["[", "{"].includes(v[i + 2])) lists2.set(v[i], i + 2);
220152
+ const inspectList = (at4) => {
220153
+ const start2 = lists2.get(v[at4]) ?? at4;
220154
+ if (!["[", "{"].includes(v[start2])) return;
220155
+ const stop = end(start2), object20 = v[start2] === "{";
220156
+ const collection2 = v[start2 - 1] === "=" && identifier4(v[start2 - 2]) ? v[start2 - 2] : void 0;
220157
+ for (let j = start2 + 1; j < stop; ) {
220158
+ const symbol2 = v[j];
220159
+ if (identifier4(symbol2) || literal2(symbol2)) {
220160
+ const key4 = literal2(symbol2) ?? symbol2;
220161
+ const ref22 = object20 && v[j + 1] === ":" ? v[j + 2] : symbol2;
220162
+ const name5 = object20 ? key4 : definitions3.get(ref22) ?? ref22;
220163
+ add(name5, ref22, j);
220164
+ const tool = result.get(name5);
220165
+ if (tool && collection2) tool.collection = collection2;
220166
+ if (tool && object20 && !collection2) tool.inlineObject = true;
220167
+ }
220168
+ j++;
220169
+ while (j < stop && v[j] !== ",") {
220170
+ if (["(", "[", "{"].includes(v[j])) j = end(j);
220171
+ j++;
220172
+ }
220173
+ j++;
220174
+ }
220175
+ };
220176
+ for (let i = 0; i < v.length; i++) {
220177
+ if (["tools", "functions"].includes(v[i]) && ["=", ":"].includes(v[i + 1])) {
220178
+ let start2 = i + 2;
220179
+ if (v[start2] === "ancha" && v[start2 + 1] === ".") start2 += 2;
220180
+ if (["wrap_tools", "wrapTools"].includes(v[start2])) start2 += 2;
220181
+ inspectList(start2);
220182
+ }
220183
+ if (["bind_tools", "bindTools", "wrap_tools", "wrapTools"].includes(v[i]) && v[i + 1] === "(") inspectList(i + 2);
220184
+ if (["create_react_agent", "createReactAgent"].includes(v[i]) && v[i + 1] === "(") {
220185
+ const stop = end(i + 1);
220186
+ for (let j = i + 2; j < stop; j++) {
220187
+ if (v[j] === ",") {
220188
+ inspectList(j + 1);
220189
+ break;
220190
+ }
220191
+ if (["(", "[", "{"].includes(v[j])) j = end(j);
220192
+ }
220193
+ }
220194
+ }
220195
+ return [...result.values()];
220196
+ }
220197
+ function functionToolWiring(tools2) {
220198
+ return ["py", "ts"].flatMap((language) => {
220199
+ const found = tools2.filter((t) => t.language === language);
220200
+ if (!found.length) return [];
220201
+ const names5 = [...new Set(found.map((t) => t.symbol))].filter(identifier4).join(", ");
220202
+ const collections3 = [...new Set(found.map((t) => t.collection))];
220203
+ const js = collections3.length === 1 && collections3[0] ? `pass wrapTools(${collections3[0]}) as the framework's tools collection` : found.some((t) => t.inlineObject) ? "wrap the existing tools object in place: tools: wrapTools({ ... })" : `pass wrapTools([${names5}]) as the framework's tools list (for an AI SDK tools object, use wrapTools({${names5}}))`;
220204
+ return [language === "py" ? `Add import ancha; pass ancha.wrap_tools([${names5}]) as the framework's tools list, then call ancha.entry(run) at the task entrypoint.` : `Add import { wrapTools, entry } from '@ancha-labs/tools'; ${js}, then call await entry(run) at the task entrypoint.`];
220205
+ });
220206
+ }
220207
+ var identifier4, literal2;
220208
+ var init_function_tools = __esm({
220209
+ "backend/src/kit/function-tools.ts"() {
220210
+ "use strict";
220211
+ identifier4 = (value5 = "") => /^[A-Za-z_$][\w$]*$/.test(value5);
220212
+ literal2 = (value5 = "") => /^["'][A-Za-z_][\w.-]{0,127}["']$/.test(value5) ? value5.slice(1, -1) : void 0;
220213
+ }
220214
+ });
220215
+
219703
220216
  // backend/src/kit/tool-signals.ts
219704
220217
  function toolsForSdk(name5, imported2 = false) {
219705
220218
  const value5 = normalize3(name5);
@@ -219880,9 +220393,14 @@ async function detectProject(cwd, agent) {
219880
220393
  for (const dependency of dependencies) for (const twin of toolsForSdk(dependency)) if (!found.has(twin)) found.set(twin, `${dependency.toLowerCase()} in ${name5}`);
219881
220394
  }
219882
220395
  let sourceNode = false, sourcePython = false;
220396
+ const apps = [];
220397
+ const functions = /* @__PURE__ */ new Map();
219883
220398
  for (const name5 of files2.filter((name6) => SOURCE_FILE.test(name6))) {
219884
220399
  const body7 = await read7(name5);
219885
220400
  if (body7 === void 0) continue;
220401
+ const app2 = slackAppInSource(body7, name5);
220402
+ if (app2) apps.push(app2);
220403
+ for (const tool of functionToolsIn(body7, name5)) if (!functions.has(tool.name)) functions.set(tool.name, tool);
219886
220404
  if (name5.endsWith(".py")) sourcePython = true;
219887
220405
  else sourceNode = true;
219888
220406
  for (const [twin, signal] of sourceToolSignals(body7, name5.endsWith(".py"))) if (!found.has(twin)) found.set(twin, `${signal} in ${name5}`);
@@ -219893,15 +220411,22 @@ async function detectProject(cwd, agent) {
219893
220411
  }
219894
220412
  if (node5 && python) evidence2.push("mixed Node/Python sources; choose connect --lang explicitly");
219895
220413
  const start2 = agent === void 0 ? await inferStartCommand(read7, files2) : { agent, agentSource: "explicit" };
220414
+ const slackApp = apps.find((app2) => start2.agent?.includes(app2.file)) ?? (apps.length === 1 ? apps[0] : void 0);
220415
+ if (slackApp && start2.agent === null) {
220416
+ const file3 = slackApp.file;
220417
+ Object.assign(start2, { agent: `${file3.endsWith(".py") ? "python" : /\.ts$/.test(file3) ? "npx tsx" : "node"} '${file3.replaceAll("'", "'\\''")}'`, agentSource: "entry-file", agentEvidence: file3 });
220418
+ }
219896
220419
  const sdks = SUPPORTED_TWINS.filter((twin) => found.has(twin));
219897
- return { language: node5 === python ? "unknown" : node5 ? "ts" : "py", sdks, sdkSources: Object.fromEntries(sdks.map((twin) => [twin, found.get(twin)])), evidence: evidence2, ...start2 };
220420
+ return { language: node5 === python ? "unknown" : node5 ? "ts" : "py", sdks, sdkSources: Object.fromEntries(sdks.map((twin) => [twin, found.get(twin)])), evidence: evidence2, functionTools: [...functions.values()], ...start2, ...slackApp && { slackApp } };
219898
220421
  }
219899
220422
  var init_detect = __esm({
219900
220423
  "backend/src/kit/detect.ts"() {
219901
220424
  "use strict";
220425
+ init_slack_app2();
219902
220426
  init_src();
219903
220427
  init_start_command();
219904
220428
  init_project_files();
220429
+ init_function_tools();
219905
220430
  init_tool_signals();
219906
220431
  }
219907
220432
  });
@@ -221438,7 +221963,7 @@ var init_harbor = __esm({
221438
221963
 
221439
221964
  // cloud/rebuild/readers/suiteql.mjs
221440
221965
  function tokenize9(sql6) {
221441
- const tokens4 = [];
221966
+ const tokens5 = [];
221442
221967
  for (let i = 0; i < sql6.length; ) {
221443
221968
  const c = sql6[i];
221444
221969
  if (/\s/.test(c)) {
@@ -221467,43 +221992,43 @@ function tokenize9(sql6) {
221467
221992
  }
221468
221993
  text30 += sql6[j++];
221469
221994
  }
221470
- tokens4.push({ t: "str", v: text30 });
221995
+ tokens5.push({ t: "str", v: text30 });
221471
221996
  i = j + 1;
221472
221997
  continue;
221473
221998
  }
221474
221999
  if (c === '"') {
221475
222000
  const end = sql6.indexOf('"', i + 1), stop = end < 0 ? sql6.length : end;
221476
- tokens4.push({ t: "id", v: sql6.slice(i + 1, stop).toLowerCase(), quoted: true });
222001
+ tokens5.push({ t: "id", v: sql6.slice(i + 1, stop).toLowerCase(), quoted: true });
221477
222002
  i = stop + 1;
221478
222003
  continue;
221479
222004
  }
221480
222005
  const number7 = /^\d*\.?\d+(?:e[+-]?\d+)?/i.exec(sql6.slice(i));
221481
222006
  if (/[0-9.]/.test(c) && number7) {
221482
- tokens4.push({ t: "num", v: Number(number7[0]) });
222007
+ tokens5.push({ t: "num", v: Number(number7[0]) });
221483
222008
  i += number7[0].length;
221484
222009
  continue;
221485
222010
  }
221486
222011
  const word2 = /^[A-Za-z_][\w$#]*/.exec(sql6.slice(i));
221487
222012
  if (word2) {
221488
- tokens4.push({ t: "id", v: word2[0].toLowerCase() });
222013
+ tokens5.push({ t: "id", v: word2[0].toLowerCase() });
221489
222014
  i += word2[0].length;
221490
222015
  continue;
221491
222016
  }
221492
222017
  const two = sql6.slice(i, i + 2);
221493
222018
  if (["<=", ">=", "<>", "!=", "||"].includes(two)) {
221494
- tokens4.push({ t: "op", v: two });
222019
+ tokens5.push({ t: "op", v: two });
221495
222020
  i += 2;
221496
222021
  continue;
221497
222022
  }
221498
- tokens4.push({ t: "op", v: c });
222023
+ tokens5.push({ t: "op", v: c });
221499
222024
  i++;
221500
222025
  }
221501
- return tokens4;
222026
+ return tokens5;
221502
222027
  }
221503
- function split(tokens4, isSeparator) {
222028
+ function split(tokens5, isSeparator) {
221504
222029
  const parts3 = [[]];
221505
222030
  let depth = 0;
221506
- for (const token4 of tokens4) {
222031
+ for (const token4 of tokens5) {
221507
222032
  if (op(token4, "(")) depth++;
221508
222033
  if (op(token4, ")")) depth--;
221509
222034
  if (depth === 0 && isSeparator(token4)) {
@@ -221514,30 +222039,30 @@ function split(tokens4, isSeparator) {
221514
222039
  }
221515
222040
  return parts3.filter((part) => part.length);
221516
222041
  }
221517
- function columnRef(tokens4) {
221518
- if (tokens4.length === 1 && tokens4[0].t === "id" && !RESERVED2.has(tokens4[0].v)) return [void 0, tokens4[0].v];
221519
- if (tokens4.length === 3 && tokens4[0].t === "id" && op(tokens4[1], ".") && tokens4[2].t === "id") return [tokens4[0].v, tokens4[2].v];
222042
+ function columnRef(tokens5) {
222043
+ if (tokens5.length === 1 && tokens5[0].t === "id" && !RESERVED2.has(tokens5[0].v)) return [void 0, tokens5[0].v];
222044
+ if (tokens5.length === 3 && tokens5[0].t === "id" && op(tokens5[1], ".") && tokens5[2].t === "id") return [tokens5[0].v, tokens5[2].v];
221520
222045
  return void 0;
221521
222046
  }
221522
- function selectItem(tokens4) {
222047
+ function selectItem(tokens5) {
221523
222048
  let alias;
221524
- if (tokens4.length >= 3 && word(tokens4.at(-2), "as") && tokens4.at(-1).t === "id") {
221525
- alias = tokens4.at(-1).v;
221526
- tokens4 = tokens4.slice(0, -2);
221527
- } else if (tokens4.length >= 2 && tokens4.at(-1).t === "id" && !RESERVED2.has(tokens4.at(-1).v) && !op(tokens4.at(-2), ".") && (tokens4.at(-2).t === "id" || op(tokens4.at(-2), ")") || tokens4.at(-2).t === "str" || tokens4.at(-2).t === "num" || word(tokens4.at(-2), "end"))) {
221528
- alias = tokens4.at(-1).v;
221529
- tokens4 = tokens4.slice(0, -1);
221530
- }
221531
- if (tokens4.length === 1 && op(tokens4[0], "*")) return { star: "*" };
221532
- if (tokens4.length === 3 && tokens4[0].t === "id" && op(tokens4[1], ".") && op(tokens4[2], "*")) return { star: tokens4[0].v };
221533
- const ref22 = columnRef(tokens4);
222049
+ if (tokens5.length >= 3 && word(tokens5.at(-2), "as") && tokens5.at(-1).t === "id") {
222050
+ alias = tokens5.at(-1).v;
222051
+ tokens5 = tokens5.slice(0, -2);
222052
+ } else if (tokens5.length >= 2 && tokens5.at(-1).t === "id" && !RESERVED2.has(tokens5.at(-1).v) && !op(tokens5.at(-2), ".") && (tokens5.at(-2).t === "id" || op(tokens5.at(-2), ")") || tokens5.at(-2).t === "str" || tokens5.at(-2).t === "num" || word(tokens5.at(-2), "end"))) {
222053
+ alias = tokens5.at(-1).v;
222054
+ tokens5 = tokens5.slice(0, -1);
222055
+ }
222056
+ if (tokens5.length === 1 && op(tokens5[0], "*")) return { star: "*" };
222057
+ if (tokens5.length === 3 && tokens5[0].t === "id" && op(tokens5[1], ".") && op(tokens5[2], "*")) return { star: tokens5[0].v };
222058
+ const ref22 = columnRef(tokens5);
221534
222059
  if (ref22) return { key: alias ?? ref22[1], table: ref22[0], column: ref22[1] };
221535
- const call4 = tokens4[0]?.t === "id" ? tokens4[0].v : void 0;
221536
- if (call4 === "builtin" && op(tokens4[1], ".") && word(tokens4[2], "df")) {
221537
- const args2 = inner(tokens4.slice(3)), column = args2 && columnRef(args2);
222060
+ const call4 = tokens5[0]?.t === "id" ? tokens5[0].v : void 0;
222061
+ if (call4 === "builtin" && op(tokens5[1], ".") && word(tokens5[2], "df")) {
222062
+ const args2 = inner(tokens5.slice(3)), column = args2 && columnRef(args2);
221538
222063
  if (column) return { key: alias, table: column[0], column: column[1], display: true };
221539
222064
  }
221540
- const args = call4 && inner(tokens4.slice(1));
222065
+ const args = call4 && inner(tokens5.slice(1));
221541
222066
  if (args) {
221542
222067
  const [first2, second] = split(args, (t) => op(t, ","));
221543
222068
  const column = first2 && columnRef(first2);
@@ -221546,10 +222071,10 @@ function selectItem(tokens4) {
221546
222071
  }
221547
222072
  return { key: alias };
221548
222073
  }
221549
- function conjuncts(tokens4, into) {
221550
- if (split(tokens4, (t) => word(t, "or")).length > 1) return;
222074
+ function conjuncts(tokens5, into) {
222075
+ if (split(tokens5, (t) => word(t, "or")).length > 1) return;
221551
222076
  let between = false;
221552
- const terms = split(tokens4, (t) => {
222077
+ const terms = split(tokens5, (t) => {
221553
222078
  if (word(t, "between")) between = true;
221554
222079
  else if (word(t, "and")) {
221555
222080
  if (between) {
@@ -221563,7 +222088,7 @@ function conjuncts(tokens4, into) {
221563
222088
  for (const term2 of terms) {
221564
222089
  const parts3 = split(term2, (t) => op(t, "="));
221565
222090
  if (parts3.length === 2) {
221566
- const [left, right] = parts3.map((p2) => columnRef(p2)), [lv, rv] = parts3.map(literal2);
222091
+ const [left, right] = parts3.map((p2) => columnRef(p2)), [lv, rv] = parts3.map(literal3);
221567
222092
  if (left && right) into.equal.push([left, right]);
221568
222093
  else if (left && rv) into.constants.push([left, rv.value]);
221569
222094
  else if (right && lv) into.constants.push([right, lv.value]);
@@ -221572,13 +222097,13 @@ function conjuncts(tokens4, into) {
221572
222097
  const at4 = term2.findIndex((t) => word(t, "in"));
221573
222098
  if (at4 > 0 && !word(term2[at4 - 1], "not")) {
221574
222099
  const column = columnRef(term2.slice(0, at4)), list18 = inner(term2.slice(at4 + 1)), values2 = list18 && split(list18, (t) => op(t, ","));
221575
- if (column && values2?.length === 1 && literal2(values2[0])) into.constants.push([column, literal2(values2[0]).value]);
222100
+ if (column && values2?.length === 1 && literal3(values2[0])) into.constants.push([column, literal3(values2[0]).value]);
221576
222101
  }
221577
222102
  }
221578
222103
  }
221579
- function fromClause(tokens4, into) {
222104
+ function fromClause(tokens5, into) {
221580
222105
  const tables = /* @__PURE__ */ new Map();
221581
- const items2 = split(tokens4, (t) => op(t, ","));
222106
+ const items2 = split(tokens5, (t) => op(t, ","));
221582
222107
  for (const item2 of items2) {
221583
222108
  let i = 0;
221584
222109
  const table4 = () => {
@@ -221612,11 +222137,11 @@ function fromClause(tokens4, into) {
221612
222137
  }
221613
222138
  function lineage2(sql6) {
221614
222139
  if (typeof sql6 !== "string") return void 0;
221615
- const tokens4 = tokenize9(sql6.trim().replace(/;\s*$/, ""));
221616
- if (!word(tokens4[0], "select")) return void 0;
222140
+ const tokens5 = tokenize9(sql6.trim().replace(/;\s*$/, ""));
222141
+ if (!word(tokens5[0], "select")) return void 0;
221617
222142
  const top = [];
221618
222143
  let depth = 0;
221619
- tokens4.forEach((t, i) => {
222144
+ tokens5.forEach((t, i) => {
221620
222145
  if (op(t, "(")) depth++;
221621
222146
  else if (op(t, ")")) depth--;
221622
222147
  else if (depth === 0 && t.t === "id" && !t.quoted) top.push([t.v, i]);
@@ -221624,15 +222149,15 @@ function lineage2(sql6) {
221624
222149
  if (top.some(([v]) => ["union", "minus", "intersect", "with"].includes(v))) return void 0;
221625
222150
  const from = top.find(([v]) => v === "from")?.[1];
221626
222151
  if (from === void 0) return void 0;
221627
- const after = (start2) => top.filter(([v, i]) => i > start2 && ["where", "group", "order", "having", "fetch", "offset", "limit"].includes(v)).map(([, i]) => i)[0] ?? tokens4.length;
222152
+ const after = (start2) => top.filter(([v, i]) => i > start2 && ["where", "group", "order", "having", "fetch", "offset", "limit"].includes(v)).map(([, i]) => i)[0] ?? tokens5.length;
221628
222153
  const into = { constants: [], equal: [] };
221629
- let list18 = tokens4.slice(1, from);
222154
+ let list18 = tokens5.slice(1, from);
221630
222155
  while (word(list18[0], "distinct", "all")) list18 = list18.slice(1);
221631
222156
  if (word(list18[0], "top") && list18[1]?.t === "num") list18 = list18.slice(2);
221632
- const tables = fromClause(tokens4.slice(from + 1, after(from)), into);
222157
+ const tables = fromClause(tokens5.slice(from + 1, after(from)), into);
221633
222158
  if (!tables?.size) return void 0;
221634
222159
  const where3 = top.find(([v]) => v === "where")?.[1];
221635
- if (where3 !== void 0) conjuncts(tokens4.slice(where3 + 1, after(where3)), into);
222160
+ if (where3 !== void 0) conjuncts(tokens5.slice(where3 + 1, after(where3)), into);
221636
222161
  const aliases = [...tables.keys()];
221637
222162
  const place2 = (alias, column) => {
221638
222163
  if (alias !== void 0) return tables.has(alias) ? alias : void 0;
@@ -221689,7 +222214,7 @@ function rowRecords(lin, row2) {
221689
222214
  }
221690
222215
  return [...by2].filter(([, e]) => Object.keys(e.fields).length).map(([alias, e]) => ({ alias, table: lin.tables.get(alias), fields: e.fields, formats: e.formats }));
221691
222216
  }
221692
- var word, op, RESERVED2, literal2, inner, COLUMNS;
222217
+ var word, op, RESERVED2, literal3, inner, COLUMNS;
221693
222218
  var init_suiteql2 = __esm({
221694
222219
  "cloud/rebuild/readers/suiteql.mjs"() {
221695
222220
  "use strict";
@@ -221743,12 +222268,12 @@ var init_suiteql2 = __esm({
221743
222268
  "first",
221744
222269
  "next"
221745
222270
  ]);
221746
- literal2 = (tokens4) => {
221747
- if (tokens4.length === 1 && (tokens4[0].t === "str" || tokens4[0].t === "num")) return { value: tokens4[0].v };
221748
- if (tokens4.length === 2 && op(tokens4[0], "-") && tokens4[1].t === "num") return { value: -tokens4[1].v };
222271
+ literal3 = (tokens5) => {
222272
+ if (tokens5.length === 1 && (tokens5[0].t === "str" || tokens5[0].t === "num")) return { value: tokens5[0].v };
222273
+ if (tokens5.length === 2 && op(tokens5[0], "-") && tokens5[1].t === "num") return { value: -tokens5[1].v };
221749
222274
  return void 0;
221750
222275
  };
221751
- inner = (tokens4) => op(tokens4[0], "(") && op(tokens4.at(-1), ")") ? tokens4.slice(1, -1) : void 0;
222276
+ inner = (tokens5) => op(tokens5[0], "(") && op(tokens5.at(-1), ")") ? tokens5.slice(1, -1) : void 0;
221752
222277
  COLUMNS = {
221753
222278
  transaction: [
221754
222279
  "id",
@@ -223543,11 +224068,11 @@ function startingState(check4, scene2) {
223543
224068
  )]);
223544
224069
  }
223545
224070
  if ("github.permission" in check4 && seed43.github) {
223546
- const args = check4["github.permission"], github2 = seed43.github;
223547
- const repo4 = github2.repos?.find((r2) => r2.ref === refName7(args.repo)), user8 = github2.users?.find((u) => u.ref === refName7(args.user));
224071
+ const args = check4["github.permission"], github3 = seed43.github;
224072
+ const repo4 = github3.repos?.find((r2) => r2.ref === refName7(args.repo)), user8 = github3.users?.find((u) => u.ref === refName7(args.user));
223548
224073
  if (!repo4 || !user8) return "unknown";
223549
224074
  const owner3 = repo4.name.split("/")[0].toLowerCase();
223550
- const member4 = github2.orgs?.find((o) => o.login.toLowerCase() === owner3)?.members?.some((m) => refName7(m.user) === user8.ref);
224075
+ const member4 = github3.orgs?.find((o) => o.login.toLowerCase() === owner3)?.members?.some((m) => refName7(m.user) === user8.ref);
223551
224076
  const collaborator = repo4.collaborators?.find((c) => refName7(c.user) === user8.ref);
223552
224077
  const direct = collaborator ? collaborator.permission ?? "write" : "none";
223553
224078
  const permission7 = owner3 === user8.login.toLowerCase() ? "admin" : direct === "none" && member4 ? "read" : direct;
@@ -223589,8 +224114,8 @@ function startingState(check4, scene2) {
223589
224114
  return "unknown";
223590
224115
  }
223591
224116
  function permissionState(check4, scene2, trace) {
223592
- const args = check4["github.permission"], github2 = scene2.seed.github;
223593
- const repo4 = github2?.repos?.find((r2) => r2.ref === refName7(args.repo)), user8 = github2?.users?.find((u) => u.ref === refName7(args.user));
224117
+ const args = check4["github.permission"], github3 = scene2.seed.github;
224118
+ const repo4 = github3?.repos?.find((r2) => r2.ref === refName7(args.repo)), user8 = github3?.users?.find((u) => u.ref === refName7(args.user));
223594
224119
  if (!repo4 || !user8) return "unknown";
223595
224120
  const path7 = `/repos/${repo4.name}/collaborators/${user8.login}/permission`.toLowerCase();
223596
224121
  let result = "unknown";
@@ -223997,7 +224522,7 @@ async function dependencyPlan(root3, options4 = {}) {
223997
224522
  if (typeof options4.install !== "string" || !options4.install.trim() || options4.install.length > 2e3 || /[\0\r\n]/.test(options4.install)) {
223998
224523
  throw new AnchaError("CONFIG_INVALID", "agent.install must be a non-empty single-line command of at most 2000 characters.");
223999
224524
  }
224000
- return { steps: [{ command: options4.install, reason: "agent.install" }], pathPrepend };
224525
+ return { steps: [{ command: PYTHON_INSTALLER.test(options4.install) ? inVenv(options4.install) : options4.install, reason: "agent.install" }], pathPrepend };
224001
224526
  }
224002
224527
  const names5 = ["package.json", "package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", ".yarnrc.yml", "uv.lock", "pyproject.toml", "requirements.txt"];
224003
224528
  const contents2 = Object.fromEntries(await Promise.all(names5.map(async (name5) => [name5, await manifest(root3, name5)])));
@@ -224034,10 +224559,13 @@ async function dependencyPlan(root3, options4 = {}) {
224034
224559
  } else if (has3("requirements.txt")) steps.push({ command: "python -m venv .venv && .venv/bin/python -m pip install --no-cache-dir -r requirements.txt", reason: "requirements.txt" });
224035
224560
  return { steps, pathPrepend };
224036
224561
  }
224562
+ var PYTHON_INSTALLER, inVenv;
224037
224563
  var init_dependency_plan = __esm({
224038
224564
  "backend/src/execution/dependency-plan.ts"() {
224039
224565
  "use strict";
224040
224566
  init_src();
224567
+ PYTHON_INSTALLER = /(?:^|[\s;&|(])(?:pip3?|pipenv|poetry|uv\s+pip|python3?(?:\.\d+)?\s+-m\s+pip)(?=\s|$)/;
224568
+ inVenv = (install) => `{ [ -x .venv/bin/python ] || python -m venv .venv; } && export VIRTUAL_ENV="$PWD/.venv" PATH="$PWD/.venv/bin:$PATH" && ${install}`;
224041
224569
  }
224042
224570
  });
224043
224571
 
@@ -224056,7 +224584,7 @@ import { closeSync as closeSync7, openSync as openSync7, writeSync as writeSync7
224056
224584
  import { mkdir as mkdir19, readFile as readFile24 } from "node:fs/promises";
224057
224585
  import { createServer as createServer5 } from "node:net";
224058
224586
  import { join as join42 } from "node:path";
224059
- import { setTimeout as sleep10 } from "node:timers/promises";
224587
+ import { setTimeout as sleep11 } from "node:timers/promises";
224060
224588
  function executable(command) {
224061
224589
  let text30 = command.trimStart();
224062
224590
  for (; ; ) {
@@ -224112,6 +224640,10 @@ async function probeVmConnection(descriptor3, deps = {}) {
224112
224640
  try {
224113
224641
  const config11 = deps.agent ? void 0 : await loadConfig(descriptor3.projectDir, descriptor3.configPath);
224114
224642
  const agent = deps.agent ?? withLocalEnvironment(resolveRunAgent(config11, descriptor3.projectDir, { ...descriptor3.options.agentCommand !== null && { agent: descriptor3.options.agentCommand }, parallel: 1 }).agent, config11);
224643
+ if (agent.mode === "endpoint") assertVmEndpoint(agent);
224644
+ if (agent.slackTransport === "socket" || agent.mode === "endpoint" && agent.slackTransport === "http" && (!agent.readyUrl || config11?.agent?.slackTransport === "http" || deps.agent?.slackTransport === "http")) {
224645
+ return await probeSlackApp(descriptor3, agent, probe, deps);
224646
+ }
224115
224647
  const http = agent.mode === "endpoint" || agent.taskInput?.kind === "http";
224116
224648
  probe.kind = http ? "http" : agent.taskInput?.kind === "per_event" ? "per_event" : "command";
224117
224649
  const twins = agent.mode === "endpoint" ? [] : await probeTwins(descriptor3.agentDir, agent, await connectionTools(descriptor3.projectDir));
@@ -224170,7 +224702,7 @@ async function probeVmConnection(descriptor3, deps = {}) {
224170
224702
  } catch {
224171
224703
  signal.throwIfAborted();
224172
224704
  }
224173
- await sleep10(25, void 0, { signal });
224705
+ await sleep11(25, void 0, { signal });
224174
224706
  }
224175
224707
  } catch (error65) {
224176
224708
  await child2?.stop();
@@ -224272,10 +224804,65 @@ async function runWithTask(descriptor3, agent, run6) {
224272
224804
  Object.assign(probe, { logTail: tail.length > 0 ? tail : text30.trimEnd().split("\n").filter(Boolean).slice(-10), ...fix !== void 0 && { fix } });
224273
224805
  return { state: "failed", probe, message: outcome4.reason.message };
224274
224806
  }
224807
+ async function probeSlackApp(descriptor3, agent, probe, deps) {
224808
+ const command = agent.mode === "endpoint" ? agent.start : agent.command;
224809
+ const socket = agent.slackTransport === "socket";
224810
+ probe.kind = socket ? "command" : "http";
224811
+ const missing9 = await deps.entryCheck?.(command);
224812
+ if (missing9) return { state: "failed", probe, message: missing9 };
224813
+ let backend, env2, child2, fd;
224814
+ const began = performance.now();
224815
+ try {
224816
+ const twins = [.../* @__PURE__ */ new Set(["slack", ...await probeTwins(descriptor3.agentDir, { command, env: agent.env }, await connectionTools(descriptor3.projectDir))])];
224817
+ const scene2 = parseScene({ id: "connection", title: "Slack app connection", twins, seed: Object.fromEntries(twins.map((twin) => [twin, toolStarterSeed(twin)])), start_time: "2026-01-01T00:00:00Z", checks: [] });
224818
+ validateAgentEnv(scene2, agent);
224819
+ backend = await (deps.openBackend ?? (() => openBackend({ peopleRelay: cloudModelAccess(descriptor3.relay).peopleRelay })))();
224820
+ env2 = await backend.createEnv(scene2, "connection", { paused: true });
224821
+ const session2 = await backend.prepareTrial(env2.id, { mode: "endpoint", slackTransport: socket ? "socket" : "http", setupCalls: true });
224822
+ const reserved = socket ? void 0 : await (deps.port ?? freePort)();
224823
+ const port = agent.mode === "endpoint" ? managedAppPort(agent.url, reserved, agentTemplateVars(env2.id, env2.services, "", 1, session2)) : void 0;
224824
+ await mkdir19(descriptor3.outDir, { recursive: true });
224825
+ fd = openSync7(join42(descriptor3.outDir, "agent.log"), "w", 384);
224826
+ const signal = AbortSignal.timeout(deps.probeMs ?? (agent.mode === "endpoint" ? agent.startupTimeoutMs : 3e4));
224827
+ child2 = await startVmAgent(command, { agent, env: env2, scene: scene2, session: session2, trial: 1, runtime: { port }, logFd: fd, dir: descriptor3.outDir, signal }, deps);
224828
+ probe.startedAt = (/* @__PURE__ */ new Date()).toISOString();
224829
+ if (socket) await waitSlackSocket(backend, env2.id, session2.id, child2, signal);
224830
+ else if (agent.mode === "endpoint") {
224831
+ const stopped = new AbortController();
224832
+ void child2.exited.then(() => stopped.abort(), () => stopped.abort());
224833
+ const vars = agentTemplateVars(env2.id, env2.services, "", 1, session2, { port });
224834
+ await waitSlackHttp(renderAgentUrl(agent.url, { ...vars, service: "slack" }), env2.services.slack.signingSecret, session2.id, AbortSignal.any([signal, stopped.signal]));
224835
+ }
224836
+ probe.passed = true;
224837
+ probe.readyAt = (/* @__PURE__ */ new Date()).toISOString();
224838
+ return { state: socket ? "ready" : "connected", probe, message: socket ? "The Slack app opened its Socket Mode connection." : "The Slack events URL answered its signed verification challenge." };
224839
+ } catch (error65) {
224840
+ await child2?.stop();
224841
+ child2 = void 0;
224842
+ const log3 = await readFile24(join42(descriptor3.outDir, "agent.log"), "utf8").catch(() => "");
224843
+ probe.logTail = log3.trimEnd().split("\n").filter(Boolean).slice(-10);
224844
+ const fix = socket ? slackSocketFix : slackHttpFix;
224845
+ return { state: "failed", probe, message: error65 instanceof AnchaError ? `${error65.message}${error65.hint ? ` ${error65.hint}` : ""}` : `The Slack app did not connect. ${fix}` };
224846
+ } finally {
224847
+ probe.durationMs = Math.round(performance.now() - began);
224848
+ try {
224849
+ await child2?.stop();
224850
+ } finally {
224851
+ if (fd !== void 0) closeSync7(fd);
224852
+ try {
224853
+ if (env2) await backend?.destroyEnv(env2.id);
224854
+ } finally {
224855
+ await backend?.close();
224856
+ }
224857
+ }
224858
+ }
224859
+ }
224275
224860
  var PROBE_TASK, PROBE_MS, NETSUITE_PROBE_TASK, NETSUITE_PROBE_MS, taskFixLine;
224276
224861
  var init_vm_connection = __esm({
224277
224862
  "backend/src/execution/vm-connection.ts"() {
224278
224863
  "use strict";
224864
+ init_slack_app();
224865
+ init_agent_env();
224279
224866
  init_src();
224280
224867
  init_backend();
224281
224868
  init_config();
@@ -224547,8 +225134,8 @@ async function assembleCloudRun(options4) {
224547
225134
  await checkFolders(options4.artifactsDir, input5);
224548
225135
  const manifest2 = await bundleManifest(options4.bundleDir);
224549
225136
  const config11 = await loadConfig(projectDir, manifest2.configPath);
224550
- const { agent } = resolveRunAgent(config11, projectDir, { ...resolved.agentCommand !== null && { agent: resolved.agentCommand } });
224551
- if (agent.mode === "endpoint") throw new AnchaError("INTERNAL", "a cloud run runs an agent started by a command");
225137
+ const { agent } = resolveRunAgent(config11, projectDir, { ...resolved.agentCommand !== null && { agent: resolved.agentCommand }, parallel: 1 });
225138
+ if (agent.mode === "endpoint") assertVmEndpoint(agent);
224552
225139
  const cases = await loadCases(projectDir, input5);
224553
225140
  const baseline = resolved.baseline === null ? void 0 : await pinnedBaseline2(projectDir, resolved.baseline);
224554
225141
  const runDir = join43(options4.outDir, runId2);
@@ -224568,7 +225155,7 @@ async function assembleCloudRun(options4) {
224568
225155
  }
224569
225156
  }
224570
225157
  const run6 = { runId: runId2, dir: runDir, startedAt: input5.startedAt, finishedAt: input5.finishedAt, results };
224571
- const engine = summarize(run6, manifest2.agentName, resolved.minPassRate, { strict: resolved.strict, agentCommand: agent.command });
225158
+ const engine = summarize(run6, manifest2.agentName, resolved.minPassRate, { strict: resolved.strict, agentCommand: agent.mode === "endpoint" ? agent.start : agent.command });
224572
225159
  if (baseline !== void 0 && engine.scenes.every((scene2) => scene2.trials > 0)) {
224573
225160
  engine.comparison = compareSummaries(engine, baseline);
224574
225161
  if (engine.comparison.regressed) engine.verdict = "fail";
@@ -224623,6 +225210,7 @@ var UUID3, ATTEMPT_ID, SHA256, CASE_ID2, FILE_NAME2, TRIAL_FILES, EXITS, TERMINA
224623
225210
  var init_assemble = __esm({
224624
225211
  "backend/src/cloud/assemble.ts"() {
224625
225212
  "use strict";
225213
+ init_slack_app();
224626
225214
  init_src();
224627
225215
  init_actions7();
224628
225216
  init_baselines();
@@ -225830,8 +226418,8 @@ function inferIntegrations(cx, { slack: slack2, datadog: datadog2, pagerduty })
225830
226418
  add({ from: "pagerduty", to: "slack", service: `$${s3.ref}` }, `PagerDuty posted about ${s3.name} in a channel the agent read`);
225831
226419
  }
225832
226420
  }
225833
- function inferPipelines(cx, github2) {
225834
- for (const repo4 of github2?.repos.values() ?? []) {
226421
+ function inferPipelines(cx, github3) {
226422
+ for (const repo4 of github3?.repos.values() ?? []) {
225835
226423
  if (!repo4.ref || !repo4.history) continue;
225836
226424
  const run6 = [...repo4.runs.values()].find((r2) => r2.status === "completed" && r2.conclusion === "success" && r2.head_branch === repo4.default_branch);
225837
226425
  if (run6) {
@@ -225852,23 +226440,23 @@ function inferPipelines(cx, github2) {
225852
226440
  }
225853
226441
  }
225854
226442
  }
225855
- function inferProblem(cx, { github: github2, datadog: datadog2 }) {
226443
+ function inferProblem(cx, { github: github3, datadog: datadog2 }) {
225856
226444
  const problem = datadog2?.problem;
225857
226445
  if (!problem) return;
225858
226446
  const rule = { ref: problem.ref, starts_at: cx.dur(Math.min(problem.first, cx.start) - cx.start) };
225859
226447
  cx.note("inferred", `world_rules.faults.${problem.ref}`, `active from ${rule.starts_at}${problem.last ? " (the first error log)" : " (no error log seen; a default)"}`);
225860
226448
  const recovered = datadog2.states.find((s3) => s3.state === "OK" && s3.ms > cx.start);
225861
- const deployed = [...github2?.repos.values() ?? []].flatMap((r2) => [...r2.runs.values()]).find((run6) => run6.status === "completed" && Date.parse(run6.created_at) >= cx.start);
225862
- const change3 = github2?.merged?.repo.writes;
226449
+ const deployed = [...github3?.repos.values() ?? []].flatMap((r2) => [...r2.runs.values()]).find((run6) => run6.status === "completed" && Date.parse(run6.created_at) >= cx.start);
226450
+ const change3 = github3?.merged?.repo.writes;
225863
226451
  if (recovered && deployed && change3?.size) {
225864
226452
  const resolvedAt = problem.last ? problem.last - cx.start + problem.every : recovered.ms - cx.start;
225865
- rule.resolved_when = { all: [...change3].map(([path7, content2]) => ({ file_at: [`$${github2.merged.repo.ref}`, "production", path7], equals: content2 })) };
226453
+ rule.resolved_when = { all: [...change3].map(([path7, content2]) => ({ file_at: [`$${github3.merged.repo.ref}`, "production", path7], equals: content2 })) };
225866
226454
  rule.recovery = cx.dur(resolvedAt - (Date.parse(deployed.updated_at) - cx.start));
225867
226455
  cx.note("inferred", `world_rules.faults.${problem.ref}.resolved_when`, `ends ${rule.recovery} after production gets the agent's change to ${[...change3.keys()].join(", ")}`);
225868
226456
  answerRecovery(cx, problem, rule);
225869
226457
  cx.ask(`recovery-${problem.ref}`, `After the fix reaches production, how does the problem end?`, [`It recovers about ${rule.recovery} after the deploy`, "It cannot recover before a minimum time has passed, then recovers quickly", "It recovers only after a manual step"], 0, { type: "recovery" });
225870
226458
  } else {
225871
- const suspect = [...github2?.repos.values() ?? []].flatMap((repo4) => (repo4.history ?? []).filter((cm) => Date.parse(cm.date) <= problem.first && cm.changed.size).map((cm) => ({ repo: repo4, cm }))).sort((a, b) => b.cm.date.localeCompare(a.cm.date))[0];
226459
+ const suspect = [...github3?.repos.values() ?? []].flatMap((repo4) => (repo4.history ?? []).filter((cm) => Date.parse(cm.date) <= problem.first && cm.changed.size).map((cm) => ({ repo: repo4, cm }))).sort((a, b) => b.cm.date.localeCompare(a.cm.date))[0];
225872
226460
  const parent2 = suspect && suspect.repo.commits.get(suspect.cm.parents[0]);
225873
226461
  const files2 = parent2 ? [...suspect.cm.changed.keys()].filter((path7) => parent2.content.has(path7)) : [];
225874
226462
  if (files2.length) {
@@ -225876,7 +226464,7 @@ function inferProblem(cx, { github: github2, datadog: datadog2 }) {
225876
226464
  rule.recovery = "20s";
225877
226465
  cx.note("inferred", `world_rules.faults.${problem.ref}.resolved_when`, `never seen to end; candidate: undoing ${suspect.cm.sha.slice(0, 7)} ("${suspect.cm.message.split("\n")[0]}") in ${files2.join(", ")}, recovering 20s later`);
225878
226466
  cx.ask(`fix-${problem.ref}`, `What ends this problem in production?`, [`Undoing ${suspect.cm.sha.slice(0, 7)} ("${suspect.cm.message.split("\n")[0]}")`, "A different change (describe it)", "It ends on its own after a while"], 0, { type: "fix" });
225879
- const merged = github2?.merged?.repo === suspect.repo ? github2.merged : void 0;
226467
+ const merged = github3?.merged?.repo === suspect.repo ? github3.merged : void 0;
225880
226468
  if (merged && files2.every((path7) => merged.repo.writes?.get(path7) === parent2.content.get(path7))) {
225881
226469
  const seen = [...datadog2.states.filter((st) => st.state === "Alert").map((st) => ({ ms: st.ms, span: st.span })), ...problem.last ? [{ ms: problem.last }] : []].filter((o) => o.ms > merged.ms).sort((a, b) => b.ms - a.ms)[0];
225882
226470
  if (seen && seen.ms > merged.ms + (suspect.repo.deployMs ?? 15e3) + 2e4) {
@@ -225956,7 +226544,7 @@ function proposeChecks(cx, { slack: slack2, datadog: datadog2, pagerduty }) {
225956
226544
  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));
225957
226545
  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));
225958
226546
  }
225959
- function proposeAccessChecks(cx, { okta, drive: drive2, pagerduty, github: github2 }) {
226547
+ function proposeAccessChecks(cx, { okta, drive: drive2, pagerduty, github: github3 }) {
225960
226548
  const add = (check4, detail3, production3) => {
225961
226549
  if (cx.checks.some((c) => c.id === check4.id)) return;
225962
226550
  cx.checks.push(check4);
@@ -225979,13 +226567,13 @@ function proposeAccessChecks(cx, { okta, drive: drive2, pagerduty, github: githu
225979
226567
  const name5 = pagerduty.schedules.get(id14)?.name ?? id14;
225980
226568
  add({ id: `oncall-covered-${slug15(name5)}`, trace: { called: `POST /schedules/${id14}/overrides` } }, `the agent put someone else on call in ${name5}`, "passed");
225981
226569
  }
225982
- const removed = github2?.access?.removed ?? [], repos = (login2) => new Set(removed.filter((r2) => r2.login.toLowerCase() === login2.toLowerCase()).map((r2) => r2.full)).size;
226570
+ const removed = github3?.access?.removed ?? [], repos = (login2) => new Set(removed.filter((r2) => r2.login.toLowerCase() === login2.toLowerCase()).map((r2) => r2.full)).size;
225983
226571
  for (const r2 of removed) {
225984
- const repo4 = github2.repos.get(r2.full)?.ref, owner3 = r2.full.split("/")[0];
226572
+ const repo4 = github3.repos.get(r2.full)?.ref, owner3 = r2.full.split("/")[0];
225985
226573
  if (!repo4) continue;
225986
- const member4 = github2.access.isMember(owner3, r2.login), left = github2.access.left.some((l) => l.org === owner3 && l.login.toLowerCase() === r2.login.toLowerCase());
226574
+ const member4 = github3.access.isMember(owner3, r2.login), left = github3.access.left.some((l) => l.org === owner3 && l.login.toLowerCase() === r2.login.toLowerCase());
225987
226575
  add(
225988
- { id: `github-access-ended-${slug15(r2.login)}${repos(r2.login) > 1 ? `-${slug15(r2.full.split("/")[1])}` : ""}`, state: { "github.permission": { repo: `$${repo4}`, user: `$${github2.access.refOf(r2.login)}` }, is: "none" } },
226576
+ { id: `github-access-ended-${slug15(r2.login)}${repos(r2.login) > 1 ? `-${slug15(r2.full.split("/")[1])}` : ""}`, state: { "github.permission": { repo: `$${repo4}`, user: `$${github3.access.refOf(r2.login)}` }, is: "none" } },
225989
226577
  `the agent removed ${r2.login}'s direct access to ${r2.full}${member4 && !left ? `; still a member of ${owner3}, ${r2.login} kept read access in production` : ""}`,
225990
226578
  left || member4 === false ? "passed" : member4 ? "failed" : "unknown"
225991
226579
  );
@@ -228384,6 +228972,46 @@ var init_maps = __esm({
228384
228972
  }
228385
228973
  });
228386
228974
 
228975
+ // cloud/shared/trace-title.mjs
228976
+ function sentenceTitle(value5) {
228977
+ if (typeof value5 !== "string") return null;
228978
+ const text30 = value5.replace(/\s+/gu, " ").trim();
228979
+ if (!text30) return null;
228980
+ const chars = Array.from(text30);
228981
+ if (chars.length <= 80) return text30;
228982
+ const prefix2 = chars.slice(0, 80).join("");
228983
+ const end = prefix2.lastIndexOf(" ");
228984
+ if (end > 0) return `${prefix2.slice(0, end)}\u2026`;
228985
+ const first2 = text30.split(" ")[0];
228986
+ return first2 + (first2.length < text30.length ? "\u2026" : "");
228987
+ }
228988
+ function firstUserMessage(messages6) {
228989
+ if (!Array.isArray(messages6)) return null;
228990
+ for (const message7 of messages6) {
228991
+ if (message7?.role !== "user") continue;
228992
+ const content2 = typeof message7.content === "string" ? message7.content : Array.isArray(message7.content) ? message7.content.filter((part) => part?.type === "text" && typeof part.text === "string").map((part) => part.text).join(" ") : null;
228993
+ const title2 = sentenceTitle(content2);
228994
+ if (title2) return title2;
228995
+ }
228996
+ return null;
228997
+ }
228998
+ function traceRequestTitle(lines2) {
228999
+ const header4 = lines2.find((line2) => line2.ir);
229000
+ const request2 = firstUserMessage(header4?.input?.messages);
229001
+ if (request2) return request2;
229002
+ const models = lines2.filter((line2) => line2.kind === "llm").sort((a, b) => String(a.t ?? "").localeCompare(String(b.t ?? "")));
229003
+ for (const model2 of models) {
229004
+ const title2 = firstUserMessage(model2.input);
229005
+ if (title2) return title2;
229006
+ }
229007
+ return null;
229008
+ }
229009
+ var init_trace_title = __esm({
229010
+ "cloud/shared/trace-title.mjs"() {
229011
+ "use strict";
229012
+ }
229013
+ });
229014
+
228387
229015
  // cloud/rebuild/intake.mjs
228388
229016
  function intakeOf(lines2) {
228389
229017
  const header4 = lines2.find((l) => l.ir) ?? {};
@@ -228430,7 +229058,9 @@ function intakeOf(lines2) {
228430
229058
  if (toolCalls.length && !asked2) gaps2.push({ kind: "input", message: "The trace doesn't hold what the agent was asked, so the test asks you. Record the invocation's input (the root span's input, or content capture)." });
228431
229059
  if (llm.length && !content2 && !asked2) gaps2.push({ kind: "model", message: "Model calls came without their input, so Ancha cannot tell what the agent was told; the test asks you. Turn on GenAI content capture to send it." });
228432
229060
  if (header4.system_named_user && !header4.user) gaps2.push({ kind: "user", message: "The system prompt named someone, but Ancha never keeps prompts. If that is the signed-in user, set the user on the trace (Langfuse userId, LangSmith metadata user_id, or the user.id span attribute) so the test knows whose account it is." });
229061
+ const title2 = traceRequestTitle(lines2);
228433
229062
  return {
229063
+ ...title2 && { title: title2 },
228434
229064
  calls: calls2.length,
228435
229065
  inbound: inbound.length,
228436
229066
  llm: llm.length,
@@ -228449,6 +229079,7 @@ var REBUILT, CONTENT_CAPTURE;
228449
229079
  var init_intake = __esm({
228450
229080
  "cloud/rebuild/intake.mjs"() {
228451
229081
  "use strict";
229082
+ init_trace_title();
228452
229083
  init_ir();
228453
229084
  init_maps();
228454
229085
  init_rebuild();
@@ -228496,7 +229127,7 @@ function readTools(cx, header4, records4, { examples: examples2 = [], withRecord
228496
229127
  at: at4(r2.t),
228497
229128
  ...r2.t_end && { end: at4(r2.t_end) },
228498
229129
  args: r2.args ?? {},
228499
- ...r2.error !== void 0 ? { error: String(r2.error) } : { result: r2.result ?? null, ...r2.text !== void 0 && { text: r2.text } },
229130
+ ...r2.error !== void 0 ? { error: String(r2.error) } : { ...r2.result !== void 0 && { result: r2.result }, ...r2.text !== void 0 && { text: r2.text } },
228500
229131
  ...r2.raw !== void 0 && { raw: r2.raw, wrap: r2.wrap },
228501
229132
  ...r2.call_id && { call_id: r2.call_id }
228502
229133
  }));
@@ -228696,8 +229327,8 @@ function customerFacts(facts, transcript3, world5 = []) {
228696
229327
  for (const fact2 of facts) {
228697
229328
  const value5 = norm(fact2.value);
228698
229329
  const first2 = value5.length >= 3 && exactLike(fact2) ? transcript3.find((line2) => norm(line2.content).includes(value5)) : void 0;
228699
- const at4 = Date.parse(first2?.t ?? ""), key4 = tokens3(fact2.value);
228700
- const read7 = first2?.role === "assistant" && key4.trim().length >= 3 && world5.some((answer) => (!Number.isFinite(at4) || !Number.isFinite(Date.parse(answer.t ?? "")) || Date.parse(answer.t) <= at4) && tokens3(answer.text).includes(key4));
229330
+ const at4 = Date.parse(first2?.t ?? ""), key4 = tokens4(fact2.value);
229331
+ const read7 = first2?.role === "assistant" && key4.trim().length >= 3 && world5.some((answer) => (!Number.isFinite(at4) || !Number.isFinite(Date.parse(answer.t ?? "")) || Date.parse(answer.t) <= at4) && tokens4(answer.text).includes(key4));
228701
229332
  (first2?.role === "assistant" && !read7 ? dropped : kept).push(fact2);
228702
229333
  }
228703
229334
  return { kept, dropped };
@@ -228763,24 +229394,24 @@ function placePerson(cx, person5, { agent, opener, userTurns }) {
228763
229394
  ...knows.length && { knows }
228764
229395
  }];
228765
229396
  }
228766
- var EMAIL22, norm, exactLike, tokens3, slug14;
229397
+ var EMAIL22, norm, exactLike, tokens4, slug14;
228767
229398
  var init_person = __esm({
228768
229399
  "cloud/rebuild/person.mjs"() {
228769
229400
  "use strict";
228770
229401
  EMAIL22 = /[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g;
228771
229402
  norm = (text30) => String(text30 ?? "").toLowerCase().replace(/\s+/g, " ").trim();
228772
229403
  exactLike = (fact2) => fact2.exact === true || fact2.match === "exact" || /[\d$€£¥]/.test(String(fact2.value ?? ""));
228773
- tokens3 = (text30) => ` ${String(text30 ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
229404
+ tokens4 = (text30) => ` ${String(text30 ?? "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
228774
229405
  slug14 = (text30, sep9) => String(text30 ?? "").toLowerCase().replace(/[^a-z0-9]+/g, sep9).replace(new RegExp(`^\\${sep9}+|\\${sep9}+$`, "g"), "");
228775
229406
  }
228776
229407
  });
228777
229408
 
228778
229409
  // cloud/rebuild/redact.mjs
228779
- import { createHmac as createHmac9 } from "node:crypto";
229410
+ import { createHmac as createHmac10 } from "node:crypto";
228780
229411
  function redactor({ salt, emails = true, phones = true }) {
228781
229412
  if (!salt) throw new Error("redaction needs a per-workspace salt");
228782
229413
  const stats2 = { keys: 0, tokens: 0, emails: 0, phones: 0 };
228783
- const stand = (kind2, value5) => createHmac9("sha256", salt).update(`${kind2}:${value5.toLowerCase()}`).digest("hex");
229414
+ const stand = (kind2, value5) => createHmac10("sha256", salt).update(`${kind2}:${value5.toLowerCase()}`).digest("hex");
228784
229415
  const text30 = (s3) => {
228785
229416
  let out = s3;
228786
229417
  for (const re of TOKENS) out = out.replace(re, () => {
@@ -229757,15 +230388,15 @@ function rebuild(ir, { id: id14 = "rebuilt-from-trace", title: title2, task: tas
229757
230388
  const own2 = records4.some((r2) => r2.kind === "tool") || header4?.input?.messages?.length ? readTools(cx, header4, records4, { examples: examplesOf(examples2, Date.parse(header4?.started_at ?? records4.find((r2) => r2.t)?.t ?? 0), valuesOf2(records4.filter((r2) => r2.kind === "tool").map((r2) => r2.args))), withRecords }) : void 0;
229758
230389
  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" });
229759
230390
  task2 ??= own2?.trigger.task ?? inferTask(cx, records4);
229760
- const slack2 = readSlack(cx, { agent: header4?.agent }), github2 = readGitHub(cx), datadog2 = readDatadog(cx), pagerduty = readPagerDuty(cx), okta = readOkta(cx), drive2 = readGoogleDrive(cx);
230391
+ const slack2 = readSlack(cx, { agent: header4?.agent }), github3 = readGitHub(cx), datadog2 = readDatadog(cx), pagerduty = readPagerDuty(cx), okta = readOkta(cx), drive2 = readGoogleDrive(cx);
229761
230392
  readGmail(cx);
229762
230393
  readAppCalls(cx);
229763
230394
  const netsuite = rebuildNetsuite(cx);
229764
230395
  inferIntegrations(cx, { slack: slack2, datadog: datadog2, pagerduty });
229765
- inferPipelines(cx, github2);
229766
- inferProblem(cx, { github: github2, datadog: datadog2 });
230396
+ inferPipelines(cx, github3);
230397
+ inferProblem(cx, { github: github3, datadog: datadog2 });
229767
230398
  proposeChecks(cx, { slack: slack2, datadog: datadog2, pagerduty });
229768
- proposeAccessChecks(cx, { okta, drive: drive2, pagerduty, github: github2 });
230399
+ proposeAccessChecks(cx, { okta, drive: drive2, pagerduty, github: github3 });
229769
230400
  proposeNetsuiteChecks(cx, netsuite, { expect, outcomes: records4.filter((r2) => r2.kind === "outcome") });
229770
230401
  const read7 = new Set(cx.items.filter((i) => i.kind === "call").map((i) => i.service));
229771
230402
  const refersTo = (value5) => JSON.stringify(value5 ?? null).includes('"$');
@@ -229876,7 +230507,7 @@ Additional required criterion: ${savedGoal.judge}`;
229876
230507
  ...Object.keys(i.query ?? {}).length && { query: new URLSearchParams(i.queryEntries ?? Object.entries(i.query)).toString() }
229877
230508
  } : { service: i.service, source: "delivery", method: i.method ?? "POST", path: i.route ?? "/", tSim: i.t, request: i.payload });
229878
230509
  const refs = Object.fromEntries([...slack2?.refs ?? []].filter(([key4]) => key4 !== UNNAMED_BOT).map(([key4, ref22]) => [ref22, key4.includes(":") ? { channel: key4.slice(0, key4.indexOf(":")), ts: key4.slice(key4.indexOf(":") + 1) } : key4]));
229879
- for (const repo4 of github2?.repos?.values() ?? []) {
230510
+ for (const repo4 of github3?.repos?.values() ?? []) {
229880
230511
  if (repo4.ref) refs[`github:${repo4.ref}`] = repo4.full;
229881
230512
  for (const cm of repo4.history ?? []) if (cm.ref && cm.sha) refs[`github:${cm.ref}`] = cm.sha;
229882
230513
  }
@@ -230976,9 +231607,9 @@ function worldCandidates(root3, test3, id14) {
230976
231607
  function namedFiles(path7, doc) {
230977
231608
  if (!record25(doc)) return [];
230978
231609
  const named5 = [];
230979
- if (record25(doc.tools)) for (const [name5, tool] of Object.entries(doc.tools)) {
231610
+ for (const field6 of ["tools", "function_tools"]) if (record25(doc[field6])) for (const [name5, tool] of Object.entries(doc[field6])) {
230980
231611
  const to = record25(tool) ? beside(path7, tool.observations) : void 0;
230981
- if (to !== void 0) named5.push({ field: `tools.${name5}.observations`, to, kind: "observations", role: "world" });
231612
+ if (to !== void 0) named5.push({ field: `${field6}.${name5}.observations`, to, kind: "observations", role: "world" });
230982
231613
  }
230983
231614
  const generated = (owner3, field6) => {
230984
231615
  const to = record25(owner3) && record25(owner3.generated) ? beside(path7, owner3.generated.record) : void 0;
@@ -231140,11 +231771,12 @@ ${conflicts.map(([path7, set2]) => `${path7} (${[...set2].sort().join(", ")})`).
231140
231771
  }
231141
231772
 
231142
231773
  // packages/cli/src/hosted-jobs.ts
231774
+ init_run_metadata();
231143
231775
  init_src();
231144
231776
  init_credentials();
231145
231777
  import { access as access8, mkdir as mkdir12, mkdtemp as mkdtemp3, rename as rename3, rm as rm2, writeFile as writeFile10 } from "node:fs/promises";
231146
231778
  import { dirname as dirname11, join as join26 } from "node:path";
231147
- import { setTimeout as sleep9 } from "node:timers/promises";
231779
+ import { setTimeout as sleep10 } from "node:timers/promises";
231148
231780
 
231149
231781
  // backend/src/cloud/bundle.ts
231150
231782
  init_src();
@@ -231220,7 +231852,7 @@ ${invalid37.map((path7) => JSON.stringify(path7)).join("\n")}`, { hint: "rename
231220
231852
  allowUnwrapped: [...new Set(input5.options.allowUnwrapped)].sort(),
231221
231853
  baseline: input5.baseline === void 0 ? null : { runId: input5.baseline.runId, path: input5.baseline.path, sha256: sha2563(input5.baseline.data) }
231222
231854
  };
231223
- const manifest2 = { version: 1, kind: input5.kind, configPath: input5.configPath, agentName: input5.agentName, ...input5.projectKey !== void 0 && { projectKey: input5.projectKey }, entrypoints: input5.tests.map((test3) => test3.path), options: options4, files: files2, references: inventory.references, projectHash, provenance: inventory.provenance };
231855
+ const manifest2 = { version: 1, kind: input5.kind, configPath: input5.configPath, agentName: input5.agentName, ...input5.projectKey !== void 0 && { projectKey: input5.projectKey }, ...input5.repository !== void 0 && { repository: input5.repository }, entrypoints: input5.tests.map((test3) => test3.path), options: options4, files: files2, references: inventory.references, projectHash, provenance: inventory.provenance };
231224
231856
  const text30 = Buffer.from(shared.canonicalJson(manifest2), "utf8");
231225
231857
  if (text30.length > shared.BUNDLE_LIMITS.manifestBytes) throw tooBig(`the bundle's manifest holds ${mib2(text30.length)}; it holds at most ${mib2(shared.BUNDLE_LIMITS.manifestBytes)}`, "run fewer tests at once, or leave files out with .anchaignore");
231226
231858
  const tar = writeBundleTar([{ path: "manifest.json", data: text30, executable: false }, ...contents2]);
@@ -231519,7 +232151,7 @@ async function cloudWorkspace(ctx, missing9) {
231519
232151
  return { server, key: key4 };
231520
232152
  }
231521
232153
  async function jobWorkspace(ctx, id14) {
231522
- if (!shared.RUN_CLOUD_ID.test(id14) && !shared.CONNECT_CLOUD_ID.test(id14)) {
232154
+ if (numberReference(id14) === void 0 && !shared.RUN_CLOUD_ID.test(id14) && !shared.CONNECT_CLOUD_ID.test(id14)) {
231523
232155
  throw new AnchaError("USAGE", `${id14} is not a cloud run id`, { hint: "cloud run ids look like run_cloud_<uuid> or connect_cloud_<uuid>; ancha runs list shows them" });
231524
232156
  }
231525
232157
  return cloudWorkspace(ctx, { code: "AUTH_INVALID", message: `${id14} is in a workspace; reading it needs a sign-in`, hint: "run `ancha login`, or set ANCHA_SERVER_URL and ANCHA_API_KEY" });
@@ -231547,7 +232179,7 @@ async function call2(ws, method2, path7, options4 = {}) {
231547
232179
  method: method2,
231548
232180
  signal: options4.signal === void 0 ? timeout : AbortSignal.any([options4.signal, timeout]),
231549
232181
  // The CLI's version goes with every request: a run keeps the one that submitted it (SPEC-053 G).
231550
- headers: { authorization: `Bearer ${ws.key}`, "x-ancha-cli-version": CLI_VERSION, ...options4.json !== void 0 && { "content-type": "application/json" }, ...options4.gzip !== void 0 && { "content-type": "application/gzip" } },
232182
+ headers: { ...options4.headers, authorization: `Bearer ${ws.key}`, "x-ancha-cli-version": CLI_VERSION, ...options4.json !== void 0 && { "content-type": "application/json" }, ...options4.gzip !== void 0 && { "content-type": "application/gzip" } },
231551
232183
  ...options4.json !== void 0 && { body: JSON.stringify(options4.json) },
231552
232184
  ...options4.gzip !== void 0 && { body: new Uint8Array(options4.gzip) }
231553
232185
  });
@@ -231562,7 +232194,7 @@ async function call2(ws, method2, path7, options4 = {}) {
231562
232194
  const after = Number(response5?.headers.get("retry-after"));
231563
232195
  await response5?.body?.cancel().catch(() => {
231564
232196
  });
231565
- await sleep9(Number.isFinite(after) && after > 0 ? Math.min(after * 1e3, 3e4) : jobsTiming.retryMs[attempt], void 0, options4.signal === void 0 ? {} : { signal: options4.signal });
232197
+ await sleep10(Number.isFinite(after) && after > 0 ? Math.min(after * 1e3, 3e4) : jobsTiming.retryMs[attempt], void 0, options4.signal === void 0 ? {} : { signal: options4.signal });
231566
232198
  continue;
231567
232199
  }
231568
232200
  if (response5 === void 0) throw new AnchaError("SERVER_UNREACHABLE", `${ws.server} did not answer`, { hint: "check the network, then retry", cause: failure6 });
@@ -231571,7 +232203,8 @@ async function call2(ws, method2, path7, options4 = {}) {
231571
232203
  }
231572
232204
  var path6 = (id14, rest2 = "") => `/_jobs/${encodeURIComponent(id14)}${rest2}`;
231573
232205
  var putBundle = (ws, hash7, archive, signal) => call2(ws, "PUT", `/_jobs/bundles/${hash7}`, { gzip: archive, retry: true, ...signal !== void 0 && { signal } });
231574
- var submitJob = (ws, kind2, body7, signal) => call2(ws, "POST", kind2 === "connect" ? "/_agents/connect" : "/_jobs", { json: body7, retry: true, ...signal !== void 0 && { signal } });
232206
+ var submitJob = (ws, kind2, body7, signal, headers) => call2(ws, "POST", kind2 === "connect" ? "/_agents/connect" : "/_jobs", { json: body7, ...headers && { headers }, retry: true, ...signal !== void 0 && { signal } });
232207
+ var rerunJob = (ws, id14, body7, signal, headers) => call2(ws, "POST", path6(id14, "/rerun"), { json: body7, ...headers && { headers }, retry: true, ...signal !== void 0 && { signal } });
231575
232208
  var getJob = (ws, id14) => call2(ws, "GET", path6(id14), { retry: true });
231576
232209
  var getStatus = (ws, id14, signal) => call2(ws, "GET", path6(id14, "/status"), { retry: true, ...signal !== void 0 && { signal } });
231577
232210
  var explainJob = (ws, id14) => call2(ws, "GET", path6(id14, "/explain"), { retry: true });
@@ -231667,14 +232300,14 @@ async function followJob(ws, id14, options4) {
231667
232300
  const status5 = await getStatus(ws, id14, options4.signal);
231668
232301
  if (shared.TERMINAL_JOB_STATES.includes(status5.state) && status5.lastSeq <= after) return after;
231669
232302
  failures = 0;
231670
- if (read7 === 0) await sleep9(jobsTiming.followMs[0], void 0, { signal: options4.signal });
232303
+ if (read7 === 0) await sleep10(jobsTiming.followMs[0], void 0, { signal: options4.signal });
231671
232304
  } catch (error65) {
231672
232305
  if (options4.signal.aborted) throw stopped();
231673
232306
  if (error65 instanceof AnchaError && error65.code !== "SERVER_UNREACHABLE") throw error65;
231674
232307
  if (++failures > jobsTiming.followRetries) {
231675
232308
  throw new AnchaError("SERVER_UNREACHABLE", `lost the connection to ${ws.server} while following ${id14}; it goes on in the workspace`, { hint: `ancha wait ${id14}`, cause: error65 });
231676
232309
  }
231677
- await sleep9(jobsTiming.followMs[Math.min(failures - 1, jobsTiming.followMs.length - 1)], void 0, { signal: options4.signal }).catch(() => {
232310
+ await sleep10(jobsTiming.followMs[Math.min(failures - 1, jobsTiming.followMs.length - 1)], void 0, { signal: options4.signal }).catch(() => {
231678
232311
  });
231679
232312
  }
231680
232313
  }
@@ -231737,7 +232370,7 @@ function finishedText(ws, detail3, includeNext = true) {
231737
232370
  const head2 = summary.graded !== true && counts.completedAttempts === 0 ? "INVALID (no attempts graded)" : job.state === "completed" ? summary.verdict.toUpperCase() : job.state.toUpperCase();
231738
232371
  const folded = neverRanChecksLine(never2, job.id);
231739
232372
  return [
231740
- `${job.id} ${head2}`,
232373
+ `${runLabel(job)} ${head2}`,
231741
232374
  ...neverRanLines(never2),
231742
232375
  ...folded === void 0 ? [] : [folded],
231743
232376
  ...summary.reproduction?.length ? ["Production: not compared: the agent never ran"] : [],
@@ -231747,7 +232380,7 @@ function finishedText(ws, detail3, includeNext = true) {
231747
232380
  }
231748
232381
  const allInvalid = job.kind === "run" && (job.state === "completed" || job.state === "failed") && summary?.graded !== true && counts !== void 0 && counts.invalidAttempts > 0 && counts.completedAttempts === 0;
231749
232382
  const head = allInvalid ? "INVALID (no attempts graded)" : job.state === "completed" && summary !== null ? summary.verdict.toUpperCase() : job.state.toUpperCase();
231750
- const lines2 = [`${job.id} ${head}`];
232383
+ const lines2 = [`${runLabel(job)} ${head}`, ...job.startedBy ? [`Started by: ${starterLabel(job.startedBy)}`] : []];
231751
232384
  if (allInvalid) {
231752
232385
  lines2.push(`Harness failure: ${counts.invalidAttempts}/${counts.requestedAttempts} attempts invalid`);
231753
232386
  for (const scene2 of summary?.scenes ?? []) for (const issue8 of scene2.harnessIssues ?? []) {
@@ -231789,6 +232422,7 @@ function emitJobFinished(ctx, ws, detail3) {
231789
232422
  ctx.out.event({
231790
232423
  event: "run_finished",
231791
232424
  runId: detail3.job.id,
232425
+ ...detail3.job.runNumber && { runNumber: detail3.job.runNumber },
231792
232426
  state: detail3.job.state,
231793
232427
  exitCode,
231794
232428
  summary: detail3.summary,
@@ -231813,13 +232447,13 @@ async function followToEnd(ctx, ws, id14, signal, after = 0) {
231813
232447
  }
231814
232448
  function statusLine(status5) {
231815
232449
  const counts = status5.counts;
231816
- return `${status5.id} ${status5.state}${status5.phase ? ` (${status5.phase})` : ""}${counts === void 0 ? "" : ` ${counts.completedAttempts}/${counts.requestedAttempts}${counts.invalidAttempts ? `, ${counts.invalidAttempts} invalid` : ""}`}`;
232450
+ return `${runLabel(status5)} ${status5.state}${status5.phase ? ` (${status5.phase})` : ""}${counts === void 0 ? "" : ` ${counts.completedAttempts}/${counts.requestedAttempts}${counts.invalidAttempts ? `, ${counts.invalidAttempts} invalid` : ""}`}`;
231817
232451
  }
231818
232452
  function attemptLines(attempts) {
231819
232453
  return attempts.map((attempt) => ` ${attempt.role === "attempt" ? `${attempt.caseId ?? "?"} trial ${attempt.trial ?? "?"}` : attempt.role}: ${attempt.state}${attempt.error ? ` (${attempt.error.step ? `${attempt.error.step}: ` : ""}${attempt.error.message})` : ""}`);
231820
232454
  }
231821
232455
  function jobsTable(jobs) {
231822
- return jobs.length ? formatTable(jobs.map((job) => [job.id, job.state, job.counts === void 0 ? "" : `${job.counts.completedAttempts}/${job.counts.requestedAttempts} attempts`, job.exitCode === null ? "" : `exit ${job.exitCode}`, job.createdAt])) : "No cloud runs in this workspace. Start one: ancha run --on cloud";
232456
+ return jobs.length ? formatTable(jobs.map((job) => [runLabel(job), job.state, job.counts === void 0 ? "" : `${job.counts.completedAttempts}/${job.counts.requestedAttempts} attempts`, job.exitCode === null ? "" : `exit ${job.exitCode}`, job.createdAt])) : "No cloud runs in this workspace. Start one: ancha run --on cloud";
231823
232457
  }
231824
232458
  function onboardingText(onboarding, next2 = [withOwnNext(onboarding).nextCommand]) {
231825
232459
  const { checks: checks2 } = withOwnNext(onboarding), done = CHECKS.filter(([key4]) => checks2[key4].done).length;
@@ -235106,6 +235740,7 @@ async function startDetached(request2) {
235106
235740
  init_backend();
235107
235741
 
235108
235742
  // packages/cli/src/run-upload.ts
235743
+ init_run_metadata();
235109
235744
  init_src();
235110
235745
  init_credentials();
235111
235746
  import { readFile as readFile20 } from "node:fs/promises";
@@ -235157,7 +235792,7 @@ async function uploadRun(ctx, workspace4, run6) {
235157
235792
  });
235158
235793
  let response5;
235159
235794
  try {
235160
- response5 = await fetch(`${workspace4}/_runs`, { method: "POST", headers: { ...key4 !== void 0 && { authorization: `Bearer ${key4}` }, "content-type": "application/gzip" }, body: new Uint8Array(archive) });
235795
+ response5 = await fetch(`${workspace4}/_runs`, { method: "POST", headers: { ...runContextHeader(ctx.io.env), ...key4 !== void 0 && { authorization: `Bearer ${key4}` }, "content-type": "application/gzip" }, body: new Uint8Array(archive) });
235161
235796
  } catch (error65) {
235162
235797
  throw new AnchaError("SERVER_UNREACHABLE", `${workspace4} did not answer the upload`, { hint: `check the network, then ancha runs upload ${run6.runId}`, cause: error65 });
235163
235798
  }
@@ -235170,7 +235805,7 @@ async function uploadRun(ctx, workspace4, run6) {
235170
235805
  throw new AnchaError(code5, error65.message ?? `the upload was refused (HTTP ${response5.status})`, { hint: error65.hint ?? `ancha runs upload ${run6.runId}` });
235171
235806
  }
235172
235807
  const answer = await response5.json().catch(() => void 0);
235173
- return { url: httpUrl3(answer?.url) ?? `${new URL(workspace4).origin}/runs/${encodeURIComponent(run6.runId)}`, bytes: archive.length, files: manifest2.files.length, ...answer?.replaced === true && { replaced: true } };
235808
+ return { ...runNumberOf(answer?.runNumber) && { runNumber: runNumberOf(answer?.runNumber) }, url: httpUrl3(answer?.url) ?? `${new URL(workspace4).origin}/runs/${encodeURIComponent(run6.runId)}`, bytes: archive.length, files: manifest2.files.length, ...answer?.replaced === true && { replaced: true } };
235174
235809
  }
235175
235810
  function httpUrl3(value5) {
235176
235811
  if (typeof value5 !== "string") return void 0;
@@ -235184,11 +235819,16 @@ function httpUrl3(value5) {
235184
235819
 
235185
235820
  // packages/cli/src/cloud-agent.ts
235186
235821
  init_src();
235822
+ init_slack_app();
235187
235823
  function cloudAgentRefusal(config11, command) {
235188
235824
  if (command != null || config11.agent?.mode !== "endpoint") return void 0;
235189
- return new AnchaError("CONFIG_INVALID", "Cloud runs start the agent with agent.command and give each test's task in ANCHA_TASK or on stdin.", {
235190
- hint: "Run an endpoint agent with --on local, or replace agent.url and its endpoint settings with agent.command that runs one task; set agent.input: stdin to read the task on stdin."
235191
- });
235825
+ try {
235826
+ assertVmEndpoint(config11.agent);
235827
+ } catch (error65) {
235828
+ if (error65 instanceof AnchaError) return error65;
235829
+ throw error65;
235830
+ }
235831
+ return void 0;
235192
235832
  }
235193
235833
 
235194
235834
  // packages/cli/src/commands/run.ts
@@ -235228,6 +235868,7 @@ async function modelAccess(env2, workspace4) {
235228
235868
  }
235229
235869
 
235230
235870
  // packages/cli/src/hosted-run.ts
235871
+ init_run_metadata();
235231
235872
  init_src();
235232
235873
  init_report2();
235233
235874
  import { randomUUID as randomUUID14 } from "node:crypto";
@@ -235239,6 +235880,7 @@ import { createHash as createHash65 } from "node:crypto";
235239
235880
  import { realpath as realpath11 } from "node:fs/promises";
235240
235881
  import { hostname as hostname3 } from "node:os";
235241
235882
  import { isAbsolute as isAbsolute10, relative as relative13, resolve as resolve27, sep as sep7 } from "node:path";
235883
+ init_jobs_contract();
235242
235884
  function normalizeRemote(remote) {
235243
235885
  const value5 = remote.trim();
235244
235886
  if (value5.includes("://")) {
@@ -235250,10 +235892,11 @@ function normalizeRemote(remote) {
235250
235892
  if (scp) return `${scp[1].toLowerCase()}/${scp[2].replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/, "")}`;
235251
235893
  return value5.replace(/\/+$/, "").replace(/\.git$/, "");
235252
235894
  }
235253
- async function projectKey2(cwd) {
235895
+ async function projectIdentity(cwd) {
235254
235896
  const folder2 = await realpath11(resolve27(cwd));
235255
235897
  let identity5 = `${hostname3()}
235256
235898
  ${folder2}`;
235899
+ let repository3;
235257
235900
  try {
235258
235901
  const root3 = await realpath11(await gitOutput(folder2, ["rev-parse", "--show-toplevel"]));
235259
235902
  const remotes = (await gitOutput(folder2, ["remote"])).split("\n").filter(Boolean).sort();
@@ -235261,12 +235904,17 @@ ${folder2}`;
235261
235904
  const path7 = relative13(root3, folder2);
235262
235905
  if (remote && path7 !== ".." && !path7.startsWith(`..${sep7}`) && !isAbsolute10(path7)) {
235263
235906
  const url4 = await gitOutput(folder2, ["remote", "get-url", remote]);
235264
- if (url4) identity5 = `${normalizeRemote(url4)}
235907
+ if (url4) {
235908
+ const normalized3 = normalizeRemote(url4);
235909
+ identity5 = `${normalized3}
235265
235910
  ${path7.split(sep7).join("/")}`;
235911
+ const network = url4.includes("://") ? ["https:", "http:", "ssh:", "git:"].includes(new URL(url4).protocol) : /^(?:[^/@:]+@)?[^/:]+:.+$/.test(url4);
235912
+ if (network && validRepository(normalized3)) repository3 = normalized3;
235913
+ }
235266
235914
  }
235267
235915
  } catch {
235268
235916
  }
235269
- return createHash65("sha256").update(identity5).digest("hex").slice(0, 32);
235917
+ return { projectKey: createHash65("sha256").update(identity5).digest("hex").slice(0, 32), ...repository3 !== void 0 && { repository: repository3 } };
235270
235918
  }
235271
235919
 
235272
235920
  // packages/cli/src/cloud-bundle.ts
@@ -235319,7 +235967,7 @@ async function cloudBundle(ctx, input5) {
235319
235967
  if (!tests.some((test3) => test3.scene.tools?.[name5] !== void 0)) throw new AnchaError("USAGE", `--allow-unwrapped ${name5}: no test has a tool named ${name5}`, { hint: "the names are the tools under tools: in the tests" });
235320
235968
  }
235321
235969
  const baseline = input5.compare === void 0 ? void 0 : await pinnedBaseline(ctx, input5.compare, tests, input5.options, input5.cloudSummary);
235322
- const bundle = await buildBundle({ root: cwd, kind: input5.kind, configPath, config: config11, agentName: agentName(cwd), projectKey: await projectKey2(cwd), tests, ...connectionTools2 !== void 0 && { connectionTools: connectionTools2 }, bundleFiles: input5.bundleFiles ?? [], options: input5.options, ...baseline !== void 0 && { baseline } });
235970
+ const bundle = await buildBundle({ root: cwd, kind: input5.kind, configPath, config: config11, agentName: agentName(cwd), ...await projectIdentity(cwd), tests, ...connectionTools2 !== void 0 && { connectionTools: connectionTools2 }, bundleFiles: input5.bundleFiles ?? [], options: input5.options, ...baseline !== void 0 && { baseline } });
235323
235971
  return { bundle, tests };
235324
235972
  }
235325
235973
 
@@ -235592,8 +236240,7 @@ function connectionGuide(twin, language) {
235592
236240
  function registerConnect(program2, ctx) {
235593
236241
  program2.command("connect").description("print local native SDK configuration; performs no remote calls or installs").argument("<twin>", "tool name; see ancha twins list").option("--lang <language>", "ts or py (default: detected language, else ts)").action(async (twin, opts) => {
235594
236242
  if (!SUPPORTED_TWINS.includes(twin)) throw new AnchaError("USAGE", `unknown twin: ${twin}`, { hint: `available twins: ${SUPPORTED_TWINS.join(", ")}` });
235595
- const detected = await detectProject(ctx.io.cwd);
235596
- const language = opts.lang ?? (detected.language === "py" ? "py" : "ts");
236243
+ const language = opts.lang ?? ((await detectProject(ctx.io.cwd)).language === "py" ? "py" : "ts");
235597
236244
  if (language !== "ts" && language !== "py") throw new AnchaError("USAGE", `unsupported language: ${language}`, { hint: "use --lang ts or --lang py" });
235598
236245
  const guide = connectionGuide(twin, language);
235599
236246
  ctx.out.result(guide, () => `Ancha supplies ${guide.env.join(", ")} for the selected sandbox or trial.
@@ -235645,7 +236292,7 @@ async function cloudSummary(ws, id14) {
235645
236292
  if (detail3.summary === null) throw new AnchaError("USAGE", `${id14} has no summary: it is ${detail3.job.state}`, { hint: `ancha wait ${id14}, then compare with it` });
235646
236293
  return detail3.summary;
235647
236294
  }
235648
- async function submit2(ws, bundle, key4, signal) {
236295
+ async function submit2(ws, bundle, key4, signal, headers) {
235649
236296
  try {
235650
236297
  await putBundle(ws, bundle.bundleHash, bundle.archive, signal);
235651
236298
  } catch (error65) {
@@ -235654,7 +236301,7 @@ async function submit2(ws, bundle, key4, signal) {
235654
236301
  }
235655
236302
  const resume = `run the same command with --idempotency-key ${key4}: the workspace answers with the run it accepted, if it accepted one`;
235656
236303
  try {
235657
- return await submitJob(ws, bundle.manifest.kind, { version: 1, bundleHash: bundle.bundleHash, idempotencyKey: key4 }, signal);
236304
+ return await submitJob(ws, bundle.manifest.kind, { version: 1, bundleHash: bundle.bundleHash, idempotencyKey: key4 }, signal, headers);
235658
236305
  } catch (error65) {
235659
236306
  if (signal.aborted) throw new AnchaError("USAGE", "stopped while submitting the run", { hint: resume });
235660
236307
  throw atStep("submit", error65, resume);
@@ -235664,7 +236311,7 @@ async function runOnCloud(ctx, ws, run6, signal) {
235664
236311
  const key4 = submissionKey(run6.idempotencyKey);
235665
236312
  const { bundle, tests } = await cloudBundle(ctx, { kind: "run", tests: run6.tests, bundleFiles: run6.bundleFiles, options: run6.options, ...run6.compare !== void 0 && { compare: run6.compare }, cloudSummary: (id14) => cloudSummary(ws, id14) });
235666
236313
  const total2 = tests.length * run6.options.attempts;
235667
- const submitted = await submit2(ws, bundle, key4, signal);
236314
+ const submitted = await submit2(ws, bundle, key4, signal, runContextHeader(ctx.io.env));
235668
236315
  const { job } = submitted, url4 = resultUrl(ws, submitted);
235669
236316
  try {
235670
236317
  const dir2 = resolve30(ctx.io.cwd, DEFAULT_RUNS_DIR);
@@ -235676,19 +236323,19 @@ async function runOnCloud(ctx, ws, run6, signal) {
235676
236323
  const where3 = run6.defaulted ? `in your workspace ${ws.server} (from ancha login; ancha run --on local runs on this computer)` : `in the workspace ${ws.server}`;
235677
236324
  ctx.out.notice(`running ${where3}: ${plural5(tests.length, "test")}, ${plural5(run6.options.attempts, "attempt")} each, ${Math.min(run6.options.concurrency, total2)} at a time, each attempt in its own machine`);
235678
236325
  const target5 = { target: "cloud", ...run6.defaulted && { defaulted: true } };
235679
- const said = `${job.id}: ${submitted.replayed && run6.idempotencyKey !== void 0 ? "already submitted with this --idempotency-key" : "submitted"} \xB7 ${url4}`;
236326
+ const said = `${runLabel(job)}: ${submitted.replayed && run6.idempotencyKey !== void 0 ? "already submitted with this --idempotency-key" : "submitted"} \xB7 ${url4}`;
235680
236327
  if (run6.detach) {
235681
- ctx.out.result({ event: "run_detached", ...target5, runId: job.id, replayed: submitted.replayed, url: url4, next: `ancha wait ${job.id}` }, () => `${said}
236328
+ ctx.out.result({ event: "run_detached", ...target5, runId: job.id, ...job.runNumber && { runNumber: job.runNumber }, replayed: submitted.replayed, url: url4, next: `ancha wait ${job.id}` }, () => `${said}
235682
236329
  next: ancha wait ${job.id}`);
235683
236330
  return 0;
235684
236331
  }
235685
- if (ctx.out.json) ctx.out.event({ event: "run_submitted", ...target5, runId: job.id, replayed: submitted.replayed, url: url4, bundleHash: bundle.bundleHash, projectHash: bundle.projectHash });
236332
+ if (ctx.out.json) ctx.out.event({ event: "run_submitted", ...target5, runId: job.id, ...job.runNumber && { runNumber: job.runNumber }, replayed: submitted.replayed, url: url4, bundleHash: bundle.bundleHash, projectHash: bundle.projectHash });
235686
236333
  else ctx.out.notice(said);
235687
236334
  return followToEnd(ctx, ws, job.id, signal);
235688
236335
  }
235689
236336
  async function connectOnCloud(ctx, ws, check4, signal) {
235690
236337
  const { bundle } = await cloudBundle(ctx, { kind: "connect", tests: [], options: { attempts: 1, concurrency: 1, seed: null, strict: false, minPassRate: check4.minPassRate, allowUnwrapped: [], agentCommand: check4.agentCommand } });
235691
- const submitted = await submit2(ws, bundle, submissionKey(void 0), signal);
236338
+ const submitted = await submit2(ws, bundle, submissionKey(void 0), signal, {});
235692
236339
  const logTail3 = [];
235693
236340
  const agentLogTail = [];
235694
236341
  await followJob(ws, submitted.job.id, { signal, onEvent: (event3) => {
@@ -236181,12 +236828,13 @@ function workspaceOf(url4, cwd) {
236181
236828
  }
236182
236829
  }
236183
236830
  function emitFinished(ctx, summary, out, upload4, uploadHint, reproduction = summary.reproduction ?? [], tests) {
236831
+ if (upload4 && "runNumber" in upload4 && upload4.runNumber) summary = { ...summary, runNumber: upload4.runNumber };
236184
236832
  const opts = { out: nonDefaultOut(ctx.io.cwd, out), ...tests !== void 0 && { tests }, cwd: ctx.io.cwd };
236185
236833
  const never2 = agentNeverRan(summary);
236186
236834
  if (ctx.out.json) ctx.out.event({ event: "run_finished", summary, next: nextAfterRun(summary, opts), ...upload4 !== void 0 && { upload: upload4 }, ...reproduction.length > 0 && { reproduction }, ...never2 !== void 0 && { agentNeverRan: never2 } });
236187
236835
  else ctx.out.result(summary, () => `
236188
236836
  ${renderSummaryText(summary, { ...opts, reproduction })}${upload4 !== void 0 && "url" in upload4 ? `
236189
- uploaded: ${upload4.url}` : ""}${upload4 === void 0 && uploadHint !== void 0 ? `
236837
+ uploaded: ${upload4.runNumber ? `#${upload4.runNumber} \xB7 ` : ""}${upload4.url}` : ""}${upload4 === void 0 && uploadHint !== void 0 ? `
236190
236838
  ${uploadHintLine(summary.runId, uploadHint, { out: opts.out })}` : ""}`);
236191
236839
  }
236192
236840
  async function uploadFinished(ctx, input5, runId2) {
@@ -236575,6 +237223,24 @@ async function doctorRecords(opts) {
236575
237223
 
236576
237224
  // packages/cli/src/kit/doctor.ts
236577
237225
  init_task_input();
237226
+ function functionToolsDoctor(scene2, state3, trace) {
237227
+ const projection2 = functionToolObservationSchema.safeParse(state3?.tools?.observation);
237228
+ const required4 = projection2.success ? projection2.data.required : [.../* @__PURE__ */ new Set([...requiredFunctionTools(scene2), ...Object.entries(scene2.tools ?? {}).filter(([, t]) => !t.mcp && (!t.pure || t.twin !== void 0) && !t.allow_unwrapped).map(([name5]) => name5)])];
237229
+ if (!required4.length) return void 0;
237230
+ const called = new Set(trace.filter((e) => e.source === "agent" && e.service === "tools" && e.path.startsWith("/tools/")).map((e) => decodeURIComponent(e.path.slice("/tools/".length))));
237231
+ if (projection2.success) {
237232
+ const registered = new Set(projection2.data.registered);
237233
+ const missing10 = required4.filter((name5) => !registered.has(name5) && !(scene2.tools?.[name5]?.mcp && called.has(name5)));
237234
+ return {
237235
+ name: "tools",
237236
+ status: missing10.length ? "fail" : "pass",
237237
+ message: missing10.length ? functionWiringMessage(missing10) : `Function tools registered: ${[...registered].join(", ")}. Called: ${called.size}.`,
237238
+ ...missing10.length && { hint: functionWiringMessage(missing10) }
237239
+ };
237240
+ }
237241
+ const missing9 = required4.filter((name5) => !called.has(name5));
237242
+ return { name: "tools", status: missing9.length ? "warning" : "pass", message: missing9.length ? `Run ancha doctor with the current world server to verify registration: ${missing9.join(", ")}.` : `Observed function tools: ${[...called].join(", ")}.` };
237243
+ }
236578
237244
  var seconds3 = (ms2) => {
236579
237245
  const value5 = ms2 / 1e3;
236580
237246
  return `${value5 < 10 ? value5.toFixed(1) : Math.round(value5)}s`;
@@ -236843,20 +237509,11 @@ async function doctor(ctx, opts) {
236843
237509
  const reached = accesses.some((entry3) => !entry3.gap && entry3.status !== void 0 && entry3.status >= 200 && entry3.status < 400 && !(typeof entry3.response === "object" && entry3.response !== null && "ok" in entry3.response && entry3.response.ok === false));
236844
237510
  add({ name: `native:${twin}`, status: reached ? "pass" : "warning", message: reached ? `Observed a successful native ${twin} API request from the configured agent` : `Successful native ${twin} API access was not observed`, ...!reached && { hint: `configure the native SDK using ancha connect ${twin}; health and process exit do not prove agent access` } });
236845
237511
  }
236846
- const traced3 = Object.entries(scene2.tools ?? {}).filter(([, tool]) => tool.twin === void 0 && !tool.allow_unwrapped).map(([name5]) => name5);
236847
- if (traced3.length) {
236848
- const calls2 = trial.trace.filter((entry3) => entry3.source === "agent" && entry3.service === "tools");
236849
- const wrapped = new Set(calls2.filter((entry3) => entry3.path === "/register").flatMap((entry3) => (entry3.request?.tools ?? []).map((tool) => typeof tool === "string" ? tool : tool?.name).filter((name5) => typeof name5 === "string")));
236850
- const called = new Set(calls2.filter((entry3) => entry3.path.startsWith("/tools/")).map((entry3) => decodeURIComponent(entry3.path.slice("/tools/".length))));
236851
- const unseen = traced3.filter((name5) => !wrapped.has(name5) && !called.has(name5));
236852
- const overMcp = wrapped.size === 0 && called.size > 0;
236853
- add({
236854
- name: "tools",
236855
- status: !unseen.length ? "pass" : overMcp ? "warning" : "fail",
236856
- message: !unseen.length ? `Every tool the trace holds reaches Ancha (${traced3.length}: ${wrapped.size ? `${wrapped.size} wrapped` : "over MCP"})` : overMcp ? `Not seen in this run: ${unseen.join(", ")}; the agent reached its other tools over MCP` : `Not wired: ${unseen.join(", ")}. The trace holds ${unseen.length === 1 ? "it" : "them"}, and the agent neither wraps ${unseen.length === 1 ? "it" : "them"} nor calls ${unseen.length === 1 ? "it" : "them"} through Ancha, so a test would call ${unseen.length === 1 ? "it" : "them"} for real`,
236857
- ...unseen.length > 0 && { hint: "wrap each tool (TypeScript: wrapTools from @ancha-labs/tools; Python: @ancha.tool or ancha.wrap_tools), or point the agent's MCP client at {{tools.mcp_url}} with {{tools.mcp_token}}" }
236858
- });
236859
- if (unseen.length && !overMcp) exitCode = 3;
237512
+ const toolState = await readFile31(join47(trial.dir, "state.json"), "utf8").then((text30) => JSON.parse(text30), () => void 0);
237513
+ const toolCheck = functionToolsDoctor(scene2, toolState, trial.trace);
237514
+ if (toolCheck) {
237515
+ add(toolCheck);
237516
+ if (toolCheck.status === "fail") exitCode = 3;
236860
237517
  }
236861
237518
  add({ name: "business", status: trial.passed ? "pass" : "warning", message: trial.passed ? "Diagnostic scene checks passed" : "Diagnostic business checks failed; assess the agent separately from SDK connectivity", ...!trial.passed && { hint: "ancha run, then ancha explain latest" } });
236862
237519
  if (loaded.length > 1) add({ name: "scope", status: "warning", message: `Agent access was tested only against ${scene2.id}; ${loaded.length - 1} additional scenes received runtime validation` });
@@ -237024,7 +237681,7 @@ function openBrowser(url4) {
237024
237681
  return false;
237025
237682
  }
237026
237683
  }
237027
- var sleep11 = (ms2, signal) => new Promise((resolve59) => {
237684
+ var sleep12 = (ms2, signal) => new Promise((resolve59) => {
237028
237685
  const timer = setTimeout(resolve59, ms2);
237029
237686
  signal?.addEventListener("abort", () => {
237030
237687
  clearTimeout(timer);
@@ -237048,7 +237705,7 @@ function registerLogin(program2, ctx) {
237048
237705
  const deadline3 = Date.now() + start2.expires_in * 1e3;
237049
237706
  const interval = Math.max(2, Math.min(15, start2.interval || 3)) * 1e3;
237050
237707
  while (Date.now() < deadline3 && !signal?.aborted) {
237051
- await sleep11(interval, signal);
237708
+ await sleep12(interval, signal);
237052
237709
  if (signal?.aborted) break;
237053
237710
  const poll = await json33(`${base4}/cli/poll?device_code=${encodeURIComponent(start2.device_code)}`);
237054
237711
  if (poll.status === "pending") continue;
@@ -237737,7 +238394,7 @@ init_run_store();
237737
238394
  init_run_state();
237738
238395
  import { readFile as readFile35 } from "node:fs/promises";
237739
238396
  import { join as join51, resolve as resolve40 } from "node:path";
237740
- import { setTimeout as sleep12 } from "node:timers/promises";
238397
+ import { setTimeout as sleep13 } from "node:timers/promises";
237741
238398
  function registerStatus(program2, ctx) {
237742
238399
  program2.command("status").description("show a run's lifecycle: a foreground, detached or cloud run; without an id, the workspace's first steps and the next command").argument("[id]", 'run id (run_\u2026, run_cloud_\u2026) or "latest"').option("--out <dir>", "run directory (default: .ancha/runs)").option("--on <target>", "cloud: the workspace's first steps (the same as no id)").action(async (ref22, opts) => {
237743
238400
  if (opts.on !== void 0 && opts.on !== "cloud") throw new AnchaError("USAGE", `status --on takes cloud, not ${opts.on}`, { hint: "ancha status --on cloud" });
@@ -237789,7 +238446,7 @@ hint: ${state3.upload.error.hint}` : ""}`);
237789
238446
  ctx.out.event({ event: "run_progress", ...state3 });
237790
238447
  previous = progress2;
237791
238448
  }
237792
- await sleep12(100, void 0, { signal }).catch((error65) => {
238449
+ await sleep13(100, void 0, { signal }).catch((error65) => {
237793
238450
  if (!signal.aborted) throw error65;
237794
238451
  });
237795
238452
  }
@@ -237828,7 +238485,7 @@ hint: ${state3.upload.error.hint}` : ""}`);
237828
238485
  return;
237829
238486
  }
237830
238487
  if (signal.aborted) throw new AnchaError("USAGE", "logs interrupted; the run continues");
237831
- await sleep12(200, void 0, { signal }).catch((error65) => {
238488
+ await sleep13(200, void 0, { signal }).catch((error65) => {
237832
238489
  if (!signal.aborted) throw error65;
237833
238490
  });
237834
238491
  }
@@ -238315,6 +238972,7 @@ ${examples2(reference3.actors)}`] : [],
238315
238972
 
238316
238973
  // packages/cli/src/kit/init.ts
238317
238974
  init_assets();
238975
+ init_function_tools();
238318
238976
  init_detect();
238319
238977
  init_task_input();
238320
238978
  init_config();
@@ -238333,9 +238991,9 @@ var CONTAINER = { jsonl: "JSON lines", json: "JSON", csv: "CSV", yaml: "YAML" };
238333
238991
  var QUESTION_KEYS = ["question", "input", "prompt", "query", "task"];
238334
238992
  var EXPECTED_KEYS = ["expected", "answer", "ideal", "output", "reference", "expected_output", "expected_answer"];
238335
238993
  var ALIASES = /* @__PURE__ */ new Set([...QUESTION_KEYS, ...EXPECTED_KEYS]);
238336
- var FIELDS5 = ["read_only", "must_call", "numbers", "contains", "judge", "tags", "records", "unchanged", "counts"];
238994
+ var FIELDS5 = ["read_only", "must_call", "must_not_call", "numbers", "contains", "judge", "tags", "records", "unchanged", "counts"];
238337
238995
  var OWN = /* @__PURE__ */ new Set([...ALIASES, "id", ...FIELDS5]);
238338
- var LIST_KEYS = /* @__PURE__ */ new Set(["numbers", "contains", "must_call", "tags", "records", "counts"]);
238996
+ var LIST_KEYS = /* @__PURE__ */ new Set(["numbers", "contains", "must_call", "must_not_call", "tags", "records", "counts"]);
238339
238997
  var UUID4 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
238340
238998
  var DATE3 = /^\d{4}-\d{2}-\d{2}(?:[T ][\d:.]+Z?)?$|^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
238341
238999
  var record26 = (value5) => value5 !== null && typeof value5 === "object" && !Array.isArray(value5);
@@ -238805,7 +239463,7 @@ function decodeEvalText(bytes3) {
238805
239463
  var JUDGE_MODES = ["auto", "always", "never"];
238806
239464
  var QUESTION = ["question", "input", "prompt", "query", "task"];
238807
239465
  var EXPECTED = ["expected", "answer", "ideal", "output", "reference", "expected_output", "expected_answer"];
238808
- var KNOWN8 = /* @__PURE__ */ new Set([...QUESTION, ...EXPECTED, "id", "read_only", "must_call", "numbers", "contains", "judge", "tags", "records", "unchanged", "counts"]);
239466
+ var KNOWN8 = /* @__PURE__ */ new Set([...QUESTION, ...EXPECTED, "id", "read_only", "must_call", "must_not_call", "numbers", "contains", "judge", "tags", "records", "unchanged", "counts"]);
238809
239467
  var ID4 = { answer: "answer", judge: "judge", readOnly: "read-only", call: (n2) => `must-call-${n2}`, record: (n2) => `record-${n2}` };
238810
239468
  var DOCUMENT = /\b[A-Z][A-Z0-9]{0,9}(?:-[A-Z][A-Z0-9]{0,9})*-\d+(?:-\d+)*\b/g;
238811
239469
  var QUOTED = /"([^"\n]{2,200})"|“([^”\n]{2,200})”/g;
@@ -238864,11 +239522,11 @@ function extractExpected(expected, question = "") {
238864
239522
  const numbers2 = readNumbers(rest2.replace(DOCUMENT, " ").replace(DATE4, " ")).filter((n2) => !asked2.has(Math.abs(n2.value))).map((n2) => ({ value: n2.value, tolerance: 0.5 * 10 ** -n2.decimals }));
238865
239523
  return { contains: unique3([...quoted4, ...documents]), numbers: numbers2.filter((n2, i) => numbers2.findIndex((o) => o.value === n2.value) === i) };
238866
239524
  }
238867
- function callPattern(value5) {
239525
+ function callPattern(value5, functions) {
238868
239526
  if (typeof value5 !== "string") return void 0;
238869
239527
  const text30 = value5.trim().replace(/\s+/g, " ");
238870
239528
  if (text30 === "*" || /^MCP [^\s/]\S*$/i.test(text30) || /^[A-Za-z*]+ [/*]\S*$/.test(text30)) return text30;
238871
- if (/^[A-Za-z_][\w.-]{0,127}$/.test(text30)) return `MCP ${text30}`;
239529
+ if (/^[A-Za-z_][\w.-]{0,127}$/.test(text30)) return functions.includes(text30) ? text30 : `MCP ${text30}`;
238872
239530
  return void 0;
238873
239531
  }
238874
239532
  function givenRecords(value5) {
@@ -238916,6 +239574,8 @@ function editedSinceImport(text30) {
238916
239574
  }
238917
239575
  function importEvals(items2, world5, options4 = {}) {
238918
239576
  const judge = options4.judge ?? "auto", out = (options4.out ?? "ancha/tests").replace(/\/+$/, "") || ".", prefix2 = slug12(options4.prefix ?? "");
239577
+ const functions = options4.functionTools ?? [];
239578
+ const warnings2 = /* @__PURE__ */ new Set();
238919
239579
  const netsuite = world5.tools.includes("netsuite");
238920
239580
  const tests = [], skipped = [], ids2 = /* @__PURE__ */ new Set();
238921
239581
  items2.forEach((raw3, index) => {
@@ -238940,7 +239600,7 @@ function importEvals(items2, world5, options4 = {}) {
238940
239600
  const records4 = givenRecords(item2.records);
238941
239601
  if (typeof records4 === "string") return skip(records4);
238942
239602
  if (records4.length > 0 && !netsuite) return skip(`records: the world ${world5.id} has no NetSuite`);
238943
- if (expected === void 0 && alternatives === void 0 && !numbers2.length && !contains3.length && rubric === void 0 && !records4.length) return skip(`no expected answer (${EXPECTED.join(", ")})`);
239603
+ if (expected === void 0 && alternatives === void 0 && !numbers2.length && !contains3.length && rubric === void 0 && !records4.length && !listOf4(item2.must_call).length && !listOf4(item2.must_not_call).length) return skip(`no expected answer (${EXPECTED.join(", ")})`);
238944
239604
  const unchanged2 = item2.unchanged === void 0 ? void 0 : NetsuiteUnchangedCheckSchema.safeParse(item2.unchanged);
238945
239605
  if (unchanged2 && !unchanged2.success) return skip("unchanged: " + unchanged2.error.message);
238946
239606
  const counts = listOf4(item2.counts).map((value5) => NetsuiteCountCheckSchema.safeParse(value5));
@@ -238948,15 +239608,16 @@ function importEvals(items2, world5, options4 = {}) {
238948
239608
  if ((unchanged2 || counts.length) && !netsuite) return skip(`state checks: the world ${world5.id} has no NetSuite`);
238949
239609
  const readOnly = records4.length > 0 && (item2.read_only === void 0 || item2.read_only === null || item2.read_only === "") ? false : readOnlyOf(item2.read_only);
238950
239610
  if (readOnly === void 0) return skip(`read_only: ${JSON.stringify(item2.read_only)} is not true or false`);
238951
- const calls2 = listOf4(item2.must_call).map((call4) => ({ call: call4, pattern: callPattern(call4) }));
239611
+ const calls2 = ["must_call", "must_not_call"].flatMap((field7) => listOf4(item2[field7]).map((call4) => ({ field: field7, call: call4, pattern: callPattern(call4, functions) })));
239612
+ for (const call4 of calls2) if (typeof call4.call === "string" && call4.pattern === `MCP ${call4.call.trim()}`) warnings2.add(`Interpreted ${call4.call.trim()} as an MCP tool. Detected function tools: ${functions.join(", ") || "none"}. Use a declared function name for a function check.`);
238952
239613
  const badCall = calls2.find((call4) => call4.pattern === void 0);
238953
- if (badCall) return skip(`must_call: ${JSON.stringify(badCall.call)} is not "METHOD /path" or an MCP tool name`);
239614
+ if (badCall) return skip(`${badCall.field}: ${JSON.stringify(badCall.call)} is not "METHOD /path" or ${functions.length ? "a function or MCP tool name" : "an MCP tool name"}`);
238954
239615
  const read7 = numbers2.length || contains3.length || expected === void 0 ? void 0 : extractExpected(expected, question);
238955
239616
  const answerContains = read7?.contains ?? contains3, answerNumbers = read7?.numbers ?? numbers2;
238956
239617
  const answer = { ...answerContains.length > 0 && { contains: answerContains }, ...answerNumbers.length > 0 && { numbers: answerNumbers } };
238957
239618
  const hasAnswer = Object.keys(answer).length > 0;
238958
239619
  const wantsJudge = judge === "always" || judge === "auto" && (!hasAnswer || rubric !== void 0);
238959
- if (!hasAnswer && !wantsJudge && !records4.length) return skip("nothing to check without a judge: the expected answer states no number, document number or quoted text (--judge auto grades it with a model)");
239620
+ if (!hasAnswer && !wantsJudge && !records4.length && !calls2.length) return skip("nothing to check without a judge: the expected answer states no number, document number or quoted text (--judge auto grades it with a model)");
238960
239621
  const judgeText = rubric ?? (alternatives ? `The final answer states one of: ${alternatives.join(" | ")}` : expected !== void 0 ? `The final answer states: ${expected}` : void 0);
238961
239622
  const base4 = slug12(String(item2.id ?? "")) || slug12(question.split(/\s+/).slice(0, 8).join(" ")) || `item-${index + 1}`;
238962
239623
  let id14 = prefix2 ? `${prefix2}-${base4}` : base4;
@@ -238966,7 +239627,7 @@ function importEvals(items2, world5, options4 = {}) {
238966
239627
  ...hasAnswer ? [{ id: ID4.answer, answer }] : [],
238967
239628
  ...wantsJudge && judgeText !== void 0 ? [{ id: ID4.judge, judge: judgeText }] : [],
238968
239629
  ...readOnly && netsuite ? [{ id: ID4.readOnly, state: { "netsuite.unchanged": { types: [...netsuiteRecordTypes] } } }] : [],
238969
- ...calls2.map((call4, n2) => ({ id: ID4.call(n2 + 1), trace: { called: call4.pattern } })),
239630
+ ...calls2.map((call4, n2) => ({ id: call4.field === "must_call" ? ID4.call(n2 + 1) : `must-not-call-${n2 + 1}`, trace: { [call4.field === "must_call" ? "called" : "not_called"]: call4.pattern } })),
238970
239631
  ...records4.map((args, n2) => ({ id: ID4.record(n2 + 1), state: { "netsuite.record": args } })),
238971
239632
  ...unchanged2?.success ? [{ id: "unrelated-records", state: { "netsuite.unchanged": unchanged2.data } }] : [],
238972
239633
  ...counts.flatMap((result, n2) => result.success ? [{ id: `count-${n2 + 1}`, state: { "netsuite.count": result.data } }] : [])
@@ -238974,6 +239635,7 @@ function importEvals(items2, world5, options4 = {}) {
238974
239635
  const optionalJudge = (hasAnswer || records4.length > 0) && checks2.some((check4) => check4.id === ID4.judge);
238975
239636
  const test3 = {
238976
239637
  version: 2,
239638
+ ...functions.length && { function_tools: Object.fromEntries(functions.map((name5) => [name5, { unrecorded: "run", allow_unwrapped: true }])) },
238977
239639
  id: id14,
238978
239640
  title: oneLine5(question, 200),
238979
239641
  world: world5.id,
@@ -238996,7 +239658,7 @@ function importEvals(items2, world5, options4 = {}) {
238996
239658
  ];
238997
239659
  tests.push({ path: posix4.join(out, `${id14}.yaml`), scene: test3, yaml: testYaml(test3, header4, `${options4.source ? `from ${options4.source}, ` : ""}item ${index + 1}`) });
238998
239660
  });
238999
- return { tests, skipped };
239661
+ return { tests, skipped, warnings: [...warnings2] };
239000
239662
  }
239001
239663
  function evalFormat(name5, text30) {
239002
239664
  const extension2 = /\.([a-z]+)$/i.exec(name5)?.[1]?.toLowerCase();
@@ -239078,7 +239740,7 @@ function readEvalItems(name5, raw3) {
239078
239740
  return { items: rows34.map((cells) => Object.fromEntries(keys6.flatMap((key4, i) => {
239079
239741
  const cell16 = (cells[i] ?? "").trim();
239080
239742
  if (!key4 || cell16 === "") return [];
239081
- return [[key4, ["numbers", "contains", "must_call", "tags", "records", "counts"].includes(key4) ? csvList(cell16) : cell16]];
239743
+ return [[key4, ["numbers", "contains", "must_call", "must_not_call", "tags", "records", "counts"].includes(key4) ? csvList(cell16) : cell16]];
239082
239744
  }))), unreadable: [] };
239083
239745
  }
239084
239746
  let value5;
@@ -239783,9 +240445,16 @@ function step2(ctx) {
239783
240445
  var BEGIN = "<!-- ancha:begin -->";
239784
240446
  var END = "<!-- ancha:end -->";
239785
240447
  var managedSection = () => readFile40(new URL("agents-section.md", assetRoot()), "utf8");
239786
- async function installAgents(cwd) {
240448
+ async function installAgents(cwd, tools2) {
239787
240449
  const target5 = join56(cwd, "AGENTS.md");
239788
- const managed = await managedSection();
240450
+ const base4 = await managedSection();
240451
+ const wiring = tools2.length ? `
240452
+ Function tools: ${tools2.map((t) => t.name).join(", ")}.
240453
+ ${functionToolWiring(tools2).join("\n")}
240454
+ Read \`ancha docs tools\` for function checks and registration.
240455
+
240456
+ ` : "";
240457
+ const managed = base4.replace(END, wiring + END);
239789
240458
  let original;
239790
240459
  try {
239791
240460
  original = await readFile40(target5, "utf8");
@@ -239795,6 +240464,10 @@ async function installAgents(cwd) {
239795
240464
  return result.created.length ? "created" : "preserved";
239796
240465
  }
239797
240466
  if (original.includes(BEGIN) || original.includes(END)) {
240467
+ if (wiring && original.includes(base4)) {
240468
+ await rewrite(cwd, "AGENTS.md", original.replace(base4, managed));
240469
+ return "updated";
240470
+ }
239798
240471
  return original.includes(managed) ? "preserved" : "conflict";
239799
240472
  }
239800
240473
  await preflightFiles(cwd, [{ relativePath: "AGENTS.md", content: "" }]);
@@ -239859,7 +240532,7 @@ var ACCESS = {
239859
240532
  "open-meteo": "* /v1/forecast*",
239860
240533
  "better-stack": "* /api/v2/*",
239861
240534
  attio: "* /v2/*",
239862
- jira: "* /rest/api/3/*",
240535
+ jira: "* /rest/*",
239863
240536
  zendesk: "* /api/v2/*",
239864
240537
  asana: "* /api/1.0/*",
239865
240538
  discord: "* /api/v10/*",
@@ -240090,7 +240763,7 @@ function registerKit(program2, ctx) {
240090
240763
  const detection = await detectProject(ctx.io.cwd, opts.agent);
240091
240764
  const configText = await readFile40(join56(ctx.io.cwd, "ancha.yaml"), "utf8").catch(() => void 0);
240092
240765
  const configured = configText !== void 0;
240093
- let task2 = configured || detection.agent === null ? void 0 : await taskSetup(ctx.io.cwd, detection.agent, { command: detection.agent });
240766
+ let task2 = configured || detection.slackApp !== void 0 || detection.agent === null ? void 0 : await taskSetup(ctx.io.cwd, detection.agent, { command: detection.agent });
240094
240767
  const existingConfig = (() => {
240095
240768
  try {
240096
240769
  return configText === void 0 ? void 0 : parseConfigText(configText);
@@ -240116,8 +240789,8 @@ function registerKit(program2, ctx) {
240116
240789
  const pe = dataSize === void 0 ? void 0 : netsuiteData(dataSize);
240117
240790
  const existingTwins = await Promise.all(existing2.map((path7) => loadSceneFile(join56(ctx.io.cwd, path7)).then((scene2) => scene2.twins, () => [])));
240118
240791
  const mapsNetsuite = task2 !== void 0 && task2.netsuite.length > 0 && opts.template === "starter" && existingTwins.every((list18) => list18.includes("netsuite")) && (!starter || twins.includes("netsuite"));
240119
- const env2 = { ...task2?.wiring?.env, ...mapsNetsuite && Object.fromEntries(task2.netsuite.map((mapping) => [mapping.name, mapping.value])) };
240120
- const agentConfig = detection.agent === null ? void 0 : { command: task2?.wiring?.command ?? detection.agent, ...Object.keys(env2).length > 0 && { env: env2 }, ...task2?.stdin && { input: "stdin" } };
240792
+ const env2 = { ...detection.slackApp?.env, ...task2?.wiring?.env, ...mapsNetsuite && Object.fromEntries(task2.netsuite.map((mapping) => [mapping.name, mapping.value])) };
240793
+ const agentConfig = detection.agent === null ? void 0 : { command: task2?.wiring?.command ?? detection.agent, ...detection.slackApp && { slack_transport: detection.slackApp.transport, ...detection.slackApp.url && { url: detection.slackApp.url } }, ...Object.keys(env2).length > 0 && { env: env2 }, ...task2?.stdin && { input: "stdin" } };
240121
240794
  const templates = opts.template !== "starter" ? await templateFiles(opts.template) : !starter ? [] : (await starterPack("starter", `Reach ${twins.map(toolName).join(", ")}`, twins)).filter((file3) => STARTER_FILES.includes(file3.relativePath));
240122
240795
  const worldFiles = await glob3("ancha/worlds/*.yaml", { cwd: ctx.io.cwd, onlyFiles: true, followSymbolicLinks: false });
240123
240796
  const starterWorld = starter && !opts.intent && (!pe && worldFiles.length === 0 || worldFiles.includes("ancha/worlds/starter.yaml")) ? {
@@ -240127,7 +240800,7 @@ function registerKit(program2, ctx) {
240127
240800
  const files2 = [
240128
240801
  { relativePath: "ancha.yaml", content: `${agentConfig === void 0 ? "# Set agent.command to the command that starts your agent.\n" : (0, import_yaml17.stringify)({ agent: agentConfig })}scenes: [scenes/**/scene.yaml, ${TESTS_GLOB}]
240129
240802
  trials: 1
240130
- parallel: 3
240803
+ parallel: ${detection.slackApp?.transport === "http" ? 1 : 3}
240131
240804
  min_pass_rate: 1
240132
240805
  ` },
240133
240806
  ...templates.map((file3) => ({ ...file3, relativePath: `scenes/${opts.template}/${file3.relativePath}` })),
@@ -240148,7 +240821,7 @@ min_pass_rate: 1
240148
240821
  updated.push(file3.relativePath);
240149
240822
  }
240150
240823
  const result = await applyScaffold(ctx.io.cwd, files2.filter((file3) => !rewritten.includes(file3)));
240151
- const agents = await installAgents(ctx.io.cwd);
240824
+ const agents = await installAgents(ctx.io.cwd, detection.functionTools);
240152
240825
  let savedCommand;
240153
240826
  if (configured) {
240154
240827
  if (opts.agent !== void 0 && existingConfig !== void 0 && existingConfig.agent?.mode !== "endpoint" && !existingAgent?.command) {
@@ -240190,8 +240863,10 @@ min_pass_rate: 1
240190
240863
  }
240191
240864
  });
240192
240865
  const savedAgent = savedConfig?.agent;
240193
- const runs = savedAgent?.mode === "endpoint" || !savedAgent?.command ? void 0 : { command: savedAgent.command, source: "ancha.yaml" };
240866
+ const savedLaunch = savedAgent?.mode === "endpoint" ? savedAgent.start : savedAgent?.command;
240867
+ const runs = savedLaunch ? { command: savedLaunch, source: "ancha.yaml" } : void 0;
240194
240868
  const next2 = runs === void 0 ? ["set agent.command in ancha.yaml", cloud ? "ancha agent upload" : "ancha run"] : generated ? cloud ? ["ancha agent upload", `ancha run ${generated.test.file}`] : [`ancha run ${generated.test.file}`] : cloud ? ["ancha agent upload", starter || existing2.length > 0 || pe ? "ancha run" : "ancha traces upload ./traces"] : ["ancha run"];
240869
+ next2.unshift(...functionToolWiring(detection.functionTools));
240195
240870
  const taskInput = task2 === void 0 ? void 0 : {
240196
240871
  native: task2.scan.native,
240197
240872
  found: task2.scan.inputs.slice(0, 5),
@@ -240209,6 +240884,7 @@ min_pass_rate: 1
240209
240884
  ctx.out.result(output2, () => [
240210
240885
  `Created ${result.created.length} files; updated ${updated.length}; preserved ${result.skipped.length}.`,
240211
240886
  `agent: ${agent}`,
240887
+ ...detection.functionTools.length ? [`function tools: ${detection.functionTools.map((t) => t.name).join(", ")}`] : [],
240212
240888
  ...savedCommand !== void 0 ? ["Saved agent.command in ancha.yaml."] : [],
240213
240889
  // The tools it uses, and where each one showed: what the coding agent confirms with the person (SPEC-053, Jay).
240214
240890
  given2 !== void 0 ? `tools: ${names5(given2)} (from --tools)` : used.length > 0 ? `tools: ${used.map((twin) => `${toolName(twin)} (from ${found.from[twin]})`).join(", ")}` : "tools: none found in its dependencies or source; name them with ancha init --tools <tools>, e.g. --tools netsuite,slack",
@@ -240377,7 +241053,7 @@ var world4 = (value5) => pick5(value5, ["id", "name", "revision"]);
240377
241053
  var test2 = (value5) => pick5(value5, ["id", "name", "revision", "agentId", "worldId", "worldRevision"]);
240378
241054
  function listRun(run6) {
240379
241055
  return {
240380
- ...pick5(run6, ["schemaVersion", "id", "agentId", "agentName", "agentCommand", "groupName", "createdAt", "finishedAt", "sourceRunId", "status", "concurrency", "requestedConcurrency", "evaluation", "summary", "origin", "queue", "verdict", "exitCode"]),
241056
+ ...pick5(run6, ["schemaVersion", "id", "runNumber", "startedBy", "agentId", "agentName", "agentCommand", "groupName", "createdAt", "finishedAt", "sourceRunId", "status", "concurrency", "requestedConcurrency", "evaluation", "summary", "origin", "queue", "verdict", "exitCode"]),
240381
241057
  // The Runs page's "vs production" and baseline columns: each verdict, not the checks behind it.
240382
241058
  ...Array.isArray(run6.reproduction) && { reproduction: run6.reproduction.map((r2) => pick5(r2, ["sceneId", "trace", "verdict"])) },
240383
241059
  ...run6.comparison && { comparison: { ...pick5(run6.comparison, ["baselineRunId", "regressed"]), scenes: (run6.comparison.scenes ?? []).map((scene2) => pick5(scene2, ["sceneId", "before", "after", "delta"])) } },
@@ -241887,6 +242563,8 @@ var CliRuns = class {
241887
242563
  return {
241888
242564
  schemaVersion: 1,
241889
242565
  id: id14,
242566
+ ...summary.runNumber && { runNumber: summary.runNumber },
242567
+ ...summary.startedBy && { startedBy: summary.startedBy },
241890
242568
  agentId: "",
241891
242569
  agentName: agent.name,
241892
242570
  ...agent.command !== void 0 && { agentCommand: agent.command },
@@ -243091,10 +243769,12 @@ import { existsSync as existsSync4 } from "node:fs";
243091
243769
  import { access as access14, mkdir as mkdir28, readFile as readFile44, writeFile as writeFile30 } from "node:fs/promises";
243092
243770
  import { basename as basename13, dirname as dirname23, extname as extname2, isAbsolute as isAbsolute12, relative as relative21, resolve as resolve46 } from "node:path";
243093
243771
  init_src();
243772
+ init_detect();
243773
+ init_function_tools();
243094
243774
  var EXAMPLE = `
243095
243775
  Each eval is a question with its expected answer. Fields: question (or input, prompt, query, task); expected (or answer,
243096
- ideal, output, reference, expected_output); optional: id, read_only (default true; false with records), must_call
243097
- ("METHOD /path" or an MCP tool name), numbers ([{ value, tolerance }]), contains (text the answer must hold), judge (a
243776
+ ideal, output, reference, expected_output); optional: id, read_only (default true; false with records), must_call and must_not_call
243777
+ ("METHOD /path", a detected function tool name or an MCP tool name), numbers ([{ value, tolerance }]), contains (text the answer must hold), judge (a
243098
243778
  rubric), tags, records (the NetSuite state a write leaves: [{ type, id or externalId, fields }]). Other fields are kept
243099
243779
  in the test's header. It also reads eval tools' files as they are: OpenAI evals, promptfoo configs and tests,
243100
243780
  LangSmith and Braintrust dataset exports, DeepEval and Ragas datasets, and CSV with any column names (it prints the
@@ -243109,7 +243789,7 @@ netsuite.record for each of its records, and a judge when nothing in the expecte
243109
243789
 
243110
243790
  ancha test import ancha/evals/netsuite-pe.jsonl --world netsuite-pe
243111
243791
  ancha test import evals.csv --prefix ops --judge never --json`;
243112
- var kind = (check4) => "answer" in check4 ? "answer" : "judge" in check4 ? "judge" : "trace" in check4 ? "trace.called" : Object.keys(check4.state ?? {})[0] ?? "state";
243792
+ var kind = (check4) => "answer" in check4 ? "answer" : "judge" in check4 ? "judge" : "trace" in check4 ? "not_called" in check4.trace ? "trace.not_called" : "trace.called" : Object.keys(check4.state ?? {})[0] ?? "state";
243113
243793
  async function testImport(ctx, file3, options4) {
243114
243794
  if (!JUDGE_MODES.includes(options4.judge)) throw new AnchaError("USAGE", `--judge must be one of ${JUDGE_MODES.join(", ")}`, { hint: "e.g. --judge never: answer checks only, no model" });
243115
243795
  if (options4.prefix !== void 0 && !/[a-z0-9]/i.test(options4.prefix)) throw new AnchaError("USAGE", "--prefix needs letters or digits", { hint: "e.g. --prefix ops" });
@@ -243132,7 +243812,8 @@ async function testImport(ctx, file3, options4) {
243132
243812
  if (read7.items.length === 0) throw new AnchaError("USAGE", `no evals in ${file3}`, { hint: 'each eval is a question with its expected answer, e.g. {"question": "\u2026", "expected": "\u2026"}' });
243133
243813
  const world5 = await chooseWorld(ctx, options4.world, `ancha test import ${file3}`);
243134
243814
  const outDir = resolve46(ctx.io.cwd, options4.out), out = relative21(ctx.io.cwd, outDir) || ".";
243135
- const imported2 = importEvals(read7.items, { id: world5.id, tools: world5.tools }, { judge: options4.judge, ...options4.prefix !== void 0 && { prefix: options4.prefix }, out, source: basename13(path7) });
243815
+ const detection = await detectProject(ctx.io.cwd);
243816
+ const imported2 = importEvals(read7.items, { id: world5.id, tools: world5.tools }, { functionTools: detection.functionTools.map((t) => t.name), judge: options4.judge, ...options4.prefix !== void 0 && { prefix: options4.prefix }, out, source: basename13(path7) });
243136
243817
  const reasons = new Map([...imported2.skipped.map((s3) => [s3.index, s3.reason]), ...read7.unreadable.map((u) => [u.index, u.reason])]);
243137
243818
  const skipped = [...reasons].sort(([a], [b]) => a - b).map(([index, reason2]) => ({ item: index + 1, reason: reason2 }));
243138
243819
  if (imported2.tests.length === 0) {
@@ -243159,6 +243840,7 @@ ${skipped.slice(0, 10).map((s3) => `item ${s3.item}: ${s3.reason}`).join("\n")}`
243159
243840
  const inProject2 = relative21(ctx.io.cwd, path7).split(/[\\/]/);
243160
243841
  const withAgent = inProject2[0] !== ".." && !isAbsolute12(inProject2.join("/")) && inProject2[0] !== "ancha" && !inProject2.some((part) => part.startsWith(".") || part === "node_modules");
243161
243842
  const notes6 = [
243843
+ ...imported2.warnings,
243162
243844
  ...withAgent ? [`${file3} goes to the agent with its files in a cloud run, expected answers and all: move it under ancha/ (e.g. ancha/evals/${basename13(path7)}), which stays with the grader`] : [],
243163
243845
  ...encoding ? [`read as ${encoding} text`] : [],
243164
243846
  ...read7.notes ?? [],
@@ -243166,6 +243848,7 @@ ${skipped.slice(0, 10).map((s3) => `item ${s3.item}: ${s3.reason}`).join("\n")}`
243166
243848
  ...checks2.judge ? ["judge checks grade with a model: in the cloud on the workspace's model credit, on this computer with OPENROUTER_API_KEY; answer checks need no model"] : []
243167
243849
  ];
243168
243850
  const next2 = configured ? [seen ? "ancha run" : `ancha run ${out}/*.yaml`] : ["ancha init", `ancha run ${out}/*.yaml`];
243851
+ next2.unshift(...functionToolWiring(detection.functionTools));
243169
243852
  const format2 = read7.format ?? { jsonl: "JSON lines", json: "JSON", csv: "CSV", yaml: "YAML" }[evalFormat(basename13(path7), text30)];
243170
243853
  const result = { file: relative21(ctx.io.cwd, path7), world: world5.id, out, format: format2, ...read7.fields && { fields: read7.fields }, tests, checks: checks2, skipped, next: next2, notes: notes6 };
243171
243854
  ctx.out.result(result, () => report6(result));
@@ -247150,7 +247833,7 @@ function buildInputRequiredRetryParams(originalParams, responses, requestState)
247150
247833
  function inputRequiredRoundsExceededMessage2(method2, maxRounds) {
247151
247834
  return `Multi-round-trip request '${method2}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
247152
247835
  }
247153
- function sleep13(ms2, signal) {
247836
+ function sleep14(ms2, signal) {
247154
247837
  return new Promise((resolve59, reject4) => {
247155
247838
  if (signal?.aborted) {
247156
247839
  reject4(signal.reason instanceof SdkError2 ? signal.reason : new SdkError2(SdkErrorCode2.RequestTimeout, String(signal.reason)));
@@ -247213,7 +247896,7 @@ async function runInputRequiredDriver(args) {
247213
247896
  } finally {
247214
247897
  round$1.dispose();
247215
247898
  }
247216
- } else await sleep13(REQUEST_STATE_ONLY_LEG_PACING_MS2, signal);
247899
+ } else await sleep14(REQUEST_STATE_ONLY_LEG_PACING_MS2, signal);
247217
247900
  const legOptions = { ...requestOptions.timeout !== void 0 && { timeout: requestOptions.timeout } };
247218
247901
  if (requestOptions.maxTotalTimeout !== void 0) {
247219
247902
  const totalElapsed = Date.now() - startedAt;
@@ -256350,22 +257033,22 @@ async function authInternal(provider, { serverUrl: serverUrl3, authorizationCode
256350
257033
  }, infoCtx);
256351
257034
  return "AUTHORIZED";
256352
257035
  }
256353
- let tokens4 = discardIfIssuerMismatch(await provider.tokens(infoCtx), issuer);
256354
- if (tokens4 && tokens4.issuer === void 0) {
256355
- tokens4 = {
256356
- ...tokens4,
257036
+ let tokens5 = discardIfIssuerMismatch(await provider.tokens(infoCtx), issuer);
257037
+ if (tokens5 && tokens5.issuer === void 0) {
257038
+ tokens5 = {
257039
+ ...tokens5,
256357
257040
  issuer
256358
257041
  };
256359
- await provider.saveTokens(tokens4, infoCtx);
257042
+ await provider.saveTokens(tokens5, infoCtx);
256360
257043
  }
256361
- if (tokens4?.refresh_token && !forceReauthorization) {
256362
- const refreshScope = await provider.scopeForRefresh?.(tokens4);
257044
+ if (tokens5?.refresh_token && !forceReauthorization) {
257045
+ const refreshScope = await provider.scopeForRefresh?.(tokens5);
256363
257046
  let newTokens;
256364
257047
  try {
256365
257048
  newTokens = await refreshAuthorization(authorizationServerUrl, {
256366
257049
  metadata: metadata7,
256367
257050
  clientInformation,
256368
- refreshToken: tokens4.refresh_token,
257051
+ refreshToken: tokens5.refresh_token,
256369
257052
  scope: refreshScope,
256370
257053
  resource: resource2,
256371
257054
  addClientAuthentication: provider.addClientAuthentication,
@@ -256660,7 +257343,7 @@ async function refreshAuthorization(authorizationServerUrl, { metadata: metadata
256660
257343
  refresh_token: refreshToken
256661
257344
  });
256662
257345
  if (scope3) tokenRequestParams.set("scope", scope3);
256663
- const tokens4 = await executeTokenRequest(authorizationServerUrl, {
257346
+ const tokens5 = await executeTokenRequest(authorizationServerUrl, {
256664
257347
  metadata: metadata7,
256665
257348
  tokenRequestParams,
256666
257349
  clientInformation,
@@ -256671,8 +257354,8 @@ async function refreshAuthorization(authorizationServerUrl, { metadata: metadata
256671
257354
  });
256672
257355
  return {
256673
257356
  refresh_token: refreshToken,
256674
- ...tokens4,
256675
- ...scope3 && !tokens4.scope && { scope: scope3 }
257357
+ ...tokens5,
257358
+ ...scope3 && !tokens5.scope && { scope: scope3 }
256676
257359
  };
256677
257360
  }
256678
257361
  async function fetchToken(provider, authorizationServerUrl, { metadata: metadata7, resource: resource2, authorizationCode, iss, scope: scope3, fetchFn } = {}) {
@@ -259347,13 +260030,13 @@ var withDpopFromProvider = (provider) => withDpop(async () => {
259347
260030
  throw markAuthSeamEscape(error65);
259348
260031
  }
259349
260032
  }, async () => {
259350
- let tokens4;
260033
+ let tokens5;
259351
260034
  try {
259352
- tokens4 = await provider.tokens();
260035
+ tokens5 = await provider.tokens();
259353
260036
  } catch (error65) {
259354
260037
  throw markAuthSeamEscape(error65);
259355
260038
  }
259356
- return tokens4?.token_type?.toLowerCase() === "dpop" ? tokens4.access_token : void 0;
260039
+ return tokens5?.token_type?.toLowerCase() === "dpop" ? tokens5.access_token : void 0;
259357
260040
  });
259358
260041
  var SseError = class extends Error {
259359
260042
  static {
@@ -259502,10 +260185,10 @@ var StreamableHTTPClientTransport = class {
259502
260185
  text: challenge.text
259503
260186
  });
259504
260187
  if (challenge.resourceMetadataUrl) this._resourceMetadataUrl = challenge.resourceMetadataUrl;
259505
- const tokens4 = await this._oauthProvider.tokens();
259506
- const unionScope = computeScopeUnion(this._scope, tokens4?.scope, challenge.scope);
260188
+ const tokens5 = await this._oauthProvider.tokens();
260189
+ const unionScope = computeScopeUnion(this._scope, tokens5?.scope, challenge.scope);
259507
260190
  this._scope = unionScope;
259508
- const forceReauthorization = isStrictScopeSuperset(unionScope, tokens4?.scope);
260191
+ const forceReauthorization = isStrictScopeSuperset(unionScope, tokens5?.scope);
259509
260192
  return auth(this._oauthProvider, {
259510
260193
  serverUrl: this._url,
259511
260194
  resourceMetadataUrl: this._resourceMetadataUrl,
@@ -263317,6 +264000,8 @@ function registerSchema(program2, ctx) {
263317
264000
  }
263318
264001
 
263319
264002
  // packages/cli/src/commands/runs.ts
264003
+ import { randomUUID as randomUUID21 } from "node:crypto";
264004
+ init_run_metadata();
263320
264005
  var import_yaml20 = __toESM(require_dist(), 1);
263321
264006
  init_src();
263322
264007
  import { mkdir as mkdir33, readFile as readFile53, stat as stat19, writeFile as writeFile36 } from "node:fs/promises";
@@ -263405,6 +264090,7 @@ function brief(run6, queue) {
263405
264090
  const waiting = queue.find((entry3) => entry3.runId === run6.id);
263406
264091
  return {
263407
264092
  id: run6.id,
264093
+ ...run6.runNumber && { runNumber: run6.runNumber },
263408
264094
  name: run6.test?.name ?? run6.groupName ?? run6.agentName,
263409
264095
  status: run6.status,
263410
264096
  createdAt: run6.createdAt,
@@ -263490,7 +264176,7 @@ next page: ancha runs list --cursor ${page18.nextCursor}`}`);
263490
264176
  const combined = [...listed2.runs.map((run6) => brief(run6, queue)), ...recorded2.map((run6) => brief(run6, []))];
263491
264177
  return { runs: combined.sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt) || b.id.localeCompare(a.id)) };
263492
264178
  });
263493
- ctx.out.result(result, () => result.runs.length ? formatTable(result.runs.map((run6) => [run6.id, run6.name, run6.status, grade(run6), run6.queue ? `queued #${run6.queue.position}` : run6.createdAt])) : "No runs yet.");
264179
+ ctx.out.result(result, () => result.runs.length ? formatTable(result.runs.map((run6) => [runLabel(run6), run6.name, run6.status, grade(run6), run6.queue ? `queued #${run6.queue.position}` : run6.createdAt])) : "No runs yet.");
263494
264180
  });
263495
264181
  runs.command("start").description("run a test with a saved agent in fresh worlds; in a hosted workspace its console runs it, so a dropped connection doesn't stop it").requiredOption("--agent <id>", "saved agent (ancha agent list)").requiredOption("--test <file>", "managed task file (version 2, start.task and an explicit saved world; other scene.yaml fields are rejected)").option("--world <id-or-name>", "saved world to run in (default: the test's world)").option("-n, --attempts <n>", "attempts (default: the test's attempts, else 1)").option("--concurrency <n>", "attempts at once", "1").option("--idempotency-key <key>", "retry safely: the same key and definition return the original run").option("--commit <sha>", "the git commit of the code this run tests (ancha run --on cloud sets it; here, the folder's own)").option("--dirty", "that code had uncommitted changes").option("--no-wait", "return once the run is accepted (hosted workspace only)").action(async (options4) => {
263496
264182
  const { task: task2, world: world5 } = await testTask(ctx, options4.test, options4.world);
@@ -263533,7 +264219,7 @@ next page: ancha runs list --cursor ${page18.nextCursor}`}`);
263533
264219
  const passEnv = inputs2.agentEnvironment?.passEnv ?? (await ctx.loadConfig().catch(() => void 0))?.agent?.passEnv ?? [];
263534
264220
  const inheritEnv = inputs2.agentEnvironment?.inheritEnv ?? summary.agentEnvironment?.inheritAll === true;
263535
264221
  const upload4 = await uploadRun(ctx, workspace4, { runId: summary.runId, runDir, passEnv, inheritEnv });
263536
- ctx.out.result({ runId: summary.runId, workspace: workspace4, upload: upload4 }, () => `uploaded: ${upload4.url}`);
264222
+ ctx.out.result({ runId: summary.runId, workspace: workspace4, upload: upload4 }, () => `uploaded: ${upload4.runNumber ? `#${upload4.runNumber} \xB7 ` : ""}${upload4.url}`);
263537
264223
  });
263538
264224
  runs.command("export").argument("<run>", 'a finished run: its id (run_\u2026) or "latest"').option("--out <dir>", "where run directories are (default: .ancha/runs)").option("--dest <dir>", "where to write the traces (default: .ancha/exports/<run>)").description("write each attempt as an Ancha trace (IR v1): the calls the agent made and the events it was sent, the shape production traces are imported in").action(async (ref22, options4) => {
263539
264225
  if (ref22 === "latest") ref22 = await latestRunId(ctx.io.cwd, options4.out);
@@ -263569,9 +264255,22 @@ next page: ancha runs list --cursor ${page18.nextCursor}`}`);
263569
264255
  });
263570
264256
  runs.command("show").argument("<id>", 'a run: run_cloud_\u2026 (a cloud run), play_\u2026 (a playground run), run_\u2026 (a run on this computer), or "latest" (the most recent run from this project, on this computer or in the workspace)').description("show one run with its attempts and grade").action(async (id14) => {
263571
264257
  if (id14 === "latest") id14 = await latestRunId(ctx.io.cwd);
263572
- if (isCloudId(id14)) {
264258
+ if (isCloudId(id14) || numberReference(id14) !== void 0) {
263573
264259
  const ws = await jobWorkspace(ctx, id14);
263574
264260
  const detail3 = await getJob(ws, id14);
264261
+ if (detail3.run) {
264262
+ const run6 = detail3.run, listed2 = brief(run6, []);
264263
+ ctx.out.result(run6, () => `${runLabel(run6)} \xB7 ${listed2.name} \xB7 ${listed2.status} \xB7 ${grade(listed2)}`);
264264
+ return;
264265
+ }
264266
+ if (!detail3.job) {
264267
+ if (!detail3.summary) throw new AnchaError("USAGE", "This run has no saved summary.");
264268
+ const summary = detail3.summary;
264269
+ ctx.out.result(summary, () => `${summary.runNumber ? `#${summary.runNumber}
264270
+ ` : ""}${renderSummaryText(summary, { cwd: ctx.io.cwd })}`);
264271
+ return;
264272
+ }
264273
+ id14 = detail3.job.id;
263575
264274
  const done = shared.TERMINAL_JOB_STATES.includes(detail3.job.state);
263576
264275
  const graded = detail3.summary !== null && detail3.summary.checkCounts?.evaluated !== 0;
263577
264276
  const never2 = done ? cloudNeverRan(detail3) : void 0;
@@ -263600,6 +264299,33 @@ next page: ancha runs list --cursor ${page18.nextCursor}`}`);
263600
264299
  });
263601
264300
  ctx.out.result(result, () => [`${result.name} \xB7 ${result.status} \xB7 ${grade(result)}`, ...result.attempts.map((attempt2) => ` ${attempt2.number} ${attempt2.taskId}: ${attempt2.outcome ?? attempt2.status}${attempt2.invalidReason ? ` (${attempt2.invalidReason})` : ""}`), `next: ancha explain ${id14}`].join("\n"));
263602
264301
  });
264302
+ runs.command("again").argument("<id>", "a finished cloud run: its number (42) or run_cloud_\u2026 ID").description("run stored cloud inputs again, with the same tests and options").option("--failed", "only tests with failed, invalid or ungraded attempts").option("--attempts <n>", "attempts per selected test").option("--detach", "return once the new run is accepted").option("--idempotency-key <key>", "retry the same submission safely").action(async (id14, options4) => {
264303
+ const number7 = numberReference(id14);
264304
+ if (number7 === void 0 && !shared.RUN_CLOUD_ID.test(id14)) throw new AnchaError("USAGE", `${id14} is not a cloud run`, { hint: "run ancha run --on cloud from your project; ancha runs list shows cloud runs" });
264305
+ const attempts = options4.attempts === void 0 ? void 0 : positiveInt("--attempts", options4.attempts);
264306
+ if (attempts !== void 0 && attempts > 1e4) throw new AnchaError("USAGE", "--attempts takes 1\u201310000");
264307
+ const key4 = options4.idempotencyKey ?? `cli-${randomUUID21()}`;
264308
+ if (!/^[\x21-\x7e]{1,200}$/.test(key4)) throw new AnchaError("USAGE", "--idempotency-key takes 1\u2013200 visible ASCII characters");
264309
+ const ws = await jobWorkspace(ctx, id14);
264310
+ if (number7 !== void 0) {
264311
+ const detail3 = await getJob(ws, id14);
264312
+ if (!detail3.job || !shared.RUN_CLOUD_ID.test(detail3.job.id)) throw new AnchaError("USAGE", `#${number7} is not a cloud run`, { hint: "run ancha run --on cloud from your project; ancha runs list shows cloud runs" });
264313
+ id14 = detail3.job.id;
264314
+ }
264315
+ ctx.exitCode = await interruptible(ctx, async (signal) => {
264316
+ const answer = await rerunJob(ws, id14, { version: 1, mode: options4.failed ? "failed" : "again", idempotencyKey: key4, ...attempts !== void 0 && { attempts } }, signal, runContextHeader(ctx.io.env));
264317
+ const url4 = resultUrl(ws, answer), runId2 = answer.job.id;
264318
+ const value5 = { event: options4.detach ? "run_detached" : "run_submitted", target: "cloud", workspace: ws.server, runId: runId2, replayed: answer.replayed, url: url4, next: `ancha wait ${runId2}` };
264319
+ if (options4.detach) {
264320
+ ctx.out.result(value5, () => `${runId2}: submitted \xB7 ${url4}
264321
+ next: ancha wait ${runId2}`);
264322
+ return 0;
264323
+ }
264324
+ if (ctx.out.json) ctx.out.event(value5);
264325
+ else ctx.out.notice(`${runId2}: submitted \xB7 ${url4}`);
264326
+ return followToEnd(ctx, ws, runId2, signal);
264327
+ });
264328
+ });
263603
264329
  runs.command("cancel").argument("<id>", "a cloud run (run_cloud_\u2026 or connect_cloud_\u2026)").description("stop a cloud run: its attempts stop and what finished is kept").action(async (id14) => {
263604
264330
  if (!isCloudId(id14)) throw new AnchaError("USAGE", `${id14} is not a cloud run`, { hint: "a run on this computer stops with Ctrl-C in its terminal; ancha runs list shows the cloud runs" });
263605
264331
  const { job } = await cancelJob(await jobWorkspace(ctx, id14), id14);
@@ -263645,7 +264371,7 @@ init_run_store();
263645
264371
  // packages/cli/src/trace-sources.ts
263646
264372
  init_src();
263647
264373
  var TRACE_SOURCES = ["langfuse", "langsmith"];
263648
- var sleep14 = (ms2) => new Promise((done) => setTimeout(done, ms2));
264374
+ var sleep15 = (ms2) => new Promise((done) => setTimeout(done, ms2));
263649
264375
  function traceRef(source, ref22) {
263650
264376
  const text30 = ref22.trim();
263651
264377
  let url4;
@@ -263667,7 +264393,7 @@ async function call3(f2, url4, init, tool, keys6) {
263667
264393
  throw new AnchaError("SERVER_UNREACHABLE", `cannot reach ${tool} at ${new URL(url4).origin}`, { cause: error65, hint: "check the host in your environment and the network" });
263668
264394
  }
263669
264395
  if (res.status === 429 && attempt < 8) {
263670
- await sleep14((Number(res.headers.get("retry-after")) || 2 ** attempt) * 1e3);
264396
+ await sleep15((Number(res.headers.get("retry-after")) || 2 ** attempt) * 1e3);
263671
264397
  continue;
263672
264398
  }
263673
264399
  if (res.status === 401 || res.status === 403) throw new AnchaError("AUTH_INVALID", `${tool} refused the keys in ${keys6}`, { hint: `check ${keys6} in this shell` });