agenttwin 0.3.30 → 0.3.31

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 (159) hide show
  1. package/dist/api.js +1742 -722
  2. package/dist/dashboard/assets/next/static/chunks/{1ea884a0-6818287fac0ec05c.js → 0e5ce63c-707674e8817dc2e1.js} +1 -1
  3. package/dist/dashboard/assets/next/static/chunks/{4420.2441fa8cd44d835a.js → 1018.4871a8dd0f112c38.js} +1 -1
  4. package/dist/dashboard/assets/next/static/chunks/1255-d4ec8dbb0865c655.js +1 -0
  5. package/dist/dashboard/assets/next/static/chunks/1937-6c86fddc443de922.js +1 -0
  6. package/dist/dashboard/assets/next/static/chunks/2743-a0efd6f4aeb11cc5.js +1 -0
  7. package/dist/dashboard/assets/next/static/chunks/{6873.a1a49381240b52fe.js → 4055.1056568a41510e92.js} +1 -1
  8. package/dist/dashboard/assets/next/static/chunks/424-83736cfafc224fc6.js +1 -0
  9. package/dist/dashboard/assets/next/static/chunks/4343.023a18f52318dbad.js +1 -0
  10. package/dist/dashboard/assets/next/static/chunks/{aebece07-770806e0a96e6d1a.js → 4bd1b696-f785427dddbba9fb.js} +1 -1
  11. package/dist/dashboard/assets/next/static/chunks/5258-3d0060b41be9ad97.js +1 -0
  12. package/dist/dashboard/assets/next/static/chunks/6751.613adb085c9a5b06.js +1 -0
  13. package/dist/dashboard/assets/next/static/chunks/6787-c85d7f794360b672.js +1 -0
  14. package/dist/dashboard/assets/next/static/chunks/{3184-58f1813266829219.js → 7772-f2d773cd3e94eea6.js} +1 -1
  15. package/dist/dashboard/assets/next/static/chunks/{5361.3484c495efb7fd7d.js → 8975.5be81ec8b09e3b45.js} +1 -1
  16. package/dist/dashboard/assets/next/static/chunks/{3619.50dfe4e6fa916c52.js → 9013.0f2be1cc70029afa.js} +2 -2
  17. package/dist/dashboard/assets/next/static/chunks/{5203.7a7ffc7f10d89929.js → 9675.d833ca9b2d89cf8a.js} +1 -1
  18. package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-5d1ba67144da5868.js +1 -0
  19. package/dist/dashboard/assets/next/static/chunks/app/about/page-b09a2d8452522c20.js +1 -0
  20. package/dist/dashboard/assets/next/static/chunks/app/account/password/{page-5775ac3aa5e4562f.js → page-b9ca284314cace59.js} +1 -1
  21. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-94d508052ae30dcb.js +1 -0
  22. package/dist/dashboard/assets/next/static/chunks/app/auth/page-94d508052ae30dcb.js +1 -0
  23. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-mockoon/{page-9f75918bfb87ef66.js → page-11a5fdc2662ff51d.js} +1 -1
  24. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-pact/{page-9f75918bfb87ef66.js → page-11a5fdc2662ff51d.js} +1 -1
  25. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-testcontainers/{page-9f75918bfb87ef66.js → page-11a5fdc2662ff51d.js} +1 -1
  26. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-wiremock/{page-9f75918bfb87ef66.js → page-11a5fdc2662ff51d.js} +1 -1
  27. package/dist/dashboard/assets/next/static/chunks/app/blog/choose-first-agent-workflow-test/page-11a5fdc2662ff51d.js +1 -0
  28. package/dist/dashboard/assets/next/static/chunks/app/blog/clean-baseline-before-fault-injection/page-11a5fdc2662ff51d.js +1 -0
  29. package/dist/dashboard/assets/next/static/chunks/app/blog/idempotency-keys-and-safe-retries/page-11a5fdc2662ff51d.js +1 -0
  30. package/dist/dashboard/assets/next/static/chunks/app/blog/keep-real-service-tests-with-digital-twins/page-11a5fdc2662ff51d.js +1 -0
  31. package/dist/dashboard/assets/next/static/chunks/app/blog/keploy-alternatives-for-database-and-payment-workflows/page-11a5fdc2662ff51d.js +1 -0
  32. package/dist/dashboard/assets/next/static/chunks/app/blog/layout-b095a34d742bd1fd.js +1 -0
  33. package/dist/dashboard/assets/next/static/chunks/app/blog/page-11a5fdc2662ff51d.js +1 -0
  34. package/dist/dashboard/assets/next/static/chunks/app/blog/read-workflow-test-receipts/page-11a5fdc2662ff51d.js +1 -0
  35. package/dist/dashboard/assets/next/static/chunks/app/blog/reset-test-environment-between-runs/page-11a5fdc2662ff51d.js +1 -0
  36. package/dist/dashboard/assets/next/static/chunks/app/blog/simulate-timeouts-and-duplicate-events/page-11a5fdc2662ff51d.js +1 -0
  37. package/dist/dashboard/assets/next/static/chunks/app/blog/test-boundaries-for-ai-agents/page-11a5fdc2662ff51d.js +1 -0
  38. package/dist/dashboard/assets/next/static/chunks/app/blog/workflow-testing-evaluation-checklist/page-11a5fdc2662ff51d.js +1 -0
  39. package/dist/dashboard/assets/next/static/chunks/app/blog/write-better-workflow-assertions/page-11a5fdc2662ff51d.js +1 -0
  40. package/dist/dashboard/assets/next/static/chunks/app/compare/page-94d508052ae30dcb.js +1 -0
  41. package/dist/dashboard/assets/next/static/chunks/app/contact/page-94d508052ae30dcb.js +1 -0
  42. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-820e83f47c1bfe08.js +1 -0
  43. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-8b436163bc85e182.js +1 -0
  44. package/dist/dashboard/assets/next/static/chunks/app/demo/page-ef75632088a6ea0b.js +1 -0
  45. package/dist/dashboard/assets/next/static/chunks/app/developers/page-94d508052ae30dcb.js +1 -0
  46. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-c25a8cab5ab065c4.js +1 -0
  47. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-94d508052ae30dcb.js +1 -0
  48. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-91c6176f28dfdccd.js +1 -0
  49. package/dist/dashboard/assets/next/static/chunks/app/guides/page-94d508052ae30dcb.js +1 -0
  50. package/dist/dashboard/assets/next/static/chunks/app/layout-be64d3e50db4b7a9.js +1 -0
  51. package/dist/dashboard/assets/next/static/chunks/app/login/page-7ee25051f2743d68.js +1 -0
  52. package/dist/dashboard/assets/next/static/chunks/app/not-found-94d508052ae30dcb.js +1 -0
  53. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-26b963fb1dc02cc7.js +1 -0
  54. package/dist/dashboard/assets/next/static/chunks/app/page-ede77810f4904ea5.js +1 -0
  55. package/dist/dashboard/assets/next/static/chunks/app/{about/page-f24aa0d77f7fa73c.js → pricing/page-535834810dc4bee1.js} +1 -1
  56. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-94d508052ae30dcb.js +1 -0
  57. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-94d508052ae30dcb.js +1 -0
  58. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-94d508052ae30dcb.js +1 -0
  59. package/dist/dashboard/assets/next/static/chunks/app/security/page-94d508052ae30dcb.js +1 -0
  60. package/dist/dashboard/assets/next/static/chunks/app/signup/page-7ee25051f2743d68.js +1 -0
  61. package/dist/dashboard/assets/next/static/chunks/app/sitemap.xml/route-11a5fdc2662ff51d.js +1 -0
  62. package/dist/dashboard/assets/next/static/chunks/app/status/{page-7ce6f0e1c434b71e.js → page-569ae36bd08d867c.js} +1 -1
  63. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-94d508052ae30dcb.js +1 -0
  64. package/dist/dashboard/assets/next/static/chunks/app/terms/page-94d508052ae30dcb.js +1 -0
  65. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-b92ad482b0164f93.js +1 -0
  66. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-b1341267b2478360.js +1 -0
  67. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-edb84faba63372b4.js +1 -0
  68. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-bfbe86a28adc6d30.js +1 -0
  69. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-79cd80f87d39230d.js +1 -0
  70. package/dist/dashboard/assets/next/static/chunks/app/v2/page-1391f1ae01a91dc0.js +1 -0
  71. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-bfbe86a28adc6d30.js +1 -0
  72. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-94d508052ae30dcb.js +1 -0
  73. package/dist/dashboard/assets/next/static/chunks/{2db4c2cd.95079e665828175d.js → b468fba8.437b212aae4abcf8.js} +1 -1
  74. package/dist/dashboard/assets/next/static/chunks/framework-e54b663a2888b5de.js +1 -0
  75. package/dist/dashboard/assets/next/static/chunks/main-5aa70aa3d6a46aa0.js +1 -0
  76. package/dist/dashboard/assets/next/static/chunks/main-app-b4faf61f2e1c2b6d.js +1 -0
  77. package/dist/dashboard/assets/next/static/chunks/pages/_app-6c8c2371b16a04b8.js +1 -0
  78. package/dist/dashboard/assets/next/static/chunks/pages/_error-94812ad32cad7365.js +1 -0
  79. package/dist/dashboard/assets/next/static/chunks/webpack-1d489f41fe167959.js +1 -0
  80. package/dist/dashboard/assets/next/static/css/542f5281c59de6ae.css +1 -0
  81. package/dist/dashboard/assets/next/static/css/605ac70c9cf7a260.css +1 -0
  82. package/dist/dashboard/assets/next/static/css/734b61a26b31f1d1.css +1 -0
  83. package/dist/dashboard/assets/next/static/m3owxChJUGxcTX3zU04al/_buildManifest.js +1 -0
  84. package/dist/dashboard/index.html +2 -2
  85. package/dist/engine.js +5513 -1836
  86. package/dist/gateway.js +1740 -720
  87. package/dist/twins/catalog.json +115 -115
  88. package/dist/twins/packs/slack/NOTICE +1 -1
  89. package/dist/twins/packs/slack/index.mjs +8 -8
  90. package/dist/twins/packs/stripe/NOTICE +1 -1
  91. package/dist/twins/packs/stripe/index.mjs +8 -8
  92. package/dist/worker.js +1239 -478
  93. package/dist/world-host.js +1381 -519
  94. package/package.json +2 -1
  95. package/dist/dashboard/assets/next/static/c1e-XsXauzTgZ5LPHO9qr/_buildManifest.js +0 -1
  96. package/dist/dashboard/assets/next/static/chunks/3023-f8f4e462320a2292.js +0 -1
  97. package/dist/dashboard/assets/next/static/chunks/3054-936b20c5b915b68e.js +0 -1
  98. package/dist/dashboard/assets/next/static/chunks/3269.db5e9e84abf99c14.js +0 -1
  99. package/dist/dashboard/assets/next/static/chunks/5153-306b5cc29af7b739.js +0 -1
  100. package/dist/dashboard/assets/next/static/chunks/5301-889a97570ecc1207.js +0 -1
  101. package/dist/dashboard/assets/next/static/chunks/709.2c0acddce9cffa19.js +0 -1
  102. package/dist/dashboard/assets/next/static/chunks/7796-dcf7d396bd4449c0.js +0 -1
  103. package/dist/dashboard/assets/next/static/chunks/9029-e0ae3088a6980a25.js +0 -1
  104. package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-abd7b06b013b863e.js +0 -1
  105. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-4a176798090a08d6.js +0 -1
  106. package/dist/dashboard/assets/next/static/chunks/app/auth/page-4a176798090a08d6.js +0 -1
  107. package/dist/dashboard/assets/next/static/chunks/app/blog/choose-first-agent-workflow-test/page-9f75918bfb87ef66.js +0 -1
  108. package/dist/dashboard/assets/next/static/chunks/app/blog/clean-baseline-before-fault-injection/page-9f75918bfb87ef66.js +0 -1
  109. package/dist/dashboard/assets/next/static/chunks/app/blog/idempotency-keys-and-safe-retries/page-9f75918bfb87ef66.js +0 -1
  110. package/dist/dashboard/assets/next/static/chunks/app/blog/keep-real-service-tests-with-digital-twins/page-9f75918bfb87ef66.js +0 -1
  111. package/dist/dashboard/assets/next/static/chunks/app/blog/keploy-alternatives-for-database-and-payment-workflows/page-9f75918bfb87ef66.js +0 -1
  112. package/dist/dashboard/assets/next/static/chunks/app/blog/layout-c4d11b2d8403020d.js +0 -1
  113. package/dist/dashboard/assets/next/static/chunks/app/blog/page-9f75918bfb87ef66.js +0 -1
  114. package/dist/dashboard/assets/next/static/chunks/app/blog/read-workflow-test-receipts/page-9f75918bfb87ef66.js +0 -1
  115. package/dist/dashboard/assets/next/static/chunks/app/blog/reset-test-environment-between-runs/page-9f75918bfb87ef66.js +0 -1
  116. package/dist/dashboard/assets/next/static/chunks/app/blog/simulate-timeouts-and-duplicate-events/page-9f75918bfb87ef66.js +0 -1
  117. package/dist/dashboard/assets/next/static/chunks/app/blog/test-boundaries-for-ai-agents/page-9f75918bfb87ef66.js +0 -1
  118. package/dist/dashboard/assets/next/static/chunks/app/blog/workflow-testing-evaluation-checklist/page-9f75918bfb87ef66.js +0 -1
  119. package/dist/dashboard/assets/next/static/chunks/app/blog/write-better-workflow-assertions/page-9f75918bfb87ef66.js +0 -1
  120. package/dist/dashboard/assets/next/static/chunks/app/compare/page-4a176798090a08d6.js +0 -1
  121. package/dist/dashboard/assets/next/static/chunks/app/contact/page-4a176798090a08d6.js +0 -1
  122. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-039b7665231d6e02.js +0 -1
  123. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-651d698c70c4751d.js +0 -1
  124. package/dist/dashboard/assets/next/static/chunks/app/demo/page-823ab04e4ce3d98d.js +0 -1
  125. package/dist/dashboard/assets/next/static/chunks/app/developers/page-4a176798090a08d6.js +0 -1
  126. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-257fb2b60b9c51ea.js +0 -1
  127. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-4a176798090a08d6.js +0 -1
  128. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-3b10665bd391180f.js +0 -1
  129. package/dist/dashboard/assets/next/static/chunks/app/guides/page-4a176798090a08d6.js +0 -1
  130. package/dist/dashboard/assets/next/static/chunks/app/layout-d5b27156a3186b08.js +0 -1
  131. package/dist/dashboard/assets/next/static/chunks/app/login/page-b7e1d396e6b8f1e5.js +0 -1
  132. package/dist/dashboard/assets/next/static/chunks/app/not-found-4a176798090a08d6.js +0 -1
  133. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-3a50aee18c830bd9.js +0 -1
  134. package/dist/dashboard/assets/next/static/chunks/app/page-f8bd9dabf8d184f0.js +0 -1
  135. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-832b691ac0762fc1.js +0 -1
  136. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-4a176798090a08d6.js +0 -1
  137. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-4a176798090a08d6.js +0 -1
  138. package/dist/dashboard/assets/next/static/chunks/app/security/page-4a176798090a08d6.js +0 -1
  139. package/dist/dashboard/assets/next/static/chunks/app/signup/page-b7e1d396e6b8f1e5.js +0 -1
  140. package/dist/dashboard/assets/next/static/chunks/app/sitemap.xml/route-9f75918bfb87ef66.js +0 -1
  141. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-4a176798090a08d6.js +0 -1
  142. package/dist/dashboard/assets/next/static/chunks/app/terms/page-4a176798090a08d6.js +0 -1
  143. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-3578b0057d2de8c7.js +0 -1
  144. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-7bb4b6860280b5cc.js +0 -1
  145. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-fbf2197ee73a9b94.js +0 -1
  146. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-830a35428306a169.js +0 -1
  147. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-8f78f1d869d1c720.js +0 -1
  148. package/dist/dashboard/assets/next/static/chunks/app/v2/page-e538ea410a189bb5.js +0 -1
  149. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-830a35428306a169.js +0 -1
  150. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-4a176798090a08d6.js +0 -1
  151. package/dist/dashboard/assets/next/static/chunks/framework-7f628fc50ede2b81.js +0 -1
  152. package/dist/dashboard/assets/next/static/chunks/main-app-c4d1f57d693643d5.js +0 -1
  153. package/dist/dashboard/assets/next/static/chunks/main-b1bb212229d52cfe.js +0 -1
  154. package/dist/dashboard/assets/next/static/chunks/pages/_app-76810ca023f9add6.js +0 -1
  155. package/dist/dashboard/assets/next/static/chunks/pages/_error-81ac1dd3015ead4e.js +0 -1
  156. package/dist/dashboard/assets/next/static/chunks/webpack-cf0b56829d9b93b8.js +0 -1
  157. package/dist/dashboard/assets/next/static/css/83930ae013ae9eac.css +0 -1
  158. package/dist/dashboard/assets/next/static/css/846a3ee2626b9e08.css +0 -1
  159. /package/dist/dashboard/assets/next/static/{c1e-XsXauzTgZ5LPHO9qr → m3owxChJUGxcTX3zU04al}/_ssgManifest.js +0 -0
package/dist/api.js CHANGED
@@ -396,9 +396,9 @@ function newId(resource, rows2, stream) {
396
396
  return `${resource.name}_${stream.nextHex(16)}`;
397
397
  }
398
398
  function routes(twin) {
399
- let list2 = cache.get(twin);
400
- if (list2) return list2;
401
- list2 = twin.operations.map((op2) => {
399
+ let list3 = cache.get(twin);
400
+ if (list3) return list3;
401
+ list3 = twin.operations.map((op2) => {
402
402
  const names = [];
403
403
  let literal = 0;
404
404
  const source = op2.path.split("/").map((seg) => {
@@ -415,8 +415,8 @@ function routes(twin) {
415
415
  }).join("/");
416
416
  return { op: op2, re: new RegExp(`^${source}/?$`), names, score: literal * 10 - names.length };
417
417
  }).sort((a, b) => b.score - a.score);
418
- cache.set(twin, list2);
419
- return list2;
418
+ cache.set(twin, list3);
419
+ return list3;
420
420
  }
421
421
  function matchOperation(twin, method, path2) {
422
422
  const candidates = [path2];
@@ -723,10 +723,69 @@ var init_adapters = __esm({
723
723
  }
724
724
  });
725
725
 
726
+ // src/runtime/compatible-packs.ts
727
+ function compatibleRequest(vendor, host, url) {
728
+ if (host.toLowerCase() !== vendor.host) return void 0;
729
+ if (vendor.prefix === "") return { host: BASE_HOST, url: url.startsWith("/v1/") ? url : "/v1" + url };
730
+ if (url === vendor.prefix || url.startsWith(vendor.prefix + "/") || url.startsWith(vendor.prefix + "?")) return { host: BASE_HOST, url: "/v1" + url.slice(vendor.prefix.length) };
731
+ return void 0;
732
+ }
733
+ function compatibleModel(pack, body2) {
734
+ const same2 = { body: body2, restore: (b) => b };
735
+ if (!compatibleVendor(pack) || !body2?.length) return same2;
736
+ let parsed;
737
+ try {
738
+ parsed = JSON.parse(body2.toString("utf8"));
739
+ } catch {
740
+ return same2;
741
+ }
742
+ const model = parsed?.model;
743
+ if (typeof model !== "string" || !model || model === STAND_IN_MODEL) return same2;
744
+ const swapped = Buffer.from(JSON.stringify({ ...parsed, model: STAND_IN_MODEL }));
745
+ const from = JSON.stringify(STAND_IN_MODEL), to = JSON.stringify(model);
746
+ return { body: swapped, restore: (b) => Buffer.from(b.toString("utf8").split(`"model":${from}`).join(`"model":${to}`).split(`[twin-stub:${STAND_IN_MODEL}]`).join(`[twin-stub:${model}]`)) };
747
+ }
748
+ var OPENAI_COMPATIBLE, BASE_PACK, BASE_HOST, compatibleVendor, STAND_IN_MODEL;
749
+ var init_compatible_packs = __esm({
750
+ "src/runtime/compatible-packs.ts"() {
751
+ "use strict";
752
+ OPENAI_COMPATIBLE = [
753
+ // https://console.groq.com/docs/openai
754
+ { name: "groq", title: "Groq", host: "api.groq.com", prefix: "/openai/v1", sdks: ["groq-sdk", "@ai-sdk/groq"], pypi: ["groq"], env: ["GROQ_API_KEY"] },
755
+ // https://inference-docs.cerebras.ai/resources/openai
756
+ { name: "cerebras", title: "Cerebras", host: "api.cerebras.ai", prefix: "/v1", sdks: ["@cerebras/cerebras_cloud_sdk", "@ai-sdk/cerebras"], pypi: ["cerebras-cloud-sdk"], env: ["CEREBRAS_API_KEY"] },
757
+ // https://docs.perplexity.ai/guides/chat-completions-guide (POST https://api.perplexity.ai/chat/completions)
758
+ { name: "perplexity", title: "Perplexity", host: "api.perplexity.ai", prefix: "", sdks: ["@ai-sdk/perplexity", "@perplexity-ai/perplexity_ai"], pypi: ["perplexityai"], env: ["PERPLEXITY_API_KEY", "PPLX_API_KEY"] },
759
+ // https://docs.sambanova.ai/cloud/docs/capabilities/openai-compatibility
760
+ { name: "sambanova", title: "SambaNova", host: "api.sambanova.ai", prefix: "/v1", sdks: ["sambanova", "@ai-sdk/sambanova"], pypi: ["sambanova"], env: ["SAMBANOVA_API_KEY"] }
761
+ ];
762
+ BASE_PACK = "openai";
763
+ BASE_HOST = "api.openai.com";
764
+ compatibleVendor = (name) => OPENAI_COMPATIBLE.find((v) => v.name === name);
765
+ STAND_IN_MODEL = "gpt-4o-mini";
766
+ }
767
+ });
768
+
726
769
  // src/runtime/packs.ts
727
- import { existsSync, readFileSync } from "fs";
770
+ import { existsSync, readdirSync, readFileSync } from "fs";
728
771
  import { dirname, join as join3, resolve } from "path";
729
772
  import { fileURLToPath, pathToFileURL } from "url";
773
+ function packWebSocketServer(generation) {
774
+ let found = webSockets.get(generation);
775
+ if (!found) {
776
+ found = (async () => {
777
+ const dir = join3(packsDir(), "engine", generation, "chunks");
778
+ for (const file of readdirSync(dir).filter((f) => f.endsWith(".mjs"))) {
779
+ if (!readFileSync(join3(dir, file), "utf8").includes("as WebSocketServer")) continue;
780
+ const mod = await import(pathToFileURL(join3(dir, file)).href);
781
+ if (mod.WebSocketServer) return mod.WebSocketServer;
782
+ }
783
+ throw new Error(`The ${generation} twin engine ships no WebSocket server`);
784
+ })();
785
+ webSockets.set(generation, found);
786
+ }
787
+ return found;
788
+ }
730
789
  function packsDir() {
731
790
  const here = dirname(fileURLToPath(import.meta.url));
732
791
  const candidates = [process.env.AGENTTWIN_TWINS_DIR, join3(here, "twins"), join3(here, "../twins"), resolve(here, "../../../twins/dist")];
@@ -736,6 +795,22 @@ function packCatalog() {
736
795
  if (cached !== void 0) return cached;
737
796
  const dir = packsDir();
738
797
  cached = dir ? JSON.parse(readFileSync(join3(dir, "catalog.json"), "utf8")) : null;
798
+ const base = cached?.packs[BASE_PACK];
799
+ if (cached && base) for (const v of OPENAI_COMPATIBLE) {
800
+ if (Object.hasOwn(cached.packs, v.name)) continue;
801
+ const field = base.credentialDoor?.fill.OPENAI_API_KEY ?? "api_key";
802
+ cached.packs[v.name] = {
803
+ ...base,
804
+ name: v.name,
805
+ vendor: v.name,
806
+ servedBy: BASE_PACK,
807
+ description: `${v.title} (OpenAI-compatible API), served by the OpenAI twin`,
808
+ hosts: [{ host: v.host }],
809
+ adoption: { sdks: v.sdks, envStems: v.env.map((e) => e.replace(/_API_KEY$/, "")), pypi: v.pypi },
810
+ credentialDoor: base.credentialDoor ? { ...base.credentialDoor, fill: Object.fromEntries(v.env.map((e) => [e, field])) } : null
811
+ };
812
+ delete cached.excluded?.[v.name];
813
+ }
739
814
  return cached;
740
815
  }
741
816
  function loadPack(name) {
@@ -743,7 +818,7 @@ function loadPack(name) {
743
818
  if (!record4) throw new Error(`No twin pack named ${name}`);
744
819
  let factory = loaded.get(name);
745
820
  if (!factory) {
746
- const file = join3(packsDir(), "packs", name, "index.mjs");
821
+ const file = join3(packsDir(), "packs", record4.servedBy ?? name, "index.mjs");
747
822
  factory = import(pathToFileURL(file).href).then((mod) => {
748
823
  if (typeof mod.createTwinFetch !== "function") throw new Error(`Twin pack ${name} exports no createTwinFetch`);
749
824
  return mod.createTwinFetch;
@@ -752,10 +827,12 @@ function loadPack(name) {
752
827
  }
753
828
  return factory;
754
829
  }
755
- var cached, PACK_PREFIX, isPackAdapter, packRecord, loaded;
830
+ var webSockets, cached, PACK_PREFIX, isPackAdapter, packRecord, loaded;
756
831
  var init_packs = __esm({
757
832
  "src/runtime/packs.ts"() {
758
833
  "use strict";
834
+ init_compatible_packs();
835
+ webSockets = /* @__PURE__ */ new Map();
759
836
  PACK_PREFIX = "pack:";
760
837
  isPackAdapter = (adapter) => typeof adapter === "string" && adapter.startsWith(PACK_PREFIX) && !!packRecord(adapter.slice(PACK_PREFIX.length));
761
838
  packRecord = (name) => {
@@ -1348,9 +1425,9 @@ var init_enterprise_twins = __esm({
1348
1425
  return write("/driveItems", record4, record4, 201);
1349
1426
  }
1350
1427
  if (!listKey) return method === "GET" ? read("/lists", { value: lists.filter((l) => l.siteId === siteId) }) : void 0;
1351
- const list2 = lists.find((l) => l.siteId === siteId && (l.id === listKey || l.displayName === decodeURIComponent(listKey)));
1352
- if (!list2) return { ...graphError(404, "itemNotFound", "The requested list was not found.", sequence), collection: "/listItems" };
1353
- const own = items.filter((i) => i.listId === list2.id);
1428
+ const list3 = lists.find((l) => l.siteId === siteId && (l.id === listKey || l.displayName === decodeURIComponent(listKey)));
1429
+ if (!list3) return { ...graphError(404, "itemNotFound", "The requested list was not found.", sequence), collection: "/listItems" };
1430
+ const own = items.filter((i) => i.listId === list3.id);
1354
1431
  const view = (i, withFields = query.expand === "fields" || query.$expand === "fields") => {
1355
1432
  const { listId: _l, siteId: _s, fields, ...rest } = i;
1356
1433
  return withFields ? { ...rest, fields } : rest;
@@ -1362,7 +1439,7 @@ var init_enterprise_twins = __esm({
1362
1439
  if (!itemId && method === "POST") {
1363
1440
  if (!isObject(body2.fields) || !flat2(body2.fields)) return { ...graphError(400, "invalidRequest", "Invalid request: fields are required.", sequence), collection: "/listItems" };
1364
1441
  const id = String(nextNumber(own, "id", 1));
1365
- const record4 = { id, listId: list2.id, siteId, createdDateTime: iso(sequence), lastModifiedDateTime: iso(sequence), webUrl: `https://contoso.sharepoint.test/sites/${siteId}/Lists/${list2.displayName}/DispForm.aspx?ID=${id}`, fields: { id, Title: body2.fields.Title ?? null, ...body2.fields } };
1442
+ const record4 = { id, listId: list3.id, siteId, createdDateTime: iso(sequence), lastModifiedDateTime: iso(sequence), webUrl: `https://contoso.sharepoint.test/sites/${siteId}/Lists/${list3.displayName}/DispForm.aspx?ID=${id}`, fields: { id, Title: body2.fields.Title ?? null, ...body2.fields } };
1366
1443
  items.push(record4);
1367
1444
  return write("/listItems", record4, view(record4, true), 201);
1368
1445
  }
@@ -1770,7 +1847,7 @@ function parseWorld(value) {
1770
1847
  if (item.adapter !== void 0 && !["json-collection", "slack", "stripe", "openai", "anthropic", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk", "google-oauth", "composio", "upstash-redis", ...ENTERPRISE_ADAPTERS].includes(String(item.adapter)) && !isGeneratedAdapter(item.adapter) && !isPackAdapter(item.adapter)) invalid("unsupported service adapter");
1771
1848
  const paths = /* @__PURE__ */ new Set();
1772
1849
  for (const entry of item.collections) {
1773
- if (!object2(entry) || typeof entry.path !== "string" || !/^\/[a-zA-Z0-9_/-]+$/.test(entry.path) || entry.path.includes("//") || paths.has(entry.path)) invalid("collection paths must be unique absolute HTTP paths");
1850
+ if (!object2(entry) || typeof entry.path !== "string" || !/^\/[a-zA-Z0-9_./-]+$/.test(entry.path) || entry.path.includes("//") || /(^|\/)\.\.?(\/|$)/.test(entry.path) || paths.has(entry.path)) invalid("collection paths must be unique absolute HTTP paths");
1774
1851
  const collection = entry;
1775
1852
  if (!Array.isArray(collection.seed) || collection.seed.length > 1e3 || !collection.seed.every(object2)) invalid("seed must be an array of up to 1000 JSON records");
1776
1853
  paths.add(collection.path);
@@ -1779,6 +1856,7 @@ function parseWorld(value) {
1779
1856
  const optional = ADAPTER_OPTIONAL_COLLECTIONS[item.adapter] ?? [];
1780
1857
  if (required && (!required.every((p) => paths.has(p)) || [...paths].some((p) => !required.includes(p) && !optional.includes(p)))) invalid(`${item.adapter} adapter requires exactly ${required.join(", ")} collections${optional.length ? ` (optionally ${optional.join(", ")})` : ""}`);
1781
1858
  if (item.account !== void 0 && (!isPackAdapter(item.adapter) || !object2(item.account) || Object.keys(item.account).length > 10 || !Object.entries(item.account).every(([k, val]) => /^_?[a-z][a-z0-9_]{0,40}$/.test(k) && ["string", "number", "boolean"].includes(typeof val) && String(val).length <= 200))) invalid("account is for twin packs only: up to 10 simple fields with string, number or boolean values");
1859
+ if (item.doorRecords !== void 0 && (!isPackAdapter(item.adapter) || !Array.isArray(item.doorRecords) || item.doorRecords.length > 5 || !item.doorRecords.every((r) => object2(r) && typeof r.type === "string" && /^[a-z][a-z0-9_]{0,40}$/.test(r.type) && typeof r.id === "string" && /^[A-Za-z0-9_.:-]{1,80}$/.test(r.id) && object2(r.fields) && JSON.stringify(r.fields).length <= 2e4))) invalid("doorRecords is for twin packs only: up to 5 records with a type, an id and their fields");
1782
1860
  services.set(item.name, /* @__PURE__ */ new Set([...paths, ...optional]));
1783
1861
  }
1784
1862
  const known2 = (entry) => typeof entry.service === "string" && typeof entry.path === "string" && services.get(entry.service)?.has(entry.path);
@@ -1976,7 +2054,8 @@ var init_spec = __esm({
1976
2054
  init_enterprise_twins();
1977
2055
  RUNTIMES = /^(?:\/[\w./-]+\/)?(?:node|python[0-9.]*|uv|poetry|pipenv|go|ruby|bundle|deno|bun|curl)$/;
1978
2056
  ADAPTER_OPTIONAL_COLLECTIONS = {
1979
- stripe: ["/v1/charges", "/v1/refunds", "/v1/events"],
2057
+ slack: ["/users"],
2058
+ stripe: ["/v1/charges", "/v1/refunds", "/v1/events", "/v1/subscription_items", "/v1/products", "/v1/prices"],
1980
2059
  gmail: ["/gmail/v1/users/me/drafts", "/gmail/v1/users/me/settings/sendAs", "/gmail/v1/users/me/watch", "/pubsub/subscriptions", "/pubsub/messages"],
1981
2060
  ...ENTERPRISE_OPTIONAL_COLLECTIONS
1982
2061
  };
@@ -2080,6 +2159,32 @@ var init_scenarios = __esm({
2080
2159
  }
2081
2160
  });
2082
2161
 
2162
+ // src/runtime/node-options.ts
2163
+ import { realpath, writeFile as writeFile3 } from "fs/promises";
2164
+ async function singlePreload(options, hook) {
2165
+ const preloads = [], rest = [];
2166
+ const tokens = options.match(/(?:[^\s"]+|"[^"]*")+/g) ?? [];
2167
+ for (let i = 0; i < tokens.length; i++) {
2168
+ const t = tokens[i], unquote = (v) => v.replace(/^"|"$/g, "");
2169
+ if (t === "--require" || t === "-r") {
2170
+ if (tokens[i + 1]) preloads.push(unquote(tokens[++i]));
2171
+ } else if (t.startsWith("--require=")) preloads.push(unquote(t.slice(10)));
2172
+ else rest.push(t);
2173
+ }
2174
+ const real = await realpath(hook).catch(() => hook);
2175
+ preloads.push(real);
2176
+ const combined = `${real}.all.cjs`;
2177
+ await writeFile3(combined, preloads.map((p) => `require(${JSON.stringify(p)});`).join("\n") + "\n", { mode: 384 });
2178
+ return [...rest, `--require ${requireArg(combined)}`].join(" ");
2179
+ }
2180
+ var requireArg;
2181
+ var init_node_options = __esm({
2182
+ "src/runtime/node-options.ts"() {
2183
+ "use strict";
2184
+ requireArg = (path2) => /[\s"']/.test(path2) ? JSON.stringify(path2) : path2;
2185
+ }
2186
+ });
2187
+
2083
2188
  // src/runtime/application-process.ts
2084
2189
  import { execFile } from "child_process";
2085
2190
  import { promisify } from "util";
@@ -2283,7 +2388,7 @@ var init_browser_process_windows = __esm({
2283
2388
  });
2284
2389
 
2285
2390
  // src/runtime/browser-process.ts
2286
- import { mkdtemp, writeFile as writeFile3, readFile as readFile4, rm } from "fs/promises";
2391
+ import { mkdtemp, writeFile as writeFile4, readFile as readFile4, rm } from "fs/promises";
2287
2392
  import { tmpdir } from "os";
2288
2393
  import { join as join5 } from "path";
2289
2394
  import { execFile as execFile3 } from "child_process";
@@ -2293,7 +2398,7 @@ async function ownBrowserProcess(executable) {
2293
2398
  });
2294
2399
  const root = await mkdtemp(join5(tmpdir(), "agenttwin-browser-owner-"));
2295
2400
  const pidFile = join5(root, "pid"), launcher = join5(root, "launch");
2296
- await writeFile3(launcher, `#!/bin/sh
2401
+ await writeFile4(launcher, `#!/bin/sh
2297
2402
  echo $$ > ${quote(pidFile)}
2298
2403
  exec ${quote(executable)} "$@"
2299
2404
  `, { mode: 448 });
@@ -2600,7 +2705,7 @@ var init_browser_execution = __esm({
2600
2705
  });
2601
2706
 
2602
2707
  // src/runtime/request-source.ts
2603
- import { mkdtemp as mkdtemp3, writeFile as writeFile4, rm as rm3, realpath, open } from "fs/promises";
2708
+ import { mkdtemp as mkdtemp3, writeFile as writeFile5, rm as rm3, realpath as realpath2, open } from "fs/promises";
2604
2709
  import { tmpdir as tmpdir3 } from "os";
2605
2710
  import { join as join7, resolve as resolve2 } from "path";
2606
2711
  function parseRequestSource(raw, spec) {
@@ -2629,7 +2734,7 @@ async function createRequestSourceHook(app, spec, credentials2, runtime) {
2629
2734
  const dir = await mkdtemp3(join7(tmpdir3(), "agenttwin-source-hook-"));
2630
2735
  const path2 = join7(dir, "hook.cjs");
2631
2736
  const violationsPath = join7(dir, "blocked.jsonl");
2632
- const config = { root: runtime?.root ?? await realpath(resolve2(app)), files: spec.files, origins: Object.values(credentials2).map((c) => new URL(c.endpoint).origin), routes: Object.fromEntries((spec.fetchRoutes ?? []).map((r) => [r.origin, credentials2[r.service]])), routing: !!spec.fetchRoutes, violationsFd: runtime?.violationsFd, stdioViolations: !!runtime?.stdioViolations, violationsPath: runtime?.violationsPath ?? violationsPath };
2737
+ const config = { root: runtime?.root ?? await realpath2(resolve2(app)), files: spec.files, origins: Object.values(credentials2).map((c) => new URL(c.endpoint).origin), routes: Object.fromEntries((spec.fetchRoutes ?? []).map((r) => [r.origin, credentials2[r.service]])), routing: !!spec.fetchRoutes, violationsFd: runtime?.violationsFd, stdioViolations: !!runtime?.stdioViolations, violationsPath: runtime?.violationsPath ?? violationsPath };
2633
2738
  const guard = "const hookKey=Symbol.for('agenttwin.requestHook.v1');if(globalThis[hookKey])return;Object.defineProperty(globalThis,hookKey,{value:true});\n";
2634
2739
  const hook = guard + applicationClockHook(spec.applicationClock) + `const config=${JSON.stringify(config)};
2635
2740
  ` + String.raw`
@@ -2643,7 +2748,7 @@ function writeViolation(violation){const line=JSON.stringify(violation)+'\n';if(
2643
2748
  // Child processes: Node descendants inherit this hook through NODE_OPTIONS, even when the app passes its own env.
2644
2749
  // Any other executable runs outside the hook, so it is recorded and the run cannot be complete.
2645
2750
  const childProcess=require('node:child_process');
2646
- const hookOption='--require '+JSON.stringify(__filename);
2751
+ const hookOption='--require '+(/[\s"']/.test(__filename)?JSON.stringify(__filename):__filename);
2647
2752
  // Trust is decided from the file that would run, never its name: the Node binary itself, a script whose shebang runs
2648
2753
  // that binary (node_modules/.bin CLIs, npm, npx), or esbuild's own binary inside its package. Results are cached per real path and PATH.
2649
2754
  const executableTrust=new Map();
@@ -2657,15 +2762,23 @@ function runsHookedNode(interpreter,options){const file=resolveCommand(interpret
2657
2762
  // '#!/path/to/node', '#!/usr/bin/env node' and '#!/usr/bin/env -S node --flags' run Node; anything else does not.
2658
2763
  function nodeShebang(head,options){if(!head.startsWith('#!'))return false;const tokens=head.slice(2).split('\n')[0].replace(/\r$/,'').trim().split(/[ \t]+/).filter(Boolean);if(!tokens.length)return false;let program=tokens[0];if(path.basename(program)==='env'){program=tokens.slice(1).find(t=>!t.startsWith('-')&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(t));if(!program)return false;}else if(!path.isAbsolute(program))return false;return runsHookedNode(program,options);}
2659
2764
  function esbuildBinary(real){const match=real.match(/^(.*[\/\\]node_modules[\/\\](?:esbuild|@esbuild[\/\\][^\/\\]+))(?:[\/\\]bin)?[\/\\]esbuild(?:\.exe)?$/);if(!match)return false;try{const name=JSON.parse(nodeFs.readFileSync(path.join(match[1],'package.json'),'utf8')).name;return name==='esbuild'||(typeof name==='string'&&name.startsWith('@esbuild/'));}catch{return false;}}
2660
- function trustedExecutable(file,options){const real=nodeFs.realpathSync(file);const key=real+'\0'+String(envPath((options&&options.env)||process.env)||'');if(executableTrust.has(key))return executableTrust.get(key);let trusted=real===nodeReal||esbuildBinary(real);if(!trusted&&isRunnable(real)){const fd=nodeFs.openSync(real,'r');try{const head=Buffer.alloc(256);const read=nodeFs.readSync(fd,head,0,256,0);trusted=nodeShebang(head.subarray(0,read).toString('latin1'),options);}finally{nodeFs.closeSync(fd);}}if(executableTrust.size<1000)executableTrust.set(key,trusted);return trusted;}
2765
+ // Operating-system tools that only print facts about this machine and cannot open a connection. SDKs and frameworks
2766
+ // run them for a user-agent string (Stripe: uname; Next.js: sw_vers). Matched by their fixed system path, so a file of
2767
+ // the same name inside a project or earlier on PATH is still reported.
2768
+ const SYSTEM_INFO_BINARIES=new Set(['/usr/bin/uname','/bin/uname','/usr/bin/sw_vers','/usr/bin/arch','/usr/bin/nproc','/usr/bin/getconf']);
2769
+ function systemInfoBinary(real){return process.platform!=='win32'&&SYSTEM_INFO_BINARIES.has(real);}
2770
+ function trustedExecutable(file,options){const real=nodeFs.realpathSync(file);const key=real+'\0'+String(envPath((options&&options.env)||process.env)||'');if(executableTrust.has(key))return executableTrust.get(key);let trusted=real===nodeReal||esbuildBinary(real)||systemInfoBinary(real);if(!trusted&&isRunnable(real)){const fd=nodeFs.openSync(real,'r');try{const head=Buffer.alloc(256);const read=nodeFs.readSync(fd,head,0,256,0);trusted=nodeShebang(head.subarray(0,read).toString('latin1'),options);}finally{nodeFs.closeSync(fd);}}if(executableTrust.size<1000)executableTrust.set(key,trusted);return trusted;}
2661
2771
  const reportedSubprocesses=new Set();
2662
2772
  function hookedEnv(options){const env={...((options&&options.env)||process.env)};const current=env.NODE_OPTIONS||'';if(!current.includes(__filename))env.NODE_OPTIONS=(current+' '+hookOption).trim();env.AGENTTWIN_HOOK_CHILD='1';return {...(options||{}),env};}
2663
2773
  // Never throws: an unclassifiable command is reported, and the application's spawn proceeds unchanged.
2664
2774
  // Shell commands are judged by their first word, so 'sh -c' style wrappers are reported as non-Node.
2665
- function checkExecutable(command,shell,options){let name='unknown',trusted=false;try{const text=String(command).trim();const first=(shell?(text.split(/\s+/).find(token=>!/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))||''):text).replace(/^["']|["']$/g,'');name=path.basename(first).replace(/\.(exe|cmd)$/i,'')||'unknown';if(reportedSubprocesses.has(name)||reportedSubprocesses.size>=100)return;const file=first&&resolveCommand(first,options);trusted=!!file&&trustedExecutable(file,options);}catch{trusted=false;}if(trusted||reportedSubprocesses.has(name)||reportedSubprocesses.size>=100)return;reportedSubprocesses.add(name);try{writeViolation({origin:('subprocess:'+name).slice(0,2048),reason:'unhooked-subprocess'});}catch{}}
2775
+ // git asked about the local checkout only (the commit a build stamps, the branch): no network, nothing written.
2776
+ const LOCAL_GIT=/^(rev-parse|describe|log|show|status|branch|symbolic-ref|ls-files|rev-list|config)$/;
2777
+ function localGit(name,words){if(name!=='git')return false;const sub=words.find(w=>!String(w).startsWith('-'));return !!sub&&LOCAL_GIT.test(String(sub))&&(sub!=='config'||words.some(w=>/^--get/.test(String(w))));}
2778
+ function checkExecutable(command,shell,options,args){let name='unknown',trusted=false;try{const text=String(command).trim();const first=(shell?(text.split(/\s+/).find(token=>!/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))||''):text).replace(/^["']|["']$/g,'');name=path.basename(first).replace(/\.(exe|cmd)$/i,'')||'unknown';if(reportedSubprocesses.has(name)||reportedSubprocesses.size>=100)return;const file=first&&resolveCommand(first,options);trusted=!!file&&trustedExecutable(file,options);if(!trusted)trusted=localGit(name,shell?text.split(/\s+/).slice(1):(Array.isArray(args)?args:[]));}catch{trusted=false;}if(trusted||reportedSubprocesses.has(name)||reportedSubprocesses.size>=100)return;reportedSubprocesses.add(name);try{writeViolation({origin:('subprocess:'+name).slice(0,2048),reason:'unhooked-subprocess'});}catch{}}
2666
2779
  // Puts the hooked env into the options argument at index i, inserting an options object when there is none.
2667
2780
  function withOptions(args,i){const out=[...args];const o=out[i];if(o&&typeof o==='object'&&!Array.isArray(o))out[i]=hookedEnv(o);else out.splice(Math.min(i,out.length),o==null&&i<out.length?1:0,hookedEnv({}));return out;}
2668
- for(const name of ['spawn','spawnSync','execFile','execFileSync','fork']){const original=childProcess[name];if(typeof original!=='function')continue;childProcess[name]=function(file,...rest){const optionsAt=Array.isArray(rest[0])||(rest[0]==null&&rest.length>1)?2:1;const patched=withOptions([file,...rest],optionsAt);if(name!=='fork')checkExecutable(file,!!patched[optionsAt].shell,patched[optionsAt]);return original.apply(this,patched);};}
2781
+ for(const name of ['spawn','spawnSync','execFile','execFileSync','fork']){const original=childProcess[name];if(typeof original!=='function')continue;childProcess[name]=function(file,...rest){const optionsAt=Array.isArray(rest[0])||(rest[0]==null&&rest.length>1)?2:1;const patched=withOptions([file,...rest],optionsAt);if(name!=='fork')checkExecutable(file,!!patched[optionsAt].shell,patched[optionsAt],Array.isArray(rest[0])?rest[0]:[]);return original.apply(this,patched);};}
2669
2782
  for(const name of ['exec','execSync']){const original=childProcess[name];if(typeof original!=='function')continue;childProcess[name]=function(command,...rest){const patched=withOptions([command,...rest],1);checkExecutable(command,true,patched[1]);return original.apply(this,patched);};}
2670
2783
  function source(){for(const frame of new Error().stack.split('\n').slice(2)){const match=frame.match(/(?:\(|\s)(file:\/\/[^\s)]+|\/[^\s)]+):(\d+):(\d+)\)?$/);if(!match)continue;let file;try{file=match[1].startsWith('file:')?fileURLToPath(match[1]):match[1];}catch{continue;}file=path.relative(config.root,file);if(files.has(file))return JSON.stringify({file,line:Number(match[2]),column:Number(match[3])});}}
2671
2784
  const blockedOrigins=new Set();
@@ -2713,7 +2826,7 @@ for(const mod of [http,https])for(const method of ['request','get']){const origi
2713
2826
  if(!origins.has(url.origin))return original.apply(this,args);const location=source();if(!location)return original.apply(this,args);const headers=Array.isArray(options.headers)?[...options.headers,'x-agenttwin-source',location]:{...options.headers,'x-agenttwin-source':location};const updated={...options,headers};if(index===1&&typeof args[1]==='function')args.splice(1,0,updated);else args[index]=updated;return original.apply(this,args);};}
2714
2827
  require('node:module').syncBuiltinESMExports();
2715
2828
  `;
2716
- await writeFile4(path2, hook, { mode: 384 });
2829
+ await writeFile5(path2, hook, { mode: 384 });
2717
2830
  return { path: path2, violationsPath, readViolations: async () => {
2718
2831
  try {
2719
2832
  const seen = /* @__PURE__ */ new Set();
@@ -2812,7 +2925,24 @@ function readOnlyOperation(method, resource, id, params, data) {
2812
2925
  const ordered = [...rows2].reverse().filter((r) => params.type === void 0 || r.type === params.type);
2813
2926
  return { status: 200, body: { object: "list", data: ordered.slice(0, limit2), has_more: ordered.length > limit2, url: collection }, collection, operation: "read" };
2814
2927
  }
2928
+ function subscriptionItemOperation(method, id, params, data) {
2929
+ const collection = "/v1/subscription_items";
2930
+ if (method !== "GET" && method !== "POST") return void 0;
2931
+ if (Object.keys(params).some((key2) => method !== "POST" || key2 !== "quantity")) return void 0;
2932
+ const item = data[collection]?.find((row) => row.id === id && row.deleted !== true);
2933
+ if (!item) return { ...stripeError(404, "resource_missing", `No such subscription_item: '${id}'`), collection };
2934
+ if (method === "GET") return { status: 200, body: item, collection, operation: "read" };
2935
+ const value = params.quantity;
2936
+ const quantity = typeof value === "string" && /^\d+$/.test(value) ? Number(value) : value;
2937
+ if (typeof quantity !== "number" || !Number.isSafeInteger(quantity) || quantity < 0) {
2938
+ return { ...stripeError(400, "parameter_invalid_integer", "quantity must be a non-negative integer", "quantity"), collection };
2939
+ }
2940
+ item.quantity = quantity;
2941
+ return { status: 200, body: item, collection, record: structuredClone(item), operation: "write" };
2942
+ }
2815
2943
  function stripeOperation(method, path2, params, data, sequence) {
2944
+ const item = /^\/v1\/subscription_items\/([^/]+)$/.exec(path2);
2945
+ if (item) return subscriptionItemOperation(method, item[1], params, data);
2816
2946
  const error = stripeError;
2817
2947
  const other = /^\/v1\/(refunds|charges|events)(?:\/([^/]+))?$/.exec(path2);
2818
2948
  if (other) return other[1] === "refunds" ? refundOperation(method, other[2], params, data, sequence) : readOnlyOperation(method, other[1], other[2], params, data);
@@ -3306,6 +3436,182 @@ var init_resp = __esm({
3306
3436
  }
3307
3437
  });
3308
3438
 
3439
+ // src/runtime/engines/redis-lua.ts
3440
+ import { createRequire } from "module";
3441
+ import { createHash as createHash8 } from "crypto";
3442
+ var vm, load2, toLua, fromLua, RedisScripts, WRITE_HINT;
3443
+ var init_redis_lua = __esm({
3444
+ "src/runtime/engines/redis-lua.ts"() {
3445
+ "use strict";
3446
+ init_resp();
3447
+ load2 = () => vm ??= createRequire(import.meta.url)("fengari");
3448
+ toLua = (s) => Uint8Array.from(Buffer.from(s, "latin1"));
3449
+ fromLua = (b) => Buffer.from(b).toString("latin1");
3450
+ RedisScripts = class {
3451
+ /** `run` executes one command on the engine and returns its RESP reply. */
3452
+ constructor(run3) {
3453
+ this.run = run3;
3454
+ }
3455
+ run;
3456
+ cache = /* @__PURE__ */ new Map();
3457
+ command(name, args) {
3458
+ if (name === "script") {
3459
+ const sub = (args[0] ?? "").toLowerCase();
3460
+ if (sub === "load") {
3461
+ const sha7 = this.store(args[1] ?? "");
3462
+ return encode.bulk(sha7);
3463
+ }
3464
+ if (sub === "exists") return encode.array(args.slice(1).map((sha7) => encode.int(this.cache.has(sha7.toLowerCase()) ? 1 : 0)));
3465
+ if (sub === "flush") {
3466
+ this.cache.clear();
3467
+ return encode.simple("OK");
3468
+ }
3469
+ return encode.error(`ERR unknown subcommand '${args[0]}'`);
3470
+ }
3471
+ const evalsha = name === "evalsha" || name === "evalsha_ro";
3472
+ const source = evalsha ? this.cache.get((args[0] ?? "").toLowerCase()) : args[0];
3473
+ if (source === void 0) return encode.error("NOSCRIPT No matching script. Please use EVAL.");
3474
+ const count = Number(args[1]);
3475
+ if (!Number.isInteger(count) || count < 0 || count > args.length - 2) return encode.error("ERR Number of keys can't be greater than number of args");
3476
+ if (!evalsha) this.store(source);
3477
+ return this.execute(source, args.slice(2, 2 + count), args.slice(2 + count), name.endsWith("_ro"));
3478
+ }
3479
+ store(source) {
3480
+ const sha7 = createHash8("sha1").update(Buffer.from(source, "latin1")).digest("hex");
3481
+ this.cache.set(sha7, source);
3482
+ return sha7;
3483
+ }
3484
+ execute(source, keys, argv, readOnly) {
3485
+ const { lua, lauxlib, lualib } = load2(), L = lauxlib.luaL_newstate();
3486
+ try {
3487
+ for (const [name, open3] of [["_G", lualib.luaopen_base], ["string", lualib.luaopen_string], ["table", lualib.luaopen_table], ["math", lualib.luaopen_math]]) {
3488
+ lauxlib.luaL_requiref(L, toLua(name), open3, 1);
3489
+ lua.lua_pop(L, 1);
3490
+ }
3491
+ for (const name of ["dofile", "loadfile", "load", "require", "print"]) lua.lua_pushnil(L), lua.lua_setglobal(L, toLua(name));
3492
+ const table2 = (items, global) => {
3493
+ lua.lua_createtable(L, items.length, 0);
3494
+ items.forEach((v, i) => {
3495
+ lua.lua_pushstring(L, toLua(v));
3496
+ lua.lua_rawseti(L, -2, i + 1);
3497
+ });
3498
+ lua.lua_setglobal(L, toLua(global));
3499
+ };
3500
+ table2(keys, "KEYS");
3501
+ table2(argv, "ARGV");
3502
+ lua.lua_createtable(L, 0, 4);
3503
+ const call2 = (raise) => (state) => {
3504
+ const n = lua.lua_gettop(state), args = [];
3505
+ for (let i = 1; i <= n; i++) {
3506
+ const t = lua.lua_type(state, i);
3507
+ if (t === lua.LUA_TNUMBER) {
3508
+ const v = lua.lua_tonumber(state, i);
3509
+ args.push(Number.isInteger(v) ? String(v) : String(v));
3510
+ } else if (t === lua.LUA_TSTRING) args.push(fromLua(lua.lua_tolstring(state, i)));
3511
+ else return lauxlib.luaL_error(state, toLua("Lua redis lib command arguments must be strings or integers"));
3512
+ }
3513
+ if (!args.length) return lauxlib.luaL_error(state, toLua("Please specify at least one argument for this redis lib call"));
3514
+ const command = args[0].toLowerCase();
3515
+ if (["eval", "evalsha", "eval_ro", "evalsha_ro", "script", "multi", "exec", "watch", "subscribe", "psubscribe", "blpop", "brpop", "blmove"].includes(command)) return lauxlib.luaL_error(state, toLua("This Redis command is not allowed from script"));
3516
+ if (readOnly && WRITE_HINT.test(command)) return lauxlib.luaL_error(state, toLua("Write commands are not allowed from read-only scripts"));
3517
+ const reply = parseResp(this.run(args))?.value ?? null;
3518
+ if (raise && reply && typeof reply === "object" && !Array.isArray(reply) && !Buffer.isBuffer(reply) && "error" in reply) return lauxlib.luaL_error(state, toLua(reply.error));
3519
+ push(state, reply);
3520
+ return 1;
3521
+ };
3522
+ const push = (state, v) => {
3523
+ if (v === null || v === false) lua.lua_pushboolean(state, 0);
3524
+ else if (v === true) lua.lua_pushinteger(state, 1);
3525
+ else if (typeof v === "number") lua.lua_pushinteger(state, v);
3526
+ else if (Buffer.isBuffer(v)) lua.lua_pushstring(state, Uint8Array.from(v));
3527
+ else if (Array.isArray(v)) {
3528
+ lua.lua_createtable(state, v.length, 0);
3529
+ v.forEach((x, i) => {
3530
+ push(state, x);
3531
+ lua.lua_rawseti(state, -2, i + 1);
3532
+ });
3533
+ } else {
3534
+ lua.lua_createtable(state, 0, 1);
3535
+ lua.lua_pushstring(state, toLua("simple" in v ? v.simple : v.error));
3536
+ lua.lua_setfield(state, -2, toLua("simple" in v ? "ok" : "err"));
3537
+ }
3538
+ };
3539
+ for (const [name, fn] of [["call", call2(true)], ["pcall", call2(false)]]) {
3540
+ lua.lua_pushcfunction(L, fn);
3541
+ lua.lua_setfield(L, -2, toLua(name));
3542
+ }
3543
+ lua.lua_pushcfunction(L, (state) => {
3544
+ lua.lua_createtable(state, 0, 1);
3545
+ lua.lua_pushvalue(state, 1);
3546
+ lua.lua_setfield(state, -2, toLua("err"));
3547
+ return 1;
3548
+ });
3549
+ lua.lua_setfield(L, -2, toLua("error_reply"));
3550
+ lua.lua_pushcfunction(L, (state) => {
3551
+ lua.lua_createtable(state, 0, 1);
3552
+ lua.lua_pushvalue(state, 1);
3553
+ lua.lua_setfield(state, -2, toLua("ok"));
3554
+ return 1;
3555
+ });
3556
+ lua.lua_setfield(L, -2, toLua("status_reply"));
3557
+ lua.lua_pushcfunction(L, () => 0);
3558
+ lua.lua_setfield(L, -2, toLua("log"));
3559
+ lua.lua_pushcfunction(L, () => 0);
3560
+ lua.lua_setfield(L, -2, toLua("replicate_commands"));
3561
+ lua.lua_setglobal(L, toLua("redis"));
3562
+ if (lauxlib.luaL_loadbuffer(L, toLua(source), null, toLua("@user_script")) !== lua.LUA_OK) return encode.error(`ERR Error compiling script (new function): ${this.message(L)}`);
3563
+ if (lua.lua_pcall(L, 0, 1, 0) !== lua.LUA_OK) return encode.error(`ERR Error running script: ${this.message(L)}`);
3564
+ return this.reply(L, -1);
3565
+ } finally {
3566
+ lua.lua_close(L);
3567
+ }
3568
+ }
3569
+ message(L) {
3570
+ const { lua } = load2();
3571
+ const m = lua.lua_tolstring(L, -1);
3572
+ return m ? fromLua(m) : "error";
3573
+ }
3574
+ /** The Lua value at `index` as a RESP reply, by Redis's conversion rules. */
3575
+ reply(L, index) {
3576
+ const { lua } = load2(), at = lua.lua_absindex(L, index);
3577
+ switch (lua.lua_type(L, at)) {
3578
+ case lua.LUA_TNUMBER:
3579
+ return encode.int(Math.trunc(lua.lua_tonumber(L, at)));
3580
+ case lua.LUA_TSTRING:
3581
+ return encode.bulk(Buffer.from(lua.lua_tolstring(L, at)));
3582
+ case lua.LUA_TBOOLEAN:
3583
+ return lua.lua_toboolean(L, at) ? encode.int(1) : encode.bulk(null);
3584
+ case lua.LUA_TTABLE: {
3585
+ for (const field of ["err", "ok"]) {
3586
+ lua.lua_getfield(L, at, toLua(field));
3587
+ if (lua.lua_type(L, -1) === lua.LUA_TSTRING) {
3588
+ const text3 = fromLua(lua.lua_tolstring(L, -1));
3589
+ lua.lua_pop(L, 1);
3590
+ return field === "err" ? encode.error(text3) : encode.simple(text3);
3591
+ }
3592
+ lua.lua_pop(L, 1);
3593
+ }
3594
+ const items = [];
3595
+ for (let i = 1; ; i++) {
3596
+ lua.lua_rawgeti(L, at, i);
3597
+ if (lua.lua_isnil(L, -1)) {
3598
+ lua.lua_pop(L, 1);
3599
+ break;
3600
+ }
3601
+ items.push(this.reply(L, -1));
3602
+ lua.lua_pop(L, 1);
3603
+ }
3604
+ return encode.array(items);
3605
+ }
3606
+ default:
3607
+ return encode.bulk(null);
3608
+ }
3609
+ }
3610
+ };
3611
+ WRITE_HINT = /^(set|setnx|setex|psetex|getset|getdel|getex|mset|msetnx|incr|incrby|incrbyfloat|decr|decrby|append|setrange|del|unlink|expire|pexpire|expireat|pexpireat|persist|rename|renamenx|copy|hset|hsetnx|hmset|hdel|hincrby|hincrbyfloat|lpush|rpush|lpop|rpop|lset|lrem|ltrim|linsert|lmove|rpoplpush|sadd|srem|spop|smove|zadd|zrem|zincrby|zpopmin|zpopmax|flushdb|flushall)$/;
3612
+ }
3613
+ });
3614
+
3309
3615
  // src/runtime/engines/host.ts
3310
3616
  import { execFile as execFile4 } from "child_process";
3311
3617
  import { access, constants } from "fs/promises";
@@ -3696,6 +4002,7 @@ var init_redis = __esm({
3696
4002
  "src/runtime/engines/redis.ts"() {
3697
4003
  "use strict";
3698
4004
  init_resp();
4005
+ init_redis_lua();
3699
4006
  init_types();
3700
4007
  init_host();
3701
4008
  WRITES = new Set("set setnx setex psetex getset getdel getex mset msetnx incr incrby incrbyfloat decr decrby append setrange del unlink expire pexpire expireat pexpireat persist rename renamenx copy move hset hsetnx hmset hdel hincrby hincrbyfloat lpush rpush lpushx rpushx lpop rpop lset lrem ltrim linsert lmove rpoplpush blpop brpop sadd srem spop smove zadd zrem zincrby zpopmin zpopmax zremrangebyscore zremrangebyrank xadd xdel xtrim flushdb flushall restore eval evalsha pfadd setbit geoadd json.set json.del".split(" "));
@@ -3819,9 +4126,12 @@ var init_redis = __esm({
3819
4126
  }
3820
4127
  return this.run(args);
3821
4128
  }
4129
+ /** Lua scripts (EVAL/EVALSHA/SCRIPT) run against this engine's own data; see redis-lua.ts. */
4130
+ scripts;
3822
4131
  run(args) {
3823
4132
  const name = args[0].toLowerCase(), a = args.slice(1);
3824
4133
  try {
4134
+ if (["eval", "evalsha", "eval_ro", "evalsha_ro", "script"].includes(name)) return (this.scripts ??= new RedisScripts((c) => this.run(c))).command(name, a);
3825
4135
  const reply = this.command(name, a);
3826
4136
  if (WRITES.has(name)) for (const k of commandKeys(name, a)) this.touch(k);
3827
4137
  return reply;
@@ -3836,7 +4146,7 @@ var init_redis = __esm({
3836
4146
  command(name, a) {
3837
4147
  const now = Date.now(), ok2 = encode.simple("OK"), key2 = a[0];
3838
4148
  const str2 = (k) => this.get(k, "string");
3839
- const bulks = (list2) => encode.array(list2.map((v) => encode.bulk(v ?? null)));
4149
+ const bulks = (list3) => encode.array(list3.map((v) => encode.bulk(v ?? null)));
3840
4150
  const setString = (k, v, expireAt) => this.data.set(k, { type: "string", value: v, ...expireAt !== void 0 ? { expireAt } : {} });
3841
4151
  const incr = (k, by) => {
3842
4152
  const cur = str2(k) ?? "0";
@@ -4356,7 +4666,7 @@ function upstashRedisOperation(method, path2, params, headers, data, _sequence,
4356
4666
  let full = false;
4357
4667
  for (const c of args) {
4358
4668
  const name = c[0].toLowerCase(), keys = commandKeys(name, c.slice(1));
4359
- if (GLOBAL_WRITES.has(name) || !keys.length && WRITE_COMMANDS.has(name)) full = true;
4669
+ if (GLOBAL_WRITES.has(name) || !keys.length && (WRITE_COMMANDS.has(name) || /^eval/.test(name))) full = true;
4360
4670
  for (const k of keys) touched.add(k);
4361
4671
  }
4362
4672
  if (full || cache3.nextExpiry <= now) resync(rows2, cache3);
@@ -4364,7 +4674,7 @@ function upstashRedisOperation(method, path2, params, headers, data, _sequence,
4364
4674
  const encoding = headers["upstash-encoding"];
4365
4675
  const base64 = typeof encoding === "string" && encoding.toLowerCase() === "base64";
4366
4676
  const results = replies.map((r) => upstashReply(r, base64));
4367
- const wrote = args.some((c) => WRITE_COMMANDS.has(c[0].toLowerCase()));
4677
+ const wrote = args.some((c) => WRITE_COMMANDS.has(c[0].toLowerCase()) || /^eval(sha)?$/.test(c[0].toLowerCase()));
4368
4678
  const record4 = { commands: args.map((c) => c[0].toUpperCase()), keys: args.map((c) => c[1] === void 0 ? null : fromBytes(c[1])) };
4369
4679
  if (single) {
4370
4680
  const result2 = results[0];
@@ -4380,7 +4690,7 @@ var init_upstash_redis_twin = __esm({
4380
4690
  init_resp();
4381
4691
  UPSTASH_KEYS = "/keys";
4382
4692
  WRITE_COMMANDS = new Set("set setnx setex psetex getset getdel getex mset msetnx incr incrby incrbyfloat decr decrby append setrange del unlink expire pexpire expireat pexpireat persist rename renamenx hset hsetnx hmset hdel hincrby hincrbyfloat lpush rpush lpushx rpushx lpop rpop lset lrem ltrim linsert lmove rpoplpush sadd srem spop smove zadd zrem zincrby zpopmin zpopmax zremrangebyscore zremrangebyrank flushdb flushall".split(" "));
4383
- REJECTED = /* @__PURE__ */ new Set(["eval", "evalsha", "eval_ro", "evalsha_ro", "script", "subscribe", "psubscribe", "blpop", "brpop", "blmove", "monitor", "multi", "exec", "watch"]);
4693
+ REJECTED = /* @__PURE__ */ new Set(["subscribe", "psubscribe", "blpop", "brpop", "blmove", "monitor", "multi", "exec", "watch"]);
4384
4694
  toBytes = (v) => Buffer.from(v, "utf8").toString("latin1");
4385
4695
  fromBytes = (v) => Buffer.from(v, "latin1").toString("utf8");
4386
4696
  caches = /* @__PURE__ */ new WeakMap();
@@ -4417,7 +4727,7 @@ function decodeEncodedWords(value) {
4417
4727
  let failure;
4418
4728
  const decoded = value.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=(\s+(?==\?))?/g, (_all, charset, kind, text3) => {
4419
4729
  if (!/^(utf-8|us-ascii)$/i.test(charset)) {
4420
- failure ??= mimeError(`Encoded header charset ${charset} is outside the verified subset`, true);
4730
+ failure ??= mimeError("Encoded header charset is outside the verified subset", true);
4421
4731
  return "";
4422
4732
  }
4423
4733
  if (kind.toUpperCase() === "B") return Buffer.from(text3, "base64").toString("utf8");
@@ -4474,12 +4784,12 @@ function decodeBody(body2, headers) {
4474
4784
  if (!/^[A-Za-z0-9+/]*={0,2}$/.test(compact)) return mimeError("Invalid base64 MIME body", false);
4475
4785
  return Buffer.from(compact, "base64");
4476
4786
  }
4477
- return mimeError(`Content-Transfer-Encoding ${encoding} is outside the verified subset`, true);
4787
+ return mimeError("Content-Transfer-Encoding is outside the verified subset", true);
4478
4788
  }
4479
4789
  function textPart(partId, headers, body2) {
4480
4790
  const { mimeType, params } = contentType(headers);
4481
- if (mimeType !== "text/plain" && mimeType !== "text/html") return mimeError(`MIME part ${mimeType} is outside the verified subset`, true);
4482
- if (params.charset && !/^(utf-8|us-ascii)$/i.test(params.charset)) return mimeError(`Charset ${params.charset} is outside the verified subset`, true);
4791
+ if (mimeType !== "text/plain" && mimeType !== "text/html") return mimeError("MIME part type is outside the verified subset", true);
4792
+ if (params.charset && !/^(utf-8|us-ascii)$/i.test(params.charset)) return mimeError("MIME charset is outside the verified subset", true);
4483
4793
  const decoded = decodeBody(body2, headers);
4484
4794
  if (!Buffer.isBuffer(decoded)) return decoded;
4485
4795
  if (Buffer.from(decoded.toString("utf8")).compare(decoded) !== 0) return mimeError("MIME text part is not valid UTF-8", true);
@@ -4500,11 +4810,21 @@ function parseGmailDraftRaw(raw) {
4500
4810
  let payload;
4501
4811
  if (mimeType === "multipart/alternative") {
4502
4812
  if (!params.boundary) return mimeError("multipart/alternative needs a boundary", false);
4503
- const sections = top.body.split(new RegExp(`(?:^|\\r?\\n)--${params.boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`));
4504
- const closing = sections.findIndex((s) => s.startsWith("--"));
4505
- if (closing < 0) return mimeError("multipart/alternative has no closing boundary", false);
4813
+ const boundary = params.boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4814
+ const delimiters = [];
4815
+ for (const match of top.body.matchAll(new RegExp(`(?:^|\\r?\\n)--${boundary}(--)?[ \\t]*(?=\\r?\\n|$)`, "g"))) {
4816
+ const start = match.index ?? 0;
4817
+ const closing = match[1] === "--";
4818
+ delimiters.push({ start, end: start + match[0].length, closing });
4819
+ if (closing || delimiters.length > 10) break;
4820
+ }
4821
+ const closed = delimiters.at(-1)?.closing === true;
4822
+ const count = delimiters.length - Number(closed);
4823
+ if (count > 10 || closed && count === 0) return mimeError("multipart/alternative needs 1 to 10 parts", false);
4824
+ if (!closed) return mimeError("multipart/alternative has no closing boundary", false);
4506
4825
  const parts = [];
4507
- for (const section of sections.slice(1, closing)) {
4826
+ for (let i = 0; i < count; i++) {
4827
+ const section = top.body.slice(delimiters[i].end, delimiters[i + 1].start);
4508
4828
  const split = splitHead(section.replace(/^[ \t]*\r?\n/, ""));
4509
4829
  if (!split) return mimeError("MIME part headers and body need a blank-line separator", false);
4510
4830
  const partHeaders = parseHeaderBlock(split.head);
@@ -4513,10 +4833,9 @@ function parseGmailDraftRaw(raw) {
4513
4833
  if ("error" in part) return part;
4514
4834
  parts.push(part);
4515
4835
  }
4516
- if (!parts.length || parts.length > 10) return mimeError("multipart/alternative needs 1 to 10 parts", false);
4517
4836
  payload = { partId: "", mimeType, filename: "", headers, body: { size: 0 }, parts };
4518
4837
  } else if (mimeType.startsWith("multipart/")) {
4519
- return mimeError(`${mimeType} (attachments or nested parts) is outside the verified subset`, true);
4838
+ return mimeError(mimeType === "multipart/mixed" ? "multipart/mixed (attachments or nested parts) is outside the verified subset" : "Multipart MIME type is outside the verified subset", true);
4520
4839
  } else {
4521
4840
  const part = textPart("", headers, top.body);
4522
4841
  if ("error" in part) return part;
@@ -4600,7 +4919,7 @@ var init_gmail_mime = __esm({
4600
4919
  });
4601
4920
 
4602
4921
  // src/runtime/rest-adapters.ts
4603
- import { createHash as createHash8 } from "crypto";
4922
+ import { createHash as createHash9 } from "crypto";
4604
4923
  function githubOperation(method, path2, params, _headers, data, sequence) {
4605
4924
  const errors = (status, message, extra) => ({ status, body: { message, documentation_url: "https://docs.github.com/rest", ...extra ?? {} }, collection: "/repos" });
4606
4925
  if (path2 === "/repos") return method === "GET" ? ok("/repos", rows(data, "/repos").map((row) => structuredClone(row))) : void 0;
@@ -5300,10 +5619,17 @@ function gmailOperation(method, path2, params, headers, data, sequence, raw) {
5300
5619
  if (params.subject !== void 0 && str(params.subject) === void 0) return fail2(400, "subject must be a string.");
5301
5620
  if (params.threadId !== void 0 && str(params.threadId) === void 0) return fail2(400, "threadId must be a string.");
5302
5621
  if (raw2 && text3 !== void 0) return fail2(400, "Provide raw or text, not both.");
5303
- const mime = raw2 ? parseGmailRaw(raw2) : void 0;
5304
- if (mime && "error" in mime) return mime.unsupported ? void 0 : fail2(400, mime.error);
5305
- const body2 = mime?.text ?? text3 ?? "";
5306
- const message = { id: `gmail_at_${sequence}`, threadId: str(params.threadId) ?? `gmail_at_${sequence}`, labelIds: ["SENT"], snippet: body2.slice(0, 100), payload: { mimeType: "text/plain", headers: mime?.headers ?? [{ name: "To", value: str(params.to) ?? "" }, { name: "Subject", value: str(params.subject) ?? "" }], body: { data: mime?.encodedBody ?? body2 } }, sizeEstimate: mime?.bytes ?? body2.length, internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) };
5622
+ const plain2 = raw2 ? parseGmailRaw(raw2) : void 0;
5623
+ const legacy = plain2 && !("error" in plain2) ? plain2 : void 0;
5624
+ const mime = raw2 && !legacy ? parseGmailDraftRaw(raw2) : void 0;
5625
+ if (mime && "error" in mime) {
5626
+ return mime.unsupported ? { status: 501, body: restUnsupportedBody("gmail"), collection: MESSAGES, unsupportedReason: mime.error } : fail2(400, mime.error);
5627
+ }
5628
+ if (mime && !headerAddresses(mime.headers.find((header3) => header3.name.toLowerCase() === "to")?.value).length) {
5629
+ return fail2(400, "Invalid To header: a sent message needs at least one recipient.");
5630
+ }
5631
+ const body2 = legacy?.text ?? mime?.snippet ?? text3 ?? "";
5632
+ const message = { id: `gmail_at_${sequence}`, threadId: str(params.threadId) ?? `gmail_at_${sequence}`, labelIds: ["SENT"], snippet: body2.slice(0, 100), payload: mime?.payload ?? { mimeType: "text/plain", headers: legacy?.headers ?? [{ name: "To", value: str(params.to) ?? "" }, { name: "Subject", value: str(params.subject) ?? "" }], body: { data: legacy?.encodedBody ?? body2 } }, sizeEstimate: mime?.bytes ?? body2.length, internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) };
5307
5633
  rowsIn(data, MESSAGES).push(message);
5308
5634
  return withPush(write2(200, MESSAGES, structuredClone(message), message), gmailPublish(data, ["SENT"], sequence));
5309
5635
  }
@@ -5346,7 +5672,38 @@ function gmailOperation(method, path2, params, headers, data, sequence, raw) {
5346
5672
  if (!message) return fail2(404, `Message not found: ${messageMatch[1]}`);
5347
5673
  return ok(MESSAGES, structuredClone(message));
5348
5674
  }
5675
+ const modifyMatch = /^\/gmail\/v1\/users\/me\/(messages|threads)\/([^/]+)\/modify$/.exec(path2);
5676
+ if (modifyMatch) {
5677
+ if (method !== "POST" || Object.keys(params).some((k) => !["addLabelIds", "removeLabelIds"].includes(k))) return void 0;
5678
+ const list3 = (v) => v === void 0 ? [] : Array.isArray(v) && v.every((x) => typeof x === "string") ? v : void 0;
5679
+ const add = list3(params.addLabelIds), remove2 = list3(params.removeLabelIds);
5680
+ if (!add || !remove2) return fail2(400, "Invalid label list.");
5681
+ const known2 = gmailLabelKnown(data), unknown = [...add, ...remove2].find((id2) => !known2(id2));
5682
+ if (unknown) return fail2(400, `Invalid label: ${unknown}`);
5683
+ const id = decodeURIComponent(modifyMatch[2]);
5684
+ const targets = modifyMatch[1] === "messages" ? rowsIn(data, MESSAGES).filter((m) => m.id === id) : rowsIn(data, MESSAGES).filter((m) => m.threadId === id);
5685
+ if (!targets.length) return fail2(404, `Requested entity was not found.`);
5686
+ const next = String(BigInt(gmailHistoryId(rowsIn(data, MESSAGES))) + 1n);
5687
+ for (const message of targets) {
5688
+ const labels = new Set(message.labelIds ?? []);
5689
+ for (const l of add) labels.add(l);
5690
+ for (const l of remove2) labels.delete(l);
5691
+ message.labelIds = [...labels];
5692
+ message.historyId = next;
5693
+ }
5694
+ const body2 = modifyMatch[1] === "messages" ? structuredClone(targets[0]) : { id, historyId: next, messages: targets.map((m) => structuredClone(m)) };
5695
+ return { status: 200, body: body2, collection: MESSAGES, operation: "write", record: { id, addLabelIds: add, removeLabelIds: remove2 } };
5696
+ }
5349
5697
  if (path2 === LABELS) {
5698
+ if (method === "POST") {
5699
+ if (Object.keys(params).some((k) => !["name", "labelListVisibility", "messageListVisibility", "color", "type"].includes(k))) return void 0;
5700
+ if (typeof params.name !== "string" || !params.name.trim()) return googleError(LABELS, 400, "Invalid label name");
5701
+ const labels = rowsIn(data, LABELS);
5702
+ if (labels.some((l) => String(l.name).toLowerCase() === String(params.name).toLowerCase()) || GMAIL_SYSTEM_LABEL_NAMES.has(String(params.name).toUpperCase())) return googleError(LABELS, 409, "Label name exists or conflicts");
5703
+ const label2 = { id: `Label_${labels.length + 1}`, name: params.name, type: "user", labelListVisibility: params.labelListVisibility ?? "labelShow", messageListVisibility: params.messageListVisibility ?? "show", ...params.color ? { color: params.color } : {} };
5704
+ (data[LABELS] ??= []).push(label2);
5705
+ return { status: 200, body: structuredClone(label2), collection: LABELS, operation: "write", record: label2 };
5706
+ }
5350
5707
  if (method !== "GET") return void 0;
5351
5708
  if (Object.keys(params).length) return void 0;
5352
5709
  return ok(LABELS, { labels: rowsIn(data, LABELS).map((row) => structuredClone(row)) });
@@ -5680,7 +6037,7 @@ function zendeskOperation(method, path2, params, _headers, data, sequence) {
5680
6037
  function restUnsupportedBody(adapter) {
5681
6038
  return UNSUPPORTED_BODIES[adapter];
5682
6039
  }
5683
- var EPOCH2, iso2, sha2, detUuid, rows, notFound, badRequest, ok, created, write2, isObject2, str, pagination, uniqueId, boundedInt, notionPropValue, notionPage, notionError, hubspotEnvelope, SHOPIFY_VERSION, shopifySlug, googleError, rowsIn, GMAIL_MESSAGES, GMAIL_THREADS, GMAIL_DRAFTS, GMAIL_SEND_AS, GMAIL_WATCH, PUBSUB_SUBSCRIPTIONS, PUBSUB_MESSAGES, gmailHeader, gmailDate, gmailThreadMessages, GMAIL_SYSTEM_LABELS, gmailLabelKnown, gmailHistoryId, withPush, JIRA_TRANSITIONS, discordError, ZENDESK_STATUSES, UNSUPPORTED_BODIES, REST_ADAPTERS, REST_ADAPTER_NAMES;
6040
+ var EPOCH2, iso2, sha2, detUuid, rows, notFound, badRequest, ok, created, write2, isObject2, str, pagination, uniqueId, boundedInt, notionPropValue, notionPage, notionError, hubspotEnvelope, SHOPIFY_VERSION, shopifySlug, googleError, rowsIn, GMAIL_MESSAGES, GMAIL_THREADS, GMAIL_DRAFTS, GMAIL_SEND_AS, GMAIL_WATCH, PUBSUB_SUBSCRIPTIONS, PUBSUB_MESSAGES, gmailHeader, gmailDate, gmailThreadMessages, GMAIL_SYSTEM_LABELS, gmailLabelKnown, gmailHistoryId, withPush, GMAIL_SYSTEM_LABEL_NAMES, JIRA_TRANSITIONS, discordError, ZENDESK_STATUSES, UNSUPPORTED_BODIES, REST_ADAPTERS, REST_ADAPTER_NAMES;
5684
6041
  var init_rest_adapters = __esm({
5685
6042
  "src/runtime/rest-adapters.ts"() {
5686
6043
  "use strict";
@@ -5692,7 +6049,7 @@ var init_rest_adapters = __esm({
5692
6049
  init_gmail_mime();
5693
6050
  EPOCH2 = 17e8;
5694
6051
  iso2 = (epoch = EPOCH2) => new Date(twinNowMs(epoch * 1e3)).toISOString();
5695
- sha2 = (value) => createHash8("sha256").update(value).digest("hex");
6052
+ sha2 = (value) => createHash9("sha256").update(value).digest("hex");
5696
6053
  detUuid = (seed) => {
5697
6054
  const hex = sha2(seed).slice(0, 32).split("");
5698
6055
  hex[12] = "4";
@@ -5755,6 +6112,7 @@ var init_rest_adapters = __esm({
5755
6112
  };
5756
6113
  gmailHistoryId = (messages) => messages.reduce((max, m) => BigInt(String(m.historyId ?? 0)) > BigInt(max) ? String(m.historyId) : max, "0");
5757
6114
  withPush = (result2, deliveries) => deliveries.length ? { ...result2, deliveries } : result2;
6115
+ GMAIL_SYSTEM_LABEL_NAMES = /* @__PURE__ */ new Set(["INBOX", "SPAM", "TRASH", "UNREAD", "STARRED", "IMPORTANT", "SENT", "DRAFT", "CHAT"]);
5758
6116
  JIRA_TRANSITIONS = { "11": "To Do", "21": "In Progress", "31": "Done" };
5759
6117
  discordError = (collection, code, message) => ({ status: code === 10003 || code === 10004 ? 404 : 400, body: { message, code }, collection });
5760
6118
  ZENDESK_STATUSES = ["new", "open", "pending", "solved", "closed"];
@@ -5802,8 +6160,168 @@ var init_rest_adapters = __esm({
5802
6160
  }
5803
6161
  });
5804
6162
 
6163
+ // src/runtime/postgrest.ts
6164
+ import pg2 from "pg";
6165
+ var ident2, OPS, RESERVED, PostgrestLayer;
6166
+ var init_postgrest = __esm({
6167
+ "src/runtime/postgrest.ts"() {
6168
+ "use strict";
6169
+ ident2 = (name) => `"${name.replace(/"/g, '""')}"`;
6170
+ OPS = { eq: "=", neq: "<>", gt: ">", gte: ">=", lt: "<", lte: "<=", like: "LIKE", ilike: "ILIKE" };
6171
+ RESERVED = /* @__PURE__ */ new Set(["select", "order", "limit", "offset", "on_conflict", "columns", "or", "and"]);
6172
+ PostgrestLayer = class _PostgrestLayer {
6173
+ pool;
6174
+ fks;
6175
+ constructor(databaseUrl) {
6176
+ this.pool = new pg2.Pool({ connectionString: databaseUrl, max: 1 });
6177
+ }
6178
+ close() {
6179
+ return this.pool.end().catch(() => {
6180
+ });
6181
+ }
6182
+ foreignKeys() {
6183
+ return this.fks ??= this.pool.query(`SELECT c.conrelid::regclass::text AS table, a.attname AS column, c.confrelid::regclass::text AS "refTable", r.attname AS "refColumn"
6184
+ FROM pg_constraint c JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attnum=c.conkey[1] JOIN pg_attribute r ON r.attrelid=c.confrelid AND r.attnum=c.confkey[1]
6185
+ WHERE c.contype='f' AND array_length(c.conkey,1)=1`).then((r) => r.rows.map((f) => ({ ...f, table: f.table.replace(/^public\./, "").replace(/"/g, ""), refTable: f.refTable.replace(/^public\./, "").replace(/"/g, "") })));
6186
+ }
6187
+ /** Splits a select list at top-level commas: `id, name, prices(*, product:products(name))`. */
6188
+ static items(select) {
6189
+ const out = [];
6190
+ let depth = 0, cur = "";
6191
+ for (const c of select) {
6192
+ if (c === "(") depth++;
6193
+ if (c === ")") depth--;
6194
+ if (c === "," && !depth) {
6195
+ out.push(cur.trim());
6196
+ cur = "";
6197
+ } else cur += c;
6198
+ }
6199
+ if (cur.trim()) out.push(cur.trim());
6200
+ return out;
6201
+ }
6202
+ async columns(table2, alias, select) {
6203
+ const parts = [];
6204
+ for (const item of _PostgrestLayer.items(select || "*")) {
6205
+ const embed = /^(?:(\w+):)?(\w+)(?:!\w+)?\((.*)\)$/s.exec(item);
6206
+ if (!embed) {
6207
+ if (item === "*") {
6208
+ parts.push(`${alias}.*`);
6209
+ continue;
6210
+ }
6211
+ const m = /^(?:(\w+):)?(\w+)(?:::\w+)?$/.exec(item);
6212
+ if (!m) continue;
6213
+ parts.push(`${alias}.${ident2(m[2])} AS ${ident2(m[1] ?? m[2])}`);
6214
+ continue;
6215
+ }
6216
+ const [, as, rel, inner] = embed, fks = await this.foreignKeys(), child = `e${parts.length}_${alias}`;
6217
+ const many = fks.find((f) => f.table === rel && f.refTable === table2), one = fks.find((f) => f.table === table2 && f.refTable === rel);
6218
+ const cols = await this.columns(rel, child, inner);
6219
+ if (one) parts.push(`(SELECT row_to_json(x) FROM (SELECT ${cols} FROM ${ident2(rel)} ${child} WHERE ${child}.${ident2(one.refColumn)} = ${alias}.${ident2(one.column)} LIMIT 1) x) AS ${ident2(as ?? rel)}`);
6220
+ else if (many) parts.push(`(SELECT coalesce(json_agg(x), '[]'::json) FROM (SELECT ${cols} FROM ${ident2(rel)} ${child} WHERE ${child}.${ident2(many.column)} = ${alias}.${ident2(many.refColumn)}) x) AS ${ident2(as ?? rel)}`);
6221
+ }
6222
+ return parts.join(", ") || `${alias}.*`;
6223
+ }
6224
+ /** WHERE clause from `col=op.value` query parameters. */
6225
+ static where(params, values) {
6226
+ const clauses = [];
6227
+ for (const [key2, raw] of params) {
6228
+ if (RESERVED.has(key2)) continue;
6229
+ const not = raw.startsWith("not."), text3 = not ? raw.slice(4) : raw, dot = text3.indexOf(".");
6230
+ const op2 = text3.slice(0, dot), value = text3.slice(dot + 1), col = ident2(key2);
6231
+ let clause;
6232
+ if (OPS[op2]) {
6233
+ values.push(op2.endsWith("like") ? value.replace(/\*/g, "%") : value);
6234
+ clause = `${col}::text ${OPS[op2]} $${values.length}`;
6235
+ if (op2 === "eq" || op2 === "neq") clause = `${col} ${OPS[op2]} $${values.length}`;
6236
+ } else if (op2 === "is") clause = `${col} IS ${value === "null" ? "NULL" : value === "true" ? "TRUE" : value === "false" ? "FALSE" : "UNKNOWN"}`;
6237
+ else if (op2 === "in") {
6238
+ values.push(value.replace(/^\(|\)$/g, "").split(",").map((v) => v.replace(/^"|"$/g, "")));
6239
+ clause = `${col}::text = ANY($${values.length}::text[])`;
6240
+ }
6241
+ if (clause) clauses.push(not ? `NOT (${clause})` : clause);
6242
+ }
6243
+ return clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
6244
+ }
6245
+ async handle(request) {
6246
+ const header3 = (name) => {
6247
+ const v = request.headers[name];
6248
+ return Array.isArray(v) ? v.join(",") : v ?? "";
6249
+ };
6250
+ const prefer = header3("prefer"), single = /vnd\.pgrst\.object/.test(header3("accept"));
6251
+ const reply = (status, body2, extra = {}) => ({ status, headers: { "content-type": "application/json; charset=utf-8", ...extra }, body: body2 === void 0 ? "" : JSON.stringify(body2) });
6252
+ const segments = request.url.pathname.replace(/^\/rest\/v1\/?/, "").split("/").filter(Boolean).map(decodeURIComponent);
6253
+ if (!segments.length) return reply(404, { code: "PGRST125", message: "Invalid path specified in request URL" });
6254
+ const params = request.url.searchParams, values = [];
6255
+ let payload;
6256
+ try {
6257
+ payload = request.body?.length ? JSON.parse(request.body.toString("utf8")) : void 0;
6258
+ } catch {
6259
+ return reply(400, { code: "PGRST102", message: "Empty or invalid json" });
6260
+ }
6261
+ try {
6262
+ if (segments[0] === "rpc" && segments[1]) {
6263
+ const args = payload && typeof payload === "object" && !Array.isArray(payload) ? Object.entries(payload) : [...params].map(([k, v]) => [k, v]);
6264
+ const list3 = args.map(([k, v], i) => {
6265
+ values.push(v !== null && typeof v === "object" ? JSON.stringify(v) : v);
6266
+ return `${ident2(k)} => $${i + 1}`;
6267
+ });
6268
+ const r = await this.pool.query(`SELECT to_json(f) AS v FROM ${ident2(segments[1])}(${list3.join(", ")}) f`, values);
6269
+ const rows3 = r.rows.map((x) => x.v);
6270
+ return reply(200, rows3.length === 1 && (typeof rows3[0] !== "object" || rows3[0] === null || !Array.isArray(rows3[0])) && r.fields.length === 1 && r.rowCount === 1 && single ? rows3[0] : rows3.length === 1 && typeof rows3[0] !== "object" ? rows3[0] : rows3);
6271
+ }
6272
+ const table2 = segments[0], t = ident2(table2);
6273
+ const returning = async (sql2) => {
6274
+ const cols = await this.columns(table2, "r", params.get("select") ?? "*");
6275
+ return `WITH r AS (${sql2} RETURNING *) SELECT coalesce(json_agg(x), '[]'::json) AS rows FROM (SELECT ${cols} FROM r) x`;
6276
+ };
6277
+ let sql, status = 200;
6278
+ const method = request.method.toUpperCase();
6279
+ if (method === "GET" || method === "HEAD") {
6280
+ const order = (params.get("order") ?? "").split(",").filter(Boolean).map((o) => {
6281
+ const [c, dir, nulls] = o.split(".");
6282
+ return `${ident2(c)} ${dir === "desc" ? "DESC" : "ASC"}${nulls === "nullsfirst" ? " NULLS FIRST" : nulls === "nullslast" ? " NULLS LAST" : ""}`;
6283
+ });
6284
+ const limit2 = Number(params.get("limit")), offset = Number(params.get("offset"));
6285
+ const cols = await this.columns(table2, "t", params.get("select") ?? "*");
6286
+ sql = `SELECT coalesce(json_agg(x), '[]'::json) AS rows FROM (SELECT ${cols} FROM ${t} t${_PostgrestLayer.where(params, values)}${order.length ? ` ORDER BY ${order.join(", ")}` : ""}${limit2 >= 0 && params.has("limit") ? ` LIMIT ${Math.trunc(limit2)}` : ""}${offset > 0 ? ` OFFSET ${Math.trunc(offset)}` : ""}) x`;
6287
+ } else if (method === "POST") {
6288
+ const rows3 = Array.isArray(payload) ? payload : [payload ?? {}];
6289
+ const keys = [...new Set(rows3.flatMap((r) => Object.keys(r)))];
6290
+ values.push(JSON.stringify(rows3));
6291
+ const target = params.get("on_conflict")?.split(",").map(ident2).join(", ");
6292
+ const pk = target ?? (await this.pool.query(`SELECT string_agg(quote_ident(a.attname), ', ') AS k FROM pg_index i JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum = ANY(i.indkey) WHERE i.indrelid=$1::regclass AND i.indisprimary`, [table2])).rows[0]?.k;
6293
+ const merge = /resolution=merge-duplicates/.test(prefer), ignore = /resolution=ignore-duplicates/.test(prefer);
6294
+ const conflict = (merge || ignore) && pk ? ` ON CONFLICT (${pk}) DO ${ignore || !keys.length ? "NOTHING" : `UPDATE SET ${keys.map((k) => `${ident2(k)} = EXCLUDED.${ident2(k)}`).join(", ")}`}` : "";
6295
+ const insert = keys.length ? `INSERT INTO ${t} (${keys.map(ident2).join(", ")}) SELECT ${keys.map(ident2).join(", ")} FROM json_populate_recordset(null::${t}, $1::json)${conflict}` : `INSERT INTO ${t} DEFAULT VALUES`;
6296
+ if (!keys.length) values.length = 0;
6297
+ sql = await returning(insert);
6298
+ status = 201;
6299
+ } else if (method === "PATCH") {
6300
+ const keys = Object.keys(payload ?? {});
6301
+ values.push(JSON.stringify(payload ?? {}));
6302
+ const set = keys.map((k) => `${ident2(k)} = (json_populate_record(null::${t}, $1::json)).${ident2(k)}`).join(", ");
6303
+ sql = await returning(`UPDATE ${t} SET ${set || "ctid = ctid"}${_PostgrestLayer.where(params, values)}`);
6304
+ } else if (method === "DELETE") {
6305
+ sql = await returning(`DELETE FROM ${t}${_PostgrestLayer.where(params, values)}`);
6306
+ } else return reply(405, { code: "PGRST117", message: `Unsupported HTTP method: ${method}` });
6307
+ const rows2 = (await this.pool.query(sql, values)).rows[0]?.rows ?? [];
6308
+ const range = { "content-range": `0-${Math.max(rows2.length - 1, 0)}/${/count=exact/.test(prefer) ? rows2.length : "*"}` };
6309
+ if (method !== "GET" && /return=minimal/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
6310
+ if (method !== "GET" && !/return=representation/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
6311
+ if (single) return rows2.length === 1 ? reply(status, rows2[0], range) : reply(406, { code: "PGRST116", message: "JSON object requested, multiple (or no) rows returned", details: `The result contains ${rows2.length} rows`, hint: null });
6312
+ return reply(status, rows2, range);
6313
+ } catch (error) {
6314
+ const e = error;
6315
+ const status = e.code === "23505" ? 409 : e.code === "42P01" ? 404 : e.code === "42501" ? 403 : 400;
6316
+ return reply(status, { code: e.code === "42P01" ? "PGRST205" : e.code ?? "PGRST000", message: e.message ?? String(error), details: e.detail ?? null, hint: e.hint ?? null });
6317
+ }
6318
+ }
6319
+ };
6320
+ }
6321
+ });
6322
+
5805
6323
  // src/runtime/pack-log.ts
5806
- import { closeSync, existsSync as existsSync2, openSync, readdirSync, readSync, statSync } from "fs";
6324
+ import { closeSync, existsSync as existsSync2, openSync, readdirSync as readdirSync2, readSync, statSync } from "fs";
5807
6325
  import { join as join10 } from "path";
5808
6326
  function packCollection(type, requestPath) {
5809
6327
  const segments = requestPath.split("/").filter(Boolean);
@@ -5844,7 +6362,7 @@ var init_pack_log = __esm({
5844
6362
  partial = /* @__PURE__ */ new Map();
5845
6363
  files() {
5846
6364
  if (!existsSync2(this.root)) return [];
5847
- return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join10(this.root, f)).sort();
6365
+ return readdirSync2(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join10(this.root, f)).sort();
5848
6366
  }
5849
6367
  drain() {
5850
6368
  const out = [];
@@ -5875,15 +6393,37 @@ var init_pack_log = __esm({
5875
6393
  }
5876
6394
  });
5877
6395
 
6396
+ // src/runtime/pack-aliases.ts
6397
+ function aliasRequest(pack, host, url) {
6398
+ const at = url.indexOf("?"), path2 = at < 0 ? url : url.slice(0, at), query = at < 0 ? "" : url.slice(at);
6399
+ const vendor = compatibleVendor(pack), compatible = vendor && compatibleRequest(vendor, host, url);
6400
+ if (compatible) return compatible;
6401
+ const alias = PACK_ALIASES[pack]?.find((a) => a.host === host.toLowerCase() && a.path === path2);
6402
+ return alias ? { host: alias.to.host, url: alias.to.path + query } : { host, url };
6403
+ }
6404
+ var PACK_ALIASES;
6405
+ var init_pack_aliases = __esm({
6406
+ "src/runtime/pack-aliases.ts"() {
6407
+ "use strict";
6408
+ init_compatible_packs();
6409
+ PACK_ALIASES = {
6410
+ // Google's OpenID Connect discovery names openidconnect.googleapis.com/v1/userinfo; the pack models the
6411
+ // equivalent www.googleapis.com/oauth2/v3/userinfo (https://developers.google.com/identity/openid-connect/openid-connect).
6412
+ googleoauth: [{ host: "openidconnect.googleapis.com", path: "/v1/userinfo", to: { host: "www.googleapis.com", path: "/oauth2/v3/userinfo" } }]
6413
+ };
6414
+ }
6415
+ });
6416
+
5878
6417
  // src/runtime/http-world.ts
5879
6418
  import { createServer as createServer3 } from "http";
6419
+ import { createServer as createNetServer } from "net";
5880
6420
  import { isDeepStrictEqual as isDeepStrictEqual5 } from "util";
5881
- import { createHash as createHash9 } from "crypto";
6421
+ import { createHash as createHash10 } from "crypto";
5882
6422
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
5883
- import { mkdir as mkdir3, mkdtemp as mkdtemp5, rm as rm5, writeFile as writeFile5 } from "fs/promises";
6423
+ import { mkdir as mkdir3, mkdtemp as mkdtemp5, rm as rm5, writeFile as writeFile6 } from "fs/promises";
5884
6424
  import { tmpdir as tmpdir5 } from "os";
5885
6425
  import { join as join11 } from "path";
5886
- var idempotencyKeyDigest, HttpWorld;
6426
+ var slackDirectMessageId, idempotencyKeyDigest, HttpWorld;
5887
6427
  var init_http_world = __esm({
5888
6428
  "src/runtime/http-world.ts"() {
5889
6429
  "use strict";
@@ -5895,9 +6435,13 @@ var init_http_world = __esm({
5895
6435
  init_spec();
5896
6436
  init_enterprise_twins();
5897
6437
  init_adapters();
6438
+ init_postgrest();
5898
6439
  init_packs();
5899
6440
  init_pack_log();
5900
- idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash9("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
6441
+ init_pack_aliases();
6442
+ init_compatible_packs();
6443
+ slackDirectMessageId = (user) => `D${createHash10("sha256").update(user).digest("hex").slice(0, 16).toUpperCase()}`;
6444
+ idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash10("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
5901
6445
  HttpWorld = class {
5902
6446
  /** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
5903
6447
  constructor(spec, seed, options = {}) {
@@ -5923,6 +6467,12 @@ var init_http_world = __esm({
5923
6467
  epoch = 0;
5924
6468
  replayKeys = /* @__PURE__ */ new Map();
5925
6469
  sourceContext = new AsyncLocalStorage2();
6470
+ postgrest;
6471
+ /** The run's PostgreSQL: a pack's PostgREST paths (/rest/v1/<table>) are served from it, so the app's own tables answer. */
6472
+ attachDatabase(url) {
6473
+ void this.postgrest?.close();
6474
+ this.postgrest = new PostgrestLayer(url);
6475
+ }
5926
6476
  record(service, operation, path2, detail, record4) {
5927
6477
  if (this.events.length >= 5e4) return;
5928
6478
  const source = this.sourceContext.getStore();
@@ -5933,6 +6483,33 @@ var init_http_world = __esm({
5933
6483
  * each, after the triggering response. Only loopback http endpoints are allowed, so a push can never leave the
5934
6484
  * machine; the outcome is written to the push row and recorded as a `push` event.
5935
6485
  */
6486
+ sentWebhooks = /* @__PURE__ */ new Set();
6487
+ /** Sends a webhook a pack signed and queued, with the pack's own signature headers. Loopback http only. */
6488
+ sendWebhook(service, url, body2, headers, eventType) {
6489
+ const epoch = this.epoch;
6490
+ const timer = setTimeout(async () => {
6491
+ this.timers.delete(timer);
6492
+ if (epoch !== this.epoch) return;
6493
+ let target;
6494
+ try {
6495
+ target = new URL(url);
6496
+ } catch {
6497
+ target = void 0;
6498
+ }
6499
+ if (!target || target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || target.username || target.password) {
6500
+ this.record(service, "webhook", url, `webhook ${eventType} not sent: the endpoint is not a loopback http URL (nothing leaves this machine)`);
6501
+ return;
6502
+ }
6503
+ try {
6504
+ const response = await fetch(target, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: body2, redirect: "error", signal: AbortSignal.timeout(6e4) });
6505
+ await response.arrayBuffer().catch(() => void 0);
6506
+ if (epoch === this.epoch) this.record(service, "webhook", url, `delivered ${eventType} to ${url}: HTTP ${response.status}`, { event: eventType, status: response.status });
6507
+ } catch (error) {
6508
+ if (epoch === this.epoch) this.record(service, "webhook", url, `webhook ${eventType} to ${url} failed: ${error instanceof Error ? error.message : String(error)}`);
6509
+ }
6510
+ }, 25);
6511
+ this.timers.add(timer);
6512
+ }
5936
6513
  push(service, deliveries, epoch) {
5937
6514
  for (const delivery of deliveries) {
5938
6515
  const timer = setTimeout(async () => {
@@ -5964,12 +6541,23 @@ var init_http_world = __esm({
5964
6541
  this.timers.add(timer);
5965
6542
  }
5966
6543
  }
6544
+ /** Tags every event recorded since index `from` with the request's idempotency key digest. */
6545
+ keyedSince(from, key2) {
6546
+ const digest6 = idempotencyKeyDigest(key2);
6547
+ if (digest6) for (let i = from; i < this.events.length; i++) this.events[i].idempotencyKey = digest6;
6548
+ }
5967
6549
  /** Tags the event just recorded with the request's idempotency key digest. */
5968
6550
  keyed(key2) {
5969
6551
  const digest6 = idempotencyKeyDigest(key2), last = this.events[this.events.length - 1];
5970
6552
  if (digest6 && last) last.idempotencyKey = digest6;
5971
6553
  }
6554
+ /** Requests the run itself sends to set a twin up (x-agenttwin-probe: 1): a refusal there is not the application's gap. */
6555
+ probes = 0;
5972
6556
  rejectUnsupported(service, method, path2, detail) {
6557
+ if (this.probes > 0) {
6558
+ this.record(service, "assumption", path2, `setup probe: ${detail}`);
6559
+ return;
6560
+ }
5973
6561
  this.unsupported.push(`${service}: ${method} ${path2}: ${detail}`);
5974
6562
  this.record(service, "unsupported", path2, detail);
5975
6563
  }
@@ -6016,340 +6604,382 @@ var init_http_world = __esm({
6016
6604
  this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server2.address().port}`, token };
6017
6605
  continue;
6018
6606
  }
6019
- const server = createServer3((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
6020
- const epoch = this.epoch;
6021
- const send2 = (code, body2, headers = {}) => {
6022
- if (!res.destroyed) {
6023
- res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {}, ...headers });
6024
- res.end(code === 204 || code === 202 && body2 === null ? void 0 : typeof body2 === "string" && headers["content-type"] ? body2 : JSON.stringify(body2));
6025
- }
6026
- };
6027
- const respond = (code, body2, headers) => {
6028
- const ms = latencyMs();
6029
- if (ms <= 0) {
6030
- send2(code, body2, headers);
6031
- return;
6032
- }
6033
- const timer = setTimeout(() => {
6034
- this.timers.delete(timer);
6035
- if (epoch === this.epoch) send2(code, body2, headers);
6036
- }, ms);
6037
- this.timers.add(timer);
6038
- };
6039
- const normalPath = (url, method) => {
6040
- const parsed = new URL(url, "http://localhost");
6041
- if (generated) return generated.collectionOf(method ?? "", parsed.pathname) ?? parsed.pathname;
6042
- if (service.adapter === "google-oauth" && parsed.pathname === "/token" && method === "POST") return "/tokens";
6043
- if (service.adapter === "composio") {
6044
- if (/^\/api\/v3(?:\.1)?\/tools\/execute\//.test(parsed.pathname)) return "/messages";
6045
- if (/^\/api\/v3(?:\.1)?\/connected_accounts(?:\/|$)/.test(parsed.pathname)) return "/connected_accounts";
6046
- }
6047
- if (service.adapter === "slack") {
6048
- const m = parsed.pathname.replace(/^\/api\//, "");
6049
- if (m === "chat.postMessage" && method === "POST") return "/messages";
6050
- if (m === "conversations.history" && ["GET", "POST"].includes(method ?? "")) return "/messages";
6051
- if (m === "conversations.list" && ["GET", "POST"].includes(method ?? "")) return "/channels";
6607
+ const server = createServer3((req, res) => {
6608
+ if (req.headers["x-agenttwin-probe"] === "1") {
6609
+ this.probes++;
6610
+ res.once("close", () => {
6611
+ this.probes--;
6612
+ });
6613
+ }
6614
+ return withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
6615
+ const epoch = this.epoch;
6616
+ const send2 = (code, body2, headers = {}) => {
6617
+ if (!res.destroyed) {
6618
+ res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {}, ...headers });
6619
+ res.end(code === 204 || code === 202 && body2 === null ? void 0 : typeof body2 === "string" && headers["content-type"] ? body2 : JSON.stringify(body2));
6620
+ }
6621
+ };
6622
+ const respond = (code, body2, headers) => {
6623
+ const ms = latencyMs();
6624
+ if (ms <= 0) {
6625
+ send2(code, body2, headers);
6626
+ return;
6627
+ }
6628
+ const timer = setTimeout(() => {
6629
+ this.timers.delete(timer);
6630
+ if (epoch === this.epoch) send2(code, body2, headers);
6631
+ }, ms);
6632
+ this.timers.add(timer);
6633
+ };
6634
+ const normalPath = (url, method) => {
6635
+ const parsed = new URL(url, "http://localhost");
6636
+ if (generated) return generated.collectionOf(method ?? "", parsed.pathname) ?? parsed.pathname;
6637
+ if (service.adapter === "google-oauth" && parsed.pathname === "/token" && method === "POST") return "/tokens";
6638
+ if (service.adapter === "composio") {
6639
+ if (/^\/api\/v3(?:\.1)?\/tools\/execute\//.test(parsed.pathname)) return "/messages";
6640
+ if (/^\/api\/v3(?:\.1)?\/connected_accounts(?:\/|$)/.test(parsed.pathname)) return "/connected_accounts";
6641
+ }
6642
+ if (service.adapter === "slack") {
6643
+ const m = parsed.pathname.replace(/^\/api\//, "");
6644
+ if (m === "chat.postMessage" && method === "POST") return "/messages";
6645
+ if (m === "conversations.history" && ["GET", "POST"].includes(method ?? "")) return "/messages";
6646
+ if (m === "conversations.list" && ["GET", "POST"].includes(method ?? "")) return "/channels";
6647
+ return parsed.pathname;
6648
+ }
6052
6649
  return parsed.pathname;
6053
- }
6054
- return parsed.pathname;
6055
- };
6056
- const matchesFault = (target) => adapterService ? target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path) : target === fault.path;
6057
- const requestKey = req.headers["idempotency-key"];
6058
- const respondSlowly = (target, operation, code, body2, headers) => {
6059
- if (fault?.type !== "slow-response" || !faultOrdinalsFor || !matchesFault(target) || !faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
6060
- respond(code, body2, headers);
6061
- return;
6062
- }
6063
- this.faultActions++;
6064
- this.record(service.name, "fault", target, `slow-response: ${operation} applied; response delayed ${fault.delayMs}ms`);
6065
- this.keyed(requestKey);
6066
- const timer = setTimeout(() => {
6067
- this.timers.delete(timer);
6068
- if (epoch === this.epoch) respond(code, body2, headers);
6069
- }, fault.delayMs);
6070
- this.timers.add(timer);
6071
- };
6072
- const darkFault = () => {
6073
- if (!fault || !faultOrdinalsFor || fault.type !== "blackhole" && fault.type !== "server-error") return "none";
6074
- const target = normalPath(req.url ?? "/", req.method);
6075
- if (!matchesFault(target)) return "none";
6076
- const ordinal = this.candidateIndex(faultKey);
6077
- if (!faultOrdinalsFor.includes(ordinal)) return "none";
6078
- this.faultActions++;
6079
- return fault.type;
6080
- };
6081
- try {
6082
- const anyCredential = !!this.options.lenientModelAuth && (service.adapter === "openai" || service.adapter === "anthropic");
6083
- if (!anyCredential && req.headers.authorization !== `Bearer ${token}` && !altAuth(req.headers) && !(enterprise && enterpriseAuth(enterprise, req.headers, req.url ?? "/", token)) && !(generated && generated.auth(req.headers, req.url ?? "/", token))) {
6084
- this.record(service.name, "auth-denied", req.url ?? "", `invalid test credential (credential headers received: ${Object.keys(req.headers).filter((k) => /auth|key|token|secret/i.test(k)).join(", ") || "none"}; all header names: ${Object.keys(req.headers).join(", ")})`);
6085
- respond(401, { error: "invalid_test_credential" });
6086
- return;
6087
- }
6088
- if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
6089
- respond(429, { error: "world_capacity" });
6090
- return;
6091
- }
6092
- const darkness = darkFault();
6093
- if (darkness === "blackhole") {
6094
- this.record(service.name, "fault", fault.path, `blackhole: request dropped (matched ordinal ${this.candidateCounts.get(faultKey) - 1} of the seeded schedule); nothing committed (${req.method ?? "request"})`);
6095
- this.keyed(requestKey);
6096
- return;
6097
- }
6098
- if (darkness === "server-error") {
6099
- const windowMs = fault.windowMs ?? 0;
6100
- const delay2 = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
6101
- this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay2}ms; nothing committed (${req.method ?? "request"})`);
6102
- this.keyed(requestKey);
6103
- const respond500 = () => respond(500, { error: { type: "api_error", message: "server_error fault" } });
6104
- if (delay2 <= 0) {
6105
- respond500();
6650
+ };
6651
+ const matchesFault = (target) => adapterService ? target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path) : target === fault.path;
6652
+ const requestKey = req.headers["idempotency-key"];
6653
+ const respondSlowly = (target, operation, code, body2, headers) => {
6654
+ if (fault?.type !== "slow-response" || !faultOrdinalsFor || !matchesFault(target) || !faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
6655
+ respond(code, body2, headers);
6106
6656
  return;
6107
6657
  }
6658
+ this.faultActions++;
6659
+ this.record(service.name, "fault", target, `slow-response: ${operation} applied; response delayed ${fault.delayMs}ms`);
6660
+ this.keyed(requestKey);
6108
6661
  const timer = setTimeout(() => {
6109
6662
  this.timers.delete(timer);
6110
- if (epoch === this.epoch) respond500();
6111
- }, delay2);
6663
+ if (epoch === this.epoch) respond(code, body2, headers);
6664
+ }, fault.delayMs);
6112
6665
  this.timers.add(timer);
6113
- return;
6114
- }
6115
- const url = new URL(req.url ?? "/", "http://localhost");
6116
- let path2 = url.pathname;
6117
- if (service.adapter === "composio" && [...url.searchParams.keys()].some((key3) => url.searchParams.getAll(key3).length !== 1)) {
6118
- this.rejectUnsupported(service.name, req.method ?? "", path2, "Repeated query parameters are unsupported");
6119
- respond(501, restUnsupportedBody("composio"));
6120
- return;
6121
- }
6122
- if (service.adapter === "google-oauth" && url.search) {
6123
- this.rejectUnsupported(service.name, req.method ?? "", path2, "OAuth token query parameters are unsupported");
6124
- respond(501, restUnsupportedBody("google-oauth"));
6125
- return;
6126
- }
6127
- const slack = service.adapter === "slack";
6128
- const slackMethod = path2.replace(/^\/api\//, "");
6129
- let payload, rawBody;
6130
- if (["POST", "PUT", "PATCH"].includes(req.method ?? "")) {
6131
- const chunks = [];
6132
- let bytes = 0;
6133
- for await (const chunk of req) {
6134
- bytes += chunk.length;
6135
- if (bytes > 1024 * 1024) {
6136
- respond(413, { error: "body_too_large" });
6666
+ };
6667
+ const darkFault = () => {
6668
+ if (!fault || !faultOrdinalsFor || fault.type !== "blackhole" && fault.type !== "server-error") return "none";
6669
+ const target = normalPath(req.url ?? "/", req.method);
6670
+ if (!matchesFault(target)) return "none";
6671
+ const ordinal = this.candidateIndex(faultKey);
6672
+ if (!faultOrdinalsFor.includes(ordinal)) return "none";
6673
+ this.faultActions++;
6674
+ return fault.type;
6675
+ };
6676
+ try {
6677
+ const anyCredential = !!this.options.lenientModelAuth && (service.adapter === "openai" || service.adapter === "anthropic");
6678
+ if (!anyCredential && req.headers.authorization !== `Bearer ${token}` && !altAuth(req.headers) && !(enterprise && enterpriseAuth(enterprise, req.headers, req.url ?? "/", token)) && !(generated && generated.auth(req.headers, req.url ?? "/", token))) {
6679
+ this.record(service.name, "auth-denied", req.url ?? "", `invalid test credential (credential headers received: ${Object.keys(req.headers).filter((k) => /auth|key|token|secret/i.test(k)).join(", ") || "none"}; all header names: ${Object.keys(req.headers).join(", ")})`);
6680
+ respond(401, { error: "invalid_test_credential" });
6681
+ return;
6682
+ }
6683
+ if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
6684
+ respond(429, { error: "world_capacity" });
6685
+ return;
6686
+ }
6687
+ const darkness = darkFault();
6688
+ if (darkness === "blackhole") {
6689
+ this.record(service.name, "fault", fault.path, `blackhole: request dropped (matched ordinal ${this.candidateCounts.get(faultKey) - 1} of the seeded schedule); nothing committed (${req.method ?? "request"})`);
6690
+ this.keyed(requestKey);
6691
+ return;
6692
+ }
6693
+ if (darkness === "server-error") {
6694
+ const windowMs = fault.windowMs ?? 0;
6695
+ const delay2 = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
6696
+ this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay2}ms; nothing committed (${req.method ?? "request"})`);
6697
+ this.keyed(requestKey);
6698
+ const respond500 = () => respond(500, { error: { type: "api_error", message: "server_error fault" } });
6699
+ if (delay2 <= 0) {
6700
+ respond500();
6137
6701
  return;
6138
6702
  }
6139
- chunks.push(Buffer.from(chunk));
6703
+ const timer = setTimeout(() => {
6704
+ this.timers.delete(timer);
6705
+ if (epoch === this.epoch) respond500();
6706
+ }, delay2);
6707
+ this.timers.add(timer);
6708
+ return;
6709
+ }
6710
+ const url = new URL(req.url ?? "/", "http://localhost");
6711
+ let path2 = url.pathname;
6712
+ if (service.adapter === "composio" && [...url.searchParams.keys()].some((key3) => url.searchParams.getAll(key3).length !== 1)) {
6713
+ this.rejectUnsupported(service.name, req.method ?? "", path2, "Repeated query parameters are unsupported");
6714
+ respond(501, restUnsupportedBody("composio"));
6715
+ return;
6140
6716
  }
6141
- const text3 = Buffer.concat(chunks).toString("utf8");
6142
- let parsed;
6143
- const mode = generated?.bodyMode(req.headers["content-type"]);
6144
- if ((enterprise || generated) && !text3.trim()) parsed = {};
6145
- else if (mode === "form") {
6146
- const form = new URLSearchParams(text3);
6147
- parsed = {};
6148
- for (const key3 of new Set(form.keys())) {
6149
- const all = form.getAll(key3);
6150
- parsed[key3] = all.length > 1 ? all : all[0];
6717
+ if (service.adapter === "google-oauth" && url.search) {
6718
+ this.rejectUnsupported(service.name, req.method ?? "", path2, "OAuth token query parameters are unsupported");
6719
+ respond(501, restUnsupportedBody("google-oauth"));
6720
+ return;
6721
+ }
6722
+ const slack = service.adapter === "slack";
6723
+ const slackMethod = path2.replace(/^\/api\//, "");
6724
+ let payload, rawBody;
6725
+ if (["POST", "PUT", "PATCH"].includes(req.method ?? "")) {
6726
+ const chunks = [];
6727
+ let bytes = 0;
6728
+ for await (const chunk of req) {
6729
+ bytes += chunk.length;
6730
+ if (bytes > 1024 * 1024) {
6731
+ respond(413, { error: "body_too_large" });
6732
+ return;
6733
+ }
6734
+ chunks.push(Buffer.from(chunk));
6151
6735
  }
6152
- } else if (mode === "raw") {
6153
- rawBody = text3;
6154
- parsed = {};
6155
- } else if (service.adapter === "gmail" && /^multipart\/mixed\b/i.test(String(req.headers["content-type"] ?? ""))) {
6156
- rawBody = text3;
6157
- parsed = {};
6158
- } else if (service.adapter === "gmail" && /^multipart\/related\b/i.test(String(req.headers["content-type"] ?? ""))) {
6159
- rawBody = text3;
6160
- parsed = Object.fromEntries(url.searchParams);
6161
- } else if (service.adapter === "upstash-redis") {
6162
- rawBody = text3;
6163
- parsed = {};
6164
- } else if (service.adapter === "gmail" && !text3.trim()) parsed = {};
6165
- else if (service.adapter === "google-oauth") {
6166
- if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
6167
- respond(400, { error: "invalid_request" });
6736
+ const text3 = Buffer.concat(chunks).toString("utf8");
6737
+ let parsed;
6738
+ const mode = generated?.bodyMode(req.headers["content-type"]);
6739
+ if ((enterprise || generated) && !text3.trim()) parsed = {};
6740
+ else if (mode === "form") {
6741
+ const form = new URLSearchParams(text3);
6742
+ parsed = {};
6743
+ for (const key3 of new Set(form.keys())) {
6744
+ const all = form.getAll(key3);
6745
+ parsed[key3] = all.length > 1 ? all : all[0];
6746
+ }
6747
+ } else if (mode === "raw") {
6748
+ rawBody = text3;
6749
+ parsed = {};
6750
+ } else if (service.adapter === "gmail" && /^multipart\/mixed\b/i.test(String(req.headers["content-type"] ?? ""))) {
6751
+ rawBody = text3;
6752
+ parsed = {};
6753
+ } else if (service.adapter === "gmail" && /^multipart\/related\b/i.test(String(req.headers["content-type"] ?? ""))) {
6754
+ rawBody = text3;
6755
+ parsed = Object.fromEntries(url.searchParams);
6756
+ } else if (service.adapter === "upstash-redis") {
6757
+ rawBody = text3;
6758
+ parsed = {};
6759
+ } else if (service.adapter === "gmail" && !text3.trim()) parsed = {};
6760
+ else if (service.adapter === "google-oauth") {
6761
+ if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
6762
+ respond(400, { error: "invalid_request" });
6763
+ return;
6764
+ }
6765
+ const form = new URLSearchParams(text3);
6766
+ if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
6767
+ respond(400, { error: "invalid_request" });
6768
+ return;
6769
+ }
6770
+ parsed = Object.fromEntries(form);
6771
+ } else try {
6772
+ parsed = (slack || service.adapter === "stripe" || service.adapter === "twilio") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(text3)) : JSON.parse(text3);
6773
+ } catch {
6774
+ respond(400, { error: "expected_json_object" });
6168
6775
  return;
6169
6776
  }
6170
- const form = new URLSearchParams(text3);
6171
- if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
6172
- respond(400, { error: "invalid_request" });
6777
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6778
+ respond(400, { error: "expected_json_object" });
6173
6779
  return;
6174
6780
  }
6175
- parsed = Object.fromEntries(form);
6176
- } else try {
6177
- parsed = (slack || service.adapter === "stripe" || service.adapter === "twilio") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(text3)) : JSON.parse(text3);
6178
- } catch {
6179
- respond(400, { error: "expected_json_object" });
6180
- return;
6781
+ payload = parsed;
6181
6782
  }
6182
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6183
- respond(400, { error: "expected_json_object" });
6783
+ if (epoch !== this.epoch) {
6784
+ respond(409, { error: "world_reset" });
6184
6785
  return;
6185
6786
  }
6186
- payload = parsed;
6187
- }
6188
- if (epoch !== this.epoch) {
6189
- respond(409, { error: "world_reset" });
6190
- return;
6191
- }
6192
- if (generated && !payload && ["PUT", "DELETE"].includes(req.method ?? "")) payload = {};
6193
- if (service.adapter === "stripe" || restAdapter || enterprise || generated) {
6194
- const params = payload ?? Object.fromEntries(url.searchParams);
6195
- const keyHeader2 = req.headers["idempotency-key"] ?? (enterprise === "netsuite" ? req.headers["x-netsuite-idempotency-key"] : void 0);
6196
- const key3 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path2}:${keyHeader2}` : void 0;
6197
- const signature2 = JSON.stringify(params);
6198
- const previous2 = key3 ? keys.get(key3) : void 0;
6199
- if (previous2) {
6200
- if (previous2.body !== signature2) {
6201
- respond(400, { error: { type: "idempotency_error", message: "Keys for idempotent requests can only be used with the same parameters" } });
6787
+ if (generated && !payload && ["PUT", "DELETE"].includes(req.method ?? "")) payload = {};
6788
+ if (service.adapter === "stripe" || restAdapter || enterprise || generated) {
6789
+ const params = payload ?? Object.fromEntries(url.searchParams);
6790
+ const keyHeader2 = req.headers["idempotency-key"] ?? (enterprise === "netsuite" ? req.headers["x-netsuite-idempotency-key"] : void 0);
6791
+ const key3 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path2}:${keyHeader2}` : void 0;
6792
+ const signature2 = JSON.stringify(params);
6793
+ const previous2 = key3 ? keys.get(key3) : void 0;
6794
+ if (previous2) {
6795
+ if (previous2.body !== signature2) {
6796
+ respond(400, { error: { type: "idempotency_error", message: "Keys for idempotent requests can only be used with the same parameters" } });
6797
+ return;
6798
+ }
6799
+ this.record(service.name, "replay", path2, "same-key response replay", previous2.record);
6800
+ this.keyed(keyHeader2);
6801
+ respondSlowly(path2, "replay", previous2.status ?? 200, previous2.record, previous2.headers);
6202
6802
  return;
6203
6803
  }
6204
- this.record(service.name, "replay", path2, "same-key response replay", previous2.record);
6205
- this.keyed(keyHeader2);
6206
- respondSlowly(path2, "replay", previous2.status ?? 200, previous2.record, previous2.headers);
6207
- return;
6208
- }
6209
- const query = Object.fromEntries(url.searchParams);
6210
- const invoke = (sequence) => generated ? generated.handle({ method: req.method ?? "", path: path2, query, headers: req.headers, ...payload ? { body: structuredClone(payload) } : {}, ...rawBody !== void 0 ? { raw: rawBody } : {} }, data, sequence, this.seed) : enterprise ? ENTERPRISE_OPERATIONS[enterprise](req.method ?? "", path2, structuredClone(payload ?? {}), query, req.headers, data, sequence) : restAdapter ? restAdapter(req.method ?? "", path2, params, req.headers, data, sequence, rawBody) : stripeOperation(req.method ?? "", path2, params, data, sequence);
6211
- const headers = (r) => "headers" in r ? r.headers : void 0;
6212
- const result2 = invoke(this.events.length + 1);
6213
- if (!result2) {
6214
- this.rejectUnsupported(service.name, req.method ?? "", path2, `unsupported ${service.adapter} operation or parameters`);
6215
- respond(501, generated ? generated.unsupported(req.method ?? "", path2) : enterprise ? ENTERPRISE_UNSUPPORTED[enterprise] : restAdapter ? restUnsupportedBody(service.adapter) : { error: { type: "invalid_request_error", code: "unsupported_operation", message: "Outside the verified AgentTwin Stripe subset" }, forwardedToProduction: false });
6804
+ const query = Object.fromEntries(url.searchParams);
6805
+ const invoke = (sequence) => generated ? generated.handle({ method: req.method ?? "", path: path2, query, headers: req.headers, ...payload ? { body: structuredClone(payload) } : {}, ...rawBody !== void 0 ? { raw: rawBody } : {} }, data, sequence, this.seed) : enterprise ? ENTERPRISE_OPERATIONS[enterprise](req.method ?? "", path2, structuredClone(payload ?? {}), query, req.headers, data, sequence) : restAdapter ? restAdapter(req.method ?? "", path2, params, req.headers, data, sequence, rawBody) : stripeOperation(req.method ?? "", path2, params, data, sequence);
6806
+ const headers = (r) => "headers" in r ? r.headers : void 0;
6807
+ const result2 = invoke(this.events.length + 1);
6808
+ if (!result2) {
6809
+ this.rejectUnsupported(service.name, req.method ?? "", path2, `unsupported ${service.adapter} operation or parameters`);
6810
+ respond(501, generated ? generated.unsupported(req.method ?? "", path2) : enterprise ? ENTERPRISE_UNSUPPORTED[enterprise] : restAdapter ? restUnsupportedBody(service.adapter) : { error: { type: "invalid_request_error", code: "unsupported_operation", message: "Outside the verified AgentTwin Stripe subset" }, forwardedToProduction: false });
6811
+ return;
6812
+ }
6813
+ if ("unsupportedReason" in result2 && result2.unsupportedReason) {
6814
+ this.rejectUnsupported(service.name, req.method ?? "", path2, String(result2.unsupportedReason));
6815
+ respond(result2.status, result2.body);
6816
+ return;
6817
+ }
6818
+ if (result2.operation) {
6819
+ this.record(service.name, result2.operation, result2.collection, path2, "record" in result2 ? result2.record : result2.body);
6820
+ this.keyed(keyHeader2);
6821
+ }
6822
+ if (key3 && (result2.status === 200 || result2.status === 201 || enterprise && (result2.status === 202 || result2.status === 204))) keys.set(key3, { body: signature2, record: structuredClone(result2.body), status: result2.status, ...headers(result2) ? { headers: headers(result2) } : {} });
6823
+ const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result2.operation === "write" && !key3 && matchesFault(result2.collection);
6824
+ const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
6825
+ const pushes = (r) => "deliveries" in r ? [...r.deliveries ?? []] : [];
6826
+ const deliveries = pushes(result2);
6827
+ if (duplicate2) {
6828
+ const second = invoke(this.events.length + 1);
6829
+ if (second?.operation === "write") {
6830
+ deliveries.push(...pushes(second));
6831
+ this.record(service.name, second.operation, second.collection, path2, "record" in second ? second.record : second.body);
6832
+ this.faultActions++;
6833
+ this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result2.collection})`);
6834
+ } else if (second) {
6835
+ this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
6836
+ respond(second.status, second.body, headers(second));
6837
+ if (deliveries.length) this.push(service.name, deliveries, epoch);
6838
+ return;
6839
+ }
6840
+ }
6841
+ if (!this.fired && result2.operation === "write" && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === result2.collection) {
6842
+ this.fired = true;
6843
+ this.faultActions++;
6844
+ this.record(service.name, "fault", result2.collection, `write committed; response delayed ${fault.delayMs}ms`);
6845
+ this.keyed(keyHeader2);
6846
+ const timer = setTimeout(() => {
6847
+ this.timers.delete(timer);
6848
+ respond(result2.status, result2.body, headers(result2));
6849
+ }, fault.delayMs);
6850
+ this.timers.add(timer);
6851
+ } else respondSlowly(result2.collection, result2.operation ?? "request", result2.status, result2.body, headers(result2));
6852
+ if (deliveries.length) this.push(service.name, deliveries, epoch);
6216
6853
  return;
6217
6854
  }
6218
- if (result2.operation) {
6219
- this.record(service.name, result2.operation, result2.collection, path2, "record" in result2 ? result2.record : result2.body);
6220
- this.keyed(keyHeader2);
6221
- }
6222
- if (key3 && (result2.status === 200 || result2.status === 201 || enterprise && (result2.status === 202 || result2.status === 204))) keys.set(key3, { body: signature2, record: structuredClone(result2.body), status: result2.status, ...headers(result2) ? { headers: headers(result2) } : {} });
6223
- const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result2.operation === "write" && !key3 && matchesFault(result2.collection);
6224
- const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
6225
- const pushes = (r) => "deliveries" in r ? [...r.deliveries ?? []] : [];
6226
- const deliveries = pushes(result2);
6227
- if (duplicate2) {
6228
- const second = invoke(this.events.length + 1);
6229
- if (second?.operation === "write") {
6230
- deliveries.push(...pushes(second));
6231
- this.record(service.name, second.operation, second.collection, path2, "record" in second ? second.record : second.body);
6232
- this.faultActions++;
6233
- this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result2.collection})`);
6234
- } else if (second) {
6235
- this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
6236
- respond(second.status, second.body, headers(second));
6237
- if (deliveries.length) this.push(service.name, deliveries, epoch);
6855
+ if (slack) {
6856
+ const params = payload ?? Object.fromEntries(url.searchParams);
6857
+ const allowed = slackMethod === "chat.postMessage" ? ["channel", "text"] : slackMethod === "conversations.history" ? ["channel"] : [];
6858
+ if (Object.keys(params).some((k) => !allowed.includes(k))) {
6859
+ this.rejectUnsupported(service.name, req.method ?? "", url.pathname, `unsupported parameters for ${slackMethod}`);
6860
+ respond(501, { ok: false, error: "unsupported_parameters", forwardedToProduction: false });
6861
+ return;
6862
+ }
6863
+ if (slackMethod === "chat.postMessage" && req.method === "POST") path2 = "/messages";
6864
+ else if (slackMethod === "conversations.history" && ["GET", "POST"].includes(req.method ?? "")) path2 = "/messages";
6865
+ else if (slackMethod === "conversations.list" && ["GET", "POST"].includes(req.method ?? "")) path2 = "/channels";
6866
+ else {
6867
+ this.rejectUnsupported(service.name, req.method ?? "", url.pathname, "unsupported operation");
6868
+ respond(501, { ok: false, error: "unsupported_operation", forwardedToProduction: false });
6238
6869
  return;
6239
6870
  }
6240
6871
  }
6241
- if (!this.fired && result2.operation === "write" && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === result2.collection) {
6242
- this.fired = true;
6243
- this.faultActions++;
6244
- this.record(service.name, "fault", result2.collection, `write committed; response delayed ${fault.delayMs}ms`);
6245
- this.keyed(keyHeader2);
6246
- const timer = setTimeout(() => {
6247
- this.timers.delete(timer);
6248
- respond(result2.status, result2.body, headers(result2));
6249
- }, fault.delayMs);
6250
- this.timers.add(timer);
6251
- } else respondSlowly(result2.collection, result2.operation ?? "request", result2.status, result2.body, headers(result2));
6252
- if (deliveries.length) this.push(service.name, deliveries, epoch);
6253
- return;
6254
- }
6255
- if (slack) {
6256
- const params = payload ?? Object.fromEntries(url.searchParams);
6257
- const allowed = slackMethod === "chat.postMessage" ? ["channel", "text"] : slackMethod === "conversations.history" ? ["channel"] : [];
6258
- if (Object.keys(params).some((k) => !allowed.includes(k))) {
6259
- this.rejectUnsupported(service.name, req.method ?? "", url.pathname, `unsupported parameters for ${slackMethod}`);
6260
- respond(501, { ok: false, error: "unsupported_parameters", forwardedToProduction: false });
6872
+ if (!Object.hasOwn(data, path2) || !["GET", "POST"].includes(req.method ?? "")) {
6873
+ this.rejectUnsupported(service.name, req.method ?? "", path2, "unsupported operation");
6874
+ respond(501, { error: "unsupported_operation", forwardedToProduction: false });
6261
6875
  return;
6262
6876
  }
6263
- if (slackMethod === "chat.postMessage" && req.method === "POST") path2 = "/messages";
6264
- else if (slackMethod === "conversations.history" && ["GET", "POST"].includes(req.method ?? "")) path2 = "/messages";
6265
- else if (slackMethod === "conversations.list" && ["GET", "POST"].includes(req.method ?? "")) path2 = "/channels";
6266
- else {
6267
- this.rejectUnsupported(service.name, req.method ?? "", url.pathname, "unsupported operation");
6268
- respond(501, { ok: false, error: "unsupported_operation", forwardedToProduction: false });
6877
+ if (req.method === "GET" || slack && slackMethod !== "chat.postMessage") {
6878
+ this.record(service.name, "read", path2, `${data[path2].length} records`);
6879
+ if (slack && path2 === "/channels") respondSlowly(path2, "read", 200, { ok: true, channels: data[path2], response_metadata: { next_cursor: "" } });
6880
+ else if (slack) {
6881
+ const channel = payload?.channel ?? url.searchParams.get("channel");
6882
+ if (!data["/channels"].some((c) => c.id === channel)) respond(200, { ok: false, error: "channel_not_found" });
6883
+ else respondSlowly(path2, "read", 200, { ok: true, messages: data[path2].filter((m) => m.channel === channel), has_more: false });
6884
+ } else respondSlowly(path2, "read", 200, { data: data[path2] });
6269
6885
  return;
6270
6886
  }
6271
- }
6272
- if (!Object.hasOwn(data, path2) || !["GET", "POST"].includes(req.method ?? "")) {
6273
- this.rejectUnsupported(service.name, req.method ?? "", path2, "unsupported operation");
6274
- respond(501, { error: "unsupported_operation", forwardedToProduction: false });
6275
- return;
6276
- }
6277
- if (req.method === "GET" || slack && slackMethod !== "chat.postMessage") {
6278
- this.record(service.name, "read", path2, `${data[path2].length} records`);
6279
- if (slack && path2 === "/channels") respondSlowly(path2, "read", 200, { ok: true, channels: data[path2], response_metadata: { next_cursor: "" } });
6280
- else if (slack) {
6281
- const channel = payload?.channel ?? url.searchParams.get("channel");
6282
- if (!data["/channels"].some((c) => c.id === channel)) respond(200, { ok: false, error: "channel_not_found" });
6283
- else respondSlowly(path2, "read", 200, { ok: true, messages: data[path2].filter((m) => m.channel === channel), has_more: false });
6284
- } else respondSlowly(path2, "read", 200, { data: data[path2] });
6285
- return;
6286
- }
6287
- const body2 = payload;
6288
- if (slack) {
6289
- const message = body2;
6290
- if (!data["/channels"].some((c) => c.id === message.channel)) {
6291
- respond(200, { ok: false, error: "channel_not_found" });
6292
- return;
6887
+ const body2 = payload;
6888
+ if (slack) {
6889
+ const message = body2;
6890
+ const channels = data["/channels"];
6891
+ const recipient = message.channel;
6892
+ let destination = channels.find((channel) => channel.id === recipient);
6893
+ if (typeof recipient === "string" && /^[UW][A-Z0-9]+$/.test(recipient)) {
6894
+ const user = data["/users"]?.find((row2) => row2.id === recipient);
6895
+ destination = channels.find((channel) => channel.is_im === true && channel.user === recipient);
6896
+ if (user?.deleted === true || user?.dmAllowed === false) destination = void 0;
6897
+ else if (!destination && user) {
6898
+ if (channels.length >= 1e4) {
6899
+ respond(429, { error: "world_capacity" });
6900
+ return;
6901
+ }
6902
+ const id = slackDirectMessageId(recipient);
6903
+ destination = { id, is_im: true, user: recipient };
6904
+ if (channels.some((channel) => channel.id === id)) {
6905
+ respond(409, { error: "channel_conflict" });
6906
+ return;
6907
+ }
6908
+ }
6909
+ }
6910
+ if (!destination) {
6911
+ respond(200, { ok: false, error: "channel_not_found" });
6912
+ return;
6913
+ }
6914
+ if (typeof message.text !== "string" || !message.text) {
6915
+ respond(200, { ok: false, error: "no_text" });
6916
+ return;
6917
+ }
6918
+ if (data[path2].length >= 1e4 || this.events.length >= 5e4) {
6919
+ respond(429, { error: "world_capacity" });
6920
+ return;
6921
+ }
6922
+ if (!channels.includes(destination)) {
6923
+ channels.push(destination);
6924
+ this.record(service.name, "write", "/channels", String(destination.id), destination);
6925
+ }
6926
+ message.channel = destination.id;
6293
6927
  }
6294
- if (typeof message.text !== "string" || !message.text) {
6295
- respond(200, { ok: false, error: "no_text" });
6928
+ if (data[path2].length >= 1e4 || this.events.length >= 5e4) {
6929
+ respond(429, { error: "world_capacity" });
6296
6930
  return;
6297
6931
  }
6298
- }
6299
- if (data[path2].length >= 1e4 || this.events.length >= 5e4) {
6300
- respond(429, { error: "world_capacity" });
6301
- return;
6302
- }
6303
- const keyHeader = slack ? void 0 : req.headers["idempotency-key"];
6304
- const key2 = typeof keyHeader === "string" ? `${path2}:${keyHeader}` : void 0;
6305
- const signature = JSON.stringify(body2);
6306
- const previous = key2 ? keys.get(key2) : void 0;
6307
- if (previous) {
6308
- if (previous.body !== signature) {
6309
- respond(409, { error: "idempotency_conflict" });
6932
+ const keyHeader = slack ? void 0 : req.headers["idempotency-key"];
6933
+ const key2 = typeof keyHeader === "string" ? `${path2}:${keyHeader}` : void 0;
6934
+ const signature = JSON.stringify(body2);
6935
+ const previous = key2 ? keys.get(key2) : void 0;
6936
+ if (previous) {
6937
+ if (previous.body !== signature) {
6938
+ respond(409, { error: "idempotency_conflict" });
6939
+ return;
6940
+ }
6941
+ this.record(service.name, "replay", path2, "same-key response replay", previous.record);
6942
+ this.keyed(keyHeader);
6943
+ respondSlowly(path2, "replay", 200, previous.record);
6310
6944
  return;
6311
6945
  }
6312
- this.record(service.name, "replay", path2, "same-key response replay", previous.record);
6313
- this.keyed(keyHeader);
6314
- respondSlowly(path2, "replay", 200, previous.record);
6315
- return;
6316
- }
6317
- const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path2 && !key2 && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
6318
- if (duplicate) this.faultActions++;
6319
- let index = data[path2].length + 1;
6320
- while (data[path2].some((r) => r.id === `${service.name}_${index}`)) index++;
6321
- const row = { ...body2, id: `${service.name}_${index}` };
6322
- if (slack) row.ts = `${index}.000001`;
6323
- const reply = slack ? { ok: true, channel: row.channel, ts: row.ts, message: row } : row;
6324
- data[path2].push(row);
6325
- if (key2) keys.set(key2, { body: signature, record: row });
6326
- this.record(service.name, "write", path2, String(row.id), row);
6327
- this.keyed(keyHeader);
6328
- if (duplicate) {
6329
- index++;
6946
+ const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path2 && !key2 && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
6947
+ if (duplicate) this.faultActions++;
6948
+ let index = data[path2].length + 1;
6330
6949
  while (data[path2].some((r) => r.id === `${service.name}_${index}`)) index++;
6331
- const second = { ...body2, id: `${service.name}_${index}` };
6332
- if (slack) second.ts = `${index}.000001`;
6333
- data[path2].push(second);
6334
- this.record(service.name, "write", path2, String(second.id), second);
6335
- this.record(service.name, "fault", fault.path, `duplicate-write: one write committed as two records (${row.id}, ${second.id})`);
6336
- }
6337
- const faultResponse = slack ? 200 : 201;
6338
- if (!this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === path2) {
6339
- this.fired = true;
6340
- this.faultActions++;
6341
- this.record(service.name, "fault", path2, `write committed; response delayed ${fault.delayMs}ms`);
6950
+ const row = { ...body2, id: `${service.name}_${index}` };
6951
+ if (slack) row.ts = `${index}.000001`;
6952
+ const reply = slack ? { ok: true, channel: row.channel, ts: row.ts, message: row } : row;
6953
+ data[path2].push(row);
6954
+ if (key2) keys.set(key2, { body: signature, record: row });
6955
+ this.record(service.name, "write", path2, String(row.id), row);
6342
6956
  this.keyed(keyHeader);
6343
- const timer = setTimeout(() => {
6344
- this.timers.delete(timer);
6345
- respond(faultResponse, reply);
6346
- }, fault.delayMs);
6347
- this.timers.add(timer);
6348
- } else respondSlowly(path2, "write", faultResponse, reply);
6349
- } catch {
6350
- respond(500, { error: "world_request_error" });
6351
- }
6352
- })));
6957
+ if (duplicate) {
6958
+ index++;
6959
+ while (data[path2].some((r) => r.id === `${service.name}_${index}`)) index++;
6960
+ const second = { ...body2, id: `${service.name}_${index}` };
6961
+ if (slack) second.ts = `${index}.000001`;
6962
+ data[path2].push(second);
6963
+ this.record(service.name, "write", path2, String(second.id), second);
6964
+ this.record(service.name, "fault", fault.path, `duplicate-write: one write committed as two records (${row.id}, ${second.id})`);
6965
+ }
6966
+ const faultResponse = slack ? 200 : 201;
6967
+ if (!this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === path2) {
6968
+ this.fired = true;
6969
+ this.faultActions++;
6970
+ this.record(service.name, "fault", path2, `write committed; response delayed ${fault.delayMs}ms`);
6971
+ this.keyed(keyHeader);
6972
+ const timer = setTimeout(() => {
6973
+ this.timers.delete(timer);
6974
+ respond(faultResponse, reply);
6975
+ }, fault.delayMs);
6976
+ this.timers.add(timer);
6977
+ } else respondSlowly(path2, "write", faultResponse, reply);
6978
+ } catch {
6979
+ respond(500, { error: "world_request_error" });
6980
+ }
6981
+ }));
6982
+ });
6353
6983
  server.requestTimeout = 1e4;
6354
6984
  await new Promise((resolve13, reject) => {
6355
6985
  server.once("error", reject);
@@ -6363,6 +6993,13 @@ var init_http_world = __esm({
6363
6993
  /** Environment each pack service's credential door issued (STRIPE_SECRET_KEY…), for the application's process. */
6364
6994
  packEnv = /* @__PURE__ */ Object.create(null);
6365
6995
  packRoots = [];
6996
+ /** Per service: 1 while a call the world makes is in flight and no envelope has been captured yet, 2 once one has. */
6997
+ causing = /* @__PURE__ */ Object.create(null);
6998
+ lastEnvelope = /* @__PURE__ */ Object.create(null);
6999
+ socketServers = [];
7000
+ rawServers = [];
7001
+ /** Each pack service's plain-TCP port for clients that open their own TLS sockets (see startPack). */
7002
+ packTcp = /* @__PURE__ */ Object.create(null);
6366
7003
  /**
6367
7004
  * A twin pack served behind this world: the run token is checked and swapped for the credential the pack issued,
6368
7005
  * seeded fault schedules apply around the pack's own handler, and every action the pack logs becomes evidence — writes
@@ -6377,10 +7014,11 @@ var init_http_world = __esm({
6377
7014
  const writeSeedLog = async (dir, text3) => {
6378
7015
  if (!text3) return;
6379
7016
  await mkdir3(join11(dir, ".volter/world", meta2.logService), { recursive: true });
6380
- await writeFile5(join11(dir, ".volter/world", meta2.logService, "actions.jsonl"), text3);
7017
+ await writeFile6(join11(dir, ".volter/world", meta2.logService, "actions.jsonl"), text3);
6381
7018
  };
6382
7019
  let tenant = {}, credential;
6383
- if (meta2.logService && meta2.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account)) {
7020
+ let doorLines = "";
7021
+ if (meta2.logService && meta2.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account || service.doorRecords?.length)) {
6384
7022
  const probe = await mkdtemp5(join11(tmpdir5(), `agenttwin-pack-${name}-probe-`));
6385
7023
  try {
6386
7024
  await writeSeedLog(probe, worldSeed);
@@ -6389,37 +7027,76 @@ var init_http_world = __esm({
6389
7027
  const probed = new PackActionTail(join11(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
6390
7028
  tenant = tenantFields(probed);
6391
7029
  credential = credentialAction(probed);
7030
+ for (const rec of service.doorRecords ?? []) {
7031
+ const own = probed.filter((a) => a.subject?.type === rec.type);
7032
+ const original = own[0]?.subject?.id;
7033
+ if (!original) continue;
7034
+ doorLines += own.filter((a) => a.subject?.id === original).map((a, i) => JSON.stringify({ ...a, id: `${String(a.id ?? `door:${rec.type}`)}:preset:${rec.id}`, subject: { type: rec.type, id: rec.id }, fields: i === 0 ? { ...a.fields, ...rec.fields } : a.fields }) + "\n").join("");
7035
+ }
6392
7036
  } finally {
6393
7037
  await rm5(probe, { recursive: true, force: true });
6394
7038
  }
6395
7039
  }
6396
7040
  const account = credential && service.account ? JSON.stringify({ ...credential, id: `${credential.id ?? "credential"}:preset`, fields: { ...credential.fields, ...service.account } }) + "\n" : "";
6397
- const seeded = meta2.logService ? worldSeed + account + seedActions(meta2.logService, service.collections, new Date(twinNowMs(Date.now())).toISOString(), tenant) : "";
7041
+ const seeded = meta2.logService ? worldSeed + account + doorLines + seedActions(meta2.logService, service.collections, new Date(twinNowMs(Date.now())).toISOString(), tenant) : "";
6398
7042
  await writeSeedLog(root, seeded);
6399
7043
  const twin = await (await loadPack(name))({ root });
6400
7044
  const baseHost = meta2.hosts[0]?.host ?? `${name}.twin.test`;
6401
7045
  const log = new PackActionTail(join11(root, ".volter"));
6402
7046
  let issued = {};
6403
7047
  if (meta2.credentialDoor) {
6404
- const r = await twin(new Request(`https://${baseHost}${meta2.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta2.credentialDoor.body ?? {}) }));
6405
- if (r.ok) issued = await r.json();
6406
- else await r.arrayBuffer();
7048
+ const hosts = [...new Set(meta2.hosts.map((h) => h.host).filter((h) => !!h))];
7049
+ const door = (host) => twin(new Request(`https://${host}${meta2.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta2.credentialDoor.body ?? {}) }));
7050
+ for (const host of hosts.length ? hosts : [baseHost]) {
7051
+ let r = await door(host);
7052
+ if (r.status === 404 && meta2.credentialDoor.body && Object.keys(meta2.credentialDoor.body).length) {
7053
+ await r.arrayBuffer();
7054
+ const made = await twin(new Request(`https://${host}/_twin/accounts`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email: "world@world.test", ...meta2.credentialDoor.body }) }));
7055
+ await made.arrayBuffer();
7056
+ r = await door(host);
7057
+ }
7058
+ if (r.ok) {
7059
+ issued = await r.json();
7060
+ break;
7061
+ }
7062
+ await r.arrayBuffer();
7063
+ if (r.status !== 404) break;
7064
+ }
6407
7065
  }
6408
7066
  const env = {};
6409
- for (const [envName, field] of Object.entries(meta2.credentialDoor?.fill ?? {})) if (typeof issued[field] === "string") env[envName] = issued[field];
7067
+ for (const [envName, field] of Object.entries(meta2.credentialDoor?.fill ?? {})) {
7068
+ if (field.startsWith("file:")) {
7069
+ const value = issued[field.slice(5)];
7070
+ if (value && typeof value === "object") {
7071
+ const file = join11(root, `${envName.toLowerCase()}.json`);
7072
+ await writeFile6(file, JSON.stringify(value, null, 2), { mode: 384 });
7073
+ env[envName] = file;
7074
+ }
7075
+ } else if (typeof issued[field] === "string") env[envName] = issued[field];
7076
+ }
6410
7077
  this.packEnv[service.name] = env;
6411
7078
  const primaryEnv = Object.keys(env).find((k) => /(SECRET|API|PRIVATE|ACCESS)_?(KEY|TOKEN)$|_TOKEN$|_KEY$/.test(k) && !/PUBLISHABLE|PUBLIC|WEBHOOK|SIGNING|ENDPOINT/.test(k));
6412
7079
  const primary = primaryEnv ? env[primaryEnv] : void 0;
6413
7080
  const authHeaders = () => primary ? { authorization: `Bearer ${primary}` } : {};
7081
+ const issuedValues = Object.values(env).filter((v) => v.length >= 12);
7082
+ const appCredential = (value) => {
7083
+ const v = Array.isArray(value) ? value[0] : value;
7084
+ return v && issuedValues.some((i) => v === `Bearer ${i}`) ? v : void 0;
7085
+ };
6414
7086
  const fault = this.spec.fault;
6415
7087
  const matchesFault = (target) => !!fault && (target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path));
6416
- const apply = (actions, method, path2, evidence) => {
7088
+ const apply = (actions, method, path2, evidence, byWorld = false) => {
6417
7089
  const wrote = [];
6418
7090
  for (const a of actions) {
6419
7091
  const type = a.subject?.type, id = a.subject?.id;
6420
7092
  if (!type || !id) continue;
6421
7093
  if (type === "_world_event_delivery") {
6422
- if (evidence) this.record(service.name, "webhook", String(a.fields?.url ?? ""), `delivered ${typeof a.fields?.body === "string" ? /"type":"([^"]+)"/.exec(a.fields.body)?.[1] ?? "event" : "event"} to ${a.fields?.url ?? "endpoint"}`);
7094
+ const f = a.fields ?? {}, eventType = typeof f.body === "string" ? /"type":"([^"]+)"/.exec(f.body)?.[1] ?? "event" : "event";
7095
+ const key2 = `${service.name}:${id}`;
7096
+ if (f.delivery_state === "queued" && typeof f.url === "string" && typeof f.body === "string" && f.headers && typeof f.headers === "object" && !this.sentWebhooks.has(key2)) {
7097
+ this.sentWebhooks.add(key2);
7098
+ this.sendWebhook(service.name, f.url, f.body, f.headers, eventType);
7099
+ } else if (evidence && !this.sentWebhooks.has(key2)) this.record(service.name, "webhook", String(f.url ?? ""), `queued ${eventType} for ${f.url ?? "endpoint"}`);
6423
7100
  continue;
6424
7101
  }
6425
7102
  if (type.startsWith("_")) continue;
@@ -6433,7 +7110,7 @@ var init_http_world = __esm({
6433
7110
  } else if (at >= 0) rows2[at] = row;
6434
7111
  else rows2.push(row);
6435
7112
  if (!evidence) continue;
6436
- const byApp = a.actor?.kind === "agent";
7113
+ const byApp = a.actor?.kind === "agent" && !byWorld;
6437
7114
  this.record(service.name, byApp ? "write" : "twin", collection, `${method} ${path2} \u2192 ${a.operation ?? type} ${id}${byApp ? "" : " (by the twin)"}`, row);
6438
7115
  if (byApp) wrote.push(collection);
6439
7116
  }
@@ -6455,146 +7132,258 @@ var init_http_world = __esm({
6455
7132
  chain = run3.then(() => void 0, () => void 0);
6456
7133
  return run3;
6457
7134
  };
6458
- const server = createServer3((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
6459
- const epoch = this.epoch;
6460
- const send2 = (status, headers, body2) => {
6461
- if (!res.destroyed) {
6462
- res.writeHead(status, headers);
6463
- res.end(body2);
6464
- }
6465
- };
6466
- const later = (ms, fn) => {
6467
- const timer = setTimeout(() => {
6468
- this.timers.delete(timer);
6469
- if (epoch === this.epoch) fn();
6470
- }, ms);
6471
- this.timers.add(timer);
6472
- };
6473
- const respond = (status, headers, body2) => {
6474
- const ms = latencyMs();
6475
- if (ms <= 0) send2(status, headers, body2);
6476
- else later(ms, () => send2(status, headers, body2));
6477
- };
6478
- const json2 = (status, value) => respond(status, { "content-type": "application/json" }, Buffer.from(JSON.stringify(value)));
6479
- try {
6480
- const ours = req.headers.authorization === `Bearer ${token}` || req.headers["x-api-key"] === token || req.headers["x-agenttwin-token"] === token;
6481
- if (!ours) {
6482
- this.record(service.name, "auth-denied", req.url ?? "", "invalid test credential");
6483
- json2(401, { error: "invalid_test_credential" });
6484
- return;
6485
- }
6486
- if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
6487
- json2(429, { error: "world_capacity" });
6488
- return;
6489
- }
6490
- const url = new URL(req.url ?? "/", "http://localhost"), method = req.method ?? "GET", path2 = url.pathname;
6491
- const requestKey = req.headers["idempotency-key"];
6492
- if (fault && faultOrdinalsFor && (fault.type === "blackhole" || fault.type === "server-error") && matchesFault(path2) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
6493
- this.faultActions++;
6494
- if (fault.type === "blackhole") {
6495
- this.record(service.name, "fault", fault.path, `blackhole: request dropped; nothing committed (${method})`);
7135
+ const server = createServer3((req, res) => {
7136
+ if (req.headers["x-agenttwin-probe"] === "1") {
7137
+ this.probes++;
7138
+ res.once("close", () => {
7139
+ this.probes--;
7140
+ });
7141
+ }
7142
+ return withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
7143
+ const epoch = this.epoch;
7144
+ const send2 = (status, headers, body2) => {
7145
+ if (!res.destroyed) {
7146
+ res.writeHead(status, headers);
7147
+ res.end(body2);
7148
+ }
7149
+ };
7150
+ const later = (ms, fn) => {
7151
+ const timer = setTimeout(() => {
7152
+ this.timers.delete(timer);
7153
+ if (epoch === this.epoch) fn();
7154
+ }, ms);
7155
+ this.timers.add(timer);
7156
+ };
7157
+ const respond = (status, headers, body2) => {
7158
+ const ms = latencyMs();
7159
+ if (ms <= 0) send2(status, headers, body2);
7160
+ else later(ms, () => send2(status, headers, body2));
7161
+ };
7162
+ const json2 = (status, value) => respond(status, { "content-type": "application/json" }, Buffer.from(JSON.stringify(value)));
7163
+ try {
7164
+ const raw = req.socket.agenttwinRaw === true;
7165
+ const ours = raw || req.headers.authorization === `Bearer ${token}` || req.headers["x-api-key"] === token || req.headers["x-agenttwin-token"] === token;
7166
+ if (!ours) {
7167
+ this.record(service.name, "auth-denied", req.url ?? "", "invalid test credential");
7168
+ json2(401, { error: "invalid_test_credential" });
7169
+ return;
7170
+ }
7171
+ if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
7172
+ json2(429, { error: "world_capacity" });
7173
+ return;
7174
+ }
7175
+ const url = new URL(req.url ?? "/", "http://localhost"), method = req.method ?? "GET", path2 = url.pathname;
7176
+ if (path2 === "/_agenttwin/redeliver" && req.headers["x-agenttwin-token"] === token) {
7177
+ const last = this.lastEnvelope[service.name];
7178
+ if (!last) {
7179
+ json2(404, { ok: false, error: "nothing_delivered" });
7180
+ return;
7181
+ }
7182
+ const attempt = Number(last.envelope.retry_attempt ?? 0) + 1;
7183
+ const again = { ...last.envelope, envelope_id: createHash10("sha256").update(`${String(last.envelope.envelope_id)}:${attempt}`).digest("hex").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12}).*/, "$1-$2-$3-$4-$5"), retry_attempt: attempt, retry_reason: "timeout" };
7184
+ last.send(JSON.stringify(again));
7185
+ this.record(service.name, "twin", path2, `redelivered ${String(last.envelope.type ?? "envelope")} (retry_attempt ${attempt}, as after a lost acknowledgment)`);
7186
+ json2(200, { ok: true, retry_attempt: attempt });
7187
+ return;
7188
+ }
7189
+ const workspace = req.headers["x-agenttwin-actor"] === "workspace" && req.headers["x-agenttwin-token"] === token;
7190
+ const requestKey = req.headers["idempotency-key"];
7191
+ if (!workspace && fault && faultOrdinalsFor && (fault.type === "blackhole" || fault.type === "server-error") && matchesFault(path2) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
7192
+ this.faultActions++;
7193
+ if (fault.type === "blackhole") {
7194
+ this.record(service.name, "fault", fault.path, `blackhole: request dropped; nothing committed (${method})`);
7195
+ this.keyed(requestKey);
7196
+ return;
7197
+ }
7198
+ const windowMs = fault.windowMs ?? 0;
7199
+ const delay2 = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
7200
+ this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay2}ms; nothing committed (${method})`);
6496
7201
  this.keyed(requestKey);
7202
+ const fail2 = () => json2(500, { error: { type: "api_error", message: "server_error fault" } });
7203
+ if (delay2 <= 0) fail2();
7204
+ else later(delay2, fail2);
6497
7205
  return;
6498
7206
  }
6499
- const windowMs = fault.windowMs ?? 0;
6500
- const delay2 = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
6501
- this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay2}ms; nothing committed (${method})`);
6502
- this.keyed(requestKey);
6503
- const fail2 = () => json2(500, { error: { type: "api_error", message: "server_error fault" } });
6504
- if (delay2 <= 0) fail2();
6505
- else later(delay2, fail2);
6506
- return;
6507
- }
6508
- const chunks = [];
6509
- let bytes = 0;
6510
- for await (const chunk of req) {
6511
- bytes += chunk.length;
6512
- if (bytes > 5 * 1024 * 1024) {
6513
- json2(413, { error: "body_too_large" });
7207
+ const chunks = [];
7208
+ let bytes = 0;
7209
+ for await (const chunk of req) {
7210
+ bytes += chunk.length;
7211
+ if (bytes > 5 * 1024 * 1024) {
7212
+ json2(413, { error: "body_too_large" });
7213
+ return;
7214
+ }
7215
+ chunks.push(Buffer.from(chunk));
7216
+ }
7217
+ const body2 = ["GET", "HEAD"].includes(method) ? void 0 : Buffer.concat(chunks);
7218
+ if (epoch !== this.epoch) {
7219
+ json2(409, { error: "world_reset" });
6514
7220
  return;
6515
7221
  }
6516
- chunks.push(Buffer.from(chunk));
6517
- }
6518
- const body2 = ["GET", "HEAD"].includes(method) ? void 0 : Buffer.concat(chunks);
6519
- if (epoch !== this.epoch) {
6520
- json2(409, { error: "world_reset" });
6521
- return;
6522
- }
6523
- let host = String(req.headers["x-agenttwin-original-host"] ?? baseHost);
6524
- if (name === "pinecone") {
6525
- const m = /^([a-z0-9-]+?)-[a-z0-9]+\.svc\.[a-z0-9.-]*pinecone\.io$/.exec(host);
6526
- const index = m && (data["/indexes"] ?? []).find((r) => r.name === m[1] && typeof r.host === "string");
6527
- if (index && index.host !== host) host = String(index.host);
6528
- }
6529
- const headers = new Headers();
6530
- for (const [k, v] of Object.entries(req.headers)) if (v !== void 0 && !/^(host|connection|keep-alive|content-length|transfer-encoding|x-agenttwin-.*)$/i.test(k)) headers.set(k, Array.isArray(v) ? v.join(", ") : v);
6531
- if (headers.get("authorization") === `Bearer ${token}`) {
6532
- if (primary) headers.set("authorization", `Bearer ${primary}`);
6533
- else headers.delete("authorization");
6534
- }
6535
- if (headers.get("x-api-key") === token) {
6536
- if (primary) headers.set("x-api-key", primary);
6537
- else headers.delete("x-api-key");
6538
- }
6539
- const call2 = async () => {
6540
- const r = await twin(new Request(`https://${host}${req.url ?? "/"}`, { method, headers, ...body2 ? { body: body2 } : {} }));
6541
- return { status: r.status, headers: r.headers, bytes: Buffer.from(await r.arrayBuffer()), actions: log.drain() };
6542
- };
6543
- const first = await serialized(call2);
6544
- if (epoch !== this.epoch) return;
6545
- const wrote = apply(first.actions, method, path2, true);
6546
- let okFalse;
6547
- if (first.status < 300 && /json/.test(first.headers.get("content-type") ?? "")) try {
6548
- const parsed = JSON.parse(first.bytes.toString("utf8"));
6549
- if (parsed.ok === false) okFalse = [parsed.error, ...parsed.response_metadata?.messages ?? []].filter(Boolean).join(": ").slice(0, 240) || "ok: false";
6550
- } catch {
6551
- }
6552
- if (wrote.length) this.keyed(requestKey);
6553
- else if (meta2.gapMessage && (first.status >= 400 || okFalse) && first.bytes.toString("utf8").includes(meta2.gapMessage)) this.rejectUnsupported(service.name, method, path2, `${name} twin does not model ${method} ${path2}`);
6554
- else if (okFalse) this.record(service.name, "rejected", path2, `${method} ${path2} \u2192 ${first.status} ok:false: ${okFalse}`);
6555
- else if (first.status >= 400) {
6556
- let reason = "";
6557
- try {
7222
+ if (this.postgrest && path2.startsWith("/rest/v1/")) {
7223
+ const r = await this.postgrest.handle({ method, url, headers: req.headers, body: body2 });
7224
+ if (method !== "GET" && method !== "HEAD") this.record(service.name, r.status < 400 ? "write" : "rejected", path2, `${method} ${path2} \u2192 ${r.status}${r.status >= 400 ? `: ${r.body.slice(0, 200)}` : ""}`);
7225
+ res.writeHead(r.status, r.headers);
7226
+ res.end(r.body);
7227
+ return;
7228
+ }
7229
+ let host = String(req.headers["x-agenttwin-original-host"] ?? (raw ? req.headers.host?.replace(/:\d+$/, "") : void 0) ?? baseHost);
7230
+ if (name === "pinecone") {
7231
+ const m = /^([a-z0-9-]+?)-[a-z0-9]+\.svc\.[a-z0-9.-]*pinecone\.io$/.exec(host);
7232
+ const index = m && (data["/indexes"] ?? []).find((r) => r.name === m[1] && typeof r.host === "string");
7233
+ if (index && index.host !== host) host = String(index.host);
7234
+ }
7235
+ const headers = new Headers();
7236
+ for (const [k, v] of Object.entries(req.headers)) if (v !== void 0 && !/^(host|connection|keep-alive|content-length|transfer-encoding|x-agenttwin-.*)$/i.test(k)) headers.set(k, Array.isArray(v) ? v.join(", ") : v);
7237
+ const own = appCredential(req.headers["x-agenttwin-app-authorization"]);
7238
+ if (own) headers.set("authorization", own);
7239
+ else if (raw) {
7240
+ const given = headers.get("authorization");
7241
+ if (given && !appCredential(given) && /^Bearer /.test(given) && primary) headers.set("authorization", `Bearer ${primary}`);
7242
+ } else if (headers.get("authorization") === `Bearer ${token}`) {
7243
+ if (primary) headers.set("authorization", `Bearer ${primary}`);
7244
+ else headers.delete("authorization");
7245
+ }
7246
+ if (headers.get("x-api-key") === token) {
7247
+ if (primary) headers.set("x-api-key", primary);
7248
+ else headers.delete("x-api-key");
7249
+ }
7250
+ const call2 = async () => {
7251
+ const target2 = aliasRequest(name, host, req.url ?? "/");
7252
+ const model = compatibleModel(name, body2);
7253
+ const r = await twin(new Request(`https://${target2.host}${target2.url}`, { method, headers, ...model.body ? { body: model.body } : {} }));
7254
+ return { status: r.status, headers: r.headers, bytes: model.restore(Buffer.from(await r.arrayBuffer())), actions: log.drain() };
7255
+ };
7256
+ if (workspace && method !== "GET") this.causing[service.name] = 1;
7257
+ const first = await serialized(call2).finally(() => {
7258
+ if (workspace) this.causing[service.name] = 0;
7259
+ });
7260
+ if (epoch !== this.epoch) return;
7261
+ const recordedBefore = this.events.length;
7262
+ const wrote = apply(first.actions, method, path2, true, workspace);
7263
+ if (workspace) {
7264
+ const out2 = {};
7265
+ first.headers.forEach((v, k) => {
7266
+ if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out2[k] = v;
7267
+ });
7268
+ send2(first.status, out2, first.bytes);
7269
+ return;
7270
+ }
7271
+ let okFalse;
7272
+ if (first.status < 300 && /json/.test(first.headers.get("content-type") ?? "")) try {
6558
7273
  const parsed = JSON.parse(first.bytes.toString("utf8"));
6559
- const e = parsed.error ?? parsed;
6560
- reason = String(e.message ?? e.error_description ?? e.code ?? "").slice(0, 240);
7274
+ if (parsed.ok === false) okFalse = [parsed.error, ...parsed.response_metadata?.messages ?? []].filter(Boolean).join(": ").slice(0, 240) || "ok: false";
6561
7275
  } catch {
6562
- reason = first.bytes.toString("utf8").slice(0, 120);
6563
7276
  }
6564
- this.record(service.name, "rejected", path2, `${method} ${path2} \u2192 ${first.status}${reason ? `: ${reason}` : ""}`);
6565
- } else if (method === "GET") this.record(service.name, "read", path2, `${first.status}`);
6566
- const target = wrote[0];
6567
- if (target && fault?.type === "duplicate-write" && fault.service === service.name && !requestKey && matchesFault(target) && faultOrdinalsFor?.includes(this.candidateIndex(faultKey))) {
6568
- const second = await serialized(call2);
6569
- apply(second.actions, method, path2, true);
6570
- this.faultActions++;
6571
- this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${target})`);
7277
+ if (wrote.length) this.keyedSince(recordedBefore, requestKey);
7278
+ else if (first.status === 501 || meta2.gapMessage && (first.status >= 400 || okFalse) && first.bytes.toString("utf8").includes(meta2.gapMessage)) this.rejectUnsupported(service.name, method, path2, `${name} twin does not model ${method} ${path2}`);
7279
+ else if (okFalse) this.record(service.name, "rejected", path2, `${method} ${path2} \u2192 ${first.status} ok:false: ${okFalse}`);
7280
+ else if (first.status >= 400) {
7281
+ let reason = "";
7282
+ try {
7283
+ const parsed = JSON.parse(first.bytes.toString("utf8"));
7284
+ const e = parsed.error ?? parsed;
7285
+ reason = String(e.message ?? e.error_description ?? e.code ?? "").slice(0, 240);
7286
+ } catch {
7287
+ reason = first.bytes.toString("utf8").slice(0, 120);
7288
+ }
7289
+ this.record(service.name, "rejected", path2, `${method} ${path2} \u2192 ${first.status}${reason ? `: ${reason}` : ""}`);
7290
+ } else if (method === "GET") this.record(service.name, "read", path2, `${first.status}`);
7291
+ const target = wrote.find(matchesFault) ?? wrote[0];
7292
+ if (target && fault?.type === "duplicate-write" && fault.service === service.name && !requestKey && matchesFault(target) && faultOrdinalsFor?.includes(this.candidateIndex(faultKey))) {
7293
+ const second = await serialized(call2);
7294
+ apply(second.actions, method, path2, true);
7295
+ this.faultActions++;
7296
+ this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${target})`);
7297
+ }
7298
+ const out = {};
7299
+ first.headers.forEach((v, k) => {
7300
+ if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out[k] = v;
7301
+ });
7302
+ if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && matchesFault(target)) {
7303
+ this.fired = true;
7304
+ this.faultActions++;
7305
+ this.record(service.name, "fault", target, `write committed; response delayed ${fault.delayMs}ms`);
7306
+ this.keyed(requestKey);
7307
+ later(fault.delayMs, () => send2(first.status, out, first.bytes));
7308
+ } else if (fault?.type === "slow-response" && faultOrdinalsFor && matchesFault(target ?? path2) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
7309
+ this.faultActions++;
7310
+ this.record(service.name, "fault", target ?? path2, `slow-response: ${target ? "write" : "request"} applied; response delayed ${fault.delayMs}ms`);
7311
+ this.keyed(requestKey);
7312
+ later(fault.delayMs, () => respond(first.status, out, first.bytes));
7313
+ } else respond(first.status, out, first.bytes);
7314
+ } catch {
7315
+ json2(500, { error: "world_request_error" });
6572
7316
  }
6573
- const out = {};
6574
- first.headers.forEach((v, k) => {
6575
- if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out[k] = v;
6576
- });
6577
- if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && matchesFault(target)) {
6578
- this.fired = true;
6579
- this.faultActions++;
6580
- this.record(service.name, "fault", target, `write committed; response delayed ${fault.delayMs}ms`);
6581
- this.keyed(requestKey);
6582
- later(fault.delayMs, () => send2(first.status, out, first.bytes));
6583
- } else if (fault?.type === "slow-response" && faultOrdinalsFor && matchesFault(target ?? path2) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
6584
- this.faultActions++;
6585
- this.record(service.name, "fault", target ?? path2, `slow-response: ${target ? "write" : "request"} applied; response delayed ${fault.delayMs}ms`);
6586
- this.keyed(requestKey);
6587
- later(fault.delayMs, () => respond(first.status, out, first.bytes));
6588
- } else respond(first.status, out, first.bytes);
6589
- } catch {
6590
- json2(500, { error: "world_request_error" });
6591
- }
6592
- })));
7317
+ }));
7318
+ });
6593
7319
  server.requestTimeout = 1e4;
7320
+ const upgrade = twin.upgrade;
7321
+ if (upgrade) {
7322
+ const WebSocketServer = await packWebSocketServer(meta2.generation);
7323
+ const toRequest = (req) => {
7324
+ const headers = new Headers();
7325
+ for (const [k, v] of Object.entries(req.headers)) if (typeof v === "string" && !/^(host|x-agenttwin-.*)$/i.test(k)) headers.set(k, v);
7326
+ const own = appCredential(req.headers["x-agenttwin-app-authorization"]);
7327
+ if (own) headers.set("authorization", own);
7328
+ else if (headers.get("authorization") === `Bearer ${token}`) headers.delete("authorization");
7329
+ const raw = req.socket.agenttwinRaw === true;
7330
+ return new Request(`https://${String(req.headers["x-agenttwin-original-host"] ?? (raw ? req.headers.host?.replace(/:\d+$/, "") : void 0) ?? baseHost)}${req.url ?? "/"}`, { headers });
7331
+ };
7332
+ const wss = new WebSocketServer({ noServer: true, handleProtocols: (_set, req) => upgrade.protocol?.(toRequest(req)) ?? false });
7333
+ this.socketServers.push(wss);
7334
+ server.on("upgrade", (req, socket, head) => {
7335
+ const ours = req.socket.agenttwinRaw === true || req.headers.authorization === `Bearer ${token}` || req.headers["x-agenttwin-token"] === token;
7336
+ const path2 = new URL(req.url ?? "/", "http://localhost").pathname;
7337
+ const request = toRequest(req);
7338
+ if (!ours || !upgrade.accepts(request)) {
7339
+ this.record(service.name, ours ? "rejected" : "auth-denied", path2, ours ? `WebSocket ${path2} \u2192 no socket endpoint` : "invalid test credential");
7340
+ socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
7341
+ return;
7342
+ }
7343
+ const epoch = this.epoch;
7344
+ wss.handleUpgrade(req, socket, head, (ws) => {
7345
+ const send2 = ws.send.bind(ws);
7346
+ ws.send = (data2, ...rest) => {
7347
+ try {
7348
+ const parsed = JSON.parse(String(data2));
7349
+ if (typeof parsed.envelope_id === "string" && this.causing[service.name] === 1) {
7350
+ this.causing[service.name] = 2;
7351
+ this.lastEnvelope[service.name] = { send: send2, envelope: parsed };
7352
+ }
7353
+ } catch {
7354
+ }
7355
+ send2(data2, ...rest);
7356
+ };
7357
+ const inWorld = (fn) => withTwinClock(this.twinClock, () => serialized(async () => fn()));
7358
+ ws.on("message", (data2, binary) => {
7359
+ if (epoch !== this.epoch) return;
7360
+ const bytes = Array.isArray(data2) ? Buffer.concat(data2) : Buffer.from(data2);
7361
+ Promise.resolve().then(() => withTwinClock(this.twinClock, () => upgrade.message(ws, binary ? new Uint8Array(bytes) : bytes.toString("utf8")))).then(() => apply(log.drain(), "WS", path2, true), () => ws.close(1011, "handler failed"));
7362
+ });
7363
+ ws.on("close", () => {
7364
+ void inWorld(() => upgrade.close(ws)).catch(() => {
7365
+ });
7366
+ });
7367
+ ws.on("error", () => ws.close());
7368
+ this.record(service.name, "read", path2, `WebSocket ${path2} opened`);
7369
+ void inWorld(() => upgrade.open(ws, request)).then(() => apply(log.drain(), "WS", path2, true), () => ws.close(1011, "handler failed"));
7370
+ });
7371
+ });
7372
+ }
6594
7373
  await new Promise((resolve13, reject) => {
6595
7374
  server.once("error", reject);
6596
7375
  server.listen(0, "127.0.0.1", resolve13);
6597
7376
  });
7377
+ const rawServer = createNetServer((socket) => {
7378
+ socket.agenttwinRaw = true;
7379
+ server.emit("connection", socket);
7380
+ });
7381
+ await new Promise((resolve13, reject) => {
7382
+ rawServer.once("error", reject);
7383
+ rawServer.listen(0, "127.0.0.1", resolve13);
7384
+ });
7385
+ this.rawServers.push(rawServer);
7386
+ this.packTcp[service.name] = rawServer.address().port;
6598
7387
  return server;
6599
7388
  }
6600
7389
  assertions() {
@@ -6630,9 +7419,16 @@ var init_http_world = __esm({
6630
7419
  return this.snapshot();
6631
7420
  }
6632
7421
  async close() {
7422
+ await this.postgrest?.close();
7423
+ this.postgrest = void 0;
6633
7424
  this.epoch++;
6634
7425
  for (const timer of this.timers) clearTimeout(timer);
6635
7426
  this.timers.clear();
7427
+ for (const wss of this.socketServers.splice(0)) {
7428
+ for (const ws of wss.clients) ws.terminate();
7429
+ wss.close();
7430
+ }
7431
+ for (const raw of this.rawServers.splice(0)) raw.close();
6636
7432
  await Promise.all(this.servers.map((server) => new Promise((resolve13) => {
6637
7433
  server.close(() => resolve13());
6638
7434
  server.closeAllConnections();
@@ -6714,7 +7510,7 @@ function evaluateProperty(policy, final, events) {
6714
7510
  const key2 = JSON.stringify(canonical(row[field]));
6715
7511
  keyed.set(key2, [...keyed.get(key2) ?? [], row.id ?? row]);
6716
7512
  }
6717
- const duplicates = [...keyed.entries()].filter(([, list2]) => list2.length > 1);
7513
+ const duplicates = [...keyed.entries()].filter(([, list3]) => list3.length > 1);
6718
7514
  return {
6719
7515
  ...base,
6720
7516
  passed: duplicates.length === 0,
@@ -6781,11 +7577,28 @@ function operationMatrix(spec) {
6781
7577
  function packContract(name, adapter) {
6782
7578
  return { name, adapter, version: "twin-pack", operations: [], pack: adapter.slice("pack:".length) };
6783
7579
  }
6784
- var CONTRACTS;
7580
+ var STRIPE_OPERATIONS, CONTRACTS;
6785
7581
  var init_contracts = __esm({
6786
7582
  "src/runtime/contracts.ts"() {
6787
7583
  "use strict";
6788
7584
  init_enterprise_twins();
7585
+ STRIPE_OPERATIONS = [
7586
+ "customers.create",
7587
+ "customers.retrieve",
7588
+ "customers.list",
7589
+ "paymentIntents.create",
7590
+ "paymentIntents.retrieve",
7591
+ "paymentIntents.confirm",
7592
+ "refunds.create",
7593
+ "refunds.retrieve",
7594
+ "refunds.list",
7595
+ "charges.retrieve",
7596
+ "charges.list",
7597
+ "events.retrieve",
7598
+ "events.list",
7599
+ "subscriptionItems.retrieve",
7600
+ "subscriptionItems.update"
7601
+ ];
6789
7602
  CONTRACTS = {
6790
7603
  composio: {
6791
7604
  version: "1.0.0",
@@ -6838,9 +7651,11 @@ var init_contracts = __esm({
6838
7651
  { method: "POST", endpoint: "/v1/refunds", effect: "refund all or part of a charge; updates amount_refunded and records charge.refunded", parameters: ["charge", "payment_intent", "amount", "reason", "metadata"], errors: ["400 resource_missing", "400 charge_not_refundable", "400 charge_already_refunded", "400 amount_too_large"] },
6839
7652
  { method: "GET", endpoint: "/v1/refunds[/<id>]", effect: "retrieve or list refunds", parameters: ["limit", "starting_after", "charge", "payment_intent"], errors: ["404 resource_missing"] },
6840
7653
  { method: "GET", endpoint: "/v1/charges[/<id>]", effect: "retrieve or list charges", parameters: ["limit"], errors: ["404 resource_missing"] },
6841
- { method: "GET", endpoint: "/v1/events[/<id>]", effect: "retrieve or list recorded charge.refunded events", parameters: ["limit", "type"], errors: ["404 resource_missing"] }
7654
+ { method: "GET", endpoint: "/v1/events[/<id>]", effect: "retrieve or list recorded charge.refunded events", parameters: ["limit", "type"], errors: ["404 resource_missing"] },
7655
+ { method: "GET", endpoint: "/v1/subscription_items/<id>", effect: "retrieve a seeded subscription item", parameters: [], errors: ["404 resource_missing"] },
7656
+ { method: "POST", endpoint: "/v1/subscription_items/<id>", effect: "update the quantity on a seeded subscription item", parameters: ["quantity"], errors: ["400 invalid quantity", "404 resource_missing"] }
6842
7657
  ],
6843
- limitations: ["Bounded subset, not full Stripe parity; minimal object fields only; no real money", "Only pm_card_visa and pm_card_chargeDeclined test methods", "Events are recorded and listable but webhooks are not pushed to your application", "No subscriptions, payment-method APIs, refund cancellation, updates or deletes", "Customers list supports limit/starting_after; payment intent listing unsupported", "POST idempotency supported; reset clears records and keys; unsupported operations/parameters return 501 and make coverage incomplete"]
7658
+ limitations: ["Bounded subset, not full Stripe parity; minimal object fields only; no real money", "Only pm_card_visa and pm_card_chargeDeclined test methods", "Events are recorded and listable but webhooks are not pushed to your application", "No subscription lifecycle, proration, payment-method APIs, refund cancellation or deletes", "Customers list supports limit/starting_after; payment intent listing unsupported", "POST idempotency supported; reset clears records and keys; unsupported operations/parameters return 501 and make coverage incomplete"]
6844
7659
  },
6845
7660
  slack: {
6846
7661
  version: "1.0.0",
@@ -6850,7 +7665,7 @@ var init_contracts = __esm({
6850
7665
  { method: "GET|POST", endpoint: "/api/conversations.history", effect: "read /messages", parameters: ["channel"], errors: ["channel_not_found"] },
6851
7666
  { method: "GET|POST", endpoint: "/api/conversations.list", effect: "read /channels", parameters: [], errors: [] }
6852
7667
  ],
6853
- limitations: ["JSON and form bodies only", "No OAuth, scopes, pagination, threads, edits, deletes, attachments or webhooks", "Errors channel_not_found/no_text use HTTP 200 with ok:false", "Unmodeled parameters and operations return HTTP 501 and make coverage incomplete"]
7668
+ limitations: ["JSON and form bodies only", "User-ID posts require a seeded user in /users (dmAllowed can disable DMs) or a seeded DM in /channels with is_im and user; the run token represents one bot", "No OAuth, scopes, pagination, threads, edits, deletes, attachments or webhooks", "Errors channel_not_found/no_text use HTTP 200 with ok:false", "Unmodeled parameters and operations return HTTP 501 and make coverage incomplete"]
6854
7669
  },
6855
7670
  github: {
6856
7671
  version: "1.0.0",
@@ -6949,6 +7764,8 @@ var init_contracts = __esm({
6949
7764
  { method: "GET", endpoint: "/gmail/v1/users/me/messages", effect: "list message ids with a snippet q filter", parameters: ["q"], errors: ["400 validation"] },
6950
7765
  { method: "GET", endpoint: "/gmail/v1/users/me/messages/<id>", effect: "retrieve message", parameters: [], errors: ["404 NOT_FOUND"] },
6951
7766
  { method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] },
7767
+ { method: "POST", endpoint: "/gmail/v1/users/me/labels", effect: "create a user label", parameters: ["name", "labelListVisibility", "messageListVisibility", "color"], errors: ["400 invalid name", "409 name exists"] },
7768
+ { method: "POST", endpoint: "/gmail/v1/users/me/{messages|threads}/<id>/modify", effect: "add and remove labels on a message or every message of a thread; bumps the mailbox historyId", parameters: ["addLabelIds", "removeLabelIds"], errors: ["400 Invalid label", "404 not found"] },
6952
7769
  { method: "GET", endpoint: "/gmail/v1/users/me/threads", effect: "list threads, newest first, excluding SPAM/TRASH", parameters: ["q (from:/to: address terms, OR-joined)", "maxResults", "labelIds"], errors: ["400 validation"] },
6953
7770
  { method: "GET", endpoint: "/gmail/v1/users/me/threads/<id>", effect: "retrieve a thread with its messages, oldest first", parameters: ["format=full"], errors: ["404 NOT_FOUND"] },
6954
7771
  { method: "GET", endpoint: "/gmail/v1/users/me/history", effect: "messagesAdded records for messages whose historyId is after startHistoryId", parameters: ["startHistoryId", "historyTypes", "maxResults"], errors: ["400 validation"] },
@@ -6966,7 +7783,7 @@ var init_contracts = __esm({
6966
7783
  { method: "POST", endpoint: "/gmail/v1/users/me/drafts/send", effect: "send a draft: its message becomes SENT in the same thread and the draft is removed", parameters: ["id", "message.raw", "message.threadId (same thread only)"], errors: ["400 missing id, invalid MIME or no recipient", "404 unknown draft"] },
6967
7784
  { method: "POST", endpoint: "/batch/gmail/v1", effect: "multipart batch of up to 100 body-less GET messages/<id> or threads/<id> requests", parameters: ["multipart/mixed body"], errors: ["400 malformed batch"] }
6968
7785
  ],
6969
- limitations: ["Bounded Gmail v1 subset: send, messages list/get, labels, threads list/get, sendAs list, drafts create/list/get/update/delete/send (JSON and media upload), history list, messages insert, watch/stop with loopback Pub/Sub push and read-only batch", "Send parses plain-text MIME only; drafts accept folded/UTF-8 encoded headers, quoted-printable/base64 bodies and text or multipart/alternative text+html, without attachments", "Thread search supports only from:/to: address terms; no pageToken or history paging, label-change history, modify or trash; Pub/Sub push is delivered once with no retry, ack deadline or ordering guarantees, and only to loopback endpoints", "Draft records add flat threadId, to, subject, inReplyTo and references evidence fields for assertions", "Unknown fields and operations return 501 and make coverage incomplete"]
7786
+ limitations: ["Bounded Gmail v1 subset: send, messages list/get, labels, threads list/get, sendAs list, drafts create/list/get/update/delete/send (JSON and media upload), history list, messages insert, watch/stop with loopback Pub/Sub push and read-only batch", "Sends and drafts accept folded/UTF-8 encoded headers, quoted-printable/base64 bodies and text or multipart/alternative text+html, without attachments", "Thread search supports only from:/to: address terms; no pageToken or history paging, label-change history, modify or trash; Pub/Sub push is delivered once with no retry, ack deadline or ordering guarantees, and only to loopback endpoints", "Draft records add flat threadId, to, subject, inReplyTo and references evidence fields for assertions", "Unknown fields and operations return 501 and make coverage incomplete"]
6970
7787
  },
6971
7788
  "upstash-redis": {
6972
7789
  version: "1.0.0",
@@ -7065,7 +7882,7 @@ var init_contracts = __esm({
7065
7882
  });
7066
7883
 
7067
7884
  // src/runtime/cost-model.ts
7068
- import { readFile as readFile5, writeFile as writeFile6 } from "fs/promises";
7885
+ import { readFile as readFile5, writeFile as writeFile7 } from "fs/promises";
7069
7886
  import { join as join12 } from "path";
7070
7887
  async function readCostConfig(cwd) {
7071
7888
  try {
@@ -7201,7 +8018,7 @@ function incidentFor(receipt, a) {
7201
8018
  const kind = /refunds$/.test(a.path) ? "duplicate-refund" : /payouts$|transfers$/.test(a.path) ? "duplicate-payout" : /charges$|payment_intents$|invoices$|orders$|payments$/.test(a.path) ? "duplicate-charge" : /slack|gmail|resend|sendgrid|postmark|mailgun|twilio|email|sms/i.test(a.service) || /\/(messages|emails|mail|sms)\b/.test(a.path) ? "duplicate-message" : "duplicate-record";
7202
8019
  return { kind, extra, ...money2 ? { money: money2 } : {}, service: a.service };
7203
8020
  }
7204
- function describe(a) {
8021
+ function describe(a, incomplete) {
7205
8022
  const what = `${serviceName(a.service)} ${recordName(a.path)}${filterText(a.where)}`;
7206
8023
  if (a.passed) return `${what}: ${a.actual ?? a.count} as expected`;
7207
8024
  if (a.absent || a.count === 0) return `${what}: expected none, found ${a.actual}`;
@@ -7209,29 +8026,37 @@ function describe(a) {
7209
8026
  const times3 = a.count === 1 && a.actual === 2 ? "the same write happened twice" : `${a.actual - a.count} more than allowed`;
7210
8027
  return `${what}: expected ${a.count}, found ${a.actual} (${times3})`;
7211
8028
  }
7212
- if (a.actual === 0) return `${what}: expected ${a.count}, found none (the write never happened)`;
8029
+ if (a.actual === 0) return `${what}: expected ${a.count}, found none${incomplete ? "" : " (the write never happened)"}`;
7213
8030
  return `${what}: expected ${a.count}, found ${a.actual}`;
7214
8031
  }
7215
8032
  function explainRun(receipt, costs) {
7216
8033
  const checks = receipt.assertions ?? [];
7217
8034
  const failed = checks.filter((a) => !a.passed);
7218
- const cost = estimateCost(failed.map((a) => incidentFor(receipt, a)), costs, { title: receipt.name });
8035
+ const unsupported2 = receipt.unsupported ?? [];
8036
+ const coverageGap = receipt.status === "incomplete" && unsupported2.length > 0;
8037
+ const duplicates = failed.filter((a) => (a.actual ?? 0) > (a.count ?? Infinity));
8038
+ const cost = estimateCost((coverageGap ? duplicates : failed).map((a) => incidentFor(receipt, a)), costs, { title: receipt.name });
7219
8039
  const money2 = failed.map((a) => extraMoney(receipt, a)).filter((m) => !!m);
7220
8040
  const atRisk = money2.length ? { amount: Math.max(...money2.map((m) => m.amount)), currency: money2[0].currency } : void 0;
7221
8041
  const moneyVerb = failed.some((a) => /refunds$/.test(a.path) && extraMoney(receipt, a)) ? "refunded" : failed.some((a) => /payouts$|transfers$/.test(a.path) && extraMoney(receipt, a)) ? "paid out" : "charged";
7222
8042
  const fault = receipt.fault?.triggered ? `${serviceName(receipt.fault.service ?? "")} ${recordName(receipt.fault.path ?? "")}: ${FAULT[receipt.fault.type ?? ""] ?? receipt.fault.type}` : void 0;
7223
- const duplicate = failed.some((a) => (a.actual ?? 0) > (a.count ?? Infinity));
8043
+ const duplicate = duplicates.length > 0;
7224
8044
  let cause;
7225
- if (duplicate && receipt.fault?.type === "timeout-after-write") cause = "Your code retried after the lost reply without an idempotency key, so the service applied the write a second time.";
8045
+ const lostReply = receipt.fault?.type === "timeout-after-write" && receipt.fault.triggered !== false && duplicates.some((a) => (!receipt.fault?.service || a.service === receipt.fault.service) && (!receipt.fault?.path || a.path === receipt.fault.path));
8046
+ if (lostReply) cause = "Your code retried after the lost reply without an idempotency key, so the service applied the write a second time.";
7226
8047
  else if (duplicate) cause = "Your code repeated a write that should happen once.";
7227
8048
  else if (failed.some((a) => a.actual === 0)) cause = "An expected write never reached the service.";
7228
- if (receipt.executionError) cause = receipt.executionError;
8049
+ if (coverageGap) {
8050
+ const first = unsupported2[0];
8051
+ const gap = typeof first === "string" ? `Unsupported twin operation: ${first}` : "A twin operation was unsupported.";
8052
+ cause = duplicate ? `${cause} ${gap}` : gap;
8053
+ } else if (receipt.executionError) cause = receipt.executionError;
7229
8054
  else if (receipt.application?.timedOut) cause = "The application did not finish before the time limit.";
7230
8055
  const clip = (text3) => text3.length > 80 ? text3.slice(0, 77) + "..." : text3;
7231
8056
  const infra = (receipt.infrastructureAssertions ?? []).map((a) => ({ passed: a.passed, text: a.service === "redis" ? `Redis key ${a.key}: ${a.passed ? "as expected" : `expected ${JSON.stringify(a.expected)}, found ${JSON.stringify(a.actual)}`}` : `PostgreSQL ${clip(a.query ?? "")}: ${a.passed ? "rows as expected" : `expected ${clip(JSON.stringify(a.expected))}, found ${clip(JSON.stringify(a.actual))}`}` }));
7232
8057
  const total = checks.length + infra.length, passedCount = total - failed.length - infra.filter((c) => !c.passed).length;
7233
8058
  const headline = receipt.status === "passed" ? `PASSED: ${receipt.name} (${total}/${total} checks)` : `${receipt.status.toUpperCase()}: ${receipt.name} (${passedCount}/${total} checks passed${atRisk ? `, ${formatMoney(atRisk)} ${moneyVerb} twice` : ""})`;
7234
- return { headline, cause, fault, atRisk, ...cost ? { cost } : {}, checks: [...checks.map((a) => ({ passed: a.passed, text: describe(a) })), ...infra], unsupported: receipt.unsupported?.length ?? 0 };
8059
+ return { headline, cause, fault, atRisk, ...cost ? { cost } : {}, checks: [...checks.map((a) => ({ passed: a.passed, text: describe(a, coverageGap) })), ...infra], unsupported: receipt.unsupported?.length ?? 0 };
7235
8060
  }
7236
8061
  function renderRunSummary(receipt, opts = {}) {
7237
8062
  const e = explainRun(receipt, opts.costs);
@@ -7246,7 +8071,7 @@ function renderRunSummary(receipt, opts = {}) {
7246
8071
  const builtIn = receipt.defaultChecks ?? [];
7247
8072
  if (builtIn.length) lines.push(bullet(`Built-in checks: ${builtIn.filter((c) => c.passed).length}/${builtIn.length} held`));
7248
8073
  for (const c of builtIn.filter((c2) => !c2.passed)) lines.push(bullet(`FINDING ${c.finding}${c.impact?.summary ? ` (impact: ${c.impact.summary})` : ""}`));
7249
- if (e.unsupported) lines.push("", bullet(`${e.unsupported} call(s) hit unsupported operations (returned 501, never forwarded).`));
8074
+ if (e.unsupported) lines.push("", bullet(`${e.unsupported} call(s) hit unsupported operations and were never forwarded.`));
7250
8075
  if (opts.next?.length) lines.push("", opts.markdown ? "## Next" : "Next:", ...opts.next.map((n) => bullet(n)));
7251
8076
  return lines.join("\n") + "\n";
7252
8077
  }
@@ -7273,7 +8098,7 @@ var init_run_summary = __esm({
7273
8098
  });
7274
8099
 
7275
8100
  // src/runtime/generic-calls.ts
7276
- import { createHash as createHash10 } from "crypto";
8101
+ import { createHash as createHash11 } from "crypto";
7277
8102
  function canonical2(value) {
7278
8103
  return Array.isArray(value) ? `[${value.map(canonical2).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical2(value[k])}`).join(",")}}` : JSON.stringify(value ?? null);
7279
8104
  }
@@ -7559,7 +8384,7 @@ var init_generic_calls = __esm({
7559
8384
  VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
7560
8385
  KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
7561
8386
  KEY_FIELDS = /^(idempotency_?key|ClientToken|ClientRequestToken|MessageDeduplicationId|client_token|request_id)$/i;
7562
- digest3 = (value) => `sha256:${createHash10("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
8387
+ digest3 = (value) => `sha256:${createHash11("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
7563
8388
  stable = (value) => Array.isArray(value) ? value.map(stable) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).filter(([k]) => !VOLATILE.test(k) && !KEY_FIELDS.test(k)).map(([k, v]) => [k, stable(v)])) : value;
7564
8389
  idLike = (segment) => /^\d+$/.test(segment) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment) || segment.length >= 3 && /\d/.test(segment) && /^[A-Za-z0-9_\-:.]+$/.test(segment) && !/^v\d+(\.\d+)*$/i.test(segment) && !/^\d{4}-\d{2}-\d{2}$/.test(segment) && !/^[A-Za-z]+\.(json|xml)$/.test(segment);
7565
8390
  outcomeOf = (status) => status === void 0 ? "ok" : status === 401 || status === 403 ? "unauthorized" : status === 429 ? "rate-limited" : status >= 500 ? "server-error" : status >= 400 ? "client-error" : "ok";
@@ -7612,7 +8437,7 @@ var init_generic_calls = __esm({
7612
8437
 
7613
8438
  // src/runtime/default-checks.ts
7614
8439
  function addedRows(initial, final) {
7615
- const rows2 = (list2) => list2.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
8440
+ const rows2 = (list3) => list3.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
7616
8441
  const ids = new Set(rows2(initial).map((r) => r.id).filter((id) => id !== void 0 && id !== null));
7617
8442
  const seen = /* @__PURE__ */ new Map();
7618
8443
  for (const r of rows2(initial)) if (r.id === void 0) seen.set(canonical3(r), (seen.get(canonical3(r)) ?? 0) + 1);
@@ -7776,7 +8601,7 @@ var init_default_checks = __esm({
7776
8601
  };
7777
8602
  stripeNoDuplicatePayment = {
7778
8603
  id: "stripe.no-duplicate-payment",
7779
- title: "No duplicate charges or customers for one request",
8604
+ title: "No duplicate charges, customers or subscriptions for one request",
7780
8605
  path: "/v1/payment_intents",
7781
8606
  coversDuplicates: true,
7782
8607
  expected: "one payment intent per amount/currency/customer/payment method and one customer per email",
@@ -7795,6 +8620,19 @@ var init_default_checks = __esm({
7795
8620
  evidence: writeSequences(ctx, s, group.map((r) => r.id))
7796
8621
  });
7797
8622
  }
8623
+ const subscriptions = addedRows(rowsOf(ctx.initialState, s, "/v1/subscriptions"), rowsOf(ctx.finalState, s, "/v1/subscriptions")).filter((r) => !["canceled", "incomplete_expired"].includes(String(r.status)));
8624
+ const itemsOf = (r) => (r.items?.data ?? []).map((i) => ({ price: typeof i.price === "object" && i.price ? i.price : { id: i.price }, quantity: Number(i.quantity ?? 1) }));
8625
+ for (const group of groups(subscriptions, (r) => typeof r.customer === "string" && itemsOf(r).length ? canonical3({ customer: r.customer, prices: itemsOf(r).map((i) => `${String(i.price.id)}x${i.quantity}`).sort() }) : void 0)) {
8626
+ const items = itemsOf(group[0]), currency = String(items[0]?.price.currency ?? group[0].currency ?? "usd");
8627
+ const perPeriod = items.reduce((n, i) => n + (typeof i.price.unit_amount === "number" ? i.price.unit_amount * i.quantity : 0), 0);
8628
+ out.push({
8629
+ path: "/v1/subscriptions",
8630
+ actual: { subscriptions: group.map((r) => r.id), customer: group[0].customer },
8631
+ finding: `Your agent subscribed ${String(group[0].customer)} ${times2(group.length)} to the same plan${faultPhrase(ctx)}`,
8632
+ impact: perPeriod > 0 ? { amount: perPeriod * (group.length - 1), currency, count: group.length - 1, summary: `billed ${money(perPeriod, currency)} extra every billing period` } : { kind: "data-integrity", count: group.length - 1 },
8633
+ evidence: writeSequences(ctx, s, group.map((r) => r.id))
8634
+ });
8635
+ }
7798
8636
  const customers = addedRows(rowsOf(ctx.initialState, s, "/v1/customers"), rowsOf(ctx.finalState, s, "/v1/customers"));
7799
8637
  for (const group of groups(customers, (r) => typeof r.email === "string" && r.email ? r.email.toLowerCase() : void 0))
7800
8638
  out.push({
@@ -7921,14 +8759,14 @@ var init_default_checks = __esm({
7921
8759
  };
7922
8760
  VENDOR_COVERS = { "retry-without-key": /\.idempotent-retries$/, "announce-after-failed-write": /\.announce-after-success$/ };
7923
8761
  DEFAULT_CHECKS["*"].push(...genericWorldChecks((adapter, rule) => !!VENDOR_COVERS[rule] && registryFor(adapter).some((c) => VENDOR_COVERS[rule].test(c.id))));
7924
- registryFor = (adapter) => DEFAULT_CHECKS[adapter ?? "json-collection"] ?? [];
8762
+ registryFor = (adapter) => DEFAULT_CHECKS[adapter ?? "json-collection"] ?? (adapter?.startsWith("pack:") ? DEFAULT_CHECKS[adapter.slice(5)] : void 0) ?? [];
7925
8763
  refOf = (s) => typeof s === "string" ? { name: s, adapter: s } : s;
7926
8764
  }
7927
8765
  });
7928
8766
 
7929
8767
  // src/runtime/twin-proxy.ts
7930
8768
  import { execFile as execFile5 } from "child_process";
7931
- import { mkdtemp as mkdtemp6, readFile as readFile6, rm as rm6, writeFile as writeFile7 } from "fs/promises";
8769
+ import { mkdtemp as mkdtemp6, readFile as readFile6, rm as rm6, writeFile as writeFile8 } from "fs/promises";
7932
8770
  import { createServer as createServer4, request as httpRequest } from "http";
7933
8771
  import { tmpdir as tmpdir6 } from "os";
7934
8772
  import { join as join13 } from "path";
@@ -7988,7 +8826,7 @@ async function runAuthority(dir) {
7988
8826
  if (!ctx) {
7989
8827
  ctx = (async () => {
7990
8828
  const base = join13(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
7991
- await writeFile7(base + ".ext", `basicConstraints=critical,CA:FALSE
8829
+ await writeFile8(base + ".ext", `basicConstraints=critical,CA:FALSE
7992
8830
  keyUsage=critical,digitalSignature
7993
8831
  extendedKeyUsage=serverAuth
7994
8832
  subjectAltName=DNS:${host}
@@ -8027,6 +8865,7 @@ async function startTwinProxy(routes2) {
8027
8865
  const headers = {};
8028
8866
  const strip = route.auth === "passthrough" ? ["host", "proxy-connection", "proxy-authorization"] : SECRET;
8029
8867
  for (const [k, v] of Object.entries(req.headers)) if (v !== void 0 && !strip.includes(k)) headers[k] = v;
8868
+ if (route.appCredential && typeof req.headers.authorization === "string" && /^Bearer \S{12,}$/.test(req.headers.authorization)) headers["x-agenttwin-app-authorization"] = req.headers.authorization;
8030
8869
  if (route.auth === "passthrough") headers["x-agenttwin-token"] = route.token;
8031
8870
  else if (route.auth === "x-api-key") headers["x-api-key"] = route.token;
8032
8871
  else headers.authorization = `Bearer ${route.token}`;
@@ -8122,7 +8961,7 @@ var init_twin_proxy = __esm({
8122
8961
  });
8123
8962
 
8124
8963
  // src/runtime/twin-routing.ts
8125
- import { mkdtemp as mkdtemp7, readFile as readFile7, rm as rm7, writeFile as writeFile8 } from "fs/promises";
8964
+ import { mkdtemp as mkdtemp7, readFile as readFile7, rm as rm7, writeFile as writeFile9 } from "fs/promises";
8126
8965
  import { tmpdir as tmpdir7 } from "os";
8127
8966
  import { join as join14 } from "path";
8128
8967
  function twinRoutes(services, world, models) {
@@ -8131,10 +8970,11 @@ function twinRoutes(services, world, models) {
8131
8970
  const adapter = service.adapter ?? "", credential = world.credentials[service.name];
8132
8971
  if (credential && isPackAdapter(adapter)) {
8133
8972
  const record4 = packRecord(adapter.slice(PACK_PREFIX.length));
8134
- const auth = record4.credentialDoor ? "bearer" : "passthrough";
8973
+ const issuesKey = !!record4.credentialDoor && Object.values(record4.credentialDoor.fill ?? {}).some((field) => !String(field).startsWith("file:"));
8974
+ const auth = issuesKey ? "bearer" : "passthrough";
8135
8975
  for (const h of record4.hosts) {
8136
8976
  const host = h.host ?? `pattern:${h.hostPattern}`;
8137
- if (!routes2.some((r) => r.host === host && !r.pathPrefix)) routes2.push({ host, ...h.suffix ? { suffix: true } : {}, ...h.hostPattern && !h.host ? { hostPattern: h.hostPattern } : {}, target: credential.endpoint, token: credential.token, auth, service: service.name });
8977
+ if (!routes2.some((r) => r.host === host && !r.pathPrefix)) routes2.push({ host, ...h.suffix ? { suffix: true } : {}, ...h.hostPattern && !h.host ? { hostPattern: h.hostPattern } : {}, target: credential.endpoint, token: credential.token, auth, service: service.name, ...auth === "bearer" ? { appCredential: true } : {} });
8138
8978
  }
8139
8979
  continue;
8140
8980
  }
@@ -8148,6 +8988,7 @@ var PROVIDER_HOSTS, TWIN_PRELOAD;
8148
8988
  var init_twin_routing = __esm({
8149
8989
  "src/runtime/twin-routing.ts"() {
8150
8990
  "use strict";
8991
+ init_node_options();
8151
8992
  init_packs();
8152
8993
  PROVIDER_HOSTS = {
8153
8994
  // OpenAI-compatible APIs answer in the same format, so they are served by the OpenAI twin (with its scripted tool calls).
@@ -8202,9 +9043,13 @@ if(originalFetch)globalThis.fetch=async function(input,init){
8202
9043
  if(!r)throw blocked('fetch',url.hostname,url.port||(url.protocol==='https:'?443:80),method);
8203
9044
  if(process.env.AGENTTWIN_DEBUG_ROUTES)console.error('route-match '+url.hostname+' auth='+r.auth+' service='+r.service);
8204
9045
  const request=new Request(input,init),headers=new Headers(request.headers);
9046
+ {const own=headers.get('authorization');if(r.appCredential&&own&&/^Bearer \S{12,}$/.test(own))headers.set('x-agenttwin-app-authorization',own);}
8205
9047
  for(const name of removed(r))headers.delete(name);const [name,value]=credential(r);headers.set(name,value);
8206
9048
  headers.set('x-agenttwin-original-host',url.hostname);const location=source();if(location)headers.set('x-agenttwin-source',location);
8207
- return originalFetch(new Request(r.target+rewrite(r,url.pathname)+url.search,request),{headers,redirect:'manual'});
9049
+ // Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch (Upstash's
9050
+ // client sets keepalive on every call).
9051
+ const body=request.body===null?undefined:Buffer.from(await request.arrayBuffer());
9052
+ return originalFetch(r.target+rewrite(r,url.pathname)+url.search,{method:request.method,headers,...(body===undefined?{}:{body}),redirect:'manual',signal:request.signal});
8208
9053
  };
8209
9054
  const originalHttpRequest=http.request;
8210
9055
  for(const [mod,scheme] of [[http,'http'],[https,'https']]){
@@ -8223,6 +9068,8 @@ for(const [mod,scheme] of [[http,'http'],[https,'https']]){
8223
9068
  const target=new URL(r.target),headers={};
8224
9069
  const given=options.headers||{};
8225
9070
  for(const [k,v] of Array.isArray(given)?[]:Object.entries(given))if(!removed(r).includes(k.toLowerCase()))headers[k]=v;
9071
+ // The app's own credential travels beside the run token: a pack host keeps it when the twin issued it (an app-level token).
9072
+ if(r.appCredential){const own=Array.isArray(given)?undefined:Object.entries(given).find(([k])=>k.toLowerCase()==='authorization')?.[1];if(typeof own==='string'&&/^Bearer \S{12,}$/.test(own))headers['x-agenttwin-app-authorization']=own;}
8226
9073
  const [name,value]=credential(r);headers[name]=value;headers.host=target.host;headers['x-agenttwin-original-host']=host;
8227
9074
  const location=source();if(location)headers['x-agenttwin-source']=location;
8228
9075
  const {agent,agents,host:_h,hostname:_hn,port:_p,protocol:_pr,servername:_s,ca,cert,key,pfx,passphrase,ciphers,rejectUnauthorized,checkServerIdentity,lookup,family,localAddress,createConnection,auth,...rest}=options;
@@ -8303,6 +9150,36 @@ function sqlTables(sql) {
8303
9150
  }
8304
9151
  return [...out];
8305
9152
  }
9153
+ function bindValues(body2) {
9154
+ try {
9155
+ let at = body2.indexOf(0) + 1;
9156
+ at = body2.indexOf(0, at) + 1;
9157
+ const formats2 = body2.readInt16BE(at);
9158
+ at += 2;
9159
+ const codes = [];
9160
+ for (let i = 0; i < formats2; i++) {
9161
+ codes.push(body2.readInt16BE(at));
9162
+ at += 2;
9163
+ }
9164
+ const count = body2.readInt16BE(at);
9165
+ at += 2;
9166
+ const values = [];
9167
+ for (let i = 0; i < count; i++) {
9168
+ const len = body2.readInt32BE(at);
9169
+ at += 4;
9170
+ if (len < 0) {
9171
+ values.push(null);
9172
+ continue;
9173
+ }
9174
+ const binary = (codes.length === 1 ? codes[0] : codes[i] ?? 0) === 1;
9175
+ values.push(binary ? null : body2.toString("utf8", at, at + len));
9176
+ at += len;
9177
+ }
9178
+ return values;
9179
+ } catch {
9180
+ return [];
9181
+ }
9182
+ }
8306
9183
  async function startPostgresEngine(options = {}) {
8307
9184
  const started = Date.now();
8308
9185
  let PGlite;
@@ -8370,7 +9247,7 @@ async function startPostgresEngine(options = {}) {
8370
9247
  if (name) {
8371
9248
  conn.names.set(name, sql);
8372
9249
  conn.statements.add(ns(name));
8373
- }
9250
+ } else conn.unnamed = sql;
8374
9251
  return { body: Buffer.concat([cstr(ns(name)), body2.subarray(end + 1)]), sql };
8375
9252
  }
8376
9253
  if (type === "B") {
@@ -8425,7 +9302,13 @@ async function startPostgresEngine(options = {}) {
8425
9302
  for (const m of prepared) outputs.push(await raw(msg(m.type, m.body)));
8426
9303
  const out = Buffer.concat(outputs), { tags, status, failed } = scan(out);
8427
9304
  for (const t of writeTables) conn.txnTables.add(t);
8428
- if (sqls.length && !writes.length && tables2.length) record(events, { engine: "postgres", operation: "read", resource: tables2.join(","), detail: tags.join("; ").slice(0, 200) });
9305
+ const binds = batch.filter((m) => m.type === "B").map((m) => {
9306
+ const pEnd = m.body.indexOf(0), sEnd = m.body.indexOf(0, pEnd + 1), stmt = m.body.toString("utf8", pEnd + 1, sEnd);
9307
+ return { sql: stmt ? conn.names.get(stmt) : conn.unnamed, params: bindValues(m.body) };
9308
+ });
9309
+ const readSql = sqls.length ? sqls : binds.flatMap((b) => b.sql && !isWriteSql(b.sql) ? [b.sql] : []);
9310
+ const readTables2 = [...new Set(readSql.flatMap(sqlTables))];
9311
+ if (readSql.length && !writes.length && readTables2.length) record(events, { engine: "postgres", operation: "read", resource: readTables2.join(","), detail: tags.join("; ").slice(0, 200), record: { sql: readSql.join("; ").slice(0, 2e3), params: binds.flatMap((b) => b.params).slice(0, 40), rows: tags.reduce((n, t) => n + (Number(/^SELECT (\d+)$/.exec(t)?.[1]) || 0), 0), complete: tags.some((t) => /^SELECT \d+$/.test(t)) } });
8429
9312
  owner = status === "I" ? null : conn;
8430
9313
  let committed = [];
8431
9314
  if (status === "I") {
@@ -8619,7 +9502,9 @@ async function startPostgresEngine(options = {}) {
8619
9502
  }
8620
9503
  };
8621
9504
  const seed = async (data) => direct(async () => {
8622
- if (data.sql) await db.exec(data.sql);
9505
+ if (data.sql) {
9506
+ for (const part of data.sql.split(/^(?=-- Schema source: )/m)) if (part.trim()) await db.exec(part);
9507
+ }
8623
9508
  for (const [table2, rows2] of Object.entries(data.tables ?? {})) {
8624
9509
  for (const row of rows2) {
8625
9510
  const fields = Object.keys(row);
@@ -8911,13 +9796,13 @@ var init_server_steps = __esm({
8911
9796
 
8912
9797
  // src/runtime/local.ts
8913
9798
  import { spawn as spawn2 } from "child_process";
8914
- import { realpath as realpath2 } from "fs/promises";
9799
+ import { realpath as realpath3 } from "fs/promises";
8915
9800
  import { dirname as dirname2, resolve as resolve4 } from "path";
8916
9801
  async function sourceRoot(app, spec) {
8917
- const real = await realpath2(app);
9802
+ const real = await realpath3(app);
8918
9803
  if (!spec.directory) return real;
8919
9804
  for (let candidate = real; ; candidate = dirname2(candidate)) {
8920
- if (await realpath2(resolve4(candidate, spec.directory)).then((p) => p === real, () => false)) return candidate;
9805
+ if (await realpath3(resolve4(candidate, spec.directory)).then((p) => p === real, () => false)) return candidate;
8921
9806
  if (dirname2(candidate) === candidate) return real;
8922
9807
  }
8923
9808
  }
@@ -8936,10 +9821,11 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
8936
9821
  }
8937
9822
  engines = await startLocalEngines(filesDir, spec);
8938
9823
  Object.assign(env, engines.env);
9824
+ if (engines.env.DATABASE_URL) world.attachDatabase(engines.env.DATABASE_URL);
8939
9825
  let stdout = "", stderr = "", timedOut = false;
8940
9826
  const node = /(^|\/)node(\.exe)?$/.test(spec.command[0]);
8941
9827
  const hook = await createRequestSourceHook(await sourceRoot(app, spec), spec, credentials2);
8942
- if (node) env.NODE_OPTIONS = [extraEnv.NODE_OPTIONS, `--require ${JSON.stringify(hook.path)}`].filter(Boolean).join(" ");
9828
+ if (node) env.NODE_OPTIONS = await singlePreload(extraEnv.NODE_OPTIONS ?? "", hook.path);
8943
9829
  let proxy;
8944
9830
  if (!node) {
8945
9831
  const configured = extraEnv.AGENTTWIN_ROUTES ? JSON.parse(extraEnv.AGENTTWIN_ROUTES).routes : void 0;
@@ -9062,6 +9948,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
9062
9948
  var init_local = __esm({
9063
9949
  "src/runtime/local.ts"() {
9064
9950
  "use strict";
9951
+ init_node_options();
9065
9952
  init_application_process();
9066
9953
  init_browser_process();
9067
9954
  init_twin_clock();
@@ -9546,7 +10433,7 @@ var init_offline = __esm({
9546
10433
  // src/runtime/credentials.ts
9547
10434
  import { homedir } from "os";
9548
10435
  import { join as join17 } from "path";
9549
- import { readFile as readFile9, mkdir as mkdir4, writeFile as writeFile9, chmod as chmod2, rm as rm9 } from "fs/promises";
10436
+ import { readFile as readFile9, mkdir as mkdir4, writeFile as writeFile10, chmod as chmod2, rm as rm9 } from "fs/promises";
9550
10437
  async function savedConnection() {
9551
10438
  try {
9552
10439
  const data = JSON.parse(await readFile9(path(), "utf8"));
@@ -9693,7 +10580,7 @@ var init_hosted_packs = __esm({
9693
10580
  });
9694
10581
 
9695
10582
  // src/runtime/e2b.ts
9696
- import { createRequire } from "module";
10583
+ import { createRequire as createRequire2 } from "module";
9697
10584
  import { readFile as readFile12 } from "fs/promises";
9698
10585
  import { randomBytes as randomBytes4 } from "crypto";
9699
10586
  import { homedir as homedir2 } from "os";
@@ -9771,7 +10658,7 @@ logfile /tmp/agenttwin-redis.log
9771
10658
  }
9772
10659
  await sandbox.files.write("/input/runtime.json", JSON.stringify(runtimeEnv), { user: "root" });
9773
10660
  await sandbox.commands.run("chmod -R a+rX /input", { user: "root" });
9774
- const playwrightVersion = createRequire(import.meta.url)("playwright/package.json").version;
10661
+ const playwrightVersion = createRequire2(import.meta.url)("playwright/package.json").version;
9775
10662
  await sandbox.files.write("/input/check-runtime.cjs", `const p=require('playwright/package.json');if(p.version!==${JSON.stringify(playwrightVersion)})throw Error('E2B template needs rebuilding with agenttwin setup: Playwright version mismatch');`, { user: "root" });
9776
10663
  await sandbox.commands.run("node /input/check-runtime.cjs", { user: "root" });
9777
10664
  if (spec.browser) {
@@ -9811,12 +10698,12 @@ var init_e2b = __esm({
9811
10698
  });
9812
10699
 
9813
10700
  // src/runtime/matrix.ts
9814
- import { createHash as createHash11 } from "crypto";
9815
- import { mkdir as mkdir5, readFile as readFile13, writeFile as writeFile10 } from "fs/promises";
10701
+ import { createHash as createHash12 } from "crypto";
10702
+ import { mkdir as mkdir5, readFile as readFile13, writeFile as writeFile11 } from "fs/promises";
9816
10703
  import { join as join21, relative, resolve as resolve5 } from "path";
9817
10704
  function filesDigest(sourceDigests) {
9818
10705
  const canonical5 = Object.keys(sourceDigests).sort().map((file) => `${file}:${sourceDigests[file]}`).join("\n");
9819
- return createHash11("sha256").update(canonical5).digest("hex");
10706
+ return createHash12("sha256").update(canonical5).digest("hex");
9820
10707
  }
9821
10708
  function checksOfReceipt(receipt) {
9822
10709
  const checks = (receipt.evaluation?.checks ?? []).map((c) => ({
@@ -9901,7 +10788,7 @@ function buildMatrixReport(input) {
9901
10788
  async function runSeedMatrix(cwd, opts) {
9902
10789
  if (!Number.isInteger(opts.seeds) || opts.seeds < 1 || opts.seeds > MAX_SEEDS) throw new CliError(`--seeds must be an integer between 1 and ${MAX_SEEDS}`, { code: EXIT.USAGE });
9903
10790
  const baseSeed = normalizeSeed(opts.seed);
9904
- const matrixName = `matrix-${createHash11("sha256").update(`${baseSeed}:${opts.seeds}`).digest("hex").slice(0, 8)}`;
10791
+ const matrixName = `matrix-${createHash12("sha256").update(`${baseSeed}:${opts.seeds}`).digest("hex").slice(0, 8)}`;
9905
10792
  const matrixDir = resolve5(cwd, opts.out ?? join21(".agenttwin/runs", matrixName));
9906
10793
  await mkdir5(matrixDir, { recursive: true, mode: 448 });
9907
10794
  const results = [];
@@ -9934,8 +10821,8 @@ async function runSeedMatrix(cwd, opts) {
9934
10821
  });
9935
10822
  const reportPath = resolve5(cwd, opts.out ?? join21(matrixDir, "matrix.json"));
9936
10823
  await mkdir5(opts.out && opts.out.endsWith(".json") ? join21(reportPath, "..") : matrixDir, { recursive: true, mode: 448 });
9937
- await writeFile10(reportPath, JSON.stringify(report, null, 2) + "\n", { mode: 384 });
9938
- await writeFile10(join21(matrixDir, "matrix.md"), `${report.verdict.summary}
10824
+ await writeFile11(reportPath, JSON.stringify(report, null, 2) + "\n", { mode: 384 });
10825
+ await writeFile11(join21(matrixDir, "matrix.md"), `${report.verdict.summary}
9939
10826
 
9940
10827
  Report: ${relative(cwd, reportPath).split("\\").join("/")}
9941
10828
  `);
@@ -9955,8 +10842,8 @@ var init_matrix = __esm({
9955
10842
  });
9956
10843
 
9957
10844
  // src/runtime/source-build.ts
9958
- import { createHash as createHash12 } from "crypto";
9959
- import { lstat, readFile as readFile14, realpath as realpath3 } from "fs/promises";
10845
+ import { createHash as createHash13 } from "crypto";
10846
+ import { lstat, readFile as readFile14, realpath as realpath4 } from "fs/promises";
9960
10847
  import { isAbsolute as isAbsolute2, join as join22, relative as relative2, resolve as resolve6, sep } from "path";
9961
10848
  import { isDeepStrictEqual as isDeepStrictEqual8 } from "util";
9962
10849
  async function checkSourceBuild(directory, spec) {
@@ -9965,7 +10852,7 @@ async function checkSourceBuild(directory, spec) {
9965
10852
  throw new CliError(`Prepared source is stale: ${message}`, { code: EXIT.BLOCKED, action: "Prepare this workflow again from the current repository before running it." });
9966
10853
  };
9967
10854
  try {
9968
- const preparedRoot = await realpath3(directory);
10855
+ const preparedRoot = await realpath4(directory);
9969
10856
  const sidecar = join22(preparedRoot, LOCAL_BUILD_FILE);
9970
10857
  const info = await lstat(sidecar);
9971
10858
  if (!info.isFile() || info.isSymbolicLink() || info.size > 2 * 1024 * 1024) stale("local source record is missing, unsafe or exceeds bounds");
@@ -9977,21 +10864,21 @@ async function checkSourceBuild(directory, spec) {
9977
10864
  if (!build2.sourceDigests || typeof build2.sourceDigests !== "object" || Array.isArray(build2.sourceDigests)) stale("original source hashes are missing");
9978
10865
  const entries = Object.entries(build2.sourceDigests);
9979
10866
  if (!entries.length || entries.length > 1501) stale("original source set exceeds bounds");
9980
- const root = await realpath3(local.sourceRoot);
10867
+ const root = await realpath4(local.sourceRoot);
9981
10868
  let total = 0;
9982
10869
  for (const [file, expected] of entries) {
9983
10870
  if (!sha3(expected) || isAbsolute2(file) || file.includes("\\") || file.split("/").some((part) => !part || part === "." || part === ".." || /^(?:\.env.*|\.git|\.ssh|\.aws|\.azure|\.config|\.npmrc|\.netrc)$/i.test(part) || !file.startsWith("node_modules/") && /^credentials.*/i.test(part)) || !/\.(?:[cm]?[jt]s|tsx|jsx|json)$/.test(file)) stale("original source path is unsafe");
9984
- const path2 = resolve6(root, file), canonical5 = await realpath3(path2);
10871
+ const path2 = resolve6(root, file), canonical5 = await realpath4(path2);
9985
10872
  const rel = relative2(root, canonical5);
9986
10873
  if (path2 !== canonical5 || rel === ".." || rel.startsWith(".." + sep) || isAbsolute2(rel) || !(await lstat(path2)).isFile()) stale(`source moved or uses a symlink: ${file}`);
9987
10874
  const size = (await lstat(path2)).size;
9988
10875
  if (total + size > 30 * 1024 * 1024) stale("original source exceeds bounds");
9989
10876
  const source = await readFile14(path2);
9990
10877
  total += source.length;
9991
- if (total > 30 * 1024 * 1024 || createHash12("sha256").update(source).digest("hex") !== expected) stale(`source changed: ${file}`);
10878
+ if (total > 30 * 1024 * 1024 || createHash13("sha256").update(source).digest("hex") !== expected) stale(`source changed: ${file}`);
9992
10879
  }
9993
10880
  const artifact = join22(preparedRoot, "application.cjs");
9994
- if (!(await lstat(artifact)).isFile() || await realpath3(artifact) !== resolve6(artifact) || (await lstat(artifact)).size > 20 * 1024 * 1024 || createHash12("sha256").update(await readFile14(artifact)).digest("hex") !== build2.bundleDigest) stale("compiled application changed");
10881
+ if (!(await lstat(artifact)).isFile() || await realpath4(artifact) !== resolve6(artifact) || (await lstat(artifact)).size > 20 * 1024 * 1024 || createHash13("sha256").update(await readFile14(artifact)).digest("hex") !== build2.bundleDigest) stale("compiled application changed");
9995
10882
  return { root, digest: spec.sourceBuild };
9996
10883
  } catch (error) {
9997
10884
  if (error instanceof CliError) throw error;
@@ -10004,7 +10891,7 @@ var init_source_build = __esm({
10004
10891
  "use strict";
10005
10892
  init_exit();
10006
10893
  LOCAL_BUILD_FILE = ".agenttwin/source-build.json";
10007
- sourceBuildDigest = (build2) => createHash12("sha256").update(JSON.stringify(build2)).digest("hex");
10894
+ sourceBuildDigest = (build2) => createHash13("sha256").update(JSON.stringify(build2)).digest("hex");
10008
10895
  sha3 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
10009
10896
  }
10010
10897
  });
@@ -10928,6 +11815,94 @@ var init_catalog = __esm({
10928
11815
  }
10929
11816
  });
10930
11817
 
11818
+ // src/inventory/service-coverage.ts
11819
+ function serviceSupport(tool) {
11820
+ const provider = tool.providerId ?? tool.title.toLowerCase();
11821
+ const adapters = ADAPTER_GROUPS[provider] ?? TWIN_ADAPTERS.filter((name) => name === provider);
11822
+ if (adapters.length) return { status: "partial", adapter: adapters[0], operations: adapters.flatMap((a) => CONTRACTS[a].operations.map((o) => ({ method: o.method, endpoint: o.endpoint, effect: o.effect, parameters: [...o.parameters], errors: [...o.errors] }))), limitations: adapters.flatMap((a) => CONTRACTS[a].limitations), nextAction: "Compare every required workflow operation and parameter with this contract; prepare and run unchanged outcome checks." };
11823
+ if (provider === "postgres" || provider === "postgresql" || provider === "redis") return { status: "real-engine", adapter: null, operations: [], limitations: ["Optional cloud engine, not an automatically provisioned production replica", "Schema, seed data, invocation and final-state checks require explicit preparation"], nextAction: "Prepare the real engine and reviewed synthetic data using the hosted runtime." };
11824
+ return { status: "missing", adapter: null, operations: [], limitations: ["No verified provider adapter", "Custom JSON collections do not establish compatibility with this provider"], nextAction: "Collect the workflow operations and provider specification, implement their stateful contract, and verify through the actual SDK before execution." };
11825
+ }
11826
+ function missingStripeOperations(workflow, tools, adapter) {
11827
+ const steps = workflow.steps.filter((step) => tools.has(step.tool));
11828
+ if (!steps.length) return [];
11829
+ const missingFor = (selected) => [...new Set(steps.flatMap((step) => step.operations.flatMap((operation) => {
11830
+ if (!(selected === "stripe" ? STRIPE_OPERATIONS.includes(operation) : PACK_STRIPE_OPERATIONS.has(operation))) return [operation];
11831
+ if (operation !== "subscriptionItems.update") return [];
11832
+ const fields = step.stripeItemFields;
11833
+ if (!fields) return [`${operation} (unverified quantity parameters)`];
11834
+ const unsupported2 = fields.filter((field) => field !== "quantity" && !(selected === "pack:stripe" && field === "expand"));
11835
+ if (unsupported2.length) return [`${operation} (${unsupported2.join(", ")})`];
11836
+ return fields.includes("quantity") ? [] : [`${operation} (quantity required)`];
11837
+ })))];
11838
+ if (adapter) return missingFor(adapter);
11839
+ const builtin = missingFor("stripe");
11840
+ if (!builtin.length || !packRecord("stripe")) return builtin;
11841
+ const pack = missingFor("pack:stripe");
11842
+ return pack.length < builtin.length ? pack : builtin;
11843
+ }
11844
+ var TWIN_ADAPTERS, ADAPTER_GROUPS, PACK_STRIPE_OPERATIONS;
11845
+ var init_service_coverage = __esm({
11846
+ "src/inventory/service-coverage.ts"() {
11847
+ "use strict";
11848
+ init_contracts();
11849
+ init_enterprise_twins();
11850
+ init_packs();
11851
+ TWIN_ADAPTERS = ["openai", "anthropic", "stripe", "slack", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk", "google-oauth", "composio", ...ENTERPRISE_ADAPTERS];
11852
+ ADAPTER_GROUPS = {
11853
+ google: ["gmail", "google-calendar", "google-oauth"],
11854
+ atlassian: ["jira", "confluence"],
11855
+ microsoft: ["microsoft-teams", "outlook", "entra-id", "sharepoint"]
11856
+ };
11857
+ PACK_STRIPE_OPERATIONS = /* @__PURE__ */ new Set([
11858
+ "accounts.create",
11859
+ "accountLinks.create",
11860
+ "balance.retrieve",
11861
+ "balanceTransactions.list",
11862
+ "billingPortal.configurations.list",
11863
+ "billingPortal.configurations.create",
11864
+ "billingPortal.sessions.create",
11865
+ "charges.list",
11866
+ "charges.retrieve",
11867
+ "checkout.sessions.create",
11868
+ "checkout.sessions.listLineItems",
11869
+ "coupons.create",
11870
+ "customers.create",
11871
+ "customers.retrieve",
11872
+ "customers.search",
11873
+ "customers.update",
11874
+ "invoicePayments.list",
11875
+ "invoices.create",
11876
+ "invoices.createPreview",
11877
+ "invoices.retrieve",
11878
+ "invoices.pay",
11879
+ "invoices.voidInvoice",
11880
+ "paymentIntents.create",
11881
+ "paymentIntents.cancel",
11882
+ "paymentMethods.retrieve",
11883
+ "paymentMethods.detach",
11884
+ "payouts.create",
11885
+ "prices.create",
11886
+ "prices.list",
11887
+ "prices.retrieve",
11888
+ "products.create",
11889
+ "products.list",
11890
+ "promotionCodes.create",
11891
+ "promotionCodes.list",
11892
+ "refunds.create",
11893
+ "subscriptions.cancel",
11894
+ "subscriptions.deleteDiscount",
11895
+ "subscriptions.list",
11896
+ "subscriptions.retrieve",
11897
+ "subscriptions.update",
11898
+ "subscriptionItems.retrieve",
11899
+ "subscriptionItems.update",
11900
+ "transfers.create",
11901
+ "webhookEndpoints.create"
11902
+ ]);
11903
+ }
11904
+ });
11905
+
10931
11906
  // src/inventory/dashboard-transfer.ts
10932
11907
  function discoveryTransfer(value) {
10933
11908
  const input = value;
@@ -10954,12 +11929,16 @@ function discoveryTransfer(value) {
10954
11929
  if (!Array.isArray(w.steps) || w.steps.length > 1e3) throw new Error("Invalid workflow steps");
10955
11930
  return { id: text3(w.id), title: text3(w.title), confidence: text3(w.confidence), supported: w.supported === true, verified: false, tools: strings(w.tools), steps: w.steps.map((rawStep) => {
10956
11931
  const step = rawStep;
10957
- return { tool: text3(step.tool), operations: strings(step.operations) };
11932
+ return { tool: text3(step.tool), operations: strings(step.operations), ...step.stripeItemFields !== void 0 ? { stripeItemFields: step.stripeItemFields === null ? null : strings(step.stripeItemFields) } : {} };
10958
11933
  }), ...w.entrypoint ? { entrypoint: entrypoint(w.entrypoint) } : {} };
10959
11934
  });
10960
11935
  if (new Set(tools.map((t) => t.id)).size !== tools.length || new Set(workflows.map((w) => w.id)).size !== workflows.length) throw new Error("Duplicate discovery IDs");
10961
11936
  const ids = new Set(tools.map((t) => t.id));
10962
11937
  if (workflows.some((w) => w.tools.some((id) => !ids.has(id)) || w.steps.some((s) => !ids.has(s.tool)))) throw new Error("Unknown workflow tool");
11938
+ const stripeTools = new Set(tools.filter((tool) => tool.title.toLowerCase() === "stripe").map((tool) => tool.id));
11939
+ for (const workflow of workflows) {
11940
+ if (missingStripeOperations(workflow, stripeTools).length) workflow.supported = false;
11941
+ }
10963
11942
  const result2 = { schema: "company-inventory/v1", name: text3(input.name), generatedAt: input.generatedAt ? text3(input.generatedAt) : "", tools, workflows, ...input.git !== void 0 ? { git: validateGit(input.git) } : {} };
10964
11943
  if (Buffer.byteLength(JSON.stringify(result2)) > 2 * 1024 * 1024) throw new Error("Discovery exceeds 2 MiB");
10965
11944
  return result2;
@@ -10967,12 +11946,13 @@ function discoveryTransfer(value) {
10967
11946
  var init_dashboard_transfer = __esm({
10968
11947
  "src/inventory/dashboard-transfer.ts"() {
10969
11948
  "use strict";
11949
+ init_service_coverage();
10970
11950
  init_git();
10971
11951
  }
10972
11952
  });
10973
11953
 
10974
11954
  // src/inventory/store.ts
10975
- import { mkdir as mkdir6, readFile as readFile16, writeFile as writeFile11 } from "fs/promises";
11955
+ import { mkdir as mkdir6, readFile as readFile16, writeFile as writeFile12 } from "fs/promises";
10976
11956
  import { join as join24 } from "path";
10977
11957
  function storeDir(cwd) {
10978
11958
  return join24(cwd, STORE_DIR);
@@ -10982,7 +11962,7 @@ function storePath(cwd, name) {
10982
11962
  }
10983
11963
  async function ensureStore(cwd) {
10984
11964
  await mkdir6(storeDir(cwd), { recursive: true });
10985
- await writeFile11(storePath(cwd, ".gitignore"), STORE_GITIGNORE, "utf8");
11965
+ await writeFile12(storePath(cwd, ".gitignore"), STORE_GITIGNORE, "utf8");
10986
11966
  }
10987
11967
  async function readJson(path2) {
10988
11968
  try {
@@ -10992,7 +11972,7 @@ async function readJson(path2) {
10992
11972
  }
10993
11973
  }
10994
11974
  async function writeJson(path2, value) {
10995
- await writeFile11(path2, `${JSON.stringify(value, null, 2)}
11975
+ await writeFile12(path2, `${JSON.stringify(value, null, 2)}
10996
11976
  `, "utf8");
10997
11977
  }
10998
11978
  function defaultSources() {
@@ -11155,7 +12135,7 @@ var init_sanitize = __esm({
11155
12135
  });
11156
12136
 
11157
12137
  // src/commands/dashboard.ts
11158
- import { cp, mkdir as mkdir7, readFile as readFile17, writeFile as writeFile12 } from "fs/promises";
12138
+ import { cp, mkdir as mkdir7, readFile as readFile17, writeFile as writeFile13 } from "fs/promises";
11159
12139
  import { basename as basename2, join as join25 } from "path";
11160
12140
  import { fileURLToPath as fileURLToPath3 } from "url";
11161
12141
  function dashboardInventory(cwd, inventory) {
@@ -11171,7 +12151,7 @@ function dashboardInventory(cwd, inventory) {
11171
12151
  confidence: t.confidence ?? "low",
11172
12152
  interface: t.kind === "runtime" ? "terminal" : "api"
11173
12153
  })),
11174
- workflows: inventory.workflows.map((w) => ({ id: w.id, title: w.title ?? w.id, confidence: w.confidence ?? "low", supported: w.supported, verified: false, ...w.entrypoint ? { entrypoint: w.entrypoint } : {}, tools: w.tools, steps: w.steps.map((s) => ({ tool: s.tool, operations: s.operations })) }))
12154
+ workflows: inventory.workflows.map((w) => ({ id: w.id, title: w.title ?? w.id, confidence: w.confidence ?? "low", supported: w.supported, verified: false, ...w.entrypoint ? { entrypoint: w.entrypoint } : {}, tools: w.tools, steps: w.steps.map((s) => ({ tool: s.tool, operations: s.operations, stripeItemFields: s.stripeItemFields })) }))
11175
12155
  })));
11176
12156
  }
11177
12157
  var init_dashboard = __esm({
@@ -11192,7 +12172,7 @@ __export(session_exports, {
11192
12172
  writeSessionTask: () => writeSessionTask
11193
12173
  });
11194
12174
  import { spawn as spawn4, spawnSync } from "child_process";
11195
- import { writeFile as writeFile13, readFile as readFile18 } from "fs/promises";
12175
+ import { writeFile as writeFile14, readFile as readFile18 } from "fs/promises";
11196
12176
  import { join as join26 } from "path";
11197
12177
  function sessionTask() {
11198
12178
  return `# Prepare this repository for AgentTwin
@@ -11219,7 +12199,7 @@ function installedOpenCode() {
11219
12199
  }
11220
12200
  async function writeSessionTask(cwd) {
11221
12201
  const path2 = join26(cwd, ".agenttwin/AGENT-TASK.md");
11222
- await writeFile13(path2, sessionTask(), "utf8");
12202
+ await writeFile14(path2, sessionTask(), "utf8");
11223
12203
  return path2;
11224
12204
  }
11225
12205
  async function launchSession(cwd) {
@@ -11277,17 +12257,17 @@ __export(run_exports, {
11277
12257
  runWorld: () => runWorld,
11278
12258
  stageApplication: () => stageApplication
11279
12259
  });
11280
- import { mkdtemp as mkdtemp8, mkdir as mkdir8, readFile as readFile19, writeFile as writeFile14, realpath as realpath4, lstat as lstat2, rm as rm10 } from "fs/promises";
12260
+ import { mkdtemp as mkdtemp8, mkdir as mkdir8, readFile as readFile19, writeFile as writeFile15, realpath as realpath5, lstat as lstat2, rm as rm10 } from "fs/promises";
11281
12261
  import { tmpdir as tmpdir8 } from "os";
11282
12262
  import { basename as basename3, dirname as dirname4, isAbsolute as isAbsolute3, join as join27, relative as relative4, resolve as resolve7, sep as sep3 } from "path";
11283
- import { createHash as createHash13, randomUUID as randomUUID5 } from "crypto";
12263
+ import { createHash as createHash14, randomUUID as randomUUID5 } from "crypto";
11284
12264
  async function stageApplication(root, files, destination) {
11285
- const canonicalRoot = await realpath4(root);
12265
+ const canonicalRoot = await realpath5(root);
11286
12266
  const digests = {};
11287
12267
  let bytes = 0;
11288
12268
  for (const file of files) {
11289
12269
  if (isAbsolute3(file) || file.includes("\\") || file.split("/").some((p) => p === ".." || /^(\.env.*|\.git|\.ssh|\.aws|\.azure|\.config|\.npmrc|\.netrc|credentials.*)$/i.test(p)) || /\.(pem|key|p12|pfx)$/i.test(file)) throw new CliError(`Unsafe application file: ${file}`, { code: EXIT.USAGE });
11290
- const source = await realpath4(resolve7(canonicalRoot, file));
12270
+ const source = await realpath5(resolve7(canonicalRoot, file));
11291
12271
  const rel = relative4(canonicalRoot, source);
11292
12272
  if (rel.startsWith(`..${sep3}`) || rel === ".." || isAbsolute3(rel) || source !== resolve7(canonicalRoot, file) || !(await lstat2(source)).isFile()) throw new CliError(`Files must be regular files within the project, without symlinks: ${file}`, { code: EXIT.USAGE });
11293
12273
  const contents = await readFile19(source);
@@ -11295,15 +12275,15 @@ async function stageApplication(root, files, destination) {
11295
12275
  if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
11296
12276
  const target = join27(destination, file);
11297
12277
  await mkdir8(dirname4(target), { recursive: true });
11298
- await writeFile14(target, contents, { mode: 420 });
11299
- digests[file] = createHash13("sha256").update(contents).digest("hex");
12278
+ await writeFile15(target, contents, { mode: 420 });
12279
+ digests[file] = createHash14("sha256").update(contents).digest("hex");
11300
12280
  }
11301
12281
  return digests;
11302
12282
  }
11303
12283
  async function resolveApplicationDirectory(worldDir, spec, stagedApp) {
11304
12284
  if (!spec.directory) return stagedApp;
11305
12285
  const target = resolve7(worldDir, spec.directory);
11306
- const dir = await realpath4(target).catch(() => {
12286
+ const dir = await realpath5(target).catch(() => {
11307
12287
  throw new CliError(`directory ${spec.directory} does not exist (resolved to ${target})`, { code: EXIT.USAGE });
11308
12288
  });
11309
12289
  if (!(await lstat2(dir)).isDirectory()) throw new CliError(`directory ${spec.directory} is not a folder`, { code: EXIT.USAGE });
@@ -11366,8 +12346,8 @@ async function runWorld(cwd, opts) {
11366
12346
  const stage = await mkdtemp8(join27(tmpdir8(), "agenttwin-world-"));
11367
12347
  try {
11368
12348
  const sourceDigests = await stageApplication(dirname4(file), spec.files, join27(stage, "app"));
11369
- await writeFile14(join27(stage, "world.json"), JSON.stringify(spec), { mode: 420 });
11370
- if (runtime === "e2b" && suppliedSeed) await writeFile14(join27(stage, "seed.json"), JSON.stringify({ seed: suppliedSeed }), { mode: 420 });
12349
+ await writeFile15(join27(stage, "world.json"), JSON.stringify(spec), { mode: 420 });
12350
+ if (runtime === "e2b" && suppliedSeed) await writeFile15(join27(stage, "seed.json"), JSON.stringify({ seed: suppliedSeed }), { mode: 420 });
11371
12351
  const git2 = await captureGit(sourceBuild?.root ?? cwd);
11372
12352
  let project;
11373
12353
  try {
@@ -11394,14 +12374,14 @@ async function runWorld(cwd, opts) {
11394
12374
  }
11395
12375
  }
11396
12376
  const runId2 = randomUUID5();
11397
- const receipt2 = { ...report2, ...sourceBuildEvidence ? { sourceBuild: sourceBuildEvidence } : {}, ...sourceBuildError ? { executionError: sourceBuildError } : {}, sourceDirectory: relative4(cwd, dirname4(file)).split(sep3).join("/"), runId: runId2, runtime, project, git: git2, createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: createHash13("sha256").update(JSON.stringify(spec)).digest("hex"), provenance: "CLI-reported execution" };
12377
+ const receipt2 = { ...report2, ...sourceBuildEvidence ? { sourceBuild: sourceBuildEvidence } : {}, ...sourceBuildError ? { executionError: sourceBuildError } : {}, sourceDirectory: relative4(cwd, dirname4(file)).split(sep3).join("/"), runId: runId2, runtime, project, git: git2, createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: createHash14("sha256").update(JSON.stringify(spec)).digest("hex"), provenance: "CLI-reported execution" };
11398
12378
  const out2 = resolve7(cwd, opts.out ?? `.agenttwin/runs/${runId2}`);
11399
12379
  await mkdir8(out2, { recursive: true });
11400
12380
  const evidencePath = join27(out2, "run.json"), reportPath = join27(out2, "report.md");
11401
- await writeFile14(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
11402
- await writeFile14(join27(out2, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
12381
+ await writeFile15(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
12382
+ await writeFile15(join27(out2, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
11403
12383
  const next = receipt2.status === "passed" ? [`Replay: agenttwin replay .agenttwin/runs/${runId2}/run.json`] : [`See the evidence and a fix task: agenttwin receipt --id ${runId2}`, `After fixing, rerun: agenttwin run --file ${relative4(cwd, file).split(sep3).join("/")}`];
11404
- await writeFile14(reportPath, renderRunSummary({ ...receipt2, runId: runId2 }, { markdown: true, next, costs: await readCostConfig(cwd) }) + `
12384
+ await writeFile15(reportPath, renderRunSummary({ ...receipt2, runId: runId2 }, { markdown: true, next, costs: await readCostConfig(cwd) }) + `
11405
12385
  Runner: CLI \xB7 Git: ${git2?.head ?? "unavailable"} \xB7 Seed: ${receipt2.seed}
11406
12386
  ${receipt2.reproducibility ?? ""}
11407
12387
  ${sourceBuildError ?? ""}
@@ -11414,15 +12394,15 @@ Full evidence (activities, fault, initial and final state): run.json
11414
12394
  const receipt2 = await executeRemote(stage, spec, opts.log, { git: git2, project, seed: suppliedSeed });
11415
12395
  if (receipt2.schema !== "agenttwin/run-v1" || typeof receipt2.runId !== "string" || !/^[a-f0-9-]{36}$/.test(receipt2.runId) || !["passed", "failed", "error", "incomplete"].includes(String(receipt2.status))) throw new CliError("Invalid hosted receipt");
11416
12396
  if (suppliedSeed && receipt2.seed !== suppliedSeed) throw new CliError("Hosted receipt does not match the requested seed");
11417
- const expectedSpec = createHash13("sha256").update(JSON.stringify(spec)).digest("hex");
12397
+ const expectedSpec = createHash14("sha256").update(JSON.stringify(spec)).digest("hex");
11418
12398
  const reportedSources = receipt2.sourceDigests;
11419
12399
  if (receipt2.specDigest !== expectedSpec || !reportedSources || Object.keys(reportedSources).length !== Object.keys(sourceDigests).length || Object.entries(sourceDigests).some(([path2, digest6]) => reportedSources[path2] !== digest6)) throw new CliError("Hosted receipt does not match the submitted source/specification");
11420
12400
  const out2 = resolve7(cwd, opts.out ?? `.agenttwin/runs/${receipt2.runId}`);
11421
12401
  await mkdir8(out2, { recursive: true });
11422
12402
  const evidencePath = join27(out2, "run.json");
11423
12403
  const reportPath = join27(out2, "report.md");
11424
- await writeFile14(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
11425
- await writeFile14(reportPath, `# ${spec.name}: ${receipt2.status}
12404
+ await writeFile15(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
12405
+ await writeFile15(reportPath, `# ${spec.name}: ${receipt2.status}
11426
12406
 
11427
12407
  Run: ${receipt2.runId}
11428
12408
 
@@ -11452,15 +12432,15 @@ See run.json for assertions, service state, application output and isolation met
11452
12432
  image,
11453
12433
  templateBuildId,
11454
12434
  sourceDigests,
11455
- specDigest: createHash13("sha256").update(JSON.stringify(spec)).digest("hex"),
12435
+ specDigest: createHash14("sha256").update(JSON.stringify(spec)).digest("hex"),
11456
12436
  isolation
11457
12437
  };
11458
12438
  const out = resolve7(cwd, opts.out ?? `.agenttwin/runs/${runId}`);
11459
12439
  await mkdir8(out, { recursive: true });
11460
- await writeFile14(join27(out, "run.json"), JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
11461
- await writeFile14(join27(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
12440
+ await writeFile15(join27(out, "run.json"), JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
12441
+ await writeFile15(join27(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
11462
12442
  const summary = [`# ${spec.name}: ${report.status}`, "", `Run: ${runId}`, `Image: ${image}`, "", "## Assertions", "", ...report.assertions.map((a) => `- ${a.passed ? "PASS" : "FAIL"} ${a.service}${a.path}: expected ${a.count}, observed ${a.actual}`), "", "## Infrastructure assertions", "", ...(report.infrastructureAssertions ?? []).map((a) => `- ${a.passed ? "PASS" : "FAIL"} ${a.service}: ${JSON.stringify(a.actual)}`), "", "## Coverage", "", report.coverage, "", "External networking disabled. Only explicitly listed source files were uploaded. New state and tokens are created for each run.", "", "See run.json for application output, faults, events, and initial/final state.", ""].join("\n");
11463
- await writeFile14(join27(out, "report.md"), summary);
12443
+ await writeFile15(join27(out, "report.md"), summary);
11464
12444
  return { ...receipt, reportPath: join27(out, "report.md"), evidencePath: join27(out, "run.json") };
11465
12445
  } finally {
11466
12446
  await rm10(stage, { recursive: true, force: true });
@@ -11489,7 +12469,7 @@ var init_run = __esm({
11489
12469
  // src/runtime/docker.ts
11490
12470
  import { execFile as execFile9, spawn as spawn5 } from "child_process";
11491
12471
  import { promisify as promisify9 } from "util";
11492
- import { chmod as chmod3, copyFile as copyFile2, mkdir as mkdir9, mkdtemp as mkdtemp9, readFile as readFile20, rm as rm11, writeFile as writeFile15 } from "fs/promises";
12472
+ import { chmod as chmod3, copyFile as copyFile2, mkdir as mkdir9, mkdtemp as mkdtemp9, readFile as readFile20, rm as rm11, writeFile as writeFile16 } from "fs/promises";
11493
12473
  import { tmpdir as tmpdir9 } from "os";
11494
12474
  import { join as join28 } from "path";
11495
12475
  import { randomUUID as randomUUID6 } from "crypto";
@@ -11520,7 +12500,7 @@ async function executeDocker(app, spec, opts = {}) {
11520
12500
  await mkdir9(support, { mode: 493 });
11521
12501
  await copyFile2(hook.path, join28(support, "source.cjs"));
11522
12502
  await chmod3(join28(support, "source.cjs"), 420);
11523
- await writeFile15(join28(support, "bridge.cjs"), stdioFetchHook(credentials2, !!database), { mode: 420 });
12503
+ await writeFile16(join28(support, "bridge.cjs"), stdioFetchHook(credentials2, !!database), { mode: 420 });
11524
12504
  const env = Object.entries(credentials2).flatMap(([name, c]) => ["--env", `AGENTTWIN_${name.toUpperCase()}_URL=${c.endpoint}`, "--env", `AGENTTWIN_${name.toUpperCase()}_TOKEN=${c.token}`]);
11525
12505
  let stdout = "", stderr = "", timedOut = false;
11526
12506
  const args = ["run", "--pull", "never", "--interactive", "--name", container, "--network", "none", "--read-only", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--user", "65534:65534", "--pids-limit", "128", "--memory", "512m", "--cpus", "1", "--tmpfs", "/tmp:rw,noexec,nosuid,size=64m", "--mount", `type=bind,src=${stagedApp},dst=/app,readonly`, "--mount", `type=bind,src=${support},dst=/agenttwin,readonly`, "--workdir", "/app", "--env", "NODE_ENV=test", ...env, "--entrypoint", "node", image, "--require", "/agenttwin/bridge.cjs", "--require", "/agenttwin/source.cjs", ...spec.command.slice(1)];
@@ -11631,54 +12611,31 @@ var init_docker = __esm({
11631
12611
  }
11632
12612
  });
11633
12613
 
11634
- // src/inventory/service-coverage.ts
11635
- function serviceSupport(tool) {
11636
- const provider = tool.providerId ?? tool.title.toLowerCase();
11637
- const adapters = ADAPTER_GROUPS[provider] ?? TWIN_ADAPTERS.filter((name) => name === provider);
11638
- if (adapters.length) return { status: "partial", adapter: adapters[0], operations: adapters.flatMap((a) => CONTRACTS[a].operations.map((o) => ({ method: o.method, endpoint: o.endpoint, effect: o.effect, parameters: [...o.parameters], errors: [...o.errors] }))), limitations: adapters.flatMap((a) => CONTRACTS[a].limitations), nextAction: "Compare every required workflow operation and parameter with this contract; prepare and run unchanged outcome checks." };
11639
- if (provider === "postgres" || provider === "postgresql" || provider === "redis") return { status: "real-engine", adapter: null, operations: [], limitations: ["Optional cloud engine, not an automatically provisioned production replica", "Schema, seed data, invocation and final-state checks require explicit preparation"], nextAction: "Prepare the real engine and reviewed synthetic data using the hosted runtime." };
11640
- return { status: "missing", adapter: null, operations: [], limitations: ["No verified provider adapter", "Custom JSON collections do not establish compatibility with this provider"], nextAction: "Collect the workflow operations and provider specification, implement their stateful contract, and verify through the actual SDK before execution." };
11641
- }
11642
- var TWIN_ADAPTERS, ADAPTER_GROUPS;
11643
- var init_service_coverage = __esm({
11644
- "src/inventory/service-coverage.ts"() {
11645
- "use strict";
11646
- init_contracts();
11647
- init_enterprise_twins();
11648
- TWIN_ADAPTERS = ["openai", "anthropic", "stripe", "slack", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk", "google-oauth", "composio", ...ENTERPRISE_ADAPTERS];
11649
- ADAPTER_GROUPS = {
11650
- google: ["gmail", "google-calendar", "google-oauth"],
11651
- atlassian: ["jira", "confluence"],
11652
- microsoft: ["microsoft-teams", "outlook", "entra-id", "sharepoint"]
11653
- };
11654
- }
11655
- });
11656
-
11657
12614
  // src/inventory/workflows.ts
11658
12615
  function permissionsFor(kind, entities) {
11659
- const list2 = [];
11660
- if (kind === "payments") list2.push("payments:read", "payments:write");
11661
- else if (kind === "comms") list2.push("messages:read", "messages:write");
11662
- else if (kind === "crm" || kind === "support") list2.push("records:read", "records:write");
11663
- else list2.push("read", "write");
11664
- for (const entity of entities) list2.push(`${entity}:read`, `${entity}:write`);
11665
- return [...new Set(list2)].sort();
12616
+ const list3 = [];
12617
+ if (kind === "payments") list3.push("payments:read", "payments:write");
12618
+ else if (kind === "comms") list3.push("messages:read", "messages:write");
12619
+ else if (kind === "crm" || kind === "support") list3.push("records:read", "records:write");
12620
+ else list3.push("read", "write");
12621
+ for (const entity of entities) list3.push(`${entity}:read`, `${entity}:write`);
12622
+ return [...new Set(list3)].sort();
11666
12623
  }
11667
12624
  function eventsFor(kind, entities) {
11668
- const list2 = [];
11669
- if (kind === "payments") list2.push("webhook: charge.refunded / payment_intent.succeeded");
11670
- if (kind === "comms") list2.push("delivery receipt / message.changed");
11671
- if (kind === "queue") list2.push("message delivery (duplicate / out-of-order)");
11672
- list2.push(...entities.map((e) => `webhook: ${e}.created / ${e}.updated`));
11673
- return [...new Set(list2)];
12625
+ const list3 = [];
12626
+ if (kind === "payments") list3.push("webhook: charge.refunded / payment_intent.succeeded");
12627
+ if (kind === "comms") list3.push("delivery receipt / message.changed");
12628
+ if (kind === "queue") list3.push("message delivery (duplicate / out-of-order)");
12629
+ list3.push(...entities.map((e) => `webhook: ${e}.created / ${e}.updated`));
12630
+ return [...new Set(list3)];
11674
12631
  }
11675
12632
  function scenariosFor(kind) {
11676
- const list2 = ["timeout after a successful write (response lost)"];
11677
- if (kind === "payments") list2.push("duplicate refund / double charge");
11678
- if (kind === "queue") list2.push("duplicate or out-of-order delivery");
11679
- if (kind === "database") list2.push("partial write / rollback");
11680
- list2.push("permission revoked mid-flow", "rate limit / 429");
11681
- return [...new Set(list2)];
12633
+ const list3 = ["timeout after a successful write (response lost)"];
12634
+ if (kind === "payments") list3.push("duplicate refund / double charge");
12635
+ if (kind === "queue") list3.push("duplicate or out-of-order delivery");
12636
+ if (kind === "database") list3.push("partial write / rollback");
12637
+ list3.push("permission revoked mid-flow", "rate limit / 429");
12638
+ return [...new Set(list3)];
11682
12639
  }
11683
12640
  function assertionsFor(candidate) {
11684
12641
  if (candidate.entrypoint) return [
@@ -11869,9 +12826,9 @@ var init_languages = __esm({
11869
12826
  const ext = file.slice(file.lastIndexOf(".") + 1).toLowerCase();
11870
12827
  const lang = EXT_LANG[ext];
11871
12828
  if (!lang) continue;
11872
- const list2 = byLang.get(lang) ?? [];
11873
- if (list2.length < 20) list2.push(file);
11874
- byLang.set(lang, list2);
12829
+ const list3 = byLang.get(lang) ?? [];
12830
+ if (list3.length < 20) list3.push(file);
12831
+ byLang.set(lang, list3);
11875
12832
  }
11876
12833
  const findings = [];
11877
12834
  for (const [lang, refs] of byLang) {
@@ -12251,8 +13208,8 @@ var init_k8s = __esm({
12251
13208
  } catch {
12252
13209
  continue;
12253
13210
  }
12254
- const list2 = Array.isArray(docs) ? docs : [docs];
12255
- for (const doc of list2) {
13211
+ const list3 = Array.isArray(docs) ? docs : [docs];
13212
+ for (const doc of list3) {
12256
13213
  const containers = extractContainers(doc);
12257
13214
  for (const image of containers) {
12258
13215
  const info = classifyImage(image);
@@ -12747,9 +13704,9 @@ var init_ci = __esm({
12747
13704
  const prefixes = provider.signatures.envPrefixes ?? [];
12748
13705
  if (prefixes.length === 0) continue;
12749
13706
  if (prefixes.some((p) => text3.includes(p))) {
12750
- const list2 = providerEvidence.get(provider.id) ?? [];
12751
- list2.push({ ref: path2, pass: "environment", signal: "ci", detail: provider.id });
12752
- providerEvidence.set(provider.id, list2);
13707
+ const list3 = providerEvidence.get(provider.id) ?? [];
13708
+ list3.push({ ref: path2, pass: "environment", signal: "ci", detail: provider.id });
13709
+ providerEvidence.set(provider.id, list3);
12753
13710
  }
12754
13711
  }
12755
13712
  }
@@ -13396,7 +14353,7 @@ var init_identity = __esm({
13396
14353
  });
13397
14354
 
13398
14355
  // src/inventory/canonical.ts
13399
- import { createHash as createHash17 } from "crypto";
14356
+ import { createHash as createHash18 } from "crypto";
13400
14357
  function sortKeys(value) {
13401
14358
  if (Array.isArray(value)) return value.map(sortKeys);
13402
14359
  if (value && typeof value === "object") {
@@ -13424,7 +14381,7 @@ function canonicalContent(inventory) {
13424
14381
  }
13425
14382
  function canonicalHash(inventory) {
13426
14383
  const content = JSON.stringify(canonicalContent(inventory));
13427
- return `sha256:${createHash17("sha256").update(content).digest("hex").slice(0, 32)}`;
14384
+ return `sha256:${createHash18("sha256").update(content).digest("hex").slice(0, 32)}`;
13428
14385
  }
13429
14386
  function withCanonicalHash(inventory) {
13430
14387
  return { ...inventory, canonicalHash: canonicalHash(inventory) };
@@ -13928,9 +14885,9 @@ function workflowGraph(sources, operations, tools, options = {}) {
13928
14885
  locals.set(mod, declared);
13929
14886
  walk2(ast.program, (node) => {
13930
14887
  if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
13931
- const list2 = declared.get(node.id.name) ?? [];
13932
- list2.push({ line: node.loc.start.line, init: node.init });
13933
- declared.set(node.id.name, list2);
14888
+ const list3 = declared.get(node.id.name) ?? [];
14889
+ list3.push({ line: node.loc.start.line, init: node.init });
14890
+ declared.set(node.id.name, list3);
13934
14891
  }
13935
14892
  if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && unwrap(node.init)) toolNames.set(unwrap(node.init), node.id.name);
13936
14893
  if (node.type === "ObjectProperty" && propertyName(node.key) && unwrap(node.value)) toolNames.set(unwrap(node.value), propertyName(node.key));
@@ -14167,9 +15124,9 @@ function workflowGraph(sources, operations, tools, options = {}) {
14167
15124
  };
14168
15125
  const byPath = /* @__PURE__ */ new Map();
14169
15126
  for (const operation of operations) {
14170
- const list2 = byPath.get(operation.path) ?? [];
14171
- list2.push(operation);
14172
- byPath.set(operation.path, list2);
15127
+ const list3 = byPath.get(operation.path) ?? [];
15128
+ list3.push(operation);
15129
+ byPath.set(operation.path, list3);
14173
15130
  }
14174
15131
  const directEffects = /* @__PURE__ */ new Map();
14175
15132
  const effects2 = (unit) => {
@@ -14509,12 +15466,12 @@ function createSdkScanner(project) {
14509
15466
  if (!ast) return ops;
14510
15467
  const consumed = /* @__PURE__ */ new Set();
14511
15468
  const seen = /* @__PURE__ */ new Set();
14512
- const push = (node, providerId, kind, label2, resource) => {
15469
+ const push = (node, providerId, kind, label2, resource, stripeItemFields) => {
14513
15470
  const line = node.loc?.start.line ?? 1;
14514
15471
  const key2 = `${line}|${providerId}|${label2}`;
14515
- if (seen.has(key2)) return;
15472
+ if (stripeItemFields === void 0 && seen.has(key2)) return;
14516
15473
  seen.add(key2);
14517
- ops.push({ line, providerId, kind, label: label2, resource: resource.replace(/[^\w.-]/g, "_") || providerId });
15474
+ ops.push({ line, providerId, kind, label: label2, resource: resource.replace(/[^\w.-]/g, "_") || providerId, stripeItemFields });
14518
15475
  };
14519
15476
  const rootBinding = (root) => {
14520
15477
  const value = unwrap(root);
@@ -14594,7 +15551,14 @@ function createSdkScanner(project) {
14594
15551
  if ((binding.pkg.startsWith("@ai-sdk/") || binding.pkg.startsWith("@openrouter/")) && names.length === 1 && /Model$|^(chat|responses|completion|embedding|image|languageModel)$/.test(verb)) return push(node, provider, "writes", "model", "model");
14595
15552
  const kind = verbKind(verb, ai);
14596
15553
  if (!kind) return;
14597
- push(node, provider, kind, names.slice(-2).join("."), names.length > 1 ? names[names.length - 2] : provider);
15554
+ const label2 = names.slice(-2).join(".");
15555
+ let stripeItemFields;
15556
+ if (provider === "stripe" && label2 === "subscriptionItems.update") {
15557
+ const params = unwrap(segments.at(-1)?.args[1]);
15558
+ const keys = params?.type === "ObjectExpression" ? params.properties.map((p) => p.type === "ObjectProperty" && !p.computed ? propertyName(p.key) : void 0) : void 0;
15559
+ stripeItemFields = keys?.every((key2) => typeof key2 === "string") ? keys : null;
15560
+ }
15561
+ push(node, provider, kind, label2, names.length > 1 ? names[names.length - 2] : provider, stripeItemFields);
14598
15562
  };
14599
15563
  walk(ast.program, (node) => {
14600
15564
  if (node.type === "TaggedTemplateExpression") {
@@ -14670,7 +15634,7 @@ var init_sdk_calls = __esm({
14670
15634
  });
14671
15635
 
14672
15636
  // src/inventory/relationships.ts
14673
- import { createHash as createHash18 } from "crypto";
15637
+ import { createHash as createHash19 } from "crypto";
14674
15638
  function datastoreFor(pkg, fallback) {
14675
15639
  if (/^(pg|pg-pool|postgres|pg-promise|slonik|@neondatabase\/serverless|@vercel\/postgres)(\/|$)/.test(pkg)) return "postgres";
14676
15640
  if (/^(mysql|mysql2|@planetscale\/database)(\/|$)/.test(pkg)) return "mysql";
@@ -14704,8 +15668,8 @@ function packagesFor(providerId) {
14704
15668
  const provider = PROVIDERS.find((p) => p.id === providerId);
14705
15669
  if (!provider) return [];
14706
15670
  const set = /* @__PURE__ */ new Set();
14707
- for (const list2 of Object.values(provider.signatures.packages ?? {})) {
14708
- for (const pkg of list2) set.add(pkg.replace(/\/$/, ""));
15671
+ for (const list3 of Object.values(provider.signatures.packages ?? {})) {
15672
+ for (const pkg of list3) set.add(pkg.replace(/\/$/, ""));
14709
15673
  }
14710
15674
  return [...set];
14711
15675
  }
@@ -14764,9 +15728,9 @@ function riskFor(kind) {
14764
15728
  function workflowGroupKey(providerId, tool) {
14765
15729
  return `${providerId}|${tool?.accounts.join(",") ?? ""}|${tool?.environment ?? ""}`;
14766
15730
  }
14767
- function stepsFor(apps, list2, toolId) {
15731
+ function stepsFor(apps, list3, toolId) {
14768
15732
  return apps.map((app) => {
14769
- const records = list2.filter((r) => r.app === app);
15733
+ const records = list3.filter((r) => r.app === app);
14770
15734
  return {
14771
15735
  app,
14772
15736
  tool: toolId,
@@ -14797,9 +15761,9 @@ async function buildRelationships(apps, tools, files, decisions) {
14797
15761
  const byApp = /* @__PURE__ */ new Map();
14798
15762
  for (const ref of fileRefs(tool)) {
14799
15763
  const app = appForPath(apps, ref);
14800
- const list2 = byApp.get(app.id) ?? [];
14801
- list2.push({ source: "static", ref });
14802
- byApp.set(app.id, list2);
15764
+ const list3 = byApp.get(app.id) ?? [];
15765
+ list3.push({ source: "static", ref });
15766
+ byApp.set(app.id, list3);
14803
15767
  }
14804
15768
  for (const [appId, evidence] of byApp) {
14805
15769
  const id = `uses:${appId}:${tool.id}`;
@@ -14858,7 +15822,7 @@ async function buildRelationships(apps, tools, files, decisions) {
14858
15822
  const sdkLines = new Set(sdkOperations.map((op2) => `${op2.line}|${op2.providerId}`));
14859
15823
  const astBindings = /\.[cm]?[jt]sx?$/.test(path2) ? scanner.bindings(path2) : /* @__PURE__ */ new Map();
14860
15824
  const operations = [
14861
- ...sdkOperations.map((op2) => ({ receiver: void 0, resource: op2.resource, verb: op2.label, kind: op2.kind, ref: `${path2}:${op2.line}`, providerId: op2.providerId, label: op2.label })),
15825
+ ...sdkOperations.map((op2) => ({ receiver: void 0, resource: op2.resource, verb: op2.label, kind: op2.kind, ref: `${path2}:${op2.line}`, providerId: op2.providerId, label: op2.label, stripeItemFields: op2.stripeItemFields })),
14862
15826
  ...scanOperations(text3, path2),
14863
15827
  ...httpOperations
14864
15828
  ];
@@ -14890,7 +15854,7 @@ async function buildRelationships(apps, tools, files, decisions) {
14890
15854
  evidence: []
14891
15855
  };
14892
15856
  const label2 = op2.label ?? `${op2.resource}.${op2.verb}`;
14893
- entrypointCalls.push({ path: path2, line: Number(op2.ref.slice(path2.length + 1)), providerId, toolId: tool.id, kind: op2.kind, label: label2, resource: op2.resource, ref: op2.ref });
15857
+ entrypointCalls.push({ path: path2, line: Number(op2.ref.slice(path2.length + 1)), providerId, toolId: tool.id, kind: op2.kind, label: label2, resource: op2.resource, ref: op2.ref, stripeItemFields: op2.stripeItemFields });
14894
15858
  if (!record4.operations.includes(label2)) record4.operations.push(label2);
14895
15859
  if (!record4.resources.includes(op2.resource)) record4.resources.push(op2.resource);
14896
15860
  if (!record4.evidence.some((e) => e.ref === op2.ref)) record4.evidence.push({ source: "static", ref: op2.ref });
@@ -14928,19 +15892,19 @@ async function buildRelationships(apps, tools, files, decisions) {
14928
15892
  for (const record4 of decidedRecords) {
14929
15893
  if (!providerTools.some((t) => t.providerId === record4.providerId)) continue;
14930
15894
  const key2 = workflowGroupKey(record4.providerId, toolByProvider.get(record4.providerId));
14931
- const list2 = byGroup.get(key2) ?? [];
14932
- list2.push(record4);
14933
- byGroup.set(key2, list2);
15895
+ const list3 = byGroup.get(key2) ?? [];
15896
+ list3.push(record4);
15897
+ byGroup.set(key2, list3);
14934
15898
  }
14935
15899
  const workflows = [];
14936
15900
  const gaps = [];
14937
- for (const list2 of byGroup.values()) {
14938
- const providerId = list2[0].providerId;
15901
+ for (const list3 of byGroup.values()) {
15902
+ const providerId = list3[0].providerId;
14939
15903
  const tool = toolByProvider.get(providerId);
14940
15904
  if (!tool) continue;
14941
- const appsInvolved = [...new Set(list2.map((r) => r.app))].sort();
14942
- const producers = list2.filter((r) => r.kind === "writes" || r.kind === "emits");
14943
- const consumers = list2.filter((r) => r.kind === "reads" || r.kind === "emits");
15905
+ const appsInvolved = [...new Set(list3.map((r) => r.app))].sort();
15906
+ const producers = list3.filter((r) => r.kind === "writes" || r.kind === "emits");
15907
+ const consumers = list3.filter((r) => r.kind === "reads" || r.kind === "emits");
14944
15908
  if (producers.length === 0 || consumers.length === 0) {
14945
15909
  if (appsInvolved.length >= 2) {
14946
15910
  gaps.push(
@@ -14949,8 +15913,8 @@ async function buildRelationships(apps, tools, files, decisions) {
14949
15913
  }
14950
15914
  continue;
14951
15915
  }
14952
- const writeResources = list2.filter((r) => r.kind === "writes").flatMap(entityResources);
14953
- const readResources = list2.filter((r) => r.kind === "reads").flatMap(entityResources);
15916
+ const writeResources = list3.filter((r) => r.kind === "writes").flatMap(entityResources);
15917
+ const readResources = list3.filter((r) => r.kind === "reads").flatMap(entityResources);
14954
15918
  const sharedIntersection = [...new Set(writeResources.filter((r) => readResources.includes(r)))];
14955
15919
  const producerApps = [...new Set(producers.map((r) => r.app))].sort();
14956
15920
  const consumerApps = [...new Set(consumers.map((r) => r.app))].sort();
@@ -14975,10 +15939,10 @@ async function buildRelationships(apps, tools, files, decisions) {
14975
15939
  title: `${app} via ${tool.title}`,
14976
15940
  apps: [app],
14977
15941
  tools: [tool.id],
14978
- steps: stepsFor([app], list2, tool.id),
15942
+ steps: stepsFor([app], list3, tool.id),
14979
15943
  sharedEntities: sharedIntersection.length > 0 ? sharedIntersection : [singularize(providerId)],
14980
- evidence: list2.flatMap((r) => r.evidence),
14981
- confidence: confidenceFrom(list2.flatMap((r) => r.evidence).length),
15944
+ evidence: list3.flatMap((r) => r.evidence),
15945
+ confidence: confidenceFrom(list3.flatMap((r) => r.evidence).length),
14982
15946
  risk: riskFor(tool.kind),
14983
15947
  rank: 0,
14984
15948
  supported: supported2,
@@ -15022,10 +15986,10 @@ async function buildRelationships(apps, tools, files, decisions) {
15022
15986
  title: `${orderedApps.join(" \u2192 ")} via ${tool.title}`,
15023
15987
  apps: orderedApps,
15024
15988
  tools: [tool.id],
15025
- steps: stepsFor(orderedApps, list2, tool.id),
15989
+ steps: stepsFor(orderedApps, list3, tool.id),
15026
15990
  sharedEntities: entities.length > 0 ? entities : [singularize(providerId)],
15027
- evidence: list2.flatMap((r) => r.evidence),
15028
- confidence: confidenceFrom(list2.flatMap((r) => r.evidence).length),
15991
+ evidence: list3.flatMap((r) => r.evidence),
15992
+ confidence: confidenceFrom(list3.flatMap((r) => r.evidence).length),
15029
15993
  risk: riskFor(tool.kind),
15030
15994
  rank: 0,
15031
15995
  supported,
@@ -15058,7 +16022,7 @@ async function buildRelationships(apps, tools, files, decisions) {
15058
16022
  const name = `script:${path2.split("/").pop()}`;
15059
16023
  entries.push({ name, startLine: 1, endLine: Number.MAX_SAFE_INTEGER, path: path2, exported: false, trigger: true, calls, evidence: [{ source: "static", ref: `${path2}:1` }] });
15060
16024
  }
15061
- const entryId = (path2, name) => "entry:" + createHash18("sha256").update(path2 + ":" + name).digest("hex").slice(0, 20);
16025
+ const entryId = (path2, name) => "entry:" + createHash19("sha256").update(path2 + ":" + name).digest("hex").slice(0, 20);
15062
16026
  for (const entry of entries) {
15063
16027
  const { path: path2 } = entry;
15064
16028
  const app = appForPath(apps, path2);
@@ -15074,7 +16038,8 @@ async function buildRelationships(apps, tools, files, decisions) {
15074
16038
  entrypoint: path2 + "#" + entry.name.replace(/\\/g, "%5C"),
15075
16039
  apps: [app.id],
15076
16040
  tools: dependencies,
15077
- steps: dependencies.map((tool) => ({ app: app.id, tool, operations: [...new Set(calls.filter((c) => c.toolId === tool).map((c) => c.label))], evidence })),
16041
+ // A step's evidence is the lines that make its calls; the workflow's evidence keeps every unit it reaches.
16042
+ steps: dependencies.map((tool) => ({ app: app.id, tool, operations: [...new Set(calls.filter((c) => c.toolId === tool).map((c) => c.label))], evidence: [...new Set(calls.filter((c) => c.toolId === tool).map((c) => c.ref))].map((ref) => ({ source: "static", ref })) })),
15078
16043
  sharedEntities: [...new Set(calls.map((call2) => singularize(call2.resource)))],
15079
16044
  evidence,
15080
16045
  confidence: "medium",
@@ -15091,6 +16056,20 @@ async function buildRelationships(apps, tools, files, decisions) {
15091
16056
  const finalWorkflows = workflows.filter((w) => !rejected.has(w.id)).map(
15092
16057
  (w) => confirmed.has(w.id) ? { ...w, supported: true, hypothesis: false, linkingSignals: [...w.linkingSignals, "confirmed by decision"] } : w
15093
16058
  );
16059
+ const stripeTools = new Set(providerTools.filter((tool) => tool.providerId === "stripe").map((tool) => tool.id));
16060
+ for (const workflow of finalWorkflows) {
16061
+ for (const step of workflow.steps) {
16062
+ if (!stripeTools.has(step.tool) || !step.operations.includes("subscriptionItems.update")) continue;
16063
+ const refs = new Set(step.evidence.map((e) => e.ref));
16064
+ const updates = allowedCalls.filter((call2) => call2.toolId === step.tool && call2.label === "subscriptionItems.update" && refs.has(call2.ref));
16065
+ const fields = updates.flatMap((call2) => call2.stripeItemFields ?? []);
16066
+ step.stripeItemFields = updates.length && updates.every((call2) => call2.stripeItemFields !== null && call2.stripeItemFields !== void 0) ? [...new Set(fields.filter((field) => field !== "quantity" || updates.every((call2) => call2.stripeItemFields?.includes("quantity"))))].sort() : null;
16067
+ }
16068
+ const missing = missingStripeOperations(workflow, stripeTools);
16069
+ if (!missing.length) continue;
16070
+ workflow.supported = false;
16071
+ workflow.linkingSignals.push(`Stripe twin does not cover ${missing.join(", ")}`);
16072
+ }
15094
16073
  const riskWeight = { low: 0, medium: 1, high: 2 };
15095
16074
  finalWorkflows.sort(
15096
16075
  (a, b) => Number(b.supported) - Number(a.supported) || // Routes and jobs are how a workflow is actually triggered; list them before helpers.
@@ -15104,6 +16083,7 @@ var SOURCE_EXTS2, MAX_FILES3, NON_USAGE_DIR2, PROVIDER_KINDS, DATASTORE_IDS, CLA
15104
16083
  var init_relationships = __esm({
15105
16084
  "src/inventory/relationships.ts"() {
15106
16085
  "use strict";
16086
+ init_service_coverage();
15107
16087
  init_provider_factories();
15108
16088
  init_entrypoints();
15109
16089
  init_workflow_graph();
@@ -15194,7 +16174,7 @@ var init_scope = __esm({
15194
16174
 
15195
16175
  // src/observation/runtime.ts
15196
16176
  import { spawn as spawn7 } from "child_process";
15197
- import { mkdtemp as mkdtemp12, open as open2, writeFile as writeFile19, rm as rm14, realpath as realpath7 } from "fs/promises";
16177
+ import { mkdtemp as mkdtemp12, open as open2, writeFile as writeFile20, rm as rm14, realpath as realpath8 } from "fs/promises";
15198
16178
  import { tmpdir as tmpdir13 } from "os";
15199
16179
  import { join as join34, basename as basename4 } from "path";
15200
16180
  function validHost(host) {
@@ -15290,7 +16270,7 @@ require('node:module').syncBuiltinESMExports();
15290
16270
  });
15291
16271
 
15292
16272
  // src/inventory/observed.ts
15293
- import { createHash as createHash19 } from "crypto";
16273
+ import { createHash as createHash20 } from "crypto";
15294
16274
  function mergeObservations(workflows, tools, report) {
15295
16275
  if (!report?.services.length) return workflows;
15296
16276
  const toolFor = (host) => {
@@ -15325,7 +16305,7 @@ function mergeObservations(workflows, tools, report) {
15325
16305
  const toolIds = [...new Set(calls.map((c) => c.tool.id))];
15326
16306
  const evidence = [...new Set(events.flatMap((e) => [e.source, ...e.frames ?? []]).filter((r) => !!r))].map((ref) => ({ source: "runtime-attempt", ref }));
15327
16307
  merged.push({
15328
- id: "runtime:" + createHash19("sha256").update(entry).digest("hex").slice(0, 20),
16308
+ id: "runtime:" + createHash20("sha256").update(entry).digest("hex").slice(0, 20),
15329
16309
  title: `runtime:${entry}`,
15330
16310
  entrypoint: `${path2}#runtime:${entry.slice(entry.lastIndexOf(":") + 1)}`,
15331
16311
  apps: ["(root)"],
@@ -16360,12 +17340,12 @@ async function runExport(opts) {
16360
17340
  const plan = await readPlan(opts.cwd);
16361
17341
  const bundle = { schema: "export/v1", inventory, plan: plan ?? null };
16362
17342
  if (opts.out) {
16363
- const { mkdir: mkdir14, writeFile: writeFile22 } = await import("fs/promises");
17343
+ const { mkdir: mkdir14, writeFile: writeFile23 } = await import("fs/promises");
16364
17344
  const { join: join39 } = await import("path");
16365
17345
  await mkdir14(opts.out, { recursive: true });
16366
- await writeFile22(join39(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
17346
+ await writeFile23(join39(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
16367
17347
  `, "utf8");
16368
- if (plan) await writeFile22(join39(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
17348
+ if (plan) await writeFile23(join39(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
16369
17349
  `, "utf8");
16370
17350
  return { schema: "export/v1", out: opts.out, wrote: ["inventory.json", ...plan ? ["plan.json"] : []] };
16371
17351
  }
@@ -16851,7 +17831,7 @@ function verifyWebhookSignature(secret, raw, header3) {
16851
17831
  return given.length === expected.length && timingSafeEqual(given, expected);
16852
17832
  }
16853
17833
  var MAX_EVENTS = 500;
16854
- var repoNames = (list2) => Array.isArray(list2) ? list2.map((r) => r?.full_name).filter((n) => typeof n === "string" && /^[\w.-]+\/[\w.-]+$/.test(n)).slice(0, 1e3) : [];
17834
+ var repoNames = (list3) => Array.isArray(list3) ? list3.map((r) => r?.full_name).filter((n) => typeof n === "string" && /^[\w.-]+\/[\w.-]+$/.test(n)).slice(0, 1e3) : [];
16855
17835
  function applyWebhook(state, event, payload, now = /* @__PURE__ */ new Date()) {
16856
17836
  const installationId = Number(payload?.installation?.id);
16857
17837
  if (!Number.isSafeInteger(installationId) || installationId <= 0) return { handled: false, detail: "no installation" };
@@ -16995,20 +17975,20 @@ init_spec();
16995
17975
  init_scenarios();
16996
17976
  init_local();
16997
17977
  init_docker();
16998
- import { createHash as createHash16 } from "crypto";
17978
+ import { createHash as createHash17 } from "crypto";
16999
17979
  import { execFile as execFile10 } from "child_process";
17000
17980
  import { promisify as promisify10 } from "util";
17001
- import { chmod as chmod4, mkdir as mkdir11, mkdtemp as mkdtemp11, readFile as readFile23, writeFile as writeFile18, rm as rm13, copyFile as copyFile3 } from "fs/promises";
17981
+ import { chmod as chmod4, mkdir as mkdir11, mkdtemp as mkdtemp11, readFile as readFile23, writeFile as writeFile19, rm as rm13, copyFile as copyFile3 } from "fs/promises";
17002
17982
  import { tmpdir as tmpdir11 } from "os";
17003
17983
  import { dirname as dirname6, join as join31, relative as relative6, resolve as resolve10, sep as sep6 } from "path";
17004
17984
 
17005
17985
  // src/runtime/callable.ts
17006
17986
  init_entrypoints();
17007
17987
  import { build } from "esbuild";
17008
- import { readFile as readFile21, realpath as realpath5, writeFile as writeFile16 } from "fs/promises";
17988
+ import { readFile as readFile21, realpath as realpath6, writeFile as writeFile17 } from "fs/promises";
17009
17989
  import { resolve as resolve8, relative as relative5, isAbsolute as isAbsolute4, sep as sep4, join as join29, extname } from "path";
17010
- import { createHash as createHash14 } from "crypto";
17011
- var digest4 = (value) => createHash14("sha256").update(value).digest("hex");
17990
+ import { createHash as createHash15 } from "crypto";
17991
+ var digest4 = (value) => createHash15("sha256").update(value).digest("hex");
17012
17992
  var object5 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
17013
17993
  function argument(value, depth = 0) {
17014
17994
  if (depth > 8 || !object5(value)) throw new Error("Invalid callable argument binding");
@@ -17043,10 +18023,10 @@ function parseCallable(value) {
17043
18023
  return value;
17044
18024
  }
17045
18025
  async function resolveCallableSource(root, entrypoint) {
17046
- const canonical5 = await realpath5(root);
18026
+ const canonical5 = await realpath6(root);
17047
18027
  const [file, member, ...extra] = entrypoint.split("#");
17048
18028
  if (extra.length || !file || !member || isAbsolute4(file) || file.includes("\\") || file.split("/").some((part) => part === ".." || part === ".") || !/\.(?:[cm]?[jt]s|tsx|jsx)$/.test(file)) throw new Error("Callable requires a repository-relative JavaScript/TypeScript discovered entrypoint");
17049
- const source = await realpath5(resolve8(canonical5, file));
18029
+ const source = await realpath6(resolve8(canonical5, file));
17050
18030
  if (source !== resolve8(canonical5, file) || relative5(canonical5, source).startsWith(".." + sep4)) throw new Error("Callable source escapes the project or uses a symlink");
17051
18031
  const text3 = await readFile21(source, "utf8"), entries = exportedEntrypoints(text3).filter((entry) => !entry.name.includes(":"));
17052
18032
  let selected = entries.find((entry) => entry.name === member);
@@ -17089,7 +18069,7 @@ for(const [index,call]of invocation.calls.entries()){
17089
18069
  let bytes = 0;
17090
18070
  const built = await build({ absWorkingDir: canonical5, stdin: { contents: driver, resolveDir: canonical5, sourcefile: "agenttwin-invocation.mjs", loader: "js" }, bundle: true, platform: "node", target: "node22", format: "cjs", write: false, metafile: true, logLevel: "silent", ...options.sourceMaps ? { sourcemap: "inline", sourcesContent: false, outfile: join29(canonical5, "application.cjs") } : {}, plugins: [{ name: "bounded-project-source", setup(plugin) {
17091
18071
  plugin.onLoad({ filter: /.*/ }, async (args) => {
17092
- const path2 = await realpath5(args.path), rel = relative5(canonical5, path2);
18072
+ const path2 = await realpath6(args.path), rel = relative5(canonical5, path2);
17093
18073
  if (isAbsolute4(rel) || rel === ".." || rel.startsWith(".." + sep4) || rel.split(sep4).some((part) => /^(?:\.env.*|\.git|\.ssh|\.aws)$/.test(part)) || !/\.(?:[cm]?[jt]s|tsx|jsx|json)$/.test(path2)) throw new Error("Build input is outside approved project JavaScript/TypeScript/JSON: " + rel);
17094
18074
  const contents = await readFile21(path2);
17095
18075
  bytes += contents.length;
@@ -17102,7 +18082,7 @@ for(const [index,call]of invocation.calls.entries()){
17102
18082
  } }] });
17103
18083
  const code = built.outputFiles[0].contents;
17104
18084
  if (code.length > 20 * 1024 * 1024) throw new Error("Callable bundle exceeds 20 MiB");
17105
- await writeFile16(join29(out, "application.cjs"), code, { flag: "wx", mode: 384 });
18085
+ await writeFile17(join29(out, "application.cjs"), code, { flag: "wx", mode: 384 });
17106
18086
  return { schema: "agenttwin/callable-build-v1", entrypoint, export: selected.name, invocation, sourceDigests: sources, invocationDigest: digest4(driver), bundleDigest: digest4(code), files: ["application.cjs"], command: ["node", "application.cjs"], coverage: "Actual exported application source; only explicitly configured invocation and dependency bindings are covered. No application scripts executed during compilation." };
17107
18087
  }
17108
18088
 
@@ -17110,12 +18090,12 @@ for(const [index,call]of invocation.calls.entries()){
17110
18090
  init_source_build();
17111
18091
 
17112
18092
  // src/runtime/protected-callable.ts
17113
- import { createHash as createHash15 } from "crypto";
17114
- import { lstat as lstat3, readFile as readFile22, realpath as realpath6, mkdir as mkdir10, writeFile as writeFile17, mkdtemp as mkdtemp10, rm as rm12 } from "fs/promises";
18093
+ import { createHash as createHash16 } from "crypto";
18094
+ import { lstat as lstat3, readFile as readFile22, realpath as realpath7, mkdir as mkdir10, writeFile as writeFile18, mkdtemp as mkdtemp10, rm as rm12 } from "fs/promises";
17115
18095
  import { dirname as dirname5, join as join30, resolve as resolve9, sep as sep5 } from "path";
17116
18096
  import { tmpdir as tmpdir10 } from "os";
17117
18097
  init_source_build();
17118
- var hash2 = (bytes) => createHash15("sha256").update(bytes).digest("hex");
18098
+ var hash2 = (bytes) => createHash16("sha256").update(bytes).digest("hex");
17119
18099
  function safeBuildPath(file) {
17120
18100
  return typeof file === "string" && !file.startsWith("/") && !file.includes("\\") && file.split("/").every((part) => part && part !== "." && part !== ".." && !/^(?:\.env.*|\.git|\.ssh|\.aws|\.azure|\.config|\.npmrc|\.netrc|credentials.*)$/i.test(part)) && /\.(?:[cm]?[jt]s|tsx|jsx|json)$/.test(file);
17121
18101
  }
@@ -17131,8 +18111,8 @@ function parseProtectedCallable(value) {
17131
18111
  }
17132
18112
  async function boundedBuildFile(root, file) {
17133
18113
  if (!safeBuildPath(file)) throw Error("Unsafe protected build path");
17134
- const canonical5 = await realpath6(root), path2 = resolve9(canonical5, file), info = await lstat3(path2);
17135
- if (!info.isFile() || await realpath6(path2) !== path2 || info.size > 20 * 1024 * 1024) throw Error("Protected build file is missing, oversized or uses a symlink: " + file);
18114
+ const canonical5 = await realpath7(root), path2 = resolve9(canonical5, file), info = await lstat3(path2);
18115
+ if (!info.isFile() || await realpath7(path2) !== path2 || info.size > 20 * 1024 * 1024) throw Error("Protected build file is missing, oversized or uses a symlink: " + file);
17136
18116
  const bytes = await readFile22(path2);
17137
18117
  if (bytes.length > 20 * 1024 * 1024) throw Error("Protected build file exceeds bounds");
17138
18118
  return bytes;
@@ -17146,13 +18126,13 @@ async function stageTrustedBuildFiles(cwd, out, files) {
17146
18126
  if (hash2(bytes) !== expected) throw Error("Trusted dependency or resolution metadata changed: " + file + "; restore the baseline installation or review a new regression");
17147
18127
  const target = join30(out, file);
17148
18128
  await mkdir10(dirname5(target), { recursive: true });
17149
- await writeFile17(target, bytes, { mode: 420 });
18129
+ await writeFile18(target, bytes, { mode: 420 });
17150
18130
  }
17151
18131
  }
17152
18132
 
17153
18133
  // src/runtime/regressions.ts
17154
18134
  var exec8 = promisify10(execFile10);
17155
- var hash3 = (v) => createHash16("sha256").update(v).digest("hex");
18135
+ var hash3 = (v) => createHash17("sha256").update(v).digest("hex");
17156
18136
  var identifier2 = /^[a-z][a-z0-9_]{0,39}$/;
17157
18137
  function parseRegression(v) {
17158
18138
  const r = v;
@@ -17190,7 +18170,7 @@ async function runProtectedCheck(cwd, opts) {
17190
18170
  if (revision === result2.candidateRevision) result2.sourceDigests[file] = hash3(bytes);
17191
18171
  const dest = join31(directory, file);
17192
18172
  await mkdir11(resolve10(dest, ".."), { recursive: true });
17193
- await writeFile18(dest, bytes, { mode: 420 });
18173
+ await writeFile19(dest, bytes, { mode: 420 });
17194
18174
  };
17195
18175
  let executionSpec = regression.spec;
17196
18176
  if (regression.callable) {
@@ -17382,9 +18362,9 @@ async function runPrCheck(cwd, opts = {}) {
17382
18362
  const diff = await git(cwd, "diff", "--unified=0", "--no-color", `${base}...${head}`).catch(() => git(cwd, "diff", "--unified=0", "--no-color", base, head));
17383
18363
  const lines = changedLines(diff);
17384
18364
  const changed = new Set(lines.keys());
17385
- const list2 = async (rev) => (await git(cwd, "ls-tree", "-r", "--name-only", rev, "--", ".agenttwin/regressions")).split("\n").filter((f) => f.endsWith(".json"));
17386
- const baseRegressions = await list2(base);
17387
- const added = (await list2(head)).filter((f) => !baseRegressions.includes(f));
18365
+ const list3 = async (rev) => (await git(cwd, "ls-tree", "-r", "--name-only", rev, "--", ".agenttwin/regressions")).split("\n").filter((f) => f.endsWith(".json"));
18366
+ const baseRegressions = await list3(base);
18367
+ const added = (await list3(head)).filter((f) => !baseRegressions.includes(f));
17388
18368
  const costs = await git(cwd, "show", `${base}:agenttwin.costs.json`).then((t) => JSON.parse(t)).catch(() => void 0);
17389
18369
  const regressions = [];
17390
18370
  for (const file of opts.execute === false ? [] : baseRegressions) {
@@ -17432,17 +18412,20 @@ async function runPrCheck(cwd, opts = {}) {
17432
18412
  file: op2.file,
17433
18413
  line: op2.line,
17434
18414
  level: "warning",
17435
- title: `AgentTwin: untested write to ${serviceTitle(op2.service)}`,
17436
- message: `This change reaches ${serviceTitle(op2.service)} ${op2.operation} in "${w.title}", and no AgentTwin check covers it yet. Add one: npx agenttwin --workflow <name>, then lock a passing run.`
18415
+ title: `AgentTwin: calls ${serviceTitle(op2.service)} with no check`,
18416
+ message: `This line sends ${serviceTitle(op2.service)} ${op2.operation} (part of "${w.title}"). No AgentTwin check runs it. Run npx agenttwin --workflow ${w.title}, fix what it finds, and commit the saved run in .agenttwin/regressions/.`
17437
18417
  });
17438
18418
  const verdict = failed.length ? "fail" : incomplete.length || notRun.length ? "incomplete" : uncovered.length ? "warn" : "pass";
17439
18419
  const services = [...new Set(touched.flatMap((w) => w.operations.filter((o) => o.changed).map((o) => serviceTitle(o.service))))];
17440
- const headline = verdict === "fail" ? `${failed.length} of ${regressions.length} twin check${regressions.length === 1 ? "" : "s"} failed${atRisk ? ` \xB7 ${formatMoney(atRisk)} at risk` : ""}` : verdict === "incomplete" && notRun.length && !incomplete.length ? `This PR changes code under ${notRun.length} locked twin check${notRun.length === 1 ? " that needs" : "s that need"} an isolated runner` : verdict === "incomplete" ? `${incomplete.length} twin check${incomplete.length === 1 ? "" : "s"} could not run` : verdict === "warn" ? `Untested change to ${services.join(", ") || "an external service"}` : regressions.length === 1 ? "The twin check passed" : regressions.length ? `All ${regressions.length} twin checks passed` : "No agent side effects changed";
18420
+ const headline = verdict === "fail" ? `${failed.length} of ${regressions.length} twin check${regressions.length === 1 ? "" : "s"} failed${atRisk ? ` \xB7 ${formatMoney(atRisk)} at risk` : ""}` : verdict === "incomplete" && notRun.length && !incomplete.length ? `This pull request changes code ${notRun.length === 1 ? "a saved check covers, and the check" : `${notRun.length} saved checks cover, and they`} did not run here` : verdict === "incomplete" ? `${incomplete.length} twin check${incomplete.length === 1 ? "" : "s"} could not run` : verdict === "warn" ? (() => {
18421
+ const n = new Set(uncovered.flatMap((w) => w.operations.filter((o) => o.changed).map((o) => `${o.file}:${o.line}`))).size;
18422
+ return `${n} changed line${n === 1 ? " calls" : "s call"} ${services.length > 1 ? `${services.slice(0, -1).join(", ")} and ${services[services.length - 1]}` : services[0] || "an external service"} with no check`;
18423
+ })() : regressions.length === 1 ? "The twin check passed" : regressions.length ? `All ${regressions.length} twin checks passed` : "No agent side effects changed";
17441
18424
  const notes = [];
17442
- if (notRun.length) notes.push(`Not run here: ${notRun.join(", ")}. Run npx agenttwin check in CI, or configure the hosted Docker runner.`);
17443
- if (opts.execute === false && baseRegressions.length && !notRun.length) notes.push(`${baseRegressions.length} locked twin check${baseRegressions.length === 1 ? "" : "s"} not run here: executing pull-request code needs an isolated runner. Run them with npx agenttwin check in CI.`);
17444
- if (runtime === "local" && regressions.length) notes.push("Checks ran without container isolation. Set AGENTTWIN_RUNNER_IMAGE (digest-pinned) to run them in Docker.");
17445
- if (added.length) notes.push(`${added.length} new check${added.length === 1 ? "" : "s"} added in this pull request; ${added.length === 1 ? "it runs" : "they run"} after merge, when the base owns ${added.length === 1 ? "it" : "them"}.`);
18425
+ if (notRun.length) notes.push(`${notRun.length} saved check${notRun.length === 1 ? "" : "s"} (${notRun.join(", ")}) did not run: this check does not run pull-request code on AgentTwin's servers. To run ${notRun.length === 1 ? "it" : "them"} on every pull request, add AgentTwin to your CI with npx agenttwin check install.`);
18426
+ if (opts.execute === false && baseRegressions.length && !notRun.length) notes.push(`${baseRegressions.length} saved check${baseRegressions.length === 1 ? "" : "s"} did not run: this check does not run pull-request code on AgentTwin's servers. To run ${baseRegressions.length === 1 ? "it" : "them"} on every pull request, add AgentTwin to your CI with npx agenttwin check install.`);
18427
+ if (runtime === "local" && regressions.length) notes.push("Checks ran directly on the CI machine, not in a container. To isolate them, set AGENTTWIN_RUNNER_IMAGE to a Docker image pinned by digest.");
18428
+ if (added.length) notes.push(`This pull request adds ${added.length} check${added.length === 1 ? "" : "s"}. ${added.length === 1 ? "It runs" : "They run"} on later pull requests, after this one is merged: a pull request cannot change the checks that judge it.`);
17446
18429
  return { schema: "agenttwin/pr-check-v1", createdAt: (/* @__PURE__ */ new Date()).toISOString(), base, head, verdict, headline, changedFiles: [...changed], regressions, addedRegressions: added, touched, ...atRisk ? { atRisk } : {}, ...cost ? { cost } : {}, annotations, notes };
17447
18430
  }
17448
18431
 
@@ -17475,6 +18458,19 @@ ${r.checks.filter((c) => !c.passed).map((c) => `- ${c.text}`).join("\n")}`,
17475
18458
  `Verify locally: npx agenttwin check --base ${short2(report.base)}`
17476
18459
  ].filter(Boolean).join("\n\n");
17477
18460
  }
18461
+ var list2 = (items) => items.length <= 1 ? items[0] ?? "an external service" : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
18462
+ function uncoveredLines(report) {
18463
+ const byLine = /* @__PURE__ */ new Map();
18464
+ for (const w of report.touched.filter((t) => !t.covered)) for (const o of w.operations.filter((op2) => op2.changed)) {
18465
+ const key2 = `${o.file}:${o.line}`, entry = byLine.get(key2) ?? { file: o.file, line: o.line, services: [], sends: [], workflows: [] };
18466
+ const service = serviceTitle(o.service), send2 = `${service} \xB7 \`${o.operation}\``;
18467
+ if (!entry.services.includes(service)) entry.services.push(service);
18468
+ if (!entry.sends.includes(send2)) entry.sends.push(send2);
18469
+ if (!entry.workflows.includes(w.title)) entry.workflows.push(w.title);
18470
+ byLine.set(key2, entry);
18471
+ }
18472
+ return [...byLine.values()].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
18473
+ }
17478
18474
  function renderMarkdown(report, opts = {}) {
17479
18475
  const out = [];
17480
18476
  if (opts.comment) out.push(COMMENT_MARKER);
@@ -17516,18 +18512,32 @@ function renderMarkdown(report, opts = {}) {
17516
18512
  for (const c of r.checks) out.push(`- ${c.passed ? "\u2705" : "\u274C"} ${c.text}`);
17517
18513
  out.push("", "<details><summary>Fix task for Claude Code, Codex or Cursor</summary>", "", "```text", fixTask(report, r), "```", "", "</details>", "");
17518
18514
  }
17519
- const uncovered = report.touched.filter((w) => !w.covered && w.operations.some((o) => o.changed));
18515
+ const uncovered = uncoveredLines(report);
17520
18516
  if (uncovered.length) {
17521
- out.push("### Changed code with no twin check", "", "| Where | Reaches | Workflow |", "|---|---|---|");
17522
- for (const w of uncovered) for (const o of w.operations.filter((op2) => op2.changed))
17523
- out.push(`| \`${o.file}:${o.line}\` | ${serviceTitle(o.service)} \`${cell(o.operation)}\` | ${cell(w.title)} |`);
17524
- out.push("", "Add a check: run `npx agenttwin --workflow <name>` on this workflow and lock a passing run. It then runs on every pull request.", "");
18517
+ const services = [...new Set(uncovered.flatMap((u) => u.services))];
18518
+ out.push(`These lines send requests to ${list2(services)}. No AgentTwin check runs them, so nothing shows what your code does when ${services.length === 1 ? "that service times out, fails or gets" : "those services time out, fail or get"} the same request twice.`, "");
18519
+ out.push("| Line | Sends | Part of |", "|---|---|---|");
18520
+ for (const u of uncovered.slice(0, 15)) {
18521
+ const where = opts.repository ? `[\`${u.file}:${u.line}\`](https://github.com/${opts.repository}/blob/${report.head}/${u.file}#L${u.line})` : `\`${u.file}:${u.line}\``;
18522
+ const flows = u.workflows.slice(0, 2).map((w) => `\`${cell(w)}\``).join(", ") + (u.workflows.length > 2 ? ` and ${u.workflows.length - 2} more` : "");
18523
+ out.push(`| ${where} | ${cell(u.sends.join(", "))} | ${flows} |`);
18524
+ }
18525
+ if (uncovered.length > 15) out.push("", `\u2026and ${uncovered.length - 15} more lines in the [full report](${opts.detailsUrl ?? "#"}).`);
18526
+ const first = uncovered[0].workflows[0];
18527
+ out.push(
18528
+ "",
18529
+ "**To cover them:**",
18530
+ `1. Run \`npx agenttwin --workflow ${first ?? "<name>"}\` on your machine. It runs the workflow against a simulated ${uncovered[0].services[0] ?? "service"} and tries timeouts, errors and duplicate requests.`,
18531
+ "2. If it finds a problem, fix it and run it again. The passing run is saved in `.agenttwin/regressions/`.",
18532
+ "3. Commit that file. This check then reruns it on every pull request.",
18533
+ ""
18534
+ );
17525
18535
  }
17526
18536
  const covered = report.touched.filter((w) => w.covered && w.operations.some((o) => o.changed));
17527
18537
  if (covered.length) out.push(`<sub>Changed and covered: ${covered.map((w) => cell(w.title)).join(", ")}.</sub>`, "");
17528
- if (!report.regressions.length && !report.touched.length) out.push("No code in this pull request reaches an external system AgentTwin knows about.", "");
18538
+ if (!report.regressions.length && !report.touched.length) out.push("No line in this pull request calls an external service AgentTwin knows about, so there is nothing to check.", "");
17529
18539
  for (const note of report.notes) out.push(`<sub>${note}</sub>`);
17530
- out.push(`<sub>Your code ran against digital twins with synthetic data; nothing reached a real service. Base \`${short2(report.base)}\` \u2192 head \`${short2(report.head)}\`${opts.detailsUrl ? ` \xB7 [Full report](${opts.detailsUrl})` : ""}</sub>`);
18540
+ out.push(`<sub>AgentTwin runs your code against simulated copies of each service with made-up data; nothing is sent to the real service. Compared \`${short2(report.base)}\` \u2192 \`${short2(report.head)}\`${opts.detailsUrl ? ` \xB7 [Full report](${opts.detailsUrl})` : ""}</sub>`);
17531
18541
  return out.join("\n") + "\n";
17532
18542
  }
17533
18543
 
@@ -17556,7 +18566,7 @@ async function startCheckRun(target) {
17556
18566
  }
17557
18567
  async function publishCheckRun(report, target, existing) {
17558
18568
  const annotations = report.annotations.map((a) => ({ path: a.file, start_line: a.line, end_line: a.line, annotation_level: a.level, title: a.title.slice(0, 255), message: a.message.slice(0, 64e3) }));
17559
- const summary = renderMarkdown(report, { detailsUrl: target.detailsUrl });
18569
+ const summary = renderMarkdown(report, { detailsUrl: target.detailsUrl, repository: target.repository });
17560
18570
  const output = (batch) => ({ title: report.headline.slice(0, 255), summary: summary.length > MAX_SUMMARY ? summary.slice(0, MAX_SUMMARY) + "\n\u2026" : summary, annotations: batch });
17561
18571
  const run3 = await api(target, existing ? "PATCH" : "POST", `/repos/${target.repository}/check-runs${existing ? `/${existing}` : ""}`, {
17562
18572
  ...existing ? {} : { name: CHECK_NAME, head_sha: target.sha },
@@ -17571,7 +18581,7 @@ async function publishCheckRun(report, target, existing) {
17571
18581
  }
17572
18582
  async function upsertComment(report, target) {
17573
18583
  if (!target.pullRequest) return void 0;
17574
- const body2 = renderMarkdown(report, { comment: true, detailsUrl: target.detailsUrl });
18584
+ const body2 = renderMarkdown(report, { comment: true, detailsUrl: target.detailsUrl, repository: target.repository });
17575
18585
  for (let page2 = 1; page2 <= 10; page2++) {
17576
18586
  const comments = await api(target, "GET", `/repos/${target.repository}/issues/${target.pullRequest}/comments?per_page=100&page=${page2}`);
17577
18587
  const mine = comments.find((c) => c.body?.startsWith(COMMENT_MARKER));
@@ -17704,7 +18714,7 @@ function requestBudget(limit2 = 1200) {
17704
18714
  }
17705
18715
 
17706
18716
  // src/runtime/oauth.ts
17707
- import { createHash as createHash20, randomBytes as randomBytes5, timingSafeEqual as timingSafeEqual3 } from "crypto";
18717
+ import { createHash as createHash21, randomBytes as randomBytes5, timingSafeEqual as timingSafeEqual3 } from "crypto";
17708
18718
  var oauthScopes = {
17709
18719
  "read:projects": "List this client\u2019s one authorized project",
17710
18720
  "read:discovery": "Read discovery metadata for the authorized project",
@@ -17716,7 +18726,7 @@ var oauthScopes = {
17716
18726
  "write:preparations": "Select and cancel local preparation requests for the authorized project",
17717
18727
  "work:preparations": "Claim and report preparation metadata; does not approve or execute application code"
17718
18728
  };
17719
- var hash4 = (v) => createHash20("sha256").update(v).digest("hex");
18729
+ var hash4 = (v) => createHash21("sha256").update(v).digest("hex");
17720
18730
  var matches3 = (a, b) => timingSafeEqual3(Buffer.from(hash4(a)), Buffer.from(b));
17721
18731
  function newOAuthClient(accountId, label2, project, scopes) {
17722
18732
  if (!Array.isArray(scopes) || !scopes.length || scopes.length > Object.keys(oauthScopes).length || scopes.some(
@@ -18000,8 +19010,8 @@ It expires in 10 minutes. Do not share this code. If you did not request it, ign
18000
19010
 
18001
19011
  // src/runtime/social-auth.ts
18002
19012
  import * as oidc from "openid-client";
18003
- import { randomBytes as randomBytes7, createHash as createHash21, timingSafeEqual as timingSafeEqual5 } from "crypto";
18004
- var hash5 = (value) => createHash21("sha256").update(value).digest();
19013
+ import { randomBytes as randomBytes7, createHash as createHash22, timingSafeEqual as timingSafeEqual5 } from "crypto";
19014
+ var hash5 = (value) => createHash22("sha256").update(value).digest();
18005
19015
  var validUrl = (value) => {
18006
19016
  const url = new URL(value);
18007
19017
  if (url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname))) throw new Error("Authentication URLs must use HTTPS (or local HTTP).");
@@ -18111,8 +19121,8 @@ function createSocialAuth(options) {
18111
19121
  }
18112
19122
 
18113
19123
  // src/runtime/auth.ts
18114
- import { randomBytes as randomBytes8, scrypt, timingSafeEqual as timingSafeEqual6, createHash as createHash22 } from "crypto";
18115
- var digest5 = (value) => createHash22("sha256").update(value).digest("hex");
19124
+ import { randomBytes as randomBytes8, scrypt, timingSafeEqual as timingSafeEqual6, createHash as createHash23 } from "crypto";
19125
+ var digest5 = (value) => createHash23("sha256").update(value).digest("hex");
18116
19126
  var derive = (password, salt) => new Promise((resolve13, reject) => scrypt(password, salt, 64, { N: 131072, r: 8, p: 1, maxmem: 160 * 1024 * 1024 }, (error, key2) => error ? reject(error) : resolve13(key2)));
18117
19127
  async function passwordHash(password) {
18118
19128
  const salt = randomBytes8(16).toString("hex");
@@ -18142,8 +19152,8 @@ init_dashboard_transfer();
18142
19152
  import { generateRegistrationOptions, verifyRegistrationResponse, generateAuthenticationOptions, verifyAuthenticationResponse } from "@simplewebauthn/server";
18143
19153
  import { isDeepStrictEqual as isDeepStrictEqual9 } from "util";
18144
19154
  import { createServer as createServer7 } from "http";
18145
- import { createHash as createHash28, randomBytes as randomBytes11, randomUUID as randomUUID10, timingSafeEqual as timingSafeEqual7 } from "crypto";
18146
- import { mkdir as mkdir13, readFile as readFile26, writeFile as writeFile21, rename as rename3, mkdtemp as mkdtemp14, rm as rm17 } from "fs/promises";
19155
+ import { createHash as createHash29, randomBytes as randomBytes11, randomUUID as randomUUID10, timingSafeEqual as timingSafeEqual7 } from "crypto";
19156
+ import { mkdir as mkdir13, readFile as readFile26, writeFile as writeFile22, rename as rename3, mkdtemp as mkdtemp14, rm as rm17 } from "fs/promises";
18147
19157
  import { resolve as resolve12, join as join38, dirname as dirname7, extname as extname2 } from "path";
18148
19158
  import { tmpdir as tmpdir15 } from "os";
18149
19159
 
@@ -18250,8 +19260,8 @@ import { join as join37 } from "path";
18250
19260
 
18251
19261
  // src/runtime/repair-proof.ts
18252
19262
  init_run_summary();
18253
- import { createHash as createHash23, randomUUID as randomUUID7 } from "crypto";
18254
- import { mkdir as mkdir12, readFile as readFile24, rm as rm16, writeFile as writeFile20 } from "fs/promises";
19263
+ import { createHash as createHash24, randomUUID as randomUUID7 } from "crypto";
19264
+ import { mkdir as mkdir12, readFile as readFile24, rm as rm16, writeFile as writeFile21 } from "fs/promises";
18255
19265
  import { isAbsolute as isAbsolute5, join as join36, relative as relative7, resolve as resolve11, sep as sep7 } from "path";
18256
19266
 
18257
19267
  // src/runtime/receipt-sync.ts
@@ -18260,8 +19270,17 @@ function validProof(p, runId) {
18260
19270
  const run3 = (r) => r === null || r && typeof r.runId === "string" && text2(r.status, 20) && Number.isSafeInteger(r.failed) && Number.isSafeInteger(r.total) && Array.isArray(r.checks) && r.checks.length <= 300 && r.checks.every((c) => c && text2(c.text, 2e3) && typeof c.passed === "boolean");
18261
19271
  return !!p && p.schema === "agenttwin/proof-v1" && /^[a-f0-9-]{36}$/.test(p.id) && text2(p.workflow, 200) && ["red-to-green", "still-red", "not-applied", "incomplete"].includes(p.verdict) && run3(p.before) && p.before !== null && run3(p.after) && (p.before.runId === runId || p.after?.runId === runId) && (p.verdict !== "red-to-green" || p.after?.status === "passed" && p.before.status !== "passed") && Array.isArray(p.findings) && p.findings.length <= 50 && p.findings.every((f) => f && text2(f.title, 500) && text2(f.kind, 40) && Array.isArray(f.impact) && f.impact.every((i) => text2(i, 500)) && Array.isArray(f.timeline) && f.timeline.length <= 200) && Array.isArray(p.services) && Array.isArray(p.faults) && (p.fix === null || p.fix && text2(p.fix.title, 2e3) && text2(p.fix.rationale, 4e3) && (p.fix.diff === void 0 || text2(p.fix.diff, 64 * 1024))) && Buffer.byteLength(JSON.stringify(p)) <= 256 * 1024;
18262
19272
  }
18263
- function portableLocalReceipt(value) {
19273
+ function normalizeReceipt(value) {
18264
19274
  const r = value;
19275
+ if (!r || typeof r !== "object") return value;
19276
+ const digests = r.sourceDigests && typeof r.sourceDigests === "object" && !Array.isArray(r.sourceDigests) ? r.sourceDigests : {};
19277
+ const inside = (file) => !file.startsWith("/") && !/^[A-Za-z]:/.test(file) && !file.split(/[\\/]/).includes("..");
19278
+ const events = Array.isArray(r.events) ? r.events.map((e) => e && e.source && typeof e.source.file === "string" && inside(e.source.file) && !Object.hasOwn(digests, e.source.file) ? (({ source: _drop, ...rest }) => rest)(e) : e) : r.events;
19279
+ const evaluation = r.evaluation && Array.isArray(r.evaluation.checks) ? { ...r.evaluation, checks: r.evaluation.checks.map((c) => c && c.kind === "default" ? { ...c, kind: "forbidden-effect" } : c) } : r.evaluation;
19280
+ return { ...r, events, ...r.evaluation !== void 0 ? { evaluation } : {} };
19281
+ }
19282
+ function portableLocalReceipt(value) {
19283
+ const r = normalizeReceipt(value);
18265
19284
  const uuid3 = (v) => typeof v === "string" && /^[a-f0-9-]{36}$/.test(v);
18266
19285
  if (r?.applicationClock !== void 0 && (!["local", "docker"].includes(r.runtime) || !validApplicationClockEvidence(r.applicationClock))) throw new Error("Invalid application clock evidence");
18267
19286
  if (!r || r.schema !== "agenttwin/run-v1" || !["local", "docker"].includes(r.runtime) || !uuid3(r.runId) || typeof r.name !== "string" || !/^[a-z][a-z0-9_]{0,39}$/.test(r.name) || typeof r.project !== "string" || r.project.length > 240 || /[\x00-\x1f]/.test(r.project) || !["passed", "failed", "error", "incomplete"].includes(r.status) || typeof r.createdAt !== "string" || !Number.isFinite(Date.parse(r.createdAt)) || !Number.isFinite(r.durationMs) || r.durationMs < 0 || !r.application || !Array.isArray(r.application.command) || !RUNTIMES.test(String(r.application.command[0])) || r.application.command.some((v) => typeof v !== "string") || !Array.isArray(r.assertions) || !r.assertions.length || r.assertions.length > 100 || r.assertions.some((a) => typeof a.service !== "string" || typeof a.path !== "string" || typeof a.passed !== "boolean" || !Number.isSafeInteger(a.count) || a.count < 0 || !Number.isSafeInteger(a.actual) || a.actual < 0 || a.passed !== (a.count === a.actual)) || !Array.isArray(r.events) || r.events.length > 5e4 || !r.finalState || typeof r.finalState !== "object" || !r.initialState || typeof r.initialState !== "object" || !r.sourceDigests || typeof r.sourceDigests !== "object" || !/^[a-f0-9]{64}$/.test(r.specDigest)) throw new Error("Invalid CLI receipt");
@@ -18299,7 +19318,7 @@ function portableLocalReceipt(value) {
18299
19318
  init_run();
18300
19319
 
18301
19320
  // src/runtime/analytics.ts
18302
- import { createHash as createHash24 } from "crypto";
19321
+ import { createHash as createHash25 } from "crypto";
18303
19322
  function analyticsConfiguration() {
18304
19323
  const key2 = process.env.POSTHOG_API_KEY;
18305
19324
  const host = process.env.POSTHOG_API_HOST || "https://us.i.posthog.com";
@@ -18336,7 +19355,7 @@ function captureAnalytics(event) {
18336
19355
  // package.json
18337
19356
  var package_default = {
18338
19357
  name: "agenttwin",
18339
- version: "0.3.30",
19358
+ version: "0.3.31",
18340
19359
  description: "AgentTwin builds digital twins for testing AI agents. The current CLI prepares supported Node.js workflows with synthetic services, failures, and outcome checks.",
18341
19360
  mcpName: "io.github.AgentTwin/agenttwin",
18342
19361
  keywords: [
@@ -18390,6 +19409,7 @@ var package_default = {
18390
19409
  bson: "^6.10.4",
18391
19410
  e2b: "^2.52.1",
18392
19411
  esbuild: "0.28.2",
19412
+ fengari: "0.1.5",
18393
19413
  "openid-client": "^6.8.8",
18394
19414
  pg: "^8.23.1",
18395
19415
  playwright: "1.64.1",
@@ -18431,7 +19451,7 @@ var package_default = {
18431
19451
  var VERSION = package_default.version;
18432
19452
 
18433
19453
  // src/runtime/audit-export.ts
18434
- import { createHash as createHash25, createPrivateKey, createPublicKey, sign, verify } from "crypto";
19454
+ import { createHash as createHash26, createPrivateKey, createPublicKey, sign, verify } from "crypto";
18435
19455
  var AUDIT_EXPORT_SCHEMA = "agenttwin/audit-export-v1";
18436
19456
  var GENESIS = "0".repeat(64);
18437
19457
  function canonical4(value) {
@@ -18439,7 +19459,7 @@ function canonical4(value) {
18439
19459
  if (value && typeof value === "object") return "{" + Object.keys(value).sort().filter((k) => value[k] !== void 0).map((k) => JSON.stringify(k) + ":" + canonical4(value[k])).join(",") + "}";
18440
19460
  return JSON.stringify(value);
18441
19461
  }
18442
- var sha4 = (s) => createHash25("sha256").update(s).digest("hex");
19462
+ var sha4 = (s) => createHash26("sha256").update(s).digest("hex");
18443
19463
  function signingKey(pem = process.env.AGENTTWIN_AUDIT_SIGNING_KEY) {
18444
19464
  if (!pem) return void 0;
18445
19465
  const key2 = createPrivateKey(pem.replace(/\\n/g, "\n"));
@@ -18660,14 +19680,14 @@ async function remoteMcp(message, token, base, fetcher) {
18660
19680
  }
18661
19681
 
18662
19682
  // src/runtime/scim.ts
18663
- import { randomBytes as randomBytes10, randomUUID as randomUUID9, createHash as createHash27 } from "crypto";
19683
+ import { randomBytes as randomBytes10, randomUUID as randomUUID9, createHash as createHash28 } from "crypto";
18664
19684
 
18665
19685
  // src/runtime/teams.ts
18666
- import { createHash as createHash26, randomBytes as randomBytes9, randomUUID as randomUUID8 } from "crypto";
19686
+ import { createHash as createHash27, randomBytes as randomBytes9, randomUUID as randomUUID8 } from "crypto";
18667
19687
  var TEAM_ROLES = ["admin", "member", "viewer"];
18668
19688
  var INVITE_DAYS = 7;
18669
19689
  var AUDIT_LIMIT = 5e3;
18670
- var sha5 = (value) => createHash26("sha256").update(value).digest("hex");
19690
+ var sha5 = (value) => createHash27("sha256").update(value).digest("hex");
18671
19691
  var isRole = (value) => typeof value === "string" && TEAM_ROLES.includes(value);
18672
19692
  function resolveWorkspace(state, person, orgToken) {
18673
19693
  if (orgToken) return { workspace: person, role: orgToken.role, actorId: `token:${orgToken.id}`, actorLabel: `API token "${orgToken.label}"`, shared: true };
@@ -18741,7 +19761,7 @@ var SCIM_USER = "urn:ietf:params:scim:schemas:core:2.0:User";
18741
19761
  var LIST = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
18742
19762
  var PATCH = "urn:ietf:params:scim:api:messages:2.0:PatchOp";
18743
19763
  var ERROR = "urn:ietf:params:scim:api:messages:2.0:Error";
18744
- var sha6 = (v) => createHash27("sha256").update(v).digest("hex");
19764
+ var sha6 = (v) => createHash28("sha256").update(v).digest("hex");
18745
19765
  var scimError = (status, detail, scimType) => ({ status, body: { schemas: [ERROR], status: String(status), detail, ...scimType ? { scimType } : {} } });
18746
19766
  function userOf(store, workspaceId, a, base) {
18747
19767
  const m = (store.teamMembers ?? []).find((x) => x.accountId === workspaceId && x.memberId === a.id);
@@ -18847,7 +19867,7 @@ function handleScim(store, workspaceId, method, path2, query, input, base) {
18847
19867
  }
18848
19868
 
18849
19869
  // src/runtime/gateway.ts
18850
- var hash6 = (value) => createHash28("sha256").update(value).digest("hex");
19870
+ var hash6 = (value) => createHash29("sha256").update(value).digest("hex");
18851
19871
  function uploadPath(path2) {
18852
19872
  if (!path2 || path2.startsWith("/") || path2.includes("\\") || path2.includes("\0") || path2.split("/").some((p) => !p || p === "." || p === ".." || /^(\.env.*|\.git|\.ssh|\.aws|\.azure|\.config|\.npmrc|\.netrc|credentials.*)$/i.test(p)) || /\.(pem|key|p12|pfx)$/i.test(path2)) throw new Error("Unsafe uploaded file path");
18853
19873
  return path2;
@@ -18939,7 +19959,7 @@ async function startGateway(opts) {
18939
19959
  if (database) await database.write(snapshot);
18940
19960
  else {
18941
19961
  const path2 = join38(directory, `state-${randomUUID10()}.tmp`);
18942
- await writeFile21(path2, snapshot, { mode: 384 });
19962
+ await writeFile22(path2, snapshot, { mode: 384 });
18943
19963
  await rename3(path2, storePath2);
18944
19964
  }
18945
19965
  committedWorkflows = workflowView;
@@ -18984,12 +20004,12 @@ async function startGateway(opts) {
18984
20004
  for (const [file, encoded] of Object.entries(item.files)) {
18985
20005
  const destination = join38(workspace, uploadPath(file));
18986
20006
  await mkdir13(dirname7(destination), { recursive: true });
18987
- await writeFile21(destination, Buffer.from(encoded, "base64"), { mode: 384 });
20007
+ await writeFile22(destination, Buffer.from(encoded, "base64"), { mode: 384 });
18988
20008
  }
18989
- await writeFile21(join38(workspace, "agenttwin.world.json"), JSON.stringify(item.spec));
20009
+ await writeFile22(join38(workspace, "agenttwin.world.json"), JSON.stringify(item.spec));
18990
20010
  if (item.spec.workflowId) {
18991
20011
  await mkdir13(join38(workspace, ".agenttwin"));
18992
- await writeFile21(join38(workspace, ".agenttwin/inventory.json"), JSON.stringify({ workflows: [{ id: item.spec.workflowId }] }));
20012
+ await writeFile22(join38(workspace, ".agenttwin/inventory.json"), JSON.stringify({ workflows: [{ id: item.spec.workflowId }] }));
18993
20013
  }
18994
20014
  const receipt = await runWorld(workspace, { runtime: "e2b", seed: item.seed, signal: controllers.get(item.job.id)?.signal, log: () => {
18995
20015
  } });