@bkm016/basalt 0.1.7 → 0.1.8

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 (250) hide show
  1. package/README.md +1 -1
  2. package/{chunk-n981vx1t.js → chunk-0d51ggzj.js} +6 -6
  3. package/chunk-12trygzx.js +25 -0
  4. package/{chunk-s6dejhfj.js → chunk-26cz8et8.js} +1 -1
  5. package/{chunk-zxkq9m8e.js → chunk-2ek3wq4b.js} +2 -2
  6. package/chunk-2gcp3xdc.js +2 -0
  7. package/{chunk-x4874m8e.js → chunk-2ks2tnac.js} +2 -2
  8. package/{chunk-0javrjcm.js → chunk-2nrkqq45.js} +22 -22
  9. package/chunk-320174qe.js +2 -0
  10. package/{chunk-ey15ye2h.js → chunk-3hg7yn1t.js} +1 -1
  11. package/{chunk-benrzwea.js → chunk-3j2kkgsc.js} +1 -1
  12. package/{chunk-8x21n7y9.js → chunk-47vf66t6.js} +1 -1
  13. package/chunk-4n49ptbz.js +3 -0
  14. package/{chunk-7hr6zw2m.js → chunk-5gxj9560.js} +1 -1
  15. package/{chunk-g0t9c3gv.js → chunk-6vnjg5x9.js} +1 -1
  16. package/{chunk-dnx91jrd.js → chunk-7kjr9gdx.js} +2 -2
  17. package/{chunk-y8dkfpmj.js → chunk-7p6e2f5s.js} +3 -3
  18. package/{chunk-053vb71h.js → chunk-86xhmz7k.js} +1 -1
  19. package/{chunk-ebpyvs1d.js → chunk-91r5nvth.js} +2 -2
  20. package/{chunk-c7rcw9fb.js → chunk-adys4qq4.js} +4 -4
  21. package/{chunk-npez1492.js → chunk-ckjw3b61.js} +2 -2
  22. package/{chunk-f156y565.js → chunk-d37gemt2.js} +3 -3
  23. package/{chunk-j7yvh0ae.js → chunk-dcwdmpw2.js} +1 -1
  24. package/chunk-dvb5nd2x.js +2 -0
  25. package/{chunk-063vbmtp.js → chunk-e6c2mzxc.js} +2 -2
  26. package/{chunk-s7skpgm2.js → chunk-ef9yhnk3.js} +1 -1
  27. package/{chunk-ecf896fz.js → chunk-fpxc6qjr.js} +2 -2
  28. package/chunk-frt9k18g.js +480 -0
  29. package/{chunk-bdy4jksd.js → chunk-fzcmzbsq.js} +1 -1
  30. package/{chunk-q9dd6fhj.js → chunk-g3ed130w.js} +3 -3
  31. package/{chunk-d48bfd2e.js → chunk-h1kb8b49.js} +2 -2
  32. package/{chunk-arcqjt91.js → chunk-hd3x1w46.js} +1 -1
  33. package/{chunk-dpz4hwqb.js → chunk-j781n7ca.js} +2 -2
  34. package/{chunk-z02sj1je.js → chunk-jp5afrwm.js} +2 -2
  35. package/{chunk-r8vvcp6c.js → chunk-jyv9cae6.js} +1 -1
  36. package/{chunk-whj87h4r.js → chunk-k3q5jqjj.js} +3 -3
  37. package/{chunk-75434aay.js → chunk-k3rmjrf1.js} +1 -1
  38. package/{chunk-peja51xv.js → chunk-kgkrccr1.js} +2 -2
  39. package/{chunk-pg5nkf1y.js → chunk-kpvaqb7c.js} +2 -2
  40. package/{chunk-sjjtxpg2.js → chunk-ky55taar.js} +330 -288
  41. package/{chunk-10p3mb40.js → chunk-mr807v9n.js} +1 -1
  42. package/chunk-n015c8nx.js +2 -0
  43. package/chunk-ndt6rjt9.js +2 -0
  44. package/{chunk-gv7wqkey.js → chunk-nmtk9xra.js} +2 -2
  45. package/{chunk-d6p2hgxh.js → chunk-pehyqj8k.js} +1 -1
  46. package/{chunk-ca982n62.js → chunk-pkpj7s2k.js} +1 -1
  47. package/{chunk-fx7f4m3c.js → chunk-pn413hjw.js} +1 -1
  48. package/{chunk-6ptv4g5e.js → chunk-ppxv5q7y.js} +3 -3
  49. package/{chunk-8wj32837.js → chunk-qmdpgbg3.js} +1 -1
  50. package/{chunk-8wv5t0w6.js → chunk-rnt1ckk9.js} +6 -6
  51. package/{chunk-prgm07j4.js → chunk-t40fag3z.js} +2 -2
  52. package/{chunk-w67dvqtb.js → chunk-t66jqz12.js} +2 -2
  53. package/{chunk-39vwrg8n.js → chunk-v2srrqcv.js} +2 -2
  54. package/{chunk-n85qs7cs.js → chunk-x496kg3v.js} +1 -1
  55. package/{chunk-6kdgk70p.js → chunk-xjw78yey.js} +4 -4
  56. package/chunk-xy2bxwq8.js +2 -0
  57. package/{chunk-y69ewdn2.js → chunk-ypqjfv3a.js} +2 -2
  58. package/{chunk-f544p9rh.js → chunk-yyy2yp6f.js} +10 -10
  59. package/{chunk-8gw5bvh3.js → chunk-yzevjkms.js} +5 -5
  60. package/chunk-z3ch1wg6.js +16 -0
  61. package/chunk-zdyd8hbn.js +2 -0
  62. package/compiled.js +6 -6
  63. package/package.json +1 -1
  64. package/ui-test-worker.js +19 -19
  65. package/web/{chunk-kjacapzd.js → chunk-0j9a7811.js} +6 -6
  66. package/web/chunk-0jfda4jw.js +2 -0
  67. package/web/{chunk-z1geewdf.js → chunk-0zwc2rvh.js} +2 -2
  68. package/web/{chunk-ht4mx2dt.js → chunk-1gx0zpmp.js} +7 -7
  69. package/web/{chunk-q3jevm51.js → chunk-1s8zg6fb.js} +51 -51
  70. package/web/chunk-2axwda8c.js +89 -0
  71. package/web/chunk-2p3fkhy8.js +1 -0
  72. package/web/{chunk-tz4twwmw.js → chunk-33w36n91.js} +2 -2
  73. package/web/{chunk-1s53190z.js → chunk-3q0v8w45.js} +81 -81
  74. package/web/chunk-3sz5qcwj.js +1 -0
  75. package/web/chunk-433c80pc.js +1 -0
  76. package/web/chunk-48cnmhvd.js +106 -0
  77. package/web/{chunk-da7m1kva.js → chunk-4anjs6yp.js} +2 -2
  78. package/web/chunk-5r37rwq1.js +4 -0
  79. package/web/{chunk-pjz30xcp.js → chunk-6e38yf3a.js} +23 -23
  80. package/web/{chunk-xckxtfp8.js → chunk-7a4xk6j9.js} +72 -72
  81. package/web/chunk-7f1t7z72.js +2 -0
  82. package/web/chunk-7qq1ypvj.js +1 -0
  83. package/web/{chunk-h6k1x096.js → chunk-7tkgbbf9.js} +2 -2
  84. package/web/chunk-7x35g67d.js +78 -0
  85. package/web/{chunk-xbpc6x9m.js → chunk-823b7866.js} +15 -15
  86. package/web/chunk-85gdsmt4.js +1 -0
  87. package/web/{chunk-gyp6v7jd.js → chunk-8773nwdc.js} +2 -2
  88. package/web/{chunk-2cem4sv7.js → chunk-8dp7h6w8.js} +24 -24
  89. package/web/{chunk-y99ed8rd.js → chunk-8nv7q5ac.js} +9 -9
  90. package/web/chunk-8pzg8qw4.js +1 -0
  91. package/web/chunk-8wg44w91.js +2 -0
  92. package/web/chunk-9p5dfvav.js +1 -0
  93. package/web/chunk-9q9w9pay.js +1 -0
  94. package/web/chunk-a3teqvz2.js +39 -0
  95. package/web/chunk-bd8ftfxn.js +3 -0
  96. package/web/chunk-c03bt2pz.js +1 -0
  97. package/web/chunk-c1ha2xg6.js +8 -0
  98. package/web/chunk-cez1k71m.js +1 -0
  99. package/web/chunk-cgng31df.js +1 -0
  100. package/web/chunk-cn0tmwjs.js +2 -0
  101. package/web/{chunk-t6sq85s6.js → chunk-cn1xpg3q.js} +2 -2
  102. package/web/chunk-cvd4f51j.js +1 -0
  103. package/web/chunk-cybvxssy.js +1 -0
  104. package/web/{chunk-geh05ghh.js → chunk-cyjnert7.js} +19 -19
  105. package/web/{chunk-twdy2f67.js → chunk-d0m0h0eb.js} +1 -1
  106. package/web/{chunk-sn3tkwme.js → chunk-dgwkqcz6.js} +37 -37
  107. package/web/{chunk-nfvqjzz5.js → chunk-dtg5yhhs.js} +1 -1
  108. package/web/chunk-dynajx8x.js +2 -0
  109. package/web/{chunk-svh4n157.js → chunk-et8q775x.js} +4 -4
  110. package/web/chunk-f3vv7n52.js +1 -0
  111. package/web/{chunk-tmndcktk.js → chunk-f93pe4kb.js} +15 -15
  112. package/web/{chunk-5nda24gv.js → chunk-fe31sv6t.js} +1 -1
  113. package/web/chunk-fpa81dv7.js +62 -0
  114. package/web/{chunk-4q7wf0wd.js → chunk-fx4mackk.js} +9 -9
  115. package/web/chunk-g17n6asp.js +1 -0
  116. package/web/chunk-g9dzaw9e.js +30 -0
  117. package/web/chunk-gcwhx3av.js +1139 -0
  118. package/web/chunk-gf8vm6b5.js +1 -0
  119. package/web/chunk-gnmeyy4h.js +1 -0
  120. package/web/chunk-h5cfg3vv.js +2 -0
  121. package/web/{chunk-femhej5w.js → chunk-hbkasy6c.js} +46 -46
  122. package/web/chunk-hn7mhsbg.js +1 -0
  123. package/web/{chunk-tfn0rqg9.js → chunk-hstbgb83.js} +26 -26
  124. package/web/chunk-jjjtv2r1.js +2 -0
  125. package/web/chunk-jzte2phh.js +2 -0
  126. package/web/chunk-k8h8zx6r.js +24 -0
  127. package/web/chunk-m3ajw575.js +1 -0
  128. package/web/chunk-m5y2d4zv.js +1 -0
  129. package/web/chunk-mbwwj216.js +1 -0
  130. package/web/chunk-mf6xng5b.js +2 -0
  131. package/web/chunk-nky3bqfg.js +1 -0
  132. package/web/chunk-np33kmn4.js +1 -0
  133. package/web/chunk-nvk8mazs.js +1 -0
  134. package/web/chunk-nyw5ewgv.js +1 -0
  135. package/web/{chunk-dg3p8db5.js → chunk-p0cjvjdx.js} +1 -1
  136. package/web/chunk-p56dcqpr.js +1 -0
  137. package/web/chunk-pdn4r8x4.js +1 -0
  138. package/web/chunk-q1xxs319.js +41 -0
  139. package/web/chunk-qpt34d8d.js +1 -0
  140. package/web/{chunk-4fm55fgb.js → chunk-qq2v8h6d.js} +7 -7
  141. package/web/chunk-qskt3tqa.js +1 -0
  142. package/web/chunk-qt3n897m.js +4 -0
  143. package/web/chunk-r1rt48h9.js +1 -0
  144. package/web/{chunk-4sve9xrj.js → chunk-r4ffr96e.js} +1 -1
  145. package/web/chunk-r7tgd2fm.js +7 -0
  146. package/web/{chunk-gksf7cek.js → chunk-rbdvc8x7.js} +7 -7
  147. package/web/{chunk-q97hn4j5.js → chunk-rkjkynm3.js} +33 -33
  148. package/web/chunk-rznszqmy.js +1 -0
  149. package/web/chunk-s1pefd34.js +1 -0
  150. package/web/chunk-s38s9ff9.js +370 -0
  151. package/web/{chunk-n754s8xd.js → chunk-s7e93552.js} +8 -8
  152. package/web/chunk-sc29azev.js +1 -0
  153. package/web/{chunk-czjk218p.js → chunk-sda7cyrt.js} +52 -52
  154. package/web/chunk-svh2gkx8.js +2 -0
  155. package/web/chunk-t4jc4nac.js +1 -0
  156. package/web/chunk-t7g366a5.js +24 -0
  157. package/web/chunk-tj1fn8v2.js +1 -0
  158. package/web/{chunk-sy7e4dmq.js → chunk-tkp72r9b.js} +1 -1
  159. package/web/{chunk-5wbnjjhg.js → chunk-v14s4vgc.js} +1 -1
  160. package/web/chunk-v94v68xg.js +36 -0
  161. package/web/{chunk-0whceqes.js → chunk-vvvd3grf.js} +2 -2
  162. package/web/chunk-w37n09px.js +21 -0
  163. package/web/chunk-wcphswcx.js +2 -0
  164. package/web/{chunk-aangfjqc.js → chunk-wj3ymejj.js} +38 -38
  165. package/web/chunk-wwcnvyjh.css +1 -0
  166. package/web/{chunk-e8yj05t1.js → chunk-xabcx3ry.js} +6 -6
  167. package/web/chunk-xb9m0092.js +1 -0
  168. package/web/chunk-xfd3b01q.js +1 -0
  169. package/web/{chunk-4vjnrz87.js → chunk-xqyazzm7.js} +17 -17
  170. package/web/{chunk-bdydzbqk.js → chunk-xsz1dfm2.js} +23 -23
  171. package/web/chunk-z0zrp8n8.js +1 -0
  172. package/web/index.html +1 -1
  173. package/worker.js +1 -1
  174. package/chunk-654cny9a.js +0 -480
  175. package/chunk-8saewt61.js +0 -3
  176. package/chunk-a0c989ky.js +0 -2
  177. package/chunk-a5apjjcn.js +0 -16
  178. package/chunk-a81p46j7.js +0 -2
  179. package/chunk-agsfy9w7.js +0 -2
  180. package/chunk-d20p02ny.js +0 -2
  181. package/chunk-ejsneb6f.js +0 -2
  182. package/chunk-fmq3zwzk.js +0 -2
  183. package/chunk-rfb85nj7.js +0 -2
  184. package/chunk-rfdt992v.js +0 -25
  185. package/web/chunk-079091ar.js +0 -39
  186. package/web/chunk-083r4f80.js +0 -1
  187. package/web/chunk-0cng7r2x.js +0 -2
  188. package/web/chunk-0k0ande6.js +0 -1
  189. package/web/chunk-14deqqhr.js +0 -2
  190. package/web/chunk-2b63adsj.js +0 -89
  191. package/web/chunk-3baypnwn.js +0 -4
  192. package/web/chunk-4067nwjp.js +0 -19
  193. package/web/chunk-59678wmg.js +0 -1
  194. package/web/chunk-5k8sv4f5.js +0 -1
  195. package/web/chunk-5vjhvw1m.js +0 -2
  196. package/web/chunk-6ft5pz3c.js +0 -1
  197. package/web/chunk-7c8rwqtx.js +0 -1
  198. package/web/chunk-7qzz025k.js +0 -1
  199. package/web/chunk-7xbaqqd7.css +0 -1
  200. package/web/chunk-80eyv2mk.js +0 -1
  201. package/web/chunk-89paytbk.js +0 -4
  202. package/web/chunk-8ceej2g7.js +0 -1
  203. package/web/chunk-8nyhy122.js +0 -1
  204. package/web/chunk-989jq2h8.js +0 -2
  205. package/web/chunk-9w5tf22s.js +0 -1
  206. package/web/chunk-c3nn0vvc.js +0 -1
  207. package/web/chunk-cpwtt6ny.js +0 -1
  208. package/web/chunk-dsw5t58p.js +0 -1
  209. package/web/chunk-dv72fat3.js +0 -1
  210. package/web/chunk-dvvs1jjq.js +0 -3
  211. package/web/chunk-e131rg6p.js +0 -2
  212. package/web/chunk-ekw54h1q.js +0 -1
  213. package/web/chunk-hwsvhst3.js +0 -1
  214. package/web/chunk-k02b36g1.js +0 -62
  215. package/web/chunk-kkfrs7d1.js +0 -41
  216. package/web/chunk-kkyn8yhj.js +0 -106
  217. package/web/chunk-mh4rx5cf.js +0 -1
  218. package/web/chunk-n448vaba.js +0 -1
  219. package/web/chunk-n8j88qxy.js +0 -1
  220. package/web/chunk-nmpbsvwb.js +0 -2
  221. package/web/chunk-nws1s56b.js +0 -1
  222. package/web/chunk-p7126wwy.js +0 -7
  223. package/web/chunk-phnqnhj9.js +0 -1
  224. package/web/chunk-qg31p6cn.js +0 -1
  225. package/web/chunk-qhm3cfq9.js +0 -1
  226. package/web/chunk-qsd595b9.js +0 -1
  227. package/web/chunk-r7frwjqx.js +0 -2
  228. package/web/chunk-rddft5ce.js +0 -1139
  229. package/web/chunk-rgbdf2m9.js +0 -370
  230. package/web/chunk-rsbkbg6x.js +0 -78
  231. package/web/chunk-s2bs5vxh.js +0 -2
  232. package/web/chunk-sgwccs54.js +0 -1
  233. package/web/chunk-sjh8gtm9.js +0 -30
  234. package/web/chunk-t3658ehb.js +0 -2
  235. package/web/chunk-t81p4wqc.js +0 -24
  236. package/web/chunk-tewmsd7t.js +0 -1
  237. package/web/chunk-tf57s7ry.js +0 -1
  238. package/web/chunk-tqr80b5w.js +0 -2
  239. package/web/chunk-v282r683.js +0 -24
  240. package/web/chunk-v4vjjtn7.js +0 -1
  241. package/web/chunk-vbwdwcdp.js +0 -1
  242. package/web/chunk-vjngfh0q.js +0 -1
  243. package/web/chunk-vnt34mkb.js +0 -1
  244. package/web/chunk-wbgkwxrc.js +0 -1
  245. package/web/chunk-wjbk50hn.js +0 -2
  246. package/web/chunk-wjy848e2.js +0 -1
  247. package/web/chunk-wqsczy57.js +0 -36
  248. package/web/chunk-wvfmmw1v.js +0 -8
  249. package/web/chunk-x1jm4zsg.js +0 -1
  250. package/web/chunk-xmsb2g71.js +0 -1
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{P}from"./chunk-c4qr1f41.js";var i="v1";function s(r){let e=new Map;if(!r)return e;for(let t of r.split(",")){let a=t.trim();if(!a)continue;let[n,o]=a.split("=",2);if(!n||!o)continue;e.set(n.trim(),o.trim())}return e}function mr(r,e){if(e?.azureDeploymentName)return e.azureDeploymentName;return s(P("AZURE_OPENAI_DEPLOYMENT_NAME_MAP",e?.env)).get(r.id)||r.id}function m(r){let e=r.trim().replace(/\/+$/,""),t;try{t=new URL(e)}catch{throw Error(`Invalid Azure OpenAI base URL: ${r}`)}let a=t.hostname.endsWith(".openai.azure.com")||t.hostname.endsWith(".cognitiveservices.azure.com")||t.hostname.endsWith(".ai.azure.com"),n=t.pathname.replace(/\/+$/,"");if(a&&(n===""||n==="/"||n==="/openai"||n==="/openai/v1/responses"))t.pathname="/openai/v1",t.search="";return t.toString().replace(/\/+$/,"")}function u(r){return`https://${r}.openai.azure.com/openai/v1`}function Yn(r,e){let t=e?.azureBaseUrl?.trim()||P("AZURE_OPENAI_BASE_URL",e?.env)?.trim()||void 0,a=e?.azureResourceName||P("AZURE_OPENAI_RESOURCE_NAME",e?.env),n=t;if(!n&&a)n=u(a);if(!n&&r.baseUrl)n=r.baseUrl;if(!n)throw Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return m(n)}function Qo(r,e){return{baseUrl:Yn(r,e),apiVersion:e?.azureApiVersion||P("AZURE_OPENAI_API_VERSION",e?.env)||i}}
3
- export{mr,Yn,Qo};
2
+ import{P}from"./chunk-c4qr1f41.js";var i="v1";function s(r){let e=new Map;if(!r)return e;for(let t of r.split(",")){let a=t.trim();if(!a)continue;let[n,o]=a.split("=",2);if(!n||!o)continue;e.set(n.trim(),o.trim())}return e}function mr(r,e){if(e?.azureDeploymentName)return e.azureDeploymentName;return s(P("AZURE_OPENAI_DEPLOYMENT_NAME_MAP",e?.env)).get(r.id)||r.id}function m(r){let e=r.trim().replace(/\/+$/,""),t;try{t=new URL(e)}catch{throw Error(`Invalid Azure OpenAI base URL: ${r}`)}let a=t.hostname.endsWith(".openai.azure.com")||t.hostname.endsWith(".cognitiveservices.azure.com")||t.hostname.endsWith(".ai.azure.com"),n=t.pathname.replace(/\/+$/,"");if(a&&(n===""||n==="/"||n==="/openai"||n==="/openai/v1/responses"))t.pathname="/openai/v1",t.search="";return t.toString().replace(/\/+$/,"")}function u(r){return`https://${r}.openai.azure.com/openai/v1`}function eo(r,e){let t=e?.azureBaseUrl?.trim()||P("AZURE_OPENAI_BASE_URL",e?.env)?.trim()||void 0,a=e?.azureResourceName||P("AZURE_OPENAI_RESOURCE_NAME",e?.env),n=t;if(!n&&a)n=u(a);if(!n&&r.baseUrl)n=r.baseUrl;if(!n)throw Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.");return m(n)}function Jo(r,e){return{baseUrl:eo(r,e),apiVersion:e?.azureApiVersion||P("AZURE_OPENAI_API_VERSION",e?.env)||i}}
3
+ export{mr,eo,Jo};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{W}from"./chunk-w67dvqtb.js";import{Pr}from"./chunk-wnzvnskb.js";import{Ye}from"./chunk-7jezts2n.js";import{ee}from"./chunk-tvm4zmgj.js";import{me,ce,V,he}from"./chunk-063vbmtp.js";import{y}from"./chunk-3k627vf2.js";import{z}from"./chunk-x4874m8e.js";import{N,Me,ne,re,Q,G}from"./chunk-n981vx1t.js";import{M}from"./chunk-z02sj1je.js";var S=9,U=4000,D=(t,e,n)=>{let r=new M,o=re(e,t.compat?.supportsMidConvoSystemMessages);return(async()=>{let s=B(t);try{let l=n?.apiKey;if(!l)throw Error(`No API key for provider: ${t.provider}`);let f=J(),u=he(o.messages,t,(d)=>f(d)),a=se(t,o,u,n),i=await n?.onPayload?.(a,t);if(i!==void 0)a=i;let c=await F(t,a,l,n);if(r.push({type:"start",partial:s}),await ie(t,s,r,c,n?.onProviderStreamEvent),n?.signal?.aborted)throw Error("Request was aborted");if(s.stopReason==="pending")throw Error("Mistral stream ended without a finish reason");if(s.stopReason==="aborted"||s.stopReason==="error")throw Error(s.errorMessage||"An unknown error occurred");r.push({type:"done",reason:s.stopReason,message:s}),r.end()}catch(l){for(let f of s.content)delete f.partialArgs;s.stopReason=n?.signal?.aborted?"aborted":"error",s.errorMessage=H(l),r.push({type:"error",reason:s.stopReason,error:s}),r.end()}})(),r},Ee=(t,e,n)=>{let r=n?.apiKey;if(!r)throw Error(`No API key for provider: ${t.provider}`);let o={...V(t,e,n,r),toolChoice:n?.toolChoice},s=n?.reasoning?G(t,n.reasoning):void 0,l=s==="off"?void 0:s,f=t.reasoning?t.thinkingLevelMap:void 0,u=f?l?f[l]??"high":f.off??void 0:void 0;return D(t,e,{...o,promptMode:t.reasoning&&!f&&l?"reasoning":void 0,reasoningEffort:u})};function B(t){return{role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function J(){let t=new Map,e=new Map;return(n)=>{let r=t.get(n);if(r)return r;let o=0;while(!0){let s=P(n,o),l=e.get(s);if(!l||l===n)return t.set(n,s),e.set(s,n),s;o++}}}function P(t,e){let n=t.replace(/[^a-zA-Z0-9]/g,"");if(e===0&&n.length===S)return n;let r=n||t,o=e===0?r:`${r}:${e}`;return Ye(o).replace(/[^a-zA-Z0-9]/g,"").slice(0,S)}function H(t){if(t instanceof Error){let e=t,n=typeof e.statusCode==="number"?e.statusCode:void 0,r=typeof e.body==="string"?e.body.trim():void 0;if(n!==void 0&&r)return`Mistral API error (${n}): ${K(r,U)}`;if(n!==void 0)return`Mistral API error (${n}): ${t.message}`;return t.message}return q(t)}function K(t,e){if(t.length<=e)return t;return`${t.slice(0,e)}... [truncated ${t.length-e} chars]`}function q(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}async function F(t,e,n,r){let o=new URL(t.baseUrl);o.pathname=`${o.pathname.replace(/\/+$/u,"")}/`;let s=new URL("v1/chat/completions",o),l=Z(t,n,r),f=r?.timeoutMs??60000,u=AbortSignal.timeout(f),a=Pr([r?.signal,u]),i;try{i=await(r?.fetch??globalThis.fetch)(s,{method:"POST",headers:l,body:JSON.stringify(X(e)),signal:a.signal})}catch(c){if(u.aborted&&!r?.signal?.aborted)throw Error(`Mistral response headers timed out after ${f}ms`);throw c}finally{a.cleanup()}if(await r?.onResponse?.({status:i.status,headers:z(i.headers)},t),!i.ok){let c=await i.text();throw new O(i.status,c,i.statusText)}if(!i.body)throw Error("Mistral response has no body");return oe(i.body,r?.signal)}class O extends Error{statusCode;body;constructor(t,e,n){super(n||`Request failed with status ${t}`);this.name="MistralHttpError",this.statusCode=t,this.body=e}}function Z(t,e,n){let r=new Headers({"User-Agent":ee(),accept:"text/event-stream",authorization:`Bearer ${e}`,"content-type":"application/json"});A(r,t.headers),A(r,n?.headers);let o=I(t.headers,"x-affinity")||I(n?.headers,"x-affinity");if(L(n)&&!o)r.set("x-affinity",n.sessionId);return r}function A(t,e){if(!e)return;for(let[n,r]of Object.entries(e))if(r===null)t.delete(n);else t.set(n,r)}function I(t,e){return!!t&&Object.keys(t).some((n)=>n.toLowerCase()===e)}function X(t){let e={...t};for(let[r,o]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])k(e,r,o);e.messages=t.messages.map((r)=>Y(r));let n=e.response_format;if(w(n)){let r={...n};k(r,"jsonSchema","json_schema");let o=r.json_schema;if(w(o)){let s={...o};k(s,"schemaDefinition","schema"),r.json_schema=s}e.response_format=r}return e}function Y(t){let e={...t};if(k(e,"toolCalls","tool_calls"),k(e,"toolCallId","tool_call_id"),Array.isArray(t.content))e.content=t.content.map((n)=>te(n));return e}function te(t){let e={...t};for(let[n,r]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])k(e,n,r);return e}function k(t,e,n){if(!(e in t))return;t[n]=t[e],delete t[e]}function w(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}var b=Symbol("mistral-stream-done");async function*oe(t,e){let n=t.getReader(),r=new TextDecoder,o="",s=()=>{n.cancel().catch(()=>{})};e?.addEventListener("abort",s,{once:!0});try{while(!0){if(e?.aborted)throw e.reason;let{done:l,value:f}=await n.read();if(e?.aborted)throw e.reason;o+=l?r.decode():r.decode(f,{stream:!0});let u=E(o);while(u){let a=v(o.slice(0,u.index));if(o=o.slice(u.index+u.length),a===b)return;if(a)yield a;u=E(o)}if(l)break}if(o.trim()){let l=v(o);if(l!==b&&l)yield l}}finally{e?.removeEventListener("abort",s);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}function E(t){let e=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(t);return e?.index===void 0?void 0:{index:e.index,length:e[0].length}}function v(t){let e=t.split(/\r\n|\r|\n/u).filter((r)=>r.startsWith("data:")).map((r)=>r.slice(5).trimStart()).join(`
3
- `).trim();if(!e)return;if(e==="[DONE]")return b;let n=JSON.parse(e);if(!w(n)||!Array.isArray(n.choices))throw Error("Invalid Mistral streaming event");return{data:n}}function se(t,e,n,r){let o={model:t.id,stream:!0,messages:fe(n,t.input.includes("image"))},s=ne(e.messages);if(s.length>0)o.tools=le(s);if(r?.temperature!==void 0)o.temperature=r.temperature;if(r?.maxTokens!==void 0)o.maxTokens=r.maxTokens;if(r?.toolChoice)o.toolChoice=ue(r.toolChoice);if(r?.promptMode)o.promptMode=r.promptMode;if(r?.reasoningEffort)o.reasoningEffort=r.reasoningEffort;if(L(r))o.promptCacheKey=r.sessionId;return o}function L(t){return t?.cacheRetention!=="none"&&!!t?.sessionId}function ae(t,e){let n=t,r=n.promptTokensDetails?.cachedTokens??n.prompt_tokens_details?.cached_tokens??n.promptTokenDetails?.cachedTokens??n.prompt_token_details?.cached_tokens??n.numCachedTokens??n.num_cached_tokens??0,o=typeof r==="number"&&Number.isFinite(r)?r:0;return Math.min(e,Math.max(0,o))}async function ie(t,e,n,r,o){let s=null,l=e.content,f=()=>l.length-1,u=new Map,a=(i)=>{if(!i)return;if(i.type==="text"){n.push({type:"text_end",contentIndex:f(),content:i.text,partial:e});return}if(i.type==="thinking")n.push({type:"thinking_end",contentIndex:f(),content:i.thinking,partial:e})};for await(let i of r){let c=i.data;if(await o?.(c,t),e.responseId||=c.id,c.usage){let p=c.usage.prompt_tokens||0,h=ae(c.usage,p);e.usage.input=Math.max(0,p-h),e.usage.output=c.usage.completion_tokens||0,e.usage.cacheRead=h,e.usage.cacheWrite=0,e.usage.totalTokens=c.usage.total_tokens||e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,Q(t,e.usage)}let d=c.choices[0];if(!d)continue;if(d.finish_reason){e.rawStopReason=d.finish_reason;let p=pe(d.finish_reason);if(e.stopReason=p.stopReason,p.errorMessage)e.errorMessage=p.errorMessage}let x=d.delta;if(x.content!==null&&x.content!==void 0){let p=typeof x.content==="string"?[x.content]:x.content;for(let h of p){if(typeof h==="string"){let m=y(h);if(!m)continue;if(!s||s.type!=="text")a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e});s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e});continue}if(h.type==="thinking"){let m=(h.thinking??[]).map((g)=>g.text??"").filter((g)=>g.length>0).join(""),_=y(m);if(!_)continue;if(!s||s.type!=="thinking")a(s),s={type:"thinking",thinking:""},e.content.push(s),n.push({type:"thinking_start",contentIndex:f(),partial:e});s.thinking+=_,n.push({type:"thinking_delta",contentIndex:f(),delta:_,partial:e});continue}if(h.type==="text"){let m=y(h.text??"");if(!m)continue;if(!s||s.type!=="text")a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e});s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e})}}}let j=x.tool_calls||[];for(let p of j){if(s)a(s),s=null;let h=p.id&&p.id!=="null"?p.id:P(`toolcall:${p.index??0}`,0),m=p.index??h,_=u.get(m),g;if(_!==void 0){let R=e.content[_];if(R?.type==="toolCall")g=R}if(!g)g={type:"toolCall",id:h,name:p.function.name,arguments:{},partialArgs:""},e.content.push(g),u.set(m,e.content.length-1),n.push({type:"toolcall_start",contentIndex:e.content.length-1,partial:e});let C=typeof p.function.arguments==="string"?p.function.arguments:JSON.stringify(p.function.arguments||{});g.partialArgs=(g.partialArgs||"")+C,g.arguments=W(g.partialArgs),n.push({type:"toolcall_delta",contentIndex:u.get(m),delta:C,partial:e})}}a(s);for(let i of u.values()){let c=e.content[i];if(c.type!=="toolCall")continue;let d=c;d.arguments=W(d.partialArgs),delete d.partialArgs,n.push({type:"toolcall_end",contentIndex:i,toolCall:d,partial:e})}}function le(t){return t.map((e)=>{let n=ce(e,!0);return{type:"function",function:{name:e.name,description:e.description,parameters:T(me(e,n)),strict:n??!1}}})}function T(t){if(Array.isArray(t))return t.map((e)=>T(e));if(t&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=T(r);return e}return t}function fe(t,e){let n=[];for(let[r,o]of t.entries()){if(o.role==="system"){let a=r===0?N(o):Me(o);if(a.length>0)n.push({role:"system",content:y(a)});continue}if(o.role==="user"){if(typeof o.content==="string"){n.push({role:"user",content:y(o.content)});continue}let a=o.content.some((c)=>c.type==="image"),i=o.content.filter((c)=>c.type==="text"||e).map((c)=>{if(c.type==="text")return{type:"text",text:y(c.text)};return{type:"image_url",imageUrl:`data:${c.mimeType};base64,${c.data}`}});if(i.length>0){n.push({role:"user",content:i});continue}if(a&&!e)n.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(o.role==="assistant"){let a=[],i=[];for(let d of o.content){if(d.type==="text"){if(d.text.trim().length>0)a.push({type:"text",text:y(d.text)});continue}if(d.type==="thinking"){if(d.thinking.trim().length>0)a.push({type:"thinking",thinking:[{type:"text",text:y(d.thinking)}]});continue}i.push({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.arguments||{})},index:0})}let c={role:"assistant",prefix:!1};if(a.length>0)c.content=a;if(i.length>0)c.toolCalls=i;if(a.length>0||i.length>0)n.push(c);continue}let s=[],l=o.content.filter((a)=>a.type==="text").map((a)=>a.type==="text"?y(a.text):"").join(`
2
+ import{W}from"./chunk-t66jqz12.js";import{Pr}from"./chunk-wnzvnskb.js";import{Ye}from"./chunk-7jezts2n.js";import{ee}from"./chunk-tvm4zmgj.js";import{he,ue,K,fe}from"./chunk-e6c2mzxc.js";import{y}from"./chunk-3k627vf2.js";import{j}from"./chunk-2ks2tnac.js";import{U,Le,oe,re,Q,G}from"./chunk-0d51ggzj.js";import{M}from"./chunk-jp5afrwm.js";var S=9,D=4000,B=(t,e,n)=>{let r=new M,o=re(e,t.compat?.supportsMidConvoSystemMessages);return(async()=>{let s=J(t);try{let l=n?.apiKey;if(!l)throw Error(`No API key for provider: ${t.provider}`);let f=z(),u=fe(o.messages,t,(d)=>f(d)),a=se(t,o,u,n),i=await n?.onPayload?.(a,t);if(i!==void 0)a=i;let c=await Z(t,a,l,n);if(r.push({type:"start",partial:s}),await ie(t,s,r,c,n?.onProviderStreamEvent),n?.signal?.aborted)throw Error("Request was aborted");if(s.stopReason==="pending")throw Error("Mistral stream ended without a finish reason");if(s.stopReason==="aborted"||s.stopReason==="error")throw Error(s.errorMessage||"An unknown error occurred");r.push({type:"done",reason:s.stopReason,message:s}),r.end()}catch(l){for(let f of s.content)delete f.partialArgs;s.stopReason=n?.signal?.aborted?"aborted":"error",s.errorMessage=H(l),r.push({type:"error",reason:s.stopReason,error:s}),r.end()}})(),r},Ie=(t,e,n)=>{let r=n?.apiKey;if(!r)throw Error(`No API key for provider: ${t.provider}`);let o={...K(t,e,n,r),toolChoice:n?.toolChoice},s=n?.reasoning?G(t,n.reasoning):void 0,l=s==="off"?void 0:s,f=t.reasoning?t.thinkingLevelMap:void 0,u=f?l?f[l]??"high":f.off??void 0:void 0;return B(t,e,{...o,promptMode:t.reasoning&&!f&&l?"reasoning":void 0,reasoningEffort:u})};function J(t){return{role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function z(){let t=new Map,e=new Map;return(n)=>{let r=t.get(n);if(r)return r;let o=0;while(!0){let s=P(n,o),l=e.get(s);if(!l||l===n)return t.set(n,s),e.set(s,n),s;o++}}}function P(t,e){let n=t.replace(/[^a-zA-Z0-9]/g,"");if(e===0&&n.length===S)return n;let r=n||t,o=e===0?r:`${r}:${e}`;return Ye(o).replace(/[^a-zA-Z0-9]/g,"").slice(0,S)}function H(t){if(t instanceof Error){let e=t,n=typeof e.statusCode==="number"?e.statusCode:void 0,r=typeof e.body==="string"?e.body.trim():void 0;if(n!==void 0&&r)return`Mistral API error (${n}): ${q(r,D)}`;if(n!==void 0)return`Mistral API error (${n}): ${t.message}`;return t.message}return F(t)}function q(t,e){if(t.length<=e)return t;return`${t.slice(0,e)}... [truncated ${t.length-e} chars]`}function F(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}async function Z(t,e,n,r){let o=new URL(t.baseUrl);o.pathname=`${o.pathname.replace(/\/+$/u,"")}/`;let s=new URL("v1/chat/completions",o),l=X(t,n,r),f=r?.timeoutMs??60000,u=AbortSignal.timeout(f),a=Pr([r?.signal,u]),i;try{i=await(r?.fetch??globalThis.fetch)(s,{method:"POST",headers:l,body:JSON.stringify(Y(e)),signal:a.signal})}catch(c){if(u.aborted&&!r?.signal?.aborted)throw Error(`Mistral response headers timed out after ${f}ms`);throw c}finally{a.cleanup()}if(await r?.onResponse?.({status:i.status,headers:j(i.headers)},t),!i.ok){let c=await i.text();throw new O(i.status,c,i.statusText)}if(!i.body)throw Error("Mistral response has no body");return ne(i.body,r?.signal)}class O extends Error{statusCode;body;constructor(t,e,n){super(n||`Request failed with status ${t}`);this.name="MistralHttpError",this.statusCode=t,this.body=e}}function X(t,e,n){let r=new Headers({"User-Agent":ee(),accept:"text/event-stream",authorization:`Bearer ${e}`,"content-type":"application/json"});A(r,t.headers),A(r,n?.headers);let o=I(t.headers,"x-affinity")||I(n?.headers,"x-affinity");if(L(n)&&!o)r.set("x-affinity",n.sessionId);return r}function A(t,e){if(!e)return;for(let[n,r]of Object.entries(e))if(r===null)t.delete(n);else t.set(n,r)}function I(t,e){return!!t&&Object.keys(t).some((n)=>n.toLowerCase()===e)}function Y(t){let e={...t};for(let[r,o]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])k(e,r,o);e.messages=t.messages.map((r)=>V(r));let n=e.response_format;if(w(n)){let r={...n};k(r,"jsonSchema","json_schema");let o=r.json_schema;if(w(o)){let s={...o};k(s,"schemaDefinition","schema"),r.json_schema=s}e.response_format=r}return e}function V(t){let e={...t};if(k(e,"toolCalls","tool_calls"),k(e,"toolCallId","tool_call_id"),Array.isArray(t.content))e.content=t.content.map((n)=>te(n));return e}function te(t){let e={...t};for(let[n,r]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])k(e,n,r);return e}function k(t,e,n){if(!(e in t))return;t[n]=t[e],delete t[e]}function w(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}var b=Symbol("mistral-stream-done");async function*ne(t,e){let n=t.getReader(),r=new TextDecoder,o="",s=()=>{n.cancel().catch(()=>{})};e?.addEventListener("abort",s,{once:!0});try{while(!0){if(e?.aborted)throw e.reason;let{done:l,value:f}=await n.read();if(e?.aborted)throw e.reason;o+=l?r.decode():r.decode(f,{stream:!0});let u=E(o);while(u){let a=v(o.slice(0,u.index));if(o=o.slice(u.index+u.length),a===b)return;if(a)yield a;u=E(o)}if(l)break}if(o.trim()){let l=v(o);if(l!==b&&l)yield l}}finally{e?.removeEventListener("abort",s);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}function E(t){let e=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(t);return e?.index===void 0?void 0:{index:e.index,length:e[0].length}}function v(t){let e=t.split(/\r\n|\r|\n/u).filter((r)=>r.startsWith("data:")).map((r)=>r.slice(5).trimStart()).join(`
3
+ `).trim();if(!e)return;if(e==="[DONE]")return b;let n=JSON.parse(e);if(!w(n)||!Array.isArray(n.choices))throw Error("Invalid Mistral streaming event");return{data:n}}function se(t,e,n,r){let o={model:t.id,stream:!0,messages:le(n,t.input.includes("image"))},s=oe(e.messages);if(s.length>0)o.tools=ce(s);if(r?.temperature!==void 0)o.temperature=r.temperature;if(r?.maxTokens!==void 0)o.maxTokens=r.maxTokens;if(r?.toolChoice)o.toolChoice=pe(r.toolChoice);if(r?.promptMode)o.promptMode=r.promptMode;if(r?.reasoningEffort)o.reasoningEffort=r.reasoningEffort;if(L(r))o.promptCacheKey=r.sessionId;return o}function L(t){return t?.cacheRetention!=="none"&&!!t?.sessionId}function ae(t,e){let n=t,r=n.promptTokensDetails?.cachedTokens??n.prompt_tokens_details?.cached_tokens??n.promptTokenDetails?.cachedTokens??n.prompt_token_details?.cached_tokens??n.numCachedTokens??n.num_cached_tokens??0,o=typeof r==="number"&&Number.isFinite(r)?r:0;return Math.min(e,Math.max(0,o))}async function ie(t,e,n,r,o){let s=null,l=e.content,f=()=>l.length-1,u=new Map,a=(i)=>{if(!i)return;if(i.type==="text"){n.push({type:"text_end",contentIndex:f(),content:i.text,partial:e});return}if(i.type==="thinking")n.push({type:"thinking_end",contentIndex:f(),content:i.thinking,partial:e})};for await(let i of r){let c=i.data;if(await o?.(c,t),e.responseId||=c.id,c.usage){let p=c.usage.prompt_tokens||0,h=ae(c.usage,p);e.usage.input=Math.max(0,p-h),e.usage.output=c.usage.completion_tokens||0,e.usage.cacheRead=h,e.usage.cacheWrite=0,e.usage.totalTokens=c.usage.total_tokens||e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,Q(t,e.usage)}let d=c.choices[0];if(!d)continue;if(d.finish_reason){e.rawStopReason=d.finish_reason;let p=me(d.finish_reason);if(e.stopReason=p.stopReason,p.errorMessage)e.errorMessage=p.errorMessage}let x=d.delta;if(x.content!==null&&x.content!==void 0){let p=typeof x.content==="string"?[x.content]:x.content;for(let h of p){if(typeof h==="string"){let m=y(h);if(!m)continue;if(!s||s.type!=="text")a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e});s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e});continue}if(h.type==="thinking"){let m=(h.thinking??[]).map((g)=>g.text??"").filter((g)=>g.length>0).join(""),_=y(m);if(!_)continue;if(!s||s.type!=="thinking")a(s),s={type:"thinking",thinking:""},e.content.push(s),n.push({type:"thinking_start",contentIndex:f(),partial:e});s.thinking+=_,n.push({type:"thinking_delta",contentIndex:f(),delta:_,partial:e});continue}if(h.type==="text"){let m=y(h.text??"");if(!m)continue;if(!s||s.type!=="text")a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e});s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e})}}}let N=x.tool_calls||[];for(let p of N){if(s)a(s),s=null;let h=p.id&&p.id!=="null"?p.id:P(`toolcall:${p.index??0}`,0),m=p.index??h,_=u.get(m),g;if(_!==void 0){let R=e.content[_];if(R?.type==="toolCall")g=R}if(!g)g={type:"toolCall",id:h,name:p.function.name,arguments:{},partialArgs:""},e.content.push(g),u.set(m,e.content.length-1),n.push({type:"toolcall_start",contentIndex:e.content.length-1,partial:e});let C=typeof p.function.arguments==="string"?p.function.arguments:JSON.stringify(p.function.arguments||{});g.partialArgs=(g.partialArgs||"")+C,g.arguments=W(g.partialArgs),n.push({type:"toolcall_delta",contentIndex:u.get(m),delta:C,partial:e})}}a(s);for(let i of u.values()){let c=e.content[i];if(c.type!=="toolCall")continue;let d=c;d.arguments=W(d.partialArgs),delete d.partialArgs,n.push({type:"toolcall_end",contentIndex:i,toolCall:d,partial:e})}}function ce(t){return t.map((e)=>{let n=ue(e,!0);return{type:"function",function:{name:e.name,description:e.description,parameters:T(he(e,n)),strict:n??!1}}})}function T(t){if(Array.isArray(t))return t.map((e)=>T(e));if(t&&typeof t==="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=T(r);return e}return t}function le(t,e){let n=[];for(let[r,o]of t.entries()){if(o.role==="system"){let a=r===0?U(o):Le(o);if(a.length>0)n.push({role:"system",content:y(a)});continue}if(o.role==="user"){if(typeof o.content==="string"){n.push({role:"user",content:y(o.content)});continue}let a=o.content.some((c)=>c.type==="image"),i=o.content.filter((c)=>c.type==="text"||e).map((c)=>{if(c.type==="text")return{type:"text",text:y(c.text)};return{type:"image_url",imageUrl:`data:${c.mimeType};base64,${c.data}`}});if(i.length>0){n.push({role:"user",content:i});continue}if(a&&!e)n.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(o.role==="assistant"){let a=[],i=[];for(let d of o.content){if(d.type==="text"){if(d.text.trim().length>0)a.push({type:"text",text:y(d.text)});continue}if(d.type==="thinking"){if(d.thinking.trim().length>0)a.push({type:"thinking",thinking:[{type:"text",text:y(d.thinking)}]});continue}i.push({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.arguments||{})},index:0})}let c={role:"assistant",prefix:!1};if(a.length>0)c.content=a;if(i.length>0)c.toolCalls=i;if(a.length>0||i.length>0)n.push(c);continue}let s=[],l=o.content.filter((a)=>a.type==="text").map((a)=>a.type==="text"?y(a.text):"").join(`
4
4
  `),f=o.content.some((a)=>a.type==="image"),u=de(l,f,e,o.isError);s.push({type:"text",text:u});for(let a of o.content){if(!e)continue;if(a.type!=="image")continue;s.push({type:"image_url",imageUrl:`data:${a.mimeType};base64,${a.data}`})}n.push({role:"tool",toolCallId:o.toolCallId,name:o.toolName,content:s})}return n}function de(t,e,n,r){let o=t.trim(),s=r?"[tool error] ":"";if(o.length>0)return`${s}${o}${e&&!n?`
5
- [tool image omitted: model does not support images]`:""}`;if(e){if(n)return r?"[tool error] (see attached image)":"(see attached image)";return r?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)"}return r?"[tool error] (no tool output)":"(no tool output)"}function ue(t){if(!t)return;if(t==="auto"||t==="none"||t==="any"||t==="required")return t;return{type:"function",function:{name:t.function.name}}}function pe(t){if(t===null)return{stopReason:"stop"};switch(t){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error (server error)"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${t}`}}}export{D as stream,Ee as streamSimple};
5
+ [tool image omitted: model does not support images]`:""}`;if(e){if(n)return r?"[tool error] (see attached image)":"(see attached image)";return r?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)"}return r?"[tool error] (no tool output)":"(no tool output)"}function pe(t){if(!t)return;if(t==="auto"||t==="none"||t==="any"||t==="required")return t;return{type:"function",function:{name:t.function.name}}}function me(t){if(t===null)return{stopReason:"stop"};switch(t){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error (server error)"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${t}`}}}export{B as stream,Ie as streamSimple};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{L}from"./chunk-q9dd6fhj.js";import{b}from"./chunk-c7rcw9fb.js";import{i}from"./chunk-bwawt15q.js";var g=i(b());var U=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var R=i(L());var f=i(b());var j=300000,k="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var q=async(e,o={},r)=>{let{SSOOIDCClient:t}=await import("./chunk-arcqjt91.js"),n=(p)=>o.clientConfig?.[p]??o.parentClientConfig?.[p]??r?.[p];return new t(Object.assign({},o.clientConfig??{},{region:e??o.clientConfig?.region,logger:n("logger"),userAgentAppId:n("userAgentAppId")}))};var W=async(e,o,r={},t)=>{let{CreateTokenCommand:n}=await import("./chunk-arcqjt91.js");return(await q(o,r,t)).send(new n({clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken,grantType:"refresh_token"}))};var X=i(b());var I=(e)=>{if(e.expiration&&e.expiration.getTime()<Date.now())throw new X.TokenProviderError(`Token is expired. ${k}`,!1)};var z=i(b());var w=(e,o,r=!1)=>{if(typeof o>"u")throw new z.TokenProviderError(`Value not present for '${e}' in SSO Token${r?". Cannot refresh":""}. ${k}`,!1)};var J=i(b());import{promises as ee}from"fs";var{writeFile:oe}=ee,V=(e,o)=>{let r=J.getSSOTokenFilepath(e),t=JSON.stringify(o,null,2);return oe(r,t)};var Y=new Map,N=(e={})=>async({callerClientConfig:o}={})=>{e.logger?.debug("@aws-sdk/token-providers - fromSso");let r=await f.parseKnownFiles(e),t=f.getProfileName({profile:e.profile??o?.profile}),n=r[t];if(!n)throw new f.TokenProviderError(`Profile '${t}' could not be found in shared credentials file.`,!1);else if(!n.sso_session)throw new f.TokenProviderError(`Profile '${t}' is missing required property 'sso_session'.`);let a=n.sso_session,S=(await f.loadSsoSessionData(e))[a];if(!S)throw new f.TokenProviderError(`Sso session '${a}' could not be found in shared credentials file.`,!1);for(let c of["sso_start_url","sso_region"])if(!S[c])throw new f.TokenProviderError(`Sso session '${a}' is missing required property '${c}'.`,!1);let{sso_start_url:d,sso_region:y}=S,s;try{s=await f.getSSOTokenFromFile(a)}catch(c){throw new f.TokenProviderError(`The SSO session token associated with profile=${t} was not found or is invalid. ${k}`,!1)}w("accessToken",s.accessToken),w("expiresAt",s.expiresAt);let{accessToken:T,expiresAt:x}=s,l={token:T,expiration:new Date(x)};if(l.expiration.getTime()-Date.now()>j)return l;let m=Y.get(a)??0;if(Date.now()-m<30000)return I(l),l;w("clientId",s.clientId,!0),w("clientSecret",s.clientSecret,!0),w("refreshToken",s.refreshToken,!0);try{Y.set(a,Date.now());let c=await W(s,y,e,o);w("accessToken",c.accessToken),w("expiresIn",c.expiresIn);let C=new Date(Date.now()+c.expiresIn*1000);try{await V(a,{...s,accessToken:c.accessToken,expiresAt:C.toISOString(),refreshToken:c.refreshToken})}catch(u){}return{token:c.accessToken,expiration:C}}catch(c){return I(l),l}};var h=i(b()),O=!1,v=async({ssoStartUrl:e,ssoSession:o,ssoAccountId:r,ssoRegion:t,ssoRoleName:n,ssoClient:a,clientConfig:p,parentClientConfig:S,callerClientConfig:d,profile:y,filepath:s,configFilepath:T,ignoreCache:x,logger:l})=>{let m,c="To refresh this SSO session run aws sso login with the corresponding profile.";if(o)try{let _=await N({profile:y,filepath:s,configFilepath:T,ignoreCache:x,clientConfig:p,parentClientConfig:S,logger:l})({callerClientConfig:d});m={accessToken:_.token,expiresAt:new Date(_.expiration).toISOString()}}catch(_){throw new h.CredentialsProviderError(_.message,{tryNextLink:O,logger:l})}else try{m=await h.getSSOTokenFromFile(e)}catch(_){throw new h.CredentialsProviderError("The SSO session associated with this profile is invalid. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:O,logger:l})}if(new Date(m.expiresAt).getTime()-Date.now()<=0)throw new h.CredentialsProviderError("The SSO session associated with this profile has expired. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:O,logger:l});let{accessToken:C}=m,{SSOClient:u,GetRoleCredentialsCommand:E}=await import("./chunk-benrzwea.js"),Z=a||new u(Object.assign({},p??{},{logger:p?.logger??d?.logger??S?.logger,region:p?.region??t,userAgentAppId:p?.userAgentAppId??d?.userAgentAppId??S?.userAgentAppId})),P;try{P=await Z.send(new E({accountId:r,roleName:n,accessToken:C}))}catch(_){throw new h.CredentialsProviderError(_,{tryNextLink:O,logger:l})}let{roleCredentials:{accessKeyId:F,secretAccessKey:D,sessionToken:M,expiration:G,credentialScope:K,accountId:H}={}}=P;if(!F||!D||!M||!G)throw new h.CredentialsProviderError("SSO returns an invalid temporary credential.",{tryNextLink:O,logger:l});let A={accessKeyId:F,secretAccessKey:D,sessionToken:M,expiration:new Date(G),...K&&{credentialScope:K},...H&&{accountId:H}};if(o)R.setCredentialFeature(A,"CREDENTIALS_SSO","s");else R.setCredentialFeature(A,"CREDENTIALS_SSO_LEGACY","u");return A};var B=i(b()),Q=(e,o)=>{let{sso_start_url:r,sso_account_id:t,sso_region:n,sso_role_name:a}=e;if(!r||!t||!n||!a)throw new B.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(e).join(", ")}
2
+ import{L}from"./chunk-g3ed130w.js";import{b}from"./chunk-adys4qq4.js";import{i}from"./chunk-bwawt15q.js";var g=i(b());var U=(e)=>e&&(typeof e.sso_start_url==="string"||typeof e.sso_account_id==="string"||typeof e.sso_session==="string"||typeof e.sso_region==="string"||typeof e.sso_role_name==="string");var R=i(L());var f=i(b());var j=300000,k="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var q=async(e,o={},r)=>{let{SSOOIDCClient:t}=await import("./chunk-hd3x1w46.js"),n=(p)=>o.clientConfig?.[p]??o.parentClientConfig?.[p]??r?.[p];return new t(Object.assign({},o.clientConfig??{},{region:e??o.clientConfig?.region,logger:n("logger"),userAgentAppId:n("userAgentAppId")}))};var W=async(e,o,r={},t)=>{let{CreateTokenCommand:n}=await import("./chunk-hd3x1w46.js");return(await q(o,r,t)).send(new n({clientId:e.clientId,clientSecret:e.clientSecret,refreshToken:e.refreshToken,grantType:"refresh_token"}))};var X=i(b());var I=(e)=>{if(e.expiration&&e.expiration.getTime()<Date.now())throw new X.TokenProviderError(`Token is expired. ${k}`,!1)};var z=i(b());var w=(e,o,r=!1)=>{if(typeof o>"u")throw new z.TokenProviderError(`Value not present for '${e}' in SSO Token${r?". Cannot refresh":""}. ${k}`,!1)};var J=i(b());import{promises as ee}from"fs";var{writeFile:oe}=ee,V=(e,o)=>{let r=J.getSSOTokenFilepath(e),t=JSON.stringify(o,null,2);return oe(r,t)};var Y=new Map,N=(e={})=>async({callerClientConfig:o}={})=>{e.logger?.debug("@aws-sdk/token-providers - fromSso");let r=await f.parseKnownFiles(e),t=f.getProfileName({profile:e.profile??o?.profile}),n=r[t];if(!n)throw new f.TokenProviderError(`Profile '${t}' could not be found in shared credentials file.`,!1);else if(!n.sso_session)throw new f.TokenProviderError(`Profile '${t}' is missing required property 'sso_session'.`);let a=n.sso_session,S=(await f.loadSsoSessionData(e))[a];if(!S)throw new f.TokenProviderError(`Sso session '${a}' could not be found in shared credentials file.`,!1);for(let c of["sso_start_url","sso_region"])if(!S[c])throw new f.TokenProviderError(`Sso session '${a}' is missing required property '${c}'.`,!1);let{sso_start_url:d,sso_region:y}=S,s;try{s=await f.getSSOTokenFromFile(a)}catch(c){throw new f.TokenProviderError(`The SSO session token associated with profile=${t} was not found or is invalid. ${k}`,!1)}w("accessToken",s.accessToken),w("expiresAt",s.expiresAt);let{accessToken:T,expiresAt:x}=s,l={token:T,expiration:new Date(x)};if(l.expiration.getTime()-Date.now()>j)return l;let m=Y.get(a)??0;if(Date.now()-m<30000)return I(l),l;w("clientId",s.clientId,!0),w("clientSecret",s.clientSecret,!0),w("refreshToken",s.refreshToken,!0);try{Y.set(a,Date.now());let c=await W(s,y,e,o);w("accessToken",c.accessToken),w("expiresIn",c.expiresIn);let C=new Date(Date.now()+c.expiresIn*1000);try{await V(a,{...s,accessToken:c.accessToken,expiresAt:C.toISOString(),refreshToken:c.refreshToken})}catch(u){}return{token:c.accessToken,expiration:C}}catch(c){return I(l),l}};var h=i(b()),O=!1,v=async({ssoStartUrl:e,ssoSession:o,ssoAccountId:r,ssoRegion:t,ssoRoleName:n,ssoClient:a,clientConfig:p,parentClientConfig:S,callerClientConfig:d,profile:y,filepath:s,configFilepath:T,ignoreCache:x,logger:l})=>{let m,c="To refresh this SSO session run aws sso login with the corresponding profile.";if(o)try{let _=await N({profile:y,filepath:s,configFilepath:T,ignoreCache:x,clientConfig:p,parentClientConfig:S,logger:l})({callerClientConfig:d});m={accessToken:_.token,expiresAt:new Date(_.expiration).toISOString()}}catch(_){throw new h.CredentialsProviderError(_.message,{tryNextLink:O,logger:l})}else try{m=await h.getSSOTokenFromFile(e)}catch(_){throw new h.CredentialsProviderError("The SSO session associated with this profile is invalid. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:O,logger:l})}if(new Date(m.expiresAt).getTime()-Date.now()<=0)throw new h.CredentialsProviderError("The SSO session associated with this profile has expired. To refresh this SSO session run aws sso login with the corresponding profile.",{tryNextLink:O,logger:l});let{accessToken:C}=m,{SSOClient:u,GetRoleCredentialsCommand:E}=await import("./chunk-3j2kkgsc.js"),Z=a||new u(Object.assign({},p??{},{logger:p?.logger??d?.logger??S?.logger,region:p?.region??t,userAgentAppId:p?.userAgentAppId??d?.userAgentAppId??S?.userAgentAppId})),P;try{P=await Z.send(new E({accountId:r,roleName:n,accessToken:C}))}catch(_){throw new h.CredentialsProviderError(_,{tryNextLink:O,logger:l})}let{roleCredentials:{accessKeyId:F,secretAccessKey:D,sessionToken:M,expiration:G,credentialScope:K,accountId:H}={}}=P;if(!F||!D||!M||!G)throw new h.CredentialsProviderError("SSO returns an invalid temporary credential.",{tryNextLink:O,logger:l});let A={accessKeyId:F,secretAccessKey:D,sessionToken:M,expiration:new Date(G),...K&&{credentialScope:K},...H&&{accountId:H}};if(o)R.setCredentialFeature(A,"CREDENTIALS_SSO","s");else R.setCredentialFeature(A,"CREDENTIALS_SSO_LEGACY","u");return A};var B=i(b()),Q=(e,o)=>{let{sso_start_url:r,sso_account_id:t,sso_region:n,sso_role_name:a}=e;if(!r||!t||!n||!a)throw new B.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", "sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(e).join(", ")}
3
3
  Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`,{tryNextLink:!1,logger:o});return e};var se=(e={})=>async({callerClientConfig:o}={})=>{e.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO");let{ssoStartUrl:r,ssoAccountId:t,ssoRegion:n,ssoRoleName:a,ssoSession:p}=e,{ssoClient:S}=e,d=g.getProfileName({profile:e.profile??o?.profile});if(!r&&!t&&!n&&!a&&!p){let s=(await g.parseKnownFiles(e))[d];if(!s)throw new g.CredentialsProviderError(`Profile ${d} was not found.`,{logger:e.logger});if(!U(s))throw new g.CredentialsProviderError(`Profile ${d} is not configured with SSO credentials.`,{logger:e.logger});if(s?.sso_session){let u=(await g.loadSsoSessionData(e))[s.sso_session],E=` configurations in profile ${d} and sso-session ${s.sso_session}`;if(n&&n!==u.sso_region)throw new g.CredentialsProviderError("Conflicting SSO region"+E,{tryNextLink:!1,logger:e.logger});if(r&&r!==u.sso_start_url)throw new g.CredentialsProviderError("Conflicting SSO start_url"+E,{tryNextLink:!1,logger:e.logger});s.sso_region=u.sso_region,s.sso_start_url=u.sso_start_url}let{sso_start_url:T,sso_account_id:x,sso_region:l,sso_role_name:m,sso_session:c}=Q(s,e.logger);return v({ssoStartUrl:T,ssoSession:c,ssoAccountId:x,ssoRegion:l,ssoRoleName:m,ssoClient:S,clientConfig:e.clientConfig,parentClientConfig:e.parentClientConfig,callerClientConfig:e.callerClientConfig,profile:d,filepath:e.filepath,configFilepath:e.configFilepath,ignoreCache:e.ignoreCache,logger:e.logger})}else if(!r||!t||!n||!a)throw new g.CredentialsProviderError('Incomplete configuration. The fromSSO() argument hash must include "ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"',{tryNextLink:!1,logger:e.logger});else return v({ssoStartUrl:r,ssoSession:p,ssoAccountId:t,ssoRegion:n,ssoRoleName:a,ssoClient:S,clientConfig:e.clientConfig,parentClientConfig:e.parentClientConfig,callerClientConfig:e.callerClientConfig,profile:d,filepath:e.filepath,configFilepath:e.configFilepath,ignoreCache:e.ignoreCache,logger:e.logger})};export{se as fromSSO};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Mn,Ii}from"./chunk-7kjr9gdx.js";export{Mn as runUIWorker,Ii as uiTest};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{N,G}from"./chunk-n981vx1t.js";class p extends Error{}var L=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function y(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function D(e){if(!y(e))return!1;let n=typeof e.type==="string"?[e.type]:Array.isArray(e.type)?e.type:[];return n.includes("object")||n.includes("array")||e.properties!==void 0||e.items!==void 0}function M(e){if(!y(e))return!1;if(e.type==="null"||Array.isArray(e.type)&&e.type.includes("null"))return!0;if(e.const===null||Array.isArray(e.enum)&&e.enum.includes(null))return!0;return Array.isArray(e.anyOf)&&e.anyOf.some((n)=>M(n))}function w(e,n){if(!y(e))throw new p("boolean schemas are unsupported");for(let a of L)if(e[a]!==void 0)throw new p(`${a} schemas are unsupported`);if(n){for(let[a,l]of Object.entries(e))if(n(a,l))throw new p(`${a}: ${JSON.stringify(l)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new p("anyOf must contain at least one schema");for(let a of e.anyOf){if(D(a))throw new p("object and array unions are unsupported");w(a,n)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new p("tuple schemas are unsupported");w(e.items,n)}let t=e.type==="object";if(e.properties!==void 0&&!t)throw new p("properties require type object");if(!t)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new p("schema-valued or true additionalProperties is unsupported");if(e.properties!==void 0&&!y(e.properties))throw new p("object properties must be a schema map");if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some((a)=>typeof a!=="string")))throw new p("object required must be a string array");let r=e.properties??{},i=Object.keys(r),o=new Set(Array.isArray(e.required)?e.required:[]);if([...o].some((a)=>!i.includes(a)))throw new p("required contains an unknown property");for(let[a,l]of Object.entries(r))if(w(l,n),!o.has(a)&&!M(l))r[a]={anyOf:[l,{type:"null"}]};e.required=i,e.additionalProperties=!1}function k(e,n){let t=structuredClone(e);if(!y(t))throw new p("root schema must have type object");if(w(t,n),t.type!=="object")throw new p("root schema must have type object");return t}function me(e,n){return n===!0?k(e.parameters):e.parameters}function Or(e,n,t){let r=n[t];if(typeof r!=="string")throw Error(`Grammar tool call "${e}" requires argument "${t}" to be a string.`);return r}function Nr(e,n,t,r){if(e.closed){if(r&&t===e.input)return;throw Error(`grammar tool input for property "${n}" changed after it was closed`)}if(!t.startsWith(e.input))throw Error(`grammar tool input for property "${n}" changed non-monotonically`);let i=t.slice(e.input.length);if(!r&&i.length===0)return;let o="";if(!e.started)o+=`{${JSON.stringify(n)}:"`,e.started=!0;if(o+=JSON.stringify(i).slice(1,-1),e.input=t,r)o+='"}',e.closed=!0;return o}function b(e){let n=e.parameters;if(n.type!=="object")throw Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(n.required)||n.required.length!==1||typeof n.required[0]!=="string")throw Error("grammar constrained sampling requires exactly one required string property");let t=n.required[0];if(!n.properties?.[t])throw Error(`grammar constrained sampling requires a properties entry for ${t}`);if(n.properties[t]?.type!=="string")throw Error(`grammar constrained sampling property ${t} must have type string`);return t}function ce(e,n,t){let r=e.constrainedSampling;if(!r||r.type!=="json_schema")return;if(n)try{return k(e.parameters,t),!0}catch(i){if(!(i instanceof p))throw i;if(r.strict!=="require")return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${i.message}.`)}if(r.strict==="require")throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);return}function Yt(e,n){let t=e.constrainedSampling;if(!t||t.type!=="grammar")return;if(!n)return;let r=t.variants.openai_lark,i=t.variants.openai_regex,o=typeof r==="string"&&r.trim().length>0,a=typeof i==="string"&&i.trim().length>0;if(!o&&!a)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:o?"lark":"regex",definition:o?r:i,inputProperty:b(e)}}catch(l){let d=l instanceof Error?l.message:String(l);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${d}.`)}}function Ae(e,n){let t=new Map;for(let r of e??[]){let i=Yt(r,n);if(i)t.set(r.name,i.inputProperty)}return t}var O=3.5,H=4800;function _(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function P(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}function W(e){if(typeof e==="string")return e.length;let n=0;for(let t of e)n+=t.type==="text"?t.text.length:H;return n}function v(e){return Math.ceil(e.length/O)}function C(e){return Math.ceil(W(e)/O)}function E(e){let n=0;if(e.role==="system")return v(N(e))+R(e.toolsAdded)+R(e.toolsRemoved);if(e.role==="user")return C(e.content);if(e.role==="toolResult")return C(e.content);for(let t of e.content)if(t.type==="text")n+=t.text.length;else if(t.type==="thinking")n+=t.thinking.length;else n+=t.name.length+P(t.arguments).length;return Math.ceil(n/O)}function B(e){let n=Number.NEGATIVE_INFINITY,t;for(let r=0;r<e.length;r++){let i=e[r];if(i.role==="assistant"){let o=i;if(o.timestamp>=n&&o.stopReason!=="aborted"&&o.stopReason!=="error"&&_(o.usage)>0)t={usage:o.usage,index:r}}n=Math.max(n,i.timestamp)}return t}function S(e){let n="messages"in e?e.messages:e,t=B(n);if(t){let i=_(t.usage),o=0;for(let a=t.index+1;a<n.length;a++)o+=E(n[a]);return{tokens:i+o,usageTokens:i,trailingTokens:o,lastUsageIndex:t.index}}let r=0;for(let i of n)r+=E(i);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function R(e){if(!e||e.length===0)return 0;return v(P(e))}var F=4096,q=1;function Zt(e,n,t){if(e.contextWindow<=0)return Math.max(q,t);let r=e.contextWindow-S(n).tokens-F;return Math.min(t,Math.max(q,r))}function ut(e,n,t){let r=G(e,n),i=e.samplingParamsByThinkingLevel?.[r];return e.samplingParams||i||t?{...e.samplingParams,...i,...t}:void 0}function V(e,n,t,r){let i=ut(e,t?.reasoning??"off",t?.samplingParams);return{temperature:t?.temperature,samplingParams:i,maxTokens:Zt(e,n,t?.maxTokens??e.maxTokens),signal:t?.signal,telemetryContext:t?.telemetryContext,apiKey:r||t?.apiKey,fetch:t?.fetch,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,onProviderStreamEvent:t?.onProviderStreamEvent,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata,env:t?.env}}var z=1024,K={minimal:1024,low:2048,medium:8192,high:16384};function Eo(e){return e==="xhigh"||e==="max"?"high":e}function Po(e,n){let t={...K,...n},r=Eo(e);return t[r]}function To(e,n){return Math.min(e,Math.max(0,n-z))}function Dr(e,n,t,r){let i=Po(t,r),o=e===void 0?n:Math.min(e+i,n);if(o<=i)i=To(i,o);return{maxTokens:o,thinkingBudget:i}}function j(e,n){let t=[],r=!1;for(let i of e){if(i.type==="image"){if(!r)t.push({type:"text",text:n});r=!0;continue}t.push(i),r=i.text===n}return t}function Y(e,n){if(n.input.includes("image"))return e;return e.map((t)=>{if(t.role==="user"&&Array.isArray(t.content))return{...t,content:j(t.content,"(image omitted: model does not support images)")};if(t.role==="toolResult")return{...t,content:j(t.content,"(tool image omitted: model does not support images)")};return t})}function he(e,n,t){let r=new Map,i=e.map((s)=>s.content==null?{...s,content:[]}:s),a=Y(i,n).map((s)=>{if(s.role==="system"||s.role==="user")return s;if(s.role==="toolResult"){let u=r.get(s.toolCallId);if(u&&u!==s.toolCallId)return{...s,toolCallId:u};return s}if(s.role==="assistant"){let u=s,c=u.provider===n.provider&&u.api===n.api&&u.model===n.id,x=u.content.flatMap((f)=>{if(f.type==="thinking"){if(f.redacted)return c?f:[];if(c&&f.thinkingSignature)return f;if(!f.thinking||f.thinking.trim()==="")return[];if(c)return f;return{type:"text",text:f.thinking}}if(f.type==="text"){if(c)return f;return{type:"text",text:f.text}}if(f.type==="toolCall"){let m=f,g=m;if(!c&&m.thoughtSignature)g={...m},delete g.thoughtSignature;if(!c&&t){let I=t(m.id,n,u);if(I!==m.id)r.set(m.id,I),g={...g,id:I}}return g}return f});return{...u,content:x}}return s}),l=[],d=[],h=new Set,T=[],A=()=>{if(d.length>0){for(let s of d)if(!h.has(s.id))l.push({role:"toolResult",toolCallId:s.id,toolName:s.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});d=[],h=new Set}l.push(...T),T.length=0};for(let s=0;s<a.length;s++){let u=a[s];if(u.role==="assistant"){A();let c=u;if(c.stopReason==="error"||c.stopReason==="aborted")continue;let x=c.content.filter((f)=>f.type==="toolCall");if(x.length>0)d=x,h=new Set;l.push(u)}else if(u.role==="toolResult")h.add(u.toolCallId),l.push(u);else if(u.role==="system")if(d.length>0)T.push(u);else l.push(u);else if(u.role==="user")A(),l.push(u);else l.push(u)}return A(),l}
3
- export{me,Or,Nr,ce,Yt,Ae,Zt,ut,V,Eo,Po,To,Dr,he};
2
+ import{U,G}from"./chunk-0d51ggzj.js";class p extends Error{}var j=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function y(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function L(e){if(!y(e))return!1;let n=typeof e.type==="string"?[e.type]:Array.isArray(e.type)?e.type:[];return n.includes("object")||n.includes("array")||e.properties!==void 0||e.items!==void 0}function M(e){if(!y(e))return!1;if(e.type==="null"||Array.isArray(e.type)&&e.type.includes("null"))return!0;if(e.const===null||Array.isArray(e.enum)&&e.enum.includes(null))return!0;return Array.isArray(e.anyOf)&&e.anyOf.some((n)=>M(n))}function w(e,n){if(!y(e))throw new p("boolean schemas are unsupported");for(let a of j)if(e[a]!==void 0)throw new p(`${a} schemas are unsupported`);if(n){for(let[a,l]of Object.entries(e))if(n(a,l))throw new p(`${a}: ${JSON.stringify(l)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new p("anyOf must contain at least one schema");for(let a of e.anyOf){if(L(a))throw new p("object and array unions are unsupported");w(a,n)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new p("tuple schemas are unsupported");w(e.items,n)}let t=e.type==="object";if(e.properties!==void 0&&!t)throw new p("properties require type object");if(!t)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new p("schema-valued or true additionalProperties is unsupported");if(e.properties!==void 0&&!y(e.properties))throw new p("object properties must be a schema map");if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some((a)=>typeof a!=="string")))throw new p("object required must be a string array");let r=e.properties??{},i=Object.keys(r),o=new Set(Array.isArray(e.required)?e.required:[]);if([...o].some((a)=>!i.includes(a)))throw new p("required contains an unknown property");for(let[a,l]of Object.entries(r))if(w(l,n),!o.has(a)&&!M(l))r[a]={anyOf:[l,{type:"null"}]};e.required=i,e.additionalProperties=!1}function N(e,n){let t=structuredClone(e);if(!y(t))throw new p("root schema must have type object");if(w(t,n),t.type!=="object")throw new p("root schema must have type object");return t}function he(e,n){return n===!0?N(e.parameters):e.parameters}function Or(e,n,t){let r=n[t];if(typeof r!=="string")throw Error(`Grammar tool call "${e}" requires argument "${t}" to be a string.`);return r}function Nr(e,n,t,r){if(e.closed){if(r&&t===e.input)return;throw Error(`grammar tool input for property "${n}" changed after it was closed`)}if(!t.startsWith(e.input))throw Error(`grammar tool input for property "${n}" changed non-monotonically`);let i=t.slice(e.input.length);if(!r&&i.length===0)return;let o="";if(!e.started)o+=`{${JSON.stringify(n)}:"`,e.started=!0;if(o+=JSON.stringify(i).slice(1,-1),e.input=t,r)o+='"}',e.closed=!0;return o}function D(e){let n=e.parameters;if(n.type!=="object")throw Error("grammar constrained sampling requires an object parameter schema");if(!Array.isArray(n.required)||n.required.length!==1||typeof n.required[0]!=="string")throw Error("grammar constrained sampling requires exactly one required string property");let t=n.required[0];if(!n.properties?.[t])throw Error(`grammar constrained sampling requires a properties entry for ${t}`);if(n.properties[t]?.type!=="string")throw Error(`grammar constrained sampling property ${t} must have type string`);return t}function ue(e,n,t){let r=e.constrainedSampling;if(!r||r.type!=="json_schema")return;if(n)try{return N(e.parameters,t),!0}catch(i){if(!(i instanceof p))throw i;if(r.strict!=="require")return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${i.message}.`)}if(r.strict==="require")throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);return}function Yt(e,n){let t=e.constrainedSampling;if(!t||t.type!=="grammar")return;if(!n)return;let r=t.variants.openai_lark,i=t.variants.openai_regex,o=typeof r==="string"&&r.trim().length>0,a=typeof i==="string"&&i.trim().length>0;if(!o&&!a)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:o?"lark":"regex",definition:o?r:i,inputProperty:D(e)}}catch(l){let d=l instanceof Error?l.message:String(l);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${d}.`)}}function Ee(e,n){let t=new Map;for(let r of e??[]){let i=Yt(r,n);if(i)t.set(r.name,i.inputProperty)}return t}var O=3.5,b=4800;function R(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function _(e){try{return JSON.stringify(e)??"undefined"}catch{return"[unserializable]"}}function H(e){if(typeof e==="string")return e.length;let n=0;for(let t of e)n+=t.type==="text"?t.text.length:b;return n}function P(e){return Math.ceil(e.length/O)}function k(e){return Math.ceil(H(e)/O)}function C(e){let n=0;if(e.role==="system")return P(U(e))+E(e.toolsAdded)+E(e.toolsRemoved);if(e.role==="user")return k(e.content);if(e.role==="toolResult")return k(e.content);for(let t of e.content)if(t.type==="text")n+=t.text.length;else if(t.type==="thinking")n+=t.thinking.length;else n+=t.name.length+_(t.arguments).length;return Math.ceil(n/O)}function W(e){let n=Number.NEGATIVE_INFINITY,t;for(let r=0;r<e.length;r++){let i=e[r];if(i.role==="assistant"){let o=i;if(o.timestamp>=n&&o.stopReason!=="aborted"&&o.stopReason!=="error"&&R(o.usage)>0)t={usage:o.usage,index:r}}n=Math.max(n,i.timestamp)}return t}function v(e){let n="messages"in e?e.messages:e,t=W(n);if(t){let i=R(t.usage),o=0;for(let a=t.index+1;a<n.length;a++)o+=C(n[a]);return{tokens:i+o,usageTokens:i,trailingTokens:o,lastUsageIndex:t.index}}let r=0;for(let i of n)r+=C(i);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function E(e){if(!e||e.length===0)return 0;return P(_(e))}var B=4096,S=1;function Zt(e,n,t){if(e.contextWindow<=0)return Math.max(S,t);let r=e.contextWindow-v(n).tokens-B;return Math.min(t,Math.max(S,r))}function ut(e,n,t){let r=G(e,n),i=e.samplingParamsByThinkingLevel?.[r];return e.samplingParams||i||t?{...e.samplingParams,...i,...t}:void 0}function K(e,n,t,r){let i=ut(e,t?.reasoning??"off",t?.samplingParams);return{temperature:t?.temperature,samplingParams:i,maxTokens:Zt(e,n,t?.maxTokens??e.maxTokens),signal:t?.signal,telemetryContext:t?.telemetryContext,apiKey:r||t?.apiKey,fetch:t?.fetch,transport:t?.transport,cacheRetention:t?.cacheRetention,sessionId:t?.sessionId,headers:t?.headers,onPayload:t?.onPayload,onResponse:t?.onResponse,onProviderStreamEvent:t?.onProviderStreamEvent,timeoutMs:t?.timeoutMs,websocketConnectTimeoutMs:t?.websocketConnectTimeoutMs,maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,metadata:t?.metadata,env:t?.env}}var F=1024,V={minimal:1024,low:2048,medium:8192,high:16384};function To(e){return e==="xhigh"||e==="max"?"high":e}function ko(e,n){let t={...V,...n},r=To(e);return t[r]}function Ro(e,n){return Math.min(e,Math.max(0,n-F))}function Dr(e,n,t,r){let i=ko(t,r),o=e===void 0?n:Math.min(e+i,n);if(o<=i)i=Ro(i,o);return{maxTokens:o,thinkingBudget:i}}function q(e,n){let t=[],r=!1;for(let i of e){if(i.type==="image"){if(!r)t.push({type:"text",text:n});r=!0;continue}t.push(i),r=i.text===n}return t}function z(e,n){if(n.input.includes("image"))return e;return e.map((t)=>{if(t.role==="user"&&Array.isArray(t.content))return{...t,content:q(t.content,"(image omitted: model does not support images)")};if(t.role==="toolResult")return{...t,content:q(t.content,"(tool image omitted: model does not support images)")};return t})}function fe(e,n,t){let r=new Map,i=e.map((s)=>s.content==null?{...s,content:[]}:s),a=z(i,n).map((s)=>{if(s.role==="system"||s.role==="user")return s;if(s.role==="toolResult"){let u=r.get(s.toolCallId);if(u&&u!==s.toolCallId)return{...s,toolCallId:u};return s}if(s.role==="assistant"){let u=s,c=u.provider===n.provider&&u.api===n.api&&u.model===n.id,x=u.content.flatMap((f)=>{if(f.type==="thinking"){if(f.redacted)return c?f:[];if(c&&f.thinkingSignature)return f;if(!f.thinking||f.thinking.trim()==="")return[];if(c)return f;return{type:"text",text:f.thinking}}if(f.type==="text"){if(c)return f;return{type:"text",text:f.text}}if(f.type==="toolCall"){let m=f,g=m;if(!c&&m.thoughtSignature)g={...m},delete g.thoughtSignature;if(!c&&t){let I=t(m.id,n,u);if(I!==m.id)r.set(m.id,I),g={...g,id:I}}return g}return f});return{...u,content:x}}return s}),l=[],d=[],h=new Set,T=[],A=()=>{if(d.length>0){for(let s of d)if(!h.has(s.id))l.push({role:"toolResult",toolCallId:s.id,toolName:s.name,content:[{type:"text",text:"No result provided"}],isError:!0,timestamp:Date.now()});d=[],h=new Set}l.push(...T),T.length=0};for(let s=0;s<a.length;s++){let u=a[s];if(u.role==="assistant"){A();let c=u;if(c.stopReason==="error"||c.stopReason==="aborted")continue;let x=c.content.filter((f)=>f.type==="toolCall");if(x.length>0)d=x,h=new Set;l.push(u)}else if(u.role==="toolResult")h.add(u.toolCallId),l.push(u);else if(u.role==="system")if(d.length>0)T.push(u);else l.push(u);else if(u.role==="user")A(),l.push(u);else l.push(u)}return A(),l}
3
+ export{he,Or,Nr,ue,Yt,Ee,Zt,ut,K,To,ko,Ro,Dr,fe};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{fr,kt,zt,jt,Vt,Kt,gr,yr,Rt,br,Sr,xr,wr,vr,_r}from"./chunk-f544p9rh.js";import{P}from"./chunk-c4qr1f41.js";import{ee}from"./chunk-tvm4zmgj.js";import{q,j}from"./chunk-y69ewdn2.js";import{V}from"./chunk-063vbmtp.js";import{y}from"./chunk-3k627vf2.js";import{fe}from"./chunk-x4874m8e.js";import{N,pe,ne,Le,Q,G}from"./chunk-n981vx1t.js";import{M}from"./chunk-z02sj1je.js";var b="v1",O="gcp-vertex-credentials",R=0,C=(e,o,t)=>{let i=new M,u=Le(o);return(async()=>{let n={role:"assistant",content:[],api:"google-vertex",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(t?.fetch&&t.fetch!==globalThis.fetch)throw Error("Custom fetch is not supported by the Google Vertex adapter");let c=L(t),g=c?S(e,c,t?.headers):I(e,U(t),D(t),t?.headers,t?.env),h=K(e,u,t),m=await t?.onPayload?.(h,e);if(m!==void 0)h=m;let p=await _r(()=>g.models.generateContentStream(h),t);i.push({type:"start",partial:n});let r=null,f=n.content,l=()=>f.length-1;for await(let s of p){await t?.onProviderStreamEvent?.(s,e),n.responseId||=s.responseId;let k=s.candidates?.[0];if(k?.content?.parts)for(let a of k.content.parts){if(a.text!==void 0){let d=yr(a);if(!r||d&&r.type!=="thinking"||!d&&r.type!=="text"){if(r)if(r.type==="text")i.push({type:"text_end",contentIndex:f.length-1,content:r.text,partial:n});else i.push({type:"thinking_end",contentIndex:l(),content:r.thinking,partial:n});if(d)r={type:"thinking",thinking:"",thinkingSignature:void 0},n.content.push(r),i.push({type:"thinking_start",contentIndex:l(),partial:n});else r={type:"text",text:""},n.content.push(r),i.push({type:"text_start",contentIndex:l(),partial:n})}if(r.type==="thinking")r.thinking+=a.text,r.thinkingSignature=Rt(r.thinkingSignature,a.thoughtSignature),i.push({type:"thinking_delta",contentIndex:l(),delta:a.text,partial:n});else r.text+=a.text,r.textSignature=Rt(r.textSignature,a.thoughtSignature),i.push({type:"text_delta",contentIndex:l(),delta:a.text,partial:n})}if(a.functionCall){if(r){if(r.type==="text")i.push({type:"text_end",contentIndex:l(),content:r.text,partial:n});else i.push({type:"thinking_end",contentIndex:l(),content:r.thinking,partial:n});r=null}let d=a.functionCall.id,x={type:"toolCall",id:!d||n.content.some((T)=>T.type==="toolCall"&&T.id===d)?`${a.functionCall.name}_${Date.now()}_${++R}`:d,name:a.functionCall.name||"",arguments:a.functionCall.args??{},...a.thoughtSignature&&{thoughtSignature:a.thoughtSignature}};n.content.push(x),i.push({type:"toolcall_start",contentIndex:l(),partial:n}),i.push({type:"toolcall_delta",contentIndex:l(),delta:JSON.stringify(x.arguments),partial:n}),i.push({type:"toolcall_end",contentIndex:l(),toolCall:x,partial:n})}}if(k?.finishReason){if(n.rawStopReason=k.finishReason,n.stopReason=vr(k.finishReason),n.content.some((a)=>a.type==="toolCall")&&n.stopReason==="stop")n.stopReason="toolUse"}if(s.usageMetadata)n.usage={input:(s.usageMetadata.promptTokenCount||0)-(s.usageMetadata.cachedContentTokenCount||0),output:(s.usageMetadata.candidatesTokenCount||0)+(s.usageMetadata.thoughtsTokenCount||0),cacheRead:s.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:s.usageMetadata.thoughtsTokenCount||0,totalTokens:s.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Q(e,n.usage)}if(r)if(r.type==="text")i.push({type:"text_end",contentIndex:l(),content:r.text,partial:n});else i.push({type:"thinking_end",contentIndex:l(),content:r.thinking,partial:n});if(t?.signal?.aborted)throw Error("Request was aborted");if(n.stopReason==="pending")throw Error("Google Vertex stream ended without a finish reason");if(n.stopReason==="aborted"||n.stopReason==="error"){let s=n.rawStopReason?`Provider stopped with: ${n.rawStopReason}`:"An unknown error occurred";throw Error(s)}i.push({type:"done",reason:n.stopReason,message:n}),i.end()}catch(c){for(let g of n.content)if("index"in g)delete g.index;n.stopReason=t?.signal?.aborted?"aborted":"error",n.errorMessage=j(q(c)),i.push({type:"error",reason:n.stopReason,error:n}),i.end()}})(),i},ue=(e,o,t)=>{let i={...V(e,o,t,void 0),toolChoice:t?.toolChoice};if(!t?.reasoning)return C(e,o,{...i,thinking:{enabled:!1}});let u=G(e,t.reasoning);if(u==="off")return C(e,o,{...i,thinking:{enabled:!1}});let n=zt(e,u);if(jt(e))return C(e,o,{...i,thinking:{enabled:!0,level:Vt(n)}});return C(e,o,{...i,thinking:{enabled:!0,budgetTokens:B(e,n,t.thinkingBudgets)}})};function I(e,o,t,i,u){let n=E(u);return new kt({vertexai:!0,project:o,location:t,apiVersion:b,...n?{googleAuthOptions:n}:{},httpOptions:v(e,i)})}function S(e,o,t){return new kt({vertexai:!0,apiKey:o,apiVersion:b,httpOptions:v(e,t)})}function v(e,o){let t={},i=w(e.baseUrl);if(i){if(t.baseUrl=i,t.baseUrlResourceScope=fr.COLLECTION,_(i))t.apiVersion=""}let u=fe({"User-Agent":ee(),...e.headers,...o});if(u)t.headers=u;return Object.keys(t).length>0?t:void 0}function w(e){let o=e.trim();if(!o||o.includes("{location}"))return;return o}function _(e){try{return new URL(e).pathname.split("/").some((t)=>/^v\d+(?:beta\d*)?$/.test(t))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(e)}}function E(e){let o=P("GOOGLE_APPLICATION_CREDENTIALS",e);return o?{keyFilename:o}:void 0}function L(e){let o=e?.apiKey?.trim();if(!o||o===O||A(o))return;return o}function A(e){return/^<[^>]+>$/.test(e)}function U(e){let o=e?.project||P("GOOGLE_CLOUD_PROJECT",e?.env)||P("GCLOUD_PROJECT",e?.env);if(!o)throw Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return o}function D(e){let o=e?.location||P("GOOGLE_CLOUD_LOCATION",e?.env);if(!o)throw Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return o}function K(e,o,t={}){let i=br(e,o),u=pe(o.messages),n=ne(o.messages),c={};if(t.temperature!==void 0)c.temperature=t.temperature;if(t.maxTokens!==void 0)c.maxOutputTokens=t.maxTokens;let g=xr(e.id),h=n.length>0?wr(n,t.toolChoice,g):void 0,m=u?N(u):"",p={...Object.keys(c).length>0&&c,...m&&{systemInstruction:y(m)},...n.length>0&&{tools:Sr(n,!1,g)},...h!==void 0&&{toolConfig:{functionCallingConfig:{mode:h}}}};if(t.thinking?.enabled&&e.reasoning){let f={includeThoughts:!0};if(t.thinking.level!==void 0)f.thinkingLevel=Kt(t.thinking.level);else if(t.thinking.budgetTokens!==void 0)f.thinkingBudget=t.thinking.budgetTokens;p.thinkingConfig=f}else if(e.reasoning&&t.thinking&&!t.thinking.enabled)p.thinkingConfig=gr(e);if(t.signal){if(t.signal.aborted)throw Error("Request aborted");p.abortSignal=t.signal}return{model:e.id,contents:i,config:p}}function B(e,o,t){if(t?.[o]!==void 0)return t[o];if(e.id.includes("2.5-pro"))return{minimal:128,low:2048,medium:8192,high:32768}[o];if(e.id.includes("2.5-flash"))return{minimal:128,low:2048,medium:8192,high:24576}[o];return-1}export{C as stream,ue as streamSimple};
2
+ import{fr,kt,zt,jt,Vt,Kt,gr,yr,Rt,br,Sr,wr,xr,vr,_r}from"./chunk-yyy2yp6f.js";import{P}from"./chunk-c4qr1f41.js";import{ee}from"./chunk-tvm4zmgj.js";import{q,V}from"./chunk-ypqjfv3a.js";import{K}from"./chunk-e6c2mzxc.js";import{y}from"./chunk-3k627vf2.js";import{ge}from"./chunk-2ks2tnac.js";import{U,de,oe,Oe,Q,G}from"./chunk-0d51ggzj.js";import{M}from"./chunk-jp5afrwm.js";var b="v1",O="gcp-vertex-credentials",R=0,C=(e,o,t)=>{let i=new M,u=Oe(o);return(async()=>{let n={role:"assistant",content:[],api:"google-vertex",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(t?.fetch&&t.fetch!==globalThis.fetch)throw Error("Custom fetch is not supported by the Google Vertex adapter");let c=L(t),g=c?S(e,c,t?.headers):I(e,D(t),N(t),t?.headers,t?.env),h=j(e,u,t),m=await t?.onPayload?.(h,e);if(m!==void 0)h=m;let p=await _r(()=>g.models.generateContentStream(h),t);i.push({type:"start",partial:n});let r=null,f=n.content,l=()=>f.length-1;for await(let s of p){await t?.onProviderStreamEvent?.(s,e),n.responseId||=s.responseId;let k=s.candidates?.[0];if(k?.content?.parts)for(let a of k.content.parts){if(a.text!==void 0){let d=yr(a);if(!r||d&&r.type!=="thinking"||!d&&r.type!=="text"){if(r)if(r.type==="text")i.push({type:"text_end",contentIndex:f.length-1,content:r.text,partial:n});else i.push({type:"thinking_end",contentIndex:l(),content:r.thinking,partial:n});if(d)r={type:"thinking",thinking:"",thinkingSignature:void 0},n.content.push(r),i.push({type:"thinking_start",contentIndex:l(),partial:n});else r={type:"text",text:""},n.content.push(r),i.push({type:"text_start",contentIndex:l(),partial:n})}if(r.type==="thinking")r.thinking+=a.text,r.thinkingSignature=Rt(r.thinkingSignature,a.thoughtSignature),i.push({type:"thinking_delta",contentIndex:l(),delta:a.text,partial:n});else r.text+=a.text,r.textSignature=Rt(r.textSignature,a.thoughtSignature),i.push({type:"text_delta",contentIndex:l(),delta:a.text,partial:n})}if(a.functionCall){if(r){if(r.type==="text")i.push({type:"text_end",contentIndex:l(),content:r.text,partial:n});else i.push({type:"thinking_end",contentIndex:l(),content:r.thinking,partial:n});r=null}let d=a.functionCall.id,x={type:"toolCall",id:!d||n.content.some((T)=>T.type==="toolCall"&&T.id===d)?`${a.functionCall.name}_${Date.now()}_${++R}`:d,name:a.functionCall.name||"",arguments:a.functionCall.args??{},...a.thoughtSignature&&{thoughtSignature:a.thoughtSignature}};n.content.push(x),i.push({type:"toolcall_start",contentIndex:l(),partial:n}),i.push({type:"toolcall_delta",contentIndex:l(),delta:JSON.stringify(x.arguments),partial:n}),i.push({type:"toolcall_end",contentIndex:l(),toolCall:x,partial:n})}}if(k?.finishReason){if(n.rawStopReason=k.finishReason,n.stopReason=vr(k.finishReason),n.content.some((a)=>a.type==="toolCall")&&n.stopReason==="stop")n.stopReason="toolUse"}if(s.usageMetadata)n.usage={input:(s.usageMetadata.promptTokenCount||0)-(s.usageMetadata.cachedContentTokenCount||0),output:(s.usageMetadata.candidatesTokenCount||0)+(s.usageMetadata.thoughtsTokenCount||0),cacheRead:s.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:s.usageMetadata.thoughtsTokenCount||0,totalTokens:s.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},Q(e,n.usage)}if(r)if(r.type==="text")i.push({type:"text_end",contentIndex:l(),content:r.text,partial:n});else i.push({type:"thinking_end",contentIndex:l(),content:r.thinking,partial:n});if(t?.signal?.aborted)throw Error("Request was aborted");if(n.stopReason==="pending")throw Error("Google Vertex stream ended without a finish reason");if(n.stopReason==="aborted"||n.stopReason==="error"){let s=n.rawStopReason?`Provider stopped with: ${n.rawStopReason}`:"An unknown error occurred";throw Error(s)}i.push({type:"done",reason:n.stopReason,message:n}),i.end()}catch(c){for(let g of n.content)if("index"in g)delete g.index;n.stopReason=t?.signal?.aborted?"aborted":"error",n.errorMessage=V(q(c)),i.push({type:"error",reason:n.stopReason,error:n}),i.end()}})(),i},ue=(e,o,t)=>{let i={...K(e,o,t,void 0),toolChoice:t?.toolChoice};if(!t?.reasoning)return C(e,o,{...i,thinking:{enabled:!1}});let u=G(e,t.reasoning);if(u==="off")return C(e,o,{...i,thinking:{enabled:!1}});let n=zt(e,u);if(jt(e))return C(e,o,{...i,thinking:{enabled:!0,level:Vt(n)}});return C(e,o,{...i,thinking:{enabled:!0,budgetTokens:B(e,n,t.thinkingBudgets)}})};function I(e,o,t,i,u){let n=E(u);return new kt({vertexai:!0,project:o,location:t,apiVersion:b,...n?{googleAuthOptions:n}:{},httpOptions:v(e,i)})}function S(e,o,t){return new kt({vertexai:!0,apiKey:o,apiVersion:b,httpOptions:v(e,t)})}function v(e,o){let t={},i=w(e.baseUrl);if(i){if(t.baseUrl=i,t.baseUrlResourceScope=fr.COLLECTION,_(i))t.apiVersion=""}let u=ge({"User-Agent":ee(),...e.headers,...o});if(u)t.headers=u;return Object.keys(t).length>0?t:void 0}function w(e){let o=e.trim();if(!o||o.includes("{location}"))return;return o}function _(e){try{return new URL(e).pathname.split("/").some((t)=>/^v\d+(?:beta\d*)?$/.test(t))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(e)}}function E(e){let o=P("GOOGLE_APPLICATION_CREDENTIALS",e);return o?{keyFilename:o}:void 0}function L(e){let o=e?.apiKey?.trim();if(!o||o===O||A(o))return;return o}function A(e){return/^<[^>]+>$/.test(e)}function D(e){let o=e?.project||P("GOOGLE_CLOUD_PROJECT",e?.env)||P("GCLOUD_PROJECT",e?.env);if(!o)throw Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return o}function N(e){let o=e?.location||P("GOOGLE_CLOUD_LOCATION",e?.env);if(!o)throw Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return o}function j(e,o,t={}){let i=br(e,o),u=de(o.messages),n=oe(o.messages),c={};if(t.temperature!==void 0)c.temperature=t.temperature;if(t.maxTokens!==void 0)c.maxOutputTokens=t.maxTokens;let g=wr(e.id),h=n.length>0?xr(n,t.toolChoice,g):void 0,m=u?U(u):"",p={...Object.keys(c).length>0&&c,...m&&{systemInstruction:y(m)},...n.length>0&&{tools:Sr(n,!1,g)},...h!==void 0&&{toolConfig:{functionCallingConfig:{mode:h}}}};if(t.thinking?.enabled&&e.reasoning){let f={includeThoughts:!0};if(t.thinking.level!==void 0)f.thinkingLevel=Kt(t.thinking.level);else if(t.thinking.budgetTokens!==void 0)f.thinkingBudget=t.thinking.budgetTokens;p.thinkingConfig=f}else if(e.reasoning&&t.thinking&&!t.thinking.enabled)p.thinkingConfig=gr(e);if(t.signal){if(t.signal.aborted)throw Error("Request aborted");p.abortSignal=t.signal}return{model:e.id,contents:i,config:p}}function B(e,o,t){if(t?.[o]!==void 0)return t[o];if(e.id.includes("2.5-pro"))return{minimal:128,low:2048,medium:8192,high:32768}[o];if(e.id.includes("2.5-flash"))return{minimal:128,low:2048,medium:8192,high:24576}[o];return-1}export{C as stream,ue as streamSimple};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{J,H}from"./chunk-c7rcw9fb.js";import{r,p}from"./chunk-bwawt15q.js";var Be=r(function(me){var{hasOwn:Q}=J(),{streamCollector:ne}=J();me.streamCollector=ne;var{buildQueryString:G,HttpResponse:X}=H(),A=p("https"),{Readable:se}=p("stream"),O=p("http2");function U(e){let t=e&&typeof e==="object"&&"reason"in e?e.reason:void 0;if(t){if(t instanceof Error){let s=Error("Request aborted");return s.name="AbortError",s.cause=t,s}let n=Error(String(t));return n.name="AbortError",n}let o=Error("Request aborted");return o.name="AbortError",o}var re=["ECONNRESET","EPIPE","ETIMEDOUT"],Y=(e)=>{let t={};for(let o in e){if(!Q(e,o))continue;let n=e[o];t[o]=Array.isArray(n)?n.join(","):n}return t},l={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)},B=1000,ie=(e,t,o=0)=>{if(!o)return-1;let n=(s)=>{let c=l.setTimeout(()=>{e.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${o} ms.`),{name:"TimeoutError"}))},o-s),a=(u)=>{if(u?.connecting)u.on("connect",()=>{l.clearTimeout(c)});else l.clearTimeout(c)};if(e.socket)a(e.socket);else e.on("socket",a)};if(o<2000)return n(0),0;return l.setTimeout(n.bind(null,B),B)},ce=(e,t,o=0,n,s)=>{if(o)return l.setTimeout(()=>{let c=`@smithy/node-http-handler - [${n?"ERROR":"WARN"}] a request has exceeded the configured ${o} ms requestTimeout.`;if(n){let a=Object.assign(Error(c),{name:"TimeoutError",code:"ETIMEDOUT"});e.destroy(a),t(a)}else c+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",s?.warn?.(c)},o);return-1},ae=3000,ue=(e,{keepAlive:t,keepAliveMsecs:o},n=ae)=>{if(t!==!0)return-1;let s=()=>{if(e.socket)e.socket.setKeepAlive(t,o||0);else e.on("socket",(c)=>{c.setKeepAlive(t,o||0)})};if(n===0)return s(),0;return l.setTimeout(s,n)},W=3000,fe=(e,t,o=0)=>{let n=(s)=>{let c=o-s,a=()=>{e.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${o} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(e.socket)e.socket.setTimeout(c,a),e.on("close",()=>e.socket?.removeListener("timeout",a));else e.setTimeout(c,a)};if(0<o&&o<6000)return n(0),0;return l.setTimeout(n.bind(null,o===0?0:W),W)},z=6000;async function Z(e,t,o=z,n=!1){let s=t.headers,c=s?s.Expect||s.expect:void 0,a=-1,u=!0;if(!n&&c==="100-continue")u=await Promise.race([new Promise((f)=>{a=Number(l.setTimeout(()=>f(!0),Math.max(z,o)))}),new Promise((f)=>{e.on("continue",()=>{l.clearTimeout(a),f(!0)}),e.on("response",()=>{l.clearTimeout(a),f(!1)}),e.on("error",()=>{l.clearTimeout(a),f(!1)})})]);if(u)de(e,t.body)}function de(e,t){if(t instanceof se){t.pipe(e);return}if(t){let o=Buffer.isBuffer(t);if(o||typeof t==="string"){if(o&&t.byteLength===0)e.end();else e.end(t);return}let s=t;if(typeof s==="object"&&s.buffer&&typeof s.byteOffset==="number"&&typeof s.byteLength==="number"){e.end(Buffer.from(s.buffer,s.byteOffset,s.byteLength));return}e.end(Buffer.from(t));return}e.end()}var he=0,M=void 0,V=void 0;class N{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(e){if(typeof e?.handle==="function")return e;return new N(e)}static checkSocketUsage(e,t,o=console){let{sockets:n,requests:s,maxSockets:c}=e;if(typeof c!=="number"||c===1/0)return t;let a=15000;if(Date.now()-a<t)return t;if(n&&s)for(let u in n){if(!Q(n,u))continue;let f=n[u]?.length??0,m=s[u]?.length??0;if(f>=c&&m>=2*c)return o?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${f} and ${m} additional requests are enqueued.
2
+ import{J,H}from"./chunk-adys4qq4.js";import{r,p}from"./chunk-bwawt15q.js";var Fe=r(function(me){var{hasOwn:Q}=J(),{streamCollector:ne}=J();me.streamCollector=ne;var{buildQueryString:G,HttpResponse:X}=H(),A=p("https"),{Readable:se}=p("stream"),O=p("http2");function U(e){let t=e&&typeof e==="object"&&"reason"in e?e.reason:void 0;if(t){if(t instanceof Error){let s=Error("Request aborted");return s.name="AbortError",s.cause=t,s}let n=Error(String(t));return n.name="AbortError",n}let o=Error("Request aborted");return o.name="AbortError",o}var re=["ECONNRESET","EPIPE","ETIMEDOUT"],Y=(e)=>{let t={};for(let o in e){if(!Q(e,o))continue;let n=e[o];t[o]=Array.isArray(n)?n.join(","):n}return t},l={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)},B=1000,ie=(e,t,o=0)=>{if(!o)return-1;let n=(s)=>{let c=l.setTimeout(()=>{e.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${o} ms.`),{name:"TimeoutError"}))},o-s),a=(u)=>{if(u?.connecting)u.on("connect",()=>{l.clearTimeout(c)});else l.clearTimeout(c)};if(e.socket)a(e.socket);else e.on("socket",a)};if(o<2000)return n(0),0;return l.setTimeout(n.bind(null,B),B)},ce=(e,t,o=0,n,s)=>{if(o)return l.setTimeout(()=>{let c=`@smithy/node-http-handler - [${n?"ERROR":"WARN"}] a request has exceeded the configured ${o} ms requestTimeout.`;if(n){let a=Object.assign(Error(c),{name:"TimeoutError",code:"ETIMEDOUT"});e.destroy(a),t(a)}else c+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",s?.warn?.(c)},o);return-1},ae=3000,ue=(e,{keepAlive:t,keepAliveMsecs:o},n=ae)=>{if(t!==!0)return-1;let s=()=>{if(e.socket)e.socket.setKeepAlive(t,o||0);else e.on("socket",(c)=>{c.setKeepAlive(t,o||0)})};if(n===0)return s(),0;return l.setTimeout(s,n)},W=3000,fe=(e,t,o=0)=>{let n=(s)=>{let c=o-s,a=()=>{e.destroy(),t(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${o} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(e.socket)e.socket.setTimeout(c,a),e.on("close",()=>e.socket?.removeListener("timeout",a));else e.setTimeout(c,a)};if(0<o&&o<6000)return n(0),0;return l.setTimeout(n.bind(null,o===0?0:W),W)},z=6000;async function Z(e,t,o=z,n=!1){let s=t.headers,c=s?s.Expect||s.expect:void 0,a=-1,u=!0;if(!n&&c==="100-continue")u=await Promise.race([new Promise((f)=>{a=Number(l.setTimeout(()=>f(!0),Math.max(z,o)))}),new Promise((f)=>{e.on("continue",()=>{l.clearTimeout(a),f(!0)}),e.on("response",()=>{l.clearTimeout(a),f(!1)}),e.on("error",()=>{l.clearTimeout(a),f(!1)})})]);if(u)de(e,t.body)}function de(e,t){if(t instanceof se){t.pipe(e);return}if(t){let o=Buffer.isBuffer(t);if(o||typeof t==="string"){if(o&&t.byteLength===0)e.end();else e.end(t);return}let s=t;if(typeof s==="object"&&s.buffer&&typeof s.byteOffset==="number"&&typeof s.byteLength==="number"){e.end(Buffer.from(s.buffer,s.byteOffset,s.byteLength));return}e.end(Buffer.from(t));return}e.end()}var he=0,M=void 0,V=void 0;class N{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(e){if(typeof e?.handle==="function")return e;return new N(e)}static checkSocketUsage(e,t,o=console){let{sockets:n,requests:s,maxSockets:c}=e;if(typeof c!=="number"||c===1/0)return t;let a=15000;if(Date.now()-a<t)return t;if(n&&s)for(let u in n){if(!Q(n,u))continue;let f=n[u]?.length??0,m=s[u]?.length??0;if(f>=c&&m>=2*c)return o?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${f} and ${m} additional requests are enqueued.
3
3
  See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
4
4
  or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return t}constructor(e){this.configProvider=new Promise((t,o)=>{if(typeof e==="function")e().then((n)=>{t(this.resolveDefaultConfig(n))}).catch(o);else t(this.resolveDefaultConfig(e))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(e,{abortSignal:t,requestTimeout:o}={}){if(!this.config)this.config=await this.configProvider;let n=this.config,s=n.logger,c=e.protocol==="https:";if(!c&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((a,u)=>{let f=void 0,m=-1,g=-1,w=-1,v=-1,C=-1,_=()=>{l.clearTimeout(m),l.clearTimeout(g),l.clearTimeout(w),l.clearTimeout(v),l.clearTimeout(C)},q=async(i)=>{await f,_(),a(i)},E=async(i)=>{await f,_(),u(i)};if(t?.aborted){let i=U(t);E(i);return}let D=e.headers,I=D?(D.Expect??D.expect)==="100-continue":!1,P=c?n.httpsAgent:n.httpAgent;if(I&&!this.externalAgent)P=new(c?A.Agent:M)({keepAlive:!1,maxSockets:1/0});m=l.setTimeout(()=>{this.socketWarningTimestamp=N.checkSocketUsage(P,this.socketWarningTimestamp,s)},n.socketAcquisitionWarningTimeout??(n.requestTimeout??2000)+(n.connectionTimeout??1000));let L=e.query?G(e.query):"",b=void 0;if(e.username!=null||e.password!=null){let i=e.username??"",d=e.password??"";b=`${i}:${d}`}let k=e.path;if(L)k+=`?${L}`;if(e.fragment)k+=`#${e.fragment}`;let y=e.hostname??"";if(y[0]==="["&&y.endsWith("]"))y=e.hostname.slice(1,-1);else y=e.hostname;let S={headers:e.headers,host:y,method:e.method,path:k,port:e.port,agent:P,auth:b},T=(c?A.request:V)(S,(i)=>{let d=new X({statusCode:i.statusCode||-1,reason:i.statusMessage,headers:Y(i.headers),body:i});q({response:d})});if(T.on("error",(i)=>{if(re.includes(i.code))E(Object.assign(i,{name:"TimeoutError"}));else E(i)}),t){let i=()=>{T.destroy();let d=U(t);E(d)};if(typeof t.addEventListener==="function"){let d=t;d.addEventListener("abort",i,{once:!0}),T.once("close",()=>d.removeEventListener("abort",i))}else t.onabort=i}let R=o??n.requestTimeout;g=ie(T,E,n.connectionTimeout),w=ce(T,E,R,n.throwOnRequestTimeout,s??console),v=fe(T,E,n.socketTimeout);let h=S.agent;if(typeof h==="object"&&"keepAlive"in h)C=ue(T,{keepAlive:h.keepAlive,keepAliveMsecs:h.keepAliveMsecs});f=Z(T,e,R,this.externalAgent).catch((i)=>(_(),u(i)))})}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then((o)=>{if(e===Symbol.for("logger"))return{...o,logger:o.logger??t};return{...o,[e]:t}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(e){let{requestTimeout:t,connectionTimeout:o,socketTimeout:n,socketAcquisitionWarningTimeout:s,httpAgent:c,httpsAgent:a,throwOnRequestTimeout:u,logger:f}=e||{},m=!0,g=50;return{connectionTimeout:o,requestTimeout:t,socketTimeout:n,socketAcquisitionWarningTimeout:s,throwOnRequestTimeout:u,httpAgentProvider:async()=>{let w=p("http"),{Agent:v,request:C}=w.default??w;if(V=C,M=v,c instanceof M||typeof c?.destroy==="function")return this.externalAgent=!0,c;return new M({keepAlive:!0,maxSockets:50,...c})},httpsAgent:(()=>{if(a instanceof A.Agent||typeof a?.destroy==="function")return this.externalAgent=!0,a;return new A.Agent({keepAlive:!0,maxSockets:50,...a})})(),logger:f}}}var le=new Uint16Array(1);class F{id=le[0]++;total=0;max=0;session;refs=0;constructor(e){e.unref(),this.session=e}retain(){if(this.session.destroyed)throw Error("@smithy/node-http-handler - cannot acquire reference to destroyed session.");this.refs+=1,this.total+=1,this.max=Math.max(this.refs,this.max),this.session.ref()}free(){if(this.session.destroyed)return;if(this.refs-=1,this.refs===0)this.session.unref();if(this.refs<0)throw Error("@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.")}deref(){return this.session}close(){if(!this.session.closed)this.session.close()}destroy(){if(this.refs=0,!this.session.destroyed)this.session.setTimeout(0),this.session.destroy()}useCount(){return this.refs}}class ee{sessions=[];maxConcurrency=0;constructor(e){this.sessions=(e??[]).map((t)=>new F(t))}poll(){let e=!1;for(let t of this.sessions){if(t.deref().destroyed){e=!0;continue}if(!this.maxConcurrency||t.useCount()<this.maxConcurrency)return t}if(e){for(let t of this.sessions)if(t.deref().destroyed)this.remove(t)}}offerLast(e){this.sessions.push(e)}remove(e){let t=this.sessions.indexOf(e);if(t>-1)this.sessions.splice(t,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(e){this.maxConcurrency=e}destroy(e){this.remove(e),e.destroy()}}class te{config;connectOptions;connectionPools=new Map;constructor(e){if(this.config=e,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(e,t){let o=this.getUrlString(e),n=this.getPool(o);if(!this.config.disableConcurrency&&!t.isEventStream){let f=n.poll();if(f)return f.retain(),f}let s=new F(this.connect(o)),c=s.deref();if(this.config.maxConcurrency)c.settings({maxConcurrentStreams:this.config.maxConcurrency},(f)=>{if(f)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+e.destination.toString())});let a=()=>{this.removeFromPoolAndClose(o,s)},u=()=>{this.removeFromPoolAndCheckedDestroy(o,s)};if(c.on("goaway",a),c.on("error",u),c.on("frameError",u),c.on("close",u),t.requestTimeout)c.setTimeout(t.requestTimeout,u);return n.offerLast(s),s.retain(),s}release(e,t){t.free()}createIsolatedSession(e,t){let o=this.getUrlString(e),n=new F(this.connect(o)),s=n.deref();s.settings({maxConcurrentStreams:1});let c=()=>{n.destroy()};s.on("error",c),s.on("frameError",c),s.on("close",c);let a=t.requestTimeout??300000;return s.setTimeout(a,c),n.retain(),n}destroy(){for(let[e,t]of this.connectionPools){for(let o of[...t])o.destroy();this.connectionPools.delete(e)}}setMaxConcurrentStreams(e){if(e&&e<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=e;for(let t of this.connectionPools.values())t.setMaxConcurrency(e)}setDisableConcurrentStreams(e){this.config.disableConcurrency=e}setNodeHttp2ConnectOptions(e){this.connectOptions=e}debug(){let e={};for(let[t,o]of this.connectionPools){let n=[];for(let s of o)n.push({id:s.id,active:s.useCount(),maxConcurrent:s.max,totalRequests:s.total});e[t]={sessions:n}}return e}removeFromPoolAndClose(e,t){this.connectionPools.get(e)?.remove(t),t.close()}removeFromPoolAndCheckedDestroy(e,t){this.connectionPools.get(e)?.remove(t),t.destroy()}getPool(e){if(!this.connectionPools.has(e)){let t=new ee;if(this.config.maxConcurrency)t.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(e,t)}return this.connectionPools.get(e)}getUrlString(e){return e.destination.toString()}connect(e){return this.connectOptions===void 0?O.connect(e):O.connect(e,this.connectOptions)}}var{constants:K}=O;class j{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new te({});static create(e){if(typeof e?.handle==="function")return e;return new j(e)}constructor(e){this.configProvider=new Promise((t,o)=>{if(typeof e==="function")e().then((n)=>{t(n||{})}).catch(o);else t(e||{})})}destroy(){this.connectionManager.destroy()}async handle(e,{abortSignal:t,requestTimeout:o,isEventStream:n}={}){if(!this.config){this.config=await this.configProvider;let{disableConcurrentStreams:f,maxConcurrentStreams:m,nodeHttp2ConnectOptions:g}=this.config;if(this.connectionManager.setDisableConcurrentStreams(f??!1),m)this.connectionManager.setMaxConcurrentStreams(m);if(g)this.connectionManager.setNodeHttp2ConnectOptions(g)}let{requestTimeout:s,disableConcurrentStreams:c}=this.config,a=c||n,u=o??s;return new Promise((f,m)=>{let g=!1,w=void 0,v=async(i)=>{await w,f(i)},C=async(i)=>{await w,m(i)};if(t?.aborted){g=!0;let i=U(t);C(i);return}let{hostname:_,method:q,port:E,protocol:D,query:I}=e,P="";if(e.username!=null||e.password!=null){let i=e.username??"",d=e.password??"";P=`${i}:${d}@`}let L=`${D}//${P}${_}${E?`:${E}`:""}`,b={destination:new URL(L)},k={requestTimeout:this.config?.sessionTimeout,isEventStream:n},y=a?this.connectionManager.createIsolatedSession(b,k):this.connectionManager.lease(b,k),S=y.deref(),x=(i)=>{if(a)y.destroy();g=!0,C(i)},T=I?G(I):"",R=e.path;if(T)R+=`?${T}`;if(e.fragment)R+=`#${e.fragment}`;let h=S.request({...e.headers,[K.HTTP2_HEADER_PATH]:R,[K.HTTP2_HEADER_METHOD]:q});if(u)h.setTimeout(u,()=>{h.close();let i=Error(`Stream timed out because of no activity for ${u} ms`);i.name="TimeoutError",x(i)});if(t){let i=()=>{h.close();let d=U(t);x(d)};if(typeof t.addEventListener==="function"){let d=t;d.addEventListener("abort",i,{once:!0}),h.once("close",()=>d.removeEventListener("abort",i))}else t.onabort=i}h.on("frameError",(i,d,oe)=>{x(Error(`Frame type id ${i} in stream id ${oe} has failed with code ${d}.`))}),h.on("error",x),h.on("aborted",()=>{x(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${h.rstCode}.`))}),h.on("response",(i)=>{let d=new X({statusCode:i[":status"]??-1,headers:Y(i),body:h});if(g=!0,v({response:d}),a)S.close(),h.on("end",()=>{y.destroy()})}),h.on("close",()=>{if(a)y.destroy();else this.connectionManager.release(b,y);if(!g){let i=Error("Unexpected error: http2 request did not get a response");if(S.destroyed)i.name="TimeoutError";x(i)}}),w=Z(h,e,u)})}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then((o)=>({...o,[e]:t}))}httpHandlerConfigs(){return this.config??{}}}me.DEFAULT_REQUEST_TIMEOUT=he;me.NodeHttp2Handler=j;me.NodeHttpHandler=N});
5
- export{Be};
5
+ export{Fe};