@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/worker.mjs CHANGED
@@ -168,10 +168,10 @@ var init_execution_support = __esm({
168
168
  "agent.input.per_event": sceneOnly,
169
169
  "agent.input.events": localOnly,
170
170
  "agent.input.http": all,
171
- "agent.endpoint": localOnly,
171
+ "agent.endpoint": { ...localOnly, "cloud-vm": true },
172
172
  "agent.slack_transport.feed": sceneOnly,
173
- "agent.slack_transport.http": localOnly,
174
- "agent.slack_transport.socket": localOnly,
173
+ "agent.slack_transport.http": { ...localOnly, "cloud-vm": true },
174
+ "agent.slack_transport.socket": { ...localOnly, "cloud-vm": true },
175
175
  "agent.env": sceneOnly,
176
176
  "agent.pass_env": sceneOnly,
177
177
  "agent.execution": sceneOnly,
@@ -31683,9 +31683,9 @@ function declarations(scene2) {
31683
31683
  const ref22 = "slack.post" in a ? a["slack.post"].ref : void 0;
31684
31684
  if (ref22 !== void 0) out.push({ name: ref22, kind: "message", path: `world_rules.actors[${i}].slack.post.ref` });
31685
31685
  });
31686
- const github2 = scene2.seed.github;
31687
- github2?.users?.forEach((u, i) => out.push({ name: u.ref, kind: "user", path: `seed.github.users[${i}].ref` }));
31688
- github2?.repos.forEach((r2, i) => {
31686
+ const github3 = scene2.seed.github;
31687
+ github3?.users?.forEach((u, i) => out.push({ name: u.ref, kind: "user", path: `seed.github.users[${i}].ref` }));
31688
+ github3?.repos.forEach((r2, i) => {
31689
31689
  const p2 = `seed.github.repos[${i}]`;
31690
31690
  out.push({ name: r2.ref, kind: "repo", path: `${p2}.ref` });
31691
31691
  r2.commits.forEach((c, j) => out.push({ name: c.ref, kind: "commit", path: `${p2}.commits[${j}].ref` }));
@@ -31817,9 +31817,9 @@ function validateRefs(scene2) {
31817
31817
  const decl = use(path6, value4, "user");
31818
31818
  if (decl && !/^seed\.(github|slack)\.users\[/.test(decl.path)) issues.push({ path: path6, message: `${value4} has no GitHub identity; use a GitHub or Slack seed user` });
31819
31819
  };
31820
- const github2 = scene2.seed.github;
31821
- if (github2?.bot !== void 0) useGitHubUser("seed.github.bot", github2.bot);
31822
- github2?.repos.forEach((r2, i) => {
31820
+ const github3 = scene2.seed.github;
31821
+ if (github3?.bot !== void 0) useGitHubUser("seed.github.bot", github3.bot);
31822
+ github3?.repos.forEach((r2, i) => {
31823
31823
  const p2 = `seed.github.repos[${i}]`;
31824
31824
  r2.commits.forEach((c, j) => {
31825
31825
  if (c.author !== void 0) useGitHubUser(`${p2}.commits[${j}].author`, c.author);
@@ -31851,7 +31851,7 @@ function validateRefs(scene2) {
31851
31851
  r2.check_runs?.forEach((c, j) => use(`${p2}.check_runs[${j}].commit`, c.commit, "commit"));
31852
31852
  r2.collaborators?.forEach((c, j) => useGitHubUser(`${p2}.collaborators[${j}].user`, c.user));
31853
31853
  });
31854
- github2?.orgs?.forEach((org5, i) => org5.members.forEach((member4, j) => useGitHubUser(`seed.github.orgs[${i}].members[${j}].user`, member4.user)));
31854
+ github3?.orgs?.forEach((org5, i) => org5.members.forEach((member4, j) => useGitHubUser(`seed.github.orgs[${i}].members[${j}].user`, member4.user)));
31855
31855
  scene2.world_rules?.pipelines?.forEach((p2, i) => use(`world_rules.pipelines[${i}].repo`, p2.repo, "repo"));
31856
31856
  scene2.world_rules?.actors?.forEach((a, i) => {
31857
31857
  const p2 = `world_rules.actors[${i}]`;
@@ -40304,7 +40304,7 @@ function validPath(value4) {
40304
40304
  return !value4.includes("\0") && !value4.split("/").some((p2) => p2 === "" || p2 === "." || p2 === "..");
40305
40305
  }
40306
40306
  function githubSeedIssues(scene2) {
40307
- const github2 = scene2.seed.github;
40307
+ const github3 = scene2.seed.github;
40308
40308
  const issues = [];
40309
40309
  const pathIssue = (path6, value4) => {
40310
40310
  if (!validPath(value4)) issues.push({ path: path6, 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" });
@@ -40313,17 +40313,17 @@ function githubSeedIssues(scene2) {
40313
40313
  if (!validPath(value4)) pathIssue(path6, value4);
40314
40314
  else if (!validGitBranch(value4)) issues.push({ path: path6, message: "invalid Git branch name", hint: "use a literal Git branch name such as main or feature/fix" });
40315
40315
  };
40316
- if (!github2 && scene2.twins.includes("github")) {
40316
+ if (!github3 && scene2.twins.includes("github")) {
40317
40317
  issues.push({ path: "seed.github", message: "required when twins includes github", hint: "add a seed.github section with repos" });
40318
40318
  }
40319
40319
  const logins = /* @__PURE__ */ new Set();
40320
- github2?.users?.forEach((user8, i) => {
40320
+ github3?.users?.forEach((user8, i) => {
40321
40321
  const key4 = user8.login.toLowerCase();
40322
40322
  if (logins.has(key4)) issues.push({ path: `seed.github.users[${i}].login`, message: `duplicate GitHub login "${user8.login}" (case-insensitive)` });
40323
40323
  logins.add(key4);
40324
40324
  });
40325
40325
  const orgLogins = /* @__PURE__ */ new Set();
40326
- github2?.orgs?.forEach((org5, i) => {
40326
+ github3?.orgs?.forEach((org5, i) => {
40327
40327
  const key4 = org5.login.toLowerCase();
40328
40328
  if (orgLogins.has(key4)) issues.push({ path: `seed.github.orgs[${i}].login`, message: `duplicate organization "${org5.login}" (case-insensitive)` });
40329
40329
  if (logins.has(key4)) issues.push({ path: `seed.github.orgs[${i}].login`, message: `"${org5.login}" is a user login, not an organization` });
@@ -40336,7 +40336,7 @@ function githubSeedIssues(scene2) {
40336
40336
  members4.add(name5);
40337
40337
  });
40338
40338
  });
40339
- github2?.repos.forEach((r2, i) => {
40339
+ github3?.repos.forEach((r2, i) => {
40340
40340
  const seen = /* @__PURE__ */ new Set();
40341
40341
  r2.collaborators?.forEach((c, j) => {
40342
40342
  const name5 = refName5(c.user);
@@ -40346,7 +40346,7 @@ function githubSeedIssues(scene2) {
40346
40346
  });
40347
40347
  });
40348
40348
  const owners = /* @__PURE__ */ new Map();
40349
- for (const r2 of github2?.repos ?? []) for (const c of r2.commits) owners.set(c.ref, r2.ref);
40349
+ for (const r2 of github3?.repos ?? []) for (const c of r2.commits) owners.set(c.ref, r2.ref);
40350
40350
  const sameRepo = (path6, value4, repo4) => {
40351
40351
  const name5 = refName5(value4);
40352
40352
  const owner3 = name5 === void 0 ? void 0 : owners.get(name5);
@@ -40357,7 +40357,7 @@ function githubSeedIssues(scene2) {
40357
40357
  return owner3 === repo4 ? name5 : void 0;
40358
40358
  };
40359
40359
  const repoNames = /* @__PURE__ */ new Set();
40360
- github2?.repos.forEach((r2, i) => {
40360
+ github3?.repos.forEach((r2, i) => {
40361
40361
  const p2 = `seed.github.repos[${i}]`;
40362
40362
  if (repoNames.has(r2.name.toLowerCase())) issues.push({ path: `${p2}.name`, message: `duplicate repo name "${r2.name}" (case-insensitive)` });
40363
40363
  repoNames.add(r2.name.toLowerCase());
@@ -40983,6 +40983,7 @@ var init_test_file = __esm({
40983
40983
  };
40984
40984
  TestFileSchema = external_exports.strictObject({
40985
40985
  ...fields2,
40986
+ function_tools: SceneSchema.shape.tools,
40986
40987
  world: external_exports.union([WorldId, external_exports.record(external_exports.string(), external_exports.unknown())], { error: WORLD_ERROR }),
40987
40988
  until: external_exports.unknown().optional(),
40988
40989
  checks: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())).optional(),
@@ -40990,6 +40991,7 @@ var init_test_file = __esm({
40990
40991
  });
40991
40992
  TestFileDocument = external_exports.strictObject({
40992
40993
  ...fields2,
40994
+ function_tools: SceneSchema.shape.tools,
40993
40995
  world: external_exports.union([WorldId, WorldBodySchema]).describe("A world file's id (ancha/worlds/<id>.yaml), or the world inline"),
40994
40996
  until: SceneSchema.shape.until,
40995
40997
  checks: SceneSchema.shape.checks.optional(),
@@ -42050,6 +42052,53 @@ var init_tool_completion = __esm({
42050
42052
  }
42051
42053
  });
42052
42054
 
42055
+ // packages/core/src/function-tool-observation.ts
42056
+ function requiredFunctionTools(scene2) {
42057
+ const names5 = Object.keys(scene2.tools ?? {}).filter((name5) => !scene2.tools[name5].mcp);
42058
+ const patterns = [];
42059
+ const visit4 = (value4) => {
42060
+ if (!value4 || typeof value4 !== "object") return;
42061
+ for (const [key4, item2] of Object.entries(value4)) {
42062
+ if (key4 === "called" || key4 === "not_called") patterns.push(...(Array.isArray(item2) ? item2 : [item2]).filter((p2) => typeof p2 === "string"));
42063
+ else visit4(item2);
42064
+ }
42065
+ };
42066
+ for (const check3 of scene2.checks) if (scene2.pass.includes(check3.id)) visit4(check3);
42067
+ return names5.filter((name5) => patterns.some((pattern) => {
42068
+ const p2 = pattern.trim();
42069
+ const bare = /^([A-Za-z_][\w.-]{0,127})(?:\s+\{.*\})?$/s.exec(p2);
42070
+ const [method2, path6] = p2.split(/\s+/);
42071
+ return p2 === "*" || bare?.[1] === name5 || (method2 === "POST" || method2 === "*") && (path6 === `/tools/${name5}` || path6 === "/tools/*");
42072
+ })).sort();
42073
+ }
42074
+ function functionWiringMessage(missing7) {
42075
+ return `Connect function tools: ${missing7.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.`;
42076
+ }
42077
+ function functionToolWiringIssues(observation) {
42078
+ return observation.missing.length ? [{ kind: "tools", owner: "harness", service: "tools", message: functionWiringMessage(observation.missing) }] : [];
42079
+ }
42080
+ var functionToolObservationSchema;
42081
+ var init_function_tool_observation = __esm({
42082
+ "packages/core/src/function-tool-observation.ts"() {
42083
+ "use strict";
42084
+ init_zod();
42085
+ functionToolObservationSchema = external_exports.strictObject({
42086
+ registered: external_exports.array(external_exports.string()),
42087
+ complete: external_exports.boolean(),
42088
+ protocol_version: external_exports.number().int().nonnegative().optional(),
42089
+ required: external_exports.array(external_exports.string()),
42090
+ missing: external_exports.array(external_exports.string()),
42091
+ tools: external_exports.array(external_exports.strictObject({
42092
+ name: external_exports.string(),
42093
+ registered: external_exports.boolean(),
42094
+ called: external_exports.number().int().nonnegative(),
42095
+ completed: external_exports.number().int().nonnegative(),
42096
+ pending: external_exports.number().int().nonnegative()
42097
+ }))
42098
+ });
42099
+ }
42100
+ });
42101
+
42053
42102
  // packages/core/src/index.ts
42054
42103
  var init_src = __esm({
42055
42104
  "packages/core/src/index.ts"() {
@@ -42126,6 +42175,7 @@ var init_src = __esm({
42126
42175
  init_carrier_portal();
42127
42176
  init_tool_call_trace();
42128
42177
  init_tool_completion();
42178
+ init_function_tool_observation();
42129
42179
  }
42130
42180
  });
42131
42181
 
@@ -42364,7 +42414,7 @@ function validateEndpointAgent(agent, parallel) {
42364
42414
  }
42365
42415
  if (agent.slackTransport === "socket") throw new AnchaError("CONFIG_INVALID", "endpoint mode cannot use slack_transport: socket; run a Socket bot with agent.command");
42366
42416
  if (agent.start !== void 0 && agent.setupUrl !== void 0) throw new AnchaError("CONFIG_INVALID", "agent.start conflicts with agent.setup_url");
42367
- if (agent.start !== void 0 && agent.readyUrl === void 0) throw new AnchaError("CONFIG_INVALID", "agent.ready_url is required with agent.start");
42417
+ 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");
42368
42418
  if (agent.start === void 0 && agent.setupUrl === void 0) throw new AnchaError("CONFIG_INVALID", "agent.setup_url is required for an external endpoint");
42369
42419
  const vars = { ...URL_TEMPLATE_VARS, ...agent.start !== void 0 && { "agent.port": "34567" } };
42370
42420
  const url4 = renderAgentUrl(agent.url, { ...vars, service: "slack" });
@@ -42372,7 +42422,7 @@ function validateEndpointAgent(agent, parallel) {
42372
42422
  if (agent.setupUrl !== void 0) renderAgentUrl(agent.setupUrl, vars);
42373
42423
  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");
42374
42424
  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");
42375
- if (parallel > 1 && (agent.start === void 0 || !hasDynamicPort(agent.url, { ...vars, service: "slack" }) || agent.readyUrl === void 0 || !hasDynamicPort(agent.readyUrl, vars))) {
42425
+ if (parallel > 1 && (agent.start === void 0 || !hasDynamicPort(agent.url, { ...vars, service: "slack" }) || (agent.readyUrl === void 0 ? agent.slackTransport !== "http" : !hasDynamicPort(agent.readyUrl, vars)))) {
42376
42426
  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" });
42377
42427
  }
42378
42428
  }
@@ -42463,11 +42513,44 @@ var init_agent_input = __esm({
42463
42513
  }
42464
42514
  });
42465
42515
 
42516
+ // cloud/shared/run-metadata.mjs
42517
+ function runNumberOf(value4) {
42518
+ return Number.isSafeInteger(value4) && value4 > 0 ? value4 : void 0;
42519
+ }
42520
+ function github2(value4) {
42521
+ if (!value4 || typeof value4 !== "object" || Array.isArray(value4) || Object.keys(value4).sort().join(",") !== "repository,runId,serverUrl") throw new Error("Invalid GitHub Actions context.");
42522
+ const { repository: repository3, runId, serverUrl: serverUrl2 } = value4;
42523
+ if (typeof repository3 !== "string" || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository3) || repository3.length > 201 || repository3.split("/").some((p2) => p2 === "." || p2 === "..") || typeof runId !== "string" || !/^[1-9]\d{0,19}$/.test(runId)) throw new Error("Invalid GitHub Actions context.");
42524
+ let url4;
42525
+ try {
42526
+ url4 = new URL(serverUrl2);
42527
+ } catch {
42528
+ throw new Error("Invalid GitHub Actions server.");
42529
+ }
42530
+ if (typeof serverUrl2 !== "string" || serverUrl2.length > 2048 || url4.protocol !== "https:" || url4.username || url4.password || url4.search || url4.hash || url4.pathname !== "/") throw new Error("Invalid GitHub Actions server.");
42531
+ return { repository: repository3, runId, serverUrl: url4.origin };
42532
+ }
42533
+ function runContextHeader(env) {
42534
+ if (env.GITHUB_ACTIONS !== "true") return {};
42535
+ try {
42536
+ const context3 = github2({ repository: env.GITHUB_REPOSITORY, runId: env.GITHUB_RUN_ID, serverUrl: env.GITHUB_SERVER_URL });
42537
+ return { "x-ancha-run-context": JSON.stringify(context3) };
42538
+ } catch {
42539
+ return {};
42540
+ }
42541
+ }
42542
+ var init_run_metadata = __esm({
42543
+ "cloud/shared/run-metadata.mjs"() {
42544
+ "use strict";
42545
+ }
42546
+ });
42547
+
42466
42548
  // cloud/shared/jobs-contract.mjs
42467
42549
  var UUID, RUN_CLOUD_ID, CONNECT_CLOUD_ID, VIEW_CLOUD_ID, ATTEMPT_CLOUD_ID, AGENT_CLOUD_ID, MIB, BUNDLE_LIMITS, ARTIFACT_LIMITS, CLOUD_MODEL_HOSTS, DEFAULT_MODEL_HOSTS, AGENT_UID, JOB_FIELDS, ATTEMPT_FIELDS, BODY_FIELDS;
42468
42550
  var init_jobs_contract = __esm({
42469
42551
  "cloud/shared/jobs-contract.mjs"() {
42470
42552
  "use strict";
42553
+ init_run_metadata();
42471
42554
  UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
42472
42555
  RUN_CLOUD_ID = new RegExp(`^run_cloud_${UUID}$`);
42473
42556
  CONNECT_CLOUD_ID = new RegExp(`^connect_cloud_${UUID}$`);
@@ -42588,6 +42671,7 @@ async function startIsolationGateway(options4) {
42588
42671
  if (upstream.pathname !== path6 || upstream.search || upstream.hash) throw new Error("Invalid trial session route");
42589
42672
  sessionRoutes2.set(path6, { method: method2, upstream });
42590
42673
  }
42674
+ const socketGrants = /* @__PURE__ */ new Map();
42591
42675
  const modelHosts = new Set((options4.modelHosts ?? []).map(normalizeModelHost));
42592
42676
  const sockets = /* @__PURE__ */ new Set();
42593
42677
  const upstreamRequests = /* @__PURE__ */ new Set();
@@ -42645,7 +42729,9 @@ async function startIsolationGateway(options4) {
42645
42729
  upstream = route12.upstream;
42646
42730
  if (path6 === "/_ancha/context") transform3 = "context";
42647
42731
  }
42648
- if (req.method === "CONNECT" || req.method === "TRACE" || req.headers.upgrade || path6.endsWith("/apps.connections.open")) return reject2(res, 501, "This transport is not qualified for contained execution.");
42732
+ const socketOpen = decodeURIComponent(path6) === `/e/${env.id}/slack/api/apps.connections.open`;
42733
+ if (req.method === "CONNECT" || req.method === "TRACE" || req.headers.upgrade || decodeURIComponent(path6).endsWith("/apps.connections.open") && !(socketOpen && options4.slackSocket && session2)) return reject2(res, 501, "This transport is not qualified for contained execution.");
42734
+ if (socketOpen && options4.slackSocket && session2) transform3 = "socket";
42649
42735
  const headers = cleanHeaders(req.headers);
42650
42736
  headers.host = modelHost ?? new URL(exposedOrigin ?? upstream.origin).host;
42651
42737
  delete headers["x-ancha-client-origin"];
@@ -42717,6 +42803,15 @@ async function startIsolationGateway(options4) {
42717
42803
  const connection4 = mapped(exposedOrigin ?? "");
42718
42804
  value4 = { ...value4, env: connection4.env, session: connection4.session };
42719
42805
  }
42806
+ if (transform3 === "socket" && reply5.statusCode === 200 && value4?.ok === true) {
42807
+ const grant = new URL(value4.url);
42808
+ const expected = loopbackOrigin(session2.eventsUrl);
42809
+ 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");
42810
+ for (const [path7, old] of socketGrants) if (old.expires <= Date.now()) socketGrants.delete(path7);
42811
+ if (socketGrants.size >= 128) throw new Error("Too many socket grants");
42812
+ socketGrants.set(grant.pathname, { url: grant, expires: Date.now() + 3e4 });
42813
+ value4 = { ...value4, url: (exposedOrigin ?? "").replace(/^http:/, "ws:") + grant.pathname };
42814
+ }
42720
42815
  const body6 = JSON.stringify(value4);
42721
42816
  delete responseHeaders["content-encoding"];
42722
42817
  delete responseHeaders["content-length"];
@@ -42757,7 +42852,52 @@ async function startIsolationGateway(options4) {
42757
42852
  });
42758
42853
  });
42759
42854
  server.on("clientError", (_error, socket) => socket.destroy());
42760
- server.on("upgrade", (_req, socket) => socket.end("HTTP/1.1 501 Not Implemented\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"));
42855
+ server.on("upgrade", (req, socket, head) => {
42856
+ const denied = () => {
42857
+ socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", () => socket.destroy());
42858
+ };
42859
+ const grant = socketGrants.get(req.url ?? "");
42860
+ if (closed || !options4.slackSocket || !grant || grant.expires <= Date.now() || req.method !== "GET" || req.headers.upgrade?.toLowerCase() !== "websocket") {
42861
+ denied();
42862
+ return;
42863
+ }
42864
+ socketGrants.delete(req.url);
42865
+ const headers = { host: grant.url.host, connection: "Upgrade", upgrade: "websocket" };
42866
+ 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];
42867
+ const target4 = request({ hostname: grant.url.hostname, port: grant.url.port || 80, path: grant.url.pathname, headers, agent: false });
42868
+ upstreamRequests.add(target4);
42869
+ target4.once("close", () => upstreamRequests.delete(target4));
42870
+ target4.once("error", () => socket.destroy());
42871
+ target4.once("response", (reply5) => {
42872
+ reply5.destroy();
42873
+ denied();
42874
+ });
42875
+ target4.setTimeout(1e4, () => target4.destroy());
42876
+ socket.once("close", () => target4.destroy());
42877
+ target4.once("upgrade", (reply5, peer, upstreamHead) => {
42878
+ target4.setTimeout(0);
42879
+ if (closed || socket.destroyed) {
42880
+ peer.destroy();
42881
+ return;
42882
+ }
42883
+ sockets.add(peer);
42884
+ peer.once("close", () => {
42885
+ sockets.delete(peer);
42886
+ socket.destroy();
42887
+ });
42888
+ peer.on("error", () => socket.destroy());
42889
+ socket.once("close", () => peer.destroy());
42890
+ socket.write(`HTTP/1.1 101 Switching Protocols\r
42891
+ ${Object.entries(reply5.headers).map(([name5, value4]) => `${name5}: ${value4}`).join("\r\n")}\r
42892
+ \r
42893
+ `);
42894
+ if (upstreamHead.length) socket.write(upstreamHead);
42895
+ if (head.length) peer.write(head);
42896
+ socket.pipe(peer);
42897
+ peer.pipe(socket);
42898
+ });
42899
+ target4.end();
42900
+ });
42761
42901
  server.on("connect", (_req, client2) => client2.end("HTTP/1.1 403 Rejected\r\nConnection: close\r\nContent-Length: 0\r\n\r\n"));
42762
42902
  await new Promise((resolve14, rejectListen) => {
42763
42903
  server.once("error", rejectListen);
@@ -42773,6 +42913,7 @@ async function startIsolationGateway(options4) {
42773
42913
  let closing;
42774
42914
  const close = () => closing ??= (async () => {
42775
42915
  closed = true;
42916
+ socketGrants.clear();
42776
42917
  options4.signal?.removeEventListener("abort", abort);
42777
42918
  for (const target4 of upstreamRequests) target4.destroy();
42778
42919
  for (const socket of sockets) socket.destroy();
@@ -43513,7 +43654,7 @@ function renderSummaryText(s2, opts = {}) {
43513
43654
  if (s2.comparison !== void 0) lines.push(...comparisonLines(s2.comparison));
43514
43655
  if ((opts.reproduction ?? []).length > 0) lines.push(renderReproduction(opts.reproduction, { neverRan: never2 !== void 0 }), "");
43515
43656
  const noneGraded = s2.scenes.length > 0 && s2.scenes.every((scene2) => scene2.trials > 0 && (scene2.invalidTrials ?? 0) >= scene2.trials);
43516
- lines.push(`${s2.pytest && !s2.pytest.graded && !s2.pytest.invalid ? s2.pytest.outcome + " (ungraded)" : noneGraded ? "invalid (no trials graded)" : s2.verdict} (minimum pass rate ${pct(s2.minPassRate)}%) run ${s2.runId}`);
43657
+ lines.push(`${s2.pytest && !s2.pytest.graded && !s2.pytest.invalid ? s2.pytest.outcome + " (ungraded)" : noneGraded ? "invalid (no trials graded)" : s2.verdict} (minimum pass rate ${pct(s2.minPassRate)}%) run ${s2.runNumber ? `#${s2.runNumber}` : s2.runId}`);
43517
43658
  const next2 = nextAfterRun(s2, opts);
43518
43659
  if (never2 !== void 0) lines.push(neverRanNextLine(never2, next2));
43519
43660
  else if (next2.length > 0) lines.push(`next: ${next2.join(", then ")}`);
@@ -62189,9 +62330,9 @@ function personAccounts(env, person4) {
62189
62330
  const row2 = env.store.db.prepare("SELECT id FROM slack_users WHERE ref = ?").get(slack2);
62190
62331
  if (row2) out.slack = row2.id;
62191
62332
  }
62192
- const github2 = person4.accounts.github === void 0 ? void 0 : refName6(person4.accounts.github);
62193
- if (github2 !== void 0 && hasTable3(env, "github_users")) {
62194
- const row2 = env.store.db.prepare("SELECT id, login FROM github_users WHERE ref = ?").get(github2);
62333
+ const github3 = person4.accounts.github === void 0 ? void 0 : refName6(person4.accounts.github);
62334
+ if (github3 !== void 0 && hasTable3(env, "github_users")) {
62335
+ const row2 = env.store.db.prepare("SELECT id, login FROM github_users WHERE ref = ?").get(github3);
62195
62336
  if (row2) out.github = { id: String(row2.id), login: row2.login };
62196
62337
  }
62197
62338
  if (person4.accounts.gmail !== void 0 && hasTable3(env, "gmail_mailboxes")) {
@@ -64005,15 +64146,15 @@ function botUser(ctx) {
64005
64146
  return user8;
64006
64147
  }
64007
64148
  function seed2(ctx) {
64008
- const github2 = ctx.scene.seed.github;
64009
- if (!github2) throw new AnchaError("SCENE_INVALID", "seed.github: required when twins includes github");
64149
+ const github3 = ctx.scene.seed.github;
64150
+ if (!github3) throw new AnchaError("SCENE_INVALID", "seed.github: required when twins includes github");
64010
64151
  ctx.store.db.transaction(() => {
64011
64152
  const insertUser2 = (ref22, login2, name5, email11, bot2) => {
64012
64153
  const id14 = resourceId(ctx);
64013
64154
  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);
64014
64155
  return id14;
64015
64156
  };
64016
- for (const u of github2.users ?? []) {
64157
+ for (const u of github3.users ?? []) {
64017
64158
  const id14 = insertUser2(u.ref, u.login, u.name ?? u.login, u.email, false);
64018
64159
  ctx.refs.register(u.ref, "user", "github", String(id14));
64019
64160
  }
@@ -64022,20 +64163,20 @@ function seed2(ctx) {
64022
64163
  insertUser2(u.ref, login2, u.real_name ?? u.name, u.email, u.is_bot ?? false);
64023
64164
  }
64024
64165
  let botId2;
64025
- if (github2.bot) botId2 = userForRef(ctx, github2.bot).id;
64166
+ if (github3.bot) botId2 = userForRef(ctx, github3.bot).id;
64026
64167
  else {
64027
64168
  const login2 = derivedLogin(ctx, "ancha-bot");
64028
64169
  botId2 = insertUser2(null, login2, "Ancha Bot", void 0, true);
64029
64170
  }
64030
64171
  ctx.store.meta.set("github:bot-user", String(botId2));
64031
64172
  const bot = botUser(ctx), at3 = ctx.clock.now().toISOString();
64032
- for (const org5 of github2.orgs ?? []) {
64173
+ for (const org5 of github3.orgs ?? []) {
64033
64174
  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`);
64034
64175
  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);
64035
64176
  const orgId = ctx.store.db.prepare("SELECT id FROM github_organizations WHERE login = ?").get(org5.login).id;
64036
64177
  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);
64037
64178
  }
64038
- for (const repo4 of github2.repos) {
64179
+ for (const repo4 of github3.repos) {
64039
64180
  const [owner3, name5] = repo4.name.split("/"), numbers2 = githubSeedNumbers(repo4);
64040
64181
  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)) {
64041
64182
  ctx.store.db.prepare("INSERT INTO github_organizations (id,login) VALUES (?,?)").run(resourceId(ctx), owner3);
@@ -71506,7 +71647,7 @@ function socketPost(socketPath) {
71506
71647
  function httpPeopleModel(options4) {
71507
71648
  const models = options4.models ?? DEFAULT_PEOPLE_MODELS;
71508
71649
  const post4 = options4.post ?? (options4.socketPath !== void 0 ? socketPost(options4.socketPath) : fetchPost);
71509
- const sleep9 = options4.sleep ?? defaultSleep;
71650
+ const sleep10 = options4.sleep ?? defaultSleep;
71510
71651
  const url4 = `${options4.baseUrl.replace(/\/+$/, "")}/chat/completions`;
71511
71652
  return {
71512
71653
  async complete(request2, signal) {
@@ -71533,7 +71674,7 @@ function httpPeopleModel(options4) {
71533
71674
  } catch (error64) {
71534
71675
  if (signal.aborted) throw error64;
71535
71676
  if (!options4.relay && options4.socketPath === void 0 && attempt < MAX_RETRIES) {
71536
- await sleep9(1e3 * (attempt + 1), signal);
71677
+ await sleep10(1e3 * (attempt + 1), signal);
71537
71678
  continue;
71538
71679
  }
71539
71680
  if (options4.relay || options4.socketPath !== void 0) {
@@ -71543,7 +71684,7 @@ function httpPeopleModel(options4) {
71543
71684
  }
71544
71685
  if ((response5.status === 429 || response5.status === 503 && response5.headers["retry-after"] !== void 0) && attempt < MAX_RETRIES) {
71545
71686
  const after = Number(response5.headers["retry-after"]);
71546
- await sleep9(Math.min(MAX_RETRY_WAIT_MS, Number.isFinite(after) && after > 0 ? after * 1e3 : 2e3 * (attempt + 1)), signal);
71687
+ await sleep10(Math.min(MAX_RETRY_WAIT_MS, Number.isFinite(after) && after > 0 ? after * 1e3 : 2e3 * (attempt + 1)), signal);
71547
71688
  continue;
71548
71689
  }
71549
71690
  let json33;
@@ -72226,8 +72367,8 @@ var init_engine = __esm({
72226
72367
  return;
72227
72368
  }
72228
72369
  const [repoId, number7] = place2.slice("github:".length).split("#").map(Number);
72229
- const github2 = this.#everyone().find((entry2) => entry2.person.ref === ref22)?.accounts.github;
72230
- const merged = mergePull(env.ctxFor("github"), repoId, number7, {}, github2 === void 0 ? void 0 : Number(github2.id));
72370
+ const github3 = this.#everyone().find((entry2) => entry2.person.ref === ref22)?.accounts.github;
72371
+ const merged = mergePull(env.ctxFor("github"), repoId, number7, {}, github3 === void 0 ? void 0 : Number(github3.id));
72231
72372
  env.trace.record({ source: "world", service: "github", method: "ACTION", path: "people.merge", request: { person: ref22, repo: repoId, number: number7 }, response: { sha: merged.sha } });
72232
72373
  });
72233
72374
  return;
@@ -73294,6 +73435,13 @@ function decide(ctx, name5, args) {
73294
73435
  ctx.store.db.prepare("INSERT INTO agent_tool_calls (key, n) VALUES (?, 1) ON CONFLICT(key) DO UPDATE SET n=n+1").run(callKey);
73295
73436
  const policy = tool?.unrecorded ?? (tool?.write ? "fail" : "simulate");
73296
73437
  const reached = Number(getState(ctx, "reached") ?? 0);
73438
+ let selected2 = Math.min(n2, same3.length - 1);
73439
+ for (let i = same3.length - 1; i > selected2; i--) if (same3[i].atMs <= reached) {
73440
+ selected2 = i;
73441
+ break;
73442
+ }
73443
+ const observation = same3[selected2];
73444
+ 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.` };
73297
73445
  const simulationKey = `${callKey} revision:${getState(ctx, "revision") ?? "0"}${tool?.schema ? ` schema:${schemaFingerprint(tool.schema)}` : ""}`;
73298
73446
  if (policy === "run" && (tool?.write || getState(ctx, "run:changed") !== void 0 || n2 >= same3.length || same3[n2].atMs >= productionFirstWrite(ctx))) {
73299
73447
  if (tool?.write) {
@@ -73309,14 +73457,14 @@ function decide(ctx, name5, args) {
73309
73457
  index = i;
73310
73458
  break;
73311
73459
  }
73312
- const observation = n2 < same3.length ? same3[index] : void 0;
73313
- if (tool.write && observation?.error !== void 0) {
73314
- setState(ctx, "reached", String(Math.max(reached, observation.endMs)));
73315
- return { source: "replayed", error: observation.error, ...observation.raw !== void 0 && { raw: observation.raw, wrap: observation.wrap } };
73460
+ const observation2 = n2 < same3.length ? same3[index] : void 0;
73461
+ if (tool.write && observation2?.error !== void 0) {
73462
+ setState(ctx, "reached", String(Math.max(reached, observation2.endMs)));
73463
+ return { source: "replayed", error: observation2.error, ...observation2.raw !== void 0 && { raw: observation2.raw, wrap: observation2.wrap } };
73316
73464
  }
73317
- if (observation) setState(ctx, "reached", String(Math.max(reached, observation.endMs)));
73465
+ if (observation2) setState(ctx, "reached", String(Math.max(reached, observation2.endMs)));
73318
73466
  if (tool.write) setState(ctx, `twin:dirty:${linked2}`, "1");
73319
- return { source: "twin", passthrough: true, ...observation && { recording: observation } };
73467
+ return { source: "twin", passthrough: true, ...observation2 && { recording: observation2 } };
73320
73468
  }
73321
73469
  const cached3 = getState(ctx, `sim:${simulationKey}`);
73322
73470
  if (cached3 !== void 0) {
@@ -73369,7 +73517,28 @@ function noteCall(ctx, name5, args, a) {
73369
73517
  setState(ctx, "calls", JSON.stringify(calls2.slice(-50)));
73370
73518
  }
73371
73519
  function toolsToWrap(ctx) {
73372
- return Object.entries(ctx.scene.tools ?? {}).filter(([, t]) => !t.mcp && (!t.pure || t.twin !== void 0) && !t.allow_unwrapped).map(([name5]) => name5).sort();
73520
+ 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();
73521
+ }
73522
+ function functionToolObservation(ctx) {
73523
+ const registered = JSON.parse(getState(ctx, "wrapped") ?? "[]");
73524
+ const required4 = toolsToWrap(ctx), calls2 = projectToolCalls(ctx.trace.list()).filter((e) => e.source === "agent" && e.service === "tools" && e.path.startsWith("/tools/"));
73525
+ const protocol = getState(ctx, "protocol");
73526
+ return {
73527
+ registered,
73528
+ complete: getState(ctx, "complete") === "1",
73529
+ ...protocol !== void 0 && { protocol_version: Number(protocol) },
73530
+ required: required4,
73531
+ missing: required4.filter((name5) => !registered.includes(name5)),
73532
+ tools: [.../* @__PURE__ */ new Set([...Object.keys(ctx.scene.tools ?? {}), ...registered])].sort().map((name5) => {
73533
+ const own2 = calls2.filter((e) => decodeURIComponent(e.path.slice("/tools/".length)) === name5);
73534
+ const pending = own2.filter((e) => e.response?.execution_status === "unknown").length;
73535
+ const completed = own2.filter((e) => {
73536
+ const r2 = e.response;
73537
+ 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);
73538
+ }).length;
73539
+ return { name: name5, registered: registered.includes(name5), called: own2.length, completed, pending };
73540
+ })
73541
+ };
73373
73542
  }
73374
73543
  function registration(ctx, names5) {
73375
73544
  const before = JSON.parse(getState(ctx, "wrapped") ?? "[]");
@@ -73402,7 +73571,7 @@ function agentToolsService() {
73402
73571
  ...t?.twin && { twin: t.twin },
73403
73572
  ...t?.write && { write: true }
73404
73573
  };
73405
- }), wrap: toolsToWrap(ctx) });
73574
+ }), wrap: toolsToWrap(ctx), observation: functionToolObservation(ctx) });
73406
73575
  }));
73407
73576
  app2.post("/register", bodyLimit({
73408
73577
  maxSize: TOOL_REGISTRATION_BYTES,
@@ -73426,11 +73595,15 @@ function agentToolsService() {
73426
73595
  }
73427
73596
  for (const d of definitions3.values()) setState(c.env.ctx, `definition:${d.name}`, JSON.stringify(d));
73428
73597
  const result = registration(c.env.ctx, [...definitions3.keys()]);
73429
- if (body6.complete) setState(c.env.ctx, "checked", "1");
73598
+ if (body6.protocol_version !== void 0) setState(c.env.ctx, "protocol", String(Math.min(body6.protocol_version, AGENT_TOOLS_PROTOCOL_VERSION)));
73599
+ if (body6.complete && !result.missing.length) {
73600
+ setState(c.env.ctx, "complete", "1");
73601
+ setState(c.env.ctx, "checked", "1");
73602
+ }
73430
73603
  return result;
73431
73604
  });
73432
73605
  const protocol_version = AGENT_TOOLS_PROTOCOL_VERSION;
73433
- if (body6.complete && missing7.length) return c.json({ protocol_version, error: unwrappedMessage(missing7, wrapped.length === 0), wrapped, missing: missing7, stop: true }, 409, { [SETUP_ISSUE_HEADER]: "1" });
73606
+ if (body6.complete && missing7.length) return c.json({ protocol_version, error: requiredFunctionTools(c.env.ctx.scene).some((name5) => missing7.includes(name5)) ? functionWiringMessage(missing7) : unwrappedMessage(missing7, wrapped.length === 0), wrapped, missing: missing7, stop: true }, 409, { [SETUP_ISSUE_HEADER]: "1" });
73434
73607
  return c.json({ protocol_version, wrapped, missing: missing7 });
73435
73608
  } catch (error64) {
73436
73609
  const message7 = error64 instanceof Error ? error64.message : String(error64);
@@ -73482,9 +73655,9 @@ function agentToolsService() {
73482
73655
  const body6 = await c.req.json().catch(() => ({}));
73483
73656
  const stop = withMutation(c.env.ctx, () => {
73484
73657
  if (getState(c.env.ctx, "checked")) return void 0;
73485
- setState(c.env.ctx, "checked", "1");
73486
73658
  const { wrapped, missing: missing7 } = registration(c.env.ctx, []);
73487
- return missing7.length ? { error: unwrappedMessage(missing7, wrapped.length === 0), wrapped, missing: missing7, stop: true } : void 0;
73659
+ if (!missing7.length) setState(c.env.ctx, "checked", "1");
73660
+ return missing7.length ? { error: requiredFunctionTools(c.env.ctx.scene).some((name6) => missing7.includes(name6)) ? functionWiringMessage(missing7) : unwrappedMessage(missing7, wrapped.length === 0), wrapped, missing: missing7, stop: true } : void 0;
73488
73661
  });
73489
73662
  if (stop) return c.json(stop, 409, { [SETUP_ISSUE_HEADER]: "1" });
73490
73663
  const ctx = c.env.ctx, args = body6.args ?? {};
@@ -73538,7 +73711,7 @@ function agentToolsService() {
73538
73711
  credentials: (ctx) => ({ token: `ancha-tools-${ctx.secrets.hex(32)}` }),
73539
73712
  actions: {},
73540
73713
  checks: {},
73541
- 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() }),
73714
+ 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() }),
73542
73715
  coverage: []
73543
73716
  };
73544
73717
  }
@@ -73598,6 +73771,8 @@ var init_env = __esm({
73598
73771
  init_engine();
73599
73772
  init_world_snapshot();
73600
73773
  init_agent_tools();
73774
+ init_src();
73775
+ init_agent_tools();
73601
73776
  agentTools = agentToolsService();
73602
73777
  ENV_ID_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789";
73603
73778
  credentialsKey = (twin) => `credentials:${twin}`;
@@ -74082,7 +74257,7 @@ var init_env = __esm({
74082
74257
  trace,
74083
74258
  state: state3,
74084
74259
  simMs: this.clock.elapsedMs(),
74085
- harnessIssues: collectHarnessIssues(trace, checks2),
74260
+ harnessIssues: [...collectHarnessIssues(trace, checks2), ...Object.keys(this.scene.tools ?? {}).length > 0 ? functionToolWiringIssues(functionToolObservation(this.ctxFor("tools"))) : []],
74086
74261
  ...people3.length && { people: people3 },
74087
74262
  ...replay && { peopleReplay: { replayed: replay.replayed, live: replay.live, divergence: replay.divergence ?? null } },
74088
74263
  ...explanations.length && { explanations },
@@ -151052,9 +151227,9 @@ var init_routes19 = __esm({
151052
151227
  path: "/user/assignable/search",
151053
151228
  coverage: { status: "supported" },
151054
151229
  run: (r2) => {
151055
- const projectKey3 = r2.query.get("project"), issueKey = r2.query.get("issueKey");
151056
- if (!projectKey3 && !issueKey && !r2.query.get("issueId")) fail2(400, "One of the following parameters must be provided: issueKey, issueId, project.");
151057
- if (projectKey3 && !projectByKey(r2.ctx, projectKey3)) fail2(404, `No project could be found with key '${projectKey3}'.`);
151230
+ const projectKey2 = r2.query.get("project"), issueKey = r2.query.get("issueKey");
151231
+ if (!projectKey2 && !issueKey && !r2.query.get("issueId")) fail2(400, "One of the following parameters must be provided: issueKey, issueId, project.");
151232
+ if (projectKey2 && !projectByKey(r2.ctx, projectKey2)) fail2(404, `No project could be found with key '${projectKey2}'.`);
151058
151233
  if ((issueKey || r2.query.get("issueId")) && !issueByKey(r2.ctx, issueKey ?? r2.query.get("issueId"))) issueNotFound();
151059
151234
  const query10 = r2.query.get("query") ?? r2.query.get("username") ?? "";
151060
151235
  const start2 = Number(r2.query.get("startAt") ?? 0), max = Number(r2.query.get("maxResults") ?? 50);
@@ -176999,6 +177174,9 @@ var init_socket2 = __esm({
176999
177174
  get pendingCount() {
177000
177175
  return this.#pending.size;
177001
177176
  }
177177
+ get connected() {
177178
+ return this.#live() && this.#socket?.readyState === import_websocket.default.OPEN;
177179
+ }
177002
177180
  isCurrent(env) {
177003
177181
  return env === this.#env && this.#live();
177004
177182
  }
@@ -177557,6 +177735,7 @@ var init_sessions = __esm({
177557
177735
  pendingJobs,
177558
177736
  pendingBlockingJobs,
177559
177737
  pendingDeliveries,
177738
+ ...record13.socket && { socketConnected: record13.socket.connected },
177560
177739
  quiet: session2.state === "running" && quietNow(env, record13.busy > 0),
177561
177740
  nextDueMs: nextDue,
177562
177741
  ...untilMs !== void 0 && { untilMs }
@@ -180177,6 +180356,115 @@ var init_run_bundle = __esm({
180177
180356
  }
180178
180357
  });
180179
180358
 
180359
+ // backend/src/runner/slack-app.ts
180360
+ import { createHmac as createHmac9 } from "node:crypto";
180361
+ import { setTimeout as sleep2 } from "node:timers/promises";
180362
+ function assertVmEndpoint(agent) {
180363
+ 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.';
180364
+ 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 });
180365
+ for (const template3 of [agent.url, agent.readyUrl, agent.setupUrl]) {
180366
+ if (template3 === void 0) continue;
180367
+ const url4 = new URL(renderAgentUrl(template3, { "agent.port": "34567", "env.id": "attempt", service: "slack" }));
180368
+ if (url4.protocol !== "http:" || !["localhost", "127.0.0.1", "[::1]"].includes(url4.hostname)) {
180369
+ 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 });
180370
+ }
180371
+ }
180372
+ }
180373
+ function managedAppPort(template3, reserved, vars) {
180374
+ if (usesPort(template3)) return reserved;
180375
+ const url4 = new URL(renderAgentUrl(template3, { ...vars, service: "slack" }));
180376
+ return Number(url4.port) || (url4.protocol === "https:" ? 443 : 80);
180377
+ }
180378
+ async function waitSlackSocket(backend, envId, sessionId, child2, signal) {
180379
+ const stopped = new AbortController();
180380
+ void child2.exited.then(() => stopped.abort(), () => stopped.abort());
180381
+ const combined = AbortSignal.any([signal, stopped.signal]);
180382
+ try {
180383
+ for (; ; ) {
180384
+ combined.throwIfAborted();
180385
+ let cancel3;
180386
+ const aborted2 = new Promise((_, reject3) => {
180387
+ cancel3 = () => reject3(combined.reason);
180388
+ combined.addEventListener("abort", cancel3, { once: true });
180389
+ if (combined.aborted) cancel3();
180390
+ });
180391
+ try {
180392
+ if ((await Promise.race([backend.trialStatus(envId, sessionId), aborted2])).socketConnected === true) {
180393
+ combined.throwIfAborted();
180394
+ return;
180395
+ }
180396
+ } finally {
180397
+ combined.removeEventListener("abort", cancel3);
180398
+ }
180399
+ await sleep2(25, void 0, { signal: combined });
180400
+ }
180401
+ } catch (cause) {
180402
+ throw new AnchaError("AGENT_UNREACHABLE", "The Slack app did not open its Socket Mode connection.", { hint: slackSocketFix, cause });
180403
+ }
180404
+ }
180405
+ async function waitSlackHttp(url4, secret, sessionId, signal) {
180406
+ const challenge = createHmac9("sha256", secret).update(`readiness:${sessionId}`).digest("hex");
180407
+ const body6 = JSON.stringify({ type: "url_verification", challenge });
180408
+ try {
180409
+ for (; ; ) {
180410
+ signal.throwIfAborted();
180411
+ try {
180412
+ const timestamp4 = String(Math.floor(Date.now() / 1e3));
180413
+ const signature2 = "v0=" + createHmac9("sha256", secret).update(`v0:${timestamp4}:${body6}`).digest("hex");
180414
+ const response5 = await fetch(url4, {
180415
+ method: "POST",
180416
+ body: body6,
180417
+ redirect: "manual",
180418
+ signal: AbortSignal.any([signal, AbortSignal.timeout(500)]),
180419
+ headers: { "content-type": "application/json", "x-slack-request-timestamp": timestamp4, "x-slack-signature": signature2 }
180420
+ });
180421
+ const reader = response5.body?.getReader();
180422
+ const chunks = [];
180423
+ let bytes2 = 0;
180424
+ if (reader) try {
180425
+ for (; ; ) {
180426
+ const { value: value4, done } = await reader.read();
180427
+ if (done) break;
180428
+ bytes2 += value4.length;
180429
+ if (bytes2 > 65536) {
180430
+ await reader.cancel();
180431
+ throw new Error("readiness response too large");
180432
+ }
180433
+ chunks.push(value4);
180434
+ }
180435
+ } finally {
180436
+ reader.releaseLock();
180437
+ }
180438
+ const text25 = Buffer.concat(chunks).toString("utf8");
180439
+ let matches9 = text25 === challenge || new URLSearchParams(text25).get("challenge") === challenge;
180440
+ try {
180441
+ matches9 ||= JSON.parse(text25)?.challenge === challenge;
180442
+ } catch {
180443
+ }
180444
+ if (response5.ok && matches9) {
180445
+ signal.throwIfAborted();
180446
+ return;
180447
+ }
180448
+ } catch {
180449
+ signal.throwIfAborted();
180450
+ }
180451
+ await sleep2(25, void 0, { signal });
180452
+ }
180453
+ } catch (cause) {
180454
+ throw new AnchaError("AGENT_UNREACHABLE", "The Slack events URL did not answer its signed verification challenge.", { hint: slackHttpFix, cause });
180455
+ }
180456
+ }
180457
+ var slackSocketFix, slackHttpFix;
180458
+ var init_slack_app = __esm({
180459
+ "backend/src/runner/slack-app.ts"() {
180460
+ "use strict";
180461
+ init_src();
180462
+ init_config();
180463
+ 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.';
180464
+ 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.';
180465
+ }
180466
+ });
180467
+
180180
180468
  // cloud/rebuild/readers/suiteql.mjs
180181
180469
  var init_suiteql2 = __esm({
180182
180470
  "cloud/rebuild/readers/suiteql.mjs"() {
@@ -180595,10 +180883,10 @@ var init_values2 = __esm({
180595
180883
  });
180596
180884
 
180597
180885
  // 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
180598
- var sleep2;
180886
+ var sleep3;
180599
180887
  var init_sleep = __esm({
180600
180888
  "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"() {
180601
- sleep2 = (ms, ...signals) => new Promise((resolve14, reject3) => {
180889
+ sleep3 = (ms, ...signals) => new Promise((resolve14, reject3) => {
180602
180890
  const activeSignals = [...new Set(signals.filter((signal) => signal != null))];
180603
180891
  let timeout;
180604
180892
  let settled = false;
@@ -196608,7 +196896,7 @@ async function pollWithResponse(retrieve, intermediateStatuses, terminalStatuses
196608
196896
  }
196609
196897
  }
196610
196898
  const signal = options4 && Object.prototype.propertyIsEnumerable.call(options4, "signal") ? options4.signal : void 0;
196611
- await (signal ? sleepUntilAborted(sleepInterval, signal) : sleep2(sleepInterval));
196899
+ await (signal ? sleepUntilAborted(sleepInterval, signal) : sleep3(sleepInterval));
196612
196900
  } else if (terminalStatuses.includes(status4)) {
196613
196901
  return data5;
196614
196902
  }
@@ -198880,7 +199168,7 @@ async function waitForFileProcessing(resource2, id14, pollInterval, maxWait) {
198880
199168
  const start2 = performance.now();
198881
199169
  let file3 = await resource2.retrieve(id14);
198882
199170
  while (!file3.status || !terminalStates.has(file3.status)) {
198883
- await sleep2(pollInterval);
199171
+ await sleep3(pollInterval);
198884
199172
  file3 = await resource2.retrieve(id14);
198885
199173
  if (performance.now() - start2 > maxWait) {
198886
199174
  throw new APIConnectionTimeoutError({
@@ -204775,7 +205063,7 @@ var init_client = __esm({
204775
205063
  } else {
204776
205064
  const retrySignals = requestSignal === options4.signal ? [requestSignal] : [requestSignal, options4.signal];
204777
205065
  try {
204778
- await sleep2(timeoutMillis, ...retrySignals);
205066
+ await sleep3(timeoutMillis, ...retrySignals);
204779
205067
  } catch (error64) {
204780
205068
  const abortedSignal = retrySignals.find((signal) => signal?.aborted);
204781
205069
  if (abortedSignal) {
@@ -205487,7 +205775,7 @@ var init_openrouter = __esm({
205487
205775
  });
205488
205776
 
205489
205777
  // backend/src/judge/relay.ts
205490
- import { setTimeout as sleep3 } from "node:timers/promises";
205778
+ import { setTimeout as sleep4 } from "node:timers/promises";
205491
205779
  function relayUrl(relay) {
205492
205780
  try {
205493
205781
  const url4 = new URL(relay.baseUrl);
@@ -205533,7 +205821,7 @@ async function requestRelayGrade(relay, model, rubric, evidence, signal) {
205533
205821
  const response5 = await relayPost(relay, body6, signal ? AbortSignal.any([signal, deadline3]) : deadline3);
205534
205822
  const after = Number(response5.headers["retry-after"]);
205535
205823
  if ((response5.status === 429 || response5.status === 503 && response5.headers["retry-after"] !== void 0) && attempt < RETRIES) {
205536
- await sleep3(Math.min(RETRY_WAIT_MS, response5.headers["retry-after"] !== void 0 && Number.isFinite(after) && after >= 0 ? after * 1e3 : 2e3 * (attempt + 1)), void 0, { signal });
205824
+ await sleep4(Math.min(RETRY_WAIT_MS, response5.headers["retry-after"] !== void 0 && Number.isFinite(after) && after >= 0 ? after * 1e3 : 2e3 * (attempt + 1)), void 0, { signal });
205537
205825
  continue;
205538
205826
  }
205539
205827
  let json33;
@@ -206132,7 +206420,7 @@ import { closeSync as closeSync2, fstatSync as fstatSync2, openSync as openSync2
206132
206420
  import { tmpdir } from "node:os";
206133
206421
  import { join as join9 } from "node:path";
206134
206422
  import { StringDecoder } from "node:string_decoder";
206135
- import { setTimeout as sleep4 } from "node:timers/promises";
206423
+ import { setTimeout as sleep5 } from "node:timers/promises";
206136
206424
  function signalGroup(pid, signal) {
206137
206425
  try {
206138
206426
  process.kill(-pid, signal);
@@ -206235,7 +206523,7 @@ function startAgentProcess(command, opts) {
206235
206523
  const exited = outcome3.then(async (result) => {
206236
206524
  try {
206237
206525
  if (pid !== void 0) {
206238
- while (terminating && groupAlive(pid) && performance.now() < graceEnds) await sleep4(GROUP_POLL_MS);
206526
+ while (terminating && groupAlive(pid) && performance.now() < graceEnds) await sleep5(GROUP_POLL_MS);
206239
206527
  }
206240
206528
  return result;
206241
206529
  } finally {
@@ -206875,8 +207163,8 @@ async function preflightExecution(agent, scenes = [], signal) {
206875
207163
  const descriptor2 = attemptDescriptor();
206876
207164
  explicitEnvironment(vmEnvironmentNames(agent), descriptor2.secretValues);
206877
207165
  vmModelHosts(descriptor2.modelHosts);
206878
- if (agent.mode === "endpoint" && agent.start === void 0) throw new AnchaError("CONFIG_INVALID", "Cloud HTTP agents require a start command.");
206879
- 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.");
207166
+ if (agent.mode === "endpoint") assertVmEndpoint(agent);
207167
+ if (scenes.some((scene2) => scene2.twins.includes("google-ads"))) throw new AnchaError("CONFIG_INVALID", "Choose HTTP tool connections for this attempt runtime.");
206880
207168
  return;
206881
207169
  }
206882
207170
  if (agent.execution === void 0) return;
@@ -207155,6 +207443,7 @@ var exec, RELAY_IMAGE, RELAY_PORT, LOG_LIMIT, LABEL2, CONTAINER_RECORDS, CONTAIN
207155
207443
  var init_docker = __esm({
207156
207444
  "backend/src/execution/docker.ts"() {
207157
207445
  "use strict";
207446
+ init_slack_app();
207158
207447
  init_src();
207159
207448
  init_agent_env();
207160
207449
  init_agent_output();
@@ -207210,7 +207499,7 @@ import { writeSync as writeSync3 } from "node:fs";
207210
207499
  import { chmod as chmod3, chown, copyFile as copyFile3, mkdir as mkdir5, mkdtemp as mkdtemp2, writeFile as writeFile7 } from "node:fs/promises";
207211
207500
  import { dirname as dirname6, join as join13 } from "node:path";
207212
207501
  import { StringDecoder as StringDecoder3 } from "node:string_decoder";
207213
- import { setTimeout as sleep5 } from "node:timers/promises";
207502
+ import { setTimeout as sleep6 } from "node:timers/promises";
207214
207503
  import { promisify as promisify3 } from "node:util";
207215
207504
  async function sweepAgentUid(uid, run4 = async (file3, args) => {
207216
207505
  await exec2(file3, args, { env: { PATH: VM_PATH }, timeout: 1e3, maxBuffer: 65536 });
@@ -207234,12 +207523,12 @@ async function sweepAgentUid(uid, run4 = async (file3, args) => {
207234
207523
  };
207235
207524
  if (!await alive()) return;
207236
207525
  await signal("TERM");
207237
- for (const grace2 = performance.now() + KILL_GRACE_MS2; performance.now() < grace2 && await alive(); ) await sleep5(50);
207526
+ for (const grace2 = performance.now() + KILL_GRACE_MS2; performance.now() < grace2 && await alive(); ) await sleep6(50);
207238
207527
  const deadline3 = performance.now() + 1e4;
207239
207528
  do {
207240
207529
  await signal("KILL");
207241
207530
  if (!await alive()) return;
207242
- await sleep5(50);
207531
+ await sleep6(50);
207243
207532
  } while (performance.now() < deadline3);
207244
207533
  throw new AnchaError("INTERNAL", "Agent processes remained after the cleanup deadline.");
207245
207534
  }
@@ -207359,6 +207648,7 @@ async function startVmAgent(command, opts, deps = {}) {
207359
207648
  ...opts.session && { session: opts.session },
207360
207649
  modelHosts,
207361
207650
  port: unsafe ? 0 : 18991,
207651
+ slackSocket: opts.agent.slackTransport === "socket",
207362
207652
  onModelReply: (host, status4, message7) => replies.add(host, status4, message7)
207363
207653
  });
207364
207654
  const mapped = gateway.rewrite(unsafe ? gateway.url : VM_GATEWAY_ORIGIN);
@@ -207686,7 +207976,7 @@ import { closeSync as closeSync3, openSync as openSync3, writeSync as writeSync4
207686
207976
  import { mkdir as mkdir6 } from "node:fs/promises";
207687
207977
  import { createServer as createServer3 } from "node:net";
207688
207978
  import { join as join15, resolve as resolve10 } from "node:path";
207689
- import { setTimeout as sleep6 } from "node:timers/promises";
207979
+ import { setTimeout as sleep7 } from "node:timers/promises";
207690
207980
  function deadline2(ms) {
207691
207981
  const controller = new AbortController();
207692
207982
  const end = performance.now() + ms;
@@ -207756,7 +208046,7 @@ async function ready2(url4, signal, expectedEnvId, headerOptional = false) {
207756
208046
  return;
207757
208047
  }
207758
208048
  }
207759
- await sleep6(25, void 0, { signal });
208049
+ await sleep7(25, void 0, { signal });
207760
208050
  }
207761
208051
  signal.throwIfAborted();
207762
208052
  }
@@ -207800,7 +208090,7 @@ async function runEndpointTrial(spec) {
207800
208090
  try {
207801
208091
  const clockFile = agent.clock === "node" ? resolve10(dir, "clock.json") : void 0;
207802
208092
  const session2 = await backend.prepareTrial(env.id, { mode: "endpoint", idleMs: agent.idleMs, slackTransport: agent.slackTransport ?? "http", ...agent.setupCalls && { setupCalls: true }, ...clockFile && { clockFile }, ...agent.execution?.mode === "container" && { clientOrigin: "http://127.0.0.1:18991" } });
207803
- const runtime2 = { ...port && { port: port.port }, ...spec.attempt && { attempt: spec.attempt } };
208093
+ const runtime2 = { ...port && { port: managedAppPort(agent.url, port.port, agentTemplateVars(env.id, env.services, scene2.task ?? "", trial, session2)) }, ...spec.attempt && { attempt: spec.attempt } };
207804
208094
  const vars = agentTemplateVars(env.id, env.services, scene2.task ?? "", trial, session2, runtime2, env.mcp);
207805
208095
  const logFd = openSync3(join15(dir, "agent.log"), "w");
207806
208096
  const startedAt = performance.now();
@@ -207825,10 +208115,12 @@ async function runEndpointTrial(spec) {
207825
208115
  } };
207826
208116
  child2 = await launchAgent(agent.start, { agent: clocked, env, scene: scene2, session: session2, trial, inheritedEnv, runtime: runtime2, logFd, dir, ...signal && { signal }, startupSignal });
207827
208117
  }
208118
+ if (child2?.pid !== void 0) spec.onAgentStarted?.();
207828
208119
  const earlyExit = child2?.exited.then((outcome3) => {
207829
208120
  throw new Error(outcome3.kind === "error" ? `could not start agent: ${outcome3.error.message}` : `agent exited during startup (code ${outcome3.code})`);
207830
208121
  });
207831
208122
  const bootstrap = async () => {
208123
+ if (agent.start && !agent.readyUrl && agent.slackTransport === "http" && env.services.slack) await waitSlackHttp(renderAgentUrl(agent.url, { ...vars, service: "slack" }), env.services.slack.signingSecret, session2.id, startupSignal);
207832
208124
  if (agent.setupUrl !== void 0) await setup(renderAgentUrl(agent.setupUrl, vars), agentSetupPayload(env, scene2, agent, trial, session2, runtime2), startupSignal);
207833
208125
  if (agent.readyUrl !== void 0) await ready2(renderAgentUrl(agent.readyUrl, vars), startupSignal, agent.start !== void 0 ? env.id : void 0, usesPort(agent.readyUrl));
207834
208126
  startupSignal.throwIfAborted();
@@ -207851,7 +208143,7 @@ async function runEndpointTrial(spec) {
207851
208143
  if (typeof status4.untilMs === "number") return { exit: "done", exitCode: null };
207852
208144
  if (status4.simMs >= timeoutMs) return { exit: "timeout", exitCode: null };
207853
208145
  if (status4.done) return { exit: status4.idle ? "idle" : "done", exitCode: null };
207854
- await sleep6(20, void 0, { signal: observingSignal });
208146
+ await sleep7(20, void 0, { signal: observingSignal });
207855
208147
  status4 = await abortable(backend.trialStatus(env.id, session2.id), observingSignal);
207856
208148
  }
207857
208149
  };
@@ -207917,6 +208209,7 @@ var CLOCK_PRELOAD;
207917
208209
  var init_endpoint = __esm({
207918
208210
  "backend/src/runner/endpoint.ts"() {
207919
208211
  "use strict";
208212
+ init_slack_app();
207920
208213
  init_agent_input();
207921
208214
  init_src();
207922
208215
  init_config();
@@ -207933,7 +208226,7 @@ import { closeSync as closeSync4, openSync as openSync4 } from "node:fs";
207933
208226
  import { mkdir as mkdir7 } from "node:fs/promises";
207934
208227
  import { createServer as createServer4 } from "node:net";
207935
208228
  import { join as join16 } from "node:path";
207936
- import { setTimeout as sleep7 } from "node:timers/promises";
208229
+ import { setTimeout as sleep8 } from "node:timers/promises";
207937
208230
  async function reserve(used) {
207938
208231
  const held = [];
207939
208232
  let chosen = false;
@@ -208021,7 +208314,7 @@ async function runHttpTaskTrial(spec) {
208021
208314
  } catch {
208022
208315
  startup2.throwIfAborted();
208023
208316
  }
208024
- if (!ready3) await sleep7(25, void 0, { signal: startup2 });
208317
+ if (!ready3) await sleep8(25, void 0, { signal: startup2 });
208025
208318
  }
208026
208319
  spec.onAgentStarted?.();
208027
208320
  await record13({ 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." });
@@ -208311,7 +208604,7 @@ var init_agent_outcome = __esm({
208311
208604
  });
208312
208605
 
208313
208606
  // backend/src/runner/trial.ts
208314
- import { setTimeout as sleep8 } from "node:timers/promises";
208607
+ import { setTimeout as sleep9 } from "node:timers/promises";
208315
208608
  import { closeSync as closeSync6, openSync as openSync6, writeSync as writeSync6 } from "node:fs";
208316
208609
  import { mkdir as mkdir9 } from "node:fs/promises";
208317
208610
  import { join as join18 } from "node:path";
@@ -208377,6 +208670,7 @@ async function runTrial(spec) {
208377
208670
  let failure5;
208378
208671
  try {
208379
208672
  if (child2.pid !== void 0) spec.onAgentStarted?.();
208673
+ if (agent.slackTransport === "socket") await waitSlackSocket(backend, env.id, session2.id, child2, AbortSignal.any([AbortSignal.timeout(3e4), ...signal ? [signal] : []]));
208380
208674
  await backend.startTrial(env.id, session2.id);
208381
208675
  signal?.throwIfAborted();
208382
208676
  const status4 = await backend.trialStatus(env.id, session2.id);
@@ -208394,11 +208688,11 @@ async function runTrial(spec) {
208394
208688
  const simulatedDeadline = parseDuration(scene2.timeout);
208395
208689
  void (async () => {
208396
208690
  while (observing && completed === void 0 && !timedOut) {
208397
- await sleep8(100);
208691
+ await sleep9(100);
208398
208692
  if (!observing || completed !== void 0 || timedOut) return;
208399
208693
  const now11 = await backend.trialStatus(env.id, session2.id);
208400
208694
  if (!observing || completed !== void 0 || timedOut) return;
208401
- if (typeof now11.untilMs === "number") {
208695
+ if (typeof now11.untilMs === "number" || agent.slackTransport === "socket" && now11.done) {
208402
208696
  untilReached = true;
208403
208697
  void child2.stop();
208404
208698
  return;
@@ -208479,6 +208773,7 @@ var EXIT_COMMAND_NOT_FOUND2, unknownRoute18;
208479
208773
  var init_trial = __esm({
208480
208774
  "backend/src/runner/trial.ts"() {
208481
208775
  "use strict";
208776
+ init_slack_app();
208482
208777
  init_src();
208483
208778
  init_launch();
208484
208779
  init_artifacts2();
@@ -208860,6 +209155,13 @@ var init_run = __esm({
208860
209155
  }
208861
209156
  });
208862
209157
 
209158
+ // backend/src/kit/slack-app.ts
209159
+ var init_slack_app2 = __esm({
209160
+ "backend/src/kit/slack-app.ts"() {
209161
+ "use strict";
209162
+ }
209163
+ });
209164
+
208863
209165
  // backend/src/kit/project-files.ts
208864
209166
  var init_project_files = __esm({
208865
209167
  "backend/src/kit/project-files.ts"() {
@@ -208875,6 +209177,13 @@ var init_start_command = __esm({
208875
209177
  }
208876
209178
  });
208877
209179
 
209180
+ // backend/src/kit/function-tools.ts
209181
+ var init_function_tools = __esm({
209182
+ "backend/src/kit/function-tools.ts"() {
209183
+ "use strict";
209184
+ }
209185
+ });
209186
+
208878
209187
  // backend/src/kit/tool-signals.ts
208879
209188
  var init_tool_signals = __esm({
208880
209189
  "backend/src/kit/tool-signals.ts"() {
@@ -208887,9 +209196,11 @@ var init_tool_signals = __esm({
208887
209196
  var init_detect = __esm({
208888
209197
  "backend/src/kit/detect.ts"() {
208889
209198
  "use strict";
209199
+ init_slack_app2();
208890
209200
  init_src();
208891
209201
  init_start_command();
208892
209202
  init_project_files();
209203
+ init_function_tools();
208893
209204
  init_tool_signals();
208894
209205
  }
208895
209206
  });
@@ -209043,6 +209354,7 @@ init_src();
209043
209354
  init_credentials();
209044
209355
 
209045
209356
  // packages/cli/src/run-upload.ts
209357
+ init_run_metadata();
209046
209358
  init_src();
209047
209359
  init_credentials();
209048
209360
  import { readFile as readFile5 } from "node:fs/promises";
@@ -209091,7 +209403,7 @@ async function uploadRun(ctx, workspace3, run4) {
209091
209403
  });
209092
209404
  let response5;
209093
209405
  try {
209094
- response5 = await fetch(`${workspace3}/_runs`, { method: "POST", headers: { ...key4 !== void 0 && { authorization: `Bearer ${key4}` }, "content-type": "application/gzip" }, body: new Uint8Array(archive) });
209406
+ response5 = await fetch(`${workspace3}/_runs`, { method: "POST", headers: { ...runContextHeader(ctx.io.env), ...key4 !== void 0 && { authorization: `Bearer ${key4}` }, "content-type": "application/gzip" }, body: new Uint8Array(archive) });
209095
209407
  } catch (error64) {
209096
209408
  throw new AnchaError("SERVER_UNREACHABLE", `${workspace3} did not answer the upload`, { hint: `check the network, then ancha runs upload ${run4.runId}`, cause: error64 });
209097
209409
  }
@@ -209104,7 +209416,7 @@ async function uploadRun(ctx, workspace3, run4) {
209104
209416
  throw new AnchaError(code2, error64.message ?? `the upload was refused (HTTP ${response5.status})`, { hint: error64.hint ?? `ancha runs upload ${run4.runId}` });
209105
209417
  }
209106
209418
  const answer = await response5.json().catch(() => void 0);
209107
- return { url: httpUrl3(answer?.url) ?? `${new URL(workspace3).origin}/runs/${encodeURIComponent(run4.runId)}`, bytes: archive.length, files: manifest.files.length, ...answer?.replaced === true && { replaced: true } };
209419
+ return { ...runNumberOf(answer?.runNumber) && { runNumber: runNumberOf(answer?.runNumber) }, url: httpUrl3(answer?.url) ?? `${new URL(workspace3).origin}/runs/${encodeURIComponent(run4.runId)}`, bytes: archive.length, files: manifest.files.length, ...answer?.replaced === true && { replaced: true } };
209108
209420
  }
209109
209421
  function httpUrl3(value4) {
209110
209422
  if (typeof value4 !== "string") return void 0;
@@ -209118,6 +209430,7 @@ function httpUrl3(value4) {
209118
209430
 
209119
209431
  // packages/cli/src/cloud-agent.ts
209120
209432
  init_src();
209433
+ init_slack_app();
209121
209434
 
209122
209435
  // packages/cli/src/commands/run.ts
209123
209436
  init_credentials();
@@ -209137,9 +209450,13 @@ init_config();
209137
209450
  init_credentials();
209138
209451
 
209139
209452
  // packages/cli/src/hosted-run.ts
209453
+ init_run_metadata();
209140
209454
  init_src();
209141
209455
  init_report();
209142
209456
 
209457
+ // packages/cli/src/project-identity.ts
209458
+ init_jobs_contract();
209459
+
209143
209460
  // packages/cli/src/cloud-bundle.ts
209144
209461
  init_src();
209145
209462
  init_connection_tools();
@@ -209172,6 +209489,7 @@ init_agent_env();
209172
209489
  init_run();
209173
209490
 
209174
209491
  // packages/cli/src/hosted-jobs.ts
209492
+ init_run_metadata();
209175
209493
  init_src();
209176
209494
  init_credentials();
209177
209495
  init_run_bundle();
@@ -209543,12 +209861,13 @@ async function interruptible(ctx, fn) {
209543
209861
  }
209544
209862
  }
209545
209863
  function emitFinished(ctx, summary, out, upload4, uploadHint, reproduction = summary.reproduction ?? [], tests) {
209864
+ if (upload4 && "runNumber" in upload4 && upload4.runNumber) summary = { ...summary, runNumber: upload4.runNumber };
209546
209865
  const opts = { out: nonDefaultOut(ctx.io.cwd, out), ...tests !== void 0 && { tests }, cwd: ctx.io.cwd };
209547
209866
  const never2 = agentNeverRan(summary);
209548
209867
  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 } });
209549
209868
  else ctx.out.result(summary, () => `
209550
209869
  ${renderSummaryText(summary, { ...opts, reproduction })}${upload4 !== void 0 && "url" in upload4 ? `
209551
- uploaded: ${upload4.url}` : ""}${upload4 === void 0 && uploadHint !== void 0 ? `
209870
+ uploaded: ${upload4.runNumber ? `#${upload4.runNumber} \xB7 ` : ""}${upload4.url}` : ""}${upload4 === void 0 && uploadHint !== void 0 ? `
209552
209871
  ${uploadHintLine(summary.runId, uploadHint, { out: opts.out })}` : ""}`);
209553
209872
  }
209554
209873
  async function uploadFinished(ctx, input5, runId) {