agenttwin 0.3.44 → 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 (79) hide show
  1. package/dist/api.js +185 -59
  2. package/dist/dashboard/assets/next/static/chunks/app/_not-found/{page-d3c4451763af3bb2.js → page-ca2a678442778cc4.js} +1 -1
  3. package/dist/dashboard/assets/next/static/chunks/app/about/{page-e8f70f456b3e001f.js → page-f12d76165cc1cfdb.js} +1 -1
  4. package/dist/dashboard/assets/next/static/chunks/app/account/password/{page-13d4d6cf28183f27.js → page-c2ce3c796c817ca1.js} +1 -1
  5. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-dc4de82f3c8b5ee5.js +1 -0
  6. package/dist/dashboard/assets/next/static/chunks/app/auth/page-dc4de82f3c8b5ee5.js +1 -0
  7. package/dist/dashboard/assets/next/static/chunks/app/blog/{layout-47a0e404f3655e69.js → layout-52698c1f7512ab03.js} +1 -1
  8. package/dist/dashboard/assets/next/static/chunks/app/compare/page-dc4de82f3c8b5ee5.js +1 -0
  9. package/dist/dashboard/assets/next/static/chunks/app/contact/page-dc4de82f3c8b5ee5.js +1 -0
  10. package/dist/dashboard/assets/next/static/chunks/app/dashboard/{layout-00f2a0cb3dd9dfcc.js → layout-b5ef02cb8f06edca.js} +1 -1
  11. package/dist/dashboard/assets/next/static/chunks/app/dashboard/{page-d2f69d996bda5b65.js → page-e175e18f842b558f.js} +1 -1
  12. package/dist/dashboard/assets/next/static/chunks/app/demo/{page-0ebf741047bacc39.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-f9e33ed2f89fd53d.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-40532b5cef9a88c1.js +1 -0
  22. package/dist/dashboard/assets/next/static/chunks/app/page-a8275b37886e34a8.js +1 -0
  23. package/dist/dashboard/assets/next/static/chunks/app/pricing/{page-0d9e6abaa82f633b.js → 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-d82d70f6caa12d7c.js → page-031ee9c843b9c428.js} +1 -1
  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-efea46ea53572102.js +1 -0
  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-8016af41043dfe3d.js → main-app-1ec13ceef4a34729.js} +1 -1
  41. package/dist/dashboard/assets/next/static/chunks/{webpack-5e3b77bcb344d4ed.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 +185 -59
  45. package/dist/gateway.js +185 -59
  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/api-policy/page-e6ac9852938ee195.js +0 -1
  51. package/dist/dashboard/assets/next/static/chunks/app/auth/page-e6ac9852938ee195.js +0 -1
  52. package/dist/dashboard/assets/next/static/chunks/app/compare/page-e6ac9852938ee195.js +0 -1
  53. package/dist/dashboard/assets/next/static/chunks/app/contact/page-e6ac9852938ee195.js +0 -1
  54. package/dist/dashboard/assets/next/static/chunks/app/developers/page-e6ac9852938ee195.js +0 -1
  55. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-e6ac9852938ee195.js +0 -1
  56. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-526ed9ed987ec1ab.js +0 -1
  57. package/dist/dashboard/assets/next/static/chunks/app/guides/page-e6ac9852938ee195.js +0 -1
  58. package/dist/dashboard/assets/next/static/chunks/app/layout-8e8607ccec674a88.js +0 -1
  59. package/dist/dashboard/assets/next/static/chunks/app/login/page-0fdb6c325a08152f.js +0 -1
  60. package/dist/dashboard/assets/next/static/chunks/app/not-found-e6ac9852938ee195.js +0 -1
  61. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-aa8315fd545cfcab.js +0 -1
  62. package/dist/dashboard/assets/next/static/chunks/app/page-563661520c08bc87.js +0 -1
  63. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-e6ac9852938ee195.js +0 -1
  64. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-e6ac9852938ee195.js +0 -1
  65. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-e6ac9852938ee195.js +0 -1
  66. package/dist/dashboard/assets/next/static/chunks/app/security/page-e6ac9852938ee195.js +0 -1
  67. package/dist/dashboard/assets/next/static/chunks/app/signup/page-0fdb6c325a08152f.js +0 -1
  68. package/dist/dashboard/assets/next/static/chunks/app/status/page-1dce1a7886e3e6f0.js +0 -1
  69. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-e6ac9852938ee195.js +0 -1
  70. package/dist/dashboard/assets/next/static/chunks/app/terms/page-e6ac9852938ee195.js +0 -1
  71. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-eac4c37292388b51.js +0 -1
  72. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-ece40a44e9fbe945.js +0 -1
  73. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-52b97f3b9b06f7f7.js +0 -1
  74. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-b5f3b1ecfef066bb.js +0 -1
  75. package/dist/dashboard/assets/next/static/chunks/app/v2/page-e63b0b6f3f0512e0.js +0 -1
  76. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-52b97f3b9b06f7f7.js +0 -1
  77. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-e6ac9852938ee195.js +0 -1
  78. /package/dist/dashboard/assets/next/static/{485syozzbgr0SePb1vNxp → pGgp6m8IvF1eEP2vBkhqX}/_buildManifest.js +0 -0
  79. /package/dist/dashboard/assets/next/static/{485syozzbgr0SePb1vNxp → pGgp6m8IvF1eEP2vBkhqX}/_ssgManifest.js +0 -0
package/dist/gateway.js CHANGED
@@ -3953,6 +3953,10 @@ function installRetry(step, output2) {
3953
3953
  const pm = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a))?.split("@")[0] : step.command;
3954
3954
  const tail = step.command === "corepack" ? step.args.slice(1) : step.command === "npx" ? step.args.slice(2) : step.args;
3955
3955
  const pinned = step.command === "corepack" || step.command === "npx" ? step.args.find((a) => /^(npm|pnpm|yarn|bun)(@|$)/.test(a)) : pm;
3956
+ 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")))
3957
+ return { why: "pnpm could not switch to the pinned version", step: { ...step, args: ["--config.manage-package-manager-versions=false", ...step.args] } };
3958
+ if (pm === "pnpm" && /ERR_PNPM_UNUSED_PATCH/.test(output2) && !step.args.some((a) => a.includes("allow-unused-patches")))
3959
+ return { why: "pnpm rejected an unused patch in the lockfile", step: { ...step, args: [...step.args, "--config.allow-unused-patches=true"] } };
3956
3960
  if (pm === "pnpm" && /ERR_PNPM_(OUTDATED_LOCKFILE|LOCKFILE_CONFIG_MISMATCH|LOCKFILE_MISSING_DEPENDENCY)|frozen.lockfile|specifiers in the lockfile/i.test(output2))
3957
3961
  return { why: "The lockfile is behind package.json, so a frozen install stops", step: { ...step, args: [...step.args, "--no-frozen-lockfile"] } };
3958
3962
  const lockfile = pm === "pnpm" ? /lockfileVersion[\s│|]+of[\s│|]+(\d+)(?:\.(\d+))?[\s│|]+is[\s│|]+incompatible/i.exec(output2) : null;
@@ -4014,8 +4018,8 @@ async function runSetup(cwd, opts) {
4014
4018
  const buildLimitMs = Number(process.env.AGENTTWIN_SETUP_BUILD_TIMEOUT_MS) || 20 * 6e4;
4015
4019
  let timedOut = false;
4016
4020
  let installedManager;
4017
- const exec12 = (step) => new Promise((resolve27) => {
4018
- 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 ?? ""}` } : {} } });
4021
+ const exec12 = (step, extraEnv) => new Promise((resolve27) => {
4022
+ 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 ?? ""}` } : {} } });
4019
4023
  let tail = "";
4020
4024
  const keep = (c) => {
4021
4025
  tail = (tail + c.toString()).slice(-4e3);
@@ -4051,12 +4055,12 @@ async function runSetup(cwd, opts) {
4051
4055
  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.)`);
4052
4056
  return false;
4053
4057
  }
4054
- for (let current2 = step, tries = 0; code !== 0 && step.id === "install" && tries < 3; tries++) {
4058
+ 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(tail)) && tries < 3; tries++) {
4055
4059
  const retry = installRetry(current2, tail);
4056
4060
  if (!retry) break;
4057
4061
  opts.log(` ${retry.why}; running ${show(retry.step)}\u2026`);
4058
4062
  current2 = retry.step;
4059
- ({ code, tail } = await exec12(retry.step));
4063
+ ({ code, tail } = 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));
4060
4064
  }
4061
4065
  let left = code !== 0 && step.id === "build" && plan.unbuilt ? unbuiltWorkspacePackages(cwd, opts.appDir) : void 0;
4062
4066
  if (left?.length) {
@@ -11072,6 +11076,11 @@ var init_http_world = __esm({
11072
11076
  const target2 = aliasRequest(name, host, req.url ?? "/");
11073
11077
  const model = compatibleModel(name, body2);
11074
11078
  const r = await twin(new Request(`https://${target2.host}${target2.url}`, { method, headers, ...model.body ? { body: model.body } : {} }));
11079
+ if ((r.status === 501 || r.status === 404) && name === "ai-gateway" && method === "GET" && /^\/(?:v1\/)?models\/([^/]+\/[^/]+)\/endpoints$/.test(target2.url.split("?")[0])) {
11080
+ const id2 = /^\/(?:v1\/)?models\/([^/]+\/[^/]+)\/endpoints$/.exec(target2.url.split("?")[0])[1];
11081
+ 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"] }] } }));
11082
+ return { status: 200, headers: new Headers({ "content-type": "application/json" }), bytes: payload, actions: [] };
11083
+ }
11075
11084
  return { status: r.status, headers: r.headers, bytes: model.restore(Buffer.from(await r.arrayBuffer())), actions: log.drain() };
11076
11085
  };
11077
11086
  if (workspace && method !== "GET") this.causing[service.name] = 1;
@@ -20139,7 +20148,7 @@ var init_state_seeding = __esm({
20139
20148
  if (/name/.test(name)) return "AgentTwin Test";
20140
20149
  return `agenttwin-${name}-${n}`;
20141
20150
  };
20142
- NOT_A_SERVICE = /(^|\.)(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)$/;
20151
+ NOT_A_SERVICE = /(^|\.)(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)$/;
20143
20152
  }
20144
20153
  });
20145
20154
 
@@ -20324,11 +20333,12 @@ function packRecordSample(pack, resource2, id2, depth = 0, read2 = /* @__PURE__
20324
20333
  }
20325
20334
  return record8;
20326
20335
  }
20327
- function sourcesNear(root2, file2) {
20336
+ function sourcesNear(root2, file2, opts) {
20328
20337
  const out = [], seen = /* @__PURE__ */ new Set();
20329
20338
  const visit2 = (path2, level) => {
20330
20339
  if (seen.has(path2) || level > 1) return;
20331
20340
  seen.add(path2);
20341
+ if (opts?.excludeEnvFiles && level > 0 && SHARED_ENV_FILE.test(path2)) return;
20332
20342
  let text5 = "";
20333
20343
  try {
20334
20344
  text5 = readFileSync8(join46(root2, path2), "utf8");
@@ -20434,14 +20444,15 @@ function inferredSignature(root2, route, file2, settings) {
20434
20444
  const text5 = source + "\n" + sourcesNear(root2, file2).join("\n");
20435
20445
  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);
20436
20446
  const secretNames = [.../* @__PURE__ */ new Set([...settings, ...[...text5.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));
20437
- if (/from\s+['"`](?:svix|standardwebhooks)['"`]|require\(\s*['"`](?:svix|standardwebhooks)['"`]\s*\)|@clerk\/[\w-]+\/webhooks|['"`](?:svix|webhook)-signature['"`]/.test(text5) && secretNames.length) {
20447
+ if (/from\s+['"`](?:svix|standardwebhooks)['"`]|require\(\s*['"`](?:svix|standardwebhooks)['"`]\s*\)|@clerk\/[\w-]+\/webhooks|['"`](?:svix|webhook)-signature['"`]|\.webhooks\.unwrap\s*\(/.test(text5) && secretNames.length) {
20438
20448
  const literals2 = [...source.matchAll(/(?:case\s*|===?\s*|!==?\s*)['"`]([a-z][a-z0-9_]*(?:\.[a-z0-9_]+){1,3})['"`]/g)].map((m) => m[1]);
20439
20449
  const type = literals2[0] ?? "test.event", resource2 = type.split(".")[0].replace(/\W/g, "_");
20450
+ const callId = /\.call_id\b/.test(source) ? { call_id: "call_agenttwin_1" } : {};
20440
20451
  return {
20441
20452
  scheme: { kind: "webhook-id", header: "webhook-signature" },
20442
20453
  secret: `whsec_${randomBytes8(24).toString("base64")}`,
20443
20454
  settings: secretNames,
20444
- body: { type, timestamp: new Date(1762257600 * 1e3).toISOString(), data: { id: `${resource2}_agenttwin_1`, object: resource2 } },
20455
+ 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 } },
20445
20456
  how: "Standard Webhooks signature (webhook-id, webhook-timestamp, webhook-signature)"
20446
20457
  };
20447
20458
  }
@@ -20463,9 +20474,15 @@ function inferredSignature(root2, route, file2, settings) {
20463
20474
  }
20464
20475
  function signedUnlessKnown(root2, route, file2, settings) {
20465
20476
  const signed = signedWebhook(root2, route, file2, settings);
20466
- return signed?.guessed && webhookEvent(route, settings) ? void 0 : signed;
20467
- }
20468
- var statIsDir, SIGNING_DRIVER, SECRET_NAME;
20477
+ if (!signed?.guessed) return signed;
20478
+ if (webhookEvent(route, settings)) return void 0;
20479
+ const segments = route.path.toLowerCase().split("/").filter((s) => s && !GENERIC_WEBHOOK_SEGMENTS.has(s) && !/^\[/.test(s) && !/^:/.test(s));
20480
+ const packTokens = /* @__PURE__ */ new Set([signed.pack.toLowerCase(), signed.vendor.toLowerCase()]);
20481
+ if (segments.some((s) => !packTokens.has(s))) return void 0;
20482
+ if (!webhookPack(route.path, sourcesNear(root2, file2, { excludeEnvFiles: true }).join("\n"))) return void 0;
20483
+ return signed;
20484
+ }
20485
+ var statIsDir, SHARED_ENV_FILE, GENERIC_WEBHOOK_SEGMENTS, SIGNING_DRIVER, SECRET_NAME;
20469
20486
  var init_webhook_signing = __esm({
20470
20487
  "src/flow/webhook-signing.ts"() {
20471
20488
  "use strict";
@@ -20479,6 +20496,8 @@ var init_webhook_signing = __esm({
20479
20496
  return false;
20480
20497
  }
20481
20498
  };
20499
+ SHARED_ENV_FILE = /(?:^|\/|\\)env(?:\.[cm]?[jt]sx?|\/(?:index|server|client|schema)\.[cm]?[jt]sx?)?$/i;
20500
+ GENERIC_WEBHOOK_SEGMENTS = /* @__PURE__ */ new Set(["api", "v1", "v2", "v3", "webhook", "webhooks", "hook", "hooks", "events", "event", "callback", "callbacks", "notify", "incoming", "route", "public", "internal"]);
20482
20501
  SIGNING_DRIVER = String.raw`
20483
20502
  // Sign with the secret the app was given: a twin pack can issue its own (STRIPE_WEBHOOK_SECRET), and the scenario's
20484
20503
  // value only fills a setting nothing else set.
@@ -42184,14 +42203,14 @@ var init_input_formats = __esm({
42184
42203
  function missingInputFields(stderr, stdout = "") {
42185
42204
  const found = /* @__PURE__ */ new Map();
42186
42205
  const bodies = [];
42187
- for (const m of stderr.matchAll(/HTTP 4\d\d from \S+ \S+?:\s*(\{.*)$/gm)) {
42188
- let body2;
42189
- try {
42190
- body2 = JSON.parse(m[1]);
42191
- } catch {
42192
- continue;
42193
- }
42194
- bodies.push(body2);
42206
+ for (const m of stderr.matchAll(/HTTP 4\d\d from \S+ \S+:(?=\s|\{)\s*(.+)$/gm)) {
42207
+ const raw2 = m[1].trim();
42208
+ if (raw2.startsWith("{")) {
42209
+ try {
42210
+ bodies.push(JSON.parse(raw2));
42211
+ } catch {
42212
+ }
42213
+ } else bodies.push({ error: raw2 });
42195
42214
  }
42196
42215
  for (const line of stdout.split("\n")) {
42197
42216
  try {
@@ -42236,10 +42255,10 @@ function missingInputFields(stderr, stdout = "") {
42236
42255
  found.set(name, { name, ...expected ? { expected } : {} });
42237
42256
  }
42238
42257
  for (const x of Object.values(o)) if (typeof x === "string") {
42239
- 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);
42258
+ 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);
42240
42259
  if (t && safeField(t[1]) && !/^(?:it|this|that|body|request|input|value|fields?|parameters?)$/i.test(t[1])) {
42241
- const name = t[1].charAt(0).toLowerCase() + t[1].slice(1), kind = t[2]?.toLowerCase();
42242
- if (!found.has(name)) found.set(name, { name, ...kind === "array" || kind === "list" ? { expected: "array" } : kind === "number" ? { expected: "number" } : {} });
42260
+ const name = t[1].charAt(0).toLowerCase() + t[1].slice(1), kind = t[2]?.toLowerCase(), plural5 = t[3].toLowerCase() === "are";
42261
+ if (!found.has(name)) found.set(name, { name, ...kind === "array" || kind === "list" || !kind && plural5 ? { expected: "array" } : kind === "number" ? { expected: "number" } : kind === "boolean" ? { expected: "boolean" } : {} });
42243
42262
  }
42244
42263
  }
42245
42264
  for (const x of Object.values(o)) if (x && typeof x === "object") visit2(x);
@@ -42254,9 +42273,10 @@ function testValueFor(field2) {
42254
42273
  if (/^(?:prompt|message|question|query|input|text|content)$/i.test(field2.name) && field2.expected !== "array" && field2.expected !== "object" && field2.expected !== "record") return CHAT_TEXT;
42255
42274
  if (field2.expected === "number" || field2.expected === "integer") return 1;
42256
42275
  if (field2.expected === "boolean") return true;
42257
- if (field2.expected === "array") return [];
42276
+ if (field2.expected === "array") return ["test"];
42258
42277
  if (field2.expected === "object" || field2.expected === "record") return {};
42259
42278
  const n = field2.name.toLowerCase();
42279
+ if (/^(?:accept|agree|allow|confirm|enabled|active|ok|verified)$/.test(n)) return true;
42260
42280
  if (/email/.test(n)) return "ada@example.com";
42261
42281
  if (/url|uri|redirect/.test(n)) return "https://example.com/";
42262
42282
  if (/(^|_)(amount|count|quantity|qty|limit|page)$/.test(n)) return 1;
@@ -42340,7 +42360,7 @@ var init_package = __esm({
42340
42360
  "package.json"() {
42341
42361
  package_default = {
42342
42362
  name: "agenttwin",
42343
- version: "0.3.44",
42363
+ version: "0.3.46",
42344
42364
  description: "AgentTwin builds digital twins for testing AI agents. The current CLI prepares supported Node.js workflows with synthetic services, failures, and outcome checks.",
42345
42365
  mcpName: "io.github.AgentTwin/agenttwin",
42346
42366
  keywords: [
@@ -45856,7 +45876,8 @@ async function analyzeWorkflows(root2, opts = {}) {
45856
45876
  for (const [exportName, local] of f.exports) {
45857
45877
  const { calls: reached, env, files: touched, channels } = closure(file2, local);
45858
45878
  const calls = reached.filter((c) => !/^use[A-Z]/.test(c.operation));
45859
- if ((/\.[jt]sx$/.test(file2) && /^[A-Z]/.test(exportName) || /^use[A-Z]/.test(exportName)) && !ROUTE_FILE.test(file2)) continue;
45879
+ 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;
45880
+ if (/(?:^|\/)(?:instrumentation(?:\.client)?|test-utils)\.[cm]?[jt]s$/i.test(file2)) continue;
45860
45881
  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);
45861
45882
  if (!calls.length && !opts.all && !verifiesWebhook && !f.trpcHandler) continue;
45862
45883
  const fn = f.functions.get(local);
@@ -46231,6 +46252,17 @@ async function analyzeWorkflows(root2, opts = {}) {
46231
46252
  const python = await analyzePythonWorkflows(root2);
46232
46253
  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));
46233
46254
  }
46255
+ function collapseCandidates(inventory, analyzed) {
46256
+ const absorbed = /* @__PURE__ */ new Map();
46257
+ for (const workflow of inventory) {
46258
+ const [file2, member] = (workflow.entrypoint ?? "").split("#");
46259
+ const routeMatch = /^route:([^:]+):(.+?)@(\d+)$/i.exec(member ?? "");
46260
+ const routeMethod = routeMatch?.[1]?.toUpperCase(), routeLine = routeMatch?.[3];
46261
+ 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}`));
46262
+ if (match) absorbed.set(workflow.id, match.id);
46263
+ }
46264
+ return absorbed;
46265
+ }
46234
46266
  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;
46235
46267
  var init_analyze = __esm({
46236
46268
  "src/flow/analyze.ts"() {
@@ -52348,12 +52380,36 @@ function resolveTwin(service) {
52348
52380
  }
52349
52381
  return gapPlan(service);
52350
52382
  }
52383
+ function contractEndpointMatches(endpoint, path2, optionalJson = false) {
52384
+ const clean = path2.split("?")[0] ?? "/";
52385
+ const pattern = endpoint.split("?")[0].split(",").map((part) => {
52386
+ let src = part.trim().replace(/[.*+?^$()|[\]\\]/g, (m) => m === "{" || m === "}" || m === "|" ? m : "\\" + m);
52387
+ src = src.replace(/\{([^{}|]+\|[^{}]+)\}/g, (_, alts) => `(?:${alts})`).replace(/<repo>/g, "[^/]+/[^/]+").replace(/<destination-url>/g, ".+").replace(/<[^>]+>|\{[^}]+\}/g, "[^/]+");
52388
+ if (optionalJson && src.endsWith("\\.json")) src = src.slice(0, -6) + "(?:\\.json)?";
52389
+ return `^${src}$`;
52390
+ }).join("|");
52391
+ return new RegExp(pattern).test(clean);
52392
+ }
52393
+ function builtinCoversCalls(key3, calls) {
52394
+ const contract = CONTRACTS[key3];
52395
+ if (!contract || !calls.length) return true;
52396
+ if (key3 === "linear") {
52397
+ return calls.every((c) => !c.operation || /^(?:graphql|request|fetch)$/i.test(c.operation) || LINEAR_OPERATIONS.has(c.operation));
52398
+ }
52399
+ const optionalJson = key3 === "twilio";
52400
+ return calls.every((c) => {
52401
+ if (!c.path) return true;
52402
+ const method = c.method?.toUpperCase();
52403
+ return contract.operations.some((op2) => (!method || op2.method.split(/[|/]/).includes(method)) && contractEndpointMatches(op2.endpoint, c.path, optionalJson));
52404
+ });
52405
+ }
52351
52406
  function packMethodCollection(pack, operation) {
52352
52407
  return METHOD_COLLECTIONS[pack]?.find(([re]) => re.test(operation))?.[1];
52353
52408
  }
52354
52409
  function packFor(service) {
52355
52410
  if (!packCatalog()) return void 0;
52356
- const byName = packRecord(service.key.startsWith("pack:") ? service.key.slice(5) : service.key);
52411
+ const rawKey = service.key.startsWith("pack:") ? service.key.slice(5) : service.key;
52412
+ const byName = packRecord(rawKey) ?? packRecord(rawKey.replace(/-/g, ""));
52357
52413
  if (byName) return byName;
52358
52414
  if (service.key.startsWith("sdk:")) {
52359
52415
  const bySdk = packForSdk(service.key.slice(4));
@@ -52389,7 +52445,7 @@ function gapPlan(service) {
52389
52445
  env: /mysql/i.test(service.key) ? { MYSQL_URL: "mysql://agenttwin-gap.invalid/db" } : /mongo/i.test(service.key) ? { MONGODB_URI: "mongodb://agenttwin-gap.invalid/db", MONGO_URL: "mongodb://agenttwin-gap.invalid/db" } : {}
52390
52446
  };
52391
52447
  }
52392
- var ENGINE_PORTS, ENGINE_TITLES, PROTOCOL_ENGINES, TIER_RANK, registry3, serviceName3, DEEP, SLACK_SUBSET, deep, postgresEngine, internalCollections, CLICKHOUSE_NOTE, engines, genericRest, METHOD_COLLECTIONS, azureOpenAIHost, packs, packTwinPlan;
52448
+ var ENGINE_PORTS, ENGINE_TITLES, PROTOCOL_ENGINES, TIER_RANK, registry3, serviceName3, DEEP, SLACK_SUBSET, LINEAR_OPERATIONS, deep, postgresEngine, internalCollections, CLICKHOUSE_NOTE, engines, genericRest, METHOD_COLLECTIONS, azureOpenAIHost, packs, packTwinPlan;
52393
52449
  var init_providers = __esm({
52394
52450
  "src/flow/providers.ts"() {
52395
52451
  "use strict";
@@ -52406,6 +52462,7 @@ var init_providers = __esm({
52406
52462
  serviceName3 = (key3) => (key3.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^[^a-z]+/, "") || "service").slice(0, 40);
52407
52463
  DEEP = new Set(Object.keys(PROVIDER_HOSTS).filter((adapter) => Object.hasOwn(ADAPTER_COLLECTIONS, adapter)));
52408
52464
  SLACK_SUBSET = (c) => c.operation === "chat.postMessage" && c.argKeys.every((k) => k === "channel" || k === "text") || /^conversations\.(history|list)$/.test(c.operation);
52465
+ LINEAR_OPERATIONS = new Set(CONTRACTS.linear.operations.map((o) => o.endpoint.replace(/^\/graphql\s+(?:query|mutation)\s+/, "").replace(/\(.*/, "").trim()));
52409
52466
  deep = { name: "hand-written twin", tier: "deep", resolve(service) {
52410
52467
  if (!DEEP.has(service.key)) return void 0;
52411
52468
  if (service.key === "slack" && packRecord("slack") && !service.calls.every(SLACK_SUBSET)) return void 0;
@@ -52414,6 +52471,10 @@ var init_providers = __esm({
52414
52471
  const builtinMissing = operations.filter((o) => !STRIPE_OPERATIONS.includes(o)), packMissing = operations.filter((o) => !PACK_STRIPE_OPERATIONS.has(o));
52415
52472
  if (builtinMissing.length && packMissing.length < builtinMissing.length) return void 0;
52416
52473
  }
52474
+ if (service.key !== "openai" && service.key !== "anthropic" && service.key !== "slack" && service.key !== "stripe") {
52475
+ const pack = packRecord(service.key) ?? packRecord(service.key.replace(/-/g, ""));
52476
+ if (pack && !builtinCoversCalls(service.key, service.calls)) return void 0;
52477
+ }
52417
52478
  return {
52418
52479
  tier: "deep",
52419
52480
  provider: this.name,
@@ -54193,6 +54254,7 @@ async function prepareWorkflow(cwd, candidate, ask, log, discovered) {
54193
54254
  const slack = signed.pack === "slack" ? scenario.services.find((sv) => sv.name === signed.pack || String(sv.adapter ?? "") === "pack:slack") : void 0;
54194
54255
  if (slack && typeof about?.channel === "string" && typeof about.ts === "string") {
54195
54256
  for (const c of slackEventSeed({ channel: about.channel, ts: about.ts, user: about.user, text: about.text })) {
54257
+ if (!String(slack.adapter ?? "").startsWith("pack:") && c.path === "/channel_members") continue;
54196
54258
  const have = slack.collections.find((x) => x.path === c.path);
54197
54259
  if (!have) slack.collections.push(c);
54198
54260
  else for (const r of c.seed) if (!have.seed.some((x) => x.id === r.id)) have.seed.push(r);
@@ -54512,7 +54574,7 @@ try{
54512
54574
  :v[${JSON.stringify(SLACK_CLIENT)}]?await slack()
54513
54575
  :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});})()
54514
54576
  :Object.fromEntries(await Promise.all(Object.entries(v).map(async([k,x])=>[k,await hydrate(x)])))):v;
54515
- 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)}:{})}));}
54577
+ 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)}:{})}));}
54516
54578
  }catch(error){console.error(error);process.exitCode=1;}
54517
54579
  // Open pools and sockets would keep the process alive; exit once the calls have settled.
54518
54580
  setTimeout(()=>process.exit(),1000).unref();
@@ -54766,7 +54828,7 @@ setTimeout(()=>process.exit(),1000).unref();
54766
54828
  ` : void 0;
54767
54829
  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.
54768
54830
  import {spawn,spawnSync} from 'node:child_process';
54769
- import {existsSync,readFileSync} from 'node:fs';
54831
+ import {existsSync,readFileSync,realpathSync} from 'node:fs';
54770
54832
  import {createRequire} from 'node:module';
54771
54833
  import net from 'node:net';
54772
54834
  const environment=${JSON.stringify(scenario.environment)},calls=${JSON.stringify(calls)},appDir=${JSON.stringify(join67(cwd, web.appDir))};
@@ -54803,16 +54865,38 @@ try{
54803
54865
  spawnSync(process.execPath,[file],{cwd:appDir,env,stdio:['ignore','ignore','pipe'],timeout:120000});
54804
54866
  }
54805
54867
  }catch{/* the dev script is optional */}
54806
- const next=createRequire(appDir+'/package.json').resolve('next/dist/bin/next');
54807
- server=spawn(process.execPath,[next,'dev','-p',String(port)],{cwd:appDir,env,stdio:['ignore','pipe','pipe'],detached:process.platform!=='win32'});
54808
- const keep=chunk=>{const text=chunk.toString();output=(output+text).slice(-20000);lastOutput=Date.now();process.stderr.write(text);};
54809
- server.stdout.on('data',keep);server.stderr.on('data',keep);server.once('exit',code=>{exited=code??1;});
54810
- const deadline=Date.now()+90000;
54811
- 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));}
54868
+ const nextReq=createRequire(appDir+'/package.json');
54869
+ const next=nextReq.resolve('next/dist/bin/next');
54870
+ let nextMajor=0,nextOutsideRepo=false;
54871
+ try{
54872
+ const nextPkg=nextReq.resolve('next/package.json');
54873
+ nextMajor=Number(String(JSON.parse(readFileSync(nextPkg,'utf8')).version??'0').split('.')[0])||0;
54874
+ const repoReal=realpathSync(${JSON.stringify(cwd)}),nextReal=realpathSync(nextPkg);
54875
+ nextOutsideRepo=!nextReal.startsWith(repoReal+'/')&&!nextReal.startsWith(repoReal+'\\\\');
54876
+ }catch{}
54877
+ const startServer=async webpack=>{
54878
+ output='';exited=null;
54879
+ const args=[next,'dev',...(webpack?['--webpack']:[]),'-p',String(port)];
54880
+ server=spawn(process.execPath,args,{cwd:appDir,env,stdio:['ignore','pipe','pipe'],detached:process.platform!=='win32'});
54881
+ const keep=chunk=>{const text=chunk.toString();output=(output+text).slice(-20000);lastOutput=Date.now();process.stderr.write(text);};
54882
+ server.stdout.on('data',keep);server.stderr.on('data',keep);server.once('exit',code=>{exited=code??1;});
54883
+ const deadline=Date.now()+90000;
54884
+ 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));}
54885
+ };
54886
+ let usingWebpack=nextMajor>=16&&nextOutsideRepo;
54887
+ if(usingWebpack)console.error('[agenttwin] Next.js '+nextMajor+' resolves outside the repo; starting with --webpack.');
54888
+ 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;}
54812
54889
  // A sign-in that fails does not stop the workflow: many (webhooks, crons) need no user, and one that does answers
54813
54890
  // 401, which the password sign-in below handles.
54814
54891
  let signedIn=false;
54815
- 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.');}}
54892
+ if(signIn){try{await signInThroughApp(signIn);signedIn=true;}catch(e){
54893
+ if(!usingWebpack&&nextMajor>=16&&/Could not find the Next\\.js package/i.test(output)){
54894
+ usingWebpack=true;stop();await new Promise(r=>setTimeout(r,300));
54895
+ console.error('[agenttwin] Next.js Turbopack failed during sign-in; restarting with --webpack.');
54896
+ await startServer(true);
54897
+ try{await signInThroughApp(signIn);signedIn=true;}catch(e2){console.error('[agenttwin] '+(e2&&e2.message||e2)+' Sending the workflow request without a signed-in user.');}
54898
+ }else console.error('[agenttwin] '+(e&&e.message||e)+' Sending the workflow request without a signed-in user.');
54899
+ }}
54816
54900
  if(signedIn){
54817
54901
  console.error('[agenttwin] '+signIn.email+' signed in through the app ('+signIn.provider+').');
54818
54902
  // Records the app creates after sign-in (mailbox, defaults) are often written in the background.
@@ -54846,6 +54930,14 @@ try{
54846
54930
  const bodyText=trpc||!qNames.size?payload:JSON.stringify(bodyArg??{});
54847
54931
  const send=()=>call(${JSON.stringify(web.path)}+(trpc?.kind==='query'?'?input='+encodeURIComponent(payload):(qs?'?'+qs:${JSON.stringify(scenario.query ? "?" + scenario.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})});
54848
54932
  let response=await send();
54933
+ if(response.status>=500&&!usingWebpack&&nextMajor>=16&&/Could not find the Next\\.js package/i.test(output)){
54934
+ await response.text().catch(()=>{});
54935
+ usingWebpack=true;stop();await new Promise(r=>setTimeout(r,300));
54936
+ console.error('[agenttwin] Next.js Turbopack failed on route; restarting with --webpack.');
54937
+ await startServer(true);
54938
+ if(signIn&&!signedIn){try{await signInThroughApp(signIn);signedIn=true;}catch{}}
54939
+ response=await send();
54940
+ }
54849
54941
  // A redirect to a sign-in or guest-session page: follow it as a browser would (the jar keeps its cookie), then ask again.
54850
54942
  // Still sent to sign-in: the workflow never ran, so the run is not a pass.
54851
54943
  const signInPath=l=>/\\/(?:api\\/)?(?:auth|login|log-in|signin|sign-in|session|guest)(?:\\/|\\?|$)/i.test(String(l).replace(/^https?:\\/\\/[^/]+/,''));
@@ -64670,7 +64762,7 @@ function routeWeight(method, path2) {
64670
64762
  if (/(^|\/)(webhooks?|callback|events?|inbound|incoming|notifications?|push|hooks?)(\/|$)/i.test(path2)) weight += 14;
64671
64763
  if (/(^|\/)(cron|jobs?|queue|tasks?|scheduled?|process|sync|digest)(\/|$)/i.test(path2)) weight += 6;
64672
64764
  if (path2.toLowerCase().split("/").some((segment) => twinnedVendors().has(segment))) weight += 5;
64673
- if (/(^|\/)(admin|debug|health|test|e2e|dev|internal|_next|og|sitemap|docs?|documentation)(\/|$)/i.test(path2)) weight -= 10;
64765
+ 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;
64674
64766
  return weight;
64675
64767
  }
64676
64768
  function workflowKind(c) {
@@ -64678,7 +64770,8 @@ function workflowKind(c) {
64678
64770
  if (c.boltApp) return WORKFLOW_KINDS[0];
64679
64771
  if (!route) return WORKFLOW_KINDS[4];
64680
64772
  if (signInCallback(route, c.file)) return WORKFLOW_KINDS[3];
64681
- if (route.method !== "GET" && WEBHOOK_PATH.test(route.path)) return WORKFLOW_KINDS[0];
64773
+ const isBrowserHook = /(^|\/)browser(\/|$)/i.test(c.file ?? "") && /(^|\/)hooks\/(dialog|file-chooser)(\/|$)/i.test(route.path) && !c.calls?.length;
64774
+ if (route.method !== "GET" && WEBHOOK_PATH.test(route.path) && !isBrowserHook) return WORKFLOW_KINDS[0];
64682
64775
  if (JOB_PATH.test(route.path)) return WORKFLOW_KINDS[2];
64683
64776
  if (route.method !== "GET" && (c.calls ?? []).some((call2) => call2.write && !DATABASE.test(call2.provider) && MONEY_OR_SEND.test(call2.operation))) return WORKFLOW_KINDS[1];
64684
64777
  return WORKFLOW_KINDS[3];
@@ -64699,7 +64792,10 @@ function moneyWeight(c) {
64699
64792
  function rankWorkflows(list5) {
64700
64793
  const kind = (c) => WORKFLOW_KINDS.indexOf(workflowKind(c));
64701
64794
  const callback = (c) => signInCallback(c.web ?? c.serve, c.file) ? 1 : 0;
64702
- return list5.sort((a, b) => kind(a) - kind(b) || callback(a) - callback(b) || b.score + moneyWeight(b) - (a.score + moneyWeight(a)));
64795
+ const emptyOtherRoute = (c) => kind(c) === 3 && !c.calls?.length ? 1 : 0;
64796
+ const nonHelperFn = (c) => kind(c) === 4 && (c.calls?.length ?? 0) > 0 && (!c.exportName || nameWeight(c.exportName) >= 0);
64797
+ const tier = (c) => nonHelperFn(c) ? 3 : kind(c);
64798
+ 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)));
64703
64799
  }
64704
64800
  function twinnedVendors() {
64705
64801
  if (vendors) return vendors;
@@ -64760,7 +64856,8 @@ async function runOneCommand(opts) {
64760
64856
  const ask = opts.ask ?? terminalAsk(interactive, log, emit2, Boolean(opts.emit));
64761
64857
  const seed = normalizeSeed(opts.seed ?? "42");
64762
64858
  const startedAt = opts.startedAt ?? Date.now();
64763
- const budgetLeft = (cap) => opts.deadline === void 0 ? cap : Math.min(cap, Math.max(0, opts.deadline - Date.now()));
64859
+ const effectiveDeadline = opts.deadline === void 0 ? void 0 : opts.deadline + setupSpentMs;
64860
+ const budgetLeft = (cap) => effectiveDeadline === void 0 ? cap : Math.min(cap, Math.max(0, effectiveDeadline - Date.now()));
64764
64861
  const caseStatus = (r) => r.status === "passed" ? "passed" : r.status === "failed" ? "found" : r.status === "incomplete" ? "skipped" : "error";
64765
64862
  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 } : {} }));
64766
64863
  if (!opts.skipSetup) {
@@ -64812,9 +64909,10 @@ async function runOneCommand(opts) {
64812
64909
  const { inventoryWorkflows, tools, exports } = await scan;
64813
64910
  if (reused) log(dim(` Repository map from this run's first scan: ${tools.size} services and ${inventoryWorkflows.length} workflows.`));
64814
64911
  const projectDashboard = await integrations.connectProject(cwd, { interactive, ask, log });
64815
- const byEntry = new Map(exports.map((c) => [c.entrypoint, c]));
64912
+ const byEntry = new Map(exports.map((c) => [c.entrypoint, c])), byId = new Map(exports.map((c) => [c.id, c]));
64913
+ const collapsed = collapseCandidates(inventoryWorkflows, exports);
64816
64914
  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");
64817
- const invocable = (w) => byEntry.get(w.entrypoint ?? "") ?? inventoryWorkflows.filter((x) => x.coveredBy === w.id).map((x) => byEntry.get(x.entrypoint ?? "")).find(Boolean);
64915
+ 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);
64818
64916
  const steps = /* @__PURE__ */ new Map(), candidates = [], notRunnable = [];
64819
64917
  let merged = 0;
64820
64918
  for (const w of inventoryWorkflows.filter((w2) => !w2.coveredBy && w2.entrypoint && w2.steps.length)) {
@@ -64941,7 +65039,7 @@ async function runOneCommand(opts) {
64941
65039
  const ownLock = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb"].some((f) => existsSync21(join90(cwd, appDir, f)));
64942
65040
  const outside = appDir !== "." && !workspaceDirs(cwd).has(appDir);
64943
65041
  at("installing dependencies", candidate.title);
64944
- if (appDir !== "." && !existsSync21(join90(cwd, appDir, "node_modules")) && (ownLock || outside || !existsSync21(join90(cwd, "node_modules")))) await runSetup(join90(cwd, appDir), { ask, log: trackCommand(log), interactive, only: "install" });
65042
+ if (appDir !== "." && !existsSync21(join90(cwd, appDir, "node_modules")) && (ownLock || outside)) await runSetup(join90(cwd, appDir), { ask, log: trackCommand(log), interactive, only: "install" });
64945
65043
  at("building workspace packages", candidate.title);
64946
65044
  {
64947
65045
  const t0 = Date.now();
@@ -65000,18 +65098,44 @@ async function runOneCommand(opts) {
65000
65098
  log(bold("3/7 Run") + dim(liveHosts.length ? " real workflow code against twins\u2026" : " real workflow code against twins (no production calls)\u2026"));
65001
65099
  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.`));
65002
65100
  let clean;
65003
- try {
65004
- clean = await track(void 0);
65005
- } catch (error62) {
65006
- const reason = (error62 instanceof Error ? error62.message : String(error62)).split("\n")[0].slice(0, 240);
65007
- const tried = [...opts.triedWorkflows ?? [], { id: candidate.id, title: candidate.title, reason }];
65008
- const triedFiles = new Set(tried.map((t) => candidates.find((c) => c.id === t.id)?.file).filter(Boolean));
65009
- const open6 = candidates.filter((c) => !c.suite && !tried.some((t) => t.id === c.id) && !(opts.testedWorkflows ?? []).includes(c.id));
65010
- const next = !candidate.suite && (!opts.workflow || opts.autoPicked) && tried.length < WORKFLOW_ATTEMPTS && Date.now() - startedAt < budgetLeft(WORKFLOW_BUDGET_MS) ? open6.find((c) => !triedFiles.has(c.file)) ?? open6[0] : void 0;
65011
- if (!next) throw error62;
65012
- log(yellow(` ${candidate.title} could not run here: ${reason}`));
65013
- log(dim(` Trying the next workflow the scan found: ${next.title}. Test this one later with npx agenttwin --workflow "${candidate.title}".`));
65014
- return runOneCommand({ ...opts, workflow: next.id, autoPicked: true, triedWorkflows: tried, skipSuites: true, startedAt });
65101
+ for (let blockedTry = 0; ; blockedTry++) {
65102
+ try {
65103
+ clean = await track(void 0);
65104
+ break;
65105
+ } catch (error62) {
65106
+ const msg2 = error62 instanceof Error ? error62.message : String(error62);
65107
+ const blockedMatch = /AgentTwin blocked .*? to ([^\s(;]+)/i.exec(msg2);
65108
+ if (blockedMatch && blockedTry < 3) {
65109
+ const host = blockedMatch[1].toLowerCase().replace(/:\d+$/, "");
65110
+ const adapter = deepTwinForHost(host), collections = adapter ? ADAPTER_COLLECTIONS[adapter] : void 0;
65111
+ let added = false;
65112
+ if (adapter && collections) {
65113
+ const name = adapter.replaceAll("-", "_");
65114
+ if (!prepared.scenario.twins.some((t) => t.name === name)) {
65115
+ const service = { name, adapter, collections: collections.map((path2) => ({ path: path2, seed: [] })) };
65116
+ prepared.scenario.services.push(service);
65117
+ prepared.world.services.push(service);
65118
+ prepared.scenario.twins.push({ tier: "deep", provider: "hand-written twin", name, title: PROVIDER_TITLES[adapter] ?? adapter, note: `${host} \u2192 found while running (the scan did not see it)`, service });
65119
+ log(dim(` Found ${host} while running (the scan missed it); using the ${PROVIDER_TITLES[adapter] ?? adapter} twin and rerunning.`));
65120
+ added = true;
65121
+ }
65122
+ } else if (!prepared.scenario.twins.some((t) => t.generic?.hosts?.includes(host))) {
65123
+ 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` });
65124
+ log(dim(` Found ${host} while running (the scan missed it); twinning it as a stateful REST service and rerunning.`));
65125
+ added = true;
65126
+ }
65127
+ if (added) continue;
65128
+ }
65129
+ const reason = msg2.split("\n")[0].slice(0, 240);
65130
+ const tried = [...opts.triedWorkflows ?? [], { id: candidate.id, title: candidate.title, reason }];
65131
+ const triedFiles = new Set(tried.map((t) => candidates.find((c) => c.id === t.id)?.file).filter(Boolean));
65132
+ const open6 = candidates.filter((c) => !c.suite && !tried.some((t) => t.id === c.id) && !(opts.testedWorkflows ?? []).includes(c.id));
65133
+ const next = !candidate.suite && (!opts.workflow || opts.autoPicked) && tried.length < WORKFLOW_ATTEMPTS && Date.now() - startedAt < budgetLeft(WORKFLOW_BUDGET_MS) ? open6.find((c) => !triedFiles.has(c.file)) ?? open6[0] : void 0;
65134
+ if (!next) throw error62;
65135
+ log(yellow(` ${candidate.title} could not run here: ${reason}`));
65136
+ log(dim(` Trying the next workflow the scan found: ${next.title}. Test this one later with npx agenttwin --workflow "${candidate.title}".`));
65137
+ return runOneCommand({ ...opts, workflow: next.id, autoPicked: true, triedWorkflows: tried, skipSuites: true, startedAt });
65138
+ }
65015
65139
  }
65016
65140
  if (pickedSuite && clean.exitCode === null && !((suiteFacts(candidate, clean.stdout).suite?.passed ?? 0) > 0)) {
65017
65141
  const fallback = candidates.find((c) => !c.suite && !(opts.testedWorkflows ?? []).includes(c.id));
@@ -65703,7 +65827,9 @@ ${clean.stdout ?? ""}`) : void 0;
65703
65827
  }
65704
65828
  }
65705
65829
  const cleanEvents = clean.events;
65706
- 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");
65830
+ const LOCAL_ENGINES = /* @__PURE__ */ new Set(["postgres", "sqlite", "mysql", "redis", "mongodb", "clickhouse"]);
65831
+ const hasExternalCall = cleanCalls.length > 0 || cleanEvents.some((e) => !LOCAL_ENGINES.has(e.service));
65832
+ 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;
65707
65833
  const emptyReads = [...new Set(cleanEvents.filter((e) => e.operation === "read" && /^SELECT 0$/.test(e.detail ?? "")).map((e) => (e.path ?? "").replace(/^\//, "")))].filter(Boolean);
65708
65834
  const autoSuite = !opts.workflow || opts.triedSuites !== void 0;
65709
65835
  const routeFallback = candidates.find((c) => !c.suite && !(opts.testedWorkflows ?? []).includes(c.id));
@@ -65741,7 +65867,7 @@ ${clean.stdout ?? ""}`) : void 0;
65741
65867
  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.`));
65742
65868
  const deferred = [];
65743
65869
  const runFault = async (fault, deferStartupFailure) => {
65744
- if (opts.deadline !== void 0 && Date.now() > opts.deadline - 15e3) {
65870
+ if (opts.deadline !== void 0 && Date.now() > opts.deadline + setupSpentMs - 15e3) {
65745
65871
  skippedFaults.push({ id: fault.id, title: fault.title, why: "time" });
65746
65872
  emit2({ type: "case-end", id: fault.id, status: "skipped", calls: [] });
65747
65873
  log(` ${yellow("SKIP ")} ${fault.title}${dim(" (the run budget ended first)")}`);
@@ -65830,7 +65956,7 @@ ${clean.stdout ?? ""}`) : void 0;
65830
65956
  log(dim(` Campaign: ${slice.length} of ${campaignCases.length} derived fault scenario${campaignCases.length === 1 ? "" : "s"} (network, filesystem, crash, clock), one per model.`));
65831
65957
  const campaignStart = Date.now();
65832
65958
  for (const fault of slice) {
65833
- if (opts.deadline !== void 0 && Date.now() > opts.deadline - 15e3 || Date.now() - campaignStart > CAMPAIGN_BUDGET_MS) {
65959
+ if (opts.deadline !== void 0 && Date.now() > opts.deadline + setupSpentMs - 15e3 || Date.now() - campaignStart > CAMPAIGN_BUDGET_MS) {
65834
65960
  skippedFaults.push({ id: fault.id, title: fault.title, why: "time" });
65835
65961
  log(` ${yellow("SKIP ")} ${fault.title}${dim(" (the run budget ended first)")}`);
65836
65962
  continue;
@@ -66399,7 +66525,7 @@ var init_one_command = __esm({
66399
66525
  WORKFLOW_BUDGET_MS = Number(process.env.AGENTTWIN_WORKFLOW_BUDGET_MS ?? 9 * 6e4);
66400
66526
  FLAT_LIST_LIMIT = 6;
66401
66527
  PROVIDER_TITLES = { openai: "OpenAI", anthropic: "Anthropic", stripe: "Stripe", slack: "Slack", gmail: "Gmail", github: "GitHub", linear: "Linear", notion: "Notion", hubspot: "HubSpot", twilio: "Twilio", "google-oauth": "Google sign-in", "google-calendar": "Google Calendar" };
66402
- TOOLCHAIN_HOST2 = /^(registry\.npmjs\.org|registry\.yarnpkg\.com|telemetry\.nextjs\.org|telemetry\.vercel\.com|api\.turbo\.build|turbo\.build|nextjs\.org|update\.electronjs\.org|checkpoint\.prisma\.io|binaries\.prisma\.sh|[\w.-]*\.sentry-cdn\.com|fonts\.googleapis\.com|fonts\.gstatic\.com)$/i;
66528
+ TOOLCHAIN_HOST2 = /^(registry\.npmjs\.org|registry\.yarnpkg\.com|registry\.npmmirror\.com|pypi\.org|files\.pythonhosted\.org|telemetry\.nextjs\.org|telemetry\.vercel\.com|vitals\.vercel-insights\.com|va\.vercel-scripts\.com|telemetry\.scarf\.sh|api\.turbo\.build|turbo\.build|nextjs\.org|update\.electronjs\.org|checkpoint\.prisma\.io|binaries\.prisma\.sh|[\w.-]*\.sentry-cdn\.com|fonts\.googleapis\.com|fonts\.gstatic\.com|openaipublic\.blob\.core\.windows\.net|playwright\.azureedge\.net|cdn\.playwright\.dev)$/i;
66403
66529
  NON_HTTP_PORTS = /* @__PURE__ */ new Set([22, 25, 465, 587, 2525, 3306, 5432, 5672, 6379, 9092, 11211, 1433, 1521, 27017, 9042, 4222, 1883]);
66404
66530
  statusMark = (status) => status === "passed" ? green("PASS") : status === "failed" ? red("FAIL") : yellow(status.toUpperCase());
66405
66531
  diffLines = (diff) => diff.trimEnd().split("\n").map((l) => " " + (l.startsWith("+") && !l.startsWith("+++") ? green(l) : l.startsWith("-") && !l.startsWith("---") ? red(l) : dim(l)));
@@ -23058,7 +23058,8 @@ async function analyzeWorkflows(root2, opts = {}) {
23058
23058
  for (const [exportName, local] of f.exports) {
23059
23059
  const { calls: reached, env, files: touched, channels } = closure(file2, local);
23060
23060
  const calls = reached.filter((c) => !/^use[A-Z]/.test(c.operation));
23061
- if ((/\.[jt]sx$/.test(file2) && /^[A-Z]/.test(exportName) || /^use[A-Z]/.test(exportName)) && !ROUTE_FILE.test(file2)) continue;
23061
+ 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;
23062
+ if (/(?:^|\/)(?:instrumentation(?:\.client)?|test-utils)\.[cm]?[jt]s$/i.test(file2)) continue;
23062
23063
  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);
23063
23064
  if (!calls.length && !opts.all && !verifiesWebhook && !f.trpcHandler) continue;
23064
23065
  const fn = f.functions.get(local);
package/dist/worker.js CHANGED
@@ -8315,6 +8315,11 @@ var HttpWorld = class {
8315
8315
  const target2 = aliasRequest(name, host, req.url ?? "/");
8316
8316
  const model = compatibleModel(name, body);
8317
8317
  const r = await twin(new Request(`https://${target2.host}${target2.url}`, { method, headers, ...model.body ? { body: model.body } : {} }));
8318
+ if ((r.status === 501 || r.status === 404) && name === "ai-gateway" && method === "GET" && /^\/(?:v1\/)?models\/([^/]+\/[^/]+)\/endpoints$/.test(target2.url.split("?")[0])) {
8319
+ const id = /^\/(?:v1\/)?models\/([^/]+\/[^/]+)\/endpoints$/.exec(target2.url.split("?")[0])[1];
8320
+ const payload = Buffer.from(JSON.stringify({ data: { id, name: id, endpoints: [{ name: id, provider: id.split("/")[0] || "openai", context_length: 128e3, pricing: { prompt: "0", completion: "0" }, supported_parameters: ["tools", "temperature", "max_tokens"] }] } }));
8321
+ return { status: 200, headers: new Headers({ "content-type": "application/json" }), bytes: payload, actions: [] };
8322
+ }
8318
8323
  return { status: r.status, headers: r.headers, bytes: model.restore(Buffer.from(await r.arrayBuffer())), actions: log.drain() };
8319
8324
  };
8320
8325
  if (workspace && method !== "GET") this.causing[service.name] = 1;
@@ -8733,6 +8733,11 @@ var init_http_world = __esm({
8733
8733
  const target2 = aliasRequest(name, host, req.url ?? "/");
8734
8734
  const model = compatibleModel(name, body);
8735
8735
  const r = await twin(new Request(`https://${target2.host}${target2.url}`, { method, headers, ...model.body ? { body: model.body } : {} }));
8736
+ if ((r.status === 501 || r.status === 404) && name === "ai-gateway" && method === "GET" && /^\/(?:v1\/)?models\/([^/]+\/[^/]+)\/endpoints$/.test(target2.url.split("?")[0])) {
8737
+ const id = /^\/(?:v1\/)?models\/([^/]+\/[^/]+)\/endpoints$/.exec(target2.url.split("?")[0])[1];
8738
+ const payload = Buffer.from(JSON.stringify({ data: { id, name: id, endpoints: [{ name: id, provider: id.split("/")[0] || "openai", context_length: 128e3, pricing: { prompt: "0", completion: "0" }, supported_parameters: ["tools", "temperature", "max_tokens"] }] } }));
8739
+ return { status: 200, headers: new Headers({ "content-type": "application/json" }), bytes: payload, actions: [] };
8740
+ }
8736
8741
  return { status: r.status, headers: r.headers, bytes: model.restore(Buffer.from(await r.arrayBuffer())), actions: log.drain() };
8737
8742
  };
8738
8743
  if (workspace && method !== "GET") this.causing[service.name] = 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agenttwin",
3
- "version": "0.3.44",
3
+ "version": "0.3.46",
4
4
  "description": "AgentTwin builds digital twins for testing AI agents. The current CLI prepares supported Node.js workflows with synthetic services, failures, and outcome checks.",
5
5
  "mcpName": "io.github.AgentTwin/agenttwin",
6
6
  "keywords": [
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[977,990,1369,2481,2882,3232,4345,6226,6402,6990,7006,7066,8365,9366,9877],{406:(e,t,n)=>{Promise.resolve().then(n.t.bind(n,3652,23)),Promise.resolve().then(n.bind(n,8765))},3652:e=>{e.exports={footer:"SiteFooter_footer__aUaTs",content:"SiteFooter_content__1J6Jy",wordmark:"SiteFooter_wordmark__B6_Tf",navigation:"SiteFooter_navigation__Zsq8o",main:"SiteFooter_main__EWvbi",brand:"SiteFooter_brand__HyIqL",groups:"SiteFooter_groups__tPgIM",group:"SiteFooter_group__FK9ik",more:"SiteFooter_more__LEh69",bottom:"SiteFooter_bottom__ADU2b",srOnly:"SiteFooter_srOnly__e7DbB"}},8765:(e,t,n)=>{"use strict";n.d(t,{default:()=>l});var a=n(5155),i=n(2115),r=n(1719);function o(){let[e,t]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{t("light"===document.documentElement.dataset.siteTheme)},[]),(0,a.jsxs)("button",{className:"site-theme-toggle",type:"button","aria-label":e?"Switch to dark mode":"Switch to light mode",title:e?"Switch to dark mode":"Switch to light mode",onClick:()=>{let e="light"!==document.documentElement.dataset.siteTheme,n=e?"light":"dark";document.documentElement.dataset.siteTheme=n,t(e);try{localStorage.setItem("agenttwin-site-theme",n)}catch(e){}},children:[(0,a.jsx)(r.gLX,{className:"site-theme-sun",width:20,height:20,"aria-hidden":"true"}),(0,a.jsx)(r.rRK,{className:"site-theme-moon",width:20,height:20,"aria-hidden":"true"})]})}let s=[{href:"/what-is-agenttwin/",label:"Product"},{href:"/#how",label:"How it works"},{href:"/pricing/",label:"Pricing"},{href:"/about/",label:"About"},{href:"/docs/",label:"Docs"},{href:"/blog/",label:"Blog"}];function l(){let[e,t]=(0,i.useState)(!1),n=(0,i.useRef)(null),r=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=e=>{var a,i;"Escape"===e.key&&(null==(a=r.current)?void 0:a.querySelector("#navlinks.is-open"))&&(t(!1),null==(i=n.current)||i.focus())},a=e=>{var n;(null==(n=r.current)?void 0:n.contains(e.target))||t(!1)},i=matchMedia("(min-width: 1024px)"),o=()=>t(!1);return document.addEventListener("keydown",e),document.addEventListener("click",a),i.addEventListener("change",o),()=>{document.removeEventListener("keydown",e),document.removeEventListener("click",a),i.removeEventListener("change",o)}},[]),(0,a.jsxs)("header",{className:"site-header",ref:r,children:[(0,a.jsxs)("a",{className:"brand",href:"/","aria-label":"AgentTwin home",children:[(0,a.jsx)("img",{src:"assets/logo/mark-twin-rings.svg?v=white-rings",alt:"","aria-hidden":"true",width:29,height:29}),"AgentTwin"]}),(0,a.jsxs)("nav",{className:"main-nav".concat(e?" is-open":""),id:"navlinks","aria-label":"Main navigation",children:[s.map(e=>(0,a.jsx)("a",{href:e.href,onClick:()=>t(!1),children:e.label},e.href)),(0,a.jsx)("a",{className:"nav-mobile-dashboard",href:"/dashboard/",onClick:()=>t(!1),children:"Open dashboard"})]}),(0,a.jsxs)("div",{className:"nav-actions",children:[(0,a.jsx)("a",{href:"/login/",children:"Sign in"}),(0,a.jsxs)("a",{className:"button button-white button-small",href:"/signup/",children:["Get started ",(0,a.jsx)("span",{"aria-hidden":"true",children:"\xbb"})]})]}),(0,a.jsx)(o,{}),(0,a.jsxs)("button",{className:"menu-toggle",ref:n,type:"button","aria-label":e?"Close menu":"Open menu","aria-expanded":e,"aria-controls":"navlinks",onClick:()=>t(!e),children:[(0,a.jsx)("span",{}),(0,a.jsx)("span",{})]})]})}}},e=>{e.O(0,[4123,5105,8441,1255,7358],()=>e(e.s=406)),_N_E=e.O()}]);
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[977,990,1369,2481,2882,3232,4345,6226,6402,6990,7006,7066,8365,9366,9877],{406:(e,t,n)=>{Promise.resolve().then(n.t.bind(n,3652,23)),Promise.resolve().then(n.bind(n,8765))},3652:e=>{e.exports={footer:"SiteFooter_footer__aUaTs",content:"SiteFooter_content__1J6Jy",wordmark:"SiteFooter_wordmark__B6_Tf",navigation:"SiteFooter_navigation__Zsq8o",main:"SiteFooter_main__EWvbi",brand:"SiteFooter_brand__HyIqL",groups:"SiteFooter_groups__tPgIM",group:"SiteFooter_group__FK9ik",more:"SiteFooter_more__LEh69",bottom:"SiteFooter_bottom__ADU2b",srOnly:"SiteFooter_srOnly__e7DbB"}},8765:(e,t,n)=>{"use strict";n.d(t,{default:()=>l});var a=n(5155),i=n(2115),r=n(1719);function o(){let[e,t]=(0,i.useState)(!1);return(0,i.useEffect)(()=>{t("light"===document.documentElement.dataset.siteTheme)},[]),(0,a.jsxs)("button",{className:"site-theme-toggle",type:"button","aria-label":e?"Switch to dark mode":"Switch to light mode",title:e?"Switch to dark mode":"Switch to light mode",onClick:()=>{let e="light"!==document.documentElement.dataset.siteTheme,n=e?"light":"dark";document.documentElement.dataset.siteTheme=n,t(e);try{localStorage.setItem("agenttwin-site-theme",n)}catch(e){}},children:[(0,a.jsx)(r.gLX,{className:"site-theme-sun",width:20,height:20,"aria-hidden":"true"}),(0,a.jsx)(r.rRK,{className:"site-theme-moon",width:20,height:20,"aria-hidden":"true"})]})}let s=[{href:"/what-is-agenttwin/",label:"Product"},{href:"/#how",label:"How it works"},{href:"/pricing/",label:"Pricing"},{href:"/about/",label:"About"},{href:"/docs/",label:"Docs"},{href:"/blog/",label:"Blog"}];function l(){let[e,t]=(0,i.useState)(!1),n=(0,i.useRef)(null),r=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=e=>{var a,i;"Escape"===e.key&&(null==(a=r.current)?void 0:a.querySelector("#navlinks.is-open"))&&(t(!1),null==(i=n.current)||i.focus())},a=e=>{var n;(null==(n=r.current)?void 0:n.contains(e.target))||t(!1)},i=matchMedia("(min-width: 1024px)"),o=()=>t(!1);return document.addEventListener("keydown",e),document.addEventListener("click",a),i.addEventListener("change",o),()=>{document.removeEventListener("keydown",e),document.removeEventListener("click",a),i.removeEventListener("change",o)}},[]),(0,a.jsxs)("header",{className:"site-header",ref:r,children:[(0,a.jsxs)("a",{className:"brand",href:"/","aria-label":"AgentTwin home",children:[(0,a.jsx)("img",{src:"assets/logo/mark-twin-rings.svg?v=white-rings",alt:"","aria-hidden":"true",width:29,height:29}),"AgentTwin"]}),(0,a.jsxs)("nav",{className:"main-nav".concat(e?" is-open":""),id:"navlinks","aria-label":"Main navigation",children:[s.map(e=>(0,a.jsx)("a",{href:e.href,onClick:()=>t(!1),children:e.label},e.href)),(0,a.jsx)("a",{className:"nav-mobile-dashboard",href:"/dashboard/",onClick:()=>t(!1),children:"Open dashboard"})]}),(0,a.jsxs)("div",{className:"nav-actions",children:[(0,a.jsx)("a",{href:"/login/",children:"Sign in"}),(0,a.jsxs)("a",{className:"button button-white button-small",href:"/signup/",children:["Get started ",(0,a.jsx)("span",{"aria-hidden":"true",children:"\xbb"})]})]}),(0,a.jsx)(o,{}),(0,a.jsxs)("button",{className:"menu-toggle",ref:n,type:"button","aria-label":e?"Close menu":"Open menu","aria-expanded":e,"aria-controls":"navlinks",onClick:()=>t(!e),children:[(0,a.jsx)("span",{}),(0,a.jsx)("span",{})]})]})}}},e=>{e.O(0,[4123,5105,8441,1255,7358],()=>e(e.s=406)),_N_E=e.O()}]);