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
@@ -104,7 +104,7 @@ function writeViolation(violation){const line=JSON.stringify(violation)+'\n';if(
104
104
  // Child processes: Node descendants inherit this hook through NODE_OPTIONS, even when the app passes its own env.
105
105
  // Any other executable runs outside the hook, so it is recorded and the run cannot be complete.
106
106
  const childProcess=require('node:child_process');
107
- const hookOption='--require '+JSON.stringify(__filename);
107
+ const hookOption='--require '+(/[\s"']/.test(__filename)?JSON.stringify(__filename):__filename);
108
108
  // Trust is decided from the file that would run, never its name: the Node binary itself, a script whose shebang runs
109
109
  // that binary (node_modules/.bin CLIs, npm, npx), or esbuild's own binary inside its package. Results are cached per real path and PATH.
110
110
  const executableTrust=new Map();
@@ -118,15 +118,23 @@ function runsHookedNode(interpreter,options){const file=resolveCommand(interpret
118
118
  // '#!/path/to/node', '#!/usr/bin/env node' and '#!/usr/bin/env -S node --flags' run Node; anything else does not.
119
119
  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);}
120
120
  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;}}
121
- 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;}
121
+ // Operating-system tools that only print facts about this machine and cannot open a connection. SDKs and frameworks
122
+ // run them for a user-agent string (Stripe: uname; Next.js: sw_vers). Matched by their fixed system path, so a file of
123
+ // the same name inside a project or earlier on PATH is still reported.
124
+ const SYSTEM_INFO_BINARIES=new Set(['/usr/bin/uname','/bin/uname','/usr/bin/sw_vers','/usr/bin/arch','/usr/bin/nproc','/usr/bin/getconf']);
125
+ function systemInfoBinary(real){return process.platform!=='win32'&&SYSTEM_INFO_BINARIES.has(real);}
126
+ 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;}
122
127
  const reportedSubprocesses=new Set();
123
128
  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};}
124
129
  // Never throws: an unclassifiable command is reported, and the application's spawn proceeds unchanged.
125
130
  // Shell commands are judged by their first word, so 'sh -c' style wrappers are reported as non-Node.
126
- 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{}}
131
+ // git asked about the local checkout only (the commit a build stamps, the branch): no network, nothing written.
132
+ const LOCAL_GIT=/^(rev-parse|describe|log|show|status|branch|symbolic-ref|ls-files|rev-list|config)$/;
133
+ 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))));}
134
+ 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{}}
127
135
  // Puts the hooked env into the options argument at index i, inserting an options object when there is none.
128
136
  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;}
129
- 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);};}
137
+ 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);};}
130
138
  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);};}
131
139
  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])});}}
132
140
  const blockedOrigins=new Set();
@@ -273,7 +281,24 @@ function readOnlyOperation(method, resource, id, params, data) {
273
281
  const ordered = [...rows2].reverse().filter((r) => params.type === void 0 || r.type === params.type);
274
282
  return { status: 200, body: { object: "list", data: ordered.slice(0, limit), has_more: ordered.length > limit, url: collection }, collection, operation: "read" };
275
283
  }
284
+ function subscriptionItemOperation(method, id, params, data) {
285
+ const collection = "/v1/subscription_items";
286
+ if (method !== "GET" && method !== "POST") return void 0;
287
+ if (Object.keys(params).some((key2) => method !== "POST" || key2 !== "quantity")) return void 0;
288
+ const item = data[collection]?.find((row) => row.id === id && row.deleted !== true);
289
+ if (!item) return { ...stripeError(404, "resource_missing", `No such subscription_item: '${id}'`), collection };
290
+ if (method === "GET") return { status: 200, body: item, collection, operation: "read" };
291
+ const value = params.quantity;
292
+ const quantity = typeof value === "string" && /^\d+$/.test(value) ? Number(value) : value;
293
+ if (typeof quantity !== "number" || !Number.isSafeInteger(quantity) || quantity < 0) {
294
+ return { ...stripeError(400, "parameter_invalid_integer", "quantity must be a non-negative integer", "quantity"), collection };
295
+ }
296
+ item.quantity = quantity;
297
+ return { status: 200, body: item, collection, record: structuredClone(item), operation: "write" };
298
+ }
276
299
  function stripeOperation(method, path, params, data, sequence) {
300
+ const item = /^\/v1\/subscription_items\/([^/]+)$/.exec(path);
301
+ if (item) return subscriptionItemOperation(method, item[1], params, data);
277
302
  const error = stripeError;
278
303
  const other = /^\/v1\/(refunds|charges|events)(?:\/([^/]+))?$/.exec(path);
279
304
  if (other) return other[1] === "refunds" ? refundOperation(method, other[2], params, data, sequence) : readOnlyOperation(method, other[1], other[2], params, data);
@@ -767,6 +792,182 @@ var init_resp = __esm({
767
792
  }
768
793
  });
769
794
 
795
+ // src/runtime/engines/redis-lua.ts
796
+ import { createRequire } from "module";
797
+ import { createHash as createHash2 } from "crypto";
798
+ var vm, load, toLua, fromLua, RedisScripts, WRITE_HINT;
799
+ var init_redis_lua = __esm({
800
+ "src/runtime/engines/redis-lua.ts"() {
801
+ "use strict";
802
+ init_resp();
803
+ load = () => vm ??= createRequire(import.meta.url)("fengari");
804
+ toLua = (s) => Uint8Array.from(Buffer.from(s, "latin1"));
805
+ fromLua = (b) => Buffer.from(b).toString("latin1");
806
+ RedisScripts = class {
807
+ /** `run` executes one command on the engine and returns its RESP reply. */
808
+ constructor(run3) {
809
+ this.run = run3;
810
+ }
811
+ run;
812
+ cache = /* @__PURE__ */ new Map();
813
+ command(name, args) {
814
+ if (name === "script") {
815
+ const sub = (args[0] ?? "").toLowerCase();
816
+ if (sub === "load") {
817
+ const sha2 = this.store(args[1] ?? "");
818
+ return encode.bulk(sha2);
819
+ }
820
+ if (sub === "exists") return encode.array(args.slice(1).map((sha2) => encode.int(this.cache.has(sha2.toLowerCase()) ? 1 : 0)));
821
+ if (sub === "flush") {
822
+ this.cache.clear();
823
+ return encode.simple("OK");
824
+ }
825
+ return encode.error(`ERR unknown subcommand '${args[0]}'`);
826
+ }
827
+ const evalsha = name === "evalsha" || name === "evalsha_ro";
828
+ const source = evalsha ? this.cache.get((args[0] ?? "").toLowerCase()) : args[0];
829
+ if (source === void 0) return encode.error("NOSCRIPT No matching script. Please use EVAL.");
830
+ const count = Number(args[1]);
831
+ 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");
832
+ if (!evalsha) this.store(source);
833
+ return this.execute(source, args.slice(2, 2 + count), args.slice(2 + count), name.endsWith("_ro"));
834
+ }
835
+ store(source) {
836
+ const sha2 = createHash2("sha1").update(Buffer.from(source, "latin1")).digest("hex");
837
+ this.cache.set(sha2, source);
838
+ return sha2;
839
+ }
840
+ execute(source, keys, argv, readOnly) {
841
+ const { lua, lauxlib, lualib } = load(), L = lauxlib.luaL_newstate();
842
+ try {
843
+ for (const [name, open2] of [["_G", lualib.luaopen_base], ["string", lualib.luaopen_string], ["table", lualib.luaopen_table], ["math", lualib.luaopen_math]]) {
844
+ lauxlib.luaL_requiref(L, toLua(name), open2, 1);
845
+ lua.lua_pop(L, 1);
846
+ }
847
+ for (const name of ["dofile", "loadfile", "load", "require", "print"]) lua.lua_pushnil(L), lua.lua_setglobal(L, toLua(name));
848
+ const table2 = (items, global) => {
849
+ lua.lua_createtable(L, items.length, 0);
850
+ items.forEach((v, i) => {
851
+ lua.lua_pushstring(L, toLua(v));
852
+ lua.lua_rawseti(L, -2, i + 1);
853
+ });
854
+ lua.lua_setglobal(L, toLua(global));
855
+ };
856
+ table2(keys, "KEYS");
857
+ table2(argv, "ARGV");
858
+ lua.lua_createtable(L, 0, 4);
859
+ const call = (raise) => (state) => {
860
+ const n = lua.lua_gettop(state), args = [];
861
+ for (let i = 1; i <= n; i++) {
862
+ const t = lua.lua_type(state, i);
863
+ if (t === lua.LUA_TNUMBER) {
864
+ const v = lua.lua_tonumber(state, i);
865
+ args.push(Number.isInteger(v) ? String(v) : String(v));
866
+ } else if (t === lua.LUA_TSTRING) args.push(fromLua(lua.lua_tolstring(state, i)));
867
+ else return lauxlib.luaL_error(state, toLua("Lua redis lib command arguments must be strings or integers"));
868
+ }
869
+ if (!args.length) return lauxlib.luaL_error(state, toLua("Please specify at least one argument for this redis lib call"));
870
+ const command = args[0].toLowerCase();
871
+ 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"));
872
+ if (readOnly && WRITE_HINT.test(command)) return lauxlib.luaL_error(state, toLua("Write commands are not allowed from read-only scripts"));
873
+ const reply = parseResp(this.run(args))?.value ?? null;
874
+ if (raise && reply && typeof reply === "object" && !Array.isArray(reply) && !Buffer.isBuffer(reply) && "error" in reply) return lauxlib.luaL_error(state, toLua(reply.error));
875
+ push(state, reply);
876
+ return 1;
877
+ };
878
+ const push = (state, v) => {
879
+ if (v === null || v === false) lua.lua_pushboolean(state, 0);
880
+ else if (v === true) lua.lua_pushinteger(state, 1);
881
+ else if (typeof v === "number") lua.lua_pushinteger(state, v);
882
+ else if (Buffer.isBuffer(v)) lua.lua_pushstring(state, Uint8Array.from(v));
883
+ else if (Array.isArray(v)) {
884
+ lua.lua_createtable(state, v.length, 0);
885
+ v.forEach((x, i) => {
886
+ push(state, x);
887
+ lua.lua_rawseti(state, -2, i + 1);
888
+ });
889
+ } else {
890
+ lua.lua_createtable(state, 0, 1);
891
+ lua.lua_pushstring(state, toLua("simple" in v ? v.simple : v.error));
892
+ lua.lua_setfield(state, -2, toLua("simple" in v ? "ok" : "err"));
893
+ }
894
+ };
895
+ for (const [name, fn] of [["call", call(true)], ["pcall", call(false)]]) {
896
+ lua.lua_pushcfunction(L, fn);
897
+ lua.lua_setfield(L, -2, toLua(name));
898
+ }
899
+ lua.lua_pushcfunction(L, (state) => {
900
+ lua.lua_createtable(state, 0, 1);
901
+ lua.lua_pushvalue(state, 1);
902
+ lua.lua_setfield(state, -2, toLua("err"));
903
+ return 1;
904
+ });
905
+ lua.lua_setfield(L, -2, toLua("error_reply"));
906
+ lua.lua_pushcfunction(L, (state) => {
907
+ lua.lua_createtable(state, 0, 1);
908
+ lua.lua_pushvalue(state, 1);
909
+ lua.lua_setfield(state, -2, toLua("ok"));
910
+ return 1;
911
+ });
912
+ lua.lua_setfield(L, -2, toLua("status_reply"));
913
+ lua.lua_pushcfunction(L, () => 0);
914
+ lua.lua_setfield(L, -2, toLua("log"));
915
+ lua.lua_pushcfunction(L, () => 0);
916
+ lua.lua_setfield(L, -2, toLua("replicate_commands"));
917
+ lua.lua_setglobal(L, toLua("redis"));
918
+ 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)}`);
919
+ if (lua.lua_pcall(L, 0, 1, 0) !== lua.LUA_OK) return encode.error(`ERR Error running script: ${this.message(L)}`);
920
+ return this.reply(L, -1);
921
+ } finally {
922
+ lua.lua_close(L);
923
+ }
924
+ }
925
+ message(L) {
926
+ const { lua } = load();
927
+ const m = lua.lua_tolstring(L, -1);
928
+ return m ? fromLua(m) : "error";
929
+ }
930
+ /** The Lua value at `index` as a RESP reply, by Redis's conversion rules. */
931
+ reply(L, index) {
932
+ const { lua } = load(), at = lua.lua_absindex(L, index);
933
+ switch (lua.lua_type(L, at)) {
934
+ case lua.LUA_TNUMBER:
935
+ return encode.int(Math.trunc(lua.lua_tonumber(L, at)));
936
+ case lua.LUA_TSTRING:
937
+ return encode.bulk(Buffer.from(lua.lua_tolstring(L, at)));
938
+ case lua.LUA_TBOOLEAN:
939
+ return lua.lua_toboolean(L, at) ? encode.int(1) : encode.bulk(null);
940
+ case lua.LUA_TTABLE: {
941
+ for (const field of ["err", "ok"]) {
942
+ lua.lua_getfield(L, at, toLua(field));
943
+ if (lua.lua_type(L, -1) === lua.LUA_TSTRING) {
944
+ const text2 = fromLua(lua.lua_tolstring(L, -1));
945
+ lua.lua_pop(L, 1);
946
+ return field === "err" ? encode.error(text2) : encode.simple(text2);
947
+ }
948
+ lua.lua_pop(L, 1);
949
+ }
950
+ const items = [];
951
+ for (let i = 1; ; i++) {
952
+ lua.lua_rawgeti(L, at, i);
953
+ if (lua.lua_isnil(L, -1)) {
954
+ lua.lua_pop(L, 1);
955
+ break;
956
+ }
957
+ items.push(this.reply(L, -1));
958
+ lua.lua_pop(L, 1);
959
+ }
960
+ return encode.array(items);
961
+ }
962
+ default:
963
+ return encode.bulk(null);
964
+ }
965
+ }
966
+ };
967
+ 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)$/;
968
+ }
969
+ });
970
+
770
971
  // src/runtime/engines/types.ts
771
972
  function record2(events, event) {
772
973
  if (events.length < 5e4) events.push({ sequence: events.length + 1, ...event });
@@ -1203,6 +1404,7 @@ var init_redis = __esm({
1203
1404
  "src/runtime/engines/redis.ts"() {
1204
1405
  "use strict";
1205
1406
  init_resp();
1407
+ init_redis_lua();
1206
1408
  init_types();
1207
1409
  init_host();
1208
1410
  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(" "));
@@ -1326,9 +1528,12 @@ var init_redis = __esm({
1326
1528
  }
1327
1529
  return this.run(args);
1328
1530
  }
1531
+ /** Lua scripts (EVAL/EVALSHA/SCRIPT) run against this engine's own data; see redis-lua.ts. */
1532
+ scripts;
1329
1533
  run(args) {
1330
1534
  const name = args[0].toLowerCase(), a = args.slice(1);
1331
1535
  try {
1536
+ if (["eval", "evalsha", "eval_ro", "evalsha_ro", "script"].includes(name)) return (this.scripts ??= new RedisScripts((c) => this.run(c))).command(name, a);
1332
1537
  const reply = this.command(name, a);
1333
1538
  if (WRITES.has(name)) for (const k of commandKeys(name, a)) this.touch(k);
1334
1539
  return reply;
@@ -1863,7 +2068,7 @@ function upstashRedisOperation(method, path, params, headers, data, _sequence, r
1863
2068
  let full = false;
1864
2069
  for (const c of args) {
1865
2070
  const name = c[0].toLowerCase(), keys = commandKeys(name, c.slice(1));
1866
- if (GLOBAL_WRITES.has(name) || !keys.length && WRITE_COMMANDS.has(name)) full = true;
2071
+ if (GLOBAL_WRITES.has(name) || !keys.length && (WRITE_COMMANDS.has(name) || /^eval/.test(name))) full = true;
1867
2072
  for (const k of keys) touched.add(k);
1868
2073
  }
1869
2074
  if (full || cache2.nextExpiry <= now) resync(rows2, cache2);
@@ -1871,7 +2076,7 @@ function upstashRedisOperation(method, path, params, headers, data, _sequence, r
1871
2076
  const encoding = headers["upstash-encoding"];
1872
2077
  const base64 = typeof encoding === "string" && encoding.toLowerCase() === "base64";
1873
2078
  const results = replies.map((r) => upstashReply(r, base64));
1874
- const wrote = args.some((c) => WRITE_COMMANDS.has(c[0].toLowerCase()));
2079
+ const wrote = args.some((c) => WRITE_COMMANDS.has(c[0].toLowerCase()) || /^eval(sha)?$/.test(c[0].toLowerCase()));
1875
2080
  const record3 = { commands: args.map((c) => c[0].toUpperCase()), keys: args.map((c) => c[1] === void 0 ? null : fromBytes(c[1])) };
1876
2081
  if (single) {
1877
2082
  const result = results[0];
@@ -1887,7 +2092,7 @@ var init_upstash_redis_twin = __esm({
1887
2092
  init_resp();
1888
2093
  UPSTASH_KEYS = "/keys";
1889
2094
  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(" "));
1890
- REJECTED = /* @__PURE__ */ new Set(["eval", "evalsha", "eval_ro", "evalsha_ro", "script", "subscribe", "psubscribe", "blpop", "brpop", "blmove", "monitor", "multi", "exec", "watch"]);
2095
+ REJECTED = /* @__PURE__ */ new Set(["subscribe", "psubscribe", "blpop", "brpop", "blmove", "monitor", "multi", "exec", "watch"]);
1891
2096
  toBytes = (v) => Buffer.from(v, "utf8").toString("latin1");
1892
2097
  fromBytes = (v) => Buffer.from(v, "latin1").toString("utf8");
1893
2098
  caches = /* @__PURE__ */ new WeakMap();
@@ -1924,7 +2129,7 @@ function decodeEncodedWords(value) {
1924
2129
  let failure;
1925
2130
  const decoded = value.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=(\s+(?==\?))?/g, (_all, charset, kind, text2) => {
1926
2131
  if (!/^(utf-8|us-ascii)$/i.test(charset)) {
1927
- failure ??= mimeError(`Encoded header charset ${charset} is outside the verified subset`, true);
2132
+ failure ??= mimeError("Encoded header charset is outside the verified subset", true);
1928
2133
  return "";
1929
2134
  }
1930
2135
  if (kind.toUpperCase() === "B") return Buffer.from(text2, "base64").toString("utf8");
@@ -1981,12 +2186,12 @@ function decodeBody(body, headers) {
1981
2186
  if (!/^[A-Za-z0-9+/]*={0,2}$/.test(compact)) return mimeError("Invalid base64 MIME body", false);
1982
2187
  return Buffer.from(compact, "base64");
1983
2188
  }
1984
- return mimeError(`Content-Transfer-Encoding ${encoding} is outside the verified subset`, true);
2189
+ return mimeError("Content-Transfer-Encoding is outside the verified subset", true);
1985
2190
  }
1986
2191
  function textPart(partId, headers, body) {
1987
2192
  const { mimeType, params } = contentType(headers);
1988
- if (mimeType !== "text/plain" && mimeType !== "text/html") return mimeError(`MIME part ${mimeType} is outside the verified subset`, true);
1989
- if (params.charset && !/^(utf-8|us-ascii)$/i.test(params.charset)) return mimeError(`Charset ${params.charset} is outside the verified subset`, true);
2193
+ if (mimeType !== "text/plain" && mimeType !== "text/html") return mimeError("MIME part type is outside the verified subset", true);
2194
+ if (params.charset && !/^(utf-8|us-ascii)$/i.test(params.charset)) return mimeError("MIME charset is outside the verified subset", true);
1990
2195
  const decoded = decodeBody(body, headers);
1991
2196
  if (!Buffer.isBuffer(decoded)) return decoded;
1992
2197
  if (Buffer.from(decoded.toString("utf8")).compare(decoded) !== 0) return mimeError("MIME text part is not valid UTF-8", true);
@@ -2007,11 +2212,21 @@ function parseGmailDraftRaw(raw) {
2007
2212
  let payload;
2008
2213
  if (mimeType === "multipart/alternative") {
2009
2214
  if (!params.boundary) return mimeError("multipart/alternative needs a boundary", false);
2010
- const sections = top.body.split(new RegExp(`(?:^|\\r?\\n)--${params.boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`));
2011
- const closing = sections.findIndex((s) => s.startsWith("--"));
2012
- if (closing < 0) return mimeError("multipart/alternative has no closing boundary", false);
2215
+ const boundary = params.boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2216
+ const delimiters = [];
2217
+ for (const match of top.body.matchAll(new RegExp(`(?:^|\\r?\\n)--${boundary}(--)?[ \\t]*(?=\\r?\\n|$)`, "g"))) {
2218
+ const start = match.index ?? 0;
2219
+ const closing = match[1] === "--";
2220
+ delimiters.push({ start, end: start + match[0].length, closing });
2221
+ if (closing || delimiters.length > 10) break;
2222
+ }
2223
+ const closed = delimiters.at(-1)?.closing === true;
2224
+ const count = delimiters.length - Number(closed);
2225
+ if (count > 10 || closed && count === 0) return mimeError("multipart/alternative needs 1 to 10 parts", false);
2226
+ if (!closed) return mimeError("multipart/alternative has no closing boundary", false);
2013
2227
  const parts = [];
2014
- for (const section of sections.slice(1, closing)) {
2228
+ for (let i = 0; i < count; i++) {
2229
+ const section = top.body.slice(delimiters[i].end, delimiters[i + 1].start);
2015
2230
  const split = splitHead(section.replace(/^[ \t]*\r?\n/, ""));
2016
2231
  if (!split) return mimeError("MIME part headers and body need a blank-line separator", false);
2017
2232
  const partHeaders = parseHeaderBlock(split.head);
@@ -2020,10 +2235,9 @@ function parseGmailDraftRaw(raw) {
2020
2235
  if ("error" in part) return part;
2021
2236
  parts.push(part);
2022
2237
  }
2023
- if (!parts.length || parts.length > 10) return mimeError("multipart/alternative needs 1 to 10 parts", false);
2024
2238
  payload = { partId: "", mimeType, filename: "", headers, body: { size: 0 }, parts };
2025
2239
  } else if (mimeType.startsWith("multipart/")) {
2026
- return mimeError(`${mimeType} (attachments or nested parts) is outside the verified subset`, true);
2240
+ 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);
2027
2241
  } else {
2028
2242
  const part = textPart("", headers, top.body);
2029
2243
  if ("error" in part) return part;
@@ -2107,7 +2321,7 @@ var init_gmail_mime = __esm({
2107
2321
  });
2108
2322
 
2109
2323
  // src/runtime/rest-adapters.ts
2110
- import { createHash as createHash2 } from "crypto";
2324
+ import { createHash as createHash3 } from "crypto";
2111
2325
  function githubOperation(method, path, params, _headers, data, sequence) {
2112
2326
  const errors = (status, message, extra) => ({ status, body: { message, documentation_url: "https://docs.github.com/rest", ...extra ?? {} }, collection: "/repos" });
2113
2327
  if (path === "/repos") return method === "GET" ? ok("/repos", rows(data, "/repos").map((row) => structuredClone(row))) : void 0;
@@ -2807,10 +3021,17 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
2807
3021
  if (params.subject !== void 0 && str(params.subject) === void 0) return fail(400, "subject must be a string.");
2808
3022
  if (params.threadId !== void 0 && str(params.threadId) === void 0) return fail(400, "threadId must be a string.");
2809
3023
  if (raw2 && text2 !== void 0) return fail(400, "Provide raw or text, not both.");
2810
- const mime = raw2 ? parseGmailRaw(raw2) : void 0;
2811
- if (mime && "error" in mime) return mime.unsupported ? void 0 : fail(400, mime.error);
2812
- const body = mime?.text ?? text2 ?? "";
2813
- const message = { id: `gmail_at_${sequence}`, threadId: str(params.threadId) ?? `gmail_at_${sequence}`, labelIds: ["SENT"], snippet: body.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 ?? body } }, sizeEstimate: mime?.bytes ?? body.length, internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) };
3024
+ const plain2 = raw2 ? parseGmailRaw(raw2) : void 0;
3025
+ const legacy = plain2 && !("error" in plain2) ? plain2 : void 0;
3026
+ const mime = raw2 && !legacy ? parseGmailDraftRaw(raw2) : void 0;
3027
+ if (mime && "error" in mime) {
3028
+ return mime.unsupported ? { status: 501, body: restUnsupportedBody("gmail"), collection: MESSAGES, unsupportedReason: mime.error } : fail(400, mime.error);
3029
+ }
3030
+ if (mime && !headerAddresses(mime.headers.find((header3) => header3.name.toLowerCase() === "to")?.value).length) {
3031
+ return fail(400, "Invalid To header: a sent message needs at least one recipient.");
3032
+ }
3033
+ const body = legacy?.text ?? mime?.snippet ?? text2 ?? "";
3034
+ const message = { id: `gmail_at_${sequence}`, threadId: str(params.threadId) ?? `gmail_at_${sequence}`, labelIds: ["SENT"], snippet: body.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 ?? body } }, sizeEstimate: mime?.bytes ?? body.length, internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) };
2814
3035
  rowsIn(data, MESSAGES).push(message);
2815
3036
  return withPush(write(200, MESSAGES, structuredClone(message), message), gmailPublish(data, ["SENT"], sequence));
2816
3037
  }
@@ -2853,7 +3074,38 @@ function gmailOperation(method, path, params, headers, data, sequence, raw) {
2853
3074
  if (!message) return fail(404, `Message not found: ${messageMatch[1]}`);
2854
3075
  return ok(MESSAGES, structuredClone(message));
2855
3076
  }
3077
+ const modifyMatch = /^\/gmail\/v1\/users\/me\/(messages|threads)\/([^/]+)\/modify$/.exec(path);
3078
+ if (modifyMatch) {
3079
+ if (method !== "POST" || Object.keys(params).some((k) => !["addLabelIds", "removeLabelIds"].includes(k))) return void 0;
3080
+ const list2 = (v) => v === void 0 ? [] : Array.isArray(v) && v.every((x) => typeof x === "string") ? v : void 0;
3081
+ const add = list2(params.addLabelIds), remove2 = list2(params.removeLabelIds);
3082
+ if (!add || !remove2) return fail(400, "Invalid label list.");
3083
+ const known2 = gmailLabelKnown(data), unknown = [...add, ...remove2].find((id2) => !known2(id2));
3084
+ if (unknown) return fail(400, `Invalid label: ${unknown}`);
3085
+ const id = decodeURIComponent(modifyMatch[2]);
3086
+ const targets = modifyMatch[1] === "messages" ? rowsIn(data, MESSAGES).filter((m) => m.id === id) : rowsIn(data, MESSAGES).filter((m) => m.threadId === id);
3087
+ if (!targets.length) return fail(404, `Requested entity was not found.`);
3088
+ const next = String(BigInt(gmailHistoryId(rowsIn(data, MESSAGES))) + 1n);
3089
+ for (const message of targets) {
3090
+ const labels = new Set(message.labelIds ?? []);
3091
+ for (const l of add) labels.add(l);
3092
+ for (const l of remove2) labels.delete(l);
3093
+ message.labelIds = [...labels];
3094
+ message.historyId = next;
3095
+ }
3096
+ const body = modifyMatch[1] === "messages" ? structuredClone(targets[0]) : { id, historyId: next, messages: targets.map((m) => structuredClone(m)) };
3097
+ return { status: 200, body, collection: MESSAGES, operation: "write", record: { id, addLabelIds: add, removeLabelIds: remove2 } };
3098
+ }
2856
3099
  if (path === LABELS) {
3100
+ if (method === "POST") {
3101
+ if (Object.keys(params).some((k) => !["name", "labelListVisibility", "messageListVisibility", "color", "type"].includes(k))) return void 0;
3102
+ if (typeof params.name !== "string" || !params.name.trim()) return googleError(LABELS, 400, "Invalid label name");
3103
+ const labels = rowsIn(data, LABELS);
3104
+ 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");
3105
+ 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 } : {} };
3106
+ (data[LABELS] ??= []).push(label2);
3107
+ return { status: 200, body: structuredClone(label2), collection: LABELS, operation: "write", record: label2 };
3108
+ }
2857
3109
  if (method !== "GET") return void 0;
2858
3110
  if (Object.keys(params).length) return void 0;
2859
3111
  return ok(LABELS, { labels: rowsIn(data, LABELS).map((row) => structuredClone(row)) });
@@ -3187,7 +3439,7 @@ function zendeskOperation(method, path, params, _headers, data, sequence) {
3187
3439
  function restUnsupportedBody(adapter) {
3188
3440
  return UNSUPPORTED_BODIES[adapter];
3189
3441
  }
3190
- var EPOCH, iso, sha, detUuid, rows, notFound, badRequest, ok, created, write, isObject, 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;
3442
+ var EPOCH, iso, sha, detUuid, rows, notFound, badRequest, ok, created, write, isObject, 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;
3191
3443
  var init_rest_adapters = __esm({
3192
3444
  "src/runtime/rest-adapters.ts"() {
3193
3445
  "use strict";
@@ -3199,7 +3451,7 @@ var init_rest_adapters = __esm({
3199
3451
  init_gmail_mime();
3200
3452
  EPOCH = 17e8;
3201
3453
  iso = (epoch = EPOCH) => new Date(twinNowMs(epoch * 1e3)).toISOString();
3202
- sha = (value) => createHash2("sha256").update(value).digest("hex");
3454
+ sha = (value) => createHash3("sha256").update(value).digest("hex");
3203
3455
  detUuid = (seed) => {
3204
3456
  const hex = sha(seed).slice(0, 32).split("");
3205
3457
  hex[12] = "4";
@@ -3262,6 +3514,7 @@ var init_rest_adapters = __esm({
3262
3514
  };
3263
3515
  gmailHistoryId = (messages) => messages.reduce((max, m) => BigInt(String(m.historyId ?? 0)) > BigInt(max) ? String(m.historyId) : max, "0");
3264
3516
  withPush = (result, deliveries) => deliveries.length ? { ...result, deliveries } : result;
3517
+ GMAIL_SYSTEM_LABEL_NAMES = /* @__PURE__ */ new Set(["INBOX", "SPAM", "TRASH", "UNREAD", "STARRED", "IMPORTANT", "SENT", "DRAFT", "CHAT"]);
3265
3518
  JIRA_TRANSITIONS = { "11": "To Do", "21": "In Progress", "31": "Done" };
3266
3519
  discordError = (collection, code, message) => ({ status: code === 10003 || code === 10004 ? 404 : 400, body: { message, code }, collection });
3267
3520
  ZENDESK_STATUSES = ["new", "open", "pending", "solved", "closed"];
@@ -3310,13 +3563,13 @@ var init_rest_adapters = __esm({
3310
3563
  });
3311
3564
 
3312
3565
  // src/runtime/seed.ts
3313
- import { createHash as createHash3, randomBytes } from "crypto";
3566
+ import { createHash as createHash4, randomBytes } from "crypto";
3314
3567
  function normalizeSeed(seed) {
3315
3568
  if (seed === void 0 || seed.trim() === "") return randomBytes(16).toString("hex");
3316
3569
  const text2 = normalizeHex(seed);
3317
3570
  if (!/^[a-f0-9]+$/.test(text2) || text2.length > 256) throw new Error(`Seed must be up to 256 hex characters or empty to generate; got ${seed.slice(0, 40)}`);
3318
3571
  if (text2.length === 32) return text2;
3319
- return createHash3("sha256").update(text2).digest("hex").slice(0, 32);
3572
+ return createHash4("sha256").update(text2).digest("hex").slice(0, 32);
3320
3573
  }
3321
3574
  function faultOrdinals(selection, seed) {
3322
3575
  const count = selection.type === "timeout-after-write" ? 1 : selection.count ?? 1;
@@ -3346,7 +3599,7 @@ var init_seed = __esm({
3346
3599
  purpose;
3347
3600
  counter = 0;
3348
3601
  draw() {
3349
- const value = createHash3("sha256").update(`agenttwin-stream|${this.seed}|${this.purpose}|${this.counter}`).digest("hex");
3602
+ const value = createHash4("sha256").update(`agenttwin-stream|${this.seed}|${this.purpose}|${this.counter}`).digest("hex");
3350
3603
  this.counter++;
3351
3604
  return value;
3352
3605
  }
@@ -3901,10 +4154,69 @@ var init_adapters = __esm({
3901
4154
  }
3902
4155
  });
3903
4156
 
4157
+ // src/runtime/compatible-packs.ts
4158
+ function compatibleRequest(vendor, host, url) {
4159
+ if (host.toLowerCase() !== vendor.host) return void 0;
4160
+ if (vendor.prefix === "") return { host: BASE_HOST, url: url.startsWith("/v1/") ? url : "/v1" + url };
4161
+ if (url === vendor.prefix || url.startsWith(vendor.prefix + "/") || url.startsWith(vendor.prefix + "?")) return { host: BASE_HOST, url: "/v1" + url.slice(vendor.prefix.length) };
4162
+ return void 0;
4163
+ }
4164
+ function compatibleModel(pack, body) {
4165
+ const same = { body, restore: (b) => b };
4166
+ if (!compatibleVendor(pack) || !body?.length) return same;
4167
+ let parsed;
4168
+ try {
4169
+ parsed = JSON.parse(body.toString("utf8"));
4170
+ } catch {
4171
+ return same;
4172
+ }
4173
+ const model = parsed?.model;
4174
+ if (typeof model !== "string" || !model || model === STAND_IN_MODEL) return same;
4175
+ const swapped = Buffer.from(JSON.stringify({ ...parsed, model: STAND_IN_MODEL }));
4176
+ const from = JSON.stringify(STAND_IN_MODEL), to = JSON.stringify(model);
4177
+ 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}]`)) };
4178
+ }
4179
+ var OPENAI_COMPATIBLE, BASE_PACK, BASE_HOST, compatibleVendor, STAND_IN_MODEL;
4180
+ var init_compatible_packs = __esm({
4181
+ "src/runtime/compatible-packs.ts"() {
4182
+ "use strict";
4183
+ OPENAI_COMPATIBLE = [
4184
+ // https://console.groq.com/docs/openai
4185
+ { name: "groq", title: "Groq", host: "api.groq.com", prefix: "/openai/v1", sdks: ["groq-sdk", "@ai-sdk/groq"], pypi: ["groq"], env: ["GROQ_API_KEY"] },
4186
+ // https://inference-docs.cerebras.ai/resources/openai
4187
+ { 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"] },
4188
+ // https://docs.perplexity.ai/guides/chat-completions-guide (POST https://api.perplexity.ai/chat/completions)
4189
+ { 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"] },
4190
+ // https://docs.sambanova.ai/cloud/docs/capabilities/openai-compatibility
4191
+ { name: "sambanova", title: "SambaNova", host: "api.sambanova.ai", prefix: "/v1", sdks: ["sambanova", "@ai-sdk/sambanova"], pypi: ["sambanova"], env: ["SAMBANOVA_API_KEY"] }
4192
+ ];
4193
+ BASE_PACK = "openai";
4194
+ BASE_HOST = "api.openai.com";
4195
+ compatibleVendor = (name) => OPENAI_COMPATIBLE.find((v) => v.name === name);
4196
+ STAND_IN_MODEL = "gpt-4o-mini";
4197
+ }
4198
+ });
4199
+
3904
4200
  // src/runtime/packs.ts
3905
- import { existsSync, readFileSync } from "fs";
4201
+ import { existsSync, readdirSync, readFileSync } from "fs";
3906
4202
  import { dirname, join as join4, resolve as resolve2 } from "path";
3907
4203
  import { fileURLToPath, pathToFileURL } from "url";
4204
+ function packWebSocketServer(generation) {
4205
+ let found = webSockets.get(generation);
4206
+ if (!found) {
4207
+ found = (async () => {
4208
+ const dir = join4(packsDir(), "engine", generation, "chunks");
4209
+ for (const file of readdirSync(dir).filter((f) => f.endsWith(".mjs"))) {
4210
+ if (!readFileSync(join4(dir, file), "utf8").includes("as WebSocketServer")) continue;
4211
+ const mod = await import(pathToFileURL(join4(dir, file)).href);
4212
+ if (mod.WebSocketServer) return mod.WebSocketServer;
4213
+ }
4214
+ throw new Error(`The ${generation} twin engine ships no WebSocket server`);
4215
+ })();
4216
+ webSockets.set(generation, found);
4217
+ }
4218
+ return found;
4219
+ }
3908
4220
  function packsDir() {
3909
4221
  const here = dirname(fileURLToPath(import.meta.url));
3910
4222
  const candidates = [process.env.AGENTTWIN_TWINS_DIR, join4(here, "twins"), join4(here, "../twins"), resolve2(here, "../../../twins/dist")];
@@ -3914,6 +4226,22 @@ function packCatalog() {
3914
4226
  if (cached !== void 0) return cached;
3915
4227
  const dir = packsDir();
3916
4228
  cached = dir ? JSON.parse(readFileSync(join4(dir, "catalog.json"), "utf8")) : null;
4229
+ const base = cached?.packs[BASE_PACK];
4230
+ if (cached && base) for (const v of OPENAI_COMPATIBLE) {
4231
+ if (Object.hasOwn(cached.packs, v.name)) continue;
4232
+ const field = base.credentialDoor?.fill.OPENAI_API_KEY ?? "api_key";
4233
+ cached.packs[v.name] = {
4234
+ ...base,
4235
+ name: v.name,
4236
+ vendor: v.name,
4237
+ servedBy: BASE_PACK,
4238
+ description: `${v.title} (OpenAI-compatible API), served by the OpenAI twin`,
4239
+ hosts: [{ host: v.host }],
4240
+ adoption: { sdks: v.sdks, envStems: v.env.map((e) => e.replace(/_API_KEY$/, "")), pypi: v.pypi },
4241
+ credentialDoor: base.credentialDoor ? { ...base.credentialDoor, fill: Object.fromEntries(v.env.map((e) => [e, field])) } : null
4242
+ };
4243
+ delete cached.excluded?.[v.name];
4244
+ }
3917
4245
  return cached;
3918
4246
  }
3919
4247
  function loadPack(name) {
@@ -3921,7 +4249,7 @@ function loadPack(name) {
3921
4249
  if (!record3) throw new Error(`No twin pack named ${name}`);
3922
4250
  let factory = loaded.get(name);
3923
4251
  if (!factory) {
3924
- const file = join4(packsDir(), "packs", name, "index.mjs");
4252
+ const file = join4(packsDir(), "packs", record3.servedBy ?? name, "index.mjs");
3925
4253
  factory = import(pathToFileURL(file).href).then((mod) => {
3926
4254
  if (typeof mod.createTwinFetch !== "function") throw new Error(`Twin pack ${name} exports no createTwinFetch`);
3927
4255
  return mod.createTwinFetch;
@@ -3930,10 +4258,12 @@ function loadPack(name) {
3930
4258
  }
3931
4259
  return factory;
3932
4260
  }
3933
- var cached, PACK_PREFIX, isPackAdapter, packRecord, loaded;
4261
+ var webSockets, cached, PACK_PREFIX, isPackAdapter, packRecord, loaded;
3934
4262
  var init_packs = __esm({
3935
4263
  "src/runtime/packs.ts"() {
3936
4264
  "use strict";
4265
+ init_compatible_packs();
4266
+ webSockets = /* @__PURE__ */ new Map();
3937
4267
  PACK_PREFIX = "pack:";
3938
4268
  isPackAdapter = (adapter) => typeof adapter === "string" && adapter.startsWith(PACK_PREFIX) && !!packRecord(adapter.slice(PACK_PREFIX.length));
3939
4269
  packRecord = (name) => {
@@ -3945,7 +4275,7 @@ var init_packs = __esm({
3945
4275
  });
3946
4276
 
3947
4277
  // src/runtime/enterprise-twins.ts
3948
- import { createHash as createHash4 } from "crypto";
4278
+ import { createHash as createHash5 } from "crypto";
3949
4279
  function eqFilter(expression, quote3) {
3950
4280
  const parts = expression.split(/\s+and\s+/i), tests = [];
3951
4281
  for (const part of parts) {
@@ -4002,7 +4332,7 @@ var init_enterprise_twins = __esm({
4002
4332
  isEnterpriseAdapter = (name) => ENTERPRISE_ADAPTERS.includes(name);
4003
4333
  EPOCH2 = 17e8;
4004
4334
  iso2 = (sequence) => new Date(twinNowMs((EPOCH2 + sequence) * 1e3)).toISOString();
4005
- hash = (seed) => createHash4("sha256").update(seed).digest("hex");
4335
+ hash = (seed) => createHash5("sha256").update(seed).digest("hex");
4006
4336
  isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
4007
4337
  scalar = (v) => v === null || ["string", "number", "boolean"].includes(typeof v);
4008
4338
  flat = (v) => Object.values(v).every(scalar);
@@ -4948,7 +5278,7 @@ function parseWorld(value) {
4948
5278
  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");
4949
5279
  const paths = /* @__PURE__ */ new Set();
4950
5280
  for (const entry of item.collections) {
4951
- 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");
5281
+ 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");
4952
5282
  const collection = entry;
4953
5283
  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");
4954
5284
  paths.add(collection.path);
@@ -4957,6 +5287,7 @@ function parseWorld(value) {
4957
5287
  const optional = ADAPTER_OPTIONAL_COLLECTIONS[item.adapter] ?? [];
4958
5288
  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(", ")})` : ""}`);
4959
5289
  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");
5290
+ 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");
4960
5291
  services.set(item.name, /* @__PURE__ */ new Set([...paths, ...optional]));
4961
5292
  }
4962
5293
  const known2 = (entry) => typeof entry.service === "string" && typeof entry.path === "string" && services.get(entry.service)?.has(entry.path);
@@ -5143,7 +5474,8 @@ var init_spec = __esm({
5143
5474
  init_enterprise_twins();
5144
5475
  RUNTIMES = /^(?:\/[\w./-]+\/)?(?:node|python[0-9.]*|uv|poetry|pipenv|go|ruby|bundle|deno|bun|curl)$/;
5145
5476
  ADAPTER_OPTIONAL_COLLECTIONS = {
5146
- stripe: ["/v1/charges", "/v1/refunds", "/v1/events"],
5477
+ slack: ["/users"],
5478
+ stripe: ["/v1/charges", "/v1/refunds", "/v1/events", "/v1/subscription_items", "/v1/products", "/v1/prices"],
5147
5479
  gmail: ["/gmail/v1/users/me/drafts", "/gmail/v1/users/me/settings/sendAs", "/gmail/v1/users/me/watch", "/pubsub/subscriptions", "/pubsub/messages"],
5148
5480
  ...ENTERPRISE_OPTIONAL_COLLECTIONS
5149
5481
  };
@@ -5181,8 +5513,169 @@ var init_spec = __esm({
5181
5513
  }
5182
5514
  });
5183
5515
 
5516
+ // src/runtime/postgrest.ts
5517
+ import { createRequire as createRequire2 } from "module";
5518
+ var loadPg, ident2, OPS, RESERVED, PostgrestLayer;
5519
+ var init_postgrest = __esm({
5520
+ "src/runtime/postgrest.ts"() {
5521
+ "use strict";
5522
+ loadPg = () => createRequire2(import.meta.url)("pg");
5523
+ ident2 = (name) => `"${name.replace(/"/g, '""')}"`;
5524
+ OPS = { eq: "=", neq: "<>", gt: ">", gte: ">=", lt: "<", lte: "<=", like: "LIKE", ilike: "ILIKE" };
5525
+ RESERVED = /* @__PURE__ */ new Set(["select", "order", "limit", "offset", "on_conflict", "columns", "or", "and"]);
5526
+ PostgrestLayer = class _PostgrestLayer {
5527
+ pool;
5528
+ fks;
5529
+ constructor(databaseUrl) {
5530
+ this.pool = new (loadPg()).Pool({ connectionString: databaseUrl, max: 1 });
5531
+ }
5532
+ close() {
5533
+ return this.pool.end().catch(() => {
5534
+ });
5535
+ }
5536
+ foreignKeys() {
5537
+ 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"
5538
+ 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]
5539
+ 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, "") })));
5540
+ }
5541
+ /** Splits a select list at top-level commas: `id, name, prices(*, product:products(name))`. */
5542
+ static items(select) {
5543
+ const out = [];
5544
+ let depth = 0, cur = "";
5545
+ for (const c of select) {
5546
+ if (c === "(") depth++;
5547
+ if (c === ")") depth--;
5548
+ if (c === "," && !depth) {
5549
+ out.push(cur.trim());
5550
+ cur = "";
5551
+ } else cur += c;
5552
+ }
5553
+ if (cur.trim()) out.push(cur.trim());
5554
+ return out;
5555
+ }
5556
+ async columns(table2, alias, select) {
5557
+ const parts = [];
5558
+ for (const item of _PostgrestLayer.items(select || "*")) {
5559
+ const embed = /^(?:(\w+):)?(\w+)(?:!\w+)?\((.*)\)$/s.exec(item);
5560
+ if (!embed) {
5561
+ if (item === "*") {
5562
+ parts.push(`${alias}.*`);
5563
+ continue;
5564
+ }
5565
+ const m = /^(?:(\w+):)?(\w+)(?:::\w+)?$/.exec(item);
5566
+ if (!m) continue;
5567
+ parts.push(`${alias}.${ident2(m[2])} AS ${ident2(m[1] ?? m[2])}`);
5568
+ continue;
5569
+ }
5570
+ const [, as, rel, inner] = embed, fks = await this.foreignKeys(), child = `e${parts.length}_${alias}`;
5571
+ const many = fks.find((f) => f.table === rel && f.refTable === table2), one = fks.find((f) => f.table === table2 && f.refTable === rel);
5572
+ const cols = await this.columns(rel, child, inner);
5573
+ 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)}`);
5574
+ 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)}`);
5575
+ }
5576
+ return parts.join(", ") || `${alias}.*`;
5577
+ }
5578
+ /** WHERE clause from `col=op.value` query parameters. */
5579
+ static where(params, values) {
5580
+ const clauses = [];
5581
+ for (const [key2, raw] of params) {
5582
+ if (RESERVED.has(key2)) continue;
5583
+ const not = raw.startsWith("not."), text2 = not ? raw.slice(4) : raw, dot = text2.indexOf(".");
5584
+ const op2 = text2.slice(0, dot), value = text2.slice(dot + 1), col = ident2(key2);
5585
+ let clause;
5586
+ if (OPS[op2]) {
5587
+ values.push(op2.endsWith("like") ? value.replace(/\*/g, "%") : value);
5588
+ clause = `${col}::text ${OPS[op2]} $${values.length}`;
5589
+ if (op2 === "eq" || op2 === "neq") clause = `${col} ${OPS[op2]} $${values.length}`;
5590
+ } else if (op2 === "is") clause = `${col} IS ${value === "null" ? "NULL" : value === "true" ? "TRUE" : value === "false" ? "FALSE" : "UNKNOWN"}`;
5591
+ else if (op2 === "in") {
5592
+ values.push(value.replace(/^\(|\)$/g, "").split(",").map((v) => v.replace(/^"|"$/g, "")));
5593
+ clause = `${col}::text = ANY($${values.length}::text[])`;
5594
+ }
5595
+ if (clause) clauses.push(not ? `NOT (${clause})` : clause);
5596
+ }
5597
+ return clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
5598
+ }
5599
+ async handle(request) {
5600
+ const header3 = (name) => {
5601
+ const v = request.headers[name];
5602
+ return Array.isArray(v) ? v.join(",") : v ?? "";
5603
+ };
5604
+ const prefer = header3("prefer"), single = /vnd\.pgrst\.object/.test(header3("accept"));
5605
+ const reply = (status, body, extra = {}) => ({ status, headers: { "content-type": "application/json; charset=utf-8", ...extra }, body: body === void 0 ? "" : JSON.stringify(body) });
5606
+ const segments = request.url.pathname.replace(/^\/rest\/v1\/?/, "").split("/").filter(Boolean).map(decodeURIComponent);
5607
+ if (!segments.length) return reply(404, { code: "PGRST125", message: "Invalid path specified in request URL" });
5608
+ const params = request.url.searchParams, values = [];
5609
+ let payload;
5610
+ try {
5611
+ payload = request.body?.length ? JSON.parse(request.body.toString("utf8")) : void 0;
5612
+ } catch {
5613
+ return reply(400, { code: "PGRST102", message: "Empty or invalid json" });
5614
+ }
5615
+ try {
5616
+ if (segments[0] === "rpc" && segments[1]) {
5617
+ const args = payload && typeof payload === "object" && !Array.isArray(payload) ? Object.entries(payload) : [...params].map(([k, v]) => [k, v]);
5618
+ const list2 = args.map(([k, v], i) => {
5619
+ values.push(v !== null && typeof v === "object" ? JSON.stringify(v) : v);
5620
+ return `${ident2(k)} => $${i + 1}`;
5621
+ });
5622
+ const r = await this.pool.query(`SELECT to_json(f) AS v FROM ${ident2(segments[1])}(${list2.join(", ")}) f`, values);
5623
+ const rows3 = r.rows.map((x) => x.v);
5624
+ 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);
5625
+ }
5626
+ const table2 = segments[0], t = ident2(table2);
5627
+ const returning = async (sql2) => {
5628
+ const cols = await this.columns(table2, "r", params.get("select") ?? "*");
5629
+ return `WITH r AS (${sql2} RETURNING *) SELECT coalesce(json_agg(x), '[]'::json) AS rows FROM (SELECT ${cols} FROM r) x`;
5630
+ };
5631
+ let sql, status = 200;
5632
+ const method = request.method.toUpperCase();
5633
+ if (method === "GET" || method === "HEAD") {
5634
+ const order = (params.get("order") ?? "").split(",").filter(Boolean).map((o) => {
5635
+ const [c, dir, nulls] = o.split(".");
5636
+ return `${ident2(c)} ${dir === "desc" ? "DESC" : "ASC"}${nulls === "nullsfirst" ? " NULLS FIRST" : nulls === "nullslast" ? " NULLS LAST" : ""}`;
5637
+ });
5638
+ const limit = Number(params.get("limit")), offset = Number(params.get("offset"));
5639
+ const cols = await this.columns(table2, "t", params.get("select") ?? "*");
5640
+ 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(", ")}` : ""}${limit >= 0 && params.has("limit") ? ` LIMIT ${Math.trunc(limit)}` : ""}${offset > 0 ? ` OFFSET ${Math.trunc(offset)}` : ""}) x`;
5641
+ } else if (method === "POST") {
5642
+ const rows3 = Array.isArray(payload) ? payload : [payload ?? {}];
5643
+ const keys = [...new Set(rows3.flatMap((r) => Object.keys(r)))];
5644
+ values.push(JSON.stringify(rows3));
5645
+ const target = params.get("on_conflict")?.split(",").map(ident2).join(", ");
5646
+ 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;
5647
+ const merge = /resolution=merge-duplicates/.test(prefer), ignore = /resolution=ignore-duplicates/.test(prefer);
5648
+ const conflict = (merge || ignore) && pk ? ` ON CONFLICT (${pk}) DO ${ignore || !keys.length ? "NOTHING" : `UPDATE SET ${keys.map((k) => `${ident2(k)} = EXCLUDED.${ident2(k)}`).join(", ")}`}` : "";
5649
+ 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`;
5650
+ if (!keys.length) values.length = 0;
5651
+ sql = await returning(insert);
5652
+ status = 201;
5653
+ } else if (method === "PATCH") {
5654
+ const keys = Object.keys(payload ?? {});
5655
+ values.push(JSON.stringify(payload ?? {}));
5656
+ const set = keys.map((k) => `${ident2(k)} = (json_populate_record(null::${t}, $1::json)).${ident2(k)}`).join(", ");
5657
+ sql = await returning(`UPDATE ${t} SET ${set || "ctid = ctid"}${_PostgrestLayer.where(params, values)}`);
5658
+ } else if (method === "DELETE") {
5659
+ sql = await returning(`DELETE FROM ${t}${_PostgrestLayer.where(params, values)}`);
5660
+ } else return reply(405, { code: "PGRST117", message: `Unsupported HTTP method: ${method}` });
5661
+ const rows2 = (await this.pool.query(sql, values)).rows[0]?.rows ?? [];
5662
+ const range = { "content-range": `0-${Math.max(rows2.length - 1, 0)}/${/count=exact/.test(prefer) ? rows2.length : "*"}` };
5663
+ if (method !== "GET" && /return=minimal/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
5664
+ if (method !== "GET" && !/return=representation/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
5665
+ 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 });
5666
+ return reply(status, rows2, range);
5667
+ } catch (error) {
5668
+ const e = error;
5669
+ const status = e.code === "23505" ? 409 : e.code === "42P01" ? 404 : e.code === "42501" ? 403 : 400;
5670
+ return reply(status, { code: e.code === "42P01" ? "PGRST205" : e.code ?? "PGRST000", message: e.message ?? String(error), details: e.detail ?? null, hint: e.hint ?? null });
5671
+ }
5672
+ }
5673
+ };
5674
+ }
5675
+ });
5676
+
5184
5677
  // src/runtime/pack-log.ts
5185
- import { closeSync, existsSync as existsSync2, openSync, readdirSync, readSync, statSync } from "fs";
5678
+ import { closeSync, existsSync as existsSync2, openSync, readdirSync as readdirSync2, readSync, statSync } from "fs";
5186
5679
  import { join as join5 } from "path";
5187
5680
  function packCollection(type, requestPath) {
5188
5681
  const segments = requestPath.split("/").filter(Boolean);
@@ -5223,7 +5716,7 @@ var init_pack_log = __esm({
5223
5716
  partial = /* @__PURE__ */ new Map();
5224
5717
  files() {
5225
5718
  if (!existsSync2(this.root)) return [];
5226
- return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join5(this.root, f)).sort();
5719
+ return readdirSync2(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join5(this.root, f)).sort();
5227
5720
  }
5228
5721
  drain() {
5229
5722
  const out = [];
@@ -5254,15 +5747,37 @@ var init_pack_log = __esm({
5254
5747
  }
5255
5748
  });
5256
5749
 
5750
+ // src/runtime/pack-aliases.ts
5751
+ function aliasRequest(pack, host, url) {
5752
+ const at = url.indexOf("?"), path = at < 0 ? url : url.slice(0, at), query = at < 0 ? "" : url.slice(at);
5753
+ const vendor = compatibleVendor(pack), compatible = vendor && compatibleRequest(vendor, host, url);
5754
+ if (compatible) return compatible;
5755
+ const alias = PACK_ALIASES[pack]?.find((a) => a.host === host.toLowerCase() && a.path === path);
5756
+ return alias ? { host: alias.to.host, url: alias.to.path + query } : { host, url };
5757
+ }
5758
+ var PACK_ALIASES;
5759
+ var init_pack_aliases = __esm({
5760
+ "src/runtime/pack-aliases.ts"() {
5761
+ "use strict";
5762
+ init_compatible_packs();
5763
+ PACK_ALIASES = {
5764
+ // Google's OpenID Connect discovery names openidconnect.googleapis.com/v1/userinfo; the pack models the
5765
+ // equivalent www.googleapis.com/oauth2/v3/userinfo (https://developers.google.com/identity/openid-connect/openid-connect).
5766
+ googleoauth: [{ host: "openidconnect.googleapis.com", path: "/v1/userinfo", to: { host: "www.googleapis.com", path: "/oauth2/v3/userinfo" } }]
5767
+ };
5768
+ }
5769
+ });
5770
+
5257
5771
  // src/runtime/http-world.ts
5258
5772
  import { createServer as createServer3 } from "http";
5773
+ import { createServer as createNetServer } from "net";
5259
5774
  import { isDeepStrictEqual } from "util";
5260
- import { createHash as createHash5 } from "crypto";
5775
+ import { createHash as createHash6 } from "crypto";
5261
5776
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
5262
5777
  import { mkdir, mkdtemp as mkdtemp3, rm as rm3, writeFile as writeFile2 } from "fs/promises";
5263
5778
  import { tmpdir as tmpdir3 } from "os";
5264
5779
  import { join as join6 } from "path";
5265
- var idempotencyKeyDigest, HttpWorld;
5780
+ var slackDirectMessageId, idempotencyKeyDigest, HttpWorld;
5266
5781
  var init_http_world = __esm({
5267
5782
  "src/runtime/http-world.ts"() {
5268
5783
  "use strict";
@@ -5274,9 +5789,13 @@ var init_http_world = __esm({
5274
5789
  init_spec();
5275
5790
  init_enterprise_twins();
5276
5791
  init_adapters();
5792
+ init_postgrest();
5277
5793
  init_packs();
5278
5794
  init_pack_log();
5279
- idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash5("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
5795
+ init_pack_aliases();
5796
+ init_compatible_packs();
5797
+ slackDirectMessageId = (user) => `D${createHash6("sha256").update(user).digest("hex").slice(0, 16).toUpperCase()}`;
5798
+ idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash6("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
5280
5799
  HttpWorld = class {
5281
5800
  /** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
5282
5801
  constructor(spec, seed, options = {}) {
@@ -5302,6 +5821,12 @@ var init_http_world = __esm({
5302
5821
  epoch = 0;
5303
5822
  replayKeys = /* @__PURE__ */ new Map();
5304
5823
  sourceContext = new AsyncLocalStorage2();
5824
+ postgrest;
5825
+ /** The run's PostgreSQL: a pack's PostgREST paths (/rest/v1/<table>) are served from it, so the app's own tables answer. */
5826
+ attachDatabase(url) {
5827
+ void this.postgrest?.close();
5828
+ this.postgrest = new PostgrestLayer(url);
5829
+ }
5305
5830
  record(service, operation, path, detail, record3) {
5306
5831
  if (this.events.length >= 5e4) return;
5307
5832
  const source = this.sourceContext.getStore();
@@ -5312,6 +5837,33 @@ var init_http_world = __esm({
5312
5837
  * each, after the triggering response. Only loopback http endpoints are allowed, so a push can never leave the
5313
5838
  * machine; the outcome is written to the push row and recorded as a `push` event.
5314
5839
  */
5840
+ sentWebhooks = /* @__PURE__ */ new Set();
5841
+ /** Sends a webhook a pack signed and queued, with the pack's own signature headers. Loopback http only. */
5842
+ sendWebhook(service, url, body, headers, eventType) {
5843
+ const epoch = this.epoch;
5844
+ const timer = setTimeout(async () => {
5845
+ this.timers.delete(timer);
5846
+ if (epoch !== this.epoch) return;
5847
+ let target;
5848
+ try {
5849
+ target = new URL(url);
5850
+ } catch {
5851
+ target = void 0;
5852
+ }
5853
+ if (!target || target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || target.username || target.password) {
5854
+ this.record(service, "webhook", url, `webhook ${eventType} not sent: the endpoint is not a loopback http URL (nothing leaves this machine)`);
5855
+ return;
5856
+ }
5857
+ try {
5858
+ const response = await fetch(target, { method: "POST", headers: { "content-type": "application/json", ...headers }, body, redirect: "error", signal: AbortSignal.timeout(6e4) });
5859
+ await response.arrayBuffer().catch(() => void 0);
5860
+ if (epoch === this.epoch) this.record(service, "webhook", url, `delivered ${eventType} to ${url}: HTTP ${response.status}`, { event: eventType, status: response.status });
5861
+ } catch (error) {
5862
+ if (epoch === this.epoch) this.record(service, "webhook", url, `webhook ${eventType} to ${url} failed: ${error instanceof Error ? error.message : String(error)}`);
5863
+ }
5864
+ }, 25);
5865
+ this.timers.add(timer);
5866
+ }
5315
5867
  push(service, deliveries, epoch) {
5316
5868
  for (const delivery of deliveries) {
5317
5869
  const timer = setTimeout(async () => {
@@ -5343,12 +5895,23 @@ var init_http_world = __esm({
5343
5895
  this.timers.add(timer);
5344
5896
  }
5345
5897
  }
5898
+ /** Tags every event recorded since index `from` with the request's idempotency key digest. */
5899
+ keyedSince(from, key2) {
5900
+ const digest2 = idempotencyKeyDigest(key2);
5901
+ if (digest2) for (let i = from; i < this.events.length; i++) this.events[i].idempotencyKey = digest2;
5902
+ }
5346
5903
  /** Tags the event just recorded with the request's idempotency key digest. */
5347
5904
  keyed(key2) {
5348
5905
  const digest2 = idempotencyKeyDigest(key2), last = this.events[this.events.length - 1];
5349
5906
  if (digest2 && last) last.idempotencyKey = digest2;
5350
5907
  }
5908
+ /** Requests the run itself sends to set a twin up (x-agenttwin-probe: 1): a refusal there is not the application's gap. */
5909
+ probes = 0;
5351
5910
  rejectUnsupported(service, method, path, detail) {
5911
+ if (this.probes > 0) {
5912
+ this.record(service, "assumption", path, `setup probe: ${detail}`);
5913
+ return;
5914
+ }
5352
5915
  this.unsupported.push(`${service}: ${method} ${path}: ${detail}`);
5353
5916
  this.record(service, "unsupported", path, detail);
5354
5917
  }
@@ -5395,340 +5958,382 @@ var init_http_world = __esm({
5395
5958
  this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server2.address().port}`, token };
5396
5959
  continue;
5397
5960
  }
5398
- const server = createServer3((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
5399
- const epoch = this.epoch;
5400
- const send = (code, body, headers = {}) => {
5401
- if (!res.destroyed) {
5402
- res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {}, ...headers });
5403
- res.end(code === 204 || code === 202 && body === null ? void 0 : typeof body === "string" && headers["content-type"] ? body : JSON.stringify(body));
5404
- }
5405
- };
5406
- const respond = (code, body, headers) => {
5407
- const ms = latencyMs();
5408
- if (ms <= 0) {
5409
- send(code, body, headers);
5410
- return;
5411
- }
5412
- const timer = setTimeout(() => {
5413
- this.timers.delete(timer);
5414
- if (epoch === this.epoch) send(code, body, headers);
5415
- }, ms);
5416
- this.timers.add(timer);
5417
- };
5418
- const normalPath = (url, method) => {
5419
- const parsed = new URL(url, "http://localhost");
5420
- if (generated) return generated.collectionOf(method ?? "", parsed.pathname) ?? parsed.pathname;
5421
- if (service.adapter === "google-oauth" && parsed.pathname === "/token" && method === "POST") return "/tokens";
5422
- if (service.adapter === "composio") {
5423
- if (/^\/api\/v3(?:\.1)?\/tools\/execute\//.test(parsed.pathname)) return "/messages";
5424
- if (/^\/api\/v3(?:\.1)?\/connected_accounts(?:\/|$)/.test(parsed.pathname)) return "/connected_accounts";
5425
- }
5426
- if (service.adapter === "slack") {
5427
- const m = parsed.pathname.replace(/^\/api\//, "");
5428
- if (m === "chat.postMessage" && method === "POST") return "/messages";
5429
- if (m === "conversations.history" && ["GET", "POST"].includes(method ?? "")) return "/messages";
5430
- if (m === "conversations.list" && ["GET", "POST"].includes(method ?? "")) return "/channels";
5961
+ const server = createServer3((req, res) => {
5962
+ if (req.headers["x-agenttwin-probe"] === "1") {
5963
+ this.probes++;
5964
+ res.once("close", () => {
5965
+ this.probes--;
5966
+ });
5967
+ }
5968
+ return withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
5969
+ const epoch = this.epoch;
5970
+ const send = (code, body, headers = {}) => {
5971
+ if (!res.destroyed) {
5972
+ res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {}, ...headers });
5973
+ res.end(code === 204 || code === 202 && body === null ? void 0 : typeof body === "string" && headers["content-type"] ? body : JSON.stringify(body));
5974
+ }
5975
+ };
5976
+ const respond = (code, body, headers) => {
5977
+ const ms = latencyMs();
5978
+ if (ms <= 0) {
5979
+ send(code, body, headers);
5980
+ return;
5981
+ }
5982
+ const timer = setTimeout(() => {
5983
+ this.timers.delete(timer);
5984
+ if (epoch === this.epoch) send(code, body, headers);
5985
+ }, ms);
5986
+ this.timers.add(timer);
5987
+ };
5988
+ const normalPath = (url, method) => {
5989
+ const parsed = new URL(url, "http://localhost");
5990
+ if (generated) return generated.collectionOf(method ?? "", parsed.pathname) ?? parsed.pathname;
5991
+ if (service.adapter === "google-oauth" && parsed.pathname === "/token" && method === "POST") return "/tokens";
5992
+ if (service.adapter === "composio") {
5993
+ if (/^\/api\/v3(?:\.1)?\/tools\/execute\//.test(parsed.pathname)) return "/messages";
5994
+ if (/^\/api\/v3(?:\.1)?\/connected_accounts(?:\/|$)/.test(parsed.pathname)) return "/connected_accounts";
5995
+ }
5996
+ if (service.adapter === "slack") {
5997
+ const m = parsed.pathname.replace(/^\/api\//, "");
5998
+ if (m === "chat.postMessage" && method === "POST") return "/messages";
5999
+ if (m === "conversations.history" && ["GET", "POST"].includes(method ?? "")) return "/messages";
6000
+ if (m === "conversations.list" && ["GET", "POST"].includes(method ?? "")) return "/channels";
6001
+ return parsed.pathname;
6002
+ }
5431
6003
  return parsed.pathname;
5432
- }
5433
- return parsed.pathname;
5434
- };
5435
- const matchesFault = (target) => adapterService ? target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path) : target === fault.path;
5436
- const requestKey = req.headers["idempotency-key"];
5437
- const respondSlowly = (target, operation, code, body, headers) => {
5438
- if (fault?.type !== "slow-response" || !faultOrdinalsFor || !matchesFault(target) || !faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
5439
- respond(code, body, headers);
5440
- return;
5441
- }
5442
- this.faultActions++;
5443
- this.record(service.name, "fault", target, `slow-response: ${operation} applied; response delayed ${fault.delayMs}ms`);
5444
- this.keyed(requestKey);
5445
- const timer = setTimeout(() => {
5446
- this.timers.delete(timer);
5447
- if (epoch === this.epoch) respond(code, body, headers);
5448
- }, fault.delayMs);
5449
- this.timers.add(timer);
5450
- };
5451
- const darkFault = () => {
5452
- if (!fault || !faultOrdinalsFor || fault.type !== "blackhole" && fault.type !== "server-error") return "none";
5453
- const target = normalPath(req.url ?? "/", req.method);
5454
- if (!matchesFault(target)) return "none";
5455
- const ordinal = this.candidateIndex(faultKey);
5456
- if (!faultOrdinalsFor.includes(ordinal)) return "none";
5457
- this.faultActions++;
5458
- return fault.type;
5459
- };
5460
- try {
5461
- const anyCredential = !!this.options.lenientModelAuth && (service.adapter === "openai" || service.adapter === "anthropic");
5462
- 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))) {
5463
- 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(", ")})`);
5464
- respond(401, { error: "invalid_test_credential" });
5465
- return;
5466
- }
5467
- if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
5468
- respond(429, { error: "world_capacity" });
5469
- return;
5470
- }
5471
- const darkness = darkFault();
5472
- if (darkness === "blackhole") {
5473
- 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"})`);
5474
- this.keyed(requestKey);
5475
- return;
5476
- }
5477
- if (darkness === "server-error") {
5478
- const windowMs = fault.windowMs ?? 0;
5479
- const delay = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
5480
- this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay}ms; nothing committed (${req.method ?? "request"})`);
5481
- this.keyed(requestKey);
5482
- const respond500 = () => respond(500, { error: { type: "api_error", message: "server_error fault" } });
5483
- if (delay <= 0) {
5484
- respond500();
6004
+ };
6005
+ const matchesFault = (target) => adapterService ? target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path) : target === fault.path;
6006
+ const requestKey = req.headers["idempotency-key"];
6007
+ const respondSlowly = (target, operation, code, body, headers) => {
6008
+ if (fault?.type !== "slow-response" || !faultOrdinalsFor || !matchesFault(target) || !faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
6009
+ respond(code, body, headers);
5485
6010
  return;
5486
6011
  }
6012
+ this.faultActions++;
6013
+ this.record(service.name, "fault", target, `slow-response: ${operation} applied; response delayed ${fault.delayMs}ms`);
6014
+ this.keyed(requestKey);
5487
6015
  const timer = setTimeout(() => {
5488
6016
  this.timers.delete(timer);
5489
- if (epoch === this.epoch) respond500();
5490
- }, delay);
6017
+ if (epoch === this.epoch) respond(code, body, headers);
6018
+ }, fault.delayMs);
5491
6019
  this.timers.add(timer);
5492
- return;
5493
- }
5494
- const url = new URL(req.url ?? "/", "http://localhost");
5495
- let path = url.pathname;
5496
- if (service.adapter === "composio" && [...url.searchParams.keys()].some((key3) => url.searchParams.getAll(key3).length !== 1)) {
5497
- this.rejectUnsupported(service.name, req.method ?? "", path, "Repeated query parameters are unsupported");
5498
- respond(501, restUnsupportedBody("composio"));
5499
- return;
5500
- }
5501
- if (service.adapter === "google-oauth" && url.search) {
5502
- this.rejectUnsupported(service.name, req.method ?? "", path, "OAuth token query parameters are unsupported");
5503
- respond(501, restUnsupportedBody("google-oauth"));
5504
- return;
5505
- }
5506
- const slack = service.adapter === "slack";
5507
- const slackMethod = path.replace(/^\/api\//, "");
5508
- let payload, rawBody;
5509
- if (["POST", "PUT", "PATCH"].includes(req.method ?? "")) {
5510
- const chunks = [];
5511
- let bytes = 0;
5512
- for await (const chunk of req) {
5513
- bytes += chunk.length;
5514
- if (bytes > 1024 * 1024) {
5515
- respond(413, { error: "body_too_large" });
6020
+ };
6021
+ const darkFault = () => {
6022
+ if (!fault || !faultOrdinalsFor || fault.type !== "blackhole" && fault.type !== "server-error") return "none";
6023
+ const target = normalPath(req.url ?? "/", req.method);
6024
+ if (!matchesFault(target)) return "none";
6025
+ const ordinal = this.candidateIndex(faultKey);
6026
+ if (!faultOrdinalsFor.includes(ordinal)) return "none";
6027
+ this.faultActions++;
6028
+ return fault.type;
6029
+ };
6030
+ try {
6031
+ const anyCredential = !!this.options.lenientModelAuth && (service.adapter === "openai" || service.adapter === "anthropic");
6032
+ 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))) {
6033
+ 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(", ")})`);
6034
+ respond(401, { error: "invalid_test_credential" });
6035
+ return;
6036
+ }
6037
+ if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
6038
+ respond(429, { error: "world_capacity" });
6039
+ return;
6040
+ }
6041
+ const darkness = darkFault();
6042
+ if (darkness === "blackhole") {
6043
+ 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"})`);
6044
+ this.keyed(requestKey);
6045
+ return;
6046
+ }
6047
+ if (darkness === "server-error") {
6048
+ const windowMs = fault.windowMs ?? 0;
6049
+ const delay = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
6050
+ this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay}ms; nothing committed (${req.method ?? "request"})`);
6051
+ this.keyed(requestKey);
6052
+ const respond500 = () => respond(500, { error: { type: "api_error", message: "server_error fault" } });
6053
+ if (delay <= 0) {
6054
+ respond500();
5516
6055
  return;
5517
6056
  }
5518
- chunks.push(Buffer.from(chunk));
6057
+ const timer = setTimeout(() => {
6058
+ this.timers.delete(timer);
6059
+ if (epoch === this.epoch) respond500();
6060
+ }, delay);
6061
+ this.timers.add(timer);
6062
+ return;
5519
6063
  }
5520
- const text2 = Buffer.concat(chunks).toString("utf8");
5521
- let parsed;
5522
- const mode = generated?.bodyMode(req.headers["content-type"]);
5523
- if ((enterprise || generated) && !text2.trim()) parsed = {};
5524
- else if (mode === "form") {
5525
- const form = new URLSearchParams(text2);
5526
- parsed = {};
5527
- for (const key3 of new Set(form.keys())) {
5528
- const all = form.getAll(key3);
5529
- parsed[key3] = all.length > 1 ? all : all[0];
6064
+ const url = new URL(req.url ?? "/", "http://localhost");
6065
+ let path = url.pathname;
6066
+ if (service.adapter === "composio" && [...url.searchParams.keys()].some((key3) => url.searchParams.getAll(key3).length !== 1)) {
6067
+ this.rejectUnsupported(service.name, req.method ?? "", path, "Repeated query parameters are unsupported");
6068
+ respond(501, restUnsupportedBody("composio"));
6069
+ return;
6070
+ }
6071
+ if (service.adapter === "google-oauth" && url.search) {
6072
+ this.rejectUnsupported(service.name, req.method ?? "", path, "OAuth token query parameters are unsupported");
6073
+ respond(501, restUnsupportedBody("google-oauth"));
6074
+ return;
6075
+ }
6076
+ const slack = service.adapter === "slack";
6077
+ const slackMethod = path.replace(/^\/api\//, "");
6078
+ let payload, rawBody;
6079
+ if (["POST", "PUT", "PATCH"].includes(req.method ?? "")) {
6080
+ const chunks = [];
6081
+ let bytes = 0;
6082
+ for await (const chunk of req) {
6083
+ bytes += chunk.length;
6084
+ if (bytes > 1024 * 1024) {
6085
+ respond(413, { error: "body_too_large" });
6086
+ return;
6087
+ }
6088
+ chunks.push(Buffer.from(chunk));
5530
6089
  }
5531
- } else if (mode === "raw") {
5532
- rawBody = text2;
5533
- parsed = {};
5534
- } else if (service.adapter === "gmail" && /^multipart\/mixed\b/i.test(String(req.headers["content-type"] ?? ""))) {
5535
- rawBody = text2;
5536
- parsed = {};
5537
- } else if (service.adapter === "gmail" && /^multipart\/related\b/i.test(String(req.headers["content-type"] ?? ""))) {
5538
- rawBody = text2;
5539
- parsed = Object.fromEntries(url.searchParams);
5540
- } else if (service.adapter === "upstash-redis") {
5541
- rawBody = text2;
5542
- parsed = {};
5543
- } else if (service.adapter === "gmail" && !text2.trim()) parsed = {};
5544
- else if (service.adapter === "google-oauth") {
5545
- if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
5546
- respond(400, { error: "invalid_request" });
6090
+ const text2 = Buffer.concat(chunks).toString("utf8");
6091
+ let parsed;
6092
+ const mode = generated?.bodyMode(req.headers["content-type"]);
6093
+ if ((enterprise || generated) && !text2.trim()) parsed = {};
6094
+ else if (mode === "form") {
6095
+ const form = new URLSearchParams(text2);
6096
+ parsed = {};
6097
+ for (const key3 of new Set(form.keys())) {
6098
+ const all = form.getAll(key3);
6099
+ parsed[key3] = all.length > 1 ? all : all[0];
6100
+ }
6101
+ } else if (mode === "raw") {
6102
+ rawBody = text2;
6103
+ parsed = {};
6104
+ } else if (service.adapter === "gmail" && /^multipart\/mixed\b/i.test(String(req.headers["content-type"] ?? ""))) {
6105
+ rawBody = text2;
6106
+ parsed = {};
6107
+ } else if (service.adapter === "gmail" && /^multipart\/related\b/i.test(String(req.headers["content-type"] ?? ""))) {
6108
+ rawBody = text2;
6109
+ parsed = Object.fromEntries(url.searchParams);
6110
+ } else if (service.adapter === "upstash-redis") {
6111
+ rawBody = text2;
6112
+ parsed = {};
6113
+ } else if (service.adapter === "gmail" && !text2.trim()) parsed = {};
6114
+ else if (service.adapter === "google-oauth") {
6115
+ if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
6116
+ respond(400, { error: "invalid_request" });
6117
+ return;
6118
+ }
6119
+ const form = new URLSearchParams(text2);
6120
+ if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
6121
+ respond(400, { error: "invalid_request" });
6122
+ return;
6123
+ }
6124
+ parsed = Object.fromEntries(form);
6125
+ } else try {
6126
+ parsed = (slack || service.adapter === "stripe" || service.adapter === "twilio") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(text2)) : JSON.parse(text2);
6127
+ } catch {
6128
+ respond(400, { error: "expected_json_object" });
5547
6129
  return;
5548
6130
  }
5549
- const form = new URLSearchParams(text2);
5550
- if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
5551
- respond(400, { error: "invalid_request" });
6131
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6132
+ respond(400, { error: "expected_json_object" });
5552
6133
  return;
5553
6134
  }
5554
- parsed = Object.fromEntries(form);
5555
- } else try {
5556
- parsed = (slack || service.adapter === "stripe" || service.adapter === "twilio") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(text2)) : JSON.parse(text2);
5557
- } catch {
5558
- respond(400, { error: "expected_json_object" });
5559
- return;
6135
+ payload = parsed;
5560
6136
  }
5561
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
5562
- respond(400, { error: "expected_json_object" });
6137
+ if (epoch !== this.epoch) {
6138
+ respond(409, { error: "world_reset" });
5563
6139
  return;
5564
6140
  }
5565
- payload = parsed;
5566
- }
5567
- if (epoch !== this.epoch) {
5568
- respond(409, { error: "world_reset" });
5569
- return;
5570
- }
5571
- if (generated && !payload && ["PUT", "DELETE"].includes(req.method ?? "")) payload = {};
5572
- if (service.adapter === "stripe" || restAdapter || enterprise || generated) {
5573
- const params = payload ?? Object.fromEntries(url.searchParams);
5574
- const keyHeader2 = req.headers["idempotency-key"] ?? (enterprise === "netsuite" ? req.headers["x-netsuite-idempotency-key"] : void 0);
5575
- const key3 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path}:${keyHeader2}` : void 0;
5576
- const signature2 = JSON.stringify(params);
5577
- const previous2 = key3 ? keys.get(key3) : void 0;
5578
- if (previous2) {
5579
- if (previous2.body !== signature2) {
5580
- respond(400, { error: { type: "idempotency_error", message: "Keys for idempotent requests can only be used with the same parameters" } });
6141
+ if (generated && !payload && ["PUT", "DELETE"].includes(req.method ?? "")) payload = {};
6142
+ if (service.adapter === "stripe" || restAdapter || enterprise || generated) {
6143
+ const params = payload ?? Object.fromEntries(url.searchParams);
6144
+ const keyHeader2 = req.headers["idempotency-key"] ?? (enterprise === "netsuite" ? req.headers["x-netsuite-idempotency-key"] : void 0);
6145
+ const key3 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path}:${keyHeader2}` : void 0;
6146
+ const signature2 = JSON.stringify(params);
6147
+ const previous2 = key3 ? keys.get(key3) : void 0;
6148
+ if (previous2) {
6149
+ if (previous2.body !== signature2) {
6150
+ respond(400, { error: { type: "idempotency_error", message: "Keys for idempotent requests can only be used with the same parameters" } });
6151
+ return;
6152
+ }
6153
+ this.record(service.name, "replay", path, "same-key response replay", previous2.record);
6154
+ this.keyed(keyHeader2);
6155
+ respondSlowly(path, "replay", previous2.status ?? 200, previous2.record, previous2.headers);
5581
6156
  return;
5582
6157
  }
5583
- this.record(service.name, "replay", path, "same-key response replay", previous2.record);
5584
- this.keyed(keyHeader2);
5585
- respondSlowly(path, "replay", previous2.status ?? 200, previous2.record, previous2.headers);
5586
- return;
5587
- }
5588
- const query = Object.fromEntries(url.searchParams);
5589
- const invoke = (sequence) => generated ? generated.handle({ method: req.method ?? "", path, query, headers: req.headers, ...payload ? { body: structuredClone(payload) } : {}, ...rawBody !== void 0 ? { raw: rawBody } : {} }, data, sequence, this.seed) : enterprise ? ENTERPRISE_OPERATIONS[enterprise](req.method ?? "", path, structuredClone(payload ?? {}), query, req.headers, data, sequence) : restAdapter ? restAdapter(req.method ?? "", path, params, req.headers, data, sequence, rawBody) : stripeOperation(req.method ?? "", path, params, data, sequence);
5590
- const headers = (r) => "headers" in r ? r.headers : void 0;
5591
- const result = invoke(this.events.length + 1);
5592
- if (!result) {
5593
- this.rejectUnsupported(service.name, req.method ?? "", path, `unsupported ${service.adapter} operation or parameters`);
5594
- respond(501, generated ? generated.unsupported(req.method ?? "", path) : 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 });
6158
+ const query = Object.fromEntries(url.searchParams);
6159
+ const invoke = (sequence) => generated ? generated.handle({ method: req.method ?? "", path, query, headers: req.headers, ...payload ? { body: structuredClone(payload) } : {}, ...rawBody !== void 0 ? { raw: rawBody } : {} }, data, sequence, this.seed) : enterprise ? ENTERPRISE_OPERATIONS[enterprise](req.method ?? "", path, structuredClone(payload ?? {}), query, req.headers, data, sequence) : restAdapter ? restAdapter(req.method ?? "", path, params, req.headers, data, sequence, rawBody) : stripeOperation(req.method ?? "", path, params, data, sequence);
6160
+ const headers = (r) => "headers" in r ? r.headers : void 0;
6161
+ const result = invoke(this.events.length + 1);
6162
+ if (!result) {
6163
+ this.rejectUnsupported(service.name, req.method ?? "", path, `unsupported ${service.adapter} operation or parameters`);
6164
+ respond(501, generated ? generated.unsupported(req.method ?? "", path) : 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 });
6165
+ return;
6166
+ }
6167
+ if ("unsupportedReason" in result && result.unsupportedReason) {
6168
+ this.rejectUnsupported(service.name, req.method ?? "", path, String(result.unsupportedReason));
6169
+ respond(result.status, result.body);
6170
+ return;
6171
+ }
6172
+ if (result.operation) {
6173
+ this.record(service.name, result.operation, result.collection, path, "record" in result ? result.record : result.body);
6174
+ this.keyed(keyHeader2);
6175
+ }
6176
+ if (key3 && (result.status === 200 || result.status === 201 || enterprise && (result.status === 202 || result.status === 204))) keys.set(key3, { body: signature2, record: structuredClone(result.body), status: result.status, ...headers(result) ? { headers: headers(result) } : {} });
6177
+ const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result.operation === "write" && !key3 && matchesFault(result.collection);
6178
+ const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
6179
+ const pushes = (r) => "deliveries" in r ? [...r.deliveries ?? []] : [];
6180
+ const deliveries = pushes(result);
6181
+ if (duplicate2) {
6182
+ const second = invoke(this.events.length + 1);
6183
+ if (second?.operation === "write") {
6184
+ deliveries.push(...pushes(second));
6185
+ this.record(service.name, second.operation, second.collection, path, "record" in second ? second.record : second.body);
6186
+ this.faultActions++;
6187
+ this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result.collection})`);
6188
+ } else if (second) {
6189
+ this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
6190
+ respond(second.status, second.body, headers(second));
6191
+ if (deliveries.length) this.push(service.name, deliveries, epoch);
6192
+ return;
6193
+ }
6194
+ }
6195
+ if (!this.fired && result.operation === "write" && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === result.collection) {
6196
+ this.fired = true;
6197
+ this.faultActions++;
6198
+ this.record(service.name, "fault", result.collection, `write committed; response delayed ${fault.delayMs}ms`);
6199
+ this.keyed(keyHeader2);
6200
+ const timer = setTimeout(() => {
6201
+ this.timers.delete(timer);
6202
+ respond(result.status, result.body, headers(result));
6203
+ }, fault.delayMs);
6204
+ this.timers.add(timer);
6205
+ } else respondSlowly(result.collection, result.operation ?? "request", result.status, result.body, headers(result));
6206
+ if (deliveries.length) this.push(service.name, deliveries, epoch);
5595
6207
  return;
5596
6208
  }
5597
- if (result.operation) {
5598
- this.record(service.name, result.operation, result.collection, path, "record" in result ? result.record : result.body);
5599
- this.keyed(keyHeader2);
5600
- }
5601
- if (key3 && (result.status === 200 || result.status === 201 || enterprise && (result.status === 202 || result.status === 204))) keys.set(key3, { body: signature2, record: structuredClone(result.body), status: result.status, ...headers(result) ? { headers: headers(result) } : {} });
5602
- const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result.operation === "write" && !key3 && matchesFault(result.collection);
5603
- const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
5604
- const pushes = (r) => "deliveries" in r ? [...r.deliveries ?? []] : [];
5605
- const deliveries = pushes(result);
5606
- if (duplicate2) {
5607
- const second = invoke(this.events.length + 1);
5608
- if (second?.operation === "write") {
5609
- deliveries.push(...pushes(second));
5610
- this.record(service.name, second.operation, second.collection, path, "record" in second ? second.record : second.body);
5611
- this.faultActions++;
5612
- this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result.collection})`);
5613
- } else if (second) {
5614
- this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
5615
- respond(second.status, second.body, headers(second));
5616
- if (deliveries.length) this.push(service.name, deliveries, epoch);
6209
+ if (slack) {
6210
+ const params = payload ?? Object.fromEntries(url.searchParams);
6211
+ const allowed = slackMethod === "chat.postMessage" ? ["channel", "text"] : slackMethod === "conversations.history" ? ["channel"] : [];
6212
+ if (Object.keys(params).some((k) => !allowed.includes(k))) {
6213
+ this.rejectUnsupported(service.name, req.method ?? "", url.pathname, `unsupported parameters for ${slackMethod}`);
6214
+ respond(501, { ok: false, error: "unsupported_parameters", forwardedToProduction: false });
6215
+ return;
6216
+ }
6217
+ if (slackMethod === "chat.postMessage" && req.method === "POST") path = "/messages";
6218
+ else if (slackMethod === "conversations.history" && ["GET", "POST"].includes(req.method ?? "")) path = "/messages";
6219
+ else if (slackMethod === "conversations.list" && ["GET", "POST"].includes(req.method ?? "")) path = "/channels";
6220
+ else {
6221
+ this.rejectUnsupported(service.name, req.method ?? "", url.pathname, "unsupported operation");
6222
+ respond(501, { ok: false, error: "unsupported_operation", forwardedToProduction: false });
5617
6223
  return;
5618
6224
  }
5619
6225
  }
5620
- if (!this.fired && result.operation === "write" && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === result.collection) {
5621
- this.fired = true;
5622
- this.faultActions++;
5623
- this.record(service.name, "fault", result.collection, `write committed; response delayed ${fault.delayMs}ms`);
5624
- this.keyed(keyHeader2);
5625
- const timer = setTimeout(() => {
5626
- this.timers.delete(timer);
5627
- respond(result.status, result.body, headers(result));
5628
- }, fault.delayMs);
5629
- this.timers.add(timer);
5630
- } else respondSlowly(result.collection, result.operation ?? "request", result.status, result.body, headers(result));
5631
- if (deliveries.length) this.push(service.name, deliveries, epoch);
5632
- return;
5633
- }
5634
- if (slack) {
5635
- const params = payload ?? Object.fromEntries(url.searchParams);
5636
- const allowed = slackMethod === "chat.postMessage" ? ["channel", "text"] : slackMethod === "conversations.history" ? ["channel"] : [];
5637
- if (Object.keys(params).some((k) => !allowed.includes(k))) {
5638
- this.rejectUnsupported(service.name, req.method ?? "", url.pathname, `unsupported parameters for ${slackMethod}`);
5639
- respond(501, { ok: false, error: "unsupported_parameters", forwardedToProduction: false });
6226
+ if (!Object.hasOwn(data, path) || !["GET", "POST"].includes(req.method ?? "")) {
6227
+ this.rejectUnsupported(service.name, req.method ?? "", path, "unsupported operation");
6228
+ respond(501, { error: "unsupported_operation", forwardedToProduction: false });
5640
6229
  return;
5641
6230
  }
5642
- if (slackMethod === "chat.postMessage" && req.method === "POST") path = "/messages";
5643
- else if (slackMethod === "conversations.history" && ["GET", "POST"].includes(req.method ?? "")) path = "/messages";
5644
- else if (slackMethod === "conversations.list" && ["GET", "POST"].includes(req.method ?? "")) path = "/channels";
5645
- else {
5646
- this.rejectUnsupported(service.name, req.method ?? "", url.pathname, "unsupported operation");
5647
- respond(501, { ok: false, error: "unsupported_operation", forwardedToProduction: false });
6231
+ if (req.method === "GET" || slack && slackMethod !== "chat.postMessage") {
6232
+ this.record(service.name, "read", path, `${data[path].length} records`);
6233
+ if (slack && path === "/channels") respondSlowly(path, "read", 200, { ok: true, channels: data[path], response_metadata: { next_cursor: "" } });
6234
+ else if (slack) {
6235
+ const channel = payload?.channel ?? url.searchParams.get("channel");
6236
+ if (!data["/channels"].some((c) => c.id === channel)) respond(200, { ok: false, error: "channel_not_found" });
6237
+ else respondSlowly(path, "read", 200, { ok: true, messages: data[path].filter((m) => m.channel === channel), has_more: false });
6238
+ } else respondSlowly(path, "read", 200, { data: data[path] });
5648
6239
  return;
5649
6240
  }
5650
- }
5651
- if (!Object.hasOwn(data, path) || !["GET", "POST"].includes(req.method ?? "")) {
5652
- this.rejectUnsupported(service.name, req.method ?? "", path, "unsupported operation");
5653
- respond(501, { error: "unsupported_operation", forwardedToProduction: false });
5654
- return;
5655
- }
5656
- if (req.method === "GET" || slack && slackMethod !== "chat.postMessage") {
5657
- this.record(service.name, "read", path, `${data[path].length} records`);
5658
- if (slack && path === "/channels") respondSlowly(path, "read", 200, { ok: true, channels: data[path], response_metadata: { next_cursor: "" } });
5659
- else if (slack) {
5660
- const channel = payload?.channel ?? url.searchParams.get("channel");
5661
- if (!data["/channels"].some((c) => c.id === channel)) respond(200, { ok: false, error: "channel_not_found" });
5662
- else respondSlowly(path, "read", 200, { ok: true, messages: data[path].filter((m) => m.channel === channel), has_more: false });
5663
- } else respondSlowly(path, "read", 200, { data: data[path] });
5664
- return;
5665
- }
5666
- const body = payload;
5667
- if (slack) {
5668
- const message = body;
5669
- if (!data["/channels"].some((c) => c.id === message.channel)) {
5670
- respond(200, { ok: false, error: "channel_not_found" });
5671
- return;
6241
+ const body = payload;
6242
+ if (slack) {
6243
+ const message = body;
6244
+ const channels = data["/channels"];
6245
+ const recipient = message.channel;
6246
+ let destination = channels.find((channel) => channel.id === recipient);
6247
+ if (typeof recipient === "string" && /^[UW][A-Z0-9]+$/.test(recipient)) {
6248
+ const user = data["/users"]?.find((row2) => row2.id === recipient);
6249
+ destination = channels.find((channel) => channel.is_im === true && channel.user === recipient);
6250
+ if (user?.deleted === true || user?.dmAllowed === false) destination = void 0;
6251
+ else if (!destination && user) {
6252
+ if (channels.length >= 1e4) {
6253
+ respond(429, { error: "world_capacity" });
6254
+ return;
6255
+ }
6256
+ const id = slackDirectMessageId(recipient);
6257
+ destination = { id, is_im: true, user: recipient };
6258
+ if (channels.some((channel) => channel.id === id)) {
6259
+ respond(409, { error: "channel_conflict" });
6260
+ return;
6261
+ }
6262
+ }
6263
+ }
6264
+ if (!destination) {
6265
+ respond(200, { ok: false, error: "channel_not_found" });
6266
+ return;
6267
+ }
6268
+ if (typeof message.text !== "string" || !message.text) {
6269
+ respond(200, { ok: false, error: "no_text" });
6270
+ return;
6271
+ }
6272
+ if (data[path].length >= 1e4 || this.events.length >= 5e4) {
6273
+ respond(429, { error: "world_capacity" });
6274
+ return;
6275
+ }
6276
+ if (!channels.includes(destination)) {
6277
+ channels.push(destination);
6278
+ this.record(service.name, "write", "/channels", String(destination.id), destination);
6279
+ }
6280
+ message.channel = destination.id;
5672
6281
  }
5673
- if (typeof message.text !== "string" || !message.text) {
5674
- respond(200, { ok: false, error: "no_text" });
6282
+ if (data[path].length >= 1e4 || this.events.length >= 5e4) {
6283
+ respond(429, { error: "world_capacity" });
5675
6284
  return;
5676
6285
  }
5677
- }
5678
- if (data[path].length >= 1e4 || this.events.length >= 5e4) {
5679
- respond(429, { error: "world_capacity" });
5680
- return;
5681
- }
5682
- const keyHeader = slack ? void 0 : req.headers["idempotency-key"];
5683
- const key2 = typeof keyHeader === "string" ? `${path}:${keyHeader}` : void 0;
5684
- const signature = JSON.stringify(body);
5685
- const previous = key2 ? keys.get(key2) : void 0;
5686
- if (previous) {
5687
- if (previous.body !== signature) {
5688
- respond(409, { error: "idempotency_conflict" });
6286
+ const keyHeader = slack ? void 0 : req.headers["idempotency-key"];
6287
+ const key2 = typeof keyHeader === "string" ? `${path}:${keyHeader}` : void 0;
6288
+ const signature = JSON.stringify(body);
6289
+ const previous = key2 ? keys.get(key2) : void 0;
6290
+ if (previous) {
6291
+ if (previous.body !== signature) {
6292
+ respond(409, { error: "idempotency_conflict" });
6293
+ return;
6294
+ }
6295
+ this.record(service.name, "replay", path, "same-key response replay", previous.record);
6296
+ this.keyed(keyHeader);
6297
+ respondSlowly(path, "replay", 200, previous.record);
5689
6298
  return;
5690
6299
  }
5691
- this.record(service.name, "replay", path, "same-key response replay", previous.record);
5692
- this.keyed(keyHeader);
5693
- respondSlowly(path, "replay", 200, previous.record);
5694
- return;
5695
- }
5696
- const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path && !key2 && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
5697
- if (duplicate) this.faultActions++;
5698
- let index = data[path].length + 1;
5699
- while (data[path].some((r) => r.id === `${service.name}_${index}`)) index++;
5700
- const row = { ...body, id: `${service.name}_${index}` };
5701
- if (slack) row.ts = `${index}.000001`;
5702
- const reply = slack ? { ok: true, channel: row.channel, ts: row.ts, message: row } : row;
5703
- data[path].push(row);
5704
- if (key2) keys.set(key2, { body: signature, record: row });
5705
- this.record(service.name, "write", path, String(row.id), row);
5706
- this.keyed(keyHeader);
5707
- if (duplicate) {
5708
- index++;
6300
+ const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path && !key2 && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
6301
+ if (duplicate) this.faultActions++;
6302
+ let index = data[path].length + 1;
5709
6303
  while (data[path].some((r) => r.id === `${service.name}_${index}`)) index++;
5710
- const second = { ...body, id: `${service.name}_${index}` };
5711
- if (slack) second.ts = `${index}.000001`;
5712
- data[path].push(second);
5713
- this.record(service.name, "write", path, String(second.id), second);
5714
- this.record(service.name, "fault", fault.path, `duplicate-write: one write committed as two records (${row.id}, ${second.id})`);
5715
- }
5716
- const faultResponse = slack ? 200 : 201;
5717
- if (!this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === path) {
5718
- this.fired = true;
5719
- this.faultActions++;
5720
- this.record(service.name, "fault", path, `write committed; response delayed ${fault.delayMs}ms`);
6304
+ const row = { ...body, id: `${service.name}_${index}` };
6305
+ if (slack) row.ts = `${index}.000001`;
6306
+ const reply = slack ? { ok: true, channel: row.channel, ts: row.ts, message: row } : row;
6307
+ data[path].push(row);
6308
+ if (key2) keys.set(key2, { body: signature, record: row });
6309
+ this.record(service.name, "write", path, String(row.id), row);
5721
6310
  this.keyed(keyHeader);
5722
- const timer = setTimeout(() => {
5723
- this.timers.delete(timer);
5724
- respond(faultResponse, reply);
5725
- }, fault.delayMs);
5726
- this.timers.add(timer);
5727
- } else respondSlowly(path, "write", faultResponse, reply);
5728
- } catch {
5729
- respond(500, { error: "world_request_error" });
5730
- }
5731
- })));
6311
+ if (duplicate) {
6312
+ index++;
6313
+ while (data[path].some((r) => r.id === `${service.name}_${index}`)) index++;
6314
+ const second = { ...body, id: `${service.name}_${index}` };
6315
+ if (slack) second.ts = `${index}.000001`;
6316
+ data[path].push(second);
6317
+ this.record(service.name, "write", path, String(second.id), second);
6318
+ this.record(service.name, "fault", fault.path, `duplicate-write: one write committed as two records (${row.id}, ${second.id})`);
6319
+ }
6320
+ const faultResponse = slack ? 200 : 201;
6321
+ if (!this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === path) {
6322
+ this.fired = true;
6323
+ this.faultActions++;
6324
+ this.record(service.name, "fault", path, `write committed; response delayed ${fault.delayMs}ms`);
6325
+ this.keyed(keyHeader);
6326
+ const timer = setTimeout(() => {
6327
+ this.timers.delete(timer);
6328
+ respond(faultResponse, reply);
6329
+ }, fault.delayMs);
6330
+ this.timers.add(timer);
6331
+ } else respondSlowly(path, "write", faultResponse, reply);
6332
+ } catch {
6333
+ respond(500, { error: "world_request_error" });
6334
+ }
6335
+ }));
6336
+ });
5732
6337
  server.requestTimeout = 1e4;
5733
6338
  await new Promise((resolve8, reject) => {
5734
6339
  server.once("error", reject);
@@ -5742,6 +6347,13 @@ var init_http_world = __esm({
5742
6347
  /** Environment each pack service's credential door issued (STRIPE_SECRET_KEY…), for the application's process. */
5743
6348
  packEnv = /* @__PURE__ */ Object.create(null);
5744
6349
  packRoots = [];
6350
+ /** Per service: 1 while a call the world makes is in flight and no envelope has been captured yet, 2 once one has. */
6351
+ causing = /* @__PURE__ */ Object.create(null);
6352
+ lastEnvelope = /* @__PURE__ */ Object.create(null);
6353
+ socketServers = [];
6354
+ rawServers = [];
6355
+ /** Each pack service's plain-TCP port for clients that open their own TLS sockets (see startPack). */
6356
+ packTcp = /* @__PURE__ */ Object.create(null);
5745
6357
  /**
5746
6358
  * A twin pack served behind this world: the run token is checked and swapped for the credential the pack issued,
5747
6359
  * seeded fault schedules apply around the pack's own handler, and every action the pack logs becomes evidence — writes
@@ -5759,7 +6371,8 @@ var init_http_world = __esm({
5759
6371
  await writeFile2(join6(dir, ".volter/world", meta.logService, "actions.jsonl"), text2);
5760
6372
  };
5761
6373
  let tenant = {}, credential;
5762
- if (meta.logService && meta.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account)) {
6374
+ let doorLines = "";
6375
+ if (meta.logService && meta.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account || service.doorRecords?.length)) {
5763
6376
  const probe = await mkdtemp3(join6(tmpdir3(), `agenttwin-pack-${name}-probe-`));
5764
6377
  try {
5765
6378
  await writeSeedLog(probe, worldSeed);
@@ -5768,37 +6381,76 @@ var init_http_world = __esm({
5768
6381
  const probed = new PackActionTail(join6(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
5769
6382
  tenant = tenantFields(probed);
5770
6383
  credential = credentialAction(probed);
6384
+ for (const rec of service.doorRecords ?? []) {
6385
+ const own = probed.filter((a) => a.subject?.type === rec.type);
6386
+ const original = own[0]?.subject?.id;
6387
+ if (!original) continue;
6388
+ 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("");
6389
+ }
5771
6390
  } finally {
5772
6391
  await rm3(probe, { recursive: true, force: true });
5773
6392
  }
5774
6393
  }
5775
6394
  const account = credential && service.account ? JSON.stringify({ ...credential, id: `${credential.id ?? "credential"}:preset`, fields: { ...credential.fields, ...service.account } }) + "\n" : "";
5776
- const seeded = meta.logService ? worldSeed + account + seedActions(meta.logService, service.collections, new Date(twinNowMs(Date.now())).toISOString(), tenant) : "";
6395
+ const seeded = meta.logService ? worldSeed + account + doorLines + seedActions(meta.logService, service.collections, new Date(twinNowMs(Date.now())).toISOString(), tenant) : "";
5777
6396
  await writeSeedLog(root, seeded);
5778
6397
  const twin = await (await loadPack(name))({ root });
5779
6398
  const baseHost = meta.hosts[0]?.host ?? `${name}.twin.test`;
5780
6399
  const log = new PackActionTail(join6(root, ".volter"));
5781
6400
  let issued = {};
5782
6401
  if (meta.credentialDoor) {
5783
- const r = await twin(new Request(`https://${baseHost}${meta.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta.credentialDoor.body ?? {}) }));
5784
- if (r.ok) issued = await r.json();
5785
- else await r.arrayBuffer();
6402
+ const hosts = [...new Set(meta.hosts.map((h) => h.host).filter((h) => !!h))];
6403
+ const door = (host) => twin(new Request(`https://${host}${meta.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta.credentialDoor.body ?? {}) }));
6404
+ for (const host of hosts.length ? hosts : [baseHost]) {
6405
+ let r = await door(host);
6406
+ if (r.status === 404 && meta.credentialDoor.body && Object.keys(meta.credentialDoor.body).length) {
6407
+ await r.arrayBuffer();
6408
+ const made = await twin(new Request(`https://${host}/_twin/accounts`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ email: "world@world.test", ...meta.credentialDoor.body }) }));
6409
+ await made.arrayBuffer();
6410
+ r = await door(host);
6411
+ }
6412
+ if (r.ok) {
6413
+ issued = await r.json();
6414
+ break;
6415
+ }
6416
+ await r.arrayBuffer();
6417
+ if (r.status !== 404) break;
6418
+ }
5786
6419
  }
5787
6420
  const env = {};
5788
- for (const [envName, field] of Object.entries(meta.credentialDoor?.fill ?? {})) if (typeof issued[field] === "string") env[envName] = issued[field];
6421
+ for (const [envName, field] of Object.entries(meta.credentialDoor?.fill ?? {})) {
6422
+ if (field.startsWith("file:")) {
6423
+ const value = issued[field.slice(5)];
6424
+ if (value && typeof value === "object") {
6425
+ const file = join6(root, `${envName.toLowerCase()}.json`);
6426
+ await writeFile2(file, JSON.stringify(value, null, 2), { mode: 384 });
6427
+ env[envName] = file;
6428
+ }
6429
+ } else if (typeof issued[field] === "string") env[envName] = issued[field];
6430
+ }
5789
6431
  this.packEnv[service.name] = env;
5790
6432
  const primaryEnv = Object.keys(env).find((k) => /(SECRET|API|PRIVATE|ACCESS)_?(KEY|TOKEN)$|_TOKEN$|_KEY$/.test(k) && !/PUBLISHABLE|PUBLIC|WEBHOOK|SIGNING|ENDPOINT/.test(k));
5791
6433
  const primary = primaryEnv ? env[primaryEnv] : void 0;
5792
6434
  const authHeaders = () => primary ? { authorization: `Bearer ${primary}` } : {};
6435
+ const issuedValues = Object.values(env).filter((v) => v.length >= 12);
6436
+ const appCredential = (value) => {
6437
+ const v = Array.isArray(value) ? value[0] : value;
6438
+ return v && issuedValues.some((i) => v === `Bearer ${i}`) ? v : void 0;
6439
+ };
5793
6440
  const fault = this.spec.fault;
5794
6441
  const matchesFault = (target) => !!fault && (target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path));
5795
- const apply = (actions, method, path, evidence) => {
6442
+ const apply = (actions, method, path, evidence, byWorld = false) => {
5796
6443
  const wrote = [];
5797
6444
  for (const a of actions) {
5798
6445
  const type = a.subject?.type, id = a.subject?.id;
5799
6446
  if (!type || !id) continue;
5800
6447
  if (type === "_world_event_delivery") {
5801
- 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"}`);
6448
+ const f = a.fields ?? {}, eventType = typeof f.body === "string" ? /"type":"([^"]+)"/.exec(f.body)?.[1] ?? "event" : "event";
6449
+ const key2 = `${service.name}:${id}`;
6450
+ if (f.delivery_state === "queued" && typeof f.url === "string" && typeof f.body === "string" && f.headers && typeof f.headers === "object" && !this.sentWebhooks.has(key2)) {
6451
+ this.sentWebhooks.add(key2);
6452
+ this.sendWebhook(service.name, f.url, f.body, f.headers, eventType);
6453
+ } else if (evidence && !this.sentWebhooks.has(key2)) this.record(service.name, "webhook", String(f.url ?? ""), `queued ${eventType} for ${f.url ?? "endpoint"}`);
5802
6454
  continue;
5803
6455
  }
5804
6456
  if (type.startsWith("_")) continue;
@@ -5812,7 +6464,7 @@ var init_http_world = __esm({
5812
6464
  } else if (at >= 0) rows2[at] = row;
5813
6465
  else rows2.push(row);
5814
6466
  if (!evidence) continue;
5815
- const byApp = a.actor?.kind === "agent";
6467
+ const byApp = a.actor?.kind === "agent" && !byWorld;
5816
6468
  this.record(service.name, byApp ? "write" : "twin", collection, `${method} ${path} \u2192 ${a.operation ?? type} ${id}${byApp ? "" : " (by the twin)"}`, row);
5817
6469
  if (byApp) wrote.push(collection);
5818
6470
  }
@@ -5834,146 +6486,258 @@ var init_http_world = __esm({
5834
6486
  chain = run3.then(() => void 0, () => void 0);
5835
6487
  return run3;
5836
6488
  };
5837
- const server = createServer3((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
5838
- const epoch = this.epoch;
5839
- const send = (status, headers, body) => {
5840
- if (!res.destroyed) {
5841
- res.writeHead(status, headers);
5842
- res.end(body);
5843
- }
5844
- };
5845
- const later = (ms, fn) => {
5846
- const timer = setTimeout(() => {
5847
- this.timers.delete(timer);
5848
- if (epoch === this.epoch) fn();
5849
- }, ms);
5850
- this.timers.add(timer);
5851
- };
5852
- const respond = (status, headers, body) => {
5853
- const ms = latencyMs();
5854
- if (ms <= 0) send(status, headers, body);
5855
- else later(ms, () => send(status, headers, body));
5856
- };
5857
- const json = (status, value) => respond(status, { "content-type": "application/json" }, Buffer.from(JSON.stringify(value)));
5858
- try {
5859
- const ours = req.headers.authorization === `Bearer ${token}` || req.headers["x-api-key"] === token || req.headers["x-agenttwin-token"] === token;
5860
- if (!ours) {
5861
- this.record(service.name, "auth-denied", req.url ?? "", "invalid test credential");
5862
- json(401, { error: "invalid_test_credential" });
5863
- return;
5864
- }
5865
- if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
5866
- json(429, { error: "world_capacity" });
5867
- return;
5868
- }
5869
- const url = new URL(req.url ?? "/", "http://localhost"), method = req.method ?? "GET", path = url.pathname;
5870
- const requestKey = req.headers["idempotency-key"];
5871
- if (fault && faultOrdinalsFor && (fault.type === "blackhole" || fault.type === "server-error") && matchesFault(path) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
5872
- this.faultActions++;
5873
- if (fault.type === "blackhole") {
5874
- this.record(service.name, "fault", fault.path, `blackhole: request dropped; nothing committed (${method})`);
6489
+ const server = createServer3((req, res) => {
6490
+ if (req.headers["x-agenttwin-probe"] === "1") {
6491
+ this.probes++;
6492
+ res.once("close", () => {
6493
+ this.probes--;
6494
+ });
6495
+ }
6496
+ return withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
6497
+ const epoch = this.epoch;
6498
+ const send = (status, headers, body) => {
6499
+ if (!res.destroyed) {
6500
+ res.writeHead(status, headers);
6501
+ res.end(body);
6502
+ }
6503
+ };
6504
+ const later = (ms, fn) => {
6505
+ const timer = setTimeout(() => {
6506
+ this.timers.delete(timer);
6507
+ if (epoch === this.epoch) fn();
6508
+ }, ms);
6509
+ this.timers.add(timer);
6510
+ };
6511
+ const respond = (status, headers, body) => {
6512
+ const ms = latencyMs();
6513
+ if (ms <= 0) send(status, headers, body);
6514
+ else later(ms, () => send(status, headers, body));
6515
+ };
6516
+ const json = (status, value) => respond(status, { "content-type": "application/json" }, Buffer.from(JSON.stringify(value)));
6517
+ try {
6518
+ const raw = req.socket.agenttwinRaw === true;
6519
+ const ours = raw || req.headers.authorization === `Bearer ${token}` || req.headers["x-api-key"] === token || req.headers["x-agenttwin-token"] === token;
6520
+ if (!ours) {
6521
+ this.record(service.name, "auth-denied", req.url ?? "", "invalid test credential");
6522
+ json(401, { error: "invalid_test_credential" });
6523
+ return;
6524
+ }
6525
+ if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
6526
+ json(429, { error: "world_capacity" });
6527
+ return;
6528
+ }
6529
+ const url = new URL(req.url ?? "/", "http://localhost"), method = req.method ?? "GET", path = url.pathname;
6530
+ if (path === "/_agenttwin/redeliver" && req.headers["x-agenttwin-token"] === token) {
6531
+ const last = this.lastEnvelope[service.name];
6532
+ if (!last) {
6533
+ json(404, { ok: false, error: "nothing_delivered" });
6534
+ return;
6535
+ }
6536
+ const attempt = Number(last.envelope.retry_attempt ?? 0) + 1;
6537
+ const again = { ...last.envelope, envelope_id: createHash6("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" };
6538
+ last.send(JSON.stringify(again));
6539
+ this.record(service.name, "twin", path, `redelivered ${String(last.envelope.type ?? "envelope")} (retry_attempt ${attempt}, as after a lost acknowledgment)`);
6540
+ json(200, { ok: true, retry_attempt: attempt });
6541
+ return;
6542
+ }
6543
+ const workspace = req.headers["x-agenttwin-actor"] === "workspace" && req.headers["x-agenttwin-token"] === token;
6544
+ const requestKey = req.headers["idempotency-key"];
6545
+ if (!workspace && fault && faultOrdinalsFor && (fault.type === "blackhole" || fault.type === "server-error") && matchesFault(path) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
6546
+ this.faultActions++;
6547
+ if (fault.type === "blackhole") {
6548
+ this.record(service.name, "fault", fault.path, `blackhole: request dropped; nothing committed (${method})`);
6549
+ this.keyed(requestKey);
6550
+ return;
6551
+ }
6552
+ const windowMs = fault.windowMs ?? 0;
6553
+ const delay = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
6554
+ this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay}ms; nothing committed (${method})`);
5875
6555
  this.keyed(requestKey);
6556
+ const fail = () => json(500, { error: { type: "api_error", message: "server_error fault" } });
6557
+ if (delay <= 0) fail();
6558
+ else later(delay, fail);
5876
6559
  return;
5877
6560
  }
5878
- const windowMs = fault.windowMs ?? 0;
5879
- const delay = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
5880
- this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay}ms; nothing committed (${method})`);
5881
- this.keyed(requestKey);
5882
- const fail = () => json(500, { error: { type: "api_error", message: "server_error fault" } });
5883
- if (delay <= 0) fail();
5884
- else later(delay, fail);
5885
- return;
5886
- }
5887
- const chunks = [];
5888
- let bytes = 0;
5889
- for await (const chunk of req) {
5890
- bytes += chunk.length;
5891
- if (bytes > 5 * 1024 * 1024) {
5892
- json(413, { error: "body_too_large" });
6561
+ const chunks = [];
6562
+ let bytes = 0;
6563
+ for await (const chunk of req) {
6564
+ bytes += chunk.length;
6565
+ if (bytes > 5 * 1024 * 1024) {
6566
+ json(413, { error: "body_too_large" });
6567
+ return;
6568
+ }
6569
+ chunks.push(Buffer.from(chunk));
6570
+ }
6571
+ const body = ["GET", "HEAD"].includes(method) ? void 0 : Buffer.concat(chunks);
6572
+ if (epoch !== this.epoch) {
6573
+ json(409, { error: "world_reset" });
5893
6574
  return;
5894
6575
  }
5895
- chunks.push(Buffer.from(chunk));
5896
- }
5897
- const body = ["GET", "HEAD"].includes(method) ? void 0 : Buffer.concat(chunks);
5898
- if (epoch !== this.epoch) {
5899
- json(409, { error: "world_reset" });
5900
- return;
5901
- }
5902
- let host = String(req.headers["x-agenttwin-original-host"] ?? baseHost);
5903
- if (name === "pinecone") {
5904
- const m = /^([a-z0-9-]+?)-[a-z0-9]+\.svc\.[a-z0-9.-]*pinecone\.io$/.exec(host);
5905
- const index = m && (data["/indexes"] ?? []).find((r) => r.name === m[1] && typeof r.host === "string");
5906
- if (index && index.host !== host) host = String(index.host);
5907
- }
5908
- const headers = new Headers();
5909
- 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);
5910
- if (headers.get("authorization") === `Bearer ${token}`) {
5911
- if (primary) headers.set("authorization", `Bearer ${primary}`);
5912
- else headers.delete("authorization");
5913
- }
5914
- if (headers.get("x-api-key") === token) {
5915
- if (primary) headers.set("x-api-key", primary);
5916
- else headers.delete("x-api-key");
5917
- }
5918
- const call = async () => {
5919
- const r = await twin(new Request(`https://${host}${req.url ?? "/"}`, { method, headers, ...body ? { body } : {} }));
5920
- return { status: r.status, headers: r.headers, bytes: Buffer.from(await r.arrayBuffer()), actions: log.drain() };
5921
- };
5922
- const first = await serialized(call);
5923
- if (epoch !== this.epoch) return;
5924
- const wrote = apply(first.actions, method, path, true);
5925
- let okFalse;
5926
- if (first.status < 300 && /json/.test(first.headers.get("content-type") ?? "")) try {
5927
- const parsed = JSON.parse(first.bytes.toString("utf8"));
5928
- if (parsed.ok === false) okFalse = [parsed.error, ...parsed.response_metadata?.messages ?? []].filter(Boolean).join(": ").slice(0, 240) || "ok: false";
5929
- } catch {
5930
- }
5931
- if (wrote.length) this.keyed(requestKey);
5932
- else if (meta.gapMessage && (first.status >= 400 || okFalse) && first.bytes.toString("utf8").includes(meta.gapMessage)) this.rejectUnsupported(service.name, method, path, `${name} twin does not model ${method} ${path}`);
5933
- else if (okFalse) this.record(service.name, "rejected", path, `${method} ${path} \u2192 ${first.status} ok:false: ${okFalse}`);
5934
- else if (first.status >= 400) {
5935
- let reason = "";
5936
- try {
6576
+ if (this.postgrest && path.startsWith("/rest/v1/")) {
6577
+ const r = await this.postgrest.handle({ method, url, headers: req.headers, body });
6578
+ if (method !== "GET" && method !== "HEAD") this.record(service.name, r.status < 400 ? "write" : "rejected", path, `${method} ${path} \u2192 ${r.status}${r.status >= 400 ? `: ${r.body.slice(0, 200)}` : ""}`);
6579
+ res.writeHead(r.status, r.headers);
6580
+ res.end(r.body);
6581
+ return;
6582
+ }
6583
+ let host = String(req.headers["x-agenttwin-original-host"] ?? (raw ? req.headers.host?.replace(/:\d+$/, "") : void 0) ?? baseHost);
6584
+ if (name === "pinecone") {
6585
+ const m = /^([a-z0-9-]+?)-[a-z0-9]+\.svc\.[a-z0-9.-]*pinecone\.io$/.exec(host);
6586
+ const index = m && (data["/indexes"] ?? []).find((r) => r.name === m[1] && typeof r.host === "string");
6587
+ if (index && index.host !== host) host = String(index.host);
6588
+ }
6589
+ const headers = new Headers();
6590
+ 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);
6591
+ const own = appCredential(req.headers["x-agenttwin-app-authorization"]);
6592
+ if (own) headers.set("authorization", own);
6593
+ else if (raw) {
6594
+ const given = headers.get("authorization");
6595
+ if (given && !appCredential(given) && /^Bearer /.test(given) && primary) headers.set("authorization", `Bearer ${primary}`);
6596
+ } else if (headers.get("authorization") === `Bearer ${token}`) {
6597
+ if (primary) headers.set("authorization", `Bearer ${primary}`);
6598
+ else headers.delete("authorization");
6599
+ }
6600
+ if (headers.get("x-api-key") === token) {
6601
+ if (primary) headers.set("x-api-key", primary);
6602
+ else headers.delete("x-api-key");
6603
+ }
6604
+ const call = async () => {
6605
+ const target2 = aliasRequest(name, host, req.url ?? "/");
6606
+ const model = compatibleModel(name, body);
6607
+ const r = await twin(new Request(`https://${target2.host}${target2.url}`, { method, headers, ...model.body ? { body: model.body } : {} }));
6608
+ return { status: r.status, headers: r.headers, bytes: model.restore(Buffer.from(await r.arrayBuffer())), actions: log.drain() };
6609
+ };
6610
+ if (workspace && method !== "GET") this.causing[service.name] = 1;
6611
+ const first = await serialized(call).finally(() => {
6612
+ if (workspace) this.causing[service.name] = 0;
6613
+ });
6614
+ if (epoch !== this.epoch) return;
6615
+ const recordedBefore = this.events.length;
6616
+ const wrote = apply(first.actions, method, path, true, workspace);
6617
+ if (workspace) {
6618
+ const out2 = {};
6619
+ first.headers.forEach((v, k) => {
6620
+ if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out2[k] = v;
6621
+ });
6622
+ send(first.status, out2, first.bytes);
6623
+ return;
6624
+ }
6625
+ let okFalse;
6626
+ if (first.status < 300 && /json/.test(first.headers.get("content-type") ?? "")) try {
5937
6627
  const parsed = JSON.parse(first.bytes.toString("utf8"));
5938
- const e = parsed.error ?? parsed;
5939
- reason = String(e.message ?? e.error_description ?? e.code ?? "").slice(0, 240);
6628
+ if (parsed.ok === false) okFalse = [parsed.error, ...parsed.response_metadata?.messages ?? []].filter(Boolean).join(": ").slice(0, 240) || "ok: false";
5940
6629
  } catch {
5941
- reason = first.bytes.toString("utf8").slice(0, 120);
5942
6630
  }
5943
- this.record(service.name, "rejected", path, `${method} ${path} \u2192 ${first.status}${reason ? `: ${reason}` : ""}`);
5944
- } else if (method === "GET") this.record(service.name, "read", path, `${first.status}`);
5945
- const target = wrote[0];
5946
- if (target && fault?.type === "duplicate-write" && fault.service === service.name && !requestKey && matchesFault(target) && faultOrdinalsFor?.includes(this.candidateIndex(faultKey))) {
5947
- const second = await serialized(call);
5948
- apply(second.actions, method, path, true);
5949
- this.faultActions++;
5950
- this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${target})`);
6631
+ if (wrote.length) this.keyedSince(recordedBefore, requestKey);
6632
+ else if (first.status === 501 || meta.gapMessage && (first.status >= 400 || okFalse) && first.bytes.toString("utf8").includes(meta.gapMessage)) this.rejectUnsupported(service.name, method, path, `${name} twin does not model ${method} ${path}`);
6633
+ else if (okFalse) this.record(service.name, "rejected", path, `${method} ${path} \u2192 ${first.status} ok:false: ${okFalse}`);
6634
+ else if (first.status >= 400) {
6635
+ let reason = "";
6636
+ try {
6637
+ const parsed = JSON.parse(first.bytes.toString("utf8"));
6638
+ const e = parsed.error ?? parsed;
6639
+ reason = String(e.message ?? e.error_description ?? e.code ?? "").slice(0, 240);
6640
+ } catch {
6641
+ reason = first.bytes.toString("utf8").slice(0, 120);
6642
+ }
6643
+ this.record(service.name, "rejected", path, `${method} ${path} \u2192 ${first.status}${reason ? `: ${reason}` : ""}`);
6644
+ } else if (method === "GET") this.record(service.name, "read", path, `${first.status}`);
6645
+ const target = wrote.find(matchesFault) ?? wrote[0];
6646
+ if (target && fault?.type === "duplicate-write" && fault.service === service.name && !requestKey && matchesFault(target) && faultOrdinalsFor?.includes(this.candidateIndex(faultKey))) {
6647
+ const second = await serialized(call);
6648
+ apply(second.actions, method, path, true);
6649
+ this.faultActions++;
6650
+ this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${target})`);
6651
+ }
6652
+ const out = {};
6653
+ first.headers.forEach((v, k) => {
6654
+ if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out[k] = v;
6655
+ });
6656
+ if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && matchesFault(target)) {
6657
+ this.fired = true;
6658
+ this.faultActions++;
6659
+ this.record(service.name, "fault", target, `write committed; response delayed ${fault.delayMs}ms`);
6660
+ this.keyed(requestKey);
6661
+ later(fault.delayMs, () => send(first.status, out, first.bytes));
6662
+ } else if (fault?.type === "slow-response" && faultOrdinalsFor && matchesFault(target ?? path) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
6663
+ this.faultActions++;
6664
+ this.record(service.name, "fault", target ?? path, `slow-response: ${target ? "write" : "request"} applied; response delayed ${fault.delayMs}ms`);
6665
+ this.keyed(requestKey);
6666
+ later(fault.delayMs, () => respond(first.status, out, first.bytes));
6667
+ } else respond(first.status, out, first.bytes);
6668
+ } catch {
6669
+ json(500, { error: "world_request_error" });
5951
6670
  }
5952
- const out = {};
5953
- first.headers.forEach((v, k) => {
5954
- if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out[k] = v;
5955
- });
5956
- if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && matchesFault(target)) {
5957
- this.fired = true;
5958
- this.faultActions++;
5959
- this.record(service.name, "fault", target, `write committed; response delayed ${fault.delayMs}ms`);
5960
- this.keyed(requestKey);
5961
- later(fault.delayMs, () => send(first.status, out, first.bytes));
5962
- } else if (fault?.type === "slow-response" && faultOrdinalsFor && matchesFault(target ?? path) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
5963
- this.faultActions++;
5964
- this.record(service.name, "fault", target ?? path, `slow-response: ${target ? "write" : "request"} applied; response delayed ${fault.delayMs}ms`);
5965
- this.keyed(requestKey);
5966
- later(fault.delayMs, () => respond(first.status, out, first.bytes));
5967
- } else respond(first.status, out, first.bytes);
5968
- } catch {
5969
- json(500, { error: "world_request_error" });
5970
- }
5971
- })));
6671
+ }));
6672
+ });
5972
6673
  server.requestTimeout = 1e4;
6674
+ const upgrade = twin.upgrade;
6675
+ if (upgrade) {
6676
+ const WebSocketServer = await packWebSocketServer(meta.generation);
6677
+ const toRequest = (req) => {
6678
+ const headers = new Headers();
6679
+ for (const [k, v] of Object.entries(req.headers)) if (typeof v === "string" && !/^(host|x-agenttwin-.*)$/i.test(k)) headers.set(k, v);
6680
+ const own = appCredential(req.headers["x-agenttwin-app-authorization"]);
6681
+ if (own) headers.set("authorization", own);
6682
+ else if (headers.get("authorization") === `Bearer ${token}`) headers.delete("authorization");
6683
+ const raw = req.socket.agenttwinRaw === true;
6684
+ return new Request(`https://${String(req.headers["x-agenttwin-original-host"] ?? (raw ? req.headers.host?.replace(/:\d+$/, "") : void 0) ?? baseHost)}${req.url ?? "/"}`, { headers });
6685
+ };
6686
+ const wss = new WebSocketServer({ noServer: true, handleProtocols: (_set, req) => upgrade.protocol?.(toRequest(req)) ?? false });
6687
+ this.socketServers.push(wss);
6688
+ server.on("upgrade", (req, socket, head) => {
6689
+ const ours = req.socket.agenttwinRaw === true || req.headers.authorization === `Bearer ${token}` || req.headers["x-agenttwin-token"] === token;
6690
+ const path = new URL(req.url ?? "/", "http://localhost").pathname;
6691
+ const request = toRequest(req);
6692
+ if (!ours || !upgrade.accepts(request)) {
6693
+ this.record(service.name, ours ? "rejected" : "auth-denied", path, ours ? `WebSocket ${path} \u2192 no socket endpoint` : "invalid test credential");
6694
+ socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
6695
+ return;
6696
+ }
6697
+ const epoch = this.epoch;
6698
+ wss.handleUpgrade(req, socket, head, (ws) => {
6699
+ const send = ws.send.bind(ws);
6700
+ ws.send = (data2, ...rest) => {
6701
+ try {
6702
+ const parsed = JSON.parse(String(data2));
6703
+ if (typeof parsed.envelope_id === "string" && this.causing[service.name] === 1) {
6704
+ this.causing[service.name] = 2;
6705
+ this.lastEnvelope[service.name] = { send, envelope: parsed };
6706
+ }
6707
+ } catch {
6708
+ }
6709
+ send(data2, ...rest);
6710
+ };
6711
+ const inWorld = (fn) => withTwinClock(this.twinClock, () => serialized(async () => fn()));
6712
+ ws.on("message", (data2, binary) => {
6713
+ if (epoch !== this.epoch) return;
6714
+ const bytes = Array.isArray(data2) ? Buffer.concat(data2) : Buffer.from(data2);
6715
+ Promise.resolve().then(() => withTwinClock(this.twinClock, () => upgrade.message(ws, binary ? new Uint8Array(bytes) : bytes.toString("utf8")))).then(() => apply(log.drain(), "WS", path, true), () => ws.close(1011, "handler failed"));
6716
+ });
6717
+ ws.on("close", () => {
6718
+ void inWorld(() => upgrade.close(ws)).catch(() => {
6719
+ });
6720
+ });
6721
+ ws.on("error", () => ws.close());
6722
+ this.record(service.name, "read", path, `WebSocket ${path} opened`);
6723
+ void inWorld(() => upgrade.open(ws, request)).then(() => apply(log.drain(), "WS", path, true), () => ws.close(1011, "handler failed"));
6724
+ });
6725
+ });
6726
+ }
5973
6727
  await new Promise((resolve8, reject) => {
5974
6728
  server.once("error", reject);
5975
6729
  server.listen(0, "127.0.0.1", resolve8);
5976
6730
  });
6731
+ const rawServer = createNetServer((socket) => {
6732
+ socket.agenttwinRaw = true;
6733
+ server.emit("connection", socket);
6734
+ });
6735
+ await new Promise((resolve8, reject) => {
6736
+ rawServer.once("error", reject);
6737
+ rawServer.listen(0, "127.0.0.1", resolve8);
6738
+ });
6739
+ this.rawServers.push(rawServer);
6740
+ this.packTcp[service.name] = rawServer.address().port;
5977
6741
  return server;
5978
6742
  }
5979
6743
  assertions() {
@@ -6009,9 +6773,16 @@ var init_http_world = __esm({
6009
6773
  return this.snapshot();
6010
6774
  }
6011
6775
  async close() {
6776
+ await this.postgrest?.close();
6777
+ this.postgrest = void 0;
6012
6778
  this.epoch++;
6013
6779
  for (const timer of this.timers) clearTimeout(timer);
6014
6780
  this.timers.clear();
6781
+ for (const wss of this.socketServers.splice(0)) {
6782
+ for (const ws of wss.clients) ws.terminate();
6783
+ wss.close();
6784
+ }
6785
+ for (const raw of this.rawServers.splice(0)) raw.close();
6015
6786
  await Promise.all(this.servers.map((server) => new Promise((resolve8) => {
6016
6787
  server.close(() => resolve8());
6017
6788
  server.closeAllConnections();
@@ -6023,6 +6794,32 @@ var init_http_world = __esm({
6023
6794
  }
6024
6795
  });
6025
6796
 
6797
+ // src/runtime/node-options.ts
6798
+ import { realpath as realpath2, writeFile as writeFile3 } from "fs/promises";
6799
+ async function singlePreload(options, hook) {
6800
+ const preloads = [], rest = [];
6801
+ const tokens = options.match(/(?:[^\s"]+|"[^"]*")+/g) ?? [];
6802
+ for (let i = 0; i < tokens.length; i++) {
6803
+ const t = tokens[i], unquote = (v) => v.replace(/^"|"$/g, "");
6804
+ if (t === "--require" || t === "-r") {
6805
+ if (tokens[i + 1]) preloads.push(unquote(tokens[++i]));
6806
+ } else if (t.startsWith("--require=")) preloads.push(unquote(t.slice(10)));
6807
+ else rest.push(t);
6808
+ }
6809
+ const real = await realpath2(hook).catch(() => hook);
6810
+ preloads.push(real);
6811
+ const combined = `${real}.all.cjs`;
6812
+ await writeFile3(combined, preloads.map((p) => `require(${JSON.stringify(p)});`).join("\n") + "\n", { mode: 384 });
6813
+ return [...rest, `--require ${requireArg(combined)}`].join(" ");
6814
+ }
6815
+ var requireArg;
6816
+ var init_node_options = __esm({
6817
+ "src/runtime/node-options.ts"() {
6818
+ "use strict";
6819
+ requireArg = (path) => /[\s"']/.test(path) ? JSON.stringify(path) : path;
6820
+ }
6821
+ });
6822
+
6026
6823
  // src/runtime/application-process.ts
6027
6824
  import { execFile as execFile2 } from "child_process";
6028
6825
  import { promisify as promisify2 } from "util";
@@ -6226,7 +7023,7 @@ var init_browser_process_windows = __esm({
6226
7023
  });
6227
7024
 
6228
7025
  // src/runtime/browser-process.ts
6229
- import { mkdtemp as mkdtemp4, writeFile as writeFile3, readFile, rm as rm4 } from "fs/promises";
7026
+ import { mkdtemp as mkdtemp4, writeFile as writeFile4, readFile, rm as rm4 } from "fs/promises";
6230
7027
  import { tmpdir as tmpdir4 } from "os";
6231
7028
  import { join as join7 } from "path";
6232
7029
  import { execFile as execFile4 } from "child_process";
@@ -6236,7 +7033,7 @@ async function ownBrowserProcess(executable) {
6236
7033
  });
6237
7034
  const root = await mkdtemp4(join7(tmpdir4(), "agenttwin-browser-owner-"));
6238
7035
  const pidFile = join7(root, "pid"), launcher = join7(root, "launch");
6239
- await writeFile3(launcher, `#!/bin/sh
7036
+ await writeFile4(launcher, `#!/bin/sh
6240
7037
  echo $$ > ${quote(pidFile)}
6241
7038
  exec ${quote(executable)} "$@"
6242
7039
  `, { mode: 448 });
@@ -6736,9 +7533,11 @@ var init_contracts = __esm({
6736
7533
  { 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"] },
6737
7534
  { method: "GET", endpoint: "/v1/refunds[/<id>]", effect: "retrieve or list refunds", parameters: ["limit", "starting_after", "charge", "payment_intent"], errors: ["404 resource_missing"] },
6738
7535
  { method: "GET", endpoint: "/v1/charges[/<id>]", effect: "retrieve or list charges", parameters: ["limit"], errors: ["404 resource_missing"] },
6739
- { method: "GET", endpoint: "/v1/events[/<id>]", effect: "retrieve or list recorded charge.refunded events", parameters: ["limit", "type"], errors: ["404 resource_missing"] }
7536
+ { method: "GET", endpoint: "/v1/events[/<id>]", effect: "retrieve or list recorded charge.refunded events", parameters: ["limit", "type"], errors: ["404 resource_missing"] },
7537
+ { method: "GET", endpoint: "/v1/subscription_items/<id>", effect: "retrieve a seeded subscription item", parameters: [], errors: ["404 resource_missing"] },
7538
+ { 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"] }
6740
7539
  ],
6741
- 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"]
7540
+ 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"]
6742
7541
  },
6743
7542
  slack: {
6744
7543
  version: "1.0.0",
@@ -6748,7 +7547,7 @@ var init_contracts = __esm({
6748
7547
  { method: "GET|POST", endpoint: "/api/conversations.history", effect: "read /messages", parameters: ["channel"], errors: ["channel_not_found"] },
6749
7548
  { method: "GET|POST", endpoint: "/api/conversations.list", effect: "read /channels", parameters: [], errors: [] }
6750
7549
  ],
6751
- 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"]
7550
+ 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"]
6752
7551
  },
6753
7552
  github: {
6754
7553
  version: "1.0.0",
@@ -6847,6 +7646,8 @@ var init_contracts = __esm({
6847
7646
  { method: "GET", endpoint: "/gmail/v1/users/me/messages", effect: "list message ids with a snippet q filter", parameters: ["q"], errors: ["400 validation"] },
6848
7647
  { method: "GET", endpoint: "/gmail/v1/users/me/messages/<id>", effect: "retrieve message", parameters: [], errors: ["404 NOT_FOUND"] },
6849
7648
  { method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] },
7649
+ { 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"] },
7650
+ { 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"] },
6850
7651
  { 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"] },
6851
7652
  { 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"] },
6852
7653
  { 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"] },
@@ -6864,7 +7665,7 @@ var init_contracts = __esm({
6864
7665
  { 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"] },
6865
7666
  { 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"] }
6866
7667
  ],
6867
- 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"]
7668
+ 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"]
6868
7669
  },
6869
7670
  "upstash-redis": {
6870
7671
  version: "1.0.0",
@@ -6963,7 +7764,7 @@ var init_contracts = __esm({
6963
7764
  });
6964
7765
 
6965
7766
  // src/runtime/cost-model.ts
6966
- import { readFile as readFile2, writeFile as writeFile4 } from "fs/promises";
7767
+ import { readFile as readFile2, writeFile as writeFile5 } from "fs/promises";
6967
7768
  import { join as join9 } from "path";
6968
7769
  var init_cost_model = __esm({
6969
7770
  "src/runtime/cost-model.ts"() {
@@ -6982,7 +7783,7 @@ var init_run_summary = __esm({
6982
7783
  });
6983
7784
 
6984
7785
  // src/runtime/generic-calls.ts
6985
- import { createHash as createHash6 } from "crypto";
7786
+ import { createHash as createHash7 } from "crypto";
6986
7787
  function canonical2(value) {
6987
7788
  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);
6988
7789
  }
@@ -7268,7 +8069,7 @@ var init_generic_calls = __esm({
7268
8069
  VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
7269
8070
  KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
7270
8071
  KEY_FIELDS = /^(idempotency_?key|ClientToken|ClientRequestToken|MessageDeduplicationId|client_token|request_id)$/i;
7271
- digest = (value) => `sha256:${createHash6("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
8072
+ digest = (value) => `sha256:${createHash7("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
7272
8073
  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;
7273
8074
  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);
7274
8075
  outcomeOf = (status) => status === void 0 ? "ok" : status === 401 || status === 403 ? "unauthorized" : status === 429 ? "rate-limited" : status >= 500 ? "server-error" : status >= 400 ? "client-error" : "ok";
@@ -7485,7 +8286,7 @@ var init_default_checks = __esm({
7485
8286
  };
7486
8287
  stripeNoDuplicatePayment = {
7487
8288
  id: "stripe.no-duplicate-payment",
7488
- title: "No duplicate charges or customers for one request",
8289
+ title: "No duplicate charges, customers or subscriptions for one request",
7489
8290
  path: "/v1/payment_intents",
7490
8291
  coversDuplicates: true,
7491
8292
  expected: "one payment intent per amount/currency/customer/payment method and one customer per email",
@@ -7504,6 +8305,19 @@ var init_default_checks = __esm({
7504
8305
  evidence: writeSequences(ctx, s, group.map((r) => r.id))
7505
8306
  });
7506
8307
  }
8308
+ const subscriptions = addedRows(rowsOf(ctx.initialState, s, "/v1/subscriptions"), rowsOf(ctx.finalState, s, "/v1/subscriptions")).filter((r) => !["canceled", "incomplete_expired"].includes(String(r.status)));
8309
+ 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) }));
8310
+ 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)) {
8311
+ const items = itemsOf(group[0]), currency = String(items[0]?.price.currency ?? group[0].currency ?? "usd");
8312
+ const perPeriod = items.reduce((n, i) => n + (typeof i.price.unit_amount === "number" ? i.price.unit_amount * i.quantity : 0), 0);
8313
+ out.push({
8314
+ path: "/v1/subscriptions",
8315
+ actual: { subscriptions: group.map((r) => r.id), customer: group[0].customer },
8316
+ finding: `Your agent subscribed ${String(group[0].customer)} ${times2(group.length)} to the same plan${faultPhrase(ctx)}`,
8317
+ 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 },
8318
+ evidence: writeSequences(ctx, s, group.map((r) => r.id))
8319
+ });
8320
+ }
7507
8321
  const customers = addedRows(rowsOf(ctx.initialState, s, "/v1/customers"), rowsOf(ctx.finalState, s, "/v1/customers"));
7508
8322
  for (const group of groups(customers, (r) => typeof r.email === "string" && r.email ? r.email.toLowerCase() : void 0))
7509
8323
  out.push({
@@ -7630,14 +8444,14 @@ var init_default_checks = __esm({
7630
8444
  };
7631
8445
  VENDOR_COVERS = { "retry-without-key": /\.idempotent-retries$/, "announce-after-failed-write": /\.announce-after-success$/ };
7632
8446
  DEFAULT_CHECKS["*"].push(...genericWorldChecks((adapter, rule) => !!VENDOR_COVERS[rule] && registryFor(adapter).some((c) => VENDOR_COVERS[rule].test(c.id))));
7633
- registryFor = (adapter) => DEFAULT_CHECKS[adapter ?? "json-collection"] ?? [];
8447
+ registryFor = (adapter) => DEFAULT_CHECKS[adapter ?? "json-collection"] ?? (adapter?.startsWith("pack:") ? DEFAULT_CHECKS[adapter.slice(5)] : void 0) ?? [];
7634
8448
  refOf = (s) => typeof s === "string" ? { name: s, adapter: s } : s;
7635
8449
  }
7636
8450
  });
7637
8451
 
7638
8452
  // src/runtime/twin-proxy.ts
7639
8453
  import { execFile as execFile5 } from "child_process";
7640
- import { mkdtemp as mkdtemp6, readFile as readFile3, rm as rm6, writeFile as writeFile5 } from "fs/promises";
8454
+ import { mkdtemp as mkdtemp6, readFile as readFile3, rm as rm6, writeFile as writeFile6 } from "fs/promises";
7641
8455
  import { createServer as createServer4, request as httpRequest } from "http";
7642
8456
  import { tmpdir as tmpdir6 } from "os";
7643
8457
  import { join as join10 } from "path";
@@ -7697,7 +8511,7 @@ async function runAuthority(dir) {
7697
8511
  if (!ctx) {
7698
8512
  ctx = (async () => {
7699
8513
  const base = join10(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
7700
- await writeFile5(base + ".ext", `basicConstraints=critical,CA:FALSE
8514
+ await writeFile6(base + ".ext", `basicConstraints=critical,CA:FALSE
7701
8515
  keyUsage=critical,digitalSignature
7702
8516
  extendedKeyUsage=serverAuth
7703
8517
  subjectAltName=DNS:${host}
@@ -7736,6 +8550,7 @@ async function startTwinProxy(routes2) {
7736
8550
  const headers = {};
7737
8551
  const strip = route.auth === "passthrough" ? ["host", "proxy-connection", "proxy-authorization"] : SECRET;
7738
8552
  for (const [k, v] of Object.entries(req.headers)) if (v !== void 0 && !strip.includes(k)) headers[k] = v;
8553
+ if (route.appCredential && typeof req.headers.authorization === "string" && /^Bearer \S{12,}$/.test(req.headers.authorization)) headers["x-agenttwin-app-authorization"] = req.headers.authorization;
7739
8554
  if (route.auth === "passthrough") headers["x-agenttwin-token"] = route.token;
7740
8555
  else if (route.auth === "x-api-key") headers["x-api-key"] = route.token;
7741
8556
  else headers.authorization = `Bearer ${route.token}`;
@@ -7831,7 +8646,7 @@ var init_twin_proxy = __esm({
7831
8646
  });
7832
8647
 
7833
8648
  // src/runtime/twin-routing.ts
7834
- import { mkdtemp as mkdtemp7, readFile as readFile4, rm as rm7, writeFile as writeFile6 } from "fs/promises";
8649
+ import { mkdtemp as mkdtemp7, readFile as readFile4, rm as rm7, writeFile as writeFile7 } from "fs/promises";
7835
8650
  import { tmpdir as tmpdir7 } from "os";
7836
8651
  import { join as join11 } from "path";
7837
8652
  function twinRoutes(services, world, models) {
@@ -7840,10 +8655,11 @@ function twinRoutes(services, world, models) {
7840
8655
  const adapter = service.adapter ?? "", credential = world.credentials[service.name];
7841
8656
  if (credential && isPackAdapter(adapter)) {
7842
8657
  const record3 = packRecord(adapter.slice(PACK_PREFIX.length));
7843
- const auth = record3.credentialDoor ? "bearer" : "passthrough";
8658
+ const issuesKey = !!record3.credentialDoor && Object.values(record3.credentialDoor.fill ?? {}).some((field) => !String(field).startsWith("file:"));
8659
+ const auth = issuesKey ? "bearer" : "passthrough";
7844
8660
  for (const h of record3.hosts) {
7845
8661
  const host = h.host ?? `pattern:${h.hostPattern}`;
7846
- 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 });
8662
+ 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 } : {} });
7847
8663
  }
7848
8664
  continue;
7849
8665
  }
@@ -7857,6 +8673,7 @@ var PROVIDER_HOSTS, TWIN_PRELOAD;
7857
8673
  var init_twin_routing = __esm({
7858
8674
  "src/runtime/twin-routing.ts"() {
7859
8675
  "use strict";
8676
+ init_node_options();
7860
8677
  init_packs();
7861
8678
  PROVIDER_HOSTS = {
7862
8679
  // OpenAI-compatible APIs answer in the same format, so they are served by the OpenAI twin (with its scripted tool calls).
@@ -7911,9 +8728,13 @@ if(originalFetch)globalThis.fetch=async function(input,init){
7911
8728
  if(!r)throw blocked('fetch',url.hostname,url.port||(url.protocol==='https:'?443:80),method);
7912
8729
  if(process.env.AGENTTWIN_DEBUG_ROUTES)console.error('route-match '+url.hostname+' auth='+r.auth+' service='+r.service);
7913
8730
  const request=new Request(input,init),headers=new Headers(request.headers);
8731
+ {const own=headers.get('authorization');if(r.appCredential&&own&&/^Bearer \S{12,}$/.test(own))headers.set('x-agenttwin-app-authorization',own);}
7914
8732
  for(const name of removed(r))headers.delete(name);const [name,value]=credential(r);headers.set(name,value);
7915
8733
  headers.set('x-agenttwin-original-host',url.hostname);const location=source();if(location)headers.set('x-agenttwin-source',location);
7916
- return originalFetch(new Request(r.target+rewrite(r,url.pathname)+url.search,request),{headers,redirect:'manual'});
8734
+ // Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch (Upstash's
8735
+ // client sets keepalive on every call).
8736
+ const body=request.body===null?undefined:Buffer.from(await request.arrayBuffer());
8737
+ return originalFetch(r.target+rewrite(r,url.pathname)+url.search,{method:request.method,headers,...(body===undefined?{}:{body}),redirect:'manual',signal:request.signal});
7917
8738
  };
7918
8739
  const originalHttpRequest=http.request;
7919
8740
  for(const [mod,scheme] of [[http,'http'],[https,'https']]){
@@ -7932,6 +8753,8 @@ for(const [mod,scheme] of [[http,'http'],[https,'https']]){
7932
8753
  const target=new URL(r.target),headers={};
7933
8754
  const given=options.headers||{};
7934
8755
  for(const [k,v] of Array.isArray(given)?[]:Object.entries(given))if(!removed(r).includes(k.toLowerCase()))headers[k]=v;
8756
+ // The app's own credential travels beside the run token: a pack host keeps it when the twin issued it (an app-level token).
8757
+ 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;}
7935
8758
  const [name,value]=credential(r);headers[name]=value;headers.host=target.host;headers['x-agenttwin-original-host']=host;
7936
8759
  const location=source();if(location)headers['x-agenttwin-source']=location;
7937
8760
  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;
@@ -8012,6 +8835,36 @@ function sqlTables(sql) {
8012
8835
  }
8013
8836
  return [...out];
8014
8837
  }
8838
+ function bindValues(body) {
8839
+ try {
8840
+ let at = body.indexOf(0) + 1;
8841
+ at = body.indexOf(0, at) + 1;
8842
+ const formats = body.readInt16BE(at);
8843
+ at += 2;
8844
+ const codes = [];
8845
+ for (let i = 0; i < formats; i++) {
8846
+ codes.push(body.readInt16BE(at));
8847
+ at += 2;
8848
+ }
8849
+ const count = body.readInt16BE(at);
8850
+ at += 2;
8851
+ const values = [];
8852
+ for (let i = 0; i < count; i++) {
8853
+ const len = body.readInt32BE(at);
8854
+ at += 4;
8855
+ if (len < 0) {
8856
+ values.push(null);
8857
+ continue;
8858
+ }
8859
+ const binary = (codes.length === 1 ? codes[0] : codes[i] ?? 0) === 1;
8860
+ values.push(binary ? null : body.toString("utf8", at, at + len));
8861
+ at += len;
8862
+ }
8863
+ return values;
8864
+ } catch {
8865
+ return [];
8866
+ }
8867
+ }
8015
8868
  async function startPostgresEngine(options = {}) {
8016
8869
  const started = Date.now();
8017
8870
  let PGlite;
@@ -8079,7 +8932,7 @@ async function startPostgresEngine(options = {}) {
8079
8932
  if (name) {
8080
8933
  conn.names.set(name, sql);
8081
8934
  conn.statements.add(ns(name));
8082
- }
8935
+ } else conn.unnamed = sql;
8083
8936
  return { body: Buffer.concat([cstr(ns(name)), body.subarray(end + 1)]), sql };
8084
8937
  }
8085
8938
  if (type === "B") {
@@ -8134,7 +8987,13 @@ async function startPostgresEngine(options = {}) {
8134
8987
  for (const m of prepared) outputs.push(await raw(msg(m.type, m.body)));
8135
8988
  const out = Buffer.concat(outputs), { tags, status, failed } = scan(out);
8136
8989
  for (const t of writeTables) conn.txnTables.add(t);
8137
- if (sqls.length && !writes.length && tables.length) record2(events, { engine: "postgres", operation: "read", resource: tables.join(","), detail: tags.join("; ").slice(0, 200) });
8990
+ const binds = batch.filter((m) => m.type === "B").map((m) => {
8991
+ const pEnd = m.body.indexOf(0), sEnd = m.body.indexOf(0, pEnd + 1), stmt = m.body.toString("utf8", pEnd + 1, sEnd);
8992
+ return { sql: stmt ? conn.names.get(stmt) : conn.unnamed, params: bindValues(m.body) };
8993
+ });
8994
+ const readSql = sqls.length ? sqls : binds.flatMap((b) => b.sql && !isWriteSql(b.sql) ? [b.sql] : []);
8995
+ const readTables2 = [...new Set(readSql.flatMap(sqlTables))];
8996
+ if (readSql.length && !writes.length && readTables2.length) record2(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)) } });
8138
8997
  owner = status === "I" ? null : conn;
8139
8998
  let committed = [];
8140
8999
  if (status === "I") {
@@ -8328,7 +9187,9 @@ async function startPostgresEngine(options = {}) {
8328
9187
  }
8329
9188
  };
8330
9189
  const seed = async (data) => direct(async () => {
8331
- if (data.sql) await db.exec(data.sql);
9190
+ if (data.sql) {
9191
+ for (const part of data.sql.split(/^(?=-- Schema source: )/m)) if (part.trim()) await db.exec(part);
9192
+ }
8332
9193
  for (const [table2, rows2] of Object.entries(data.tables ?? {})) {
8333
9194
  for (const row of rows2) {
8334
9195
  const fields = Object.keys(row);
@@ -8620,13 +9481,13 @@ var init_server_steps = __esm({
8620
9481
 
8621
9482
  // src/runtime/local.ts
8622
9483
  import { spawn as spawn2 } from "child_process";
8623
- import { realpath as realpath2 } from "fs/promises";
9484
+ import { realpath as realpath3 } from "fs/promises";
8624
9485
  import { dirname as dirname2, resolve as resolve3 } from "path";
8625
9486
  async function sourceRoot(app, spec) {
8626
- const real = await realpath2(app);
9487
+ const real = await realpath3(app);
8627
9488
  if (!spec.directory) return real;
8628
9489
  for (let candidate = real; ; candidate = dirname2(candidate)) {
8629
- if (await realpath2(resolve3(candidate, spec.directory)).then((p) => p === real, () => false)) return candidate;
9490
+ if (await realpath3(resolve3(candidate, spec.directory)).then((p) => p === real, () => false)) return candidate;
8630
9491
  if (dirname2(candidate) === candidate) return real;
8631
9492
  }
8632
9493
  }
@@ -8645,10 +9506,11 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
8645
9506
  }
8646
9507
  engines = await startLocalEngines(filesDir, spec);
8647
9508
  Object.assign(env, engines.env);
9509
+ if (engines.env.DATABASE_URL) world.attachDatabase(engines.env.DATABASE_URL);
8648
9510
  let stdout = "", stderr = "", timedOut = false;
8649
9511
  const node = /(^|\/)node(\.exe)?$/.test(spec.command[0]);
8650
9512
  const hook = await createRequestSourceHook(await sourceRoot(app, spec), spec, credentials);
8651
- if (node) env.NODE_OPTIONS = [extraEnv.NODE_OPTIONS, `--require ${JSON.stringify(hook.path)}`].filter(Boolean).join(" ");
9513
+ if (node) env.NODE_OPTIONS = await singlePreload(extraEnv.NODE_OPTIONS ?? "", hook.path);
8652
9514
  let proxy;
8653
9515
  if (!node) {
8654
9516
  const configured = extraEnv.AGENTTWIN_ROUTES ? JSON.parse(extraEnv.AGENTTWIN_ROUTES).routes : void 0;
@@ -8771,6 +9633,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
8771
9633
  var init_local = __esm({
8772
9634
  "src/runtime/local.ts"() {
8773
9635
  "use strict";
9636
+ init_node_options();
8774
9637
  init_application_process();
8775
9638
  init_browser_process();
8776
9639
  init_twin_clock();
@@ -8789,8 +9652,8 @@ var init_local = __esm({
8789
9652
  });
8790
9653
 
8791
9654
  // src/runtime/scenarios.ts
8792
- import { createHash as createHash7 } from "crypto";
8793
- import { mkdir as mkdir3, readFile as readFile6, readdir, writeFile as writeFile7 } from "fs/promises";
9655
+ import { createHash as createHash8 } from "crypto";
9656
+ import { mkdir as mkdir3, readFile as readFile6, readdir, writeFile as writeFile8 } from "fs/promises";
8794
9657
  import { join as join13 } from "path";
8795
9658
  import { isDeepStrictEqual as isDeepStrictEqual4 } from "util";
8796
9659
  function parseScenario(value) {
@@ -8850,7 +9713,7 @@ var init_scenarios = __esm({
8850
9713
  identifier = /^[a-z][a-z0-9_]{0,39}$/;
8851
9714
  object3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
8852
9715
  sort = (v) => Array.isArray(v) ? v.map(sort) : object3(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sort(v[k])])) : v;
8853
- scenarioDigest = (scenario) => createHash7("sha256").update(JSON.stringify(sort(scenario))).digest("hex");
9716
+ scenarioDigest = (scenario) => createHash8("sha256").update(JSON.stringify(sort(scenario))).digest("hex");
8854
9717
  }
8855
9718
  });
8856
9719
 
@@ -8901,7 +9764,7 @@ var init_offline = __esm({
8901
9764
  // src/runtime/credentials.ts
8902
9765
  import { homedir } from "os";
8903
9766
  import { join as join15 } from "path";
8904
- import { readFile as readFile7, mkdir as mkdir4, writeFile as writeFile8, chmod as chmod2, rm as rm9 } from "fs/promises";
9767
+ import { readFile as readFile7, mkdir as mkdir4, writeFile as writeFile9, chmod as chmod2, rm as rm9 } from "fs/promises";
8905
9768
  var init_credentials = __esm({
8906
9769
  "src/runtime/credentials.ts"() {
8907
9770
  "use strict";
@@ -8959,7 +9822,7 @@ var init_stdio_fetch = __esm({
8959
9822
  // src/runtime/docker.ts
8960
9823
  import { execFile as execFile8, spawn as spawn4 } from "child_process";
8961
9824
  import { promisify as promisify8 } from "util";
8962
- import { chmod as chmod3, copyFile as copyFile2, mkdir as mkdir5, mkdtemp as mkdtemp8, readFile as readFile9, rm as rm10, writeFile as writeFile9 } from "fs/promises";
9825
+ import { chmod as chmod3, copyFile as copyFile2, mkdir as mkdir5, mkdtemp as mkdtemp8, readFile as readFile9, rm as rm10, writeFile as writeFile10 } from "fs/promises";
8963
9826
  import { tmpdir as tmpdir8 } from "os";
8964
9827
  import { join as join17 } from "path";
8965
9828
  import { randomUUID as randomUUID4 } from "crypto";
@@ -9024,7 +9887,7 @@ var init_hosted_packs = __esm({
9024
9887
  });
9025
9888
 
9026
9889
  // src/runtime/e2b.ts
9027
- import { createRequire } from "module";
9890
+ import { createRequire as createRequire3 } from "module";
9028
9891
  import { readFile as readFile11 } from "fs/promises";
9029
9892
  import { randomBytes as randomBytes3 } from "crypto";
9030
9893
  import { homedir as homedir2 } from "os";
@@ -9040,8 +9903,8 @@ var init_e2b = __esm({
9040
9903
  });
9041
9904
 
9042
9905
  // src/runtime/matrix.ts
9043
- import { createHash as createHash8 } from "crypto";
9044
- import { mkdir as mkdir6, readFile as readFile12, writeFile as writeFile10 } from "fs/promises";
9906
+ import { createHash as createHash9 } from "crypto";
9907
+ import { mkdir as mkdir6, readFile as readFile12, writeFile as writeFile11 } from "fs/promises";
9045
9908
  import { join as join20, relative, resolve as resolve4 } from "path";
9046
9909
  var init_matrix = __esm({
9047
9910
  "src/runtime/matrix.ts"() {
@@ -9053,8 +9916,8 @@ var init_matrix = __esm({
9053
9916
  });
9054
9917
 
9055
9918
  // src/runtime/source-build.ts
9056
- import { createHash as createHash9 } from "crypto";
9057
- import { lstat, readFile as readFile13, realpath as realpath3 } from "fs/promises";
9919
+ import { createHash as createHash10 } from "crypto";
9920
+ import { lstat, readFile as readFile13, realpath as realpath4 } from "fs/promises";
9058
9921
  import { isAbsolute as isAbsolute2, join as join21, relative as relative2, resolve as resolve5, sep } from "path";
9059
9922
  import { isDeepStrictEqual as isDeepStrictEqual6 } from "util";
9060
9923
  var init_source_build = __esm({
@@ -9065,17 +9928,17 @@ var init_source_build = __esm({
9065
9928
  });
9066
9929
 
9067
9930
  // src/commands/run.ts
9068
- import { mkdtemp as mkdtemp9, mkdir as mkdir7, readFile as readFile14, writeFile as writeFile11, realpath as realpath4, lstat as lstat2, rm as rm11 } from "fs/promises";
9931
+ import { mkdtemp as mkdtemp9, mkdir as mkdir7, readFile as readFile14, writeFile as writeFile12, realpath as realpath5, lstat as lstat2, rm as rm11 } from "fs/promises";
9069
9932
  import { tmpdir as tmpdir9 } from "os";
9070
9933
  import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join22, relative as relative3, resolve as resolve6, sep as sep2 } from "path";
9071
- import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
9934
+ import { createHash as createHash11, randomUUID as randomUUID5 } from "crypto";
9072
9935
  async function stageApplication(root, files, destination) {
9073
- const canonicalRoot = await realpath4(root);
9936
+ const canonicalRoot = await realpath5(root);
9074
9937
  const digests = {};
9075
9938
  let bytes = 0;
9076
9939
  for (const file of files) {
9077
9940
  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 });
9078
- const source = await realpath4(resolve6(canonicalRoot, file));
9941
+ const source = await realpath5(resolve6(canonicalRoot, file));
9079
9942
  const rel = relative3(canonicalRoot, source);
9080
9943
  if (rel.startsWith(`..${sep2}`) || rel === ".." || isAbsolute3(rel) || source !== resolve6(canonicalRoot, file) || !(await lstat2(source)).isFile()) throw new CliError(`Files must be regular files within the project, without symlinks: ${file}`, { code: EXIT.USAGE });
9081
9944
  const contents = await readFile14(source);
@@ -9083,8 +9946,8 @@ async function stageApplication(root, files, destination) {
9083
9946
  if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
9084
9947
  const target = join22(destination, file);
9085
9948
  await mkdir7(dirname4(target), { recursive: true });
9086
- await writeFile11(target, contents, { mode: 420 });
9087
- digests[file] = createHash10("sha256").update(contents).digest("hex");
9949
+ await writeFile12(target, contents, { mode: 420 });
9950
+ digests[file] = createHash11("sha256").update(contents).digest("hex");
9088
9951
  }
9089
9952
  return digests;
9090
9953
  }
@@ -9117,21 +9980,21 @@ init_contracts();
9117
9980
  init_run();
9118
9981
  init_git();
9119
9982
  import { createServer as createServer6 } from "http";
9120
- import { randomBytes as randomBytes4, randomUUID as randomUUID6, createHash as createHash11 } from "crypto";
9121
- import { mkdir as mkdir8, mkdtemp as mkdtemp10, readFile as readFile15, readdir as readdir3, rename, rm as rm12, writeFile as writeFile12 } from "fs/promises";
9983
+ import { randomBytes as randomBytes4, randomUUID as randomUUID6, createHash as createHash12 } from "crypto";
9984
+ import { mkdir as mkdir8, mkdtemp as mkdtemp10, readFile as readFile15, readdir as readdir3, rename, rm as rm12, writeFile as writeFile13 } from "fs/promises";
9122
9985
  import { dirname as dirname5, join as join23, resolve as resolve7, relative as relative4, sep as sep3 } from "path";
9123
9986
  import { tmpdir as tmpdir10 } from "os";
9124
9987
  import { fileURLToPath as fileURLToPath3 } from "url";
9125
9988
  import { spawn as spawn5 } from "child_process";
9126
9989
  var uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
9127
- var hash2 = (spec) => createHash11("sha256").update(JSON.stringify(spec)).digest("hex");
9990
+ var hash2 = (spec) => createHash12("sha256").update(JSON.stringify(spec)).digest("hex");
9128
9991
  function duration(value) {
9129
9992
  if (!Number.isInteger(value) || value < 1 || value > 86400) throw new Error("ttlSeconds must be 1\u201386400");
9130
9993
  return value;
9131
9994
  }
9132
9995
  async function persist(directory2, session) {
9133
9996
  const temporary = join23(directory2, `${randomUUID6()}.tmp`);
9134
- await writeFile12(temporary, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
9997
+ await writeFile13(temporary, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
9135
9998
  await rename(temporary, join23(directory2, "session.json"));
9136
9999
  }
9137
10000
  var view = ({ controlToken: _token, cwd: _cwd, file: _file, controlUrl: _control, ...session }) => session;
@@ -9264,8 +10127,8 @@ async function serveWorldSession(directory2) {
9264
10127
  const out = join23(session.cwd, ".agenttwin/runs", runId);
9265
10128
  await mkdir8(out, { recursive: true, mode: 448 });
9266
10129
  const evidencePath = join23(out, "run.json");
9267
- await writeFile12(evidencePath, JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
9268
- await writeFile12(join23(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
10130
+ await writeFile13(evidencePath, JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
10131
+ await writeFile13(join23(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
9269
10132
  session.lastRunId = runId;
9270
10133
  result = { ...receipt, evidencePath };
9271
10134
  } finally {