agenttwin 0.3.45 → 0.3.46

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.
Files changed (75) hide show
  1. package/dist/api.js +153 -56
  2. package/dist/dashboard/assets/next/static/chunks/app/_not-found/{page-90e7c4625d67caa3.js → page-ca2a678442778cc4.js} +1 -1
  3. package/dist/dashboard/assets/next/static/chunks/app/about/{page-7b6ab8f6081f5e77.js → page-f12d76165cc1cfdb.js} +1 -1
  4. package/dist/dashboard/assets/next/static/chunks/app/account/password/{page-037fec5f56012be1.js → page-c2ce3c796c817ca1.js} +1 -1
  5. package/dist/dashboard/assets/next/static/chunks/app/{auth/page-540d65d1057a7527.js → api-policy/page-dc4de82f3c8b5ee5.js} +1 -1
  6. package/dist/dashboard/assets/next/static/chunks/app/{compare/page-540d65d1057a7527.js → auth/page-dc4de82f3c8b5ee5.js} +1 -1
  7. package/dist/dashboard/assets/next/static/chunks/app/blog/{layout-1f35c9c8280d8e88.js → layout-52698c1f7512ab03.js} +1 -1
  8. package/dist/dashboard/assets/next/static/chunks/app/{contact/page-540d65d1057a7527.js → compare/page-dc4de82f3c8b5ee5.js} +1 -1
  9. package/dist/dashboard/assets/next/static/chunks/app/{api-policy/page-540d65d1057a7527.js → contact/page-dc4de82f3c8b5ee5.js} +1 -1
  10. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-b5ef02cb8f06edca.js +1 -0
  11. package/dist/dashboard/assets/next/static/chunks/app/dashboard/{page-7ee71756cadd81da.js → page-e175e18f842b558f.js} +1 -1
  12. package/dist/dashboard/assets/next/static/chunks/app/demo/{page-fa467521a350a22e.js → page-4dc63755e0013e7c.js} +1 -1
  13. package/dist/dashboard/assets/next/static/chunks/app/developers/page-dc4de82f3c8b5ee5.js +1 -0
  14. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/{page-2f02d1a4e3c44daa.js → page-ba0ec7ecc08eff9f.js} +1 -1
  15. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-dc4de82f3c8b5ee5.js +1 -0
  16. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-4bc33047e4c9fe8e.js +1 -0
  17. package/dist/dashboard/assets/next/static/chunks/app/guides/page-dc4de82f3c8b5ee5.js +1 -0
  18. package/dist/dashboard/assets/next/static/chunks/app/layout-cd911546738f01ed.js +1 -0
  19. package/dist/dashboard/assets/next/static/chunks/app/login/page-d6d4276397724d29.js +1 -0
  20. package/dist/dashboard/assets/next/static/chunks/app/not-found-dc4de82f3c8b5ee5.js +1 -0
  21. package/dist/dashboard/assets/next/static/chunks/app/onboarding/{page-0ef60a890802e3ea.js → page-40532b5cef9a88c1.js} +1 -1
  22. package/dist/dashboard/assets/next/static/chunks/app/page-a8275b37886e34a8.js +1 -0
  23. package/dist/dashboard/assets/next/static/chunks/app/{enterprise/page-5d3aa113786c4257.js → pricing/page-8f3a108c73f12071.js} +1 -1
  24. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-dc4de82f3c8b5ee5.js +1 -0
  25. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-dc4de82f3c8b5ee5.js +1 -0
  26. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-dc4de82f3c8b5ee5.js +1 -0
  27. package/dist/dashboard/assets/next/static/chunks/app/security/page-dc4de82f3c8b5ee5.js +1 -0
  28. package/dist/dashboard/assets/next/static/chunks/app/signup/page-d6d4276397724d29.js +1 -0
  29. package/dist/dashboard/assets/next/static/chunks/app/status/page-b39797a55d029518.js +1 -0
  30. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-dc4de82f3c8b5ee5.js +1 -0
  31. package/dist/dashboard/assets/next/static/chunks/app/terms/page-dc4de82f3c8b5ee5.js +1 -0
  32. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-09d48e9ba6876ea1.js +1 -0
  33. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-031ee9c843b9c428.js +1 -0
  34. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-abbd9f3b8811f559.js +1 -0
  35. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-4f4a342a4c28f9de.js +1 -0
  36. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/{page-cb95f6e08d868cb9.js → page-efea46ea53572102.js} +1 -1
  37. package/dist/dashboard/assets/next/static/chunks/app/v2/page-4c5b8b508cf0da4c.js +1 -0
  38. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-4f4a342a4c28f9de.js +1 -0
  39. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-dc4de82f3c8b5ee5.js +1 -0
  40. package/dist/dashboard/assets/next/static/chunks/{main-app-09f87cf7a6813e7b.js → main-app-1ec13ceef4a34729.js} +1 -1
  41. package/dist/dashboard/assets/next/static/chunks/{webpack-956fc59a9b8e1c9d.js → webpack-b34c6469f0501f3e.js} +1 -1
  42. package/dist/dashboard/index.html +2 -2
  43. package/dist/discover-worker.js +1 -1
  44. package/dist/engine.js +153 -56
  45. package/dist/gateway.js +153 -56
  46. package/dist/scan-worker.js +2 -1
  47. package/dist/worker.js +5 -0
  48. package/dist/world-host.js +5 -0
  49. package/package.json +1 -1
  50. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-0a7a4610c777d4ca.js +0 -1
  51. package/dist/dashboard/assets/next/static/chunks/app/developers/page-540d65d1057a7527.js +0 -1
  52. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-540d65d1057a7527.js +0 -1
  53. package/dist/dashboard/assets/next/static/chunks/app/guides/page-540d65d1057a7527.js +0 -1
  54. package/dist/dashboard/assets/next/static/chunks/app/layout-f1fad0b3adfa8650.js +0 -1
  55. package/dist/dashboard/assets/next/static/chunks/app/login/page-0fcaa825ae57072e.js +0 -1
  56. package/dist/dashboard/assets/next/static/chunks/app/not-found-540d65d1057a7527.js +0 -1
  57. package/dist/dashboard/assets/next/static/chunks/app/page-02d88045d016e184.js +0 -1
  58. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-b20818439dc8daa3.js +0 -1
  59. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-540d65d1057a7527.js +0 -1
  60. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-540d65d1057a7527.js +0 -1
  61. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-540d65d1057a7527.js +0 -1
  62. package/dist/dashboard/assets/next/static/chunks/app/security/page-540d65d1057a7527.js +0 -1
  63. package/dist/dashboard/assets/next/static/chunks/app/signup/page-0fcaa825ae57072e.js +0 -1
  64. package/dist/dashboard/assets/next/static/chunks/app/status/page-477b90a47b806b39.js +0 -1
  65. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-540d65d1057a7527.js +0 -1
  66. package/dist/dashboard/assets/next/static/chunks/app/terms/page-540d65d1057a7527.js +0 -1
  67. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-f3b848d905696aa6.js +0 -1
  68. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-5114d5bc25cc925a.js +0 -1
  69. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-c5a3a914ad02b396.js +0 -1
  70. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-391350c8e39d35fe.js +0 -1
  71. package/dist/dashboard/assets/next/static/chunks/app/v2/page-ba5549311d95d01d.js +0 -1
  72. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-391350c8e39d35fe.js +0 -1
  73. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-540d65d1057a7527.js +0 -1
  74. /package/dist/dashboard/assets/next/static/{iCEc5bCzyYUPa74FKyLIp → pGgp6m8IvF1eEP2vBkhqX}/_buildManifest.js +0 -0
  75. /package/dist/dashboard/assets/next/static/{iCEc5bCzyYUPa74FKyLIp → pGgp6m8IvF1eEP2vBkhqX}/_ssgManifest.js +0 -0
package/dist/engine.js CHANGED
@@ -224,7 +224,7 @@ var init_package = __esm({
224
224
  "package.json"() {
225
225
  package_default = {
226
226
  name: "agenttwin",
227
- version: "0.3.45",
227
+ version: "0.3.46",
228
228
  description: "AgentTwin builds digital twins for testing AI agents. The current CLI prepares supported Node.js workflows with synthetic services, failures, and outcome checks.",
229
229
  mcpName: "io.github.AgentTwin/agenttwin",
230
230
  keywords: [
@@ -4770,6 +4770,10 @@ function installRetry(step, output2) {
4770
4770
  const pm = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a))?.split("@")[0] : step.command;
4771
4771
  const tail2 = step.command === "corepack" ? step.args.slice(1) : step.command === "npx" ? step.args.slice(2) : step.args;
4772
4772
  const pinned = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a)) : pm;
4773
+ if (pm === "pnpm" && /Failed to switch pnpm|ERR_PNPM_BAD_PM_VERSION|manage-package-manager-versions/i.test(output2) && !step.args.some((a) => a.includes("manage-package-manager-versions")))
4774
+ return { why: "pnpm could not switch to the pinned version", step: { ...step, args: ["--config.manage-package-manager-versions=false", ...step.args] } };
4775
+ if (pm === "pnpm" && /ERR_PNPM_UNUSED_PATCH/.test(output2) && !step.args.some((a) => a.includes("allow-unused-patches")))
4776
+ return { why: "pnpm rejected an unused patch in the lockfile", step: { ...step, args: [...step.args, "--config.allow-unused-patches=true"] } };
4773
4777
  if (pm === "pnpm" && /ERR_PNPM_(OUTDATED_LOCKFILE|LOCKFILE_CONFIG_MISMATCH|LOCKFILE_MISSING_DEPENDENCY)|frozen.lockfile|specifiers in the lockfile/i.test(output2))
4774
4778
  return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-frozen-lockfile"] } };
4775
4779
  const lockfile = pm === "pnpm" ? /lockfileVersion[\s│|]+of[\s│|]+(\d+)(?:\.(\d+))?[\s│|]+is[\s│|]+incompatible/i.exec(output2) : null;
@@ -4831,8 +4835,8 @@ async function runSetup(cwd, opts) {
4831
4835
  const buildLimitMs = Number(process.env.AGENTTWIN_SETUP_BUILD_TIMEOUT_MS) || 20 * 6e4;
4832
4836
  let timedOut = false;
4833
4837
  let installedManager;
4834
- const exec12 = (step) => new Promise((resolve45) => {
4835
- const child = spawn2(step.command, step.args, { cwd: step.dir, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"], env: { ...BUILD_PLACEHOLDERS, ...process.env, CI: "1", COREPACK_ENABLE_DOWNLOAD_PROMPT: "0", ...shims ? { PATH: `${shims}${delimiter}${process.env.PATH ?? ""}` } : {} } });
4838
+ const exec12 = (step, extraEnv) => new Promise((resolve45) => {
4839
+ const child = spawn2(step.command, step.args, { cwd: step.dir, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"], env: { ...BUILD_PLACEHOLDERS, ...process.env, ...extraEnv ?? {}, CI: "1", COREPACK_ENABLE_DOWNLOAD_PROMPT: "0", ...shims ? { PATH: `${shims}${delimiter}${process.env.PATH ?? ""}` } : {} } });
4836
4840
  let tail2 = "";
4837
4841
  const keep = (c) => {
4838
4842
  tail2 = (tail2 + c.toString()).slice(-4e3);
@@ -4868,12 +4872,12 @@ async function runSetup(cwd, opts) {
4868
4872
  opts.log(` The build was still running after ${Math.round(buildLimitMs / 6e4)} min, so it was stopped. What it finished stays built: run npx agenttwin again to carry on, or run it from the folder of the one service you want to test so only its packages are built. (Set AGENTTWIN_SETUP_BUILD_TIMEOUT_MS to change the limit.)`);
4869
4873
  return false;
4870
4874
  }
4871
- for (let current2 = step, tries = 0; code !== 0 && step.id === "install" && tries < 3; tries++) {
4875
+ for (let current2 = step, tries = 0; code !== 0 && (step.id === "install" || /Failed to switch pnpm|ERR_PNPM_BAD_PM_VERSION|manage-package-manager-versions/i.test(tail2)) && tries < 3; tries++) {
4872
4876
  const retry = installRetry(current2, tail2);
4873
4877
  if (!retry) break;
4874
4878
  opts.log(` ${retry.why}; running ${show(retry.step)}\u2026`);
4875
4879
  current2 = retry.step;
4876
- ({ code, tail: tail2 } = await exec12(retry.step));
4880
+ ({ code, tail: tail2 } = await exec12(retry.step, retry.step.args.some((a) => a.includes("manage-package-manager-versions")) ? { npm_config_manage_package_manager_versions: "false", pnpm_config_manage_package_manager_versions: "false" } : void 0));
4877
4881
  }
4878
4882
  let left = code !== 0 && step.id === "build" && plan.unbuilt ? unbuiltWorkspacePackages(cwd, opts.appDir) : void 0;
4879
4883
  if (left?.length) {
@@ -11896,6 +11900,11 @@ var init_http_world = __esm({
11896
11900
  const target2 = aliasRequest(name2, host, req.url ?? "/");
11897
11901
  const model = compatibleModel(name2, body);
11898
11902
  const r = await twin(new Request(`https://${target2.host}${target2.url}`, { method, headers, ...model.body ? { body: model.body } : {} }));
11903
+ if ((r.status === 501 || r.status === 404) && name2 === "ai-gateway" && method === "GET" && /^\/(?:v1\/)?models\/([^/]+\/[^/]+)\/endpoints$/.test(target2.url.split("?")[0])) {
11904
+ const id2 = /^\/(?:v1\/)?models\/([^/]+\/[^/]+)\/endpoints$/.exec(target2.url.split("?")[0])[1];
11905
+ const payload = Buffer.from(JSON.stringify({ data: { id: id2, name: id2, endpoints: [{ name: id2, provider: id2.split("/")[0] || "openai", context_length: 128e3, pricing: { prompt: "0", completion: "0" }, supported_parameters: ["tools", "temperature", "max_tokens"] }] } }));
11906
+ return { status: 200, headers: new Headers({ "content-type": "application/json" }), bytes: payload, actions: [] };
11907
+ }
11899
11908
  return { status: r.status, headers: r.headers, bytes: model.restore(Buffer.from(await r.arrayBuffer())), actions: log.drain() };
11900
11909
  };
11901
11910
  if (workspace && method !== "GET") this.causing[service.name] = 1;
@@ -28240,7 +28249,7 @@ var init_state_seeding = __esm({
28240
28249
  if (/name/.test(name2)) return "AgentTwin Test";
28241
28250
  return `agenttwin-${name2}-${n}`;
28242
28251
  };
28243
- NOT_A_SERVICE2 = /(^|\.)(registry\.npmjs\.org|registry\.yarnpkg\.com|npmjs\.(?:com|org)|pypi\.org|files\.pythonhosted\.org|crates\.io|proxy\.golang\.org|rubygems\.org|github\.com|githubusercontent\.com|amazonaws\.com)$/;
28252
+ NOT_A_SERVICE2 = /(^|\.)(registry\.npmjs\.org|registry\.yarnpkg\.com|npmjs\.(?:com|org)|pypi\.org|files\.pythonhosted\.org|crates\.io|proxy\.golang\.org|rubygems\.org|githubusercontent\.com|amazonaws\.com)$/;
28244
28253
  }
28245
28254
  });
28246
28255
 
@@ -28425,11 +28434,12 @@ function packRecordSample(pack, resource2, id2, depth = 0, read2 = /* @__PURE__
28425
28434
  }
28426
28435
  return record7;
28427
28436
  }
28428
- function sourcesNear(root2, file2) {
28437
+ function sourcesNear(root2, file2, opts) {
28429
28438
  const out = [], seen = /* @__PURE__ */ new Set();
28430
28439
  const visit2 = (path2, level) => {
28431
28440
  if (seen.has(path2) || level > 1) return;
28432
28441
  seen.add(path2);
28442
+ if (opts?.excludeEnvFiles && level > 0 && SHARED_ENV_FILE.test(path2)) return;
28433
28443
  let text4 = "";
28434
28444
  try {
28435
28445
  text4 = readFileSync10(join63(root2, path2), "utf8");
@@ -28535,14 +28545,15 @@ function inferredSignature(root2, route, file2, settings) {
28535
28545
  const text4 = source + "\n" + sourcesNear(root2, file2).join("\n");
28536
28546
  const envOf = (expr) => /process\.env\.([A-Z][A-Z0-9_]*)|process\.env\[['"`]([A-Z][A-Z0-9_]*)['"`]\]|\benv\.([A-Z][A-Z0-9_]*)/.exec(expr)?.slice(1).find(Boolean);
28537
28547
  const secretNames = [.../* @__PURE__ */ new Set([...settings, ...[...text4.matchAll(/\b([A-Z][A-Z0-9_]*(?:WEBHOOK|SIGNING)[A-Z0-9_]*)\b/g)].map((m) => m[1])])].filter((n) => SECRET_NAME.test(n) && /(SECRET|KEY|TOKEN)/.test(n) && /(WEBHOOK|SIGNING)/.test(n));
28538
- if (/from\s+['"`](?:svix|standardwebhooks)['"`]|require\(\s*['"`](?:svix|standardwebhooks)['"`]\s*\)|@clerk\/[\w-]+\/webhooks|['"`](?:svix|webhook)-signature['"`]/.test(text4) && secretNames.length) {
28548
+ if (/from\s+['"`](?:svix|standardwebhooks)['"`]|require\(\s*['"`](?:svix|standardwebhooks)['"`]\s*\)|@clerk\/[\w-]+\/webhooks|['"`](?:svix|webhook)-signature['"`]|\.webhooks\.unwrap\s*\(/.test(text4) && secretNames.length) {
28539
28549
  const literals2 = [...source.matchAll(/(?:case\s*|===?\s*|!==?\s*)['"`]([a-z][a-z0-9_]*(?:\.[a-z0-9_]+){1,3})['"`]/g)].map((m) => m[1]);
28540
28550
  const type = literals2[0] ?? "test.event", resource2 = type.split(".")[0].replace(/\W/g, "_");
28551
+ const callId = /\.call_id\b/.test(source) ? { call_id: "call_agenttwin_1" } : {};
28541
28552
  return {
28542
28553
  scheme: { kind: "webhook-id", header: "webhook-signature" },
28543
28554
  secret: `whsec_${randomBytes8(24).toString("base64")}`,
28544
28555
  settings: secretNames,
28545
- body: { type, timestamp: new Date(1762257600 * 1e3).toISOString(), data: { id: `${resource2}_agenttwin_1`, object: resource2 } },
28556
+ body: { id: `evt_agenttwin_1`, object: "event", type, created_at: 1762257600, timestamp: new Date(1762257600 * 1e3).toISOString(), data: { id: `${resource2}_agenttwin_1`, object: resource2, ...callId } },
28546
28557
  how: "Standard Webhooks signature (webhook-id, webhook-timestamp, webhook-signature)"
28547
28558
  };
28548
28559
  }
@@ -28564,9 +28575,15 @@ function inferredSignature(root2, route, file2, settings) {
28564
28575
  }
28565
28576
  function signedUnlessKnown(root2, route, file2, settings) {
28566
28577
  const signed = signedWebhook(root2, route, file2, settings);
28567
- return signed?.guessed && webhookEvent(route, settings) ? void 0 : signed;
28568
- }
28569
- var statIsDir, SIGNING_DRIVER, SECRET_NAME;
28578
+ if (!signed?.guessed) return signed;
28579
+ if (webhookEvent(route, settings)) return void 0;
28580
+ const segments = route.path.toLowerCase().split("/").filter((s) => s && !GENERIC_WEBHOOK_SEGMENTS.has(s) && !/^\[/.test(s) && !/^:/.test(s));
28581
+ const packTokens = /* @__PURE__ */ new Set([signed.pack.toLowerCase(), signed.vendor.toLowerCase()]);
28582
+ if (segments.some((s) => !packTokens.has(s))) return void 0;
28583
+ if (!webhookPack(route.path, sourcesNear(root2, file2, { excludeEnvFiles: true }).join("\n"))) return void 0;
28584
+ return signed;
28585
+ }
28586
+ var statIsDir, SHARED_ENV_FILE, GENERIC_WEBHOOK_SEGMENTS, SIGNING_DRIVER, SECRET_NAME;
28570
28587
  var init_webhook_signing = __esm({
28571
28588
  "src/flow/webhook-signing.ts"() {
28572
28589
  "use strict";
@@ -28580,6 +28597,8 @@ var init_webhook_signing = __esm({
28580
28597
  return false;
28581
28598
  }
28582
28599
  };
28600
+ SHARED_ENV_FILE = /(?:^|\/|\\)env(?:\.[cm]?[jt]sx?|\/(?:index|server|client|schema)\.[cm]?[jt]sx?)?$/i;
28601
+ GENERIC_WEBHOOK_SEGMENTS = /* @__PURE__ */ new Set(["api", "v1", "v2", "v3", "webhook", "webhooks", "hook", "hooks", "events", "event", "callback", "callbacks", "notify", "incoming", "route", "public", "internal"]);
28583
28602
  SIGNING_DRIVER = String.raw`
28584
28603
  // Sign with the secret the app was given: a twin pack can issue its own (STRIPE_WEBHOOK_SECRET), and the scenario's
28585
28604
  // value only fills a setting nothing else set.
@@ -50285,14 +50304,14 @@ var init_input_formats = __esm({
50285
50304
  function missingInputFields(stderr, stdout = "") {
50286
50305
  const found = /* @__PURE__ */ new Map();
50287
50306
  const bodies = [];
50288
- for (const m of stderr.matchAll(/HTTP 4\d\d from \S+ \S+?:\s*(\{.*)$/gm)) {
50289
- let body;
50290
- try {
50291
- body = JSON.parse(m[1]);
50292
- } catch {
50293
- continue;
50294
- }
50295
- bodies.push(body);
50307
+ for (const m of stderr.matchAll(/HTTP 4\d\d from \S+ \S+:(?=\s|\{)\s*(.+)$/gm)) {
50308
+ const raw = m[1].trim();
50309
+ if (raw.startsWith("{")) {
50310
+ try {
50311
+ bodies.push(JSON.parse(raw));
50312
+ } catch {
50313
+ }
50314
+ } else bodies.push({ error: raw });
50296
50315
  }
50297
50316
  for (const line of stdout.split("\n")) {
50298
50317
  try {
@@ -50337,10 +50356,10 @@ function missingInputFields(stderr, stdout = "") {
50337
50356
  found.set(name2, { name: name2, ...expected ? { expected } : {} });
50338
50357
  }
50339
50358
  for (const x of Object.values(o)) if (typeof x === "string") {
50340
- const t = /^\s*['"`]?([A-Za-z_][\w-]{0,63})['"`]?(?:\s+(array|string|object|number|field|parameter|list))?\s+(?:is|are)\s+(?:required|missing)\b/i.exec(x);
50359
+ const t = /^\s*['"`]?([A-Za-z_][\w-]{0,63})['"`]?(?:\s+(array|string|object|number|boolean|field|parameter|list))?\s+(is|are)\s+(?:required|missing)\b/i.exec(x);
50341
50360
  if (t && safeField(t[1]) && !/^(?:it|this|that|body|request|input|value|fields?|parameters?)$/i.test(t[1])) {
50342
- const name2 = t[1].charAt(0).toLowerCase() + t[1].slice(1), kind = t[2]?.toLowerCase();
50343
- if (!found.has(name2)) found.set(name2, { name: name2, ...kind === "array" || kind === "list" ? { expected: "array" } : kind === "number" ? { expected: "number" } : {} });
50361
+ const name2 = t[1].charAt(0).toLowerCase() + t[1].slice(1), kind = t[2]?.toLowerCase(), plural6 = t[3].toLowerCase() === "are";
50362
+ if (!found.has(name2)) found.set(name2, { name: name2, ...kind === "array" || kind === "list" || !kind && plural6 ? { expected: "array" } : kind === "number" ? { expected: "number" } : kind === "boolean" ? { expected: "boolean" } : {} });
50344
50363
  }
50345
50364
  }
50346
50365
  for (const x of Object.values(o)) if (x && typeof x === "object") visit2(x);
@@ -50355,9 +50374,10 @@ function testValueFor(field2) {
50355
50374
  if (/^(?:prompt|message|question|query|input|text|content)$/i.test(field2.name) && field2.expected !== "array" && field2.expected !== "object" && field2.expected !== "record") return CHAT_TEXT;
50356
50375
  if (field2.expected === "number" || field2.expected === "integer") return 1;
50357
50376
  if (field2.expected === "boolean") return true;
50358
- if (field2.expected === "array") return [];
50377
+ if (field2.expected === "array") return ["test"];
50359
50378
  if (field2.expected === "object" || field2.expected === "record") return {};
50360
50379
  const n = field2.name.toLowerCase();
50380
+ if (/^(?:accept|agree|allow|confirm|enabled|active|ok|verified)$/.test(n)) return true;
50361
50381
  if (/email/.test(n)) return "ada@example.com";
50362
50382
  if (/url|uri|redirect/.test(n)) return "https://example.com/";
50363
50383
  if (/(^|_)(amount|count|quantity|qty|limit|page)$/.test(n)) return 1;
@@ -52456,7 +52476,8 @@ async function analyzeWorkflows(root2, opts = {}) {
52456
52476
  for (const [exportName, local] of f.exports) {
52457
52477
  const { calls: reached, env, files: touched, channels } = closure(file2, local);
52458
52478
  const calls = reached.filter((c) => !/^use[A-Z]/.test(c.operation));
52459
- if ((/\.[jt]sx$/.test(file2) && /^[A-Z]/.test(exportName) || /^use[A-Z]/.test(exportName)) && !ROUTE_FILE.test(file2)) continue;
52479
+ if ((/\.[jt]sx$/.test(file2) && (/^[A-Z]/.test(exportName) || exportName === "default") || /^use[A-Z]/.test(exportName)) && !ROUTE_FILE.test(file2) && !PAGES_API_FILE.test(file2)) continue;
52480
+ if (/(?:^|\/)(?:instrumentation(?:\.client)?|test-utils)\.[cm]?[jt]s$/i.test(file2)) continue;
52460
52481
  const verifiesWebhook = (ROUTE_FILE.test(file2) || PAGES_API_FILE.test(file2) || SVELTE_ROUTE_FILE.test(file2)) && /\.webhooks\.constructEvent(Async)?\(|verifyWebhook|webhooks?\.verify\(|new Webhook\(|validateRequest\(|stripe-signature|x-hub-signature|svix-signature|x-slack-signature/i.test(byFile.get(file2).text);
52461
52482
  if (!calls.length && !opts.all && !verifiesWebhook && !f.trpcHandler) continue;
52462
52483
  const fn = f.functions.get(local);
@@ -52831,6 +52852,17 @@ async function analyzeWorkflows(root2, opts = {}) {
52831
52852
  const python = await analyzePythonWorkflows(root2);
52832
52853
  return [...unique.values(), ...scripts, ...python].map((c) => ({ ...c, score: c.score + (c.triggers.length ? 2 : 0) })).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
52833
52854
  }
52855
+ function collapseCandidates(inventory, analyzed) {
52856
+ const absorbed = /* @__PURE__ */ new Map();
52857
+ for (const workflow of inventory) {
52858
+ const [file2, member] = (workflow.entrypoint ?? "").split("#");
52859
+ const routeMatch = /^route:([^:]+):(.+?)@(\d+)$/i.exec(member ?? "");
52860
+ const routeMethod = routeMatch?.[1]?.toUpperCase(), routeLine = routeMatch?.[3];
52861
+ const match = analyzed.find((c) => c.entrypoint === workflow.entrypoint || routeLine && c.triggers.some((t) => t.file === file2 && String(t.line) === routeLine) || routeMethod && c.file === file2 && (c.web?.method.toUpperCase() === routeMethod || c.serve?.method.toUpperCase() === routeMethod) || (workflow.evidence ?? []).some((e) => e.ref === `${c.file}:${c.calls[0]?.line}`));
52862
+ if (match) absorbed.set(workflow.id, match.id);
52863
+ }
52864
+ return absorbed;
52865
+ }
52834
52866
  var WHOLE_INPUT, PROVIDER_MODULES, FETCH_HOSTS, KNOWN_PROVIDERS, escapeHost, packHosts, fetchHosts, READ_OPS, SOURCE, SKIP3, SETTINGS_MODULE_SIZE, SOURCE_FILE_LIMIT, ROUTE_FILE, SVELTE_ROUTE_FILE, FUNCTION_FILE, PAGES_API_FILE, REQUEST_TARGET_KEYS, chain2, literal3, objectLiteral, templateSql, ENTRY_NAME, nextApps, LazyFunctions;
52835
52867
  var init_analyze = __esm({
52836
52868
  "src/flow/analyze.ts"() {
@@ -55999,6 +56031,7 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
55999
56031
  const slack = signed.pack === "slack" ? scenario2.services.find((sv) => sv.name === signed.pack || String(sv.adapter ?? "") === "pack:slack") : void 0;
56000
56032
  if (slack && typeof about?.channel === "string" && typeof about.ts === "string") {
56001
56033
  for (const c of slackEventSeed({ channel: about.channel, ts: about.ts, user: about.user, text: about.text })) {
56034
+ if (!String(slack.adapter ?? "").startsWith("pack:") && c.path === "/channel_members") continue;
56002
56035
  const have = slack.collections.find((x) => x.path === c.path);
56003
56036
  if (!have) slack.collections.push(c);
56004
56037
  else for (const r of c.seed) if (!have.seed.some((x) => x.id === r.id)) have.seed.push(r);
@@ -56318,7 +56351,7 @@ try{
56318
56351
  :v[${JSON.stringify(SLACK_CLIENT)}]?await slack()
56319
56352
  :typeof v[${JSON.stringify(SAY)}]==='string'?(()=>{const channel=v[${JSON.stringify(SAY)}];return async m=>(await slack()).chat.postMessage(typeof m==='string'?{channel,text:m}:{channel,...m});})()
56320
56353
  :Object.fromEntries(await Promise.all(Object.entries(v).map(async([k,x])=>[k,await hydrate(x)])))):v;
56321
- for(const [index,raw] of calls.entries()){const args=await hydrate(raw);const result=await fn(...args);console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,result:result??null,...(invoked.length?{invoked:invoked.splice(0)}:{})}));}
56354
+ for(const [index,raw] of calls.entries()){const args=await hydrate(raw);let result=await fn(...args);if(result&&typeof result[Symbol.asyncIterator]==='function'){const chunks=[];for await(const chunk of result)chunks.push(chunk);result=chunks.every(c=>typeof c==='string')?chunks.join(''):chunks;}console.log(JSON.stringify({schema:'agenttwin/call-result-v1',call:index+1,result:result??null,...(invoked.length?{invoked:invoked.splice(0)}:{})}));}
56322
56355
  }catch(error){console.error(error);process.exitCode=1;}
56323
56356
  // Open pools and sockets would keep the process alive; exit once the calls have settled.
56324
56357
  setTimeout(()=>process.exit(),1000).unref();
@@ -56572,7 +56605,7 @@ setTimeout(()=>process.exit(),1000).unref();
56572
56605
  ` : void 0;
56573
56606
  const nextDriver = web && web.appDir !== void 0 ? `// Generated by AgentTwin: starts the Next.js app in ${web.appDir || "."} and sends ${web.method} ${web.path} to it on twins.
56574
56607
  import {spawn,spawnSync} from 'node:child_process';
56575
- import {existsSync,readFileSync} from 'node:fs';
56608
+ import {existsSync,readFileSync,realpathSync} from 'node:fs';
56576
56609
  import {createRequire} from 'node:module';
56577
56610
  import net from 'node:net';
56578
56611
  const environment=${JSON.stringify(scenario2.environment)},calls=${JSON.stringify(calls)},appDir=${JSON.stringify(join77(cwd, web.appDir))};
@@ -56609,16 +56642,38 @@ try{
56609
56642
  spawnSync(process.execPath,[file],{cwd:appDir,env,stdio:['ignore','ignore','pipe'],timeout:120000});
56610
56643
  }
56611
56644
  }catch{/* the dev script is optional */}
56612
- const next=createRequire(appDir+'/package.json').resolve('next/dist/bin/next');
56613
- server=spawn(process.execPath,[next,'dev','-p',String(port)],{cwd:appDir,env,stdio:['ignore','pipe','pipe'],detached:process.platform!=='win32'});
56614
- const keep=chunk=>{const text=chunk.toString();output=(output+text).slice(-20000);lastOutput=Date.now();process.stderr.write(text);};
56615
- server.stdout.on('data',keep);server.stderr.on('data',keep);server.once('exit',code=>{exited=code??1;});
56616
- const deadline=Date.now()+90000;
56617
- while(!(await open())){if(exited!==null)throw new Error('The Next.js server stopped while starting (exit '+exited+').');if(Date.now()>deadline)throw new Error('The Next.js server did not start listening within 90 seconds.');await new Promise(r=>setTimeout(r,150));}
56645
+ const nextReq=createRequire(appDir+'/package.json');
56646
+ const next=nextReq.resolve('next/dist/bin/next');
56647
+ let nextMajor=0,nextOutsideRepo=false;
56648
+ try{
56649
+ const nextPkg=nextReq.resolve('next/package.json');
56650
+ nextMajor=Number(String(JSON.parse(readFileSync(nextPkg,'utf8')).version??'0').split('.')[0])||0;
56651
+ const repoReal=realpathSync(${JSON.stringify(cwd)}),nextReal=realpathSync(nextPkg);
56652
+ nextOutsideRepo=!nextReal.startsWith(repoReal+'/')&&!nextReal.startsWith(repoReal+'\\\\');
56653
+ }catch{}
56654
+ const startServer=async webpack=>{
56655
+ output='';exited=null;
56656
+ const args=[next,'dev',...(webpack?['--webpack']:[]),'-p',String(port)];
56657
+ server=spawn(process.execPath,args,{cwd:appDir,env,stdio:['ignore','pipe','pipe'],detached:process.platform!=='win32'});
56658
+ const keep=chunk=>{const text=chunk.toString();output=(output+text).slice(-20000);lastOutput=Date.now();process.stderr.write(text);};
56659
+ server.stdout.on('data',keep);server.stderr.on('data',keep);server.once('exit',code=>{exited=code??1;});
56660
+ const deadline=Date.now()+90000;
56661
+ while(!(await open())){if(exited!==null)throw new Error('The Next.js server stopped while starting (exit '+exited+').');if(Date.now()>deadline)throw new Error('The Next.js server did not start listening within 90 seconds.');await new Promise(r=>setTimeout(r,150));}
56662
+ };
56663
+ let usingWebpack=nextMajor>=16&&nextOutsideRepo;
56664
+ if(usingWebpack)console.error('[agenttwin] Next.js '+nextMajor+' resolves outside the repo; starting with --webpack.');
56665
+ try{await startServer(usingWebpack);}catch(err){if(!usingWebpack&&nextMajor>=16&&/Could not find the Next\\.js package/i.test(output)){usingWebpack=true;console.error('[agenttwin] Next.js Turbopack could not resolve next/package.json; retrying with --webpack.');await startServer(true);}else throw err;}
56618
56666
  // A sign-in that fails does not stop the workflow: many (webhooks, crons) need no user, and one that does answers
56619
56667
  // 401, which the password sign-in below handles.
56620
56668
  let signedIn=false;
56621
- if(signIn){try{await signInThroughApp(signIn);signedIn=true;}catch(e){console.error('[agenttwin] '+(e&&e.message||e)+' Sending the workflow request without a signed-in user.');}}
56669
+ if(signIn){try{await signInThroughApp(signIn);signedIn=true;}catch(e){
56670
+ if(!usingWebpack&&nextMajor>=16&&/Could not find the Next\\.js package/i.test(output)){
56671
+ usingWebpack=true;stop();await new Promise(r=>setTimeout(r,300));
56672
+ console.error('[agenttwin] Next.js Turbopack failed during sign-in; restarting with --webpack.');
56673
+ await startServer(true);
56674
+ try{await signInThroughApp(signIn);signedIn=true;}catch(e2){console.error('[agenttwin] '+(e2&&e2.message||e2)+' Sending the workflow request without a signed-in user.');}
56675
+ }else console.error('[agenttwin] '+(e&&e.message||e)+' Sending the workflow request without a signed-in user.');
56676
+ }}
56622
56677
  if(signedIn){
56623
56678
  console.error('[agenttwin] '+signIn.email+' signed in through the app ('+signIn.provider+').');
56624
56679
  // Records the app creates after sign-in (mailbox, defaults) are often written in the background.
@@ -56652,6 +56707,14 @@ try{
56652
56707
  const bodyText=trpc||!qNames.size?payload:JSON.stringify(bodyArg??{});
56653
56708
  const send=()=>call(${JSON.stringify(web.path)}+(trpc?.kind==='query'?'?input='+encodeURIComponent(payload):(qs?'?'+qs:${JSON.stringify(scenario2.query ? "?" + scenario2.query : "")})),{method:${JSON.stringify(web.method)},headers:{...(slackForm?{'content-type':'application/x-www-form-urlencoded'}:form?{}:{'content-type':'application/json'}),'idempotency-key':'agenttwin-'+[...payload].reduce((h,c)=>(h*31+c.charCodeAt(0))>>>0,7).toString(16),...signed},...(['GET','HEAD'].includes(${JSON.stringify(web.method)})?{}:{body:slackForm?payload:form?formBody(bodyArg):bodyText})});
56654
56709
  let response=await send();
56710
+ if(response.status>=500&&!usingWebpack&&nextMajor>=16&&/Could not find the Next\\.js package/i.test(output)){
56711
+ await response.text().catch(()=>{});
56712
+ usingWebpack=true;stop();await new Promise(r=>setTimeout(r,300));
56713
+ console.error('[agenttwin] Next.js Turbopack failed on route; restarting with --webpack.');
56714
+ await startServer(true);
56715
+ if(signIn&&!signedIn){try{await signInThroughApp(signIn);signedIn=true;}catch{}}
56716
+ response=await send();
56717
+ }
56655
56718
  // A redirect to a sign-in or guest-session page: follow it as a browser would (the jar keeps its cookie), then ask again.
56656
56719
  // Still sent to sign-in: the workflow never ran, so the run is not a pass.
56657
56720
  const signInPath=l=>/\\/(?:api\\/)?(?:auth|login|log-in|signin|sign-in|session|guest)(?:\\/|\\?|$)/i.test(String(l).replace(/^https?:\\/\\/[^/]+/,''));
@@ -66147,7 +66210,7 @@ function routeWeight(method, path2) {
66147
66210
  if (/(^|\/)(webhooks?|callback|events?|inbound|incoming|notifications?|push|hooks?)(\/|$)/i.test(path2)) weight += 14;
66148
66211
  if (/(^|\/)(cron|jobs?|queue|tasks?|scheduled?|process|sync|digest)(\/|$)/i.test(path2)) weight += 6;
66149
66212
  if (path2.toLowerCase().split("/").some((segment) => twinnedVendors().has(segment))) weight += 5;
66150
- if (/(^|\/)(admin|debug|health|test|e2e|dev|internal|_next|og|sitemap|docs?|documentation)(\/|$)/i.test(path2)) weight -= 10;
66213
+ if (/(^|\/)(admin|debug|health|ping|status|version|metrics|ready|live|conf|config|settings|trace|test|e2e|dev|internal|_next|og|sitemap|docs?|documentation)(\/|$)/i.test(path2) || path2 === "/") weight -= 10;
66151
66214
  return weight;
66152
66215
  }
66153
66216
  function workflowKind(c) {
@@ -66155,7 +66218,8 @@ function workflowKind(c) {
66155
66218
  if (c.boltApp) return WORKFLOW_KINDS[0];
66156
66219
  if (!route) return WORKFLOW_KINDS[4];
66157
66220
  if (signInCallback(route, c.file)) return WORKFLOW_KINDS[3];
66158
- if (route.method !== "GET" && WEBHOOK_PATH.test(route.path)) return WORKFLOW_KINDS[0];
66221
+ const isBrowserHook = /(^|\/)browser(\/|$)/i.test(c.file ?? "") && /(^|\/)hooks\/(dialog|file-chooser)(\/|$)/i.test(route.path) && !c.calls?.length;
66222
+ if (route.method !== "GET" && WEBHOOK_PATH.test(route.path) && !isBrowserHook) return WORKFLOW_KINDS[0];
66159
66223
  if (JOB_PATH.test(route.path)) return WORKFLOW_KINDS[2];
66160
66224
  if (route.method !== "GET" && (c.calls ?? []).some((call2) => call2.write && !DATABASE.test(call2.provider) && MONEY_OR_SEND.test(call2.operation))) return WORKFLOW_KINDS[1];
66161
66225
  return WORKFLOW_KINDS[3];
@@ -66176,7 +66240,10 @@ function moneyWeight(c) {
66176
66240
  function rankWorkflows(list5) {
66177
66241
  const kind = (c) => WORKFLOW_KINDS.indexOf(workflowKind(c));
66178
66242
  const callback = (c) => signInCallback(c.web ?? c.serve, c.file) ? 1 : 0;
66179
- return list5.sort((a, b) => kind(a) - kind(b) || callback(a) - callback(b) || b.score + moneyWeight(b) - (a.score + moneyWeight(a)));
66243
+ const emptyOtherRoute = (c) => kind(c) === 3 && !c.calls?.length ? 1 : 0;
66244
+ const nonHelperFn = (c) => kind(c) === 4 && (c.calls?.length ?? 0) > 0 && (!c.exportName || nameWeight(c.exportName) >= 0);
66245
+ const tier = (c) => nonHelperFn(c) ? 3 : kind(c);
66246
+ return list5.sort((a, b) => tier(a) - tier(b) || callback(a) - callback(b) || emptyOtherRoute(a) - emptyOtherRoute(b) || b.score + moneyWeight(b) - (a.score + moneyWeight(a)));
66180
66247
  }
66181
66248
  function twinnedVendors() {
66182
66249
  if (vendors) return vendors;
@@ -66237,7 +66304,8 @@ async function runOneCommand(opts) {
66237
66304
  const ask = opts.ask ?? terminalAsk(interactive, log, emit2, Boolean(opts.emit));
66238
66305
  const seed = normalizeSeed(opts.seed ?? "42");
66239
66306
  const startedAt = opts.startedAt ?? Date.now();
66240
- const budgetLeft = (cap) => opts.deadline === void 0 ? cap : Math.min(cap, Math.max(0, opts.deadline - Date.now()));
66307
+ const effectiveDeadline = opts.deadline === void 0 ? void 0 : opts.deadline + setupSpentMs;
66308
+ const budgetLeft = (cap) => effectiveDeadline === void 0 ? cap : Math.min(cap, Math.max(0, effectiveDeadline - Date.now()));
66241
66309
  const caseStatus = (r) => r.status === "passed" ? "passed" : r.status === "failed" ? "found" : r.status === "incomplete" ? "skipped" : "error";
66242
66310
  const calls = (r) => r.events.filter((e) => isApplicationWrite(e) || e.operation === "fault").map((e) => ({ service: e.service, operation: e.operation, path: e.path, fault: e.operation === "fault", ...e.operation === "fault" && e.detail ? { detail: e.detail } : {} }));
66243
66311
  if (!opts.skipSetup) {
@@ -66289,9 +66357,10 @@ async function runOneCommand(opts) {
66289
66357
  const { inventoryWorkflows, tools, exports } = await scan;
66290
66358
  if (reused) log(dim(` Repository map from this run's first scan: ${tools.size} services and ${inventoryWorkflows.length} workflows.`));
66291
66359
  const projectDashboard = await integrations.connectProject(cwd, { interactive, ask, log });
66292
- const byEntry = new Map(exports.map((c) => [c.entrypoint, c]));
66360
+ const byEntry = new Map(exports.map((c) => [c.entrypoint, c])), byId = new Map(exports.map((c) => [c.id, c]));
66361
+ const collapsed = collapseCandidates(inventoryWorkflows, exports);
66293
66362
  const stepsOf = (w) => w.steps.map((step) => ({ ...tools.get(step.tool), operations: step.operations, title: tools.get(step.tool)?.title ?? step.tool })).filter((step) => step.category === "dependency");
66294
- const invocable = (w) => byEntry.get(w.entrypoint ?? "") ?? inventoryWorkflows.filter((x) => x.coveredBy === w.id).map((x) => byEntry.get(x.entrypoint ?? "")).find(Boolean);
66363
+ const invocable = (w) => byEntry.get(w.entrypoint ?? "") ?? byId.get(collapsed.get(w.id) ?? "") ?? inventoryWorkflows.filter((x) => x.coveredBy === w.id).map((x) => byEntry.get(x.entrypoint ?? "") ?? byId.get(collapsed.get(x.id) ?? "")).find(Boolean);
66295
66364
  const steps = /* @__PURE__ */ new Map(), candidates = [], notRunnable = [];
66296
66365
  let merged = 0;
66297
66366
  for (const w of inventoryWorkflows.filter((w2) => !w2.coveredBy && w2.entrypoint && w2.steps.length)) {
@@ -66418,7 +66487,7 @@ async function runOneCommand(opts) {
66418
66487
  const ownLock = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb"].some((f) => existsSync22(join95(cwd, appDir, f)));
66419
66488
  const outside = appDir !== "." && !workspaceDirs(cwd).has(appDir);
66420
66489
  at("installing dependencies", candidate.title);
66421
- if (appDir !== "." && !existsSync22(join95(cwd, appDir, "node_modules")) && (ownLock || outside || !existsSync22(join95(cwd, "node_modules")))) await runSetup(join95(cwd, appDir), { ask, log: trackCommand(log), interactive, only: "install" });
66490
+ if (appDir !== "." && !existsSync22(join95(cwd, appDir, "node_modules")) && (ownLock || outside)) await runSetup(join95(cwd, appDir), { ask, log: trackCommand(log), interactive, only: "install" });
66422
66491
  at("building workspace packages", candidate.title);
66423
66492
  {
66424
66493
  const t0 = Date.now();
@@ -66477,18 +66546,44 @@ async function runOneCommand(opts) {
66477
66546
  log(bold("3/7 Run") + dim(liveHosts.length ? " real workflow code against twins\u2026" : " real workflow code against twins (no production calls)\u2026"));
66478
66547
  if (liveHosts.length) log(yellow(` Connected for real: ${liveHosts.join(", ")}. Every case, including faults and duplicate runs, calls these with your key; use a sandbox account. agenttwin disconnect <host> returns a host to its twin.`));
66479
66548
  let clean;
66480
- try {
66481
- clean = await track(void 0);
66482
- } catch (error62) {
66483
- const reason2 = (error62 instanceof Error ? error62.message : String(error62)).split("\n")[0].slice(0, 240);
66484
- const tried = [...opts.triedWorkflows ?? [], { id: candidate.id, title: candidate.title, reason: reason2 }];
66485
- const triedFiles = new Set(tried.map((t) => candidates.find((c) => c.id === t.id)?.file).filter(Boolean));
66486
- const open7 = candidates.filter((c) => !c.suite && !tried.some((t) => t.id === c.id) && !(opts.testedWorkflows ?? []).includes(c.id));
66487
- const next = !candidate.suite && (!opts.workflow || opts.autoPicked) && tried.length < WORKFLOW_ATTEMPTS && Date.now() - startedAt < budgetLeft(WORKFLOW_BUDGET_MS) ? open7.find((c) => !triedFiles.has(c.file)) ?? open7[0] : void 0;
66488
- if (!next) throw error62;
66489
- log(yellow(` ${candidate.title} could not run here: ${reason2}`));
66490
- log(dim(` Trying the next workflow the scan found: ${next.title}. Test this one later with npx agenttwin --workflow "${candidate.title}".`));
66491
- return runOneCommand({ ...opts, workflow: next.id, autoPicked: true, triedWorkflows: tried, skipSuites: true, startedAt });
66549
+ for (let blockedTry = 0; ; blockedTry++) {
66550
+ try {
66551
+ clean = await track(void 0);
66552
+ break;
66553
+ } catch (error62) {
66554
+ const msg2 = error62 instanceof Error ? error62.message : String(error62);
66555
+ const blockedMatch = /AgentTwin blocked .*? to ([^\s(;]+)/i.exec(msg2);
66556
+ if (blockedMatch && blockedTry < 3) {
66557
+ const host = blockedMatch[1].toLowerCase().replace(/:\d+$/, "");
66558
+ const adapter = deepTwinForHost(host), collections = adapter ? ADAPTER_COLLECTIONS[adapter] : void 0;
66559
+ let added = false;
66560
+ if (adapter && collections) {
66561
+ const name2 = adapter.replaceAll("-", "_");
66562
+ if (!prepared.scenario.twins.some((t) => t.name === name2)) {
66563
+ const service = { name: name2, adapter, collections: collections.map((path2) => ({ path: path2, seed: [] })) };
66564
+ prepared.scenario.services.push(service);
66565
+ prepared.world.services.push(service);
66566
+ prepared.scenario.twins.push({ tier: "deep", provider: "hand-written twin", name: name2, title: PROVIDER_TITLES[adapter] ?? adapter, note: `${host} \u2192 found while running (the scan did not see it)`, service });
66567
+ log(dim(` Found ${host} while running (the scan missed it); using the ${PROVIDER_TITLES[adapter] ?? adapter} twin and rerunning.`));
66568
+ added = true;
66569
+ }
66570
+ } else if (!prepared.scenario.twins.some((t) => t.generic?.hosts?.includes(host))) {
66571
+ prepared.scenario.twins.push({ tier: "inferred", provider: "stateful REST twin inferred from calls", name: serviceName3(host), title: host, generic: { hosts: [host] }, note: `${host} \u2192 found while running (the scan did not see it): stateful REST twin, vendor-specific behavior is not modelled` });
66572
+ log(dim(` Found ${host} while running (the scan missed it); twinning it as a stateful REST service and rerunning.`));
66573
+ added = true;
66574
+ }
66575
+ if (added) continue;
66576
+ }
66577
+ const reason2 = msg2.split("\n")[0].slice(0, 240);
66578
+ const tried = [...opts.triedWorkflows ?? [], { id: candidate.id, title: candidate.title, reason: reason2 }];
66579
+ const triedFiles = new Set(tried.map((t) => candidates.find((c) => c.id === t.id)?.file).filter(Boolean));
66580
+ const open7 = candidates.filter((c) => !c.suite && !tried.some((t) => t.id === c.id) && !(opts.testedWorkflows ?? []).includes(c.id));
66581
+ const next = !candidate.suite && (!opts.workflow || opts.autoPicked) && tried.length < WORKFLOW_ATTEMPTS && Date.now() - startedAt < budgetLeft(WORKFLOW_BUDGET_MS) ? open7.find((c) => !triedFiles.has(c.file)) ?? open7[0] : void 0;
66582
+ if (!next) throw error62;
66583
+ log(yellow(` ${candidate.title} could not run here: ${reason2}`));
66584
+ log(dim(` Trying the next workflow the scan found: ${next.title}. Test this one later with npx agenttwin --workflow "${candidate.title}".`));
66585
+ return runOneCommand({ ...opts, workflow: next.id, autoPicked: true, triedWorkflows: tried, skipSuites: true, startedAt });
66586
+ }
66492
66587
  }
66493
66588
  if (pickedSuite && clean.exitCode === null && !((suiteFacts(candidate, clean.stdout).suite?.passed ?? 0) > 0)) {
66494
66589
  const fallback = candidates.find((c) => !c.suite && !(opts.testedWorkflows ?? []).includes(c.id));
@@ -67180,7 +67275,9 @@ ${clean.stdout ?? ""}`) : void 0;
67180
67275
  }
67181
67276
  }
67182
67277
  const cleanEvents = clean.events;
67183
- const idle = (clean.status === "passed" || !!candidate.suite && suiteRan()) && !cleanEvents.some(isApplicationWrite) && !cleanCalls.some((c) => c.isWrite && c.committed === true) && !clean.assertions.some((a) => a.service !== "none");
67278
+ const LOCAL_ENGINES = /* @__PURE__ */ new Set(["postgres", "sqlite", "mysql", "redis", "mongodb", "clickhouse"]);
67279
+ const hasExternalCall = cleanCalls.length > 0 || cleanEvents.some((e) => !LOCAL_ENGINES.has(e.service));
67280
+ const idle = (clean.status === "passed" || !!candidate.suite && suiteRan()) && !cleanEvents.some(isApplicationWrite) && !cleanCalls.some((c) => c.isWrite && c.committed === true) && !clean.assertions.some((a) => a.service !== "none") && !hasExternalCall;
67184
67281
  const emptyReads = [...new Set(cleanEvents.filter((e) => e.operation === "read" && /^SELECT 0$/.test(e.detail ?? "")).map((e) => (e.path ?? "").replace(/^\//, "")))].filter(Boolean);
67185
67282
  const autoSuite = !opts.workflow || opts.triedSuites !== void 0;
67186
67283
  const routeFallback = candidates.find((c) => !c.suite && !(opts.testedWorkflows ?? []).includes(c.id));
@@ -67218,7 +67315,7 @@ ${clean.stdout ?? ""}`) : void 0;
67218
67315
  if (runnable.length < supportedFaults.length) log(dim(` ${faultConcurrency > 1 ? `${faultConcurrency} failure scenarios run at a time, a wave takes about ${Math.round(cleanMs / 1e3)} s` : `One run takes about ${Math.round(cleanMs / 1e3)} s here`}, so ${runnable.length} of ${supportedFaults.length} failure scenarios fit the time. The rest: npx agenttwin --workflow "${candidate.title}" with AGENTTWIN_WORKFLOW_BUDGET_MS set higher.`));
67219
67316
  const deferred = [];
67220
67317
  const runFault = async (fault, deferStartupFailure) => {
67221
- if (opts.deadline !== void 0 && Date.now() > opts.deadline - 15e3) {
67318
+ if (opts.deadline !== void 0 && Date.now() > opts.deadline + setupSpentMs - 15e3) {
67222
67319
  skippedFaults.push({ id: fault.id, title: fault.title, why: "time" });
67223
67320
  emit2({ type: "case-end", id: fault.id, status: "skipped", calls: [] });
67224
67321
  log(` ${yellow("SKIP ")} ${fault.title}${dim(" (the run budget ended first)")}`);
@@ -67307,7 +67404,7 @@ ${clean.stdout ?? ""}`) : void 0;
67307
67404
  log(dim(` Campaign: ${slice.length} of ${campaignCases.length} derived fault scenario${campaignCases.length === 1 ? "" : "s"} (network, filesystem, crash, clock), one per model.`));
67308
67405
  const campaignStart = Date.now();
67309
67406
  for (const fault of slice) {
67310
- if (opts.deadline !== void 0 && Date.now() > opts.deadline - 15e3 || Date.now() - campaignStart > CAMPAIGN_BUDGET_MS) {
67407
+ if (opts.deadline !== void 0 && Date.now() > opts.deadline + setupSpentMs - 15e3 || Date.now() - campaignStart > CAMPAIGN_BUDGET_MS) {
67311
67408
  skippedFaults.push({ id: fault.id, title: fault.title, why: "time" });
67312
67409
  log(` ${yellow("SKIP ")} ${fault.title}${dim(" (the run budget ended first)")}`);
67313
67410
  continue;