@bkm016/basalt 0.1.4 → 0.1.5

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 (287) hide show
  1. package/README.md +53 -5
  2. package/{chunk-y648fzx0.js → chunk-0039s4jt.js} +3 -3
  3. package/{chunk-m40gxwq4.js → chunk-00gwse5r.js} +3 -3
  4. package/{chunk-t6zs4kw0.js → chunk-0fwdxd45.js} +2 -2
  5. package/{chunk-nmca5h6m.js → chunk-0j0qggej.js} +1 -1
  6. package/chunk-0n99m9m4.js +2 -0
  7. package/{chunk-pjyn2s97.js → chunk-0stvywr8.js} +1 -1
  8. package/{chunk-ztsjgssj.js → chunk-1xa7d5mh.js} +1 -1
  9. package/chunk-2nb3d92s.js +2 -0
  10. package/chunk-2nkfxhef.js +3868 -0
  11. package/chunk-2pa1z37c.js +2 -0
  12. package/{chunk-fw2bpqmw.js → chunk-2qcpq99g.js} +1 -1
  13. package/{chunk-981f9dw8.js → chunk-36cqq0ga.js} +6 -6
  14. package/{chunk-whvj83b7.js → chunk-3c330qna.js} +2 -2
  15. package/chunk-3k627vf2.js +3 -0
  16. package/{chunk-r7fpkb49.js → chunk-3k7ejpkc.js} +1 -1
  17. package/chunk-4g5f43ea.js +3 -0
  18. package/{chunk-fjtvjrkg.js → chunk-539ekagy.js} +4 -4
  19. package/{chunk-97rzj7f6.js → chunk-5v4g21rw.js} +1 -1
  20. package/{chunk-r0scgfwx.js → chunk-6dsq0fns.js} +2 -2
  21. package/{chunk-pbcy6zdt.js → chunk-7as47pcw.js} +1 -1
  22. package/{chunk-g2t6t8fk.js → chunk-7jezts2n.js} +2 -2
  23. package/{chunk-8wc8qdx8.js → chunk-7qq99360.js} +6 -6
  24. package/{chunk-9rmqgc3c.js → chunk-7tgqhveh.js} +15 -15
  25. package/{chunk-mvfsxdx6.js → chunk-7w0mefgk.js} +10 -10
  26. package/{chunk-y58ygzn9.js → chunk-818nd6s1.js} +3 -3
  27. package/{chunk-vv7fp27r.js → chunk-8mezk0cb.js} +2 -2
  28. package/{chunk-q7t30zz2.js → chunk-8xb636vr.js} +5 -5
  29. package/{chunk-ev6yvy5y.js → chunk-980drajf.js} +15 -15
  30. package/{chunk-3x94302m.js → chunk-9z7sdh5e.js} +3 -3
  31. package/{chunk-zggzfa7j.js → chunk-a4b75ekk.js} +2 -2
  32. package/{chunk-2zp1mv3q.js → chunk-ar3dbfp9.js} +1 -1
  33. package/{chunk-vk1gxk1t.js → chunk-aw65h276.js} +1 -1
  34. package/{chunk-f3xadvab.js → chunk-b9fqretv.js} +2 -2
  35. package/{chunk-7tbya5b5.js → chunk-bgkegf0k.js} +22 -22
  36. package/{chunk-0y7ne3d0.js → chunk-bwawt15q.js} +2 -2
  37. package/{chunk-pxsrqrd0.js → chunk-c4qr1f41.js} +2 -2
  38. package/chunk-dddsrff6.js +478 -0
  39. package/{chunk-xfvvh1s5.js → chunk-e63c1186.js} +1 -1
  40. package/{chunk-em187cy3.js → chunk-ebzkckyw.js} +2 -2
  41. package/chunk-eegztdzb.js +2 -0
  42. package/{chunk-rmj5b73e.js → chunk-gw05p4g3.js} +1 -1
  43. package/{chunk-k23t7vhs.js → chunk-h1rypb99.js} +5 -5
  44. package/{chunk-akr0a8nc.js → chunk-hq5ke1yp.js} +1 -1
  45. package/{chunk-jwdb0ccj.js → chunk-jvwg4rn1.js} +3 -3
  46. package/{chunk-7afmgncg.js → chunk-jyrwk08p.js} +1 -1
  47. package/chunk-kns4kv7b.js +3 -0
  48. package/{chunk-8d46jtbj.js → chunk-mat08ab1.js} +2 -2
  49. package/{chunk-jk25nt60.js → chunk-mkp28k1x.js} +2 -2
  50. package/{chunk-3ct2tkr8.js → chunk-npez1492.js} +2 -2
  51. package/{chunk-shadcb9z.js → chunk-nx3jnbv8.js} +2 -2
  52. package/{chunk-ykens1hy.js → chunk-nxkmd29x.js} +1 -1
  53. package/{chunk-y7nma9rk.js → chunk-pjr91g6k.js} +2 -2
  54. package/{chunk-m8vkwdgr.js → chunk-r0jc8e7t.js} +4 -4
  55. package/chunk-rxj6tct8.js +2 -0
  56. package/{chunk-362g64pd.js → chunk-sqaam5ak.js} +1 -1
  57. package/{chunk-4w17tzp5.js → chunk-srjgvdvs.js} +12 -12
  58. package/{chunk-r9aatvwm.js → chunk-stj493dn.js} +2 -2
  59. package/{chunk-k6w6y71k.js → chunk-t7sc0wwc.js} +2 -2
  60. package/{chunk-kp22kaez.js → chunk-v4k3qmdm.js} +2 -2
  61. package/{chunk-1vd0f74z.js → chunk-vt1anydc.js} +4 -4
  62. package/chunk-wd3z74av.js +2 -0
  63. package/{chunk-xh3vr5vz.js → chunk-wfyrfvfn.js} +1 -1
  64. package/{chunk-2hbfk5xd.js → chunk-wnzvnskb.js} +2 -2
  65. package/{chunk-cjc90f84.js → chunk-x89em726.js} +3 -3
  66. package/{chunk-vexrrw1b.js → chunk-xtq1xpq0.js} +2 -2
  67. package/chunk-yna8bwqc.js +2 -0
  68. package/{chunk-aky4tztg.js → chunk-zn0g0859.js} +2 -2
  69. package/{chunk-qe0teyn1.js → chunk-zrkh5dw7.js} +1 -1
  70. package/chunk-zzwjt7fp.js +2 -0
  71. package/compiled.js +12 -12
  72. package/package.json +1 -1
  73. package/ui-test-worker.js +20 -20
  74. package/web/chunk-01hcjafh.js +2 -0
  75. package/web/{chunk-n8sky2q6.js → chunk-07agqp8h.js} +1 -1
  76. package/web/{chunk-hvw3gn2a.js → chunk-0k9aec1s.js} +20 -20
  77. package/web/{chunk-74j07k8k.js → chunk-0p1nmj5n.js} +2 -2
  78. package/web/chunk-0qr891eq.js +70 -0
  79. package/web/{chunk-ts7zrf5b.js → chunk-0whceqes.js} +2 -2
  80. package/web/chunk-0ytga215.js +1 -0
  81. package/web/{chunk-0z0y25zf.js → chunk-12z7d0hp.js} +3 -3
  82. package/web/chunk-14bad871.js +2 -0
  83. package/web/chunk-1amzv4ha.js +1 -0
  84. package/web/chunk-1cfh0e2e.js +324 -0
  85. package/web/chunk-1pasbxwh.js +89 -0
  86. package/web/{chunk-4d3a7xs2.js → chunk-1s2hp6h1.js} +1 -1
  87. package/web/chunk-26bwh1sb.js +169 -0
  88. package/web/{chunk-wnskxerq.js → chunk-2nht58dc.js} +5 -5
  89. package/web/chunk-2y0rc1fe.js +1 -0
  90. package/web/chunk-3hkgdw6f.js +36 -0
  91. package/web/chunk-4a4j030b.js +1 -0
  92. package/web/{chunk-nvhmq4z5.js → chunk-4m3zdd41.js} +6 -6
  93. package/web/chunk-4w298aqs.js +1 -0
  94. package/web/{chunk-t4c8xavd.js → chunk-56krfj3b.js} +7 -7
  95. package/web/{chunk-ds7srg4p.js → chunk-5nda24gv.js} +1 -1
  96. package/web/{chunk-42e3b9hv.js → chunk-5shygfgb.js} +19 -19
  97. package/web/chunk-65nwc4cf.js +1 -0
  98. package/web/chunk-6bwgdvf6.js +1 -0
  99. package/web/chunk-6enn8p66.js +1 -0
  100. package/web/chunk-6stt9d18.js +1 -0
  101. package/web/{chunk-4gavbw65.js → chunk-7a3c137d.js} +1 -1
  102. package/web/chunk-7e47b1sn.js +1 -0
  103. package/web/chunk-7pypx5h8.js +2 -0
  104. package/web/chunk-7znyd1mj.js +39 -0
  105. package/web/{chunk-3re8y26v.js → chunk-892nf39p.js} +7 -7
  106. package/web/chunk-8r0s8tx7.js +1 -0
  107. package/web/chunk-9dy7z3ej.js +2 -0
  108. package/web/chunk-9mq2cdtq.js +1 -0
  109. package/web/chunk-9w5tf22s.js +1 -0
  110. package/web/{chunk-bhsaj6qq.js → chunk-9xgspn75.js} +2 -2
  111. package/web/{chunk-zx8zec24.js → chunk-abhad4zj.js} +56 -56
  112. package/web/chunk-advfpyb9.js +140 -0
  113. package/web/chunk-affear07.js +3 -0
  114. package/web/chunk-ahztazsg.js +1 -0
  115. package/web/chunk-aqt7kc3s.js +106 -0
  116. package/web/chunk-b5hah4mf.js +1 -0
  117. package/web/chunk-b8tfetd8.js +1 -0
  118. package/web/{chunk-9cx1be43.js → chunk-bnb9xhgw.js} +15 -15
  119. package/web/{chunk-n1dmrz44.js → chunk-c01176kn.js} +2 -2
  120. package/web/chunk-c3nn0vvc.js +1 -0
  121. package/web/chunk-c53xmf48.js +30 -0
  122. package/web/chunk-ckgpy4r4.js +1 -0
  123. package/web/chunk-crzseqbx.js +24 -0
  124. package/web/chunk-d22wq71s.js +1 -0
  125. package/web/{chunk-pws2seas.js → chunk-d60dpf69.js} +19 -19
  126. package/web/{chunk-6cnek1xh.js → chunk-d6ddkh6e.js} +1 -1
  127. package/web/{chunk-cg3jterp.js → chunk-d9wdsjkk.js} +2 -2
  128. package/web/{chunk-ttg6tbwx.js → chunk-da7m1kva.js} +2 -2
  129. package/web/chunk-dbnrfxt1.js +8 -0
  130. package/web/chunk-ddxf8e84.js +1 -0
  131. package/web/chunk-dzg1pv80.js +200 -0
  132. package/web/{chunk-yqbnps3a.js → chunk-e8h45nyr.js} +1 -1
  133. package/web/chunk-ej9vb61c.js +1 -0
  134. package/web/chunk-f9k3xrwb.js +2 -0
  135. package/web/{chunk-fh2vj0wv.js → chunk-fjag6yg8.js} +2 -2
  136. package/web/chunk-fnnrrzqa.js +78 -0
  137. package/web/{chunk-n90cqdvg.js → chunk-fv6vm14n.js} +2 -2
  138. package/web/{chunk-b1bgzz66.js → chunk-g5jxwkdh.js} +1 -1
  139. package/web/{chunk-sspfxp5e.js → chunk-g8kkc6vz.js} +1 -1
  140. package/web/chunk-g9sqbafw.js +2 -0
  141. package/web/{chunk-0h0vb6gt.js → chunk-gcv91974.js} +4 -4
  142. package/web/{chunk-sfg2wkhe.js → chunk-gxqaa4sv.js} +7 -7
  143. package/web/chunk-gxsb5tx3.js +1 -0
  144. package/web/{chunk-54thej0t.js → chunk-gyp6v7jd.js} +2 -2
  145. package/web/chunk-h0c42zy3.js +1 -0
  146. package/web/chunk-h2ag4kvz.js +2 -0
  147. package/web/{chunk-kmr7r9xj.js → chunk-h6gh63xj.js} +2 -2
  148. package/web/{chunk-6m69hczt.js → chunk-h6k1x096.js} +2 -2
  149. package/web/{chunk-24mfx6w1.js → chunk-j1bw5v1g.js} +2 -2
  150. package/web/chunk-j34q5jn6.js +1 -0
  151. package/web/{chunk-0pbjgdgp.js → chunk-ja7w629n.js} +2 -2
  152. package/web/{chunk-zbj1trar.js → chunk-jam45rqg.js} +2 -2
  153. package/web/{chunk-f4tacm06.js → chunk-jcdw85mv.js} +1 -1
  154. package/web/chunk-jfvxxp5c.js +1 -0
  155. package/web/chunk-jg6fmz2d.js +1 -0
  156. package/web/{chunk-92ssjk2y.js → chunk-k67v6dyg.js} +40 -40
  157. package/web/chunk-ka7c5rhx.js +99 -0
  158. package/web/{chunk-df5zx17h.js → chunk-kza0t0gj.js} +1 -1
  159. package/web/{chunk-0b47eyrf.js → chunk-m8knte9z.js} +1 -1
  160. package/web/{chunk-v5cnt7c8.js → chunk-mnzramhc.js} +1 -1
  161. package/web/{chunk-a408enpy.js → chunk-mpfgr049.js} +1 -1
  162. package/web/chunk-mz1dabxh.js +1 -0
  163. package/web/chunk-mz9b5bsa.js +1 -0
  164. package/web/chunk-p53n0hwr.js +1 -0
  165. package/web/chunk-paywgcf7.js +40 -0
  166. package/web/chunk-pfcnr9tw.js +1 -0
  167. package/web/chunk-pyg1mr80.js +303 -0
  168. package/web/chunk-q7xkscc5.js +1 -0
  169. package/web/{chunk-xzp7jf7e.js → chunk-qcge7d6s.js} +2 -2
  170. package/web/chunk-qmbgb79a.js +1139 -0
  171. package/web/{chunk-pjkdrgm0.js → chunk-qq5gh5zr.js} +1 -1
  172. package/web/chunk-qrdh9j62.js +1 -0
  173. package/web/{chunk-9t5dnjaz.js → chunk-s24qs1bn.js} +9 -9
  174. package/web/chunk-sd22cnjy.js +1 -0
  175. package/web/{chunk-ydtrc1ay.js → chunk-sd3cdqcm.js} +2 -2
  176. package/web/{chunk-rykfak98.js → chunk-sf101c23.js} +2 -2
  177. package/web/{chunk-1gbd61z0.js → chunk-sfq6cw45.js} +2 -2
  178. package/web/chunk-svqj4az8.js +1 -0
  179. package/web/chunk-t7jwyvvr.js +1 -0
  180. package/web/{chunk-rvrf0f3h.js → chunk-tcp77cp2.js} +2 -2
  181. package/web/chunk-tf18d2dk.css +1 -0
  182. package/web/chunk-thbqwq6b.js +1 -0
  183. package/web/chunk-v0g4cqc1.js +4 -0
  184. package/web/chunk-vhzys0rr.js +292 -0
  185. package/web/chunk-vnt34mkb.js +1 -0
  186. package/web/chunk-vqfz99ff.js +1 -0
  187. package/web/chunk-vttgyb5v.js +2 -0
  188. package/web/chunk-x7sb3bwf.js +370 -0
  189. package/web/chunk-xce8n339.js +1 -0
  190. package/web/{chunk-kwccs9f6.js → chunk-xk1t58c4.js} +12 -12
  191. package/web/chunk-xsrvw7dt.js +4 -0
  192. package/web/chunk-xtss82z2.js +1 -0
  193. package/web/{chunk-2j4m0bh1.js → chunk-y7jq61nv.js} +2 -2
  194. package/web/{chunk-1eg9sbbt.js → chunk-ybw6vgf6.js} +2 -2
  195. package/web/{chunk-ybrf9mhz.js → chunk-yvgs6bm3.js} +4 -4
  196. package/web/{chunk-b53bfkys.js → chunk-z4aj066q.js} +1 -1
  197. package/web/chunk-zazs8p6c.js +1 -0
  198. package/web/{chunk-aqfpnhmt.js → chunk-zc1mk10n.js} +19 -19
  199. package/web/{chunk-d11v5s7w.js → chunk-zqht0jzx.js} +6 -6
  200. package/web/{chunk-pz9ps2jm.js → chunk-zz397b0v.js} +12 -12
  201. package/web/index.html +1 -1
  202. package/worker.js +1 -1
  203. package/chunk-06hdzq5n.js +0 -2
  204. package/chunk-5dfbezv9.js +0 -2
  205. package/chunk-5x1sankd.js +0 -3753
  206. package/chunk-71h08f4g.js +0 -2
  207. package/chunk-7nzhdrv9.js +0 -2
  208. package/chunk-7q51n619.js +0 -2
  209. package/chunk-9mmz6wt3.js +0 -2
  210. package/chunk-bpw6q7g0.js +0 -3
  211. package/chunk-fvn32nzj.js +0 -478
  212. package/chunk-n6e43rvk.js +0 -3
  213. package/chunk-ry0z4ev6.js +0 -2
  214. package/chunk-vkpvcxjr.js +0 -2
  215. package/web/chunk-0rmkpsgp.js +0 -1
  216. package/web/chunk-0s80zw00.js +0 -1
  217. package/web/chunk-0xkyryrq.js +0 -1
  218. package/web/chunk-2s0bmrkv.js +0 -39
  219. package/web/chunk-2z1rwr28.js +0 -2
  220. package/web/chunk-344bq59c.js +0 -89
  221. package/web/chunk-3t0211rw.js +0 -1
  222. package/web/chunk-44rmrmcn.js +0 -1
  223. package/web/chunk-4bzqrwr0.js +0 -1139
  224. package/web/chunk-4jmazh6x.js +0 -370
  225. package/web/chunk-4re74xwm.js +0 -140
  226. package/web/chunk-4rm1vy7w.js +0 -1
  227. package/web/chunk-59kqahb3.js +0 -1
  228. package/web/chunk-5qtyq3ce.js +0 -292
  229. package/web/chunk-5z4jcqct.js +0 -200
  230. package/web/chunk-5z6x2n5h.js +0 -1
  231. package/web/chunk-6beqrmtq.js +0 -1
  232. package/web/chunk-6f5ke0x9.js +0 -1
  233. package/web/chunk-6xaqxcq8.js +0 -1
  234. package/web/chunk-7q6wvv2x.js +0 -1
  235. package/web/chunk-7qsa4p8h.js +0 -1
  236. package/web/chunk-8nja0ygy.js +0 -1
  237. package/web/chunk-8y64fkpz.js +0 -24
  238. package/web/chunk-9ad7v7bm.js +0 -8
  239. package/web/chunk-9dzxv335.js +0 -4
  240. package/web/chunk-a497tykb.js +0 -70
  241. package/web/chunk-b6k9w215.js +0 -2
  242. package/web/chunk-cjfssg3m.js +0 -2
  243. package/web/chunk-cqp1d4p0.js +0 -1
  244. package/web/chunk-dy2gm1fs.js +0 -1
  245. package/web/chunk-e0zre35a.js +0 -1
  246. package/web/chunk-e9twvs9n.js +0 -3
  247. package/web/chunk-f2kgtyfp.js +0 -1
  248. package/web/chunk-f8bn5tzf.js +0 -1
  249. package/web/chunk-f91wzwtk.js +0 -1
  250. package/web/chunk-fdp9bsj7.js +0 -1
  251. package/web/chunk-g1ev11wx.js +0 -1
  252. package/web/chunk-gmzqdm7v.js +0 -1
  253. package/web/chunk-hfaffkrh.js +0 -1
  254. package/web/chunk-j2vt8c8v.js +0 -1
  255. package/web/chunk-ka3q31t1.js +0 -1
  256. package/web/chunk-khxcn8tt.js +0 -106
  257. package/web/chunk-kqqmp1am.js +0 -1
  258. package/web/chunk-m2d1sp30.js +0 -1
  259. package/web/chunk-nbgqbxcy.js +0 -1
  260. package/web/chunk-ncpnpe9w.js +0 -99
  261. package/web/chunk-ne0v8mfb.js +0 -2
  262. package/web/chunk-ngx2cp8x.js +0 -2
  263. package/web/chunk-nxcgf7ec.js +0 -1
  264. package/web/chunk-p0kvmf28.js +0 -2
  265. package/web/chunk-p3k7m5nr.js +0 -1
  266. package/web/chunk-pggaffrh.js +0 -169
  267. package/web/chunk-pxe3vna4.js +0 -1
  268. package/web/chunk-qh15dxav.css +0 -1
  269. package/web/chunk-qpmbxhh6.js +0 -1
  270. package/web/chunk-r0rctnxz.js +0 -1
  271. package/web/chunk-rn3dnqm8.js +0 -1
  272. package/web/chunk-rtf2zzzv.js +0 -1
  273. package/web/chunk-srrfphes.js +0 -1
  274. package/web/chunk-tdr6x2xc.js +0 -1
  275. package/web/chunk-tncvg1nn.js +0 -1
  276. package/web/chunk-vyp0ns1f.js +0 -2
  277. package/web/chunk-wvdehm9y.js +0 -303
  278. package/web/chunk-x7ahcpj7.js +0 -1
  279. package/web/chunk-y38bf0wm.js +0 -1
  280. package/web/chunk-y56aaba5.js +0 -2
  281. package/web/chunk-ye58t45p.js +0 -4
  282. package/web/chunk-z1h20s8c.js +0 -78
  283. package/web/chunk-zj4q9jth.js +0 -36
  284. package/web/chunk-zj5k94dk.js +0 -40
  285. package/web/chunk-zqch0sc8.js +0 -30
  286. package/web/install.ps1 +0 -91
  287. package/web/install.sh +0 -177
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{b,B}from"./chunk-981f9dw8.js";import{i}from"./chunk-0y7ne3d0.js";var I=i(b());var h=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.AccessKeyId==="string"&&typeof e.SecretAccessKey==="string"&&typeof e.Token==="string"&&typeof e.Expiration==="string",C=(e)=>({accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretAccessKey,sessionToken:e.Token,expiration:new Date(e.Expiration),...e.AccountId&&{accountId:e.AccountId}});var v=({maxRetries:e=0,timeout:t=1000})=>({maxRetries:e,timeout:t});var g=i(b());import y from"http";function _(e){return new Promise((t,n)=>{let o=y.request({method:"GET",...e,hostname:e.hostname?.replace(/^\[(.+)\]$/,"$1")});o.on("error",(r)=>{n(Object.assign(new g.ProviderError("Unable to connect to instance metadata service"),r)),o.destroy()}),o.on("timeout",()=>{n(new g.ProviderError("TimeoutError from instance metadata service")),o.destroy()}),o.on("response",(r)=>{let{statusCode:a=400}=r;if(a<200||300<=a)n(Object.assign(new g.ProviderError("Error response received from instance metadata service"),{statusCode:a})),o.destroy();let m=[];r.on("data",(s)=>{m.push(s)}),r.on("end",()=>{t(Buffer.concat(m)),o.destroy()})}),o.end()})}var A=(e,t)=>{let n=e();for(let o=0;o<t;o++)n=n.catch(e);return n};var S="AWS_CONTAINER_CREDENTIALS_FULL_URI",O="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",w="AWS_CONTAINER_AUTHORIZATION_TOKEN",Y=(e={})=>{let{timeout:t,maxRetries:n}=v(e);return()=>A(async()=>{let o=await Z({logger:e.logger}),r=JSON.parse(await j(t,o));if(!h(r))throw new I.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:e.logger});return C(r)},n)},j=async(e,t)=>{if(process.env[w])t.headers={...t.headers,Authorization:process.env[w]};return(await _({...t,timeout:e})).toString()},J="169.254.170.2",X=new Set(["localhost","127.0.0.1"]),z=new Set(["http:","https:"]),Z=async({logger:e})=>{if(process.env[O])return{hostname:J,path:process.env[O]};if(process.env[S]){let t;try{t=new URL(process.env[S])}catch{throw new I.CredentialsProviderError(`${process.env[S]} is not a valid container metadata service URL`,{tryNextLink:!1,logger:e})}if(!t.hostname||!X.has(t.hostname))throw new I.CredentialsProviderError(`${t.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:e});if(!t.protocol||!z.has(t.protocol))throw new I.CredentialsProviderError(`${t.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:e});return{protocol:t.protocol,hostname:t.hostname,path:t.pathname+t.search,port:t.port?parseInt(t.port,10):void 0}}throw new I.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${O} or ${S} environment variable is set`,{tryNextLink:!1,logger:e})};var N=i(b());var P=i(b());class D extends P.CredentialsProviderError{tryNextLink;name="InstanceMetadataV1FallbackError";constructor(e,t=!0){super(e,t);this.tryNextLink=t,Object.setPrototypeOf(this,D.prototype)}}var M=i(b()),V=i(B());var u;(function(e){e.IPv4="http://169.254.169.254",e.IPv6="http://[fd00:ec2::254]"})(u||(u={}));var L={environmentVariableSelector:(e)=>e.AWS_EC2_METADATA_SERVICE_ENDPOINT,configFileSelector:(e)=>e.ec2_metadata_service_endpoint,default:void 0};var p;(function(e){e.IPv4="IPv4",e.IPv6="IPv6"})(p||(p={}));var Q="AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",ee="ec2_metadata_service_endpoint_mode",F={environmentVariableSelector:(e)=>e[Q],configFileSelector:(e)=>e[ee],default:p.IPv4};var k=async()=>V.parseUrl(await te()||await oe()),te=async()=>M.loadConfig(L)(),oe=async()=>{let e=await M.loadConfig(F)();switch(e){case p.IPv4:return u.IPv4;case p.IPv6:return u.IPv6;default:throw Error(`Unsupported endpoint mode: ${e}. Select from ${Object.values(p)}`)}};var x=(e,t)=>{let n=300+Math.floor(Math.random()*300),o=new Date(Date.now()+n*1000);t.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(o)}.
3
- For more information, please visit: https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html`);let r=e.originalExpiration??e.expiration;return{...e,...r?{originalExpiration:r}:{},expiration:o}};var U=(e,t={})=>{let n=t?.logger||console,o;return async()=>{let r;try{if(r=await e(),r.expiration&&r.expiration.getTime()<Date.now())r=x(r,n)}catch(a){if(o)n.warn("Credential renew failed: ",a),r=x(o,n);else throw a}return o=r,r}};var G="/latest/meta-data/iam/security-credentials/",re="/latest/api/token",R="AWS_EC2_METADATA_V1_DISABLED",W="ec2_metadata_v1_disabled",K="x-aws-ec2-metadata-token",ne=(e={})=>U(ae(e),{logger:e.logger}),ae=(e={})=>{let t=!1,{logger:n,profile:o}=e,{timeout:r,maxRetries:a}=v(e),m=async(s,f)=>{if(t||f.headers?.[K]==null){let c=!1,d=!1,q=await N.loadConfig({environmentVariableSelector:(l)=>{let E=l[R];if(d=!!E&&E!=="false",E===void 0)throw new N.CredentialsProviderError(`${R} not set in env, checking config file next.`,{logger:e.logger});return d},configFileSelector:(l)=>{let E=l[W];return c=!!E&&E!=="false",c},default:!1},{profile:o})();if(e.ec2MetadataV1Disabled||q){let l=[];if(e.ec2MetadataV1Disabled)l.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");if(c)l.push(`config file profile (${W})`);if(d)l.push(`process environment variable (${R})`);throw new D(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${l.join(", ")}].`)}}let H=(await A(async()=>{let c;try{c=await ie(f)}catch(d){if(d.statusCode===401)t=!1;throw d}return c},s)).trim();return A(async()=>{let c;try{c=await ce(H,f,e)}catch(d){if(d.statusCode===401)t=!1;throw d}return c},s)};return async()=>{let s=await k();if(t)return n?.debug("AWS SDK Instance Metadata","using v1 fallback (no token fetch)"),m(a,{...s,timeout:r});else{let f;try{f=(await se({...s,timeout:r})).toString()}catch(T){if(T?.statusCode===400)throw Object.assign(T,{message:"EC2 Metadata token request returned error"});else if(T.message==="TimeoutError"||[403,404,405].includes(T.statusCode))t=!0;return n?.debug("AWS SDK Instance Metadata","using v1 fallback (initial)"),m(a,{...s,timeout:r})}return m(a,{...s,headers:{[K]:f},timeout:r})}}},se=async(e)=>_({...e,path:re,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"21600"}}),ie=async(e)=>(await _({...e,path:G})).toString(),ce=async(e,t,n)=>{let o=JSON.parse((await _({...t,path:G+e})).toString());if(!h(o))throw new N.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:n.logger});return C(o)};export{S as ENV_CMDS_FULL_URI,O as ENV_CMDS_RELATIVE_URI,Y as fromContainerMetadata,ne as fromInstanceMetadata};
2
+ import{b,H}from"./chunk-36cqq0ga.js";import{i}from"./chunk-bwawt15q.js";var I=i(b());var h=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.AccessKeyId==="string"&&typeof e.SecretAccessKey==="string"&&typeof e.Token==="string"&&typeof e.Expiration==="string",C=(e)=>({accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretAccessKey,sessionToken:e.Token,expiration:new Date(e.Expiration),...e.AccountId&&{accountId:e.AccountId}});var v=({maxRetries:e=0,timeout:t=1000})=>({maxRetries:e,timeout:t});var g=i(b());import y from"http";function _(e){return new Promise((t,n)=>{let o=y.request({method:"GET",...e,hostname:e.hostname?.replace(/^\[(.+)\]$/,"$1")});o.on("error",(r)=>{n(Object.assign(new g.ProviderError("Unable to connect to instance metadata service"),r)),o.destroy()}),o.on("timeout",()=>{n(new g.ProviderError("TimeoutError from instance metadata service")),o.destroy()}),o.on("response",(r)=>{let{statusCode:a=400}=r;if(a<200||300<=a)n(Object.assign(new g.ProviderError("Error response received from instance metadata service"),{statusCode:a})),o.destroy();let m=[];r.on("data",(s)=>{m.push(s)}),r.on("end",()=>{t(Buffer.concat(m)),o.destroy()})}),o.end()})}var A=(e,t)=>{let n=e();for(let o=0;o<t;o++)n=n.catch(e);return n};var S="AWS_CONTAINER_CREDENTIALS_FULL_URI",O="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",w="AWS_CONTAINER_AUTHORIZATION_TOKEN",Y=(e={})=>{let{timeout:t,maxRetries:n}=v(e);return()=>A(async()=>{let o=await Z({logger:e.logger}),r=JSON.parse(await j(t,o));if(!h(r))throw new I.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:e.logger});return C(r)},n)},j=async(e,t)=>{if(process.env[w])t.headers={...t.headers,Authorization:process.env[w]};return(await _({...t,timeout:e})).toString()},J="169.254.170.2",X=new Set(["localhost","127.0.0.1"]),z=new Set(["http:","https:"]),Z=async({logger:e})=>{if(process.env[O])return{hostname:J,path:process.env[O]};if(process.env[S]){let t;try{t=new URL(process.env[S])}catch{throw new I.CredentialsProviderError(`${process.env[S]} is not a valid container metadata service URL`,{tryNextLink:!1,logger:e})}if(!t.hostname||!X.has(t.hostname))throw new I.CredentialsProviderError(`${t.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:e});if(!t.protocol||!z.has(t.protocol))throw new I.CredentialsProviderError(`${t.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:e});return{protocol:t.protocol,hostname:t.hostname,path:t.pathname+t.search,port:t.port?parseInt(t.port,10):void 0}}throw new I.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${O} or ${S} environment variable is set`,{tryNextLink:!1,logger:e})};var N=i(b());var P=i(b());class D extends P.CredentialsProviderError{tryNextLink;name="InstanceMetadataV1FallbackError";constructor(e,t=!0){super(e,t);this.tryNextLink=t,Object.setPrototypeOf(this,D.prototype)}}var M=i(b()),V=i(H());var u;(function(e){e.IPv4="http://169.254.169.254",e.IPv6="http://[fd00:ec2::254]"})(u||(u={}));var L={environmentVariableSelector:(e)=>e.AWS_EC2_METADATA_SERVICE_ENDPOINT,configFileSelector:(e)=>e.ec2_metadata_service_endpoint,default:void 0};var p;(function(e){e.IPv4="IPv4",e.IPv6="IPv6"})(p||(p={}));var Q="AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",ee="ec2_metadata_service_endpoint_mode",F={environmentVariableSelector:(e)=>e[Q],configFileSelector:(e)=>e[ee],default:p.IPv4};var k=async()=>V.parseUrl(await te()||await oe()),te=async()=>M.loadConfig(L)(),oe=async()=>{let e=await M.loadConfig(F)();switch(e){case p.IPv4:return u.IPv4;case p.IPv6:return u.IPv6;default:throw Error(`Unsupported endpoint mode: ${e}. Select from ${Object.values(p)}`)}};var x=(e,t)=>{let n=300+Math.floor(Math.random()*300),o=new Date(Date.now()+n*1000);t.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(o)}.
3
+ For more information, please visit: https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html`);let r=e.originalExpiration??e.expiration;return{...e,...r?{originalExpiration:r}:{},expiration:o}};var U=(e,t={})=>{let n=t?.logger||console,o;return async()=>{let r;try{if(r=await e(),r.expiration&&r.expiration.getTime()<Date.now())r=x(r,n)}catch(a){if(o)n.warn("Credential renew failed: ",a),r=x(o,n);else throw a}return o=r,r}};var B="/latest/meta-data/iam/security-credentials/",re="/latest/api/token",R="AWS_EC2_METADATA_V1_DISABLED",W="ec2_metadata_v1_disabled",K="x-aws-ec2-metadata-token",ne=(e={})=>U(ae(e),{logger:e.logger}),ae=(e={})=>{let t=!1,{logger:n,profile:o}=e,{timeout:r,maxRetries:a}=v(e),m=async(s,f)=>{if(t||f.headers?.[K]==null){let c=!1,d=!1,q=await N.loadConfig({environmentVariableSelector:(l)=>{let E=l[R];if(d=!!E&&E!=="false",E===void 0)throw new N.CredentialsProviderError(`${R} not set in env, checking config file next.`,{logger:e.logger});return d},configFileSelector:(l)=>{let E=l[W];return c=!!E&&E!=="false",c},default:!1},{profile:o})();if(e.ec2MetadataV1Disabled||q){let l=[];if(e.ec2MetadataV1Disabled)l.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");if(c)l.push(`config file profile (${W})`);if(d)l.push(`process environment variable (${R})`);throw new D(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${l.join(", ")}].`)}}let G=(await A(async()=>{let c;try{c=await ie(f)}catch(d){if(d.statusCode===401)t=!1;throw d}return c},s)).trim();return A(async()=>{let c;try{c=await ce(G,f,e)}catch(d){if(d.statusCode===401)t=!1;throw d}return c},s)};return async()=>{let s=await k();if(t)return n?.debug("AWS SDK Instance Metadata","using v1 fallback (no token fetch)"),m(a,{...s,timeout:r});else{let f;try{f=(await se({...s,timeout:r})).toString()}catch(T){if(T?.statusCode===400)throw Object.assign(T,{message:"EC2 Metadata token request returned error"});else if(T.message==="TimeoutError"||[403,404,405].includes(T.statusCode))t=!0;return n?.debug("AWS SDK Instance Metadata","using v1 fallback (initial)"),m(a,{...s,timeout:r})}return m(a,{...s,headers:{[K]:f},timeout:r})}}},se=async(e)=>_({...e,path:re,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"21600"}}),ie=async(e)=>(await _({...e,path:B})).toString(),ce=async(e,t,n)=>{let o=JSON.parse((await _({...t,path:B+e})).toString());if(!h(o))throw new N.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:n.logger});return C(o)};export{S as ENV_CMDS_FULL_URI,O as ENV_CMDS_RELATIVE_URI,Y as fromContainerMetadata,ne as fromInstanceMetadata};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{i,r}from"./chunk-0y7ne3d0.js";var R=r(function(m){Object.defineProperty(m,"__esModule",{value:!0});m.Allow=m.ALL=m.COLLECTION=m.ATOM=m.SPECIAL=m.INF=m._INFINITY=m.INFINITY=m.NAN=m.BOOL=m.NULL=m.OBJ=m.ARR=m.NUM=m.STR=void 0;m.STR=1;m.NUM=2;m.ARR=4;m.OBJ=8;m.NULL=16;m.BOOL=32;m.NAN=64;m.INFINITY=128;m._INFINITY=256;m.INF=m.INFINITY|m._INFINITY;m.SPECIAL=m.NULL|m.BOOL|m.INF|m.NAN;m.ATOM=m.STR|m.NUM|m.SPECIAL;m.COLLECTION=m.ARR|m.OBJ;m.ALL=m.ATOM|m.COLLECTION;m.Allow={STR:m.STR,NUM:m.NUM,ARR:m.ARR,OBJ:m.OBJ,NULL:m.NULL,BOOL:m.BOOL,NAN:m.NAN,INFINITY:m.INFINITY,_INFINITY:m._INFINITY,INF:m.INF,SPECIAL:m.SPECIAL,ATOM:m.ATOM,COLLECTION:m.COLLECTION,ALL:m.ALL};m.default=m.Allow});var W=r(function(o){var G=o&&o.__createBinding||(Object.create?function(t,s,u,e){if(e===void 0)e=u;var c=Object.getOwnPropertyDescriptor(s,u);if(!c||("get"in c?!s.__esModule:c.writable||c.configurable))c={enumerable:!0,get:function(){return s[u]}};Object.defineProperty(t,e,c)}:function(t,s,u,e){if(e===void 0)e=u;t[e]=s[u]}),H=o&&o.__exportStar||function(t,s){for(var u in t)if(u!=="default"&&!Object.prototype.hasOwnProperty.call(s,u))G(s,t,u)};Object.defineProperty(o,"__esModule",{value:!0});o.Allow=o.MalformedJSON=o.PartialJSON=o.parseJSON=o.parse=void 0;var n=R();Object.defineProperty(o,"Allow",{enumerable:!0,get:function(){return n.Allow}});H(R(),o);class B extends Error{}o.PartialJSON=B;class P extends Error{}o.MalformedJSON=P;function v(t,s=n.Allow.ALL){if(typeof t!=="string")throw TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw Error(`${t} is empty`);return K(t.trim(),s)}o.parseJSON=v;var K=(t,s)=>{let u=t.length,e=0,c=(a)=>{throw new B(`${a} at position ${e}`)},p=(a)=>{throw new P(`${a} at position ${e}`)},l=()=>{if(O(),e>=u)c("Unexpected end of input");if(t[e]==='"')return U();if(t[e]==="{")return D();if(t[e]==="[")return q();if(t.substring(e,e+4)==="null"||n.Allow.NULL&s&&u-e<4&&"null".startsWith(t.substring(e)))return e+=4,null;if(t.substring(e,e+4)==="true"||n.Allow.BOOL&s&&u-e<4&&"true".startsWith(t.substring(e)))return e+=4,!0;if(t.substring(e,e+5)==="false"||n.Allow.BOOL&s&&u-e<5&&"false".startsWith(t.substring(e)))return e+=5,!1;if(t.substring(e,e+8)==="Infinity"||n.Allow.INFINITY&s&&u-e<8&&"Infinity".startsWith(t.substring(e)))return e+=8,1/0;if(t.substring(e,e+9)==="-Infinity"||n.Allow._INFINITY&s&&1<u-e&&u-e<9&&"-Infinity".startsWith(t.substring(e)))return e+=9,-1/0;if(t.substring(e,e+3)==="NaN"||n.Allow.NAN&s&&u-e<3&&"NaN".startsWith(t.substring(e)))return e+=3,NaN;return V()},U=()=>{let a=e,f=!1;e++;while(e<u&&(t[e]!=='"'||f&&t[e-1]==="\\"))f=t[e]==="\\"?!f:!1,e++;if(t.charAt(e)=='"')try{return JSON.parse(t.substring(a,++e-Number(f)))}catch(N){p(String(N))}else if(n.Allow.STR&s)try{return JSON.parse(t.substring(a,e-Number(f))+'"')}catch(N){return JSON.parse(t.substring(a,t.lastIndexOf("\\"))+'"')}c("Unterminated string literal")},D=()=>{e++,O();let a={};try{while(t[e]!=="}"){if(O(),e>=u&&n.Allow.OBJ&s)return a;let f=U();O(),e++;try{let N=l();a[f]=N}catch(N){if(n.Allow.OBJ&s)return a;else throw N}if(O(),t[e]===",")e++}}catch(f){if(n.Allow.OBJ&s)return a;else c("Expected '}' at end of object")}return e++,a},q=()=>{e++;let a=[];try{while(t[e]!=="]")if(a.push(l()),O(),t[e]===",")e++}catch(f){if(n.Allow.ARR&s)return a;c("Expected ']' at end of array")}return e++,a},V=()=>{if(e===0){if(t==="-")p("Not sure what '-' is");try{return JSON.parse(t)}catch(f){if(n.Allow.NUM&s)try{return JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch(N){}p(String(f))}}let a=e;if(t[e]==="-")e++;while(t[e]&&",]}".indexOf(t[e])===-1)e++;if(e==u&&!(n.Allow.NUM&s))c("Unterminated number literal");try{return JSON.parse(t.substring(a,e))}catch(f){if(t.substring(a,e)==="-")c("Not sure what '-' is");try{return JSON.parse(t.substring(a,t.lastIndexOf("e")))}catch(N){p(String(N))}}},O=()=>{while(e<u&&`
3
- \r `.includes(t[e]))e++};return l()},Q=v;o.parse=Q});var M=i(W(),1),X=new Set(['"',"\\","/","b","f","n","r","t","u"]);function Z(t){let s=t.codePointAt(0);return s!==void 0&&s>=0&&s<=31}function S(t){switch(t){case"\b":return"\\b";case"\f":return"\\f";case`
4
- `:return"\\n";case"\r":return"\\r";case"\t":return"\\t";default:return`\\u${t.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function Do(t){let s="",u=!1;for(let e=0;e<t.length;e++){let c=t[e];if(!u){if(s+=c,c==='"')u=!0;continue}if(c==='"'){s+=c,u=!1;continue}if(c==="\\"){let p=t[e+1];if(p===void 0){s+="\\\\";continue}if(p==="u"){let l=t.slice(e+2,e+6);if(/^[0-9a-fA-F]{4}$/.test(l)){s+=`\\u${l}`,e+=5;continue}}if(X.has(p)){s+=`\\${p}`,e+=1;continue}s+="\\\\";continue}s+=Z(c)?S(c):c}return s}function zr(t){try{return JSON.parse(t)}catch(s){let u=Do(t);if(u!==t)return JSON.parse(u);throw s}}function F(t){if(!t||t.trim()==="")return{};try{return zr(t)}catch{try{return M.parse(t)??{}}catch{try{return M.parse(Do(t))??{}}catch{return{}}}}}
5
- export{Do,zr,F};
2
+ import{i,r}from"./chunk-bwawt15q.js";var R=r(function(U){Object.defineProperty(U,"__esModule",{value:!0});U.Allow=U.ALL=U.COLLECTION=U.ATOM=U.SPECIAL=U.INF=U._INFINITY=U.INFINITY=U.NAN=U.BOOL=U.NULL=U.OBJ=U.ARR=U.NUM=U.STR=void 0;U.STR=1;U.NUM=2;U.ARR=4;U.OBJ=8;U.NULL=16;U.BOOL=32;U.NAN=64;U.INFINITY=128;U._INFINITY=256;U.INF=U.INFINITY|U._INFINITY;U.SPECIAL=U.NULL|U.BOOL|U.INF|U.NAN;U.ATOM=U.STR|U.NUM|U.SPECIAL;U.COLLECTION=U.ARR|U.OBJ;U.ALL=U.ATOM|U.COLLECTION;U.Allow={STR:U.STR,NUM:U.NUM,ARR:U.ARR,OBJ:U.OBJ,NULL:U.NULL,BOOL:U.BOOL,NAN:U.NAN,INFINITY:U.INFINITY,_INFINITY:U._INFINITY,INF:U.INF,SPECIAL:U.SPECIAL,ATOM:U.ATOM,COLLECTION:U.COLLECTION,ALL:U.ALL};U.default=U.Allow});var v=r(function(o){var G=o&&o.__createBinding||(Object.create?function(t,s,u,e){if(e===void 0)e=u;var c=Object.getOwnPropertyDescriptor(s,u);if(!c||("get"in c?!s.__esModule:c.writable||c.configurable))c={enumerable:!0,get:function(){return s[u]}};Object.defineProperty(t,e,c)}:function(t,s,u,e){if(e===void 0)e=u;t[e]=s[u]}),H=o&&o.__exportStar||function(t,s){for(var u in t)if(u!=="default"&&!Object.prototype.hasOwnProperty.call(s,u))G(s,t,u)};Object.defineProperty(o,"__esModule",{value:!0});o.Allow=o.MalformedJSON=o.PartialJSON=o.parseJSON=o.parse=void 0;var n=R();Object.defineProperty(o,"Allow",{enumerable:!0,get:function(){return n.Allow}});H(R(),o);class B extends Error{}o.PartialJSON=B;class F extends Error{}o.MalformedJSON=F;function Y(t,s=n.Allow.ALL){if(typeof t!=="string")throw TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw Error(`${t} is empty`);return K(t.trim(),s)}o.parseJSON=Y;var K=(t,s)=>{let u=t.length,e=0,c=(a)=>{throw new B(`${a} at position ${e}`)},p=(a)=>{throw new F(`${a} at position ${e}`)},l=()=>{if(O(),e>=u)c("Unexpected end of input");if(t[e]==='"')return M();if(t[e]==="{")return D();if(t[e]==="[")return q();if(t.substring(e,e+4)==="null"||n.Allow.NULL&s&&u-e<4&&"null".startsWith(t.substring(e)))return e+=4,null;if(t.substring(e,e+4)==="true"||n.Allow.BOOL&s&&u-e<4&&"true".startsWith(t.substring(e)))return e+=4,!0;if(t.substring(e,e+5)==="false"||n.Allow.BOOL&s&&u-e<5&&"false".startsWith(t.substring(e)))return e+=5,!1;if(t.substring(e,e+8)==="Infinity"||n.Allow.INFINITY&s&&u-e<8&&"Infinity".startsWith(t.substring(e)))return e+=8,1/0;if(t.substring(e,e+9)==="-Infinity"||n.Allow._INFINITY&s&&1<u-e&&u-e<9&&"-Infinity".startsWith(t.substring(e)))return e+=9,-1/0;if(t.substring(e,e+3)==="NaN"||n.Allow.NAN&s&&u-e<3&&"NaN".startsWith(t.substring(e)))return e+=3,NaN;return V()},M=()=>{let a=e,f=!1;e++;while(e<u&&(t[e]!=='"'||f&&t[e-1]==="\\"))f=t[e]==="\\"?!f:!1,e++;if(t.charAt(e)=='"')try{return JSON.parse(t.substring(a,++e-Number(f)))}catch(N){p(String(N))}else if(n.Allow.STR&s)try{return JSON.parse(t.substring(a,e-Number(f))+'"')}catch(N){return JSON.parse(t.substring(a,t.lastIndexOf("\\"))+'"')}c("Unterminated string literal")},D=()=>{e++,O();let a={};try{while(t[e]!=="}"){if(O(),e>=u&&n.Allow.OBJ&s)return a;let f=M();O(),e++;try{let N=l();a[f]=N}catch(N){if(n.Allow.OBJ&s)return a;else throw N}if(O(),t[e]===",")e++}}catch(f){if(n.Allow.OBJ&s)return a;else c("Expected '}' at end of object")}return e++,a},q=()=>{e++;let a=[];try{while(t[e]!=="]")if(a.push(l()),O(),t[e]===",")e++}catch(f){if(n.Allow.ARR&s)return a;c("Expected ']' at end of array")}return e++,a},V=()=>{if(e===0){if(t==="-")p("Not sure what '-' is");try{return JSON.parse(t)}catch(f){if(n.Allow.NUM&s)try{return JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch(N){}p(String(f))}}let a=e;if(t[e]==="-")e++;while(t[e]&&",]}".indexOf(t[e])===-1)e++;if(e==u&&!(n.Allow.NUM&s))c("Unterminated number literal");try{return JSON.parse(t.substring(a,e))}catch(f){if(t.substring(a,e)==="-")c("Not sure what '-' is");try{return JSON.parse(t.substring(a,t.lastIndexOf("e")))}catch(N){p(String(N))}}},O=()=>{while(e<u&&`
3
+ \r `.includes(t[e]))e++};return l()},Q=Y;o.parse=Q});var P=i(v(),1),X=new Set(['"',"\\","/","b","f","n","r","t","u"]);function Z(t){let s=t.codePointAt(0);return s!==void 0&&s>=0&&s<=31}function S(t){switch(t){case"\b":return"\\b";case"\f":return"\\f";case`
4
+ `:return"\\n";case"\r":return"\\r";case"\t":return"\\t";default:return`\\u${t.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function Bo(t){let s="",u=!1;for(let e=0;e<t.length;e++){let c=t[e];if(!u){if(s+=c,c==='"')u=!0;continue}if(c==='"'){s+=c,u=!1;continue}if(c==="\\"){let p=t[e+1];if(p===void 0){s+="\\\\";continue}if(p==="u"){let l=t.slice(e+2,e+6);if(/^[0-9a-fA-F]{4}$/.test(l)){s+=`\\u${l}`,e+=5;continue}}if(X.has(p)){s+=`\\${p}`,e+=1;continue}s+="\\\\";continue}s+=Z(c)?S(c):c}return s}function jr(t){try{return JSON.parse(t)}catch(s){let u=Bo(t);if(u!==t)return JSON.parse(u);throw s}}function W(t){if(!t||t.trim()==="")return{};try{return jr(t)}catch{try{return P.parse(t)??{}}catch{try{return P.parse(Bo(t))??{}}catch{return{}}}}}
5
+ export{Bo,jr,W};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{kt,zt,jt,Vt,Kt,gr,yr,Rt,br,Sr,xr,wr,vr,_r}from"./chunk-7tgqhveh.js";import{ee}from"./chunk-tvm4zmgj.js";import{q,j}from"./chunk-y69ewdn2.js";import{V}from"./chunk-3c330qna.js";import{y}from"./chunk-3k627vf2.js";import{fe}from"./chunk-x4874m8e.js";import{N,pe,ne,Le,Q,G}from"./chunk-7qq99360.js";import{M}from"./chunk-nx3jnbv8.js";var w=0,C=(n,a,t)=>{let o=new M,g=Le(a);return(async()=>{let e={role:"assistant",content:[],api:"google-generative-ai",provider:n.provider,model:n.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 Generative AI adapter");let l=t?.apiKey;if(!l)throw Error(`No API key for provider: ${n.provider}`);let c=T(n,l,t?.headers),h=S(n,g,t),k=await t?.onPayload?.(h,n);if(k!==void 0)h=k;let p=await _r(()=>c.models.generateContentStream(h),t);o.push({type:"start",partial:e});let i=null,f=e.content,u=()=>f.length-1;for await(let s of p){await t?.onProviderStreamEvent?.(s,n),e.responseId||=s.responseId;let m=s.candidates?.[0];if(m?.content?.parts)for(let r of m.content.parts){if(r.text!==void 0){let d=yr(r);if(!i||d&&i.type!=="thinking"||!d&&i.type!=="text"){if(i)if(i.type==="text")o.push({type:"text_end",contentIndex:f.length-1,content:i.text,partial:e});else o.push({type:"thinking_end",contentIndex:u(),content:i.thinking,partial:e});if(d)i={type:"thinking",thinking:"",thinkingSignature:void 0},e.content.push(i),o.push({type:"thinking_start",contentIndex:u(),partial:e});else i={type:"text",text:""},e.content.push(i),o.push({type:"text_start",contentIndex:u(),partial:e})}if(i.type==="thinking")i.thinking+=r.text,i.thinkingSignature=Rt(i.thinkingSignature,r.thoughtSignature),o.push({type:"thinking_delta",contentIndex:u(),delta:r.text,partial:e});else i.text+=r.text,i.textSignature=Rt(i.textSignature,r.thoughtSignature),o.push({type:"text_delta",contentIndex:u(),delta:r.text,partial:e})}if(r.functionCall){if(i){if(i.type==="text")o.push({type:"text_end",contentIndex:u(),content:i.text,partial:e});else o.push({type:"thinking_end",contentIndex:u(),content:i.thinking,partial:e});i=null}let d=r.functionCall.id,x={type:"toolCall",id:!d||e.content.some((b)=>b.type==="toolCall"&&b.id===d)?`${r.functionCall.name}_${Date.now()}_${++w}`:d,name:r.functionCall.name||"",arguments:r.functionCall.args??{},...r.thoughtSignature&&{thoughtSignature:r.thoughtSignature}};e.content.push(x),o.push({type:"toolcall_start",contentIndex:u(),partial:e}),o.push({type:"toolcall_delta",contentIndex:u(),delta:JSON.stringify(x.arguments),partial:e}),o.push({type:"toolcall_end",contentIndex:u(),toolCall:x,partial:e})}}if(m?.finishReason){if(e.rawStopReason=m.finishReason,e.stopReason=vr(m.finishReason),e.content.some((r)=>r.type==="toolCall")&&e.stopReason==="stop")e.stopReason="toolUse"}if(s.usageMetadata)e.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(n,e.usage)}if(i)if(i.type==="text")o.push({type:"text_end",contentIndex:u(),content:i.text,partial:e});else o.push({type:"thinking_end",contentIndex:u(),content:i.thinking,partial:e});if(t?.signal?.aborted)throw Error("Request was aborted");if(e.stopReason==="pending")throw Error("Google stream ended without a finish reason");if(e.stopReason==="aborted"||e.stopReason==="error"){let s=e.rawStopReason?`Provider stopped with: ${e.rawStopReason}`:"An unknown error occurred";throw Error(s)}o.push({type:"done",reason:e.stopReason,message:e}),o.end()}catch(l){for(let c of e.content)if("index"in c)delete c.index;e.stopReason=t?.signal?.aborted?"aborted":"error",e.errorMessage=j(q(l)),o.push({type:"error",reason:e.stopReason,error:e}),o.end()}})(),o},D=(n,a,t)=>{let o=t?.apiKey;if(!o)throw Error(`No API key for provider: ${n.provider}`);let g={...V(n,a,t,o),toolChoice:t?.toolChoice};if(!t?.reasoning)return C(n,a,{...g,thinking:{enabled:!1}});let e=G(n,t.reasoning);if(e==="off")return C(n,a,{...g,thinking:{enabled:!1}});let l=zt(n,e);if(jt(n))return C(n,a,{...g,thinking:{enabled:!0,level:Vt(l)}});return C(n,a,{...g,thinking:{enabled:!0,budgetTokens:I(n,l,t.thinkingBudgets)}})};function T(n,a,t){let o={};if(n.baseUrl)o.baseUrl=n.baseUrl,o.apiVersion="";let g=fe({"User-Agent":ee(),...n.headers,...t});if(g)o.headers=g;return new kt({apiKey:a,httpOptions:Object.keys(o).length>0?o:void 0})}function S(n,a,t={}){let o=br(n,a),g=pe(a.messages),e=ne(a.messages),l={};if(t.temperature!==void 0)l.temperature=t.temperature;if(t.maxTokens!==void 0)l.maxOutputTokens=t.maxTokens;let c=xr(n.id),h=e.length>0?wr(e,t.toolChoice,c):void 0,k=g?N(g):"",p={...Object.keys(l).length>0&&l,...k&&{systemInstruction:y(k)},...e.length>0&&{tools:Sr(e,!1,c)},...h!==void 0&&{toolConfig:{functionCallingConfig:{mode:h}}}};if(t.thinking?.enabled&&n.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(n.reasoning&&t.thinking&&!t.thinking.enabled)p.thinkingConfig=gr(n);if(t.signal){if(t.signal.aborted)throw Error("Request aborted");p.abortSignal=t.signal}return{model:n.id,contents:o,config:p}}function I(n,a,t){if(t?.[a]!==void 0)return t[a];if(n.id.includes("2.5-pro"))return{minimal:128,low:2048,medium:8192,high:32768}[a];if(n.id.includes("2.5-flash-lite"))return{minimal:512,low:2048,medium:8192,high:24576}[a];if(n.id.includes("2.5-flash"))return{minimal:128,low:2048,medium:8192,high:24576}[a];return-1}export{C as stream,D as streamSimple};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{f}from"./chunk-mvfsxdx6.js";import{ie}from"./chunk-d48bfd2e.js";import{q,j}from"./chunk-y69ewdn2.js";import{g}from"./chunk-n6e43rvk.js";import{z,fe}from"./chunk-x4874m8e.js";var P=async(e,s,t)=>{let a={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:"stop",timestamp:Date.now()};try{let r=t?.apiKey;if(!r)throw Error(`No API key for provider: ${e.provider}`);let c=x(e,r,t?.headers,t?.fetch),n=_(e,s),i=await t?.onPayload?.(n,e);if(i!==void 0)n=i;let o={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:R,response:l}=await ie(()=>c.chat.completions.create(n,o).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:l.status,headers:z(l.headers)},e);let u=R;if(a.responseId=u.id,u.usage)a.usage=k(u.usage,e);let p=u.choices[0];if(p){let m=p.message.content;if(typeof m==="string"&&m.length>0)a.output.push({type:"text",text:m});for(let d of p.message.images??[]){let y=typeof d.image_url==="string"?d.image_url:d.image_url?.url;if(!y?.startsWith("data:"))continue;let h=y.match(/^data:([^;]+);base64,(.+)$/);if(!h)continue;a.output.push({type:"image",mimeType:h[1],data:h[2]})}}return a}catch(r){return a.stopReason=t?.signal?.aborted?"aborted":"error",a.errorMessage=j(q(r)),a}};function x(e,s,t,a){return new f({apiKey:s,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:fe({...e.headers,...t})})}function _(e,s){let t=s.input.map((a)=>{if(a.type==="text")return{type:"text",text:g(a.text)};return{type:"image_url",image_url:{url:`data:${a.mimeType};base64,${a.data}`}}});return{model:e.id,messages:[{role:"user",content:t}],stream:!1,modalities:e.output.includes("text")?["image","text"]:["image"]}}function k(e,s){let t=e.prompt_tokens||0,a=e.prompt_tokens_details?.cached_tokens||0,r=e.prompt_tokens_details?.cache_write_tokens||0,c=r>0?Math.max(0,a-r):a,n=Math.max(0,t-c-r),i=e.completion_tokens||0,o={input:n,output:i,cacheRead:c,cacheWrite:r,totalTokens:n+i+c+r,cost:{input:s.cost.input/1e6*n,output:s.cost.output/1e6*i,cacheRead:s.cost.cacheRead/1e6*c,cacheWrite:s.cost.cacheWrite/1e6*r,total:0}};return o.cost.total=o.cost.input+o.cost.output+o.cost.cacheRead+o.cost.cacheWrite,o}export{P as generateImages};
2
+ import{g}from"./chunk-7w0mefgk.js";import{ie}from"./chunk-d48bfd2e.js";import{q,j}from"./chunk-y69ewdn2.js";import{y}from"./chunk-3k627vf2.js";import{z,fe}from"./chunk-x4874m8e.js";var P=async(e,s,t)=>{let a={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:"stop",timestamp:Date.now()};try{let r=t?.apiKey;if(!r)throw Error(`No API key for provider: ${e.provider}`);let c=x(e,r,t?.headers,t?.fetch),n=_(e,s),i=await t?.onPayload?.(n,e);if(i!==void 0)n=i;let o={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:R,response:l}=await ie(()=>c.chat.completions.create(n,o).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:l.status,headers:z(l.headers)},e);let u=R;if(a.responseId=u.id,u.usage)a.usage=k(u.usage,e);let p=u.choices[0];if(p){let m=p.message.content;if(typeof m==="string"&&m.length>0)a.output.push({type:"text",text:m});for(let d of p.message.images??[]){let f=typeof d.image_url==="string"?d.image_url:d.image_url?.url;if(!f?.startsWith("data:"))continue;let h=f.match(/^data:([^;]+);base64,(.+)$/);if(!h)continue;a.output.push({type:"image",mimeType:h[1],data:h[2]})}}return a}catch(r){return a.stopReason=t?.signal?.aborted?"aborted":"error",a.errorMessage=j(q(r)),a}};function x(e,s,t,a){return new g({apiKey:s,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:a,defaultHeaders:fe({...e.headers,...t})})}function _(e,s){let t=s.input.map((a)=>{if(a.type==="text")return{type:"text",text:y(a.text)};return{type:"image_url",image_url:{url:`data:${a.mimeType};base64,${a.data}`}}});return{model:e.id,messages:[{role:"user",content:t}],stream:!1,modalities:e.output.includes("text")?["image","text"]:["image"]}}function k(e,s){let t=e.prompt_tokens||0,a=e.prompt_tokens_details?.cached_tokens||0,r=e.prompt_tokens_details?.cache_write_tokens||0,c=r>0?Math.max(0,a-r):a,n=Math.max(0,t-c-r),i=e.completion_tokens||0,o={input:n,output:i,cacheRead:c,cacheWrite:r,totalTokens:n+i+c+r,cost:{input:s.cost.input/1e6*n,output:s.cost.output/1e6*i,cacheRead:s.cost.cacheRead/1e6*c,cacheWrite:s.cost.cacheWrite/1e6*r,total:0}};return o.cost.total=o.cost.input+o.cost.output+o.cost.cacheRead+o.cost.cacheWrite,o}export{P as generateImages};
@@ -1,16 +1,16 @@
1
1
  // @bun
2
- import{mo,St,st,x,an,ho}from"./chunk-ry0z4ev6.js";import{n,e,c,Nt,vt,T,le,E,wo,Ir,Ut}from"./chunk-zggzfa7j.js";import*as S from"fs/promises";import*as ne from"fs";import*as M from"path";import*as $e from"child_process";import*as ct from"crypto";import*as lt from"readline";function C(a){if(a.inputSchema.type!=="object")throw Error(`JSON schema for tool "${a.name}" must be an object, but got ${a.inputSchema.type}`);return{type:"custom",name:a.name,input_schema:a.inputSchema,description:a.description,run:a.run,parse:(r)=>r,...a.close?{close:a.close}:{}}}var F=st.promises,J=448,yt=384;function ae(a,r){let t=x.relative(a,r);return t===""||!t.startsWith(".."+x.sep)&&t!==".."&&!x.isAbsolute(t)}async function Ee(a,r){for(let t of a)if(ae(await X(x.resolve(t)),r))return t;return}var wt=40;function Z(a){let r=a?.code;return typeof r==="string"?r:void 0}async function X(a){let r=[],t=a,i=0;for(;;){let o;try{o=await F.realpath(t)}catch(s){let l;try{l=(await F.lstat(t)).isSymbolicLink()}catch(f){let d=Z(f);if(d!=="ENOENT"&&d!=="ENOTDIR")throw f;let m=x.dirname(t);if(m===t)throw f;r.push(x.basename(t)),t=m;continue}if(!l)throw s;if(++i>wt)throw Object.assign(Error("too many levels of symbolic links"),{code:"ELOOP"});t=x.resolve(x.dirname(t),await F.readlink(t));continue}return r.length?x.join(o,...r.reverse()):o}}async function Ae(a,r,t){let i=t?.allowedRoots??[],o=await X(x.resolve(a)),s;try{s=await X(x.resolve(o,r))}catch(f){throw new E(q(f,`path ${JSON.stringify(r)}`))}if(ae(o,s)||await Ee(i,s)!==void 0)return s;let l=i.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new E(`path ${JSON.stringify(r)} is outside ${l}`)}async function be(a,r){let t=x.dirname(a),i=x.join(t,`.tmp-${process.pid}-${St.randomUUID()}`),o=await F.stat(a).then((l)=>l.mode&511,()=>{return}),s;try{if(s=await F.open(i,"wx",yt),o!==void 0)await s.chmod(o);await s.writeFile(r,"utf-8"),await s.sync(),await s.close(),s=void 0,await F.rename(i,a)}catch(l){if(s)await s.close().catch(()=>{});throw await F.unlink(i).catch(()=>{}),l}}function q(a,r){let t=Z(a);switch(t){case"ENOENT":return`${r}: no such file or directory`;case"EACCES":case"EPERM":return`${r}: permission denied`;case"ENOTDIR":return`${r}: not a directory`;case"EISDIR":return`${r}: is a directory`;case"ELOOP":return`${r}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${r}: file name too long`;case"ENOSPC":return`${r}: no space left on device`;case"EMFILE":case"ENFILE":return`${r}: too many open files`;default:return`${r}: ${t!==void 0?`i/o error (${t})`:"i/o error"}`}}var I=st.promises,_t=ho.promisify(mo.execFile);async function gt(a){let{client:r,sessionId:t}=a;if(!r)return async()=>{};let i=T(r),o=a.session;if(!o){if(t===void 0)return async()=>{};i.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),o=await r.beta.sessions.retrieve(t)}let s=x.resolve(a.workdir,"skills"),l=[];for(let f of o.agent.skills)try{let d=await r.beta.skills.versions.retrieve(f.version,{skill_id:f.skill_id}),m=x.basename(d.name.trim());if(m===""||m==="."||m==="..")m=f.skill_id;let h=x.resolve(s,m);if(h!==s&&!h.startsWith(s+x.sep)){i.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:d.name});continue}let u=await r.beta.skills.versions.download(d.id,{skill_id:f.skill_id});await I.rm(h,{recursive:!0,force:!0}),await I.mkdir(h,{recursive:!0,mode:J}),l.push(h),await Ce(u,h),i.info("downloaded skill",{component:"agent-tool-context",skill_id:f.skill_id,version:d.id,dest:h})}catch(d){i.warn("failed to download skill",{component:"agent-tool-context",skill_id:f.skill_id,error:String(d)})}return async()=>{for(let f of l)await I.rm(f,{recursive:!0,force:!0}).catch((d)=>{i.warn("failed to clean up skill",{component:"agent-tool-context",dest:f,error:String(d)})})}}function Et(a){for(let r of a){let t=r.trim();if(!t)continue;if(x.isAbsolute(t)||t.split(/[\\/]/).includes(".."))throw new c(`refusing to extract unsafe archive member: ${t}`)}}var Me="skill archive listing is inconsistent; refusing to extract",bt={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function xe(a){let r=a.split(`
3
- `);if(r[r.length-1]==="")r.pop();return r}function Ot(a,r){return/^[\x20-\x7E]+$/.test(r)&&!/[\\^#]/.test(r)&&!(a==="unzip"&&r.startsWith("-"))}function Mt(a,r,t){let i=xe(r),o=xe(t);if(i.length!==o.length)throw new c(Me);let s=[],l=[];return i.forEach((f,d)=>{if(bt[a].has(o[d].charAt(0))){s.push(f);return}if(!Ot(a,f))throw new c(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(f)}`);l.push(f)}),{plain:s,special:l}}async function De(a){for(let r of await I.readdir(a,{withFileTypes:!0}))if(r.isDirectory())await De(x.join(a,r.name));else if(!r.isFile())throw new c(Me)}async function Oe(a,r){try{let{stdout:t}=await _t(a,r);return t}catch(t){if(Z(t)==="ENOENT")throw new c(`skill extraction requires the \`${a}\` command, but it was not found on PATH`);throw t}}function kt(a){let r,t=!1;for(let i of a){let o=i.trim().split("/").filter((l)=>l!==""&&l!==".");if(o.length===0)continue;let s=o[0];if(r===void 0)r=s;else if(s!==r)return"";if(o.length>1)t=!0}return r!==void 0&&t?r:""}async function Ce(a,r){let t=x.join(r,`.skill-archive-${process.pid}-${Date.now()}`);if(!a.body)throw new c("skill download response had no body");await an.promises.pipeline(an.Readable.fromWeb(a.body),st.createWriteStream(t));let i=x.join(x.dirname(r),`.skill-stage-${process.pid}-${Date.now()}`),o=x.join(x.dirname(r),`.skill-exclude-${process.pid}-${Date.now()}`);try{let s=await Rt(t,4),l=s.length>=4&&s[0]===80&&s[1]===75&&s[2]===3&&s[3]===4,f=l?"unzip":"tar",d=await Oe(f,l?["-Z1",t]:["-tf",t]),m=await Oe(f,l?["-Z","--h","--t",t]:["-tvf",t]),{plain:h,special:u}=Mt(f,d,m);Et([...h,...u]);let _=kt(h);if(await I.mkdir(i,{recursive:!0,mode:J}),h.length>0)await Oe(f,await It(f,t,i,u,o));await De(i);let b=_?x.join(i,_):i,D=await I.readdir(b).catch((v)=>{throw Z(v)==="ENOENT"?new c(Me):v});for(let v of D)await I.rename(x.join(b,v),x.join(r,v))}finally{await I.rm(t,{force:!0}),await I.rm(o,{force:!0}),await I.rm(i,{recursive:!0,force:!0})}}async function It(a,r,t,i,o){let s=i.map((l)=>l.replace(/[*?[\\]/g,"\\$&"));if(a==="unzip")return["-oq",r,"-d",t,...s.length>0?["-x",...s]:[]];if(s.length===0)return["-xf",r,"-C",t];return await I.writeFile(o,s.join(`
2
+ import{go,St,st,x,ln,yo}from"./chunk-eegztdzb.js";import{n,e,c,Nt,vt,T,le,A,Ao,Mr,Ut}from"./chunk-a4b75ekk.js";import*as S from"fs/promises";import*as ne from"fs";import*as O from"path";import*as $e from"child_process";import*as ct from"crypto";import*as lt from"readline";function C(a){if(a.inputSchema.type!=="object")throw Error(`JSON schema for tool "${a.name}" must be an object, but got ${a.inputSchema.type}`);return{type:"custom",name:a.name,input_schema:a.inputSchema,description:a.description,run:a.run,parse:(r)=>r,...a.close?{close:a.close}:{}}}var F=st.promises,J=448,yt=384;function ae(a,r){let t=x.relative(a,r);return t===""||!t.startsWith(".."+x.sep)&&t!==".."&&!x.isAbsolute(t)}async function Ee(a,r){for(let t of a)if(ae(await X(x.resolve(t)),r))return t;return}var wt=40;function Z(a){let r=a?.code;return typeof r==="string"?r:void 0}async function X(a){let r=[],t=a,i=0;for(;;){let o;try{o=await F.realpath(t)}catch(s){let l;try{l=(await F.lstat(t)).isSymbolicLink()}catch(f){let d=Z(f);if(d!=="ENOENT"&&d!=="ENOTDIR")throw f;let m=x.dirname(t);if(m===t)throw f;r.push(x.basename(t)),t=m;continue}if(!l)throw s;if(++i>wt)throw Object.assign(Error("too many levels of symbolic links"),{code:"ELOOP"});t=x.resolve(x.dirname(t),await F.readlink(t));continue}return r.length?x.join(o,...r.reverse()):o}}async function Ae(a,r,t){let i=t?.allowedRoots??[],o=await X(x.resolve(a)),s;try{s=await X(x.resolve(o,r))}catch(f){throw new A(q(f,`path ${JSON.stringify(r)}`))}if(ae(o,s)||await Ee(i,s)!==void 0)return s;let l=i.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new A(`path ${JSON.stringify(r)} is outside ${l}`)}async function be(a,r){let t=x.dirname(a),i=x.join(t,`.tmp-${process.pid}-${St.randomUUID()}`),o=await F.stat(a).then((l)=>l.mode&511,()=>{return}),s;try{if(s=await F.open(i,"wx",yt),o!==void 0)await s.chmod(o);await s.writeFile(r,"utf-8"),await s.sync(),await s.close(),s=void 0,await F.rename(i,a)}catch(l){if(s)await s.close().catch(()=>{});throw await F.unlink(i).catch(()=>{}),l}}function q(a,r){let t=Z(a);switch(t){case"ENOENT":return`${r}: no such file or directory`;case"EACCES":case"EPERM":return`${r}: permission denied`;case"ENOTDIR":return`${r}: not a directory`;case"EISDIR":return`${r}: is a directory`;case"ELOOP":return`${r}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${r}: file name too long`;case"ENOSPC":return`${r}: no space left on device`;case"EMFILE":case"ENFILE":return`${r}: too many open files`;default:return`${r}: ${t!==void 0?`i/o error (${t})`:"i/o error"}`}}var k=st.promises,_t=yo.promisify(go.execFile);async function gt(a){let{client:r,sessionId:t}=a;if(!r)return async()=>{};let i=T(r),o=a.session;if(!o){if(t===void 0)return async()=>{};i.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),o=await r.beta.sessions.retrieve(t)}let s=x.resolve(a.workdir,"skills"),l=[];for(let f of o.agent.skills)try{let d=await r.beta.skills.versions.retrieve(f.version,{skill_id:f.skill_id}),m=x.basename(d.name.trim());if(m===""||m==="."||m==="..")m=f.skill_id;let h=x.resolve(s,m);if(h!==s&&!h.startsWith(s+x.sep)){i.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:d.name});continue}let u=await r.beta.skills.versions.download(d.id,{skill_id:f.skill_id});await k.rm(h,{recursive:!0,force:!0}),await k.mkdir(h,{recursive:!0,mode:J}),l.push(h),await Ce(u,h),i.info("downloaded skill",{component:"agent-tool-context",skill_id:f.skill_id,version:d.id,dest:h})}catch(d){i.warn("failed to download skill",{component:"agent-tool-context",skill_id:f.skill_id,error:String(d)})}return async()=>{for(let f of l)await k.rm(f,{recursive:!0,force:!0}).catch((d)=>{i.warn("failed to clean up skill",{component:"agent-tool-context",dest:f,error:String(d)})})}}function Et(a){for(let r of a){let t=r.trim();if(!t)continue;if(x.isAbsolute(t)||t.split(/[\\/]/).includes(".."))throw new c(`refusing to extract unsafe archive member: ${t}`)}}var Me="skill archive listing is inconsistent; refusing to extract",bt={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function xe(a){let r=a.split(`
3
+ `);if(r[r.length-1]==="")r.pop();return r}function Ot(a,r){return/^[\x20-\x7E]+$/.test(r)&&!/[\\^#]/.test(r)&&!(a==="unzip"&&r.startsWith("-"))}function Mt(a,r,t){let i=xe(r),o=xe(t);if(i.length!==o.length)throw new c(Me);let s=[],l=[];return i.forEach((f,d)=>{if(bt[a].has(o[d].charAt(0))){s.push(f);return}if(!Ot(a,f))throw new c(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(f)}`);l.push(f)}),{plain:s,special:l}}async function De(a){for(let r of await k.readdir(a,{withFileTypes:!0}))if(r.isDirectory())await De(x.join(a,r.name));else if(!r.isFile())throw new c(Me)}async function Oe(a,r){try{let{stdout:t}=await _t(a,r);return t}catch(t){if(Z(t)==="ENOENT")throw new c(`skill extraction requires the \`${a}\` command, but it was not found on PATH`);throw t}}function kt(a){let r,t=!1;for(let i of a){let o=i.trim().split("/").filter((l)=>l!==""&&l!==".");if(o.length===0)continue;let s=o[0];if(r===void 0)r=s;else if(s!==r)return"";if(o.length>1)t=!0}return r!==void 0&&t?r:""}async function Ce(a,r){let t=x.join(r,`.skill-archive-${process.pid}-${Date.now()}`);if(!a.body)throw new c("skill download response had no body");await ln.promises.pipeline(ln.Readable.fromWeb(a.body),st.createWriteStream(t));let i=x.join(x.dirname(r),`.skill-stage-${process.pid}-${Date.now()}`),o=x.join(x.dirname(r),`.skill-exclude-${process.pid}-${Date.now()}`);try{let s=await Rt(t,4),l=s.length>=4&&s[0]===80&&s[1]===75&&s[2]===3&&s[3]===4,f=l?"unzip":"tar",d=await Oe(f,l?["-Z1",t]:["-tf",t]),m=await Oe(f,l?["-Z","--h","--t",t]:["-tvf",t]),{plain:h,special:u}=Mt(f,d,m);Et([...h,...u]);let _=kt(h);if(await k.mkdir(i,{recursive:!0,mode:J}),h.length>0)await Oe(f,await It(f,t,i,u,o));await De(i);let E=_?x.join(i,_):i,D=await k.readdir(E).catch((M)=>{throw Z(M)==="ENOENT"?new c(Me):M});for(let M of D)await k.rename(x.join(E,M),x.join(r,M))}finally{await k.rm(t,{force:!0}),await k.rm(o,{force:!0}),await k.rm(i,{recursive:!0,force:!0})}}async function It(a,r,t,i,o){let s=i.map((l)=>l.replace(/[*?[\\]/g,"\\$&"));if(a==="unzip")return["-oq",r,"-d",t,...s.length>0?["-x",...s]:[]];if(s.length===0)return["-xf",r,"-C",t];return await k.writeFile(o,s.join(`
4
4
  `)+`
5
- `,{flag:"wx",mode:384}),["-xf",r,"-C",t,"-X",o]}async function Rt(a,r){let t=await I.open(a,"r");try{let i=Buffer.alloc(r),{bytesRead:o}=await t.read(i,0,r,0);return i.subarray(0,o)}finally{await t.close()}}var g=st.promises,z=st.constants,Ue=448,Tt=384,Lt=448,ke=z.O_NOFOLLOW??0,$t=z.O_NONBLOCK??0,y=(()=>{class a extends Error{constructor(r,t){super(`path ${JSON.stringify(t)} ${r}`);this.name="FileStoreError",this.reason=r,this.relPath=t}}return a.ESCAPES_ROOT="escapes the store root",a.IS_A_SYMLINK="is a symlink",a.NOT_A_FILE="is not a regular file",a.NOT_A_DIRECTORY="is not a directory",a.NOT_UTF8="is not valid utf-8",a.MOVE_DESTINATION_EXISTS="already exists",a})();function Ie(a){return a.startsWith("/")&&!a.split("/").includes("..")}var ve=(()=>{class a{constructor(r,t,i=!1){this.hashes=new Map,this.rootPath=r,this.removedOnDispose=t,this.decoder=i?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(r,t){if(!At())throw Error("FileStore requires O_NOFOLLOW support on this platform");let i=!1;try{await g.lstat(r)}catch(o){if(o.code!=="ENOENT")throw o;i=!0}return new a(x.resolve(r),i,t?.utf8??!1)}async createRoot(){await xt(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){if(!this.removedOnDispose)return;await g.rm(this.rootPath,{recursive:!0,force:!0})}async put(r,t,i){let o=r.replace(/\\/g,"/");if(o.endsWith("/")||o.endsWith("/.")||o===""||o===".")throw new y(y.NOT_A_FILE,r);let s=this.resolveUnderRoot(r),l=typeof t==="string"?Nt(t):t;this.requireUtf8(r,l),await Fe(this.rootPath,x.dirname(s)),await Dt(s,l,i?.executable??!1)}async get(r){let t=this.resolveUnderRoot(r),i;try{i=await je(r,t)}catch(s){if(s.code==="ENOENT")return null;throw s}let o;try{let s=await i.readFile();o=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}finally{await i.close()}return this.requireUtf8(r,o),o}async ls(r="/"){let t=this.resolveUnderRoot(r);return new Set((await Pe(this.rootPath,r,t)).map(([i])=>i))}async findSymlinks(r="/"){let t=this.resolveUnderRoot(r);return Ft(this.rootPath,r,t)}async hashtree(r="/"){let t=this.resolveUnderRoot(r),i=ce.nowNs(),o=Object.create(null);for(let[s,l]of await Pe(this.rootPath,r,t)){let f=await this.hashViaCache(s,l,i);if(f!==null)o[s]=f}return o}async hashFile(r){let t=this.resolveUnderRoot(r),i;try{i=await g.lstat(t,{bigint:!0})}catch(s){if(s.code==="ENOENT")return null;throw s}if(i.isSymbolicLink())throw new y(y.IS_A_SYMLINK,r);if(!i.isFile())throw new y(y.NOT_A_FILE,r);let o=x.relative(this.rootPath,t).split(x.sep).join("/");return this.hashViaCache(o,t,ce.nowNs())}async move(r,t){let i=this.resolveUnderRoot(r),o=this.resolveUnderRoot(t);if(i===this.rootPath||o===this.rootPath)return;if(await g.stat(o).then(()=>!0,()=>!1))throw new y(y.MOVE_DESTINATION_EXISTS,t);await Fe(this.rootPath,x.dirname(o)),await g.rename(i,o)}async remove(r){let t=this.resolveUnderRoot(r);if(t===this.rootPath)return;let i;try{i=await g.lstat(t,{bigint:!0})}catch(o){if(o.code==="ENOENT")return;throw o}if(i.isDirectory())await g.rm(t,{recursive:!0,force:!0});else try{await g.unlink(t)}catch(o){if(o.code!=="ENOENT")throw o}}resolveUnderRoot(r){let t=r.replace(/\\/g,"/").replace(/^\/+/,""),i=t.split("/").filter((o)=>o!==""&&o!==".");if(x.posix.isAbsolute(t)||i.includes(".."))throw new y(y.ESCAPES_ROOT,r);return i.length===0?this.rootPath:x.join(this.rootPath,...i)}requireUtf8(r,t){if(!this.decoder)return;try{this.decoder.decode(t)}catch{throw new y(y.NOT_UTF8,r)}}async hashViaCache(r,t,i){let o;try{o=await g.lstat(t,{bigint:!0})}catch(f){if(f.code==="ENOENT")return null;throw f}if(!o.isFile())return null;let s=this.hashes.get(r),l;if(s!==void 0&&Wt(s,o))l=s.sha;else try{l=await ce.hashFile(t)}catch(f){let d=f.code;if(d==="ENOENT"||f instanceof y)return null;if(d==="ELOOP"||d==="EMLINK")return null;throw f}if(jt(o,i))this.hashes.set(r,{mtimeNs:o.mtimeNs,ctimeNs:o.ctimeNs,size:o.size,sha:l});return l}}return a.isPathLegal=Ie,a})();function At(){return ke!==0}async function xt(a){let r=[],t=a;for(;;){try{await g.stat(t);break}catch(o){let s=o.code;if(s!=="ENOENT"&&s!=="ENOTDIR"&&s!=="ELOOP")throw o}r.push(t);let i=x.dirname(t);if(i===t)break;t=i}for(let i of r.reverse())try{await g.mkdir(i,{mode:Ue})}catch(o){if(o.code!=="EEXIST")throw o}}async function Fe(a,r){let t=x.relative(a,r);if(t==="")return;let i=a;for(let o of t.split(x.sep)){i=x.join(i,o);try{await g.mkdir(i,{mode:Ue})}catch(s){if(s.code!=="EEXIST")throw s}}}async function Dt(a,r,t){let i=t?Lt:Tt,o=x.join(x.dirname(a),`.fs-${St.randomBytes(8).toString("hex")}.tmp`),s;try{s=await g.open(o,z.O_WRONLY|z.O_CREAT|z.O_EXCL|ke,i),await s.writeFile(r),await s.close(),s=void 0,await g.rename(o,a)}catch(l){if(s)await s.close().catch(()=>{});throw await g.unlink(o).catch(()=>{}),l}}async function je(a,r){let t;try{t=await g.open(r,z.O_RDONLY|ke|$t)}catch(i){let o=i.code;if(o==="ELOOP"||o==="EMLINK")throw new y(y.IS_A_SYMLINK,a);throw i}try{if(!(await t.stat()).isFile())throw new y(y.NOT_A_FILE,a)}catch(i){throw await t.close().catch(()=>{}),i}return t}async function Ct(a){let r=St.createHash("sha256"),t=await je(x.basename(a),a),i=new Uint8Array(1048576);try{for(;;){let{bytesRead:o}=await t.read(i,0,i.length);if(o===0)break;r.update(i.subarray(0,o))}}finally{await t.close()}return r.digest("hex")}async function Pe(a,r,t){if(!await Pt(r,t))return[];let i=[];return await Be(t,(o,s)=>{if(s.isFile())i.push([x.relative(a,o).split(x.sep).join("/"),o])}),i.sort(),i}async function Ft(a,r,t){let i=(l)=>x.relative(a,l).split(x.sep).join("/"),o;try{o=await g.lstat(t,{bigint:!0})}catch(l){let f=l.code;if(f==="ENOENT"||f==="ENOTDIR")return new Set;throw l}if(o.isSymbolicLink())return new Set([i(t)]);if(!o.isDirectory())throw new y(y.NOT_A_DIRECTORY,r);let s=new Set;return await Be(t,(l,f)=>{if(f.isSymbolicLink())s.add(i(l))}),s}async function Pt(a,r){let t;try{t=await g.lstat(r,{bigint:!0})}catch(i){let o=i.code;if(o==="ENOENT"||o==="ENOTDIR")return!1;throw i}if(!t.isDirectory())throw new y(y.NOT_A_DIRECTORY,a);return!0}async function Be(a,r){let t=[a];while(t.length){let i=t.pop(),o;try{o=await g.readdir(i,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){let l=x.join(i,s.name);if(r(l,s),s.isDirectory()&&!s.isSymbolicLink())t.push(l)}}}function Wt(a,r){return r.mtimeNs===a.mtimeNs&&r.ctimeNs===a.ctimeNs&&r.size===a.size}function jt(a,r){return(a.mtimeNs>a.ctimeNs?a.mtimeNs:a.ctimeNs)<r-ce.timestampTrustMarginNs}var Bt=2000000000n,ce={hashFile:Ct,timestampTrustMarginNs:Bt,nowNs:()=>BigInt(Date.now())*1000000n},Ye=ve,We=Symbol.asyncDispose;if(We)Object.defineProperty(ve.prototype,We,{value:ve.prototype.dispose,configurable:!0,writable:!0});var w,N,fe,Q,de,p,G,he,L,qe,me,ze,Ge,Re,Ne,He,Ke,Te,Ve,Xe,ue,pe,Je,Ze,Yt=30000,K=".anthropic-memory-store",et=1;function Qe(a){return St.createHash("sha256").update(`version ${et}
6
- ${a}`,"utf-8").digest("hex")}var qt=30000,zt=100,Gt=20,Ht=16,Kt=32,Vt=8,Xt=50;class P extends c{constructor(a,r){super(a);if(this.name="SessionMemoryError",r!==void 0)this.cause=r}}class tt{constructor(a,r,t){this.mode=a,this.cap=r,this.waiveWindow=t,this.attempted=0,this.capped=0,this.suppressed=0}takeSlot(){if(this.attempted>=this.cap)return this.capped++,!1;return this.attempted++,!0}}var Jt=(()=>{class a{constructor(r,t){w.add(this),N.set(this,void 0),fe.set(this,void 0),Q.set(this,void 0),de.set(this,void 0),p.set(this,void 0),G.set(this,void 0),he.set(this,!1),L.set(this,[]),n(this,N,r,"f"),n(this,fe,t.workdir,"f"),n(this,Q,t.syncIntervalMs??wo,"f"),Ir(e(this,Q,"f"),"syncIntervalMs"),n(this,de,t.syncDeletions??"enabled","f"),n(this,p,T(r),"f"),n(this,G,Date.now(),"f")}get roots(){return e(this,L,"f").map((r)=>r.files.root().path)}get readOnlyRoots(){return e(this,L,"f").filter((r)=>r.readOnly).map((r)=>r.files.root().path)}async download(r){for(let t of r.resources){if(t.type!=="memory_store")continue;let i=e(this,w,"m",qe).call(this,t),o;try{if(o={memoryStoreId:t.memory_store_id,files:await Ye.open(i,{utf8:!0}),readOnly:t.access==="read_only",baseline:new Map,refusedShas:new Map,pendingDeletes:new Map},!o.files.root().removedOnDispose)throw new P(`something already exists at the memory store's path: ${i} (memory_store_id=${t.memory_store_id}); it must not exist when the session starts`);try{await o.files.createRoot()}catch(s){if(!H(s))throw s;throw new P(`cannot create the memory store's folder: ${i} (memory_store_id=${t.memory_store_id}): ${s}; the worker host must make this mount path writable`,s)}await e(this,w,"m",Ne).call(this,o),e(this,p,"f").info("downloaded memories",{count:o.baseline.size,memory_store_id:o.memoryStoreId,dest:o.files.root().path}),e(this,L,"f").push(o)}catch(s){if(o)await o.files.dispose().catch(()=>{});if(s instanceof P)throw s;throw new P(`failed to download memory store memory_store_id=${t.memory_store_id}: ${s}`,s)}}n(this,G,Date.now(),"f")}async finish(){if(e(this,he,"f"))throw new c("finish() was already called: it is the session's last sync and runs once");n(this,he,!0,"f"),await this.syncAll(!0)}async syncAll(r){await Promise.all(e(this,L,"f").map((t)=>e(this,w,"m",ze).call(this,t,r))),n(this,G,Date.now(),"f")}async syncIfDue(){if(Date.now()-e(this,G,"f")<e(this,Q,"f"))return;await this.syncAll(!1)}async flushWrites(r){await Promise.all(e(this,L,"f").map((t)=>e(this,w,"m",Ge).call(this,t,r)))}async dispose(){for(let r of e(this,L,"f")){let t=r.files.root();try{let i=await e(this,w,"m",me).call(this,r);if(!i.markerOk&&Object.keys(i.files).length>0){e(this,p,"f").warn(`${i.distrustReason}; leaving the memory store folder on disk`,{root:t.path,memory_store_id:r.memoryStoreId});continue}await r.files.dispose()}catch(i){if(!(i instanceof y)&&!H(i))throw i;e(this,p,"f").warn("failed to remove the memory store folder",{root:r.files.root().path,memory_store_id:r.memoryStoreId,error:String(i)});continue}if(t.removedOnDispose)e(this,p,"f").info("removed memory store dir",{dest:t.path,memory_store_id:r.memoryStoreId})}}}return N=new WeakMap,fe=new WeakMap,Q=new WeakMap,de=new WeakMap,p=new WeakMap,G=new WeakMap,he=new WeakMap,L=new WeakMap,w=new WeakSet,qe=function(t){if(t.mount_path){if(!Ie(t.mount_path))throw new P(`memory store mount_path is not a clean absolute path: ${JSON.stringify(t.mount_path)} (memory_store_id=${t.memory_store_id})`);return t.mount_path}return x.join(e(this,fe,"f"),"memory",t.name||t.memory_store_id)},me=async function(t){let i=await t.files.hashtree(),o=i[K];if(delete i[K],o===Qe(t.memoryStoreId))return{files:i,markerOk:!0,distrustReason:null};return{files:i,markerOk:!1,distrustReason:o!==void 0?"the marker file does not match this store":"the marker file is gone"}},ze=async function(t,i){try{let o=await e(this,w,"m",me).call(this,t),s=o.files;if(!o.markerOk){if(Object.keys(s).length>0){e(this,p,"f").warn(`${o.distrustReason}; leaving the memory store folder as found and not syncing`,{root:t.files.root().path,memory_store_id:t.memoryStoreId});return}await e(this,w,"m",Re).call(this,t,"the folder or its marker is gone");return}if(Object.keys(s).length===0&&t.baseline.size>1){await e(this,w,"m",Re).call(this,t,"every memory file is gone at once");return}let l=new Map;for await(let[u,_]of e(this,w,"m",ue).call(this,t.memoryStoreId))l.set(u,_);let f=new tt(e(this,de,"f"),Math.max(Vt,Math.min(Xt,Math.floor(t.baseline.size/4))),i),d=[],m=new Map,h=[...new Set([...l.keys(),...Object.keys(s),...t.baseline.keys()])].sort();for(let u of h){let _=l.get(u),b=s[u],D=t.baseline.get(u),v;if(b===void 0&&D!==void 0&&_!==void 0&&_.content_sha256===D&&!t.readOnly)v=await e(this,w,"m",Je).call(this,t,u,_,D,f);else v=await e(this,w,"m",He).call(this,t,u,_,b,d);if(v!==void 0)m.set(u,v)}if(t.baseline=m,await e(this,w,"m",Ve).call(this,t,d),f.suppressed>0)e(this,p,"f").debug("remote deletes are disabled; locally deleted memories stay on the server",{count:f.suppressed,memory_store_id:t.memoryStoreId});if(f.capped>0)e(this,p,"f").warn(`delete cap reached: ${f.mode==="log_only"?"would send":"sent"} ${f.attempted} deletes, held ${f.capped} for later syncs`,{memory_store_id:t.memoryStoreId})}catch(o){e(this,p,"f").warn("memory sync failed",{memory_store_id:t.memoryStoreId,error:String(o)})}},Ge=async function(t,i){let o=new Map,s=new Set,l=async()=>{if(t.readOnly)return;let f=await e(this,w,"m",me).call(this,t);if(!f.markerOk){e(this,p,"f").warn(`${f.distrustReason}; not uploading anything from the memory store folder`,{root:t.files.root().path,memory_store_id:t.memoryStoreId});return}for(let[h,u]of Object.entries(f.files))if(u!==t.baseline.get(h)&&t.refusedShas.get(h)!==u)o.set(h,u),s.add(h);if(o.size===0||i?.aborted)return;let d=new Map;for await(let[h,u]of e(this,w,"m",ue).call(this,t.memoryStoreId)){if(i?.aborted)return;d.set(h,u)}let m=[];for(let h of[...o.keys()].sort()){let u=o.get(h),_=t.baseline.get(h),b=d.get(h);if(b!==void 0&&b.content_sha256===u){t.baseline.set(h,b.content_sha256),s.delete(h);continue}if(b!==void 0&&b.content_sha256!==_){e(this,p,"f").warn("memory changed both locally and remotely; the flush leaves the remote version",{path:h,memory_store_id:t.memoryStoreId}),s.delete(h);continue}m.push([h,u,b])}await e(this,w,"m",Xe).call(this,t,m,s,i)};try{if(await Zt(l(),i),i?.aborted&&s.size>0)e(this,p,"f").warn(`memory flush cut off part-way; ${s.size} of ${o.size} changed files had not finished uploading`,{memory_store_id:t.memoryStoreId})}catch(f){e(this,p,"f").warn("memory flush failed",{memory_store_id:t.memoryStoreId,error:String(f)})}},Re=async function(t,i){e(this,p,"f").warn(`${i}; re-downloading the memory store folder instead of syncing`,{root:t.files.root().path,memory_store_id:t.memoryStoreId}),await t.files.createRoot(),await e(this,w,"m",Ne).call(this,t)},Ne=async function(t){t.baseline=new Map,t.pendingDeletes.clear(),await t.files.put(K,`version ${et}
7
- ${t.memoryStoreId}`);for await(let[i,o]of e(this,w,"m",ue).call(this,t.memoryStoreId,"full"))if(await e(this,w,"m",Te).call(this,t,i,o.content??""))t.baseline.set(i,o.content_sha256)},He=async function(t,i,o,s,l){let f=t.baseline.get(i);if(s!==void 0)t.pendingDeletes.delete(i);if(!o){if(s===void 0){t.pendingDeletes.delete(i);return}if(f!==void 0){if(s===f){let _=await e(this,w,"m",Ke).call(this,t,i,f);if(_===void 0)return;if(_===f)return f;s=_}if(t.readOnly)e(this,p,"f").warn("memory deleted remotely but edited locally; keeping the file, which a read-only store cannot push",{path:i,memory_store_id:t.memoryStoreId});else if(t.refusedShas.get(i)!==s)e(this,p,"f").info("memory deleted remotely but edited locally; re-creating it from the file",{path:i,memory_store_id:t.memoryStoreId})}if(t.readOnly)return;if(t.refusedShas.get(i)===s)return;return await e(this,w,"m",pe).call(this,t,i,s,void 0)}let d=o.content_sha256,m=d!==f,h=s!==void 0&&s!==f&&s!==d,u=!t.readOnly&&h;if(s===void 0&&f!==void 0){if(m)e(this,p,"f").warn("memory deleted locally but changed remotely; restoring the remote version",{path:i,memory_store_id:t.memoryStoreId}),t.pendingDeletes.delete(i),l.push([i,o]);return f}if(m){if(s===d)return d;if(h)e(this,p,"f").warn("memory changed both locally and remotely; keeping the remote version",{path:i,memory_store_id:t.memoryStoreId});return l.push([i,o]),f}if(u){if(t.refusedShas.get(i)===s)return d;return await e(this,w,"m",pe).call(this,t,i,s,o)??d}return d},Ke=async function(t,i,o){let s;try{s=await t.files.hashFile(i)}catch(l){if(!(l instanceof y)&&!H(l))throw l;return o}if(s===null)return;if(s!==o)return s;try{await t.files.remove(i)}catch(l){if(!(l instanceof y)&&!H(l))throw l;return e(this,p,"f").warn("failed to remove memory deleted remotely",{path:i,memory_store_id:t.memoryStoreId,error:String(l)}),o}return},Te=async function(t,i,o){try{await t.files.put(i,o)}catch(s){if(!(s instanceof y)&&!H(s))throw s;return e(this,p,"f").warn("failed to write memory",{path:i,memory_store_id:t.memoryStoreId,error:String(s)}),!1}return!0},Ve=async function(t,i){if(i.length===0)return;let o=async(f,d)=>{let m;try{m=await e(this,N,"f").beta.memoryStores.memories.retrieve(d.id,{memory_store_id:t.memoryStoreId,view:"full"})}catch(h){if(le(h,404))return;e(this,p,"f").warn("failed to fetch memory content",{path:f,memory_store_id:t.memoryStoreId,error:String(h)});return}if(await e(this,w,"m",Te).call(this,t,f,m.content??""))t.baseline.set(f,m.content_sha256)},s=i[Symbol.iterator](),l=async()=>{for(let[f,d]of s)await o(f,d)};await Promise.all(Array.from({length:Math.min(Ht,i.length)},l))},Xe=async function(t,i,o,s){let l=i[Symbol.iterator](),f=async()=>{for(let[d,m,h]of l){if(s?.aborted)return;let u=await e(this,w,"m",pe).call(this,t,d,m,h);if(o.delete(d),u!==void 0)t.baseline.set(d,u)}};await Promise.all(Array.from({length:Math.min(Kt,i.length)},f))},ue=async function*(t,i="basic"){let o=i==="basic"?zt:Gt;for await(let s of e(this,N,"f").beta.memoryStores.memories.list(t,{view:i,limit:o})){if(s.type!=="memory")continue;let l=s.path.replace(/^\/+/,"");if(l===K){e(this,p,"f").warn("the server listed the reserved marker path; skipping",{path:s.path,memory_store_id:t});continue}yield[l,s]}},pe=async function r(t,i,o,s){try{let l=await t.files.get(i);if(l===null)return;let f=vt(l),d=s?await e(this,N,"f").beta.memoryStores.memories.update(s.id,{memory_store_id:t.memoryStoreId,content:f,precondition:{type:"content_sha256",content_sha256:s.content_sha256}}):await e(this,N,"f").beta.memoryStores.memories.create(t.memoryStoreId,{path:"/"+i,content:f});return t.refusedShas.delete(i),d.content_sha256}catch(l){if(s&&le(l,404))return await e(this,w,"m",r).call(this,t,i,o,void 0);let f=l instanceof y||le(l,400)||le(l,413);if(s&&le(l,409))e(this,p,"f").warn("memory changed both locally and remotely; the upload was refused and the local edit loses",{path:i,memory_store_id:t.memoryStoreId});else if(f&&o!==void 0)t.refusedShas.set(i,o),e(this,p,"f").warn("the server rejected this memory file, so it stays un-synced until its content changes",{path:i,memory_store_id:t.memoryStoreId,rejection:String(l)});else e(this,p,"f").warn("failed to upload memory",{path:i,memory_store_id:t.memoryStoreId,error:String(l)});return}},Je=async function(t,i,o,s,l){if(l.mode==="disabled")return l.suppressed++,s;let f=t.pendingDeletes.get(i);if(f===void 0)f=Date.now(),t.pendingDeletes.set(i,f);if(!l.waiveWindow&&Date.now()-f<qt)return s;let d,m;try{d=await t.files.hashFile(K)===Qe(t.memoryStoreId),m=await t.files.hashFile(i)===null}catch(u){if(!(u instanceof y)&&!H(u))throw u;d=m=!1}if(!d)return s;if(!m)return t.pendingDeletes.delete(i),s;if(!l.takeSlot())return s;if(l.mode==="log_only")return e(this,p,"f").info("log-only: sync would delete this memory on the server",{path:i,memory_store_id:t.memoryStoreId}),s;let h=await e(this,w,"m",Ze).call(this,t,i,o,s);if(h===void 0)t.pendingDeletes.delete(i);return h},Ze=async function(t,i,o,s){try{await e(this,N,"f").beta.memoryStores.memories.delete(o.id,{memory_store_id:t.memoryStoreId,expected_content_sha256:s})}catch(l){if(le(l,404))return;if(le(l,409)||le(l,412))e(this,p,"f").warn("memory deleted locally but changed remotely; keeping the remote version",{path:i,memory_store_id:t.memoryStoreId});else e(this,p,"f").warn("failed to delete memory",{path:i,memory_store_id:t.memoryStoreId,error:String(l)});return s}e(this,p,"f").info("propagated local deletion",{path:i,memory_store_id:t.memoryStoreId});return},a})();function H(a){return typeof a==="object"&&a!==null&&typeof a.code==="string"}async function Zt(a,r){if(!r){await a;return}let t,i=new Promise((o)=>{if(t=o,r.aborted)o()});r.addEventListener("abort",t,{once:!0});try{await Promise.race([a,i])}finally{r.removeEventListener("abort",t)}}var ye,O,k,ee,W,R,Le,we,te,_e,ge,U,j,V,B,re,A,rt,it,nt=102400,ft=120000,Qt=262144,er=65536,ot=Buffer.from(`
8
- `),ie=102400,tr=2000,rr=200;class dt extends c{constructor(a){super(`bash command timed out after ${a}ms`);this.name="BashTimeoutError",this.timeoutMs=a}}var ir=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,nr=S.glob;function ht(a){return a===void 0?Qt:a}function Y(a){if(a===void 0)return;throw new c("The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` from your context; to let the file tools reach any other directory, add it to `allowedRoots`.")}function Xr(a){return[ar(a),cr(a),dr(a),hr(a),ur(a),pr(a)]}async function oe(a,r){return Y(a.unrestrictedPaths),Ae(a.workdir,r,{allowedRoots:a.allowedRoots??[]})}function mt(a,r){return Ee(a.readOnlyRoots??[],r)}function or(){let a={};for(let[r,t]of Object.entries(process.env)){if(r.startsWith("ANTHROPIC_"))continue;a[r]=t}return a}var sr=(()=>{class a{constructor(r,t=or()){ye.add(this),O.set(this,void 0),k.set(this,""),ee.set(this,!1),W.set(this,!1),R.set(this,null),n(this,O,$e.spawn("/bin/bash",["--noprofile","--norc"],{cwd:r,env:{...t,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),"f"),e(this,O,"f").stdout.setEncoding("utf8"),e(this,O,"f").stderr.setEncoding("utf8"),e(this,O,"f").stdout.on("data",(i)=>e(this,ye,"m",Le).call(this,i)),e(this,O,"f").stderr.on("data",(i)=>e(this,ye,"m",Le).call(this,i)),e(this,O,"f").once("close",()=>{n(this,W,!0,"f");let i=e(this,R,"f");n(this,R,null,"f"),i?.resolve()})}get closed(){return e(this,W,"f")}async exec(r,t={}){if(e(this,W,"f"))throw new c("bash session terminated");let i=t.timeoutMs??ft,o=t.signal;o?.throwIfAborted(),n(this,k,"","f"),n(this,ee,!1,"f");let s=`__ANT_CMD_${ct.randomUUID()}_DONE__`,l=`${s.slice(0,8)}''${s.slice(8)}`,f=`{ ${r}
5
+ `,{flag:"wx",mode:384}),["-xf",r,"-C",t,"-X",o]}async function Rt(a,r){let t=await k.open(a,"r");try{let i=Buffer.alloc(r),{bytesRead:o}=await t.read(i,0,r,0);return i.subarray(0,o)}finally{await t.close()}}var g=st.promises,z=st.constants,Ue=448,Tt=384,Lt=448,ke=z.O_NOFOLLOW??0,$t=z.O_NONBLOCK??0,y=(()=>{class a extends Error{constructor(r,t){super(`path ${JSON.stringify(t)} ${r}`);this.name="FileStoreError",this.reason=r,this.relPath=t}}return a.ESCAPES_ROOT="escapes the store root",a.IS_A_SYMLINK="is a symlink",a.NOT_A_FILE="is not a regular file",a.NOT_A_DIRECTORY="is not a directory",a.NOT_UTF8="is not valid utf-8",a.MOVE_DESTINATION_EXISTS="already exists",a})();function Ie(a){return a.startsWith("/")&&!a.split("/").includes("..")}var ve=(()=>{class a{constructor(r,t,i=!1){this.hashes=new Map,this.rootPath=r,this.removedOnDispose=t,this.decoder=i?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(r,t){if(!At())throw Error("FileStore requires O_NOFOLLOW support on this platform");let i=!1;try{await g.lstat(r)}catch(o){if(o.code!=="ENOENT")throw o;i=!0}return new a(x.resolve(r),i,t?.utf8??!1)}async createRoot(){await xt(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){if(!this.removedOnDispose)return;await g.rm(this.rootPath,{recursive:!0,force:!0})}async put(r,t,i){let o=r.replace(/\\/g,"/");if(o.endsWith("/")||o.endsWith("/.")||o===""||o===".")throw new y(y.NOT_A_FILE,r);let s=this.resolveUnderRoot(r),l=typeof t==="string"?Nt(t):t;this.requireUtf8(r,l),await Fe(this.rootPath,x.dirname(s)),await Dt(s,l,i?.executable??!1)}async get(r){let t=this.resolveUnderRoot(r),i;try{i=await je(r,t)}catch(s){if(s.code==="ENOENT")return null;throw s}let o;try{let s=await i.readFile();o=new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}finally{await i.close()}return this.requireUtf8(r,o),o}async ls(r="/"){let t=this.resolveUnderRoot(r);return new Set((await Pe(this.rootPath,r,t)).map(([i])=>i))}async findSymlinks(r="/"){let t=this.resolveUnderRoot(r);return Ft(this.rootPath,r,t)}async hashtree(r="/"){let t=this.resolveUnderRoot(r),i=ce.nowNs(),o=Object.create(null);for(let[s,l]of await Pe(this.rootPath,r,t)){let f=await this.hashViaCache(s,l,i);if(f!==null)o[s]=f}return o}async hashFile(r){let t=this.resolveUnderRoot(r),i;try{i=await g.lstat(t,{bigint:!0})}catch(s){if(s.code==="ENOENT")return null;throw s}if(i.isSymbolicLink())throw new y(y.IS_A_SYMLINK,r);if(!i.isFile())throw new y(y.NOT_A_FILE,r);let o=x.relative(this.rootPath,t).split(x.sep).join("/");return this.hashViaCache(o,t,ce.nowNs())}async move(r,t){let i=this.resolveUnderRoot(r),o=this.resolveUnderRoot(t);if(i===this.rootPath||o===this.rootPath)return;if(await g.stat(o).then(()=>!0,()=>!1))throw new y(y.MOVE_DESTINATION_EXISTS,t);await Fe(this.rootPath,x.dirname(o)),await g.rename(i,o)}async remove(r){let t=this.resolveUnderRoot(r);if(t===this.rootPath)return;let i;try{i=await g.lstat(t,{bigint:!0})}catch(o){if(o.code==="ENOENT")return;throw o}if(i.isDirectory())await g.rm(t,{recursive:!0,force:!0});else try{await g.unlink(t)}catch(o){if(o.code!=="ENOENT")throw o}}resolveUnderRoot(r){let t=r.replace(/\\/g,"/").replace(/^\/+/,""),i=t.split("/").filter((o)=>o!==""&&o!==".");if(x.posix.isAbsolute(t)||i.includes(".."))throw new y(y.ESCAPES_ROOT,r);return i.length===0?this.rootPath:x.join(this.rootPath,...i)}requireUtf8(r,t){if(!this.decoder)return;try{this.decoder.decode(t)}catch{throw new y(y.NOT_UTF8,r)}}async hashViaCache(r,t,i){let o;try{o=await g.lstat(t,{bigint:!0})}catch(f){if(f.code==="ENOENT")return null;throw f}if(!o.isFile())return null;let s=this.hashes.get(r),l;if(s!==void 0&&Wt(s,o))l=s.sha;else try{l=await ce.hashFile(t)}catch(f){let d=f.code;if(d==="ENOENT"||f instanceof y)return null;if(d==="ELOOP"||d==="EMLINK")return null;throw f}if(jt(o,i))this.hashes.set(r,{mtimeNs:o.mtimeNs,ctimeNs:o.ctimeNs,size:o.size,sha:l});return l}}return a.isPathLegal=Ie,a})();function At(){return ke!==0}async function xt(a){let r=[],t=a;for(;;){try{await g.stat(t);break}catch(o){let s=o.code;if(s!=="ENOENT"&&s!=="ENOTDIR"&&s!=="ELOOP")throw o}r.push(t);let i=x.dirname(t);if(i===t)break;t=i}for(let i of r.reverse())try{await g.mkdir(i,{mode:Ue})}catch(o){if(o.code!=="EEXIST")throw o}}async function Fe(a,r){let t=x.relative(a,r);if(t==="")return;let i=a;for(let o of t.split(x.sep)){i=x.join(i,o);try{await g.mkdir(i,{mode:Ue})}catch(s){if(s.code!=="EEXIST")throw s}}}async function Dt(a,r,t){let i=t?Lt:Tt,o=x.join(x.dirname(a),`.fs-${St.randomBytes(8).toString("hex")}.tmp`),s;try{s=await g.open(o,z.O_WRONLY|z.O_CREAT|z.O_EXCL|ke,i),await s.writeFile(r),await s.close(),s=void 0,await g.rename(o,a)}catch(l){if(s)await s.close().catch(()=>{});throw await g.unlink(o).catch(()=>{}),l}}async function je(a,r){let t;try{t=await g.open(r,z.O_RDONLY|ke|$t)}catch(i){let o=i.code;if(o==="ELOOP"||o==="EMLINK")throw new y(y.IS_A_SYMLINK,a);throw i}try{if(!(await t.stat()).isFile())throw new y(y.NOT_A_FILE,a)}catch(i){throw await t.close().catch(()=>{}),i}return t}async function Ct(a){let r=St.createHash("sha256"),t=await je(x.basename(a),a),i=new Uint8Array(1048576);try{for(;;){let{bytesRead:o}=await t.read(i,0,i.length);if(o===0)break;r.update(i.subarray(0,o))}}finally{await t.close()}return r.digest("hex")}async function Pe(a,r,t){if(!await Pt(r,t))return[];let i=[];return await Be(t,(o,s)=>{if(s.isFile())i.push([x.relative(a,o).split(x.sep).join("/"),o])}),i.sort(),i}async function Ft(a,r,t){let i=(l)=>x.relative(a,l).split(x.sep).join("/"),o;try{o=await g.lstat(t,{bigint:!0})}catch(l){let f=l.code;if(f==="ENOENT"||f==="ENOTDIR")return new Set;throw l}if(o.isSymbolicLink())return new Set([i(t)]);if(!o.isDirectory())throw new y(y.NOT_A_DIRECTORY,r);let s=new Set;return await Be(t,(l,f)=>{if(f.isSymbolicLink())s.add(i(l))}),s}async function Pt(a,r){let t;try{t=await g.lstat(r,{bigint:!0})}catch(i){let o=i.code;if(o==="ENOENT"||o==="ENOTDIR")return!1;throw i}if(!t.isDirectory())throw new y(y.NOT_A_DIRECTORY,a);return!0}async function Be(a,r){let t=[a];while(t.length){let i=t.pop(),o;try{o=await g.readdir(i,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){let l=x.join(i,s.name);if(r(l,s),s.isDirectory()&&!s.isSymbolicLink())t.push(l)}}}function Wt(a,r){return r.mtimeNs===a.mtimeNs&&r.ctimeNs===a.ctimeNs&&r.size===a.size}function jt(a,r){return(a.mtimeNs>a.ctimeNs?a.mtimeNs:a.ctimeNs)<r-ce.timestampTrustMarginNs}var Bt=2000000000n,ce={hashFile:Ct,timestampTrustMarginNs:Bt,nowNs:()=>BigInt(Date.now())*1000000n},Ye=ve,We=Symbol.asyncDispose;if(We)Object.defineProperty(ve.prototype,We,{value:ve.prototype.dispose,configurable:!0,writable:!0});var w,R,fe,Q,de,p,G,he,N,qe,me,ze,Ge,Re,Ne,He,Ke,Te,Ve,Xe,ue,pe,Je,Ze,Yt=30000,K=".anthropic-memory-store",et=1;function Qe(a){return St.createHash("sha256").update(`version ${et}
6
+ ${a}`,"utf-8").digest("hex")}var qt=30000,zt=100,Gt=20,Ht=16,Kt=32,Vt=8,Xt=50;class P extends c{constructor(a,r){super(a);if(this.name="SessionMemoryError",r!==void 0)this.cause=r}}class tt{constructor(a,r,t){this.mode=a,this.cap=r,this.waiveWindow=t,this.attempted=0,this.capped=0,this.suppressed=0}takeSlot(){if(this.attempted>=this.cap)return this.capped++,!1;return this.attempted++,!0}}var Jt=(()=>{class a{constructor(r,t){w.add(this),R.set(this,void 0),fe.set(this,void 0),Q.set(this,void 0),de.set(this,void 0),p.set(this,void 0),G.set(this,void 0),he.set(this,!1),N.set(this,[]),n(this,R,r,"f"),n(this,fe,t.workdir,"f"),n(this,Q,t.syncIntervalMs??Ao,"f"),Mr(e(this,Q,"f"),"syncIntervalMs"),n(this,de,t.syncDeletions??"enabled","f"),n(this,p,T(r),"f"),n(this,G,Date.now(),"f")}get roots(){return e(this,N,"f").map((r)=>r.files.root().path)}get readOnlyRoots(){return e(this,N,"f").filter((r)=>r.readOnly).map((r)=>r.files.root().path)}async download(r){for(let t of r.resources){if(t.type!=="memory_store")continue;let i=e(this,w,"m",qe).call(this,t),o;try{if(o={memoryStoreId:t.memory_store_id,files:await Ye.open(i,{utf8:!0}),readOnly:t.access==="read_only",baseline:new Map,refusedShas:new Map,pendingDeletes:new Map},!o.files.root().removedOnDispose)throw new P(`something already exists at the memory store's path: ${i} (memory_store_id=${t.memory_store_id}); it must not exist when the session starts`);try{await o.files.createRoot()}catch(s){if(!H(s))throw s;throw new P(`cannot create the memory store's folder: ${i} (memory_store_id=${t.memory_store_id}): ${s}; the worker host must make this mount path writable`,s)}await e(this,w,"m",Ne).call(this,o),e(this,p,"f").info("downloaded memories",{count:o.baseline.size,memory_store_id:o.memoryStoreId,dest:o.files.root().path}),e(this,N,"f").push(o)}catch(s){if(o)await o.files.dispose().catch(()=>{});if(s instanceof P)throw s;throw new P(`failed to download memory store memory_store_id=${t.memory_store_id}: ${s}`,s)}}n(this,G,Date.now(),"f")}async finish(){if(e(this,he,"f"))throw new c("finish() was already called: it is the session's last sync and runs once");n(this,he,!0,"f"),await this.syncAll(!0)}async syncAll(r){await Promise.all(e(this,N,"f").map((t)=>e(this,w,"m",ze).call(this,t,r))),n(this,G,Date.now(),"f")}async syncIfDue(){if(Date.now()-e(this,G,"f")<e(this,Q,"f"))return;await this.syncAll(!1)}async flushWrites(r){await Promise.all(e(this,N,"f").map((t)=>e(this,w,"m",Ge).call(this,t,r)))}async dispose(){for(let r of e(this,N,"f")){let t=r.files.root();try{let i=await e(this,w,"m",me).call(this,r);if(!i.markerOk&&Object.keys(i.files).length>0){e(this,p,"f").warn(`${i.distrustReason}; leaving the memory store folder on disk`,{root:t.path,memory_store_id:r.memoryStoreId});continue}await r.files.dispose()}catch(i){if(!(i instanceof y)&&!H(i))throw i;e(this,p,"f").warn("failed to remove the memory store folder",{root:r.files.root().path,memory_store_id:r.memoryStoreId,error:String(i)});continue}if(t.removedOnDispose)e(this,p,"f").info("removed memory store dir",{dest:t.path,memory_store_id:r.memoryStoreId})}}}return R=new WeakMap,fe=new WeakMap,Q=new WeakMap,de=new WeakMap,p=new WeakMap,G=new WeakMap,he=new WeakMap,N=new WeakMap,w=new WeakSet,qe=function(t){if(t.mount_path){if(!Ie(t.mount_path))throw new P(`memory store mount_path is not a clean absolute path: ${JSON.stringify(t.mount_path)} (memory_store_id=${t.memory_store_id})`);return t.mount_path}return x.join(e(this,fe,"f"),"memory",t.name||t.memory_store_id)},me=async function(t){let i=await t.files.hashtree(),o=i[K];if(delete i[K],o===Qe(t.memoryStoreId))return{files:i,markerOk:!0,distrustReason:null};return{files:i,markerOk:!1,distrustReason:o!==void 0?"the marker file does not match this store":"the marker file is gone"}},ze=async function(t,i){try{let o=await e(this,w,"m",me).call(this,t),s=o.files;if(!o.markerOk){if(Object.keys(s).length>0){e(this,p,"f").warn(`${o.distrustReason}; leaving the memory store folder as found and not syncing`,{root:t.files.root().path,memory_store_id:t.memoryStoreId});return}await e(this,w,"m",Re).call(this,t,"the folder or its marker is gone");return}if(Object.keys(s).length===0&&t.baseline.size>1){await e(this,w,"m",Re).call(this,t,"every memory file is gone at once");return}let l=new Map;for await(let[u,_]of e(this,w,"m",ue).call(this,t.memoryStoreId))l.set(u,_);let f=new tt(e(this,de,"f"),Math.max(Vt,Math.min(Xt,Math.floor(t.baseline.size/4))),i),d=[],m=new Map,h=[...new Set([...l.keys(),...Object.keys(s),...t.baseline.keys()])].sort();for(let u of h){let _=l.get(u),E=s[u],D=t.baseline.get(u),M;if(E===void 0&&D!==void 0&&_!==void 0&&_.content_sha256===D&&!t.readOnly)M=await e(this,w,"m",Je).call(this,t,u,_,D,f);else M=await e(this,w,"m",He).call(this,t,u,_,E,d);if(M!==void 0)m.set(u,M)}if(t.baseline=m,await e(this,w,"m",Ve).call(this,t,d),f.suppressed>0)e(this,p,"f").debug("remote deletes are disabled; locally deleted memories stay on the server",{count:f.suppressed,memory_store_id:t.memoryStoreId});if(f.capped>0)e(this,p,"f").warn(`delete cap reached: ${f.mode==="log_only"?"would send":"sent"} ${f.attempted} deletes, held ${f.capped} for later syncs`,{memory_store_id:t.memoryStoreId})}catch(o){e(this,p,"f").warn("memory sync failed",{memory_store_id:t.memoryStoreId,error:String(o)})}},Ge=async function(t,i){let o=new Map,s=new Set,l=async()=>{if(t.readOnly)return;let f=await e(this,w,"m",me).call(this,t);if(!f.markerOk){e(this,p,"f").warn(`${f.distrustReason}; not uploading anything from the memory store folder`,{root:t.files.root().path,memory_store_id:t.memoryStoreId});return}for(let[h,u]of Object.entries(f.files))if(u!==t.baseline.get(h)&&t.refusedShas.get(h)!==u)o.set(h,u),s.add(h);if(o.size===0||i?.aborted)return;let d=new Map;for await(let[h,u]of e(this,w,"m",ue).call(this,t.memoryStoreId)){if(i?.aborted)return;d.set(h,u)}let m=[];for(let h of[...o.keys()].sort()){let u=o.get(h),_=t.baseline.get(h),E=d.get(h);if(E!==void 0&&E.content_sha256===u){t.baseline.set(h,E.content_sha256),s.delete(h);continue}if(E!==void 0&&E.content_sha256!==_){e(this,p,"f").warn("memory changed both locally and remotely; the flush leaves the remote version",{path:h,memory_store_id:t.memoryStoreId}),s.delete(h);continue}m.push([h,u,E])}await e(this,w,"m",Xe).call(this,t,m,s,i)};try{if(await Zt(l(),i),i?.aborted&&s.size>0)e(this,p,"f").warn(`memory flush cut off part-way; ${s.size} of ${o.size} changed files had not finished uploading`,{memory_store_id:t.memoryStoreId})}catch(f){e(this,p,"f").warn("memory flush failed",{memory_store_id:t.memoryStoreId,error:String(f)})}},Re=async function(t,i){e(this,p,"f").warn(`${i}; re-downloading the memory store folder instead of syncing`,{root:t.files.root().path,memory_store_id:t.memoryStoreId}),await t.files.createRoot(),await e(this,w,"m",Ne).call(this,t)},Ne=async function(t){t.baseline=new Map,t.pendingDeletes.clear(),await t.files.put(K,`version ${et}
7
+ ${t.memoryStoreId}`);for await(let[i,o]of e(this,w,"m",ue).call(this,t.memoryStoreId,"full"))if(await e(this,w,"m",Te).call(this,t,i,o.content??""))t.baseline.set(i,o.content_sha256)},He=async function(t,i,o,s,l){let f=t.baseline.get(i);if(s!==void 0)t.pendingDeletes.delete(i);if(!o){if(s===void 0){t.pendingDeletes.delete(i);return}if(f!==void 0){if(s===f){let _=await e(this,w,"m",Ke).call(this,t,i,f);if(_===void 0)return;if(_===f)return f;s=_}if(t.readOnly)e(this,p,"f").warn("memory deleted remotely but edited locally; keeping the file, which a read-only store cannot push",{path:i,memory_store_id:t.memoryStoreId});else if(t.refusedShas.get(i)!==s)e(this,p,"f").info("memory deleted remotely but edited locally; re-creating it from the file",{path:i,memory_store_id:t.memoryStoreId})}if(t.readOnly)return;if(t.refusedShas.get(i)===s)return;return await e(this,w,"m",pe).call(this,t,i,s,void 0)}let d=o.content_sha256,m=d!==f,h=s!==void 0&&s!==f&&s!==d,u=!t.readOnly&&h;if(s===void 0&&f!==void 0){if(m)e(this,p,"f").warn("memory deleted locally but changed remotely; restoring the remote version",{path:i,memory_store_id:t.memoryStoreId}),t.pendingDeletes.delete(i),l.push([i,o]);return f}if(m){if(s===d)return d;if(h)e(this,p,"f").warn("memory changed both locally and remotely; keeping the remote version",{path:i,memory_store_id:t.memoryStoreId});return l.push([i,o]),f}if(u){if(t.refusedShas.get(i)===s)return d;return await e(this,w,"m",pe).call(this,t,i,s,o)??d}return d},Ke=async function(t,i,o){let s;try{s=await t.files.hashFile(i)}catch(l){if(!(l instanceof y)&&!H(l))throw l;return o}if(s===null)return;if(s!==o)return s;try{await t.files.remove(i)}catch(l){if(!(l instanceof y)&&!H(l))throw l;return e(this,p,"f").warn("failed to remove memory deleted remotely",{path:i,memory_store_id:t.memoryStoreId,error:String(l)}),o}return},Te=async function(t,i,o){try{await t.files.put(i,o)}catch(s){if(!(s instanceof y)&&!H(s))throw s;return e(this,p,"f").warn("failed to write memory",{path:i,memory_store_id:t.memoryStoreId,error:String(s)}),!1}return!0},Ve=async function(t,i){if(i.length===0)return;let o=async(f,d)=>{let m;try{m=await e(this,R,"f").beta.memoryStores.memories.retrieve(d.id,{memory_store_id:t.memoryStoreId,view:"full"})}catch(h){if(le(h,404))return;e(this,p,"f").warn("failed to fetch memory content",{path:f,memory_store_id:t.memoryStoreId,error:String(h)});return}if(await e(this,w,"m",Te).call(this,t,f,m.content??""))t.baseline.set(f,m.content_sha256)},s=i[Symbol.iterator](),l=async()=>{for(let[f,d]of s)await o(f,d)};await Promise.all(Array.from({length:Math.min(Ht,i.length)},l))},Xe=async function(t,i,o,s){let l=i[Symbol.iterator](),f=async()=>{for(let[d,m,h]of l){if(s?.aborted)return;let u=await e(this,w,"m",pe).call(this,t,d,m,h);if(o.delete(d),u!==void 0)t.baseline.set(d,u)}};await Promise.all(Array.from({length:Math.min(Kt,i.length)},f))},ue=async function*(t,i="basic"){let o=i==="basic"?zt:Gt;for await(let s of e(this,R,"f").beta.memoryStores.memories.list(t,{view:i,limit:o})){if(s.type!=="memory")continue;let l=s.path.replace(/^\/+/,"");if(l===K){e(this,p,"f").warn("the server listed the reserved marker path; skipping",{path:s.path,memory_store_id:t});continue}yield[l,s]}},pe=async function r(t,i,o,s){try{let l=await t.files.get(i);if(l===null)return;let f=vt(l),d=s?await e(this,R,"f").beta.memoryStores.memories.update(s.id,{memory_store_id:t.memoryStoreId,content:f,precondition:{type:"content_sha256",content_sha256:s.content_sha256}}):await e(this,R,"f").beta.memoryStores.memories.create(t.memoryStoreId,{path:"/"+i,content:f});return t.refusedShas.delete(i),d.content_sha256}catch(l){if(s&&le(l,404))return await e(this,w,"m",r).call(this,t,i,o,void 0);let f=l instanceof y||le(l,400)||le(l,413);if(s&&le(l,409))e(this,p,"f").warn("memory changed both locally and remotely; the upload was refused and the local edit loses",{path:i,memory_store_id:t.memoryStoreId});else if(f&&o!==void 0)t.refusedShas.set(i,o),e(this,p,"f").warn("the server rejected this memory file, so it stays un-synced until its content changes",{path:i,memory_store_id:t.memoryStoreId,rejection:String(l)});else e(this,p,"f").warn("failed to upload memory",{path:i,memory_store_id:t.memoryStoreId,error:String(l)});return}},Je=async function(t,i,o,s,l){if(l.mode==="disabled")return l.suppressed++,s;let f=t.pendingDeletes.get(i);if(f===void 0)f=Date.now(),t.pendingDeletes.set(i,f);if(!l.waiveWindow&&Date.now()-f<qt)return s;let d,m;try{d=await t.files.hashFile(K)===Qe(t.memoryStoreId),m=await t.files.hashFile(i)===null}catch(u){if(!(u instanceof y)&&!H(u))throw u;d=m=!1}if(!d)return s;if(!m)return t.pendingDeletes.delete(i),s;if(!l.takeSlot())return s;if(l.mode==="log_only")return e(this,p,"f").info("log-only: sync would delete this memory on the server",{path:i,memory_store_id:t.memoryStoreId}),s;let h=await e(this,w,"m",Ze).call(this,t,i,o,s);if(h===void 0)t.pendingDeletes.delete(i);return h},Ze=async function(t,i,o,s){try{await e(this,R,"f").beta.memoryStores.memories.delete(o.id,{memory_store_id:t.memoryStoreId,expected_content_sha256:s})}catch(l){if(le(l,404))return;if(le(l,409)||le(l,412))e(this,p,"f").warn("memory deleted locally but changed remotely; keeping the remote version",{path:i,memory_store_id:t.memoryStoreId});else e(this,p,"f").warn("failed to delete memory",{path:i,memory_store_id:t.memoryStoreId,error:String(l)});return s}e(this,p,"f").info("propagated local deletion",{path:i,memory_store_id:t.memoryStoreId});return},a})();function H(a){return typeof a==="object"&&a!==null&&typeof a.code==="string"}async function Zt(a,r){if(!r){await a;return}let t,i=new Promise((o)=>{if(t=o,r.aborted)o()});r.addEventListener("abort",t,{once:!0});try{await Promise.race([a,i])}finally{r.removeEventListener("abort",t)}}var ye,b,v,ee,W,I,Le,we,te,_e,ge,U,j,V,B,re,L,rt,it,nt=102400,ft=120000,Qt=262144,er=65536,ot=Buffer.from(`
8
+ `),ie=102400,tr=2000,rr=200;class dt extends c{constructor(a){super(`bash command timed out after ${a}ms`);this.name="BashTimeoutError",this.timeoutMs=a}}var ir=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,nr=S.glob;function ht(a){return a===void 0?Qt:a}function Y(a){if(a===void 0)return;throw new c("The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` from your context; to let the file tools reach any other directory, add it to `allowedRoots`.")}function Xr(a){return[ar(a),cr(a),dr(a),hr(a),ur(a),pr(a)]}async function oe(a,r){return Y(a.unrestrictedPaths),Ae(a.workdir,r,{allowedRoots:a.allowedRoots??[]})}function mt(a,r){return Ee(a.readOnlyRoots??[],r)}function or(){let a={};for(let[r,t]of Object.entries(process.env)){if(r.startsWith("ANTHROPIC_"))continue;a[r]=t}return a}var sr=(()=>{class a{constructor(r,t=or()){ye.add(this),b.set(this,void 0),v.set(this,""),ee.set(this,!1),W.set(this,!1),I.set(this,null),n(this,b,$e.spawn("/bin/bash",["--noprofile","--norc"],{cwd:r,env:{...t,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),"f"),e(this,b,"f").stdout.setEncoding("utf8"),e(this,b,"f").stderr.setEncoding("utf8"),e(this,b,"f").stdout.on("data",(i)=>e(this,ye,"m",Le).call(this,i)),e(this,b,"f").stderr.on("data",(i)=>e(this,ye,"m",Le).call(this,i)),e(this,b,"f").once("close",()=>{n(this,W,!0,"f");let i=e(this,I,"f");n(this,I,null,"f"),i?.resolve()})}get closed(){return e(this,W,"f")}async exec(r,t={}){if(e(this,W,"f"))throw new c("bash session terminated");let i=t.timeoutMs??ft,o=t.signal;o?.throwIfAborted(),n(this,v,"","f"),n(this,ee,!1,"f");let s=`__ANT_CMD_${ct.randomUUID()}_DONE__`,l=`${s.slice(0,8)}''${s.slice(8)}`,f=`{ ${r}
9
9
  } </dev/null 2>&1; printf '\\n${l}%d\\n' $?
10
- `;if(e(this,O,"f").stdin.write(f),e(this,k,"f").indexOf(s)<0){let{promise:b,resolve:D}=Ut();n(this,R,{sentinel:s,resolve:D},"f");let v,se;try{await Promise.race([b,new Promise((pt,Se)=>{v=setTimeout(()=>Se(new dt(i)),i)}),new Promise((pt,Se)=>{if(!o)return;se=()=>Se(o.reason),o.addEventListener("abort",se,{once:!0})})])}finally{if(v)clearTimeout(v);if(se&&o)o.removeEventListener("abort",se);n(this,R,null,"f")}}let d=e(this,k,"f").indexOf(s);if(d<0)throw new c("bash session terminated");let h=e(this,k,"f").slice(d+s.length).match(/^(-?\d+)/),u=h?parseInt(h[1],10):-1,_=e(this,k,"f").slice(0,d).replace(ir,"").replace(/\n+$/,"");if(e(this,ee,"f"))_=`[output truncated]
11
- ${_}`;return{output:_,exitCode:u}}close(){if(e(this,W,"f"))return;n(this,W,!0,"f");let r=e(this,R,"f");n(this,R,null,"f"),r?.resolve(),e(this,O,"f").stdout.destroy(),e(this,O,"f").stderr.destroy(),e(this,O,"f").stdin.destroy();try{process.kill(-e(this,O,"f").pid,"SIGKILL")}catch{e(this,O,"f").kill("SIGKILL")}e(this,O,"f").unref()}}return O=new WeakMap,k=new WeakMap,ee=new WeakMap,W=new WeakMap,R=new WeakMap,ye=new WeakSet,Le=function(t){if(n(this,k,e(this,k,"f")+t,"f"),e(this,k,"f").length>nt)n(this,k,e(this,k,"f").slice(e(this,k,"f").length-nt),"f"),n(this,ee,!0,"f");if(e(this,R,"f")&&e(this,k,"f").indexOf(e(this,R,"f").sentinel)>=0){let i=e(this,R,"f");n(this,R,null,"f"),i.resolve()}},a})();function ar(a){Y(a.unrestrictedPaths);let r,t=Promise.resolve();return C({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command:i,restart:o,timeout_ms:s},l)=>{let f=t,d=Ut();t=d.promise;try{await f}catch{}try{if(o)r?.close(),r=void 0;if(!i){if(o)return"bash session restarted";throw new E("bash: command is required")}r??(r=new sr(a.workdir,a.env));try{let{output:m,exitCode:h}=await r.exec(i,{timeoutMs:s??ft,signal:l?.signal});if(h!==0)throw new E(m||`exit ${h}`);return m}catch(m){if(m instanceof E)throw m;throw r.close(),r=void 0,new E(`bash: ${m instanceof Error?m.message:String(m)}`)}}finally{d.resolve()}},close:()=>{r?.close(),r=void 0}})}function cr(a){return Y(a.unrestrictedPaths),C({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path:r,view_range:t})=>{if(!r)throw new E("read: file_path is required");let i=await oe(a,r);if(t?.length&&t.length!==2)throw new E("read: view_range must be [start_line, end_line]");let o;try{let h=await S.stat(i);if(!h.isFile())throw new E(`read: ${r} is not a regular file`);let u=ht(a.maxFileBytes);if(u!==null&&h.size>u){if(!t?.length)throw new E(`read: ${r} is ${h.size} bytes, exceeds ${u}-byte limit. Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500].`);let[_,b]=t;return await lr(i,r,_,b,u)}o=await S.readFile(i,"utf8")}catch(h){if(h instanceof E)throw h;throw new E(`read: ${q(h,r)}`)}if(!t?.length)return o;let[s,l]=t,f=o.split(`
10
+ `;if(e(this,b,"f").stdin.write(f),e(this,v,"f").indexOf(s)<0){let{promise:E,resolve:D}=Ut();n(this,I,{sentinel:s,resolve:D},"f");let M,se;try{await Promise.race([E,new Promise((pt,Se)=>{M=setTimeout(()=>Se(new dt(i)),i)}),new Promise((pt,Se)=>{if(!o)return;se=()=>Se(o.reason),o.addEventListener("abort",se,{once:!0})})])}finally{if(M)clearTimeout(M);if(se&&o)o.removeEventListener("abort",se);n(this,I,null,"f")}}let d=e(this,v,"f").indexOf(s);if(d<0)throw new c("bash session terminated");let h=e(this,v,"f").slice(d+s.length).match(/^(-?\d+)/),u=h?parseInt(h[1],10):-1,_=e(this,v,"f").slice(0,d).replace(ir,"").replace(/\n+$/,"");if(e(this,ee,"f"))_=`[output truncated]
11
+ ${_}`;return{output:_,exitCode:u}}close(){if(e(this,W,"f"))return;n(this,W,!0,"f");let r=e(this,I,"f");n(this,I,null,"f"),r?.resolve(),e(this,b,"f").stdout.destroy(),e(this,b,"f").stderr.destroy(),e(this,b,"f").stdin.destroy();try{process.kill(-e(this,b,"f").pid,"SIGKILL")}catch{e(this,b,"f").kill("SIGKILL")}e(this,b,"f").unref()}}return b=new WeakMap,v=new WeakMap,ee=new WeakMap,W=new WeakMap,I=new WeakMap,ye=new WeakSet,Le=function(t){if(n(this,v,e(this,v,"f")+t,"f"),e(this,v,"f").length>nt)n(this,v,e(this,v,"f").slice(e(this,v,"f").length-nt),"f"),n(this,ee,!0,"f");if(e(this,I,"f")&&e(this,v,"f").indexOf(e(this,I,"f").sentinel)>=0){let i=e(this,I,"f");n(this,I,null,"f"),i.resolve()}},a})();function ar(a){Y(a.unrestrictedPaths);let r,t=Promise.resolve();return C({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command:i,restart:o,timeout_ms:s},l)=>{let f=t,d=Ut();t=d.promise;try{await f}catch{}try{if(o)r?.close(),r=void 0;if(!i){if(o)return"bash session restarted";throw new A("bash: command is required")}r??(r=new sr(a.workdir,a.env));try{let{output:m,exitCode:h}=await r.exec(i,{timeoutMs:s??ft,signal:l?.signal});if(h!==0)throw new A(m||`exit ${h}`);return m}catch(m){if(m instanceof A)throw m;throw r.close(),r=void 0,new A(`bash: ${m instanceof Error?m.message:String(m)}`)}}finally{d.resolve()}},close:()=>{r?.close(),r=void 0}})}function cr(a){return Y(a.unrestrictedPaths),C({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path:r,view_range:t})=>{if(!r)throw new A("read: file_path is required");let i=await oe(a,r);if(t?.length&&t.length!==2)throw new A("read: view_range must be [start_line, end_line]");let o;try{let h=await S.stat(i);if(!h.isFile())throw new A(`read: ${r} is not a regular file`);let u=ht(a.maxFileBytes);if(u!==null&&h.size>u){if(!t?.length)throw new A(`read: ${r} is ${h.size} bytes, exceeds ${u}-byte limit. Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500].`);let[_,E]=t;return await lr(i,r,_,E,u)}o=await S.readFile(i,"utf8")}catch(h){if(h instanceof A)throw h;throw new A(`read: ${q(h,r)}`)}if(!t?.length)return o;let[s,l]=t,f=o.split(`
12
12
  `),d=Math.max(0,s-1),m=l>0?l:f.length;return f.slice(d,m).join(`
13
- `)}})}async function lr(a,r,t,i,o){let s=new fr(r,t,i,o);if(s.rangeIsEmpty())return"";let l=ne.createReadStream(a,{highWaterMark:er});try{for await(let f of l)if(s.collectFrom(f),s.rangeIsCollected())break}finally{l.destroy()}return s.text()}var fr=(()=>{class a{constructor(r,t,i,o){we.add(this),te.set(this,void 0),_e.set(this,void 0),ge.set(this,void 0),U.set(this,void 0),j.set(this,void 0),V.set(this,void 0),B.set(this,0),re.set(this,[]),A.set(this,0),n(this,te,r,"f"),n(this,_e,t,"f"),n(this,ge,i,"f"),n(this,U,Math.max(0,t-1),"f"),n(this,j,i>0?i:1/0,"f"),n(this,V,o,"f")}rangeIsEmpty(){return e(this,j,"f")<=e(this,U,"f")}rangeIsCollected(){return e(this,B,"f")>=e(this,j,"f")}collectFrom(r){var t;let i=0;while(i<r.length&&!this.rangeIsCollected()){let o=r.indexOf(10,i),s=o<0?r.length:o;if(e(this,B,"f")>=e(this,U,"f"))e(this,we,"m",rt).call(this,r.subarray(i,s),o>=0);if(o<0)break;n(this,B,(t=e(this,B,"f"),t++,t),"f"),i=o+1}}text(){return Buffer.concat(e(this,re,"f"),e(this,A,"f")).toString("utf8")}}return te=new WeakMap,_e=new WeakMap,ge=new WeakMap,U=new WeakMap,j=new WeakMap,V=new WeakMap,B=new WeakMap,re=new WeakMap,A=new WeakMap,we=new WeakSet,rt=function(t,i){if(e(this,re,"f").push(t),n(this,A,e(this,A,"f")+t.length,"f"),i&&e(this,B,"f")+1<e(this,j,"f"))e(this,re,"f").push(ot),n(this,A,e(this,A,"f")+ot.length,"f");if(e(this,A,"f")>e(this,V,"f"))throw e(this,we,"m",it).call(this)},it=function(){if(e(this,j,"f")-e(this,U,"f")===1)return new E(`read: line ${e(this,U,"f")+1} of ${e(this,te,"f")} alone exceeds ${e(this,V,"f")}-byte limit. The read tool cannot return part of a line, so view_range cannot narrow this further.`);return new E(`read: view_range [${e(this,_e,"f")}, ${e(this,ge,"f")}] of ${e(this,te,"f")} exceeds ${e(this,V,"f")}-byte limit. Narrow the view_range to read a smaller portion.`)},a})();function dr(a){return Y(a.unrestrictedPaths),C({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path:r,content:t})=>{if(!r)throw new E("write: file_path is required");let i=await oe(a,r),o=await mt(a,i);if(o!==void 0)throw new E(`write: ${r} is inside read-only directory ${o}`);try{await S.mkdir(M.dirname(i),{recursive:!0,mode:J}),await be(i,t??"")}catch(s){throw new E(`write: ${q(s,r)}`)}return`wrote ${Buffer.byteLength(t??"")} bytes to ${r}`}})}function hr(a){return Y(a.unrestrictedPaths),C({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path:r,old_string:t,new_string:i,replace_all:o})=>{if(!r)throw new E("edit: file_path is required");if(!t)throw new E("edit: old_string is required");let s=await oe(a,r),l=await mt(a,s);if(l!==void 0)throw new E(`edit: ${r} is inside read-only directory ${l}`);let f;try{let h=await S.stat(s);if(!h.isFile())throw new E(`edit: ${r} is not a regular file`);let u=ht(a.maxFileBytes);if(u!==null&&h.size>u)throw new E(`edit: ${r} is ${h.size} bytes, exceeds ${u}-byte limit. The edit tool loads the whole file and cannot modify a file this large.`);f=await S.readFile(s,"utf8")}catch(h){if(h instanceof E)throw h;throw new E(`edit: ${q(h,r)}`)}let d=f.split(t).length-1;if(d===0)throw new E(`edit: old_string not found in ${r}`);let m;if(o)m=f.split(t).join(i);else{if(d>1)throw new E(`edit: old_string appears ${d} times in ${r} (must be unique)`);m=f.replace(t,()=>i)}try{await be(s,m)}catch(h){throw new E(`edit: write: ${q(h,r)}`)}return`edited ${r} (${o?d:1} replacement(s))`}})}function mr(a){return a.split(/[\\/{},]/).includes("..")}function ur(a){return Y(a.unrestrictedPaths),C({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern:r,path:t})=>{if(!r)throw new E("glob: pattern is required");if(M.isAbsolute(r))throw new E("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(mr(r))throw new E('glob: ".." is not permitted in the pattern');let i=t?await oe(a,t):M.resolve(a.workdir),o=t?i:await X(i),s=[],l=ut;try{for await(let f of nr(r,{cwd:i,withFileTypes:!0,exclude:(d)=>d.name===".git"||d.name==="node_modules"})){if(l--<=0)break;if(!f.isFile())continue;let d=M.join(f.parentPath,f.name),m;try{m=await S.realpath(d)}catch{continue}if(!ae(o,m))continue;let h=0;try{h=(await S.stat(d)).mtimeMs}catch{}s.push({path:d,mtime:h})}}catch(f){throw new E(`glob: ${f instanceof Error?f.message:String(f)}`)}if(s.length===0)return"no matches";return s.sort((f,d)=>d.mtime-f.mtime),s.slice(0,rr).map((f)=>f.path).join(`
14
- `)}})}function pr(a){return Y(a.unrestrictedPaths),C({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern:r,path:t},i)=>{if(!r)throw new E("grep: pattern is required");let o=M.resolve(a.workdir);if(t)o=await oe(a,t);let s=await Sr();return s?yr(s,r,o,i?.signal):wr(r,o,i?.signal)}})}function yr(a,r,t,i){return new Promise((o,s)=>{let l=$e.spawn(a,["-n","--no-heading","-e",r,"--",t],{...i?{signal:i}:{}}),f="",d="",m=!1;l.stdout.on("data",(h)=>{if(m)return;if(f+=h,f.length>ie)m=!0,f=f.slice(0,ie),l.kill("SIGKILL")}),l.stderr.on("data",(h)=>d+=h),l.on("close",(h)=>{if(i?.aborted)return s(new E("grep: aborted"));if(m)return o(f+`
15
- [output truncated at ${ie} bytes]`);if(h===0)return o(f);if(h===1)return o("no matches");s(new E(`grep: rg failed: ${d||`exit ${h}`}`))}),l.on("error",(h)=>{if(i?.aborted)return s(new E("grep: aborted"));s(new E(`grep: rg failed: ${h.message}`))})})}async function wr(a,r,t){let i;try{i=new RegExp(a)}catch(d){throw new E(`grep: invalid regex: ${d instanceof Error?d.message:String(d)}`)}let o=[],s=ie,l=(d)=>{if(s-=d.length+1,s<0)return o.push(`[output truncated at ${ie} bytes]`),!1;return o.push(d),!0};if((await S.stat(r).catch(()=>null))?.isFile())await at(r,i,l);else await gr(r,"",(d)=>at(M.join(r,d),i,l),t);if(t?.aborted)throw new E("grep: aborted");if(o.length===0)return"no matches";return o.join(`
16
- `)}async function at(a,r,t){let i=ne.createReadStream(a,{encoding:"utf8"}),o=lt.createInterface({input:i,crlfDelay:1/0}),s=0;try{for await(let l of o){if(s++,l.length>tr)continue;if(r.test(l)&&!t(`${a}:${s}:${l}`))return!1}}catch{}finally{i.destroy()}return!0}var _r=40,ut=50000;async function gr(a,r,t,i){let o=ut;async function s(l,f){if(f>_r)return!0;if(i?.aborted)return!1;let d;try{d=await S.readdir(M.join(a,l),{withFileTypes:!0})}catch{return!0}for(let m of d){if(m.name===".git"||m.name==="node_modules")continue;if(o--<=0)return!1;if(i?.aborted)return!1;let h=l?M.join(l,m.name):m.name;if(m.isDirectory()){if(!await s(h,f+1))return!1}else if(m.isFile()){if(await t(h)===!1)return!1}}return!0}await s(r,0)}async function Sr(){let a=(process.env.PATH??"").split(M.delimiter);for(let r of a){let t=M.join(r,"rg");try{return await S.access(t,ne.constants.X_OK),t}catch{}}return null}export{Yt as MEMORY_FLUSH_TIMEOUT_MS,P as SessionMemoryError,Jt as SessionMemoryStores,Xr as betaAgentToolset20260401,gt as setupSkills};
13
+ `)}})}async function lr(a,r,t,i,o){let s=new fr(r,t,i,o);if(s.rangeIsEmpty())return"";let l=ne.createReadStream(a,{highWaterMark:er});try{for await(let f of l)if(s.collectFrom(f),s.rangeIsCollected())break}finally{l.destroy()}return s.text()}var fr=(()=>{class a{constructor(r,t,i,o){we.add(this),te.set(this,void 0),_e.set(this,void 0),ge.set(this,void 0),U.set(this,void 0),j.set(this,void 0),V.set(this,void 0),B.set(this,0),re.set(this,[]),L.set(this,0),n(this,te,r,"f"),n(this,_e,t,"f"),n(this,ge,i,"f"),n(this,U,Math.max(0,t-1),"f"),n(this,j,i>0?i:1/0,"f"),n(this,V,o,"f")}rangeIsEmpty(){return e(this,j,"f")<=e(this,U,"f")}rangeIsCollected(){return e(this,B,"f")>=e(this,j,"f")}collectFrom(r){var t;let i=0;while(i<r.length&&!this.rangeIsCollected()){let o=r.indexOf(10,i),s=o<0?r.length:o;if(e(this,B,"f")>=e(this,U,"f"))e(this,we,"m",rt).call(this,r.subarray(i,s),o>=0);if(o<0)break;n(this,B,(t=e(this,B,"f"),t++,t),"f"),i=o+1}}text(){return Buffer.concat(e(this,re,"f"),e(this,L,"f")).toString("utf8")}}return te=new WeakMap,_e=new WeakMap,ge=new WeakMap,U=new WeakMap,j=new WeakMap,V=new WeakMap,B=new WeakMap,re=new WeakMap,L=new WeakMap,we=new WeakSet,rt=function(t,i){if(e(this,re,"f").push(t),n(this,L,e(this,L,"f")+t.length,"f"),i&&e(this,B,"f")+1<e(this,j,"f"))e(this,re,"f").push(ot),n(this,L,e(this,L,"f")+ot.length,"f");if(e(this,L,"f")>e(this,V,"f"))throw e(this,we,"m",it).call(this)},it=function(){if(e(this,j,"f")-e(this,U,"f")===1)return new A(`read: line ${e(this,U,"f")+1} of ${e(this,te,"f")} alone exceeds ${e(this,V,"f")}-byte limit. The read tool cannot return part of a line, so view_range cannot narrow this further.`);return new A(`read: view_range [${e(this,_e,"f")}, ${e(this,ge,"f")}] of ${e(this,te,"f")} exceeds ${e(this,V,"f")}-byte limit. Narrow the view_range to read a smaller portion.`)},a})();function dr(a){return Y(a.unrestrictedPaths),C({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path:r,content:t})=>{if(!r)throw new A("write: file_path is required");let i=await oe(a,r),o=await mt(a,i);if(o!==void 0)throw new A(`write: ${r} is inside read-only directory ${o}`);try{await S.mkdir(O.dirname(i),{recursive:!0,mode:J}),await be(i,t??"")}catch(s){throw new A(`write: ${q(s,r)}`)}return`wrote ${Buffer.byteLength(t??"")} bytes to ${r}`}})}function hr(a){return Y(a.unrestrictedPaths),C({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path:r,old_string:t,new_string:i,replace_all:o})=>{if(!r)throw new A("edit: file_path is required");if(!t)throw new A("edit: old_string is required");let s=await oe(a,r),l=await mt(a,s);if(l!==void 0)throw new A(`edit: ${r} is inside read-only directory ${l}`);let f;try{let h=await S.stat(s);if(!h.isFile())throw new A(`edit: ${r} is not a regular file`);let u=ht(a.maxFileBytes);if(u!==null&&h.size>u)throw new A(`edit: ${r} is ${h.size} bytes, exceeds ${u}-byte limit. The edit tool loads the whole file and cannot modify a file this large.`);f=await S.readFile(s,"utf8")}catch(h){if(h instanceof A)throw h;throw new A(`edit: ${q(h,r)}`)}let d=f.split(t).length-1;if(d===0)throw new A(`edit: old_string not found in ${r}`);let m;if(o)m=f.split(t).join(i);else{if(d>1)throw new A(`edit: old_string appears ${d} times in ${r} (must be unique)`);m=f.replace(t,()=>i)}try{await be(s,m)}catch(h){throw new A(`edit: write: ${q(h,r)}`)}return`edited ${r} (${o?d:1} replacement(s))`}})}function mr(a){return a.split(/[\\/{},]/).includes("..")}function ur(a){return Y(a.unrestrictedPaths),C({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern:r,path:t})=>{if(!r)throw new A("glob: pattern is required");if(O.isAbsolute(r))throw new A("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(mr(r))throw new A('glob: ".." is not permitted in the pattern');let i=t?await oe(a,t):O.resolve(a.workdir),o=t?i:await X(i),s=[],l=ut;try{for await(let f of nr(r,{cwd:i,withFileTypes:!0,exclude:(d)=>d.name===".git"||d.name==="node_modules"})){if(l--<=0)break;if(!f.isFile())continue;let d=O.join(f.parentPath,f.name),m;try{m=await S.realpath(d)}catch{continue}if(!ae(o,m))continue;let h=0;try{h=(await S.stat(d)).mtimeMs}catch{}s.push({path:d,mtime:h})}}catch(f){throw new A(`glob: ${f instanceof Error?f.message:String(f)}`)}if(s.length===0)return"no matches";return s.sort((f,d)=>d.mtime-f.mtime),s.slice(0,rr).map((f)=>f.path).join(`
14
+ `)}})}function pr(a){return Y(a.unrestrictedPaths),C({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern:r,path:t},i)=>{if(!r)throw new A("grep: pattern is required");let o=O.resolve(a.workdir);if(t)o=await oe(a,t);let s=await Sr();return s?yr(s,r,o,i?.signal):wr(r,o,i?.signal)}})}function yr(a,r,t,i){return new Promise((o,s)=>{let l=$e.spawn(a,["-n","--no-heading","-e",r,"--",t],{...i?{signal:i}:{}}),f="",d="",m=!1;l.stdout.on("data",(h)=>{if(m)return;if(f+=h,f.length>ie)m=!0,f=f.slice(0,ie),l.kill("SIGKILL")}),l.stderr.on("data",(h)=>d+=h),l.on("close",(h)=>{if(i?.aborted)return s(new A("grep: aborted"));if(m)return o(f+`
15
+ [output truncated at ${ie} bytes]`);if(h===0)return o(f);if(h===1)return o("no matches");s(new A(`grep: rg failed: ${d||`exit ${h}`}`))}),l.on("error",(h)=>{if(i?.aborted)return s(new A("grep: aborted"));s(new A(`grep: rg failed: ${h.message}`))})})}async function wr(a,r,t){let i;try{i=new RegExp(a)}catch(d){throw new A(`grep: invalid regex: ${d instanceof Error?d.message:String(d)}`)}let o=[],s=ie,l=(d)=>{if(s-=d.length+1,s<0)return o.push(`[output truncated at ${ie} bytes]`),!1;return o.push(d),!0};if((await S.stat(r).catch(()=>null))?.isFile())await at(r,i,l);else await gr(r,"",(d)=>at(O.join(r,d),i,l),t);if(t?.aborted)throw new A("grep: aborted");if(o.length===0)return"no matches";return o.join(`
16
+ `)}async function at(a,r,t){let i=ne.createReadStream(a,{encoding:"utf8"}),o=lt.createInterface({input:i,crlfDelay:1/0}),s=0;try{for await(let l of o){if(s++,l.length>tr)continue;if(r.test(l)&&!t(`${a}:${s}:${l}`))return!1}}catch{}finally{i.destroy()}return!0}var _r=40,ut=50000;async function gr(a,r,t,i){let o=ut;async function s(l,f){if(f>_r)return!0;if(i?.aborted)return!1;let d;try{d=await S.readdir(O.join(a,l),{withFileTypes:!0})}catch{return!0}for(let m of d){if(m.name===".git"||m.name==="node_modules")continue;if(o--<=0)return!1;if(i?.aborted)return!1;let h=l?O.join(l,m.name):m.name;if(m.isDirectory()){if(!await s(h,f+1))return!1}else if(m.isFile()){if(await t(h)===!1)return!1}}return!0}await s(r,0)}async function Sr(){let a=(process.env.PATH??"").split(O.delimiter);for(let r of a){let t=O.join(r,"rg");try{return await S.access(t,ne.constants.X_OK),t}catch{}}return null}export{Yt as MEMORY_FLUSH_TIMEOUT_MS,P as SessionMemoryError,Jt as SessionMemoryStores,Xr as betaAgentToolset20260401,gt as setupSkills};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- function r(e){let t=e[e.length-1];return t&&t.role!=="user"?"agent":"user"}function At(e){return e.some((t)=>{if(t.role==="user"&&Array.isArray(t.content))return t.content.some((n)=>n.type==="image");if(t.role==="toolResult"&&Array.isArray(t.content))return t.content.some((n)=>n.type==="image");return!1})}function Et(e){let t={"X-Initiator":r(e.messages),"Openai-Intent":"conversation-edits"};if(e.hasImages)t["Copilot-Vision-Request"]="true";return t}
3
- export{At,Et};
2
+ function r(e){let t=e[e.length-1];return t&&t.role!=="user"?"agent":"user"}function _t(e){return e.some((t)=>{if(t.role==="user"&&Array.isArray(t.content))return t.content.some((n)=>n.type==="image");if(t.role==="toolResult"&&Array.isArray(t.content))return t.content.some((n)=>n.type==="image");return!1})}function At(e){let t={"X-Initiator":r(e.messages),"Openai-Intent":"conversation-edits"};if(e.hasImages)t["Copilot-Vision-Request"]="true";return t}
3
+ export{_t,At};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Xt}from"./chunk-vv7fp27r.js";var y=Promise.resolve(),M=60000,T=1e4,E=(r)=>r instanceof Error?r.message:String(r);function R(){return new Worker(new URL("./ui-test-worker.js",import.meta.url))}function I(r,e,t){if(!Number.isInteger(e)||e<1||e>t)throw Error(`${r} must be between 1 and ${t}`)}async function kn(r,e,t={}){let l=t.timeoutMs??M,u=t.importTimeoutMs??T;I("timeoutMs",l,M),I("importTimeoutMs",u,T);let i=y,p=Promise.withResolvers();y=i.then(()=>p.promise);let o=new AbortController,n=t.signal?AbortSignal.any([t.signal,o.signal]):o.signal,g,b,f,w=new Map,c=Promise.withResolvers(),k=()=>c.reject(n.reason??Error("UI test cancelled"));n.addEventListener("abort",k,{once:!0});async function h(d,s){let m=new AbortController;w.set(s.id,m);try{if(!t.runtime)throw Error("API unavailable during module inspection");let a=await Xt(t.runtime,s.input,AbortSignal.any([n,m.signal]));if(!n.aborted)d.postMessage({type:"response",id:s.id,response:a})}catch(a){if(!n.aborted)d.postMessage({type:"response",id:s.id,error:E(a)})}finally{w.delete(s.id)}}try{n.throwIfAborted(),f=setTimeout(()=>o.abort(Error(`UI execution timed out after ${l}ms`)),l),await Promise.race([i,c.promise]),n.throwIfAborted();let d=typeof r==="string"?{source:r,css:t.css}:await Promise.race([r(),c.promise.then(()=>{throw Error("Worker finished before startup")})]);n.throwIfAborted();let s=R();return g=s,s.onerror=(m)=>c.reject(Error(m.message)),s.onmessage=(m)=>{let a=m.data;switch(a.type){case"importing":b=setTimeout(()=>o.abort(Error(`UI import timed out after ${u}ms`)),u);break;case"imported":clearTimeout(b);break;case"done":c.resolve(a.result);break;case"error":c.reject(Error(a.error));break;case"cancel":w.get(a.id)?.abort();break;case"request":h(s,a);break}},s.postMessage({type:"start",...d,id:e,input:t.input}),await c.promise}finally{clearTimeout(f),clearTimeout(b),n.removeEventListener("abort",k),o.abort();for(let d of w.values())d.abort();g?.terminate(),p.resolve()}}async function Ri(r,e,t){t?.throwIfAborted();let l=r.plugins.list().find((o)=>o.id===e.id);if(l?.status!=="enabled")throw Error("Load and enable the plugin before ui_test");if([e.slot,e.view,e.codeBlock].filter(Boolean).length!==1)throw Error("ui_test requires exactly one of slot, view or codeBlock");let u=e.view?l.web?.find((o)=>o.view===e.view):void 0;if(e.view&&u&&e.kind&&u.kind!==e.kind)throw Error(`View kind mismatch: expected ${u.kind}, got ${e.kind}`);let i=e.kind??u?.kind;if(i!==void 0&&i!=="page"&&i!=="tab"&&i!=="card"&&i!=="sidebar")throw Error(`Unsupported view kind: ${i}`);let p=await kn(async()=>{let o=await r.plugins.webBundle(e.id);if(!o)throw Error("Plugin has no dynamic Web bundle");let n=await r.plugins.webCSS(e.id);return{source:o,css:n}},e.id,{input:{...e,kind:i},runtime:r,signal:t,timeoutMs:e.timeoutMs,importTimeoutMs:e.importTimeoutMs});if(!("steps"in p))throw Error("Worker returned an invalid UI report");return p}
3
- export{kn,Ri};
2
+ import{Jt}from"./chunk-8mezk0cb.js";var y=Promise.resolve(),M=60000,T=1e4,E=(r)=>r instanceof Error?r.message:String(r);function R(){return new Worker(new URL("./ui-test-worker.js",import.meta.url))}function I(r,e,t){if(!Number.isInteger(e)||e<1||e>t)throw Error(`${r} must be between 1 and ${t}`)}async function Rn(r,e,t={}){let l=t.timeoutMs??M,u=t.importTimeoutMs??T;I("timeoutMs",l,M),I("importTimeoutMs",u,T);let i=y,p=Promise.withResolvers();y=i.then(()=>p.promise);let o=new AbortController,n=t.signal?AbortSignal.any([t.signal,o.signal]):o.signal,g,b,f,w=new Map,c=Promise.withResolvers(),k=()=>c.reject(n.reason??Error("UI test cancelled"));n.addEventListener("abort",k,{once:!0});async function h(d,s){let m=new AbortController;w.set(s.id,m);try{if(!t.runtime)throw Error("API unavailable during module inspection");let a=await Jt(t.runtime,s.input,AbortSignal.any([n,m.signal]));if(!n.aborted)d.postMessage({type:"response",id:s.id,response:a})}catch(a){if(!n.aborted)d.postMessage({type:"response",id:s.id,error:E(a)})}finally{w.delete(s.id)}}try{n.throwIfAborted(),f=setTimeout(()=>o.abort(Error(`UI execution timed out after ${l}ms`)),l),await Promise.race([i,c.promise]),n.throwIfAborted();let d=typeof r==="string"?{source:r,css:t.css}:await Promise.race([r(),c.promise.then(()=>{throw Error("Worker finished before startup")})]);n.throwIfAborted();let s=R();return g=s,s.onerror=(m)=>c.reject(Error(m.message)),s.onmessage=(m)=>{let a=m.data;switch(a.type){case"importing":b=setTimeout(()=>o.abort(Error(`UI import timed out after ${u}ms`)),u);break;case"imported":clearTimeout(b);break;case"done":c.resolve(a.result);break;case"error":c.reject(Error(a.error));break;case"cancel":w.get(a.id)?.abort();break;case"request":h(s,a);break}},s.postMessage({type:"start",...d,id:e,input:t.input}),await c.promise}finally{clearTimeout(f),clearTimeout(b),n.removeEventListener("abort",k),o.abort();for(let d of w.values())d.abort();g?.terminate(),p.resolve()}}async function Ii(r,e,t){t?.throwIfAborted();let l=r.plugins.list().find((o)=>o.id===e.id);if(l?.status!=="enabled")throw Error("Load and enable the plugin before ui_test");if([e.slot,e.view,e.codeBlock].filter(Boolean).length!==1)throw Error("ui_test requires exactly one of slot, view or codeBlock");let u=e.view?l.web?.find((o)=>o.view===e.view):void 0;if(e.view&&u&&e.kind&&u.kind!==e.kind)throw Error(`View kind mismatch: expected ${u.kind}, got ${e.kind}`);let i=e.kind??u?.kind;if(i!==void 0&&i!=="page"&&i!=="tab"&&i!=="card"&&i!=="sidebar")throw Error(`Unsupported view kind: ${i}`);let p=await Rn(async()=>{let o=await r.plugins.webBundle(e.id);if(!o)throw Error("Plugin has no dynamic Web bundle");let n=await r.plugins.webCSS(e.id);return{source:o,css:n}},e.id,{input:{...e,kind:i},runtime:r,signal:t,timeoutMs:e.timeoutMs,importTimeoutMs:e.importTimeoutMs});if(!("steps"in p))throw Error("Worker returned an invalid UI report");return p}
3
+ export{Rn,Ii};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{F}from"./chunk-m8vkwdgr.js";import{wr}from"./chunk-2hbfk5xd.js";import{Ze}from"./chunk-g2t6t8fk.js";import{ee}from"./chunk-tvm4zmgj.js";import{me,ce,V,he}from"./chunk-whvj83b7.js";import{g}from"./chunk-n6e43rvk.js";import{z}from"./chunk-x4874m8e.js";import{N,Me,ne,re,Q,H}from"./chunk-8wc8qdx8.js";import{M}from"./chunk-shadcb9z.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 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=K(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?H(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 Ze(o).replace(/[^a-zA-Z0-9]/g,"").slice(0,S)}function K(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}): ${W(r,U)}`;if(n!==void 0)return`Mistral API error (${n}): ${t.message}`;return t.message}return q(t)}function W(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 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=G(t,n,r),f=r?.timeoutMs??60000,u=AbortSignal.timeout(f),a=wr([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 G(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=g(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((y)=>y.text??"").filter((y)=>y.length>0).join(""),_=g(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=g(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),y;if(_!==void 0){let R=e.content[_];if(R?.type==="toolCall")y=R}if(!y)y={type:"toolCall",id:h,name:p.function.name,arguments:{},partialArgs:""},e.content.push(y),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||{});y.partialArgs=(y.partialArgs||"")+C,y.arguments=F(y.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=F(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:g(a)});continue}if(o.role==="user"){if(typeof o.content==="string"){n.push({role:"user",content:g(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:g(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:g(d.text)});continue}if(d.type==="thinking"){if(d.thinking.trim().length>0)a.push({type:"thinking",thinking:[{type:"text",text:g(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"?g(a.text):"").join(`
2
+ import{W}from"./chunk-r0jc8e7t.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-3c330qna.js";import{y}from"./chunk-3k627vf2.js";import{z}from"./chunk-x4874m8e.js";import{N,Me,ne,re,Q,G}from"./chunk-7qq99360.js";import{M}from"./chunk-nx3jnbv8.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(`
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
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};
@@ -1,12 +1,12 @@
1
1
  // @bun
2
- import{F}from"./chunk-m8vkwdgr.js";import{Ze}from"./chunk-g2t6t8fk.js";import{me,Lr,Or,ce,Jt,he}from"./chunk-whvj83b7.js";import{g}from"./chunk-n6e43rvk.js";import{N,Me,re,ye,Q}from"./chunk-8wc8qdx8.js";function j(a,o){let l={v:1,id:a};if(o)l.phase=o;return JSON.stringify(l)}function E(a){if(!a)return;if(a.startsWith("{"))try{let o=JSON.parse(a);if(o.v===1&&typeof o.id==="string"){if(o.phase==="commentary"||o.phase==="final_answer")return{id:o.id,phase:o.phase};return{id:o.id}}}catch{}return{id:a}}function W(a,o){let l=o.filter((c)=>c.type==="text").map((c)=>c.text).join(`
3
- `),d=o.filter((c)=>c.type==="image"),u=l.length>0;if(d.length===0||!a.input.includes("image"))return g(u?l:d.length>0?"(see attached image)":"(no tool output)");let p=[];if(u)p.push({type:"input_text",text:g(l)});for(let c of d)p.push({type:"input_image",detail:"auto",image_url:`data:${c.mimeType};base64,${c.data}`});return p}function at(a,o,l,d){let u=re(o,d?.supportsMidConvoSystemMessages),p=[],c=(n)=>{let s=n.replace(/[^a-zA-Z0-9_-]/g,"_");return(s.length>64?s.slice(0,64):s).replace(/_+$/,"")},b=(n)=>{let s=`fc_${Ze(n)}`;return s.length>64?s.slice(0,64):s},k=(n,s,i)=>{if(!l.has(a.provider))return c(n);if(!n.includes("|"))return c(n);let[r,_]=n.split("|"),y=c(r),x=i.provider!==a.provider||i.api!==a.api?b(_):c(_);if(!x.startsWith("fc_"))x=c(`fc_${x}`);return`${y}|${x}`},m=he(u.messages,a,k),I=ye(u.messages,(d?.supportsAdditionalTools??!1)||(d?.supportsToolSearch??!1)),v=(n,s)=>{let i=I.anchorsAdditions?n.toolsAdded??[]:[];if(i.length===0)return;if(d?.supportsAdditionalTools){p.push({type:"additional_tools",role:"developer",tools:Je(i,d.toolOptions)});return}if(!d?.supportsToolSearch)return;let r=i.map((y)=>y.name),_=`pi_tool_load_${Ze(`${s}:${r.join(",")}`)}`;p.push({type:"tool_search_call",call_id:_,execution:"client",status:"completed",arguments:{query:r.join(" "),limit:r.length}}),p.push({type:"tool_search_output",call_id:_,execution:"client",status:"completed",tools:Je(i,{...d.toolOptions,toolSearchResult:!0})})},C=d?.includeSystemPrompt??!0,w=a.compat,M=a.reasoning&&w?.supportsDeveloperRole!==!1?"developer":"system",t=0,e=0;for(let n of m){let s=e++===0&&n.role==="system";if(n.role==="system"){if(!s)v(n,`system:${t}`);if(!s||C){let i=s?N(n):Me(n);if(i.length>0)p.push({role:M,content:g(i)})}}else if(n.role==="user")if(typeof n.content==="string")p.push({role:"user",content:[{type:"input_text",text:g(n.content)}]});else{let i=n.content.map((r)=>{if(r.type==="text")return{type:"input_text",text:g(r.text)};return{type:"input_image",detail:"auto",image_url:`data:${r.mimeType};base64,${r.data}`}});if(i.length===0)continue;p.push({role:"user",content:i})}else if(n.role==="assistant"){let i=[],r=n,_=r.provider===a.provider&&r.api===a.api,y=_&&r.model===a.id,P=_&&r.model!==a.id,x=0;for(let S of n.content)if(S.type==="thinking"){if(S.thinkingSignature){let f=JSON.parse(S.thinkingSignature);i.push(f)}}else if(S.type==="text"){let f=S,T=E(f.textSignature),J=x===0?`msg_pi_${t}`:`msg_pi_${t}_${x}`;x++;let h=T?.id;if(!h)h=J;else if(h.length>64)h=`msg_${Ze(h)}`;i.push({type:"message",role:"assistant",content:[{type:"output_text",text:g(f.text),annotations:[]}],status:"completed",id:h,phase:T?.phase})}else if(S.type==="toolCall"){let f=S,[T,J]=f.id.split("|"),h=d?.grammarToolInputProperties?.get(f.name),R=J,A=h===void 0?"fc_":"ctc_";if(P||!R?.startsWith(A))R=void 0;if(h!==void 0)i.push({type:"custom_tool_call",id:R,call_id:T,name:f.name,input:g(Lr(f.name,f.arguments,h)),...y&&f.namespace!==void 0?{namespace:f.namespace}:{}});else i.push({type:"function_call",id:R,call_id:T,name:f.name,arguments:JSON.stringify(f.arguments),...y&&f.namespace!==void 0?{namespace:f.namespace}:{}})}if(i.length===0)continue;p.push(...i)}else if(n.role==="toolResult"){let[i]=n.toolCallId.split("|"),r=W(a,n.content);if(d?.grammarToolInputProperties?.has(n.toolName))p.push({type:"custom_tool_call_output",call_id:i,output:r});else p.push({type:"function_call_output",call_id:i,output:r})}if(!s)t++}return p}function Je(a,o){let l=o?.strict===void 0?!1:o.strict,d=o?.supportsStrictMode??!0,u=o?.supportsOpenAIGrammarTools??!1;return a.map((p)=>{let c=Jt(p,u);if(c)return{type:"custom",name:p.name,description:p.description,format:{type:"grammar",syntax:c.format,definition:c.definition},...o?.toolSearchResult?{defer_loading:!0}:{}};let k=ce(p,d)??l,m={type:"function",name:p.name,description:p.description,parameters:me(p,k===!0),...o?.toolSearchResult?{defer_loading:!0}:{}};if(d)m.strict=k;return m})}function z(a){let o=a.customInput?.property;if(o===void 0)return"";let l=a.arguments[o];return typeof l==="string"?l:""}function O(a,o,l){let d=a.customInput;if(!d)return;let u=Or(d.jsonBuffer,d.property,o,l);return a.arguments={[d.property]:o},u}async function lt(a,o,l,d,u){let p=!1,c=new Map,b=new Map,k=(t)=>{if(t.type==="message"&&t.phase==="final_answer")o.stopReason="stop"},m=(t,e)=>{let n=c.get(t);return n?.type===e?n:void 0},I=(t,e)=>{if(e===void 0)return;l.push({type:"toolcall_delta",contentIndex:t.contentIndex,delta:e,partial:o})},v=(t,e)=>{if(e.type==="reasoning"){let n={type:"thinking",thinking:""};o.content.push(n);let s={type:"thinking",block:n,contentIndex:o.content.length-1};return c.set(t,s),l.push({type:"thinking_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="message"){k(e);let n={type:"text",text:""};o.content.push(n);let s={type:"text",block:n,contentIndex:o.content.length-1};return c.set(t,s),l.push({type:"text_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="function_call"){let n={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},...e.namespace!==void 0?{namespace:e.namespace}:{},partialJson:e.arguments||""};o.content.push(n);let s={type:"toolCall",block:n,contentIndex:o.content.length-1};return c.set(t,s),l.push({type:"toolcall_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="custom_tool_call"){let n=u?.grammarToolInputProperties?.get(e.name)??"input",s=e.input||"",i={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{[n]:s},...e.namespace!==void 0?{namespace:e.namespace}:{},customInput:{property:n,jsonBuffer:{input:"",started:!1,closed:!1}}};o.content.push(i);let r={type:"toolCall",block:i,contentIndex:o.content.length-1};return c.set(t,r),l.push({type:"toolcall_start",contentIndex:r.contentIndex,partial:o}),r}return},C=(t,e)=>c.get(t)??v(t,e),w=(t)=>{for(let e of t){if(e.type!=="reasoning"||!e.encrypted_content)continue;let n=b.get(e.id);if(!n?.thinkingSignature)continue;let s=JSON.parse(n.thinkingSignature);if(s.encrypted_content)continue;n.thinkingSignature=JSON.stringify({...s,encrypted_content:e.encrypted_content})}},M=(t)=>{if(p=!0,w(t.output??[]),t?.id)o.responseId=t.id;if(t?.usage){let r=t.usage.input_tokens_details,_=r?.cached_tokens||0,y=r?.cache_write_tokens||0;o.usage={input:Math.max(0,(t.usage.input_tokens||0)-_-y),output:t.usage.output_tokens||0,cacheRead:_,cacheWrite:y,reasoning:t.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(Q(d,o.usage),u?.applyServiceTierPricing){let r=u.resolveServiceTier?u.resolveServiceTier(t?.service_tier,u.serviceTier):t?.service_tier??u.serviceTier;u.applyServiceTierPricing(o.usage,r)}let e=t?.status,n=t?.incomplete_details,s=typeof n?.reason==="string"?n.reason:void 0;o.rawStopReason=s?`${e}.${s}`:e;let i=B(e,s);if(o.stopReason=i.stopReason,i.errorMessage===void 0)delete o.errorMessage;else o.errorMessage=i.errorMessage;if(o.content.some((r)=>r.type==="toolCall")&&o.stopReason==="stop")o.stopReason="toolUse"};for await(let t of a)if(await u?.onProviderStreamEvent?.(t,d),t.type==="response.created")o.responseId=t.response.id;else if(t.type==="response.output_item.added")v(t.output_index,t.item);else if(t.type==="response.reasoning_summary_text.delta"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,l.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.reasoning_summary_part.done"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=`
2
+ import{W}from"./chunk-r0jc8e7t.js";import{Ye}from"./chunk-7jezts2n.js";import{me,Or,Nr,ce,Yt,he}from"./chunk-3c330qna.js";import{y}from"./chunk-3k627vf2.js";import{N,Me,re,ye,Q}from"./chunk-7qq99360.js";function j(a,o){let l={v:1,id:a};if(o)l.phase=o;return JSON.stringify(l)}function E(a){if(!a)return;if(a.startsWith("{"))try{let o=JSON.parse(a);if(o.v===1&&typeof o.id==="string"){if(o.phase==="commentary"||o.phase==="final_answer")return{id:o.id,phase:o.phase};return{id:o.id}}}catch{}return{id:a}}function B(a,o){let l=o.filter((c)=>c.type==="text").map((c)=>c.text).join(`
3
+ `),d=o.filter((c)=>c.type==="image"),u=l.length>0;if(d.length===0||!a.input.includes("image"))return y(u?l:d.length>0?"(see attached image)":"(no tool output)");let p=[];if(u)p.push({type:"input_text",text:y(l)});for(let c of d)p.push({type:"input_image",detail:"auto",image_url:`data:${c.mimeType};base64,${c.data}`});return p}function at(a,o,l,d){let u=re(o,d?.supportsMidConvoSystemMessages),p=[],c=(n)=>{let s=n.replace(/[^a-zA-Z0-9_-]/g,"_");return(s.length>64?s.slice(0,64):s).replace(/_+$/,"")},b=(n)=>{let s=`fc_${Ye(n)}`;return s.length>64?s.slice(0,64):s},k=(n,s,i)=>{if(!l.has(a.provider))return c(n);if(!n.includes("|"))return c(n);let[r,g]=n.split("|"),h=c(r),x=i.provider!==a.provider||i.api!==a.api?b(g):c(g);if(!x.startsWith("fc_"))x=c(`fc_${x}`);return`${h}|${x}`},m=he(u.messages,a,k),I=ye(u.messages,(d?.supportsAdditionalTools??!1)||(d?.supportsToolSearch??!1)),v=(n,s)=>{let i=I.anchorsAdditions?n.toolsAdded??[]:[];if(i.length===0)return;if(d?.supportsAdditionalTools){p.push({type:"additional_tools",role:"developer",tools:Je(i,d.toolOptions)});return}if(!d?.supportsToolSearch)return;let r=i.map((h)=>h.name),g=`pi_tool_load_${Ye(`${s}:${r.join(",")}`)}`;p.push({type:"tool_search_call",call_id:g,execution:"client",status:"completed",arguments:{query:r.join(" "),limit:r.length}}),p.push({type:"tool_search_output",call_id:g,execution:"client",status:"completed",tools:Je(i,{...d.toolOptions,toolSearchResult:!0})})},C=d?.includeSystemPrompt??!0,w=a.compat,M=a.reasoning&&w?.supportsDeveloperRole!==!1?"developer":"system",t=0,e=0;for(let n of m){let s=e++===0&&n.role==="system";if(n.role==="system"){if(!s)v(n,`system:${t}`);if(!s||C){let i=s?N(n):Me(n);if(i.length>0)p.push({role:M,content:y(i)})}}else if(n.role==="user")if(typeof n.content==="string")p.push({role:"user",content:[{type:"input_text",text:y(n.content)}]});else{let i=n.content.map((r)=>{if(r.type==="text")return{type:"input_text",text:y(r.text)};return{type:"input_image",detail:"auto",image_url:`data:${r.mimeType};base64,${r.data}`}});if(i.length===0)continue;p.push({role:"user",content:i})}else if(n.role==="assistant"){let i=[],r=n,g=r.provider===a.provider&&r.api===a.api,h=g&&r.model===a.id,P=g&&r.model!==a.id,x=0;for(let S of n.content)if(S.type==="thinking"){if(S.thinkingSignature){let f=JSON.parse(S.thinkingSignature);i.push(f)}}else if(S.type==="text"){let f=S,T=E(f.textSignature),J=x===0?`msg_pi_${t}`:`msg_pi_${t}_${x}`;x++;let _=T?.id;if(!_)_=J;else if(_.length>64)_=`msg_${Ye(_)}`;i.push({type:"message",role:"assistant",content:[{type:"output_text",text:y(f.text),annotations:[]}],status:"completed",id:_,phase:T?.phase})}else if(S.type==="toolCall"){let f=S,[T,J]=f.id.split("|"),_=d?.grammarToolInputProperties?.get(f.name),R=J,A=_===void 0?"fc_":"ctc_";if(P||!R?.startsWith(A))R=void 0;if(_!==void 0)i.push({type:"custom_tool_call",id:R,call_id:T,name:f.name,input:y(Or(f.name,f.arguments,_)),...h&&f.namespace!==void 0?{namespace:f.namespace}:{}});else i.push({type:"function_call",id:R,call_id:T,name:f.name,arguments:JSON.stringify(f.arguments),...h&&f.namespace!==void 0?{namespace:f.namespace}:{}})}if(i.length===0)continue;p.push(...i)}else if(n.role==="toolResult"){let[i]=n.toolCallId.split("|"),r=B(a,n.content);if(d?.grammarToolInputProperties?.has(n.toolName))p.push({type:"custom_tool_call_output",call_id:i,output:r});else p.push({type:"function_call_output",call_id:i,output:r})}if(!s)t++}return p}function Je(a,o){let l=o?.strict===void 0?!1:o.strict,d=o?.supportsStrictMode??!0,u=o?.supportsOpenAIGrammarTools??!1;return a.map((p)=>{let c=Yt(p,u);if(c)return{type:"custom",name:p.name,description:p.description,format:{type:"grammar",syntax:c.format,definition:c.definition},...o?.toolSearchResult?{defer_loading:!0}:{}};let k=ce(p,d)??l,m={type:"function",name:p.name,description:p.description,parameters:me(p,k===!0),...o?.toolSearchResult?{defer_loading:!0}:{}};if(d)m.strict=k;return m})}function z(a){let o=a.customInput?.property;if(o===void 0)return"";let l=a.arguments[o];return typeof l==="string"?l:""}function O(a,o,l){let d=a.customInput;if(!d)return;let u=Nr(d.jsonBuffer,d.property,o,l);return a.arguments={[d.property]:o},u}async function lt(a,o,l,d,u){let p=!1,c=new Map,b=new Map,k=(t)=>{if(t.type==="message"&&t.phase==="final_answer")o.stopReason="stop"},m=(t,e)=>{let n=c.get(t);return n?.type===e?n:void 0},I=(t,e)=>{if(e===void 0)return;l.push({type:"toolcall_delta",contentIndex:t.contentIndex,delta:e,partial:o})},v=(t,e)=>{if(e.type==="reasoning"){let n={type:"thinking",thinking:""};o.content.push(n);let s={type:"thinking",block:n,contentIndex:o.content.length-1};return c.set(t,s),l.push({type:"thinking_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="message"){k(e);let n={type:"text",text:""};o.content.push(n);let s={type:"text",block:n,contentIndex:o.content.length-1};return c.set(t,s),l.push({type:"text_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="function_call"){let n={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},...e.namespace!==void 0?{namespace:e.namespace}:{},partialJson:e.arguments||""};o.content.push(n);let s={type:"toolCall",block:n,contentIndex:o.content.length-1};return c.set(t,s),l.push({type:"toolcall_start",contentIndex:s.contentIndex,partial:o}),s}if(e.type==="custom_tool_call"){let n=u?.grammarToolInputProperties?.get(e.name)??"input",s=e.input||"",i={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{[n]:s},...e.namespace!==void 0?{namespace:e.namespace}:{},customInput:{property:n,jsonBuffer:{input:"",started:!1,closed:!1}}};o.content.push(i);let r={type:"toolCall",block:i,contentIndex:o.content.length-1};return c.set(t,r),l.push({type:"toolcall_start",contentIndex:r.contentIndex,partial:o}),r}return},C=(t,e)=>c.get(t)??v(t,e),w=(t)=>{for(let e of t){if(e.type!=="reasoning"||!e.encrypted_content)continue;let n=b.get(e.id);if(!n?.thinkingSignature)continue;let s=JSON.parse(n.thinkingSignature);if(s.encrypted_content)continue;n.thinkingSignature=JSON.stringify({...s,encrypted_content:e.encrypted_content})}},M=(t)=>{if(p=!0,w(t.output??[]),t?.id)o.responseId=t.id;if(t?.usage){let r=t.usage.input_tokens_details,g=r?.cached_tokens||0,h=r?.cache_write_tokens||0;o.usage={input:Math.max(0,(t.usage.input_tokens||0)-g-h),output:t.usage.output_tokens||0,cacheRead:g,cacheWrite:h,reasoning:t.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(Q(d,o.usage),u?.applyServiceTierPricing){let r=u.resolveServiceTier?u.resolveServiceTier(t?.service_tier,u.serviceTier):t?.service_tier??u.serviceTier;u.applyServiceTierPricing(o.usage,r)}let e=t?.status,n=t?.incomplete_details,s=typeof n?.reason==="string"?n.reason:void 0;o.rawStopReason=s?`${e}.${s}`:e;let i=D(e,s);if(o.stopReason=i.stopReason,i.errorMessage===void 0)delete o.errorMessage;else o.errorMessage=i.errorMessage;if(o.content.some((r)=>r.type==="toolCall")&&o.stopReason==="stop")o.stopReason="toolUse"};for await(let t of a)if(await u?.onProviderStreamEvent?.(t,d),t.type==="response.created")o.responseId=t.response.id;else if(t.type==="response.output_item.added")v(t.output_index,t.item);else if(t.type==="response.reasoning_summary_text.delta"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,l.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.reasoning_summary_part.done"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=`
4
4
 
5
5
  `,l.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:`
6
6
 
7
- `,partial:o})}else if(t.type==="response.reasoning_text.delta"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,l.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.output_text.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,l.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.refusal.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,l.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.function_call_arguments.delta"){let e=m(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;e.block.partialJson+=t.delta,e.block.arguments=F(e.block.partialJson),I(e,t.delta)}else if(t.type==="response.function_call_arguments.done"){let e=m(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;let n=e.block.partialJson;if(e.block.partialJson=t.arguments,e.block.arguments=F(e.block.partialJson),t.arguments.startsWith(n)){let s=t.arguments.slice(n.length);if(s.length>0)I(e,s)}}else if(t.type==="response.custom_tool_call_input.delta"){let e=m(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;I(e,O(e.block,z(e.block)+t.delta,!1))}else if(t.type==="response.custom_tool_call_input.done"){let e=m(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;I(e,O(e.block,t.input,!0))}else if(t.type==="response.output_item.done"){let e=t.item;k(e);let n=C(t.output_index,e);if(e.type==="reasoning"&&n?.type==="thinking"){let s=e.summary?.map((r)=>r.text).join(`
7
+ `,partial:o})}else if(t.type==="response.reasoning_text.delta"){let e=m(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,l.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.output_text.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,l.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.refusal.delta"){let e=m(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,l.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.function_call_arguments.delta"){let e=m(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;e.block.partialJson+=t.delta,e.block.arguments=W(e.block.partialJson),I(e,t.delta)}else if(t.type==="response.function_call_arguments.done"){let e=m(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;let n=e.block.partialJson;if(e.block.partialJson=t.arguments,e.block.arguments=W(e.block.partialJson),t.arguments.startsWith(n)){let s=t.arguments.slice(n.length);if(s.length>0)I(e,s)}}else if(t.type==="response.custom_tool_call_input.delta"){let e=m(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;I(e,O(e.block,z(e.block)+t.delta,!1))}else if(t.type==="response.custom_tool_call_input.done"){let e=m(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;I(e,O(e.block,t.input,!0))}else if(t.type==="response.output_item.done"){let e=t.item;k(e);let n=C(t.output_index,e);if(e.type==="reasoning"&&n?.type==="thinking"){let s=e.summary?.map((r)=>r.text).join(`
8
8
 
9
9
  `)||"",i=e.content?.map((r)=>r.text).join(`
10
10
 
11
- `)||"";n.block.thinking=s||i||n.block.thinking,n.block.thinkingSignature=JSON.stringify(e),b.set(e.id,n.block),l.push({type:"thinking_end",contentIndex:n.contentIndex,content:n.block.thinking,partial:o}),c.delete(t.output_index)}else if(e.type==="message"&&n?.type==="text")n.block.text=e.content?.map((s)=>s.type==="output_text"?s.text:s.refusal).join("")||"",n.block.textSignature=j(e.id,e.phase??void 0),l.push({type:"text_end",contentIndex:n.contentIndex,content:n.block.text,partial:o}),c.delete(t.output_index);else if(e.type==="function_call"&&n?.type==="toolCall"&&n.block.partialJson!==void 0){if(n.block.arguments=F(e.arguments||n.block.partialJson||"{}"),e.namespace!==void 0)n.block.namespace=e.namespace;delete n.block.partialJson,l.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),c.delete(t.output_index)}else if(e.type==="custom_tool_call"&&n?.type==="toolCall"&&n.block.customInput){if(I(n,O(n.block,e.input??z(n.block),!0)),e.namespace!==void 0)n.block.namespace=e.namespace;delete n.block.customInput,l.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),c.delete(t.output_index)}}else if(t.type==="response.completed"||t.type==="response.incomplete")M(t.response);else if(t.type==="error")throw Error(`Error Code ${t.code}: ${t.message}`||"Unknown error");else if(t.type==="response.failed"){p=!0,o.rawStopReason=t.response?.status;let e=t.response?.error,n=t.response?.incomplete_details,s=e?`${e.code||"unknown"}: ${e.message||"no message"}`:n?.reason?`incomplete: ${n.reason}`:"Unknown error (no error details in response)";throw Error(s)}if(!p)throw Error("OpenAI Responses stream ended before a terminal response event");if(o.stopReason==="toolUse")for(let t of o.content){if(t.type!=="toolCall")continue;let e=t;if(e.partialJson!==void 0||e.customInput!==void 0)throw Error(`OpenAI Responses stream completed with an unfinished tool call: ${e.name} (${e.id})`)}}function B(a,o){if(!a)return{stopReason:"stop"};switch(a){case"completed":return{stopReason:"stop"};case"incomplete":if(o==="max_output_tokens")return{stopReason:"length"};return{stopReason:"error",errorMessage:o?`Response incomplete: ${o}`:"Response incomplete without a provider reason"};case"failed":case"cancelled":return{stopReason:"error"};case"in_progress":case"queued":return{stopReason:"stop"};default:throw Error(`Unhandled stop reason: ${a}`)}}
11
+ `)||"";n.block.thinking=s||i||n.block.thinking,n.block.thinkingSignature=JSON.stringify(e),b.set(e.id,n.block),l.push({type:"thinking_end",contentIndex:n.contentIndex,content:n.block.thinking,partial:o}),c.delete(t.output_index)}else if(e.type==="message"&&n?.type==="text")n.block.text=e.content?.map((s)=>s.type==="output_text"?s.text:s.refusal).join("")||"",n.block.textSignature=j(e.id,e.phase??void 0),l.push({type:"text_end",contentIndex:n.contentIndex,content:n.block.text,partial:o}),c.delete(t.output_index);else if(e.type==="function_call"&&n?.type==="toolCall"&&n.block.partialJson!==void 0){if(n.block.arguments=W(e.arguments||n.block.partialJson||"{}"),e.namespace!==void 0)n.block.namespace=e.namespace;delete n.block.partialJson,l.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),c.delete(t.output_index)}else if(e.type==="custom_tool_call"&&n?.type==="toolCall"&&n.block.customInput){if(I(n,O(n.block,e.input??z(n.block),!0)),e.namespace!==void 0)n.block.namespace=e.namespace;delete n.block.customInput,l.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),c.delete(t.output_index)}}else if(t.type==="response.completed"||t.type==="response.incomplete")M(t.response);else if(t.type==="error")throw Error(`Error Code ${t.code}: ${t.message}`||"Unknown error");else if(t.type==="response.failed"){p=!0,o.rawStopReason=t.response?.status;let e=t.response?.error,n=t.response?.incomplete_details,s=e?`${e.code||"unknown"}: ${e.message||"no message"}`:n?.reason?`incomplete: ${n.reason}`:"Unknown error (no error details in response)";throw Error(s)}if(!p)throw Error("OpenAI Responses stream ended before a terminal response event");if(o.stopReason==="toolUse")for(let t of o.content){if(t.type!=="toolCall")continue;let e=t;if(e.partialJson!==void 0||e.customInput!==void 0)throw Error(`OpenAI Responses stream completed with an unfinished tool call: ${e.name} (${e.id})`)}}function D(a,o){if(!a)return{stopReason:"stop"};switch(a){case"completed":return{stopReason:"stop"};case"incomplete":if(o==="max_output_tokens")return{stopReason:"length"};return{stopReason:"error",errorMessage:o?`Response incomplete: ${o}`:"Response incomplete without a provider reason"};case"failed":case"cancelled":return{stopReason:"error"};case"in_progress":case"queued":return{stopReason:"stop"};default:throw Error(`Unhandled stop reason: ${a}`)}}
12
12
  export{at,Je,lt};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Xt,So}from"./chunk-980drajf.js";import"./chunk-c4qr1f41.js";import"./chunk-r0jc8e7t.js";export{Xt as stream,So as streamSimple};