agenttwin 0.3.30 → 0.3.32

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 +1743 -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-53525dd96c1c1e70.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/dQPcd2gl7ABZiL9lr9ruM/_buildManifest.js +1 -0
  84. package/dist/dashboard/index.html +2 -2
  85. package/dist/engine.js +5506 -1828
  86. package/dist/gateway.js +1741 -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 +1240 -478
  93. package/dist/world-host.js +1382 -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 → dQPcd2gl7ABZiL9lr9ruM}/_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,169 @@ var init_rest_adapters = __esm({
5802
6160
  }
5803
6161
  });
5804
6162
 
6163
+ // src/runtime/postgrest.ts
6164
+ import { createRequire as createRequire2 } from "module";
6165
+ var loadPg, ident2, OPS, RESERVED, PostgrestLayer;
6166
+ var init_postgrest = __esm({
6167
+ "src/runtime/postgrest.ts"() {
6168
+ "use strict";
6169
+ loadPg = () => createRequire2(import.meta.url)("pg");
6170
+ ident2 = (name) => `"${name.replace(/"/g, '""')}"`;
6171
+ OPS = { eq: "=", neq: "<>", gt: ">", gte: ">=", lt: "<", lte: "<=", like: "LIKE", ilike: "ILIKE" };
6172
+ RESERVED = /* @__PURE__ */ new Set(["select", "order", "limit", "offset", "on_conflict", "columns", "or", "and"]);
6173
+ PostgrestLayer = class _PostgrestLayer {
6174
+ pool;
6175
+ fks;
6176
+ constructor(databaseUrl) {
6177
+ this.pool = new (loadPg()).Pool({ connectionString: databaseUrl, max: 1 });
6178
+ }
6179
+ close() {
6180
+ return this.pool.end().catch(() => {
6181
+ });
6182
+ }
6183
+ foreignKeys() {
6184
+ 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"
6185
+ 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]
6186
+ 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, "") })));
6187
+ }
6188
+ /** Splits a select list at top-level commas: `id, name, prices(*, product:products(name))`. */
6189
+ static items(select) {
6190
+ const out = [];
6191
+ let depth = 0, cur = "";
6192
+ for (const c of select) {
6193
+ if (c === "(") depth++;
6194
+ if (c === ")") depth--;
6195
+ if (c === "," && !depth) {
6196
+ out.push(cur.trim());
6197
+ cur = "";
6198
+ } else cur += c;
6199
+ }
6200
+ if (cur.trim()) out.push(cur.trim());
6201
+ return out;
6202
+ }
6203
+ async columns(table2, alias, select) {
6204
+ const parts = [];
6205
+ for (const item of _PostgrestLayer.items(select || "*")) {
6206
+ const embed = /^(?:(\w+):)?(\w+)(?:!\w+)?\((.*)\)$/s.exec(item);
6207
+ if (!embed) {
6208
+ if (item === "*") {
6209
+ parts.push(`${alias}.*`);
6210
+ continue;
6211
+ }
6212
+ const m = /^(?:(\w+):)?(\w+)(?:::\w+)?$/.exec(item);
6213
+ if (!m) continue;
6214
+ parts.push(`${alias}.${ident2(m[2])} AS ${ident2(m[1] ?? m[2])}`);
6215
+ continue;
6216
+ }
6217
+ const [, as, rel, inner] = embed, fks = await this.foreignKeys(), child = `e${parts.length}_${alias}`;
6218
+ const many = fks.find((f) => f.table === rel && f.refTable === table2), one = fks.find((f) => f.table === table2 && f.refTable === rel);
6219
+ const cols = await this.columns(rel, child, inner);
6220
+ 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)}`);
6221
+ 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)}`);
6222
+ }
6223
+ return parts.join(", ") || `${alias}.*`;
6224
+ }
6225
+ /** WHERE clause from `col=op.value` query parameters. */
6226
+ static where(params, values) {
6227
+ const clauses = [];
6228
+ for (const [key2, raw] of params) {
6229
+ if (RESERVED.has(key2)) continue;
6230
+ const not = raw.startsWith("not."), text3 = not ? raw.slice(4) : raw, dot = text3.indexOf(".");
6231
+ const op2 = text3.slice(0, dot), value = text3.slice(dot + 1), col = ident2(key2);
6232
+ let clause;
6233
+ if (OPS[op2]) {
6234
+ values.push(op2.endsWith("like") ? value.replace(/\*/g, "%") : value);
6235
+ clause = `${col}::text ${OPS[op2]} $${values.length}`;
6236
+ if (op2 === "eq" || op2 === "neq") clause = `${col} ${OPS[op2]} $${values.length}`;
6237
+ } else if (op2 === "is") clause = `${col} IS ${value === "null" ? "NULL" : value === "true" ? "TRUE" : value === "false" ? "FALSE" : "UNKNOWN"}`;
6238
+ else if (op2 === "in") {
6239
+ values.push(value.replace(/^\(|\)$/g, "").split(",").map((v) => v.replace(/^"|"$/g, "")));
6240
+ clause = `${col}::text = ANY($${values.length}::text[])`;
6241
+ }
6242
+ if (clause) clauses.push(not ? `NOT (${clause})` : clause);
6243
+ }
6244
+ return clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
6245
+ }
6246
+ async handle(request) {
6247
+ const header3 = (name) => {
6248
+ const v = request.headers[name];
6249
+ return Array.isArray(v) ? v.join(",") : v ?? "";
6250
+ };
6251
+ const prefer = header3("prefer"), single = /vnd\.pgrst\.object/.test(header3("accept"));
6252
+ const reply = (status, body2, extra = {}) => ({ status, headers: { "content-type": "application/json; charset=utf-8", ...extra }, body: body2 === void 0 ? "" : JSON.stringify(body2) });
6253
+ const segments = request.url.pathname.replace(/^\/rest\/v1\/?/, "").split("/").filter(Boolean).map(decodeURIComponent);
6254
+ if (!segments.length) return reply(404, { code: "PGRST125", message: "Invalid path specified in request URL" });
6255
+ const params = request.url.searchParams, values = [];
6256
+ let payload;
6257
+ try {
6258
+ payload = request.body?.length ? JSON.parse(request.body.toString("utf8")) : void 0;
6259
+ } catch {
6260
+ return reply(400, { code: "PGRST102", message: "Empty or invalid json" });
6261
+ }
6262
+ try {
6263
+ if (segments[0] === "rpc" && segments[1]) {
6264
+ const args = payload && typeof payload === "object" && !Array.isArray(payload) ? Object.entries(payload) : [...params].map(([k, v]) => [k, v]);
6265
+ const list3 = args.map(([k, v], i) => {
6266
+ values.push(v !== null && typeof v === "object" ? JSON.stringify(v) : v);
6267
+ return `${ident2(k)} => $${i + 1}`;
6268
+ });
6269
+ const r = await this.pool.query(`SELECT to_json(f) AS v FROM ${ident2(segments[1])}(${list3.join(", ")}) f`, values);
6270
+ const rows3 = r.rows.map((x) => x.v);
6271
+ 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);
6272
+ }
6273
+ const table2 = segments[0], t = ident2(table2);
6274
+ const returning = async (sql2) => {
6275
+ const cols = await this.columns(table2, "r", params.get("select") ?? "*");
6276
+ return `WITH r AS (${sql2} RETURNING *) SELECT coalesce(json_agg(x), '[]'::json) AS rows FROM (SELECT ${cols} FROM r) x`;
6277
+ };
6278
+ let sql, status = 200;
6279
+ const method = request.method.toUpperCase();
6280
+ if (method === "GET" || method === "HEAD") {
6281
+ const order = (params.get("order") ?? "").split(",").filter(Boolean).map((o) => {
6282
+ const [c, dir, nulls] = o.split(".");
6283
+ return `${ident2(c)} ${dir === "desc" ? "DESC" : "ASC"}${nulls === "nullsfirst" ? " NULLS FIRST" : nulls === "nullslast" ? " NULLS LAST" : ""}`;
6284
+ });
6285
+ const limit2 = Number(params.get("limit")), offset = Number(params.get("offset"));
6286
+ const cols = await this.columns(table2, "t", params.get("select") ?? "*");
6287
+ 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`;
6288
+ } else if (method === "POST") {
6289
+ const rows3 = Array.isArray(payload) ? payload : [payload ?? {}];
6290
+ const keys = [...new Set(rows3.flatMap((r) => Object.keys(r)))];
6291
+ values.push(JSON.stringify(rows3));
6292
+ const target = params.get("on_conflict")?.split(",").map(ident2).join(", ");
6293
+ 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;
6294
+ const merge = /resolution=merge-duplicates/.test(prefer), ignore = /resolution=ignore-duplicates/.test(prefer);
6295
+ const conflict = (merge || ignore) && pk ? ` ON CONFLICT (${pk}) DO ${ignore || !keys.length ? "NOTHING" : `UPDATE SET ${keys.map((k) => `${ident2(k)} = EXCLUDED.${ident2(k)}`).join(", ")}`}` : "";
6296
+ 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`;
6297
+ if (!keys.length) values.length = 0;
6298
+ sql = await returning(insert);
6299
+ status = 201;
6300
+ } else if (method === "PATCH") {
6301
+ const keys = Object.keys(payload ?? {});
6302
+ values.push(JSON.stringify(payload ?? {}));
6303
+ const set = keys.map((k) => `${ident2(k)} = (json_populate_record(null::${t}, $1::json)).${ident2(k)}`).join(", ");
6304
+ sql = await returning(`UPDATE ${t} SET ${set || "ctid = ctid"}${_PostgrestLayer.where(params, values)}`);
6305
+ } else if (method === "DELETE") {
6306
+ sql = await returning(`DELETE FROM ${t}${_PostgrestLayer.where(params, values)}`);
6307
+ } else return reply(405, { code: "PGRST117", message: `Unsupported HTTP method: ${method}` });
6308
+ const rows2 = (await this.pool.query(sql, values)).rows[0]?.rows ?? [];
6309
+ const range = { "content-range": `0-${Math.max(rows2.length - 1, 0)}/${/count=exact/.test(prefer) ? rows2.length : "*"}` };
6310
+ if (method !== "GET" && /return=minimal/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
6311
+ if (method !== "GET" && !/return=representation/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
6312
+ 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 });
6313
+ return reply(status, rows2, range);
6314
+ } catch (error) {
6315
+ const e = error;
6316
+ const status = e.code === "23505" ? 409 : e.code === "42P01" ? 404 : e.code === "42501" ? 403 : 400;
6317
+ return reply(status, { code: e.code === "42P01" ? "PGRST205" : e.code ?? "PGRST000", message: e.message ?? String(error), details: e.detail ?? null, hint: e.hint ?? null });
6318
+ }
6319
+ }
6320
+ };
6321
+ }
6322
+ });
6323
+
5805
6324
  // src/runtime/pack-log.ts
5806
- import { closeSync, existsSync as existsSync2, openSync, readdirSync, readSync, statSync } from "fs";
6325
+ import { closeSync, existsSync as existsSync2, openSync, readdirSync as readdirSync2, readSync, statSync } from "fs";
5807
6326
  import { join as join10 } from "path";
5808
6327
  function packCollection(type, requestPath) {
5809
6328
  const segments = requestPath.split("/").filter(Boolean);
@@ -5844,7 +6363,7 @@ var init_pack_log = __esm({
5844
6363
  partial = /* @__PURE__ */ new Map();
5845
6364
  files() {
5846
6365
  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();
6366
+ return readdirSync2(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join10(this.root, f)).sort();
5848
6367
  }
5849
6368
  drain() {
5850
6369
  const out = [];
@@ -5875,15 +6394,37 @@ var init_pack_log = __esm({
5875
6394
  }
5876
6395
  });
5877
6396
 
6397
+ // src/runtime/pack-aliases.ts
6398
+ function aliasRequest(pack, host, url) {
6399
+ const at = url.indexOf("?"), path2 = at < 0 ? url : url.slice(0, at), query = at < 0 ? "" : url.slice(at);
6400
+ const vendor = compatibleVendor(pack), compatible = vendor && compatibleRequest(vendor, host, url);
6401
+ if (compatible) return compatible;
6402
+ const alias = PACK_ALIASES[pack]?.find((a) => a.host === host.toLowerCase() && a.path === path2);
6403
+ return alias ? { host: alias.to.host, url: alias.to.path + query } : { host, url };
6404
+ }
6405
+ var PACK_ALIASES;
6406
+ var init_pack_aliases = __esm({
6407
+ "src/runtime/pack-aliases.ts"() {
6408
+ "use strict";
6409
+ init_compatible_packs();
6410
+ PACK_ALIASES = {
6411
+ // Google's OpenID Connect discovery names openidconnect.googleapis.com/v1/userinfo; the pack models the
6412
+ // equivalent www.googleapis.com/oauth2/v3/userinfo (https://developers.google.com/identity/openid-connect/openid-connect).
6413
+ googleoauth: [{ host: "openidconnect.googleapis.com", path: "/v1/userinfo", to: { host: "www.googleapis.com", path: "/oauth2/v3/userinfo" } }]
6414
+ };
6415
+ }
6416
+ });
6417
+
5878
6418
  // src/runtime/http-world.ts
5879
6419
  import { createServer as createServer3 } from "http";
6420
+ import { createServer as createNetServer } from "net";
5880
6421
  import { isDeepStrictEqual as isDeepStrictEqual5 } from "util";
5881
- import { createHash as createHash9 } from "crypto";
6422
+ import { createHash as createHash10 } from "crypto";
5882
6423
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
5883
- import { mkdir as mkdir3, mkdtemp as mkdtemp5, rm as rm5, writeFile as writeFile5 } from "fs/promises";
6424
+ import { mkdir as mkdir3, mkdtemp as mkdtemp5, rm as rm5, writeFile as writeFile6 } from "fs/promises";
5884
6425
  import { tmpdir as tmpdir5 } from "os";
5885
6426
  import { join as join11 } from "path";
5886
- var idempotencyKeyDigest, HttpWorld;
6427
+ var slackDirectMessageId, idempotencyKeyDigest, HttpWorld;
5887
6428
  var init_http_world = __esm({
5888
6429
  "src/runtime/http-world.ts"() {
5889
6430
  "use strict";
@@ -5895,9 +6436,13 @@ var init_http_world = __esm({
5895
6436
  init_spec();
5896
6437
  init_enterprise_twins();
5897
6438
  init_adapters();
6439
+ init_postgrest();
5898
6440
  init_packs();
5899
6441
  init_pack_log();
5900
- idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash9("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
6442
+ init_pack_aliases();
6443
+ init_compatible_packs();
6444
+ slackDirectMessageId = (user) => `D${createHash10("sha256").update(user).digest("hex").slice(0, 16).toUpperCase()}`;
6445
+ idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash10("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
5901
6446
  HttpWorld = class {
5902
6447
  /** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
5903
6448
  constructor(spec, seed, options = {}) {
@@ -5923,6 +6468,12 @@ var init_http_world = __esm({
5923
6468
  epoch = 0;
5924
6469
  replayKeys = /* @__PURE__ */ new Map();
5925
6470
  sourceContext = new AsyncLocalStorage2();
6471
+ postgrest;
6472
+ /** The run's PostgreSQL: a pack's PostgREST paths (/rest/v1/<table>) are served from it, so the app's own tables answer. */
6473
+ attachDatabase(url) {
6474
+ void this.postgrest?.close();
6475
+ this.postgrest = new PostgrestLayer(url);
6476
+ }
5926
6477
  record(service, operation, path2, detail, record4) {
5927
6478
  if (this.events.length >= 5e4) return;
5928
6479
  const source = this.sourceContext.getStore();
@@ -5933,6 +6484,33 @@ var init_http_world = __esm({
5933
6484
  * each, after the triggering response. Only loopback http endpoints are allowed, so a push can never leave the
5934
6485
  * machine; the outcome is written to the push row and recorded as a `push` event.
5935
6486
  */
6487
+ sentWebhooks = /* @__PURE__ */ new Set();
6488
+ /** Sends a webhook a pack signed and queued, with the pack's own signature headers. Loopback http only. */
6489
+ sendWebhook(service, url, body2, headers, eventType) {
6490
+ const epoch = this.epoch;
6491
+ const timer = setTimeout(async () => {
6492
+ this.timers.delete(timer);
6493
+ if (epoch !== this.epoch) return;
6494
+ let target;
6495
+ try {
6496
+ target = new URL(url);
6497
+ } catch {
6498
+ target = void 0;
6499
+ }
6500
+ if (!target || target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || target.username || target.password) {
6501
+ this.record(service, "webhook", url, `webhook ${eventType} not sent: the endpoint is not a loopback http URL (nothing leaves this machine)`);
6502
+ return;
6503
+ }
6504
+ try {
6505
+ const response = await fetch(target, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: body2, redirect: "error", signal: AbortSignal.timeout(6e4) });
6506
+ await response.arrayBuffer().catch(() => void 0);
6507
+ if (epoch === this.epoch) this.record(service, "webhook", url, `delivered ${eventType} to ${url}: HTTP ${response.status}`, { event: eventType, status: response.status });
6508
+ } catch (error) {
6509
+ if (epoch === this.epoch) this.record(service, "webhook", url, `webhook ${eventType} to ${url} failed: ${error instanceof Error ? error.message : String(error)}`);
6510
+ }
6511
+ }, 25);
6512
+ this.timers.add(timer);
6513
+ }
5936
6514
  push(service, deliveries, epoch) {
5937
6515
  for (const delivery of deliveries) {
5938
6516
  const timer = setTimeout(async () => {
@@ -5964,12 +6542,23 @@ var init_http_world = __esm({
5964
6542
  this.timers.add(timer);
5965
6543
  }
5966
6544
  }
6545
+ /** Tags every event recorded since index `from` with the request's idempotency key digest. */
6546
+ keyedSince(from, key2) {
6547
+ const digest6 = idempotencyKeyDigest(key2);
6548
+ if (digest6) for (let i = from; i < this.events.length; i++) this.events[i].idempotencyKey = digest6;
6549
+ }
5967
6550
  /** Tags the event just recorded with the request's idempotency key digest. */
5968
6551
  keyed(key2) {
5969
6552
  const digest6 = idempotencyKeyDigest(key2), last = this.events[this.events.length - 1];
5970
6553
  if (digest6 && last) last.idempotencyKey = digest6;
5971
6554
  }
6555
+ /** Requests the run itself sends to set a twin up (x-agenttwin-probe: 1): a refusal there is not the application's gap. */
6556
+ probes = 0;
5972
6557
  rejectUnsupported(service, method, path2, detail) {
6558
+ if (this.probes > 0) {
6559
+ this.record(service, "assumption", path2, `setup probe: ${detail}`);
6560
+ return;
6561
+ }
5973
6562
  this.unsupported.push(`${service}: ${method} ${path2}: ${detail}`);
5974
6563
  this.record(service, "unsupported", path2, detail);
5975
6564
  }
@@ -6016,340 +6605,382 @@ var init_http_world = __esm({
6016
6605
  this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server2.address().port}`, token };
6017
6606
  continue;
6018
6607
  }
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";
6608
+ const server = createServer3((req, res) => {
6609
+ if (req.headers["x-agenttwin-probe"] === "1") {
6610
+ this.probes++;
6611
+ res.once("close", () => {
6612
+ this.probes--;
6613
+ });
6614
+ }
6615
+ return withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
6616
+ const epoch = this.epoch;
6617
+ const send2 = (code, body2, headers = {}) => {
6618
+ if (!res.destroyed) {
6619
+ res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {}, ...headers });
6620
+ res.end(code === 204 || code === 202 && body2 === null ? void 0 : typeof body2 === "string" && headers["content-type"] ? body2 : JSON.stringify(body2));
6621
+ }
6622
+ };
6623
+ const respond = (code, body2, headers) => {
6624
+ const ms = latencyMs();
6625
+ if (ms <= 0) {
6626
+ send2(code, body2, headers);
6627
+ return;
6628
+ }
6629
+ const timer = setTimeout(() => {
6630
+ this.timers.delete(timer);
6631
+ if (epoch === this.epoch) send2(code, body2, headers);
6632
+ }, ms);
6633
+ this.timers.add(timer);
6634
+ };
6635
+ const normalPath = (url, method) => {
6636
+ const parsed = new URL(url, "http://localhost");
6637
+ if (generated) return generated.collectionOf(method ?? "", parsed.pathname) ?? parsed.pathname;
6638
+ if (service.adapter === "google-oauth" && parsed.pathname === "/token" && method === "POST") return "/tokens";
6639
+ if (service.adapter === "composio") {
6640
+ if (/^\/api\/v3(?:\.1)?\/tools\/execute\//.test(parsed.pathname)) return "/messages";
6641
+ if (/^\/api\/v3(?:\.1)?\/connected_accounts(?:\/|$)/.test(parsed.pathname)) return "/connected_accounts";
6642
+ }
6643
+ if (service.adapter === "slack") {
6644
+ const m = parsed.pathname.replace(/^\/api\//, "");
6645
+ if (m === "chat.postMessage" && method === "POST") return "/messages";
6646
+ if (m === "conversations.history" && ["GET", "POST"].includes(method ?? "")) return "/messages";
6647
+ if (m === "conversations.list" && ["GET", "POST"].includes(method ?? "")) return "/channels";
6648
+ return parsed.pathname;
6649
+ }
6052
6650
  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();
6651
+ };
6652
+ const matchesFault = (target) => adapterService ? target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path) : target === fault.path;
6653
+ const requestKey = req.headers["idempotency-key"];
6654
+ const respondSlowly = (target, operation, code, body2, headers) => {
6655
+ if (fault?.type !== "slow-response" || !faultOrdinalsFor || !matchesFault(target) || !faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
6656
+ respond(code, body2, headers);
6106
6657
  return;
6107
6658
  }
6659
+ this.faultActions++;
6660
+ this.record(service.name, "fault", target, `slow-response: ${operation} applied; response delayed ${fault.delayMs}ms`);
6661
+ this.keyed(requestKey);
6108
6662
  const timer = setTimeout(() => {
6109
6663
  this.timers.delete(timer);
6110
- if (epoch === this.epoch) respond500();
6111
- }, delay2);
6664
+ if (epoch === this.epoch) respond(code, body2, headers);
6665
+ }, fault.delayMs);
6112
6666
  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" });
6667
+ };
6668
+ const darkFault = () => {
6669
+ if (!fault || !faultOrdinalsFor || fault.type !== "blackhole" && fault.type !== "server-error") return "none";
6670
+ const target = normalPath(req.url ?? "/", req.method);
6671
+ if (!matchesFault(target)) return "none";
6672
+ const ordinal = this.candidateIndex(faultKey);
6673
+ if (!faultOrdinalsFor.includes(ordinal)) return "none";
6674
+ this.faultActions++;
6675
+ return fault.type;
6676
+ };
6677
+ try {
6678
+ const anyCredential = !!this.options.lenientModelAuth && (service.adapter === "openai" || service.adapter === "anthropic");
6679
+ 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))) {
6680
+ 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(", ")})`);
6681
+ respond(401, { error: "invalid_test_credential" });
6682
+ return;
6683
+ }
6684
+ if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
6685
+ respond(429, { error: "world_capacity" });
6686
+ return;
6687
+ }
6688
+ const darkness = darkFault();
6689
+ if (darkness === "blackhole") {
6690
+ 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"})`);
6691
+ this.keyed(requestKey);
6692
+ return;
6693
+ }
6694
+ if (darkness === "server-error") {
6695
+ const windowMs = fault.windowMs ?? 0;
6696
+ const delay2 = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
6697
+ this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay2}ms; nothing committed (${req.method ?? "request"})`);
6698
+ this.keyed(requestKey);
6699
+ const respond500 = () => respond(500, { error: { type: "api_error", message: "server_error fault" } });
6700
+ if (delay2 <= 0) {
6701
+ respond500();
6137
6702
  return;
6138
6703
  }
6139
- chunks.push(Buffer.from(chunk));
6704
+ const timer = setTimeout(() => {
6705
+ this.timers.delete(timer);
6706
+ if (epoch === this.epoch) respond500();
6707
+ }, delay2);
6708
+ this.timers.add(timer);
6709
+ return;
6710
+ }
6711
+ const url = new URL(req.url ?? "/", "http://localhost");
6712
+ let path2 = url.pathname;
6713
+ if (service.adapter === "composio" && [...url.searchParams.keys()].some((key3) => url.searchParams.getAll(key3).length !== 1)) {
6714
+ this.rejectUnsupported(service.name, req.method ?? "", path2, "Repeated query parameters are unsupported");
6715
+ respond(501, restUnsupportedBody("composio"));
6716
+ return;
6140
6717
  }
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];
6718
+ if (service.adapter === "google-oauth" && url.search) {
6719
+ this.rejectUnsupported(service.name, req.method ?? "", path2, "OAuth token query parameters are unsupported");
6720
+ respond(501, restUnsupportedBody("google-oauth"));
6721
+ return;
6722
+ }
6723
+ const slack = service.adapter === "slack";
6724
+ const slackMethod = path2.replace(/^\/api\//, "");
6725
+ let payload, rawBody;
6726
+ if (["POST", "PUT", "PATCH"].includes(req.method ?? "")) {
6727
+ const chunks = [];
6728
+ let bytes = 0;
6729
+ for await (const chunk of req) {
6730
+ bytes += chunk.length;
6731
+ if (bytes > 1024 * 1024) {
6732
+ respond(413, { error: "body_too_large" });
6733
+ return;
6734
+ }
6735
+ chunks.push(Buffer.from(chunk));
6151
6736
  }
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" });
6737
+ const text3 = Buffer.concat(chunks).toString("utf8");
6738
+ let parsed;
6739
+ const mode = generated?.bodyMode(req.headers["content-type"]);
6740
+ if ((enterprise || generated) && !text3.trim()) parsed = {};
6741
+ else if (mode === "form") {
6742
+ const form = new URLSearchParams(text3);
6743
+ parsed = {};
6744
+ for (const key3 of new Set(form.keys())) {
6745
+ const all = form.getAll(key3);
6746
+ parsed[key3] = all.length > 1 ? all : all[0];
6747
+ }
6748
+ } else if (mode === "raw") {
6749
+ rawBody = text3;
6750
+ parsed = {};
6751
+ } else if (service.adapter === "gmail" && /^multipart\/mixed\b/i.test(String(req.headers["content-type"] ?? ""))) {
6752
+ rawBody = text3;
6753
+ parsed = {};
6754
+ } else if (service.adapter === "gmail" && /^multipart\/related\b/i.test(String(req.headers["content-type"] ?? ""))) {
6755
+ rawBody = text3;
6756
+ parsed = Object.fromEntries(url.searchParams);
6757
+ } else if (service.adapter === "upstash-redis") {
6758
+ rawBody = text3;
6759
+ parsed = {};
6760
+ } else if (service.adapter === "gmail" && !text3.trim()) parsed = {};
6761
+ else if (service.adapter === "google-oauth") {
6762
+ if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
6763
+ respond(400, { error: "invalid_request" });
6764
+ return;
6765
+ }
6766
+ const form = new URLSearchParams(text3);
6767
+ if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
6768
+ respond(400, { error: "invalid_request" });
6769
+ return;
6770
+ }
6771
+ parsed = Object.fromEntries(form);
6772
+ } else try {
6773
+ 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);
6774
+ } catch {
6775
+ respond(400, { error: "expected_json_object" });
6168
6776
  return;
6169
6777
  }
6170
- const form = new URLSearchParams(text3);
6171
- if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
6172
- respond(400, { error: "invalid_request" });
6778
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6779
+ respond(400, { error: "expected_json_object" });
6173
6780
  return;
6174
6781
  }
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;
6782
+ payload = parsed;
6181
6783
  }
6182
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6183
- respond(400, { error: "expected_json_object" });
6784
+ if (epoch !== this.epoch) {
6785
+ respond(409, { error: "world_reset" });
6184
6786
  return;
6185
6787
  }
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" } });
6788
+ if (generated && !payload && ["PUT", "DELETE"].includes(req.method ?? "")) payload = {};
6789
+ if (service.adapter === "stripe" || restAdapter || enterprise || generated) {
6790
+ const params = payload ?? Object.fromEntries(url.searchParams);
6791
+ const keyHeader2 = req.headers["idempotency-key"] ?? (enterprise === "netsuite" ? req.headers["x-netsuite-idempotency-key"] : void 0);
6792
+ const key3 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path2}:${keyHeader2}` : void 0;
6793
+ const signature2 = JSON.stringify(params);
6794
+ const previous2 = key3 ? keys.get(key3) : void 0;
6795
+ if (previous2) {
6796
+ if (previous2.body !== signature2) {
6797
+ respond(400, { error: { type: "idempotency_error", message: "Keys for idempotent requests can only be used with the same parameters" } });
6798
+ return;
6799
+ }
6800
+ this.record(service.name, "replay", path2, "same-key response replay", previous2.record);
6801
+ this.keyed(keyHeader2);
6802
+ respondSlowly(path2, "replay", previous2.status ?? 200, previous2.record, previous2.headers);
6202
6803
  return;
6203
6804
  }
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 });
6805
+ const query = Object.fromEntries(url.searchParams);
6806
+ 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);
6807
+ const headers = (r) => "headers" in r ? r.headers : void 0;
6808
+ const result2 = invoke(this.events.length + 1);
6809
+ if (!result2) {
6810
+ this.rejectUnsupported(service.name, req.method ?? "", path2, `unsupported ${service.adapter} operation or parameters`);
6811
+ 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 });
6812
+ return;
6813
+ }
6814
+ if ("unsupportedReason" in result2 && result2.unsupportedReason) {
6815
+ this.rejectUnsupported(service.name, req.method ?? "", path2, String(result2.unsupportedReason));
6816
+ respond(result2.status, result2.body);
6817
+ return;
6818
+ }
6819
+ if (result2.operation) {
6820
+ this.record(service.name, result2.operation, result2.collection, path2, "record" in result2 ? result2.record : result2.body);
6821
+ this.keyed(keyHeader2);
6822
+ }
6823
+ 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) } : {} });
6824
+ const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result2.operation === "write" && !key3 && matchesFault(result2.collection);
6825
+ const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
6826
+ const pushes = (r) => "deliveries" in r ? [...r.deliveries ?? []] : [];
6827
+ const deliveries = pushes(result2);
6828
+ if (duplicate2) {
6829
+ const second = invoke(this.events.length + 1);
6830
+ if (second?.operation === "write") {
6831
+ deliveries.push(...pushes(second));
6832
+ this.record(service.name, second.operation, second.collection, path2, "record" in second ? second.record : second.body);
6833
+ this.faultActions++;
6834
+ this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result2.collection})`);
6835
+ } else if (second) {
6836
+ this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
6837
+ respond(second.status, second.body, headers(second));
6838
+ if (deliveries.length) this.push(service.name, deliveries, epoch);
6839
+ return;
6840
+ }
6841
+ }
6842
+ if (!this.fired && result2.operation === "write" && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === result2.collection) {
6843
+ this.fired = true;
6844
+ this.faultActions++;
6845
+ this.record(service.name, "fault", result2.collection, `write committed; response delayed ${fault.delayMs}ms`);
6846
+ this.keyed(keyHeader2);
6847
+ const timer = setTimeout(() => {
6848
+ this.timers.delete(timer);
6849
+ respond(result2.status, result2.body, headers(result2));
6850
+ }, fault.delayMs);
6851
+ this.timers.add(timer);
6852
+ } else respondSlowly(result2.collection, result2.operation ?? "request", result2.status, result2.body, headers(result2));
6853
+ if (deliveries.length) this.push(service.name, deliveries, epoch);
6216
6854
  return;
6217
6855
  }
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);
6856
+ if (slack) {
6857
+ const params = payload ?? Object.fromEntries(url.searchParams);
6858
+ const allowed = slackMethod === "chat.postMessage" ? ["channel", "text"] : slackMethod === "conversations.history" ? ["channel"] : [];
6859
+ if (Object.keys(params).some((k) => !allowed.includes(k))) {
6860
+ this.rejectUnsupported(service.name, req.method ?? "", url.pathname, `unsupported parameters for ${slackMethod}`);
6861
+ respond(501, { ok: false, error: "unsupported_parameters", forwardedToProduction: false });
6862
+ return;
6863
+ }
6864
+ if (slackMethod === "chat.postMessage" && req.method === "POST") path2 = "/messages";
6865
+ else if (slackMethod === "conversations.history" && ["GET", "POST"].includes(req.method ?? "")) path2 = "/messages";
6866
+ else if (slackMethod === "conversations.list" && ["GET", "POST"].includes(req.method ?? "")) path2 = "/channels";
6867
+ else {
6868
+ this.rejectUnsupported(service.name, req.method ?? "", url.pathname, "unsupported operation");
6869
+ respond(501, { ok: false, error: "unsupported_operation", forwardedToProduction: false });
6238
6870
  return;
6239
6871
  }
6240
6872
  }
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 });
6873
+ if (!Object.hasOwn(data, path2) || !["GET", "POST"].includes(req.method ?? "")) {
6874
+ this.rejectUnsupported(service.name, req.method ?? "", path2, "unsupported operation");
6875
+ respond(501, { error: "unsupported_operation", forwardedToProduction: false });
6261
6876
  return;
6262
6877
  }
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 });
6878
+ if (req.method === "GET" || slack && slackMethod !== "chat.postMessage") {
6879
+ this.record(service.name, "read", path2, `${data[path2].length} records`);
6880
+ if (slack && path2 === "/channels") respondSlowly(path2, "read", 200, { ok: true, channels: data[path2], response_metadata: { next_cursor: "" } });
6881
+ else if (slack) {
6882
+ const channel = payload?.channel ?? url.searchParams.get("channel");
6883
+ if (!data["/channels"].some((c) => c.id === channel)) respond(200, { ok: false, error: "channel_not_found" });
6884
+ else respondSlowly(path2, "read", 200, { ok: true, messages: data[path2].filter((m) => m.channel === channel), has_more: false });
6885
+ } else respondSlowly(path2, "read", 200, { data: data[path2] });
6269
6886
  return;
6270
6887
  }
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;
6888
+ const body2 = payload;
6889
+ if (slack) {
6890
+ const message = body2;
6891
+ const channels = data["/channels"];
6892
+ const recipient = message.channel;
6893
+ let destination = channels.find((channel) => channel.id === recipient);
6894
+ if (typeof recipient === "string" && /^[UW][A-Z0-9]+$/.test(recipient)) {
6895
+ const user = data["/users"]?.find((row2) => row2.id === recipient);
6896
+ destination = channels.find((channel) => channel.is_im === true && channel.user === recipient);
6897
+ if (user?.deleted === true || user?.dmAllowed === false) destination = void 0;
6898
+ else if (!destination && user) {
6899
+ if (channels.length >= 1e4) {
6900
+ respond(429, { error: "world_capacity" });
6901
+ return;
6902
+ }
6903
+ const id = slackDirectMessageId(recipient);
6904
+ destination = { id, is_im: true, user: recipient };
6905
+ if (channels.some((channel) => channel.id === id)) {
6906
+ respond(409, { error: "channel_conflict" });
6907
+ return;
6908
+ }
6909
+ }
6910
+ }
6911
+ if (!destination) {
6912
+ respond(200, { ok: false, error: "channel_not_found" });
6913
+ return;
6914
+ }
6915
+ if (typeof message.text !== "string" || !message.text) {
6916
+ respond(200, { ok: false, error: "no_text" });
6917
+ return;
6918
+ }
6919
+ if (data[path2].length >= 1e4 || this.events.length >= 5e4) {
6920
+ respond(429, { error: "world_capacity" });
6921
+ return;
6922
+ }
6923
+ if (!channels.includes(destination)) {
6924
+ channels.push(destination);
6925
+ this.record(service.name, "write", "/channels", String(destination.id), destination);
6926
+ }
6927
+ message.channel = destination.id;
6293
6928
  }
6294
- if (typeof message.text !== "string" || !message.text) {
6295
- respond(200, { ok: false, error: "no_text" });
6929
+ if (data[path2].length >= 1e4 || this.events.length >= 5e4) {
6930
+ respond(429, { error: "world_capacity" });
6296
6931
  return;
6297
6932
  }
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" });
6933
+ const keyHeader = slack ? void 0 : req.headers["idempotency-key"];
6934
+ const key2 = typeof keyHeader === "string" ? `${path2}:${keyHeader}` : void 0;
6935
+ const signature = JSON.stringify(body2);
6936
+ const previous = key2 ? keys.get(key2) : void 0;
6937
+ if (previous) {
6938
+ if (previous.body !== signature) {
6939
+ respond(409, { error: "idempotency_conflict" });
6940
+ return;
6941
+ }
6942
+ this.record(service.name, "replay", path2, "same-key response replay", previous.record);
6943
+ this.keyed(keyHeader);
6944
+ respondSlowly(path2, "replay", 200, previous.record);
6310
6945
  return;
6311
6946
  }
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++;
6947
+ const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path2 && !key2 && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
6948
+ if (duplicate) this.faultActions++;
6949
+ let index = data[path2].length + 1;
6330
6950
  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`);
6951
+ const row = { ...body2, id: `${service.name}_${index}` };
6952
+ if (slack) row.ts = `${index}.000001`;
6953
+ const reply = slack ? { ok: true, channel: row.channel, ts: row.ts, message: row } : row;
6954
+ data[path2].push(row);
6955
+ if (key2) keys.set(key2, { body: signature, record: row });
6956
+ this.record(service.name, "write", path2, String(row.id), row);
6342
6957
  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
- })));
6958
+ if (duplicate) {
6959
+ index++;
6960
+ while (data[path2].some((r) => r.id === `${service.name}_${index}`)) index++;
6961
+ const second = { ...body2, id: `${service.name}_${index}` };
6962
+ if (slack) second.ts = `${index}.000001`;
6963
+ data[path2].push(second);
6964
+ this.record(service.name, "write", path2, String(second.id), second);
6965
+ this.record(service.name, "fault", fault.path, `duplicate-write: one write committed as two records (${row.id}, ${second.id})`);
6966
+ }
6967
+ const faultResponse = slack ? 200 : 201;
6968
+ if (!this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === path2) {
6969
+ this.fired = true;
6970
+ this.faultActions++;
6971
+ this.record(service.name, "fault", path2, `write committed; response delayed ${fault.delayMs}ms`);
6972
+ this.keyed(keyHeader);
6973
+ const timer = setTimeout(() => {
6974
+ this.timers.delete(timer);
6975
+ respond(faultResponse, reply);
6976
+ }, fault.delayMs);
6977
+ this.timers.add(timer);
6978
+ } else respondSlowly(path2, "write", faultResponse, reply);
6979
+ } catch {
6980
+ respond(500, { error: "world_request_error" });
6981
+ }
6982
+ }));
6983
+ });
6353
6984
  server.requestTimeout = 1e4;
6354
6985
  await new Promise((resolve13, reject) => {
6355
6986
  server.once("error", reject);
@@ -6363,6 +6994,13 @@ var init_http_world = __esm({
6363
6994
  /** Environment each pack service's credential door issued (STRIPE_SECRET_KEY…), for the application's process. */
6364
6995
  packEnv = /* @__PURE__ */ Object.create(null);
6365
6996
  packRoots = [];
6997
+ /** Per service: 1 while a call the world makes is in flight and no envelope has been captured yet, 2 once one has. */
6998
+ causing = /* @__PURE__ */ Object.create(null);
6999
+ lastEnvelope = /* @__PURE__ */ Object.create(null);
7000
+ socketServers = [];
7001
+ rawServers = [];
7002
+ /** Each pack service's plain-TCP port for clients that open their own TLS sockets (see startPack). */
7003
+ packTcp = /* @__PURE__ */ Object.create(null);
6366
7004
  /**
6367
7005
  * A twin pack served behind this world: the run token is checked and swapped for the credential the pack issued,
6368
7006
  * seeded fault schedules apply around the pack's own handler, and every action the pack logs becomes evidence — writes
@@ -6377,10 +7015,11 @@ var init_http_world = __esm({
6377
7015
  const writeSeedLog = async (dir, text3) => {
6378
7016
  if (!text3) return;
6379
7017
  await mkdir3(join11(dir, ".volter/world", meta2.logService), { recursive: true });
6380
- await writeFile5(join11(dir, ".volter/world", meta2.logService, "actions.jsonl"), text3);
7018
+ await writeFile6(join11(dir, ".volter/world", meta2.logService, "actions.jsonl"), text3);
6381
7019
  };
6382
7020
  let tenant = {}, credential;
6383
- if (meta2.logService && meta2.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account)) {
7021
+ let doorLines = "";
7022
+ if (meta2.logService && meta2.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account || service.doorRecords?.length)) {
6384
7023
  const probe = await mkdtemp5(join11(tmpdir5(), `agenttwin-pack-${name}-probe-`));
6385
7024
  try {
6386
7025
  await writeSeedLog(probe, worldSeed);
@@ -6389,37 +7028,76 @@ var init_http_world = __esm({
6389
7028
  const probed = new PackActionTail(join11(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
6390
7029
  tenant = tenantFields(probed);
6391
7030
  credential = credentialAction(probed);
7031
+ for (const rec of service.doorRecords ?? []) {
7032
+ const own = probed.filter((a) => a.subject?.type === rec.type);
7033
+ const original = own[0]?.subject?.id;
7034
+ if (!original) continue;
7035
+ 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("");
7036
+ }
6392
7037
  } finally {
6393
7038
  await rm5(probe, { recursive: true, force: true });
6394
7039
  }
6395
7040
  }
6396
7041
  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) : "";
7042
+ const seeded = meta2.logService ? worldSeed + account + doorLines + seedActions(meta2.logService, service.collections, new Date(twinNowMs(Date.now())).toISOString(), tenant) : "";
6398
7043
  await writeSeedLog(root, seeded);
6399
7044
  const twin = await (await loadPack(name))({ root });
6400
7045
  const baseHost = meta2.hosts[0]?.host ?? `${name}.twin.test`;
6401
7046
  const log = new PackActionTail(join11(root, ".volter"));
6402
7047
  let issued = {};
6403
7048
  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();
7049
+ const hosts = [...new Set(meta2.hosts.map((h) => h.host).filter((h) => !!h))];
7050
+ const door = (host) => twin(new Request(`https://${host}${meta2.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta2.credentialDoor.body ?? {}) }));
7051
+ for (const host of hosts.length ? hosts : [baseHost]) {
7052
+ let r = await door(host);
7053
+ if (r.status === 404 && meta2.credentialDoor.body && Object.keys(meta2.credentialDoor.body).length) {
7054
+ await r.arrayBuffer();
7055
+ 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 }) }));
7056
+ await made.arrayBuffer();
7057
+ r = await door(host);
7058
+ }
7059
+ if (r.ok) {
7060
+ issued = await r.json();
7061
+ break;
7062
+ }
7063
+ await r.arrayBuffer();
7064
+ if (r.status !== 404) break;
7065
+ }
6407
7066
  }
6408
7067
  const env = {};
6409
- for (const [envName, field] of Object.entries(meta2.credentialDoor?.fill ?? {})) if (typeof issued[field] === "string") env[envName] = issued[field];
7068
+ for (const [envName, field] of Object.entries(meta2.credentialDoor?.fill ?? {})) {
7069
+ if (field.startsWith("file:")) {
7070
+ const value = issued[field.slice(5)];
7071
+ if (value && typeof value === "object") {
7072
+ const file = join11(root, `${envName.toLowerCase()}.json`);
7073
+ await writeFile6(file, JSON.stringify(value, null, 2), { mode: 384 });
7074
+ env[envName] = file;
7075
+ }
7076
+ } else if (typeof issued[field] === "string") env[envName] = issued[field];
7077
+ }
6410
7078
  this.packEnv[service.name] = env;
6411
7079
  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
7080
  const primary = primaryEnv ? env[primaryEnv] : void 0;
6413
7081
  const authHeaders = () => primary ? { authorization: `Bearer ${primary}` } : {};
7082
+ const issuedValues = Object.values(env).filter((v) => v.length >= 12);
7083
+ const appCredential = (value) => {
7084
+ const v = Array.isArray(value) ? value[0] : value;
7085
+ return v && issuedValues.some((i) => v === `Bearer ${i}`) ? v : void 0;
7086
+ };
6414
7087
  const fault = this.spec.fault;
6415
7088
  const matchesFault = (target) => !!fault && (target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path));
6416
- const apply = (actions, method, path2, evidence) => {
7089
+ const apply = (actions, method, path2, evidence, byWorld = false) => {
6417
7090
  const wrote = [];
6418
7091
  for (const a of actions) {
6419
7092
  const type = a.subject?.type, id = a.subject?.id;
6420
7093
  if (!type || !id) continue;
6421
7094
  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"}`);
7095
+ const f = a.fields ?? {}, eventType = typeof f.body === "string" ? /"type":"([^"]+)"/.exec(f.body)?.[1] ?? "event" : "event";
7096
+ const key2 = `${service.name}:${id}`;
7097
+ if (f.delivery_state === "queued" && typeof f.url === "string" && typeof f.body === "string" && f.headers && typeof f.headers === "object" && !this.sentWebhooks.has(key2)) {
7098
+ this.sentWebhooks.add(key2);
7099
+ this.sendWebhook(service.name, f.url, f.body, f.headers, eventType);
7100
+ } else if (evidence && !this.sentWebhooks.has(key2)) this.record(service.name, "webhook", String(f.url ?? ""), `queued ${eventType} for ${f.url ?? "endpoint"}`);
6423
7101
  continue;
6424
7102
  }
6425
7103
  if (type.startsWith("_")) continue;
@@ -6433,7 +7111,7 @@ var init_http_world = __esm({
6433
7111
  } else if (at >= 0) rows2[at] = row;
6434
7112
  else rows2.push(row);
6435
7113
  if (!evidence) continue;
6436
- const byApp = a.actor?.kind === "agent";
7114
+ const byApp = a.actor?.kind === "agent" && !byWorld;
6437
7115
  this.record(service.name, byApp ? "write" : "twin", collection, `${method} ${path2} \u2192 ${a.operation ?? type} ${id}${byApp ? "" : " (by the twin)"}`, row);
6438
7116
  if (byApp) wrote.push(collection);
6439
7117
  }
@@ -6455,146 +7133,258 @@ var init_http_world = __esm({
6455
7133
  chain = run3.then(() => void 0, () => void 0);
6456
7134
  return run3;
6457
7135
  };
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})`);
7136
+ const server = createServer3((req, res) => {
7137
+ if (req.headers["x-agenttwin-probe"] === "1") {
7138
+ this.probes++;
7139
+ res.once("close", () => {
7140
+ this.probes--;
7141
+ });
7142
+ }
7143
+ return withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
7144
+ const epoch = this.epoch;
7145
+ const send2 = (status, headers, body2) => {
7146
+ if (!res.destroyed) {
7147
+ res.writeHead(status, headers);
7148
+ res.end(body2);
7149
+ }
7150
+ };
7151
+ const later = (ms, fn) => {
7152
+ const timer = setTimeout(() => {
7153
+ this.timers.delete(timer);
7154
+ if (epoch === this.epoch) fn();
7155
+ }, ms);
7156
+ this.timers.add(timer);
7157
+ };
7158
+ const respond = (status, headers, body2) => {
7159
+ const ms = latencyMs();
7160
+ if (ms <= 0) send2(status, headers, body2);
7161
+ else later(ms, () => send2(status, headers, body2));
7162
+ };
7163
+ const json2 = (status, value) => respond(status, { "content-type": "application/json" }, Buffer.from(JSON.stringify(value)));
7164
+ try {
7165
+ const raw = req.socket.agenttwinRaw === true;
7166
+ const ours = raw || req.headers.authorization === `Bearer ${token}` || req.headers["x-api-key"] === token || req.headers["x-agenttwin-token"] === token;
7167
+ if (!ours) {
7168
+ this.record(service.name, "auth-denied", req.url ?? "", "invalid test credential");
7169
+ json2(401, { error: "invalid_test_credential" });
7170
+ return;
7171
+ }
7172
+ if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
7173
+ json2(429, { error: "world_capacity" });
7174
+ return;
7175
+ }
7176
+ const url = new URL(req.url ?? "/", "http://localhost"), method = req.method ?? "GET", path2 = url.pathname;
7177
+ if (path2 === "/_agenttwin/redeliver" && req.headers["x-agenttwin-token"] === token) {
7178
+ const last = this.lastEnvelope[service.name];
7179
+ if (!last) {
7180
+ json2(404, { ok: false, error: "nothing_delivered" });
7181
+ return;
7182
+ }
7183
+ const attempt = Number(last.envelope.retry_attempt ?? 0) + 1;
7184
+ 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" };
7185
+ last.send(JSON.stringify(again));
7186
+ this.record(service.name, "twin", path2, `redelivered ${String(last.envelope.type ?? "envelope")} (retry_attempt ${attempt}, as after a lost acknowledgment)`);
7187
+ json2(200, { ok: true, retry_attempt: attempt });
7188
+ return;
7189
+ }
7190
+ const workspace = req.headers["x-agenttwin-actor"] === "workspace" && req.headers["x-agenttwin-token"] === token;
7191
+ const requestKey = req.headers["idempotency-key"];
7192
+ if (!workspace && fault && faultOrdinalsFor && (fault.type === "blackhole" || fault.type === "server-error") && matchesFault(path2) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
7193
+ this.faultActions++;
7194
+ if (fault.type === "blackhole") {
7195
+ this.record(service.name, "fault", fault.path, `blackhole: request dropped; nothing committed (${method})`);
7196
+ this.keyed(requestKey);
7197
+ return;
7198
+ }
7199
+ const windowMs = fault.windowMs ?? 0;
7200
+ const delay2 = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
7201
+ this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay2}ms; nothing committed (${method})`);
6496
7202
  this.keyed(requestKey);
7203
+ const fail2 = () => json2(500, { error: { type: "api_error", message: "server_error fault" } });
7204
+ if (delay2 <= 0) fail2();
7205
+ else later(delay2, fail2);
6497
7206
  return;
6498
7207
  }
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" });
7208
+ const chunks = [];
7209
+ let bytes = 0;
7210
+ for await (const chunk of req) {
7211
+ bytes += chunk.length;
7212
+ if (bytes > 5 * 1024 * 1024) {
7213
+ json2(413, { error: "body_too_large" });
7214
+ return;
7215
+ }
7216
+ chunks.push(Buffer.from(chunk));
7217
+ }
7218
+ const body2 = ["GET", "HEAD"].includes(method) ? void 0 : Buffer.concat(chunks);
7219
+ if (epoch !== this.epoch) {
7220
+ json2(409, { error: "world_reset" });
6514
7221
  return;
6515
7222
  }
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 {
7223
+ if (this.postgrest && path2.startsWith("/rest/v1/")) {
7224
+ const r = await this.postgrest.handle({ method, url, headers: req.headers, body: body2 });
7225
+ 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)}` : ""}`);
7226
+ res.writeHead(r.status, r.headers);
7227
+ res.end(r.body);
7228
+ return;
7229
+ }
7230
+ let host = String(req.headers["x-agenttwin-original-host"] ?? (raw ? req.headers.host?.replace(/:\d+$/, "") : void 0) ?? baseHost);
7231
+ if (name === "pinecone") {
7232
+ const m = /^([a-z0-9-]+?)-[a-z0-9]+\.svc\.[a-z0-9.-]*pinecone\.io$/.exec(host);
7233
+ const index = m && (data["/indexes"] ?? []).find((r) => r.name === m[1] && typeof r.host === "string");
7234
+ if (index && index.host !== host) host = String(index.host);
7235
+ }
7236
+ const headers = new Headers();
7237
+ 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);
7238
+ const own = appCredential(req.headers["x-agenttwin-app-authorization"]);
7239
+ if (own) headers.set("authorization", own);
7240
+ else if (raw) {
7241
+ const given = headers.get("authorization");
7242
+ if (given && !appCredential(given) && /^Bearer /.test(given) && primary) headers.set("authorization", `Bearer ${primary}`);
7243
+ } else if (headers.get("authorization") === `Bearer ${token}`) {
7244
+ if (primary) headers.set("authorization", `Bearer ${primary}`);
7245
+ else headers.delete("authorization");
7246
+ }
7247
+ if (headers.get("x-api-key") === token) {
7248
+ if (primary) headers.set("x-api-key", primary);
7249
+ else headers.delete("x-api-key");
7250
+ }
7251
+ const call2 = async () => {
7252
+ const target2 = aliasRequest(name, host, req.url ?? "/");
7253
+ const model = compatibleModel(name, body2);
7254
+ const r = await twin(new Request(`https://${target2.host}${target2.url}`, { method, headers, ...model.body ? { body: model.body } : {} }));
7255
+ return { status: r.status, headers: r.headers, bytes: model.restore(Buffer.from(await r.arrayBuffer())), actions: log.drain() };
7256
+ };
7257
+ if (workspace && method !== "GET") this.causing[service.name] = 1;
7258
+ const first = await serialized(call2).finally(() => {
7259
+ if (workspace) this.causing[service.name] = 0;
7260
+ });
7261
+ if (epoch !== this.epoch) return;
7262
+ const recordedBefore = this.events.length;
7263
+ const wrote = apply(first.actions, method, path2, true, workspace);
7264
+ if (workspace) {
7265
+ const out2 = {};
7266
+ first.headers.forEach((v, k) => {
7267
+ if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out2[k] = v;
7268
+ });
7269
+ send2(first.status, out2, first.bytes);
7270
+ return;
7271
+ }
7272
+ let okFalse;
7273
+ if (first.status < 300 && /json/.test(first.headers.get("content-type") ?? "")) try {
6558
7274
  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);
7275
+ if (parsed.ok === false) okFalse = [parsed.error, ...parsed.response_metadata?.messages ?? []].filter(Boolean).join(": ").slice(0, 240) || "ok: false";
6561
7276
  } catch {
6562
- reason = first.bytes.toString("utf8").slice(0, 120);
6563
7277
  }
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})`);
7278
+ if (wrote.length) this.keyedSince(recordedBefore, requestKey);
7279
+ 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}`);
7280
+ else if (okFalse) this.record(service.name, "rejected", path2, `${method} ${path2} \u2192 ${first.status} ok:false: ${okFalse}`);
7281
+ else if (first.status >= 400) {
7282
+ let reason = "";
7283
+ try {
7284
+ const parsed = JSON.parse(first.bytes.toString("utf8"));
7285
+ const e = parsed.error ?? parsed;
7286
+ reason = String(e.message ?? e.error_description ?? e.code ?? "").slice(0, 240);
7287
+ } catch {
7288
+ reason = first.bytes.toString("utf8").slice(0, 120);
7289
+ }
7290
+ this.record(service.name, "rejected", path2, `${method} ${path2} \u2192 ${first.status}${reason ? `: ${reason}` : ""}`);
7291
+ } else if (method === "GET") this.record(service.name, "read", path2, `${first.status}`);
7292
+ const target = wrote.find(matchesFault) ?? wrote[0];
7293
+ if (target && fault?.type === "duplicate-write" && fault.service === service.name && !requestKey && matchesFault(target) && faultOrdinalsFor?.includes(this.candidateIndex(faultKey))) {
7294
+ const second = await serialized(call2);
7295
+ apply(second.actions, method, path2, true);
7296
+ this.faultActions++;
7297
+ this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${target})`);
7298
+ }
7299
+ const out = {};
7300
+ first.headers.forEach((v, k) => {
7301
+ if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out[k] = v;
7302
+ });
7303
+ if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && matchesFault(target)) {
7304
+ this.fired = true;
7305
+ this.faultActions++;
7306
+ this.record(service.name, "fault", target, `write committed; response delayed ${fault.delayMs}ms`);
7307
+ this.keyed(requestKey);
7308
+ later(fault.delayMs, () => send2(first.status, out, first.bytes));
7309
+ } else if (fault?.type === "slow-response" && faultOrdinalsFor && matchesFault(target ?? path2) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
7310
+ this.faultActions++;
7311
+ this.record(service.name, "fault", target ?? path2, `slow-response: ${target ? "write" : "request"} applied; response delayed ${fault.delayMs}ms`);
7312
+ this.keyed(requestKey);
7313
+ later(fault.delayMs, () => respond(first.status, out, first.bytes));
7314
+ } else respond(first.status, out, first.bytes);
7315
+ } catch {
7316
+ json2(500, { error: "world_request_error" });
6572
7317
  }
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
- })));
7318
+ }));
7319
+ });
6593
7320
  server.requestTimeout = 1e4;
7321
+ const upgrade = twin.upgrade;
7322
+ if (upgrade) {
7323
+ const WebSocketServer = await packWebSocketServer(meta2.generation);
7324
+ const toRequest = (req) => {
7325
+ const headers = new Headers();
7326
+ for (const [k, v] of Object.entries(req.headers)) if (typeof v === "string" && !/^(host|x-agenttwin-.*)$/i.test(k)) headers.set(k, v);
7327
+ const own = appCredential(req.headers["x-agenttwin-app-authorization"]);
7328
+ if (own) headers.set("authorization", own);
7329
+ else if (headers.get("authorization") === `Bearer ${token}`) headers.delete("authorization");
7330
+ const raw = req.socket.agenttwinRaw === true;
7331
+ return new Request(`https://${String(req.headers["x-agenttwin-original-host"] ?? (raw ? req.headers.host?.replace(/:\d+$/, "") : void 0) ?? baseHost)}${req.url ?? "/"}`, { headers });
7332
+ };
7333
+ const wss = new WebSocketServer({ noServer: true, handleProtocols: (_set, req) => upgrade.protocol?.(toRequest(req)) ?? false });
7334
+ this.socketServers.push(wss);
7335
+ server.on("upgrade", (req, socket, head) => {
7336
+ const ours = req.socket.agenttwinRaw === true || req.headers.authorization === `Bearer ${token}` || req.headers["x-agenttwin-token"] === token;
7337
+ const path2 = new URL(req.url ?? "/", "http://localhost").pathname;
7338
+ const request = toRequest(req);
7339
+ if (!ours || !upgrade.accepts(request)) {
7340
+ this.record(service.name, ours ? "rejected" : "auth-denied", path2, ours ? `WebSocket ${path2} \u2192 no socket endpoint` : "invalid test credential");
7341
+ socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
7342
+ return;
7343
+ }
7344
+ const epoch = this.epoch;
7345
+ wss.handleUpgrade(req, socket, head, (ws) => {
7346
+ const send2 = ws.send.bind(ws);
7347
+ ws.send = (data2, ...rest) => {
7348
+ try {
7349
+ const parsed = JSON.parse(String(data2));
7350
+ if (typeof parsed.envelope_id === "string" && this.causing[service.name] === 1) {
7351
+ this.causing[service.name] = 2;
7352
+ this.lastEnvelope[service.name] = { send: send2, envelope: parsed };
7353
+ }
7354
+ } catch {
7355
+ }
7356
+ send2(data2, ...rest);
7357
+ };
7358
+ const inWorld = (fn) => withTwinClock(this.twinClock, () => serialized(async () => fn()));
7359
+ ws.on("message", (data2, binary) => {
7360
+ if (epoch !== this.epoch) return;
7361
+ const bytes = Array.isArray(data2) ? Buffer.concat(data2) : Buffer.from(data2);
7362
+ 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"));
7363
+ });
7364
+ ws.on("close", () => {
7365
+ void inWorld(() => upgrade.close(ws)).catch(() => {
7366
+ });
7367
+ });
7368
+ ws.on("error", () => ws.close());
7369
+ this.record(service.name, "read", path2, `WebSocket ${path2} opened`);
7370
+ void inWorld(() => upgrade.open(ws, request)).then(() => apply(log.drain(), "WS", path2, true), () => ws.close(1011, "handler failed"));
7371
+ });
7372
+ });
7373
+ }
6594
7374
  await new Promise((resolve13, reject) => {
6595
7375
  server.once("error", reject);
6596
7376
  server.listen(0, "127.0.0.1", resolve13);
6597
7377
  });
7378
+ const rawServer = createNetServer((socket) => {
7379
+ socket.agenttwinRaw = true;
7380
+ server.emit("connection", socket);
7381
+ });
7382
+ await new Promise((resolve13, reject) => {
7383
+ rawServer.once("error", reject);
7384
+ rawServer.listen(0, "127.0.0.1", resolve13);
7385
+ });
7386
+ this.rawServers.push(rawServer);
7387
+ this.packTcp[service.name] = rawServer.address().port;
6598
7388
  return server;
6599
7389
  }
6600
7390
  assertions() {
@@ -6630,9 +7420,16 @@ var init_http_world = __esm({
6630
7420
  return this.snapshot();
6631
7421
  }
6632
7422
  async close() {
7423
+ await this.postgrest?.close();
7424
+ this.postgrest = void 0;
6633
7425
  this.epoch++;
6634
7426
  for (const timer of this.timers) clearTimeout(timer);
6635
7427
  this.timers.clear();
7428
+ for (const wss of this.socketServers.splice(0)) {
7429
+ for (const ws of wss.clients) ws.terminate();
7430
+ wss.close();
7431
+ }
7432
+ for (const raw of this.rawServers.splice(0)) raw.close();
6636
7433
  await Promise.all(this.servers.map((server) => new Promise((resolve13) => {
6637
7434
  server.close(() => resolve13());
6638
7435
  server.closeAllConnections();
@@ -6714,7 +7511,7 @@ function evaluateProperty(policy, final, events) {
6714
7511
  const key2 = JSON.stringify(canonical(row[field]));
6715
7512
  keyed.set(key2, [...keyed.get(key2) ?? [], row.id ?? row]);
6716
7513
  }
6717
- const duplicates = [...keyed.entries()].filter(([, list2]) => list2.length > 1);
7514
+ const duplicates = [...keyed.entries()].filter(([, list3]) => list3.length > 1);
6718
7515
  return {
6719
7516
  ...base,
6720
7517
  passed: duplicates.length === 0,
@@ -6781,11 +7578,28 @@ function operationMatrix(spec) {
6781
7578
  function packContract(name, adapter) {
6782
7579
  return { name, adapter, version: "twin-pack", operations: [], pack: adapter.slice("pack:".length) };
6783
7580
  }
6784
- var CONTRACTS;
7581
+ var STRIPE_OPERATIONS, CONTRACTS;
6785
7582
  var init_contracts = __esm({
6786
7583
  "src/runtime/contracts.ts"() {
6787
7584
  "use strict";
6788
7585
  init_enterprise_twins();
7586
+ STRIPE_OPERATIONS = [
7587
+ "customers.create",
7588
+ "customers.retrieve",
7589
+ "customers.list",
7590
+ "paymentIntents.create",
7591
+ "paymentIntents.retrieve",
7592
+ "paymentIntents.confirm",
7593
+ "refunds.create",
7594
+ "refunds.retrieve",
7595
+ "refunds.list",
7596
+ "charges.retrieve",
7597
+ "charges.list",
7598
+ "events.retrieve",
7599
+ "events.list",
7600
+ "subscriptionItems.retrieve",
7601
+ "subscriptionItems.update"
7602
+ ];
6789
7603
  CONTRACTS = {
6790
7604
  composio: {
6791
7605
  version: "1.0.0",
@@ -6838,9 +7652,11 @@ var init_contracts = __esm({
6838
7652
  { 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
7653
  { method: "GET", endpoint: "/v1/refunds[/<id>]", effect: "retrieve or list refunds", parameters: ["limit", "starting_after", "charge", "payment_intent"], errors: ["404 resource_missing"] },
6840
7654
  { 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"] }
7655
+ { method: "GET", endpoint: "/v1/events[/<id>]", effect: "retrieve or list recorded charge.refunded events", parameters: ["limit", "type"], errors: ["404 resource_missing"] },
7656
+ { method: "GET", endpoint: "/v1/subscription_items/<id>", effect: "retrieve a seeded subscription item", parameters: [], errors: ["404 resource_missing"] },
7657
+ { 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
7658
  ],
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"]
7659
+ 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
7660
  },
6845
7661
  slack: {
6846
7662
  version: "1.0.0",
@@ -6850,7 +7666,7 @@ var init_contracts = __esm({
6850
7666
  { method: "GET|POST", endpoint: "/api/conversations.history", effect: "read /messages", parameters: ["channel"], errors: ["channel_not_found"] },
6851
7667
  { method: "GET|POST", endpoint: "/api/conversations.list", effect: "read /channels", parameters: [], errors: [] }
6852
7668
  ],
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"]
7669
+ 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
7670
  },
6855
7671
  github: {
6856
7672
  version: "1.0.0",
@@ -6949,6 +7765,8 @@ var init_contracts = __esm({
6949
7765
  { method: "GET", endpoint: "/gmail/v1/users/me/messages", effect: "list message ids with a snippet q filter", parameters: ["q"], errors: ["400 validation"] },
6950
7766
  { method: "GET", endpoint: "/gmail/v1/users/me/messages/<id>", effect: "retrieve message", parameters: [], errors: ["404 NOT_FOUND"] },
6951
7767
  { method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] },
7768
+ { 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"] },
7769
+ { 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
7770
  { 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
7771
  { 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
7772
  { 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 +7784,7 @@ var init_contracts = __esm({
6966
7784
  { 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
7785
  { 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
7786
  ],
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"]
7787
+ 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
7788
  },
6971
7789
  "upstash-redis": {
6972
7790
  version: "1.0.0",
@@ -7065,7 +7883,7 @@ var init_contracts = __esm({
7065
7883
  });
7066
7884
 
7067
7885
  // src/runtime/cost-model.ts
7068
- import { readFile as readFile5, writeFile as writeFile6 } from "fs/promises";
7886
+ import { readFile as readFile5, writeFile as writeFile7 } from "fs/promises";
7069
7887
  import { join as join12 } from "path";
7070
7888
  async function readCostConfig(cwd) {
7071
7889
  try {
@@ -7201,7 +8019,7 @@ function incidentFor(receipt, a) {
7201
8019
  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
8020
  return { kind, extra, ...money2 ? { money: money2 } : {}, service: a.service };
7203
8021
  }
7204
- function describe(a) {
8022
+ function describe(a, incomplete) {
7205
8023
  const what = `${serviceName(a.service)} ${recordName(a.path)}${filterText(a.where)}`;
7206
8024
  if (a.passed) return `${what}: ${a.actual ?? a.count} as expected`;
7207
8025
  if (a.absent || a.count === 0) return `${what}: expected none, found ${a.actual}`;
@@ -7209,29 +8027,37 @@ function describe(a) {
7209
8027
  const times3 = a.count === 1 && a.actual === 2 ? "the same write happened twice" : `${a.actual - a.count} more than allowed`;
7210
8028
  return `${what}: expected ${a.count}, found ${a.actual} (${times3})`;
7211
8029
  }
7212
- if (a.actual === 0) return `${what}: expected ${a.count}, found none (the write never happened)`;
8030
+ if (a.actual === 0) return `${what}: expected ${a.count}, found none${incomplete ? "" : " (the write never happened)"}`;
7213
8031
  return `${what}: expected ${a.count}, found ${a.actual}`;
7214
8032
  }
7215
8033
  function explainRun(receipt, costs) {
7216
8034
  const checks = receipt.assertions ?? [];
7217
8035
  const failed = checks.filter((a) => !a.passed);
7218
- const cost = estimateCost(failed.map((a) => incidentFor(receipt, a)), costs, { title: receipt.name });
8036
+ const unsupported2 = receipt.unsupported ?? [];
8037
+ const coverageGap = receipt.status === "incomplete" && unsupported2.length > 0;
8038
+ const duplicates = failed.filter((a) => (a.actual ?? 0) > (a.count ?? Infinity));
8039
+ const cost = estimateCost((coverageGap ? duplicates : failed).map((a) => incidentFor(receipt, a)), costs, { title: receipt.name });
7219
8040
  const money2 = failed.map((a) => extraMoney(receipt, a)).filter((m) => !!m);
7220
8041
  const atRisk = money2.length ? { amount: Math.max(...money2.map((m) => m.amount)), currency: money2[0].currency } : void 0;
7221
8042
  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
8043
  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));
8044
+ const duplicate = duplicates.length > 0;
7224
8045
  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.";
8046
+ 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));
8047
+ if (lostReply) cause = "Your code retried after the lost reply without an idempotency key, so the service applied the write a second time.";
7226
8048
  else if (duplicate) cause = "Your code repeated a write that should happen once.";
7227
8049
  else if (failed.some((a) => a.actual === 0)) cause = "An expected write never reached the service.";
7228
- if (receipt.executionError) cause = receipt.executionError;
8050
+ if (coverageGap) {
8051
+ const first = unsupported2[0];
8052
+ const gap = typeof first === "string" ? `Unsupported twin operation: ${first}` : "A twin operation was unsupported.";
8053
+ cause = duplicate ? `${cause} ${gap}` : gap;
8054
+ } else if (receipt.executionError) cause = receipt.executionError;
7229
8055
  else if (receipt.application?.timedOut) cause = "The application did not finish before the time limit.";
7230
8056
  const clip = (text3) => text3.length > 80 ? text3.slice(0, 77) + "..." : text3;
7231
8057
  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
8058
  const total = checks.length + infra.length, passedCount = total - failed.length - infra.filter((c) => !c.passed).length;
7233
8059
  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 };
8060
+ 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
8061
  }
7236
8062
  function renderRunSummary(receipt, opts = {}) {
7237
8063
  const e = explainRun(receipt, opts.costs);
@@ -7246,7 +8072,7 @@ function renderRunSummary(receipt, opts = {}) {
7246
8072
  const builtIn = receipt.defaultChecks ?? [];
7247
8073
  if (builtIn.length) lines.push(bullet(`Built-in checks: ${builtIn.filter((c) => c.passed).length}/${builtIn.length} held`));
7248
8074
  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).`));
8075
+ if (e.unsupported) lines.push("", bullet(`${e.unsupported} call(s) hit unsupported operations and were never forwarded.`));
7250
8076
  if (opts.next?.length) lines.push("", opts.markdown ? "## Next" : "Next:", ...opts.next.map((n) => bullet(n)));
7251
8077
  return lines.join("\n") + "\n";
7252
8078
  }
@@ -7273,7 +8099,7 @@ var init_run_summary = __esm({
7273
8099
  });
7274
8100
 
7275
8101
  // src/runtime/generic-calls.ts
7276
- import { createHash as createHash10 } from "crypto";
8102
+ import { createHash as createHash11 } from "crypto";
7277
8103
  function canonical2(value) {
7278
8104
  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
8105
  }
@@ -7559,7 +8385,7 @@ var init_generic_calls = __esm({
7559
8385
  VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
7560
8386
  KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
7561
8387
  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)}`;
8388
+ digest3 = (value) => `sha256:${createHash11("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
7563
8389
  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
8390
  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
8391
  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 +8438,7 @@ var init_generic_calls = __esm({
7612
8438
 
7613
8439
  // src/runtime/default-checks.ts
7614
8440
  function addedRows(initial, final) {
7615
- const rows2 = (list2) => list2.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
8441
+ const rows2 = (list3) => list3.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
7616
8442
  const ids = new Set(rows2(initial).map((r) => r.id).filter((id) => id !== void 0 && id !== null));
7617
8443
  const seen = /* @__PURE__ */ new Map();
7618
8444
  for (const r of rows2(initial)) if (r.id === void 0) seen.set(canonical3(r), (seen.get(canonical3(r)) ?? 0) + 1);
@@ -7776,7 +8602,7 @@ var init_default_checks = __esm({
7776
8602
  };
7777
8603
  stripeNoDuplicatePayment = {
7778
8604
  id: "stripe.no-duplicate-payment",
7779
- title: "No duplicate charges or customers for one request",
8605
+ title: "No duplicate charges, customers or subscriptions for one request",
7780
8606
  path: "/v1/payment_intents",
7781
8607
  coversDuplicates: true,
7782
8608
  expected: "one payment intent per amount/currency/customer/payment method and one customer per email",
@@ -7795,6 +8621,19 @@ var init_default_checks = __esm({
7795
8621
  evidence: writeSequences(ctx, s, group.map((r) => r.id))
7796
8622
  });
7797
8623
  }
8624
+ const subscriptions = addedRows(rowsOf(ctx.initialState, s, "/v1/subscriptions"), rowsOf(ctx.finalState, s, "/v1/subscriptions")).filter((r) => !["canceled", "incomplete_expired"].includes(String(r.status)));
8625
+ 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) }));
8626
+ 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)) {
8627
+ const items = itemsOf(group[0]), currency = String(items[0]?.price.currency ?? group[0].currency ?? "usd");
8628
+ const perPeriod = items.reduce((n, i) => n + (typeof i.price.unit_amount === "number" ? i.price.unit_amount * i.quantity : 0), 0);
8629
+ out.push({
8630
+ path: "/v1/subscriptions",
8631
+ actual: { subscriptions: group.map((r) => r.id), customer: group[0].customer },
8632
+ finding: `Your agent subscribed ${String(group[0].customer)} ${times2(group.length)} to the same plan${faultPhrase(ctx)}`,
8633
+ 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 },
8634
+ evidence: writeSequences(ctx, s, group.map((r) => r.id))
8635
+ });
8636
+ }
7798
8637
  const customers = addedRows(rowsOf(ctx.initialState, s, "/v1/customers"), rowsOf(ctx.finalState, s, "/v1/customers"));
7799
8638
  for (const group of groups(customers, (r) => typeof r.email === "string" && r.email ? r.email.toLowerCase() : void 0))
7800
8639
  out.push({
@@ -7921,14 +8760,14 @@ var init_default_checks = __esm({
7921
8760
  };
7922
8761
  VENDOR_COVERS = { "retry-without-key": /\.idempotent-retries$/, "announce-after-failed-write": /\.announce-after-success$/ };
7923
8762
  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"] ?? [];
8763
+ registryFor = (adapter) => DEFAULT_CHECKS[adapter ?? "json-collection"] ?? (adapter?.startsWith("pack:") ? DEFAULT_CHECKS[adapter.slice(5)] : void 0) ?? [];
7925
8764
  refOf = (s) => typeof s === "string" ? { name: s, adapter: s } : s;
7926
8765
  }
7927
8766
  });
7928
8767
 
7929
8768
  // src/runtime/twin-proxy.ts
7930
8769
  import { execFile as execFile5 } from "child_process";
7931
- import { mkdtemp as mkdtemp6, readFile as readFile6, rm as rm6, writeFile as writeFile7 } from "fs/promises";
8770
+ import { mkdtemp as mkdtemp6, readFile as readFile6, rm as rm6, writeFile as writeFile8 } from "fs/promises";
7932
8771
  import { createServer as createServer4, request as httpRequest } from "http";
7933
8772
  import { tmpdir as tmpdir6 } from "os";
7934
8773
  import { join as join13 } from "path";
@@ -7988,7 +8827,7 @@ async function runAuthority(dir) {
7988
8827
  if (!ctx) {
7989
8828
  ctx = (async () => {
7990
8829
  const base = join13(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
7991
- await writeFile7(base + ".ext", `basicConstraints=critical,CA:FALSE
8830
+ await writeFile8(base + ".ext", `basicConstraints=critical,CA:FALSE
7992
8831
  keyUsage=critical,digitalSignature
7993
8832
  extendedKeyUsage=serverAuth
7994
8833
  subjectAltName=DNS:${host}
@@ -8027,6 +8866,7 @@ async function startTwinProxy(routes2) {
8027
8866
  const headers = {};
8028
8867
  const strip = route.auth === "passthrough" ? ["host", "proxy-connection", "proxy-authorization"] : SECRET;
8029
8868
  for (const [k, v] of Object.entries(req.headers)) if (v !== void 0 && !strip.includes(k)) headers[k] = v;
8869
+ if (route.appCredential && typeof req.headers.authorization === "string" && /^Bearer \S{12,}$/.test(req.headers.authorization)) headers["x-agenttwin-app-authorization"] = req.headers.authorization;
8030
8870
  if (route.auth === "passthrough") headers["x-agenttwin-token"] = route.token;
8031
8871
  else if (route.auth === "x-api-key") headers["x-api-key"] = route.token;
8032
8872
  else headers.authorization = `Bearer ${route.token}`;
@@ -8122,7 +8962,7 @@ var init_twin_proxy = __esm({
8122
8962
  });
8123
8963
 
8124
8964
  // src/runtime/twin-routing.ts
8125
- import { mkdtemp as mkdtemp7, readFile as readFile7, rm as rm7, writeFile as writeFile8 } from "fs/promises";
8965
+ import { mkdtemp as mkdtemp7, readFile as readFile7, rm as rm7, writeFile as writeFile9 } from "fs/promises";
8126
8966
  import { tmpdir as tmpdir7 } from "os";
8127
8967
  import { join as join14 } from "path";
8128
8968
  function twinRoutes(services, world, models) {
@@ -8131,10 +8971,11 @@ function twinRoutes(services, world, models) {
8131
8971
  const adapter = service.adapter ?? "", credential = world.credentials[service.name];
8132
8972
  if (credential && isPackAdapter(adapter)) {
8133
8973
  const record4 = packRecord(adapter.slice(PACK_PREFIX.length));
8134
- const auth = record4.credentialDoor ? "bearer" : "passthrough";
8974
+ const issuesKey = !!record4.credentialDoor && Object.values(record4.credentialDoor.fill ?? {}).some((field) => !String(field).startsWith("file:"));
8975
+ const auth = issuesKey ? "bearer" : "passthrough";
8135
8976
  for (const h of record4.hosts) {
8136
8977
  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 });
8978
+ 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
8979
  }
8139
8980
  continue;
8140
8981
  }
@@ -8148,6 +8989,7 @@ var PROVIDER_HOSTS, TWIN_PRELOAD;
8148
8989
  var init_twin_routing = __esm({
8149
8990
  "src/runtime/twin-routing.ts"() {
8150
8991
  "use strict";
8992
+ init_node_options();
8151
8993
  init_packs();
8152
8994
  PROVIDER_HOSTS = {
8153
8995
  // OpenAI-compatible APIs answer in the same format, so they are served by the OpenAI twin (with its scripted tool calls).
@@ -8202,9 +9044,13 @@ if(originalFetch)globalThis.fetch=async function(input,init){
8202
9044
  if(!r)throw blocked('fetch',url.hostname,url.port||(url.protocol==='https:'?443:80),method);
8203
9045
  if(process.env.AGENTTWIN_DEBUG_ROUTES)console.error('route-match '+url.hostname+' auth='+r.auth+' service='+r.service);
8204
9046
  const request=new Request(input,init),headers=new Headers(request.headers);
9047
+ {const own=headers.get('authorization');if(r.appCredential&&own&&/^Bearer \S{12,}$/.test(own))headers.set('x-agenttwin-app-authorization',own);}
8205
9048
  for(const name of removed(r))headers.delete(name);const [name,value]=credential(r);headers.set(name,value);
8206
9049
  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'});
9050
+ // Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch (Upstash's
9051
+ // client sets keepalive on every call).
9052
+ const body=request.body===null?undefined:Buffer.from(await request.arrayBuffer());
9053
+ return originalFetch(r.target+rewrite(r,url.pathname)+url.search,{method:request.method,headers,...(body===undefined?{}:{body}),redirect:'manual',signal:request.signal});
8208
9054
  };
8209
9055
  const originalHttpRequest=http.request;
8210
9056
  for(const [mod,scheme] of [[http,'http'],[https,'https']]){
@@ -8223,6 +9069,8 @@ for(const [mod,scheme] of [[http,'http'],[https,'https']]){
8223
9069
  const target=new URL(r.target),headers={};
8224
9070
  const given=options.headers||{};
8225
9071
  for(const [k,v] of Array.isArray(given)?[]:Object.entries(given))if(!removed(r).includes(k.toLowerCase()))headers[k]=v;
9072
+ // The app's own credential travels beside the run token: a pack host keeps it when the twin issued it (an app-level token).
9073
+ 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
9074
  const [name,value]=credential(r);headers[name]=value;headers.host=target.host;headers['x-agenttwin-original-host']=host;
8227
9075
  const location=source();if(location)headers['x-agenttwin-source']=location;
8228
9076
  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 +9151,36 @@ function sqlTables(sql) {
8303
9151
  }
8304
9152
  return [...out];
8305
9153
  }
9154
+ function bindValues(body2) {
9155
+ try {
9156
+ let at = body2.indexOf(0) + 1;
9157
+ at = body2.indexOf(0, at) + 1;
9158
+ const formats2 = body2.readInt16BE(at);
9159
+ at += 2;
9160
+ const codes = [];
9161
+ for (let i = 0; i < formats2; i++) {
9162
+ codes.push(body2.readInt16BE(at));
9163
+ at += 2;
9164
+ }
9165
+ const count = body2.readInt16BE(at);
9166
+ at += 2;
9167
+ const values = [];
9168
+ for (let i = 0; i < count; i++) {
9169
+ const len = body2.readInt32BE(at);
9170
+ at += 4;
9171
+ if (len < 0) {
9172
+ values.push(null);
9173
+ continue;
9174
+ }
9175
+ const binary = (codes.length === 1 ? codes[0] : codes[i] ?? 0) === 1;
9176
+ values.push(binary ? null : body2.toString("utf8", at, at + len));
9177
+ at += len;
9178
+ }
9179
+ return values;
9180
+ } catch {
9181
+ return [];
9182
+ }
9183
+ }
8306
9184
  async function startPostgresEngine(options = {}) {
8307
9185
  const started = Date.now();
8308
9186
  let PGlite;
@@ -8370,7 +9248,7 @@ async function startPostgresEngine(options = {}) {
8370
9248
  if (name) {
8371
9249
  conn.names.set(name, sql);
8372
9250
  conn.statements.add(ns(name));
8373
- }
9251
+ } else conn.unnamed = sql;
8374
9252
  return { body: Buffer.concat([cstr(ns(name)), body2.subarray(end + 1)]), sql };
8375
9253
  }
8376
9254
  if (type === "B") {
@@ -8425,7 +9303,13 @@ async function startPostgresEngine(options = {}) {
8425
9303
  for (const m of prepared) outputs.push(await raw(msg(m.type, m.body)));
8426
9304
  const out = Buffer.concat(outputs), { tags, status, failed } = scan(out);
8427
9305
  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) });
9306
+ const binds = batch.filter((m) => m.type === "B").map((m) => {
9307
+ const pEnd = m.body.indexOf(0), sEnd = m.body.indexOf(0, pEnd + 1), stmt = m.body.toString("utf8", pEnd + 1, sEnd);
9308
+ return { sql: stmt ? conn.names.get(stmt) : conn.unnamed, params: bindValues(m.body) };
9309
+ });
9310
+ const readSql = sqls.length ? sqls : binds.flatMap((b) => b.sql && !isWriteSql(b.sql) ? [b.sql] : []);
9311
+ const readTables2 = [...new Set(readSql.flatMap(sqlTables))];
9312
+ 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
9313
  owner = status === "I" ? null : conn;
8430
9314
  let committed = [];
8431
9315
  if (status === "I") {
@@ -8619,7 +9503,9 @@ async function startPostgresEngine(options = {}) {
8619
9503
  }
8620
9504
  };
8621
9505
  const seed = async (data) => direct(async () => {
8622
- if (data.sql) await db.exec(data.sql);
9506
+ if (data.sql) {
9507
+ for (const part of data.sql.split(/^(?=-- Schema source: )/m)) if (part.trim()) await db.exec(part);
9508
+ }
8623
9509
  for (const [table2, rows2] of Object.entries(data.tables ?? {})) {
8624
9510
  for (const row of rows2) {
8625
9511
  const fields = Object.keys(row);
@@ -8911,13 +9797,13 @@ var init_server_steps = __esm({
8911
9797
 
8912
9798
  // src/runtime/local.ts
8913
9799
  import { spawn as spawn2 } from "child_process";
8914
- import { realpath as realpath2 } from "fs/promises";
9800
+ import { realpath as realpath3 } from "fs/promises";
8915
9801
  import { dirname as dirname2, resolve as resolve4 } from "path";
8916
9802
  async function sourceRoot(app, spec) {
8917
- const real = await realpath2(app);
9803
+ const real = await realpath3(app);
8918
9804
  if (!spec.directory) return real;
8919
9805
  for (let candidate = real; ; candidate = dirname2(candidate)) {
8920
- if (await realpath2(resolve4(candidate, spec.directory)).then((p) => p === real, () => false)) return candidate;
9806
+ if (await realpath3(resolve4(candidate, spec.directory)).then((p) => p === real, () => false)) return candidate;
8921
9807
  if (dirname2(candidate) === candidate) return real;
8922
9808
  }
8923
9809
  }
@@ -8936,10 +9822,11 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
8936
9822
  }
8937
9823
  engines = await startLocalEngines(filesDir, spec);
8938
9824
  Object.assign(env, engines.env);
9825
+ if (engines.env.DATABASE_URL) world.attachDatabase(engines.env.DATABASE_URL);
8939
9826
  let stdout = "", stderr = "", timedOut = false;
8940
9827
  const node = /(^|\/)node(\.exe)?$/.test(spec.command[0]);
8941
9828
  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(" ");
9829
+ if (node) env.NODE_OPTIONS = await singlePreload(extraEnv.NODE_OPTIONS ?? "", hook.path);
8943
9830
  let proxy;
8944
9831
  if (!node) {
8945
9832
  const configured = extraEnv.AGENTTWIN_ROUTES ? JSON.parse(extraEnv.AGENTTWIN_ROUTES).routes : void 0;
@@ -9062,6 +9949,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
9062
9949
  var init_local = __esm({
9063
9950
  "src/runtime/local.ts"() {
9064
9951
  "use strict";
9952
+ init_node_options();
9065
9953
  init_application_process();
9066
9954
  init_browser_process();
9067
9955
  init_twin_clock();
@@ -9546,7 +10434,7 @@ var init_offline = __esm({
9546
10434
  // src/runtime/credentials.ts
9547
10435
  import { homedir } from "os";
9548
10436
  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";
10437
+ import { readFile as readFile9, mkdir as mkdir4, writeFile as writeFile10, chmod as chmod2, rm as rm9 } from "fs/promises";
9550
10438
  async function savedConnection() {
9551
10439
  try {
9552
10440
  const data = JSON.parse(await readFile9(path(), "utf8"));
@@ -9693,7 +10581,7 @@ var init_hosted_packs = __esm({
9693
10581
  });
9694
10582
 
9695
10583
  // src/runtime/e2b.ts
9696
- import { createRequire } from "module";
10584
+ import { createRequire as createRequire3 } from "module";
9697
10585
  import { readFile as readFile12 } from "fs/promises";
9698
10586
  import { randomBytes as randomBytes4 } from "crypto";
9699
10587
  import { homedir as homedir2 } from "os";
@@ -9771,7 +10659,7 @@ logfile /tmp/agenttwin-redis.log
9771
10659
  }
9772
10660
  await sandbox.files.write("/input/runtime.json", JSON.stringify(runtimeEnv), { user: "root" });
9773
10661
  await sandbox.commands.run("chmod -R a+rX /input", { user: "root" });
9774
- const playwrightVersion = createRequire(import.meta.url)("playwright/package.json").version;
10662
+ const playwrightVersion = createRequire3(import.meta.url)("playwright/package.json").version;
9775
10663
  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
10664
  await sandbox.commands.run("node /input/check-runtime.cjs", { user: "root" });
9777
10665
  if (spec.browser) {
@@ -9811,12 +10699,12 @@ var init_e2b = __esm({
9811
10699
  });
9812
10700
 
9813
10701
  // 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";
10702
+ import { createHash as createHash12 } from "crypto";
10703
+ import { mkdir as mkdir5, readFile as readFile13, writeFile as writeFile11 } from "fs/promises";
9816
10704
  import { join as join21, relative, resolve as resolve5 } from "path";
9817
10705
  function filesDigest(sourceDigests) {
9818
10706
  const canonical5 = Object.keys(sourceDigests).sort().map((file) => `${file}:${sourceDigests[file]}`).join("\n");
9819
- return createHash11("sha256").update(canonical5).digest("hex");
10707
+ return createHash12("sha256").update(canonical5).digest("hex");
9820
10708
  }
9821
10709
  function checksOfReceipt(receipt) {
9822
10710
  const checks = (receipt.evaluation?.checks ?? []).map((c) => ({
@@ -9901,7 +10789,7 @@ function buildMatrixReport(input) {
9901
10789
  async function runSeedMatrix(cwd, opts) {
9902
10790
  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
10791
  const baseSeed = normalizeSeed(opts.seed);
9904
- const matrixName = `matrix-${createHash11("sha256").update(`${baseSeed}:${opts.seeds}`).digest("hex").slice(0, 8)}`;
10792
+ const matrixName = `matrix-${createHash12("sha256").update(`${baseSeed}:${opts.seeds}`).digest("hex").slice(0, 8)}`;
9905
10793
  const matrixDir = resolve5(cwd, opts.out ?? join21(".agenttwin/runs", matrixName));
9906
10794
  await mkdir5(matrixDir, { recursive: true, mode: 448 });
9907
10795
  const results = [];
@@ -9934,8 +10822,8 @@ async function runSeedMatrix(cwd, opts) {
9934
10822
  });
9935
10823
  const reportPath = resolve5(cwd, opts.out ?? join21(matrixDir, "matrix.json"));
9936
10824
  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}
10825
+ await writeFile11(reportPath, JSON.stringify(report, null, 2) + "\n", { mode: 384 });
10826
+ await writeFile11(join21(matrixDir, "matrix.md"), `${report.verdict.summary}
9939
10827
 
9940
10828
  Report: ${relative(cwd, reportPath).split("\\").join("/")}
9941
10829
  `);
@@ -9955,8 +10843,8 @@ var init_matrix = __esm({
9955
10843
  });
9956
10844
 
9957
10845
  // src/runtime/source-build.ts
9958
- import { createHash as createHash12 } from "crypto";
9959
- import { lstat, readFile as readFile14, realpath as realpath3 } from "fs/promises";
10846
+ import { createHash as createHash13 } from "crypto";
10847
+ import { lstat, readFile as readFile14, realpath as realpath4 } from "fs/promises";
9960
10848
  import { isAbsolute as isAbsolute2, join as join22, relative as relative2, resolve as resolve6, sep } from "path";
9961
10849
  import { isDeepStrictEqual as isDeepStrictEqual8 } from "util";
9962
10850
  async function checkSourceBuild(directory, spec) {
@@ -9965,7 +10853,7 @@ async function checkSourceBuild(directory, spec) {
9965
10853
  throw new CliError(`Prepared source is stale: ${message}`, { code: EXIT.BLOCKED, action: "Prepare this workflow again from the current repository before running it." });
9966
10854
  };
9967
10855
  try {
9968
- const preparedRoot = await realpath3(directory);
10856
+ const preparedRoot = await realpath4(directory);
9969
10857
  const sidecar = join22(preparedRoot, LOCAL_BUILD_FILE);
9970
10858
  const info = await lstat(sidecar);
9971
10859
  if (!info.isFile() || info.isSymbolicLink() || info.size > 2 * 1024 * 1024) stale("local source record is missing, unsafe or exceeds bounds");
@@ -9977,21 +10865,21 @@ async function checkSourceBuild(directory, spec) {
9977
10865
  if (!build2.sourceDigests || typeof build2.sourceDigests !== "object" || Array.isArray(build2.sourceDigests)) stale("original source hashes are missing");
9978
10866
  const entries = Object.entries(build2.sourceDigests);
9979
10867
  if (!entries.length || entries.length > 1501) stale("original source set exceeds bounds");
9980
- const root = await realpath3(local.sourceRoot);
10868
+ const root = await realpath4(local.sourceRoot);
9981
10869
  let total = 0;
9982
10870
  for (const [file, expected] of entries) {
9983
10871
  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);
10872
+ const path2 = resolve6(root, file), canonical5 = await realpath4(path2);
9985
10873
  const rel = relative2(root, canonical5);
9986
10874
  if (path2 !== canonical5 || rel === ".." || rel.startsWith(".." + sep) || isAbsolute2(rel) || !(await lstat(path2)).isFile()) stale(`source moved or uses a symlink: ${file}`);
9987
10875
  const size = (await lstat(path2)).size;
9988
10876
  if (total + size > 30 * 1024 * 1024) stale("original source exceeds bounds");
9989
10877
  const source = await readFile14(path2);
9990
10878
  total += source.length;
9991
- if (total > 30 * 1024 * 1024 || createHash12("sha256").update(source).digest("hex") !== expected) stale(`source changed: ${file}`);
10879
+ if (total > 30 * 1024 * 1024 || createHash13("sha256").update(source).digest("hex") !== expected) stale(`source changed: ${file}`);
9992
10880
  }
9993
10881
  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");
10882
+ 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
10883
  return { root, digest: spec.sourceBuild };
9996
10884
  } catch (error) {
9997
10885
  if (error instanceof CliError) throw error;
@@ -10004,7 +10892,7 @@ var init_source_build = __esm({
10004
10892
  "use strict";
10005
10893
  init_exit();
10006
10894
  LOCAL_BUILD_FILE = ".agenttwin/source-build.json";
10007
- sourceBuildDigest = (build2) => createHash12("sha256").update(JSON.stringify(build2)).digest("hex");
10895
+ sourceBuildDigest = (build2) => createHash13("sha256").update(JSON.stringify(build2)).digest("hex");
10008
10896
  sha3 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
10009
10897
  }
10010
10898
  });
@@ -10928,6 +11816,94 @@ var init_catalog = __esm({
10928
11816
  }
10929
11817
  });
10930
11818
 
11819
+ // src/inventory/service-coverage.ts
11820
+ function serviceSupport(tool) {
11821
+ const provider = tool.providerId ?? tool.title.toLowerCase();
11822
+ const adapters = ADAPTER_GROUPS[provider] ?? TWIN_ADAPTERS.filter((name) => name === provider);
11823
+ 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." };
11824
+ 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." };
11825
+ 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." };
11826
+ }
11827
+ function missingStripeOperations(workflow, tools, adapter) {
11828
+ const steps = workflow.steps.filter((step) => tools.has(step.tool));
11829
+ if (!steps.length) return [];
11830
+ const missingFor = (selected) => [...new Set(steps.flatMap((step) => step.operations.flatMap((operation) => {
11831
+ if (!(selected === "stripe" ? STRIPE_OPERATIONS.includes(operation) : PACK_STRIPE_OPERATIONS.has(operation))) return [operation];
11832
+ if (operation !== "subscriptionItems.update") return [];
11833
+ const fields = step.stripeItemFields;
11834
+ if (!fields) return [`${operation} (unverified quantity parameters)`];
11835
+ const unsupported2 = fields.filter((field) => field !== "quantity" && !(selected === "pack:stripe" && field === "expand"));
11836
+ if (unsupported2.length) return [`${operation} (${unsupported2.join(", ")})`];
11837
+ return fields.includes("quantity") ? [] : [`${operation} (quantity required)`];
11838
+ })))];
11839
+ if (adapter) return missingFor(adapter);
11840
+ const builtin = missingFor("stripe");
11841
+ if (!builtin.length || !packRecord("stripe")) return builtin;
11842
+ const pack = missingFor("pack:stripe");
11843
+ return pack.length < builtin.length ? pack : builtin;
11844
+ }
11845
+ var TWIN_ADAPTERS, ADAPTER_GROUPS, PACK_STRIPE_OPERATIONS;
11846
+ var init_service_coverage = __esm({
11847
+ "src/inventory/service-coverage.ts"() {
11848
+ "use strict";
11849
+ init_contracts();
11850
+ init_enterprise_twins();
11851
+ init_packs();
11852
+ 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];
11853
+ ADAPTER_GROUPS = {
11854
+ google: ["gmail", "google-calendar", "google-oauth"],
11855
+ atlassian: ["jira", "confluence"],
11856
+ microsoft: ["microsoft-teams", "outlook", "entra-id", "sharepoint"]
11857
+ };
11858
+ PACK_STRIPE_OPERATIONS = /* @__PURE__ */ new Set([
11859
+ "accounts.create",
11860
+ "accountLinks.create",
11861
+ "balance.retrieve",
11862
+ "balanceTransactions.list",
11863
+ "billingPortal.configurations.list",
11864
+ "billingPortal.configurations.create",
11865
+ "billingPortal.sessions.create",
11866
+ "charges.list",
11867
+ "charges.retrieve",
11868
+ "checkout.sessions.create",
11869
+ "checkout.sessions.listLineItems",
11870
+ "coupons.create",
11871
+ "customers.create",
11872
+ "customers.retrieve",
11873
+ "customers.search",
11874
+ "customers.update",
11875
+ "invoicePayments.list",
11876
+ "invoices.create",
11877
+ "invoices.createPreview",
11878
+ "invoices.retrieve",
11879
+ "invoices.pay",
11880
+ "invoices.voidInvoice",
11881
+ "paymentIntents.create",
11882
+ "paymentIntents.cancel",
11883
+ "paymentMethods.retrieve",
11884
+ "paymentMethods.detach",
11885
+ "payouts.create",
11886
+ "prices.create",
11887
+ "prices.list",
11888
+ "prices.retrieve",
11889
+ "products.create",
11890
+ "products.list",
11891
+ "promotionCodes.create",
11892
+ "promotionCodes.list",
11893
+ "refunds.create",
11894
+ "subscriptions.cancel",
11895
+ "subscriptions.deleteDiscount",
11896
+ "subscriptions.list",
11897
+ "subscriptions.retrieve",
11898
+ "subscriptions.update",
11899
+ "subscriptionItems.retrieve",
11900
+ "subscriptionItems.update",
11901
+ "transfers.create",
11902
+ "webhookEndpoints.create"
11903
+ ]);
11904
+ }
11905
+ });
11906
+
10931
11907
  // src/inventory/dashboard-transfer.ts
10932
11908
  function discoveryTransfer(value) {
10933
11909
  const input = value;
@@ -10954,12 +11930,16 @@ function discoveryTransfer(value) {
10954
11930
  if (!Array.isArray(w.steps) || w.steps.length > 1e3) throw new Error("Invalid workflow steps");
10955
11931
  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
11932
  const step = rawStep;
10957
- return { tool: text3(step.tool), operations: strings(step.operations) };
11933
+ return { tool: text3(step.tool), operations: strings(step.operations), ...step.stripeItemFields !== void 0 ? { stripeItemFields: step.stripeItemFields === null ? null : strings(step.stripeItemFields) } : {} };
10958
11934
  }), ...w.entrypoint ? { entrypoint: entrypoint(w.entrypoint) } : {} };
10959
11935
  });
10960
11936
  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
11937
  const ids = new Set(tools.map((t) => t.id));
10962
11938
  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");
11939
+ const stripeTools = new Set(tools.filter((tool) => tool.title.toLowerCase() === "stripe").map((tool) => tool.id));
11940
+ for (const workflow of workflows) {
11941
+ if (missingStripeOperations(workflow, stripeTools).length) workflow.supported = false;
11942
+ }
10963
11943
  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
11944
  if (Buffer.byteLength(JSON.stringify(result2)) > 2 * 1024 * 1024) throw new Error("Discovery exceeds 2 MiB");
10965
11945
  return result2;
@@ -10967,12 +11947,13 @@ function discoveryTransfer(value) {
10967
11947
  var init_dashboard_transfer = __esm({
10968
11948
  "src/inventory/dashboard-transfer.ts"() {
10969
11949
  "use strict";
11950
+ init_service_coverage();
10970
11951
  init_git();
10971
11952
  }
10972
11953
  });
10973
11954
 
10974
11955
  // src/inventory/store.ts
10975
- import { mkdir as mkdir6, readFile as readFile16, writeFile as writeFile11 } from "fs/promises";
11956
+ import { mkdir as mkdir6, readFile as readFile16, writeFile as writeFile12 } from "fs/promises";
10976
11957
  import { join as join24 } from "path";
10977
11958
  function storeDir(cwd) {
10978
11959
  return join24(cwd, STORE_DIR);
@@ -10982,7 +11963,7 @@ function storePath(cwd, name) {
10982
11963
  }
10983
11964
  async function ensureStore(cwd) {
10984
11965
  await mkdir6(storeDir(cwd), { recursive: true });
10985
- await writeFile11(storePath(cwd, ".gitignore"), STORE_GITIGNORE, "utf8");
11966
+ await writeFile12(storePath(cwd, ".gitignore"), STORE_GITIGNORE, "utf8");
10986
11967
  }
10987
11968
  async function readJson(path2) {
10988
11969
  try {
@@ -10992,7 +11973,7 @@ async function readJson(path2) {
10992
11973
  }
10993
11974
  }
10994
11975
  async function writeJson(path2, value) {
10995
- await writeFile11(path2, `${JSON.stringify(value, null, 2)}
11976
+ await writeFile12(path2, `${JSON.stringify(value, null, 2)}
10996
11977
  `, "utf8");
10997
11978
  }
10998
11979
  function defaultSources() {
@@ -11155,7 +12136,7 @@ var init_sanitize = __esm({
11155
12136
  });
11156
12137
 
11157
12138
  // src/commands/dashboard.ts
11158
- import { cp, mkdir as mkdir7, readFile as readFile17, writeFile as writeFile12 } from "fs/promises";
12139
+ import { cp, mkdir as mkdir7, readFile as readFile17, writeFile as writeFile13 } from "fs/promises";
11159
12140
  import { basename as basename2, join as join25 } from "path";
11160
12141
  import { fileURLToPath as fileURLToPath3 } from "url";
11161
12142
  function dashboardInventory(cwd, inventory) {
@@ -11171,7 +12152,7 @@ function dashboardInventory(cwd, inventory) {
11171
12152
  confidence: t.confidence ?? "low",
11172
12153
  interface: t.kind === "runtime" ? "terminal" : "api"
11173
12154
  })),
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 })) }))
12155
+ 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
12156
  })));
11176
12157
  }
11177
12158
  var init_dashboard = __esm({
@@ -11192,7 +12173,7 @@ __export(session_exports, {
11192
12173
  writeSessionTask: () => writeSessionTask
11193
12174
  });
11194
12175
  import { spawn as spawn4, spawnSync } from "child_process";
11195
- import { writeFile as writeFile13, readFile as readFile18 } from "fs/promises";
12176
+ import { writeFile as writeFile14, readFile as readFile18 } from "fs/promises";
11196
12177
  import { join as join26 } from "path";
11197
12178
  function sessionTask() {
11198
12179
  return `# Prepare this repository for AgentTwin
@@ -11219,7 +12200,7 @@ function installedOpenCode() {
11219
12200
  }
11220
12201
  async function writeSessionTask(cwd) {
11221
12202
  const path2 = join26(cwd, ".agenttwin/AGENT-TASK.md");
11222
- await writeFile13(path2, sessionTask(), "utf8");
12203
+ await writeFile14(path2, sessionTask(), "utf8");
11223
12204
  return path2;
11224
12205
  }
11225
12206
  async function launchSession(cwd) {
@@ -11277,17 +12258,17 @@ __export(run_exports, {
11277
12258
  runWorld: () => runWorld,
11278
12259
  stageApplication: () => stageApplication
11279
12260
  });
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";
12261
+ 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
12262
  import { tmpdir as tmpdir8 } from "os";
11282
12263
  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";
12264
+ import { createHash as createHash14, randomUUID as randomUUID5 } from "crypto";
11284
12265
  async function stageApplication(root, files, destination) {
11285
- const canonicalRoot = await realpath4(root);
12266
+ const canonicalRoot = await realpath5(root);
11286
12267
  const digests = {};
11287
12268
  let bytes = 0;
11288
12269
  for (const file of files) {
11289
12270
  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));
12271
+ const source = await realpath5(resolve7(canonicalRoot, file));
11291
12272
  const rel = relative4(canonicalRoot, source);
11292
12273
  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
12274
  const contents = await readFile19(source);
@@ -11295,15 +12276,15 @@ async function stageApplication(root, files, destination) {
11295
12276
  if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
11296
12277
  const target = join27(destination, file);
11297
12278
  await mkdir8(dirname4(target), { recursive: true });
11298
- await writeFile14(target, contents, { mode: 420 });
11299
- digests[file] = createHash13("sha256").update(contents).digest("hex");
12279
+ await writeFile15(target, contents, { mode: 420 });
12280
+ digests[file] = createHash14("sha256").update(contents).digest("hex");
11300
12281
  }
11301
12282
  return digests;
11302
12283
  }
11303
12284
  async function resolveApplicationDirectory(worldDir, spec, stagedApp) {
11304
12285
  if (!spec.directory) return stagedApp;
11305
12286
  const target = resolve7(worldDir, spec.directory);
11306
- const dir = await realpath4(target).catch(() => {
12287
+ const dir = await realpath5(target).catch(() => {
11307
12288
  throw new CliError(`directory ${spec.directory} does not exist (resolved to ${target})`, { code: EXIT.USAGE });
11308
12289
  });
11309
12290
  if (!(await lstat2(dir)).isDirectory()) throw new CliError(`directory ${spec.directory} is not a folder`, { code: EXIT.USAGE });
@@ -11366,8 +12347,8 @@ async function runWorld(cwd, opts) {
11366
12347
  const stage = await mkdtemp8(join27(tmpdir8(), "agenttwin-world-"));
11367
12348
  try {
11368
12349
  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 });
12350
+ await writeFile15(join27(stage, "world.json"), JSON.stringify(spec), { mode: 420 });
12351
+ if (runtime === "e2b" && suppliedSeed) await writeFile15(join27(stage, "seed.json"), JSON.stringify({ seed: suppliedSeed }), { mode: 420 });
11371
12352
  const git2 = await captureGit(sourceBuild?.root ?? cwd);
11372
12353
  let project;
11373
12354
  try {
@@ -11394,14 +12375,14 @@ async function runWorld(cwd, opts) {
11394
12375
  }
11395
12376
  }
11396
12377
  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" };
12378
+ 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
12379
  const out2 = resolve7(cwd, opts.out ?? `.agenttwin/runs/${runId2}`);
11399
12380
  await mkdir8(out2, { recursive: true });
11400
12381
  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 });
12382
+ await writeFile15(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
12383
+ await writeFile15(join27(out2, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
11403
12384
  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) }) + `
12385
+ await writeFile15(reportPath, renderRunSummary({ ...receipt2, runId: runId2 }, { markdown: true, next, costs: await readCostConfig(cwd) }) + `
11405
12386
  Runner: CLI \xB7 Git: ${git2?.head ?? "unavailable"} \xB7 Seed: ${receipt2.seed}
11406
12387
  ${receipt2.reproducibility ?? ""}
11407
12388
  ${sourceBuildError ?? ""}
@@ -11414,15 +12395,15 @@ Full evidence (activities, fault, initial and final state): run.json
11414
12395
  const receipt2 = await executeRemote(stage, spec, opts.log, { git: git2, project, seed: suppliedSeed });
11415
12396
  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
12397
  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");
12398
+ const expectedSpec = createHash14("sha256").update(JSON.stringify(spec)).digest("hex");
11418
12399
  const reportedSources = receipt2.sourceDigests;
11419
12400
  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
12401
  const out2 = resolve7(cwd, opts.out ?? `.agenttwin/runs/${receipt2.runId}`);
11421
12402
  await mkdir8(out2, { recursive: true });
11422
12403
  const evidencePath = join27(out2, "run.json");
11423
12404
  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}
12405
+ await writeFile15(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
12406
+ await writeFile15(reportPath, `# ${spec.name}: ${receipt2.status}
11426
12407
 
11427
12408
  Run: ${receipt2.runId}
11428
12409
 
@@ -11452,15 +12433,15 @@ See run.json for assertions, service state, application output and isolation met
11452
12433
  image,
11453
12434
  templateBuildId,
11454
12435
  sourceDigests,
11455
- specDigest: createHash13("sha256").update(JSON.stringify(spec)).digest("hex"),
12436
+ specDigest: createHash14("sha256").update(JSON.stringify(spec)).digest("hex"),
11456
12437
  isolation
11457
12438
  };
11458
12439
  const out = resolve7(cwd, opts.out ?? `.agenttwin/runs/${runId}`);
11459
12440
  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 });
12441
+ await writeFile15(join27(out, "run.json"), JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
12442
+ await writeFile15(join27(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
11462
12443
  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);
12444
+ await writeFile15(join27(out, "report.md"), summary);
11464
12445
  return { ...receipt, reportPath: join27(out, "report.md"), evidencePath: join27(out, "run.json") };
11465
12446
  } finally {
11466
12447
  await rm10(stage, { recursive: true, force: true });
@@ -11489,7 +12470,7 @@ var init_run = __esm({
11489
12470
  // src/runtime/docker.ts
11490
12471
  import { execFile as execFile9, spawn as spawn5 } from "child_process";
11491
12472
  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";
12473
+ 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
12474
  import { tmpdir as tmpdir9 } from "os";
11494
12475
  import { join as join28 } from "path";
11495
12476
  import { randomUUID as randomUUID6 } from "crypto";
@@ -11520,7 +12501,7 @@ async function executeDocker(app, spec, opts = {}) {
11520
12501
  await mkdir9(support, { mode: 493 });
11521
12502
  await copyFile2(hook.path, join28(support, "source.cjs"));
11522
12503
  await chmod3(join28(support, "source.cjs"), 420);
11523
- await writeFile15(join28(support, "bridge.cjs"), stdioFetchHook(credentials2, !!database), { mode: 420 });
12504
+ await writeFile16(join28(support, "bridge.cjs"), stdioFetchHook(credentials2, !!database), { mode: 420 });
11524
12505
  const env = Object.entries(credentials2).flatMap(([name, c]) => ["--env", `AGENTTWIN_${name.toUpperCase()}_URL=${c.endpoint}`, "--env", `AGENTTWIN_${name.toUpperCase()}_TOKEN=${c.token}`]);
11525
12506
  let stdout = "", stderr = "", timedOut = false;
11526
12507
  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 +12612,31 @@ var init_docker = __esm({
11631
12612
  }
11632
12613
  });
11633
12614
 
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
12615
  // src/inventory/workflows.ts
11658
12616
  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();
12617
+ const list3 = [];
12618
+ if (kind === "payments") list3.push("payments:read", "payments:write");
12619
+ else if (kind === "comms") list3.push("messages:read", "messages:write");
12620
+ else if (kind === "crm" || kind === "support") list3.push("records:read", "records:write");
12621
+ else list3.push("read", "write");
12622
+ for (const entity of entities) list3.push(`${entity}:read`, `${entity}:write`);
12623
+ return [...new Set(list3)].sort();
11666
12624
  }
11667
12625
  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)];
12626
+ const list3 = [];
12627
+ if (kind === "payments") list3.push("webhook: charge.refunded / payment_intent.succeeded");
12628
+ if (kind === "comms") list3.push("delivery receipt / message.changed");
12629
+ if (kind === "queue") list3.push("message delivery (duplicate / out-of-order)");
12630
+ list3.push(...entities.map((e) => `webhook: ${e}.created / ${e}.updated`));
12631
+ return [...new Set(list3)];
11674
12632
  }
11675
12633
  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)];
12634
+ const list3 = ["timeout after a successful write (response lost)"];
12635
+ if (kind === "payments") list3.push("duplicate refund / double charge");
12636
+ if (kind === "queue") list3.push("duplicate or out-of-order delivery");
12637
+ if (kind === "database") list3.push("partial write / rollback");
12638
+ list3.push("permission revoked mid-flow", "rate limit / 429");
12639
+ return [...new Set(list3)];
11682
12640
  }
11683
12641
  function assertionsFor(candidate) {
11684
12642
  if (candidate.entrypoint) return [
@@ -11869,9 +12827,9 @@ var init_languages = __esm({
11869
12827
  const ext = file.slice(file.lastIndexOf(".") + 1).toLowerCase();
11870
12828
  const lang = EXT_LANG[ext];
11871
12829
  if (!lang) continue;
11872
- const list2 = byLang.get(lang) ?? [];
11873
- if (list2.length < 20) list2.push(file);
11874
- byLang.set(lang, list2);
12830
+ const list3 = byLang.get(lang) ?? [];
12831
+ if (list3.length < 20) list3.push(file);
12832
+ byLang.set(lang, list3);
11875
12833
  }
11876
12834
  const findings = [];
11877
12835
  for (const [lang, refs] of byLang) {
@@ -12251,8 +13209,8 @@ var init_k8s = __esm({
12251
13209
  } catch {
12252
13210
  continue;
12253
13211
  }
12254
- const list2 = Array.isArray(docs) ? docs : [docs];
12255
- for (const doc of list2) {
13212
+ const list3 = Array.isArray(docs) ? docs : [docs];
13213
+ for (const doc of list3) {
12256
13214
  const containers = extractContainers(doc);
12257
13215
  for (const image of containers) {
12258
13216
  const info = classifyImage(image);
@@ -12747,9 +13705,9 @@ var init_ci = __esm({
12747
13705
  const prefixes = provider.signatures.envPrefixes ?? [];
12748
13706
  if (prefixes.length === 0) continue;
12749
13707
  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);
13708
+ const list3 = providerEvidence.get(provider.id) ?? [];
13709
+ list3.push({ ref: path2, pass: "environment", signal: "ci", detail: provider.id });
13710
+ providerEvidence.set(provider.id, list3);
12753
13711
  }
12754
13712
  }
12755
13713
  }
@@ -13396,7 +14354,7 @@ var init_identity = __esm({
13396
14354
  });
13397
14355
 
13398
14356
  // src/inventory/canonical.ts
13399
- import { createHash as createHash17 } from "crypto";
14357
+ import { createHash as createHash18 } from "crypto";
13400
14358
  function sortKeys(value) {
13401
14359
  if (Array.isArray(value)) return value.map(sortKeys);
13402
14360
  if (value && typeof value === "object") {
@@ -13424,7 +14382,7 @@ function canonicalContent(inventory) {
13424
14382
  }
13425
14383
  function canonicalHash(inventory) {
13426
14384
  const content = JSON.stringify(canonicalContent(inventory));
13427
- return `sha256:${createHash17("sha256").update(content).digest("hex").slice(0, 32)}`;
14385
+ return `sha256:${createHash18("sha256").update(content).digest("hex").slice(0, 32)}`;
13428
14386
  }
13429
14387
  function withCanonicalHash(inventory) {
13430
14388
  return { ...inventory, canonicalHash: canonicalHash(inventory) };
@@ -13928,9 +14886,9 @@ function workflowGraph(sources, operations, tools, options = {}) {
13928
14886
  locals.set(mod, declared);
13929
14887
  walk2(ast.program, (node) => {
13930
14888
  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);
14889
+ const list3 = declared.get(node.id.name) ?? [];
14890
+ list3.push({ line: node.loc.start.line, init: node.init });
14891
+ declared.set(node.id.name, list3);
13934
14892
  }
13935
14893
  if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && unwrap(node.init)) toolNames.set(unwrap(node.init), node.id.name);
13936
14894
  if (node.type === "ObjectProperty" && propertyName(node.key) && unwrap(node.value)) toolNames.set(unwrap(node.value), propertyName(node.key));
@@ -14167,9 +15125,9 @@ function workflowGraph(sources, operations, tools, options = {}) {
14167
15125
  };
14168
15126
  const byPath = /* @__PURE__ */ new Map();
14169
15127
  for (const operation of operations) {
14170
- const list2 = byPath.get(operation.path) ?? [];
14171
- list2.push(operation);
14172
- byPath.set(operation.path, list2);
15128
+ const list3 = byPath.get(operation.path) ?? [];
15129
+ list3.push(operation);
15130
+ byPath.set(operation.path, list3);
14173
15131
  }
14174
15132
  const directEffects = /* @__PURE__ */ new Map();
14175
15133
  const effects2 = (unit) => {
@@ -14509,12 +15467,12 @@ function createSdkScanner(project) {
14509
15467
  if (!ast) return ops;
14510
15468
  const consumed = /* @__PURE__ */ new Set();
14511
15469
  const seen = /* @__PURE__ */ new Set();
14512
- const push = (node, providerId, kind, label2, resource) => {
15470
+ const push = (node, providerId, kind, label2, resource, stripeItemFields) => {
14513
15471
  const line = node.loc?.start.line ?? 1;
14514
15472
  const key2 = `${line}|${providerId}|${label2}`;
14515
- if (seen.has(key2)) return;
15473
+ if (stripeItemFields === void 0 && seen.has(key2)) return;
14516
15474
  seen.add(key2);
14517
- ops.push({ line, providerId, kind, label: label2, resource: resource.replace(/[^\w.-]/g, "_") || providerId });
15475
+ ops.push({ line, providerId, kind, label: label2, resource: resource.replace(/[^\w.-]/g, "_") || providerId, stripeItemFields });
14518
15476
  };
14519
15477
  const rootBinding = (root) => {
14520
15478
  const value = unwrap(root);
@@ -14594,7 +15552,14 @@ function createSdkScanner(project) {
14594
15552
  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
15553
  const kind = verbKind(verb, ai);
14596
15554
  if (!kind) return;
14597
- push(node, provider, kind, names.slice(-2).join("."), names.length > 1 ? names[names.length - 2] : provider);
15555
+ const label2 = names.slice(-2).join(".");
15556
+ let stripeItemFields;
15557
+ if (provider === "stripe" && label2 === "subscriptionItems.update") {
15558
+ const params = unwrap(segments.at(-1)?.args[1]);
15559
+ const keys = params?.type === "ObjectExpression" ? params.properties.map((p) => p.type === "ObjectProperty" && !p.computed ? propertyName(p.key) : void 0) : void 0;
15560
+ stripeItemFields = keys?.every((key2) => typeof key2 === "string") ? keys : null;
15561
+ }
15562
+ push(node, provider, kind, label2, names.length > 1 ? names[names.length - 2] : provider, stripeItemFields);
14598
15563
  };
14599
15564
  walk(ast.program, (node) => {
14600
15565
  if (node.type === "TaggedTemplateExpression") {
@@ -14670,7 +15635,7 @@ var init_sdk_calls = __esm({
14670
15635
  });
14671
15636
 
14672
15637
  // src/inventory/relationships.ts
14673
- import { createHash as createHash18 } from "crypto";
15638
+ import { createHash as createHash19 } from "crypto";
14674
15639
  function datastoreFor(pkg, fallback) {
14675
15640
  if (/^(pg|pg-pool|postgres|pg-promise|slonik|@neondatabase\/serverless|@vercel\/postgres)(\/|$)/.test(pkg)) return "postgres";
14676
15641
  if (/^(mysql|mysql2|@planetscale\/database)(\/|$)/.test(pkg)) return "mysql";
@@ -14704,8 +15669,8 @@ function packagesFor(providerId) {
14704
15669
  const provider = PROVIDERS.find((p) => p.id === providerId);
14705
15670
  if (!provider) return [];
14706
15671
  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(/\/$/, ""));
15672
+ for (const list3 of Object.values(provider.signatures.packages ?? {})) {
15673
+ for (const pkg of list3) set.add(pkg.replace(/\/$/, ""));
14709
15674
  }
14710
15675
  return [...set];
14711
15676
  }
@@ -14764,9 +15729,9 @@ function riskFor(kind) {
14764
15729
  function workflowGroupKey(providerId, tool) {
14765
15730
  return `${providerId}|${tool?.accounts.join(",") ?? ""}|${tool?.environment ?? ""}`;
14766
15731
  }
14767
- function stepsFor(apps, list2, toolId) {
15732
+ function stepsFor(apps, list3, toolId) {
14768
15733
  return apps.map((app) => {
14769
- const records = list2.filter((r) => r.app === app);
15734
+ const records = list3.filter((r) => r.app === app);
14770
15735
  return {
14771
15736
  app,
14772
15737
  tool: toolId,
@@ -14797,9 +15762,9 @@ async function buildRelationships(apps, tools, files, decisions) {
14797
15762
  const byApp = /* @__PURE__ */ new Map();
14798
15763
  for (const ref of fileRefs(tool)) {
14799
15764
  const app = appForPath(apps, ref);
14800
- const list2 = byApp.get(app.id) ?? [];
14801
- list2.push({ source: "static", ref });
14802
- byApp.set(app.id, list2);
15765
+ const list3 = byApp.get(app.id) ?? [];
15766
+ list3.push({ source: "static", ref });
15767
+ byApp.set(app.id, list3);
14803
15768
  }
14804
15769
  for (const [appId, evidence] of byApp) {
14805
15770
  const id = `uses:${appId}:${tool.id}`;
@@ -14858,7 +15823,7 @@ async function buildRelationships(apps, tools, files, decisions) {
14858
15823
  const sdkLines = new Set(sdkOperations.map((op2) => `${op2.line}|${op2.providerId}`));
14859
15824
  const astBindings = /\.[cm]?[jt]sx?$/.test(path2) ? scanner.bindings(path2) : /* @__PURE__ */ new Map();
14860
15825
  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 })),
15826
+ ...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
15827
  ...scanOperations(text3, path2),
14863
15828
  ...httpOperations
14864
15829
  ];
@@ -14890,7 +15855,7 @@ async function buildRelationships(apps, tools, files, decisions) {
14890
15855
  evidence: []
14891
15856
  };
14892
15857
  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 });
15858
+ 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
15859
  if (!record4.operations.includes(label2)) record4.operations.push(label2);
14895
15860
  if (!record4.resources.includes(op2.resource)) record4.resources.push(op2.resource);
14896
15861
  if (!record4.evidence.some((e) => e.ref === op2.ref)) record4.evidence.push({ source: "static", ref: op2.ref });
@@ -14928,19 +15893,19 @@ async function buildRelationships(apps, tools, files, decisions) {
14928
15893
  for (const record4 of decidedRecords) {
14929
15894
  if (!providerTools.some((t) => t.providerId === record4.providerId)) continue;
14930
15895
  const key2 = workflowGroupKey(record4.providerId, toolByProvider.get(record4.providerId));
14931
- const list2 = byGroup.get(key2) ?? [];
14932
- list2.push(record4);
14933
- byGroup.set(key2, list2);
15896
+ const list3 = byGroup.get(key2) ?? [];
15897
+ list3.push(record4);
15898
+ byGroup.set(key2, list3);
14934
15899
  }
14935
15900
  const workflows = [];
14936
15901
  const gaps = [];
14937
- for (const list2 of byGroup.values()) {
14938
- const providerId = list2[0].providerId;
15902
+ for (const list3 of byGroup.values()) {
15903
+ const providerId = list3[0].providerId;
14939
15904
  const tool = toolByProvider.get(providerId);
14940
15905
  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");
15906
+ const appsInvolved = [...new Set(list3.map((r) => r.app))].sort();
15907
+ const producers = list3.filter((r) => r.kind === "writes" || r.kind === "emits");
15908
+ const consumers = list3.filter((r) => r.kind === "reads" || r.kind === "emits");
14944
15909
  if (producers.length === 0 || consumers.length === 0) {
14945
15910
  if (appsInvolved.length >= 2) {
14946
15911
  gaps.push(
@@ -14949,8 +15914,8 @@ async function buildRelationships(apps, tools, files, decisions) {
14949
15914
  }
14950
15915
  continue;
14951
15916
  }
14952
- const writeResources = list2.filter((r) => r.kind === "writes").flatMap(entityResources);
14953
- const readResources = list2.filter((r) => r.kind === "reads").flatMap(entityResources);
15917
+ const writeResources = list3.filter((r) => r.kind === "writes").flatMap(entityResources);
15918
+ const readResources = list3.filter((r) => r.kind === "reads").flatMap(entityResources);
14954
15919
  const sharedIntersection = [...new Set(writeResources.filter((r) => readResources.includes(r)))];
14955
15920
  const producerApps = [...new Set(producers.map((r) => r.app))].sort();
14956
15921
  const consumerApps = [...new Set(consumers.map((r) => r.app))].sort();
@@ -14975,10 +15940,10 @@ async function buildRelationships(apps, tools, files, decisions) {
14975
15940
  title: `${app} via ${tool.title}`,
14976
15941
  apps: [app],
14977
15942
  tools: [tool.id],
14978
- steps: stepsFor([app], list2, tool.id),
15943
+ steps: stepsFor([app], list3, tool.id),
14979
15944
  sharedEntities: sharedIntersection.length > 0 ? sharedIntersection : [singularize(providerId)],
14980
- evidence: list2.flatMap((r) => r.evidence),
14981
- confidence: confidenceFrom(list2.flatMap((r) => r.evidence).length),
15945
+ evidence: list3.flatMap((r) => r.evidence),
15946
+ confidence: confidenceFrom(list3.flatMap((r) => r.evidence).length),
14982
15947
  risk: riskFor(tool.kind),
14983
15948
  rank: 0,
14984
15949
  supported: supported2,
@@ -15022,10 +15987,10 @@ async function buildRelationships(apps, tools, files, decisions) {
15022
15987
  title: `${orderedApps.join(" \u2192 ")} via ${tool.title}`,
15023
15988
  apps: orderedApps,
15024
15989
  tools: [tool.id],
15025
- steps: stepsFor(orderedApps, list2, tool.id),
15990
+ steps: stepsFor(orderedApps, list3, tool.id),
15026
15991
  sharedEntities: entities.length > 0 ? entities : [singularize(providerId)],
15027
- evidence: list2.flatMap((r) => r.evidence),
15028
- confidence: confidenceFrom(list2.flatMap((r) => r.evidence).length),
15992
+ evidence: list3.flatMap((r) => r.evidence),
15993
+ confidence: confidenceFrom(list3.flatMap((r) => r.evidence).length),
15029
15994
  risk: riskFor(tool.kind),
15030
15995
  rank: 0,
15031
15996
  supported,
@@ -15058,7 +16023,7 @@ async function buildRelationships(apps, tools, files, decisions) {
15058
16023
  const name = `script:${path2.split("/").pop()}`;
15059
16024
  entries.push({ name, startLine: 1, endLine: Number.MAX_SAFE_INTEGER, path: path2, exported: false, trigger: true, calls, evidence: [{ source: "static", ref: `${path2}:1` }] });
15060
16025
  }
15061
- const entryId = (path2, name) => "entry:" + createHash18("sha256").update(path2 + ":" + name).digest("hex").slice(0, 20);
16026
+ const entryId = (path2, name) => "entry:" + createHash19("sha256").update(path2 + ":" + name).digest("hex").slice(0, 20);
15062
16027
  for (const entry of entries) {
15063
16028
  const { path: path2 } = entry;
15064
16029
  const app = appForPath(apps, path2);
@@ -15074,7 +16039,8 @@ async function buildRelationships(apps, tools, files, decisions) {
15074
16039
  entrypoint: path2 + "#" + entry.name.replace(/\\/g, "%5C"),
15075
16040
  apps: [app.id],
15076
16041
  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 })),
16042
+ // A step's evidence is the lines that make its calls; the workflow's evidence keeps every unit it reaches.
16043
+ 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
16044
  sharedEntities: [...new Set(calls.map((call2) => singularize(call2.resource)))],
15079
16045
  evidence,
15080
16046
  confidence: "medium",
@@ -15091,6 +16057,20 @@ async function buildRelationships(apps, tools, files, decisions) {
15091
16057
  const finalWorkflows = workflows.filter((w) => !rejected.has(w.id)).map(
15092
16058
  (w) => confirmed.has(w.id) ? { ...w, supported: true, hypothesis: false, linkingSignals: [...w.linkingSignals, "confirmed by decision"] } : w
15093
16059
  );
16060
+ const stripeTools = new Set(providerTools.filter((tool) => tool.providerId === "stripe").map((tool) => tool.id));
16061
+ for (const workflow of finalWorkflows) {
16062
+ for (const step of workflow.steps) {
16063
+ if (!stripeTools.has(step.tool) || !step.operations.includes("subscriptionItems.update")) continue;
16064
+ const refs = new Set(step.evidence.map((e) => e.ref));
16065
+ const updates = allowedCalls.filter((call2) => call2.toolId === step.tool && call2.label === "subscriptionItems.update" && refs.has(call2.ref));
16066
+ const fields = updates.flatMap((call2) => call2.stripeItemFields ?? []);
16067
+ 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;
16068
+ }
16069
+ const missing = missingStripeOperations(workflow, stripeTools);
16070
+ if (!missing.length) continue;
16071
+ workflow.supported = false;
16072
+ workflow.linkingSignals.push(`Stripe twin does not cover ${missing.join(", ")}`);
16073
+ }
15094
16074
  const riskWeight = { low: 0, medium: 1, high: 2 };
15095
16075
  finalWorkflows.sort(
15096
16076
  (a, b) => Number(b.supported) - Number(a.supported) || // Routes and jobs are how a workflow is actually triggered; list them before helpers.
@@ -15104,6 +16084,7 @@ var SOURCE_EXTS2, MAX_FILES3, NON_USAGE_DIR2, PROVIDER_KINDS, DATASTORE_IDS, CLA
15104
16084
  var init_relationships = __esm({
15105
16085
  "src/inventory/relationships.ts"() {
15106
16086
  "use strict";
16087
+ init_service_coverage();
15107
16088
  init_provider_factories();
15108
16089
  init_entrypoints();
15109
16090
  init_workflow_graph();
@@ -15194,7 +16175,7 @@ var init_scope = __esm({
15194
16175
 
15195
16176
  // src/observation/runtime.ts
15196
16177
  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";
16178
+ import { mkdtemp as mkdtemp12, open as open2, writeFile as writeFile20, rm as rm14, realpath as realpath8 } from "fs/promises";
15198
16179
  import { tmpdir as tmpdir13 } from "os";
15199
16180
  import { join as join34, basename as basename4 } from "path";
15200
16181
  function validHost(host) {
@@ -15290,7 +16271,7 @@ require('node:module').syncBuiltinESMExports();
15290
16271
  });
15291
16272
 
15292
16273
  // src/inventory/observed.ts
15293
- import { createHash as createHash19 } from "crypto";
16274
+ import { createHash as createHash20 } from "crypto";
15294
16275
  function mergeObservations(workflows, tools, report) {
15295
16276
  if (!report?.services.length) return workflows;
15296
16277
  const toolFor = (host) => {
@@ -15325,7 +16306,7 @@ function mergeObservations(workflows, tools, report) {
15325
16306
  const toolIds = [...new Set(calls.map((c) => c.tool.id))];
15326
16307
  const evidence = [...new Set(events.flatMap((e) => [e.source, ...e.frames ?? []]).filter((r) => !!r))].map((ref) => ({ source: "runtime-attempt", ref }));
15327
16308
  merged.push({
15328
- id: "runtime:" + createHash19("sha256").update(entry).digest("hex").slice(0, 20),
16309
+ id: "runtime:" + createHash20("sha256").update(entry).digest("hex").slice(0, 20),
15329
16310
  title: `runtime:${entry}`,
15330
16311
  entrypoint: `${path2}#runtime:${entry.slice(entry.lastIndexOf(":") + 1)}`,
15331
16312
  apps: ["(root)"],
@@ -16360,12 +17341,12 @@ async function runExport(opts) {
16360
17341
  const plan = await readPlan(opts.cwd);
16361
17342
  const bundle = { schema: "export/v1", inventory, plan: plan ?? null };
16362
17343
  if (opts.out) {
16363
- const { mkdir: mkdir14, writeFile: writeFile22 } = await import("fs/promises");
17344
+ const { mkdir: mkdir14, writeFile: writeFile23 } = await import("fs/promises");
16364
17345
  const { join: join39 } = await import("path");
16365
17346
  await mkdir14(opts.out, { recursive: true });
16366
- await writeFile22(join39(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
17347
+ await writeFile23(join39(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
16367
17348
  `, "utf8");
16368
- if (plan) await writeFile22(join39(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
17349
+ if (plan) await writeFile23(join39(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
16369
17350
  `, "utf8");
16370
17351
  return { schema: "export/v1", out: opts.out, wrote: ["inventory.json", ...plan ? ["plan.json"] : []] };
16371
17352
  }
@@ -16851,7 +17832,7 @@ function verifyWebhookSignature(secret, raw, header3) {
16851
17832
  return given.length === expected.length && timingSafeEqual(given, expected);
16852
17833
  }
16853
17834
  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) : [];
17835
+ 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
17836
  function applyWebhook(state, event, payload, now = /* @__PURE__ */ new Date()) {
16856
17837
  const installationId = Number(payload?.installation?.id);
16857
17838
  if (!Number.isSafeInteger(installationId) || installationId <= 0) return { handled: false, detail: "no installation" };
@@ -16995,20 +17976,20 @@ init_spec();
16995
17976
  init_scenarios();
16996
17977
  init_local();
16997
17978
  init_docker();
16998
- import { createHash as createHash16 } from "crypto";
17979
+ import { createHash as createHash17 } from "crypto";
16999
17980
  import { execFile as execFile10 } from "child_process";
17000
17981
  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";
17982
+ 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
17983
  import { tmpdir as tmpdir11 } from "os";
17003
17984
  import { dirname as dirname6, join as join31, relative as relative6, resolve as resolve10, sep as sep6 } from "path";
17004
17985
 
17005
17986
  // src/runtime/callable.ts
17006
17987
  init_entrypoints();
17007
17988
  import { build } from "esbuild";
17008
- import { readFile as readFile21, realpath as realpath5, writeFile as writeFile16 } from "fs/promises";
17989
+ import { readFile as readFile21, realpath as realpath6, writeFile as writeFile17 } from "fs/promises";
17009
17990
  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");
17991
+ import { createHash as createHash15 } from "crypto";
17992
+ var digest4 = (value) => createHash15("sha256").update(value).digest("hex");
17012
17993
  var object5 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
17013
17994
  function argument(value, depth = 0) {
17014
17995
  if (depth > 8 || !object5(value)) throw new Error("Invalid callable argument binding");
@@ -17043,10 +18024,10 @@ function parseCallable(value) {
17043
18024
  return value;
17044
18025
  }
17045
18026
  async function resolveCallableSource(root, entrypoint) {
17046
- const canonical5 = await realpath5(root);
18027
+ const canonical5 = await realpath6(root);
17047
18028
  const [file, member, ...extra] = entrypoint.split("#");
17048
18029
  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));
18030
+ const source = await realpath6(resolve8(canonical5, file));
17050
18031
  if (source !== resolve8(canonical5, file) || relative5(canonical5, source).startsWith(".." + sep4)) throw new Error("Callable source escapes the project or uses a symlink");
17051
18032
  const text3 = await readFile21(source, "utf8"), entries = exportedEntrypoints(text3).filter((entry) => !entry.name.includes(":"));
17052
18033
  let selected = entries.find((entry) => entry.name === member);
@@ -17089,7 +18070,7 @@ for(const [index,call]of invocation.calls.entries()){
17089
18070
  let bytes = 0;
17090
18071
  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
18072
  plugin.onLoad({ filter: /.*/ }, async (args) => {
17092
- const path2 = await realpath5(args.path), rel = relative5(canonical5, path2);
18073
+ const path2 = await realpath6(args.path), rel = relative5(canonical5, path2);
17093
18074
  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
18075
  const contents = await readFile21(path2);
17095
18076
  bytes += contents.length;
@@ -17102,7 +18083,7 @@ for(const [index,call]of invocation.calls.entries()){
17102
18083
  } }] });
17103
18084
  const code = built.outputFiles[0].contents;
17104
18085
  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 });
18086
+ await writeFile17(join29(out, "application.cjs"), code, { flag: "wx", mode: 384 });
17106
18087
  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
18088
  }
17108
18089
 
@@ -17110,12 +18091,12 @@ for(const [index,call]of invocation.calls.entries()){
17110
18091
  init_source_build();
17111
18092
 
17112
18093
  // 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";
18094
+ import { createHash as createHash16 } from "crypto";
18095
+ 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
18096
  import { dirname as dirname5, join as join30, resolve as resolve9, sep as sep5 } from "path";
17116
18097
  import { tmpdir as tmpdir10 } from "os";
17117
18098
  init_source_build();
17118
- var hash2 = (bytes) => createHash15("sha256").update(bytes).digest("hex");
18099
+ var hash2 = (bytes) => createHash16("sha256").update(bytes).digest("hex");
17119
18100
  function safeBuildPath(file) {
17120
18101
  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
18102
  }
@@ -17131,8 +18112,8 @@ function parseProtectedCallable(value) {
17131
18112
  }
17132
18113
  async function boundedBuildFile(root, file) {
17133
18114
  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);
18115
+ const canonical5 = await realpath7(root), path2 = resolve9(canonical5, file), info = await lstat3(path2);
18116
+ 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
18117
  const bytes = await readFile22(path2);
17137
18118
  if (bytes.length > 20 * 1024 * 1024) throw Error("Protected build file exceeds bounds");
17138
18119
  return bytes;
@@ -17146,13 +18127,13 @@ async function stageTrustedBuildFiles(cwd, out, files) {
17146
18127
  if (hash2(bytes) !== expected) throw Error("Trusted dependency or resolution metadata changed: " + file + "; restore the baseline installation or review a new regression");
17147
18128
  const target = join30(out, file);
17148
18129
  await mkdir10(dirname5(target), { recursive: true });
17149
- await writeFile17(target, bytes, { mode: 420 });
18130
+ await writeFile18(target, bytes, { mode: 420 });
17150
18131
  }
17151
18132
  }
17152
18133
 
17153
18134
  // src/runtime/regressions.ts
17154
18135
  var exec8 = promisify10(execFile10);
17155
- var hash3 = (v) => createHash16("sha256").update(v).digest("hex");
18136
+ var hash3 = (v) => createHash17("sha256").update(v).digest("hex");
17156
18137
  var identifier2 = /^[a-z][a-z0-9_]{0,39}$/;
17157
18138
  function parseRegression(v) {
17158
18139
  const r = v;
@@ -17190,7 +18171,7 @@ async function runProtectedCheck(cwd, opts) {
17190
18171
  if (revision === result2.candidateRevision) result2.sourceDigests[file] = hash3(bytes);
17191
18172
  const dest = join31(directory, file);
17192
18173
  await mkdir11(resolve10(dest, ".."), { recursive: true });
17193
- await writeFile18(dest, bytes, { mode: 420 });
18174
+ await writeFile19(dest, bytes, { mode: 420 });
17194
18175
  };
17195
18176
  let executionSpec = regression.spec;
17196
18177
  if (regression.callable) {
@@ -17382,9 +18363,9 @@ async function runPrCheck(cwd, opts = {}) {
17382
18363
  const diff = await git(cwd, "diff", "--unified=0", "--no-color", `${base}...${head}`).catch(() => git(cwd, "diff", "--unified=0", "--no-color", base, head));
17383
18364
  const lines = changedLines(diff);
17384
18365
  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));
18366
+ const list3 = async (rev) => (await git(cwd, "ls-tree", "-r", "--name-only", rev, "--", ".agenttwin/regressions")).split("\n").filter((f) => f.endsWith(".json"));
18367
+ const baseRegressions = await list3(base);
18368
+ const added = (await list3(head)).filter((f) => !baseRegressions.includes(f));
17388
18369
  const costs = await git(cwd, "show", `${base}:agenttwin.costs.json`).then((t) => JSON.parse(t)).catch(() => void 0);
17389
18370
  const regressions = [];
17390
18371
  for (const file of opts.execute === false ? [] : baseRegressions) {
@@ -17432,17 +18413,20 @@ async function runPrCheck(cwd, opts = {}) {
17432
18413
  file: op2.file,
17433
18414
  line: op2.line,
17434
18415
  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.`
18416
+ title: `AgentTwin: calls ${serviceTitle(op2.service)} with no check`,
18417
+ 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
18418
  });
17438
18419
  const verdict = failed.length ? "fail" : incomplete.length || notRun.length ? "incomplete" : uncovered.length ? "warn" : "pass";
17439
18420
  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";
18421
+ 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" ? (() => {
18422
+ const n = new Set(uncovered.flatMap((w) => w.operations.filter((o) => o.changed).map((o) => `${o.file}:${o.line}`))).size;
18423
+ 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`;
18424
+ })() : regressions.length === 1 ? "The twin check passed" : regressions.length ? `All ${regressions.length} twin checks passed` : "No agent side effects changed";
17441
18425
  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"}.`);
18426
+ 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.`);
18427
+ 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.`);
18428
+ 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.");
18429
+ 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
18430
  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
18431
  }
17448
18432
 
@@ -17475,6 +18459,19 @@ ${r.checks.filter((c) => !c.passed).map((c) => `- ${c.text}`).join("\n")}`,
17475
18459
  `Verify locally: npx agenttwin check --base ${short2(report.base)}`
17476
18460
  ].filter(Boolean).join("\n\n");
17477
18461
  }
18462
+ var list2 = (items) => items.length <= 1 ? items[0] ?? "an external service" : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
18463
+ function uncoveredLines(report) {
18464
+ const byLine = /* @__PURE__ */ new Map();
18465
+ for (const w of report.touched.filter((t) => !t.covered)) for (const o of w.operations.filter((op2) => op2.changed)) {
18466
+ const key2 = `${o.file}:${o.line}`, entry = byLine.get(key2) ?? { file: o.file, line: o.line, services: [], sends: [], workflows: [] };
18467
+ const service = serviceTitle(o.service), send2 = `${service} \xB7 \`${o.operation}\``;
18468
+ if (!entry.services.includes(service)) entry.services.push(service);
18469
+ if (!entry.sends.includes(send2)) entry.sends.push(send2);
18470
+ if (!entry.workflows.includes(w.title)) entry.workflows.push(w.title);
18471
+ byLine.set(key2, entry);
18472
+ }
18473
+ return [...byLine.values()].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
18474
+ }
17478
18475
  function renderMarkdown(report, opts = {}) {
17479
18476
  const out = [];
17480
18477
  if (opts.comment) out.push(COMMENT_MARKER);
@@ -17516,18 +18513,32 @@ function renderMarkdown(report, opts = {}) {
17516
18513
  for (const c of r.checks) out.push(`- ${c.passed ? "\u2705" : "\u274C"} ${c.text}`);
17517
18514
  out.push("", "<details><summary>Fix task for Claude Code, Codex or Cursor</summary>", "", "```text", fixTask(report, r), "```", "", "</details>", "");
17518
18515
  }
17519
- const uncovered = report.touched.filter((w) => !w.covered && w.operations.some((o) => o.changed));
18516
+ const uncovered = uncoveredLines(report);
17520
18517
  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.", "");
18518
+ const services = [...new Set(uncovered.flatMap((u) => u.services))];
18519
+ 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.`, "");
18520
+ out.push("| Line | Sends | Part of |", "|---|---|---|");
18521
+ for (const u of uncovered.slice(0, 15)) {
18522
+ 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}\``;
18523
+ const flows = u.workflows.slice(0, 2).map((w) => `\`${cell(w)}\``).join(", ") + (u.workflows.length > 2 ? ` and ${u.workflows.length - 2} more` : "");
18524
+ out.push(`| ${where} | ${cell(u.sends.join(", "))} | ${flows} |`);
18525
+ }
18526
+ if (uncovered.length > 15) out.push("", `\u2026and ${uncovered.length - 15} more lines in the [full report](${opts.detailsUrl ?? "#"}).`);
18527
+ const first = uncovered[0].workflows[0];
18528
+ out.push(
18529
+ "",
18530
+ "**To cover them:**",
18531
+ `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.`,
18532
+ "2. If it finds a problem, fix it and run it again. The passing run is saved in `.agenttwin/regressions/`.",
18533
+ "3. Commit that file. This check then reruns it on every pull request.",
18534
+ ""
18535
+ );
17525
18536
  }
17526
18537
  const covered = report.touched.filter((w) => w.covered && w.operations.some((o) => o.changed));
17527
18538
  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.", "");
18539
+ 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
18540
  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>`);
18541
+ 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
18542
  return out.join("\n") + "\n";
17532
18543
  }
17533
18544
 
@@ -17556,7 +18567,7 @@ async function startCheckRun(target) {
17556
18567
  }
17557
18568
  async function publishCheckRun(report, target, existing) {
17558
18569
  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 });
18570
+ const summary = renderMarkdown(report, { detailsUrl: target.detailsUrl, repository: target.repository });
17560
18571
  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
18572
  const run3 = await api(target, existing ? "PATCH" : "POST", `/repos/${target.repository}/check-runs${existing ? `/${existing}` : ""}`, {
17562
18573
  ...existing ? {} : { name: CHECK_NAME, head_sha: target.sha },
@@ -17571,7 +18582,7 @@ async function publishCheckRun(report, target, existing) {
17571
18582
  }
17572
18583
  async function upsertComment(report, target) {
17573
18584
  if (!target.pullRequest) return void 0;
17574
- const body2 = renderMarkdown(report, { comment: true, detailsUrl: target.detailsUrl });
18585
+ const body2 = renderMarkdown(report, { comment: true, detailsUrl: target.detailsUrl, repository: target.repository });
17575
18586
  for (let page2 = 1; page2 <= 10; page2++) {
17576
18587
  const comments = await api(target, "GET", `/repos/${target.repository}/issues/${target.pullRequest}/comments?per_page=100&page=${page2}`);
17577
18588
  const mine = comments.find((c) => c.body?.startsWith(COMMENT_MARKER));
@@ -17704,7 +18715,7 @@ function requestBudget(limit2 = 1200) {
17704
18715
  }
17705
18716
 
17706
18717
  // src/runtime/oauth.ts
17707
- import { createHash as createHash20, randomBytes as randomBytes5, timingSafeEqual as timingSafeEqual3 } from "crypto";
18718
+ import { createHash as createHash21, randomBytes as randomBytes5, timingSafeEqual as timingSafeEqual3 } from "crypto";
17708
18719
  var oauthScopes = {
17709
18720
  "read:projects": "List this client\u2019s one authorized project",
17710
18721
  "read:discovery": "Read discovery metadata for the authorized project",
@@ -17716,7 +18727,7 @@ var oauthScopes = {
17716
18727
  "write:preparations": "Select and cancel local preparation requests for the authorized project",
17717
18728
  "work:preparations": "Claim and report preparation metadata; does not approve or execute application code"
17718
18729
  };
17719
- var hash4 = (v) => createHash20("sha256").update(v).digest("hex");
18730
+ var hash4 = (v) => createHash21("sha256").update(v).digest("hex");
17720
18731
  var matches3 = (a, b) => timingSafeEqual3(Buffer.from(hash4(a)), Buffer.from(b));
17721
18732
  function newOAuthClient(accountId, label2, project, scopes) {
17722
18733
  if (!Array.isArray(scopes) || !scopes.length || scopes.length > Object.keys(oauthScopes).length || scopes.some(
@@ -18000,8 +19011,8 @@ It expires in 10 minutes. Do not share this code. If you did not request it, ign
18000
19011
 
18001
19012
  // src/runtime/social-auth.ts
18002
19013
  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();
19014
+ import { randomBytes as randomBytes7, createHash as createHash22, timingSafeEqual as timingSafeEqual5 } from "crypto";
19015
+ var hash5 = (value) => createHash22("sha256").update(value).digest();
18005
19016
  var validUrl = (value) => {
18006
19017
  const url = new URL(value);
18007
19018
  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 +19122,8 @@ function createSocialAuth(options) {
18111
19122
  }
18112
19123
 
18113
19124
  // 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");
19125
+ import { randomBytes as randomBytes8, scrypt, timingSafeEqual as timingSafeEqual6, createHash as createHash23 } from "crypto";
19126
+ var digest5 = (value) => createHash23("sha256").update(value).digest("hex");
18116
19127
  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
19128
  async function passwordHash(password) {
18118
19129
  const salt = randomBytes8(16).toString("hex");
@@ -18142,8 +19153,8 @@ init_dashboard_transfer();
18142
19153
  import { generateRegistrationOptions, verifyRegistrationResponse, generateAuthenticationOptions, verifyAuthenticationResponse } from "@simplewebauthn/server";
18143
19154
  import { isDeepStrictEqual as isDeepStrictEqual9 } from "util";
18144
19155
  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";
19156
+ import { createHash as createHash29, randomBytes as randomBytes11, randomUUID as randomUUID10, timingSafeEqual as timingSafeEqual7 } from "crypto";
19157
+ import { mkdir as mkdir13, readFile as readFile26, writeFile as writeFile22, rename as rename3, mkdtemp as mkdtemp14, rm as rm17 } from "fs/promises";
18147
19158
  import { resolve as resolve12, join as join38, dirname as dirname7, extname as extname2 } from "path";
18148
19159
  import { tmpdir as tmpdir15 } from "os";
18149
19160
 
@@ -18250,8 +19261,8 @@ import { join as join37 } from "path";
18250
19261
 
18251
19262
  // src/runtime/repair-proof.ts
18252
19263
  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";
19264
+ import { createHash as createHash24, randomUUID as randomUUID7 } from "crypto";
19265
+ import { mkdir as mkdir12, readFile as readFile24, rm as rm16, writeFile as writeFile21 } from "fs/promises";
18255
19266
  import { isAbsolute as isAbsolute5, join as join36, relative as relative7, resolve as resolve11, sep as sep7 } from "path";
18256
19267
 
18257
19268
  // src/runtime/receipt-sync.ts
@@ -18260,8 +19271,17 @@ function validProof(p, runId) {
18260
19271
  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
19272
  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
19273
  }
18263
- function portableLocalReceipt(value) {
19274
+ function normalizeReceipt(value) {
18264
19275
  const r = value;
19276
+ if (!r || typeof r !== "object") return value;
19277
+ const digests = r.sourceDigests && typeof r.sourceDigests === "object" && !Array.isArray(r.sourceDigests) ? r.sourceDigests : {};
19278
+ const inside = (file) => !file.startsWith("/") && !/^[A-Za-z]:/.test(file) && !file.split(/[\\/]/).includes("..");
19279
+ 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;
19280
+ 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;
19281
+ return { ...r, events, ...r.evaluation !== void 0 ? { evaluation } : {} };
19282
+ }
19283
+ function portableLocalReceipt(value) {
19284
+ const r = normalizeReceipt(value);
18265
19285
  const uuid3 = (v) => typeof v === "string" && /^[a-f0-9-]{36}$/.test(v);
18266
19286
  if (r?.applicationClock !== void 0 && (!["local", "docker"].includes(r.runtime) || !validApplicationClockEvidence(r.applicationClock))) throw new Error("Invalid application clock evidence");
18267
19287
  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 +19319,7 @@ function portableLocalReceipt(value) {
18299
19319
  init_run();
18300
19320
 
18301
19321
  // src/runtime/analytics.ts
18302
- import { createHash as createHash24 } from "crypto";
19322
+ import { createHash as createHash25 } from "crypto";
18303
19323
  function analyticsConfiguration() {
18304
19324
  const key2 = process.env.POSTHOG_API_KEY;
18305
19325
  const host = process.env.POSTHOG_API_HOST || "https://us.i.posthog.com";
@@ -18336,7 +19356,7 @@ function captureAnalytics(event) {
18336
19356
  // package.json
18337
19357
  var package_default = {
18338
19358
  name: "agenttwin",
18339
- version: "0.3.30",
19359
+ version: "0.3.32",
18340
19360
  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
19361
  mcpName: "io.github.AgentTwin/agenttwin",
18342
19362
  keywords: [
@@ -18390,6 +19410,7 @@ var package_default = {
18390
19410
  bson: "^6.10.4",
18391
19411
  e2b: "^2.52.1",
18392
19412
  esbuild: "0.28.2",
19413
+ fengari: "0.1.5",
18393
19414
  "openid-client": "^6.8.8",
18394
19415
  pg: "^8.23.1",
18395
19416
  playwright: "1.64.1",
@@ -18431,7 +19452,7 @@ var package_default = {
18431
19452
  var VERSION = package_default.version;
18432
19453
 
18433
19454
  // src/runtime/audit-export.ts
18434
- import { createHash as createHash25, createPrivateKey, createPublicKey, sign, verify } from "crypto";
19455
+ import { createHash as createHash26, createPrivateKey, createPublicKey, sign, verify } from "crypto";
18435
19456
  var AUDIT_EXPORT_SCHEMA = "agenttwin/audit-export-v1";
18436
19457
  var GENESIS = "0".repeat(64);
18437
19458
  function canonical4(value) {
@@ -18439,7 +19460,7 @@ function canonical4(value) {
18439
19460
  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
19461
  return JSON.stringify(value);
18441
19462
  }
18442
- var sha4 = (s) => createHash25("sha256").update(s).digest("hex");
19463
+ var sha4 = (s) => createHash26("sha256").update(s).digest("hex");
18443
19464
  function signingKey(pem = process.env.AGENTTWIN_AUDIT_SIGNING_KEY) {
18444
19465
  if (!pem) return void 0;
18445
19466
  const key2 = createPrivateKey(pem.replace(/\\n/g, "\n"));
@@ -18660,14 +19681,14 @@ async function remoteMcp(message, token, base, fetcher) {
18660
19681
  }
18661
19682
 
18662
19683
  // src/runtime/scim.ts
18663
- import { randomBytes as randomBytes10, randomUUID as randomUUID9, createHash as createHash27 } from "crypto";
19684
+ import { randomBytes as randomBytes10, randomUUID as randomUUID9, createHash as createHash28 } from "crypto";
18664
19685
 
18665
19686
  // src/runtime/teams.ts
18666
- import { createHash as createHash26, randomBytes as randomBytes9, randomUUID as randomUUID8 } from "crypto";
19687
+ import { createHash as createHash27, randomBytes as randomBytes9, randomUUID as randomUUID8 } from "crypto";
18667
19688
  var TEAM_ROLES = ["admin", "member", "viewer"];
18668
19689
  var INVITE_DAYS = 7;
18669
19690
  var AUDIT_LIMIT = 5e3;
18670
- var sha5 = (value) => createHash26("sha256").update(value).digest("hex");
19691
+ var sha5 = (value) => createHash27("sha256").update(value).digest("hex");
18671
19692
  var isRole = (value) => typeof value === "string" && TEAM_ROLES.includes(value);
18672
19693
  function resolveWorkspace(state, person, orgToken) {
18673
19694
  if (orgToken) return { workspace: person, role: orgToken.role, actorId: `token:${orgToken.id}`, actorLabel: `API token "${orgToken.label}"`, shared: true };
@@ -18741,7 +19762,7 @@ var SCIM_USER = "urn:ietf:params:scim:schemas:core:2.0:User";
18741
19762
  var LIST = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
18742
19763
  var PATCH = "urn:ietf:params:scim:api:messages:2.0:PatchOp";
18743
19764
  var ERROR = "urn:ietf:params:scim:api:messages:2.0:Error";
18744
- var sha6 = (v) => createHash27("sha256").update(v).digest("hex");
19765
+ var sha6 = (v) => createHash28("sha256").update(v).digest("hex");
18745
19766
  var scimError = (status, detail, scimType) => ({ status, body: { schemas: [ERROR], status: String(status), detail, ...scimType ? { scimType } : {} } });
18746
19767
  function userOf(store, workspaceId, a, base) {
18747
19768
  const m = (store.teamMembers ?? []).find((x) => x.accountId === workspaceId && x.memberId === a.id);
@@ -18847,7 +19868,7 @@ function handleScim(store, workspaceId, method, path2, query, input, base) {
18847
19868
  }
18848
19869
 
18849
19870
  // src/runtime/gateway.ts
18850
- var hash6 = (value) => createHash28("sha256").update(value).digest("hex");
19871
+ var hash6 = (value) => createHash29("sha256").update(value).digest("hex");
18851
19872
  function uploadPath(path2) {
18852
19873
  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
19874
  return path2;
@@ -18939,7 +19960,7 @@ async function startGateway(opts) {
18939
19960
  if (database) await database.write(snapshot);
18940
19961
  else {
18941
19962
  const path2 = join38(directory, `state-${randomUUID10()}.tmp`);
18942
- await writeFile21(path2, snapshot, { mode: 384 });
19963
+ await writeFile22(path2, snapshot, { mode: 384 });
18943
19964
  await rename3(path2, storePath2);
18944
19965
  }
18945
19966
  committedWorkflows = workflowView;
@@ -18984,12 +20005,12 @@ async function startGateway(opts) {
18984
20005
  for (const [file, encoded] of Object.entries(item.files)) {
18985
20006
  const destination = join38(workspace, uploadPath(file));
18986
20007
  await mkdir13(dirname7(destination), { recursive: true });
18987
- await writeFile21(destination, Buffer.from(encoded, "base64"), { mode: 384 });
20008
+ await writeFile22(destination, Buffer.from(encoded, "base64"), { mode: 384 });
18988
20009
  }
18989
- await writeFile21(join38(workspace, "agenttwin.world.json"), JSON.stringify(item.spec));
20010
+ await writeFile22(join38(workspace, "agenttwin.world.json"), JSON.stringify(item.spec));
18990
20011
  if (item.spec.workflowId) {
18991
20012
  await mkdir13(join38(workspace, ".agenttwin"));
18992
- await writeFile21(join38(workspace, ".agenttwin/inventory.json"), JSON.stringify({ workflows: [{ id: item.spec.workflowId }] }));
20013
+ await writeFile22(join38(workspace, ".agenttwin/inventory.json"), JSON.stringify({ workflows: [{ id: item.spec.workflowId }] }));
18993
20014
  }
18994
20015
  const receipt = await runWorld(workspace, { runtime: "e2b", seed: item.seed, signal: controllers.get(item.job.id)?.signal, log: () => {
18995
20016
  } });