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/gateway.js CHANGED
@@ -847,9 +847,9 @@ function newId(resource, rows2, stream) {
847
847
  return `${resource.name}_${stream.nextHex(16)}`;
848
848
  }
849
849
  function routes(twin) {
850
- let list2 = cache.get(twin);
851
- if (list2) return list2;
852
- list2 = twin.operations.map((op2) => {
850
+ let list3 = cache.get(twin);
851
+ if (list3) return list3;
852
+ list3 = twin.operations.map((op2) => {
853
853
  const names = [];
854
854
  let literal = 0;
855
855
  const source = op2.path.split("/").map((seg) => {
@@ -866,8 +866,8 @@ function routes(twin) {
866
866
  }).join("/");
867
867
  return { op: op2, re: new RegExp(`^${source}/?$`), names, score: literal * 10 - names.length };
868
868
  }).sort((a, b) => b.score - a.score);
869
- cache.set(twin, list2);
870
- return list2;
869
+ cache.set(twin, list3);
870
+ return list3;
871
871
  }
872
872
  function matchOperation(twin, method, path2) {
873
873
  const candidates = [path2];
@@ -1174,10 +1174,69 @@ var init_adapters = __esm({
1174
1174
  }
1175
1175
  });
1176
1176
 
1177
+ // src/runtime/compatible-packs.ts
1178
+ function compatibleRequest(vendor, host, url) {
1179
+ if (host.toLowerCase() !== vendor.host) return void 0;
1180
+ if (vendor.prefix === "") return { host: BASE_HOST, url: url.startsWith("/v1/") ? url : "/v1" + url };
1181
+ if (url === vendor.prefix || url.startsWith(vendor.prefix + "/") || url.startsWith(vendor.prefix + "?")) return { host: BASE_HOST, url: "/v1" + url.slice(vendor.prefix.length) };
1182
+ return void 0;
1183
+ }
1184
+ function compatibleModel(pack, body2) {
1185
+ const same2 = { body: body2, restore: (b) => b };
1186
+ if (!compatibleVendor(pack) || !body2?.length) return same2;
1187
+ let parsed;
1188
+ try {
1189
+ parsed = JSON.parse(body2.toString("utf8"));
1190
+ } catch {
1191
+ return same2;
1192
+ }
1193
+ const model = parsed?.model;
1194
+ if (typeof model !== "string" || !model || model === STAND_IN_MODEL) return same2;
1195
+ const swapped = Buffer.from(JSON.stringify({ ...parsed, model: STAND_IN_MODEL }));
1196
+ const from = JSON.stringify(STAND_IN_MODEL), to = JSON.stringify(model);
1197
+ 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}]`)) };
1198
+ }
1199
+ var OPENAI_COMPATIBLE, BASE_PACK, BASE_HOST, compatibleVendor, STAND_IN_MODEL;
1200
+ var init_compatible_packs = __esm({
1201
+ "src/runtime/compatible-packs.ts"() {
1202
+ "use strict";
1203
+ OPENAI_COMPATIBLE = [
1204
+ // https://console.groq.com/docs/openai
1205
+ { name: "groq", title: "Groq", host: "api.groq.com", prefix: "/openai/v1", sdks: ["groq-sdk", "@ai-sdk/groq"], pypi: ["groq"], env: ["GROQ_API_KEY"] },
1206
+ // https://inference-docs.cerebras.ai/resources/openai
1207
+ { 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"] },
1208
+ // https://docs.perplexity.ai/guides/chat-completions-guide (POST https://api.perplexity.ai/chat/completions)
1209
+ { 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"] },
1210
+ // https://docs.sambanova.ai/cloud/docs/capabilities/openai-compatibility
1211
+ { name: "sambanova", title: "SambaNova", host: "api.sambanova.ai", prefix: "/v1", sdks: ["sambanova", "@ai-sdk/sambanova"], pypi: ["sambanova"], env: ["SAMBANOVA_API_KEY"] }
1212
+ ];
1213
+ BASE_PACK = "openai";
1214
+ BASE_HOST = "api.openai.com";
1215
+ compatibleVendor = (name) => OPENAI_COMPATIBLE.find((v) => v.name === name);
1216
+ STAND_IN_MODEL = "gpt-4o-mini";
1217
+ }
1218
+ });
1219
+
1177
1220
  // src/runtime/packs.ts
1178
- import { existsSync, readFileSync } from "fs";
1221
+ import { existsSync, readdirSync, readFileSync } from "fs";
1179
1222
  import { dirname, join as join3, resolve } from "path";
1180
1223
  import { fileURLToPath, pathToFileURL } from "url";
1224
+ function packWebSocketServer(generation) {
1225
+ let found = webSockets.get(generation);
1226
+ if (!found) {
1227
+ found = (async () => {
1228
+ const dir = join3(packsDir(), "engine", generation, "chunks");
1229
+ for (const file of readdirSync(dir).filter((f) => f.endsWith(".mjs"))) {
1230
+ if (!readFileSync(join3(dir, file), "utf8").includes("as WebSocketServer")) continue;
1231
+ const mod = await import(pathToFileURL(join3(dir, file)).href);
1232
+ if (mod.WebSocketServer) return mod.WebSocketServer;
1233
+ }
1234
+ throw new Error(`The ${generation} twin engine ships no WebSocket server`);
1235
+ })();
1236
+ webSockets.set(generation, found);
1237
+ }
1238
+ return found;
1239
+ }
1181
1240
  function packsDir() {
1182
1241
  const here = dirname(fileURLToPath(import.meta.url));
1183
1242
  const candidates = [process.env.AGENTTWIN_TWINS_DIR, join3(here, "twins"), join3(here, "../twins"), resolve(here, "../../../twins/dist")];
@@ -1187,6 +1246,22 @@ function packCatalog() {
1187
1246
  if (cached !== void 0) return cached;
1188
1247
  const dir = packsDir();
1189
1248
  cached = dir ? JSON.parse(readFileSync(join3(dir, "catalog.json"), "utf8")) : null;
1249
+ const base = cached?.packs[BASE_PACK];
1250
+ if (cached && base) for (const v of OPENAI_COMPATIBLE) {
1251
+ if (Object.hasOwn(cached.packs, v.name)) continue;
1252
+ const field = base.credentialDoor?.fill.OPENAI_API_KEY ?? "api_key";
1253
+ cached.packs[v.name] = {
1254
+ ...base,
1255
+ name: v.name,
1256
+ vendor: v.name,
1257
+ servedBy: BASE_PACK,
1258
+ description: `${v.title} (OpenAI-compatible API), served by the OpenAI twin`,
1259
+ hosts: [{ host: v.host }],
1260
+ adoption: { sdks: v.sdks, envStems: v.env.map((e) => e.replace(/_API_KEY$/, "")), pypi: v.pypi },
1261
+ credentialDoor: base.credentialDoor ? { ...base.credentialDoor, fill: Object.fromEntries(v.env.map((e) => [e, field])) } : null
1262
+ };
1263
+ delete cached.excluded?.[v.name];
1264
+ }
1190
1265
  return cached;
1191
1266
  }
1192
1267
  function loadPack(name) {
@@ -1194,7 +1269,7 @@ function loadPack(name) {
1194
1269
  if (!record4) throw new Error(`No twin pack named ${name}`);
1195
1270
  let factory = loaded.get(name);
1196
1271
  if (!factory) {
1197
- const file = join3(packsDir(), "packs", name, "index.mjs");
1272
+ const file = join3(packsDir(), "packs", record4.servedBy ?? name, "index.mjs");
1198
1273
  factory = import(pathToFileURL(file).href).then((mod) => {
1199
1274
  if (typeof mod.createTwinFetch !== "function") throw new Error(`Twin pack ${name} exports no createTwinFetch`);
1200
1275
  return mod.createTwinFetch;
@@ -1203,10 +1278,12 @@ function loadPack(name) {
1203
1278
  }
1204
1279
  return factory;
1205
1280
  }
1206
- var cached, PACK_PREFIX, isPackAdapter, packRecord, loaded;
1281
+ var webSockets, cached, PACK_PREFIX, isPackAdapter, packRecord, loaded;
1207
1282
  var init_packs = __esm({
1208
1283
  "src/runtime/packs.ts"() {
1209
1284
  "use strict";
1285
+ init_compatible_packs();
1286
+ webSockets = /* @__PURE__ */ new Map();
1210
1287
  PACK_PREFIX = "pack:";
1211
1288
  isPackAdapter = (adapter) => typeof adapter === "string" && adapter.startsWith(PACK_PREFIX) && !!packRecord(adapter.slice(PACK_PREFIX.length));
1212
1289
  packRecord = (name) => {
@@ -1799,9 +1876,9 @@ var init_enterprise_twins = __esm({
1799
1876
  return write("/driveItems", record4, record4, 201);
1800
1877
  }
1801
1878
  if (!listKey) return method === "GET" ? read("/lists", { value: lists.filter((l) => l.siteId === siteId) }) : void 0;
1802
- const list2 = lists.find((l) => l.siteId === siteId && (l.id === listKey || l.displayName === decodeURIComponent(listKey)));
1803
- if (!list2) return { ...graphError(404, "itemNotFound", "The requested list was not found.", sequence), collection: "/listItems" };
1804
- const own = items.filter((i) => i.listId === list2.id);
1879
+ const list3 = lists.find((l) => l.siteId === siteId && (l.id === listKey || l.displayName === decodeURIComponent(listKey)));
1880
+ if (!list3) return { ...graphError(404, "itemNotFound", "The requested list was not found.", sequence), collection: "/listItems" };
1881
+ const own = items.filter((i) => i.listId === list3.id);
1805
1882
  const view = (i, withFields = query.expand === "fields" || query.$expand === "fields") => {
1806
1883
  const { listId: _l, siteId: _s, fields, ...rest } = i;
1807
1884
  return withFields ? { ...rest, fields } : rest;
@@ -1813,7 +1890,7 @@ var init_enterprise_twins = __esm({
1813
1890
  if (!itemId && method === "POST") {
1814
1891
  if (!isObject(body2.fields) || !flat2(body2.fields)) return { ...graphError(400, "invalidRequest", "Invalid request: fields are required.", sequence), collection: "/listItems" };
1815
1892
  const id = String(nextNumber(own, "id", 1));
1816
- 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 } };
1893
+ 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 } };
1817
1894
  items.push(record4);
1818
1895
  return write("/listItems", record4, view(record4, true), 201);
1819
1896
  }
@@ -2221,7 +2298,7 @@ function parseWorld(value) {
2221
2298
  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");
2222
2299
  const paths = /* @__PURE__ */ new Set();
2223
2300
  for (const entry of item.collections) {
2224
- 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");
2301
+ 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");
2225
2302
  const collection = entry;
2226
2303
  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");
2227
2304
  paths.add(collection.path);
@@ -2230,6 +2307,7 @@ function parseWorld(value) {
2230
2307
  const optional = ADAPTER_OPTIONAL_COLLECTIONS[item.adapter] ?? [];
2231
2308
  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(", ")})` : ""}`);
2232
2309
  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");
2310
+ 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");
2233
2311
  services.set(item.name, /* @__PURE__ */ new Set([...paths, ...optional]));
2234
2312
  }
2235
2313
  const known2 = (entry) => typeof entry.service === "string" && typeof entry.path === "string" && services.get(entry.service)?.has(entry.path);
@@ -2427,7 +2505,8 @@ var init_spec = __esm({
2427
2505
  init_enterprise_twins();
2428
2506
  RUNTIMES = /^(?:\/[\w./-]+\/)?(?:node|python[0-9.]*|uv|poetry|pipenv|go|ruby|bundle|deno|bun|curl)$/;
2429
2507
  ADAPTER_OPTIONAL_COLLECTIONS = {
2430
- stripe: ["/v1/charges", "/v1/refunds", "/v1/events"],
2508
+ slack: ["/users"],
2509
+ stripe: ["/v1/charges", "/v1/refunds", "/v1/events", "/v1/subscription_items", "/v1/products", "/v1/prices"],
2431
2510
  gmail: ["/gmail/v1/users/me/drafts", "/gmail/v1/users/me/settings/sendAs", "/gmail/v1/users/me/watch", "/pubsub/subscriptions", "/pubsub/messages"],
2432
2511
  ...ENTERPRISE_OPTIONAL_COLLECTIONS
2433
2512
  };
@@ -2531,6 +2610,32 @@ var init_scenarios = __esm({
2531
2610
  }
2532
2611
  });
2533
2612
 
2613
+ // src/runtime/node-options.ts
2614
+ import { realpath, writeFile as writeFile3 } from "fs/promises";
2615
+ async function singlePreload(options, hook) {
2616
+ const preloads = [], rest = [];
2617
+ const tokens = options.match(/(?:[^\s"]+|"[^"]*")+/g) ?? [];
2618
+ for (let i = 0; i < tokens.length; i++) {
2619
+ const t = tokens[i], unquote = (v) => v.replace(/^"|"$/g, "");
2620
+ if (t === "--require" || t === "-r") {
2621
+ if (tokens[i + 1]) preloads.push(unquote(tokens[++i]));
2622
+ } else if (t.startsWith("--require=")) preloads.push(unquote(t.slice(10)));
2623
+ else rest.push(t);
2624
+ }
2625
+ const real = await realpath(hook).catch(() => hook);
2626
+ preloads.push(real);
2627
+ const combined = `${real}.all.cjs`;
2628
+ await writeFile3(combined, preloads.map((p) => `require(${JSON.stringify(p)});`).join("\n") + "\n", { mode: 384 });
2629
+ return [...rest, `--require ${requireArg(combined)}`].join(" ");
2630
+ }
2631
+ var requireArg;
2632
+ var init_node_options = __esm({
2633
+ "src/runtime/node-options.ts"() {
2634
+ "use strict";
2635
+ requireArg = (path2) => /[\s"']/.test(path2) ? JSON.stringify(path2) : path2;
2636
+ }
2637
+ });
2638
+
2534
2639
  // src/runtime/application-process.ts
2535
2640
  import { execFile } from "child_process";
2536
2641
  import { promisify } from "util";
@@ -2734,7 +2839,7 @@ var init_browser_process_windows = __esm({
2734
2839
  });
2735
2840
 
2736
2841
  // src/runtime/browser-process.ts
2737
- import { mkdtemp, writeFile as writeFile3, readFile as readFile4, rm } from "fs/promises";
2842
+ import { mkdtemp, writeFile as writeFile4, readFile as readFile4, rm } from "fs/promises";
2738
2843
  import { tmpdir } from "os";
2739
2844
  import { join as join5 } from "path";
2740
2845
  import { execFile as execFile3 } from "child_process";
@@ -2744,7 +2849,7 @@ async function ownBrowserProcess(executable) {
2744
2849
  });
2745
2850
  const root = await mkdtemp(join5(tmpdir(), "agenttwin-browser-owner-"));
2746
2851
  const pidFile = join5(root, "pid"), launcher = join5(root, "launch");
2747
- await writeFile3(launcher, `#!/bin/sh
2852
+ await writeFile4(launcher, `#!/bin/sh
2748
2853
  echo $$ > ${quote(pidFile)}
2749
2854
  exec ${quote(executable)} "$@"
2750
2855
  `, { mode: 448 });
@@ -3051,7 +3156,7 @@ var init_browser_execution = __esm({
3051
3156
  });
3052
3157
 
3053
3158
  // src/runtime/request-source.ts
3054
- import { mkdtemp as mkdtemp3, writeFile as writeFile4, rm as rm3, realpath, open } from "fs/promises";
3159
+ import { mkdtemp as mkdtemp3, writeFile as writeFile5, rm as rm3, realpath as realpath2, open } from "fs/promises";
3055
3160
  import { tmpdir as tmpdir3 } from "os";
3056
3161
  import { join as join7, resolve as resolve2 } from "path";
3057
3162
  function parseRequestSource(raw, spec) {
@@ -3080,7 +3185,7 @@ async function createRequestSourceHook(app, spec, credentials2, runtime) {
3080
3185
  const dir = await mkdtemp3(join7(tmpdir3(), "agenttwin-source-hook-"));
3081
3186
  const path2 = join7(dir, "hook.cjs");
3082
3187
  const violationsPath = join7(dir, "blocked.jsonl");
3083
- 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 };
3188
+ 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 };
3084
3189
  const guard = "const hookKey=Symbol.for('agenttwin.requestHook.v1');if(globalThis[hookKey])return;Object.defineProperty(globalThis,hookKey,{value:true});\n";
3085
3190
  const hook = guard + applicationClockHook(spec.applicationClock) + `const config=${JSON.stringify(config)};
3086
3191
  ` + String.raw`
@@ -3094,7 +3199,7 @@ function writeViolation(violation){const line=JSON.stringify(violation)+'\n';if(
3094
3199
  // Child processes: Node descendants inherit this hook through NODE_OPTIONS, even when the app passes its own env.
3095
3200
  // Any other executable runs outside the hook, so it is recorded and the run cannot be complete.
3096
3201
  const childProcess=require('node:child_process');
3097
- const hookOption='--require '+JSON.stringify(__filename);
3202
+ const hookOption='--require '+(/[\s"']/.test(__filename)?JSON.stringify(__filename):__filename);
3098
3203
  // Trust is decided from the file that would run, never its name: the Node binary itself, a script whose shebang runs
3099
3204
  // that binary (node_modules/.bin CLIs, npm, npx), or esbuild's own binary inside its package. Results are cached per real path and PATH.
3100
3205
  const executableTrust=new Map();
@@ -3108,15 +3213,23 @@ function runsHookedNode(interpreter,options){const file=resolveCommand(interpret
3108
3213
  // '#!/path/to/node', '#!/usr/bin/env node' and '#!/usr/bin/env -S node --flags' run Node; anything else does not.
3109
3214
  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);}
3110
3215
  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;}}
3111
- 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;}
3216
+ // Operating-system tools that only print facts about this machine and cannot open a connection. SDKs and frameworks
3217
+ // run them for a user-agent string (Stripe: uname; Next.js: sw_vers). Matched by their fixed system path, so a file of
3218
+ // the same name inside a project or earlier on PATH is still reported.
3219
+ const SYSTEM_INFO_BINARIES=new Set(['/usr/bin/uname','/bin/uname','/usr/bin/sw_vers','/usr/bin/arch','/usr/bin/nproc','/usr/bin/getconf']);
3220
+ function systemInfoBinary(real){return process.platform!=='win32'&&SYSTEM_INFO_BINARIES.has(real);}
3221
+ 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;}
3112
3222
  const reportedSubprocesses=new Set();
3113
3223
  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};}
3114
3224
  // Never throws: an unclassifiable command is reported, and the application's spawn proceeds unchanged.
3115
3225
  // Shell commands are judged by their first word, so 'sh -c' style wrappers are reported as non-Node.
3116
- 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{}}
3226
+ // git asked about the local checkout only (the commit a build stamps, the branch): no network, nothing written.
3227
+ const LOCAL_GIT=/^(rev-parse|describe|log|show|status|branch|symbolic-ref|ls-files|rev-list|config)$/;
3228
+ 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))));}
3229
+ 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{}}
3117
3230
  // Puts the hooked env into the options argument at index i, inserting an options object when there is none.
3118
3231
  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;}
3119
- 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);};}
3232
+ 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);};}
3120
3233
  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);};}
3121
3234
  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])});}}
3122
3235
  const blockedOrigins=new Set();
@@ -3164,7 +3277,7 @@ for(const mod of [http,https])for(const method of ['request','get']){const origi
3164
3277
  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);};}
3165
3278
  require('node:module').syncBuiltinESMExports();
3166
3279
  `;
3167
- await writeFile4(path2, hook, { mode: 384 });
3280
+ await writeFile5(path2, hook, { mode: 384 });
3168
3281
  return { path: path2, violationsPath, readViolations: async () => {
3169
3282
  try {
3170
3283
  const seen = /* @__PURE__ */ new Set();
@@ -3263,7 +3376,24 @@ function readOnlyOperation(method, resource, id, params, data) {
3263
3376
  const ordered = [...rows2].reverse().filter((r) => params.type === void 0 || r.type === params.type);
3264
3377
  return { status: 200, body: { object: "list", data: ordered.slice(0, limit2), has_more: ordered.length > limit2, url: collection }, collection, operation: "read" };
3265
3378
  }
3379
+ function subscriptionItemOperation(method, id, params, data) {
3380
+ const collection = "/v1/subscription_items";
3381
+ if (method !== "GET" && method !== "POST") return void 0;
3382
+ if (Object.keys(params).some((key2) => method !== "POST" || key2 !== "quantity")) return void 0;
3383
+ const item = data[collection]?.find((row) => row.id === id && row.deleted !== true);
3384
+ if (!item) return { ...stripeError(404, "resource_missing", `No such subscription_item: '${id}'`), collection };
3385
+ if (method === "GET") return { status: 200, body: item, collection, operation: "read" };
3386
+ const value = params.quantity;
3387
+ const quantity = typeof value === "string" && /^\d+$/.test(value) ? Number(value) : value;
3388
+ if (typeof quantity !== "number" || !Number.isSafeInteger(quantity) || quantity < 0) {
3389
+ return { ...stripeError(400, "parameter_invalid_integer", "quantity must be a non-negative integer", "quantity"), collection };
3390
+ }
3391
+ item.quantity = quantity;
3392
+ return { status: 200, body: item, collection, record: structuredClone(item), operation: "write" };
3393
+ }
3266
3394
  function stripeOperation(method, path2, params, data, sequence) {
3395
+ const item = /^\/v1\/subscription_items\/([^/]+)$/.exec(path2);
3396
+ if (item) return subscriptionItemOperation(method, item[1], params, data);
3267
3397
  const error = stripeError;
3268
3398
  const other = /^\/v1\/(refunds|charges|events)(?:\/([^/]+))?$/.exec(path2);
3269
3399
  if (other) return other[1] === "refunds" ? refundOperation(method, other[2], params, data, sequence) : readOnlyOperation(method, other[1], other[2], params, data);
@@ -3757,6 +3887,182 @@ var init_resp = __esm({
3757
3887
  }
3758
3888
  });
3759
3889
 
3890
+ // src/runtime/engines/redis-lua.ts
3891
+ import { createRequire } from "module";
3892
+ import { createHash as createHash9 } from "crypto";
3893
+ var vm, load2, toLua, fromLua, RedisScripts, WRITE_HINT;
3894
+ var init_redis_lua = __esm({
3895
+ "src/runtime/engines/redis-lua.ts"() {
3896
+ "use strict";
3897
+ init_resp();
3898
+ load2 = () => vm ??= createRequire(import.meta.url)("fengari");
3899
+ toLua = (s) => Uint8Array.from(Buffer.from(s, "latin1"));
3900
+ fromLua = (b) => Buffer.from(b).toString("latin1");
3901
+ RedisScripts = class {
3902
+ /** `run` executes one command on the engine and returns its RESP reply. */
3903
+ constructor(run3) {
3904
+ this.run = run3;
3905
+ }
3906
+ run;
3907
+ cache = /* @__PURE__ */ new Map();
3908
+ command(name, args) {
3909
+ if (name === "script") {
3910
+ const sub = (args[0] ?? "").toLowerCase();
3911
+ if (sub === "load") {
3912
+ const sha7 = this.store(args[1] ?? "");
3913
+ return encode.bulk(sha7);
3914
+ }
3915
+ if (sub === "exists") return encode.array(args.slice(1).map((sha7) => encode.int(this.cache.has(sha7.toLowerCase()) ? 1 : 0)));
3916
+ if (sub === "flush") {
3917
+ this.cache.clear();
3918
+ return encode.simple("OK");
3919
+ }
3920
+ return encode.error(`ERR unknown subcommand '${args[0]}'`);
3921
+ }
3922
+ const evalsha = name === "evalsha" || name === "evalsha_ro";
3923
+ const source = evalsha ? this.cache.get((args[0] ?? "").toLowerCase()) : args[0];
3924
+ if (source === void 0) return encode.error("NOSCRIPT No matching script. Please use EVAL.");
3925
+ const count = Number(args[1]);
3926
+ 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");
3927
+ if (!evalsha) this.store(source);
3928
+ return this.execute(source, args.slice(2, 2 + count), args.slice(2 + count), name.endsWith("_ro"));
3929
+ }
3930
+ store(source) {
3931
+ const sha7 = createHash9("sha1").update(Buffer.from(source, "latin1")).digest("hex");
3932
+ this.cache.set(sha7, source);
3933
+ return sha7;
3934
+ }
3935
+ execute(source, keys, argv, readOnly) {
3936
+ const { lua, lauxlib, lualib } = load2(), L = lauxlib.luaL_newstate();
3937
+ try {
3938
+ for (const [name, open3] of [["_G", lualib.luaopen_base], ["string", lualib.luaopen_string], ["table", lualib.luaopen_table], ["math", lualib.luaopen_math]]) {
3939
+ lauxlib.luaL_requiref(L, toLua(name), open3, 1);
3940
+ lua.lua_pop(L, 1);
3941
+ }
3942
+ for (const name of ["dofile", "loadfile", "load", "require", "print"]) lua.lua_pushnil(L), lua.lua_setglobal(L, toLua(name));
3943
+ const table2 = (items, global) => {
3944
+ lua.lua_createtable(L, items.length, 0);
3945
+ items.forEach((v, i) => {
3946
+ lua.lua_pushstring(L, toLua(v));
3947
+ lua.lua_rawseti(L, -2, i + 1);
3948
+ });
3949
+ lua.lua_setglobal(L, toLua(global));
3950
+ };
3951
+ table2(keys, "KEYS");
3952
+ table2(argv, "ARGV");
3953
+ lua.lua_createtable(L, 0, 4);
3954
+ const call2 = (raise) => (state) => {
3955
+ const n = lua.lua_gettop(state), args = [];
3956
+ for (let i = 1; i <= n; i++) {
3957
+ const t = lua.lua_type(state, i);
3958
+ if (t === lua.LUA_TNUMBER) {
3959
+ const v = lua.lua_tonumber(state, i);
3960
+ args.push(Number.isInteger(v) ? String(v) : String(v));
3961
+ } else if (t === lua.LUA_TSTRING) args.push(fromLua(lua.lua_tolstring(state, i)));
3962
+ else return lauxlib.luaL_error(state, toLua("Lua redis lib command arguments must be strings or integers"));
3963
+ }
3964
+ if (!args.length) return lauxlib.luaL_error(state, toLua("Please specify at least one argument for this redis lib call"));
3965
+ const command = args[0].toLowerCase();
3966
+ 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"));
3967
+ if (readOnly && WRITE_HINT.test(command)) return lauxlib.luaL_error(state, toLua("Write commands are not allowed from read-only scripts"));
3968
+ const reply = parseResp(this.run(args))?.value ?? null;
3969
+ if (raise && reply && typeof reply === "object" && !Array.isArray(reply) && !Buffer.isBuffer(reply) && "error" in reply) return lauxlib.luaL_error(state, toLua(reply.error));
3970
+ push(state, reply);
3971
+ return 1;
3972
+ };
3973
+ const push = (state, v) => {
3974
+ if (v === null || v === false) lua.lua_pushboolean(state, 0);
3975
+ else if (v === true) lua.lua_pushinteger(state, 1);
3976
+ else if (typeof v === "number") lua.lua_pushinteger(state, v);
3977
+ else if (Buffer.isBuffer(v)) lua.lua_pushstring(state, Uint8Array.from(v));
3978
+ else if (Array.isArray(v)) {
3979
+ lua.lua_createtable(state, v.length, 0);
3980
+ v.forEach((x, i) => {
3981
+ push(state, x);
3982
+ lua.lua_rawseti(state, -2, i + 1);
3983
+ });
3984
+ } else {
3985
+ lua.lua_createtable(state, 0, 1);
3986
+ lua.lua_pushstring(state, toLua("simple" in v ? v.simple : v.error));
3987
+ lua.lua_setfield(state, -2, toLua("simple" in v ? "ok" : "err"));
3988
+ }
3989
+ };
3990
+ for (const [name, fn] of [["call", call2(true)], ["pcall", call2(false)]]) {
3991
+ lua.lua_pushcfunction(L, fn);
3992
+ lua.lua_setfield(L, -2, toLua(name));
3993
+ }
3994
+ lua.lua_pushcfunction(L, (state) => {
3995
+ lua.lua_createtable(state, 0, 1);
3996
+ lua.lua_pushvalue(state, 1);
3997
+ lua.lua_setfield(state, -2, toLua("err"));
3998
+ return 1;
3999
+ });
4000
+ lua.lua_setfield(L, -2, toLua("error_reply"));
4001
+ lua.lua_pushcfunction(L, (state) => {
4002
+ lua.lua_createtable(state, 0, 1);
4003
+ lua.lua_pushvalue(state, 1);
4004
+ lua.lua_setfield(state, -2, toLua("ok"));
4005
+ return 1;
4006
+ });
4007
+ lua.lua_setfield(L, -2, toLua("status_reply"));
4008
+ lua.lua_pushcfunction(L, () => 0);
4009
+ lua.lua_setfield(L, -2, toLua("log"));
4010
+ lua.lua_pushcfunction(L, () => 0);
4011
+ lua.lua_setfield(L, -2, toLua("replicate_commands"));
4012
+ lua.lua_setglobal(L, toLua("redis"));
4013
+ 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)}`);
4014
+ if (lua.lua_pcall(L, 0, 1, 0) !== lua.LUA_OK) return encode.error(`ERR Error running script: ${this.message(L)}`);
4015
+ return this.reply(L, -1);
4016
+ } finally {
4017
+ lua.lua_close(L);
4018
+ }
4019
+ }
4020
+ message(L) {
4021
+ const { lua } = load2();
4022
+ const m = lua.lua_tolstring(L, -1);
4023
+ return m ? fromLua(m) : "error";
4024
+ }
4025
+ /** The Lua value at `index` as a RESP reply, by Redis's conversion rules. */
4026
+ reply(L, index) {
4027
+ const { lua } = load2(), at = lua.lua_absindex(L, index);
4028
+ switch (lua.lua_type(L, at)) {
4029
+ case lua.LUA_TNUMBER:
4030
+ return encode.int(Math.trunc(lua.lua_tonumber(L, at)));
4031
+ case lua.LUA_TSTRING:
4032
+ return encode.bulk(Buffer.from(lua.lua_tolstring(L, at)));
4033
+ case lua.LUA_TBOOLEAN:
4034
+ return lua.lua_toboolean(L, at) ? encode.int(1) : encode.bulk(null);
4035
+ case lua.LUA_TTABLE: {
4036
+ for (const field of ["err", "ok"]) {
4037
+ lua.lua_getfield(L, at, toLua(field));
4038
+ if (lua.lua_type(L, -1) === lua.LUA_TSTRING) {
4039
+ const text3 = fromLua(lua.lua_tolstring(L, -1));
4040
+ lua.lua_pop(L, 1);
4041
+ return field === "err" ? encode.error(text3) : encode.simple(text3);
4042
+ }
4043
+ lua.lua_pop(L, 1);
4044
+ }
4045
+ const items = [];
4046
+ for (let i = 1; ; i++) {
4047
+ lua.lua_rawgeti(L, at, i);
4048
+ if (lua.lua_isnil(L, -1)) {
4049
+ lua.lua_pop(L, 1);
4050
+ break;
4051
+ }
4052
+ items.push(this.reply(L, -1));
4053
+ lua.lua_pop(L, 1);
4054
+ }
4055
+ return encode.array(items);
4056
+ }
4057
+ default:
4058
+ return encode.bulk(null);
4059
+ }
4060
+ }
4061
+ };
4062
+ 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)$/;
4063
+ }
4064
+ });
4065
+
3760
4066
  // src/runtime/engines/host.ts
3761
4067
  import { execFile as execFile4 } from "child_process";
3762
4068
  import { access, constants } from "fs/promises";
@@ -4147,6 +4453,7 @@ var init_redis = __esm({
4147
4453
  "src/runtime/engines/redis.ts"() {
4148
4454
  "use strict";
4149
4455
  init_resp();
4456
+ init_redis_lua();
4150
4457
  init_types();
4151
4458
  init_host();
4152
4459
  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(" "));
@@ -4270,9 +4577,12 @@ var init_redis = __esm({
4270
4577
  }
4271
4578
  return this.run(args);
4272
4579
  }
4580
+ /** Lua scripts (EVAL/EVALSHA/SCRIPT) run against this engine's own data; see redis-lua.ts. */
4581
+ scripts;
4273
4582
  run(args) {
4274
4583
  const name = args[0].toLowerCase(), a = args.slice(1);
4275
4584
  try {
4585
+ if (["eval", "evalsha", "eval_ro", "evalsha_ro", "script"].includes(name)) return (this.scripts ??= new RedisScripts((c) => this.run(c))).command(name, a);
4276
4586
  const reply = this.command(name, a);
4277
4587
  if (WRITES.has(name)) for (const k of commandKeys(name, a)) this.touch(k);
4278
4588
  return reply;
@@ -4287,7 +4597,7 @@ var init_redis = __esm({
4287
4597
  command(name, a) {
4288
4598
  const now = Date.now(), ok2 = encode.simple("OK"), key2 = a[0];
4289
4599
  const str2 = (k) => this.get(k, "string");
4290
- const bulks = (list2) => encode.array(list2.map((v) => encode.bulk(v ?? null)));
4600
+ const bulks = (list3) => encode.array(list3.map((v) => encode.bulk(v ?? null)));
4291
4601
  const setString = (k, v, expireAt) => this.data.set(k, { type: "string", value: v, ...expireAt !== void 0 ? { expireAt } : {} });
4292
4602
  const incr = (k, by) => {
4293
4603
  const cur = str2(k) ?? "0";
@@ -4807,7 +5117,7 @@ function upstashRedisOperation(method, path2, params, headers, data, _sequence,
4807
5117
  let full = false;
4808
5118
  for (const c of args) {
4809
5119
  const name = c[0].toLowerCase(), keys = commandKeys(name, c.slice(1));
4810
- if (GLOBAL_WRITES.has(name) || !keys.length && WRITE_COMMANDS.has(name)) full = true;
5120
+ if (GLOBAL_WRITES.has(name) || !keys.length && (WRITE_COMMANDS.has(name) || /^eval/.test(name))) full = true;
4811
5121
  for (const k of keys) touched.add(k);
4812
5122
  }
4813
5123
  if (full || cache3.nextExpiry <= now) resync(rows2, cache3);
@@ -4815,7 +5125,7 @@ function upstashRedisOperation(method, path2, params, headers, data, _sequence,
4815
5125
  const encoding = headers["upstash-encoding"];
4816
5126
  const base64 = typeof encoding === "string" && encoding.toLowerCase() === "base64";
4817
5127
  const results = replies.map((r) => upstashReply(r, base64));
4818
- const wrote = args.some((c) => WRITE_COMMANDS.has(c[0].toLowerCase()));
5128
+ const wrote = args.some((c) => WRITE_COMMANDS.has(c[0].toLowerCase()) || /^eval(sha)?$/.test(c[0].toLowerCase()));
4819
5129
  const record4 = { commands: args.map((c) => c[0].toUpperCase()), keys: args.map((c) => c[1] === void 0 ? null : fromBytes(c[1])) };
4820
5130
  if (single) {
4821
5131
  const result2 = results[0];
@@ -4831,7 +5141,7 @@ var init_upstash_redis_twin = __esm({
4831
5141
  init_resp();
4832
5142
  UPSTASH_KEYS = "/keys";
4833
5143
  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(" "));
4834
- REJECTED = /* @__PURE__ */ new Set(["eval", "evalsha", "eval_ro", "evalsha_ro", "script", "subscribe", "psubscribe", "blpop", "brpop", "blmove", "monitor", "multi", "exec", "watch"]);
5144
+ REJECTED = /* @__PURE__ */ new Set(["subscribe", "psubscribe", "blpop", "brpop", "blmove", "monitor", "multi", "exec", "watch"]);
4835
5145
  toBytes = (v) => Buffer.from(v, "utf8").toString("latin1");
4836
5146
  fromBytes = (v) => Buffer.from(v, "latin1").toString("utf8");
4837
5147
  caches = /* @__PURE__ */ new WeakMap();
@@ -4868,7 +5178,7 @@ function decodeEncodedWords(value) {
4868
5178
  let failure;
4869
5179
  const decoded = value.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=(\s+(?==\?))?/g, (_all, charset, kind, text3) => {
4870
5180
  if (!/^(utf-8|us-ascii)$/i.test(charset)) {
4871
- failure ??= mimeError(`Encoded header charset ${charset} is outside the verified subset`, true);
5181
+ failure ??= mimeError("Encoded header charset is outside the verified subset", true);
4872
5182
  return "";
4873
5183
  }
4874
5184
  if (kind.toUpperCase() === "B") return Buffer.from(text3, "base64").toString("utf8");
@@ -4925,12 +5235,12 @@ function decodeBody(body2, headers) {
4925
5235
  if (!/^[A-Za-z0-9+/]*={0,2}$/.test(compact)) return mimeError("Invalid base64 MIME body", false);
4926
5236
  return Buffer.from(compact, "base64");
4927
5237
  }
4928
- return mimeError(`Content-Transfer-Encoding ${encoding} is outside the verified subset`, true);
5238
+ return mimeError("Content-Transfer-Encoding is outside the verified subset", true);
4929
5239
  }
4930
5240
  function textPart(partId, headers, body2) {
4931
5241
  const { mimeType, params } = contentType(headers);
4932
- if (mimeType !== "text/plain" && mimeType !== "text/html") return mimeError(`MIME part ${mimeType} is outside the verified subset`, true);
4933
- if (params.charset && !/^(utf-8|us-ascii)$/i.test(params.charset)) return mimeError(`Charset ${params.charset} is outside the verified subset`, true);
5242
+ if (mimeType !== "text/plain" && mimeType !== "text/html") return mimeError("MIME part type is outside the verified subset", true);
5243
+ if (params.charset && !/^(utf-8|us-ascii)$/i.test(params.charset)) return mimeError("MIME charset is outside the verified subset", true);
4934
5244
  const decoded = decodeBody(body2, headers);
4935
5245
  if (!Buffer.isBuffer(decoded)) return decoded;
4936
5246
  if (Buffer.from(decoded.toString("utf8")).compare(decoded) !== 0) return mimeError("MIME text part is not valid UTF-8", true);
@@ -4951,11 +5261,21 @@ function parseGmailDraftRaw(raw) {
4951
5261
  let payload;
4952
5262
  if (mimeType === "multipart/alternative") {
4953
5263
  if (!params.boundary) return mimeError("multipart/alternative needs a boundary", false);
4954
- const sections = top.body.split(new RegExp(`(?:^|\\r?\\n)--${params.boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`));
4955
- const closing = sections.findIndex((s) => s.startsWith("--"));
4956
- if (closing < 0) return mimeError("multipart/alternative has no closing boundary", false);
5264
+ const boundary = params.boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5265
+ const delimiters = [];
5266
+ for (const match of top.body.matchAll(new RegExp(`(?:^|\\r?\\n)--${boundary}(--)?[ \\t]*(?=\\r?\\n|$)`, "g"))) {
5267
+ const start = match.index ?? 0;
5268
+ const closing = match[1] === "--";
5269
+ delimiters.push({ start, end: start + match[0].length, closing });
5270
+ if (closing || delimiters.length > 10) break;
5271
+ }
5272
+ const closed = delimiters.at(-1)?.closing === true;
5273
+ const count = delimiters.length - Number(closed);
5274
+ if (count > 10 || closed && count === 0) return mimeError("multipart/alternative needs 1 to 10 parts", false);
5275
+ if (!closed) return mimeError("multipart/alternative has no closing boundary", false);
4957
5276
  const parts = [];
4958
- for (const section of sections.slice(1, closing)) {
5277
+ for (let i = 0; i < count; i++) {
5278
+ const section = top.body.slice(delimiters[i].end, delimiters[i + 1].start);
4959
5279
  const split = splitHead(section.replace(/^[ \t]*\r?\n/, ""));
4960
5280
  if (!split) return mimeError("MIME part headers and body need a blank-line separator", false);
4961
5281
  const partHeaders = parseHeaderBlock(split.head);
@@ -4964,10 +5284,9 @@ function parseGmailDraftRaw(raw) {
4964
5284
  if ("error" in part) return part;
4965
5285
  parts.push(part);
4966
5286
  }
4967
- if (!parts.length || parts.length > 10) return mimeError("multipart/alternative needs 1 to 10 parts", false);
4968
5287
  payload = { partId: "", mimeType, filename: "", headers, body: { size: 0 }, parts };
4969
5288
  } else if (mimeType.startsWith("multipart/")) {
4970
- return mimeError(`${mimeType} (attachments or nested parts) is outside the verified subset`, true);
5289
+ 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);
4971
5290
  } else {
4972
5291
  const part = textPart("", headers, top.body);
4973
5292
  if ("error" in part) return part;
@@ -5051,7 +5370,7 @@ var init_gmail_mime = __esm({
5051
5370
  });
5052
5371
 
5053
5372
  // src/runtime/rest-adapters.ts
5054
- import { createHash as createHash9 } from "crypto";
5373
+ import { createHash as createHash10 } from "crypto";
5055
5374
  function githubOperation(method, path2, params, _headers, data, sequence) {
5056
5375
  const errors = (status, message, extra) => ({ status, body: { message, documentation_url: "https://docs.github.com/rest", ...extra ?? {} }, collection: "/repos" });
5057
5376
  if (path2 === "/repos") return method === "GET" ? ok("/repos", rows(data, "/repos").map((row) => structuredClone(row))) : void 0;
@@ -5751,10 +6070,17 @@ function gmailOperation(method, path2, params, headers, data, sequence, raw) {
5751
6070
  if (params.subject !== void 0 && str(params.subject) === void 0) return fail2(400, "subject must be a string.");
5752
6071
  if (params.threadId !== void 0 && str(params.threadId) === void 0) return fail2(400, "threadId must be a string.");
5753
6072
  if (raw2 && text3 !== void 0) return fail2(400, "Provide raw or text, not both.");
5754
- const mime = raw2 ? parseGmailRaw(raw2) : void 0;
5755
- if (mime && "error" in mime) return mime.unsupported ? void 0 : fail2(400, mime.error);
5756
- const body2 = mime?.text ?? text3 ?? "";
5757
- 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) };
6073
+ const plain2 = raw2 ? parseGmailRaw(raw2) : void 0;
6074
+ const legacy = plain2 && !("error" in plain2) ? plain2 : void 0;
6075
+ const mime = raw2 && !legacy ? parseGmailDraftRaw(raw2) : void 0;
6076
+ if (mime && "error" in mime) {
6077
+ return mime.unsupported ? { status: 501, body: restUnsupportedBody("gmail"), collection: MESSAGES, unsupportedReason: mime.error } : fail2(400, mime.error);
6078
+ }
6079
+ if (mime && !headerAddresses(mime.headers.find((header3) => header3.name.toLowerCase() === "to")?.value).length) {
6080
+ return fail2(400, "Invalid To header: a sent message needs at least one recipient.");
6081
+ }
6082
+ const body2 = legacy?.text ?? mime?.snippet ?? text3 ?? "";
6083
+ 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) };
5758
6084
  rowsIn(data, MESSAGES).push(message);
5759
6085
  return withPush(write2(200, MESSAGES, structuredClone(message), message), gmailPublish(data, ["SENT"], sequence));
5760
6086
  }
@@ -5797,7 +6123,38 @@ function gmailOperation(method, path2, params, headers, data, sequence, raw) {
5797
6123
  if (!message) return fail2(404, `Message not found: ${messageMatch[1]}`);
5798
6124
  return ok(MESSAGES, structuredClone(message));
5799
6125
  }
6126
+ const modifyMatch = /^\/gmail\/v1\/users\/me\/(messages|threads)\/([^/]+)\/modify$/.exec(path2);
6127
+ if (modifyMatch) {
6128
+ if (method !== "POST" || Object.keys(params).some((k) => !["addLabelIds", "removeLabelIds"].includes(k))) return void 0;
6129
+ const list3 = (v) => v === void 0 ? [] : Array.isArray(v) && v.every((x) => typeof x === "string") ? v : void 0;
6130
+ const add = list3(params.addLabelIds), remove2 = list3(params.removeLabelIds);
6131
+ if (!add || !remove2) return fail2(400, "Invalid label list.");
6132
+ const known2 = gmailLabelKnown(data), unknown = [...add, ...remove2].find((id2) => !known2(id2));
6133
+ if (unknown) return fail2(400, `Invalid label: ${unknown}`);
6134
+ const id = decodeURIComponent(modifyMatch[2]);
6135
+ const targets = modifyMatch[1] === "messages" ? rowsIn(data, MESSAGES).filter((m) => m.id === id) : rowsIn(data, MESSAGES).filter((m) => m.threadId === id);
6136
+ if (!targets.length) return fail2(404, `Requested entity was not found.`);
6137
+ const next = String(BigInt(gmailHistoryId(rowsIn(data, MESSAGES))) + 1n);
6138
+ for (const message of targets) {
6139
+ const labels = new Set(message.labelIds ?? []);
6140
+ for (const l of add) labels.add(l);
6141
+ for (const l of remove2) labels.delete(l);
6142
+ message.labelIds = [...labels];
6143
+ message.historyId = next;
6144
+ }
6145
+ const body2 = modifyMatch[1] === "messages" ? structuredClone(targets[0]) : { id, historyId: next, messages: targets.map((m) => structuredClone(m)) };
6146
+ return { status: 200, body: body2, collection: MESSAGES, operation: "write", record: { id, addLabelIds: add, removeLabelIds: remove2 } };
6147
+ }
5800
6148
  if (path2 === LABELS) {
6149
+ if (method === "POST") {
6150
+ if (Object.keys(params).some((k) => !["name", "labelListVisibility", "messageListVisibility", "color", "type"].includes(k))) return void 0;
6151
+ if (typeof params.name !== "string" || !params.name.trim()) return googleError(LABELS, 400, "Invalid label name");
6152
+ const labels = rowsIn(data, LABELS);
6153
+ 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");
6154
+ 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 } : {} };
6155
+ (data[LABELS] ??= []).push(label2);
6156
+ return { status: 200, body: structuredClone(label2), collection: LABELS, operation: "write", record: label2 };
6157
+ }
5801
6158
  if (method !== "GET") return void 0;
5802
6159
  if (Object.keys(params).length) return void 0;
5803
6160
  return ok(LABELS, { labels: rowsIn(data, LABELS).map((row) => structuredClone(row)) });
@@ -6131,7 +6488,7 @@ function zendeskOperation(method, path2, params, _headers, data, sequence) {
6131
6488
  function restUnsupportedBody(adapter) {
6132
6489
  return UNSUPPORTED_BODIES[adapter];
6133
6490
  }
6134
- 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;
6491
+ 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;
6135
6492
  var init_rest_adapters = __esm({
6136
6493
  "src/runtime/rest-adapters.ts"() {
6137
6494
  "use strict";
@@ -6143,7 +6500,7 @@ var init_rest_adapters = __esm({
6143
6500
  init_gmail_mime();
6144
6501
  EPOCH2 = 17e8;
6145
6502
  iso2 = (epoch = EPOCH2) => new Date(twinNowMs(epoch * 1e3)).toISOString();
6146
- sha2 = (value) => createHash9("sha256").update(value).digest("hex");
6503
+ sha2 = (value) => createHash10("sha256").update(value).digest("hex");
6147
6504
  detUuid = (seed) => {
6148
6505
  const hex = sha2(seed).slice(0, 32).split("");
6149
6506
  hex[12] = "4";
@@ -6206,6 +6563,7 @@ var init_rest_adapters = __esm({
6206
6563
  };
6207
6564
  gmailHistoryId = (messages) => messages.reduce((max, m) => BigInt(String(m.historyId ?? 0)) > BigInt(max) ? String(m.historyId) : max, "0");
6208
6565
  withPush = (result2, deliveries) => deliveries.length ? { ...result2, deliveries } : result2;
6566
+ GMAIL_SYSTEM_LABEL_NAMES = /* @__PURE__ */ new Set(["INBOX", "SPAM", "TRASH", "UNREAD", "STARRED", "IMPORTANT", "SENT", "DRAFT", "CHAT"]);
6209
6567
  JIRA_TRANSITIONS = { "11": "To Do", "21": "In Progress", "31": "Done" };
6210
6568
  discordError = (collection, code, message) => ({ status: code === 10003 || code === 10004 ? 404 : 400, body: { message, code }, collection });
6211
6569
  ZENDESK_STATUSES = ["new", "open", "pending", "solved", "closed"];
@@ -6253,8 +6611,169 @@ var init_rest_adapters = __esm({
6253
6611
  }
6254
6612
  });
6255
6613
 
6614
+ // src/runtime/postgrest.ts
6615
+ import { createRequire as createRequire2 } from "module";
6616
+ var loadPg, ident2, OPS, RESERVED, PostgrestLayer;
6617
+ var init_postgrest = __esm({
6618
+ "src/runtime/postgrest.ts"() {
6619
+ "use strict";
6620
+ loadPg = () => createRequire2(import.meta.url)("pg");
6621
+ ident2 = (name) => `"${name.replace(/"/g, '""')}"`;
6622
+ OPS = { eq: "=", neq: "<>", gt: ">", gte: ">=", lt: "<", lte: "<=", like: "LIKE", ilike: "ILIKE" };
6623
+ RESERVED = /* @__PURE__ */ new Set(["select", "order", "limit", "offset", "on_conflict", "columns", "or", "and"]);
6624
+ PostgrestLayer = class _PostgrestLayer {
6625
+ pool;
6626
+ fks;
6627
+ constructor(databaseUrl2) {
6628
+ this.pool = new (loadPg()).Pool({ connectionString: databaseUrl2, max: 1 });
6629
+ }
6630
+ close() {
6631
+ return this.pool.end().catch(() => {
6632
+ });
6633
+ }
6634
+ foreignKeys() {
6635
+ 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"
6636
+ 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]
6637
+ 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, "") })));
6638
+ }
6639
+ /** Splits a select list at top-level commas: `id, name, prices(*, product:products(name))`. */
6640
+ static items(select) {
6641
+ const out = [];
6642
+ let depth = 0, cur = "";
6643
+ for (const c of select) {
6644
+ if (c === "(") depth++;
6645
+ if (c === ")") depth--;
6646
+ if (c === "," && !depth) {
6647
+ out.push(cur.trim());
6648
+ cur = "";
6649
+ } else cur += c;
6650
+ }
6651
+ if (cur.trim()) out.push(cur.trim());
6652
+ return out;
6653
+ }
6654
+ async columns(table2, alias, select) {
6655
+ const parts = [];
6656
+ for (const item of _PostgrestLayer.items(select || "*")) {
6657
+ const embed = /^(?:(\w+):)?(\w+)(?:!\w+)?\((.*)\)$/s.exec(item);
6658
+ if (!embed) {
6659
+ if (item === "*") {
6660
+ parts.push(`${alias}.*`);
6661
+ continue;
6662
+ }
6663
+ const m = /^(?:(\w+):)?(\w+)(?:::\w+)?$/.exec(item);
6664
+ if (!m) continue;
6665
+ parts.push(`${alias}.${ident2(m[2])} AS ${ident2(m[1] ?? m[2])}`);
6666
+ continue;
6667
+ }
6668
+ const [, as, rel, inner] = embed, fks = await this.foreignKeys(), child = `e${parts.length}_${alias}`;
6669
+ const many = fks.find((f) => f.table === rel && f.refTable === table2), one = fks.find((f) => f.table === table2 && f.refTable === rel);
6670
+ const cols = await this.columns(rel, child, inner);
6671
+ 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)}`);
6672
+ 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)}`);
6673
+ }
6674
+ return parts.join(", ") || `${alias}.*`;
6675
+ }
6676
+ /** WHERE clause from `col=op.value` query parameters. */
6677
+ static where(params, values) {
6678
+ const clauses = [];
6679
+ for (const [key2, raw] of params) {
6680
+ if (RESERVED.has(key2)) continue;
6681
+ const not = raw.startsWith("not."), text3 = not ? raw.slice(4) : raw, dot = text3.indexOf(".");
6682
+ const op2 = text3.slice(0, dot), value = text3.slice(dot + 1), col = ident2(key2);
6683
+ let clause;
6684
+ if (OPS[op2]) {
6685
+ values.push(op2.endsWith("like") ? value.replace(/\*/g, "%") : value);
6686
+ clause = `${col}::text ${OPS[op2]} $${values.length}`;
6687
+ if (op2 === "eq" || op2 === "neq") clause = `${col} ${OPS[op2]} $${values.length}`;
6688
+ } else if (op2 === "is") clause = `${col} IS ${value === "null" ? "NULL" : value === "true" ? "TRUE" : value === "false" ? "FALSE" : "UNKNOWN"}`;
6689
+ else if (op2 === "in") {
6690
+ values.push(value.replace(/^\(|\)$/g, "").split(",").map((v) => v.replace(/^"|"$/g, "")));
6691
+ clause = `${col}::text = ANY($${values.length}::text[])`;
6692
+ }
6693
+ if (clause) clauses.push(not ? `NOT (${clause})` : clause);
6694
+ }
6695
+ return clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
6696
+ }
6697
+ async handle(request) {
6698
+ const header3 = (name) => {
6699
+ const v = request.headers[name];
6700
+ return Array.isArray(v) ? v.join(",") : v ?? "";
6701
+ };
6702
+ const prefer = header3("prefer"), single = /vnd\.pgrst\.object/.test(header3("accept"));
6703
+ const reply = (status, body2, extra = {}) => ({ status, headers: { "content-type": "application/json; charset=utf-8", ...extra }, body: body2 === void 0 ? "" : JSON.stringify(body2) });
6704
+ const segments = request.url.pathname.replace(/^\/rest\/v1\/?/, "").split("/").filter(Boolean).map(decodeURIComponent);
6705
+ if (!segments.length) return reply(404, { code: "PGRST125", message: "Invalid path specified in request URL" });
6706
+ const params = request.url.searchParams, values = [];
6707
+ let payload;
6708
+ try {
6709
+ payload = request.body?.length ? JSON.parse(request.body.toString("utf8")) : void 0;
6710
+ } catch {
6711
+ return reply(400, { code: "PGRST102", message: "Empty or invalid json" });
6712
+ }
6713
+ try {
6714
+ if (segments[0] === "rpc" && segments[1]) {
6715
+ const args = payload && typeof payload === "object" && !Array.isArray(payload) ? Object.entries(payload) : [...params].map(([k, v]) => [k, v]);
6716
+ const list3 = args.map(([k, v], i) => {
6717
+ values.push(v !== null && typeof v === "object" ? JSON.stringify(v) : v);
6718
+ return `${ident2(k)} => $${i + 1}`;
6719
+ });
6720
+ const r = await this.pool.query(`SELECT to_json(f) AS v FROM ${ident2(segments[1])}(${list3.join(", ")}) f`, values);
6721
+ const rows3 = r.rows.map((x) => x.v);
6722
+ 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);
6723
+ }
6724
+ const table2 = segments[0], t = ident2(table2);
6725
+ const returning = async (sql2) => {
6726
+ const cols = await this.columns(table2, "r", params.get("select") ?? "*");
6727
+ return `WITH r AS (${sql2} RETURNING *) SELECT coalesce(json_agg(x), '[]'::json) AS rows FROM (SELECT ${cols} FROM r) x`;
6728
+ };
6729
+ let sql, status = 200;
6730
+ const method = request.method.toUpperCase();
6731
+ if (method === "GET" || method === "HEAD") {
6732
+ const order = (params.get("order") ?? "").split(",").filter(Boolean).map((o) => {
6733
+ const [c, dir, nulls] = o.split(".");
6734
+ return `${ident2(c)} ${dir === "desc" ? "DESC" : "ASC"}${nulls === "nullsfirst" ? " NULLS FIRST" : nulls === "nullslast" ? " NULLS LAST" : ""}`;
6735
+ });
6736
+ const limit2 = Number(params.get("limit")), offset = Number(params.get("offset"));
6737
+ const cols = await this.columns(table2, "t", params.get("select") ?? "*");
6738
+ 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`;
6739
+ } else if (method === "POST") {
6740
+ const rows3 = Array.isArray(payload) ? payload : [payload ?? {}];
6741
+ const keys = [...new Set(rows3.flatMap((r) => Object.keys(r)))];
6742
+ values.push(JSON.stringify(rows3));
6743
+ const target = params.get("on_conflict")?.split(",").map(ident2).join(", ");
6744
+ 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;
6745
+ const merge = /resolution=merge-duplicates/.test(prefer), ignore = /resolution=ignore-duplicates/.test(prefer);
6746
+ const conflict = (merge || ignore) && pk ? ` ON CONFLICT (${pk}) DO ${ignore || !keys.length ? "NOTHING" : `UPDATE SET ${keys.map((k) => `${ident2(k)} = EXCLUDED.${ident2(k)}`).join(", ")}`}` : "";
6747
+ 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`;
6748
+ if (!keys.length) values.length = 0;
6749
+ sql = await returning(insert);
6750
+ status = 201;
6751
+ } else if (method === "PATCH") {
6752
+ const keys = Object.keys(payload ?? {});
6753
+ values.push(JSON.stringify(payload ?? {}));
6754
+ const set = keys.map((k) => `${ident2(k)} = (json_populate_record(null::${t}, $1::json)).${ident2(k)}`).join(", ");
6755
+ sql = await returning(`UPDATE ${t} SET ${set || "ctid = ctid"}${_PostgrestLayer.where(params, values)}`);
6756
+ } else if (method === "DELETE") {
6757
+ sql = await returning(`DELETE FROM ${t}${_PostgrestLayer.where(params, values)}`);
6758
+ } else return reply(405, { code: "PGRST117", message: `Unsupported HTTP method: ${method}` });
6759
+ const rows2 = (await this.pool.query(sql, values)).rows[0]?.rows ?? [];
6760
+ const range = { "content-range": `0-${Math.max(rows2.length - 1, 0)}/${/count=exact/.test(prefer) ? rows2.length : "*"}` };
6761
+ if (method !== "GET" && /return=minimal/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
6762
+ if (method !== "GET" && !/return=representation/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
6763
+ 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 });
6764
+ return reply(status, rows2, range);
6765
+ } catch (error) {
6766
+ const e = error;
6767
+ const status = e.code === "23505" ? 409 : e.code === "42P01" ? 404 : e.code === "42501" ? 403 : 400;
6768
+ return reply(status, { code: e.code === "42P01" ? "PGRST205" : e.code ?? "PGRST000", message: e.message ?? String(error), details: e.detail ?? null, hint: e.hint ?? null });
6769
+ }
6770
+ }
6771
+ };
6772
+ }
6773
+ });
6774
+
6256
6775
  // src/runtime/pack-log.ts
6257
- import { closeSync, existsSync as existsSync2, openSync, readdirSync, readSync, statSync } from "fs";
6776
+ import { closeSync, existsSync as existsSync2, openSync, readdirSync as readdirSync2, readSync, statSync } from "fs";
6258
6777
  import { join as join10 } from "path";
6259
6778
  function packCollection(type, requestPath) {
6260
6779
  const segments = requestPath.split("/").filter(Boolean);
@@ -6295,7 +6814,7 @@ var init_pack_log = __esm({
6295
6814
  partial = /* @__PURE__ */ new Map();
6296
6815
  files() {
6297
6816
  if (!existsSync2(this.root)) return [];
6298
- return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join10(this.root, f)).sort();
6817
+ return readdirSync2(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join10(this.root, f)).sort();
6299
6818
  }
6300
6819
  drain() {
6301
6820
  const out = [];
@@ -6326,15 +6845,37 @@ var init_pack_log = __esm({
6326
6845
  }
6327
6846
  });
6328
6847
 
6848
+ // src/runtime/pack-aliases.ts
6849
+ function aliasRequest(pack, host, url) {
6850
+ const at = url.indexOf("?"), path2 = at < 0 ? url : url.slice(0, at), query = at < 0 ? "" : url.slice(at);
6851
+ const vendor = compatibleVendor(pack), compatible = vendor && compatibleRequest(vendor, host, url);
6852
+ if (compatible) return compatible;
6853
+ const alias = PACK_ALIASES[pack]?.find((a) => a.host === host.toLowerCase() && a.path === path2);
6854
+ return alias ? { host: alias.to.host, url: alias.to.path + query } : { host, url };
6855
+ }
6856
+ var PACK_ALIASES;
6857
+ var init_pack_aliases = __esm({
6858
+ "src/runtime/pack-aliases.ts"() {
6859
+ "use strict";
6860
+ init_compatible_packs();
6861
+ PACK_ALIASES = {
6862
+ // Google's OpenID Connect discovery names openidconnect.googleapis.com/v1/userinfo; the pack models the
6863
+ // equivalent www.googleapis.com/oauth2/v3/userinfo (https://developers.google.com/identity/openid-connect/openid-connect).
6864
+ googleoauth: [{ host: "openidconnect.googleapis.com", path: "/v1/userinfo", to: { host: "www.googleapis.com", path: "/oauth2/v3/userinfo" } }]
6865
+ };
6866
+ }
6867
+ });
6868
+
6329
6869
  // src/runtime/http-world.ts
6330
6870
  import { createServer as createServer3 } from "http";
6871
+ import { createServer as createNetServer } from "net";
6331
6872
  import { isDeepStrictEqual as isDeepStrictEqual5 } from "util";
6332
- import { createHash as createHash10 } from "crypto";
6873
+ import { createHash as createHash11 } from "crypto";
6333
6874
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
6334
- import { mkdir as mkdir3, mkdtemp as mkdtemp5, rm as rm5, writeFile as writeFile5 } from "fs/promises";
6875
+ import { mkdir as mkdir3, mkdtemp as mkdtemp5, rm as rm5, writeFile as writeFile6 } from "fs/promises";
6335
6876
  import { tmpdir as tmpdir5 } from "os";
6336
6877
  import { join as join11 } from "path";
6337
- var idempotencyKeyDigest, HttpWorld;
6878
+ var slackDirectMessageId, idempotencyKeyDigest, HttpWorld;
6338
6879
  var init_http_world = __esm({
6339
6880
  "src/runtime/http-world.ts"() {
6340
6881
  "use strict";
@@ -6346,9 +6887,13 @@ var init_http_world = __esm({
6346
6887
  init_spec();
6347
6888
  init_enterprise_twins();
6348
6889
  init_adapters();
6890
+ init_postgrest();
6349
6891
  init_packs();
6350
6892
  init_pack_log();
6351
- idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash10("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
6893
+ init_pack_aliases();
6894
+ init_compatible_packs();
6895
+ slackDirectMessageId = (user) => `D${createHash11("sha256").update(user).digest("hex").slice(0, 16).toUpperCase()}`;
6896
+ idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash11("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
6352
6897
  HttpWorld = class {
6353
6898
  /** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
6354
6899
  constructor(spec, seed, options = {}) {
@@ -6374,6 +6919,12 @@ var init_http_world = __esm({
6374
6919
  epoch = 0;
6375
6920
  replayKeys = /* @__PURE__ */ new Map();
6376
6921
  sourceContext = new AsyncLocalStorage2();
6922
+ postgrest;
6923
+ /** The run's PostgreSQL: a pack's PostgREST paths (/rest/v1/<table>) are served from it, so the app's own tables answer. */
6924
+ attachDatabase(url) {
6925
+ void this.postgrest?.close();
6926
+ this.postgrest = new PostgrestLayer(url);
6927
+ }
6377
6928
  record(service, operation, path2, detail, record4) {
6378
6929
  if (this.events.length >= 5e4) return;
6379
6930
  const source = this.sourceContext.getStore();
@@ -6384,6 +6935,33 @@ var init_http_world = __esm({
6384
6935
  * each, after the triggering response. Only loopback http endpoints are allowed, so a push can never leave the
6385
6936
  * machine; the outcome is written to the push row and recorded as a `push` event.
6386
6937
  */
6938
+ sentWebhooks = /* @__PURE__ */ new Set();
6939
+ /** Sends a webhook a pack signed and queued, with the pack's own signature headers. Loopback http only. */
6940
+ sendWebhook(service, url, body2, headers, eventType) {
6941
+ const epoch = this.epoch;
6942
+ const timer = setTimeout(async () => {
6943
+ this.timers.delete(timer);
6944
+ if (epoch !== this.epoch) return;
6945
+ let target;
6946
+ try {
6947
+ target = new URL(url);
6948
+ } catch {
6949
+ target = void 0;
6950
+ }
6951
+ if (!target || target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || target.username || target.password) {
6952
+ this.record(service, "webhook", url, `webhook ${eventType} not sent: the endpoint is not a loopback http URL (nothing leaves this machine)`);
6953
+ return;
6954
+ }
6955
+ try {
6956
+ const response = await fetch(target, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: body2, redirect: "error", signal: AbortSignal.timeout(6e4) });
6957
+ await response.arrayBuffer().catch(() => void 0);
6958
+ if (epoch === this.epoch) this.record(service, "webhook", url, `delivered ${eventType} to ${url}: HTTP ${response.status}`, { event: eventType, status: response.status });
6959
+ } catch (error) {
6960
+ if (epoch === this.epoch) this.record(service, "webhook", url, `webhook ${eventType} to ${url} failed: ${error instanceof Error ? error.message : String(error)}`);
6961
+ }
6962
+ }, 25);
6963
+ this.timers.add(timer);
6964
+ }
6387
6965
  push(service, deliveries, epoch) {
6388
6966
  for (const delivery of deliveries) {
6389
6967
  const timer = setTimeout(async () => {
@@ -6415,12 +6993,23 @@ var init_http_world = __esm({
6415
6993
  this.timers.add(timer);
6416
6994
  }
6417
6995
  }
6996
+ /** Tags every event recorded since index `from` with the request's idempotency key digest. */
6997
+ keyedSince(from, key2) {
6998
+ const digest6 = idempotencyKeyDigest(key2);
6999
+ if (digest6) for (let i = from; i < this.events.length; i++) this.events[i].idempotencyKey = digest6;
7000
+ }
6418
7001
  /** Tags the event just recorded with the request's idempotency key digest. */
6419
7002
  keyed(key2) {
6420
7003
  const digest6 = idempotencyKeyDigest(key2), last = this.events[this.events.length - 1];
6421
7004
  if (digest6 && last) last.idempotencyKey = digest6;
6422
7005
  }
7006
+ /** Requests the run itself sends to set a twin up (x-agenttwin-probe: 1): a refusal there is not the application's gap. */
7007
+ probes = 0;
6423
7008
  rejectUnsupported(service, method, path2, detail) {
7009
+ if (this.probes > 0) {
7010
+ this.record(service, "assumption", path2, `setup probe: ${detail}`);
7011
+ return;
7012
+ }
6424
7013
  this.unsupported.push(`${service}: ${method} ${path2}: ${detail}`);
6425
7014
  this.record(service, "unsupported", path2, detail);
6426
7015
  }
@@ -6467,340 +7056,382 @@ var init_http_world = __esm({
6467
7056
  this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server2.address().port}`, token };
6468
7057
  continue;
6469
7058
  }
6470
- const server = createServer3((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
6471
- const epoch = this.epoch;
6472
- const send2 = (code, body2, headers = {}) => {
6473
- if (!res.destroyed) {
6474
- res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {}, ...headers });
6475
- res.end(code === 204 || code === 202 && body2 === null ? void 0 : typeof body2 === "string" && headers["content-type"] ? body2 : JSON.stringify(body2));
6476
- }
6477
- };
6478
- const respond = (code, body2, headers) => {
6479
- const ms = latencyMs();
6480
- if (ms <= 0) {
6481
- send2(code, body2, headers);
6482
- return;
6483
- }
6484
- const timer = setTimeout(() => {
6485
- this.timers.delete(timer);
6486
- if (epoch === this.epoch) send2(code, body2, headers);
6487
- }, ms);
6488
- this.timers.add(timer);
6489
- };
6490
- const normalPath = (url, method) => {
6491
- const parsed = new URL(url, "http://localhost");
6492
- if (generated) return generated.collectionOf(method ?? "", parsed.pathname) ?? parsed.pathname;
6493
- if (service.adapter === "google-oauth" && parsed.pathname === "/token" && method === "POST") return "/tokens";
6494
- if (service.adapter === "composio") {
6495
- if (/^\/api\/v3(?:\.1)?\/tools\/execute\//.test(parsed.pathname)) return "/messages";
6496
- if (/^\/api\/v3(?:\.1)?\/connected_accounts(?:\/|$)/.test(parsed.pathname)) return "/connected_accounts";
6497
- }
6498
- if (service.adapter === "slack") {
6499
- const m = parsed.pathname.replace(/^\/api\//, "");
6500
- if (m === "chat.postMessage" && method === "POST") return "/messages";
6501
- if (m === "conversations.history" && ["GET", "POST"].includes(method ?? "")) return "/messages";
6502
- if (m === "conversations.list" && ["GET", "POST"].includes(method ?? "")) return "/channels";
7059
+ const server = createServer3((req, res) => {
7060
+ if (req.headers["x-agenttwin-probe"] === "1") {
7061
+ this.probes++;
7062
+ res.once("close", () => {
7063
+ this.probes--;
7064
+ });
7065
+ }
7066
+ return withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
7067
+ const epoch = this.epoch;
7068
+ const send2 = (code, body2, headers = {}) => {
7069
+ if (!res.destroyed) {
7070
+ res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {}, ...headers });
7071
+ res.end(code === 204 || code === 202 && body2 === null ? void 0 : typeof body2 === "string" && headers["content-type"] ? body2 : JSON.stringify(body2));
7072
+ }
7073
+ };
7074
+ const respond = (code, body2, headers) => {
7075
+ const ms = latencyMs();
7076
+ if (ms <= 0) {
7077
+ send2(code, body2, headers);
7078
+ return;
7079
+ }
7080
+ const timer = setTimeout(() => {
7081
+ this.timers.delete(timer);
7082
+ if (epoch === this.epoch) send2(code, body2, headers);
7083
+ }, ms);
7084
+ this.timers.add(timer);
7085
+ };
7086
+ const normalPath = (url, method) => {
7087
+ const parsed = new URL(url, "http://localhost");
7088
+ if (generated) return generated.collectionOf(method ?? "", parsed.pathname) ?? parsed.pathname;
7089
+ if (service.adapter === "google-oauth" && parsed.pathname === "/token" && method === "POST") return "/tokens";
7090
+ if (service.adapter === "composio") {
7091
+ if (/^\/api\/v3(?:\.1)?\/tools\/execute\//.test(parsed.pathname)) return "/messages";
7092
+ if (/^\/api\/v3(?:\.1)?\/connected_accounts(?:\/|$)/.test(parsed.pathname)) return "/connected_accounts";
7093
+ }
7094
+ if (service.adapter === "slack") {
7095
+ const m = parsed.pathname.replace(/^\/api\//, "");
7096
+ if (m === "chat.postMessage" && method === "POST") return "/messages";
7097
+ if (m === "conversations.history" && ["GET", "POST"].includes(method ?? "")) return "/messages";
7098
+ if (m === "conversations.list" && ["GET", "POST"].includes(method ?? "")) return "/channels";
7099
+ return parsed.pathname;
7100
+ }
6503
7101
  return parsed.pathname;
6504
- }
6505
- return parsed.pathname;
6506
- };
6507
- const matchesFault = (target) => adapterService ? target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path) : target === fault.path;
6508
- const requestKey = req.headers["idempotency-key"];
6509
- const respondSlowly = (target, operation, code, body2, headers) => {
6510
- if (fault?.type !== "slow-response" || !faultOrdinalsFor || !matchesFault(target) || !faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
6511
- respond(code, body2, headers);
6512
- return;
6513
- }
6514
- this.faultActions++;
6515
- this.record(service.name, "fault", target, `slow-response: ${operation} applied; response delayed ${fault.delayMs}ms`);
6516
- this.keyed(requestKey);
6517
- const timer = setTimeout(() => {
6518
- this.timers.delete(timer);
6519
- if (epoch === this.epoch) respond(code, body2, headers);
6520
- }, fault.delayMs);
6521
- this.timers.add(timer);
6522
- };
6523
- const darkFault = () => {
6524
- if (!fault || !faultOrdinalsFor || fault.type !== "blackhole" && fault.type !== "server-error") return "none";
6525
- const target = normalPath(req.url ?? "/", req.method);
6526
- if (!matchesFault(target)) return "none";
6527
- const ordinal = this.candidateIndex(faultKey);
6528
- if (!faultOrdinalsFor.includes(ordinal)) return "none";
6529
- this.faultActions++;
6530
- return fault.type;
6531
- };
6532
- try {
6533
- const anyCredential = !!this.options.lenientModelAuth && (service.adapter === "openai" || service.adapter === "anthropic");
6534
- 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))) {
6535
- 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(", ")})`);
6536
- respond(401, { error: "invalid_test_credential" });
6537
- return;
6538
- }
6539
- if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
6540
- respond(429, { error: "world_capacity" });
6541
- return;
6542
- }
6543
- const darkness = darkFault();
6544
- if (darkness === "blackhole") {
6545
- 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"})`);
6546
- this.keyed(requestKey);
6547
- return;
6548
- }
6549
- if (darkness === "server-error") {
6550
- const windowMs = fault.windowMs ?? 0;
6551
- const delay2 = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
6552
- this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay2}ms; nothing committed (${req.method ?? "request"})`);
6553
- this.keyed(requestKey);
6554
- const respond500 = () => respond(500, { error: { type: "api_error", message: "server_error fault" } });
6555
- if (delay2 <= 0) {
6556
- respond500();
7102
+ };
7103
+ const matchesFault = (target) => adapterService ? target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path) : target === fault.path;
7104
+ const requestKey = req.headers["idempotency-key"];
7105
+ const respondSlowly = (target, operation, code, body2, headers) => {
7106
+ if (fault?.type !== "slow-response" || !faultOrdinalsFor || !matchesFault(target) || !faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
7107
+ respond(code, body2, headers);
6557
7108
  return;
6558
7109
  }
7110
+ this.faultActions++;
7111
+ this.record(service.name, "fault", target, `slow-response: ${operation} applied; response delayed ${fault.delayMs}ms`);
7112
+ this.keyed(requestKey);
6559
7113
  const timer = setTimeout(() => {
6560
7114
  this.timers.delete(timer);
6561
- if (epoch === this.epoch) respond500();
6562
- }, delay2);
7115
+ if (epoch === this.epoch) respond(code, body2, headers);
7116
+ }, fault.delayMs);
6563
7117
  this.timers.add(timer);
6564
- return;
6565
- }
6566
- const url = new URL(req.url ?? "/", "http://localhost");
6567
- let path2 = url.pathname;
6568
- if (service.adapter === "composio" && [...url.searchParams.keys()].some((key3) => url.searchParams.getAll(key3).length !== 1)) {
6569
- this.rejectUnsupported(service.name, req.method ?? "", path2, "Repeated query parameters are unsupported");
6570
- respond(501, restUnsupportedBody("composio"));
6571
- return;
6572
- }
6573
- if (service.adapter === "google-oauth" && url.search) {
6574
- this.rejectUnsupported(service.name, req.method ?? "", path2, "OAuth token query parameters are unsupported");
6575
- respond(501, restUnsupportedBody("google-oauth"));
6576
- return;
6577
- }
6578
- const slack = service.adapter === "slack";
6579
- const slackMethod = path2.replace(/^\/api\//, "");
6580
- let payload, rawBody;
6581
- if (["POST", "PUT", "PATCH"].includes(req.method ?? "")) {
6582
- const chunks = [];
6583
- let bytes = 0;
6584
- for await (const chunk of req) {
6585
- bytes += chunk.length;
6586
- if (bytes > 1024 * 1024) {
6587
- respond(413, { error: "body_too_large" });
7118
+ };
7119
+ const darkFault = () => {
7120
+ if (!fault || !faultOrdinalsFor || fault.type !== "blackhole" && fault.type !== "server-error") return "none";
7121
+ const target = normalPath(req.url ?? "/", req.method);
7122
+ if (!matchesFault(target)) return "none";
7123
+ const ordinal = this.candidateIndex(faultKey);
7124
+ if (!faultOrdinalsFor.includes(ordinal)) return "none";
7125
+ this.faultActions++;
7126
+ return fault.type;
7127
+ };
7128
+ try {
7129
+ const anyCredential = !!this.options.lenientModelAuth && (service.adapter === "openai" || service.adapter === "anthropic");
7130
+ 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))) {
7131
+ 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(", ")})`);
7132
+ respond(401, { error: "invalid_test_credential" });
7133
+ return;
7134
+ }
7135
+ if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
7136
+ respond(429, { error: "world_capacity" });
7137
+ return;
7138
+ }
7139
+ const darkness = darkFault();
7140
+ if (darkness === "blackhole") {
7141
+ 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"})`);
7142
+ this.keyed(requestKey);
7143
+ return;
7144
+ }
7145
+ if (darkness === "server-error") {
7146
+ const windowMs = fault.windowMs ?? 0;
7147
+ const delay2 = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
7148
+ this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay2}ms; nothing committed (${req.method ?? "request"})`);
7149
+ this.keyed(requestKey);
7150
+ const respond500 = () => respond(500, { error: { type: "api_error", message: "server_error fault" } });
7151
+ if (delay2 <= 0) {
7152
+ respond500();
6588
7153
  return;
6589
7154
  }
6590
- chunks.push(Buffer.from(chunk));
7155
+ const timer = setTimeout(() => {
7156
+ this.timers.delete(timer);
7157
+ if (epoch === this.epoch) respond500();
7158
+ }, delay2);
7159
+ this.timers.add(timer);
7160
+ return;
7161
+ }
7162
+ const url = new URL(req.url ?? "/", "http://localhost");
7163
+ let path2 = url.pathname;
7164
+ if (service.adapter === "composio" && [...url.searchParams.keys()].some((key3) => url.searchParams.getAll(key3).length !== 1)) {
7165
+ this.rejectUnsupported(service.name, req.method ?? "", path2, "Repeated query parameters are unsupported");
7166
+ respond(501, restUnsupportedBody("composio"));
7167
+ return;
7168
+ }
7169
+ if (service.adapter === "google-oauth" && url.search) {
7170
+ this.rejectUnsupported(service.name, req.method ?? "", path2, "OAuth token query parameters are unsupported");
7171
+ respond(501, restUnsupportedBody("google-oauth"));
7172
+ return;
6591
7173
  }
6592
- const text3 = Buffer.concat(chunks).toString("utf8");
6593
- let parsed;
6594
- const mode = generated?.bodyMode(req.headers["content-type"]);
6595
- if ((enterprise || generated) && !text3.trim()) parsed = {};
6596
- else if (mode === "form") {
6597
- const form = new URLSearchParams(text3);
6598
- parsed = {};
6599
- for (const key3 of new Set(form.keys())) {
6600
- const all = form.getAll(key3);
6601
- parsed[key3] = all.length > 1 ? all : all[0];
7174
+ const slack = service.adapter === "slack";
7175
+ const slackMethod = path2.replace(/^\/api\//, "");
7176
+ let payload, rawBody;
7177
+ if (["POST", "PUT", "PATCH"].includes(req.method ?? "")) {
7178
+ const chunks = [];
7179
+ let bytes = 0;
7180
+ for await (const chunk of req) {
7181
+ bytes += chunk.length;
7182
+ if (bytes > 1024 * 1024) {
7183
+ respond(413, { error: "body_too_large" });
7184
+ return;
7185
+ }
7186
+ chunks.push(Buffer.from(chunk));
6602
7187
  }
6603
- } else if (mode === "raw") {
6604
- rawBody = text3;
6605
- parsed = {};
6606
- } else if (service.adapter === "gmail" && /^multipart\/mixed\b/i.test(String(req.headers["content-type"] ?? ""))) {
6607
- rawBody = text3;
6608
- parsed = {};
6609
- } else if (service.adapter === "gmail" && /^multipart\/related\b/i.test(String(req.headers["content-type"] ?? ""))) {
6610
- rawBody = text3;
6611
- parsed = Object.fromEntries(url.searchParams);
6612
- } else if (service.adapter === "upstash-redis") {
6613
- rawBody = text3;
6614
- parsed = {};
6615
- } else if (service.adapter === "gmail" && !text3.trim()) parsed = {};
6616
- else if (service.adapter === "google-oauth") {
6617
- if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
6618
- respond(400, { error: "invalid_request" });
7188
+ const text3 = Buffer.concat(chunks).toString("utf8");
7189
+ let parsed;
7190
+ const mode = generated?.bodyMode(req.headers["content-type"]);
7191
+ if ((enterprise || generated) && !text3.trim()) parsed = {};
7192
+ else if (mode === "form") {
7193
+ const form = new URLSearchParams(text3);
7194
+ parsed = {};
7195
+ for (const key3 of new Set(form.keys())) {
7196
+ const all = form.getAll(key3);
7197
+ parsed[key3] = all.length > 1 ? all : all[0];
7198
+ }
7199
+ } else if (mode === "raw") {
7200
+ rawBody = text3;
7201
+ parsed = {};
7202
+ } else if (service.adapter === "gmail" && /^multipart\/mixed\b/i.test(String(req.headers["content-type"] ?? ""))) {
7203
+ rawBody = text3;
7204
+ parsed = {};
7205
+ } else if (service.adapter === "gmail" && /^multipart\/related\b/i.test(String(req.headers["content-type"] ?? ""))) {
7206
+ rawBody = text3;
7207
+ parsed = Object.fromEntries(url.searchParams);
7208
+ } else if (service.adapter === "upstash-redis") {
7209
+ rawBody = text3;
7210
+ parsed = {};
7211
+ } else if (service.adapter === "gmail" && !text3.trim()) parsed = {};
7212
+ else if (service.adapter === "google-oauth") {
7213
+ if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
7214
+ respond(400, { error: "invalid_request" });
7215
+ return;
7216
+ }
7217
+ const form = new URLSearchParams(text3);
7218
+ if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
7219
+ respond(400, { error: "invalid_request" });
7220
+ return;
7221
+ }
7222
+ parsed = Object.fromEntries(form);
7223
+ } else try {
7224
+ 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);
7225
+ } catch {
7226
+ respond(400, { error: "expected_json_object" });
6619
7227
  return;
6620
7228
  }
6621
- const form = new URLSearchParams(text3);
6622
- if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
6623
- respond(400, { error: "invalid_request" });
7229
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
7230
+ respond(400, { error: "expected_json_object" });
6624
7231
  return;
6625
7232
  }
6626
- parsed = Object.fromEntries(form);
6627
- } else try {
6628
- 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);
6629
- } catch {
6630
- respond(400, { error: "expected_json_object" });
6631
- return;
7233
+ payload = parsed;
6632
7234
  }
6633
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6634
- respond(400, { error: "expected_json_object" });
7235
+ if (epoch !== this.epoch) {
7236
+ respond(409, { error: "world_reset" });
6635
7237
  return;
6636
7238
  }
6637
- payload = parsed;
6638
- }
6639
- if (epoch !== this.epoch) {
6640
- respond(409, { error: "world_reset" });
6641
- return;
6642
- }
6643
- if (generated && !payload && ["PUT", "DELETE"].includes(req.method ?? "")) payload = {};
6644
- if (service.adapter === "stripe" || restAdapter || enterprise || generated) {
6645
- const params = payload ?? Object.fromEntries(url.searchParams);
6646
- const keyHeader2 = req.headers["idempotency-key"] ?? (enterprise === "netsuite" ? req.headers["x-netsuite-idempotency-key"] : void 0);
6647
- const key3 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path2}:${keyHeader2}` : void 0;
6648
- const signature2 = JSON.stringify(params);
6649
- const previous2 = key3 ? keys.get(key3) : void 0;
6650
- if (previous2) {
6651
- if (previous2.body !== signature2) {
6652
- respond(400, { error: { type: "idempotency_error", message: "Keys for idempotent requests can only be used with the same parameters" } });
7239
+ if (generated && !payload && ["PUT", "DELETE"].includes(req.method ?? "")) payload = {};
7240
+ if (service.adapter === "stripe" || restAdapter || enterprise || generated) {
7241
+ const params = payload ?? Object.fromEntries(url.searchParams);
7242
+ const keyHeader2 = req.headers["idempotency-key"] ?? (enterprise === "netsuite" ? req.headers["x-netsuite-idempotency-key"] : void 0);
7243
+ const key3 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path2}:${keyHeader2}` : void 0;
7244
+ const signature2 = JSON.stringify(params);
7245
+ const previous2 = key3 ? keys.get(key3) : void 0;
7246
+ if (previous2) {
7247
+ if (previous2.body !== signature2) {
7248
+ respond(400, { error: { type: "idempotency_error", message: "Keys for idempotent requests can only be used with the same parameters" } });
7249
+ return;
7250
+ }
7251
+ this.record(service.name, "replay", path2, "same-key response replay", previous2.record);
7252
+ this.keyed(keyHeader2);
7253
+ respondSlowly(path2, "replay", previous2.status ?? 200, previous2.record, previous2.headers);
6653
7254
  return;
6654
7255
  }
6655
- this.record(service.name, "replay", path2, "same-key response replay", previous2.record);
6656
- this.keyed(keyHeader2);
6657
- respondSlowly(path2, "replay", previous2.status ?? 200, previous2.record, previous2.headers);
6658
- return;
6659
- }
6660
- const query = Object.fromEntries(url.searchParams);
6661
- 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);
6662
- const headers = (r) => "headers" in r ? r.headers : void 0;
6663
- const result2 = invoke(this.events.length + 1);
6664
- if (!result2) {
6665
- this.rejectUnsupported(service.name, req.method ?? "", path2, `unsupported ${service.adapter} operation or parameters`);
6666
- 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 });
7256
+ const query = Object.fromEntries(url.searchParams);
7257
+ 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);
7258
+ const headers = (r) => "headers" in r ? r.headers : void 0;
7259
+ const result2 = invoke(this.events.length + 1);
7260
+ if (!result2) {
7261
+ this.rejectUnsupported(service.name, req.method ?? "", path2, `unsupported ${service.adapter} operation or parameters`);
7262
+ 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 });
7263
+ return;
7264
+ }
7265
+ if ("unsupportedReason" in result2 && result2.unsupportedReason) {
7266
+ this.rejectUnsupported(service.name, req.method ?? "", path2, String(result2.unsupportedReason));
7267
+ respond(result2.status, result2.body);
7268
+ return;
7269
+ }
7270
+ if (result2.operation) {
7271
+ this.record(service.name, result2.operation, result2.collection, path2, "record" in result2 ? result2.record : result2.body);
7272
+ this.keyed(keyHeader2);
7273
+ }
7274
+ 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) } : {} });
7275
+ const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result2.operation === "write" && !key3 && matchesFault(result2.collection);
7276
+ const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
7277
+ const pushes = (r) => "deliveries" in r ? [...r.deliveries ?? []] : [];
7278
+ const deliveries = pushes(result2);
7279
+ if (duplicate2) {
7280
+ const second = invoke(this.events.length + 1);
7281
+ if (second?.operation === "write") {
7282
+ deliveries.push(...pushes(second));
7283
+ this.record(service.name, second.operation, second.collection, path2, "record" in second ? second.record : second.body);
7284
+ this.faultActions++;
7285
+ this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result2.collection})`);
7286
+ } else if (second) {
7287
+ this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
7288
+ respond(second.status, second.body, headers(second));
7289
+ if (deliveries.length) this.push(service.name, deliveries, epoch);
7290
+ return;
7291
+ }
7292
+ }
7293
+ if (!this.fired && result2.operation === "write" && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === result2.collection) {
7294
+ this.fired = true;
7295
+ this.faultActions++;
7296
+ this.record(service.name, "fault", result2.collection, `write committed; response delayed ${fault.delayMs}ms`);
7297
+ this.keyed(keyHeader2);
7298
+ const timer = setTimeout(() => {
7299
+ this.timers.delete(timer);
7300
+ respond(result2.status, result2.body, headers(result2));
7301
+ }, fault.delayMs);
7302
+ this.timers.add(timer);
7303
+ } else respondSlowly(result2.collection, result2.operation ?? "request", result2.status, result2.body, headers(result2));
7304
+ if (deliveries.length) this.push(service.name, deliveries, epoch);
6667
7305
  return;
6668
7306
  }
6669
- if (result2.operation) {
6670
- this.record(service.name, result2.operation, result2.collection, path2, "record" in result2 ? result2.record : result2.body);
6671
- this.keyed(keyHeader2);
6672
- }
6673
- 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) } : {} });
6674
- const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result2.operation === "write" && !key3 && matchesFault(result2.collection);
6675
- const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
6676
- const pushes = (r) => "deliveries" in r ? [...r.deliveries ?? []] : [];
6677
- const deliveries = pushes(result2);
6678
- if (duplicate2) {
6679
- const second = invoke(this.events.length + 1);
6680
- if (second?.operation === "write") {
6681
- deliveries.push(...pushes(second));
6682
- this.record(service.name, second.operation, second.collection, path2, "record" in second ? second.record : second.body);
6683
- this.faultActions++;
6684
- this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result2.collection})`);
6685
- } else if (second) {
6686
- this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
6687
- respond(second.status, second.body, headers(second));
6688
- if (deliveries.length) this.push(service.name, deliveries, epoch);
7307
+ if (slack) {
7308
+ const params = payload ?? Object.fromEntries(url.searchParams);
7309
+ const allowed = slackMethod === "chat.postMessage" ? ["channel", "text"] : slackMethod === "conversations.history" ? ["channel"] : [];
7310
+ if (Object.keys(params).some((k) => !allowed.includes(k))) {
7311
+ this.rejectUnsupported(service.name, req.method ?? "", url.pathname, `unsupported parameters for ${slackMethod}`);
7312
+ respond(501, { ok: false, error: "unsupported_parameters", forwardedToProduction: false });
7313
+ return;
7314
+ }
7315
+ if (slackMethod === "chat.postMessage" && req.method === "POST") path2 = "/messages";
7316
+ else if (slackMethod === "conversations.history" && ["GET", "POST"].includes(req.method ?? "")) path2 = "/messages";
7317
+ else if (slackMethod === "conversations.list" && ["GET", "POST"].includes(req.method ?? "")) path2 = "/channels";
7318
+ else {
7319
+ this.rejectUnsupported(service.name, req.method ?? "", url.pathname, "unsupported operation");
7320
+ respond(501, { ok: false, error: "unsupported_operation", forwardedToProduction: false });
6689
7321
  return;
6690
7322
  }
6691
7323
  }
6692
- if (!this.fired && result2.operation === "write" && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === result2.collection) {
6693
- this.fired = true;
6694
- this.faultActions++;
6695
- this.record(service.name, "fault", result2.collection, `write committed; response delayed ${fault.delayMs}ms`);
6696
- this.keyed(keyHeader2);
6697
- const timer = setTimeout(() => {
6698
- this.timers.delete(timer);
6699
- respond(result2.status, result2.body, headers(result2));
6700
- }, fault.delayMs);
6701
- this.timers.add(timer);
6702
- } else respondSlowly(result2.collection, result2.operation ?? "request", result2.status, result2.body, headers(result2));
6703
- if (deliveries.length) this.push(service.name, deliveries, epoch);
6704
- return;
6705
- }
6706
- if (slack) {
6707
- const params = payload ?? Object.fromEntries(url.searchParams);
6708
- const allowed = slackMethod === "chat.postMessage" ? ["channel", "text"] : slackMethod === "conversations.history" ? ["channel"] : [];
6709
- if (Object.keys(params).some((k) => !allowed.includes(k))) {
6710
- this.rejectUnsupported(service.name, req.method ?? "", url.pathname, `unsupported parameters for ${slackMethod}`);
6711
- respond(501, { ok: false, error: "unsupported_parameters", forwardedToProduction: false });
7324
+ if (!Object.hasOwn(data, path2) || !["GET", "POST"].includes(req.method ?? "")) {
7325
+ this.rejectUnsupported(service.name, req.method ?? "", path2, "unsupported operation");
7326
+ respond(501, { error: "unsupported_operation", forwardedToProduction: false });
6712
7327
  return;
6713
7328
  }
6714
- if (slackMethod === "chat.postMessage" && req.method === "POST") path2 = "/messages";
6715
- else if (slackMethod === "conversations.history" && ["GET", "POST"].includes(req.method ?? "")) path2 = "/messages";
6716
- else if (slackMethod === "conversations.list" && ["GET", "POST"].includes(req.method ?? "")) path2 = "/channels";
6717
- else {
6718
- this.rejectUnsupported(service.name, req.method ?? "", url.pathname, "unsupported operation");
6719
- respond(501, { ok: false, error: "unsupported_operation", forwardedToProduction: false });
7329
+ if (req.method === "GET" || slack && slackMethod !== "chat.postMessage") {
7330
+ this.record(service.name, "read", path2, `${data[path2].length} records`);
7331
+ if (slack && path2 === "/channels") respondSlowly(path2, "read", 200, { ok: true, channels: data[path2], response_metadata: { next_cursor: "" } });
7332
+ else if (slack) {
7333
+ const channel = payload?.channel ?? url.searchParams.get("channel");
7334
+ if (!data["/channels"].some((c) => c.id === channel)) respond(200, { ok: false, error: "channel_not_found" });
7335
+ else respondSlowly(path2, "read", 200, { ok: true, messages: data[path2].filter((m) => m.channel === channel), has_more: false });
7336
+ } else respondSlowly(path2, "read", 200, { data: data[path2] });
6720
7337
  return;
6721
7338
  }
6722
- }
6723
- if (!Object.hasOwn(data, path2) || !["GET", "POST"].includes(req.method ?? "")) {
6724
- this.rejectUnsupported(service.name, req.method ?? "", path2, "unsupported operation");
6725
- respond(501, { error: "unsupported_operation", forwardedToProduction: false });
6726
- return;
6727
- }
6728
- if (req.method === "GET" || slack && slackMethod !== "chat.postMessage") {
6729
- this.record(service.name, "read", path2, `${data[path2].length} records`);
6730
- if (slack && path2 === "/channels") respondSlowly(path2, "read", 200, { ok: true, channels: data[path2], response_metadata: { next_cursor: "" } });
6731
- else if (slack) {
6732
- const channel = payload?.channel ?? url.searchParams.get("channel");
6733
- if (!data["/channels"].some((c) => c.id === channel)) respond(200, { ok: false, error: "channel_not_found" });
6734
- else respondSlowly(path2, "read", 200, { ok: true, messages: data[path2].filter((m) => m.channel === channel), has_more: false });
6735
- } else respondSlowly(path2, "read", 200, { data: data[path2] });
6736
- return;
6737
- }
6738
- const body2 = payload;
6739
- if (slack) {
6740
- const message = body2;
6741
- if (!data["/channels"].some((c) => c.id === message.channel)) {
6742
- respond(200, { ok: false, error: "channel_not_found" });
6743
- return;
7339
+ const body2 = payload;
7340
+ if (slack) {
7341
+ const message = body2;
7342
+ const channels = data["/channels"];
7343
+ const recipient = message.channel;
7344
+ let destination = channels.find((channel) => channel.id === recipient);
7345
+ if (typeof recipient === "string" && /^[UW][A-Z0-9]+$/.test(recipient)) {
7346
+ const user = data["/users"]?.find((row2) => row2.id === recipient);
7347
+ destination = channels.find((channel) => channel.is_im === true && channel.user === recipient);
7348
+ if (user?.deleted === true || user?.dmAllowed === false) destination = void 0;
7349
+ else if (!destination && user) {
7350
+ if (channels.length >= 1e4) {
7351
+ respond(429, { error: "world_capacity" });
7352
+ return;
7353
+ }
7354
+ const id = slackDirectMessageId(recipient);
7355
+ destination = { id, is_im: true, user: recipient };
7356
+ if (channels.some((channel) => channel.id === id)) {
7357
+ respond(409, { error: "channel_conflict" });
7358
+ return;
7359
+ }
7360
+ }
7361
+ }
7362
+ if (!destination) {
7363
+ respond(200, { ok: false, error: "channel_not_found" });
7364
+ return;
7365
+ }
7366
+ if (typeof message.text !== "string" || !message.text) {
7367
+ respond(200, { ok: false, error: "no_text" });
7368
+ return;
7369
+ }
7370
+ if (data[path2].length >= 1e4 || this.events.length >= 5e4) {
7371
+ respond(429, { error: "world_capacity" });
7372
+ return;
7373
+ }
7374
+ if (!channels.includes(destination)) {
7375
+ channels.push(destination);
7376
+ this.record(service.name, "write", "/channels", String(destination.id), destination);
7377
+ }
7378
+ message.channel = destination.id;
6744
7379
  }
6745
- if (typeof message.text !== "string" || !message.text) {
6746
- respond(200, { ok: false, error: "no_text" });
7380
+ if (data[path2].length >= 1e4 || this.events.length >= 5e4) {
7381
+ respond(429, { error: "world_capacity" });
6747
7382
  return;
6748
7383
  }
6749
- }
6750
- if (data[path2].length >= 1e4 || this.events.length >= 5e4) {
6751
- respond(429, { error: "world_capacity" });
6752
- return;
6753
- }
6754
- const keyHeader = slack ? void 0 : req.headers["idempotency-key"];
6755
- const key2 = typeof keyHeader === "string" ? `${path2}:${keyHeader}` : void 0;
6756
- const signature = JSON.stringify(body2);
6757
- const previous = key2 ? keys.get(key2) : void 0;
6758
- if (previous) {
6759
- if (previous.body !== signature) {
6760
- respond(409, { error: "idempotency_conflict" });
7384
+ const keyHeader = slack ? void 0 : req.headers["idempotency-key"];
7385
+ const key2 = typeof keyHeader === "string" ? `${path2}:${keyHeader}` : void 0;
7386
+ const signature = JSON.stringify(body2);
7387
+ const previous = key2 ? keys.get(key2) : void 0;
7388
+ if (previous) {
7389
+ if (previous.body !== signature) {
7390
+ respond(409, { error: "idempotency_conflict" });
7391
+ return;
7392
+ }
7393
+ this.record(service.name, "replay", path2, "same-key response replay", previous.record);
7394
+ this.keyed(keyHeader);
7395
+ respondSlowly(path2, "replay", 200, previous.record);
6761
7396
  return;
6762
7397
  }
6763
- this.record(service.name, "replay", path2, "same-key response replay", previous.record);
6764
- this.keyed(keyHeader);
6765
- respondSlowly(path2, "replay", 200, previous.record);
6766
- return;
6767
- }
6768
- const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path2 && !key2 && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
6769
- if (duplicate) this.faultActions++;
6770
- let index = data[path2].length + 1;
6771
- while (data[path2].some((r) => r.id === `${service.name}_${index}`)) index++;
6772
- const row = { ...body2, id: `${service.name}_${index}` };
6773
- if (slack) row.ts = `${index}.000001`;
6774
- const reply = slack ? { ok: true, channel: row.channel, ts: row.ts, message: row } : row;
6775
- data[path2].push(row);
6776
- if (key2) keys.set(key2, { body: signature, record: row });
6777
- this.record(service.name, "write", path2, String(row.id), row);
6778
- this.keyed(keyHeader);
6779
- if (duplicate) {
6780
- index++;
7398
+ const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path2 && !key2 && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
7399
+ if (duplicate) this.faultActions++;
7400
+ let index = data[path2].length + 1;
6781
7401
  while (data[path2].some((r) => r.id === `${service.name}_${index}`)) index++;
6782
- const second = { ...body2, id: `${service.name}_${index}` };
6783
- if (slack) second.ts = `${index}.000001`;
6784
- data[path2].push(second);
6785
- this.record(service.name, "write", path2, String(second.id), second);
6786
- this.record(service.name, "fault", fault.path, `duplicate-write: one write committed as two records (${row.id}, ${second.id})`);
6787
- }
6788
- const faultResponse = slack ? 200 : 201;
6789
- if (!this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === path2) {
6790
- this.fired = true;
6791
- this.faultActions++;
6792
- this.record(service.name, "fault", path2, `write committed; response delayed ${fault.delayMs}ms`);
7402
+ const row = { ...body2, id: `${service.name}_${index}` };
7403
+ if (slack) row.ts = `${index}.000001`;
7404
+ const reply = slack ? { ok: true, channel: row.channel, ts: row.ts, message: row } : row;
7405
+ data[path2].push(row);
7406
+ if (key2) keys.set(key2, { body: signature, record: row });
7407
+ this.record(service.name, "write", path2, String(row.id), row);
6793
7408
  this.keyed(keyHeader);
6794
- const timer = setTimeout(() => {
6795
- this.timers.delete(timer);
6796
- respond(faultResponse, reply);
6797
- }, fault.delayMs);
6798
- this.timers.add(timer);
6799
- } else respondSlowly(path2, "write", faultResponse, reply);
6800
- } catch {
6801
- respond(500, { error: "world_request_error" });
6802
- }
6803
- })));
7409
+ if (duplicate) {
7410
+ index++;
7411
+ while (data[path2].some((r) => r.id === `${service.name}_${index}`)) index++;
7412
+ const second = { ...body2, id: `${service.name}_${index}` };
7413
+ if (slack) second.ts = `${index}.000001`;
7414
+ data[path2].push(second);
7415
+ this.record(service.name, "write", path2, String(second.id), second);
7416
+ this.record(service.name, "fault", fault.path, `duplicate-write: one write committed as two records (${row.id}, ${second.id})`);
7417
+ }
7418
+ const faultResponse = slack ? 200 : 201;
7419
+ if (!this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === path2) {
7420
+ this.fired = true;
7421
+ this.faultActions++;
7422
+ this.record(service.name, "fault", path2, `write committed; response delayed ${fault.delayMs}ms`);
7423
+ this.keyed(keyHeader);
7424
+ const timer = setTimeout(() => {
7425
+ this.timers.delete(timer);
7426
+ respond(faultResponse, reply);
7427
+ }, fault.delayMs);
7428
+ this.timers.add(timer);
7429
+ } else respondSlowly(path2, "write", faultResponse, reply);
7430
+ } catch {
7431
+ respond(500, { error: "world_request_error" });
7432
+ }
7433
+ }));
7434
+ });
6804
7435
  server.requestTimeout = 1e4;
6805
7436
  await new Promise((resolve13, reject) => {
6806
7437
  server.once("error", reject);
@@ -6814,6 +7445,13 @@ var init_http_world = __esm({
6814
7445
  /** Environment each pack service's credential door issued (STRIPE_SECRET_KEY…), for the application's process. */
6815
7446
  packEnv = /* @__PURE__ */ Object.create(null);
6816
7447
  packRoots = [];
7448
+ /** Per service: 1 while a call the world makes is in flight and no envelope has been captured yet, 2 once one has. */
7449
+ causing = /* @__PURE__ */ Object.create(null);
7450
+ lastEnvelope = /* @__PURE__ */ Object.create(null);
7451
+ socketServers = [];
7452
+ rawServers = [];
7453
+ /** Each pack service's plain-TCP port for clients that open their own TLS sockets (see startPack). */
7454
+ packTcp = /* @__PURE__ */ Object.create(null);
6817
7455
  /**
6818
7456
  * A twin pack served behind this world: the run token is checked and swapped for the credential the pack issued,
6819
7457
  * seeded fault schedules apply around the pack's own handler, and every action the pack logs becomes evidence — writes
@@ -6828,10 +7466,11 @@ var init_http_world = __esm({
6828
7466
  const writeSeedLog = async (dir, text3) => {
6829
7467
  if (!text3) return;
6830
7468
  await mkdir3(join11(dir, ".volter/world", meta2.logService), { recursive: true });
6831
- await writeFile5(join11(dir, ".volter/world", meta2.logService, "actions.jsonl"), text3);
7469
+ await writeFile6(join11(dir, ".volter/world", meta2.logService, "actions.jsonl"), text3);
6832
7470
  };
6833
7471
  let tenant = {}, credential;
6834
- if (meta2.logService && meta2.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account)) {
7472
+ let doorLines = "";
7473
+ if (meta2.logService && meta2.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account || service.doorRecords?.length)) {
6835
7474
  const probe = await mkdtemp5(join11(tmpdir5(), `agenttwin-pack-${name}-probe-`));
6836
7475
  try {
6837
7476
  await writeSeedLog(probe, worldSeed);
@@ -6840,37 +7479,76 @@ var init_http_world = __esm({
6840
7479
  const probed = new PackActionTail(join11(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
6841
7480
  tenant = tenantFields(probed);
6842
7481
  credential = credentialAction(probed);
7482
+ for (const rec of service.doorRecords ?? []) {
7483
+ const own = probed.filter((a) => a.subject?.type === rec.type);
7484
+ const original = own[0]?.subject?.id;
7485
+ if (!original) continue;
7486
+ 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("");
7487
+ }
6843
7488
  } finally {
6844
7489
  await rm5(probe, { recursive: true, force: true });
6845
7490
  }
6846
7491
  }
6847
7492
  const account = credential && service.account ? JSON.stringify({ ...credential, id: `${credential.id ?? "credential"}:preset`, fields: { ...credential.fields, ...service.account } }) + "\n" : "";
6848
- const seeded = meta2.logService ? worldSeed + account + seedActions(meta2.logService, service.collections, new Date(twinNowMs(Date.now())).toISOString(), tenant) : "";
7493
+ const seeded = meta2.logService ? worldSeed + account + doorLines + seedActions(meta2.logService, service.collections, new Date(twinNowMs(Date.now())).toISOString(), tenant) : "";
6849
7494
  await writeSeedLog(root, seeded);
6850
7495
  const twin = await (await loadPack(name))({ root });
6851
7496
  const baseHost = meta2.hosts[0]?.host ?? `${name}.twin.test`;
6852
7497
  const log = new PackActionTail(join11(root, ".volter"));
6853
7498
  let issued = {};
6854
7499
  if (meta2.credentialDoor) {
6855
- const r = await twin(new Request(`https://${baseHost}${meta2.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta2.credentialDoor.body ?? {}) }));
6856
- if (r.ok) issued = await r.json();
6857
- else await r.arrayBuffer();
7500
+ const hosts = [...new Set(meta2.hosts.map((h) => h.host).filter((h) => !!h))];
7501
+ const door = (host) => twin(new Request(`https://${host}${meta2.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta2.credentialDoor.body ?? {}) }));
7502
+ for (const host of hosts.length ? hosts : [baseHost]) {
7503
+ let r = await door(host);
7504
+ if (r.status === 404 && meta2.credentialDoor.body && Object.keys(meta2.credentialDoor.body).length) {
7505
+ await r.arrayBuffer();
7506
+ 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 }) }));
7507
+ await made.arrayBuffer();
7508
+ r = await door(host);
7509
+ }
7510
+ if (r.ok) {
7511
+ issued = await r.json();
7512
+ break;
7513
+ }
7514
+ await r.arrayBuffer();
7515
+ if (r.status !== 404) break;
7516
+ }
6858
7517
  }
6859
7518
  const env = {};
6860
- for (const [envName, field] of Object.entries(meta2.credentialDoor?.fill ?? {})) if (typeof issued[field] === "string") env[envName] = issued[field];
7519
+ for (const [envName, field] of Object.entries(meta2.credentialDoor?.fill ?? {})) {
7520
+ if (field.startsWith("file:")) {
7521
+ const value = issued[field.slice(5)];
7522
+ if (value && typeof value === "object") {
7523
+ const file = join11(root, `${envName.toLowerCase()}.json`);
7524
+ await writeFile6(file, JSON.stringify(value, null, 2), { mode: 384 });
7525
+ env[envName] = file;
7526
+ }
7527
+ } else if (typeof issued[field] === "string") env[envName] = issued[field];
7528
+ }
6861
7529
  this.packEnv[service.name] = env;
6862
7530
  const primaryEnv = Object.keys(env).find((k) => /(SECRET|API|PRIVATE|ACCESS)_?(KEY|TOKEN)$|_TOKEN$|_KEY$/.test(k) && !/PUBLISHABLE|PUBLIC|WEBHOOK|SIGNING|ENDPOINT/.test(k));
6863
7531
  const primary = primaryEnv ? env[primaryEnv] : void 0;
6864
7532
  const authHeaders = () => primary ? { authorization: `Bearer ${primary}` } : {};
7533
+ const issuedValues = Object.values(env).filter((v) => v.length >= 12);
7534
+ const appCredential = (value) => {
7535
+ const v = Array.isArray(value) ? value[0] : value;
7536
+ return v && issuedValues.some((i) => v === `Bearer ${i}`) ? v : void 0;
7537
+ };
6865
7538
  const fault = this.spec.fault;
6866
7539
  const matchesFault = (target) => !!fault && (target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path));
6867
- const apply = (actions, method, path2, evidence) => {
7540
+ const apply = (actions, method, path2, evidence, byWorld = false) => {
6868
7541
  const wrote = [];
6869
7542
  for (const a of actions) {
6870
7543
  const type = a.subject?.type, id = a.subject?.id;
6871
7544
  if (!type || !id) continue;
6872
7545
  if (type === "_world_event_delivery") {
6873
- 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"}`);
7546
+ const f = a.fields ?? {}, eventType = typeof f.body === "string" ? /"type":"([^"]+)"/.exec(f.body)?.[1] ?? "event" : "event";
7547
+ const key2 = `${service.name}:${id}`;
7548
+ if (f.delivery_state === "queued" && typeof f.url === "string" && typeof f.body === "string" && f.headers && typeof f.headers === "object" && !this.sentWebhooks.has(key2)) {
7549
+ this.sentWebhooks.add(key2);
7550
+ this.sendWebhook(service.name, f.url, f.body, f.headers, eventType);
7551
+ } else if (evidence && !this.sentWebhooks.has(key2)) this.record(service.name, "webhook", String(f.url ?? ""), `queued ${eventType} for ${f.url ?? "endpoint"}`);
6874
7552
  continue;
6875
7553
  }
6876
7554
  if (type.startsWith("_")) continue;
@@ -6884,7 +7562,7 @@ var init_http_world = __esm({
6884
7562
  } else if (at >= 0) rows2[at] = row;
6885
7563
  else rows2.push(row);
6886
7564
  if (!evidence) continue;
6887
- const byApp = a.actor?.kind === "agent";
7565
+ const byApp = a.actor?.kind === "agent" && !byWorld;
6888
7566
  this.record(service.name, byApp ? "write" : "twin", collection, `${method} ${path2} \u2192 ${a.operation ?? type} ${id}${byApp ? "" : " (by the twin)"}`, row);
6889
7567
  if (byApp) wrote.push(collection);
6890
7568
  }
@@ -6906,146 +7584,258 @@ var init_http_world = __esm({
6906
7584
  chain = run3.then(() => void 0, () => void 0);
6907
7585
  return run3;
6908
7586
  };
6909
- const server = createServer3((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
6910
- const epoch = this.epoch;
6911
- const send2 = (status, headers, body2) => {
6912
- if (!res.destroyed) {
6913
- res.writeHead(status, headers);
6914
- res.end(body2);
6915
- }
6916
- };
6917
- const later = (ms, fn) => {
6918
- const timer = setTimeout(() => {
6919
- this.timers.delete(timer);
6920
- if (epoch === this.epoch) fn();
6921
- }, ms);
6922
- this.timers.add(timer);
6923
- };
6924
- const respond = (status, headers, body2) => {
6925
- const ms = latencyMs();
6926
- if (ms <= 0) send2(status, headers, body2);
6927
- else later(ms, () => send2(status, headers, body2));
6928
- };
6929
- const json2 = (status, value) => respond(status, { "content-type": "application/json" }, Buffer.from(JSON.stringify(value)));
6930
- try {
6931
- const ours = req.headers.authorization === `Bearer ${token}` || req.headers["x-api-key"] === token || req.headers["x-agenttwin-token"] === token;
6932
- if (!ours) {
6933
- this.record(service.name, "auth-denied", req.url ?? "", "invalid test credential");
6934
- json2(401, { error: "invalid_test_credential" });
6935
- return;
6936
- }
6937
- if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
6938
- json2(429, { error: "world_capacity" });
6939
- return;
6940
- }
6941
- const url = new URL(req.url ?? "/", "http://localhost"), method = req.method ?? "GET", path2 = url.pathname;
6942
- const requestKey = req.headers["idempotency-key"];
6943
- if (fault && faultOrdinalsFor && (fault.type === "blackhole" || fault.type === "server-error") && matchesFault(path2) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
6944
- this.faultActions++;
6945
- if (fault.type === "blackhole") {
6946
- this.record(service.name, "fault", fault.path, `blackhole: request dropped; nothing committed (${method})`);
7587
+ const server = createServer3((req, res) => {
7588
+ if (req.headers["x-agenttwin-probe"] === "1") {
7589
+ this.probes++;
7590
+ res.once("close", () => {
7591
+ this.probes--;
7592
+ });
7593
+ }
7594
+ return withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
7595
+ const epoch = this.epoch;
7596
+ const send2 = (status, headers, body2) => {
7597
+ if (!res.destroyed) {
7598
+ res.writeHead(status, headers);
7599
+ res.end(body2);
7600
+ }
7601
+ };
7602
+ const later = (ms, fn) => {
7603
+ const timer = setTimeout(() => {
7604
+ this.timers.delete(timer);
7605
+ if (epoch === this.epoch) fn();
7606
+ }, ms);
7607
+ this.timers.add(timer);
7608
+ };
7609
+ const respond = (status, headers, body2) => {
7610
+ const ms = latencyMs();
7611
+ if (ms <= 0) send2(status, headers, body2);
7612
+ else later(ms, () => send2(status, headers, body2));
7613
+ };
7614
+ const json2 = (status, value) => respond(status, { "content-type": "application/json" }, Buffer.from(JSON.stringify(value)));
7615
+ try {
7616
+ const raw = req.socket.agenttwinRaw === true;
7617
+ const ours = raw || req.headers.authorization === `Bearer ${token}` || req.headers["x-api-key"] === token || req.headers["x-agenttwin-token"] === token;
7618
+ if (!ours) {
7619
+ this.record(service.name, "auth-denied", req.url ?? "", "invalid test credential");
7620
+ json2(401, { error: "invalid_test_credential" });
7621
+ return;
7622
+ }
7623
+ if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
7624
+ json2(429, { error: "world_capacity" });
7625
+ return;
7626
+ }
7627
+ const url = new URL(req.url ?? "/", "http://localhost"), method = req.method ?? "GET", path2 = url.pathname;
7628
+ if (path2 === "/_agenttwin/redeliver" && req.headers["x-agenttwin-token"] === token) {
7629
+ const last = this.lastEnvelope[service.name];
7630
+ if (!last) {
7631
+ json2(404, { ok: false, error: "nothing_delivered" });
7632
+ return;
7633
+ }
7634
+ const attempt = Number(last.envelope.retry_attempt ?? 0) + 1;
7635
+ const again = { ...last.envelope, envelope_id: createHash11("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" };
7636
+ last.send(JSON.stringify(again));
7637
+ this.record(service.name, "twin", path2, `redelivered ${String(last.envelope.type ?? "envelope")} (retry_attempt ${attempt}, as after a lost acknowledgment)`);
7638
+ json2(200, { ok: true, retry_attempt: attempt });
7639
+ return;
7640
+ }
7641
+ const workspace = req.headers["x-agenttwin-actor"] === "workspace" && req.headers["x-agenttwin-token"] === token;
7642
+ const requestKey = req.headers["idempotency-key"];
7643
+ if (!workspace && fault && faultOrdinalsFor && (fault.type === "blackhole" || fault.type === "server-error") && matchesFault(path2) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
7644
+ this.faultActions++;
7645
+ if (fault.type === "blackhole") {
7646
+ this.record(service.name, "fault", fault.path, `blackhole: request dropped; nothing committed (${method})`);
7647
+ this.keyed(requestKey);
7648
+ return;
7649
+ }
7650
+ const windowMs = fault.windowMs ?? 0;
7651
+ const delay2 = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
7652
+ this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay2}ms; nothing committed (${method})`);
6947
7653
  this.keyed(requestKey);
7654
+ const fail2 = () => json2(500, { error: { type: "api_error", message: "server_error fault" } });
7655
+ if (delay2 <= 0) fail2();
7656
+ else later(delay2, fail2);
6948
7657
  return;
6949
7658
  }
6950
- const windowMs = fault.windowMs ?? 0;
6951
- const delay2 = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
6952
- this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay2}ms; nothing committed (${method})`);
6953
- this.keyed(requestKey);
6954
- const fail2 = () => json2(500, { error: { type: "api_error", message: "server_error fault" } });
6955
- if (delay2 <= 0) fail2();
6956
- else later(delay2, fail2);
6957
- return;
6958
- }
6959
- const chunks = [];
6960
- let bytes = 0;
6961
- for await (const chunk of req) {
6962
- bytes += chunk.length;
6963
- if (bytes > 5 * 1024 * 1024) {
6964
- json2(413, { error: "body_too_large" });
7659
+ const chunks = [];
7660
+ let bytes = 0;
7661
+ for await (const chunk of req) {
7662
+ bytes += chunk.length;
7663
+ if (bytes > 5 * 1024 * 1024) {
7664
+ json2(413, { error: "body_too_large" });
7665
+ return;
7666
+ }
7667
+ chunks.push(Buffer.from(chunk));
7668
+ }
7669
+ const body2 = ["GET", "HEAD"].includes(method) ? void 0 : Buffer.concat(chunks);
7670
+ if (epoch !== this.epoch) {
7671
+ json2(409, { error: "world_reset" });
6965
7672
  return;
6966
7673
  }
6967
- chunks.push(Buffer.from(chunk));
6968
- }
6969
- const body2 = ["GET", "HEAD"].includes(method) ? void 0 : Buffer.concat(chunks);
6970
- if (epoch !== this.epoch) {
6971
- json2(409, { error: "world_reset" });
6972
- return;
6973
- }
6974
- let host = String(req.headers["x-agenttwin-original-host"] ?? baseHost);
6975
- if (name === "pinecone") {
6976
- const m = /^([a-z0-9-]+?)-[a-z0-9]+\.svc\.[a-z0-9.-]*pinecone\.io$/.exec(host);
6977
- const index = m && (data["/indexes"] ?? []).find((r) => r.name === m[1] && typeof r.host === "string");
6978
- if (index && index.host !== host) host = String(index.host);
6979
- }
6980
- const headers = new Headers();
6981
- 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);
6982
- if (headers.get("authorization") === `Bearer ${token}`) {
6983
- if (primary) headers.set("authorization", `Bearer ${primary}`);
6984
- else headers.delete("authorization");
6985
- }
6986
- if (headers.get("x-api-key") === token) {
6987
- if (primary) headers.set("x-api-key", primary);
6988
- else headers.delete("x-api-key");
6989
- }
6990
- const call2 = async () => {
6991
- const r = await twin(new Request(`https://${host}${req.url ?? "/"}`, { method, headers, ...body2 ? { body: body2 } : {} }));
6992
- return { status: r.status, headers: r.headers, bytes: Buffer.from(await r.arrayBuffer()), actions: log.drain() };
6993
- };
6994
- const first = await serialized(call2);
6995
- if (epoch !== this.epoch) return;
6996
- const wrote = apply(first.actions, method, path2, true);
6997
- let okFalse;
6998
- if (first.status < 300 && /json/.test(first.headers.get("content-type") ?? "")) try {
6999
- const parsed = JSON.parse(first.bytes.toString("utf8"));
7000
- if (parsed.ok === false) okFalse = [parsed.error, ...parsed.response_metadata?.messages ?? []].filter(Boolean).join(": ").slice(0, 240) || "ok: false";
7001
- } catch {
7002
- }
7003
- if (wrote.length) this.keyed(requestKey);
7004
- 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}`);
7005
- else if (okFalse) this.record(service.name, "rejected", path2, `${method} ${path2} \u2192 ${first.status} ok:false: ${okFalse}`);
7006
- else if (first.status >= 400) {
7007
- let reason = "";
7008
- try {
7674
+ if (this.postgrest && path2.startsWith("/rest/v1/")) {
7675
+ const r = await this.postgrest.handle({ method, url, headers: req.headers, body: body2 });
7676
+ 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)}` : ""}`);
7677
+ res.writeHead(r.status, r.headers);
7678
+ res.end(r.body);
7679
+ return;
7680
+ }
7681
+ let host = String(req.headers["x-agenttwin-original-host"] ?? (raw ? req.headers.host?.replace(/:\d+$/, "") : void 0) ?? baseHost);
7682
+ if (name === "pinecone") {
7683
+ const m = /^([a-z0-9-]+?)-[a-z0-9]+\.svc\.[a-z0-9.-]*pinecone\.io$/.exec(host);
7684
+ const index = m && (data["/indexes"] ?? []).find((r) => r.name === m[1] && typeof r.host === "string");
7685
+ if (index && index.host !== host) host = String(index.host);
7686
+ }
7687
+ const headers = new Headers();
7688
+ 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);
7689
+ const own = appCredential(req.headers["x-agenttwin-app-authorization"]);
7690
+ if (own) headers.set("authorization", own);
7691
+ else if (raw) {
7692
+ const given = headers.get("authorization");
7693
+ if (given && !appCredential(given) && /^Bearer /.test(given) && primary) headers.set("authorization", `Bearer ${primary}`);
7694
+ } else if (headers.get("authorization") === `Bearer ${token}`) {
7695
+ if (primary) headers.set("authorization", `Bearer ${primary}`);
7696
+ else headers.delete("authorization");
7697
+ }
7698
+ if (headers.get("x-api-key") === token) {
7699
+ if (primary) headers.set("x-api-key", primary);
7700
+ else headers.delete("x-api-key");
7701
+ }
7702
+ const call2 = async () => {
7703
+ const target2 = aliasRequest(name, host, req.url ?? "/");
7704
+ const model = compatibleModel(name, body2);
7705
+ const r = await twin(new Request(`https://${target2.host}${target2.url}`, { method, headers, ...model.body ? { body: model.body } : {} }));
7706
+ return { status: r.status, headers: r.headers, bytes: model.restore(Buffer.from(await r.arrayBuffer())), actions: log.drain() };
7707
+ };
7708
+ if (workspace && method !== "GET") this.causing[service.name] = 1;
7709
+ const first = await serialized(call2).finally(() => {
7710
+ if (workspace) this.causing[service.name] = 0;
7711
+ });
7712
+ if (epoch !== this.epoch) return;
7713
+ const recordedBefore = this.events.length;
7714
+ const wrote = apply(first.actions, method, path2, true, workspace);
7715
+ if (workspace) {
7716
+ const out2 = {};
7717
+ first.headers.forEach((v, k) => {
7718
+ if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out2[k] = v;
7719
+ });
7720
+ send2(first.status, out2, first.bytes);
7721
+ return;
7722
+ }
7723
+ let okFalse;
7724
+ if (first.status < 300 && /json/.test(first.headers.get("content-type") ?? "")) try {
7009
7725
  const parsed = JSON.parse(first.bytes.toString("utf8"));
7010
- const e = parsed.error ?? parsed;
7011
- reason = String(e.message ?? e.error_description ?? e.code ?? "").slice(0, 240);
7726
+ if (parsed.ok === false) okFalse = [parsed.error, ...parsed.response_metadata?.messages ?? []].filter(Boolean).join(": ").slice(0, 240) || "ok: false";
7012
7727
  } catch {
7013
- reason = first.bytes.toString("utf8").slice(0, 120);
7014
7728
  }
7015
- this.record(service.name, "rejected", path2, `${method} ${path2} \u2192 ${first.status}${reason ? `: ${reason}` : ""}`);
7016
- } else if (method === "GET") this.record(service.name, "read", path2, `${first.status}`);
7017
- const target = wrote[0];
7018
- if (target && fault?.type === "duplicate-write" && fault.service === service.name && !requestKey && matchesFault(target) && faultOrdinalsFor?.includes(this.candidateIndex(faultKey))) {
7019
- const second = await serialized(call2);
7020
- apply(second.actions, method, path2, true);
7021
- this.faultActions++;
7022
- this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${target})`);
7729
+ if (wrote.length) this.keyedSince(recordedBefore, requestKey);
7730
+ 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}`);
7731
+ else if (okFalse) this.record(service.name, "rejected", path2, `${method} ${path2} \u2192 ${first.status} ok:false: ${okFalse}`);
7732
+ else if (first.status >= 400) {
7733
+ let reason = "";
7734
+ try {
7735
+ const parsed = JSON.parse(first.bytes.toString("utf8"));
7736
+ const e = parsed.error ?? parsed;
7737
+ reason = String(e.message ?? e.error_description ?? e.code ?? "").slice(0, 240);
7738
+ } catch {
7739
+ reason = first.bytes.toString("utf8").slice(0, 120);
7740
+ }
7741
+ this.record(service.name, "rejected", path2, `${method} ${path2} \u2192 ${first.status}${reason ? `: ${reason}` : ""}`);
7742
+ } else if (method === "GET") this.record(service.name, "read", path2, `${first.status}`);
7743
+ const target = wrote.find(matchesFault) ?? wrote[0];
7744
+ if (target && fault?.type === "duplicate-write" && fault.service === service.name && !requestKey && matchesFault(target) && faultOrdinalsFor?.includes(this.candidateIndex(faultKey))) {
7745
+ const second = await serialized(call2);
7746
+ apply(second.actions, method, path2, true);
7747
+ this.faultActions++;
7748
+ this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${target})`);
7749
+ }
7750
+ const out = {};
7751
+ first.headers.forEach((v, k) => {
7752
+ if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out[k] = v;
7753
+ });
7754
+ if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && matchesFault(target)) {
7755
+ this.fired = true;
7756
+ this.faultActions++;
7757
+ this.record(service.name, "fault", target, `write committed; response delayed ${fault.delayMs}ms`);
7758
+ this.keyed(requestKey);
7759
+ later(fault.delayMs, () => send2(first.status, out, first.bytes));
7760
+ } else if (fault?.type === "slow-response" && faultOrdinalsFor && matchesFault(target ?? path2) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
7761
+ this.faultActions++;
7762
+ this.record(service.name, "fault", target ?? path2, `slow-response: ${target ? "write" : "request"} applied; response delayed ${fault.delayMs}ms`);
7763
+ this.keyed(requestKey);
7764
+ later(fault.delayMs, () => respond(first.status, out, first.bytes));
7765
+ } else respond(first.status, out, first.bytes);
7766
+ } catch {
7767
+ json2(500, { error: "world_request_error" });
7023
7768
  }
7024
- const out = {};
7025
- first.headers.forEach((v, k) => {
7026
- if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out[k] = v;
7027
- });
7028
- if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && matchesFault(target)) {
7029
- this.fired = true;
7030
- this.faultActions++;
7031
- this.record(service.name, "fault", target, `write committed; response delayed ${fault.delayMs}ms`);
7032
- this.keyed(requestKey);
7033
- later(fault.delayMs, () => send2(first.status, out, first.bytes));
7034
- } else if (fault?.type === "slow-response" && faultOrdinalsFor && matchesFault(target ?? path2) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
7035
- this.faultActions++;
7036
- this.record(service.name, "fault", target ?? path2, `slow-response: ${target ? "write" : "request"} applied; response delayed ${fault.delayMs}ms`);
7037
- this.keyed(requestKey);
7038
- later(fault.delayMs, () => respond(first.status, out, first.bytes));
7039
- } else respond(first.status, out, first.bytes);
7040
- } catch {
7041
- json2(500, { error: "world_request_error" });
7042
- }
7043
- })));
7769
+ }));
7770
+ });
7044
7771
  server.requestTimeout = 1e4;
7772
+ const upgrade2 = twin.upgrade;
7773
+ if (upgrade2) {
7774
+ const WebSocketServer = await packWebSocketServer(meta2.generation);
7775
+ const toRequest = (req) => {
7776
+ const headers = new Headers();
7777
+ for (const [k, v] of Object.entries(req.headers)) if (typeof v === "string" && !/^(host|x-agenttwin-.*)$/i.test(k)) headers.set(k, v);
7778
+ const own = appCredential(req.headers["x-agenttwin-app-authorization"]);
7779
+ if (own) headers.set("authorization", own);
7780
+ else if (headers.get("authorization") === `Bearer ${token}`) headers.delete("authorization");
7781
+ const raw = req.socket.agenttwinRaw === true;
7782
+ return new Request(`https://${String(req.headers["x-agenttwin-original-host"] ?? (raw ? req.headers.host?.replace(/:\d+$/, "") : void 0) ?? baseHost)}${req.url ?? "/"}`, { headers });
7783
+ };
7784
+ const wss = new WebSocketServer({ noServer: true, handleProtocols: (_set, req) => upgrade2.protocol?.(toRequest(req)) ?? false });
7785
+ this.socketServers.push(wss);
7786
+ server.on("upgrade", (req, socket, head) => {
7787
+ const ours = req.socket.agenttwinRaw === true || req.headers.authorization === `Bearer ${token}` || req.headers["x-agenttwin-token"] === token;
7788
+ const path2 = new URL(req.url ?? "/", "http://localhost").pathname;
7789
+ const request = toRequest(req);
7790
+ if (!ours || !upgrade2.accepts(request)) {
7791
+ this.record(service.name, ours ? "rejected" : "auth-denied", path2, ours ? `WebSocket ${path2} \u2192 no socket endpoint` : "invalid test credential");
7792
+ socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
7793
+ return;
7794
+ }
7795
+ const epoch = this.epoch;
7796
+ wss.handleUpgrade(req, socket, head, (ws) => {
7797
+ const send2 = ws.send.bind(ws);
7798
+ ws.send = (data2, ...rest) => {
7799
+ try {
7800
+ const parsed = JSON.parse(String(data2));
7801
+ if (typeof parsed.envelope_id === "string" && this.causing[service.name] === 1) {
7802
+ this.causing[service.name] = 2;
7803
+ this.lastEnvelope[service.name] = { send: send2, envelope: parsed };
7804
+ }
7805
+ } catch {
7806
+ }
7807
+ send2(data2, ...rest);
7808
+ };
7809
+ const inWorld = (fn) => withTwinClock(this.twinClock, () => serialized(async () => fn()));
7810
+ ws.on("message", (data2, binary) => {
7811
+ if (epoch !== this.epoch) return;
7812
+ const bytes = Array.isArray(data2) ? Buffer.concat(data2) : Buffer.from(data2);
7813
+ Promise.resolve().then(() => withTwinClock(this.twinClock, () => upgrade2.message(ws, binary ? new Uint8Array(bytes) : bytes.toString("utf8")))).then(() => apply(log.drain(), "WS", path2, true), () => ws.close(1011, "handler failed"));
7814
+ });
7815
+ ws.on("close", () => {
7816
+ void inWorld(() => upgrade2.close(ws)).catch(() => {
7817
+ });
7818
+ });
7819
+ ws.on("error", () => ws.close());
7820
+ this.record(service.name, "read", path2, `WebSocket ${path2} opened`);
7821
+ void inWorld(() => upgrade2.open(ws, request)).then(() => apply(log.drain(), "WS", path2, true), () => ws.close(1011, "handler failed"));
7822
+ });
7823
+ });
7824
+ }
7045
7825
  await new Promise((resolve13, reject) => {
7046
7826
  server.once("error", reject);
7047
7827
  server.listen(0, "127.0.0.1", resolve13);
7048
7828
  });
7829
+ const rawServer = createNetServer((socket) => {
7830
+ socket.agenttwinRaw = true;
7831
+ server.emit("connection", socket);
7832
+ });
7833
+ await new Promise((resolve13, reject) => {
7834
+ rawServer.once("error", reject);
7835
+ rawServer.listen(0, "127.0.0.1", resolve13);
7836
+ });
7837
+ this.rawServers.push(rawServer);
7838
+ this.packTcp[service.name] = rawServer.address().port;
7049
7839
  return server;
7050
7840
  }
7051
7841
  assertions() {
@@ -7081,9 +7871,16 @@ var init_http_world = __esm({
7081
7871
  return this.snapshot();
7082
7872
  }
7083
7873
  async close() {
7874
+ await this.postgrest?.close();
7875
+ this.postgrest = void 0;
7084
7876
  this.epoch++;
7085
7877
  for (const timer of this.timers) clearTimeout(timer);
7086
7878
  this.timers.clear();
7879
+ for (const wss of this.socketServers.splice(0)) {
7880
+ for (const ws of wss.clients) ws.terminate();
7881
+ wss.close();
7882
+ }
7883
+ for (const raw of this.rawServers.splice(0)) raw.close();
7087
7884
  await Promise.all(this.servers.map((server) => new Promise((resolve13) => {
7088
7885
  server.close(() => resolve13());
7089
7886
  server.closeAllConnections();
@@ -7165,7 +7962,7 @@ function evaluateProperty(policy, final, events) {
7165
7962
  const key2 = JSON.stringify(canonical(row[field]));
7166
7963
  keyed.set(key2, [...keyed.get(key2) ?? [], row.id ?? row]);
7167
7964
  }
7168
- const duplicates = [...keyed.entries()].filter(([, list2]) => list2.length > 1);
7965
+ const duplicates = [...keyed.entries()].filter(([, list3]) => list3.length > 1);
7169
7966
  return {
7170
7967
  ...base,
7171
7968
  passed: duplicates.length === 0,
@@ -7232,11 +8029,28 @@ function operationMatrix(spec) {
7232
8029
  function packContract(name, adapter) {
7233
8030
  return { name, adapter, version: "twin-pack", operations: [], pack: adapter.slice("pack:".length) };
7234
8031
  }
7235
- var CONTRACTS;
8032
+ var STRIPE_OPERATIONS, CONTRACTS;
7236
8033
  var init_contracts = __esm({
7237
8034
  "src/runtime/contracts.ts"() {
7238
8035
  "use strict";
7239
8036
  init_enterprise_twins();
8037
+ STRIPE_OPERATIONS = [
8038
+ "customers.create",
8039
+ "customers.retrieve",
8040
+ "customers.list",
8041
+ "paymentIntents.create",
8042
+ "paymentIntents.retrieve",
8043
+ "paymentIntents.confirm",
8044
+ "refunds.create",
8045
+ "refunds.retrieve",
8046
+ "refunds.list",
8047
+ "charges.retrieve",
8048
+ "charges.list",
8049
+ "events.retrieve",
8050
+ "events.list",
8051
+ "subscriptionItems.retrieve",
8052
+ "subscriptionItems.update"
8053
+ ];
7240
8054
  CONTRACTS = {
7241
8055
  composio: {
7242
8056
  version: "1.0.0",
@@ -7289,9 +8103,11 @@ var init_contracts = __esm({
7289
8103
  { 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"] },
7290
8104
  { method: "GET", endpoint: "/v1/refunds[/<id>]", effect: "retrieve or list refunds", parameters: ["limit", "starting_after", "charge", "payment_intent"], errors: ["404 resource_missing"] },
7291
8105
  { method: "GET", endpoint: "/v1/charges[/<id>]", effect: "retrieve or list charges", parameters: ["limit"], errors: ["404 resource_missing"] },
7292
- { method: "GET", endpoint: "/v1/events[/<id>]", effect: "retrieve or list recorded charge.refunded events", parameters: ["limit", "type"], errors: ["404 resource_missing"] }
8106
+ { method: "GET", endpoint: "/v1/events[/<id>]", effect: "retrieve or list recorded charge.refunded events", parameters: ["limit", "type"], errors: ["404 resource_missing"] },
8107
+ { method: "GET", endpoint: "/v1/subscription_items/<id>", effect: "retrieve a seeded subscription item", parameters: [], errors: ["404 resource_missing"] },
8108
+ { 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"] }
7293
8109
  ],
7294
- 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"]
8110
+ 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"]
7295
8111
  },
7296
8112
  slack: {
7297
8113
  version: "1.0.0",
@@ -7301,7 +8117,7 @@ var init_contracts = __esm({
7301
8117
  { method: "GET|POST", endpoint: "/api/conversations.history", effect: "read /messages", parameters: ["channel"], errors: ["channel_not_found"] },
7302
8118
  { method: "GET|POST", endpoint: "/api/conversations.list", effect: "read /channels", parameters: [], errors: [] }
7303
8119
  ],
7304
- 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"]
8120
+ 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"]
7305
8121
  },
7306
8122
  github: {
7307
8123
  version: "1.0.0",
@@ -7400,6 +8216,8 @@ var init_contracts = __esm({
7400
8216
  { method: "GET", endpoint: "/gmail/v1/users/me/messages", effect: "list message ids with a snippet q filter", parameters: ["q"], errors: ["400 validation"] },
7401
8217
  { method: "GET", endpoint: "/gmail/v1/users/me/messages/<id>", effect: "retrieve message", parameters: [], errors: ["404 NOT_FOUND"] },
7402
8218
  { method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] },
8219
+ { 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"] },
8220
+ { 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"] },
7403
8221
  { 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"] },
7404
8222
  { 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"] },
7405
8223
  { 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"] },
@@ -7417,7 +8235,7 @@ var init_contracts = __esm({
7417
8235
  { 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"] },
7418
8236
  { 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"] }
7419
8237
  ],
7420
- 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"]
8238
+ 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"]
7421
8239
  },
7422
8240
  "upstash-redis": {
7423
8241
  version: "1.0.0",
@@ -7516,7 +8334,7 @@ var init_contracts = __esm({
7516
8334
  });
7517
8335
 
7518
8336
  // src/runtime/cost-model.ts
7519
- import { readFile as readFile5, writeFile as writeFile6 } from "fs/promises";
8337
+ import { readFile as readFile5, writeFile as writeFile7 } from "fs/promises";
7520
8338
  import { join as join12 } from "path";
7521
8339
  async function readCostConfig(cwd) {
7522
8340
  try {
@@ -7652,7 +8470,7 @@ function incidentFor(receipt, a) {
7652
8470
  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";
7653
8471
  return { kind, extra, ...money2 ? { money: money2 } : {}, service: a.service };
7654
8472
  }
7655
- function describe(a) {
8473
+ function describe(a, incomplete) {
7656
8474
  const what = `${serviceName(a.service)} ${recordName(a.path)}${filterText(a.where)}`;
7657
8475
  if (a.passed) return `${what}: ${a.actual ?? a.count} as expected`;
7658
8476
  if (a.absent || a.count === 0) return `${what}: expected none, found ${a.actual}`;
@@ -7660,29 +8478,37 @@ function describe(a) {
7660
8478
  const times3 = a.count === 1 && a.actual === 2 ? "the same write happened twice" : `${a.actual - a.count} more than allowed`;
7661
8479
  return `${what}: expected ${a.count}, found ${a.actual} (${times3})`;
7662
8480
  }
7663
- if (a.actual === 0) return `${what}: expected ${a.count}, found none (the write never happened)`;
8481
+ if (a.actual === 0) return `${what}: expected ${a.count}, found none${incomplete ? "" : " (the write never happened)"}`;
7664
8482
  return `${what}: expected ${a.count}, found ${a.actual}`;
7665
8483
  }
7666
8484
  function explainRun(receipt, costs) {
7667
8485
  const checks = receipt.assertions ?? [];
7668
8486
  const failed = checks.filter((a) => !a.passed);
7669
- const cost = estimateCost(failed.map((a) => incidentFor(receipt, a)), costs, { title: receipt.name });
8487
+ const unsupported2 = receipt.unsupported ?? [];
8488
+ const coverageGap = receipt.status === "incomplete" && unsupported2.length > 0;
8489
+ const duplicates = failed.filter((a) => (a.actual ?? 0) > (a.count ?? Infinity));
8490
+ const cost = estimateCost((coverageGap ? duplicates : failed).map((a) => incidentFor(receipt, a)), costs, { title: receipt.name });
7670
8491
  const money2 = failed.map((a) => extraMoney(receipt, a)).filter((m) => !!m);
7671
8492
  const atRisk = money2.length ? { amount: Math.max(...money2.map((m) => m.amount)), currency: money2[0].currency } : void 0;
7672
8493
  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";
7673
8494
  const fault = receipt.fault?.triggered ? `${serviceName(receipt.fault.service ?? "")} ${recordName(receipt.fault.path ?? "")}: ${FAULT[receipt.fault.type ?? ""] ?? receipt.fault.type}` : void 0;
7674
- const duplicate = failed.some((a) => (a.actual ?? 0) > (a.count ?? Infinity));
8495
+ const duplicate = duplicates.length > 0;
7675
8496
  let cause;
7676
- 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.";
8497
+ 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));
8498
+ if (lostReply) cause = "Your code retried after the lost reply without an idempotency key, so the service applied the write a second time.";
7677
8499
  else if (duplicate) cause = "Your code repeated a write that should happen once.";
7678
8500
  else if (failed.some((a) => a.actual === 0)) cause = "An expected write never reached the service.";
7679
- if (receipt.executionError) cause = receipt.executionError;
8501
+ if (coverageGap) {
8502
+ const first = unsupported2[0];
8503
+ const gap = typeof first === "string" ? `Unsupported twin operation: ${first}` : "A twin operation was unsupported.";
8504
+ cause = duplicate ? `${cause} ${gap}` : gap;
8505
+ } else if (receipt.executionError) cause = receipt.executionError;
7680
8506
  else if (receipt.application?.timedOut) cause = "The application did not finish before the time limit.";
7681
8507
  const clip = (text3) => text3.length > 80 ? text3.slice(0, 77) + "..." : text3;
7682
8508
  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))}`}` }));
7683
8509
  const total = checks.length + infra.length, passedCount = total - failed.length - infra.filter((c) => !c.passed).length;
7684
8510
  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` : ""})`;
7685
- return { headline, cause, fault, atRisk, ...cost ? { cost } : {}, checks: [...checks.map((a) => ({ passed: a.passed, text: describe(a) })), ...infra], unsupported: receipt.unsupported?.length ?? 0 };
8511
+ return { headline, cause, fault, atRisk, ...cost ? { cost } : {}, checks: [...checks.map((a) => ({ passed: a.passed, text: describe(a, coverageGap) })), ...infra], unsupported: receipt.unsupported?.length ?? 0 };
7686
8512
  }
7687
8513
  function renderRunSummary(receipt, opts = {}) {
7688
8514
  const e = explainRun(receipt, opts.costs);
@@ -7697,7 +8523,7 @@ function renderRunSummary(receipt, opts = {}) {
7697
8523
  const builtIn = receipt.defaultChecks ?? [];
7698
8524
  if (builtIn.length) lines.push(bullet(`Built-in checks: ${builtIn.filter((c) => c.passed).length}/${builtIn.length} held`));
7699
8525
  for (const c of builtIn.filter((c2) => !c2.passed)) lines.push(bullet(`FINDING ${c.finding}${c.impact?.summary ? ` (impact: ${c.impact.summary})` : ""}`));
7700
- if (e.unsupported) lines.push("", bullet(`${e.unsupported} call(s) hit unsupported operations (returned 501, never forwarded).`));
8526
+ if (e.unsupported) lines.push("", bullet(`${e.unsupported} call(s) hit unsupported operations and were never forwarded.`));
7701
8527
  if (opts.next?.length) lines.push("", opts.markdown ? "## Next" : "Next:", ...opts.next.map((n) => bullet(n)));
7702
8528
  return lines.join("\n") + "\n";
7703
8529
  }
@@ -7724,7 +8550,7 @@ var init_run_summary = __esm({
7724
8550
  });
7725
8551
 
7726
8552
  // src/runtime/generic-calls.ts
7727
- import { createHash as createHash11 } from "crypto";
8553
+ import { createHash as createHash12 } from "crypto";
7728
8554
  function canonical2(value) {
7729
8555
  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);
7730
8556
  }
@@ -8010,7 +8836,7 @@ var init_generic_calls = __esm({
8010
8836
  VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
8011
8837
  KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
8012
8838
  KEY_FIELDS = /^(idempotency_?key|ClientToken|ClientRequestToken|MessageDeduplicationId|client_token|request_id)$/i;
8013
- digest3 = (value) => `sha256:${createHash11("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
8839
+ digest3 = (value) => `sha256:${createHash12("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
8014
8840
  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;
8015
8841
  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);
8016
8842
  outcomeOf = (status) => status === void 0 ? "ok" : status === 401 || status === 403 ? "unauthorized" : status === 429 ? "rate-limited" : status >= 500 ? "server-error" : status >= 400 ? "client-error" : "ok";
@@ -8063,7 +8889,7 @@ var init_generic_calls = __esm({
8063
8889
 
8064
8890
  // src/runtime/default-checks.ts
8065
8891
  function addedRows(initial, final) {
8066
- const rows2 = (list2) => list2.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
8892
+ const rows2 = (list3) => list3.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
8067
8893
  const ids = new Set(rows2(initial).map((r) => r.id).filter((id) => id !== void 0 && id !== null));
8068
8894
  const seen = /* @__PURE__ */ new Map();
8069
8895
  for (const r of rows2(initial)) if (r.id === void 0) seen.set(canonical3(r), (seen.get(canonical3(r)) ?? 0) + 1);
@@ -8227,7 +9053,7 @@ var init_default_checks = __esm({
8227
9053
  };
8228
9054
  stripeNoDuplicatePayment = {
8229
9055
  id: "stripe.no-duplicate-payment",
8230
- title: "No duplicate charges or customers for one request",
9056
+ title: "No duplicate charges, customers or subscriptions for one request",
8231
9057
  path: "/v1/payment_intents",
8232
9058
  coversDuplicates: true,
8233
9059
  expected: "one payment intent per amount/currency/customer/payment method and one customer per email",
@@ -8246,6 +9072,19 @@ var init_default_checks = __esm({
8246
9072
  evidence: writeSequences(ctx, s, group.map((r) => r.id))
8247
9073
  });
8248
9074
  }
9075
+ const subscriptions = addedRows(rowsOf(ctx.initialState, s, "/v1/subscriptions"), rowsOf(ctx.finalState, s, "/v1/subscriptions")).filter((r) => !["canceled", "incomplete_expired"].includes(String(r.status)));
9076
+ 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) }));
9077
+ 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)) {
9078
+ const items = itemsOf(group[0]), currency = String(items[0]?.price.currency ?? group[0].currency ?? "usd");
9079
+ const perPeriod = items.reduce((n, i) => n + (typeof i.price.unit_amount === "number" ? i.price.unit_amount * i.quantity : 0), 0);
9080
+ out.push({
9081
+ path: "/v1/subscriptions",
9082
+ actual: { subscriptions: group.map((r) => r.id), customer: group[0].customer },
9083
+ finding: `Your agent subscribed ${String(group[0].customer)} ${times2(group.length)} to the same plan${faultPhrase(ctx)}`,
9084
+ 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 },
9085
+ evidence: writeSequences(ctx, s, group.map((r) => r.id))
9086
+ });
9087
+ }
8249
9088
  const customers = addedRows(rowsOf(ctx.initialState, s, "/v1/customers"), rowsOf(ctx.finalState, s, "/v1/customers"));
8250
9089
  for (const group of groups(customers, (r) => typeof r.email === "string" && r.email ? r.email.toLowerCase() : void 0))
8251
9090
  out.push({
@@ -8372,14 +9211,14 @@ var init_default_checks = __esm({
8372
9211
  };
8373
9212
  VENDOR_COVERS = { "retry-without-key": /\.idempotent-retries$/, "announce-after-failed-write": /\.announce-after-success$/ };
8374
9213
  DEFAULT_CHECKS["*"].push(...genericWorldChecks((adapter, rule) => !!VENDOR_COVERS[rule] && registryFor(adapter).some((c) => VENDOR_COVERS[rule].test(c.id))));
8375
- registryFor = (adapter) => DEFAULT_CHECKS[adapter ?? "json-collection"] ?? [];
9214
+ registryFor = (adapter) => DEFAULT_CHECKS[adapter ?? "json-collection"] ?? (adapter?.startsWith("pack:") ? DEFAULT_CHECKS[adapter.slice(5)] : void 0) ?? [];
8376
9215
  refOf = (s) => typeof s === "string" ? { name: s, adapter: s } : s;
8377
9216
  }
8378
9217
  });
8379
9218
 
8380
9219
  // src/runtime/twin-proxy.ts
8381
9220
  import { execFile as execFile5 } from "child_process";
8382
- import { mkdtemp as mkdtemp6, readFile as readFile6, rm as rm6, writeFile as writeFile7 } from "fs/promises";
9221
+ import { mkdtemp as mkdtemp6, readFile as readFile6, rm as rm6, writeFile as writeFile8 } from "fs/promises";
8383
9222
  import { createServer as createServer4, request as httpRequest } from "http";
8384
9223
  import { tmpdir as tmpdir6 } from "os";
8385
9224
  import { join as join13 } from "path";
@@ -8439,7 +9278,7 @@ async function runAuthority(dir) {
8439
9278
  if (!ctx) {
8440
9279
  ctx = (async () => {
8441
9280
  const base = join13(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
8442
- await writeFile7(base + ".ext", `basicConstraints=critical,CA:FALSE
9281
+ await writeFile8(base + ".ext", `basicConstraints=critical,CA:FALSE
8443
9282
  keyUsage=critical,digitalSignature
8444
9283
  extendedKeyUsage=serverAuth
8445
9284
  subjectAltName=DNS:${host}
@@ -8478,6 +9317,7 @@ async function startTwinProxy(routes2) {
8478
9317
  const headers = {};
8479
9318
  const strip = route.auth === "passthrough" ? ["host", "proxy-connection", "proxy-authorization"] : SECRET;
8480
9319
  for (const [k, v] of Object.entries(req.headers)) if (v !== void 0 && !strip.includes(k)) headers[k] = v;
9320
+ if (route.appCredential && typeof req.headers.authorization === "string" && /^Bearer \S{12,}$/.test(req.headers.authorization)) headers["x-agenttwin-app-authorization"] = req.headers.authorization;
8481
9321
  if (route.auth === "passthrough") headers["x-agenttwin-token"] = route.token;
8482
9322
  else if (route.auth === "x-api-key") headers["x-api-key"] = route.token;
8483
9323
  else headers.authorization = `Bearer ${route.token}`;
@@ -8573,7 +9413,7 @@ var init_twin_proxy = __esm({
8573
9413
  });
8574
9414
 
8575
9415
  // src/runtime/twin-routing.ts
8576
- import { mkdtemp as mkdtemp7, readFile as readFile7, rm as rm7, writeFile as writeFile8 } from "fs/promises";
9416
+ import { mkdtemp as mkdtemp7, readFile as readFile7, rm as rm7, writeFile as writeFile9 } from "fs/promises";
8577
9417
  import { tmpdir as tmpdir7 } from "os";
8578
9418
  import { join as join14 } from "path";
8579
9419
  function twinRoutes(services, world, models) {
@@ -8582,10 +9422,11 @@ function twinRoutes(services, world, models) {
8582
9422
  const adapter = service.adapter ?? "", credential = world.credentials[service.name];
8583
9423
  if (credential && isPackAdapter(adapter)) {
8584
9424
  const record4 = packRecord(adapter.slice(PACK_PREFIX.length));
8585
- const auth = record4.credentialDoor ? "bearer" : "passthrough";
9425
+ const issuesKey = !!record4.credentialDoor && Object.values(record4.credentialDoor.fill ?? {}).some((field) => !String(field).startsWith("file:"));
9426
+ const auth = issuesKey ? "bearer" : "passthrough";
8586
9427
  for (const h of record4.hosts) {
8587
9428
  const host = h.host ?? `pattern:${h.hostPattern}`;
8588
- 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 });
9429
+ 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 } : {} });
8589
9430
  }
8590
9431
  continue;
8591
9432
  }
@@ -8599,6 +9440,7 @@ var PROVIDER_HOSTS, TWIN_PRELOAD;
8599
9440
  var init_twin_routing = __esm({
8600
9441
  "src/runtime/twin-routing.ts"() {
8601
9442
  "use strict";
9443
+ init_node_options();
8602
9444
  init_packs();
8603
9445
  PROVIDER_HOSTS = {
8604
9446
  // OpenAI-compatible APIs answer in the same format, so they are served by the OpenAI twin (with its scripted tool calls).
@@ -8653,9 +9495,13 @@ if(originalFetch)globalThis.fetch=async function(input,init){
8653
9495
  if(!r)throw blocked('fetch',url.hostname,url.port||(url.protocol==='https:'?443:80),method);
8654
9496
  if(process.env.AGENTTWIN_DEBUG_ROUTES)console.error('route-match '+url.hostname+' auth='+r.auth+' service='+r.service);
8655
9497
  const request=new Request(input,init),headers=new Headers(request.headers);
9498
+ {const own=headers.get('authorization');if(r.appCredential&&own&&/^Bearer \S{12,}$/.test(own))headers.set('x-agenttwin-app-authorization',own);}
8656
9499
  for(const name of removed(r))headers.delete(name);const [name,value]=credential(r);headers.set(name,value);
8657
9500
  headers.set('x-agenttwin-original-host',url.hostname);const location=source();if(location)headers.set('x-agenttwin-source',location);
8658
- return originalFetch(new Request(r.target+rewrite(r,url.pathname)+url.search,request),{headers,redirect:'manual'});
9501
+ // Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch (Upstash's
9502
+ // client sets keepalive on every call).
9503
+ const body=request.body===null?undefined:Buffer.from(await request.arrayBuffer());
9504
+ return originalFetch(r.target+rewrite(r,url.pathname)+url.search,{method:request.method,headers,...(body===undefined?{}:{body}),redirect:'manual',signal:request.signal});
8659
9505
  };
8660
9506
  const originalHttpRequest=http.request;
8661
9507
  for(const [mod,scheme] of [[http,'http'],[https,'https']]){
@@ -8674,6 +9520,8 @@ for(const [mod,scheme] of [[http,'http'],[https,'https']]){
8674
9520
  const target=new URL(r.target),headers={};
8675
9521
  const given=options.headers||{};
8676
9522
  for(const [k,v] of Array.isArray(given)?[]:Object.entries(given))if(!removed(r).includes(k.toLowerCase()))headers[k]=v;
9523
+ // The app's own credential travels beside the run token: a pack host keeps it when the twin issued it (an app-level token).
9524
+ 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;}
8677
9525
  const [name,value]=credential(r);headers[name]=value;headers.host=target.host;headers['x-agenttwin-original-host']=host;
8678
9526
  const location=source();if(location)headers['x-agenttwin-source']=location;
8679
9527
  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;
@@ -8754,6 +9602,36 @@ function sqlTables(sql) {
8754
9602
  }
8755
9603
  return [...out];
8756
9604
  }
9605
+ function bindValues(body2) {
9606
+ try {
9607
+ let at = body2.indexOf(0) + 1;
9608
+ at = body2.indexOf(0, at) + 1;
9609
+ const formats2 = body2.readInt16BE(at);
9610
+ at += 2;
9611
+ const codes = [];
9612
+ for (let i = 0; i < formats2; i++) {
9613
+ codes.push(body2.readInt16BE(at));
9614
+ at += 2;
9615
+ }
9616
+ const count = body2.readInt16BE(at);
9617
+ at += 2;
9618
+ const values = [];
9619
+ for (let i = 0; i < count; i++) {
9620
+ const len = body2.readInt32BE(at);
9621
+ at += 4;
9622
+ if (len < 0) {
9623
+ values.push(null);
9624
+ continue;
9625
+ }
9626
+ const binary = (codes.length === 1 ? codes[0] : codes[i] ?? 0) === 1;
9627
+ values.push(binary ? null : body2.toString("utf8", at, at + len));
9628
+ at += len;
9629
+ }
9630
+ return values;
9631
+ } catch {
9632
+ return [];
9633
+ }
9634
+ }
8757
9635
  async function startPostgresEngine(options = {}) {
8758
9636
  const started = Date.now();
8759
9637
  let PGlite;
@@ -8821,7 +9699,7 @@ async function startPostgresEngine(options = {}) {
8821
9699
  if (name) {
8822
9700
  conn.names.set(name, sql);
8823
9701
  conn.statements.add(ns(name));
8824
- }
9702
+ } else conn.unnamed = sql;
8825
9703
  return { body: Buffer.concat([cstr(ns(name)), body2.subarray(end + 1)]), sql };
8826
9704
  }
8827
9705
  if (type === "B") {
@@ -8876,7 +9754,13 @@ async function startPostgresEngine(options = {}) {
8876
9754
  for (const m of prepared) outputs.push(await raw(msg(m.type, m.body)));
8877
9755
  const out = Buffer.concat(outputs), { tags, status, failed } = scan(out);
8878
9756
  for (const t of writeTables) conn.txnTables.add(t);
8879
- if (sqls.length && !writes.length && tables2.length) record(events, { engine: "postgres", operation: "read", resource: tables2.join(","), detail: tags.join("; ").slice(0, 200) });
9757
+ const binds = batch.filter((m) => m.type === "B").map((m) => {
9758
+ const pEnd = m.body.indexOf(0), sEnd = m.body.indexOf(0, pEnd + 1), stmt = m.body.toString("utf8", pEnd + 1, sEnd);
9759
+ return { sql: stmt ? conn.names.get(stmt) : conn.unnamed, params: bindValues(m.body) };
9760
+ });
9761
+ const readSql = sqls.length ? sqls : binds.flatMap((b) => b.sql && !isWriteSql(b.sql) ? [b.sql] : []);
9762
+ const readTables2 = [...new Set(readSql.flatMap(sqlTables))];
9763
+ 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)) } });
8880
9764
  owner = status === "I" ? null : conn;
8881
9765
  let committed = [];
8882
9766
  if (status === "I") {
@@ -9070,7 +9954,9 @@ async function startPostgresEngine(options = {}) {
9070
9954
  }
9071
9955
  };
9072
9956
  const seed = async (data) => direct(async () => {
9073
- if (data.sql) await db.exec(data.sql);
9957
+ if (data.sql) {
9958
+ for (const part of data.sql.split(/^(?=-- Schema source: )/m)) if (part.trim()) await db.exec(part);
9959
+ }
9074
9960
  for (const [table2, rows2] of Object.entries(data.tables ?? {})) {
9075
9961
  for (const row of rows2) {
9076
9962
  const fields = Object.keys(row);
@@ -9362,13 +10248,13 @@ var init_server_steps = __esm({
9362
10248
 
9363
10249
  // src/runtime/local.ts
9364
10250
  import { spawn as spawn2 } from "child_process";
9365
- import { realpath as realpath2 } from "fs/promises";
10251
+ import { realpath as realpath3 } from "fs/promises";
9366
10252
  import { dirname as dirname2, resolve as resolve4 } from "path";
9367
10253
  async function sourceRoot(app, spec) {
9368
- const real = await realpath2(app);
10254
+ const real = await realpath3(app);
9369
10255
  if (!spec.directory) return real;
9370
10256
  for (let candidate = real; ; candidate = dirname2(candidate)) {
9371
- if (await realpath2(resolve4(candidate, spec.directory)).then((p) => p === real, () => false)) return candidate;
10257
+ if (await realpath3(resolve4(candidate, spec.directory)).then((p) => p === real, () => false)) return candidate;
9372
10258
  if (dirname2(candidate) === candidate) return real;
9373
10259
  }
9374
10260
  }
@@ -9387,10 +10273,11 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
9387
10273
  }
9388
10274
  engines = await startLocalEngines(filesDir, spec);
9389
10275
  Object.assign(env, engines.env);
10276
+ if (engines.env.DATABASE_URL) world.attachDatabase(engines.env.DATABASE_URL);
9390
10277
  let stdout = "", stderr = "", timedOut = false;
9391
10278
  const node = /(^|\/)node(\.exe)?$/.test(spec.command[0]);
9392
10279
  const hook = await createRequestSourceHook(await sourceRoot(app, spec), spec, credentials2);
9393
- if (node) env.NODE_OPTIONS = [extraEnv.NODE_OPTIONS, `--require ${JSON.stringify(hook.path)}`].filter(Boolean).join(" ");
10280
+ if (node) env.NODE_OPTIONS = await singlePreload(extraEnv.NODE_OPTIONS ?? "", hook.path);
9394
10281
  let proxy;
9395
10282
  if (!node) {
9396
10283
  const configured = extraEnv.AGENTTWIN_ROUTES ? JSON.parse(extraEnv.AGENTTWIN_ROUTES).routes : void 0;
@@ -9513,6 +10400,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
9513
10400
  var init_local = __esm({
9514
10401
  "src/runtime/local.ts"() {
9515
10402
  "use strict";
10403
+ init_node_options();
9516
10404
  init_application_process();
9517
10405
  init_browser_process();
9518
10406
  init_twin_clock();
@@ -9997,7 +10885,7 @@ var init_offline = __esm({
9997
10885
  // src/runtime/credentials.ts
9998
10886
  import { homedir } from "os";
9999
10887
  import { join as join17 } from "path";
10000
- import { readFile as readFile9, mkdir as mkdir4, writeFile as writeFile9, chmod as chmod2, rm as rm9 } from "fs/promises";
10888
+ import { readFile as readFile9, mkdir as mkdir4, writeFile as writeFile10, chmod as chmod2, rm as rm9 } from "fs/promises";
10001
10889
  async function savedConnection() {
10002
10890
  try {
10003
10891
  const data = JSON.parse(await readFile9(path(), "utf8"));
@@ -10144,7 +11032,7 @@ var init_hosted_packs = __esm({
10144
11032
  });
10145
11033
 
10146
11034
  // src/runtime/e2b.ts
10147
- import { createRequire } from "module";
11035
+ import { createRequire as createRequire3 } from "module";
10148
11036
  import { readFile as readFile12 } from "fs/promises";
10149
11037
  import { randomBytes as randomBytes6 } from "crypto";
10150
11038
  import { homedir as homedir2 } from "os";
@@ -10222,7 +11110,7 @@ logfile /tmp/agenttwin-redis.log
10222
11110
  }
10223
11111
  await sandbox.files.write("/input/runtime.json", JSON.stringify(runtimeEnv), { user: "root" });
10224
11112
  await sandbox.commands.run("chmod -R a+rX /input", { user: "root" });
10225
- const playwrightVersion = createRequire(import.meta.url)("playwright/package.json").version;
11113
+ const playwrightVersion = createRequire3(import.meta.url)("playwright/package.json").version;
10226
11114
  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" });
10227
11115
  await sandbox.commands.run("node /input/check-runtime.cjs", { user: "root" });
10228
11116
  if (spec.browser) {
@@ -10262,12 +11150,12 @@ var init_e2b = __esm({
10262
11150
  });
10263
11151
 
10264
11152
  // src/runtime/matrix.ts
10265
- import { createHash as createHash12 } from "crypto";
10266
- import { mkdir as mkdir5, readFile as readFile13, writeFile as writeFile10 } from "fs/promises";
11153
+ import { createHash as createHash13 } from "crypto";
11154
+ import { mkdir as mkdir5, readFile as readFile13, writeFile as writeFile11 } from "fs/promises";
10267
11155
  import { join as join21, relative, resolve as resolve5 } from "path";
10268
11156
  function filesDigest(sourceDigests) {
10269
11157
  const canonical5 = Object.keys(sourceDigests).sort().map((file) => `${file}:${sourceDigests[file]}`).join("\n");
10270
- return createHash12("sha256").update(canonical5).digest("hex");
11158
+ return createHash13("sha256").update(canonical5).digest("hex");
10271
11159
  }
10272
11160
  function checksOfReceipt(receipt) {
10273
11161
  const checks = (receipt.evaluation?.checks ?? []).map((c) => ({
@@ -10352,7 +11240,7 @@ function buildMatrixReport(input) {
10352
11240
  async function runSeedMatrix(cwd, opts) {
10353
11241
  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 });
10354
11242
  const baseSeed = normalizeSeed(opts.seed);
10355
- const matrixName = `matrix-${createHash12("sha256").update(`${baseSeed}:${opts.seeds}`).digest("hex").slice(0, 8)}`;
11243
+ const matrixName = `matrix-${createHash13("sha256").update(`${baseSeed}:${opts.seeds}`).digest("hex").slice(0, 8)}`;
10356
11244
  const matrixDir = resolve5(cwd, opts.out ?? join21(".agenttwin/runs", matrixName));
10357
11245
  await mkdir5(matrixDir, { recursive: true, mode: 448 });
10358
11246
  const results = [];
@@ -10385,8 +11273,8 @@ async function runSeedMatrix(cwd, opts) {
10385
11273
  });
10386
11274
  const reportPath = resolve5(cwd, opts.out ?? join21(matrixDir, "matrix.json"));
10387
11275
  await mkdir5(opts.out && opts.out.endsWith(".json") ? join21(reportPath, "..") : matrixDir, { recursive: true, mode: 448 });
10388
- await writeFile10(reportPath, JSON.stringify(report, null, 2) + "\n", { mode: 384 });
10389
- await writeFile10(join21(matrixDir, "matrix.md"), `${report.verdict.summary}
11276
+ await writeFile11(reportPath, JSON.stringify(report, null, 2) + "\n", { mode: 384 });
11277
+ await writeFile11(join21(matrixDir, "matrix.md"), `${report.verdict.summary}
10390
11278
 
10391
11279
  Report: ${relative(cwd, reportPath).split("\\").join("/")}
10392
11280
  `);
@@ -10406,8 +11294,8 @@ var init_matrix = __esm({
10406
11294
  });
10407
11295
 
10408
11296
  // src/runtime/source-build.ts
10409
- import { createHash as createHash13 } from "crypto";
10410
- import { lstat, readFile as readFile14, realpath as realpath3 } from "fs/promises";
11297
+ import { createHash as createHash14 } from "crypto";
11298
+ import { lstat, readFile as readFile14, realpath as realpath4 } from "fs/promises";
10411
11299
  import { isAbsolute as isAbsolute2, join as join22, relative as relative2, resolve as resolve6, sep } from "path";
10412
11300
  import { isDeepStrictEqual as isDeepStrictEqual8 } from "util";
10413
11301
  async function checkSourceBuild(directory, spec) {
@@ -10416,7 +11304,7 @@ async function checkSourceBuild(directory, spec) {
10416
11304
  throw new CliError(`Prepared source is stale: ${message}`, { code: EXIT.BLOCKED, action: "Prepare this workflow again from the current repository before running it." });
10417
11305
  };
10418
11306
  try {
10419
- const preparedRoot = await realpath3(directory);
11307
+ const preparedRoot = await realpath4(directory);
10420
11308
  const sidecar = join22(preparedRoot, LOCAL_BUILD_FILE);
10421
11309
  const info = await lstat(sidecar);
10422
11310
  if (!info.isFile() || info.isSymbolicLink() || info.size > 2 * 1024 * 1024) stale("local source record is missing, unsafe or exceeds bounds");
@@ -10428,21 +11316,21 @@ async function checkSourceBuild(directory, spec) {
10428
11316
  if (!build2.sourceDigests || typeof build2.sourceDigests !== "object" || Array.isArray(build2.sourceDigests)) stale("original source hashes are missing");
10429
11317
  const entries = Object.entries(build2.sourceDigests);
10430
11318
  if (!entries.length || entries.length > 1501) stale("original source set exceeds bounds");
10431
- const root = await realpath3(local.sourceRoot);
11319
+ const root = await realpath4(local.sourceRoot);
10432
11320
  let total = 0;
10433
11321
  for (const [file, expected] of entries) {
10434
11322
  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");
10435
- const path2 = resolve6(root, file), canonical5 = await realpath3(path2);
11323
+ const path2 = resolve6(root, file), canonical5 = await realpath4(path2);
10436
11324
  const rel = relative2(root, canonical5);
10437
11325
  if (path2 !== canonical5 || rel === ".." || rel.startsWith(".." + sep) || isAbsolute2(rel) || !(await lstat(path2)).isFile()) stale(`source moved or uses a symlink: ${file}`);
10438
11326
  const size = (await lstat(path2)).size;
10439
11327
  if (total + size > 30 * 1024 * 1024) stale("original source exceeds bounds");
10440
11328
  const source = await readFile14(path2);
10441
11329
  total += source.length;
10442
- if (total > 30 * 1024 * 1024 || createHash13("sha256").update(source).digest("hex") !== expected) stale(`source changed: ${file}`);
11330
+ if (total > 30 * 1024 * 1024 || createHash14("sha256").update(source).digest("hex") !== expected) stale(`source changed: ${file}`);
10443
11331
  }
10444
11332
  const artifact = join22(preparedRoot, "application.cjs");
10445
- if (!(await lstat(artifact)).isFile() || await realpath3(artifact) !== resolve6(artifact) || (await lstat(artifact)).size > 20 * 1024 * 1024 || createHash13("sha256").update(await readFile14(artifact)).digest("hex") !== build2.bundleDigest) stale("compiled application changed");
11333
+ if (!(await lstat(artifact)).isFile() || await realpath4(artifact) !== resolve6(artifact) || (await lstat(artifact)).size > 20 * 1024 * 1024 || createHash14("sha256").update(await readFile14(artifact)).digest("hex") !== build2.bundleDigest) stale("compiled application changed");
10446
11334
  return { root, digest: spec.sourceBuild };
10447
11335
  } catch (error) {
10448
11336
  if (error instanceof CliError) throw error;
@@ -10455,7 +11343,7 @@ var init_source_build = __esm({
10455
11343
  "use strict";
10456
11344
  init_exit();
10457
11345
  LOCAL_BUILD_FILE = ".agenttwin/source-build.json";
10458
- sourceBuildDigest = (build2) => createHash13("sha256").update(JSON.stringify(build2)).digest("hex");
11346
+ sourceBuildDigest = (build2) => createHash14("sha256").update(JSON.stringify(build2)).digest("hex");
10459
11347
  sha3 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
10460
11348
  }
10461
11349
  });
@@ -11379,6 +12267,94 @@ var init_catalog = __esm({
11379
12267
  }
11380
12268
  });
11381
12269
 
12270
+ // src/inventory/service-coverage.ts
12271
+ function serviceSupport(tool) {
12272
+ const provider = tool.providerId ?? tool.title.toLowerCase();
12273
+ const adapters = ADAPTER_GROUPS[provider] ?? TWIN_ADAPTERS.filter((name) => name === provider);
12274
+ 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." };
12275
+ 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." };
12276
+ 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." };
12277
+ }
12278
+ function missingStripeOperations(workflow, tools, adapter) {
12279
+ const steps = workflow.steps.filter((step) => tools.has(step.tool));
12280
+ if (!steps.length) return [];
12281
+ const missingFor = (selected) => [...new Set(steps.flatMap((step) => step.operations.flatMap((operation) => {
12282
+ if (!(selected === "stripe" ? STRIPE_OPERATIONS.includes(operation) : PACK_STRIPE_OPERATIONS.has(operation))) return [operation];
12283
+ if (operation !== "subscriptionItems.update") return [];
12284
+ const fields = step.stripeItemFields;
12285
+ if (!fields) return [`${operation} (unverified quantity parameters)`];
12286
+ const unsupported2 = fields.filter((field) => field !== "quantity" && !(selected === "pack:stripe" && field === "expand"));
12287
+ if (unsupported2.length) return [`${operation} (${unsupported2.join(", ")})`];
12288
+ return fields.includes("quantity") ? [] : [`${operation} (quantity required)`];
12289
+ })))];
12290
+ if (adapter) return missingFor(adapter);
12291
+ const builtin = missingFor("stripe");
12292
+ if (!builtin.length || !packRecord("stripe")) return builtin;
12293
+ const pack = missingFor("pack:stripe");
12294
+ return pack.length < builtin.length ? pack : builtin;
12295
+ }
12296
+ var TWIN_ADAPTERS, ADAPTER_GROUPS, PACK_STRIPE_OPERATIONS;
12297
+ var init_service_coverage = __esm({
12298
+ "src/inventory/service-coverage.ts"() {
12299
+ "use strict";
12300
+ init_contracts();
12301
+ init_enterprise_twins();
12302
+ init_packs();
12303
+ 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];
12304
+ ADAPTER_GROUPS = {
12305
+ google: ["gmail", "google-calendar", "google-oauth"],
12306
+ atlassian: ["jira", "confluence"],
12307
+ microsoft: ["microsoft-teams", "outlook", "entra-id", "sharepoint"]
12308
+ };
12309
+ PACK_STRIPE_OPERATIONS = /* @__PURE__ */ new Set([
12310
+ "accounts.create",
12311
+ "accountLinks.create",
12312
+ "balance.retrieve",
12313
+ "balanceTransactions.list",
12314
+ "billingPortal.configurations.list",
12315
+ "billingPortal.configurations.create",
12316
+ "billingPortal.sessions.create",
12317
+ "charges.list",
12318
+ "charges.retrieve",
12319
+ "checkout.sessions.create",
12320
+ "checkout.sessions.listLineItems",
12321
+ "coupons.create",
12322
+ "customers.create",
12323
+ "customers.retrieve",
12324
+ "customers.search",
12325
+ "customers.update",
12326
+ "invoicePayments.list",
12327
+ "invoices.create",
12328
+ "invoices.createPreview",
12329
+ "invoices.retrieve",
12330
+ "invoices.pay",
12331
+ "invoices.voidInvoice",
12332
+ "paymentIntents.create",
12333
+ "paymentIntents.cancel",
12334
+ "paymentMethods.retrieve",
12335
+ "paymentMethods.detach",
12336
+ "payouts.create",
12337
+ "prices.create",
12338
+ "prices.list",
12339
+ "prices.retrieve",
12340
+ "products.create",
12341
+ "products.list",
12342
+ "promotionCodes.create",
12343
+ "promotionCodes.list",
12344
+ "refunds.create",
12345
+ "subscriptions.cancel",
12346
+ "subscriptions.deleteDiscount",
12347
+ "subscriptions.list",
12348
+ "subscriptions.retrieve",
12349
+ "subscriptions.update",
12350
+ "subscriptionItems.retrieve",
12351
+ "subscriptionItems.update",
12352
+ "transfers.create",
12353
+ "webhookEndpoints.create"
12354
+ ]);
12355
+ }
12356
+ });
12357
+
11382
12358
  // src/inventory/dashboard-transfer.ts
11383
12359
  function discoveryTransfer(value) {
11384
12360
  const input = value;
@@ -11405,12 +12381,16 @@ function discoveryTransfer(value) {
11405
12381
  if (!Array.isArray(w.steps) || w.steps.length > 1e3) throw new Error("Invalid workflow steps");
11406
12382
  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) => {
11407
12383
  const step = rawStep;
11408
- return { tool: text3(step.tool), operations: strings(step.operations) };
12384
+ return { tool: text3(step.tool), operations: strings(step.operations), ...step.stripeItemFields !== void 0 ? { stripeItemFields: step.stripeItemFields === null ? null : strings(step.stripeItemFields) } : {} };
11409
12385
  }), ...w.entrypoint ? { entrypoint: entrypoint(w.entrypoint) } : {} };
11410
12386
  });
11411
12387
  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");
11412
12388
  const ids = new Set(tools.map((t) => t.id));
11413
12389
  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");
12390
+ const stripeTools = new Set(tools.filter((tool) => tool.title.toLowerCase() === "stripe").map((tool) => tool.id));
12391
+ for (const workflow of workflows) {
12392
+ if (missingStripeOperations(workflow, stripeTools).length) workflow.supported = false;
12393
+ }
11414
12394
  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) } : {} };
11415
12395
  if (Buffer.byteLength(JSON.stringify(result2)) > 2 * 1024 * 1024) throw new Error("Discovery exceeds 2 MiB");
11416
12396
  return result2;
@@ -11418,12 +12398,13 @@ function discoveryTransfer(value) {
11418
12398
  var init_dashboard_transfer = __esm({
11419
12399
  "src/inventory/dashboard-transfer.ts"() {
11420
12400
  "use strict";
12401
+ init_service_coverage();
11421
12402
  init_git();
11422
12403
  }
11423
12404
  });
11424
12405
 
11425
12406
  // src/inventory/store.ts
11426
- import { mkdir as mkdir6, readFile as readFile16, writeFile as writeFile11 } from "fs/promises";
12407
+ import { mkdir as mkdir6, readFile as readFile16, writeFile as writeFile12 } from "fs/promises";
11427
12408
  import { join as join24 } from "path";
11428
12409
  function storeDir(cwd) {
11429
12410
  return join24(cwd, STORE_DIR);
@@ -11433,7 +12414,7 @@ function storePath(cwd, name) {
11433
12414
  }
11434
12415
  async function ensureStore(cwd) {
11435
12416
  await mkdir6(storeDir(cwd), { recursive: true });
11436
- await writeFile11(storePath(cwd, ".gitignore"), STORE_GITIGNORE, "utf8");
12417
+ await writeFile12(storePath(cwd, ".gitignore"), STORE_GITIGNORE, "utf8");
11437
12418
  }
11438
12419
  async function readJson(path2) {
11439
12420
  try {
@@ -11443,7 +12424,7 @@ async function readJson(path2) {
11443
12424
  }
11444
12425
  }
11445
12426
  async function writeJson(path2, value) {
11446
- await writeFile11(path2, `${JSON.stringify(value, null, 2)}
12427
+ await writeFile12(path2, `${JSON.stringify(value, null, 2)}
11447
12428
  `, "utf8");
11448
12429
  }
11449
12430
  function defaultSources() {
@@ -11606,7 +12587,7 @@ var init_sanitize = __esm({
11606
12587
  });
11607
12588
 
11608
12589
  // src/commands/dashboard.ts
11609
- import { cp, mkdir as mkdir7, readFile as readFile17, writeFile as writeFile12 } from "fs/promises";
12590
+ import { cp, mkdir as mkdir7, readFile as readFile17, writeFile as writeFile13 } from "fs/promises";
11610
12591
  import { basename as basename2, join as join25 } from "path";
11611
12592
  import { fileURLToPath as fileURLToPath3 } from "url";
11612
12593
  function dashboardInventory(cwd, inventory) {
@@ -11622,7 +12603,7 @@ function dashboardInventory(cwd, inventory) {
11622
12603
  confidence: t.confidence ?? "low",
11623
12604
  interface: t.kind === "runtime" ? "terminal" : "api"
11624
12605
  })),
11625
- 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 })) }))
12606
+ 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 })) }))
11626
12607
  })));
11627
12608
  }
11628
12609
  var init_dashboard = __esm({
@@ -11643,7 +12624,7 @@ __export(session_exports, {
11643
12624
  writeSessionTask: () => writeSessionTask
11644
12625
  });
11645
12626
  import { spawn as spawn4, spawnSync } from "child_process";
11646
- import { writeFile as writeFile13, readFile as readFile18 } from "fs/promises";
12627
+ import { writeFile as writeFile14, readFile as readFile18 } from "fs/promises";
11647
12628
  import { join as join26 } from "path";
11648
12629
  function sessionTask() {
11649
12630
  return `# Prepare this repository for AgentTwin
@@ -11670,7 +12651,7 @@ function installedOpenCode() {
11670
12651
  }
11671
12652
  async function writeSessionTask(cwd) {
11672
12653
  const path2 = join26(cwd, ".agenttwin/AGENT-TASK.md");
11673
- await writeFile13(path2, sessionTask(), "utf8");
12654
+ await writeFile14(path2, sessionTask(), "utf8");
11674
12655
  return path2;
11675
12656
  }
11676
12657
  async function launchSession(cwd) {
@@ -11728,17 +12709,17 @@ __export(run_exports, {
11728
12709
  runWorld: () => runWorld,
11729
12710
  stageApplication: () => stageApplication
11730
12711
  });
11731
- 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";
12712
+ 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";
11732
12713
  import { tmpdir as tmpdir8 } from "os";
11733
12714
  import { basename as basename3, dirname as dirname4, isAbsolute as isAbsolute3, join as join27, relative as relative4, resolve as resolve7, sep as sep3 } from "path";
11734
- import { createHash as createHash14, randomUUID as randomUUID5 } from "crypto";
12715
+ import { createHash as createHash15, randomUUID as randomUUID5 } from "crypto";
11735
12716
  async function stageApplication(root, files, destination) {
11736
- const canonicalRoot = await realpath4(root);
12717
+ const canonicalRoot = await realpath5(root);
11737
12718
  const digests = {};
11738
12719
  let bytes = 0;
11739
12720
  for (const file of files) {
11740
12721
  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 });
11741
- const source = await realpath4(resolve7(canonicalRoot, file));
12722
+ const source = await realpath5(resolve7(canonicalRoot, file));
11742
12723
  const rel = relative4(canonicalRoot, source);
11743
12724
  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 });
11744
12725
  const contents = await readFile19(source);
@@ -11746,15 +12727,15 @@ async function stageApplication(root, files, destination) {
11746
12727
  if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
11747
12728
  const target = join27(destination, file);
11748
12729
  await mkdir8(dirname4(target), { recursive: true });
11749
- await writeFile14(target, contents, { mode: 420 });
11750
- digests[file] = createHash14("sha256").update(contents).digest("hex");
12730
+ await writeFile15(target, contents, { mode: 420 });
12731
+ digests[file] = createHash15("sha256").update(contents).digest("hex");
11751
12732
  }
11752
12733
  return digests;
11753
12734
  }
11754
12735
  async function resolveApplicationDirectory(worldDir, spec, stagedApp) {
11755
12736
  if (!spec.directory) return stagedApp;
11756
12737
  const target = resolve7(worldDir, spec.directory);
11757
- const dir = await realpath4(target).catch(() => {
12738
+ const dir = await realpath5(target).catch(() => {
11758
12739
  throw new CliError(`directory ${spec.directory} does not exist (resolved to ${target})`, { code: EXIT.USAGE });
11759
12740
  });
11760
12741
  if (!(await lstat2(dir)).isDirectory()) throw new CliError(`directory ${spec.directory} is not a folder`, { code: EXIT.USAGE });
@@ -11817,8 +12798,8 @@ async function runWorld(cwd, opts) {
11817
12798
  const stage = await mkdtemp8(join27(tmpdir8(), "agenttwin-world-"));
11818
12799
  try {
11819
12800
  const sourceDigests = await stageApplication(dirname4(file), spec.files, join27(stage, "app"));
11820
- await writeFile14(join27(stage, "world.json"), JSON.stringify(spec), { mode: 420 });
11821
- if (runtime === "e2b" && suppliedSeed) await writeFile14(join27(stage, "seed.json"), JSON.stringify({ seed: suppliedSeed }), { mode: 420 });
12801
+ await writeFile15(join27(stage, "world.json"), JSON.stringify(spec), { mode: 420 });
12802
+ if (runtime === "e2b" && suppliedSeed) await writeFile15(join27(stage, "seed.json"), JSON.stringify({ seed: suppliedSeed }), { mode: 420 });
11822
12803
  const git2 = await captureGit(sourceBuild?.root ?? cwd);
11823
12804
  let project;
11824
12805
  try {
@@ -11845,14 +12826,14 @@ async function runWorld(cwd, opts) {
11845
12826
  }
11846
12827
  }
11847
12828
  const runId2 = randomUUID5();
11848
- 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" };
12829
+ 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: createHash15("sha256").update(JSON.stringify(spec)).digest("hex"), provenance: "CLI-reported execution" };
11849
12830
  const out2 = resolve7(cwd, opts.out ?? `.agenttwin/runs/${runId2}`);
11850
12831
  await mkdir8(out2, { recursive: true });
11851
12832
  const evidencePath = join27(out2, "run.json"), reportPath = join27(out2, "report.md");
11852
- await writeFile14(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
11853
- await writeFile14(join27(out2, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
12833
+ await writeFile15(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
12834
+ await writeFile15(join27(out2, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
11854
12835
  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("/")}`];
11855
- await writeFile14(reportPath, renderRunSummary({ ...receipt2, runId: runId2 }, { markdown: true, next, costs: await readCostConfig(cwd) }) + `
12836
+ await writeFile15(reportPath, renderRunSummary({ ...receipt2, runId: runId2 }, { markdown: true, next, costs: await readCostConfig(cwd) }) + `
11856
12837
  Runner: CLI \xB7 Git: ${git2?.head ?? "unavailable"} \xB7 Seed: ${receipt2.seed}
11857
12838
  ${receipt2.reproducibility ?? ""}
11858
12839
  ${sourceBuildError ?? ""}
@@ -11865,15 +12846,15 @@ Full evidence (activities, fault, initial and final state): run.json
11865
12846
  const receipt2 = await executeRemote(stage, spec, opts.log, { git: git2, project, seed: suppliedSeed });
11866
12847
  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");
11867
12848
  if (suppliedSeed && receipt2.seed !== suppliedSeed) throw new CliError("Hosted receipt does not match the requested seed");
11868
- const expectedSpec = createHash14("sha256").update(JSON.stringify(spec)).digest("hex");
12849
+ const expectedSpec = createHash15("sha256").update(JSON.stringify(spec)).digest("hex");
11869
12850
  const reportedSources = receipt2.sourceDigests;
11870
12851
  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");
11871
12852
  const out2 = resolve7(cwd, opts.out ?? `.agenttwin/runs/${receipt2.runId}`);
11872
12853
  await mkdir8(out2, { recursive: true });
11873
12854
  const evidencePath = join27(out2, "run.json");
11874
12855
  const reportPath = join27(out2, "report.md");
11875
- await writeFile14(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
11876
- await writeFile14(reportPath, `# ${spec.name}: ${receipt2.status}
12856
+ await writeFile15(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
12857
+ await writeFile15(reportPath, `# ${spec.name}: ${receipt2.status}
11877
12858
 
11878
12859
  Run: ${receipt2.runId}
11879
12860
 
@@ -11903,15 +12884,15 @@ See run.json for assertions, service state, application output and isolation met
11903
12884
  image,
11904
12885
  templateBuildId,
11905
12886
  sourceDigests,
11906
- specDigest: createHash14("sha256").update(JSON.stringify(spec)).digest("hex"),
12887
+ specDigest: createHash15("sha256").update(JSON.stringify(spec)).digest("hex"),
11907
12888
  isolation
11908
12889
  };
11909
12890
  const out = resolve7(cwd, opts.out ?? `.agenttwin/runs/${runId}`);
11910
12891
  await mkdir8(out, { recursive: true });
11911
- await writeFile14(join27(out, "run.json"), JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
11912
- await writeFile14(join27(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
12892
+ await writeFile15(join27(out, "run.json"), JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
12893
+ await writeFile15(join27(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
11913
12894
  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");
11914
- await writeFile14(join27(out, "report.md"), summary);
12895
+ await writeFile15(join27(out, "report.md"), summary);
11915
12896
  return { ...receipt, reportPath: join27(out, "report.md"), evidencePath: join27(out, "run.json") };
11916
12897
  } finally {
11917
12898
  await rm10(stage, { recursive: true, force: true });
@@ -11940,7 +12921,7 @@ var init_run = __esm({
11940
12921
  // src/runtime/docker.ts
11941
12922
  import { execFile as execFile9, spawn as spawn5 } from "child_process";
11942
12923
  import { promisify as promisify9 } from "util";
11943
- 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";
12924
+ 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";
11944
12925
  import { tmpdir as tmpdir9 } from "os";
11945
12926
  import { join as join28 } from "path";
11946
12927
  import { randomUUID as randomUUID6 } from "crypto";
@@ -11971,7 +12952,7 @@ async function executeDocker(app, spec, opts = {}) {
11971
12952
  await mkdir9(support, { mode: 493 });
11972
12953
  await copyFile2(hook.path, join28(support, "source.cjs"));
11973
12954
  await chmod3(join28(support, "source.cjs"), 420);
11974
- await writeFile15(join28(support, "bridge.cjs"), stdioFetchHook(credentials2, !!database), { mode: 420 });
12955
+ await writeFile16(join28(support, "bridge.cjs"), stdioFetchHook(credentials2, !!database), { mode: 420 });
11975
12956
  const env = Object.entries(credentials2).flatMap(([name, c]) => ["--env", `AGENTTWIN_${name.toUpperCase()}_URL=${c.endpoint}`, "--env", `AGENTTWIN_${name.toUpperCase()}_TOKEN=${c.token}`]);
11976
12957
  let stdout = "", stderr = "", timedOut = false;
11977
12958
  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)];
@@ -12082,54 +13063,31 @@ var init_docker = __esm({
12082
13063
  }
12083
13064
  });
12084
13065
 
12085
- // src/inventory/service-coverage.ts
12086
- function serviceSupport(tool) {
12087
- const provider = tool.providerId ?? tool.title.toLowerCase();
12088
- const adapters = ADAPTER_GROUPS[provider] ?? TWIN_ADAPTERS.filter((name) => name === provider);
12089
- 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." };
12090
- 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." };
12091
- 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." };
12092
- }
12093
- var TWIN_ADAPTERS, ADAPTER_GROUPS;
12094
- var init_service_coverage = __esm({
12095
- "src/inventory/service-coverage.ts"() {
12096
- "use strict";
12097
- init_contracts();
12098
- init_enterprise_twins();
12099
- 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];
12100
- ADAPTER_GROUPS = {
12101
- google: ["gmail", "google-calendar", "google-oauth"],
12102
- atlassian: ["jira", "confluence"],
12103
- microsoft: ["microsoft-teams", "outlook", "entra-id", "sharepoint"]
12104
- };
12105
- }
12106
- });
12107
-
12108
13066
  // src/inventory/workflows.ts
12109
13067
  function permissionsFor(kind, entities) {
12110
- const list2 = [];
12111
- if (kind === "payments") list2.push("payments:read", "payments:write");
12112
- else if (kind === "comms") list2.push("messages:read", "messages:write");
12113
- else if (kind === "crm" || kind === "support") list2.push("records:read", "records:write");
12114
- else list2.push("read", "write");
12115
- for (const entity of entities) list2.push(`${entity}:read`, `${entity}:write`);
12116
- return [...new Set(list2)].sort();
13068
+ const list3 = [];
13069
+ if (kind === "payments") list3.push("payments:read", "payments:write");
13070
+ else if (kind === "comms") list3.push("messages:read", "messages:write");
13071
+ else if (kind === "crm" || kind === "support") list3.push("records:read", "records:write");
13072
+ else list3.push("read", "write");
13073
+ for (const entity of entities) list3.push(`${entity}:read`, `${entity}:write`);
13074
+ return [...new Set(list3)].sort();
12117
13075
  }
12118
13076
  function eventsFor(kind, entities) {
12119
- const list2 = [];
12120
- if (kind === "payments") list2.push("webhook: charge.refunded / payment_intent.succeeded");
12121
- if (kind === "comms") list2.push("delivery receipt / message.changed");
12122
- if (kind === "queue") list2.push("message delivery (duplicate / out-of-order)");
12123
- list2.push(...entities.map((e) => `webhook: ${e}.created / ${e}.updated`));
12124
- return [...new Set(list2)];
13077
+ const list3 = [];
13078
+ if (kind === "payments") list3.push("webhook: charge.refunded / payment_intent.succeeded");
13079
+ if (kind === "comms") list3.push("delivery receipt / message.changed");
13080
+ if (kind === "queue") list3.push("message delivery (duplicate / out-of-order)");
13081
+ list3.push(...entities.map((e) => `webhook: ${e}.created / ${e}.updated`));
13082
+ return [...new Set(list3)];
12125
13083
  }
12126
13084
  function scenariosFor(kind) {
12127
- const list2 = ["timeout after a successful write (response lost)"];
12128
- if (kind === "payments") list2.push("duplicate refund / double charge");
12129
- if (kind === "queue") list2.push("duplicate or out-of-order delivery");
12130
- if (kind === "database") list2.push("partial write / rollback");
12131
- list2.push("permission revoked mid-flow", "rate limit / 429");
12132
- return [...new Set(list2)];
13085
+ const list3 = ["timeout after a successful write (response lost)"];
13086
+ if (kind === "payments") list3.push("duplicate refund / double charge");
13087
+ if (kind === "queue") list3.push("duplicate or out-of-order delivery");
13088
+ if (kind === "database") list3.push("partial write / rollback");
13089
+ list3.push("permission revoked mid-flow", "rate limit / 429");
13090
+ return [...new Set(list3)];
12133
13091
  }
12134
13092
  function assertionsFor(candidate) {
12135
13093
  if (candidate.entrypoint) return [
@@ -12320,9 +13278,9 @@ var init_languages = __esm({
12320
13278
  const ext = file.slice(file.lastIndexOf(".") + 1).toLowerCase();
12321
13279
  const lang = EXT_LANG[ext];
12322
13280
  if (!lang) continue;
12323
- const list2 = byLang.get(lang) ?? [];
12324
- if (list2.length < 20) list2.push(file);
12325
- byLang.set(lang, list2);
13281
+ const list3 = byLang.get(lang) ?? [];
13282
+ if (list3.length < 20) list3.push(file);
13283
+ byLang.set(lang, list3);
12326
13284
  }
12327
13285
  const findings = [];
12328
13286
  for (const [lang, refs] of byLang) {
@@ -12702,8 +13660,8 @@ var init_k8s = __esm({
12702
13660
  } catch {
12703
13661
  continue;
12704
13662
  }
12705
- const list2 = Array.isArray(docs) ? docs : [docs];
12706
- for (const doc of list2) {
13663
+ const list3 = Array.isArray(docs) ? docs : [docs];
13664
+ for (const doc of list3) {
12707
13665
  const containers = extractContainers(doc);
12708
13666
  for (const image of containers) {
12709
13667
  const info = classifyImage(image);
@@ -13198,9 +14156,9 @@ var init_ci = __esm({
13198
14156
  const prefixes = provider.signatures.envPrefixes ?? [];
13199
14157
  if (prefixes.length === 0) continue;
13200
14158
  if (prefixes.some((p) => text3.includes(p))) {
13201
- const list2 = providerEvidence.get(provider.id) ?? [];
13202
- list2.push({ ref: path2, pass: "environment", signal: "ci", detail: provider.id });
13203
- providerEvidence.set(provider.id, list2);
14159
+ const list3 = providerEvidence.get(provider.id) ?? [];
14160
+ list3.push({ ref: path2, pass: "environment", signal: "ci", detail: provider.id });
14161
+ providerEvidence.set(provider.id, list3);
13204
14162
  }
13205
14163
  }
13206
14164
  }
@@ -13847,7 +14805,7 @@ var init_identity = __esm({
13847
14805
  });
13848
14806
 
13849
14807
  // src/inventory/canonical.ts
13850
- import { createHash as createHash18 } from "crypto";
14808
+ import { createHash as createHash19 } from "crypto";
13851
14809
  function sortKeys(value) {
13852
14810
  if (Array.isArray(value)) return value.map(sortKeys);
13853
14811
  if (value && typeof value === "object") {
@@ -13875,7 +14833,7 @@ function canonicalContent(inventory) {
13875
14833
  }
13876
14834
  function canonicalHash(inventory) {
13877
14835
  const content = JSON.stringify(canonicalContent(inventory));
13878
- return `sha256:${createHash18("sha256").update(content).digest("hex").slice(0, 32)}`;
14836
+ return `sha256:${createHash19("sha256").update(content).digest("hex").slice(0, 32)}`;
13879
14837
  }
13880
14838
  function withCanonicalHash(inventory) {
13881
14839
  return { ...inventory, canonicalHash: canonicalHash(inventory) };
@@ -14379,9 +15337,9 @@ function workflowGraph(sources, operations, tools, options = {}) {
14379
15337
  locals.set(mod, declared);
14380
15338
  walk2(ast.program, (node) => {
14381
15339
  if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
14382
- const list2 = declared.get(node.id.name) ?? [];
14383
- list2.push({ line: node.loc.start.line, init: node.init });
14384
- declared.set(node.id.name, list2);
15340
+ const list3 = declared.get(node.id.name) ?? [];
15341
+ list3.push({ line: node.loc.start.line, init: node.init });
15342
+ declared.set(node.id.name, list3);
14385
15343
  }
14386
15344
  if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && unwrap(node.init)) toolNames.set(unwrap(node.init), node.id.name);
14387
15345
  if (node.type === "ObjectProperty" && propertyName(node.key) && unwrap(node.value)) toolNames.set(unwrap(node.value), propertyName(node.key));
@@ -14618,9 +15576,9 @@ function workflowGraph(sources, operations, tools, options = {}) {
14618
15576
  };
14619
15577
  const byPath = /* @__PURE__ */ new Map();
14620
15578
  for (const operation of operations) {
14621
- const list2 = byPath.get(operation.path) ?? [];
14622
- list2.push(operation);
14623
- byPath.set(operation.path, list2);
15579
+ const list3 = byPath.get(operation.path) ?? [];
15580
+ list3.push(operation);
15581
+ byPath.set(operation.path, list3);
14624
15582
  }
14625
15583
  const directEffects = /* @__PURE__ */ new Map();
14626
15584
  const effects2 = (unit) => {
@@ -14960,12 +15918,12 @@ function createSdkScanner(project) {
14960
15918
  if (!ast) return ops;
14961
15919
  const consumed = /* @__PURE__ */ new Set();
14962
15920
  const seen = /* @__PURE__ */ new Set();
14963
- const push = (node, providerId, kind, label2, resource) => {
15921
+ const push = (node, providerId, kind, label2, resource, stripeItemFields) => {
14964
15922
  const line = node.loc?.start.line ?? 1;
14965
15923
  const key2 = `${line}|${providerId}|${label2}`;
14966
- if (seen.has(key2)) return;
15924
+ if (stripeItemFields === void 0 && seen.has(key2)) return;
14967
15925
  seen.add(key2);
14968
- ops.push({ line, providerId, kind, label: label2, resource: resource.replace(/[^\w.-]/g, "_") || providerId });
15926
+ ops.push({ line, providerId, kind, label: label2, resource: resource.replace(/[^\w.-]/g, "_") || providerId, stripeItemFields });
14969
15927
  };
14970
15928
  const rootBinding = (root) => {
14971
15929
  const value = unwrap(root);
@@ -15045,7 +16003,14 @@ function createSdkScanner(project) {
15045
16003
  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");
15046
16004
  const kind = verbKind(verb, ai);
15047
16005
  if (!kind) return;
15048
- push(node, provider, kind, names.slice(-2).join("."), names.length > 1 ? names[names.length - 2] : provider);
16006
+ const label2 = names.slice(-2).join(".");
16007
+ let stripeItemFields;
16008
+ if (provider === "stripe" && label2 === "subscriptionItems.update") {
16009
+ const params = unwrap(segments.at(-1)?.args[1]);
16010
+ const keys = params?.type === "ObjectExpression" ? params.properties.map((p) => p.type === "ObjectProperty" && !p.computed ? propertyName(p.key) : void 0) : void 0;
16011
+ stripeItemFields = keys?.every((key2) => typeof key2 === "string") ? keys : null;
16012
+ }
16013
+ push(node, provider, kind, label2, names.length > 1 ? names[names.length - 2] : provider, stripeItemFields);
15049
16014
  };
15050
16015
  walk(ast.program, (node) => {
15051
16016
  if (node.type === "TaggedTemplateExpression") {
@@ -15121,7 +16086,7 @@ var init_sdk_calls = __esm({
15121
16086
  });
15122
16087
 
15123
16088
  // src/inventory/relationships.ts
15124
- import { createHash as createHash19 } from "crypto";
16089
+ import { createHash as createHash20 } from "crypto";
15125
16090
  function datastoreFor(pkg, fallback) {
15126
16091
  if (/^(pg|pg-pool|postgres|pg-promise|slonik|@neondatabase\/serverless|@vercel\/postgres)(\/|$)/.test(pkg)) return "postgres";
15127
16092
  if (/^(mysql|mysql2|@planetscale\/database)(\/|$)/.test(pkg)) return "mysql";
@@ -15155,8 +16120,8 @@ function packagesFor(providerId) {
15155
16120
  const provider = PROVIDERS.find((p) => p.id === providerId);
15156
16121
  if (!provider) return [];
15157
16122
  const set = /* @__PURE__ */ new Set();
15158
- for (const list2 of Object.values(provider.signatures.packages ?? {})) {
15159
- for (const pkg of list2) set.add(pkg.replace(/\/$/, ""));
16123
+ for (const list3 of Object.values(provider.signatures.packages ?? {})) {
16124
+ for (const pkg of list3) set.add(pkg.replace(/\/$/, ""));
15160
16125
  }
15161
16126
  return [...set];
15162
16127
  }
@@ -15215,9 +16180,9 @@ function riskFor(kind) {
15215
16180
  function workflowGroupKey(providerId, tool) {
15216
16181
  return `${providerId}|${tool?.accounts.join(",") ?? ""}|${tool?.environment ?? ""}`;
15217
16182
  }
15218
- function stepsFor(apps, list2, toolId) {
16183
+ function stepsFor(apps, list3, toolId) {
15219
16184
  return apps.map((app) => {
15220
- const records = list2.filter((r) => r.app === app);
16185
+ const records = list3.filter((r) => r.app === app);
15221
16186
  return {
15222
16187
  app,
15223
16188
  tool: toolId,
@@ -15248,9 +16213,9 @@ async function buildRelationships(apps, tools, files, decisions) {
15248
16213
  const byApp = /* @__PURE__ */ new Map();
15249
16214
  for (const ref of fileRefs(tool)) {
15250
16215
  const app = appForPath(apps, ref);
15251
- const list2 = byApp.get(app.id) ?? [];
15252
- list2.push({ source: "static", ref });
15253
- byApp.set(app.id, list2);
16216
+ const list3 = byApp.get(app.id) ?? [];
16217
+ list3.push({ source: "static", ref });
16218
+ byApp.set(app.id, list3);
15254
16219
  }
15255
16220
  for (const [appId, evidence] of byApp) {
15256
16221
  const id = `uses:${appId}:${tool.id}`;
@@ -15309,7 +16274,7 @@ async function buildRelationships(apps, tools, files, decisions) {
15309
16274
  const sdkLines = new Set(sdkOperations.map((op2) => `${op2.line}|${op2.providerId}`));
15310
16275
  const astBindings = /\.[cm]?[jt]sx?$/.test(path2) ? scanner.bindings(path2) : /* @__PURE__ */ new Map();
15311
16276
  const operations = [
15312
- ...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 })),
16277
+ ...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 })),
15313
16278
  ...scanOperations(text3, path2),
15314
16279
  ...httpOperations
15315
16280
  ];
@@ -15341,7 +16306,7 @@ async function buildRelationships(apps, tools, files, decisions) {
15341
16306
  evidence: []
15342
16307
  };
15343
16308
  const label2 = op2.label ?? `${op2.resource}.${op2.verb}`;
15344
- 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 });
16309
+ 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 });
15345
16310
  if (!record4.operations.includes(label2)) record4.operations.push(label2);
15346
16311
  if (!record4.resources.includes(op2.resource)) record4.resources.push(op2.resource);
15347
16312
  if (!record4.evidence.some((e) => e.ref === op2.ref)) record4.evidence.push({ source: "static", ref: op2.ref });
@@ -15379,19 +16344,19 @@ async function buildRelationships(apps, tools, files, decisions) {
15379
16344
  for (const record4 of decidedRecords) {
15380
16345
  if (!providerTools.some((t) => t.providerId === record4.providerId)) continue;
15381
16346
  const key2 = workflowGroupKey(record4.providerId, toolByProvider.get(record4.providerId));
15382
- const list2 = byGroup.get(key2) ?? [];
15383
- list2.push(record4);
15384
- byGroup.set(key2, list2);
16347
+ const list3 = byGroup.get(key2) ?? [];
16348
+ list3.push(record4);
16349
+ byGroup.set(key2, list3);
15385
16350
  }
15386
16351
  const workflows = [];
15387
16352
  const gaps = [];
15388
- for (const list2 of byGroup.values()) {
15389
- const providerId = list2[0].providerId;
16353
+ for (const list3 of byGroup.values()) {
16354
+ const providerId = list3[0].providerId;
15390
16355
  const tool = toolByProvider.get(providerId);
15391
16356
  if (!tool) continue;
15392
- const appsInvolved = [...new Set(list2.map((r) => r.app))].sort();
15393
- const producers = list2.filter((r) => r.kind === "writes" || r.kind === "emits");
15394
- const consumers = list2.filter((r) => r.kind === "reads" || r.kind === "emits");
16357
+ const appsInvolved = [...new Set(list3.map((r) => r.app))].sort();
16358
+ const producers = list3.filter((r) => r.kind === "writes" || r.kind === "emits");
16359
+ const consumers = list3.filter((r) => r.kind === "reads" || r.kind === "emits");
15395
16360
  if (producers.length === 0 || consumers.length === 0) {
15396
16361
  if (appsInvolved.length >= 2) {
15397
16362
  gaps.push(
@@ -15400,8 +16365,8 @@ async function buildRelationships(apps, tools, files, decisions) {
15400
16365
  }
15401
16366
  continue;
15402
16367
  }
15403
- const writeResources = list2.filter((r) => r.kind === "writes").flatMap(entityResources);
15404
- const readResources = list2.filter((r) => r.kind === "reads").flatMap(entityResources);
16368
+ const writeResources = list3.filter((r) => r.kind === "writes").flatMap(entityResources);
16369
+ const readResources = list3.filter((r) => r.kind === "reads").flatMap(entityResources);
15405
16370
  const sharedIntersection = [...new Set(writeResources.filter((r) => readResources.includes(r)))];
15406
16371
  const producerApps = [...new Set(producers.map((r) => r.app))].sort();
15407
16372
  const consumerApps = [...new Set(consumers.map((r) => r.app))].sort();
@@ -15426,10 +16391,10 @@ async function buildRelationships(apps, tools, files, decisions) {
15426
16391
  title: `${app} via ${tool.title}`,
15427
16392
  apps: [app],
15428
16393
  tools: [tool.id],
15429
- steps: stepsFor([app], list2, tool.id),
16394
+ steps: stepsFor([app], list3, tool.id),
15430
16395
  sharedEntities: sharedIntersection.length > 0 ? sharedIntersection : [singularize(providerId)],
15431
- evidence: list2.flatMap((r) => r.evidence),
15432
- confidence: confidenceFrom(list2.flatMap((r) => r.evidence).length),
16396
+ evidence: list3.flatMap((r) => r.evidence),
16397
+ confidence: confidenceFrom(list3.flatMap((r) => r.evidence).length),
15433
16398
  risk: riskFor(tool.kind),
15434
16399
  rank: 0,
15435
16400
  supported: supported2,
@@ -15473,10 +16438,10 @@ async function buildRelationships(apps, tools, files, decisions) {
15473
16438
  title: `${orderedApps.join(" \u2192 ")} via ${tool.title}`,
15474
16439
  apps: orderedApps,
15475
16440
  tools: [tool.id],
15476
- steps: stepsFor(orderedApps, list2, tool.id),
16441
+ steps: stepsFor(orderedApps, list3, tool.id),
15477
16442
  sharedEntities: entities.length > 0 ? entities : [singularize(providerId)],
15478
- evidence: list2.flatMap((r) => r.evidence),
15479
- confidence: confidenceFrom(list2.flatMap((r) => r.evidence).length),
16443
+ evidence: list3.flatMap((r) => r.evidence),
16444
+ confidence: confidenceFrom(list3.flatMap((r) => r.evidence).length),
15480
16445
  risk: riskFor(tool.kind),
15481
16446
  rank: 0,
15482
16447
  supported,
@@ -15509,7 +16474,7 @@ async function buildRelationships(apps, tools, files, decisions) {
15509
16474
  const name = `script:${path2.split("/").pop()}`;
15510
16475
  entries.push({ name, startLine: 1, endLine: Number.MAX_SAFE_INTEGER, path: path2, exported: false, trigger: true, calls, evidence: [{ source: "static", ref: `${path2}:1` }] });
15511
16476
  }
15512
- const entryId = (path2, name) => "entry:" + createHash19("sha256").update(path2 + ":" + name).digest("hex").slice(0, 20);
16477
+ const entryId = (path2, name) => "entry:" + createHash20("sha256").update(path2 + ":" + name).digest("hex").slice(0, 20);
15513
16478
  for (const entry of entries) {
15514
16479
  const { path: path2 } = entry;
15515
16480
  const app = appForPath(apps, path2);
@@ -15525,7 +16490,8 @@ async function buildRelationships(apps, tools, files, decisions) {
15525
16490
  entrypoint: path2 + "#" + entry.name.replace(/\\/g, "%5C"),
15526
16491
  apps: [app.id],
15527
16492
  tools: dependencies,
15528
- steps: dependencies.map((tool) => ({ app: app.id, tool, operations: [...new Set(calls.filter((c) => c.toolId === tool).map((c) => c.label))], evidence })),
16493
+ // A step's evidence is the lines that make its calls; the workflow's evidence keeps every unit it reaches.
16494
+ 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 })) })),
15529
16495
  sharedEntities: [...new Set(calls.map((call2) => singularize(call2.resource)))],
15530
16496
  evidence,
15531
16497
  confidence: "medium",
@@ -15542,6 +16508,20 @@ async function buildRelationships(apps, tools, files, decisions) {
15542
16508
  const finalWorkflows = workflows.filter((w) => !rejected.has(w.id)).map(
15543
16509
  (w) => confirmed.has(w.id) ? { ...w, supported: true, hypothesis: false, linkingSignals: [...w.linkingSignals, "confirmed by decision"] } : w
15544
16510
  );
16511
+ const stripeTools = new Set(providerTools.filter((tool) => tool.providerId === "stripe").map((tool) => tool.id));
16512
+ for (const workflow of finalWorkflows) {
16513
+ for (const step of workflow.steps) {
16514
+ if (!stripeTools.has(step.tool) || !step.operations.includes("subscriptionItems.update")) continue;
16515
+ const refs = new Set(step.evidence.map((e) => e.ref));
16516
+ const updates = allowedCalls.filter((call2) => call2.toolId === step.tool && call2.label === "subscriptionItems.update" && refs.has(call2.ref));
16517
+ const fields = updates.flatMap((call2) => call2.stripeItemFields ?? []);
16518
+ 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;
16519
+ }
16520
+ const missing = missingStripeOperations(workflow, stripeTools);
16521
+ if (!missing.length) continue;
16522
+ workflow.supported = false;
16523
+ workflow.linkingSignals.push(`Stripe twin does not cover ${missing.join(", ")}`);
16524
+ }
15545
16525
  const riskWeight = { low: 0, medium: 1, high: 2 };
15546
16526
  finalWorkflows.sort(
15547
16527
  (a, b) => Number(b.supported) - Number(a.supported) || // Routes and jobs are how a workflow is actually triggered; list them before helpers.
@@ -15555,6 +16535,7 @@ var SOURCE_EXTS2, MAX_FILES3, NON_USAGE_DIR2, PROVIDER_KINDS, DATASTORE_IDS, CLA
15555
16535
  var init_relationships = __esm({
15556
16536
  "src/inventory/relationships.ts"() {
15557
16537
  "use strict";
16538
+ init_service_coverage();
15558
16539
  init_provider_factories();
15559
16540
  init_entrypoints();
15560
16541
  init_workflow_graph();
@@ -15645,7 +16626,7 @@ var init_scope = __esm({
15645
16626
 
15646
16627
  // src/observation/runtime.ts
15647
16628
  import { spawn as spawn7 } from "child_process";
15648
- import { mkdtemp as mkdtemp12, open as open2, writeFile as writeFile19, rm as rm14, realpath as realpath7 } from "fs/promises";
16629
+ import { mkdtemp as mkdtemp12, open as open2, writeFile as writeFile20, rm as rm14, realpath as realpath8 } from "fs/promises";
15649
16630
  import { tmpdir as tmpdir13 } from "os";
15650
16631
  import { join as join34, basename as basename4 } from "path";
15651
16632
  function validHost(host) {
@@ -15741,7 +16722,7 @@ require('node:module').syncBuiltinESMExports();
15741
16722
  });
15742
16723
 
15743
16724
  // src/inventory/observed.ts
15744
- import { createHash as createHash20 } from "crypto";
16725
+ import { createHash as createHash21 } from "crypto";
15745
16726
  function mergeObservations(workflows, tools, report) {
15746
16727
  if (!report?.services.length) return workflows;
15747
16728
  const toolFor = (host) => {
@@ -15776,7 +16757,7 @@ function mergeObservations(workflows, tools, report) {
15776
16757
  const toolIds = [...new Set(calls.map((c) => c.tool.id))];
15777
16758
  const evidence = [...new Set(events.flatMap((e) => [e.source, ...e.frames ?? []]).filter((r) => !!r))].map((ref) => ({ source: "runtime-attempt", ref }));
15778
16759
  merged.push({
15779
- id: "runtime:" + createHash20("sha256").update(entry).digest("hex").slice(0, 20),
16760
+ id: "runtime:" + createHash21("sha256").update(entry).digest("hex").slice(0, 20),
15780
16761
  title: `runtime:${entry}`,
15781
16762
  entrypoint: `${path2}#runtime:${entry.slice(entry.lastIndexOf(":") + 1)}`,
15782
16763
  apps: ["(root)"],
@@ -16811,12 +17792,12 @@ async function runExport(opts) {
16811
17792
  const plan = await readPlan(opts.cwd);
16812
17793
  const bundle = { schema: "export/v1", inventory, plan: plan ?? null };
16813
17794
  if (opts.out) {
16814
- const { mkdir: mkdir14, writeFile: writeFile22 } = await import("fs/promises");
17795
+ const { mkdir: mkdir14, writeFile: writeFile23 } = await import("fs/promises");
16815
17796
  const { join: join39 } = await import("path");
16816
17797
  await mkdir14(opts.out, { recursive: true });
16817
- await writeFile22(join39(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
17798
+ await writeFile23(join39(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
16818
17799
  `, "utf8");
16819
- if (plan) await writeFile22(join39(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
17800
+ if (plan) await writeFile23(join39(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
16820
17801
  `, "utf8");
16821
17802
  return { schema: "export/v1", out: opts.out, wrote: ["inventory.json", ...plan ? ["plan.json"] : []] };
16822
17803
  }
@@ -17013,7 +17994,7 @@ function verifyWebhookSignature(secret, raw, header3) {
17013
17994
  return given.length === expected.length && timingSafeEqual2(given, expected);
17014
17995
  }
17015
17996
  var MAX_EVENTS = 500;
17016
- var repoNames = (list2) => Array.isArray(list2) ? list2.map((r) => r?.full_name).filter((n) => typeof n === "string" && /^[\w.-]+\/[\w.-]+$/.test(n)).slice(0, 1e3) : [];
17997
+ var repoNames = (list3) => Array.isArray(list3) ? list3.map((r) => r?.full_name).filter((n) => typeof n === "string" && /^[\w.-]+\/[\w.-]+$/.test(n)).slice(0, 1e3) : [];
17017
17998
  function applyWebhook(state, event, payload, now = /* @__PURE__ */ new Date()) {
17018
17999
  const installationId = Number(payload?.installation?.id);
17019
18000
  if (!Number.isSafeInteger(installationId) || installationId <= 0) return { handled: false, detail: "no installation" };
@@ -17323,20 +18304,20 @@ init_spec();
17323
18304
  init_scenarios();
17324
18305
  init_local();
17325
18306
  init_docker();
17326
- import { createHash as createHash17 } from "crypto";
18307
+ import { createHash as createHash18 } from "crypto";
17327
18308
  import { execFile as execFile10 } from "child_process";
17328
18309
  import { promisify as promisify10 } from "util";
17329
- 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";
18310
+ 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";
17330
18311
  import { tmpdir as tmpdir11 } from "os";
17331
18312
  import { dirname as dirname6, join as join31, relative as relative6, resolve as resolve10, sep as sep6 } from "path";
17332
18313
 
17333
18314
  // src/runtime/callable.ts
17334
18315
  init_entrypoints();
17335
18316
  import { build } from "esbuild";
17336
- import { readFile as readFile21, realpath as realpath5, writeFile as writeFile16 } from "fs/promises";
18317
+ import { readFile as readFile21, realpath as realpath6, writeFile as writeFile17 } from "fs/promises";
17337
18318
  import { resolve as resolve8, relative as relative5, isAbsolute as isAbsolute4, sep as sep4, join as join29, extname } from "path";
17338
- import { createHash as createHash15 } from "crypto";
17339
- var digest4 = (value) => createHash15("sha256").update(value).digest("hex");
18319
+ import { createHash as createHash16 } from "crypto";
18320
+ var digest4 = (value) => createHash16("sha256").update(value).digest("hex");
17340
18321
  var object5 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
17341
18322
  function argument(value, depth = 0) {
17342
18323
  if (depth > 8 || !object5(value)) throw new Error("Invalid callable argument binding");
@@ -17371,10 +18352,10 @@ function parseCallable(value) {
17371
18352
  return value;
17372
18353
  }
17373
18354
  async function resolveCallableSource(root, entrypoint) {
17374
- const canonical5 = await realpath5(root);
18355
+ const canonical5 = await realpath6(root);
17375
18356
  const [file, member, ...extra] = entrypoint.split("#");
17376
18357
  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");
17377
- const source = await realpath5(resolve8(canonical5, file));
18358
+ const source = await realpath6(resolve8(canonical5, file));
17378
18359
  if (source !== resolve8(canonical5, file) || relative5(canonical5, source).startsWith(".." + sep4)) throw new Error("Callable source escapes the project or uses a symlink");
17379
18360
  const text3 = await readFile21(source, "utf8"), entries = exportedEntrypoints(text3).filter((entry) => !entry.name.includes(":"));
17380
18361
  let selected = entries.find((entry) => entry.name === member);
@@ -17417,7 +18398,7 @@ for(const [index,call]of invocation.calls.entries()){
17417
18398
  let bytes = 0;
17418
18399
  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) {
17419
18400
  plugin.onLoad({ filter: /.*/ }, async (args) => {
17420
- const path2 = await realpath5(args.path), rel = relative5(canonical5, path2);
18401
+ const path2 = await realpath6(args.path), rel = relative5(canonical5, path2);
17421
18402
  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);
17422
18403
  const contents = await readFile21(path2);
17423
18404
  bytes += contents.length;
@@ -17430,7 +18411,7 @@ for(const [index,call]of invocation.calls.entries()){
17430
18411
  } }] });
17431
18412
  const code = built.outputFiles[0].contents;
17432
18413
  if (code.length > 20 * 1024 * 1024) throw new Error("Callable bundle exceeds 20 MiB");
17433
- await writeFile16(join29(out, "application.cjs"), code, { flag: "wx", mode: 384 });
18414
+ await writeFile17(join29(out, "application.cjs"), code, { flag: "wx", mode: 384 });
17434
18415
  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." };
17435
18416
  }
17436
18417
 
@@ -17438,12 +18419,12 @@ for(const [index,call]of invocation.calls.entries()){
17438
18419
  init_source_build();
17439
18420
 
17440
18421
  // src/runtime/protected-callable.ts
17441
- import { createHash as createHash16 } from "crypto";
17442
- 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";
18422
+ import { createHash as createHash17 } from "crypto";
18423
+ 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";
17443
18424
  import { dirname as dirname5, join as join30, resolve as resolve9, sep as sep5 } from "path";
17444
18425
  import { tmpdir as tmpdir10 } from "os";
17445
18426
  init_source_build();
17446
- var hash3 = (bytes) => createHash16("sha256").update(bytes).digest("hex");
18427
+ var hash3 = (bytes) => createHash17("sha256").update(bytes).digest("hex");
17447
18428
  function safeBuildPath(file) {
17448
18429
  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);
17449
18430
  }
@@ -17459,8 +18440,8 @@ function parseProtectedCallable(value) {
17459
18440
  }
17460
18441
  async function boundedBuildFile(root, file) {
17461
18442
  if (!safeBuildPath(file)) throw Error("Unsafe protected build path");
17462
- const canonical5 = await realpath6(root), path2 = resolve9(canonical5, file), info = await lstat3(path2);
17463
- 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);
18443
+ const canonical5 = await realpath7(root), path2 = resolve9(canonical5, file), info = await lstat3(path2);
18444
+ 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);
17464
18445
  const bytes = await readFile22(path2);
17465
18446
  if (bytes.length > 20 * 1024 * 1024) throw Error("Protected build file exceeds bounds");
17466
18447
  return bytes;
@@ -17474,13 +18455,13 @@ async function stageTrustedBuildFiles(cwd, out, files) {
17474
18455
  if (hash3(bytes) !== expected) throw Error("Trusted dependency or resolution metadata changed: " + file + "; restore the baseline installation or review a new regression");
17475
18456
  const target = join30(out, file);
17476
18457
  await mkdir10(dirname5(target), { recursive: true });
17477
- await writeFile17(target, bytes, { mode: 420 });
18458
+ await writeFile18(target, bytes, { mode: 420 });
17478
18459
  }
17479
18460
  }
17480
18461
 
17481
18462
  // src/runtime/regressions.ts
17482
18463
  var exec8 = promisify10(execFile10);
17483
- var hash4 = (v) => createHash17("sha256").update(v).digest("hex");
18464
+ var hash4 = (v) => createHash18("sha256").update(v).digest("hex");
17484
18465
  var identifier2 = /^[a-z][a-z0-9_]{0,39}$/;
17485
18466
  function parseRegression(v) {
17486
18467
  const r = v;
@@ -17518,7 +18499,7 @@ async function runProtectedCheck(cwd, opts) {
17518
18499
  if (revision === result2.candidateRevision) result2.sourceDigests[file] = hash4(bytes);
17519
18500
  const dest = join31(directory, file);
17520
18501
  await mkdir11(resolve10(dest, ".."), { recursive: true });
17521
- await writeFile18(dest, bytes, { mode: 420 });
18502
+ await writeFile19(dest, bytes, { mode: 420 });
17522
18503
  };
17523
18504
  let executionSpec = regression.spec;
17524
18505
  if (regression.callable) {
@@ -17710,9 +18691,9 @@ async function runPrCheck(cwd, opts = {}) {
17710
18691
  const diff = await git(cwd, "diff", "--unified=0", "--no-color", `${base}...${head}`).catch(() => git(cwd, "diff", "--unified=0", "--no-color", base, head));
17711
18692
  const lines = changedLines(diff);
17712
18693
  const changed = new Set(lines.keys());
17713
- const list2 = async (rev) => (await git(cwd, "ls-tree", "-r", "--name-only", rev, "--", ".agenttwin/regressions")).split("\n").filter((f) => f.endsWith(".json"));
17714
- const baseRegressions = await list2(base);
17715
- const added = (await list2(head)).filter((f) => !baseRegressions.includes(f));
18694
+ const list3 = async (rev) => (await git(cwd, "ls-tree", "-r", "--name-only", rev, "--", ".agenttwin/regressions")).split("\n").filter((f) => f.endsWith(".json"));
18695
+ const baseRegressions = await list3(base);
18696
+ const added = (await list3(head)).filter((f) => !baseRegressions.includes(f));
17716
18697
  const costs = await git(cwd, "show", `${base}:agenttwin.costs.json`).then((t) => JSON.parse(t)).catch(() => void 0);
17717
18698
  const regressions = [];
17718
18699
  for (const file of opts.execute === false ? [] : baseRegressions) {
@@ -17760,17 +18741,20 @@ async function runPrCheck(cwd, opts = {}) {
17760
18741
  file: op2.file,
17761
18742
  line: op2.line,
17762
18743
  level: "warning",
17763
- title: `AgentTwin: untested write to ${serviceTitle(op2.service)}`,
17764
- 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.`
18744
+ title: `AgentTwin: calls ${serviceTitle(op2.service)} with no check`,
18745
+ 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/.`
17765
18746
  });
17766
18747
  const verdict = failed.length ? "fail" : incomplete.length || notRun.length ? "incomplete" : uncovered.length ? "warn" : "pass";
17767
18748
  const services = [...new Set(touched.flatMap((w) => w.operations.filter((o) => o.changed).map((o) => serviceTitle(o.service))))];
17768
- 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";
18749
+ 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" ? (() => {
18750
+ const n = new Set(uncovered.flatMap((w) => w.operations.filter((o) => o.changed).map((o) => `${o.file}:${o.line}`))).size;
18751
+ 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`;
18752
+ })() : regressions.length === 1 ? "The twin check passed" : regressions.length ? `All ${regressions.length} twin checks passed` : "No agent side effects changed";
17769
18753
  const notes = [];
17770
- if (notRun.length) notes.push(`Not run here: ${notRun.join(", ")}. Run npx agenttwin check in CI, or configure the hosted Docker runner.`);
17771
- 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.`);
17772
- if (runtime === "local" && regressions.length) notes.push("Checks ran without container isolation. Set AGENTTWIN_RUNNER_IMAGE (digest-pinned) to run them in Docker.");
17773
- 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"}.`);
18754
+ 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.`);
18755
+ 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.`);
18756
+ 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.");
18757
+ 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.`);
17774
18758
  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 };
17775
18759
  }
17776
18760
 
@@ -17803,6 +18787,19 @@ ${r.checks.filter((c) => !c.passed).map((c) => `- ${c.text}`).join("\n")}`,
17803
18787
  `Verify locally: npx agenttwin check --base ${short2(report.base)}`
17804
18788
  ].filter(Boolean).join("\n\n");
17805
18789
  }
18790
+ var list2 = (items) => items.length <= 1 ? items[0] ?? "an external service" : `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
18791
+ function uncoveredLines(report) {
18792
+ const byLine = /* @__PURE__ */ new Map();
18793
+ for (const w of report.touched.filter((t) => !t.covered)) for (const o of w.operations.filter((op2) => op2.changed)) {
18794
+ const key2 = `${o.file}:${o.line}`, entry = byLine.get(key2) ?? { file: o.file, line: o.line, services: [], sends: [], workflows: [] };
18795
+ const service = serviceTitle(o.service), send2 = `${service} \xB7 \`${o.operation}\``;
18796
+ if (!entry.services.includes(service)) entry.services.push(service);
18797
+ if (!entry.sends.includes(send2)) entry.sends.push(send2);
18798
+ if (!entry.workflows.includes(w.title)) entry.workflows.push(w.title);
18799
+ byLine.set(key2, entry);
18800
+ }
18801
+ return [...byLine.values()].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
18802
+ }
17806
18803
  function renderMarkdown(report, opts = {}) {
17807
18804
  const out = [];
17808
18805
  if (opts.comment) out.push(COMMENT_MARKER);
@@ -17844,18 +18841,32 @@ function renderMarkdown(report, opts = {}) {
17844
18841
  for (const c of r.checks) out.push(`- ${c.passed ? "\u2705" : "\u274C"} ${c.text}`);
17845
18842
  out.push("", "<details><summary>Fix task for Claude Code, Codex or Cursor</summary>", "", "```text", fixTask(report, r), "```", "", "</details>", "");
17846
18843
  }
17847
- const uncovered = report.touched.filter((w) => !w.covered && w.operations.some((o) => o.changed));
18844
+ const uncovered = uncoveredLines(report);
17848
18845
  if (uncovered.length) {
17849
- out.push("### Changed code with no twin check", "", "| Where | Reaches | Workflow |", "|---|---|---|");
17850
- for (const w of uncovered) for (const o of w.operations.filter((op2) => op2.changed))
17851
- out.push(`| \`${o.file}:${o.line}\` | ${serviceTitle(o.service)} \`${cell(o.operation)}\` | ${cell(w.title)} |`);
17852
- 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.", "");
18846
+ const services = [...new Set(uncovered.flatMap((u) => u.services))];
18847
+ 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.`, "");
18848
+ out.push("| Line | Sends | Part of |", "|---|---|---|");
18849
+ for (const u of uncovered.slice(0, 15)) {
18850
+ 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}\``;
18851
+ const flows = u.workflows.slice(0, 2).map((w) => `\`${cell(w)}\``).join(", ") + (u.workflows.length > 2 ? ` and ${u.workflows.length - 2} more` : "");
18852
+ out.push(`| ${where} | ${cell(u.sends.join(", "))} | ${flows} |`);
18853
+ }
18854
+ if (uncovered.length > 15) out.push("", `\u2026and ${uncovered.length - 15} more lines in the [full report](${opts.detailsUrl ?? "#"}).`);
18855
+ const first = uncovered[0].workflows[0];
18856
+ out.push(
18857
+ "",
18858
+ "**To cover them:**",
18859
+ `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.`,
18860
+ "2. If it finds a problem, fix it and run it again. The passing run is saved in `.agenttwin/regressions/`.",
18861
+ "3. Commit that file. This check then reruns it on every pull request.",
18862
+ ""
18863
+ );
17853
18864
  }
17854
18865
  const covered = report.touched.filter((w) => w.covered && w.operations.some((o) => o.changed));
17855
18866
  if (covered.length) out.push(`<sub>Changed and covered: ${covered.map((w) => cell(w.title)).join(", ")}.</sub>`, "");
17856
- if (!report.regressions.length && !report.touched.length) out.push("No code in this pull request reaches an external system AgentTwin knows about.", "");
18867
+ 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.", "");
17857
18868
  for (const note of report.notes) out.push(`<sub>${note}</sub>`);
17858
- 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>`);
18869
+ 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>`);
17859
18870
  return out.join("\n") + "\n";
17860
18871
  }
17861
18872
 
@@ -17884,7 +18895,7 @@ async function startCheckRun(target) {
17884
18895
  }
17885
18896
  async function publishCheckRun(report, target, existing) {
17886
18897
  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) }));
17887
- const summary = renderMarkdown(report, { detailsUrl: target.detailsUrl });
18898
+ const summary = renderMarkdown(report, { detailsUrl: target.detailsUrl, repository: target.repository });
17888
18899
  const output = (batch) => ({ title: report.headline.slice(0, 255), summary: summary.length > MAX_SUMMARY ? summary.slice(0, MAX_SUMMARY) + "\n\u2026" : summary, annotations: batch });
17889
18900
  const run3 = await api(target, existing ? "PATCH" : "POST", `/repos/${target.repository}/check-runs${existing ? `/${existing}` : ""}`, {
17890
18901
  ...existing ? {} : { name: CHECK_NAME, head_sha: target.sha },
@@ -17899,7 +18910,7 @@ async function publishCheckRun(report, target, existing) {
17899
18910
  }
17900
18911
  async function upsertComment(report, target) {
17901
18912
  if (!target.pullRequest) return void 0;
17902
- const body2 = renderMarkdown(report, { comment: true, detailsUrl: target.detailsUrl });
18913
+ const body2 = renderMarkdown(report, { comment: true, detailsUrl: target.detailsUrl, repository: target.repository });
17903
18914
  for (let page2 = 1; page2 <= 10; page2++) {
17904
18915
  const comments = await api(target, "GET", `/repos/${target.repository}/issues/${target.pullRequest}/comments?per_page=100&page=${page2}`);
17905
18916
  const mine = comments.find((c) => c.body?.startsWith(COMMENT_MARKER));
@@ -18032,7 +19043,7 @@ function requestBudget(limit2 = 1200) {
18032
19043
  }
18033
19044
 
18034
19045
  // src/runtime/oauth.ts
18035
- import { createHash as createHash21, randomBytes as randomBytes7, timingSafeEqual as timingSafeEqual5 } from "crypto";
19046
+ import { createHash as createHash22, randomBytes as randomBytes7, timingSafeEqual as timingSafeEqual5 } from "crypto";
18036
19047
  var oauthScopes = {
18037
19048
  "read:projects": "List this client\u2019s one authorized project",
18038
19049
  "read:discovery": "Read discovery metadata for the authorized project",
@@ -18044,7 +19055,7 @@ var oauthScopes = {
18044
19055
  "write:preparations": "Select and cancel local preparation requests for the authorized project",
18045
19056
  "work:preparations": "Claim and report preparation metadata; does not approve or execute application code"
18046
19057
  };
18047
- var hash5 = (v) => createHash21("sha256").update(v).digest("hex");
19058
+ var hash5 = (v) => createHash22("sha256").update(v).digest("hex");
18048
19059
  var matches3 = (a, b) => timingSafeEqual5(Buffer.from(hash5(a)), Buffer.from(b));
18049
19060
  function newOAuthClient(accountId, label2, project, scopes) {
18050
19061
  if (!Array.isArray(scopes) || !scopes.length || scopes.length > Object.keys(oauthScopes).length || scopes.some(
@@ -18281,8 +19292,8 @@ function validateWorkspaceProfile(input) {
18281
19292
  }
18282
19293
 
18283
19294
  // src/runtime/auth.ts
18284
- import { randomBytes as randomBytes8, scrypt, timingSafeEqual as timingSafeEqual6, createHash as createHash22 } from "crypto";
18285
- var digest5 = (value) => createHash22("sha256").update(value).digest("hex");
19295
+ import { randomBytes as randomBytes8, scrypt, timingSafeEqual as timingSafeEqual6, createHash as createHash23 } from "crypto";
19296
+ var digest5 = (value) => createHash23("sha256").update(value).digest("hex");
18286
19297
  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)));
18287
19298
  async function passwordHash(password) {
18288
19299
  const salt = randomBytes8(16).toString("hex");
@@ -18312,8 +19323,8 @@ init_dashboard_transfer();
18312
19323
  import { generateRegistrationOptions, verifyRegistrationResponse, generateAuthenticationOptions, verifyAuthenticationResponse } from "@simplewebauthn/server";
18313
19324
  import { isDeepStrictEqual as isDeepStrictEqual9 } from "util";
18314
19325
  import { createServer as createServer7 } from "http";
18315
- import { createHash as createHash28, randomBytes as randomBytes11, randomUUID as randomUUID10, timingSafeEqual as timingSafeEqual7 } from "crypto";
18316
- import { mkdir as mkdir13, readFile as readFile26, writeFile as writeFile21, rename as rename3, mkdtemp as mkdtemp14, rm as rm17 } from "fs/promises";
19326
+ import { createHash as createHash29, randomBytes as randomBytes11, randomUUID as randomUUID10, timingSafeEqual as timingSafeEqual7 } from "crypto";
19327
+ import { mkdir as mkdir13, readFile as readFile26, writeFile as writeFile22, rename as rename3, mkdtemp as mkdtemp14, rm as rm17 } from "fs/promises";
18317
19328
  import { resolve as resolve12, join as join38, dirname as dirname7, extname as extname2 } from "path";
18318
19329
  import { tmpdir as tmpdir15 } from "os";
18319
19330
 
@@ -18420,8 +19431,8 @@ import { join as join37 } from "path";
18420
19431
 
18421
19432
  // src/runtime/repair-proof.ts
18422
19433
  init_run_summary();
18423
- import { createHash as createHash23, randomUUID as randomUUID7 } from "crypto";
18424
- import { mkdir as mkdir12, readFile as readFile24, rm as rm16, writeFile as writeFile20 } from "fs/promises";
19434
+ import { createHash as createHash24, randomUUID as randomUUID7 } from "crypto";
19435
+ import { mkdir as mkdir12, readFile as readFile24, rm as rm16, writeFile as writeFile21 } from "fs/promises";
18425
19436
  import { isAbsolute as isAbsolute5, join as join36, relative as relative7, resolve as resolve11, sep as sep7 } from "path";
18426
19437
 
18427
19438
  // src/runtime/receipt-sync.ts
@@ -18430,8 +19441,17 @@ function validProof(p, runId) {
18430
19441
  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");
18431
19442
  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;
18432
19443
  }
18433
- function portableLocalReceipt(value) {
19444
+ function normalizeReceipt(value) {
18434
19445
  const r = value;
19446
+ if (!r || typeof r !== "object") return value;
19447
+ const digests = r.sourceDigests && typeof r.sourceDigests === "object" && !Array.isArray(r.sourceDigests) ? r.sourceDigests : {};
19448
+ const inside = (file) => !file.startsWith("/") && !/^[A-Za-z]:/.test(file) && !file.split(/[\\/]/).includes("..");
19449
+ 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;
19450
+ 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;
19451
+ return { ...r, events, ...r.evaluation !== void 0 ? { evaluation } : {} };
19452
+ }
19453
+ function portableLocalReceipt(value) {
19454
+ const r = normalizeReceipt(value);
18435
19455
  const uuid3 = (v) => typeof v === "string" && /^[a-f0-9-]{36}$/.test(v);
18436
19456
  if (r?.applicationClock !== void 0 && (!["local", "docker"].includes(r.runtime) || !validApplicationClockEvidence(r.applicationClock))) throw new Error("Invalid application clock evidence");
18437
19457
  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");
@@ -18469,7 +19489,7 @@ function portableLocalReceipt(value) {
18469
19489
  init_run();
18470
19490
 
18471
19491
  // src/runtime/analytics.ts
18472
- import { createHash as createHash24 } from "crypto";
19492
+ import { createHash as createHash25 } from "crypto";
18473
19493
  function analyticsConfiguration() {
18474
19494
  const key2 = process.env.POSTHOG_API_KEY;
18475
19495
  const host = process.env.POSTHOG_API_HOST || "https://us.i.posthog.com";
@@ -18506,7 +19526,7 @@ function captureAnalytics(event) {
18506
19526
  // package.json
18507
19527
  var package_default = {
18508
19528
  name: "agenttwin",
18509
- version: "0.3.30",
19529
+ version: "0.3.32",
18510
19530
  description: "AgentTwin builds digital twins for testing AI agents. The current CLI prepares supported Node.js workflows with synthetic services, failures, and outcome checks.",
18511
19531
  mcpName: "io.github.AgentTwin/agenttwin",
18512
19532
  keywords: [
@@ -18560,6 +19580,7 @@ var package_default = {
18560
19580
  bson: "^6.10.4",
18561
19581
  e2b: "^2.52.1",
18562
19582
  esbuild: "0.28.2",
19583
+ fengari: "0.1.5",
18563
19584
  "openid-client": "^6.8.8",
18564
19585
  pg: "^8.23.1",
18565
19586
  playwright: "1.64.1",
@@ -18601,7 +19622,7 @@ var package_default = {
18601
19622
  var VERSION = package_default.version;
18602
19623
 
18603
19624
  // src/runtime/audit-export.ts
18604
- import { createHash as createHash25, createPrivateKey, createPublicKey, sign, verify } from "crypto";
19625
+ import { createHash as createHash26, createPrivateKey, createPublicKey, sign, verify } from "crypto";
18605
19626
  var AUDIT_EXPORT_SCHEMA = "agenttwin/audit-export-v1";
18606
19627
  var GENESIS = "0".repeat(64);
18607
19628
  function canonical4(value) {
@@ -18609,7 +19630,7 @@ function canonical4(value) {
18609
19630
  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(",") + "}";
18610
19631
  return JSON.stringify(value);
18611
19632
  }
18612
- var sha4 = (s) => createHash25("sha256").update(s).digest("hex");
19633
+ var sha4 = (s) => createHash26("sha256").update(s).digest("hex");
18613
19634
  function signingKey(pem = process.env.AGENTTWIN_AUDIT_SIGNING_KEY) {
18614
19635
  if (!pem) return void 0;
18615
19636
  const key2 = createPrivateKey(pem.replace(/\\n/g, "\n"));
@@ -18830,14 +19851,14 @@ async function remoteMcp(message, token, base, fetcher) {
18830
19851
  }
18831
19852
 
18832
19853
  // src/runtime/scim.ts
18833
- import { randomBytes as randomBytes10, randomUUID as randomUUID9, createHash as createHash27 } from "crypto";
19854
+ import { randomBytes as randomBytes10, randomUUID as randomUUID9, createHash as createHash28 } from "crypto";
18834
19855
 
18835
19856
  // src/runtime/teams.ts
18836
- import { createHash as createHash26, randomBytes as randomBytes9, randomUUID as randomUUID8 } from "crypto";
19857
+ import { createHash as createHash27, randomBytes as randomBytes9, randomUUID as randomUUID8 } from "crypto";
18837
19858
  var TEAM_ROLES = ["admin", "member", "viewer"];
18838
19859
  var INVITE_DAYS = 7;
18839
19860
  var AUDIT_LIMIT = 5e3;
18840
- var sha5 = (value) => createHash26("sha256").update(value).digest("hex");
19861
+ var sha5 = (value) => createHash27("sha256").update(value).digest("hex");
18841
19862
  var isRole = (value) => typeof value === "string" && TEAM_ROLES.includes(value);
18842
19863
  function resolveWorkspace(state, person, orgToken) {
18843
19864
  if (orgToken) return { workspace: person, role: orgToken.role, actorId: `token:${orgToken.id}`, actorLabel: `API token "${orgToken.label}"`, shared: true };
@@ -18911,7 +19932,7 @@ var SCIM_USER = "urn:ietf:params:scim:schemas:core:2.0:User";
18911
19932
  var LIST = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
18912
19933
  var PATCH = "urn:ietf:params:scim:api:messages:2.0:PatchOp";
18913
19934
  var ERROR = "urn:ietf:params:scim:api:messages:2.0:Error";
18914
- var sha6 = (v) => createHash27("sha256").update(v).digest("hex");
19935
+ var sha6 = (v) => createHash28("sha256").update(v).digest("hex");
18915
19936
  var scimError = (status, detail, scimType) => ({ status, body: { schemas: [ERROR], status: String(status), detail, ...scimType ? { scimType } : {} } });
18916
19937
  function userOf(store, workspaceId, a, base) {
18917
19938
  const m = (store.teamMembers ?? []).find((x) => x.accountId === workspaceId && x.memberId === a.id);
@@ -19017,7 +20038,7 @@ function handleScim(store, workspaceId, method, path2, query, input, base) {
19017
20038
  }
19018
20039
 
19019
20040
  // src/runtime/gateway.ts
19020
- var hash6 = (value) => createHash28("sha256").update(value).digest("hex");
20041
+ var hash6 = (value) => createHash29("sha256").update(value).digest("hex");
19021
20042
  function uploadPath(path2) {
19022
20043
  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");
19023
20044
  return path2;
@@ -19109,7 +20130,7 @@ async function startGateway(opts) {
19109
20130
  if (database) await database.write(snapshot);
19110
20131
  else {
19111
20132
  const path2 = join38(directory, `state-${randomUUID10()}.tmp`);
19112
- await writeFile21(path2, snapshot, { mode: 384 });
20133
+ await writeFile22(path2, snapshot, { mode: 384 });
19113
20134
  await rename3(path2, storePath2);
19114
20135
  }
19115
20136
  committedWorkflows = workflowView;
@@ -19154,12 +20175,12 @@ async function startGateway(opts) {
19154
20175
  for (const [file, encoded] of Object.entries(item.files)) {
19155
20176
  const destination = join38(workspace, uploadPath(file));
19156
20177
  await mkdir13(dirname7(destination), { recursive: true });
19157
- await writeFile21(destination, Buffer.from(encoded, "base64"), { mode: 384 });
20178
+ await writeFile22(destination, Buffer.from(encoded, "base64"), { mode: 384 });
19158
20179
  }
19159
- await writeFile21(join38(workspace, "agenttwin.world.json"), JSON.stringify(item.spec));
20180
+ await writeFile22(join38(workspace, "agenttwin.world.json"), JSON.stringify(item.spec));
19160
20181
  if (item.spec.workflowId) {
19161
20182
  await mkdir13(join38(workspace, ".agenttwin"));
19162
- await writeFile21(join38(workspace, ".agenttwin/inventory.json"), JSON.stringify({ workflows: [{ id: item.spec.workflowId }] }));
20183
+ await writeFile22(join38(workspace, ".agenttwin/inventory.json"), JSON.stringify({ workflows: [{ id: item.spec.workflowId }] }));
19163
20184
  }
19164
20185
  const receipt = await runWorld(workspace, { runtime: "e2b", seed: item.seed, signal: controllers.get(item.job.id)?.signal, log: () => {
19165
20186
  } });