eser 4.1.36 → 4.1.39

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 (294) hide show
  1. package/chunks/add-V7YYHLFH.js +8 -0
  2. package/chunks/{anthropic-2MXDKLNX.js → anthropic-QBGNUIP3.js} +1 -1
  3. package/chunks/approve-HVIH2A3C.js +2 -0
  4. package/chunks/ask-PMB64QWG.js +3 -0
  5. package/chunks/block-JSK5CJPO.js +2 -0
  6. package/chunks/browser-JGBNWUEQ.js +2 -0
  7. package/chunks/{build-EJLFNB4I.js → build-HUKFUVPB.js} +2 -2
  8. package/chunks/bun-HIMXX54I.js +2 -0
  9. package/chunks/changelog-gen-JV3EHOMV.js +10 -0
  10. package/chunks/{chunk-GJ4LCA6D.js → chunk-2KKLYXSA.js} +1 -1
  11. package/chunks/{chunk-JYNHFD6B.js → chunk-2XNFZXHY.js} +1 -1
  12. package/chunks/{chunk-2EVWKUN6.js → chunk-3AA3RXKD.js} +1 -1
  13. package/chunks/{chunk-CUIMSX4V.js → chunk-3IZX4OZ7.js} +1 -1
  14. package/chunks/{chunk-KPWEJXPI.js → chunk-3QF3I2RD.js} +1 -1
  15. package/chunks/{chunk-K6H7JTIH.js → chunk-4EHAL3NK.js} +1 -1
  16. package/chunks/chunk-4FGLERUG.js +2 -0
  17. package/chunks/{chunk-IDMI5OBK.js → chunk-4QDEJUAF.js} +1 -1
  18. package/chunks/{chunk-4MVO4LD5.js → chunk-5224ZYEW.js} +1 -1
  19. package/chunks/{chunk-LCG4SK6K.js → chunk-5DWJ7WEE.js} +1 -1
  20. package/chunks/chunk-5WJ6AUNY.js +2 -0
  21. package/chunks/chunk-6E6JUBFH.js +2 -0
  22. package/chunks/chunk-7UASU4NU.js +10 -0
  23. package/chunks/chunk-A3JJKZ4C.js +4 -0
  24. package/chunks/chunk-A3MZV73T.js +32 -0
  25. package/chunks/chunk-A6K5L4SG.js +3 -0
  26. package/chunks/{chunk-YVIGHK4H.js → chunk-AHKNU2JM.js} +1 -1
  27. package/chunks/{chunk-BCPCQHDL.js → chunk-BBOEAL63.js} +1 -1
  28. package/chunks/chunk-BQT5RJZB.js +2 -0
  29. package/chunks/{chunk-EBCQCAQ7.js → chunk-BWDCKK63.js} +1 -1
  30. package/chunks/{chunk-FORPNESQ.js → chunk-CMSPX2RN.js} +1 -1
  31. package/chunks/{chunk-H4SPMUT6.js → chunk-DKFL6XPX.js} +1 -1
  32. package/chunks/{chunk-HVLKXRPA.js → chunk-DWLFTRZS.js} +1 -1
  33. package/chunks/{chunk-PVPMHMKP.js → chunk-ECY4MUD3.js} +1 -1
  34. package/chunks/{chunk-IIIMOOFE.js → chunk-EGMYM4TM.js} +1 -1
  35. package/chunks/{chunk-I4C675WP.js → chunk-F35K7YVH.js} +1 -1
  36. package/chunks/{chunk-IZONBJSX.js → chunk-F5HQDZLN.js} +1 -1
  37. package/chunks/{chunk-A6RDYP6R.js → chunk-FFWPJP7A.js} +1 -1
  38. package/chunks/chunk-H2O5G3XB.js +2 -0
  39. package/chunks/{chunk-Y53YTL4C.js → chunk-HLKFDKLZ.js} +1 -1
  40. package/chunks/{chunk-SOBOSRJB.js → chunk-HP5W5XT6.js} +1 -1
  41. package/chunks/{chunk-BP3IFAPO.js → chunk-HTJLIAH4.js} +1 -1
  42. package/chunks/{chunk-7BFBOLLC.js → chunk-HVTJ5LVU.js} +1 -1
  43. package/chunks/chunk-HZ2ALFWG.js +66 -0
  44. package/chunks/{chunk-YQVWAWMO.js → chunk-ILROPD5P.js} +1 -1
  45. package/chunks/{chunk-QSION3QA.js → chunk-ISQIZSXN.js} +1 -1
  46. package/chunks/chunk-JI536JLJ.js +2 -0
  47. package/chunks/{chunk-UJPVEQX7.js → chunk-K2MKYDPY.js} +1 -1
  48. package/chunks/{chunk-T2DRBZ4X.js → chunk-KEOTIPA6.js} +1 -1
  49. package/chunks/chunk-L2E2H7YT.js +2 -0
  50. package/chunks/chunk-L7UCWRDZ.js +3 -0
  51. package/chunks/{chunk-4WQGB7NO.js → chunk-LBMJGMDD.js} +1 -1
  52. package/chunks/{chunk-2VEVVX6U.js → chunk-LFNUSULJ.js} +1 -1
  53. package/chunks/{chunk-5GGGQJ4P.js → chunk-MBCPGD5L.js} +1 -1
  54. package/chunks/chunk-MEZCXQAX.js +2 -0
  55. package/chunks/{chunk-B6EATLKL.js → chunk-MOY4CXAZ.js} +2 -2
  56. package/chunks/{chunk-P74JF7XR.js → chunk-MQ4EMT35.js} +1 -1
  57. package/chunks/chunk-NEHZOG23.js +7 -0
  58. package/chunks/{chunk-QZ44TAIY.js → chunk-NJUIBCQR.js} +1 -1
  59. package/chunks/{chunk-5MWX3POX.js → chunk-NZRU3N6C.js} +1 -1
  60. package/chunks/{chunk-N2VBT43E.js → chunk-O2TA7OHJ.js} +1 -1
  61. package/chunks/{chunk-ER4ZWF4Y.js → chunk-OAFB4A6D.js} +1 -1
  62. package/chunks/chunk-OAT2D23A.js +2 -0
  63. package/chunks/{chunk-3QIPK7NI.js → chunk-OPPOHKNZ.js} +1 -1
  64. package/chunks/{chunk-ZNGLZECE.js → chunk-OWV223WQ.js} +1 -1
  65. package/chunks/{chunk-3BEX5FYF.js → chunk-P2MUEKFT.js} +1 -1
  66. package/chunks/{chunk-455V3AE5.js → chunk-P72TUTYK.js} +1 -1
  67. package/chunks/{chunk-Q2KSOC32.js → chunk-PPSDIDOI.js} +1 -1
  68. package/chunks/chunk-PXCM4FHO.js +2 -0
  69. package/chunks/{chunk-KVTG56GS.js → chunk-QFFGKP3M.js} +1 -1
  70. package/chunks/{chunk-PZNCE6QK.js → chunk-QXATB6Z5.js} +1 -1
  71. package/chunks/chunk-RGUPFAEE.js +68 -0
  72. package/chunks/{chunk-SP43S32B.js → chunk-RVJZFWN7.js} +1 -1
  73. package/chunks/{chunk-B5IPHVXT.js → chunk-SBAXURB7.js} +1 -1
  74. package/chunks/{chunk-7NUMDHE2.js → chunk-T4WKRBQZ.js} +1 -1
  75. package/chunks/{chunk-UJ6LH5FY.js → chunk-TEOMM3RD.js} +1 -1
  76. package/chunks/{chunk-QOX7VSID.js → chunk-TLVGNOK3.js} +1 -1
  77. package/chunks/{chunk-HYT26FYU.js → chunk-U5Q5MC74.js} +1 -1
  78. package/chunks/chunk-ULNEO3RY.js +4 -0
  79. package/chunks/{chunk-MXGRYONZ.js → chunk-UMKCOU3N.js} +1 -1
  80. package/chunks/{chunk-536RBSFU.js → chunk-UQ2BC7UA.js} +1 -1
  81. package/chunks/{chunk-HVOPUZOM.js → chunk-VIQLCQOI.js} +1 -1
  82. package/chunks/chunk-VWQLQJVX.js +2 -0
  83. package/chunks/{chunk-CKNA5LIK.js → chunk-WAEXOK7L.js} +1 -1
  84. package/chunks/{chunk-NP723K5L.js → chunk-WILZ4OR2.js} +1 -1
  85. package/chunks/chunk-WJKE6XHF.js +2 -0
  86. package/chunks/{chunk-KQE6FMKW.js → chunk-XYUJCTPP.js} +1 -1
  87. package/chunks/{chunk-P2TABZ4A.js → chunk-YEWODYET.js} +1 -1
  88. package/chunks/{chunk-3SXTMY75.js → chunk-YVN2NZL4.js} +1 -1
  89. package/chunks/{chunk-GBM3TZFD.js → chunk-ZC4F4MYU.js} +1 -1
  90. package/chunks/{chunk-KBFKBL6A.js → chunk-ZWMJQZQF.js} +1 -1
  91. package/chunks/claude-code-ELUDT5TV.js +2 -0
  92. package/chunks/{clone-H3UAEVVP.js → clone-YEBQK7CG.js} +1 -1
  93. package/chunks/cmd-2DAVTVOF.js +2 -0
  94. package/chunks/{commitmsg-7XZGGERO.js → commitmsg-FQ3IZ3TH.js} +2 -2
  95. package/chunks/concern-TIGYH5DX.js +2 -0
  96. package/chunks/deno-XQHOVHKR.js +2 -0
  97. package/chunks/dev-BNGJJR2O.js +4 -0
  98. package/chunks/dist-QVOR7USR.js +13 -0
  99. package/chunks/done-GGPPHJW2.js +2 -0
  100. package/chunks/file-tools-shared-KBTCO2FV.js +2 -0
  101. package/chunks/{gemini-F4KLO5VU.js → gemini-43AWJEWI.js} +1 -1
  102. package/chunks/gh-Q7VEABJS.js +4 -0
  103. package/chunks/gh-contributors-4KGARSNL.js +12 -0
  104. package/chunks/init-45ODFAV3.js +2 -0
  105. package/chunks/{init-J4IHOVZL.js → init-RV7K5JC4.js} +3 -3
  106. package/chunks/{install-KNZDCGIB.js → install-6XIQS5E7.js} +2 -2
  107. package/chunks/invoke-hook-Q3NMJXDO.js +11 -0
  108. package/chunks/kiro-NZ7LM6HA.js +2 -0
  109. package/chunks/list-BOLPKAEY.js +2 -0
  110. package/chunks/{list-N4ZKDFW7.js → list-NYLFIF2U.js} +1 -1
  111. package/chunks/list-UQMPOF5Y.js +2 -0
  112. package/chunks/load-config-G4DHKB5K.js +2 -0
  113. package/chunks/{main-HJQEBLLN.js → main-236QYA7G.js} +2 -2
  114. package/chunks/manifest-3VJ4O6HR.js +2 -0
  115. package/chunks/{mod-4ILLF5PK.js → mod-5JT4O5L3.js} +1 -1
  116. package/chunks/mod-BQJDMCYC.js +2 -0
  117. package/chunks/mod-DXA25A4J.js +2 -0
  118. package/chunks/mod-EWLBSEHA.js +2 -0
  119. package/chunks/mod-GSWVSC2C.js +28 -0
  120. package/chunks/mod-IHYN4TEM.js +3 -0
  121. package/chunks/mod-IXVUQHXS.js +2 -0
  122. package/chunks/mod-P4AVZJNK.js +2 -0
  123. package/chunks/mod-PZSJGUM7.js +2 -0
  124. package/chunks/mod-QWYXFGRG.js +2 -0
  125. package/chunks/{mod-OS3BCM2G.js → mod-SXL6PDQM.js} +1 -1
  126. package/chunks/mod-YH5Z6G4Q.js +2 -0
  127. package/chunks/multipart-parser-SSRHOBFH.js +3 -0
  128. package/chunks/{new-BOGCXTIY.js → new-U5U4E6HR.js} +1 -1
  129. package/chunks/next-AQ4TIEL7.js +9 -0
  130. package/chunks/node-IN5OQP4N.js +68 -0
  131. package/chunks/node-ZGM6SXXI.js +2 -0
  132. package/chunks/ollama-LHWMXMLY.js +2 -0
  133. package/chunks/openai-2KONKHWL.js +2 -0
  134. package/chunks/openai-IRQY5SCR.js +24 -0
  135. package/chunks/opencode-24O2MW3L.js +2 -0
  136. package/chunks/purge-RM6OD5PV.js +5 -0
  137. package/chunks/recipe-applier-TTZEZGSC.js +2 -0
  138. package/chunks/registry-fetcher-SPENFEOH.js +2 -0
  139. package/chunks/release-UEX6YK4K.js +9 -0
  140. package/chunks/release-notes-GA7CTA54.js +4 -0
  141. package/chunks/release-tag-VJWBXG5G.js +2 -0
  142. package/chunks/reset-WHYTPTFB.js +2 -0
  143. package/chunks/rule-ZQOGLQQI.js +3 -0
  144. package/chunks/run-IX74MQTI.js +4 -0
  145. package/chunks/run-L35K3KRF.js +5 -0
  146. package/chunks/scripts-VI2TKQOH.js +2 -0
  147. package/chunks/sdk-L2SQCWYV.js +41 -0
  148. package/chunks/serve-AVVEYGQB.js +4 -0
  149. package/chunks/{server-KNWQV2HW.js → server-R347ON4B.js} +1 -1
  150. package/chunks/spec-KMKZDLV2.js +2 -0
  151. package/chunks/src-6SFGTAGT.js +4 -0
  152. package/chunks/status-MLX4O37A.js +2 -0
  153. package/chunks/sync-PB4KWB3R.js +2 -0
  154. package/chunks/system-BXJ2LV5O.js +2 -0
  155. package/chunks/system-YLXVXRXW.js +2 -0
  156. package/chunks/{unstable_chmod-GDQI7NKH.js → unstable_chmod-2W47KJY3.js} +1 -1
  157. package/chunks/update-522VXIKX.js +6 -0
  158. package/chunks/validate-bom-JCMRVAUT.js +2 -0
  159. package/chunks/validate-case-conflict-WZQCMKSZ.js +2 -0
  160. package/chunks/validate-circular-deps-7R4F2YDV.js +2 -0
  161. package/chunks/validate-commit-msg-PH7Y3JEI.js +2 -0
  162. package/chunks/validate-docs-WCIOHNYP.js +2 -0
  163. package/chunks/validate-eof-KRYQLTFQ.js +2 -0
  164. package/chunks/validate-export-names-OCQ2XSY6.js +2 -0
  165. package/chunks/validate-filenames-46O7FCXF.js +2 -0
  166. package/chunks/validate-json-3EZ2L64H.js +2 -0
  167. package/chunks/validate-large-files-7YX6MSOB.js +2 -0
  168. package/chunks/validate-licenses-OC7JRVAH.js +2 -0
  169. package/chunks/validate-line-endings-2DM5UGCJ.js +2 -0
  170. package/chunks/validate-merge-conflict-UDMWYMJ5.js +2 -0
  171. package/chunks/validate-mod-exports-W24IV367.js +2 -0
  172. package/chunks/validate-package-configs-3Y55ZLUY.js +2 -0
  173. package/chunks/validate-secrets-66VXCCUF.js +2 -0
  174. package/chunks/validate-shebangs-AMEAHVLB.js +2 -0
  175. package/chunks/validate-submodules-DYCE27WK.js +2 -0
  176. package/chunks/validate-symlinks-QN744GUH.js +2 -0
  177. package/chunks/validate-toml-5K2XNHAE.js +2 -0
  178. package/chunks/validate-trailing-whitespace-QYWHHIAK.js +2 -0
  179. package/chunks/validate-yaml-VGKLHEAQ.js +2 -0
  180. package/chunks/versions-FYALONNL.js +2 -0
  181. package/chunks/{vertexai-EXTYPVHK.js → vertexai-2F2A3VTE.js} +1 -1
  182. package/chunks/watch-P56QT3Q2.js +9 -0
  183. package/chunks/workerd-LOWXXQEU.js +2 -0
  184. package/eser.js +1 -1
  185. package/package.json +1 -1
  186. package/chunks/add-5SDE43IH.js +0 -8
  187. package/chunks/approve-XNUZYGYJ.js +0 -2
  188. package/chunks/ask-L3N6REQI.js +0 -3
  189. package/chunks/block-NWIP4USQ.js +0 -2
  190. package/chunks/browser-SG2DBNGS.js +0 -2
  191. package/chunks/bun-3AACRJXG.js +0 -2
  192. package/chunks/changelog-gen-MX6L2Z24.js +0 -10
  193. package/chunks/chunk-2HBVIH7V.js +0 -3
  194. package/chunks/chunk-32HV3K27.js +0 -2
  195. package/chunks/chunk-46ZWBKIW.js +0 -2
  196. package/chunks/chunk-4DOMGQOO.js +0 -2
  197. package/chunks/chunk-AHLJCH32.js +0 -2
  198. package/chunks/chunk-CDPSH56U.js +0 -2
  199. package/chunks/chunk-DAK2I7UC.js +0 -2
  200. package/chunks/chunk-DAYSTLLV.js +0 -2
  201. package/chunks/chunk-DTO2YJWZ.js +0 -2
  202. package/chunks/chunk-DYRTLYTU.js +0 -3
  203. package/chunks/chunk-G6NAG2EK.js +0 -2
  204. package/chunks/chunk-JAQN64PH.js +0 -13
  205. package/chunks/chunk-JOTAKQMZ.js +0 -2
  206. package/chunks/chunk-LNNNLUZT.js +0 -2
  207. package/chunks/chunk-MRCBHVSB.js +0 -2
  208. package/chunks/chunk-OIZ7HL2C.js +0 -61
  209. package/chunks/chunk-PE2TDUXD.js +0 -19
  210. package/chunks/chunk-RGUETQSC.js +0 -4
  211. package/chunks/chunk-STI6DX7K.js +0 -2
  212. package/chunks/chunk-TFPT4BDY.js +0 -15
  213. package/chunks/chunk-UESOCN2G.js +0 -2
  214. package/chunks/chunk-W3RVRCUB.js +0 -2
  215. package/chunks/chunk-WG6J7DFO.js +0 -7
  216. package/chunks/chunk-XVSIRN6G.js +0 -4
  217. package/chunks/chunk-Y4ARZGGL.js +0 -2
  218. package/chunks/claude-code-VUBEU7RR.js +0 -2
  219. package/chunks/concern-ZO533WR2.js +0 -2
  220. package/chunks/deno-7BSPHDRG.js +0 -2
  221. package/chunks/dev-PTMXZEVC.js +0 -4
  222. package/chunks/done-DIN56LXZ.js +0 -2
  223. package/chunks/file-tools-shared-G36OYF5S.js +0 -2
  224. package/chunks/fileFromPath-MB3IRZVW.js +0 -7
  225. package/chunks/gh-L25JQWOY.js +0 -5
  226. package/chunks/gh-contributors-E7IZ2LFS.js +0 -12
  227. package/chunks/init-3B7XMH2J.js +0 -2
  228. package/chunks/invoke-hook-I2T7HYRT.js +0 -10
  229. package/chunks/kiro-HQLXD6ZU.js +0 -2
  230. package/chunks/list-5TGTYMAU.js +0 -2
  231. package/chunks/list-PY3A762R.js +0 -2
  232. package/chunks/load-config-FTQMJVEW.js +0 -2
  233. package/chunks/manifest-NF2EK757.js +0 -2
  234. package/chunks/mod-FEGQZ3ZY.js +0 -2
  235. package/chunks/mod-HKYPZOU7.js +0 -2
  236. package/chunks/mod-JI2A2546.js +0 -2
  237. package/chunks/mod-JZNE2HH6.js +0 -2
  238. package/chunks/mod-MLRQFSBE.js +0 -2
  239. package/chunks/mod-NCF6OSXO.js +0 -2
  240. package/chunks/mod-PFWQZF3T.js +0 -28
  241. package/chunks/mod-T5VHCXJT.js +0 -2
  242. package/chunks/mod-W3DBWTCY.js +0 -11
  243. package/chunks/mod-YX3JRMSI.js +0 -2
  244. package/chunks/next-TMHSP2BS.js +0 -4
  245. package/chunks/node-KCQF6QQA.js +0 -60
  246. package/chunks/node-MFKYO4CY.js +0 -2
  247. package/chunks/ollama-36F5QAOO.js +0 -2
  248. package/chunks/openai-EU5TJZ5T.js +0 -2
  249. package/chunks/openai-IKXRJYI3.js +0 -20
  250. package/chunks/opencode-7J3JDC44.js +0 -2
  251. package/chunks/purge-XYNNHOEN.js +0 -5
  252. package/chunks/recipe-applier-6QZYAZ57.js +0 -2
  253. package/chunks/registry-fetcher-76ISLGRR.js +0 -2
  254. package/chunks/release-J3PVDROM.js +0 -9
  255. package/chunks/release-notes-AARDYXYA.js +0 -4
  256. package/chunks/release-tag-H2YWUXRU.js +0 -2
  257. package/chunks/reset-EYLAZVKO.js +0 -2
  258. package/chunks/rule-JMNIMEH3.js +0 -3
  259. package/chunks/run-NSJ5YV6R.js +0 -4
  260. package/chunks/run-RGEZUAPM.js +0 -5
  261. package/chunks/scripts-JK6W2MCO.js +0 -2
  262. package/chunks/sdk-MXV452BR.js +0 -19
  263. package/chunks/serve-XVAIQ37L.js +0 -4
  264. package/chunks/spec-3UGU4UBE.js +0 -2
  265. package/chunks/status-6SC3L7U2.js +0 -2
  266. package/chunks/sync-M7MKXMYN.js +0 -2
  267. package/chunks/system-L2JVPTCT.js +0 -2
  268. package/chunks/system-WTPEDJU6.js +0 -2
  269. package/chunks/update-4C4WNXCE.js +0 -6
  270. package/chunks/validate-bom-QVE5HNBO.js +0 -2
  271. package/chunks/validate-case-conflict-XFS3URQN.js +0 -2
  272. package/chunks/validate-circular-deps-BMPAT3PF.js +0 -2
  273. package/chunks/validate-commit-msg-BPESCI7P.js +0 -2
  274. package/chunks/validate-docs-ITL4L6KY.js +0 -2
  275. package/chunks/validate-eof-DTFV74VL.js +0 -2
  276. package/chunks/validate-export-names-HLOH7D73.js +0 -2
  277. package/chunks/validate-filenames-J4RTDEBD.js +0 -2
  278. package/chunks/validate-json-KMODGNSU.js +0 -2
  279. package/chunks/validate-large-files-X5YF7D7T.js +0 -2
  280. package/chunks/validate-licenses-OZ7DXQTY.js +0 -2
  281. package/chunks/validate-line-endings-PFF6QJ3W.js +0 -2
  282. package/chunks/validate-merge-conflict-KB2X6QLW.js +0 -2
  283. package/chunks/validate-mod-exports-VHK2NVKI.js +0 -2
  284. package/chunks/validate-package-configs-ZNCAIYRO.js +0 -2
  285. package/chunks/validate-secrets-RM6DMZVG.js +0 -2
  286. package/chunks/validate-shebangs-WC66D7RK.js +0 -2
  287. package/chunks/validate-submodules-SPAXASAG.js +0 -2
  288. package/chunks/validate-symlinks-4LOWK2MQ.js +0 -2
  289. package/chunks/validate-toml-SG4IITMN.js +0 -2
  290. package/chunks/validate-trailing-whitespace-GRE2PJ6T.js +0 -2
  291. package/chunks/validate-yaml-RA22QNW6.js +0 -2
  292. package/chunks/versions-ODYWYT7U.js +0 -2
  293. package/chunks/watch-YKYNWTZF.js +0 -9
  294. package/chunks/workerd-VVSAKLDZ.js +0 -2
@@ -0,0 +1,2 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{a as h,b as S,c as P,d as w}from"./chunk-VWQLQJVX.js";import{s as c,t as f}from"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";import*as p from"node:child_process";import l from"node:process";import{Buffer as d}from"node:buffer";import{Readable as C,Writable as g}from"node:stream";var y={fs:!0,fsSync:!0,exec:!0,process:!0,env:!0,stdin:!0,stdout:!0,kv:!1},b=(i,u=[],s)=>new Promise((e,a)=>{let n=p.spawn(i,u,{cwd:s?.cwd,env:s?.env?{...l.env,...s.env}:void 0,stdio:c(s),signal:s?.signal}),o=[],t=[];n.stdout?.on("data",r=>o.push(r)),n.stderr?.on("data",r=>t.push(r)),n.on("error",a),n.on("close",r=>{e({success:r===0,code:r??1,stdout:new Uint8Array(d.concat(o)),stderr:new Uint8Array(d.concat(t))})})}),A=(i,u=[],s)=>{let e=p.spawn(i,u,{cwd:s?.cwd,env:s?.env?{...l.env,...s.env}:void 0,stdio:c(s),signal:s?.signal}),a=[],n=[];e.stdout?.on("data",t=>a.push(t)),e.stderr?.on("data",t=>n.push(t));let o=new Promise((t,r)=>{e.on("error",r),e.on("close",(m,v)=>{t({success:m===0,code:m??1,signal:v??void 0})})});return{pid:e.pid,stdin:e.stdin?g.toWeb(e.stdin):null,stdout:e.stdout?C.toWeb(e.stdout):null,stderr:e.stderr?C.toWeb(e.stderr):null,status:o,output:async()=>{let t=await o;return{success:t.success,code:t.code,stdout:new Uint8Array(d.concat(a)),stderr:new Uint8Array(d.concat(n))}},kill:t=>{e.kill(t)}}},U=()=>({name:"node",version:l.versions.node,capabilities:y,fs:h(),path:S(),exec:f(b,A),env:P(),process:w()});export{y as NODE_CAPABILITIES,U as createNodeRuntime};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{a,b}from"./chunk-XYUJCTPP.js";import"./chunk-P72TUTYK.js";import"./chunk-J7YTWK67.js";import"./chunk-ECY4MUD3.js";import"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";export{a as OllamaModel,b as ollamaFactory};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{a,b}from"./chunk-SBAXURB7.js";import"./chunk-J7YTWK67.js";import"./chunk-5WJ6AUNY.js";export{a as OpenAIModel,b as openaiFactory};
@@ -0,0 +1,24 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import"./chunk-5WJ6AUNY.js";function b(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function a(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var Wr=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return Wr=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Gt(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var zt=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var _=class extends Error{},T=class s extends _{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new _e({message:r,cause:zt(t)});let o=t?.error;return e===400?new rt(e,o,r,n):e===401?new st(e,o,r,n):e===403?new nt(e,o,r,n):e===404?new ot(e,o,r,n):e===409?new it(e,o,r,n):e===422?new at(e,o,r,n):e===429?new lt(e,o,r,n):e>=500?new ct(e,o,r,n):new s(e,o,r,n)}},$=class extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},_e=class extends T{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends _e{constructor({message:e}={}){super({message:e??"Request timed out."})}},rt=class extends T{},st=class extends T{},nt=class extends T{},ot=class extends T{},it=class extends T{},at=class extends T{},lt=class extends T{},ct=class extends T{},ut=class extends _{constructor(){super("Could not parse response content as the length limit was reached")}},ft=class extends _{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},ee=class extends Error{constructor(e){super(e)}};var Bn=/^[a-z][a-z0-9+.-]*:/i,$s=s=>Bn.test(s),D=s=>(D=Array.isArray,D(s)),Hr=D;function Jr(s){return typeof s!="object"?{}:s??{}}function Xr(s){if(!s)return!0;for(let e in s)return!1;return!0}function ks(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function ht(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var Ts=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new _(`${s} must be an integer`);if(e<0)throw new _(`${s} must be a positive integer`);return e};var Fs=s=>{try{return JSON.parse(s)}catch{return}};var te=s=>new Promise(e=>setTimeout(e,s));var ye="6.33.0";var Bs=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function jn(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Un=()=>{let s=jn();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":Ms(Deno.build.os),"X-Stainless-Arch":Ns(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":Ms(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ns(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Dn();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Dn(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var Ns=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Ms=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),Ls,js=()=>Ls??(Ls=Un());function Us(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Vr(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function mr(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Vr({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function Kr(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Ds(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var qs=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Gr="RFC3986",zr=s=>String(s),Qr={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:zr},Ws="RFC1738";var _r=(s,e)=>(_r=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),_r(s,e)),re=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Yr=1024,Hs=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=Yr){let h=o.length>=Yr?o.slice(l,l+Yr):o,m=[];for(let g=0;g<h.length;++g){let d=h.charCodeAt(g);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||n===Ws&&(d===40||d===41)){m[m.length]=h.charAt(g);continue}if(d<128){m[m.length]=re[d];continue}if(d<2048){m[m.length]=re[192|d>>6]+re[128|d&63];continue}if(d<55296||d>=57344){m[m.length]=re[224|d>>12]+re[128|d>>6&63]+re[128|d&63];continue}g+=1,d=65536+((d&1023)<<10|h.charCodeAt(g)&1023),m[m.length]=re[240|d>>18]+re[128|d>>12&63]+re[128|d>>6&63]+re[128|d&63]}i+=m.join("")}return i};function Js(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Zr(s,e){if(D(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var Vs={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Ks=function(s,e){Array.prototype.push.apply(s,D(e)?e:[e])},Xs,F={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Hs,encodeValuesOnly:!1,format:Gr,formatter:zr,indices:!1,serializeDate(s){return(Xs??(Xs=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function Hn(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var es={};function Gs(s,e,t,r,n,o,i,l,h,m,g,d,y,f,P,x,v,R){let w=s,M=R,S=0,J=!1;for(;(M=M.get(es))!==void 0&&!J;){let O=M.get(s);if(S+=1,typeof O<"u"){if(O===S)throw new RangeError("Cyclic object value");J=!0}typeof M.get(es)>"u"&&(S=0)}if(typeof m=="function"?w=m(e,w):w instanceof Date?w=y?.(w):t==="comma"&&D(w)&&(w=Zr(w,function(O){return O instanceof Date?y?.(O):O})),w===null){if(o)return h&&!x?h(e,F.encoder,v,"key",f):e;w=""}if(Hn(w)||Js(w)){if(h){let O=x?e:h(e,F.encoder,v,"key",f);return[P?.(O)+"="+P?.(h(w,F.encoder,v,"value",f))]}return[P?.(e)+"="+P?.(String(w))]}let W=[];if(typeof w>"u")return W;let C;if(t==="comma"&&D(w))x&&h&&(w=Zr(w,h)),C=[{value:w.length>0?w.join(",")||null:void 0}];else if(D(m))C=m;else{let O=Object.keys(w);C=g?O.sort(g):O}let L=l?String(e).replace(/\./g,"%2E"):String(e),B=r&&D(w)&&w.length===1?L+"[]":L;if(n&&D(w)&&w.length===0)return B+"[]";for(let O=0;O<C.length;++O){let k=C[O],vs=typeof k=="object"&&typeof k.value<"u"?k.value:w[k];if(i&&vs===null)continue;let qr=d&&l?k.replace(/\./g,"%2E"):k,Mn=D(w)?typeof t=="function"?t(B,qr):B:B+(d?"."+qr:"["+qr+"]");R.set(s,S);let Os=new WeakMap;Os.set(es,R),Ks(W,Gs(vs,Mn,t,r,n,o,i,l,t==="comma"&&x&&D(w)?null:h,m,g,d,y,f,P,x,v,Os))}return W}function Jn(s=F){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||F.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Gr;if(typeof s.format<"u"){if(!_r(Qr,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=Qr[t],n=F.filter;(typeof s.filter=="function"||D(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Vs?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=F.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:F.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:F.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:F.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:F.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?F.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:F.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:F.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:F.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:F.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:F.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:F.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:F.strictNullHandling}}function zs(s,e={}){let t=s,r=Jn(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):D(r.filter)&&(o=r.filter,n=o);let i=[];if(typeof t!="object"||t===null)return"";let l=Vs[r.arrayFormat],h=l==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let m=new WeakMap;for(let y=0;y<n.length;++y){let f=n[y];r.skipNulls&&t[f]===null||Ks(i,Gs(t[f],f,l,h,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,m))}let g=i.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),g.length>0?d+g:""}function Qs(s){return zs(s,{arrayFormat:"brackets"})}function en(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Ys;function dt(s){let e;return(Ys??(e=new globalThis.TextEncoder,Ys=e.encode.bind(e)))(s)}var Zs;function ts(s){let e;return(Zs??(e=new globalThis.TextDecoder,Zs=e.decode.bind(e)))(s)}var X,V,ke=class{constructor(){X.set(this,void 0),V.set(this,void 0),b(this,X,new Uint8Array,"f"),b(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?dt(e):e;b(this,X,en([a(this,X,"f"),t]),"f");let r=[],n;for(;(n=Vn(a(this,X,"f"),a(this,V,"f")))!=null;){if(n.carriage&&a(this,V,"f")==null){b(this,V,n.index,"f");continue}if(a(this,V,"f")!=null&&(n.index!==a(this,V,"f")+1||n.carriage)){r.push(ts(a(this,X,"f").subarray(0,a(this,V,"f")-1))),b(this,X,a(this,X,"f").subarray(a(this,V,"f")),"f"),b(this,V,null,"f");continue}let o=a(this,V,"f")!==null?n.preceding-1:n.preceding,i=ts(a(this,X,"f").subarray(0,o));r.push(i),b(this,X,a(this,X,"f").subarray(n.index),"f"),b(this,V,null,"f")}return r}flush(){return a(this,X,"f").length?this.decode(`
3
+ `):[]}};X=new WeakMap,V=new WeakMap;ke.NEWLINE_CHARS=new Set([`
4
+ `,"\r"]);ke.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Vn(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function tn(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var yr={off:0,error:200,warn:300,info:400,debug:500},rs=(s,e,t)=>{if(s){if(ks(yr,s))return s;E(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(yr))}`)}};function Qt(){}function gr(s,e,t){return!e||yr[s]>yr[t]?Qt:e[s].bind(e)}var Kn={error:Qt,warn:Qt,info:Qt,debug:Qt},rn=new WeakMap;function E(s){let e=s.logger,t=s.logLevel??"off";if(!e)return Kn;let r=rn.get(e);if(r&&r[0]===t)return r[1];let n={error:gr("error",e,t),warn:gr("warn",e,t),info:gr("info",e,t),debug:gr("debug",e,t)};return rn.set(e,[t,n]),n}var ae=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Yt,se=class s{constructor(e,t,r){this.iterator=e,Yt.set(this,void 0),this.controller=t,b(this,Yt,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,i=r?E(r):console;async function*l(){if(o)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let h=!1;try{for await(let m of Gn(e,t))if(!h){if(m.data.startsWith("[DONE]")){h=!0;continue}if(m.event===null||!m.event.startsWith("thread.")){let g;try{g=JSON.parse(m.data)}catch(d){throw i.error("Could not parse message into JSON:",m.data),i.error("From chunk:",m.raw),d}if(g&&g.error)throw new T(void 0,g.error,void 0,e.headers);yield n?{event:m.event,data:g}:g}else{let g;try{g=JSON.parse(m.data)}catch(d){throw console.error("Could not parse message into JSON:",m.data),console.error("From chunk:",m.raw),d}if(m.event=="error")throw new T(void 0,g.error,g.message,void 0);yield{event:m.event,data:g}}}h=!0}catch(m){if(Gt(m))return;throw m}finally{h||t.abort()}}return new s(l,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let l=new ke,h=Kr(e);for await(let m of h)for(let g of l.decode(m))yield g;for(let m of l.flush())yield m}async function*i(){if(n)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{for await(let h of o())l||h&&(yield JSON.parse(h));l=!0}catch(h){if(Gt(h))return;throw h}finally{l||t.abort()}}return new s(i,t,r)}[(Yt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new s(()=>n(e),this.controller,a(this,Yt,"f")),new s(()=>n(t),this.controller,a(this,Yt,"f"))]}toReadableStream(){let e=this,t;return Vr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let i=dt(JSON.stringify(n)+`
5
+ `);r.enqueue(i)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*Gn(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new _("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new _("Attempted to iterate over a response with no body");let t=new ss,r=new ke,n=Kr(s.body);for await(let o of zn(n))for(let i of r.decode(o)){let l=t.decode(i);l&&(yield l)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*zn(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?dt(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=tn(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var ss=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
6
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=Qn(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Qn(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function br(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,i=await(async()=>{if(e.options.stream)return E(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData):se.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let h=t.headers.get("content-type")?.split(";")[0]?.trim();if(h?.includes("application/json")||h?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let y=await t.json();return ns(y,t)}return await t.text()})();return E(s).debug(`[${r}] response parsed`,ae({retryOfRequestLogID:n,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function ns(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Zt,Te=class s extends Promise{constructor(e,t,r=br){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,Zt.set(this,void 0),b(this,Zt,e,"f")}_thenUnwrap(e){return new s(a(this,Zt,"f"),this.responsePromise,async(t,r)=>ns(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(a(this,Zt,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Zt=new WeakMap;var wr,er=class{constructor(e,t,r,n){wr.set(this,void 0),b(this,wr,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new _("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,wr,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(wr=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},tr=class extends Te{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await br(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ne=class extends er{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},I=class extends er{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Jr(this.options.query),after:t}}:null}},G=class extends er{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Jr(this.options.query),after:e}}:null}};var as=()=>{if(typeof File>"u"){let{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function pt(s,e,t){return as(),new File(s,e??"unknown_file",t)}function rr(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}var xr=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",be=async(s,e)=>os(s.body)?{...s,body:await nn(s.body,e)}:s,q=async(s,e)=>({...s,body:await nn(s.body,e)}),sn=new WeakMap;function Zn(s){let e=typeof s=="function"?s:s.fetch,t=sn.get(e);if(t)return t;let r=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return sn.set(e,r),r}var nn=async(s,e)=>{if(!await Zn(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(s||{}).map(([r,n])=>is(t,r,n))),t},on=s=>s instanceof Blob&&"name"in s,eo=s=>typeof s=="object"&&s!==null&&(s instanceof Response||xr(s)||on(s)),os=s=>{if(eo(s))return!0;if(Array.isArray(s))return s.some(os);if(s&&typeof s=="object"){for(let e in s)if(os(s[e]))return!0}return!1},is=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,pt([await t.blob()],rr(t)));else if(xr(t))s.append(e,pt([await new Response(mr(t)).blob()],rr(t)));else if(on(t))s.append(e,t,rr(t));else if(Array.isArray(t))await Promise.all(t.map(r=>is(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>is(s,`${e}[${r}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var an=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",to=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&an(s),ro=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function Ar(s,e,t){if(as(),s=await s,to(s))return s instanceof File?s:pt([await s.arrayBuffer()],s.name);if(ro(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),pt(await ls(n),e,t)}let r=await ls(s);if(e||(e=rr(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return pt(r,e,t)}async function ls(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(an(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(xr(s))for await(let t of s)e.push(...await ls(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${so(s)}`)}return e}function so(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var u=class{constructor(e){this._client=e}};function cn(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ln=Object.freeze(Object.create(null)),oo=(s=cn)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],i=t.reduce((g,d,y)=>{/[?#]/.test(d)&&(n=!0);let f=r[y],P=(n?encodeURIComponent:s)(""+f);return y!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??ln)??ln)?.toString)&&(P=f+"",o.push({start:g.length+d.length,length:P.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),g+d+(y===r.length?"":P)},""),l=i.split(/[?#]/,1)[0],h=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,m;for(;(m=h.exec(l))!==null;)o.push({start:m.index,length:m[0].length,error:`Value "${m[0]}" can't be safely passed as a path parameter`});if(o.sort((g,d)=>g.start-d.start),o.length>0){let g=0,d=o.reduce((y,f)=>{let P=" ".repeat(f.start-g),x="^".repeat(f.length);return g=f.start+f.length,y+P+x},"");throw new _(`Path parameters result in path with invalid segments:
7
+ ${o.map(y=>y.error).join(`
8
+ `)}
9
+ ${i}
10
+ ${d}`)}return i},c=oo(cn);var Fe=class extends u{list(e,t={},r){return this._client.getAPIList(c`/chat/completions/${e}/messages`,I,{query:t,...r})}};function sr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function nr(s){return s?.$brand==="auto-parseable-response-format"}function Ne(s){return s?.$brand==="auto-parseable-tool"}function un(s,e){return!e||!cs(e)?{...s,choices:s.choices.map(t=>(hn(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:or(s,e)}function or(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new ut;if(r.finish_reason==="content_filter")throw new ft;return hn(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>co(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?lo(e,r.message.content):null}}});return{...s,choices:t}}function lo(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function co(s,e){let t=s.tools?.find(r=>sr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ne(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function fn(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>sr(r)&&r.function?.name===e.function.name);return sr(t)&&(Ne(t)||t?.function.strict||!1)}function cs(s){return nr(s.response_format)?!0:s.tools?.some(e=>Ne(e)||e.type==="function"&&e.function.strict===!0)??!1}function hn(s){for(let e of s||[])if(e.type!=="function")throw new _(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function dn(s){for(let e of s??[]){if(e.type!=="function")throw new _(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new _(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var mt=s=>s?.role==="assistant",us=s=>s?.role==="tool";var fs,Ir,Pr,ir,ar,Rr,lr,le,cr,Sr,Cr,_t,pn,we=class{constructor(){fs.add(this),this.controller=new AbortController,Ir.set(this,void 0),Pr.set(this,()=>{}),ir.set(this,()=>{}),ar.set(this,void 0),Rr.set(this,()=>{}),lr.set(this,()=>{}),le.set(this,{}),cr.set(this,!1),Sr.set(this,!1),Cr.set(this,!1),_t.set(this,!1),b(this,Ir,new Promise((e,t)=>{b(this,Pr,e,"f"),b(this,ir,t,"f")}),"f"),b(this,ar,new Promise((e,t)=>{b(this,Rr,e,"f"),b(this,lr,t,"f")}),"f"),a(this,Ir,"f").catch(()=>{}),a(this,ar,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},a(this,fs,"m",pn).bind(this))},0)}_connected(){this.ended||(a(this,Pr,"f").call(this),this._emit("connect"))}get ended(){return a(this,cr,"f")}get errored(){return a(this,Sr,"f")}get aborted(){return a(this,Cr,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,le,"f")[e]||(a(this,le,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,le,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(a(this,le,"f")[e]||(a(this,le,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{b(this,_t,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){b(this,_t,!0,"f"),await a(this,ar,"f")}_emit(e,...t){if(a(this,cr,"f"))return;e==="end"&&(b(this,cr,!0,"f"),a(this,Rr,"f").call(this));let r=a(this,le,"f")[e];if(r&&(a(this,le,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!a(this,_t,"f")&&!r?.length&&Promise.reject(n),a(this,ir,"f").call(this,n),a(this,lr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!a(this,_t,"f")&&!r?.length&&Promise.reject(n),a(this,ir,"f").call(this,n),a(this,lr,"f").call(this,n),this._emit("end")}}_emitFinal(){}};Ir=new WeakMap,Pr=new WeakMap,ir=new WeakMap,ar=new WeakMap,Rr=new WeakMap,lr=new WeakMap,le=new WeakMap,cr=new WeakMap,Sr=new WeakMap,Cr=new WeakMap,_t=new WeakMap,fs=new WeakSet,pn=function(e){if(b(this,Sr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new $),e instanceof $)return b(this,Cr,!0,"f"),this._emit("abort",e);if(e instanceof _)return this._emit("error",e);if(e instanceof Error){let t=new _(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new _(String(e)))};function mn(s){return typeof s.parse=="function"}var H,hs,Er,ds,ps,ms,_n,gn,uo=10,gt=class extends we{constructor(){super(...arguments),H.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),us(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(mt(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new _("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),a(this,H,"m",hs).call(this)}async finalMessage(){return await this.done(),a(this,H,"m",Er).call(this)}async finalFunctionToolCall(){return await this.done(),a(this,H,"m",ds).call(this)}async finalFunctionToolCallResult(){return await this.done(),a(this,H,"m",ps).call(this)}async totalUsage(){return await this.done(),a(this,H,"m",ms).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=a(this,H,"m",Er).call(this);t&&this._emit("finalMessage",t);let r=a(this,H,"m",hs).call(this);r&&this._emit("finalContent",r);let n=a(this,H,"m",ds).call(this);n&&this._emit("finalFunctionToolCall",n);let o=a(this,H,"m",ps).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",a(this,H,"m",ms).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),a(this,H,"m",_n).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(or(o,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let n="tool",{tool_choice:o="auto",stream:i,...l}=t,h=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:m=uo}=r||{},g=t.tools.map(f=>{if(Ne(f)){if(!f.$callback)throw new _("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),d={};for(let f of g)f.type==="function"&&(d[f.function.name||f.function.function.name]=f.function);let y="tools"in t?g.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<m;++f){let x=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:y,messages:[...this.messages]},r)).choices[0]?.message;if(!x)throw new _("missing message in ChatCompletion response");if(!x.tool_calls?.length)return;for(let v of x.tool_calls){if(v.type!=="function")continue;let R=v.id,{name:w,arguments:M}=v.function,S=d[w];if(S){if(h&&h!==w){let L=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(h)} requested. Please try again`;this._addMessage({role:n,tool_call_id:R,content:L});continue}}else{let L=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(d).map(B=>JSON.stringify(B)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:R,content:L});continue}let J;try{J=mn(S)?await S.parse(M):M}catch(L){let B=L instanceof Error?L.message:String(L);this._addMessage({role:n,tool_call_id:R,content:B});continue}let W=await S.function(J,this),C=a(this,H,"m",gn).call(this,W);if(this._addMessage({role:n,tool_call_id:R,content:C}),h)return}}}};H=new WeakSet,hs=function(){return a(this,H,"m",Er).call(this).content??null},Er=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(mt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new _("stream ended without producing a ChatCompletionMessage with role=assistant")},ds=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(mt(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},ps=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(us(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},ms=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},_n=function(e){if(e.n!=null&&e.n>1)throw new _("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},gn=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var ur=class s extends gt{static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),mt(e)&&e.content&&this._emit("content",e.content)}};var j={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},_s=class extends Error{},gs=class extends Error{};function fo(s,e=j.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return ho(s.trim(),e)}var ho=(s,e)=>{let t=s.length,r=0,n=y=>{throw new _s(`${y} at position ${r}`)},o=y=>{throw new gs(`${y} at position ${r}`)},i=()=>(d(),r>=t&&n("Unexpected end of input"),s[r]==='"'?l():s[r]==="{"?h():s[r]==="["?m():s.substring(r,r+4)==="null"||j.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||j.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||j.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||j.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||j.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||j.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):g()),l=()=>{let y=r,f=!1;for(r++;r<t&&(s[r]!=='"'||f&&s[r-1]==="\\");)f=s[r]==="\\"?!f:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(y,++r-Number(f)))}catch(P){o(String(P))}else if(j.STR&e)try{return JSON.parse(s.substring(y,r-Number(f))+'"')}catch{return JSON.parse(s.substring(y,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},h=()=>{r++,d();let y={};try{for(;s[r]!=="}";){if(d(),r>=t&&j.OBJ&e)return y;let f=l();d(),r++;try{let P=i();Object.defineProperty(y,f,{value:P,writable:!0,enumerable:!0,configurable:!0})}catch(P){if(j.OBJ&e)return y;throw P}d(),s[r]===","&&r++}}catch{if(j.OBJ&e)return y;n("Expected '}' at end of object")}return r++,y},m=()=>{r++;let y=[];try{for(;s[r]!=="]";)y.push(i()),d(),s[r]===","&&r++}catch{if(j.ARR&e)return y;n("Expected ']' at end of array")}return r++,y},g=()=>{if(r===0){s==="-"&&j.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(f){if(j.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(f))}}let y=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(j.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(y,r))}catch{s.substring(y,r)==="-"&&j.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(y,s.lastIndexOf("e")))}catch(P){o(String(P))}}},d=()=>{for(;r<t&&`
11
+ \r `.includes(s[r]);)r++};return i()},ys=s=>fo(s,j.ALL^j.NUM);var N,ce,yt,xe,bs,vr,ws,xs,As,Or,Is,yn,Me=class s extends gt{constructor(e){super(),N.add(this),ce.set(this,void 0),yt.set(this,void 0),xe.set(this,void 0),b(this,ce,e,"f"),b(this,yt,[],"f")}get currentChatCompletionSnapshot(){return a(this,xe,"f")}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),a(this,N,"m",bs).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)a(this,N,"m",ws).call(this,i);if(o.controller.signal?.aborted)throw new $;return this._addChatCompletion(a(this,N,"m",Or).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),a(this,N,"m",bs).call(this),this._connected();let n=se.fromReadableStream(e,this.controller),o;for await(let i of n)o&&o!==i.id&&this._addChatCompletion(a(this,N,"m",Or).call(this)),a(this,N,"m",ws).call(this,i),o=i.id;if(n.controller.signal?.aborted)throw new $;return this._addChatCompletion(a(this,N,"m",Or).call(this))}[(ce=new WeakMap,yt=new WeakMap,xe=new WeakMap,N=new WeakSet,bs=function(){this.ended||b(this,xe,void 0,"f")},vr=function(t){let r=a(this,yt,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},a(this,yt,"f")[t.index]=r,r)},ws=function(t){if(this.ended)return;let r=a(this,N,"m",yn).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=a(this,N,"m",vr).call(this,o);o.finish_reason&&(a(this,N,"m",As).call(this,o),i.current_tool_call_index!=null&&a(this,N,"m",xs).call(this,o,i.current_tool_call_index));for(let l of n.delta.tool_calls??[])i.current_tool_call_index!==l.index&&(a(this,N,"m",As).call(this,o),i.current_tool_call_index!=null&&a(this,N,"m",xs).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=l.index;for(let l of n.delta.tool_calls??[]){let h=o.message.tool_calls?.[l.index];h?.type&&(h?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:h.function?.name,index:l.index,arguments:h.function.arguments,parsed_arguments:h.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(h?.type,void 0))}}},xs=function(t,r){if(a(this,N,"m",vr).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=a(this,ce,"f")?.tools?.find(l=>sr(l)&&l.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Ne(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},As=function(t){let r=a(this,N,"m",vr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=a(this,N,"m",Is).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Or=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=a(this,xe,"f");if(!t)throw new _("request ended without sending any chunks");return b(this,xe,void 0,"f"),b(this,yt,[],"f"),po(t,a(this,ce,"f"))},Is=function(){let t=a(this,ce,"f")?.response_format;return nr(t)?t:null},yn=function(t){var r,n,o,i;let l=a(this,xe,"f"),{choices:h,...m}=t;l?Object.assign(l,m):l=b(this,xe,{...m,choices:[]},"f");for(let{delta:g,finish_reason:d,index:y,logprobs:f=null,...P}of t.choices){let x=l.choices[y];if(x||(x=l.choices[y]={finish_reason:d,index:y,message:{},logprobs:f,...P}),f)if(!x.logprobs)x.logprobs=Object.assign({},f);else{let{content:W,refusal:C,...L}=f;Object.assign(x.logprobs,L),W&&((r=x.logprobs).content??(r.content=[]),x.logprobs.content.push(...W)),C&&((n=x.logprobs).refusal??(n.refusal=[]),x.logprobs.refusal.push(...C))}if(d&&(x.finish_reason=d,a(this,ce,"f")&&cs(a(this,ce,"f")))){if(d==="length")throw new ut;if(d==="content_filter")throw new ft}if(Object.assign(x,P),!g)continue;let{content:v,refusal:R,function_call:w,role:M,tool_calls:S,...J}=g;if(Object.assign(x.message,J),R&&(x.message.refusal=(x.message.refusal||"")+R),M&&(x.message.role=M),w&&(x.message.function_call?(w.name&&(x.message.function_call.name=w.name),w.arguments&&((o=x.message.function_call).arguments??(o.arguments=""),x.message.function_call.arguments+=w.arguments)):x.message.function_call=w),v&&(x.message.content=(x.message.content||"")+v,!x.message.refusal&&a(this,N,"m",Is).call(this)&&(x.message.parsed=ys(x.message.content))),S){x.message.tool_calls||(x.message.tool_calls=[]);for(let{index:W,id:C,type:L,function:B,...O}of S){let k=(i=x.message.tool_calls)[W]??(i[W]={});Object.assign(k,O),C&&(k.id=C),L&&(k.type=L),B&&(k.function??(k.function={name:B.name??"",arguments:""})),B?.name&&(k.function.name=B.name),B?.arguments&&(k.function.arguments+=B.arguments,fn(a(this,ce,"f"),k)&&(k.function.parsed_arguments=ys(k.function.arguments)))}}}return l},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new se(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function po(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:i,...l}=s,h={...l,id:t,choices:r.map(({message:m,finish_reason:g,index:d,logprobs:y,...f})=>{if(!g)throw new _(`missing finish_reason for choice ${d}`);let{content:P=null,function_call:x,tool_calls:v,...R}=m,w=m.role;if(!w)throw new _(`missing role for choice ${d}`);if(x){let{arguments:M,name:S}=x;if(M==null)throw new _(`missing function_call.arguments for choice ${d}`);if(!S)throw new _(`missing function_call.name for choice ${d}`);return{...f,message:{content:P,function_call:{arguments:M,name:S},role:w,refusal:m.refusal??null},finish_reason:g,index:d,logprobs:y}}return v?{...f,index:d,finish_reason:g,logprobs:y,message:{...R,role:w,content:P,refusal:m.refusal??null,tool_calls:v.map((M,S)=>{let{function:J,type:W,id:C,...L}=M,{arguments:B,name:O,...k}=J||{};if(C==null)throw new _(`missing choices[${d}].tool_calls[${S}].id
12
+ ${$r(s)}`);if(W==null)throw new _(`missing choices[${d}].tool_calls[${S}].type
13
+ ${$r(s)}`);if(O==null)throw new _(`missing choices[${d}].tool_calls[${S}].function.name
14
+ ${$r(s)}`);if(B==null)throw new _(`missing choices[${d}].tool_calls[${S}].function.arguments
15
+ ${$r(s)}`);return{...L,id:C,type:W,function:{...k,name:O,arguments:B}}})}}:{...f,message:{...R,content:P,role:w,refusal:m.refusal??null},finish_reason:g,index:d,logprobs:y}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return un(h,e)}function $r(s){return JSON.stringify(s)}var fr=class s extends Me{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}};var ue=class extends u{constructor(){super(...arguments),this.messages=new Fe(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(c`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(c`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/chat/completions/${e}`,t)}parse(e,t){return dn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>or(r,e))}runTools(e,t){return e.stream?fr.runTools(this._client,e,t):ur.runTools(this._client,e,t)}stream(e,t){return Me.createChatCompletion(this._client,e,t)}};ue.Messages=Fe;var Ae=class extends u{constructor(){super(...arguments),this.completions=new ue(this._client)}};Ae.Completions=ue;var bn=Symbol("brand.privateNullableHeaders");function*_o(s){if(!s)return;if(bn in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():Hr(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=Hr(r[1])?r[1]:[r[1]],i=!1;for(let l of o)l!==void 0&&(e&&!i&&(i=!0,yield[n,null]),yield[n,l])}}var p=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,i]of _o(r)){let l=o.toLowerCase();n.has(l)||(e.delete(o),n.add(l)),i===null?(e.delete(o),t.add(l)):(e.append(o,i),t.delete(l))}}return{[bn]:!0,values:e,nulls:t}};var bt=class extends u{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:p([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var wt=class extends u{create(e,t){return this._client.post("/audio/transcriptions",q({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var xt=class extends u{create(e,t){return this._client.post("/audio/translations",q({body:e,...t,__metadata:{model:e.model}},this._client))}};var oe=class extends u{constructor(){super(...arguments),this.transcriptions=new wt(this._client),this.translations=new xt(this._client),this.speech=new bt(this._client)}};oe.Transcriptions=wt;oe.Translations=xt;oe.Speech=bt;var Le=class extends u{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(c`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",I,{query:e,...t})}cancel(e,t){return this._client.post(c`/batches/${e}/cancel`,t)}};var At=class extends u{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/assistants/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",I,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var It=class extends u{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Pt=class extends u{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Ie=class extends u{constructor(){super(...arguments),this.sessions=new It(this._client),this.transcriptionSessions=new Pt(this._client)}};Ie.Sessions=It;Ie.TranscriptionSessions=Pt;var Rt=class extends u{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(c`/chatkit/sessions/${e}/cancel`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}};var St=class extends u{retrieve(e,t){return this._client.get(c`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",G,{query:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(c`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(c`/chatkit/threads/${e}/items`,G,{query:t,...r,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};var Pe=class extends u{constructor(){super(...arguments),this.sessions=new Rt(this._client),this.threads=new St(this._client)}};Pe.Sessions=Rt;Pe.Threads=St;var Ct=class extends u{create(e,t,r){return this._client.post(c`/threads/${e}/messages`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/messages/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/messages/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/messages`,I,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(c`/threads/${n}/messages/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Et=class extends u{retrieve(e,t,r){let{thread_id:n,run_id:o,...i}=t;return this._client.get(c`/threads/${n}/runs/${o}/steps/${e}`,{query:i,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(c`/threads/${n}/runs/${e}/steps`,I,{query:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var wn=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var z=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()};var U,je,Ps,ie,kr,Q,Ue,vt,Be,Nr,K,Tr,Fr,pr,hr,dr,xn,An,In,Pn,Rn,Sn,Cn,fe=class extends we{constructor(){super(...arguments),U.add(this),Ps.set(this,[]),ie.set(this,{}),kr.set(this,{}),Q.set(this,void 0),Ue.set(this,void 0),vt.set(this,void 0),Be.set(this,void 0),Nr.set(this,void 0),K.set(this,void 0),Tr.set(this,void 0),Fr.set(this,void 0),pr.set(this,void 0)}[(Ps=new WeakMap,ie=new WeakMap,kr=new WeakMap,Q=new WeakMap,Ue=new WeakMap,vt=new WeakMap,Be=new WeakMap,Nr=new WeakMap,K=new WeakMap,Tr=new WeakMap,Fr=new WeakMap,pr=new WeakMap,U=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new je;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=se.fromReadableStream(e,this.controller);for await(let o of n)a(this,U,"m",hr).call(this,o);if(n.controller.signal?.aborted)throw new $;return this._addRun(a(this,U,"m",dr).call(this))}toReadableStream(){return new se(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new je;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(let h of l)a(this,U,"m",hr).call(this,h);if(l.controller.signal?.aborted)throw new $;return this._addRun(a(this,U,"m",dr).call(this))}static createThreadAssistantStream(e,t,r){let n=new je;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new je;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return a(this,Tr,"f")}currentRun(){return a(this,Fr,"f")}currentMessageSnapshot(){return a(this,Q,"f")}currentRunStepSnapshot(){return a(this,pr,"f")}async finalRunSteps(){return await this.done(),Object.values(a(this,ie,"f"))}async finalMessages(){return await this.done(),Object.values(a(this,kr,"f"))}async finalRun(){if(await this.done(),!a(this,Ue,"f"))throw Error("Final run was not received.");return a(this,Ue,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let l of i)a(this,U,"m",hr).call(this,l);if(i.controller.signal?.aborted)throw new $;return this._addRun(a(this,U,"m",dr).call(this))}async _createAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(let h of l)a(this,U,"m",hr).call(this,h);if(l.controller.signal?.aborted)throw new $;return this._addRun(a(this,U,"m",dr).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(ht(o)&&ht(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!ht(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let h=o[l];h==null?o.push(i):o[l]=this.accumulateDelta(h,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};je=fe,hr=function(e){if(!this.ended)switch(b(this,Tr,e,"f"),a(this,U,"m",In).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":a(this,U,"m",Cn).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":a(this,U,"m",An).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":a(this,U,"m",xn).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},dr=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");if(!a(this,Ue,"f"))throw Error("Final run has not been received");return a(this,Ue,"f")},xn=function(e){let[t,r]=a(this,U,"m",Rn).call(this,e,a(this,Q,"f"));b(this,Q,t,"f"),a(this,kr,"f")[t.id]=t;for(let n of r){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,i=t.content[n.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=a(this,vt,"f")){if(a(this,Be,"f"))switch(a(this,Be,"f").type){case"text":this._emit("textDone",a(this,Be,"f").text,a(this,Q,"f"));break;case"image_file":this._emit("imageFileDone",a(this,Be,"f").image_file,a(this,Q,"f"));break}b(this,vt,n.index,"f")}b(this,Be,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(a(this,vt,"f")!==void 0){let n=e.data.content[a(this,vt,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,a(this,Q,"f"));break;case"text":this._emit("textDone",n.text,a(this,Q,"f"));break}}a(this,Q,"f")&&this._emit("messageDone",e.data),b(this,Q,void 0,"f")}},An=function(e){let t=a(this,U,"m",Pn).call(this,e);switch(b(this,pr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==a(this,Nr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(a(this,K,"f")&&this._emit("toolCallDone",a(this,K,"f")),b(this,Nr,o.index,"f"),b(this,K,t.step_details.tool_calls[o.index],"f"),a(this,K,"f")&&this._emit("toolCallCreated",a(this,K,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":b(this,pr,void 0,"f"),e.data.step_details.type=="tool_calls"&&a(this,K,"f")&&(this._emit("toolCallDone",a(this,K,"f")),b(this,K,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},In=function(e){a(this,Ps,"f").push(e),this._emit("event",e)},Pn=function(e){switch(e.event){case"thread.run.step.created":return a(this,ie,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=a(this,ie,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=je.accumulateDelta(t,r.delta);a(this,ie,"f")[e.data.id]=n}return a(this,ie,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":a(this,ie,"f")[e.data.id]=e.data;break}if(a(this,ie,"f")[e.data.id])return a(this,ie,"f")[e.data.id];throw new Error("No snapshot available")},Rn=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=a(this,U,"m",Sn).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Sn=function(e,t){return je.accumulateDelta(t,e)},Cn=function(e){switch(b(this,Fr,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":b(this,Ue,e.data,"f"),a(this,K,"f")&&(this._emit("toolCallDone",a(this,K,"f")),b(this,K,void 0,"f"));break;case"thread.run.cancelling":break}};var De=class extends u{constructor(){super(...arguments),this.steps=new Et(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/runs/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/runs`,I,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(c`/threads/${n}/runs/${e}/cancel`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return fe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=p([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let h=i.headers.get("openai-poll-after-ms");if(h){let m=parseInt(h);isNaN(m)||(l=m)}}await te(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return fe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return fe.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};De.Steps=Et;var Re=class extends u{constructor(){super(...arguments),this.runs=new De(this._client),this.messages=new Ct(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/threads/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(c`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return fe.createThreadAssistantStream(e,this._client.beta.threads,t)}};Re.Runs=De;Re.Messages=Ct;var Y=class extends u{constructor(){super(...arguments),this.realtime=new Ie(this._client),this.chatkit=new Pe(this._client),this.assistants=new At(this._client),this.threads=new Re(this._client)}};Y.Realtime=Ie;Y.ChatKit=Pe;Y.Assistants=At;Y.Threads=Re;var qe=class extends u{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var Ot=class extends u{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}/content`,{...r,headers:p([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var We=class extends u{constructor(){super(...arguments),this.content=new Ot(this._client)}create(e,t,r){return this._client.post(c`/containers/${e}/files`,be({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/containers/${e}/files`,I,{query:t,...r})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(c`/containers/${n}/files/${e}`,{...r,headers:p([{Accept:"*/*"},r?.headers])})}};We.Content=Ot;var Se=class extends u{constructor(){super(...arguments),this.files=new We(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(c`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/containers/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}};Se.Files=We;var $t=class extends u{create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/conversations/${e}/items`,{query:{include:n},body:o,...r})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(c`/conversations/${n}/items/${e}`,{query:o,...r})}list(e,t={},r){return this._client.getAPIList(c`/conversations/${e}/items`,G,{query:t,...r})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(c`/conversations/${n}/items/${e}`,r)}};var Ce=class extends u{constructor(){super(...arguments),this.items=new $t(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(c`/conversations/${e}`,t)}update(e,t,r){return this._client.post(c`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(c`/conversations/${e}`,t)}};Ce.Items=$t;var He=class extends u{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&E(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?o:(E(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{let h=l.embedding;l.embedding=wn(h)}),i)))}};var kt=class extends u{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(c`/evals/${n}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(c`/evals/${n}/runs/${e}/output_items`,I,{query:o,...r})}};var Je=class extends u{constructor(){super(...arguments),this.outputItems=new kt(this._client)}create(e,t,r){return this._client.post(c`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(c`/evals/${n}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/evals/${e}/runs`,I,{query:t,...r})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(c`/evals/${n}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(c`/evals/${n}/runs/${e}`,r)}};Je.OutputItems=kt;var Ee=class extends u{constructor(){super(...arguments),this.runs=new Je(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(c`/evals/${e}`,t)}update(e,t,r){return this._client.post(c`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/evals/${e}`,t)}};Ee.Runs=Je;var Xe=class extends u{create(e,t){return this._client.post("/files",q({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/files/${e}`,t)}content(e,t){return this._client.get(c`/files/${e}/content`,{...t,headers:p([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=30*60*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await te(t),i=await this.retrieve(e),Date.now()-o>r)throw new ge({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};var Tt=class extends u{};var Ft=class extends u{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var Ve=class extends u{constructor(){super(...arguments),this.graders=new Ft(this._client)}};Ve.Graders=Ft;var Nt=class extends u{create(e,t,r){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,ne,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(c`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}list(e,t={},r){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,G,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(c`/fine_tuning/checkpoints/${n}/permissions/${e}`,r)}};var Ke=class extends u{constructor(){super(...arguments),this.permissions=new Nt(this._client)}};Ke.Permissions=Nt;var Mt=class extends u{list(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/checkpoints`,I,{query:t,...r})}};var Ge=class extends u{constructor(){super(...arguments),this.checkpoints=new Mt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(c`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",I,{query:e,...t})}cancel(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/events`,I,{query:t,...r})}pause(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/resume`,t)}};Ge.Checkpoints=Mt;var Z=class extends u{constructor(){super(...arguments),this.methods=new Tt(this._client),this.jobs=new Ge(this._client),this.checkpoints=new Ke(this._client),this.alpha=new Ve(this._client)}};Z.Methods=Tt;Z.Jobs=Ge;Z.Checkpoints=Ke;Z.Alpha=Ve;var Lt=class extends u{};var ve=class extends u{constructor(){super(...arguments),this.graderModels=new Lt(this._client)}};ve.GraderModels=Lt;var ze=class extends u{createVariation(e,t){return this._client.post("/images/variations",q({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",q({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};var Qe=class extends u{retrieve(e,t){return this._client.get(c`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ne,e)}delete(e,t){return this._client.delete(c`/models/${e}`,t)}};var Ye=class extends u{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var Bt=class extends u{accept(e,t,r){return this._client.post(c`/realtime/calls/${e}/accept`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(c`/realtime/calls/${e}/hangup`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(c`/realtime/calls/${e}/refer`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(c`/realtime/calls/${e}/reject`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers])})}};var jt=class extends u{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}};var he=class extends u{constructor(){super(...arguments),this.clientSecrets=new jt(this._client),this.calls=new Bt(this._client)}};he.ClientSecrets=jt;he.Calls=Bt;function En(s,e){return!e||!Vo(e)?{...s,output_parsed:null,output:s.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:Rs(s,e)}function Rs(s,e){let t=s.output.map(n=>{if(n.type==="function_call")return{...n,parsed_arguments:zo(e,n)};if(n.type==="message"){let o=n.content.map(i=>i.type==="output_text"?{...i,parsed:Xo(e,i.text)}:i);return{...n,content:o}}return n}),r=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||Mr(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let n of r.output)if(n.type==="message"){for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function Xo(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Vo(s){return!!nr(s.text?.format)}function Ko(s){return s?.$brand==="auto-parseable-tool"}function Go(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function zo(s,e){let t=Go(s.tools??[],e.name);return{...e,...e,parsed_arguments:Ko(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Mr(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}var Ut,Lr,Oe,Br,vn,On,$n,kn,jr=class s extends we{constructor(e){super(),Ut.add(this),Lr.set(this,void 0),Oe.set(this,void 0),Br.set(this,void 0),b(this,Lr,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),a(this,Ut,"m",vn).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let l of o)a(this,Ut,"m",On).call(this,l,i);if(o.controller.signal?.aborted)throw new $;return a(this,Ut,"m",$n).call(this)}[(Lr=new WeakMap,Oe=new WeakMap,Br=new WeakMap,Ut=new WeakSet,vn=function(){this.ended||b(this,Oe,void 0,"f")},On=function(t,r){if(this.ended)return;let n=(i,l)=>{(r==null||l.sequence_number>r)&&this._emit(i,l)},o=a(this,Ut,"m",kn).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new _(`missing output at index ${t.output_index}`);if(i.type==="message"){let l=i.content[t.content_index];if(!l)throw new _(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new _(`expected content to be 'output_text', got ${l.type}`);n("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new _(`missing output at index ${t.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:n(t.type,t);break}},$n=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=a(this,Oe,"f");if(!t)throw new _("request ended without sending any events");b(this,Oe,void 0,"f");let r=Qo(t,a(this,Lr,"f"));return b(this,Br,r,"f"),r},kn=function(t){let r=a(this,Oe,"f");if(!r){if(t.type!=="response.created")throw new _(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=b(this,Oe,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let n=r.output[t.output_index];if(!n)throw new _(`missing output at index ${t.output_index}`);let o=n.type,i=t.part;o==="message"&&i.type!=="reasoning_text"?n.content.push(i):o==="reasoning"&&i.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(i));break}case"response.output_text.delta":{let n=r.output[t.output_index];if(!n)throw new _(`missing output at index ${t.output_index}`);if(n.type==="message"){let o=n.content[t.content_index];if(!o)throw new _(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new _(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=r.output[t.output_index];if(!n)throw new _(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.reasoning_text.delta":{let n=r.output[t.output_index];if(!n)throw new _(`missing output at index ${t.output_index}`);if(n.type==="reasoning"){let o=n.content?.[t.content_index];if(!o)throw new _(`missing content at index ${t.content_index}`);if(o.type!=="reasoning_text")throw new _(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=t.delta}break}case"response.completed":{b(this,Oe,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=a(this,Br,"f");if(!e)throw new _("stream ended without producing a ChatCompletion");return e}};function Qo(s,e){return En(s,e)}var Dt=class extends u{list(e,t={},r){return this._client.getAPIList(c`/responses/${e}/input_items`,I,{query:t,...r})}};var qt=class extends u{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}};var de=class extends u{constructor(){super(...arguments),this.inputItems=new Dt(this._client),this.inputTokens=new qt(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Mr(r),r))}retrieve(e,t={},r){return this._client.get(c`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Mr(n),n))}delete(e,t){return this._client.delete(c`/responses/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Rs(r,e))}stream(e,t){return jr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(c`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}};de.InputItems=Dt;de.InputTokens=qt;var Wt=class extends u{retrieve(e,t){return this._client.get(c`/skills/${e}/content`,{...t,headers:p([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}};var Ht=class extends u{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(c`/skills/${n}/versions/${e}/content`,{...r,headers:p([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var Ze=class extends u{constructor(){super(...arguments),this.content=new Ht(this._client)}create(e,t={},r){return this._client.post(c`/skills/${e}/versions`,be({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(c`/skills/${n}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/skills/${e}/versions`,I,{query:t,...r})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(c`/skills/${n}/versions/${e}`,r)}};Ze.Content=Ht;var pe=class extends u{constructor(){super(...arguments),this.content=new Wt(this._client),this.versions=new Ze(this._client)}create(e={},t){return this._client.post("/skills",be({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/skills/${e}`,t)}update(e,t,r){return this._client.post(c`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/skills/${e}`,t)}};pe.Content=Wt;pe.Versions=Ze;var Jt=class extends u{create(e,t,r){return this._client.post(c`/uploads/${e}/parts`,q({body:t,...r},this._client))}};var $e=class extends u{constructor(){super(...arguments),this.parts=new Jt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(c`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(c`/uploads/${e}/complete`,{body:t,...r})}};$e.Parts=Jt;var Tn=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var Xt=class extends u{create(e,t,r){return this._client.post(c`/vector_stores/${e}/file_batches`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/file_batches/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(c`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...o}=t;return this._client.getAPIList(c`/vector_stores/${n}/file_batches/${e}/files`,I,{query:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let n=p([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let h=i.headers.get("openai-poll-after-ms");if(h){let m=parseInt(h);isNaN(m)||(l=m)}}await te(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,i=Math.min(o,t.length),l=this._client,h=t.values(),m=[...r];async function g(y){for(let f of y){let P=await l.files.create({file:f,purpose:"assistants"},n);m.push(P.id)}}let d=Array(i).fill(h).map(g);return await Tn(d),await this.createAndPoll(e,{file_ids:m})}};var Vt=class extends u{create(e,t,r){return this._client.post(c`/vector_stores/${e}/files`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/files/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(c`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/vector_stores/${e}/files`,I,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(c`/vector_stores/${n}/files/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=p([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),i=o.data;switch(i.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let h=o.response.headers.get("openai-poll-after-ms");if(h){let m=parseInt(h);isNaN(m)||(l=m)}}await te(l);break;case"failed":case"completed":return i}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(c`/vector_stores/${n}/files/${e}/content`,ne,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var me=class extends u{constructor(){super(...arguments),this.files=new Vt(this._client),this.fileBatches=new Xt(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/vector_stores/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",I,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(c`/vector_stores/${e}/search`,ne,{body:t,method:"post",...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};me.Files=Vt;me.FileBatches=Xt;var et=class extends u{create(e,t){return this._client.post("/videos",q({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",G,{query:e,...t})}delete(e,t){return this._client.delete(c`/videos/${e}`,t)}createCharacter(e,t){return this._client.post("/videos/characters",q({body:e,...t},this._client))}downloadContent(e,t={},r){return this._client.get(c`/videos/${e}/content`,{query:t,...r,headers:p([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",q({body:e,...t},this._client))}extend(e,t){return this._client.post("/videos/extensions",q({body:e,...t},this._client))}getCharacter(e,t){return this._client.get(c`/videos/characters/${e}`,t)}remix(e,t,r){return this._client.post(c`/videos/${e}/remix`,be({body:t,...r},this._client))}};var Kt,Fn,Ur,tt=class extends u{constructor(){super(...arguments),Kt.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");a(this,Kt,"m",Fn).call(this,r);let o=p([t]).values,i=a(this,Kt,"m",Ur).call(this,o,"webhook-signature"),l=a(this,Kt,"m",Ur).call(this,o,"webhook-timestamp"),h=a(this,Kt,"m",Ur).call(this,o,"webhook-id"),m=parseInt(l,10);if(isNaN(m))throw new ee("Invalid webhook timestamp format");let g=Math.floor(Date.now()/1e3);if(g-m>n)throw new ee("Webhook timestamp is too old");if(m>g+n)throw new ee("Webhook timestamp is too new");let d=i.split(" ").map(x=>x.startsWith("v1,")?x.substring(3):x),y=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=h?`${h}.${l}.${e}`:`${l}.${e}`,P=await crypto.subtle.importKey("raw",y,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let x of d)try{let v=Buffer.from(x,"base64");if(await crypto.subtle.verify("HMAC",P,v,new TextEncoder().encode(f)))return}catch{continue}throw new ee("The given webhook signature does not match the expected signature")}};Kt=new WeakSet,Fn=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Ur=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var Ss,Cs,Dr,Nn,A=class{constructor({baseURL:e=z("OPENAI_BASE_URL"),apiKey:t=z("OPENAI_API_KEY"),organization:r=z("OPENAI_ORG_ID")??null,project:n=z("OPENAI_PROJECT_ID")??null,webhookSecret:o=z("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Ss.add(this),Dr.set(this,void 0),this.completions=new qe(this),this.chat=new Ae(this),this.embeddings=new He(this),this.files=new Xe(this),this.images=new ze(this),this.audio=new oe(this),this.moderations=new Ye(this),this.models=new Qe(this),this.fineTuning=new Z(this),this.graders=new ve(this),this.vectorStores=new me(this),this.webhooks=new tt(this),this.beta=new Y(this),this.batches=new Le(this),this.uploads=new $e(this),this.responses=new de(this),this.realtime=new he(this),this.conversations=new Ce(this),this.evals=new Ee(this),this.containers=new Se(this),this.skills=new pe(this),this.videos=new et(this),t===void 0)throw new _("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let l={apiKey:t,organization:r,project:n,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&Bs())throw new _(`It looks like you're running in a browser-like environment.
16
+
17
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
18
+ If you understand the risks and have appropriate mitigations in place,
19
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
20
+
21
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
22
+
23
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
24
+ `);this.baseURL=l.baseURL,this.timeout=l.timeout??Cs.DEFAULT_TIMEOUT,this.logger=l.logger??console;let h="warn";this.logLevel=h,this.logLevel=rs(l.logLevel,"ClientOptions.logLevel",this)??rs(z("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??h,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??Us(),b(this,Dr,qs,"f"),this._options=l,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=r,this.project=n,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return p([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Qs(e)}getUserAgent(){return`${this.constructor.name}/JS ${ye}`}defaultIdempotencyKey(){return`stainless-node-retry-${Wr()}`}makeStatusError(e,t,r,n){return T.generate(e,t,r,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof _?r:new _(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new _(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!a(this,Ss,"m",Nn).call(this)&&r||this.baseURL,o=$s(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),l=Object.fromEntries(o.searchParams);return(!Xr(i)||!Xr(l))&&(t={...l,...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Te(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:i,url:l,timeout:h}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(i,{url:l,options:n});let m="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(E(this).debug(`[${m}] sending request`,ae({retryOfRequestLogID:r,method:n.method,url:l,options:n,headers:i.headers})),n.signal?.aborted)throw new $;let y=new AbortController,f=await this.fetchWithTimeout(l,i,h,y).catch(zt),P=Date.now();if(f instanceof globalThis.Error){let R=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new $;let w=Gt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return E(this).info(`[${m}] connection ${w?"timed out":"failed"} - ${R}`),E(this).debug(`[${m}] connection ${w?"timed out":"failed"} (${R})`,ae({retryOfRequestLogID:r,url:l,durationMs:P-d,message:f.message})),this.retryRequest(n,t,r??m);throw E(this).info(`[${m}] connection ${w?"timed out":"failed"} - error; no more retries left`),E(this).debug(`[${m}] connection ${w?"timed out":"failed"} (error; no more retries left)`,ae({retryOfRequestLogID:r,url:l,durationMs:P-d,message:f.message})),w?new ge:new _e({cause:f})}let x=[...f.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,w])=>", "+R+": "+JSON.stringify(w)).join(""),v=`[${m}${g}${x}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${P-d}ms`;if(!f.ok){let R=await this.shouldRetry(f);if(t&&R){let C=`retrying, ${t} attempts remaining`;return await Ds(f.body),E(this).info(`${v} - ${C}`),E(this).debug(`[${m}] response error (${C})`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:P-d})),this.retryRequest(n,t,r??m,f.headers)}let w=R?"error; no more retries left":"error; not retryable";E(this).info(`${v} - ${w}`);let M=await f.text().catch(C=>zt(C).message),S=Fs(M),J=S?void 0:M;throw E(this).debug(`[${m}] response error (${w})`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:J,durationMs:Date.now()-d})),this.makeStatusError(f.status,S,J,f.headers)}return E(this).info(v),E(this).debug(`[${m}] response start`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:P-d})),{response:f,options:n,controller:y,requestLogID:m,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new tr(this,r,e)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:i,...l}=t||{},h=this._makeAbort(n);o&&o.addEventListener("abort",h,{once:!0});let m=setTimeout(h,r),g=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,d={signal:n.signal,...g?{duplex:"half"}:{},method:"GET",...l};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(m)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,n){let o,i=n?.get("retry-after-ms");if(i){let h=parseFloat(i);Number.isNaN(h)||(o=h)}let l=n?.get("retry-after");if(l&&!o){let h=parseFloat(l);Number.isNaN(h)?o=Date.parse(l)-Date.now():o=h*1e3}if(o===void 0){let h=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,h)}return await te(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:i,defaultBaseURL:l}=r,h=this.buildURL(o,i,l);"timeout"in r&&Ts("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:m,body:g}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:m,retryCount:t});return{req:{method:n,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...r.fetchOptions??{}},url:h,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=p([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...js(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=p([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:mr(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:a(this,Dr,"f").call(this,{body:e,headers:r})}};Cs=A,Dr=new WeakMap,Ss=new WeakSet,Nn=function(){return this.baseURL!=="https://api.openai.com/v1"};A.OpenAI=Cs;A.DEFAULT_TIMEOUT=6e5;A.OpenAIError=_;A.APIError=T;A.APIConnectionError=_e;A.APIConnectionTimeoutError=ge;A.APIUserAbortError=$;A.NotFoundError=ot;A.ConflictError=it;A.RateLimitError=lt;A.BadRequestError=rt;A.AuthenticationError=st;A.InternalServerError=ct;A.PermissionDeniedError=nt;A.UnprocessableEntityError=at;A.InvalidWebhookSignatureError=ee;A.toFile=Ar;A.Completions=qe;A.Chat=Ae;A.Embeddings=He;A.Files=Xe;A.Images=ze;A.Audio=oe;A.Moderations=Ye;A.Models=Qe;A.FineTuning=Z;A.Graders=ve;A.VectorStores=me;A.Webhooks=tt;A.Beta=Y;A.Batches=Le;A.Uploads=$e;A.Responses=de;A.Realtime=he;A.Conversations=Ce;A.Evals=Ee;A.Containers=Se;A.Skills=pe;A.Videos=et;var Es=class extends A{constructor({baseURL:e=z("OPENAI_BASE_URL"),apiKey:t=z("AZURE_OPENAI_API_KEY"),apiVersion:r=z("OPENAI_API_VERSION"),endpoint:n,deployment:o,azureADTokenProvider:i,dangerouslyAllowBrowser:l,...h}={}){if(!r)throw new _("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof i=="function"&&(l=!0),!i&&!t)throw new _("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&t)throw new _("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(h.defaultQuery={...h.defaultQuery,"api-version":r},e){if(n)throw new _("baseURL and endpoint are mutually exclusive")}else{if(n||(n=process.env.AZURE_OPENAI_ENDPOINT),!n)throw new _("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${n}/openai`}super({apiKey:i??t,baseURL:e,...h,...l!==void 0?{dangerouslyAllowBrowser:l}:{}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=o}async buildRequest(e,t={}){if(ai.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!ht(e.body))throw new Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;r!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${r}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e){return typeof this._options.apiKey=="string"?p([{"api-key":this.apiKey}]):super.authHeaders(e)}},ai=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{_e as APIConnectionError,ge as APIConnectionTimeoutError,T as APIError,Te as APIPromise,$ as APIUserAbortError,st as AuthenticationError,Es as AzureOpenAI,rt as BadRequestError,it as ConflictError,ct as InternalServerError,ee as InvalidWebhookSignatureError,ot as NotFoundError,A as OpenAI,_ as OpenAIError,tr as PagePromise,nt as PermissionDeniedError,lt as RateLimitError,at as UnprocessableEntityError,A as default,Ar as toFile};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{a,b}from"./chunk-UMKCOU3N.js";import"./chunk-P72TUTYK.js";import"./chunk-J7YTWK67.js";import"./chunk-ECY4MUD3.js";import"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";export{a as OpenCodeModel,b as openCodeFactory};
@@ -0,0 +1,5 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{a as D,b as P}from"./chunk-RVJZFWN7.js";import"./chunk-MBCPGD5L.js";import{c as l,k as R,p as x}from"./chunk-NEHZOG23.js";import{a as E}from"./chunk-2XNFZXHY.js";import{a as k,b as C,c as v,l as o}from"./chunk-H2O5G3XB.js";import"./chunk-ZC4F4MYU.js";import"./chunk-YVN2NZL4.js";import{a as d,b as $}from"./chunk-FFWPJP7A.js";import{i as a}from"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import{e as j}from"./chunk-5WJ6AUNY.js";var S=j(E(),1);var Y=async e=>{let t=a.process.cwd(),n=D(e),s=C({target:n==="agent"?"non-interactive":"interactive"}),u=P(e).includes("--force");if(!u&&n==="agent")return o.error(s,"Purge requires `--force` flag in agent mode."),$({exitCode:1});if(u)return o.step(s,"Purging noskills content..."),await q(t,s),o.success(s,"Purge complete."),d(void 0);let g=(await N(t)).filter(i=>i.exists);if(g.length===0)return o.info(s,"Nothing to remove."),d(void 0);let p=[];for(let i of g){let y=await v(s,{message:i.message});if(k(y))return o.info(s,"Aborted."),d(void 0);p.push({id:i.id,confirmed:y===!0})}let f=p.filter(i=>i.confirmed),I=p.filter(i=>!i.confirmed);if(f.length===0)return o.info(s,"Nothing selected for removal."),d(void 0);let T=new Set(f.map(i=>i.id)),w=[];for(let i of f)await H(t,i.id)?o.step(s,` Removed ${h(i.id)}`):(w.push(i.id),o.step(s,` Failed to remove ${h(i.id)}`));for(let i of I)o.step(s,` Kept ${h(i.id)}`);T.size>0&&await b(t);let M=f.length-w.length;return o.success(s,`Purge complete (${M} of ${g.length} categories removed).`),d(void 0)},N=async e=>{let[t,n,s,r]=await Promise.all([O(e),L(e),J(e),U(e)]);return[t,n,s,r]},O=async e=>{let t=await x(e),n=t.map(s=>s.id).join(", ");return{id:"concerns",exists:t.length>0,message:`Remove concerns? (${n})`}},L=async e=>{let t=await R(e),n=0;try{for await(let c of a.fs.readDir(`${e}/${l.specsDir}`))c.isDirectory&&n++}catch{}let s=Math.max(t.length,n);if(s===0)return{id:"specs",exists:!1,message:""};let r=t.map(c=>`${c.name} ${c.state.phase}`).join(", ");return{id:"specs",exists:!0,message:t.length>0?`Remove specs? (${s} specs: ${r})`:`Remove specs? (${s} spec directories)`}},J=async e=>{let t=0;try{for await(let n of a.fs.readDir(`${e}/${l.rulesDir}`))n.isFile&&t++}catch{}return{id:"rules",exists:t>0,message:`Remove rules? (${t} active rules)`}},U=async e=>{let t=!1,n=!1,s=!1;try{let c=await a.fs.readTextFile(`${e}/.claude/settings.json`);t=JSON.parse(c).hooks!==void 0}catch{}try{n=(await a.fs.readTextFile(`${e}/CLAUDE.md`)).includes("<!-- noskills:start -->")}catch{}let r=[`${e}/.claude/agents/noskills-executor.md`,`${e}/.claude/agents/noskills-verifier.md`];for(let c of r)try{await a.fs.stat(c),s=!0;break}catch{}return{id:"agent-integration",exists:t||n||s,message:"Remove agent integration? (.claude/settings.json, CLAUDE.md, .claude/agents/noskills-*.md)"}},h=e=>({concerns:"concerns",specs:"specs",rules:"rules","agent-integration":"agent integration"})[e],H=(e,t)=>{switch(t){case"concerns":return m(`${e}/${l.concernsDir}`);case"specs":return z([`${e}/${l.specsDir}`,`${e}/${l.stateDir}`]);case"rules":return m(`${e}/${l.rulesDir}`);case"agent-integration":return A(e)}},q=async(e,t)=>{await m(`${e}/${l.concernsDir}`)&&o.step(t," Removed `.eser/concerns/`"),await m(`${e}/${l.specsDir}`)&&o.step(t," Removed `.eser/specs/`"),await m(`${e}/${l.rulesDir}`)&&o.step(t," Removed `.eser/rules/`"),await m(`${e}/${l.stateDir}`)&&o.step(t," Removed `.eser/.state/`"),await b(e)&&o.step(t," Removed noskills section from `manifest.yml`"),await A(e)&&o.step(t," Removed agent integration")},m=async e=>{try{await a.fs.stat(e);let{rmSync:t}=await import("node:fs");return t(e,{recursive:!0,force:!0}),!0}catch{return!1}},z=async e=>{let t=!1;for(let n of e)await m(n)&&(t=!0);return t},F=async e=>{try{await a.fs.stat(e);let{unlinkSync:t}=await import("node:fs");return t(e),!0}catch{return!1}},b=async e=>{let t=`${e}/${l.manifestFile}`;try{let n=await a.fs.readTextFile(t),s=S.parseDocument(n);return s.has("noskills")?(s.delete("noskills"),await a.fs.writeTextFile(t,s.toString()),!0):!1}catch{return!1}},B=async e=>{let t=`${e}/CLAUDE.md`,n="<!-- noskills:start -->",s="<!-- noskills:end -->";try{let r=await a.fs.readTextFile(t),u=r.indexOf(n),c=r.indexOf(s);return u!==-1&&c!==-1?(r=r.slice(0,u).trimEnd()+`
3
+ `+r.slice(c+s.length).trimStart(),await a.fs.writeTextFile(t,r.trimEnd()+`
4
+ `),!0):!1}catch{return!1}},K=async e=>{let t=`${e}/.claude/settings.json`;try{let n=await a.fs.readTextFile(t),s=JSON.parse(n);return s.hooks!==void 0?(delete s.hooks,await a.fs.writeTextFile(t,JSON.stringify(s,null,2)+`
5
+ `),!0):!1}catch{return!1}},A=async e=>{let t=!1;await K(e)&&(t=!0),await B(e)&&(t=!0);let n=[`${e}/.claude/agents/noskills-executor.md`,`${e}/.claude/agents/noskills-verifier.md`];for(let r of n)await F(r)&&(t=!0);let s=[`${e}/.cursorrules`,`${e}/.windsurfrules`,`${e}/.kiro/steering/conventions.md`,`${e}/.github/copilot-instructions.md`];for(let r of s)await F(r)&&(t=!0);return t};export{Y as main};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{a,b,c,d,e,f}from"./chunk-F35K7YVH.js";import"./chunk-TEOMM3RD.js";import"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";export{e as applyRecipe,f as applyRecipeChain,b as fileExists,a as isPathSafe,c as processContent,d as runPostInstall};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p}from"./chunk-TEOMM3RD.js";import"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";export{b as DEFAULT_OWNER,d as DEFAULT_REF,f as DEFAULT_REGISTRY_URL,c as DEFAULT_REPO,a as FETCH_TIMEOUT_MS,g as LOCAL_REGISTRY_PATH,e as RECIPES_FILENAME,j as detectLocalRegistry,m as fetchRecipeFile,o as fetchRecipeFolder,p as fetchRecipeFromRepo,k as fetchRegistry,l as fetchRegistryFromRepo,n as parseGitHubRawUrl,i as registryFetch,h as resolveSpecifier};
@@ -0,0 +1,9 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{a as c}from"./chunk-L7UCWRDZ.js";import"./chunk-A6K5L4SG.js";import"./chunk-GTHXGAMQ.js";import"./chunk-3XJLLDR5.js";import"./chunk-P7WCO724.js";import"./chunk-2XNFZXHY.js";import{a as g}from"./chunk-LFNUSULJ.js";import{a as v,c as f}from"./chunk-4FGLERUG.js";import{l as n}from"./chunk-H2O5G3XB.js";import"./chunk-WF6JNPZS.js";import"./chunk-J2Z7NG2X.js";import"./chunk-VAIRJES2.js";import"./chunk-S7S2I2K5.js";import"./chunk-NBA6EFWU.js";import{f as m}from"./chunk-P2MUEKFT.js";import"./chunk-ZC4F4MYU.js";import"./chunk-7DPLGQHN.js";import"./chunk-YVN2NZL4.js";import{d as a}from"./chunk-ECY4MUD3.js";import{a as p}from"./chunk-MG65QJY6.js";import{g as i}from"./chunk-FFWPJP7A.js";import"./chunk-2BOCLC67.js";import"./chunk-N7DXBY3O.js";import"./chunk-7ATUODBM.js";import"./chunk-AP72BKVG.js";import"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";var{ctx:t,output:C}=v(),R=async()=>(await a`git status --porcelain`.noThrow().text()).length===0,x=async()=>{let e=await a`git log @{u}..HEAD --oneline`.noThrow().text();return e.length>0?e.split(`
3
+ `):[]},A=async(e,r)=>{for(let s of r)await a`git add ${s}`.spawn();await a`git commit -m ${e}`.spawn()},$=async()=>{await a`git push origin HEAD`.spawn()},P=async e=>{await a`git tag -d ${e}`.noThrow().spawn();let r=`:refs/tags/${e}`;await a`git push origin ${r}`.noThrow().spawn()},b=async e=>{let r=new TextEncoder,s=new TextDecoder,o=new Uint8Array(256);await Deno.stderr.write(r.encode(`${e} [y/N] `));let u=await Deno.stdin.read(o),l=s.decode(o.subarray(0,u??0)).trim();return l==="y"||l==="Y"},O=async e=>{let{type:r,dryRun:s=!1}=e;if(!await R())throw new Error("Working tree is dirty. Commit or stash changes first.");let o=await x();if(o.length>0&&e.yes!==!0)throw new Error(`You have ${o.length} unpushed commit(s):
4
+ ${o.join(`
5
+ `)}
6
+
7
+ Push first, or re-run with --yes to continue anyway.`);let u=await c()??"0.0.0";r!=="same"&&await(await import("./versions-FYALONNL.js")).versions(r,{dryRun:s});let l=await c()??u,d=!1;try{await(await import("./changelog-gen-JV3EHOMV.js")).generateChangelog({dryRun:s}),d=!0}catch{d=!1}let h=!1,w=!1;if(!s){d&&await a`deno fmt CHANGELOG.md`.noThrow().spawn();let y=["VERSION","CHANGELOG.md","pkg/*/deno.json","pkg/*/package.json","package.json"],E=`chore(codebase): release v${l}`;await A(E,y),h=!0,await $(),w=!0}return{version:l,previousVersion:u,changelogGenerated:d,committed:h,pushed:w,dryRun:s}},k=async(e={})=>{let{dryRun:r=!1}=e;if(!await R())throw new Error("Working tree is dirty. Commit and push first.");let s=await x();if(s.length>0)throw new Error(`You have unpushed commits. Push first, then rerelease.
8
+ ${s.join(`
9
+ `)}`);let o=await c();if(o===void 0||!/^\d+\.\d+\.\d+$/.test(o))throw new Error(`Invalid or missing version in VERSION file: "${o}"`);let u=`v${o}`;if(!r){let l=`chore(codebase): release v${o}`;await a`git commit --allow-empty -m ${l}`.spawn(),await a`git push origin HEAD`.spawn()}return{version:o,tag:u,dryRun:r}},T=async(e={})=>{let r=await c();if(r===void 0||!/^\d+\.\d+\.\d+$/.test(r))throw new Error(`Invalid or missing version in VERSION file: "${r}"`);let s=`v${r}`;if(e.yes!==!0)throw new Error(`This will delete tag ${s} locally and remotely. Re-run with --yes to confirm.`);return await P(s),{version:r,tag:s,deleted:!0}},M=e=>m.fromPromise(()=>O(e)),U=e=>m.fromPromise(()=>k(e)),H=e=>m.fromPromise(()=>T(e)),I=e=>{let r=e.args[0];return r===void 0||!["patch","minor","major","same"].includes(r)?i.fail(g.adaptError("Usage: eser codebase release <patch|minor|major|same> [--dry-run] [--yes]")):i.ok({type:r,dryRun:e.flags["dry-run"]===!0,yes:e.flags.yes===!0})},V=e=>i.ok({dryRun:e.flags["dry-run"]===!0}),D=e=>i.ok({yes:e.flags.yes===!0}),j=e=>{if(i.isFail(e)){let s=e.error,o=s instanceof Error?s.message:s.message??String(s);return n.error(t,o),i.fail({exitCode:1})}let{value:r}=e;return r.dryRun?(n.warn(t,"[DRY RUN] Release preview:"),n.info(t,` Version: ${r.previousVersion} -> ${r.version}`),n.info(t,` Changelog: ${r.changelogGenerated?"generated":"no user-facing changes"}`),n.info(t," No changes were made.")):(n.success(t,`Released v${r.version}`),n.info(t,` Version: ${r.previousVersion} -> ${r.version}`),n.info(t,` Changelog: ${r.changelogGenerated?"updated":"no user-facing changes"}`),n.info(t,` Committed: ${r.committed}`),n.info(t,` Pushed: ${r.pushed}`),n.info(t," CI will validate, tag, and publish."),n.info(t," Watch: https://github.com/eser/stack/actions")),i.ok(void 0)},N=e=>{if(i.isFail(e)){let s=e.error,o=s instanceof Error?s.message:s.message??String(s);return n.error(t,o),i.fail({exitCode:1})}let{value:r}=e;return r.dryRun?n.warn(t,`[DRY RUN] Would delete and recreate tag ${r.tag}`):(n.success(t,`Re-tagged ${r.tag}`),n.info(t,"CI will validate and publish.")),i.ok(void 0)},G=e=>{if(i.isFail(e)){let s=e.error,o=s instanceof Error?s.message:s.message??String(s);return n.error(t,o),i.fail({exitCode:1})}let{value:r}=e;return r.deleted&&n.success(t,`Deleted tag v${r.version} (local + remote).`),i.ok(void 0)},S=g.createTrigger({handler:M,adaptInput:I,adaptOutput:j}),Y=g.createTrigger({handler:U,adaptInput:V,adaptOutput:N}),F=g.createTrigger({handler:H,adaptInput:D,adaptOutput:G}),Z=async e=>{let r=p(e??[],{boolean:["dry-run","yes"],alias:{n:"dry-run",y:"yes"}}),s=r._[0],o=r["dry-run"]===!0,u=r.yes===!0;if(s!==void 0&&!o&&!u&&["patch","minor","major","same"].includes(s)){let d=await c()??"0.0.0";if(n.info(t,`Current version: ${d}`),n.info(t,`Bump type: ${s}`),n.info(t,"This will bump version, generate changelog, commit, and push."),await C.flush(),!await b("Proceed?"))return n.warn(t,"Aborted."),i.ok(void 0);r.yes=!0}let l=f("release",r);return await S(l)},ee=async e=>{let r=p(e??[],{boolean:["dry-run"],alias:{n:"dry-run"}}),s=f("rerelease",r);return await Y(s)},re=async e=>{let r=p(e??[],{boolean:["yes"],alias:{y:"yes"}}),s=f("unrelease",r);return await F(s)};export{S as handleReleaseCli,Y as handleRereleaseCli,F as handleUnreleaseCli,Z as main,O as release,M as releaseHandler,k as rerelease,U as rereleaseHandler,ee as rereleaseMain,T as unrelease,H as unreleaseHandler,re as unreleaseMain};
@@ -0,0 +1,4 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import"./chunk-SOSF762G.js";import{a as m}from"./chunk-LFNUSULJ.js";import{a as C,c as P}from"./chunk-4FGLERUG.js";import{l as u}from"./chunk-H2O5G3XB.js";import"./chunk-WF6JNPZS.js";import"./chunk-J2Z7NG2X.js";import"./chunk-VAIRJES2.js";import"./chunk-S7S2I2K5.js";import"./chunk-NBA6EFWU.js";import{f as w}from"./chunk-P2MUEKFT.js";import"./chunk-ZC4F4MYU.js";import"./chunk-7DPLGQHN.js";import"./chunk-YVN2NZL4.js";import{e as p}from"./chunk-ECY4MUD3.js";import"./chunk-PWLF3WXM.js";import"./chunk-QFFGKP3M.js";import"./chunk-QXATB6Z5.js";import{a as v}from"./chunk-MG65QJY6.js";import{g as l}from"./chunk-FFWPJP7A.js";import"./chunk-2BOCLC67.js";import"./chunk-N7DXBY3O.js";import{j as x,n as R}from"./chunk-7ATUODBM.js";import"./chunk-AP72BKVG.js";import{j as c}from"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";var{ctx:h,output:Y}=C(),E=/^##\s{1,100}\[?([^\]\s]+)\]?\s{0,100}-?\s{0,100}([0-9]{4}-[0-9]{2}-[0-9]{2})?\s{0,100}$/,A=t=>{let e=t.trim().replace(/^refs\/tags\//,"");return e.startsWith("v")?e:`v${e}`},N=t=>{let e=t.split(/\r?\n/),n=[];for(let s=0;s<e.length;s+=1){let i=e[s].match(E);i!==null&&/^\d/.test(i[1])&&n.push({version:i[1],date:i[2]??"",headingLineIndex:s})}return n.length===0?[]:n.map((s,o)=>{let i=n[o+1],g=s.headingLineIndex+1,a=i!==void 0?i.headingLineIndex:e.length,r=e.slice(g,a);for(;r.length>0&&r[0].trim()==="";)r.shift();for(;r.length>0&&r[r.length-1].trim()==="";)r.pop();let d=[`## ${s.version}${s.date!==""?` - ${s.date}`:""}`];return r.length>0&&d.push("",...r),{version:s.version,date:s.date,tag:`v${s.version}`,notes:`${d.join(`
3
+ `).trim()}
4
+ `}})},T=async(t={})=>{let{changelogPath:e="CHANGELOG.md",root:n="."}=t,s=R(n,e),o=await c.runtime.fs.readTextFile(s);return{entries:N(o)}},O=async(t,e)=>{try{return await p.exec`gh release view ${t} --repo ${e}`.quiet().text(),!0}catch{return!1}},k=async t=>{let{repo:e,createIfMissing:n=!1,changelogPath:s="CHANGELOG.md",root:o=".",releaseTitle:i="eserstack {tag}"}=t,{entries:g}=await T({changelogPath:s,root:o});if(g.length===0)throw new Error("No release headings found in CHANGELOG.md.");let a=t.tag!==void 0?A(t.tag):g[0].tag,r=g.find(y=>y.tag===a);if(r===void 0)throw new Error(`No matching changelog section found for ${a}.`);let d=await c.runtime.fs.makeTempDir({prefix:"eserstack-release-"}),f=x(d,`${a}-notes.md`);await c.runtime.fs.writeTextFile(f,r.notes);try{if(await O(a,e))return await p.exec`gh release edit ${a} --repo ${e} --notes-file ${f}`.spawn(),{tag:a,entry:r,action:"updated"};if(!n)return{tag:a,entry:r,action:"skipped"};let $=i.replace("{tag}",a);try{return await p.exec`gh release create ${a} --repo ${e} --title ${$} --notes-file ${f}`.spawn(),{tag:a,entry:r,action:"created"}}catch{return await p.exec`gh release edit ${a} --repo ${e} --notes-file ${f}`.spawn(),{tag:a,entry:r,action:"updated"}}}finally{await c.runtime.fs.remove(d,{recursive:!0})}},I=t=>w.fromPromise(()=>k(t)),S=t=>{let e=t.flags.repo??c.runtime.env.get("GITHUB_REPOSITORY")??"";return e===""?l.fail(m.adaptError("Missing repository. Pass --repo or set GITHUB_REPOSITORY.")):l.ok({repo:e,tag:t.flags.tag??void 0,createIfMissing:t.flags["create-if-missing"]===!0})},b=t=>{if(l.isFail(t)){let n=t.error,s=n instanceof Error?n.message:n.message??String(n);return u.error(h,s),l.fail({exitCode:1})}let{value:e}=t;switch(e.action){case"created":u.success(h,`Created release ${e.tag} with changelog notes.`);break;case"updated":u.success(h,`Updated release notes for ${e.tag}.`);break;case"skipped":u.warn(h,`Release ${e.tag} not found. Skipping (pass --create-if-missing to create).`);break}return l.ok(void 0)},G=m.createTrigger({handler:I,adaptInput:S,adaptOutput:b}),q=async t=>{let e=v(t??[],{string:["repo","tag"],boolean:["create-if-missing"],alias:{h:"help"}}),n=P("release-notes",e);return await G(n)};export{G as handleCli,O as hasGitHubRelease,q as main,A as normalizeTag,T as parseChangelog,N as parseChangelogText,k as syncReleaseNotes,I as syncReleaseNotesHandler};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{c,d as f}from"./chunk-HTJLIAH4.js";import{a as R}from"./chunk-L7UCWRDZ.js";import"./chunk-A6K5L4SG.js";import"./chunk-GTHXGAMQ.js";import"./chunk-3XJLLDR5.js";import"./chunk-P7WCO724.js";import"./chunk-2XNFZXHY.js";import{a as m}from"./chunk-LFNUSULJ.js";import{a as d,c as p}from"./chunk-4FGLERUG.js";import{l as n}from"./chunk-H2O5G3XB.js";import"./chunk-WF6JNPZS.js";import"./chunk-J2Z7NG2X.js";import"./chunk-VAIRJES2.js";import"./chunk-S7S2I2K5.js";import"./chunk-NBA6EFWU.js";import{f as u}from"./chunk-P2MUEKFT.js";import"./chunk-ZC4F4MYU.js";import"./chunk-7DPLGQHN.js";import"./chunk-YVN2NZL4.js";import"./chunk-ECY4MUD3.js";import{a as g}from"./chunk-MG65QJY6.js";import{g as a}from"./chunk-FFWPJP7A.js";import"./chunk-2BOCLC67.js";import"./chunk-N7DXBY3O.js";import"./chunk-7ATUODBM.js";import"./chunk-AP72BKVG.js";import"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";var{ctx:i,output:N}=d(),P=async(e={})=>{let{root:r=".",remote:s="origin",tagPrefix:h="v",messageTemplate:y="Release {tag}",dryRun:l=!1}=e,t=await R({root:r});if(t===void 0||!/^\d+\.\d+\.\d+$/.test(t))throw new Error(`Invalid or missing version in VERSION file: "${t}"`);let o=`${h}${t}`,v=y.replace("{tag}",o).replace("{version}",t);return l||(await c(o,v),await f(s,o)),{version:t,tag:o,remote:s,dryRun:l}},T=e=>u.fromPromise(()=>P(e)),C=e=>a.ok({dryRun:e.flags["dry-run"]===!0}),x=e=>{if(a.isFail(e)){let s=e.error instanceof Error?e.error.message:String(e.error);return n.error(i,s),a.fail({exitCode:1})}let{value:r}=e;return r.dryRun?n.warn(i,`[DRY RUN] Would create and push tag ${r.tag}`):(n.success(i,`Created tag ${r.tag}`),n.info(i,`Pushed tag ${r.tag} to ${r.remote}`)),a.ok(void 0)},A=m.createTrigger({handler:T,adaptInput:C,adaptOutput:x}),S=async e=>{let r=g(e??[],{boolean:["dry-run"],alias:{n:"dry-run"}}),s=p("release-tag",r);return await A(s)};export{A as handleCli,S as main,P as pushReleaseTag,T as pushReleaseTagHandler};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{k as f}from"./chunk-JI536JLJ.js";import{e as c,f as d,g as u}from"./chunk-NEHZOG23.js";import"./chunk-2XNFZXHY.js";import{f as p,h as l,k as m}from"./chunk-ZC4F4MYU.js";import{d as a,g as o}from"./chunk-YVN2NZL4.js";import{a as r}from"./chunk-FFWPJP7A.js";import{i}from"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";var v=async w=>{let e=p({renderer:m.ansi(),sink:l.stdout()}),n=i.process.cwd(),g=d(w),s=await c(n,g);if(s.phase==="IDLE"||s.phase==="UNINITIALIZED")return e.writeln(a("Already idle. Nothing to reset.")),await e.close(),r(void 0);let t=s.spec,h=f(s);return await u(n,h),e.writeln(o("\u2714")," Reset to IDLE."),t!==null&&e.writeln(a(`Spec "${t}" state cleared. Files in .eser/specs/${t}/ preserved.`)),await e.close(),r(void 0)};export{v as main};
@@ -0,0 +1,3 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{a as k,b as x}from"./chunk-RGUPFAEE.js";import{c as f,l as h}from"./chunk-NEHZOG23.js";import{b as y,c as w}from"./chunk-OAT2D23A.js";import"./chunk-2XNFZXHY.js";import{f as o,h as l,k as a}from"./chunk-ZC4F4MYU.js";import{c as m,d as i,f as p,g}from"./chunk-YVN2NZL4.js";import{a as u,b as c}from"./chunk-FFWPJP7A.js";import{i as n}from"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";var U=async s=>{let e=s?.[0];if(e==="add")return await $(s?.slice(1));if(e==="list")return await v();if(e==="promote")return await C(s?.slice(1));let t=y(),r=o({renderer:a.ansi(),sink:l.stdout()});return r.writeln(`Usage: ${t} rule <add "rule text" | list | promote "decision">`),await r.close(),u(void 0)},$=async s=>{let e=o({renderer:a.ansi(),sink:l.stdout()}),t=n.process.cwd(),r=s?.join(" "),d=await h(t);if(r===void 0||r.length===0)return e.writeln(p("Please provide a rule: "),m(`${w('rule add "Use Deno Tests for all tests"')}`)),await e.close(),c({exitCode:1});let P=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50),A=`${t}/${f.rulesDir}/${P}.md`;return await n.fs.mkdir(`${t}/${f.rulesDir}`,{recursive:!0}),await n.fs.writeTextFile(A,r+`
3
+ `),e.writeln(g("\u2714")," Rule added: ",i(r)),d!==null&&d.tools.length>0&&(await x(t,d.tools,d),e.writeln(i(" Tool files synced."))),await e.close(),u(void 0)},v=async()=>{let s=o({renderer:a.ansi(),sink:l.stdout()}),e=n.process.cwd(),t=await k(e);if(s.writeln(m("Rules")),s.writeln(""),t.length===0)s.writeln(i(` No rules yet. Add one with: ${w('rule add "..."')}`));else for(let r of t)s.writeln(" ",i("\u2022"),` ${r}`);return await s.close(),u(void 0)},C=async s=>{let e=o({renderer:a.ansi(),sink:l.stdout()}),t=s?.join(" ");return t===void 0||t.length===0?(e.writeln(p("Please provide the decision text to promote.")),await e.close(),c({exitCode:1})):(await e.close(),await $(s))};export{U as main};
@@ -0,0 +1,4 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{d as M}from"./chunk-7UASU4NU.js";import"./chunk-OCPEFZBJ.js";import{a as W}from"./chunk-RGUPFAEE.js";import{a as X,h as _}from"./chunk-JI536JLJ.js";import{d as g,e as N,f as U,g as $,l as G,p as V,s as B}from"./chunk-NEHZOG23.js";import{b,c as L}from"./chunk-OAT2D23A.js";import"./chunk-2XNFZXHY.js";import{a as D,b as A,d as F}from"./chunk-H2O5G3XB.js";import{f as R,h as O,k as T}from"./chunk-ZC4F4MYU.js";import{c as v,d as o,f as l,g as P,h,k as I}from"./chunk-YVN2NZL4.js";import{a as S,b as w}from"./chunk-FFWPJP7A.js";import{i as y}from"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";var le=async t=>{let e=R({renderer:T.ansi(),sink:O.stdout()}),i=y.process.cwd(),n=t?.includes("--unattended")??!1,r=j(t,"--max-turns")??10,p=j(t,"--max-iterations")??50;if(!await B(i))return e.writeln(l(`noskills not initialized. Run: ${L("init")}`)),await e.close(),w({exitCode:1});let x=U(t),c=await N(i,x);if(c.phase!=="EXECUTING"&&c.phase!=="SPEC_APPROVED")return e.writeln(l(`Cannot run from phase: ${c.phase}`)),e.writeln(o("Must be in SPEC_APPROVED or EXECUTING to start.")),await e.close(),w({exitCode:1});if(c.phase==="SPEC_APPROVED"){e.writeln(o("Starting execution from approved spec..."));let s=_(c);await $(i,s)}let d=await G(i);if(d===null)return e.writeln(l("Config not found.")),await e.close(),w({exitCode:1});e.writeln(v(`${b()} run`)),e.writeln(o(`Mode: ${n?"unattended":"interactive"}, max-turns: ${r}, max-iterations: ${p}`)),e.writeln("");let m=0,u=0;for(;m<p;){m++;let s=await g(i);if(s.phase==="DONE"){e.writeln(""),e.writeln(P("\u2714")," Spec completed!"),e.writeln(` Iterations: ${s.execution.iteration}`),e.writeln(` Decisions: ${s.decisions.length}`);break}if(s.phase==="BLOCKED"){let a=s.execution.lastProgress??"Unknown";if(e.writeln(""),e.writeln(h("\u26A0")," Execution blocked: ",o(a)),n){await Q(i,a,m),e.writeln(o("Logged to .eser/.state/blocked.log. Resolve and re-run.")),u=1;break}let C=A(),f=await F(C,{message:"Enter resolution (or leave empty to stop):"});if(D(f)||f===""){e.writeln(o("Stopped by user."));break}let k=X(s,"EXECUTING");await $(i,{...k,execution:{...k.execution,lastProgress:`Resolved: ${f}`}});continue}if(s.phase!=="EXECUTING"){e.writeln(l(`Unexpected phase: ${s.phase}. Stopping.`)),u=1;break}let z=(await V(i)).filter(a=>d.concerns.includes(a.id)),q=await W(i),H=M(s,z,q,d),K=J(H);e.writeln(I(`\u2500\u2500 Iteration ${m}`),o(` (execution: ${s.execution.iteration}, debt: ${s.execution.debt?.items.length??0})`)),s.execution.lastProgress!==null&&e.writeln(o(` Last: ${s.execution.lastProgress}`)),s.execution.lastVerification?.passed===!1&&e.writeln(l(" Verification failed \u2014 agent will fix")),s.execution.debt!==null&&e.writeln(h(` Debt: ${s.execution.debt.items.length} items`)),e.writeln(o(" Spawning agent..."));try{await(await import("./mod-BQJDMCYC.js")).exec`claude -p ${K} --max-turns ${String(r)} --output-format json`.noThrow().text()}catch{e.writeln(l(" Failed to spawn claude CLI. Is it installed?")),u=1;break}e.writeln(o(" Agent exited. Stop hook captured state."));let E=await g(i);if(d.autoCommit===!0&&d.allowGit!==!1)try{let a=await import("./mod-BQJDMCYC.js");if((await a.exec`git diff --name-only`.noThrow().text()).trim().length>0){await a.exec`git add -A`.noThrow().text();let f=`noskills: iteration ${E.execution.iteration} \u2014 ${E.execution.lastProgress??"progress"}`;await a.exec`git commit -m ${f}`.noThrow().text(),e.writeln(o(" Auto-committed."))}}catch{e.writeln(o(" Auto-commit failed (non-fatal)."))}}return m>=p&&(e.writeln(""),e.writeln(h("\u26A0"),` Max iterations (${p}) reached. Stopping.`),u=2),await e.close(),u!==0?w({exitCode:u}):S(void 0)},J=t=>{let e=[];if(e.push(t.meta.resumeHint),e.push(""),t.meta.spec!==null&&(e.push(`Working on spec: ${t.meta.spec}`),e.push("")),"instruction"in t&&(e.push(t.instruction),e.push("")),"previousIterationDebt"in t){let n=t.previousIterationDebt;if(n!==void 0){e.push(`DEBT from iteration ${n.fromIteration} (address first):`);for(let r of n.items)e.push(`- ${r}`);e.push("")}}if("statusReportRequired"in t){let n=t.statusReport;if(n!==void 0){e.push("Report against these acceptance criteria:");for(let r of n.criteria)e.push(`- ${r}`);e.push("")}}if("verificationFailed"in t&&t.verificationFailed===!0&&(e.push("Test output:"),e.push(("verificationOutput"in t?t.verificationOutput:"")??""),e.push("")),t.behavioral.rules.length>0){e.push("Rules:");for(let n of t.behavioral.rules)e.push(`- ${n}`);e.push("")}if("context"in t){let n=t.context;if(n.concernReminders.length>0){e.push("Reminders:");for(let r of n.concernReminders)e.push(`- ${r}`);e.push("")}}let i=b();return e.push(`When done, report progress: ${i} next --answer="your progress"`),e.push(`If blocked, run: ${i} block "reason"`),e.push(`When all tasks are complete: ${i} done`),e.join(`
3
+ `)},j=(t,e)=>{if(t===void 0)return null;let i=`${e}=`;for(let n of t)if(n.startsWith(i)){let r=parseInt(n.slice(i.length),10);if(!isNaN(r)&&r>0)return r}return null},Q=async(t,e,i)=>{let n=`${t}/.eser/.state/blocked.log`,r=`[${new Date().toISOString()}] iteration=${i} reason=${e}
4
+ `;try{let{appendFileSync:p,mkdirSync:x}=await import("node:fs"),{dirname:c}=await import("node:path");x(c(n),{recursive:!0}),p(n,r)}catch{}};export{le as main};
@@ -0,0 +1,5 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{a as V,b as q,c as z}from"./chunk-YEWODYET.js";import"./chunk-L2E2H7YT.js";import"./chunk-2XNFZXHY.js";import{a as A,c as J,d as k,e as L}from"./chunk-P2MUEKFT.js";import{f as N,h as U,k as B}from"./chunk-ZC4F4MYU.js";import{f as x,g as C,h as F}from"./chunk-YVN2NZL4.js";import{d as H}from"./chunk-ECY4MUD3.js";import{a as I}from"./chunk-MG65QJY6.js";import{a as W,b as c,c as P,d as S}from"./chunk-FFWPJP7A.js";import{i as _}from"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";var O=s=>({_tag:"WorkflowError",message:s}),Z=s=>{if(typeof s=="string")return{name:s,options:{},continueOnError:!1};let o=Object.entries(s);if(o.length!==1)throw new Error(`Invalid step config: expected exactly one key, got ${o.length}`);let[e,n]=o[0],r={},i=!1,l;for(let[a,t]of Object.entries(n))a==="continueOnError"?i=t===!0:a==="timeout"?l=t*1e3:r[a]=t;return{name:e,options:r,continueOnError:i,timeout:l}},ee=(s,o,e)=>L(J(s,n=>O(n instanceof Error?n.message:String(n))),o,O(`Step '${e}' timed out after ${(o/1e3).toFixed(0)}s`)),G=(s,o,e={})=>A(async()=>{let n=performance.now(),r=[],i=e.defaultTimeout??6e4;for(let a of s.steps){let t=Z(a);if(e.only!==void 0&&t.name!==e.only)continue;let T=o.get(t.name);if(T===void 0)return c(O(`Unknown tool '${t.name}' in workflow '${s.id}'. Registered tools: ${o.names().join(", ")||"(none)"}`));let v={...t.options,root:e.root??".",fix:e.fix??!1,_args:e.args??[]};e.changedFiles!==void 0&&(v._changedFiles=e.changedFiles),e.onStepStart?.(t.name);let g=performance.now(),j=t.timeout??i,h=ee(()=>T.run(v),j,t.name),p=await k(h),d;if(P(p))d=p.value;else if(t.continueOnError)d={name:t.name,passed:!1,issues:[{message:p.error.message}],mutations:[],stats:{}};else return p;let b=performance.now()-g,y={...d,durationMs:b};r.push(y),d.mutations.length>0&&e.onMutations!==void 0&&await e.onMutations(d.mutations),e.onStepEnd?.(y)}let l=performance.now()-n;return W({workflowId:s.id,passed:r.every(a=>a.passed),steps:r,totalDurationMs:l})}),D=(s,o,e=new Set)=>{if(s.includes===void 0||s.includes.length===0)return s;let n=new Set(e);n.add(s.id);let r=[];for(let i of s.includes){if(n.has(i))throw new Error(`Circular include detected: workflow '${s.id}' includes '${i}' which is already in the include chain: ${[...n].join(" \u2192 ")}`);let l=o.find(t=>t.id===i);if(l===void 0)throw new Error(`Workflow '${s.id}' includes '${i}' but no workflow with that id exists. Available: ${o.map(t=>t.id).join(", ")||"(none)"}`);let a=D(l,o,n);r.push(...a.steps)}return{...s,steps:[...r,...s.steps],includes:void 0}},K=(s,o,e,n={})=>A(async()=>{let r=o.workflows.find(l=>l.id===s);if(r===void 0)return c(O(`Workflow '${s}' not found. Available: ${o.workflows.map(l=>l.id).join(", ")||"(none)"}`));let i=D(r,o.workflows);return await k(G(i,e,n))}),Q=(s,o,e,n={})=>A(async()=>{let r=o.filter(l=>l.on.includes(s));if(r.length===0)return c(O(`No workflows found for event '${s}'. Available: ${o.map(l=>`${l.id} (${l.on.join(", ")})`).join("; ")||"(none)"}`));let i=[];for(let l of r){let a=D(l,o),t=await k(G(a,e,n));if(S(t))return t;i.push(t.value)}return W(i)});var oe=50,$=B.ansi(),se=(s,o,e)=>{let n=".".repeat(Math.max(1,oe-s.length)),r=`${(o.durationMs/1e3).toFixed(1)}s`,i;if(o.passed&&o.mutations.length>0)i=$.render([F(`Fixed (${o.mutations.length} file${o.mutations.length===1?"":"s"}, ${r})`)]);else if(o.passed)if(e&&Object.keys(o.stats).length>0){let l=Object.entries(o.stats).map(([a,t])=>`${t} ${a}`).join(", ");i=$.render([C(`Passed (${l}, ${r})`)])}else i=$.render([C(`Passed (${r})`)]);else i=$.render([x(`Failed (${r})`)]);return`${s}${n}${i}`},pe=async(s,o)=>{let e=I(s??[],{string:["event","workflow","only","config"],boolean:["fix","dry-run","help","verbose","json","changed"],alias:{e:"event",w:"workflow",h:"help",v:"verbose"}});if(e.help)return console.log(`eser workflows run \u2014 Run workflow pipelines
3
+ `),console.log("Usage:"),console.log(" eser workflows run -e <event> Run by event"),console.log(" eser workflows run -w <workflow-id> Run by workflow id"),console.log(),console.log("Options:"),console.log(" -e, --event <name> Event to trigger (precommit, commitmsg, prepush)"),console.log(" -w, --workflow <id> Workflow id to run"),console.log(" --fix Auto-fix issues where supported"),console.log(" --dry-run Preview mutations without writing"),console.log(" --only <step> Run only a specific step"),console.log(" --config <path> Config directory (default: .)"),console.log(" -v, --verbose Show stats and issues for all steps"),console.log(" --json Output results as JSON"),console.log(" --changed Only check files changed in git"),console.log(" -h, --help Show this help"),W(void 0);let n=N({renderer:$,sink:U.stdout()}),r=e.event,i=e.workflow,l=e.fix??!1,a=e["dry-run"]??!1,t=e.only,T=e._,v=e.verbose??!1,g=e.json??!1,j=e.changed??!1;if(r===void 0&&i===void 0)return console.error("Error: specify -e <event> or -w <workflow-id>. Use --help for usage."),await n.close(),c({exitCode:1});let h=V();h.register(z),o?.tools!==void 0&&h.registerAll(o.tools);let p=e.config??".",d=await q(p);if(d===null)return console.error("Error: no .eser/manifest.yml found in current directory."),await n.close(),c({exitCode:1});let b;if(j)try{b=await H`git diff --name-only HEAD`.cwd(p).noThrow().lines()}catch{n.writeln(F("Warning: could not run git, running without file filtering."))}let y=[],M={root:p,fix:l,dryRun:a,only:t,args:T,changedFiles:b,onStepStart:void 0,onStepEnd:g?void 0:f=>{if(console.log(se(f.name,f,v)),!f.passed||v)for(let u of f.issues){let R=u.path!==void 0?u.line!==void 0?`${u.path}:${u.line}`:u.path:"";console.log(` ${$.render([x("\u2717")])} ${R}${R.length>0?": ":""}${u.message}`)}},onMutations:async f=>{if(!a)for(let u of f)u.oldContent!==u.newContent&&await _.fs.writeTextFile(u.path,u.newContent)}};try{let f=!0,u=0,R=0;if(r!==void 0){let w=await k(Q(r,d.workflows,h,M));if(S(w))throw new Error(w.error.message);for(let m of w.value){y.push(m),m.passed||(f=!1);for(let E of m.steps)E.passed||(R++,u+=E.issues.length)}}else{let w=await k(K(i,d,h,M));if(S(w))throw new Error(w.error.message);let m=w.value;y.push(m),f=m.passed;for(let E of m.steps)E.passed||(R++,u+=E.issues.length)}return g&&console.log(JSON.stringify(y,null,2)),f?(g||n.writeln(C(`
4
+ All checks passed!`)),await n.close(),W(void 0)):(g||n.writeln(x(`
5
+ ${R} check(s) failed with ${u} issue(s)`)),await n.close(),c({exitCode:1}))}catch(f){return n.writeln(x(`Error: ${f instanceof Error?f.message:String(f)}`)),await n.close(),c({exitCode:1})}};export{pe as main};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from "node:module"; const require = createRequire(import.meta.url);
2
+ import{f as w,h as g,k as y}from"./chunk-ZC4F4MYU.js";import{b as m,d as p,f as C}from"./chunk-YVN2NZL4.js";import{b as x}from"./chunk-ECY4MUD3.js";import{a as h,b as f}from"./chunk-FFWPJP7A.js";import{i as S}from"./chunk-WJKE6XHF.js";import"./chunk-6E6JUBFH.js";import"./chunk-BQT5RJZB.js";import"./chunk-5WJ6AUNY.js";var l=(e,r)=>typeof r=="string"?{command:r,description:e,workingDirectory:void 0,depends:[]}:{command:r.command,description:r.description??e,workingDirectory:r.workingDirectory,depends:r.depends??[]},k=(e,r,t=new Set,s=new Set)=>{if(s.has(e))return[];if(t.has(e))throw new Error(`Circular dependency detected: ${e} depends on itself (cycle in dependency chain)`);let n=r[e];if(n===void 0)throw new Error(`Unknown script dependency: "${e}"`);t.add(e);let c=l(e,n),o=[];for(let a of c.depends){let i=k(a,r,t,s);for(let d of i)s.has(d)||(o.push(d),s.add(d))}return s.add(e),o},P=()=>{let e=new URL("./main.ts",import.meta.url),r=e.protocol==="file:"?e.pathname:e.href;return`${S.process.execPath()} run --allow-all ${r}`},R=e=>{if(e==="eser"||e.startsWith("eser ")){let r=e.slice(4);return`${P()}${r}`}return e},$=async(e,r,t)=>{let s=R(e),n=t!==void 0&&t.length>0?`${s} ${t.join(" ")}`:s,c=r??".";return(await new x("sh",["-c",n]).cwd(c).stdout("inherit").stderr("inherit").noThrow().spawn()).code},O=async(e,r,t,s)=>{let n=w({renderer:y.ansi(),sink:g.stdout()}),c=k(e,t);for(let i of c){let d=l(i,t[i]);n.writeln(p(`$ ${i}`));let u=await $(d.command,d.workingDirectory);if(u!==0)return n.writeln(C(`Script dependency "${i}" failed with exit code ${u}`)),await n.close(),f({exitCode:u})}let o=l(e,t[e]);n.writeln(p(`$ ${e}`));let a=await $(o.command,o.workingDirectory,s);return a!==0?(await n.close(),f({exitCode:a})):(await n.close(),h(void 0))},B=e=>{let r=w({renderer:y.ansi(),sink:g.stdout()});r.writeln(m("Scripts:"));for(let[t,s]of Object.entries(e)){let n=l(t,s);r.writeln(m(` ${t.padEnd(20)} `),p(n.description))}r.writeln()};export{$ as executeCommand,l as parseScript,k as resolveDependencies,O as runScript,B as showScripts};