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
@@ -0,0 +1,38 @@
1
+ import{createRequire as __atReq}from'node:module';const require=__atReq(import.meta.url);
2
+ var ee=[{id:"blob",title:"Azure Blob Storage",service:"azure-blob",wire:"storage-xml",hosts:[{suffix:".blob.core.windows.net"}],status:"built",specSource:"Azure Blob Service REST API (learn.microsoft.com/rest/api/storageservices/blob-service-rest-api), cross-checked operation-by-operation against the generated operation specs in the installed @azure/storage-blob 12.33.0 (dist/esm/generated/src/operations/{service,container,blob,blockBlob,appendBlob,pageBlob}.js) at REST version 2026-06-06.",notServed:{code:"UnsupportedHeader",message:"One of the headers specified in the request is not supported.",status:400}},{id:"openai",title:"Azure OpenAI / Azure AI inference",service:"azure-openai",wire:"openai-json",hosts:[{suffix:".openai.azure.com"},{suffix:".cognitiveservices.azure.com",pathPattern:"^/openai/"}],status:"built",specSource:"Azure OpenAI Service data-plane REST API (learn.microsoft.com/azure/ai-services/openai/reference and /reference-preview), grounded route-by-route in the clients an integrator actually uses: the `openai` npm package's AzureOpenAI class (which builds both the deployment-based /openai/deployments/{deployment}/\u2026 path and the newer /openai/v1/\u2026 path style, and requires an api-version query), and @ai-sdk/azure. The Azure-only response members (prompt_filter_results, per-choice content_filter_results, the string error `code` with `innererror`) come from the legacy @azure/openai client's own types.",notServed:{code:"DeploymentNotFound",message:"The API deployment for this resource does not exist.",status:404}},{id:"entra",title:"Microsoft Entra ID (OAuth2/OIDC)",service:"azure-entra",wire:"oauth2-json",hosts:[{host:"login.microsoftonline.com"}],status:"deferred",specSource:"OAuth 2.0 (RFC 6749) + OpenID Connect Discovery, as profiled by the Microsoft identity platform endpoints.",reason:"Service area 3 of the azure family pack is a FOLLOW-UP BUILD and is not served here. No token, authorize, discovery or JWKS endpoint answers, so this twin cannot mint or validate a real Entra token \u2014 which is exactly why the shared core accepts an Entra bearer on SHAPE only and says so, rather than claiming a validation it cannot perform.",notServed:{code:"invalid_request",message:"The request is not supported by this endpoint.",status:400}}],de=e=>{let t=ee.find(o=>o.id===e);if(!t)throw new Error(`azure: unknown service area '${e}'`);return t};var F="00000000-0000-0000-0000-0000000000t1",ue="2026-06-06";function bt(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ht(e){let t=[e.message,`RequestId:${F}`,`Time:${e.time??"1970-01-01T00:00:00.0000000Z"}`];return`<?xml version="1.0" encoding="utf-8"?><Error><Code>${bt(e.code)}</Code><Message>${bt(t.join(`
3
+ `))}</Message></Error>`}function pe(e){return{status:e.status,headers:{"content-type":"application/xml","x-ms-error-code":e.code,"x-ms-version":ue,"x-ms-request-id":F},body:ht({code:e.code,message:e.message,...e.time!==void 0?{time:e.time}:{}})}}function xt(e){return{status:e.status,headers:{"content-type":"application/json"},body:JSON.stringify({error:{code:e.code,message:e.message,param:null,type:null}})}}function gt(e){return{status:e.status,headers:{"content-type":"application/json"},body:JSON.stringify({error:e.error,error_description:e.description})}}function fe(e,t){return e==="openai-json"?xt(t):e==="oauth2-json"?gt({error:t.code,description:t.message,status:t.status}):pe(t)}import{applyTwinWrite as Tn,projectResources as wn,worldPaths as kn,worldNow as On}from"../../engine/v2/volter_world-core.mjs";import{join as mn,relative as bn}from"node:path";import{blobDigest as yt,getActiveBlobStore as hn,readResourceBlob as xn,worldPaths as _t}from"../../engine/v2/volter_world-core.mjs";function St(e,t){if(!/^[0-9a-f]{64}$/.test(e))throw new Error("Invalid Azure blob digest");return mn(_t("azure-blob",t).resources,"blobs","sha256",e.slice(0,2),e)}async function te(e,t){let o=yt(e),n=hn(),r=St(o,t);return await n.exists(r)||await n.put(r,e),{blob_sha256:o}}async function V(e,t){if(e==null||typeof e=="string")return Buffer.from(e??"","base64");let o=e.blob_sha256,n=await xn("azure-blob",bn(_t("azure-blob",t).resources,St(o,t)),t);if(!n||yt(n)!==o)throw new Error("Missing or corrupt Azure blob");return Buffer.from(n.buffer,n.byteOffset,n.byteLength)}var gn=new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1820,0,1823,1825,1827,1829,0,0,0,1837,2051,0,0,1843,0,3331,3354,3356,3358,3360,3362,3364,3366,3368,3370,0,0,0,0,0,0,0,3586,3593,3594,3610,3617,3619,3621,3628,3634,3637,3638,3656,3665,3696,3708,3710,3721,3722,3729,3737,3743,3746,3748,3750,3751,3753,0,0,0,1859,1860,1864,3586,3593,3594,3610,3617,3619,3621,3628,3634,3637,3638,3656,3665,3696,3708,3710,3721,3722,3729,3737,3743,3746,3748,3750,3751,3753,0,1868,0,1872,0]),yn=new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),_n=new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32786,0,0,0,0,0,33298,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function Sn(e,t){let o=[gn,yn,_n],n=0,r=0,s=0;for(;n<o.length;){if(n===o.length-1&&r!==s)return r>s;let a=o[n],i=r<e.length?a[e.charCodeAt(r)]??0:1,c=s<t.length?a[t.charCodeAt(s)]??0:1;if(i===1&&c===1)r=0,s=0,++n;else if(i===c)++r,++s;else if(i===0)++r;else if(c===0)++s;else return i<c}return!1}function me(e,t){return e===t?0:Sn(e,t)?-1:1}var _=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function v(e){let t=new Date(e);return Number.isNaN(t.getTime())?new Date(0).toUTCString():t.toUTCString()}function At(e){let t=Object.entries(e??{});return t.length===0?"<Metadata />":`<Metadata>${t.map(([o,n])=>`<${o}>${_(n)}</${o}>`).join("")}</Metadata>`}var H='<?xml version="1.0" encoding="utf-8"?>';function Et(e){return`<Container><Name>${_(e.name)}</Name><Properties><Last-Modified>${v(e.lastModified)}</Last-Modified><Etag>${_(e.etag)}</Etag><LeaseStatus>unlocked</LeaseStatus><LeaseState>available</LeaseState>`+(e.publicAccess?`<PublicAccess>${_(e.publicAccess)}</PublicAccess>`:"")+"<HasImmutabilityPolicy>false</HasImmutabilityPolicy><HasLegalHold>false</HasLegalHold><ImmutableStorageWithVersioningEnabled>false</ImmutableStorageWithVersioningEnabled></Properties>"+At(e.metadata)+"</Container>"}function Ie(e){return H+`<EnumerationResults ServiceEndpoint="${_(e.serviceEndpoint)}">`+(e.prefix!==void 0?`<Prefix>${_(e.prefix)}</Prefix>`:"")+(e.marker!==void 0?`<Marker>${_(e.marker)}</Marker>`:"")+(e.maxResults!==void 0?`<MaxResults>${e.maxResults}</MaxResults>`:"")+`<Containers>${e.containers.map(Et).join("")}</Containers><NextMarker>${e.nextMarker?_(e.nextMarker):""}</NextMarker></EnumerationResults>`}function Ne(e){return`<Blob><Name>${_(e.name)}</Name><Properties><Creation-Time>${v(e.createdAt)}</Creation-Time><Last-Modified>${v(e.lastModified)}</Last-Modified><Etag>${_(e.etag)}</Etag><Content-Length>${e.contentLength}</Content-Length><Content-Type>${_(e.contentType)}</Content-Type>`+(e.contentEncoding?`<Content-Encoding>${_(e.contentEncoding)}</Content-Encoding>`:"<Content-Encoding />")+(e.contentLanguage?`<Content-Language>${_(e.contentLanguage)}</Content-Language>`:"<Content-Language />")+(e.contentMd5?`<Content-MD5>${_(e.contentMd5)}</Content-MD5>`:"<Content-MD5 />")+(e.contentDisposition?`<Content-Disposition>${_(e.contentDisposition)}</Content-Disposition>`:"")+(e.cacheControl?`<Cache-Control>${_(e.cacheControl)}</Cache-Control>`:"<Cache-Control />")+`<BlobType>${_(e.blobType)}</BlobType><LeaseStatus>unlocked</LeaseStatus><LeaseState>available</LeaseState><ServerEncrypted>true</ServerEncrypted><AccessTier>Hot</AccessTier><AccessTierInferred>true</AccessTierInferred></Properties>`+At(e.metadata)+"</Blob>"}function $e(e){return H+`<EnumerationResults ServiceEndpoint="${_(e.serviceEndpoint)}" ContainerName="${_(e.containerName)}">`+(e.prefix!==void 0?`<Prefix>${_(e.prefix)}</Prefix>`:"")+(e.marker!==void 0?`<Marker>${_(e.marker)}</Marker>`:"")+(e.maxResults!==void 0?`<MaxResults>${e.maxResults}</MaxResults>`:"")+`<Blobs>${e.blobs.map(Ne).join("")}</Blobs><NextMarker>${e.nextMarker?_(e.nextMarker):""}</NextMarker></EnumerationResults>`}function Ce(e){return H+`<EnumerationResults ServiceEndpoint="${_(e.serviceEndpoint)}" ContainerName="${_(e.containerName)}">`+(e.prefix!==void 0?`<Prefix>${_(e.prefix)}</Prefix>`:"")+(e.marker!==void 0?`<Marker>${_(e.marker)}</Marker>`:"")+(e.maxResults!==void 0?`<MaxResults>${e.maxResults}</MaxResults>`:"")+`<Delimiter>${_(e.delimiter)}</Delimiter><Blobs>`+e.blobs.map(Ne).join("")+e.blobPrefixes.map(t=>`<BlobPrefix><Name>${_(t)}</Name></BlobPrefix>`).join("")+`</Blobs><NextMarker>${e.nextMarker?_(e.nextMarker):""}</NextMarker></EnumerationResults>`}function ze(e){let t=n=>`<Block><Name>${_(n.name)}</Name><Size>${n.size}</Size></Block>`,o=(n,r)=>r===void 0?"":r.length===0?`<${n} />`:`<${n}>${r.map(t).join("")}</${n}>`;return H+"<BlockList>"+o("CommittedBlocks",e.committed)+o("UncommittedBlocks",e.uncommitted)+"</BlockList>"}function Pe(e){let t={latest:[],committed:[],uncommitted:[],order:[]},o=/<(Latest|Committed|Uncommitted)>([\s\S]*?)<\/\1>/g,n;for(;(n=o.exec(e))!==null;){let r=n[1],s=(n[2]??"").trim();t.order.push({list:r,id:s}),r==="Latest"?t.latest.push(s):r==="Committed"?t.committed.push(s):t.uncommitted.push(s)}return t}function Be(){return H+"<StorageServiceProperties><Logging><Version>1.0</Version><Delete>false</Delete><Read>false</Read><Write>false</Write><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></Logging><HourMetrics><Version>1.0</Version><Enabled>false</Enabled><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></HourMetrics><MinuteMetrics><Version>1.0</Version><Enabled>false</Enabled><RetentionPolicy><Enabled>false</Enabled></RetentionPolicy></MinuteMetrics><Cors /><DefaultServiceVersion>2026-06-06</DefaultServiceVersion></StorageServiceProperties>"}function Me(e){return H+`<StorageServiceStats><GeoReplication><Status>live</Status><LastSyncTime>${v(e)}</LastSyncTime></GeoReplication></StorageServiceStats>`}import{createHash as vt}from"node:crypto";function G(e){return vt("md5").update(e).digest("base64")}function C(e){return`"0x8D${vt("sha256").update(`${e.subject}|${e.rev}|${e.digest}`).digest("hex").slice(0,14).toUpperCase()}"`}function je(e){return e.trim().replace(/^W\//i,"").replace(/^"/,"").replace(/"$/,"")}function be(e,t){let o=je(t);return e.split(",").map(n=>n.trim()).some(n=>n==="*"||je(n)===o)}import{createHmac as An}from"node:crypto";var W="devstoreaccount1",ne="Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==";function Ue(e){return e===W?ne:void 0}var En=["content-language","content-encoding","content-length","content-md5","content-type","date","if-modified-since","if-match","if-none-match","if-unmodified-since","range"];function Fe(e){let t={};for(let[o,n]of Object.entries(e))t[o.toLowerCase()]=n;return t}function Tt(e){let t=Fe(e),o=Object.keys(t).filter(n=>n.startsWith("x-ms-"));return o.sort(me),o.map(n=>`${n.trimEnd()}:${(t[n]??"").trimStart()}
4
+ `).join("")}function wt(e){let t=(e.startsWith("?")?e.slice(1):e).trim();if(t==="")return[];let o=[];for(let n of t.split("&")){let r=n.indexOf("="),s=n.lastIndexOf("=");r>0&&r===s&&s<n.length-1&&o.push([n.slice(0,r),n.slice(r+1)])}return o}function kt(e,t,o){let n=`/${e}${t||"/"}`,r=new Map;for(let[s,a]of wt(o))r.set(s.toLowerCase(),decodeURIComponent(a));for(let s of[...r.keys()].sort())n+=`
5
+ ${s}:${r.get(s)}`;return n}function De(e){let t=Fe(e.headers),o=En.map(n=>{let r=t[n];return!r||n==="content-length"&&r==="0"?"":r});return[e.method.toUpperCase(),...o].join(`
6
+ `)+`
7
+ `+Tt(e.headers)+kt(e.accountName,e.pathname,e.rawQuery)}function Le(e,t){return An("sha256",Buffer.from(t,"base64")).update(De(e),"utf8").digest("base64")}function Ve(e,t){let n=Fe(e).authorization??"";if(n){let r=n.indexOf(" "),s=(r<0?n:n.slice(0,r)).trim(),a=r<0?"":n.slice(r+1).trim();if(/^SharedKey$/i.test(s)||/^SharedKeyLite$/i.test(s)){let i=a.indexOf(":");return{kind:"shared-key",lite:/lite$/i.test(s),accountName:i<0?a:a.slice(0,i),signature:i<0?"":a.slice(i+1)}}return/^Bearer$/i.test(s)?{kind:"bearer",token:a}:{kind:"unknown",scheme:s}}return t&&t.get("sig")&&t.get("sv")?{kind:"sas",token:t.get("sig")??""}:{kind:"anonymous"}}var vn={storage:{pattern:/^https:\/\/(storage\.azure\.com|[a-z0-9-]+\.blob\.core\.windows\.net)\/?$/,label:"storage"},cognitiveservices:{pattern:/^https:\/\/(cognitiveservices\.azure\.com|[a-z0-9-]+\.(openai|cognitiveservices)\.azure\.com)\/?$/,label:"Cognitive Services"}};function oe(e,t="storage"){let o=e.split(".");if(o.length!==3||o.some(a=>a===""))return{accepted:!1,reason:"not a three-segment JWT"};let n;try{let a=Buffer.from(o[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8");n=JSON.parse(a)}catch{return{accepted:!1,reason:"JWT payload is not decodable JSON"}}let r=vn[t],s=typeof n.aud=="string"?[n.aud]:Array.isArray(n.aud)?n.aud.filter(a=>typeof a=="string"):[];return s.length===0?{accepted:!1,reason:`the bearer carries no audience claim, so it cannot be a ${r.label} token`,claims:n}:s.some(a=>r.pattern.test(a))?{accepted:!0,reason:"well-formed bearer accepted locally (no tenant is contacted)",claims:n}:{accepted:!1,reason:`audience '${s.join(", ")}' is not a ${r.label} audience`,claims:n}}function he(e,t){let o=(e??"").split(":")[0]?.toLowerCase()??"";if(o.endsWith(".blob.core.windows.net")&&o.length>22)return{accountName:o.slice(0,-22),pathname:t};let n=t.replace(/^\/+/,"").split("/"),r=n[0]??"";if(r===W)return{accountName:r,pathname:`/${n.slice(1).join("/")}`}}var re="azure-blob";function Rt(e,t){return wn(re,t).filter(o=>o.type===e)}function z(e,t){return Rt(e,t).filter(o=>o._deleted!==!0)}function B(e,t,o){return z(e,o).find(n=>n.id===t)}function T(e,t,o){let n=Rt(e,o).find(s=>s.id===t);return(typeof n?.rev=="number"?n.rev:0)+1}async function w(e,t,o,n,r){let{resource:s}=await Tn(re,{operation:n,subjectType:e,subjectId:t,fields:o,...r.occurredAt?{occurredAt:r.occurredAt}:{},actor:{kind:"agent"}},r.root);return s}var $=e=>e.occurredAt??On(),Rn=e=>`${new Date(e).toISOString().replace("Z","")}0000Z`;function J(e){let t=Ge(e.headers)["x-ms-client-request-id"];return{"x-ms-request-id":F,"x-ms-version":ue,...t?{"x-ms-client-request-id":t}:{}}}function h(e,t,o,n){let r=pe({code:t,message:o,status:n,time:Rn($(e))});return{...r,headers:{...J(e),...r.headers}}}var D=(e,t,o,n={})=>({status:t,headers:{"content-type":"application/xml",...J(e),...n},body:o}),R=(e,t,o={})=>({status:t,headers:{...J(e),...o},body:""}),A=(e,t)=>h(e,"NotImplemented",`The requested operation is not implemented on the specified resource (${t}).`,501);function Ge(e){let t={};for(let[o,n]of Object.entries(e??{}))t[o.toLowerCase()]=n;return t}function L(e){let t={};for(let[o,n]of Object.entries(e))o.startsWith("x-ms-meta-")&&(t[o.slice(10)]=n);return t}function It(e){let t={};for(let[o,n]of Object.entries(e))t[`x-ms-meta-${o}`]=n;return t}function In(e){let t=e.path.indexOf("?"),o=t>=0?e.path.slice(0,t):e.path,n=t>=0?e.path.slice(t+1):"",r=new URLSearchParams(n),s=he(e.host,o),a=s?.accountName??W,i=s?s.pathname:o,c=i.replace(/^\/+/,"").split("/").filter(d=>d!==""),u=c.length>0?decodeURIComponent(c[0]):void 0,p=c.length>1?c.slice(1).map(d=>decodeURIComponent(d)).join("/"):void 0;return{account:a,...u!==void 0?{container:u}:{},...p!==void 0?{blob:p}:{},query:r,pathname:i,rawPath:o,rawQuery:n,accountAddressed:s!==void 0}}function Nt(e,t){return e.host&&e.host.toLowerCase().endsWith(".blob.core.windows.net")?`https://${e.host}/`:`http://${e.endpoint??e.host??"127.0.0.1"}/${t}/`}function $t(e,t){let o=Ge(e.headers),n=Ve(o,t.query);if(n.kind==="anonymous")return{ok:!0,scheme:"anonymous"};if(n.kind==="sas")return{ok:!0,scheme:"sas"};if(n.kind==="bearer"){let a=oe(n.token);return a.accepted?{ok:!0,scheme:"bearer"}:{ok:!1,status:401,code:"InvalidAuthenticationInfo",message:`Server failed to authenticate the request. Authentication information is not given in the correct format (${a.reason}).`}}if(n.kind==="unknown")return{ok:!1,status:400,code:"InvalidAuthenticationInfo",message:`Server failed to authenticate the request. The authentication scheme '${n.scheme}' is not supported.`};if(n.lite)return{ok:!1,status:400,code:"InvalidAuthenticationInfo",message:"Server failed to authenticate the request. SharedKeyLite is not supported by this twin."};let r=Ue(n.accountName);return r?Le({method:e.method,pathname:t.rawPath,rawQuery:t.rawQuery,headers:o,accountName:n.accountName},r)!==n.signature?{ok:!1,status:403,code:"AuthenticationFailed",message:"Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature."}:{ok:!0,scheme:"shared-key"}:{ok:!1,status:403,code:"InvalidAuthenticationInfo",message:`Server failed to authenticate the request. Account '${n.accountName}' is not known to this twin.`}}function He(e){return{name:String(e.id),lastModified:String(e.last_modified??e.created_at??new Date(0).toISOString()),etag:String(e.etag??""),metadata:e.metadata??{},...e.public_access?{publicAccess:String(e.public_access)}:{}}}function Nn(e){return{name:String(e.name),createdAt:String(e.created_at??new Date(0).toISOString()),lastModified:String(e.last_modified??e.created_at??new Date(0).toISOString()),etag:String(e.etag??""),contentLength:Number(e.size??0),contentType:String(e.content_type||"application/octet-stream"),...e.content_md5?{contentMd5:String(e.content_md5)}:{},...e.content_encoding?{contentEncoding:String(e.content_encoding)}:{},...e.content_language?{contentLanguage:String(e.content_language)}:{},...e.cache_control?{cacheControl:String(e.cache_control)}:{},...e.content_disposition?{contentDisposition:String(e.content_disposition)}:{},blobType:String(e.blob_type??"BlockBlob"),metadata:e.metadata??{}}}function $n(e){let t=e.metadata??{};return{etag:String(e.etag??""),"last-modified":v(String(e.last_modified??e.created_at??new Date(0).toISOString())),"x-ms-creation-time":v(String(e.created_at??new Date(0).toISOString())),"content-type":String(e.content_type||"application/octet-stream"),...e.content_md5?{"content-md5":String(e.content_md5)}:{},...e.content_encoding?{"content-encoding":String(e.content_encoding)}:{},...e.content_language?{"content-language":String(e.content_language)}:{},...e.cache_control?{"cache-control":String(e.cache_control)}:{},...e.content_disposition?{"content-disposition":String(e.content_disposition)}:{},"x-ms-blob-type":String(e.blob_type??"BlockBlob"),"x-ms-lease-status":"unlocked","x-ms-lease-state":"available","x-ms-server-encrypted":"true","accept-ranges":"bytes",...It(t)}}var Ct=new Set(["PUT","POST","DELETE","PATCH","MERGE"]),xe=new Map;async function We(e){if(!Ct.has(e.method.toUpperCase()))return Ot(e);let t=kn(re,e.root).dir,o=xe.get(t),n,r=new Promise(s=>{n=s});xe.set(t,r),await o;try{return await Ot(e)}finally{n(),xe.get(t)===r&&xe.delete(t)}}async function Ot(e){let t=In(e),o=Ge(e.headers),n=e.method.toUpperCase(),r=$t(e,t);return r.ok?e.readOnly&&Ct.has(n)?h(e,"UnsupportedHttpVerb","The resource doesn't support the specified HTTP verb; this twin is read-only.",405):t.container===void 0?Cn(e,t,n):t.blob===void 0?zn(e,t,n,o):Bn(e,t,n,o):h(e,r.code,r.message,r.status)}async function Cn(e,t,o){let n=t.query.get("comp"),r=t.query.get("restype");if(o!=="GET")return o==="POST"&&n==="batch"?A(e,"Blob Batch"):o==="POST"&&n==="userdelegationkey"?A(e,"Get User Delegation Key"):o==="PUT"&&r==="service"?A(e,"Set Blob Service Properties"):h(e,"UnsupportedHttpVerb",`The resource doesn't support the specified HTTP verb (${o} at the service root).`,405);if(r==="account"&&n==="properties")return R(e,200,{"x-ms-sku-name":"Standard_LRS","x-ms-account-kind":"StorageV2","x-ms-is-hns-enabled":"false"});if(r==="service"&&n==="properties")return D(e,200,Be());if(r==="service"&&n==="stats")return D(e,200,Me($(e)));if(n==="blobs")return A(e,"Find Blobs by Tags");if(n!=="list")return h(e,"InvalidUri","The requested URI does not represent any resource on the server.",400);let s=t.query.get("prefix")??void 0,a=t.query.get("maxresults"),i=a===null?void 0:Number(a);if(i!==void 0&&(!Number.isInteger(i)||i<1))return h(e,"OutOfRangeQueryParameterValue","One of the query parameters specified in the request URI is outside the permissible range.",400);let c=t.query.get("marker")??void 0,u=z("container",e.root).map(He).filter(l=>s?l.name.startsWith(s):!0).filter(l=>c?l.name>c:!0).sort((l,m)=>l.name<m.name?-1:l.name>m.name?1:0),p=i===void 0?u:u.slice(0,i),d=i!==void 0&&u.length>p.length?p[p.length-1].name:void 0;return D(e,200,Ie({serviceEndpoint:Nt(e,t.account),...s!==void 0?{prefix:s}:{},...c!==void 0?{marker:c}:{},...i!==void 0?{maxResults:i}:{},containers:p,...d!==void 0?{nextMarker:d}:{}}))}async function zn(e,t,o,n){let r=t.container,s=t.query.get("comp");if(t.query.get("restype")!=="container")return h(e,"InvalidUri","The requested URI does not represent any resource on the server.",400);if(!/^[a-z0-9](?:[a-z0-9-]{1,61})[a-z0-9]$/.test(r)||r.includes("--"))return h(e,"InvalidResourceName","The specified resource name contains invalid characters.",400);let i=B("container",r,e.root);if(o==="PUT"&&s===null){if(i)return h(e,"ContainerAlreadyExists","The specified container already exists.",409);let c=$(e),u=T("container",r,e.root),p=C({subject:`container/${r}`,rev:u,digest:r}),d=n["x-ms-blob-public-access"];return await w("container",r,{object:"container",name:r,created_at:c,last_modified:c,etag:p,rev:u,metadata:L(n),public_access:d??"",_deleted:!1},"container.create",e),R(e,201,{etag:p,"last-modified":v(c)})}if((o==="GET"||o==="HEAD")&&s===null){if(!i)return h(e,"ContainerNotFound","The specified container does not exist.",404);let c=He(i);return R(e,200,{etag:c.etag,"last-modified":v(c.lastModified),"x-ms-lease-status":"unlocked","x-ms-lease-state":"available","x-ms-has-immutability-policy":"false","x-ms-has-legal-hold":"false",...c.publicAccess?{"x-ms-blob-public-access":c.publicAccess}:{},...It(c.metadata??{})})}if(o==="DELETE"&&s===null){if(!i)return h(e,"ContainerNotFound","The specified container does not exist.",404);let c=$(e);for(let u of z("blob",e.root).filter(p=>p.container===r))await w("blob",String(u.id),{_deleted:!0,rev:T("blob",String(u.id),e.root),last_modified:c},"blob.delete",e);for(let u of z("block",e.root).filter(p=>p.container===r))await w("block",String(u.id),{_deleted:!0,rev:T("block",String(u.id),e.root),last_modified:c},"block.delete",e);return await w("container",r,{_deleted:!0,rev:T("container",r,e.root),last_modified:c},"container.delete",e),R(e,202)}if(o==="PUT"&&s==="metadata"){if(!i)return h(e,"ContainerNotFound","The specified container does not exist.",404);let c=$(e),u=T("container",r,e.root),p=L(n),d=C({subject:`container/${r}`,rev:u,digest:JSON.stringify(p)});return await w("container",r,{metadata:p,last_modified:c,etag:d,rev:u},"container.set_metadata",e),R(e,200,{etag:d,"last-modified":v(c)})}if(o==="PUT"&&s==="acl"){if(!i)return h(e,"ContainerNotFound","The specified container does not exist.",404);let c=n["x-ms-blob-public-access"]??"";if(c!==""&&c!=="container"&&c!=="blob")return h(e,"InvalidHeaderValue","The value for one of the HTTP headers is not in the correct format.",400);let u=$(e),p=T("container",r,e.root),d=C({subject:`container/${r}`,rev:p,digest:`acl:${c}`});return await w("container",r,{public_access:c,last_modified:u,etag:d,rev:p},"container.set_acl",e),R(e,200,{etag:d,"last-modified":v(u)})}if(o==="GET"&&s==="acl"){if(!i)return h(e,"ContainerNotFound","The specified container does not exist.",404);let c=He(i);return D(e,200,'<?xml version="1.0" encoding="utf-8"?><SignedIdentifiers />',{etag:c.etag,"last-modified":v(c.lastModified),...c.publicAccess?{"x-ms-blob-public-access":c.publicAccess}:{}})}return o==="GET"&&s==="list"?i?Pn(e,t,r):h(e,"ContainerNotFound","The specified container does not exist.",404):s==="lease"?A(e,"Lease Container"):s==="undelete"?A(e,"Restore Container"):s==="rename"?A(e,"Rename Container"):s==="batch"?A(e,"Blob Batch"):s==="blobs"?A(e,"Find Blobs by Tags"):h(e,"UnsupportedHttpVerb",`The resource doesn't support the specified HTTP verb (${o} ${s?`comp=${s}`:"on a container"}).`,405)}function Pn(e,t,o){let n=t.query.get("prefix")??void 0,r=t.query.get("delimiter")??void 0,s=t.query.get("marker")??void 0,a=t.query.get("maxresults"),i=a===null?void 0:Number(a);if(i!==void 0&&(!Number.isInteger(i)||i<1))return h(e,"OutOfRangeQueryParameterValue","One of the query parameters specified in the request URI is outside the permissible range.",400);let c=z("blob",e.root).filter(l=>l.container===o).map(Nn).filter(l=>n?l.name.startsWith(n):!0).filter(l=>s?l.name>s:!0).sort((l,m)=>l.name<m.name?-1:l.name>m.name?1:0),u=Nt(e,t.account);if(r){let l=new Set,m=[];for(let f of c){let b=f.name.slice((n??"").length),y=b.indexOf(r);y>=0?l.add(`${n??""}${b.slice(0,y+r.length)}`):m.push(f)}let x=i===void 0?m:m.slice(0,i);return D(e,200,Ce({serviceEndpoint:u,containerName:o,delimiter:r,...n!==void 0?{prefix:n}:{},...s!==void 0?{marker:s}:{},...i!==void 0?{maxResults:i}:{},blobs:x,blobPrefixes:[...l].sort()}))}let p=i===void 0?c:c.slice(0,i),d=i!==void 0&&c.length>p.length?p[p.length-1].name:void 0;return D(e,200,$e({serviceEndpoint:u,containerName:o,...n!==void 0?{prefix:n}:{},...s!==void 0?{marker:s}:{},...i!==void 0?{maxResults:i}:{},blobs:p,...d!==void 0?{nextMarker:d}:{}}))}async function Bn(e,t,o,n){let r=t.container,s=t.blob,a=`${r}/${s}`,i=t.query.get("comp");if(t.query.get("restype")==="account"&&i==="properties"&&o==="GET")return R(e,200,{"x-ms-sku-name":"Standard_LRS","x-ms-account-kind":"StorageV2","x-ms-is-hns-enabled":"false"});if(!B("container",r,e.root))return h(e,"ContainerNotFound","The specified container does not exist.",404);let u=B("blob",a,e.root);if(o==="PUT"&&i===null&&n["x-ms-copy-source"]!==void 0)return Un(e,t,r,s,a,n);if(o==="PUT"&&i===null)return jn(e,r,s,a,n);if(o==="PUT"&&i==="block")return Fn(e,t,r,s,n);if(o==="PUT"&&i==="blocklist")return Dn(e,r,s,a,n);if(o==="GET"&&i==="blocklist")return Ln(e,t,r,s,a);if((o==="GET"||o==="HEAD")&&i===null)return u?Mn(e,u,o,n):h(e,"BlobNotFound","The specified blob does not exist.",404);if(o==="DELETE"&&i===null){if(!u)return h(e,"BlobNotFound","The specified blob does not exist.",404);let p=$(e);await w("blob",a,{_deleted:!0,rev:T("blob",a,e.root),last_modified:p},"blob.delete",e);for(let d of z("block",e.root).filter(l=>l.container===r&&l.blob===s))await w("block",String(d.id),{_deleted:!0,rev:T("block",String(d.id),e.root)},"block.delete",e);return R(e,202)}if(o==="PUT"&&i==="metadata"){if(!u)return h(e,"BlobNotFound","The specified blob does not exist.",404);let p=$(e),d=T("blob",a,e.root),l=L(n),m=C({subject:`blob/${a}`,rev:d,digest:JSON.stringify(l)});return await w("blob",a,{metadata:l,last_modified:p,etag:m,rev:d},"blob.set_metadata",e),R(e,200,{etag:m,"last-modified":v(p)})}if(o==="PUT"&&i==="properties"){if(!u)return h(e,"BlobNotFound","The specified blob does not exist.",404);let p=$(e),d=T("blob",a,e.root),l={content_type:n["x-ms-blob-content-type"]??"",content_encoding:n["x-ms-blob-content-encoding"]??"",content_language:n["x-ms-blob-content-language"]??"",cache_control:n["x-ms-blob-cache-control"]??"",content_disposition:n["x-ms-blob-content-disposition"]??"",last_modified:p,rev:d};return l.etag=C({subject:`blob/${a}`,rev:d,digest:JSON.stringify(l)}),await w("blob",a,l,"blob.set_http_headers",e),R(e,200,{etag:String(l.etag),"last-modified":v(p)})}return i==="lease"?A(e,"Lease Blob"):i==="snapshot"?A(e,"Snapshot Blob"):i==="tags"?A(e,"Blob Tags"):i==="tier"?A(e,"Set Blob Tier"):i==="expiry"?A(e,"Set Blob Expiry"):i==="undelete"?A(e,"Undelete Blob"):i==="query"?A(e,"Query Blob Contents"):i==="page"||i==="pagelist"||i==="incrementalcopy"?A(e,"Page Blob"):i==="appendblock"?A(e,"Append Blob"):i==="immutabilityPolicies"||i==="legalhold"?A(e,"Immutable storage"):i==="copy"?A(e,"Abort Copy Blob"):h(e,"UnsupportedHttpVerb",`The resource doesn't support the specified HTTP verb (${o} ${i?`comp=${i}`:"on a blob"}).`,405)}async function Mn(e,t,o,n){let r=await V(t.data_b64,e.root),s=String(t.etag??""),a=n["if-match"],i=n["if-none-match"];if(a!==void 0&&!be(a,s))return h(e,"ConditionNotMet","The condition specified using HTTP conditional header(s) is not met.",412);if(i!==void 0&&be(i,s))return{status:304,headers:{...J(e),etag:s},body:""};let c=n["x-ms-range"]??n.range,u=$n(t);if(c){let p=/^bytes=(\d+)-(\d*)$/.exec(c.trim());if(!p)return h(e,"InvalidHeaderValue","The value for one of the HTTP headers is not in the correct format.",400);let d=Number(p[1]),l=p[2]===""?r.length-1:Number(p[2]);if(d>=r.length)return h(e,"InvalidRange","The range specified is invalid for the current size of the resource.",416);let m=r.subarray(d,Math.min(l,r.length-1)+1);return{status:206,headers:{...J(e),...u,"content-length":String(m.length),"content-range":`bytes ${d}-${d+m.length-1}/${r.length}`},body:o==="HEAD"?"":m}}return{status:200,headers:{...J(e),...u,"content-length":String(r.length)},body:o==="HEAD"?"":r}}function Je(e){return e===void 0?Buffer.alloc(0):typeof e=="string"?Buffer.from(e,"utf8"):Buffer.isBuffer(e)?e:Buffer.from(e)}async function zt(e,t,o){for(let n of z("block",e.root).filter(r=>r.container===t&&r.blob===o)){let r=String(n.id);await w("block",r,{_deleted:!0,rev:T("block",r,e.root)},"block.discard",e)}}async function jn(e,t,o,n,r){let s=r["x-ms-blob-type"]??"";if(s!=="BlockBlob")return s==="PageBlob"||s==="AppendBlob"?A(e,`${s} (only BlockBlob is modeled in service area 1)`):h(e,"MissingRequiredHeader","An HTTP header that's mandatory for this request is not specified (x-ms-blob-type).",400);let a=Je(e.body),i=G(a),c=r["content-md5"];if(c!==void 0&&c!==i)return h(e,"Md5Mismatch","The MD5 value specified in the request did not match with the MD5 value calculated by the server.",400);let u=$(e),p=B("blob",n,e.root),d=T("blob",n,e.root),l=C({subject:`blob/${n}`,rev:d,digest:i});return await w("blob",n,{object:"blob",container:t,name:o,blob_type:"BlockBlob",data_b64:await te(a,e.root),size:a.length,content_md5:i,content_type:r["x-ms-blob-content-type"]??r["content-type"]??"application/octet-stream",content_encoding:r["x-ms-blob-content-encoding"]??"",content_language:r["x-ms-blob-content-language"]??"",cache_control:r["x-ms-blob-cache-control"]??"",content_disposition:r["x-ms-blob-content-disposition"]??"",metadata:L(r),committed_blocks:[],created_at:p?String(p.created_at??u):u,last_modified:u,etag:l,rev:d,_deleted:!1},"blob.put",e),await zt(e,t,o),R(e,201,{etag:l,"last-modified":v(u),"content-md5":i,"x-ms-request-server-encrypted":"true"})}async function Un(e,t,o,n,r,s){let a=s["x-ms-copy-source"]??"",i;try{i=new URL(a).pathname}catch{i=a.startsWith("/")?a:`/${a}`}let c=he(e.host,i),u=(c?c.pathname:i).replace(/^\/+/,"").split("/").filter(g=>g!==""),p=u.length>0?decodeURIComponent(u[0]):"",d=u.slice(1).map(g=>decodeURIComponent(g)).join("/"),l=B("blob",`${p}/${d}`,e.root);if(!l)return h(e,"CannotVerifyCopySource","The specified blob does not exist (copy source could not be read).",404);let m=$(e),x=T("blob",r,e.root),f=String(l.content_md5??G(await V(l.data_b64,e.root))),b=C({subject:`blob/${r}`,rev:x,digest:f}),y=B("blob",r,e.root);return await w("blob",r,{object:"blob",container:o,name:n,blob_type:"BlockBlob",data_b64:typeof l.data_b64=="string"||l.data_b64==null?await te(await V(l.data_b64,e.root),e.root):l.data_b64,size:Number(l.size??0),content_md5:f,content_type:String(l.content_type??"application/octet-stream"),content_encoding:String(l.content_encoding??""),content_language:String(l.content_language??""),cache_control:String(l.cache_control??""),content_disposition:String(l.content_disposition??""),metadata:Object.keys(L(s)).length>0?L(s):l.metadata??{},committed_blocks:[],created_at:y?String(y.created_at??m):m,last_modified:m,etag:b,rev:x,copy_source:a,_deleted:!1},"blob.copy",e),await zt(e,o,n),R(e,202,{etag:b,"last-modified":v(m),"x-ms-copy-id":`twin-copy-${x}`,"x-ms-copy-status":"success"})}async function Fn(e,t,o,n,r){let s=t.query.get("blockid");if(!s)return h(e,"MissingRequiredQueryParameter","A query parameter that's mandatory for this request is not specified (blockid).",400);if(!/^[A-Za-z0-9+/]+={0,2}$/.test(s)||s.length%4!==0)return h(e,"InvalidBlockId","The specified block ID is invalid. The block ID must be Base64-encoded.",400);let a=Buffer.from(s,"base64").length,c=z("block",e.root).filter(x=>x.container===o&&x.blob===n).find(x=>Number(x.block_id_length??0)!==a);if(c)return h(e,"InvalidBlockId",`The specified block ID is invalid. All block IDs for a blob must be the same length (this blob's blocks are ${String(c.block_id_length)} bytes, this one is ${a}).`,400);let u=Je(e.body),p=G(u),d=r["content-md5"];if(d!==void 0&&d!==p)return h(e,"Md5Mismatch","The MD5 value specified in the request did not match with the MD5 value calculated by the server.",400);let l=`${o}/${n}/${s}`,m=T("block",l,e.root);return await w("block",l,{object:"block",container:o,blob:n,block_id:s,block_id_length:a,data_b64:await te(u,e.root),size:u.length,state:"uncommitted",rev:m,_deleted:!1},"block.stage",e),R(e,201,{"content-md5":p,"x-ms-request-server-encrypted":"true"})}async function Dn(e,t,o,n,r){let s=typeof e.body=="string"?e.body:Je(e.body).toString("utf8"),a=Pe(s);if(a.order.length===0)return h(e,"InvalidXmlDocument","The specified XML is not syntactically valid.",400);let i=z("block",e.root).filter(g=>g.container===t&&g.blob===o),c=new Map(i.map(g=>[String(g.block_id),g])),u=[],p=[];for(let g of a.order){let E=c.get(g.id);if(!E||g.list==="Committed"&&E.state!=="committed"||g.list==="Uncommitted"&&E.state!=="uncommitted")return h(e,"InvalidBlockList","The specified block list is invalid.",400);let k=await V(E.data_b64,e.root);u.push(k),p.push({id:g.id,size:k.length})}let d=Buffer.concat(u),l=G(d),m=$(e),x=B("blob",n,e.root),f=T("blob",n,e.root),b=C({subject:`blob/${n}`,rev:f,digest:l});await w("blob",n,{object:"blob",container:t,name:o,blob_type:"BlockBlob",data_b64:await te(d,e.root),size:d.length,content_md5:l,content_type:r["x-ms-blob-content-type"]??"application/octet-stream",content_encoding:r["x-ms-blob-content-encoding"]??"",content_language:r["x-ms-blob-content-language"]??"",cache_control:r["x-ms-blob-cache-control"]??"",content_disposition:r["x-ms-blob-content-disposition"]??"",metadata:L(r),created_at:x?String(x.created_at??m):m,last_modified:m,etag:b,rev:f,committed_blocks:p,_deleted:!1},"blob.commit_block_list",e);let y=new Set(p.map(g=>g.id));for(let g of i){let E=String(g.block_id),k=String(g.id);y.has(E)?await w("block",k,{state:"committed",rev:T("block",k,e.root)},"block.commit",e):await w("block",k,{_deleted:!0,rev:T("block",k,e.root)},"block.discard",e)}return R(e,201,{etag:b,"last-modified":v(m),"content-md5":l,"x-ms-request-server-encrypted":"true"})}function Ln(e,t,o,n,r){let s=(t.query.get("blocklisttype")??"committed").toLowerCase();if(s!=="committed"&&s!=="uncommitted"&&s!=="all")return h(e,"InvalidQueryParameterValue","Value for one of the query parameters specified in the request URI is invalid (blocklisttype).",400);let a=B("blob",r,e.root),i=z("block",e.root).filter(d=>d.container===o&&d.blob===n);if(!a&&i.length===0)return h(e,"BlobNotFound","The specified blob does not exist.",404);let c=(a?.committed_blocks??[]).map(d=>({name:String(d.id),size:Number(d.size??0)})),u=i.filter(d=>d.state==="uncommitted").map(d=>({name:String(d.block_id),size:Number(d.size??0)})).sort((d,l)=>d.name<l.name?-1:1),p=ze({...s==="committed"||s==="all"?{committed:c}:{},...s==="uncommitted"||s==="all"?{uncommitted:u}:{}});return D(e,200,p,{...a?{etag:String(a.etag??""),"last-modified":v(String(a.last_modified??a.created_at)),"x-ms-blob-content-length":String(a.size??0)}:{}})}import{applyTwinWrite as on,projectResources as sn}from"../../engine/v2/volter_world-core.mjs";var I={"content-type":"application/json","apim-request-id":F};function N(e){let t={code:e.code,message:e.message};return e.param!==void 0&&(t.param=e.param),e.type!==void 0&&(t.type=e.type),e.echoStatus&&(t.status=e.status),e.innererror!==void 0&&(t.innererror=e.innererror),{status:e.status,headers:{...I},body:JSON.stringify({error:t})}}var K=e=>N({status:404,code:"DeploymentNotFound",message:`The API deployment for this resource does not exist: '${e}'.`,param:"model",type:null}),Pt=e=>N({status:400,code:"content_filter",message:"The response was filtered due to the prompt triggering Azure OpenAI's content management policy. Please modify your prompt and retry.",param:"prompt",type:null,echoStatus:!0,innererror:{code:"ResponsibleAIPolicyViolation",content_filter_result:e}}),Bt=()=>N({status:401,code:"TwinUnauthorized",message:"No credential was presented. Azure OpenAI accepts an `api-key` header or an `Authorization: Bearer` Microsoft Entra token. (Azure does not publish a wire error body for this case; this code is the twin's.)"}),Ke=e=>N({status:401,code:"TwinUnauthorized",message:`The presented credential was not accepted: ${e}. (Azure does not publish a wire error body for this case; this code is the twin's.)`}),Mt=()=>N({status:400,code:"TwinMissingApiVersion",message:"The api-version query parameter (?api-version=) is required on this surface \u2014 every classic Azure OpenAI operation declares it as required. (Azure does not publish a wire error body for this case; this code is the twin's.)",param:"api-version",type:"invalid_request_error"}),ge=e=>N({status:400,code:"TwinInvalidApiVersion",message:`${e} (Azure does not publish a wire error body for this case; this code is the twin's.)`,param:"api-version",type:"invalid_request_error"}),S=(e,t)=>N({status:400,code:"TwinBadRequest",message:e,...t!==void 0?{param:t}:{},type:"invalid_request_error"}),se=(e,t)=>N({status:404,code:"TwinResourceNotFound",message:`Resource not found: ${e} ${t}`}),jt=e=>N({status:404,code:"TwinResponseNotFound",message:`Response with id '${e.length>80?`${e.slice(0,80)}\u2026`:e}' not found. This twin does not STORE responses, so no \`previous_response_id\` can ever resolve \u2014 tracked as the 'azure.openai.responses.retrieve' capability.`,param:"previous_response_id",type:"invalid_request_error"}),P=(e,t)=>N({status:405,code:"TwinMethodNotAllowed",message:`The HTTP method ${e} is not supported for ${t}.`}),Xe=()=>N({status:405,code:"TwinReadOnly",message:"This twin is read-only; writes are refused."}),ye=(e,t,o)=>N({status:501,code:"TwinOperationNotModeled",message:`Azure OpenAI serves ${e} ${t}, but this twin does not model it yet (tracked as the '${o}' capability). This is the twin refusing, not the service: no response is fabricated for an operation that has no handler.`}),Ze=(e,t,o)=>N({status:404,code:"TwinRetiredOperation",message:`${e} is a RETIRED data-plane operation: Azure declared it only at api-version ${o.join(" and ")}, and removed it from 2024-02-01 onward (deployment management moved to Azure Resource Manager). This request used api-version '${t}'.`,param:"api-version"});var ie=[{id:"gpt-4o",version:"2024-11-20",kind:"chat",lifecycleStatus:"generally-available"},{id:"gpt-4o-mini",version:"2024-07-18",kind:"chat",lifecycleStatus:"generally-available"},{id:"gpt-4.1",version:"2025-04-14",kind:"chat",lifecycleStatus:"generally-available"},{id:"gpt-4.1-mini",version:"2025-04-14",kind:"chat",lifecycleStatus:"generally-available"},{id:"gpt-35-turbo",version:"0125",kind:"chat",lifecycleStatus:"generally-available"},{id:"gpt-35-turbo-instruct",version:"0914",kind:"completion",lifecycleStatus:"generally-available"},{id:"text-embedding-3-small",version:"1",kind:"embedding",dimensions:1536,lifecycleStatus:"generally-available"},{id:"text-embedding-3-large",version:"1",kind:"embedding",dimensions:3072,lifecycleStatus:"generally-available"},{id:"text-embedding-ada-002",version:"2",kind:"embedding",dimensions:1536,lifecycleStatus:"generally-available"},{id:"whisper",version:"001",kind:"audio",lifecycleStatus:"generally-available"},{id:"dall-e-3",version:"3.0",kind:"image",lifecycleStatus:"generally-available"}];function X(e){return ie.find(t=>t.id===e)}var Ye=ie.map(e=>({deployment:e.id,model:e.id}));function Qe(e){return{id:e.id,object:"model",created:0,owned_by:"system"}}function _e(e){return{id:e.id,object:"model",created_at:0,status:"succeeded",lifecycle_status:e.lifecycleStatus,capabilities:{chat_completion:e.kind==="chat",completion:e.kind==="completion",embeddings:e.kind==="embedding",fine_tune:!1,inference:!0,scale_types:["standard"]},model:e.id,...e.dimensions!==void 0?{max_output_dimensions:e.dimensions}:{}}}function j(e){let t=2166136261;for(let o=0;o<e.length;o++)t^=e.charCodeAt(o),t=Math.imul(t,16777619);return t>>>0}function O(e){return e?Math.max(1,Math.ceil(e.length/4)):0}function M(e){return typeof e=="string"?e:e==null||!Array.isArray(e)?"":e.map(t=>t&&typeof t=="object"&&t.type==="text"?String(t.text??""):JSON.stringify(t)).join(`
8
+ `)}function qe(e){let t=0;for(let o of e){t+=O(M(o.content)),o.name&&(t+=O(o.name));for(let n of o.tool_calls??[])t+=O(JSON.stringify(n))}return t}function U(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="user")return M(e[t].content);return e.length?M(e[e.length-1].content):""}function ae(e,t,o){let n=U(e).trim(),r=n.length>200?`${n.slice(0,200)}\u2026`:n;return`[twin-stub:azure-openai:${t}:${o}] This is a deterministic stub from the Azure OpenAI twin (no model weights are run). Echoing your last message: ${r||"(empty)"}`}function et(e,t,o){let n=e.length>200?`${e.slice(0,200)}\u2026`:e;return`[twin-stub:azure-openai:${t}:${o}] deterministic completion (no model weights are run). Prompt: ${n||"(empty)"}`}function Ut(e){let t=e;return t?.function&&typeof t.function.name=="string"?t.function.name:typeof t?.name=="string"?t.name:"unknown_function"}function Ft(e){let t=e;if(Array.isArray(t?.enum)&&t.enum.length)return t.enum[0];switch(t?.type){case"number":case"integer":return 0;case"boolean":return!1;case"array":return[];case"object":return{};default:return""}}function Vn(e){let t=e,o=t?.function?.parameters??t?.parameters,n=o&&typeof o=="object"?o.properties:void 0;if(!n||typeof n!="object")return"{}";let r={};for(let[s,a]of Object.entries(n))r[s]=Ft(a);return JSON.stringify(r)}function tt(e,t,o){if(!Array.isArray(e)||e.length===0)return null;let n=o?e.find(s=>Ut(s)===o)??e[0]:e[0],r=Ut(n);return{id:`call_twin_${j(`${r}#${t}`).toString(36)}`,type:"function",function:{name:r,arguments:Vn(n)}}}function Dt(e,t,o){let n=o,r=n?.schema?.properties??n?.properties;if(r&&typeof r=="object"){let s={};for(let[a,i]of Object.entries(r))s[a]=Ft(i);return JSON.stringify(s)}return JSON.stringify({_twin_stub:!0,model:t,echo:U(e).slice(0,200)})}function nt(e,t){let o=Math.max(1,Math.floor(t)),n=j(e)||1,r=new Array(o),s=0;for(let a=0;a<o;a++){n^=n<<13,n>>>=0,n^=n>>17,n^=n<<5,n>>>=0;let i=n/4294967295*2-1;r[a]=i,s+=i*i}s=Math.sqrt(s)||1;for(let a=0;a<o;a++)r[a]=r[a]/s;return r}var Lt=["hate","self_harm","sexual","violence"],Hn={kill:"violence",murder:"violence",attack:"violence",bomb:"violence",hate:"hate",slur:"hate",suicide:"self_harm","self-harm":"self_harm",sexual:"sexual",explicit:"sexual"},Vt=["damn","crap"],Gn=["ignore previous instructions","ignore all previous","dan mode"];function Ht(e){let t=e.toLowerCase(),o={};for(let n of Lt)o[n]={filtered:!1,severity:"safe"};for(let[n,r]of Object.entries(Hn))t.includes(n)&&(o[r]={filtered:!1,severity:"medium"});return o}var Wn=["<!-- system:","disregard the document above"];function Se(e){let t=e.toLowerCase();return{...Ht(e),profanity:{filtered:!1,detected:Vt.some(o=>t.includes(o))},jailbreak:{filtered:!1,detected:Gn.some(o=>t.includes(o))},indirect_attack:{filtered:!1,detected:Wn.some(o=>t.includes(o))}}}function Ae(e){let t=e.toLowerCase();return{...Ht(e),profanity:{filtered:!1,detected:Vt.some(o=>t.includes(o))},protected_material_text:{filtered:!1,detected:!1},protected_material_code:{filtered:!1,detected:!1}}}function Ee(e){return e.map((t,o)=>({prompt_index:o,content_filter_results:Se(t)}))}function ve(e){if(!e)return[];let t=[];for(let o=0;o<e.length;o+=20)t.push(e.slice(o,o+20));return t}import{createHash as Jn}from"node:crypto";var ot=["json","text","srt","verbose_json","vtt"],rt=["word","segment"];function Gt(e,t){let o={parts:[],fields:{},files:{}},n=/boundary=("?)([^";]+)\1/i.exec(t??"");if(!n)return o;let r=Buffer.from(`--${n[2]}`),s=Buffer.from(`\r
9
+ `),a=Buffer.from(`\r
10
+ \r
11
+ `),i=[],c=e.indexOf(r);for(;c>=0;){let d=e.indexOf(r,c+r.length);if(d<0)break;let l=e.subarray(c+r.length,d);l.subarray(0,2).equals(s)&&(l=l.subarray(2));let m=l.indexOf(a);if(m>=0){let x=l.subarray(0,m).toString("utf8"),f=l.subarray(m+a.length);f.length>=2&&f.subarray(f.length-2).equals(s)&&(f=f.subarray(0,f.length-2));let b=/name="([^"]*)"/i.exec(x)?.[1]??"",y=/filename="([^"]*)"/i.exec(x)?.[1],g=/content-type:\s*([^\r\n]+)/i.exec(x)?.[1]?.trim();b!==""&&i.push({name:b,value:Buffer.from(f),...y!==void 0?{filename:y}:{},...g!==void 0?{contentType:g}:{}})}c=d}let u={},p={};for(let d of i)d.filename!==void 0?p[d.name]={bytes:d.value,...d.filename!==""?{filename:d.filename}:{}}:u[d.name]=d.value.toString("utf8");return{parts:i,fields:u,files:p}}function Wt(e,t,o,n){let r=Jn("sha256").update(e).digest("hex").slice(0,16),s=[`[twin-stub:azure-openai:${t}:${o}] This is a deterministic transcript from the Azure OpenAI twin; no audio was decoded and no model weights were run.`,`The upload was ${e.length} bytes and hashes to ${r}.`,n?`The caller's prompt was: ${n}.`:"The caller supplied no prompt."],a=Math.max(1,Math.round(e.length/16e3)),i=a/s.length,c=s.map((u,p)=>({id:p,start:Number((p*i).toFixed(3)),end:Number(((p+1)*i).toFixed(3)),text:u}));return{text:s.join(" "),segments:c,durationSeconds:a}}function Jt(e){let t=[];for(let o of e){let n=o.text.split(/\s+/).filter(Boolean),r=(o.end-o.start)/Math.max(1,n.length);n.forEach((s,a)=>{t.push({word:s,start:Number((o.start+a*r).toFixed(3)),end:Number((o.start+(a+1)*r).toFixed(3))})})}return t}function Te(e,t){let o=Math.floor(e),n=Math.round((e-o)*1e3),r=String(Math.floor(o/3600)).padStart(2,"0"),s=String(Math.floor(o%3600/60)).padStart(2,"0"),a=String(o%60).padStart(2,"0");return`${r}:${s}:${a}${t}${String(n).padStart(3,"0")}`}function Kt(e){return e.map((t,o)=>`${o+1}
12
+ ${Te(t.start,",")} --> ${Te(t.end,",")}
13
+ ${t.text}
14
+ `).join(`
15
+ `)}function Xt(e){return`WEBVTT
16
+
17
+ ${e.map(t=>`${Te(t.start,".")} --> ${Te(t.end,".")}
18
+ ${t.text}
19
+ `).join(`
20
+ `)}`}function Zt(e,t){let o="";for(let n=0;o.length<32;n+=1)o+=j(`${n}:${t}`).toString(16).padStart(8,"0");return`${e}_${o.slice(0,32)}`}function Yt(e,t){let o=ae(e.input,e.deployment,e.modelId),n=e.maxOutputTokens,r=n!==void 0&&O(o)>n,s=r?o.slice(0,n*4):o,a=e.input.reduce((p,d)=>p+O(typeof d.content=="string"?d.content:JSON.stringify(d.content??"")),0)+(e.instructions?O(e.instructions):0),i=O(s),c=Zt("resp",JSON.stringify([e.input,e.deployment,e.modelId,e.instructions??null,n??null])),u=Zt("msg",c);return{id:c,object:"response",created_at:t,status:r?"incomplete":"completed",error:null,incomplete_details:r?{reason:"max_output_tokens"}:null,model:e.modelId,instructions:e.instructions??null,max_output_tokens:n??null,metadata:e.metadata??{},parallel_tool_calls:e.parallelToolCalls,temperature:e.temperature??null,top_p:e.topP??null,truncation:e.truncation??"disabled",previous_response_id:null,reasoning:e.reasoning??{effort:null,summary:null},text:e.text??{format:{type:"text"}},tools:e.tools??[],tool_choice:e.toolChoice??"auto",store:!1,...e.user!==void 0?{user:e.user}:{},output:[{id:u,type:"message",role:"assistant",status:r?"incomplete":"completed",content:[{type:"output_text",text:s,annotations:[]}]}],output_text:s,usage:{input_tokens:a,input_tokens_details:{cached_tokens:0},output_tokens:i,output_tokens_details:{reasoning_tokens:0},total_tokens:a+i}}}function st(e,t){let o=0,n=(i,c)=>{t({event:i,data:{...c,type:i,sequence_number:o++}})},r={...e,status:"in_progress",output:[],output_text:"",incomplete_details:null};n("response.created",{response:r}),n("response.in_progress",{response:r});let s=e.output[0],a=s.content[0].text;n("response.output_item.added",{output_index:0,item:{...s,status:"in_progress",content:[]}}),n("response.content_part.added",{item_id:s.id,output_index:0,content_index:0,part:{type:"output_text",text:"",annotations:[]}});for(let i of ve(a))n("response.output_text.delta",{item_id:s.id,output_index:0,content_index:0,delta:i,logprobs:[]});n("response.output_text.done",{item_id:s.id,output_index:0,content_index:0,text:a,logprobs:[]}),n("response.content_part.done",{item_id:s.id,output_index:0,content_index:0,part:s.content[0]}),n("response.output_item.done",{output_index:0,item:s}),e.status==="incomplete"?n("response.incomplete",{response:e}):n("response.completed",{response:e})}import{getActiveWorldStore as Kn,parseScenarioDocument as Xn,ScenarioError as Zn,ScenarioEngine as Yn}from"../../engine/v2/volter_world-core.mjs";var Qt=new Set(["text","toolCalls","finishReason","contentFilter"]),qt=new Set(["stop","length","tool_calls","content_filter"]),en=new Set(["hate","self_harm","sexual","violence"]),Z=e=>typeof e=="string"&&e.length>0;function tn(e){let t=new Set,o=e[e.length-1];if(!o||o.role!=="tool"||typeof o.tool_call_id!="string")return t;for(let n of e){let r=n;if(!(r.role!=="assistant"||!Array.isArray(r.tool_calls)))for(let s of r.tool_calls)s?.id===o.tool_call_id&&typeof s?.function?.name=="string"&&t.add(s.function.name)}return t}function nn(e){return Array.isArray(e)?e.map(t=>typeof t?.function?.name=="string"?t.function.name:typeof t?.name=="string"?t.name:null).filter(t=>t!==null):[]}var it={vendor:"azure",features:e=>({deployment:e.deployment,model:e.model,lastUserText:U(e.messages).slice(0,300),tools:nn(e.tools),lastMessageIsToolResult:e.messages[e.messages.length-1]?.role==="tool",toolResultFor:[...tn(e.messages)]}),matchers:{deploymentEquals:(e,t)=>Z(t)&&e.deployment===t,modelEquals:(e,t)=>Z(t)&&e.model===t,userTextIncludes:(e,t)=>Z(t)&&U(e.messages).toLowerCase().includes(t.toLowerCase()),anyTextIncludes:(e,t)=>Z(t)&&e.messages.map(o=>M(o.content)).join(`
21
+ `).toLowerCase().includes(t.toLowerCase()),lastMessageIsToolResult:(e,t)=>typeof t=="boolean"&&e.messages[e.messages.length-1]?.role==="tool"===t,toolResultFor:(e,t)=>Z(t)&&tn(e.messages).has(t),hasTool:(e,t)=>Z(t)&&nn(e.tools).includes(t)},text:e=>e.messages.map(t=>M(t.content)).join(`
22
+ `),scopeKey:e=>e.user??"",validateOn:e=>{for(let t of["deploymentEquals","modelEquals","userTextIncludes","anyTextIncludes","toolResultFor","hasTool"])if(e[t]!==void 0&&(typeof e[t]!="string"||!e[t]))return`on.${t} is a non-empty string`;return e.lastMessageIsToolResult!==void 0&&typeof e.lastMessageIsToolResult!="boolean"?"on.lastMessageIsToolResult is a boolean":null},validateRespond:e=>{if(typeof e!="object"||e===null||Array.isArray(e))return"respond is an object { text?, toolCalls?, finishReason?, contentFilter? }";let t=e;for(let o of Object.keys(t))if(!Qt.has(o))return`respond: unknown key "${o}" (valid: ${[...Qt].join(", ")})`;if(t.text!==void 0&&typeof t.text!="string")return"respond.text is a string";if(t.finishReason!==void 0&&(typeof t.finishReason!="string"||!qt.has(t.finishReason)))return`respond.finishReason is one of ${[...qt].join(", ")}`;if(t.toolCalls!==void 0)for(let o of Array.isArray(t.toolCalls)?t.toolCalls:[t.toolCalls]){let n=o;if(!n||typeof n!="object"||Array.isArray(n))return"respond.toolCalls entries are objects";if(typeof n.name!="string"||!n.name)return"respond.toolCalls[].name is a non-empty string";if(!n.arguments||typeof n.arguments!="object"||Array.isArray(n.arguments))return"respond.toolCalls[].arguments is an object";if(n.id!==void 0&&typeof n.id!="string")return"respond.toolCalls[].id is a string"}if(t.contentFilter!==void 0){let o=t.contentFilter;if(!o||typeof o!="object"||Array.isArray(o))return"respond.contentFilter is an object { category, on? }";if(typeof o.category!="string"||!en.has(o.category))return`respond.contentFilter.category is one of ${[...en].join(", ")}`;if(o.on!==void 0&&o.on!=="prompt"&&o.on!=="completion")return"respond.contentFilter.on is 'prompt' or 'completion'";if(o.on!=="completion"&&(t.text!==void 0||t.toolCalls!==void 0))return"respond.contentFilter on the prompt is a refusal: it cannot be combined with text/toolCalls"}return t.text===void 0&&t.toolCalls===void 0&&t.contentFilter===void 0?"respond needs text, toolCalls or contentFilter":null}};function at(e){let t;try{let o=Kn().read(e);if(o===null)throw new Error(`ENOENT: no such file or directory, open '${e}'`);t=JSON.parse(o)}catch(o){throw new Zn(`azure scenario: cannot read/parse ${e}: ${o instanceof Error?o.message:String(o)}`)}return Xn(t,it)}function ct(e){return new Yn(it,e)}function lt(e){let t=[];(e.toolCalls?Array.isArray(e.toolCalls)?e.toolCalls:[e.toolCalls]:[]).forEach((r,s)=>{t.push({id:r.id??`call_scripted_${j(`${r.name}#${s}#${JSON.stringify(r.arguments)}`).toString(36)}`,type:"function",function:{name:r.name,arguments:JSON.stringify(r.arguments)}})});let n=e.contentFilter?{category:e.contentFilter.category,on:e.contentFilter.on??"prompt"}:null;return{text:e.text??(t.length||n&&n.on==="prompt"?null:""),toolCalls:t,finishReason:e.finishReason??(t.length?"tool_calls":n?.on==="completion"?"content_filter":"stop"),contentFilter:n}}var q="azure-openai";var an=[{match:/^\/openai\/(v1\/)?responses\/[^/]+\/input_items$/,method:"GET",capability:"azure.openai.responses.input_items"},{match:/^\/openai\/(v1\/)?responses\/[^/]+$/,method:"DELETE",capability:"azure.openai.responses.delete"},{match:/^\/openai\/(v1\/)?responses\/[^/]+$/,method:"GET",capability:"azure.openai.responses.retrieve"},{match:/^\/openai\/(v1\/|deployments\/[^/]+\/)?audio\/translations$/,capability:"azure.openai.audio.translations"},{match:/^\/openai\/(v1\/|deployments\/[^/]+\/)?audio\/speech$/,capability:"azure.openai.audio.speech"},{match:/^\/openai\/(v1\/|deployments\/[^/]+\/)?images\/generations$/,capability:"azure.openai.images.generations"},{match:/^\/openai\/(v1\/|deployments\/[^/]+\/)?images\/edits$/,capability:"azure.openai.images.edits"},{match:/^\/openai\/(v1\/|deployments\/[^/]+\/)?files(\/|$)/,capability:"azure.openai.files.upload"},{match:/^\/openai\/(v1\/|deployments\/[^/]+\/)?batches(\/|$)/,capability:"azure.openai.batch.create"},{match:/^\/openai\/(v1\/)?fine_tuning(\/|$)/,capability:"azure.openai.fine_tuning.create_job"},{match:/^\/openai\/(v1\/)?assistants(\/|$)/,capability:"azure.openai.assistants.create"},{match:/^\/openai\/(v1\/)?threads(\/|$)/,capability:"azure.openai.threads.create"},{match:/^\/openai\/(v1\/)?vector_stores(\/|$)/,capability:"azure.openai.vector_stores.create"},{match:/^\/openai\/(v1\/)?evals(\/|$)/,capability:"azure.openai.evaluations.create"},{match:/^\/openai\/(v1\/)?realtime(\/|$)/,capability:"azure.openai.realtime.session"},{match:/^\/openai\/deployments\/[^/]+\/extensions\/chat\/completions$/,capability:"azure.openai.on_your_data"}];function cn(e){let t={};for(let[o,n]of Object.entries(e??{}))t[o.toLowerCase()]=n;return t}var Y=(e,t={})=>({status:200,headers:{...I,...t},body:JSON.stringify(e)});function qn(e){return e===void 0?"":typeof e=="string"?e:Buffer.from(e).toString("utf8")}function pt(e){let t=e?Date.parse(e):Number.NaN;return Number.isNaN(t)?0:Math.floor(t/1e3)}function ln(e){return j(JSON.stringify(e)).toString(36)}var ce=["2022-12-01","2023-03-15-preview"],eo=/^\d{4}-\d{2}-\d{2}(-preview)?$/,to=new Set(["v1","preview"]);function we(e){return eo.test(e)?"dated":to.has(e)?"v1-token":"malformed"}function no(e){return new Set(sn(q,e).filter(t=>t.type==="deployment"&&t._deleted).map(t=>String(t.id)))}function ft(e){let t=no(e),o=sn(q,e).filter(s=>s.type==="deployment"&&!s._deleted).map(s=>({deployment:String(s.id),model:String(s.model??s.id),source:"state"})),n=new Set(o.map(s=>s.deployment));return[...Ye.filter(s=>!n.has(s.deployment)&&!t.has(s.deployment)).map(s=>({...s,source:"default"})),...o].sort((s,a)=>s.deployment.localeCompare(a.deployment))}function Q(e,t){return ft(t).find(o=>o.deployment===e)}function dt(e){let t=X(e.model);return{id:e.deployment,object:"deployment",status:"succeeded",model:e.model,...t?{model_version:t.version}:{},owner:"organization-owner",scale_settings:{scale_type:"standard"},created_at:0,updated_at:0}}function oo(e){for(let t of["max_completion_tokens","max_tokens"]){let o=e[t];if(o!=null)return typeof o!="number"||!Number.isInteger(o)||o<1?{error:S(`'${t}' must be an integer >= 1.`,t)}:{value:o}}return{}}function ke(e){if(!e.trim())return{error:S("The request body is empty; a JSON object is required.")};try{let t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?{error:S("The request body must be a JSON object.")}:{params:t}}catch{return{error:S("The request body is not valid JSON.")}}}function ro(e,t){if(!Array.isArray(e.messages))return{error:S("Missing required parameter: 'messages'.","messages")};if(e.messages.length===0)return{error:S("[] is too short - 'messages'.","messages")};let o=e.messages;for(let l of o)if(!l||typeof l!="object"||typeof l.role!="string")return{error:S("Each message must carry a 'role'.","messages")};let n=1;if(e.n!==void 0&&(n=Number(e.n),!Number.isInteger(n)||n<1))return{error:S("'n' must be an integer >= 1.","n")};let r=e.stream===!0,s=e.stream_options,a,i=e.tool_choice;if(i&&typeof i=="object"){let l=i.function;typeof l?.name=="string"&&(a=l.name)}let c=oo(e);if("error"in c)return{error:c.error};let u="text",p,d=e.response_format;return d&&typeof d=="object"&&(d.type==="json_object"?u="json_object":d.type==="json_schema"&&(u="json_schema",p=d.json_schema)),{args:{deployment:t.deployment,model:X(t.model),modelId:t.model,messages:o,...e.tools!==void 0?{tools:e.tools}:{},n,stream:r,streamOptionsIncludeUsage:s?.include_usage===!0,...a!==void 0?{toolChoiceName:a}:{},responseFormat:u,...p!==void 0?{jsonSchema:p}:{},...typeof e.user=="string"?{user:e.user}:{},...c.value!==void 0?{maxOutputTokens:c.value}:{}}}}function so(e,t){if(!t)return{scripted:null,miss:""};let o=t.next({deployment:e.deployment,model:e.modelId,messages:e.messages,...e.tools!==void 0?{tools:e.tools}:{},...e.user!==void 0?{user:e.user}:{}});return o.kind==="handler"?{scripted:lt(o.respond),miss:""}:{scripted:null,miss:`
23
+ [twin-scenario miss \u2014 no handler matched. Author one in the world dir's handlers/azure.json (GET /twin explains; GET /twin/scenario lists handlers + misses). Features seen: ${JSON.stringify(o.miss.features)}]`}}function io(e,t,o){let{scripted:n,miss:r}=so(e,o);if(n?.contentFilter&&n.contentFilter.on==="prompt"){let c=Se(U(e.messages));return Pt({...c,[n.contentFilter.category]:{filtered:!0,severity:"high"}})}let s=qe(e.messages),a=[],i=0;for(let c=0;c<e.n;c++){let u,p,d=n?.toolCalls??[];if(n)u=n.text,p=n.finishReason;else{let f=e.tools!==void 0?tt(e.tools,c,e.toolChoiceName):null;f?(d=[f],u=null,p="tool_calls"):(u=e.responseFormat==="text"?ae(e.messages,e.deployment,e.modelId)+r:Dt(e.messages,e.modelId,e.jsonSchema),p="stop")}e.maxOutputTokens!==void 0&&d.length===0&&u!==null&&O(u)>e.maxOutputTokens&&(u=u.slice(0,e.maxOutputTokens*4),p="length");let l=d.length?{role:"assistant",content:u,refusal:null,tool_calls:d}:{role:"assistant",content:u??"",refusal:null},m=d.length?JSON.stringify(d):u??"";i+=O(m);let x=Ae(m);n?.contentFilter&&n.contentFilter.on==="completion"&&(x[n.contentFilter.category]={filtered:!0,severity:"high"}),a.push({index:c,message:l,logprobs:null,finish_reason:p,content_filter_results:x})}return{id:`chatcmpl-twin-${ln([e.messages,e.deployment,e.modelId,e.n])}`,object:"chat.completion",created:pt(t),model:e.modelId,choices:a,usage:{prompt_tokens:s,completion_tokens:i,total_tokens:s+i},system_fingerprint:"fp_twin_azure",prompt_filter_results:Ee([e.messages.map(c=>M(c.content)).join(`
24
+ `)])}}function ut(e,t,o){o({data:{id:"",object:"",created:0,model:"",choices:[],prompt_filter_results:e.prompt_filter_results??[]}});let n={id:e.id,object:"chat.completion.chunk",created:e.created,model:e.model,system_fingerprint:e.system_fingerprint};for(let r of e.choices){let s=r.index;o({data:{...n,choices:[{index:s,delta:{role:"assistant",content:""},logprobs:null,finish_reason:null}]}});let a=r.message.tool_calls??[];if(a.length)a.forEach((i,c)=>{o({data:{...n,choices:[{index:s,delta:{tool_calls:[{index:c,id:i.id,type:"function",function:{name:i.function.name,arguments:""}}]},logprobs:null,finish_reason:null}]}}),o({data:{...n,choices:[{index:s,delta:{tool_calls:[{index:c,function:{arguments:i.function.arguments}}]},logprobs:null,finish_reason:null}]}})});else for(let i of ve(r.message.content??""))o({data:{...n,choices:[{index:s,delta:{content:i},logprobs:null,finish_reason:null}]}});o({data:{...n,choices:[{index:s,delta:{},logprobs:null,finish_reason:r.finish_reason,content_filter_results:r.content_filter_results}]}})}t&&o({data:{...n,choices:[],usage:e.usage}}),o({done:!0})}function ao(e,t,o){let n=e.map((a,i)=>{let c=et(a,t.deployment,t.model);return{text:c,index:i,logprobs:null,finish_reason:"stop",content_filter_results:Ae(c)}}),r=e.reduce((a,i)=>a+O(i),0),s=n.reduce((a,i)=>a+O(i.text),0);return{id:`cmpl-twin-${ln([e,t.deployment])}`,object:"text_completion",created:pt(o),model:t.model,choices:n,usage:{prompt_tokens:r,completion_tokens:s,total_tokens:r+s},prompt_filter_results:Ee(e)}}function co(e){let t=Buffer.alloc(e.length*4);return e.forEach((o,n)=>t.writeFloatLE(o,n*4)),t.toString("base64")}function lo(e,t,o,n){let r=X(t.model),s=o??r?.dimensions??1536,a=e.map((c,u)=>{let p=nt(c,s);return{object:"embedding",index:u,embedding:n==="base64"?co(p):p}}),i=e.reduce((c,u)=>c+O(u),0);return{object:"list",data:a,model:t.model,usage:{prompt_tokens:i,total_tokens:i}}}async function mt(e){let t=(e.method??"GET").toUpperCase(),[o="/",n=""]=(e.path??"/").split("?"),r=o.replace(/\/+$/,"")||"/",s=new URLSearchParams(n),a=cn(e.headers),i=qn(e.body),c=a["api-key"]??"",u=a.authorization??"";if(!c&&!u)return Bt();if(!c){let f=/^Bearer\s+(.+)$/i.exec(u.trim());if(!f)return Ke(`unsupported Authorization scheme '${u.split(" ")[0]??""}'`);let b=f[1];if(b.split(".").length===3){let y=oe(b,"cognitiveservices");if(!y.accepted)return Ke(y.reason)}}if(r==="/openai/_twin/deployments"){if(t!=="POST")return P(t,r);if(e.readOnly)return Xe();let f=ke(i);if("error"in f)return f.error;let b=typeof f.params.deployment=="string"?f.params.deployment:"",y=typeof f.params.model=="string"?f.params.model:"";return!b||!y?S("Seeding a deployment needs 'deployment' and 'model'.","deployment"):(await on(q,{operation:"deployment.create",subjectType:"deployment",subjectId:b,fields:{id:b,model:y,_deleted:!1},...e.occurredAt?{occurredAt:e.occurredAt}:{},actor:{kind:"agent"}},e.root),{status:201,headers:I,body:JSON.stringify(dt({deployment:b,model:y,source:"state"}))})}let p=/^\/openai\/_twin\/deployments\/([^/]+)$/.exec(r);if(p){if(t!=="DELETE")return P(t,r);if(e.readOnly)return Xe();let f=decodeURIComponent(p[1]);return Q(f,e.root)?(await on(q,{operation:"deployment.delete",subjectType:"deployment",subjectId:f,fields:{id:f,_deleted:!0},...e.occurredAt?{occurredAt:e.occurredAt}:{},actor:{kind:"agent"}},e.root),{status:204,headers:I,body:""}):K(f)}let d=r.startsWith("/openai/v1/")||r==="/openai/v1",l=s.get("api-version");if(d){if(l!==null&&we(l)!=="v1-token")return ge(`The api-version '${l}' is not valid on the /openai/v1 surface, whose api-version parameter is a closed set of 'v1' and 'preview' (default 'v1').`)}else{if(l===null)return Mt();if(we(l)==="malformed")return ge(`The api-version '${l}' is not a recognised version. The classic surface takes a dated version such as '2024-10-21'.`);if(we(l)==="v1-token")return ge(`The api-version '${l}' belongs to the /openai/v1 surface and is not valid on the classic surface. Use a dated api-version such as '2025-04-01-preview'.`)}for(let f of an)if(!(f.method!==void 0&&f.method!==t)&&f.match.test(r))return ye(t,r,f.capability);if(r==="/openai/models"||r==="/openai/v1/models"){if(t!=="GET")return P(t,r);let f=d?Qe:_e;return Y({object:"list",data:ie.map(f)})}let m=/^\/openai\/(?:v1\/)?models\/([^/]+)$/.exec(r);if(m){if(t!=="GET")return P(t,r);let f=decodeURIComponent(m[1]),b=X(f);return b?Y(d?Qe(b):_e(b)):se(t,r)}if(r==="/openai/deployments")return ce.includes(l??"")?t!=="GET"?ye(t,r,"azure.openai.deployments.legacy_data_plane_write"):Y({object:"list",data:ft(e.root).map(dt)}):Ze(r,l??"",ce);if(r==="/openai/responses"||r==="/openai/v1/responses"){if(t!=="POST")return P(t,r);let f=ke(i);if("error"in f)return f.error;let b=po(f.params,e.root);if("error"in b)return b.error;let y=b.args,g=Yt(y,pt(e.occurredAt));if(!y.stream)return{status:200,headers:I,body:JSON.stringify(g)};let E={...I,"content-type":"text/event-stream; charset=utf-8"};if(e.sseSink)return st(g,e.sseSink),{status:200,headers:E,body:""};let k=[];return st(g,le=>{k.push(le.done?`data: [DONE]
25
+
26
+ `:`${le.event?`event: ${le.event}
27
+ `:""}data: ${JSON.stringify(le.data)}
28
+
29
+ `)}),{status:200,headers:E,body:k.join("")}}let x=/^\/openai\/deployments\/([^/]+)(\/.*)?$/.exec(r);if(x){let f=decodeURIComponent(x[1]),b=x[2]??"";if(b===""){if(!ce.includes(l??""))return Ze(r,l??"",ce);if(t!=="GET")return ye(t,r,"azure.openai.deployments.legacy_data_plane_write");let g=Q(f,e.root);return g?Y(dt(g)):K(f)}let y=Q(f,e.root);return y?rn(b,t,y,e,i):K(f)}if(d){let f=r.slice(10);if(!new Set(["/chat/completions","/completions","/embeddings"]).has(f))return se(t,r);if(t!=="POST")return P(t,r);let y=ke(i);if("error"in y)return y.error;let g=y.params.model;if(typeof g!="string"||g==="")return S("Missing required parameter: 'model' (on the /openai/v1 surface the deployment is named in the body).","model");let E=Q(g,e.root);return E?rn(f,t,E,e,i):K(g)}return se(t,r)}async function rn(e,t,o,n,r){if(e==="/audio/transcriptions")return t!=="POST"?P(t,e):uo(o,n);if(e!=="/chat/completions"&&e!=="/completions"&&e!=="/embeddings")return se(t,n.path.split("?")[0]??e);if(t!=="POST")return P(t,e);let s=ke(r);if("error"in s)return s.error;let a=s.params;if(e==="/chat/completions"){let l=ro(a,o);if("error"in l)return l.error;let m=l.args,x=io(m,n.occurredAt,n.scenarioEngine);if("status"in x)return x;let f=x;if(m.stream){if(n.sseSink)return ut(f,m.streamOptionsIncludeUsage,n.sseSink),{status:200,headers:{...I,"content-type":"text/event-stream; charset=utf-8"},body:""};let b=[];return ut(f,m.streamOptionsIncludeUsage,y=>b.push(y.done?`data: [DONE]
30
+
31
+ `:`data: ${JSON.stringify(y.data)}
32
+
33
+ `)),{status:200,headers:{...I,"content-type":"text/event-stream; charset=utf-8"},body:b.join("")}}return{status:200,headers:I,body:JSON.stringify(f)}}if(e==="/completions"){let l=a.prompt,m;if(typeof l=="string")m=[l];else if(Array.isArray(l)&&l.every(x=>typeof x=="string"))m=l;else return S("Missing required parameter: 'prompt' (a string or an array of strings).","prompt");return{status:200,headers:I,body:JSON.stringify(ao(m,o,n.occurredAt))}}let i=a.input,c;if(typeof i=="string")c=[i];else if(Array.isArray(i)&&i.every(l=>typeof l=="string"))c=i;else return S("Missing required parameter: 'input' (a string or an array of strings).","input");let u=typeof a.dimensions=="number"?a.dimensions:void 0,p=a.encoding_format;return p!==void 0&&p!=="float"&&p!=="base64"?S("'encoding_format' must be 'float' or 'base64'.","encoding_format"):{status:200,headers:I,body:JSON.stringify(lo(c,o,u,p==="base64"?"base64":"float"))}}function uo(e,t){let n=cn(t.headers)["content-type"]??"";if(!/^multipart\/form-data/i.test(n))return S("The audio transcription endpoint expects a 'multipart/form-data' body carrying a 'file' part.");let r=t.body===void 0?Buffer.alloc(0):Buffer.isBuffer(t.body)?t.body:Buffer.from(t.body),s=Gt(r,n),a=s.files.file;if(!a||a.bytes.length===0)return S("Missing required parameter: 'file' (the audio file to transcribe).","file");let i=s.fields.response_format;if(i!==void 0&&!ot.includes(i))return S(`'response_format' must be one of ${ot.join(", ")}.`,"response_format");let c=i??"json",u=s.parts.filter(f=>f.name==="timestamp_granularities[]").map(f=>f.value.toString("utf8"));for(let f of u)if(!rt.includes(f))return S(`'timestamp_granularities[]' must be one of ${rt.join(", ")}.`,"timestamp_granularities[]");if(u.length>0&&c!=="verbose_json")return S("'timestamp_granularities[]' requires 'response_format' to be 'verbose_json'.","timestamp_granularities[]");let p=s.fields.prompt,{text:d,segments:l,durationSeconds:m}=Wt(a.bytes,e.deployment,e.model,p),x={...I,"content-type":"text/plain; charset=utf-8"};return c==="text"?{status:200,headers:x,body:d}:c==="srt"?{status:200,headers:x,body:Kt(l)}:c==="vtt"?{status:200,headers:x,body:Xt(l)}:Y(c==="json"?{text:d}:{text:d,task:"transcribe",language:s.fields.language??"english",duration:m,segments:l,...u.includes("word")?{words:Jt(l)}:{}})}function po(e,t){let o=e.model;if(typeof o!="string"||o==="")return{error:S("Missing required parameter: 'model' (the Responses API names the deployment in the body).","model")};let n=Q(o,t);if(!n)return{error:K(o)};let r=e.input,s;if(typeof r=="string")s=[{role:"user",content:r}];else if(Array.isArray(r)&&r.length>0)s=r;else return{error:S("Missing required parameter: 'input' (a string, or a non-empty array of input items).","input")};if(e.previous_response_id!==void 0&&e.previous_response_id!==null)return typeof e.previous_response_id!="string"||e.previous_response_id===""?{error:S("'previous_response_id' must be the id of a previous response.","previous_response_id")}:{error:jt(e.previous_response_id)};let a;if(e.max_output_tokens!==void 0&&e.max_output_tokens!==null){let i=e.max_output_tokens;if(typeof i!="number"||!Number.isInteger(i)||i<1)return{error:S("'max_output_tokens' must be an integer >= 1.","max_output_tokens")};a=i}return{args:{deployment:n.deployment,modelId:n.model,input:s,...typeof e.instructions=="string"?{instructions:e.instructions}:{},...a!==void 0?{maxOutputTokens:a}:{},...e.metadata!==null&&typeof e.metadata=="object"?{metadata:e.metadata}:{},stream:e.stream===!0,store:e.store!==!1,parallelToolCalls:e.parallel_tool_calls!==!1,...typeof e.temperature=="number"?{temperature:e.temperature}:{},...typeof e.top_p=="number"?{topP:e.top_p}:{},...typeof e.user=="string"?{user:e.user}:{},...typeof e.truncation=="string"?{truncation:e.truncation}:{},...e.reasoning!==null&&typeof e.reasoning=="object"?{reasoning:e.reasoning}:{},...e.text!==null&&typeof e.text=="object"?{text:e.text}:{},...Array.isArray(e.tools)?{tools:e.tools}:{},...e.tool_choice!==void 0?{toolChoice:e.tool_choice}:{}}}}function dn(e,t,o){return e.hosts.some(n=>(n.host!==void 0?t===n.host:n.suffix!==void 0?t.endsWith(n.suffix):!1)?n.pathPattern===void 0||new RegExp(n.pathPattern).test(o):!1)}function un(e){if(e.area)return e.area;let t=(e.host??"").split(":")[0]?.toLowerCase()??"",n=(e.path??"/").split("?")[0]??"/";if(t){for(let s of ee)if(s.id!=="blob"&&dn(s,t,n))return s.id;if(dn(de("blob"),t,n))return"blob";let r=ee.find(s=>s.id!=="blob"&&s.hosts.some(a=>a.pathPattern===void 0&&(a.host!==void 0?t===a.host:a.suffix!==void 0&&t.endsWith(a.suffix))));if(r)return r.id}return/^\/openai\//.test(n)?"openai":/^\/[^/]+\/oauth2\//.test(n)||n==="/common/discovery/keys"?"entra":"blob"}function Oe(e){return de(un(e))}function fo(e){if(!((e.host??"").split(":")[0]?.toLowerCase()??"").endsWith(".cognitiveservices.azure.com")||e.area!==void 0)return!1;let o=(e.path??"/").split("?")[0]??"/";return!/^\/openai\//.test(o)}async function Re(e){if(fo(e))return fe("openai-json",{code:"TwinUnclaimedCognitiveServicesPath",message:`${e.path??"/"} is on the shared *.cognitiveservices.azure.com domain but belongs to no service area of this pack: it owns /openai/* only, and the azureformrecognizer pack owns /documentintelligence/* and /formrecognizer/*. Refusing loudly rather than answering from the wrong area.`,status:404});let t=Oe(e);if(t.status!=="built")return fe(t.wire,{code:t.notServed.code,message:t.notServed.message,status:t.notServed.status});if(t.id==="openai"){let n={method:e.method??"GET",path:e.path??"/",...e.headers!==void 0?{headers:e.headers}:{},...e.body!==void 0?{body:e.body}:{},...e.host!==void 0?{host:e.host}:{},...e.occurredAt!==void 0?{occurredAt:e.occurredAt}:{},...e.root!==void 0?{root:e.root}:{},...e.readOnly!==void 0?{readOnly:e.readOnly}:{},...e.scenarioEngine!==void 0?{scenarioEngine:e.scenarioEngine}:{},...e.sseSink!==void 0?{sseSink:e.sseSink}:{}};return mt(n)}let o={method:e.method??"GET",path:e.path??"/",...e.headers!==void 0?{headers:e.headers}:{},...e.body!==void 0?{body:e.body}:{},...e.host!==void 0?{host:e.host}:{},...e.endpoint!==void 0?{endpoint:e.endpoint}:{},...e.occurredAt!==void 0?{occurredAt:e.occurredAt}:{},...e.root!==void 0?{root:e.root}:{},...e.readOnly!==void 0?{readOnly:e.readOnly}:{}};return We(o)}import{serveHttp as lr}from"../../engine/v2/volter_world-core.mjs";import{worldNow as pn,twinManifest as mo}from"../../engine/v2/volter_world-core.mjs";function bo(e,t){let o=e.replace(/\/+$/,"");if(!(/^\/openai\/(v1\/|deployments\/[^/]+\/)chat\/completions$/.test(o)||/^\/openai\/(v1\/)?responses$/.test(o))||!t||t.length===0)return!1;try{return JSON.parse(t.toString("utf8"))?.stream===!0}catch{return!1}}function fn(e={}){let t=e.readOnly??!1,o=e.scenarioPath??process.env.TWIN_AZURE_SCENARIO,n=o?ct(at(o)):void 0;return async function(s){let a=new URL(s.url);if(s.method==="GET"&&a.pathname.replace(/\/+$/,"")==="/twin")return Response.json(mo({vendor:"azure",twinOf:"Azure \u2014 service areas over one endpoint: Blob Storage (area 1) and Azure OpenAI (area 2)",stateSentence:"Stateful: Blob Storage containers, block blobs and staged blocks are created through the vendor's OWN API (@azure/storage-blob, a connection string, plain fetch). Azure OpenAI deployments come from the connector's pull of a real resource or the twin-only POST /openai/_twin/deployments seed route \u2014 the Azure DATA plane has no create-deployment operation at any current api-version (that is ARM, a different host), so there is no vendor API to seed through.",behaviorSentence:"Azure OpenAI chat completions are scripted by MSW-shaped handlers in the world dir (handlers/azure.json): {on:{deploymentEquals|modelEquals|userTextIncludes|anyTextIncludes|hasTool|toolResultFor|lastMessageIsToolResult|nthCall}, respond:{text|toolCalls|contentFilter, finishReason?}, once?, phase?}. Unmatched requests answer a labeled [twin-stub:azure-openai:\u2026] naming this door. Storage is state, not scripting.",exampleHandler:{on:{deploymentEquals:"gpt-4o",userTextIncludes:"summarize"},respond:{text:"Scripted summary."},once:!0},engine:n}));if(s.method==="GET"&&a.pathname.replace(/\/+$/,"")==="/twin/scenario")return Response.json(n?n.status():{vendor:"azure",handlers:[],misses:0,recentMisses:[]});let i=s.headers.get("host")??a.host,c=typeof e.endpoint=="function"?e.endpoint():e.endpoint??i,u={};s.headers.forEach((f,b)=>u[b]=f);let d=s.method==="GET"||s.method==="HEAD"?void 0:Buffer.from(await s.arrayBuffer());if(!t&&s.method.toUpperCase()==="POST"&&bo(a.pathname,d)){let f=[],b=await Re({method:s.method,path:a.pathname+(a.search||""),headers:u,...d!==void 0?{body:d}:{},host:i,endpoint:c,readOnly:t,occurredAt:pn(),...e.root!==void 0?{root:e.root}:{},...n?{scenarioEngine:n}:{},sseSink:E=>f.push(E)});if(b.status>=400){let E=typeof b.body=="string"?b.body:Buffer.from(b.body).toString("utf8");return new Response(E,{status:b.status,headers:{"content-type":"application/json",server:"Volter-Twin-Azure/1.0",...b.headers??{}}})}let y=new TextEncoder,g=new ReadableStream({start(E){for(let k of f)E.enqueue(y.encode(k.done?`data: [DONE]
34
+
35
+ `:`${k.event?`event: ${k.event}
36
+ `:""}data: ${JSON.stringify(k.data)}
37
+
38
+ `));E.close()}});return new Response(g,{headers:{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",server:"Volter-Twin-Azure/1.0"}})}let l;try{l=await Re({method:s.method,path:a.pathname+(a.search||""),headers:u,...d!==void 0?{body:d}:{},host:i,endpoint:c,readOnly:t,occurredAt:pn(),...e.root!==void 0?{root:e.root}:{},...n?{scenarioEngine:n}:{}})}catch(f){let b=String(f instanceof Error?f.message:f);return Oe({method:s.method,path:a.pathname+(a.search||""),host:i}).wire!=="storage-xml"?new Response(JSON.stringify({error:{code:"InternalServerError",message:b,details:[]}}),{status:500,headers:{"content-type":"application/json","x-ms-error-code":"InternalServerError"}}):new Response(`<?xml version="1.0" encoding="utf-8"?><Error><Code>InternalError</Code><Message>${b}</Message></Error>`,{status:500,headers:{"content-type":"application/xml","x-ms-error-code":"InternalError"}})}let m=l.body,x=typeof m=="string"?m:new Uint8Array(m);return new Response(s.method==="HEAD"?null:x,{status:l.status,headers:{server:"Volter-Twin-Blob/1.0",...l.headers}})}}var ho=`DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=${ne};BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;`;import{pendingActions as gr,syncPull as yr}from"../../engine/v2/volter_world-core.mjs";import{confirmAction as vr,pendingActions as Tr,syncPull as wr}from"../../engine/v2/volter_world-core.mjs";export{fn as createTwinFetch};
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,7 @@
1
+ @agenttwin/twin-azureformrecognizer
2
+
3
+ Contains @volter/twin-azureformrecognizer 0.1.37 by Volter (https://github.com/volter-ai),
4
+ licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ Modified by AgentTwin: bundled and minified into one file; only code reachable from the pack's
7
+ fetch factory is included; shared modules are imported from the AgentTwin twin engine.
@@ -0,0 +1,3 @@
1
+ import{createRequire as __atReq}from'node:module';const require=__atReq(import.meta.url);
2
+ import{createHash as rt}from"node:crypto";import{applyTwinWrite as st,projectResources as Ne,worldNow as it}from"../../engine/v2/volter_world-core.mjs";var j="2024-11-30",Z="/documentintelligence",Je="2024-11-30T00:00:00Z",M={type:"currency"},K={type:"string"},Qe={type:"date"},Xe={VendorName:{type:"string",description:"Vendor name.",example:"CONTOSO LTD."},VendorAddressRecipient:K,CustomerName:{type:"string",description:"Customer name.",example:"MICROSOFT CORPORATION"},CustomerId:K,InvoiceId:{type:"string",description:"Invoice identification number.",example:"INV-100"},InvoiceDate:{type:"date",description:"Invoice date.",example:"2019-11-15"},DueDate:{type:"date",description:"Invoice due date.",example:"2019-12-15"},PurchaseOrder:K,SubTotal:{type:"currency",description:"Subtotal of the invoice."},TotalTax:{type:"currency",description:"Total tax of the invoice."},InvoiceTotal:{type:"currency",description:"Total charges of the invoice."},AmountDue:{type:"currency",description:"Amount due at the due date."},Items:{type:"array",description:"Line items of the invoice.",items:{type:"object",properties:{Description:K,Quantity:{type:"number"},UnitPrice:M,Amount:M}}}},qe={MerchantName:{type:"string",description:"Name of the merchant issuing the receipt.",example:"Contoso"},MerchantPhoneNumber:{type:"phoneNumber"},TransactionDate:Qe,TransactionTime:{type:"time"},Subtotal:M,TotalTax:M,Tip:M,Total:{type:"currency",description:"Full transaction total of the receipt."},Items:{type:"array",items:{type:"object",properties:{Description:K,Quantity:{type:"number"},Price:M,TotalPrice:M}}}},X=[{modelId:"prebuilt-read",description:"Extract text from documents."},{modelId:"prebuilt-layout",description:"Extract text and layout information from documents."},{modelId:"prebuilt-invoice",description:"Extract key information from invoices.",docTypes:{invoice:{fieldSchema:Xe}}},{modelId:"prebuilt-receipt",description:"Extract key information from receipts.",docTypes:{receipt:{fieldSchema:qe}}}],re={"prebuilt-document":"The 'prebuilt-document' (general document) model is deprecated in API version 2024-11-30. Use 'prebuilt-layout' with the query parameter features=keyValuePairs instead."};function V(e){return X.find(t=>t.modelId===e)}function Ee(e){let t=V(e);return t?.docTypes?Object.keys(t.docTypes)[0]??null:null}function se(e){return{modelId:e.modelId,description:e.description,createdDateTime:Je,apiVersion:j,...e.docTypes?{docTypes:e.docTypes}:{}}}import{createHash as Ae}from"node:crypto";function N(e){return Ae("sha256").update(e).digest()}function ee(e){return Ae("sha256").update(e).digest("hex").slice(0,8)}function w(e,t,n){let r=N(`${t}:${e}`);return(r[0]<<8|r[1])%n}function ie(e,t,n,r){let o=N(`${t}:${e}`),d=(o[0]<<16|o[1]<<8|o[2])%((r-n)*100)+n*100;return Math.round(d)/100}function k(e){return e.toFixed(2)}function ae(e,t,n=0){let r=w(e,`${t}:d`,28)+1+n,o=w(e,`${t}:m`,12)+1,d=Date.UTC(2026,o-1,r);return new Date(d).toISOString().slice(0,10)}var G=["Contoso Ltd.","Fabrikam Inc.","Northwind Traders","Adventure Works"],Se=["Woodgrove Bank","Tailspin Toys","Proseware Inc.","Litware Corp."],q=["Consulting hours","Widget assembly","Annual support plan","Onsite training"];function ze(e,t){return`[twin-stub:document] Azure Document Intelligence twin extraction for ${e} (seed ${ee(t)}). No OCR or document model is run.`}function F(e,t,n=!0){return{parts:[e],sep:" ",paragraph:n,...t?{role:t}:{}}}function et(e){return e!=="prebuilt-invoice"&&e!=="prebuilt-receipt"}function tt(e){return e!=="prebuilt-read"}function nt(e,t,n,r){let o=[],d=[],a=[],m=[],b=[],p=et(e),S=tt(e);o.push(F(ze(n,t),S?"title":void 0,p));let E=r.scripted?.lines;if(E&&E.length>0)for(let g of E)o.push(F(g,void 0,p));if(e==="prebuilt-read")return o.push(F("Read extracts text, lines and words with page geometry; it emits no tables, no key-value pairs and no typed fields.")),o.push(F(`Deterministic body paragraph ${ee(`${t}:body`)} for the twin read model.`)),{lines:o,tables:d,kv:a,fields:m,selectionMarks:b,docType:null};if(e==="prebuilt-layout"){o.push(F("Document Summary","sectionHeading")),o.push(F("Layout extracts paragraphs with roles, selection marks and tables; key-value pairs require ?features=keyValuePairs."));let g=o.length;o.push({parts:["Approved:",":selected:"],sep:" ",paragraph:!1}),b.push({line:g,part:1,state:"selected"});let u=[],c=["Item","Quantity","Amount"],l=o.length;o.push({parts:c,sep:" | ",paragraph:!1}),c.forEach((i,s)=>u.push({row:0,col:s,line:l,part:s,kind:"columnHeader"}));for(let i=1;i<=2;i++){let s=o.length,f=q[w(t,`layout:item:${i}`,q.length)],T=String(w(t,`layout:qty:${i}`,9)+1),v=k(ie(t,`layout:amt:${i}`,10,900));o.push({parts:[f,T,v],sep:" | ",paragraph:!1});for(let y=0;y<3;y++)u.push({row:i,col:y,line:s,part:y})}if(d.push({rowCount:3,columnCount:3,cells:u}),(r.features??[]).includes("keyValuePairs")){let i=[["Document ID",`DOC-${ee(`${t}:docid`).toUpperCase()}`],["Prepared By",G[w(t,"layout:vendor",G.length)]]];for(let[s,f]of i){let T=o.length;o.push({parts:[`${s}:`,f],sep:" ",paragraph:!1}),a.push({line:T,keyPart:0,valuePart:1})}a.push({line:g,keyPart:0,valuePart:1})}return{lines:o,tables:d,kv:a,fields:m,selectionMarks:b,docType:null}}if(e==="prebuilt-invoice"){let g=r.scripted?.fields??{},u=g.VendorName??G[w(t,"inv:vendor",G.length)],c=g.CustomerName??Se[w(t,"inv:cust",Se.length)],l=g.InvoiceId??`INV-${ee(`${t}:inv`).toUpperCase()}`,i=g.InvoiceDate??ae(t,"inv:date"),s=g.DueDate??ae(t,"inv:date",30),f=[["VendorName","Vendor Name",u,u],["CustomerName","Customer Name",c,c],["InvoiceId","Invoice Number",l,l],["InvoiceDate","Invoice Date",i,i],["DueDate","Due Date",s,s]],T=(r.features??[]).includes("keyValuePairs");for(let[z,D,P,$]of f){let L=o.length;o.push({parts:[`${D}:`,P],sep:" ",paragraph:!1}),T&&a.push({line:L,keyPart:0,valuePart:1}),m.push({name:z,type:z.endsWith("Date")?"date":"string",line:L,part:1,value:$})}let v=[],y=["Description","Quantity","Unit Price","Amount"],h=o.length;o.push({parts:y,sep:" | ",paragraph:!1}),y.forEach((z,D)=>v.push({row:0,col:D,line:h,part:D,kind:"columnHeader"}));let I=[],A=0,R=2;for(let z=1;z<=R;z++){let D=q[w(t,`inv:item:${z}`,q.length)],P=w(t,`inv:qty:${z}`,8)+1,$=ie(t,`inv:unit:${z}`,15,400),L=Math.round(P*$*100)/100;A=Math.round((A+L)*100)/100;let B=o.length;o.push({parts:[D,String(P),k($),k(L)],sep:" | ",paragraph:!1});for(let Q=0;Q<4;Q++)v.push({row:z,col:Q,line:B,part:Q});I.push([{name:"Description",type:"string",line:B,part:0,value:D},{name:"Quantity",type:"number",line:B,part:1,value:P},{name:"UnitPrice",type:"currency",line:B,part:2,value:{amount:$,currencySymbol:"$",currencyCode:"USD"}},{name:"Amount",type:"currency",line:B,part:3,value:{amount:L,currencySymbol:"$",currencyCode:"USD"}}])}d.push({rowCount:R+1,columnCount:4,cells:v}),m.push({name:"Items",type:"array",line:h,part:0,value:null,children:I});let x=Math.round(A*.0875*100)/100,J=Math.round((A+x)*100)/100,Ye=[["SubTotal","Subtotal",A],["TotalTax","Total Tax",x],["InvoiceTotal","Invoice Total",J],["AmountDue","Amount Due",J]];for(let[z,D,P]of Ye){let $=o.length;o.push({parts:[`${D}:`,`$${k(P)}`],sep:" ",paragraph:!1}),T&&a.push({line:$,keyPart:0,valuePart:1}),m.push({name:z,type:"currency",line:$,part:1,value:{amount:P,currencySymbol:"$",currencyCode:"USD"}})}return{lines:o,tables:d,kv:a,fields:m,selectionMarks:b,docType:"invoice"}}if(e==="prebuilt-receipt"){let g=r.scripted?.fields??{},u=g.MerchantName??G[w(t,"rcp:merchant",G.length)],c=g.TransactionDate??ae(t,"rcp:date"),l=ie(t,"rcp:sub",5,200),i=Math.round(l*.0875*100)/100,s=Math.round((l+i)*100)/100,f=[["MerchantName","Merchant",u,"string",u],["TransactionDate","Date",c,"date",c],["Subtotal","Subtotal",`$${k(l)}`,"currency",{amount:l,currencySymbol:"$",currencyCode:"USD"}],["TotalTax","Tax",`$${k(i)}`,"currency",{amount:i,currencySymbol:"$",currencyCode:"USD"}],["Total","Total",`$${k(s)}`,"currency",{amount:s,currencySymbol:"$",currencyCode:"USD"}]];for(let[T,v,y,h,I]of f){let A=o.length;o.push({parts:[`${v}:`,y],sep:" ",paragraph:!1}),m.push({name:T,type:h,line:A,part:1,value:I})}return{lines:o,tables:d,kv:a,fields:m,selectionMarks:b,docType:"receipt"}}return o.push(F(`Custom model ${e} analyzed by the twin; no trained field schema is available locally.`)),{lines:o,tables:d,kv:a,fields:m,selectionMarks:b,docType:null}}function ot(e){let t=[],n=[],r=[],o=0;for(let d of e){let a=d.parts.join(d.sep),m=[],b=o;d.parts.forEach((p,S)=>{S>0&&(b+=d.sep.length),m.push({offset:b,length:p.length}),b+=p.length}),t.push(a),n.push({offset:o,length:a.length}),r.push(m),o+=a.length+1}return{content:t.join(`
3
+ `),lineSpans:n,partSpans:r,lineTexts:t}}var te=8.5,ce=11,we=.6,xe=.32,le=.085,De=.2;function O(e){return Math.round(e*1e4)/1e4}function Pe(e,t,n,r){return[O(e),O(t),O(e+n),O(t),O(e+n),O(t+r),O(e),O(t+r)]}function ve(e,t){return Pe(.6,we+e*xe,Math.min(te-1.2,le*t.length),De)}function Ie(e,t,n){return Pe(.6+le*t,we+e*xe,le*n,De)}function Re(){return[0,0,te,0,te,ce,0,ce]}var ue=1;function ne(e){if(!e)return null;let t=new Set;for(let n of e.split(",")){let r=n.trim();if(!r)continue;let o=/^(\d+)\s*-\s*(\d+)$/.exec(r);if(o){let a=Number(o[1]),m=Number(o[2]);if(!Number.isInteger(a)||!Number.isInteger(m)||a<1||m<a)return null;for(let b=a;b<=m;b++)t.add(b);continue}if(!/^\d+$/.test(r))return null;let d=Number(r);if(d<1)return null;t.add(d)}return t.size===0?null:[...t].sort((n,r)=>n-r)}function de(e){let t=e.options??{},n=nt(e.modelId,e.seed,e.sourceLabel,t),r=ot(n.lines),{content:o,lineSpans:d,partSpans:a,lineTexts:m}=r,b=t.features??[],p=ne(t.pages)??[1],S=p.map((c,l)=>{let i=l===0,s=i?m.flatMap((y,h)=>{let I=[],A=/\S+/g,R;for(;(R=A.exec(y))!==null;){let x=R.index,J=N(`w:${e.seed}:${h}:${x}`);I.push({content:R[0],polygon:Ie(h,x,R[0].length),span:{offset:d[h].offset+x,length:R[0].length},confidence:(900+J[0]%100)/1e3})}return I}):[],f=i?m.map((y,h)=>({content:y,polygon:ve(h,y),spans:[d[h]]})):[],T=i?[{offset:0,length:o.length}]:[{offset:o.length,length:0}],v={pageNumber:c,angle:0,width:te,height:ce,unit:"inch",spans:T,words:s,lines:f};return i&&n.selectionMarks.length>0&&(v.selectionMarks=n.selectionMarks.map(y=>{let h=a[y.line][y.part],I=N(`sm:${e.seed}:${y.line}`);return{state:y.state,polygon:Ie(y.line,h.offset-d[y.line].offset,h.length),span:h,confidence:(900+I[0]%100)/1e3}})),v}),E=c=>[{pageNumber:p[0]??1,polygon:ve(c,m[c]??"")}],g={apiVersion:"2024-11-30",modelId:e.modelId,stringIndexType:e.stringIndexType??"textElements",content:o,pages:S},u=n.lines.map((c,l)=>({l:c,i:l})).filter(({l:c})=>c.paragraph);if(u.length>0&&(g.paragraphs=u.map(({l:c,i:l})=>({...c.role?{role:c.role}:{},content:m[l],boundingRegions:E(l),spans:[d[l]]}))),n.tables.length>0&&(g.tables=n.tables.map(c=>({rowCount:c.rowCount,columnCount:c.columnCount,cells:c.cells.map(l=>{let i=a[l.line][l.part];return{...l.kind?{kind:l.kind}:{},rowIndex:l.row,columnIndex:l.col,content:o.slice(i.offset,i.offset+i.length),boundingRegions:E(l.line),spans:[i]}}),boundingRegions:[{pageNumber:p[0]??1,polygon:Re()}],spans:[(()=>{let l=a[c.cells[0].line][c.cells[0].part],i=c.cells[c.cells.length-1],s=a[i.line][i.part];return{offset:l.offset,length:s.offset+s.length-l.offset}})()]}))),n.kv.length>0){let c=(l,i)=>{let s=a[l][i];return{content:o.slice(s.offset,s.offset+s.length),boundingRegions:E(l),spans:[s]}};g.keyValuePairs=n.kv.map(l=>{let i=N(`kv:${e.seed}:${l.line}`);return{key:c(l.line,l.keyPart),value:c(l.line,l.valuePart),confidence:(880+i[0]%120)/1e3}})}if(n.docType){let c=i=>{let s=a[i.line][i.part],f={type:i.type};if(i.type==="array"){f.valueArray=(i.children??[]).map(h=>{let I=a[h[0].line][h[0].part],A=h[h.length-1],R=a[A.line][A.part];return{type:"object",valueObject:Object.fromEntries(h.map(x=>[x.name,c(x)])),content:o.slice(I.offset,R.offset+R.length),boundingRegions:E(h[0].line),spans:[{offset:I.offset,length:R.offset+R.length-I.offset}],confidence:.95}});let y=(i.children??[]).flat();if(y.length>0){let h=a[y[0].line][y[0].part],I=y[y.length-1],A=a[I.line][I.part],R=A.offset+A.length-h.offset;f.content=o.slice(h.offset,h.offset+R),f.spans=[{offset:h.offset,length:R}],f.boundingRegions=E(y[0].line)}return f.confidence=.95,f}let T=o.slice(s.offset,s.offset+s.length),v=N(`f:${e.seed}:${i.name}`);switch(i.type){case"date":f.valueDate=i.value;break;case"number":f.valueNumber=i.value;break;case"integer":f.valueInteger=i.value;break;case"currency":f.valueCurrency=i.value;break;default:f.valueString=i.value;break}return f.content=T,f.boundingRegions=E(i.line),f.spans=[s],f.confidence=(900+v[0]%100)/1e3,f},l=(900+N(`doc:${e.seed}`)[0]%100)/1e3;g.documents=[{docType:n.docType,boundingRegions:[{pageNumber:p[0]??1,polygon:Re()}],spans:[{offset:0,length:o.length}],fields:Object.fromEntries(n.fields.map(i=>[i.name,c(i)])),confidence:l}]}if(b.includes("languages")){let c=N(`lang:${e.seed}`);g.languages=[{locale:"en",spans:[{offset:0,length:o.length}],confidence:(900+c[0]%100)/1e3}]}return g}var fe="azureformrecognizer";var _e="https://twin-docintel.cognitiveservices.azure.com",Ce=["application/json","application/octet-stream","application/pdf","image/jpeg","image/png","image/tiff","image/bmp","image/heif","text/html","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.presentation"],Me=["ocrHighResolution","languages","barcodes","formulas","keyValuePairs","styleFont","queryFields"];function C(e,t,n,r){return{status:e,body:{error:{code:t,message:n,...r?{innererror:r}:{}}}}}function H(e){return C(404,"NotFound","Resource not found.",e)}function pe(e){let t=re[e];return H({code:"ModelNotFound",message:t??"The requested model was not found."})}function $e(){return H({code:"OperationNotFound",message:"The requested operation was not found."})}function _(e){return C(400,"InvalidArgument","Invalid argument.",e)}function me(e){return C(400,"InvalidRequest","Invalid request.",e)}function at(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n.toLowerCase()]=r;return t}function Y(e){return e??it()}function ke(e){return rt("sha256").update(e).digest("hex")}function ct(e,t){let n=ke(`${e}:${t}`);return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-a${n.slice(17,20)}-${n.slice(20,32)}`}function lt(e,t){return`${e}:${t}`}function oe(e,t){let n=`${e}:`;return Ne(fe,t).filter(r=>r.type===e&&r.id.startsWith(n)&&r.deleted!==!0).map(r=>({...r,id:r.id.slice(n.length)}))}function U(e,t,n){return oe(e,n).find(r=>r.id===t)}async function W(e,t,n,r,o){await st(fe,{operation:r,subjectType:e,subjectId:lt(e,t),fields:n,...o.occurredAt?{occurredAt:o.occurredAt}:{},actor:{kind:"agent"}},o.root)}function Fe(e){return oe("analysis",e).filter(t=>t._purged!==!0).map(t=>{let n={};for(let[r,o]of Object.entries(t))!r.startsWith("_")&&r!=="type"&&(n[r]=o);return n}).sort((t,n)=>String(t.id).localeCompare(String(n.id)))}function Oe(e){let t=oe("model",e).map(n=>({modelId:n.id,...n.description!==void 0&&n.description!==null?{description:n.description}:{},...n.createdDateTime?{createdDateTime:n.createdDateTime}:{},...n.apiVersion?{apiVersion:n.apiVersion}:{},...n.buildMode?{buildMode:n.buildMode}:{},...n.docTypes?{docTypes:n.docTypes}:{},...n.tags?{tags:n.tags}:{}}));return[...X.map(se),...t]}async function ut(e,t){let n=e.id;if(e.status==="notStarted")return await W("analysis",n,{status:"running",lastUpdatedDateTime:Y(t.occurredAt)},"analysis.running",t),U("analysis",n,t.root);if(e.status!=="running")return e;if(e._scripted_error){let o=e._scripted_error;return await W("analysis",n,{status:"failed",lastUpdatedDateTime:Y(t.occurredAt),error:{code:o.code,message:o.message}},"analysis.failed",t),U("analysis",n,t.root)}let r=de({modelId:String(e.modelId),seed:String(e.seed),sourceLabel:String(e.sourceLabel),stringIndexType:String(e.stringIndexType??"textElements"),options:{features:e.features??[],...e.pages?{pages:String(e.pages)}:{},...e.locale?{locale:String(e.locale)}:{},...e._scripted_fields||e._scripted_lines?{scripted:{...e._scripted_fields?{fields:e._scripted_fields}:{},...e._scripted_lines?{lines:e._scripted_lines}:{}}}:{}}});return await W("analysis",n,{status:"succeeded",lastUpdatedDateTime:Y(t.occurredAt),analyzeResult:r},"analysis.succeeded",t),U("analysis",n,t.root)}function dt(e){let t=e.status;return{status:t,createdDateTime:e.createdDateTime,lastUpdatedDateTime:e.lastUpdatedDateTime,...t==="failed"?{error:e.error}:{},...t==="succeeded"?{analyzeResult:e.analyzeResult}:{}}}async function ge(e){let t=e.method.toUpperCase(),n=at(e.headers),[r,o]=e.path.split("?"),d=(r??"/").replace(/\/+$/,"")||"/",a=Object.fromEntries(new URLSearchParams(o??""));if(d==="/")return{status:200,body:{service:"azureformrecognizer",object:"twin"}};let m=n["ocp-apim-subscription-key"]??"";if(!m)return C(401,"401","Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API.");if(e.apiKey!==void 0&&m!==e.apiKey)return C(401,"401","Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.");if(!d.startsWith(Z))return H();let p=(d.slice(Z.length)||"/").replace(/^\/+/,"").split("/").filter(Boolean),S=a["api-version"];if(!S)return _({code:"ParameterMissing",message:"The parameter api-version is required."});if(S!==j)return me({code:"NotSupportedApiVersion",message:`API version '${S}' is not supported. Supported version: ${j}.`});if(e.readOnly&&t!=="GET")return C(405,"MethodNotAllowed","twin is read-only; omit readOnly to accept writes");if(p.length===1&&p[0]==="info"&&t==="GET")return{status:200,body:{customDocumentModels:{count:oe("model",e.root).length,limit:5e3}}};if(p[0]==="operations"&&t==="GET"){if(p.length===1)return{status:200,body:{value:[]}};if(p.length===2)return $e()}if(p[0]==="documentModels"){if(p.length===1&&t==="GET")return{status:200,body:{value:Oe(e.root)}};if(p.length>=2){let E=decodeURIComponent(p[1]??""),g=E.indexOf(":"),u=g>=0?E.slice(0,g):E,c=g>=0?E.slice(g+1):"";if(p.length===2&&c==="analyze"&&t==="POST")return pt(u,a,n,e);if(c&&c!=="analyze")return H({code:"InvalidParameter",message:`The operation '${c}' is not modeled by this twin.`});let l=V(u)??U("model",u,e.root);if(p.length===2&&t==="GET")return l?{status:200,body:Oe(e.root).find(s=>s.modelId===u)}:pe(u);if(p.length===2&&t==="DELETE")return V(u)?me({code:"ModelReadOnly",message:"The requested model is read-only and cannot be deleted."}):U("model",u,e.root)?(await W("model",u,{deleted:!0},"model.delete",e),{status:204,body:null}):pe(u);if(p.length===4&&p[2]==="analyzeResults"){let i=decodeURIComponent(p[3]??""),s=U("analysis",i,e.root);if(!s||s._purged===!0||s.modelId!==u)return $e();if(t==="GET"){let f=!e.readOnly&&(s.status==="notStarted"||s.status==="running")?await ut(s,e):s;return{status:200,body:dt(f)}}if(t==="DELETE")return await W("analysis",i,{_purged:!0,lastUpdatedDateTime:Y(e.occurredAt)},"analysis.purge",e),{status:204,body:null}}if(p.length>=5&&p[2]==="analyzeResults")return H({code:"InvalidParameter",message:"Generated analyze output (searchable PDF / figure crops) is not modeled by this twin."})}}return H()}async function pt(e,t,n,r){let o=(n["content-type"]??"").split(";")[0].trim().toLowerCase();if(!o)return C(415,"UnsupportedMediaType","Request content type isn't supported.",{code:"InvalidContent",message:"A Content-Type header is required for analyze requests."});if(!Ce.includes(o))return C(415,"UnsupportedMediaType","Request content type isn't supported.",{code:"InvalidContent",message:`The content type '${o}' is unsupported. Refer to documentation for the list of supported formats.`});if(!V(e)&&!U("model",e,r.root))return pe(e);let d,a,m,b;if(o==="application/json"){let s;try{s=JSON.parse(r.body??"")}catch{return _({code:"InvalidParameter",message:"The request body could not be parsed as JSON."})}let f=s&&typeof s=="object"&&!Array.isArray(s)?s:{},T=f.urlSource,v=f.base64Source;if(typeof T=="string"&&T.length>0){if(!/^https?:\/\//.test(T))return _({code:"InvalidContentSourceFormat",message:"Invalid content source format: urlSource must be a valid HTTP or HTTPS URL."});d="url",a=T,m=T,b=T}else if(typeof v=="string"&&v.length>0)d="base64",a=ke(v),m=`base64:${a.slice(0,12)}`,b=a;else return _({code:"ParameterMissing",message:"Either urlSource or base64Source must be specified."})}else{let s={};try{s=JSON.parse(r.body??"{}")}catch{s={}}let f=Number(s._binary_bytes??0),T=typeof s._binary_sha256=="string"?s._binary_sha256:"";if(!T||f<=0)return me({code:"InvalidContent",message:"The file format is unsupported or corrupted. Refer to documentation for the list of supported formats."});d="base64",a=T,m=`${o}:${T.slice(0,12)}`,b=T}let p=t.features?t.features.split(",").map(s=>s.trim()).filter(Boolean):[];for(let s of p)if(!Me.includes(s))return _({code:"InvalidParameter",message:`Invalid value '${s}' for parameter 'features'.`});if(t.pages!==void 0){let s=ne(t.pages);if(s===null)return _({code:"InvalidParameter",message:`Invalid value '${t.pages}' for parameter 'pages'. Expected 1-based page numbers, e.g. "1-3,5".`});if(s.filter(T=>T>ue).length>0)return _({code:"InvalidParameter",message:`Invalid value '${t.pages}' for parameter 'pages'. The document has ${ue} page(s).`})}let S=t.stringIndexType??"textElements";if(!["textElements","unicodeCodePoint","utf16CodeUnit"].includes(S))return _({code:"InvalidParameter",message:`Invalid value '${S}' for parameter 'stringIndexType'.`});let E=Ne(fe,r.root).filter(s=>s.type==="analysis").length+1,g=ct(`analysis:${b}:${e}`,E),u=r.scenarioEngine?(()=>{let s=r.scenarioEngine.next({urlSource:d==="url"?a:m,modelId:e,nthAnalysis:E});return s.kind==="handler"?s.respond:null})():null,c=Y(r.occurredAt);return await W("analysis",g,{modelId:e,sourceKind:d,source:a,sourceLabel:m,seed:b,docType:Ee(e),status:"notStarted",createdDateTime:c,lastUpdatedDateTime:c,features:p,...t.pages?{pages:t.pages}:{},...t.locale?{locale:t.locale}:{},stringIndexType:S,...u?.error?{_scripted_error:u.error}:{},...u?.fields?{_scripted_fields:u.fields}:{},...u?.lines?{_scripted_lines:u.lines}:{}},"analysis.submit",r),{status:202,body:null,headers:{"operation-location":`${(r.baseUrl??_e).replace(/\/+$/,"")}${Z}/documentModels/${encodeURIComponent(e)}/analyzeResults/${g}?api-version=${j}`,"retry-after":"1","apim-request-id":g}}}import{serveHttp as jt}from"../../engine/v2/volter_world-core.mjs";import{createHash as bt}from"node:crypto";import{isReadOnlyRequest as Tt,twinManifest as Et,twinPublicBase as St,withRequestScopes as vt,worldNow as It}from"../../engine/v2/volter_world-core.mjs";import{getActiveWorldStore as mt,parseScenarioDocument as ft,ScenarioError as gt,ScenarioEngine as yt}from"../../engine/v2/volter_world-core.mjs";var Ue=new Set(["fields","lines","error"]),ht=new Set(["code","message"]),ye=e=>typeof e=="string"&&e.length>0,he={vendor:"azureformrecognizer",features:e=>({urlSource:e.urlSource,modelId:e.modelId,nthAnalysis:e.nthAnalysis}),matchers:{urlSourceEquals:(e,t)=>ye(t)&&e.urlSource===t,urlSourceIncludes:(e,t)=>ye(t)&&e.urlSource.toLowerCase().includes(t.toLowerCase()),modelId:(e,t)=>ye(t)&&e.modelId===t,nthAnalysis:(e,t)=>Number.isInteger(t)&&e.nthAnalysis===t},validateOn:e=>{for(let t of["urlSourceEquals","urlSourceIncludes","modelId"])if(e[t]!==void 0&&(typeof e[t]!="string"||!e[t]))return`on.${t} is a non-empty string`;return e.nthAnalysis!==void 0&&(!Number.isInteger(e.nthAnalysis)||e.nthAnalysis<1)?"on.nthAnalysis is a positive integer":null},validateRespond:e=>{if(typeof e!="object"||e===null||Array.isArray(e))return"respond is an object { fields | lines | error }";let t=e;for(let n of Object.keys(t))if(!Ue.has(n))return`respond: unknown key "${n}" (valid: ${[...Ue].join(", ")})`;if(t.fields!==void 0){let n=t.fields;if(!n||typeof n!="object"||Array.isArray(n))return"respond.fields is an object of fieldName \u2192 string";for(let[r,o]of Object.entries(n))if(typeof o!="string"||!o)return`respond.fields.${r} is a non-empty string`}if(t.lines!==void 0){if(!Array.isArray(t.lines)||t.lines.length===0)return"respond.lines is a non-empty array of strings";for(let[n,r]of t.lines.entries())if(typeof r!="string"||!r)return`respond.lines[${n}] is a non-empty string`}if(t.error!==void 0){let n=t.error;if(!n||typeof n!="object"||Array.isArray(n))return"respond.error is an object { code, message }";for(let r of Object.keys(n))if(!ht.has(r))return`respond.error: unknown key "${r}"`;for(let r of["code","message"])if(typeof n[r]!="string"||!n[r])return`respond.error.${r} is a non-empty string`;if(t.fields!==void 0||t.lines!==void 0)return"respond cannot script both an error and fields/lines"}return t.error===void 0&&t.fields===void 0&&t.lines===void 0?"respond needs fields, lines, or error":null}};function be(e){let t;try{let n=mt().read(e);if(n===null)throw new Error(`ENOENT: no such file or directory, open '${e}'`);t=JSON.parse(n)}catch(n){throw new gt(`azureformrecognizer scenario: cannot read/parse ${e}: ${n instanceof Error?n.message:String(n)}`)}return ft(t,he)}function Te(e){return new yt(he,e)}var Le=["analyses"];function je(e={}){let t=e.scenarioPath??process.env.TWIN_AZUREFORMRECOGNIZER_SCENARIO,n=t?Te(be(t)):void 0;return vt(async function(o){let d=(e.readOnly??!1)||Tt(o),a=new URL(o.url);if(o.method==="GET"&&a.pathname.replace(/\/+$/,"")==="/twin"){let u=Et({vendor:"azureformrecognizer",twinOf:"Azure AI Document Intelligence (Form Recognizer)",stateSentence:"Seed by submitting analyses through the ordinary API with any key.",behaviorSentence:"Analyze OUTCOMES are scripted by MSW-shaped handlers in the world dir (handlers/azureformrecognizer.json): {on:{urlSourceEquals|urlSourceIncludes|modelId|nthAnalysis}, respond:{fields | lines | error}}. Unmatched submits get the deterministic labeled stub; misses are inspectable at GET /twin/scenario.",exampleHandler:{on:{urlSourceIncludes:"invoice-042"},respond:{fields:{InvoiceTotal:"$1,499.00"}}},engine:n});return Response.json({...u,stores:Le,doors:{...u.doors,store:"GET /twin/store/<name>"}})}if(o.method==="GET"&&a.pathname.replace(/\/+$/,"").startsWith("/twin/store/")){let u=a.pathname.replace(/\/+$/,"").slice(12);return u!=="analyses"?Response.json({error:"unknown store",store:u,stores:Le},{status:404}):Response.json(Fe(e.root))}if(o.method==="GET"&&a.pathname.replace(/\/+$/,"")==="/twin/scenario")return Response.json(n?n.status():{vendor:"azureformrecognizer",handlers:[],misses:0,recentMisses:[]});let m={};o.headers.forEach((u,c)=>{m[c.toLowerCase()]=u});let b=(m["content-type"]??"").split(";")[0].trim().toLowerCase(),p="";if(o.method!=="GET"&&o.method!=="DELETE")if(b&&b!=="application/json"){let u=new Uint8Array(await o.arrayBuffer());p=JSON.stringify({_binary_bytes:u.length,_binary_sha256:bt("sha256").update(u).digest("hex")})}else p=await o.text();let{status:S,body:E,headers:g}=await ge({method:o.method,path:a.pathname+(a.search||""),body:p,headers:m,readOnly:d,occurredAt:It(),baseUrl:St(o),...e.apiKey!==void 0?{apiKey:e.apiKey}:{},...n?{scenarioEngine:n}:{},...e.root!==void 0?{root:e.root}:{}});return S===202||S===204||E===null?new Response(null,{status:S,headers:{...g??{}}}):new Response(JSON.stringify(E),{status:S,headers:{"content-type":"application/json",...g??{}}})},{refuse:()=>Response.json({error:{code:"MethodNotAllowed",message:"twin is read-only; omit readOnly to accept writes"}},{status:405})})}import{observeResources as Rt}from"../../engine/v2/volter_world-core.mjs";var Ve="azureformrecognizer";function At(e,t){return`${e}:${t}`}function zt(e){return e==null?null:e instanceof Date?e.toISOString():String(e)}function Ge(e){return!e.startsWith("prebuilt-")}function He(e){return{type:"model",id:At("model",String(e.modelId)),fields:{description:e.description??null,createdDateTime:zt(e.createdDateTime),apiVersion:e.apiVersion??null,buildMode:e.buildMode??null,tags:e.tags??null,docTypes:e.docTypes??null}}}async function We(e){if(!e.documentModels)return[];let{value:t}=await e.documentModels.list(),n=[];for(let r of t){if(!Ge(String(r.modelId)))continue;let o=e.documentModels.get?await e.documentModels.get(r.modelId):r;n.push(He(o))}return n}async function Be(e,t={}){let n=t.occurredAt??new Date().toISOString(),r=await We(e),o=Rt(Ve,r.map(d=>({type:d.type,id:d.id,fields:d.fields})),{...t.root!==void 0?{root:t.root}:{},at:n,batch:`obs:${Ve}:${n}`});return{observed:o.observed,deltasAppended:o.appended}}function wt(e){return{documentModels:{list:async()=>{let t=await e({method:"GET",path:"/documentintelligence/documentModels?api-version=2024-11-30",headers:{accept:"application/json","ocp-apim-subscription-key":"twin"}});if(t.status<200||t.status>=300)throw new Error(`azureformrecognizer list refused: HTTP ${t.status} ${t.body.slice(0,200)}`);return JSON.parse(t.body||"{}")}}}}async function Ke(e,t={}){return Be(wt(e),{...t.root!==void 0?{root:t.root}:{},occurredAt:t.occurredAt??new Date().toISOString()})}async function Ze(e,t,n){return{externalId:t.subject.id,data:{performed:!1,reason:`${t.operation??t.subject.type}: Form Recognizer ANALYSES what you send it \u2014 the twin's rows are models the account has and analyses it already answered`}}}import{registerPack as xt}from"../../engine/v2/volter_world-core.mjs";var Dt={protocol:"2",refresh:{every:"30m",onDemand:{atMost:"60s"}},stateSystem:{perform:Ze,refresh:Ke},roundTrip:{method:"POST",path:"/documentintelligence/documentModels/prebuilt-read:analyze?api-version=2024-11-30",body:{urlSource:"https://round.trip.test/doc.pdf"},headers:{"ocp-apim-subscription-key":"round-trip"}},parityOrigin:"http://twin",vendor:"azureformrecognizer",transport:"rest",archetype:"generative",bin:"world-azureformrecognizer",resourcesUnreachable:{model:"prebuilt models are the vendor's catalog; a custom model is born of a training job this twin does not run"},resources:["analysis","model"],specSource:"azureformrecognizer-conformance.ts (endpoint/resource/model inventory from the Azure AI Document Intelligence v4.0 REST reference \u2014 learn.microsoft.com/rest/api/aiservices, api-version 2024-11-30 \u2014 cross-checked against the official @azure-rest/ai-document-intelligence v1.1.0 SDK routes/types)",description:"Azure AI Document Intelligence (Form Recognizer) twin \u2014 async analyze lifecycle (202 + Operation-Location \u2192 poll notStarted/running/succeeded/failed), prebuilt models (read/layout/invoice/receipt), model catalog + detail, resource info, analyze-result deletion. Extracted content is a deterministic [twin-stub:document] seeded from the document source (no OCR / document model) with a faithful AnalyzeResult envelope incl. exact content/span algebra, page geometry, tables, key-value pairs and typed fields; scenario files script exact field values or a failed operation per document. Kernel-backed.",browserRouting:{apiPathPrefix:"/documentintelligence/",loaderHost:"https://twin-docintel.cognitiveservices.azure.com"},hosts:[{suffix:".cognitiveservices.azure.com",pathPattern:"^/(documentintelligence|formrecognizer)/"}],adoption:{pypi:["azure-ai-documentintelligence","azure-ai-formrecognizer"],sdks:["@azure-rest/ai-document-intelligence","@azure/ai-form-recognizer"],envStems:["AZUREFORMRECOGNIZER","AZUREDOCUMENTINTELLIGENCE"]}};xt(Dt);export{je as createTwinFetch};