agenttwin 0.3.21 → 0.3.23

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 (411) hide show
  1. package/dist/api.js +2113 -609
  2. package/dist/dashboard/assets/dashboard/agent-home.css +7 -7
  3. package/dist/dashboard/assets/dashboard/bay-morning.webp +0 -0
  4. package/dist/dashboard/assets/dashboard/golden-gate-afternoon.webp +0 -0
  5. package/dist/dashboard/assets/dashboard/golden-gate-portrait.webp +0 -0
  6. package/dist/dashboard/assets/dashboard/moonlit-coast.webp +0 -0
  7. package/dist/dashboard/assets/next/static/chunks/{1250-7571b1a697f6bb4a.js → 1250-a3c859fd20517500.js} +1 -1
  8. package/dist/dashboard/assets/next/static/chunks/{2743-a0efd6f4aeb11cc5.js → 2743-72610a5d5a3f8462.js} +1 -1
  9. package/dist/dashboard/assets/next/static/chunks/5663-403316746afad10e.js +1 -0
  10. package/dist/dashboard/assets/next/static/chunks/app/dashboard/{page-9c11295678539a5f.js → page-0e0392368e0a891e.js} +1 -1
  11. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-4981ea4966b19e3e.js +1 -0
  12. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-dd4ac0f5f36e6bfa.js +1 -0
  13. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/{page-34574448d210c775.js → page-de0fe6d84be21e6a.js} +1 -1
  14. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-360cbffc57981f6b.js +1 -0
  15. package/dist/dashboard/assets/next/static/chunks/app/v2/page-fc4df4912ce3af44.js +1 -0
  16. package/dist/dashboard/assets/next/static/chunks/{webpack-40324749d289e4a5.js → webpack-9e40ef55e5f2fb53.js} +1 -1
  17. package/dist/dashboard/assets/next/static/css/{42045de5f39b50ca.css → 37d81e1d2804cc5f.css} +1 -1
  18. package/dist/dashboard/assets/next/static/css/69ec1bae997c3bb0.css +1 -0
  19. package/dist/dashboard/assets/next/static/css/ad85402a1595e56e.css +1 -0
  20. package/dist/dashboard/assets/next/static/css/{4bbe78c2fe206b92.css → da981fb878a02b8c.css} +1 -1
  21. package/dist/dashboard/assets/next/static/media/bay-morning.82669113.webp +0 -0
  22. package/dist/dashboard/assets/next/static/media/golden-gate-afternoon.0aa49492.webp +0 -0
  23. package/dist/dashboard/assets/next/static/media/golden-gate-portrait.89fc667a.webp +0 -0
  24. package/dist/dashboard/assets/next/static/media/moonlit-coast.09739ef4.webp +0 -0
  25. package/dist/dashboard/index.html +2 -2
  26. package/dist/engine.js +6386 -4974
  27. package/dist/gateway.js +2194 -604
  28. package/dist/twins/catalog.json +6020 -0
  29. package/dist/twins/engine/v2/THIRD-PARTY.txt +25 -0
  30. package/dist/twins/engine/v2/chunks/2CHBP57N.mjs +8 -0
  31. package/dist/twins/engine/v2/chunks/4CPL6MPF.mjs +30 -0
  32. package/dist/twins/engine/v2/chunks/OYLYKZGD.mjs +2 -0
  33. package/dist/twins/engine/v2/chunks/SQSP35HM.mjs +38 -0
  34. package/dist/twins/engine/v2/chunks/YSJQQVUM.mjs +2 -0
  35. package/dist/twins/engine/v2/react-dom_client.mjs +272 -0
  36. package/dist/twins/engine/v2/react-dom_server.mjs +263 -0
  37. package/dist/twins/engine/v2/react.mjs +2 -0
  38. package/dist/twins/engine/v2/react_jsx-runtime.mjs +31 -0
  39. package/dist/twins/engine/v2/volter_world-core.mjs +195 -0
  40. package/dist/twins/engine/v2/volter_world-core_app-route.mjs +2 -0
  41. package/dist/twins/engine/v2/volter_world-core_network-policy.mjs +2 -0
  42. package/dist/twins/engine/v3/THIRD-PARTY.txt +65 -0
  43. package/dist/twins/engine/v3/chunks/2CHBP57N.mjs +8 -0
  44. package/dist/twins/engine/v3/chunks/2YSSPA5O.mjs +65 -0
  45. package/dist/twins/engine/v3/chunks/5PWRY4UK.mjs +154 -0
  46. package/dist/twins/engine/v3/chunks/7XRKSFFJ.mjs +2 -0
  47. package/dist/twins/engine/v3/chunks/AWOWH2H5.mjs +2 -0
  48. package/dist/twins/engine/v3/chunks/C46M5U3Q.mjs +2 -0
  49. package/dist/twins/engine/v3/chunks/MFH2VZPP.mjs +2 -0
  50. package/dist/twins/engine/v3/chunks/MWCO5UV3.mjs +2 -0
  51. package/dist/twins/engine/v3/chunks/N5BL5RDF.mjs +313 -0
  52. package/dist/twins/engine/v3/chunks/O7HGPMXG.mjs +2 -0
  53. package/dist/twins/engine/v3/chunks/OYLYKZGD.mjs +2 -0
  54. package/dist/twins/engine/v3/chunks/PLB7HTON.mjs +8 -0
  55. package/dist/twins/engine/v3/chunks/TY4LDBVH.mjs +7 -0
  56. package/dist/twins/engine/v3/chunks/VDIRUSCM.mjs +2 -0
  57. package/dist/twins/engine/v3/chunks/WGUCFQK6.mjs +2 -0
  58. package/dist/twins/engine/v3/chunks/WPATONSC.mjs +2 -0
  59. package/dist/twins/engine/v3/react_jsx-runtime.mjs +2 -0
  60. package/dist/twins/engine/v3/volter_world-core.mjs +2 -0
  61. package/dist/twins/engine/v3/volter_world-ui.mjs +559 -0
  62. package/dist/twins/packs/ahrefs/LICENSE +202 -0
  63. package/dist/twins/packs/ahrefs/NOTICE +7 -0
  64. package/dist/twins/packs/ahrefs/index.mjs +2 -0
  65. package/dist/twins/packs/ai-gateway/LICENSE +202 -0
  66. package/dist/twins/packs/ai-gateway/NOTICE +7 -0
  67. package/dist/twins/packs/ai-gateway/index.mjs +14 -0
  68. package/dist/twins/packs/airtable/LICENSE +202 -0
  69. package/dist/twins/packs/airtable/NOTICE +7 -0
  70. package/dist/twins/packs/airtable/index.mjs +2 -0
  71. package/dist/twins/packs/algolia/LICENSE +202 -0
  72. package/dist/twins/packs/algolia/NOTICE +7 -0
  73. package/dist/twins/packs/algolia/index.mjs +2 -0
  74. package/dist/twins/packs/ambientcg/LICENSE +202 -0
  75. package/dist/twins/packs/ambientcg/NOTICE +7 -0
  76. package/dist/twins/packs/ambientcg/index.mjs +2 -0
  77. package/dist/twins/packs/anthropic/LICENSE +202 -0
  78. package/dist/twins/packs/anthropic/NOTICE +7 -0
  79. package/dist/twins/packs/anthropic/index.mjs +18 -0
  80. package/dist/twins/packs/assemblyai/LICENSE +202 -0
  81. package/dist/twins/packs/assemblyai/NOTICE +7 -0
  82. package/dist/twins/packs/assemblyai/index.mjs +11 -0
  83. package/dist/twins/packs/aws/LICENSE +202 -0
  84. package/dist/twins/packs/aws/NOTICE +7 -0
  85. package/dist/twins/packs/aws/index.mjs +2 -0
  86. package/dist/twins/packs/azure/LICENSE +202 -0
  87. package/dist/twins/packs/azure/NOTICE +7 -0
  88. package/dist/twins/packs/azure/index.mjs +38 -0
  89. package/dist/twins/packs/azureformrecognizer/LICENSE +202 -0
  90. package/dist/twins/packs/azureformrecognizer/NOTICE +7 -0
  91. package/dist/twins/packs/azureformrecognizer/index.mjs +3 -0
  92. package/dist/twins/packs/bitly/LICENSE +202 -0
  93. package/dist/twins/packs/bitly/NOTICE +7 -0
  94. package/dist/twins/packs/bitly/index.mjs +2 -0
  95. package/dist/twins/packs/bluesky/LICENSE +202 -0
  96. package/dist/twins/packs/bluesky/NOTICE +7 -0
  97. package/dist/twins/packs/bluesky/index.mjs +30 -0
  98. package/dist/twins/packs/calcom/LICENSE +202 -0
  99. package/dist/twins/packs/calcom/NOTICE +7 -0
  100. package/dist/twins/packs/calcom/index.mjs +2 -0
  101. package/dist/twins/packs/clerk/LICENSE +202 -0
  102. package/dist/twins/packs/clerk/NOTICE +7 -0
  103. package/dist/twins/packs/clerk/index.mjs +5 -0
  104. package/dist/twins/packs/cloudflare/LICENSE +202 -0
  105. package/dist/twins/packs/cloudflare/NOTICE +7 -0
  106. package/dist/twins/packs/cloudflare/index.mjs +79 -0
  107. package/dist/twins/packs/cohere/LICENSE +202 -0
  108. package/dist/twins/packs/cohere/NOTICE +7 -0
  109. package/dist/twins/packs/cohere/index.mjs +2 -0
  110. package/dist/twins/packs/datadog/LICENSE +202 -0
  111. package/dist/twins/packs/datadog/NOTICE +7 -0
  112. package/dist/twins/packs/datadog/index.mjs +3 -0
  113. package/dist/twins/packs/deepinfra/LICENSE +202 -0
  114. package/dist/twins/packs/deepinfra/NOTICE +7 -0
  115. package/dist/twins/packs/deepinfra/index.mjs +13 -0
  116. package/dist/twins/packs/deepseek/LICENSE +202 -0
  117. package/dist/twins/packs/deepseek/NOTICE +7 -0
  118. package/dist/twins/packs/deepseek/index.mjs +12 -0
  119. package/dist/twins/packs/discord/LICENSE +202 -0
  120. package/dist/twins/packs/discord/NOTICE +7 -0
  121. package/dist/twins/packs/discord/index.mjs +2 -0
  122. package/dist/twins/packs/duckduckgo/LICENSE +202 -0
  123. package/dist/twins/packs/duckduckgo/NOTICE +7 -0
  124. package/dist/twins/packs/duckduckgo/index.mjs +532 -0
  125. package/dist/twins/packs/dynadot/LICENSE +202 -0
  126. package/dist/twins/packs/dynadot/NOTICE +7 -0
  127. package/dist/twins/packs/dynadot/index.mjs +2 -0
  128. package/dist/twins/packs/e2b/LICENSE +202 -0
  129. package/dist/twins/packs/e2b/NOTICE +7 -0
  130. package/dist/twins/packs/e2b/index.mjs +2 -0
  131. package/dist/twins/packs/elevenlabs/LICENSE +202 -0
  132. package/dist/twins/packs/elevenlabs/NOTICE +7 -0
  133. package/dist/twins/packs/elevenlabs/index.mjs +4 -0
  134. package/dist/twins/packs/expo/LICENSE +202 -0
  135. package/dist/twins/packs/expo/NOTICE +7 -0
  136. package/dist/twins/packs/expo/index.mjs +2 -0
  137. package/dist/twins/packs/fal/LICENSE +202 -0
  138. package/dist/twins/packs/fal/NOTICE +7 -0
  139. package/dist/twins/packs/fal/index.mjs +2 -0
  140. package/dist/twins/packs/figma/LICENSE +202 -0
  141. package/dist/twins/packs/figma/NOTICE +7 -0
  142. package/dist/twins/packs/figma/index.mjs +2 -0
  143. package/dist/twins/packs/firecrawl/LICENSE +202 -0
  144. package/dist/twins/packs/firecrawl/NOTICE +7 -0
  145. package/dist/twins/packs/firecrawl/index.mjs +9 -0
  146. package/dist/twins/packs/fireworks/LICENSE +202 -0
  147. package/dist/twins/packs/fireworks/NOTICE +7 -0
  148. package/dist/twins/packs/fireworks/index.mjs +13 -0
  149. package/dist/twins/packs/fly/LICENSE +202 -0
  150. package/dist/twins/packs/fly/NOTICE +7 -0
  151. package/dist/twins/packs/fly/index.mjs +2 -0
  152. package/dist/twins/packs/gcs/LICENSE +202 -0
  153. package/dist/twins/packs/gcs/NOTICE +7 -0
  154. package/dist/twins/packs/gcs/index.mjs +8 -0
  155. package/dist/twins/packs/gemini/LICENSE +202 -0
  156. package/dist/twins/packs/gemini/NOTICE +7 -0
  157. package/dist/twins/packs/gemini/index.mjs +7 -0
  158. package/dist/twins/packs/github/LICENSE +202 -0
  159. package/dist/twins/packs/github/NOTICE +7 -0
  160. package/dist/twins/packs/github/index.mjs +75153 -0
  161. package/dist/twins/packs/googleads/LICENSE +202 -0
  162. package/dist/twins/packs/googleads/NOTICE +7 -0
  163. package/dist/twins/packs/googleads/index.mjs +3 -0
  164. package/dist/twins/packs/googlemaps/LICENSE +202 -0
  165. package/dist/twins/packs/googlemaps/NOTICE +7 -0
  166. package/dist/twins/packs/googlemaps/index.mjs +2 -0
  167. package/dist/twins/packs/googleoauth/LICENSE +202 -0
  168. package/dist/twins/packs/googleoauth/NOTICE +7 -0
  169. package/dist/twins/packs/googleoauth/index.mjs +2 -0
  170. package/dist/twins/packs/hackernews/LICENSE +202 -0
  171. package/dist/twins/packs/hackernews/NOTICE +7 -0
  172. package/dist/twins/packs/hackernews/index.mjs +35 -0
  173. package/dist/twins/packs/huggingface/LICENSE +202 -0
  174. package/dist/twins/packs/huggingface/NOTICE +7 -0
  175. package/dist/twins/packs/huggingface/index.mjs +9 -0
  176. package/dist/twins/packs/inngest/LICENSE +202 -0
  177. package/dist/twins/packs/inngest/NOTICE +7 -0
  178. package/dist/twins/packs/inngest/index.mjs +2 -0
  179. package/dist/twins/packs/instagram/LICENSE +202 -0
  180. package/dist/twins/packs/instagram/NOTICE +7 -0
  181. package/dist/twins/packs/instagram/index.mjs +2 -0
  182. package/dist/twins/packs/jira/LICENSE +202 -0
  183. package/dist/twins/packs/jira/NOTICE +7 -0
  184. package/dist/twins/packs/jira/index.mjs +2 -0
  185. package/dist/twins/packs/langfuse/LICENSE +202 -0
  186. package/dist/twins/packs/langfuse/NOTICE +7 -0
  187. package/dist/twins/packs/langfuse/index.mjs +2 -0
  188. package/dist/twins/packs/linear/LICENSE +202 -0
  189. package/dist/twins/packs/linear/NOTICE +7 -0
  190. package/dist/twins/packs/linear/index.mjs +52866 -0
  191. package/dist/twins/packs/linkedin/LICENSE +202 -0
  192. package/dist/twins/packs/linkedin/NOTICE +7 -0
  193. package/dist/twins/packs/linkedin/index.mjs +78 -0
  194. package/dist/twins/packs/livekit/LICENSE +202 -0
  195. package/dist/twins/packs/livekit/NOTICE +7 -0
  196. package/dist/twins/packs/livekit/index.mjs +2 -0
  197. package/dist/twins/packs/mailgun/LICENSE +202 -0
  198. package/dist/twins/packs/mailgun/NOTICE +7 -0
  199. package/dist/twins/packs/mailgun/index.mjs +13 -0
  200. package/dist/twins/packs/mapbox/LICENSE +202 -0
  201. package/dist/twins/packs/mapbox/NOTICE +7 -0
  202. package/dist/twins/packs/mapbox/index.mjs +2 -0
  203. package/dist/twins/packs/merge/LICENSE +202 -0
  204. package/dist/twins/packs/merge/NOTICE +7 -0
  205. package/dist/twins/packs/merge/index.mjs +4 -0
  206. package/dist/twins/packs/mistral/LICENSE +202 -0
  207. package/dist/twins/packs/mistral/NOTICE +7 -0
  208. package/dist/twins/packs/mistral/index.mjs +6 -0
  209. package/dist/twins/packs/mixpanel/LICENSE +202 -0
  210. package/dist/twins/packs/mixpanel/NOTICE +8 -0
  211. package/dist/twins/packs/mixpanel/index.mjs +2 -0
  212. package/dist/twins/packs/mongodb/LICENSE +202 -0
  213. package/dist/twins/packs/mongodb/NOTICE +7 -0
  214. package/dist/twins/packs/mongodb/index.mjs +8 -0
  215. package/dist/twins/packs/moonshot/LICENSE +202 -0
  216. package/dist/twins/packs/moonshot/NOTICE +7 -0
  217. package/dist/twins/packs/moonshot/index.mjs +18 -0
  218. package/dist/twins/packs/notion/LICENSE +202 -0
  219. package/dist/twins/packs/notion/NOTICE +7 -0
  220. package/dist/twins/packs/notion/index.mjs +2 -0
  221. package/dist/twins/packs/npm-registry/LICENSE +202 -0
  222. package/dist/twins/packs/npm-registry/NOTICE +7 -0
  223. package/dist/twins/packs/npm-registry/index.mjs +2 -0
  224. package/dist/twins/packs/oa-treasury/LICENSE +202 -0
  225. package/dist/twins/packs/oa-treasury/NOTICE +8 -0
  226. package/dist/twins/packs/oa-treasury/index.mjs +16 -0
  227. package/dist/twins/packs/openai/LICENSE +202 -0
  228. package/dist/twins/packs/openai/NOTICE +7 -0
  229. package/dist/twins/packs/openai/index.mjs +3473 -0
  230. package/dist/twins/packs/openrouter/LICENSE +202 -0
  231. package/dist/twins/packs/openrouter/NOTICE +7 -0
  232. package/dist/twins/packs/openrouter/index.mjs +2 -0
  233. package/dist/twins/packs/openweather/LICENSE +202 -0
  234. package/dist/twins/packs/openweather/NOTICE +7 -0
  235. package/dist/twins/packs/openweather/index.mjs +2 -0
  236. package/dist/twins/packs/paypal/LICENSE +202 -0
  237. package/dist/twins/packs/paypal/NOTICE +7 -0
  238. package/dist/twins/packs/paypal/index.mjs +51 -0
  239. package/dist/twins/packs/pinecone/LICENSE +202 -0
  240. package/dist/twins/packs/pinecone/NOTICE +7 -0
  241. package/dist/twins/packs/pinecone/index.mjs +2 -0
  242. package/dist/twins/packs/plain/LICENSE +202 -0
  243. package/dist/twins/packs/plain/NOTICE +8 -0
  244. package/dist/twins/packs/plain/index.mjs +18426 -0
  245. package/dist/twins/packs/planetscale/LICENSE +202 -0
  246. package/dist/twins/packs/planetscale/NOTICE +7 -0
  247. package/dist/twins/packs/planetscale/index.mjs +18 -0
  248. package/dist/twins/packs/polar/LICENSE +202 -0
  249. package/dist/twins/packs/polar/NOTICE +7 -0
  250. package/dist/twins/packs/polar/index.mjs +2 -0
  251. package/dist/twins/packs/polyhaven/LICENSE +202 -0
  252. package/dist/twins/packs/polyhaven/NOTICE +7 -0
  253. package/dist/twins/packs/polyhaven/index.mjs +3 -0
  254. package/dist/twins/packs/postmark/LICENSE +202 -0
  255. package/dist/twins/packs/postmark/NOTICE +7 -0
  256. package/dist/twins/packs/postmark/index.mjs +12 -0
  257. package/dist/twins/packs/reddit/LICENSE +202 -0
  258. package/dist/twins/packs/reddit/NOTICE +7 -0
  259. package/dist/twins/packs/reddit/index.mjs +324 -0
  260. package/dist/twins/packs/redis/LICENSE +202 -0
  261. package/dist/twins/packs/redis/NOTICE +7 -0
  262. package/dist/twins/packs/redis/index.mjs +2 -0
  263. package/dist/twins/packs/replicate/LICENSE +202 -0
  264. package/dist/twins/packs/replicate/NOTICE +7 -0
  265. package/dist/twins/packs/replicate/index.mjs +2 -0
  266. package/dist/twins/packs/resend/LICENSE +202 -0
  267. package/dist/twins/packs/resend/NOTICE +7 -0
  268. package/dist/twins/packs/resend/index.mjs +139 -0
  269. package/dist/twins/packs/runhuman/LICENSE +202 -0
  270. package/dist/twins/packs/runhuman/NOTICE +7 -0
  271. package/dist/twins/packs/runhuman/index.mjs +3 -0
  272. package/dist/twins/packs/scrapecreators/LICENSE +202 -0
  273. package/dist/twins/packs/scrapecreators/NOTICE +7 -0
  274. package/dist/twins/packs/scrapecreators/index.mjs +2 -0
  275. package/dist/twins/packs/segment/LICENSE +202 -0
  276. package/dist/twins/packs/segment/NOTICE +8 -0
  277. package/dist/twins/packs/segment/index.mjs +2 -0
  278. package/dist/twins/packs/sendblue/LICENSE +202 -0
  279. package/dist/twins/packs/sendblue/NOTICE +7 -0
  280. package/dist/twins/packs/sendblue/index.mjs +2 -0
  281. package/dist/twins/packs/sendgrid/LICENSE +202 -0
  282. package/dist/twins/packs/sendgrid/NOTICE +8 -0
  283. package/dist/twins/packs/sendgrid/index.mjs +4 -0
  284. package/dist/twins/packs/sentry/LICENSE +202 -0
  285. package/dist/twins/packs/sentry/NOTICE +7 -0
  286. package/dist/twins/packs/sentry/index.mjs +5 -0
  287. package/dist/twins/packs/sigstore/LICENSE +202 -0
  288. package/dist/twins/packs/sigstore/NOTICE +7 -0
  289. package/dist/twins/packs/sigstore/index.mjs +12 -0
  290. package/dist/twins/packs/slack/LICENSE +202 -0
  291. package/dist/twins/packs/slack/NOTICE +7 -0
  292. package/dist/twins/packs/slack/index.mjs +66 -0
  293. package/dist/twins/packs/smtp/LICENSE +202 -0
  294. package/dist/twins/packs/smtp/NOTICE +7 -0
  295. package/dist/twins/packs/smtp/index.mjs +3 -0
  296. package/dist/twins/packs/snowflake/LICENSE +202 -0
  297. package/dist/twins/packs/snowflake/NOTICE +8 -0
  298. package/dist/twins/packs/snowflake/index.mjs +30 -0
  299. package/dist/twins/packs/stigg/LICENSE +202 -0
  300. package/dist/twins/packs/stigg/NOTICE +8 -0
  301. package/dist/twins/packs/stigg/index.mjs +22194 -0
  302. package/dist/twins/packs/stream/LICENSE +202 -0
  303. package/dist/twins/packs/stream/NOTICE +7 -0
  304. package/dist/twins/packs/stream/index.mjs +2 -0
  305. package/dist/twins/packs/stripe/LICENSE +202 -0
  306. package/dist/twins/packs/stripe/NOTICE +7 -0
  307. package/dist/twins/packs/stripe/index.mjs +211 -0
  308. package/dist/twins/packs/supabase/LICENSE +202 -0
  309. package/dist/twins/packs/supabase/NOTICE +7 -0
  310. package/dist/twins/packs/supabase/index.mjs +2 -0
  311. package/dist/twins/packs/supermemory/LICENSE +202 -0
  312. package/dist/twins/packs/supermemory/NOTICE +7 -0
  313. package/dist/twins/packs/supermemory/index.mjs +2 -0
  314. package/dist/twins/packs/svix/LICENSE +202 -0
  315. package/dist/twins/packs/svix/NOTICE +7 -0
  316. package/dist/twins/packs/svix/index.mjs +2 -0
  317. package/dist/twins/packs/tavily/LICENSE +202 -0
  318. package/dist/twins/packs/tavily/NOTICE +7 -0
  319. package/dist/twins/packs/tavily/index.mjs +2 -0
  320. package/dist/twins/packs/telegram/LICENSE +202 -0
  321. package/dist/twins/packs/telegram/NOTICE +7 -0
  322. package/dist/twins/packs/telegram/index.mjs +11 -0
  323. package/dist/twins/packs/temporal/LICENSE +202 -0
  324. package/dist/twins/packs/temporal/NOTICE +7 -0
  325. package/dist/twins/packs/temporal/index.mjs +44 -0
  326. package/dist/twins/packs/tiktok/LICENSE +202 -0
  327. package/dist/twins/packs/tiktok/NOTICE +7 -0
  328. package/dist/twins/packs/tiktok/index.mjs +2 -0
  329. package/dist/twins/packs/tinybird/LICENSE +202 -0
  330. package/dist/twins/packs/tinybird/NOTICE +7 -0
  331. package/dist/twins/packs/tinybird/index.mjs +50 -0
  332. package/dist/twins/packs/togetherai/LICENSE +202 -0
  333. package/dist/twins/packs/togetherai/NOTICE +7 -0
  334. package/dist/twins/packs/togetherai/index.mjs +11 -0
  335. package/dist/twins/packs/tremendous/LICENSE +202 -0
  336. package/dist/twins/packs/tremendous/NOTICE +7 -0
  337. package/dist/twins/packs/tremendous/index.mjs +2 -0
  338. package/dist/twins/packs/tripo/LICENSE +202 -0
  339. package/dist/twins/packs/tripo/NOTICE +7 -0
  340. package/dist/twins/packs/tripo/index.mjs +9 -0
  341. package/dist/twins/packs/tunnel/LICENSE +202 -0
  342. package/dist/twins/packs/tunnel/NOTICE +7 -0
  343. package/dist/twins/packs/tunnel/index.mjs +2 -0
  344. package/dist/twins/packs/twelvelabs/LICENSE +202 -0
  345. package/dist/twins/packs/twelvelabs/NOTICE +7 -0
  346. package/dist/twins/packs/twelvelabs/index.mjs +5 -0
  347. package/dist/twins/packs/twilio/LICENSE +202 -0
  348. package/dist/twins/packs/twilio/NOTICE +7 -0
  349. package/dist/twins/packs/twilio/index.mjs +2 -0
  350. package/dist/twins/packs/twitch/LICENSE +202 -0
  351. package/dist/twins/packs/twitch/NOTICE +7 -0
  352. package/dist/twins/packs/twitch/index.mjs +68 -0
  353. package/dist/twins/packs/upstash/LICENSE +202 -0
  354. package/dist/twins/packs/upstash/NOTICE +7 -0
  355. package/dist/twins/packs/upstash/index.mjs +14 -0
  356. package/dist/twins/packs/upstashvector/LICENSE +202 -0
  357. package/dist/twins/packs/upstashvector/NOTICE +7 -0
  358. package/dist/twins/packs/upstashvector/index.mjs +3 -0
  359. package/dist/twins/packs/vercel/LICENSE +202 -0
  360. package/dist/twins/packs/vercel/NOTICE +7 -0
  361. package/dist/twins/packs/vercel/index.mjs +10 -0
  362. package/dist/twins/packs/veriff/LICENSE +202 -0
  363. package/dist/twins/packs/veriff/NOTICE +7 -0
  364. package/dist/twins/packs/veriff/index.mjs +2 -0
  365. package/dist/twins/packs/vgauth/LICENSE +202 -0
  366. package/dist/twins/packs/vgauth/NOTICE +7 -0
  367. package/dist/twins/packs/vgauth/index.mjs +2 -0
  368. package/dist/twins/packs/vital/LICENSE +202 -0
  369. package/dist/twins/packs/vital/NOTICE +7 -0
  370. package/dist/twins/packs/vital/index.mjs +2 -0
  371. package/dist/twins/packs/volteridentity/LICENSE +202 -0
  372. package/dist/twins/packs/volteridentity/NOTICE +7 -0
  373. package/dist/twins/packs/volteridentity/index.mjs +2 -0
  374. package/dist/twins/packs/webrisk/LICENSE +202 -0
  375. package/dist/twins/packs/webrisk/NOTICE +7 -0
  376. package/dist/twins/packs/webrisk/index.mjs +2 -0
  377. package/dist/twins/packs/worldlabs/LICENSE +202 -0
  378. package/dist/twins/packs/worldlabs/NOTICE +7 -0
  379. package/dist/twins/packs/worldlabs/index.mjs +2 -0
  380. package/dist/twins/packs/x/LICENSE +202 -0
  381. package/dist/twins/packs/x/NOTICE +7 -0
  382. package/dist/twins/packs/x/index.mjs +63 -0
  383. package/dist/twins/packs/xai/LICENSE +202 -0
  384. package/dist/twins/packs/xai/NOTICE +7 -0
  385. package/dist/twins/packs/xai/index.mjs +4 -0
  386. package/dist/twins/packs/xidentity/LICENSE +202 -0
  387. package/dist/twins/packs/xidentity/NOTICE +8 -0
  388. package/dist/twins/packs/xidentity/index.mjs +209 -0
  389. package/dist/twins/packs/youtube/LICENSE +202 -0
  390. package/dist/twins/packs/youtube/NOTICE +7 -0
  391. package/dist/twins/packs/youtube/index.mjs +5 -0
  392. package/dist/worker.js +442 -18
  393. package/dist/world-host.js +928 -91
  394. package/package.json +6 -5
  395. package/dist/dashboard/assets/dashboard/bay-morning.png +0 -0
  396. package/dist/dashboard/assets/dashboard/golden-gate-afternoon.png +0 -0
  397. package/dist/dashboard/assets/dashboard/golden-gate-portrait.png +0 -0
  398. package/dist/dashboard/assets/dashboard/moonlit-coast.png +0 -0
  399. package/dist/dashboard/assets/next/static/chunks/2868-424d32cfc8ae81c9.js +0 -1
  400. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-f9fca2c08f779fa0.js +0 -1
  401. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-bc480c9258e5cc4d.js +0 -1
  402. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-f04c0b236abaead3.js +0 -1
  403. package/dist/dashboard/assets/next/static/chunks/app/v2/page-07c8054d57c9089b.js +0 -1
  404. package/dist/dashboard/assets/next/static/css/4af3c8ca0da0f48b.css +0 -1
  405. package/dist/dashboard/assets/next/static/css/6b8edde77e493a51.css +0 -1
  406. package/dist/dashboard/assets/next/static/media/bay-morning.1a9f358c.png +0 -0
  407. package/dist/dashboard/assets/next/static/media/golden-gate-afternoon.3e7cea58.png +0 -0
  408. package/dist/dashboard/assets/next/static/media/golden-gate-portrait.7941528f.png +0 -0
  409. package/dist/dashboard/assets/next/static/media/moonlit-coast.bbe901a1.png +0 -0
  410. /package/dist/dashboard/assets/next/static/{5ub3D2yzS8DE7w2qZd1nv → GTd0IQ6HYyhE_2HqcgFno}/_buildManifest.js +0 -0
  411. /package/dist/dashboard/assets/next/static/{5ub3D2yzS8DE7w2qZd1nv → GTd0IQ6HYyhE_2HqcgFno}/_ssgManifest.js +0 -0
@@ -277,7 +277,7 @@ var init_stripe_adapter = __esm({
277
277
 
278
278
  // src/runtime/llm-adapter.ts
279
279
  function hasToolResult(messages) {
280
- return Array.isArray(messages) && messages.some((m) => !!m && typeof m === "object" && (m.role === "tool" || Array.isArray(m.content) && m.content.some((part) => !!part && typeof part === "object" && part.type === "tool_result")));
280
+ return Array.isArray(messages) && messages.some((m) => !!m && typeof m === "object" && (m.role === "tool" || m.type === "function_call_output" || Array.isArray(m.content) && m.content.some((part) => !!part && typeof part === "object" && part.type === "tool_result")));
281
281
  }
282
282
  function lastUserText(messages) {
283
283
  if (typeof messages === "string") return messages;
@@ -314,12 +314,65 @@ function parsedInput(value) {
314
314
  return { value };
315
315
  }
316
316
  }
317
+ function streamed(result, events) {
318
+ return { ...result, body: events, headers: { ...result.headers ?? {}, ...SSE } };
319
+ }
320
+ function chatStream(body) {
321
+ const base = { id: body.id, object: "chat.completion.chunk", created: body.created, model: body.model, system_fingerprint: null };
322
+ const message = body.choices[0].message, chunk = (delta, finish = null) => frame({ ...base, choices: [{ index: 0, delta, logprobs: null, finish_reason: finish }] });
323
+ let out = chunk({ role: "assistant", content: "", refusal: null });
324
+ if (typeof message.content === "string") for (const part of pieces(message.content)) out += chunk({ content: part });
325
+ (message.tool_calls ?? []).forEach((call, index) => {
326
+ out += chunk({ tool_calls: [{ index, id: call.id, type: "function", function: { name: call.function.name, arguments: "" } }] });
327
+ for (const part of pieces(call.function.arguments)) out += chunk({ tool_calls: [{ index, function: { arguments: part } }] });
328
+ });
329
+ out += chunk({}, body.choices[0].finish_reason);
330
+ return out + frame("[DONE]");
331
+ }
332
+ function responsesStream(body) {
333
+ let n = 0;
334
+ const ev = (type, data) => frame({ type, sequence_number: n++, ...data }, type);
335
+ const pending = { ...body, status: "in_progress", output: [], usage: null };
336
+ let out = ev("response.created", { response: pending }) + ev("response.in_progress", { response: pending });
337
+ body.output.forEach((item, output_index) => {
338
+ if (item.type === "message") {
339
+ const text = item.content[0]?.text ?? "";
340
+ out += ev("response.output_item.added", { output_index, item: { ...item, status: "in_progress", content: [] } });
341
+ out += ev("response.content_part.added", { item_id: item.id, output_index, content_index: 0, part: { type: "output_text", text: "", annotations: [] } });
342
+ for (const delta of pieces(text)) out += ev("response.output_text.delta", { item_id: item.id, output_index, content_index: 0, delta, logprobs: [] });
343
+ out += ev("response.output_text.done", { item_id: item.id, output_index, content_index: 0, text, logprobs: [] });
344
+ out += ev("response.content_part.done", { item_id: item.id, output_index, content_index: 0, part: item.content[0] });
345
+ } else {
346
+ out += ev("response.output_item.added", { output_index, item: { ...item, arguments: "", status: "in_progress" } });
347
+ for (const delta of pieces(item.arguments)) out += ev("response.function_call_arguments.delta", { item_id: item.id, output_index, delta });
348
+ out += ev("response.function_call_arguments.done", { item_id: item.id, output_index, arguments: item.arguments });
349
+ }
350
+ out += ev("response.output_item.done", { output_index, item });
351
+ });
352
+ return out + ev("response.completed", { response: body });
353
+ }
354
+ function anthropicStream(body) {
355
+ const ev = (type, data) => frame({ type, ...data }, type);
356
+ let out = ev("message_start", { message: { ...body, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } } });
357
+ body.content.forEach((block, index) => {
358
+ if (block.type === "text") {
359
+ out += ev("content_block_start", { index, content_block: { type: "text", text: "" } });
360
+ for (const text of pieces(block.text)) out += ev("content_block_delta", { index, delta: { type: "text_delta", text } });
361
+ } else {
362
+ out += ev("content_block_start", { index, content_block: { type: "tool_use", id: block.id, name: block.name, input: {} } });
363
+ for (const partial_json of pieces(JSON.stringify(block.input ?? {}))) out += ev("content_block_delta", { index, delta: { type: "input_json_delta", partial_json } });
364
+ }
365
+ out += ev("content_block_stop", { index });
366
+ });
367
+ out += ev("message_delta", { delta: { stop_reason: body.stop_reason, stop_sequence: null }, usage: { output_tokens: 0 } });
368
+ return out + ev("message_stop", {});
369
+ }
317
370
  function openaiOperation(method, path, params, _headers, data, sequence) {
318
371
  const collection = "/requests";
319
372
  if (path === "/v1/requests" || path === "/requests") return method === "GET" ? { status: 200, body: { object: "list", data: data[collection] }, collection, operation: "read" } : void 0;
320
373
  if (method === "POST" && ["/v1/responses", "/responses"].includes(path)) return openaiResponsesOperation(params, data, sequence);
321
374
  if (method !== "POST" || !["/v1/chat/completions", "/chat/completions"].includes(path)) return void 0;
322
- if (params.stream === true || !Array.isArray(params.messages)) return void 0;
375
+ if (!Array.isArray(params.messages)) return void 0;
323
376
  const prompt = lastUserText(params.messages);
324
377
  const script = nextScripted(data, prompt, hasToolResult(params.messages));
325
378
  if (!script) return void 0;
@@ -335,13 +388,14 @@ function openaiOperation(method, path, params, _headers, data, sequence) {
335
388
  choices: [{ index: 0, message: { role: "assistant", content: script.content, refusal: null, ...toolCalls.length ? { tool_calls: toolCalls } : {} }, logprobs: null, finish_reason: toolCalls.length ? "tool_calls" : "stop" }],
336
389
  usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
337
390
  };
338
- return { status: 200, body, collection, record: entry, operation: "write" };
391
+ const result = { status: 200, body, collection, record: entry, operation: "write" };
392
+ return params.stream === true ? streamed(result, chatStream(body)) : result;
339
393
  }
340
394
  function openaiResponsesOperation(params, data, sequence) {
341
395
  const collection = "/requests";
342
- if (params.stream === true || typeof params.input !== "string" && !Array.isArray(params.input)) return void 0;
396
+ if (typeof params.input !== "string" && !Array.isArray(params.input)) return void 0;
343
397
  const prompt = lastUserText(params.input);
344
- const script = nextScripted(data, prompt);
398
+ const script = nextScripted(data, prompt, hasToolResult(params.input));
345
399
  if (!script) return void 0;
346
400
  const id = `resp_at_${sequence}`;
347
401
  const calls = script.calls.map((call, index) => ({ type: "function_call", id: `fc_at_${sequence}_${index}`, call_id: `call_at_${sequence}_${index}`, name: String(call.name), arguments: arg(call.arguments), status: "completed" }));
@@ -362,13 +416,14 @@ function openaiResponsesOperation(params, data, sequence) {
362
416
  tools: Array.isArray(params.tools) ? params.tools : [],
363
417
  usage: { input_tokens: 0, output_tokens: 0, total_tokens: 0, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 } }
364
418
  };
365
- return { status: 200, body, collection, record: entry, operation: "write" };
419
+ const result = { status: 200, body, collection, record: entry, operation: "write" };
420
+ return params.stream === true ? streamed(result, responsesStream(body)) : result;
366
421
  }
367
422
  function anthropicOperation(method, path, params, _headers, data, sequence) {
368
423
  const collection = "/requests";
369
424
  if (path === "/v1/requests" || path === "/requests") return method === "GET" ? { status: 200, body: { data: data[collection] }, collection, operation: "read" } : void 0;
370
425
  if (method !== "POST" || !["/v1/messages", "/messages"].includes(path)) return void 0;
371
- if (params.stream === true || !Array.isArray(params.messages)) return void 0;
426
+ if (!Array.isArray(params.messages)) return void 0;
372
427
  const prompt = lastUserText(params.messages);
373
428
  const script = nextScripted(data, prompt, hasToolResult(params.messages));
374
429
  if (!script) return void 0;
@@ -386,13 +441,25 @@ function anthropicOperation(method, path, params, _headers, data, sequence) {
386
441
  stop_sequence: null,
387
442
  usage: { input_tokens: 0, output_tokens: 0 }
388
443
  };
389
- return { status: 200, body, collection, record: entry, operation: "write" };
444
+ const result = { status: 200, body, collection, record: entry, operation: "write" };
445
+ return params.stream === true ? streamed(result, anthropicStream(body)) : result;
390
446
  }
391
- var arg;
447
+ var arg, SSE, pieces, frame;
392
448
  var init_llm_adapter = __esm({
393
449
  "src/runtime/llm-adapter.ts"() {
394
450
  "use strict";
395
451
  arg = (value) => typeof value === "string" ? value : JSON.stringify(value ?? {});
452
+ SSE = { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache" };
453
+ pieces = (text) => {
454
+ const out = [];
455
+ const size = Math.max(1, Math.ceil(text.length / 3));
456
+ for (let i = 0; i < text.length; i += size) out.push(text.slice(i, i + size));
457
+ return out.length ? out : [""];
458
+ };
459
+ frame = (data, event) => `${event ? `event: ${event}
460
+ ` : ""}data: ${typeof data === "string" ? data : JSON.stringify(data)}
461
+
462
+ `;
396
463
  }
397
464
  });
398
465
 
@@ -534,9 +601,9 @@ function githubOperation(method, path, params, _headers, data, sequence) {
534
601
  if (Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
535
602
  if (params.status !== void 0 && !["queued", "in_progress", "completed"].includes(String(params.status))) return errors(422, "Validation Failed", { errors: [{ resource: "CheckRun", field: "status", code: "invalid" }] });
536
603
  if (params.conclusion !== void 0 && !["success", "failure", "neutral", "cancelled", "skipped", "timed_out"].includes(String(params.conclusion))) return errors(422, "Validation Failed", { errors: [{ resource: "CheckRun", field: "conclusion", code: "invalid" }] });
537
- const run = { id: `github_at_${sequence}`, name: params.name, head_sha: params.head_sha, status: str(params.status) ?? (params.conclusion !== void 0 ? "completed" : "queued"), conclusion: params.conclusion === void 0 ? null : params.conclusion, repo, html_url: null, started_at: iso(), completed_at: params.conclusion === void 0 ? null : iso() };
538
- rows(data, "/check-runs").push(run);
539
- return created("/check-runs", structuredClone(run), run);
604
+ const run2 = { id: `github_at_${sequence}`, name: params.name, head_sha: params.head_sha, status: str(params.status) ?? (params.conclusion !== void 0 ? "completed" : "queued"), conclusion: params.conclusion === void 0 ? null : params.conclusion, repo, html_url: null, started_at: iso(), completed_at: params.conclusion === void 0 ? null : iso() };
605
+ rows(data, "/check-runs").push(run2);
606
+ return created("/check-runs", structuredClone(run2), run2);
540
607
  }
541
608
  if (resource === "issues") {
542
609
  const inRepo = rows(data, "/issues").filter((r) => r.repo === repo);
@@ -2012,6 +2079,49 @@ var init_adapters = __esm({
2012
2079
  }
2013
2080
  });
2014
2081
 
2082
+ // src/runtime/packs.ts
2083
+ import { existsSync, readFileSync } from "fs";
2084
+ import { dirname, join as join2, resolve as resolve2 } from "path";
2085
+ import { fileURLToPath, pathToFileURL } from "url";
2086
+ function packsDir() {
2087
+ const here = dirname(fileURLToPath(import.meta.url));
2088
+ const candidates = [process.env.AGENTTWIN_TWINS_DIR, join2(here, "twins"), join2(here, "../twins"), resolve2(here, "../../../twins/dist")];
2089
+ return candidates.find((dir) => !!dir && existsSync(join2(dir, "catalog.json")));
2090
+ }
2091
+ function packCatalog() {
2092
+ if (cached !== void 0) return cached;
2093
+ const dir = packsDir();
2094
+ cached = dir ? JSON.parse(readFileSync(join2(dir, "catalog.json"), "utf8")) : null;
2095
+ return cached;
2096
+ }
2097
+ function loadPack(name) {
2098
+ const record2 = packRecord(name);
2099
+ if (!record2) throw new Error(`No twin pack named ${name}`);
2100
+ let factory = loaded.get(name);
2101
+ if (!factory) {
2102
+ const file = join2(packsDir(), "packs", name, "index.mjs");
2103
+ factory = import(pathToFileURL(file).href).then((mod) => {
2104
+ if (typeof mod.createTwinFetch !== "function") throw new Error(`Twin pack ${name} exports no createTwinFetch`);
2105
+ return mod.createTwinFetch;
2106
+ });
2107
+ loaded.set(name, factory);
2108
+ }
2109
+ return factory;
2110
+ }
2111
+ var cached, PACK_PREFIX, isPackAdapter, packRecord, loaded;
2112
+ var init_packs = __esm({
2113
+ "src/runtime/packs.ts"() {
2114
+ "use strict";
2115
+ PACK_PREFIX = "pack:";
2116
+ isPackAdapter = (adapter) => typeof adapter === "string" && adapter.startsWith(PACK_PREFIX) && !!packRecord(adapter.slice(PACK_PREFIX.length));
2117
+ packRecord = (name) => {
2118
+ const c = packCatalog();
2119
+ return c && Object.hasOwn(c.packs, name) ? c.packs[name] : void 0;
2120
+ };
2121
+ loaded = /* @__PURE__ */ new Map();
2122
+ }
2123
+ });
2124
+
2015
2125
  // src/runtime/enterprise-twins.ts
2016
2126
  import { createHash as createHash4 } from "crypto";
2017
2127
  function eqFilter(expression, quote) {
@@ -2999,7 +3109,7 @@ function parseWorld(value) {
2999
3109
  if (typeof v.name !== "string" || !namePattern.test(v.name)) invalid("name must be lowercase letters, digits or underscores");
3000
3110
  if (!Array.isArray(v.files) || !v.files.length || v.files.length > 100 || !v.files.every((f) => typeof f === "string" && f.length > 0)) invalid("files must explicitly list 1\u2013100 application files");
3001
3111
  if (new Set(v.files).size !== v.files.length) invalid("files must be unique");
3002
- if (!Array.isArray(v.command) || !v.command.length || !v.command.every((c) => typeof c === "string" && c.length > 0) || v.command[0] !== "node") invalid("command must be an argv array starting with node; supply a bundled Node application");
3112
+ if (!Array.isArray(v.command) || !v.command.length || !v.command.every((c) => typeof c === "string" && c.length > 0) || !RUNTIMES.test(v.command[0])) invalid("command must be an argv array starting with node, python, python3, uv, poetry, go, ruby, bundle, deno, bun or curl");
3003
3113
  if (!Number.isInteger(v.timeoutSeconds) || Number(v.timeoutSeconds) < 1 || Number(v.timeoutSeconds) > 300) invalid("timeoutSeconds must be 1\u2013300");
3004
3114
  if (v.workflowId !== void 0 && (typeof v.workflowId !== "string" || !v.workflowId)) invalid("workflowId must be a nonempty string");
3005
3115
  if (v.sourceBuild !== void 0 && (typeof v.sourceBuild !== "string" || !/^[a-f0-9]{64}$/.test(v.sourceBuild))) invalid("sourceBuild must be a SHA-256 build-record digest");
@@ -3010,7 +3120,7 @@ function parseWorld(value) {
3010
3120
  if (!object2(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid("service names must be unique lowercase identifiers");
3011
3121
  const item = service;
3012
3122
  if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
3013
- 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", ...ENTERPRISE_ADAPTERS].includes(String(item.adapter)) && !isGeneratedAdapter(item.adapter)) invalid("unsupported service adapter");
3123
+ 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", ...ENTERPRISE_ADAPTERS].includes(String(item.adapter)) && !isGeneratedAdapter(item.adapter) && !isPackAdapter(item.adapter)) invalid("unsupported service adapter");
3014
3124
  const paths = /* @__PURE__ */ new Set();
3015
3125
  for (const entry of item.collections) {
3016
3126
  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");
@@ -3021,6 +3131,7 @@ function parseWorld(value) {
3021
3131
  const required = ADAPTER_COLLECTIONS[item.adapter];
3022
3132
  const optional = ADAPTER_OPTIONAL_COLLECTIONS[item.adapter] ?? [];
3023
3133
  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(", ")})` : ""}`);
3134
+ 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");
3024
3135
  services.set(item.name, /* @__PURE__ */ new Set([...paths, ...optional]));
3025
3136
  }
3026
3137
  const known2 = (entry) => typeof entry.service === "string" && typeof entry.path === "string" && services.get(entry.service)?.has(entry.path);
@@ -3159,14 +3270,16 @@ function parseWorld(value) {
3159
3270
  if (Object.keys(v).some((k) => !keys.includes(k))) invalid("unknown world field");
3160
3271
  return v;
3161
3272
  }
3162
- var ADAPTER_OPTIONAL_COLLECTIONS, ADAPTER_COLLECTIONS, FAULT_TYPES, PROPERTY_KINDS, object2, namePattern, inRangeInt;
3273
+ var RUNTIMES, ADAPTER_OPTIONAL_COLLECTIONS, ADAPTER_COLLECTIONS, FAULT_TYPES, PROPERTY_KINDS, object2, namePattern, inRangeInt;
3163
3274
  var init_spec = __esm({
3164
3275
  "src/runtime/spec.ts"() {
3165
3276
  "use strict";
3166
3277
  init_postgres_clock();
3167
3278
  init_adapters();
3279
+ init_packs();
3168
3280
  init_application_clock();
3169
3281
  init_enterprise_twins();
3282
+ RUNTIMES = /^(?:\/[\w./-]+\/)?(?:node|python[0-9.]*|uv|poetry|pipenv|go|ruby|bundle|deno|bun|curl)$/;
3170
3283
  ADAPTER_OPTIONAL_COLLECTIONS = {
3171
3284
  stripe: ["/v1/charges", "/v1/refunds", "/v1/events"],
3172
3285
  ...ENTERPRISE_OPTIONAL_COLLECTIONS
@@ -3202,11 +3315,87 @@ var init_spec = __esm({
3202
3315
  }
3203
3316
  });
3204
3317
 
3318
+ // src/runtime/pack-log.ts
3319
+ import { closeSync, existsSync as existsSync2, openSync, readdirSync, readSync, statSync } from "fs";
3320
+ import { join as join3 } from "path";
3321
+ function packCollection(type, requestPath) {
3322
+ const segments = requestPath.split("/").filter(Boolean);
3323
+ const at = segments.findIndex((s) => s === type || singular2(s) === type || s.replace(/-/g, "_") === type || singular2(s.replace(/-/g, "_")) === type);
3324
+ if (at >= 0) return "/" + segments.slice(0, at + 1).join("/");
3325
+ const prefix = segments[0] && /^v\d+(?:\.\d+)?$/i.test(segments[0]) ? `/${segments[0]}` : "";
3326
+ return `${prefix}/${plural(type)}`;
3327
+ }
3328
+ function credentialAction(actions) {
3329
+ return actions.find(isCredential);
3330
+ }
3331
+ function tenantFields(actions) {
3332
+ const owner = actions.find(isCredential);
3333
+ return Object.fromEntries(Object.entries(owner?.fields ?? {}).filter(([k, v]) => /^_(team|account|tenant|org|organization|workspace|project|platform)(_id)?$/.test(k) && (typeof v === "string" || typeof v === "number")));
3334
+ }
3335
+ function seedActions(service, collections, at, tenant = {}) {
3336
+ const lines = [];
3337
+ for (const c of collections) {
3338
+ const last = c.path.split("/").filter(Boolean).pop() ?? "record", type = singular2(last.replace(/-/g, "_"));
3339
+ c.seed.forEach((row, i) => {
3340
+ const id = typeof row.id === "string" && row.id ? row.id : `${type}_seed_${i + 1}`;
3341
+ const fields = { ...tenant, ...Object.fromEntries(Object.entries(row).filter(([k]) => k !== "id")) };
3342
+ lines.push(JSON.stringify({ id: `twin:${service}:${type}.create:${id}:${at}:seed${i + 1}`, service, op: "set", operation: `${type}.create`, subject: { type, id }, occurredAt: at, actor: { kind: "system" }, fields }));
3343
+ });
3344
+ }
3345
+ return lines.length ? lines.join("\n") + "\n" : "";
3346
+ }
3347
+ var PackActionTail, singular2, plural, isCredential;
3348
+ var init_pack_log = __esm({
3349
+ "src/runtime/pack-log.ts"() {
3350
+ "use strict";
3351
+ PackActionTail = class {
3352
+ constructor(root) {
3353
+ this.root = root;
3354
+ }
3355
+ root;
3356
+ offsets = /* @__PURE__ */ new Map();
3357
+ partial = /* @__PURE__ */ new Map();
3358
+ files() {
3359
+ if (!existsSync2(this.root)) return [];
3360
+ return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join3(this.root, f)).sort();
3361
+ }
3362
+ drain() {
3363
+ const out = [];
3364
+ for (const file of this.files()) {
3365
+ const size = statSync(file).size, from = this.offsets.get(file) ?? 0;
3366
+ if (size <= from) continue;
3367
+ const buffer = Buffer.alloc(size - from), fd = openSync(file, "r");
3368
+ try {
3369
+ readSync(fd, buffer, 0, buffer.length, from);
3370
+ } finally {
3371
+ closeSync(fd);
3372
+ }
3373
+ this.offsets.set(file, size);
3374
+ const text = (this.partial.get(file) ?? "") + buffer.toString("utf8");
3375
+ const lines = text.split("\n");
3376
+ this.partial.set(file, lines.pop() ?? "");
3377
+ for (const line of lines) if (line.trim()) try {
3378
+ out.push(JSON.parse(line));
3379
+ } catch {
3380
+ }
3381
+ }
3382
+ return out;
3383
+ }
3384
+ };
3385
+ singular2 = (s) => s.endsWith("ies") ? s.slice(0, -3) + "y" : s.endsWith("ses") ? s.slice(0, -2) : s.endsWith("s") ? s.slice(0, -1) : s;
3386
+ plural = (s) => /[^aeiou]y$/.test(s) ? s.slice(0, -1) + "ies" : /(s|x|ch|sh)$/.test(s) ? s + "es" : s + "s";
3387
+ isCredential = (a) => /^_.*(key|token|credential)/i.test(a.subject?.type ?? "") && !!a.fields;
3388
+ }
3389
+ });
3390
+
3205
3391
  // src/runtime/http-world.ts
3206
3392
  import { createServer } from "http";
3207
3393
  import { isDeepStrictEqual } from "util";
3208
3394
  import { createHash as createHash5 } from "crypto";
3209
3395
  import { AsyncLocalStorage } from "async_hooks";
3396
+ import { mkdir, mkdtemp as mkdtemp2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
3397
+ import { tmpdir as tmpdir2 } from "os";
3398
+ import { join as join4 } from "path";
3210
3399
  var idempotencyKeyDigest, HttpWorld;
3211
3400
  var init_http_world = __esm({
3212
3401
  "src/runtime/http-world.ts"() {
@@ -3218,6 +3407,8 @@ var init_http_world = __esm({
3218
3407
  init_spec();
3219
3408
  init_enterprise_twins();
3220
3409
  init_adapters();
3410
+ init_packs();
3411
+ init_pack_log();
3221
3412
  idempotencyKeyDigest = (key) => typeof key === "string" && key ? `sha256:${createHash5("sha256").update(key).digest("hex").slice(0, 16)}` : void 0;
3222
3413
  HttpWorld = class {
3223
3414
  /** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
@@ -3282,6 +3473,12 @@ var init_http_world = __esm({
3282
3473
  this.replayKeys.set(service.name, keys);
3283
3474
  const latency = this.spec.latency && (this.spec.latency.maxMs > this.spec.latency.minMs || this.spec.latency.minMs > 0) ? new SeedStream(this.seed, `latency:${service.name}`) : null;
3284
3475
  const latencyMs = () => latency && this.spec.latency ? this.spec.latency.minMs + latency.nextInt(this.spec.latency.maxMs - this.spec.latency.minMs + 1) : 0;
3476
+ if (isPackAdapter(service.adapter)) {
3477
+ const server2 = await this.startPack(service, token, faultOrdinalsFor, faultKey, data, latencyMs);
3478
+ this.servers.push(server2);
3479
+ this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server2.address().port}`, token };
3480
+ continue;
3481
+ }
3285
3482
  const server = createServer((req, res) => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
3286
3483
  const epoch = this.epoch;
3287
3484
  const send = (code, body, headers = {}) => {
@@ -3602,15 +3799,251 @@ var init_http_world = __esm({
3602
3799
  }
3603
3800
  }));
3604
3801
  server.requestTimeout = 1e4;
3605
- await new Promise((resolve6, reject) => {
3802
+ await new Promise((resolve7, reject) => {
3606
3803
  server.once("error", reject);
3607
- server.listen(0, "127.0.0.1", resolve6);
3804
+ server.listen(0, "127.0.0.1", resolve7);
3608
3805
  });
3609
3806
  this.servers.push(server);
3610
3807
  this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server.address().port}`, token };
3611
3808
  }
3612
3809
  return this.credentials;
3613
3810
  }
3811
+ /** Environment each pack service's credential door issued (STRIPE_SECRET_KEY…), for the application's process. */
3812
+ packEnv = /* @__PURE__ */ Object.create(null);
3813
+ packRoots = [];
3814
+ /**
3815
+ * A twin pack served behind this world: the run token is checked and swapped for the credential the pack issued,
3816
+ * seeded fault schedules apply around the pack's own handler, and every action the pack logs becomes evidence — writes
3817
+ * caused by the application's request, the twin's own records (events), webhook deliveries and modelled gaps.
3818
+ */
3819
+ async startPack(service, token, faultOrdinalsFor, faultKey, data, latencyMs) {
3820
+ const name = service.adapter.slice(PACK_PREFIX.length), meta = packRecord(name);
3821
+ const root = await mkdtemp2(join4(tmpdir2(), `agenttwin-pack-${name}-`));
3822
+ this.packRoots.push(root);
3823
+ const worldSeed = meta.logService ? JSON.stringify({ id: `twin:${meta.logService}:world_seed.record:seed:agenttwin`, service: meta.logService, op: "set", operation: "world_seed.record", subject: { type: "_world_seed", id: "seed" }, occurredAt: (/* @__PURE__ */ new Date()).toISOString(), actor: { kind: "system" }, fields: { value: new SeedStream(this.seed, `pack-world:${service.name}`).nextHex(64) } }) + "\n" : "";
3824
+ const writeSeedLog = async (dir, text) => {
3825
+ if (!text) return;
3826
+ await mkdir(join4(dir, ".volter/world", meta.logService), { recursive: true });
3827
+ await writeFile2(join4(dir, ".volter/world", meta.logService, "actions.jsonl"), text);
3828
+ };
3829
+ let tenant = {}, credential;
3830
+ if (meta.logService && meta.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account)) {
3831
+ const probe = await mkdtemp2(join4(tmpdir2(), `agenttwin-pack-${name}-probe-`));
3832
+ try {
3833
+ await writeSeedLog(probe, worldSeed);
3834
+ const scratch = await (await loadPack(name))({ root: probe });
3835
+ await (await scratch(new Request(`https://${meta.hosts[0]?.host ?? `${name}.twin.test`}${meta.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta.credentialDoor.body ?? {}) }))).arrayBuffer();
3836
+ const probed = new PackActionTail(join4(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
3837
+ tenant = tenantFields(probed);
3838
+ credential = credentialAction(probed);
3839
+ } finally {
3840
+ await rm2(probe, { recursive: true, force: true });
3841
+ }
3842
+ }
3843
+ const account = credential && service.account ? JSON.stringify({ ...credential, id: `${credential.id ?? "credential"}:preset`, fields: { ...credential.fields, ...service.account } }) + "\n" : "";
3844
+ const seeded = meta.logService ? worldSeed + account + seedActions(meta.logService, service.collections, (/* @__PURE__ */ new Date()).toISOString(), tenant) : "";
3845
+ await writeSeedLog(root, seeded);
3846
+ const twin = await (await loadPack(name))({ root });
3847
+ const baseHost = meta.hosts[0]?.host ?? `${name}.twin.test`;
3848
+ const log = new PackActionTail(join4(root, ".volter"));
3849
+ let issued = {};
3850
+ if (meta.credentialDoor) {
3851
+ const r = await twin(new Request(`https://${baseHost}${meta.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta.credentialDoor.body ?? {}) }));
3852
+ if (r.ok) issued = await r.json();
3853
+ else await r.arrayBuffer();
3854
+ }
3855
+ const env = {};
3856
+ for (const [envName, field] of Object.entries(meta.credentialDoor?.fill ?? {})) if (typeof issued[field] === "string") env[envName] = issued[field];
3857
+ this.packEnv[service.name] = env;
3858
+ const primaryEnv = Object.keys(env).find((k) => /(SECRET|API|PRIVATE|ACCESS)_?(KEY|TOKEN)$|_TOKEN$|_KEY$/.test(k) && !/PUBLISHABLE|PUBLIC|WEBHOOK|SIGNING|ENDPOINT/.test(k));
3859
+ const primary = primaryEnv ? env[primaryEnv] : void 0;
3860
+ const authHeaders = () => primary ? { authorization: `Bearer ${primary}` } : {};
3861
+ const fault = this.spec.fault;
3862
+ const matchesFault = (target) => !!fault && (target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path));
3863
+ const apply = (actions, method, path, evidence) => {
3864
+ const wrote = [];
3865
+ for (const a of actions) {
3866
+ const type = a.subject?.type, id = a.subject?.id;
3867
+ if (!type || !id) continue;
3868
+ if (type === "_world_event_delivery") {
3869
+ 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"}`);
3870
+ continue;
3871
+ }
3872
+ if (type.startsWith("_")) continue;
3873
+ const collection = packCollection(type, path);
3874
+ const rows2 = data[collection] ??= [];
3875
+ const at = rows2.findIndex((r) => r.id === id);
3876
+ const removed = /^(del|delete|remove)$/i.test(a.op ?? "") || /\.(delete|del)$/.test(a.operation ?? "");
3877
+ const row = { id, ...a.fields ?? {} };
3878
+ if (removed) {
3879
+ if (at >= 0) rows2.splice(at, 1);
3880
+ } else if (at >= 0) rows2[at] = row;
3881
+ else rows2.push(row);
3882
+ if (!evidence) continue;
3883
+ const byApp = a.actor?.kind === "agent";
3884
+ this.record(service.name, byApp ? "write" : "twin", collection, `${method} ${path} \u2192 ${a.operation ?? type} ${id}${byApp ? "" : " (by the twin)"}`, row);
3885
+ if (byApp) wrote.push(collection);
3886
+ }
3887
+ return [...new Set(wrote)].sort((x, y) => Number(path.startsWith(y)) - Number(path.startsWith(x)));
3888
+ };
3889
+ for (const path of Object.keys(data)) data[path] = [];
3890
+ for (const a of log.drain()) if (a.actor?.kind === "system" && /:seed\d+$/.test(String(a.id ?? ""))) apply([a], "POST", service.collections.find((c) => packCollection(a.subject?.type ?? "", c.path) === c.path)?.path ?? "/", false);
3891
+ if (!seeded) for (const collection of service.collections) for (const seedRow of collection.seed) {
3892
+ const body = meta.acceptsProvidedIds ? seedRow : Object.fromEntries(Object.entries(seedRow).filter(([k]) => k !== "id"));
3893
+ const encoded = meta.bodyMode === "form" ? new URLSearchParams(Object.entries(body).filter(([, v]) => v !== null && typeof v !== "object").map(([k, v]) => [k, String(v)])).toString() : JSON.stringify(body);
3894
+ const r = await twin(new Request(`https://${baseHost}${collection.path}`, { method: "POST", headers: { ...authHeaders(), "content-type": meta.bodyMode === "form" ? "application/x-www-form-urlencoded" : "application/json" }, body: encoded }));
3895
+ await r.arrayBuffer();
3896
+ apply(log.drain(), "POST", collection.path, false);
3897
+ }
3898
+ for (const collection of service.collections) data[collection.path] ??= [];
3899
+ let chain = Promise.resolve();
3900
+ const serialized = (fn) => {
3901
+ const run2 = chain.then(fn, fn);
3902
+ chain = run2.then(() => void 0, () => void 0);
3903
+ return run2;
3904
+ };
3905
+ const server = createServer((req, res) => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
3906
+ const epoch = this.epoch;
3907
+ const send = (status, headers, body) => {
3908
+ if (!res.destroyed) {
3909
+ res.writeHead(status, headers);
3910
+ res.end(body);
3911
+ }
3912
+ };
3913
+ const later = (ms, fn) => {
3914
+ const timer = setTimeout(() => {
3915
+ this.timers.delete(timer);
3916
+ if (epoch === this.epoch) fn();
3917
+ }, ms);
3918
+ this.timers.add(timer);
3919
+ };
3920
+ const respond = (status, headers, body) => {
3921
+ const ms = latencyMs();
3922
+ if (ms <= 0) send(status, headers, body);
3923
+ else later(ms, () => send(status, headers, body));
3924
+ };
3925
+ const json = (status, value) => respond(status, { "content-type": "application/json" }, Buffer.from(JSON.stringify(value)));
3926
+ try {
3927
+ const ours = req.headers.authorization === `Bearer ${token}` || req.headers["x-api-key"] === token || req.headers["x-agenttwin-token"] === token;
3928
+ if (!ours) {
3929
+ this.record(service.name, "auth-denied", req.url ?? "", "invalid test credential");
3930
+ json(401, { error: "invalid_test_credential" });
3931
+ return;
3932
+ }
3933
+ if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
3934
+ json(429, { error: "world_capacity" });
3935
+ return;
3936
+ }
3937
+ const url = new URL(req.url ?? "/", "http://localhost"), method = req.method ?? "GET", path = url.pathname;
3938
+ const requestKey = req.headers["idempotency-key"];
3939
+ if (fault && faultOrdinalsFor && (fault.type === "blackhole" || fault.type === "server-error") && matchesFault(path) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
3940
+ this.faultActions++;
3941
+ if (fault.type === "blackhole") {
3942
+ this.record(service.name, "fault", fault.path, `blackhole: request dropped; nothing committed (${method})`);
3943
+ this.keyed(requestKey);
3944
+ return;
3945
+ }
3946
+ const windowMs = fault.windowMs ?? 0;
3947
+ const delay = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
3948
+ this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay}ms; nothing committed (${method})`);
3949
+ this.keyed(requestKey);
3950
+ const fail = () => json(500, { error: { type: "api_error", message: "server_error fault" } });
3951
+ if (delay <= 0) fail();
3952
+ else later(delay, fail);
3953
+ return;
3954
+ }
3955
+ const chunks = [];
3956
+ let bytes = 0;
3957
+ for await (const chunk of req) {
3958
+ bytes += chunk.length;
3959
+ if (bytes > 5 * 1024 * 1024) {
3960
+ json(413, { error: "body_too_large" });
3961
+ return;
3962
+ }
3963
+ chunks.push(Buffer.from(chunk));
3964
+ }
3965
+ const body = ["GET", "HEAD"].includes(method) ? void 0 : Buffer.concat(chunks);
3966
+ if (epoch !== this.epoch) {
3967
+ json(409, { error: "world_reset" });
3968
+ return;
3969
+ }
3970
+ let host = String(req.headers["x-agenttwin-original-host"] ?? baseHost);
3971
+ if (name === "pinecone") {
3972
+ const m = /^([a-z0-9-]+?)-[a-z0-9]+\.svc\.[a-z0-9.-]*pinecone\.io$/.exec(host);
3973
+ const index = m && (data["/indexes"] ?? []).find((r) => r.name === m[1] && typeof r.host === "string");
3974
+ if (index && index.host !== host) host = String(index.host);
3975
+ }
3976
+ const headers = new Headers();
3977
+ 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);
3978
+ if (headers.get("authorization") === `Bearer ${token}`) {
3979
+ if (primary) headers.set("authorization", `Bearer ${primary}`);
3980
+ else headers.delete("authorization");
3981
+ }
3982
+ if (headers.get("x-api-key") === token) {
3983
+ if (primary) headers.set("x-api-key", primary);
3984
+ else headers.delete("x-api-key");
3985
+ }
3986
+ const call = async () => {
3987
+ const r = await twin(new Request(`https://${host}${req.url ?? "/"}`, { method, headers, ...body ? { body } : {} }));
3988
+ return { status: r.status, headers: r.headers, bytes: Buffer.from(await r.arrayBuffer()), actions: log.drain() };
3989
+ };
3990
+ const first = await serialized(call);
3991
+ if (epoch !== this.epoch) return;
3992
+ const wrote = apply(first.actions, method, path, true);
3993
+ let okFalse;
3994
+ if (first.status < 300 && /json/.test(first.headers.get("content-type") ?? "")) try {
3995
+ const parsed = JSON.parse(first.bytes.toString("utf8"));
3996
+ if (parsed.ok === false) okFalse = [parsed.error, ...parsed.response_metadata?.messages ?? []].filter(Boolean).join(": ").slice(0, 240) || "ok: false";
3997
+ } catch {
3998
+ }
3999
+ if (wrote.length) this.keyed(requestKey);
4000
+ 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}`);
4001
+ else if (okFalse) this.record(service.name, "rejected", path, `${method} ${path} \u2192 ${first.status} ok:false: ${okFalse}`);
4002
+ else if (first.status >= 400) {
4003
+ let reason = "";
4004
+ try {
4005
+ const parsed = JSON.parse(first.bytes.toString("utf8"));
4006
+ const e = parsed.error ?? parsed;
4007
+ reason = String(e.message ?? e.error_description ?? e.code ?? "").slice(0, 240);
4008
+ } catch {
4009
+ reason = first.bytes.toString("utf8").slice(0, 120);
4010
+ }
4011
+ this.record(service.name, "rejected", path, `${method} ${path} \u2192 ${first.status}${reason ? `: ${reason}` : ""}`);
4012
+ } else if (method === "GET") this.record(service.name, "read", path, `${first.status}`);
4013
+ const target = wrote[0];
4014
+ if (target && fault?.type === "duplicate-write" && fault.service === service.name && !requestKey && matchesFault(target) && faultOrdinalsFor?.includes(this.candidateIndex(faultKey))) {
4015
+ const second = await serialized(call);
4016
+ apply(second.actions, method, path, true);
4017
+ this.faultActions++;
4018
+ this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${target})`);
4019
+ }
4020
+ const out = {};
4021
+ first.headers.forEach((v, k) => {
4022
+ if (!/^(content-length|transfer-encoding|connection)$/i.test(k)) out[k] = v;
4023
+ });
4024
+ if (target && !this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && matchesFault(target)) {
4025
+ this.fired = true;
4026
+ this.faultActions++;
4027
+ this.record(service.name, "fault", target, `write committed; response delayed ${fault.delayMs}ms`);
4028
+ this.keyed(requestKey);
4029
+ later(fault.delayMs, () => send(first.status, out, first.bytes));
4030
+ } else if (fault?.type === "slow-response" && faultOrdinalsFor && matchesFault(target ?? path) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
4031
+ this.faultActions++;
4032
+ this.record(service.name, "fault", target ?? path, `slow-response: ${target ? "write" : "request"} applied; response delayed ${fault.delayMs}ms`);
4033
+ this.keyed(requestKey);
4034
+ later(fault.delayMs, () => respond(first.status, out, first.bytes));
4035
+ } else respond(first.status, out, first.bytes);
4036
+ } catch {
4037
+ json(500, { error: "world_request_error" });
4038
+ }
4039
+ }));
4040
+ server.requestTimeout = 1e4;
4041
+ await new Promise((resolve7, reject) => {
4042
+ server.once("error", reject);
4043
+ server.listen(0, "127.0.0.1", resolve7);
4044
+ });
4045
+ return server;
4046
+ }
3614
4047
  assertions() {
3615
4048
  return this.spec.assertions.map((a) => {
3616
4049
  const rows2 = this.state[a.service][a.path].filter((row) => !a.where || Object.entries(a.where).every(([k, v]) => isDeepStrictEqual(row[k], v)));
@@ -3647,11 +4080,12 @@ var init_http_world = __esm({
3647
4080
  this.epoch++;
3648
4081
  for (const timer of this.timers) clearTimeout(timer);
3649
4082
  this.timers.clear();
3650
- await Promise.all(this.servers.map((server) => new Promise((resolve6) => {
3651
- server.close(() => resolve6());
4083
+ await Promise.all(this.servers.map((server) => new Promise((resolve7) => {
4084
+ server.close(() => resolve7());
3652
4085
  server.closeAllConnections();
3653
4086
  })));
3654
4087
  this.servers.length = 0;
4088
+ await Promise.all(this.packRoots.splice(0).map((root) => rm2(root, { recursive: true, force: true })));
3655
4089
  }
3656
4090
  };
3657
4091
  }
@@ -3865,14 +4299,17 @@ function operationMatrix(spec) {
3865
4299
  schema: "agenttwin/contracts-v1",
3866
4300
  unsupported: { status: 501, marker: "X-AgentTwin-Unsupported", coverage: "incomplete", forwardedToProduction: false },
3867
4301
  adapters: CONTRACTS,
3868
- services: spec?.services.map((s) => ({
4302
+ services: spec?.services.map((s) => typeof s.adapter === "string" && s.adapter.startsWith("pack:") ? packContract(s.name, s.adapter) : {
3869
4303
  name: s.name,
3870
4304
  adapter: s.adapter ?? "json-collection",
3871
4305
  version: CONTRACTS[s.adapter ?? "json-collection"].version,
3872
4306
  operations: s.adapter === "slack" ? CONTRACTS.slack.operations : s.adapter === "stripe" ? CONTRACTS.stripe.operations : s.adapter && s.adapter !== "json-collection" ? CONTRACTS[s.adapter].operations : s.collections.flatMap((c) => CONTRACTS["json-collection"].operations.map((op2) => ({ ...op2, endpoint: c.path })))
3873
- })) ?? []
4307
+ }) ?? []
3874
4308
  };
3875
4309
  }
4310
+ function packContract(name, adapter) {
4311
+ return { name, adapter, version: "twin-pack", operations: [], pack: adapter.slice("pack:".length) };
4312
+ }
3876
4313
  var CONTRACTS;
3877
4314
  var init_contracts = __esm({
3878
4315
  "src/runtime/contracts.ts"() {
@@ -4130,11 +4567,21 @@ var init_contracts = __esm({
4130
4567
  }
4131
4568
  });
4132
4569
 
4570
+ // src/runtime/cost-model.ts
4571
+ import { readFile as readFile2, writeFile as writeFile3 } from "fs/promises";
4572
+ import { join as join5 } from "path";
4573
+ var init_cost_model = __esm({
4574
+ "src/runtime/cost-model.ts"() {
4575
+ "use strict";
4576
+ }
4577
+ });
4578
+
4133
4579
  // src/runtime/run-summary.ts
4134
4580
  var formatMoney;
4135
4581
  var init_run_summary = __esm({
4136
4582
  "src/runtime/run-summary.ts"() {
4137
4583
  "use strict";
4584
+ init_cost_model();
4138
4585
  formatMoney = (m) => new Intl.NumberFormat("en-US", { style: "currency", currency: m.currency.length === 3 ? m.currency : "USD" }).format(m.amount);
4139
4586
  }
4140
4587
  });
@@ -4793,6 +5240,373 @@ var init_default_checks = __esm({
4793
5240
  }
4794
5241
  });
4795
5242
 
5243
+ // src/runtime/twin-proxy.ts
5244
+ import { execFile } from "child_process";
5245
+ import { mkdtemp as mkdtemp3, readFile as readFile3, rm as rm3, writeFile as writeFile4 } from "fs/promises";
5246
+ import { createServer as createServer2, request as httpRequest } from "http";
5247
+ import { tmpdir as tmpdir3 } from "os";
5248
+ import { join as join6 } from "path";
5249
+ import { createSecureContext, TLSSocket } from "tls";
5250
+ import { promisify } from "util";
5251
+ function matchRoute(routes2, host, pathname) {
5252
+ host = host.toLowerCase().replace(/\.$/, "");
5253
+ let best;
5254
+ for (const r of routes2) {
5255
+ if (r.hostPattern) {
5256
+ try {
5257
+ if (!new RegExp(r.hostPattern, "i").test(host)) continue;
5258
+ } catch {
5259
+ continue;
5260
+ }
5261
+ } else if (r.host !== host && !(r.suffix && host.endsWith("." + r.host))) continue;
5262
+ if (r.pathPrefix && pathname !== r.pathPrefix && !pathname.startsWith(r.pathPrefix + "/")) continue;
5263
+ if (!best || (r.pathPrefix ?? "").length > (best.pathPrefix ?? "").length) best = r;
5264
+ }
5265
+ return best;
5266
+ }
5267
+ function rewrite(r, p) {
5268
+ if (r.strip && p.startsWith(r.strip)) p = p.slice(r.strip.length) || "/";
5269
+ if (r.add && !p.startsWith(r.add)) p = r.add + (p === "/" ? "" : p);
5270
+ return p;
5271
+ }
5272
+ async function runAuthority(dir) {
5273
+ const ca = { key: join6(dir, "ca.key"), cert: join6(dir, "ca.pem") };
5274
+ await run("openssl", [
5275
+ "req",
5276
+ "-x509",
5277
+ "-newkey",
5278
+ "ec",
5279
+ "-pkeyopt",
5280
+ "ec_paramgen_curve:prime256v1",
5281
+ "-nodes",
5282
+ "-keyout",
5283
+ ca.key,
5284
+ "-out",
5285
+ ca.cert,
5286
+ "-days",
5287
+ "2",
5288
+ "-subj",
5289
+ "/CN=AgentTwin run CA (this run only)",
5290
+ "-addext",
5291
+ "basicConstraints=critical,CA:TRUE",
5292
+ "-addext",
5293
+ "keyUsage=critical,keyCertSign,cRLSign",
5294
+ "-addext",
5295
+ "subjectKeyIdentifier=hash"
5296
+ ]);
5297
+ const contexts = /* @__PURE__ */ new Map();
5298
+ return {
5299
+ caFile: ca.cert,
5300
+ context(host) {
5301
+ let ctx = contexts.get(host);
5302
+ if (!ctx) {
5303
+ ctx = (async () => {
5304
+ const base = join6(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
5305
+ await writeFile4(base + ".ext", `basicConstraints=critical,CA:FALSE
5306
+ keyUsage=critical,digitalSignature
5307
+ extendedKeyUsage=serverAuth
5308
+ subjectAltName=DNS:${host}
5309
+ subjectKeyIdentifier=hash
5310
+ authorityKeyIdentifier=keyid,issuer
5311
+ `);
5312
+ await run("openssl", ["req", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", "-keyout", base + ".key", "-out", base + ".csr", "-subj", `/CN=${host}`]);
5313
+ await run("openssl", ["x509", "-req", "-in", base + ".csr", "-CA", ca.cert, "-CAkey", ca.key, "-set_serial", "0x" + Buffer.from(host).toString("hex").slice(0, 30).padEnd(16, "1"), "-days", "2", "-out", base + ".pem", "-extfile", base + ".ext"]);
5314
+ return createSecureContext({ key: await readFile3(base + ".key"), cert: await readFile3(base + ".pem") });
5315
+ })();
5316
+ contexts.set(host, ctx);
5317
+ }
5318
+ return ctx;
5319
+ }
5320
+ };
5321
+ }
5322
+ async function startTwinProxy(routes2) {
5323
+ const dir = await mkdtemp3(join6(tmpdir3(), "agenttwin-proxy-"));
5324
+ const authority = await runAuthority(dir).catch((error) => {
5325
+ throw new Error(`The twin proxy needs the openssl command to make this run's certificate authority: ${error instanceof Error ? error.message : error}`);
5326
+ });
5327
+ const blocked = [];
5328
+ const block = (kind, host, port, method) => {
5329
+ if (!blocked.some((b) => b.host === host && b.port === port) && blocked.length < 200) blocked.push({ kind, host, port, method, provider: null, reason: "unmapped-host" });
5330
+ };
5331
+ const forward = (req, res, host, path) => {
5332
+ const route = matchRoute(routes2, host, path.split("?")[0]);
5333
+ if (!route) {
5334
+ block("https", host, null, req.method ?? "GET");
5335
+ res.writeHead(403, { "content-type": "text/plain" });
5336
+ res.end(`AgentTwin blocked ${req.method} ${host}${path}: no twin serves it in this run; nothing was sent.
5337
+ `);
5338
+ return;
5339
+ }
5340
+ const target = new URL(route.target);
5341
+ const headers = {};
5342
+ const strip = route.auth === "passthrough" ? ["host", "proxy-connection", "proxy-authorization"] : SECRET;
5343
+ for (const [k, v] of Object.entries(req.headers)) if (v !== void 0 && !strip.includes(k)) headers[k] = v;
5344
+ if (route.auth === "passthrough") headers["x-agenttwin-token"] = route.token;
5345
+ else if (route.auth === "x-api-key") headers["x-api-key"] = route.token;
5346
+ else headers.authorization = `Bearer ${route.token}`;
5347
+ headers["x-agenttwin-original-host"] = host;
5348
+ const upstream = httpRequest({ host: target.hostname, port: target.port, method: req.method, path: (target.pathname.replace(/\/$/, "") || "") + rewrite(route, path), headers }, (answer) => {
5349
+ res.writeHead(answer.statusCode ?? 502, answer.headers);
5350
+ answer.pipe(res);
5351
+ });
5352
+ upstream.on("error", (error) => {
5353
+ if (!res.headersSent) res.writeHead(502, { "content-type": "text/plain" });
5354
+ res.end(`twin unavailable: ${error.message}
5355
+ `);
5356
+ });
5357
+ req.pipe(upstream);
5358
+ };
5359
+ const inner = createServer2((req, res) => forward(req, res, req.socket.twinHost ?? "", req.url ?? "/"));
5360
+ const server = createServer2((req, res) => {
5361
+ let url2;
5362
+ try {
5363
+ url2 = new URL(req.url ?? "");
5364
+ } catch {
5365
+ res.writeHead(400);
5366
+ res.end();
5367
+ return;
5368
+ }
5369
+ forward(req, res, url2.hostname, url2.pathname + url2.search);
5370
+ });
5371
+ server.on("connect", (req, socket, head) => {
5372
+ const [host, portText] = (req.url ?? "").split(":");
5373
+ const port = Number(portText) || 443;
5374
+ if (!host || !hostRouted(routes2, host.toLowerCase())) {
5375
+ block("https", host ?? "", port, "CONNECT");
5376
+ socket.end("HTTP/1.1 403 Forbidden\r\ncontent-type: text/plain\r\n\r\nAgentTwin: no twin serves this host in this run; nothing was sent.\n");
5377
+ return;
5378
+ }
5379
+ authority.context(host.toLowerCase()).then((secureContext) => {
5380
+ socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
5381
+ const tls = new TLSSocket(socket, { isServer: true, secureContext, ALPNProtocols: ["http/1.1"] });
5382
+ tls.twinHost = host.toLowerCase();
5383
+ if (head.length) socket.unshift(head);
5384
+ tls.on("error", () => socket.destroy());
5385
+ inner.emit("connection", tls);
5386
+ }, () => socket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n"));
5387
+ socket.on("error", () => {
5388
+ });
5389
+ });
5390
+ await new Promise((resolve7) => server.listen(0, "127.0.0.1", resolve7));
5391
+ const url = `http://127.0.0.1:${server.address().port}`;
5392
+ const env = {
5393
+ HTTPS_PROXY: url,
5394
+ HTTP_PROXY: url,
5395
+ https_proxy: url,
5396
+ http_proxy: url,
5397
+ ALL_PROXY: url,
5398
+ NO_PROXY: "",
5399
+ no_proxy: "",
5400
+ SSL_CERT_FILE: authority.caFile,
5401
+ REQUESTS_CA_BUNDLE: authority.caFile,
5402
+ CURL_CA_BUNDLE: authority.caFile,
5403
+ NODE_EXTRA_CA_CERTS: authority.caFile,
5404
+ GRPC_DEFAULT_SSL_ROOTS_FILE_PATH: authority.caFile,
5405
+ AGENTTWIN_PROXY: url
5406
+ };
5407
+ return {
5408
+ url,
5409
+ caFile: authority.caFile,
5410
+ env,
5411
+ blocked,
5412
+ async close() {
5413
+ await new Promise((resolve7) => {
5414
+ server.close(() => resolve7());
5415
+ server.closeAllConnections();
5416
+ });
5417
+ inner.closeAllConnections();
5418
+ await rm3(dir, { recursive: true, force: true });
5419
+ }
5420
+ };
5421
+ }
5422
+ var run, SECRET, hostRouted;
5423
+ var init_twin_proxy = __esm({
5424
+ "src/runtime/twin-proxy.ts"() {
5425
+ "use strict";
5426
+ run = promisify(execFile);
5427
+ SECRET = ["authorization", "x-api-key", "cookie", "proxy-authorization", "host", "proxy-connection"];
5428
+ hostRouted = (routes2, host) => routes2.some((r) => r.hostPattern ? (() => {
5429
+ try {
5430
+ return new RegExp(r.hostPattern, "i").test(host);
5431
+ } catch {
5432
+ return false;
5433
+ }
5434
+ })() : r.host === host || !!r.suffix && host.endsWith("." + r.host));
5435
+ }
5436
+ });
5437
+
5438
+ // src/runtime/twin-routing.ts
5439
+ import { mkdtemp as mkdtemp4, readFile as readFile4, rm as rm4, writeFile as writeFile5 } from "fs/promises";
5440
+ import { tmpdir as tmpdir4 } from "os";
5441
+ import { join as join7 } from "path";
5442
+ function twinRoutes(services, world, models) {
5443
+ const routes2 = [];
5444
+ for (const service of services) {
5445
+ const adapter = service.adapter ?? "", credential = world.credentials[service.name];
5446
+ if (credential && isPackAdapter(adapter)) {
5447
+ const record2 = packRecord(adapter.slice(PACK_PREFIX.length));
5448
+ const auth = record2.credentialDoor ? "bearer" : "passthrough";
5449
+ for (const h of record2.hosts) {
5450
+ const host = h.host ?? `pattern:${h.hostPattern}`;
5451
+ 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 });
5452
+ }
5453
+ continue;
5454
+ }
5455
+ if (!credential || !PROVIDER_HOSTS[adapter] || models && (adapter === "openai" || adapter === "anthropic")) continue;
5456
+ for (const entry of PROVIDER_HOSTS[adapter]) for (const host of entry.hosts) if (!routes2.some((r) => r.host === host && r.pathPrefix === entry.pathPrefix)) routes2.push({ host, ...entry.pathPrefix ? { pathPrefix: entry.pathPrefix } : {}, ...entry.strip ? { strip: entry.strip } : {}, ...entry.add ? { add: entry.add } : {}, target: credential.endpoint, token: credential.token, auth: entry.auth, service: service.name });
5457
+ }
5458
+ if (models) for (const provider of ["openai", "anthropic"]) for (const entry of PROVIDER_HOSTS[provider]) for (const host of entry.hosts) routes2.push({ host, target: models.targets[provider].endpoint, token: models.targets[provider].token, auth: entry.auth, service: `model:${provider}` });
5459
+ return routes2;
5460
+ }
5461
+ var PROVIDER_HOSTS, TWIN_PRELOAD;
5462
+ var init_twin_routing = __esm({
5463
+ "src/runtime/twin-routing.ts"() {
5464
+ "use strict";
5465
+ init_packs();
5466
+ PROVIDER_HOSTS = {
5467
+ // OpenAI-compatible APIs answer in the same format, so they are served by the OpenAI twin (with its scripted tool calls).
5468
+ openai: [
5469
+ { hosts: ["api.openai.com", "api.mistral.ai", "api.together.xyz", "api.x.ai", "api.cerebras.ai", "api.sambanova.ai", "integrate.api.nvidia.com", "api.moonshot.ai"], auth: "bearer" },
5470
+ { hosts: ["api.groq.com"], pathPrefix: "/openai", strip: "/openai", auth: "bearer" },
5471
+ { hosts: ["openrouter.ai"], pathPrefix: "/api", strip: "/api", auth: "bearer" },
5472
+ { hosts: ["api.fireworks.ai"], pathPrefix: "/inference", strip: "/inference", auth: "bearer" },
5473
+ { hosts: ["api.deepseek.com", "api.perplexity.ai"], add: "/v1", auth: "bearer" }
5474
+ ],
5475
+ anthropic: [{ hosts: ["api.anthropic.com"], auth: "x-api-key" }],
5476
+ stripe: [{ hosts: ["api.stripe.com", "files.stripe.com"], auth: "bearer" }],
5477
+ slack: [{ hosts: ["slack.com", "www.slack.com"], auth: "bearer" }],
5478
+ gmail: [{ hosts: ["gmail.googleapis.com"], auth: "bearer" }, { hosts: ["www.googleapis.com"], pathPrefix: "/gmail", auth: "bearer" }],
5479
+ "google-calendar": [{ hosts: ["www.googleapis.com"], pathPrefix: "/calendar", auth: "bearer" }],
5480
+ "google-oauth": [{ hosts: ["oauth2.googleapis.com"], auth: "bearer" }],
5481
+ github: [{ hosts: ["api.github.com"], auth: "bearer" }],
5482
+ linear: [{ hosts: ["api.linear.app"], auth: "bearer" }],
5483
+ notion: [{ hosts: ["api.notion.com"], auth: "bearer" }],
5484
+ hubspot: [{ hosts: ["api.hubapi.com"], auth: "bearer" }],
5485
+ twilio: [{ hosts: ["api.twilio.com"], auth: "bearer" }]
5486
+ };
5487
+ TWIN_PRELOAD = String.raw`'use strict';
5488
+ if(process.env.AGENTTWIN==='1'&&!globalThis.__agenttwinRouting){(()=>{
5489
+ const fs=require('node:fs'),http=require('node:http'),https=require('node:https'),net=require('node:net'),path=require('node:path'),{fileURLToPath}=require('node:url');
5490
+ let config={};try{config=JSON.parse(process.env.AGENTTWIN_ROUTES||'{}');}catch{}
5491
+ const tcp=Array.isArray(config.tcp)?config.tcp:[],routes=Array.isArray(config.routes)?config.routes:[],providers=config.providers||{},out=process.env.AGENTTWIN_VIOLATIONS,files=new Set(config.files||[]);
5492
+ globalThis.__agenttwinRouting={routes:routes.length};
5493
+ let realRoot=config.root;try{realRoot=fs.realpathSync(config.root);}catch{}
5494
+ const seen=new Set();
5495
+ const bare=h=>String(h||'').toLowerCase().replace(/^\[|\]$/g,'');
5496
+ const tcpRoute=(h,p)=>{h=bare(h);return tcp.find(r=>r.host===h&&(!r.port||Number(r.port)===Number(p)));};
5497
+ const loopback=h=>{h=bare(h);return h===''||h==='localhost'||h.endsWith('.localhost')||h==='::1'||h==='0:0:0:0:0:0:0:1'||/^127\./.test(h)||/^::ffff:127\./.test(h);};
5498
+ const providerOf=h=>{for(const [suffix,name] of Object.entries(providers))if(h===suffix||h.endsWith('.'+suffix))return name;return null;};
5499
+ function blocked(kind,host,port,method){
5500
+ host=bare(host);const provider=providerOf(host),key=kind+' '+host+':'+port+' '+method;
5501
+ if(!seen.has(key)&&seen.size<200){seen.add(key);if(out)try{fs.appendFileSync(out,JSON.stringify({kind,host:host.slice(0,253),port:Number(port)||null,method:String(method).slice(0,16),provider,reason:provider?'provider-without-twin':'unmapped-host'})+'\n');}catch{}}
5502
+ const error=new Error('AgentTwin blocked '+(kind==='socket'?'a connection':method+' '+kind)+' to '+host+(provider?' ('+provider+' has no twin in this run)':'')+'; nothing was sent');error.code='AGENTTWIN_BLOCKED';return error;
5503
+ }
5504
+ const patterns=new Map();const patternOf=r=>{if(!patterns.has(r.hostPattern)){let re=null;try{re=new RegExp(r.hostPattern,'i');}catch{}patterns.set(r.hostPattern,re);}return patterns.get(r.hostPattern);};
5505
+ function match(host,pathname){host=bare(host);let best;for(const r of routes){if(r.hostPattern?!patternOf(r)?.test(host):r.host!==host&&!(r.suffix&&host.endsWith('.'+r.host)))continue;if(r.pathPrefix&&pathname!==r.pathPrefix&&!pathname.startsWith(r.pathPrefix+'/'))continue;if(!best||(r.pathPrefix||'').length>(best.pathPrefix||'').length)best=r;}return best;}
5506
+ function source(){if(!files.size)return;for(const frame of new Error().stack.split('\n').slice(2)){const m=frame.match(/(?:\(|\s)(file:\/\/[^\s)]+|\/[^\s)]+):(\d+):(\d+)\)?$/);if(!m)continue;let file;try{file=m[1].startsWith('file:')?fileURLToPath(m[1]):m[1];}catch{continue;}const given=file;file=path.relative(config.root,given);if(!files.has(file))file=path.relative(realRoot,given);if(files.has(file))return JSON.stringify({file,line:Number(m[2]),column:Number(m[3])});}}
5507
+ const SECRET=['authorization','x-api-key','cookie','proxy-authorization','host'];
5508
+ function rewrite(r,p){if(r.strip&&p.startsWith(r.strip))p=p.slice(r.strip.length)||'/';if(r.add&&!p.startsWith(r.add))p=r.add+(p==='/'?'':p);return p;}
5509
+ function credential(r){return r.auth==='passthrough'?['x-agenttwin-token',r.token]:r.auth==='x-api-key'?['x-api-key',r.token]:['authorization','Bearer '+r.token];}
5510
+ const removed=r=>r.auth==='passthrough'?['host']:SECRET;
5511
+ const originalFetch=globalThis.fetch;
5512
+ if(originalFetch)globalThis.fetch=async function(input,init){
5513
+ let url;try{url=new URL(typeof input==='string'||input instanceof URL?String(input):input.url);}catch{return originalFetch(input,init);}
5514
+ if((url.protocol!=='http:'&&url.protocol!=='https:')||loopback(url.hostname))return originalFetch(input,init);
5515
+ const method=String(init?.method||input?.method||'GET').toUpperCase(),r=match(url.hostname,url.pathname);
5516
+ if(!r)throw blocked('fetch',url.hostname,url.port||(url.protocol==='https:'?443:80),method);
5517
+ if(process.env.AGENTTWIN_DEBUG_ROUTES)console.error('route-match '+url.hostname+' auth='+r.auth+' service='+r.service);
5518
+ const request=new Request(input,init),headers=new Headers(request.headers);
5519
+ for(const name of removed(r))headers.delete(name);const [name,value]=credential(r);headers.set(name,value);
5520
+ headers.set('x-agenttwin-original-host',url.hostname);const location=source();if(location)headers.set('x-agenttwin-source',location);
5521
+ return originalFetch(new Request(r.target+rewrite(r,url.pathname)+url.search,request),{headers,redirect:'manual'});
5522
+ };
5523
+ const originalHttpRequest=http.request;
5524
+ for(const [mod,scheme] of [[http,'http'],[https,'https']]){
5525
+ const original=mod.request;
5526
+ mod.request=function(...args){
5527
+ let url,options={},i=0;
5528
+ if(typeof args[0]==='string'||args[0] instanceof URL){url=new URL(String(args[0]));i=1;}
5529
+ if(args[i]&&typeof args[i]==='object')options=args[i];
5530
+ const callback=args.find(a=>typeof a==='function');
5531
+ if(options.socketPath)return original.apply(this,args);
5532
+ const host=url?url.hostname:(options.hostname||String(options.host||'localhost').replace(/:\d+$/,''));
5533
+ if(loopback(host))return original.apply(this,args);
5534
+ const method=String(options.method||'GET').toUpperCase(),requestPath=options.path||(url?url.pathname+url.search:'/');
5535
+ const r=match(host,String(requestPath).split('?')[0]);
5536
+ if(!r)throw blocked(scheme,host,options.port||url?.port||(scheme==='https'?443:80),method);
5537
+ const target=new URL(r.target),headers={};
5538
+ const given=options.headers||{};
5539
+ for(const [k,v] of Array.isArray(given)?[]:Object.entries(given))if(!removed(r).includes(k.toLowerCase()))headers[k]=v;
5540
+ const [name,value]=credential(r);headers[name]=value;headers.host=target.host;headers['x-agenttwin-original-host']=host;
5541
+ const location=source();if(location)headers['x-agenttwin-source']=location;
5542
+ 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;
5543
+ const routed={...rest,method,protocol:target.protocol,hostname:target.hostname,port:target.port,path:target.pathname.replace(/\/$/,'')+rewrite(r,String(requestPath).split('?')[0])+(String(requestPath).includes('?')?'?'+String(requestPath).split('?').slice(1).join('?'):''),headers};
5544
+ const req=callback?originalHttpRequest(routed,callback):originalHttpRequest(routed);
5545
+ // The twin speaks plain HTTP. Clients that wait for the TLS handshake before writing (stripe-node writes
5546
+ // its body on 'secureConnect') would otherwise never send it; signal the handshake on connect.
5547
+ if(scheme==='https')req.once('socket',socket=>{if(socket.connecting)socket.once('connect',()=>socket.emit('secureConnect'));else socket.emit('secureConnect');});
5548
+ return req;
5549
+ };
5550
+ mod.get=function(...args){const req=mod.request(...args);req.end();return req;};
5551
+ }
5552
+ const dns=require('node:dns');
5553
+ // Every public name resolves to a reserved sinkhole address (198.18.0.0/15, not routable) that remembers its name. A connection to
5554
+ // it is mapped back to the name: routed to an engine when a TCP route exists, otherwise blocked and reported by name so the run can learn it.
5555
+ const fakeByIp=new Map(),fakeByName=new Map();
5556
+ const isIp=h=>/^\d+\.\d+\.\d+\.\d+$/.test(h)||h.includes(':');
5557
+ const addressFor=h=>{h=bare(h);if(!h||isIp(h)||loopback(h))return undefined;let ip=fakeByName.get(h);if(!ip){const n=fakeByName.size+1;ip='198.18.'+(n>>8&1)+'.'+(n&255);fakeByName.set(h,ip);fakeByIp.set(ip,h);}return ip;};
5558
+ {
5559
+ const lookup=dns.lookup;dns.lookup=function(h,o,cb){if(typeof o==='function'){cb=o;o={};}const ip=addressFor(h);if(ip)return process.nextTick(()=>o&&o.all?cb(null,[{address:ip,family:4}]):cb(null,ip,4));return lookup.apply(this,arguments);};
5560
+ const plookup=dns.promises.lookup;dns.promises.lookup=function(h,o){const ip=addressFor(h);if(ip)return Promise.resolve(o&&o.all?[{address:ip,family:4}]:{address:ip,family:4});return plookup.apply(this,arguments);};
5561
+ for(const name of ['resolve','resolve4']){const orig=dns[name];dns[name]=function(h,...rest){const cb=rest.pop(),ip=addressFor(h);if(ip&&typeof cb==='function')return process.nextTick(()=>cb(null,[ip]));return orig.apply(this,[h,...rest,cb]);};const porig=dns.promises[name];dns.promises[name]=function(h,...rest){const ip=addressFor(h);if(ip)return Promise.resolve([ip]);return porig.apply(this,[h,...rest]);};}
5562
+ }
5563
+ const http2=require('node:http2'),originalHttp2Connect=http2.connect;
5564
+ http2.connect=function(authority,...rest){
5565
+ let host;try{host=new URL(typeof authority==='string'?authority:authority.href).hostname;}catch{}
5566
+ if(!host||loopback(host))return originalHttp2Connect.apply(this,arguments);
5567
+ const r=match(host,'/');
5568
+ if(r&&r.h2target){const options=rest[0]&&typeof rest[0]==='object'?{...rest[0]}:{};delete options.createConnection;return originalHttp2Connect.call(this,r.h2target,options,...rest.filter(a=>typeof a==='function'));}
5569
+ throw blocked('http2',host,443,'CONNECT');
5570
+ };
5571
+ const tlsModule=require('node:tls'),originalTlsConnect=tlsModule.connect;
5572
+ tlsModule.connect=function(...args){
5573
+ let o=args[0];if(!o||typeof o!=='object'||Array.isArray(o))o={port:args[0],host:typeof args[1]==='string'?args[1]:undefined};
5574
+ const given=o.host||o.servername;
5575
+ if(!given||loopback(given))return originalTlsConnect.apply(this,args);
5576
+ const name=fakeByIp.get(given)||given,route=tcpRoute(name,o.port||443);
5577
+ if(!route||!route.http)return originalTlsConnect.apply(this,args);
5578
+ // A routed HTTP service: speak plain HTTP to the twin and present the socket as secure. The Host header says which service it is.
5579
+ const socket=net.connect({host:'127.0.0.1',port:route.targetPort});
5580
+ socket.encrypted=true;socket.authorized=true;socket.alpnProtocol=false;
5581
+ const done=args.find(a=>typeof a==='function');if(done)socket.once('secureConnect',done);
5582
+ socket.once('connect',()=>socket.emit('secureConnect'));
5583
+ return socket;
5584
+ };
5585
+ const originalConnect=net.Socket.prototype.connect;
5586
+ net.Socket.prototype.connect=function(...args){
5587
+ let options=args[0];if(Array.isArray(options))options=options[0];
5588
+ let host,port;
5589
+ if(options&&typeof options==='object'){if(options.path)return originalConnect.apply(this,args);host=options.host;port=options.port;}
5590
+ else if(typeof options==='string'&&!/^\d+$/.test(options))return originalConnect.apply(this,args);
5591
+ else{port=options;host=typeof args[1]==='string'?args[1]:undefined;}
5592
+ if(host===undefined||loopback(host))return originalConnect.apply(this,args);
5593
+ host=fakeByIp.get(host)||host;
5594
+ const t=tcpRoute(host,port);
5595
+ if(t){
5596
+ // net.connect passes a normalized [options, callback] array (marked with an internal symbol); keep its shape so the connect callback survives.
5597
+ if(Array.isArray(args[0])){const n=args[0],c=n.slice();for(const sym of Object.getOwnPropertySymbols(n))c[sym]=n[sym];c[0]={...n[0],host:'127.0.0.1',port:t.targetPort};args[0]=c;}
5598
+ else if(options&&typeof options==='object')args[0]={...options,host:'127.0.0.1',port:t.targetPort};
5599
+ else{args[0]=t.targetPort;args[1]='127.0.0.1';}
5600
+ return originalConnect.apply(this,args);
5601
+ }
5602
+ const error=blocked('socket',host,port,'CONNECT');process.nextTick(()=>this.destroy(error));return this;
5603
+ };
5604
+ require('node:module').syncBuiltinESMExports();
5605
+ })();}
5606
+ `;
5607
+ }
5608
+ });
5609
+
4796
5610
  // src/runtime/local.ts
4797
5611
  import { spawn } from "child_process";
4798
5612
  async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {}) {
@@ -4803,14 +5617,22 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
4803
5617
  try {
4804
5618
  const credentials = existingWorld ? world.credentials : await world.start();
4805
5619
  const initialState = world.snapshot();
4806
- const env = { ...extraEnv, PATH: process.env.PATH ?? "", NODE_ENV: "test" };
5620
+ const env = { ...Object.assign({}, ...Object.values(world.packEnv)), ...extraEnv, PATH: process.env.PATH ?? "", NODE_ENV: "test" };
4807
5621
  for (const [name, c] of Object.entries(credentials)) {
4808
5622
  env[`AGENTTWIN_${name.toUpperCase()}_URL`] = c.endpoint;
4809
5623
  env[`AGENTTWIN_${name.toUpperCase()}_TOKEN`] = c.token;
4810
5624
  }
4811
5625
  let stdout = "", stderr = "", timedOut = false;
4812
5626
  const hook = await createRequestSourceHook(app, spec, credentials);
4813
- const child = spawn(process.execPath, ["--require", hook.path, ...spec.command.slice(1)], { cwd: app, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" });
5627
+ const node = /(^|\/)node(\.exe)?$/.test(spec.command[0]);
5628
+ let proxy;
5629
+ if (!node) {
5630
+ const configured = extraEnv.AGENTTWIN_ROUTES ? JSON.parse(extraEnv.AGENTTWIN_ROUTES).routes : void 0;
5631
+ proxy = await startTwinProxy(configured ?? twinRoutes(spec.services, { credentials, packEnv: world.packEnv }));
5632
+ Object.assign(env, proxy.env, { HOME: process.env.HOME ?? "", LANG: process.env.LANG ?? "C.UTF-8", PYTHONUNBUFFERED: "1", PYTHONDONTWRITEBYTECODE: "1" });
5633
+ if (process.env.VIRTUAL_ENV) env.VIRTUAL_ENV = process.env.VIRTUAL_ENV;
5634
+ }
5635
+ const child = node ? spawn(process.execPath, ["--require", hook.path, ...spec.command.slice(1)], { cwd: app, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" }) : spawn(spec.command[0], spec.command.slice(1), { cwd: app, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" });
4814
5636
  child.stdout.on("data", (b) => {
4815
5637
  stdout = (stdout + b.toString()).slice(-65536);
4816
5638
  });
@@ -4836,9 +5658,9 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
4836
5658
  executionAbort.abort();
4837
5659
  kill();
4838
5660
  }, spec.timeoutSeconds * 1e3);
4839
- const completion = new Promise((resolve6, reject) => {
5661
+ const completion = new Promise((resolve7, reject) => {
4840
5662
  child.once("error", reject);
4841
- child.once("close", resolve6);
5663
+ child.once("close", resolve7);
4842
5664
  });
4843
5665
  let browser, background, executionError;
4844
5666
  let exitCode;
@@ -4869,6 +5691,10 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
4869
5691
  blockedFetches = await hook.readViolations();
4870
5692
  } finally {
4871
5693
  await hook.close();
5694
+ if (proxy) {
5695
+ blockedFetches.push(...proxy.blocked.map((b) => ({ origin: `https://${b.host}${b.port && b.port !== 443 ? `:${b.port}` : ""}`, reason: "no twin serves this host; blocked by the twin proxy before anything was sent" })));
5696
+ await proxy.close();
5697
+ }
4872
5698
  }
4873
5699
  }
4874
5700
  signal?.throwIfAborted();
@@ -4897,13 +5723,15 @@ var init_local = __esm({
4897
5723
  init_evaluation();
4898
5724
  init_contracts();
4899
5725
  init_default_checks();
5726
+ init_twin_proxy();
5727
+ init_twin_routing();
4900
5728
  }
4901
5729
  });
4902
5730
 
4903
5731
  // src/runtime/scenarios.ts
4904
5732
  import { createHash as createHash7 } from "crypto";
4905
- import { mkdir, readFile as readFile2, readdir, writeFile as writeFile2 } from "fs/promises";
4906
- import { join as join2 } from "path";
5733
+ import { mkdir as mkdir2, readFile as readFile5, readdir, writeFile as writeFile6 } from "fs/promises";
5734
+ import { join as join8 } from "path";
4907
5735
  import { isDeepStrictEqual as isDeepStrictEqual4 } from "util";
4908
5736
  function parseScenario(value) {
4909
5737
  const fail = (detail) => {
@@ -4942,8 +5770,8 @@ function reference(ref) {
4942
5770
  }
4943
5771
  async function loadScenario(cwd, ref) {
4944
5772
  const { id, version } = reference(ref);
4945
- const path = join2(cwd, ".agenttwin/scenarios", id, `${version}.json`);
4946
- const bytes = await readFile2(path);
5773
+ const path = join8(cwd, ".agenttwin/scenarios", id, `${version}.json`);
5774
+ const bytes = await readFile5(path);
4947
5775
  if (bytes.length > 2 * 1024 * 1024) throw new Error("Scenario exceeds 2 MiB");
4948
5776
  const scenario = parseScenario(JSON.parse(bytes.toString()));
4949
5777
  if (scenario.id !== id || scenario.version !== version) throw new Error("Scenario identity does not match its stored version");
@@ -4966,10 +5794,17 @@ var init_scenarios = __esm({
4966
5794
  }
4967
5795
  });
4968
5796
 
5797
+ // src/lib/offline.ts
5798
+ var init_offline = __esm({
5799
+ "src/lib/offline.ts"() {
5800
+ "use strict";
5801
+ }
5802
+ });
5803
+
4969
5804
  // src/runtime/credentials.ts
4970
5805
  import { homedir } from "os";
4971
- import { join as join3 } from "path";
4972
- import { readFile as readFile3, mkdir as mkdir2, writeFile as writeFile3, chmod, rm as rm2 } from "fs/promises";
5806
+ import { join as join9 } from "path";
5807
+ import { readFile as readFile6, mkdir as mkdir3, writeFile as writeFile7, chmod, rm as rm5 } from "fs/promises";
4973
5808
  var init_credentials = __esm({
4974
5809
  "src/runtime/credentials.ts"() {
4975
5810
  "use strict";
@@ -5003,31 +5838,32 @@ var init_exit = __esm({
5003
5838
  });
5004
5839
 
5005
5840
  // src/runtime/remote.ts
5006
- import { readFile as readFile4 } from "fs/promises";
5007
- import { join as join4 } from "path";
5841
+ import { readFile as readFile7 } from "fs/promises";
5842
+ import { join as join10 } from "path";
5008
5843
  var init_remote = __esm({
5009
5844
  "src/runtime/remote.ts"() {
5010
5845
  "use strict";
5846
+ init_offline();
5011
5847
  init_credentials();
5012
5848
  init_exit();
5013
5849
  }
5014
5850
  });
5015
5851
 
5016
5852
  // src/runtime/docker-engine.ts
5017
- import { execFile } from "child_process";
5018
- import { promisify } from "util";
5853
+ import { execFile as execFile2 } from "child_process";
5854
+ import { promisify as promisify2 } from "util";
5019
5855
  var exec;
5020
5856
  var init_docker_engine = __esm({
5021
5857
  "src/runtime/docker-engine.ts"() {
5022
5858
  "use strict";
5023
- exec = promisify(execFile);
5859
+ exec = promisify2(execFile2);
5024
5860
  }
5025
5861
  });
5026
5862
 
5027
5863
  // src/runtime/docker-postgres.ts
5028
5864
  import postgres from "postgres";
5029
- import { execFile as execFile2, spawn as spawn2 } from "child_process";
5030
- import { promisify as promisify2, isDeepStrictEqual as isDeepStrictEqual5 } from "util";
5865
+ import { execFile as execFile3, spawn as spawn2 } from "child_process";
5866
+ import { promisify as promisify3, isDeepStrictEqual as isDeepStrictEqual5 } from "util";
5031
5867
  import { randomBytes as randomBytes2, randomUUID } from "crypto";
5032
5868
  import { Duplex } from "stream";
5033
5869
  var exec2;
@@ -5036,7 +5872,7 @@ var init_docker_postgres = __esm({
5036
5872
  "use strict";
5037
5873
  init_docker_engine();
5038
5874
  init_postgres_clock();
5039
- exec2 = promisify2(execFile2);
5875
+ exec2 = promisify3(execFile3);
5040
5876
  }
5041
5877
  });
5042
5878
 
@@ -5050,11 +5886,11 @@ var init_stdio_fetch = __esm({
5050
5886
  });
5051
5887
 
5052
5888
  // src/runtime/docker.ts
5053
- import { execFile as execFile3, spawn as spawn3 } from "child_process";
5054
- import { promisify as promisify3 } from "util";
5055
- import { chmod as chmod2, copyFile, mkdir as mkdir3, mkdtemp as mkdtemp2, readFile as readFile5, rm as rm3, writeFile as writeFile4 } from "fs/promises";
5056
- import { tmpdir as tmpdir2 } from "os";
5057
- import { join as join5 } from "path";
5889
+ import { execFile as execFile4, spawn as spawn3 } from "child_process";
5890
+ import { promisify as promisify4 } from "util";
5891
+ import { chmod as chmod2, copyFile, mkdir as mkdir4, mkdtemp as mkdtemp5, readFile as readFile8, rm as rm6, writeFile as writeFile8 } from "fs/promises";
5892
+ import { tmpdir as tmpdir5 } from "os";
5893
+ import { join as join11 } from "path";
5058
5894
  import { randomUUID as randomUUID2 } from "crypto";
5059
5895
  var exec3;
5060
5896
  var init_docker = __esm({
@@ -5070,15 +5906,15 @@ var init_docker = __esm({
5070
5906
  init_application_clock();
5071
5907
  init_docker_engine();
5072
5908
  init_docker_engine();
5073
- exec3 = promisify3(execFile3);
5909
+ exec3 = promisify4(execFile4);
5074
5910
  }
5075
5911
  });
5076
5912
 
5077
5913
  // src/runtime/git.ts
5078
- import { execFile as execFile4 } from "child_process";
5079
- import { promisify as promisify4 } from "util";
5914
+ import { execFile as execFile5 } from "child_process";
5915
+ import { promisify as promisify5 } from "util";
5080
5916
  async function captureGit(cwd, previousHead) {
5081
- const exec4 = promisify4(execFile4);
5917
+ const exec4 = promisify5(execFile5);
5082
5918
  const git = async (...args) => (await exec4("git", args, { cwd, timeout: 5e3, maxBuffer: 1024 * 1024 })).stdout.trim();
5083
5919
  try {
5084
5920
  const head = await git("rev-parse", "HEAD");
@@ -5106,10 +5942,10 @@ var init_git = __esm({
5106
5942
  });
5107
5943
 
5108
5944
  // src/runtime/e2b.ts
5109
- import { readFile as readFile6 } from "fs/promises";
5945
+ import { readFile as readFile9 } from "fs/promises";
5110
5946
  import { randomBytes as randomBytes3 } from "crypto";
5111
5947
  import { homedir as homedir2 } from "os";
5112
- import { join as join6 } from "path";
5948
+ import { join as join12 } from "path";
5113
5949
  var init_e2b = __esm({
5114
5950
  "src/runtime/e2b.ts"() {
5115
5951
  "use strict";
@@ -5119,8 +5955,8 @@ var init_e2b = __esm({
5119
5955
 
5120
5956
  // src/runtime/matrix.ts
5121
5957
  import { createHash as createHash8 } from "crypto";
5122
- import { mkdir as mkdir4, readFile as readFile7, writeFile as writeFile5 } from "fs/promises";
5123
- import { join as join7, relative, resolve as resolve2 } from "path";
5958
+ import { mkdir as mkdir5, readFile as readFile10, writeFile as writeFile9 } from "fs/promises";
5959
+ import { join as join13, relative, resolve as resolve3 } from "path";
5124
5960
  var init_matrix = __esm({
5125
5961
  "src/runtime/matrix.ts"() {
5126
5962
  "use strict";
@@ -5132,8 +5968,8 @@ var init_matrix = __esm({
5132
5968
 
5133
5969
  // src/runtime/source-build.ts
5134
5970
  import { createHash as createHash9 } from "crypto";
5135
- import { lstat, readFile as readFile8, realpath as realpath2 } from "fs/promises";
5136
- import { isAbsolute, join as join8, relative as relative2, resolve as resolve3, sep } from "path";
5971
+ import { lstat, readFile as readFile11, realpath as realpath2 } from "fs/promises";
5972
+ import { isAbsolute, join as join14, relative as relative2, resolve as resolve4, sep } from "path";
5137
5973
  import { isDeepStrictEqual as isDeepStrictEqual6 } from "util";
5138
5974
  var init_source_build = __esm({
5139
5975
  "src/runtime/source-build.ts"() {
@@ -5143,10 +5979,10 @@ var init_source_build = __esm({
5143
5979
  });
5144
5980
 
5145
5981
  // src/commands/run.ts
5146
- import { mkdtemp as mkdtemp3, mkdir as mkdir5, readFile as readFile9, writeFile as writeFile6, realpath as realpath3, lstat as lstat2, rm as rm4, copyFile as copyFile2 } from "fs/promises";
5147
- import { tmpdir as tmpdir3 } from "os";
5148
- import { basename, dirname, isAbsolute as isAbsolute2, join as join9, relative as relative3, resolve as resolve4, sep as sep2 } from "path";
5149
- import { fileURLToPath } from "url";
5982
+ import { mkdtemp as mkdtemp6, mkdir as mkdir6, readFile as readFile12, writeFile as writeFile10, realpath as realpath3, lstat as lstat2, rm as rm7, copyFile as copyFile2 } from "fs/promises";
5983
+ import { tmpdir as tmpdir6 } from "os";
5984
+ import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join15, relative as relative3, resolve as resolve5, sep as sep2 } from "path";
5985
+ import { fileURLToPath as fileURLToPath2 } from "url";
5150
5986
  import { createHash as createHash10, randomUUID as randomUUID3 } from "crypto";
5151
5987
  async function stageApplication(root, files, destination) {
5152
5988
  const canonicalRoot = await realpath3(root);
@@ -5154,15 +5990,15 @@ async function stageApplication(root, files, destination) {
5154
5990
  let bytes = 0;
5155
5991
  for (const file of files) {
5156
5992
  if (isAbsolute2(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 });
5157
- const source = await realpath3(resolve4(canonicalRoot, file));
5993
+ const source = await realpath3(resolve5(canonicalRoot, file));
5158
5994
  const rel = relative3(canonicalRoot, source);
5159
- if (rel.startsWith(`..${sep2}`) || rel === ".." || isAbsolute2(rel) || source !== resolve4(canonicalRoot, file) || !(await lstat2(source)).isFile()) throw new CliError(`Files must be regular files within the project, without symlinks: ${file}`, { code: EXIT.USAGE });
5160
- const contents = await readFile9(source);
5995
+ if (rel.startsWith(`..${sep2}`) || rel === ".." || isAbsolute2(rel) || source !== resolve5(canonicalRoot, file) || !(await lstat2(source)).isFile()) throw new CliError(`Files must be regular files within the project, without symlinks: ${file}`, { code: EXIT.USAGE });
5996
+ const contents = await readFile12(source);
5161
5997
  bytes += contents.length;
5162
5998
  if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
5163
- const target = join9(destination, file);
5164
- await mkdir5(dirname(target), { recursive: true });
5165
- await writeFile6(target, contents, { mode: 420 });
5999
+ const target = join15(destination, file);
6000
+ await mkdir6(dirname2(target), { recursive: true });
6001
+ await writeFile10(target, contents, { mode: 420 });
5166
6002
  digests[file] = createHash10("sha256").update(contents).digest("hex");
5167
6003
  }
5168
6004
  return digests;
@@ -5171,6 +6007,7 @@ var init_run = __esm({
5171
6007
  "src/commands/run.ts"() {
5172
6008
  "use strict";
5173
6009
  init_run_summary();
6010
+ init_cost_model();
5174
6011
  init_remote();
5175
6012
  init_local();
5176
6013
  init_docker();
@@ -5193,12 +6030,12 @@ init_scenarios();
5193
6030
  init_contracts();
5194
6031
  init_run();
5195
6032
  init_git();
5196
- import { createServer as createServer2 } from "http";
6033
+ import { createServer as createServer3 } from "http";
5197
6034
  import { randomBytes as randomBytes4, randomUUID as randomUUID4, createHash as createHash11 } from "crypto";
5198
- import { mkdir as mkdir6, mkdtemp as mkdtemp4, readFile as readFile10, readdir as readdir2, rename, rm as rm5, writeFile as writeFile7 } from "fs/promises";
5199
- import { dirname as dirname2, join as join10, resolve as resolve5, relative as relative4, sep as sep3 } from "path";
5200
- import { tmpdir as tmpdir4 } from "os";
5201
- import { fileURLToPath as fileURLToPath2 } from "url";
6035
+ import { mkdir as mkdir7, mkdtemp as mkdtemp7, readFile as readFile13, readdir as readdir2, rename, rm as rm8, writeFile as writeFile11 } from "fs/promises";
6036
+ import { dirname as dirname3, join as join16, resolve as resolve6, relative as relative4, sep as sep3 } from "path";
6037
+ import { tmpdir as tmpdir7 } from "os";
6038
+ import { fileURLToPath as fileURLToPath3 } from "url";
5202
6039
  import { spawn as spawn4 } from "child_process";
5203
6040
  var uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
5204
6041
  var hash2 = (spec) => createHash11("sha256").update(JSON.stringify(spec)).digest("hex");
@@ -5207,15 +6044,15 @@ function duration(value) {
5207
6044
  return value;
5208
6045
  }
5209
6046
  async function persist(directory2, session) {
5210
- const temporary = join10(directory2, `${randomUUID4()}.tmp`);
5211
- await writeFile7(temporary, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
5212
- await rename(temporary, join10(directory2, "session.json"));
6047
+ const temporary = join16(directory2, `${randomUUID4()}.tmp`);
6048
+ await writeFile11(temporary, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
6049
+ await rename(temporary, join16(directory2, "session.json"));
5213
6050
  }
5214
6051
  var view = ({ controlToken: _token, cwd: _cwd, file: _file, controlUrl: _control, ...session }) => session;
5215
6052
  async function serveWorldSession(directory2) {
5216
- const session = JSON.parse(await readFile10(join10(directory2, "session.json"), "utf8"));
6053
+ const session = JSON.parse(await readFile13(join16(directory2, "session.json"), "utf8"));
5217
6054
  if (session.status !== "provisioning" || !uuid.test(session.id)) throw new Error("Session is not awaiting provisioning");
5218
- const spec = parseWorld(JSON.parse(await readFile10(join10(directory2, "world.json"), "utf8")));
6055
+ const spec = parseWorld(JSON.parse(await readFile13(join16(directory2, "world.json"), "utf8")));
5219
6056
  const world = new HttpWorld(spec);
5220
6057
  let control;
5221
6058
  let timer;
@@ -5240,8 +6077,8 @@ async function serveWorldSession(directory2) {
5240
6077
  session.status = status;
5241
6078
  session.credentials = void 0;
5242
6079
  await world.close();
5243
- if (control) await new Promise((resolve6) => {
5244
- control.close(() => resolve6());
6080
+ if (control) await new Promise((resolve7) => {
6081
+ control.close(() => resolve7());
5245
6082
  control.closeAllConnections();
5246
6083
  });
5247
6084
  await save();
@@ -5256,7 +6093,7 @@ async function serveWorldSession(directory2) {
5256
6093
  };
5257
6094
  try {
5258
6095
  session.credentials = await world.start();
5259
- control = createServer2(async (req, res) => {
6096
+ control = createServer3(async (req, res) => {
5260
6097
  const reply = (status, value) => {
5261
6098
  if (!res.destroyed) {
5262
6099
  res.writeHead(status, { "content-type": "application/json" });
@@ -5315,10 +6152,10 @@ async function serveWorldSession(directory2) {
5315
6152
  reply(200, { ...view(session), state: world.snapshot() });
5316
6153
  return;
5317
6154
  }
5318
- let current = parseWorld(JSON.parse(await readFile10(session.file, "utf8")));
6155
+ let current = parseWorld(JSON.parse(await readFile13(session.file, "utf8")));
5319
6156
  if (session.scenario) current = applyScenario(current, await loadScenario(session.cwd, session.scenario));
5320
6157
  if (hash2(current) !== hash2(spec)) throw new Error("World specification or scenario changed; provision a new world. Source patches are allowed.");
5321
- const stage = await mkdtemp4(join10(tmpdir4(), "agenttwin-session-run-"));
6158
+ const stage = await mkdtemp7(join16(tmpdir7(), "agenttwin-session-run-"));
5322
6159
  active = new AbortController();
5323
6160
  let result;
5324
6161
  try {
@@ -5326,7 +6163,7 @@ async function serveWorldSession(directory2) {
5326
6163
  session.status = "running";
5327
6164
  await save();
5328
6165
  active.signal.throwIfAborted();
5329
- const sourceDigests = await stageApplication(dirname2(session.file), spec.files, stage);
6166
+ const sourceDigests = await stageApplication(dirname3(session.file), spec.files, stage);
5330
6167
  active.signal.throwIfAborted();
5331
6168
  world.reset();
5332
6169
  const report = await executeLocal(stage, spec, active.signal, world);
@@ -5334,20 +6171,20 @@ async function serveWorldSession(directory2) {
5334
6171
  const runId = randomUUID4();
5335
6172
  let project = "local-workspace";
5336
6173
  try {
5337
- project = JSON.parse(await readFile10(join10(session.cwd, ".agenttwin/inventory.json"), "utf8")).name ?? project;
6174
+ project = JSON.parse(await readFile13(join16(session.cwd, ".agenttwin/inventory.json"), "utf8")).name ?? project;
5338
6175
  } catch {
5339
6176
  }
5340
- const receipt = { ...report, sourceDirectory: relative4(session.cwd, dirname2(session.file)).split(sep3).join("/"), runId, worldId: session.id, runtime: "local", project, git: await captureGit(session.cwd), createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: hash2(spec), provenance: "CLI-reported execution; not independently attested" };
5341
- const out = join10(session.cwd, ".agenttwin/runs", runId);
5342
- await mkdir6(out, { recursive: true, mode: 448 });
5343
- const evidencePath = join10(out, "run.json");
5344
- await writeFile7(evidencePath, JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
5345
- await writeFile7(join10(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
6177
+ const receipt = { ...report, sourceDirectory: relative4(session.cwd, dirname3(session.file)).split(sep3).join("/"), runId, worldId: session.id, runtime: "local", project, git: await captureGit(session.cwd), createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: hash2(spec), provenance: "CLI-reported execution; not independently attested" };
6178
+ const out = join16(session.cwd, ".agenttwin/runs", runId);
6179
+ await mkdir7(out, { recursive: true, mode: 448 });
6180
+ const evidencePath = join16(out, "run.json");
6181
+ await writeFile11(evidencePath, JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
6182
+ await writeFile11(join16(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
5346
6183
  session.lastRunId = runId;
5347
6184
  result = { ...receipt, evidencePath };
5348
6185
  } finally {
5349
6186
  active = void 0;
5350
- await rm5(stage, { recursive: true, force: true });
6187
+ await rm8(stage, { recursive: true, force: true });
5351
6188
  if (!stopping) {
5352
6189
  session.status = "ready";
5353
6190
  await save();
@@ -5361,11 +6198,11 @@ async function serveWorldSession(directory2) {
5361
6198
  }
5362
6199
  });
5363
6200
  control.requestTimeout = 1e4;
5364
- await new Promise((resolve6, reject) => {
6201
+ await new Promise((resolve7, reject) => {
5365
6202
  control.once("error", reject);
5366
- control.listen(0, "127.0.0.1", resolve6);
6203
+ control.listen(0, "127.0.0.1", resolve7);
5367
6204
  });
5368
- const latest = JSON.parse(await readFile10(join10(directory2, "session.json"), "utf8"));
6205
+ const latest = JSON.parse(await readFile13(join16(directory2, "session.json"), "utf8"));
5369
6206
  if (latest.status !== "provisioning") throw new Error("Provisioning was abandoned");
5370
6207
  session.controlUrl = `http://127.0.0.1:${control.address().port}`;
5371
6208
  if (stopping) throw new Error("World expired during provisioning");