@caspian2026/agent-sdk 0.0.7 → 0.0.9

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 (312) hide show
  1. package/dist/chunk-04h360ha.js +57 -0
  2. package/dist/{chunk-jmkn11my.js → chunk-04pw5akr.js} +20 -20
  3. package/dist/{chunk-cd7mmbch.js → chunk-0gpem3pk.js} +46 -45
  4. package/dist/{chunk-8572g6er.js → chunk-0txtpamh.js} +14 -14
  5. package/dist/{chunk-4m9df5ef.js → chunk-0v89r445.js} +17 -21
  6. package/dist/chunk-0vp3wfab.js +12 -0
  7. package/dist/{chunk-9acr8n74.js → chunk-1486qzk5.js} +6 -4
  8. package/dist/chunk-1efrnkxx.js +468 -0
  9. package/dist/chunk-1gaw18rz.js +93 -0
  10. package/dist/{chunk-ew7mrr5b.js → chunk-1hqb50ne.js} +13 -19
  11. package/dist/chunk-1hqvvvrt.js +96 -0
  12. package/dist/{chunk-bgfrg1s9.js → chunk-1hx5g6qy.js} +6 -10
  13. package/dist/{chunk-3g1vqhyx.js → chunk-1kmwf4vn.js} +17 -21
  14. package/dist/{chunk-naybw0p0.js → chunk-1nhnn2rg.js} +8 -8
  15. package/dist/{chunk-f42s8t42.js → chunk-1nvcmzj1.js} +66 -77
  16. package/dist/{chunk-2f21meep.js → chunk-1v01c96r.js} +1 -1
  17. package/dist/{chunk-spvdb8m2.js → chunk-1vp22nex.js} +2 -2
  18. package/dist/{chunk-fnny13es.js → chunk-1yfc1d48.js} +52 -90
  19. package/dist/{chunk-83e71kz6.js → chunk-2072dpbx.js} +2 -2
  20. package/dist/{chunk-7rnqsng2.js → chunk-22mfb6bp.js} +19 -19
  21. package/dist/{chunk-d7886r6a.js → chunk-26wtxbdc.js} +7774 -7774
  22. package/dist/{chunk-x94btg29.js → chunk-2m32xn94.js} +17 -21
  23. package/dist/{chunk-mw1kpeg9.js → chunk-2nrarbza.js} +1909 -1377
  24. package/dist/chunk-2vbash3m.js +331 -0
  25. package/dist/{chunk-c11swzas.js → chunk-2vteceqh.js} +5 -5
  26. package/dist/{chunk-h5k7m3dv.js → chunk-2y8x7xt7.js} +2 -2
  27. package/dist/{chunk-sc3r8ja1.js → chunk-2yxqz99n.js} +9 -9
  28. package/dist/{chunk-z15sw2rn.js → chunk-35nft36d.js} +205 -261
  29. package/dist/{chunk-73hc55wr.js → chunk-35z2vxep.js} +49 -48
  30. package/dist/{chunk-15m49c67.js → chunk-3e28fvn0.js} +2 -2
  31. package/dist/{chunk-82h5qtz0.js → chunk-3e4r5pmc.js} +3 -3
  32. package/dist/{chunk-4anwkx68.js → chunk-3fn3ysvs.js} +47 -46
  33. package/dist/{chunk-4hv90qcz.js → chunk-3mgywd32.js} +1 -1
  34. package/dist/{chunk-ncvr5h4e.js → chunk-3npsy4c4.js} +46 -45
  35. package/dist/{chunk-xz655xxa.js → chunk-3pzwd6qq.js} +2 -2
  36. package/dist/{chunk-70eey1nh.js → chunk-40s88wdg.js} +2 -2
  37. package/dist/{chunk-41dgt6cv.js → chunk-42a0nyrq.js} +47 -46
  38. package/dist/{chunk-a6e0hsgy.js → chunk-44t1xk05.js} +46 -45
  39. package/dist/{chunk-0awwmrwr.js → chunk-4ayjwyqj.js} +2 -2
  40. package/dist/{chunk-wmqazvaj.js → chunk-4myad919.js} +46 -45
  41. package/dist/{chunk-8g747a8x.js → chunk-4pbx3g7s.js} +1 -1
  42. package/dist/chunk-4vtvwg7e.js +99 -0
  43. package/dist/{chunk-qcnhb4cd.js → chunk-54wn2jdr.js} +3 -3
  44. package/dist/{chunk-1nk93fqz.js → chunk-5cxjxxx8.js} +2 -7
  45. package/dist/chunk-5m3m7hr5.js +108 -0
  46. package/dist/{chunk-v37jby04.js → chunk-5mrc0ps5.js} +37 -41
  47. package/dist/{chunk-d97v7nqz.js → chunk-5tw3gj5z.js} +47 -46
  48. package/dist/{chunk-savtj5a5.js → chunk-5zcygjb2.js} +46 -45
  49. package/dist/{chunk-mk1y74w7.js → chunk-65q3hqkw.js} +17 -21
  50. package/dist/{chunk-vajwapkf.js → chunk-67wms97m.js} +17 -23
  51. package/dist/chunk-6cfcqjty.js +441 -0
  52. package/dist/{chunk-2pn3hdmh.js → chunk-6hs0cptm.js} +56 -55
  53. package/dist/{chunk-bmbq6nt1.js → chunk-6wzg2hpc.js} +2 -2
  54. package/dist/chunk-72qa16xm.js +91 -0
  55. package/dist/chunk-7cdy4aj6.js +150 -0
  56. package/dist/chunk-7cje7scj.js +1534 -0
  57. package/dist/{chunk-e7h4qxgw.js → chunk-7etkb4pr.js} +4 -4
  58. package/dist/{chunk-1ax1znzj.js → chunk-7hrmxpha.js} +6 -6
  59. package/dist/{chunk-wha6v7za.js → chunk-7krg0dkt.js} +2 -2
  60. package/dist/{chunk-8g5qecvg.js → chunk-7skyagc2.js} +2 -2
  61. package/dist/{chunk-hzknr99c.js → chunk-83b2frat.js} +4 -4
  62. package/dist/{chunk-ze3z2k77.js → chunk-84cdy41j.js} +5 -5
  63. package/dist/{chunk-bxcfz5gy.js → chunk-87xg6yb4.js} +1 -1
  64. package/dist/{chunk-nrtksr2p.js → chunk-8b2y3x7a.js} +1 -1
  65. package/dist/{chunk-1xpvkabk.js → chunk-8ckwc9k8.js} +46 -45
  66. package/dist/{chunk-n5fmkn61.js → chunk-8jy18nx9.js} +1 -1
  67. package/dist/{chunk-9s832vcg.js → chunk-93vwm44t.js} +100422 -57117
  68. package/dist/{chunk-rsgwykdr.js → chunk-9957ffjc.js} +2 -2
  69. package/dist/{chunk-mnmnk0vk.js → chunk-9byfzaeq.js} +46 -45
  70. package/dist/chunk-9ewnsd7f.js +31 -0
  71. package/dist/{chunk-xwg327ys.js → chunk-9w114071.js} +6 -6
  72. package/dist/chunk-9wf3fc4t.js +29 -0
  73. package/dist/chunk-9z9teq7p.js +87 -0
  74. package/dist/{chunk-6p4cyhb3.js → chunk-a6d2q415.js} +2 -2
  75. package/dist/{chunk-reahw5sg.js → chunk-ay5fvc2r.js} +52 -52
  76. package/dist/{chunk-4sp1bd4k.js → chunk-ayx9aq2k.js} +47 -46
  77. package/dist/{chunk-xd7zbrwg.js → chunk-azv68vk1.js} +2 -2
  78. package/dist/chunk-b547q41s.js +92 -0
  79. package/dist/{chunk-jgjqa49s.js → chunk-b56smerd.js} +3 -3
  80. package/dist/{chunk-enkdxqas.js → chunk-b5asw4tj.js} +6 -6
  81. package/dist/{chunk-nk82j7r2.js → chunk-b6prbsae.js} +7 -7
  82. package/dist/{chunk-dxc3zg1a.js → chunk-b89ese8r.js} +46 -45
  83. package/dist/{chunk-094bjqmt.js → chunk-be77bcs8.js} +118 -450
  84. package/dist/{chunk-9y9mn19n.js → chunk-bf03a1w7.js} +48 -47
  85. package/dist/{chunk-hzzhz6bk.js → chunk-bjdknxqn.js} +46 -45
  86. package/dist/{chunk-m87bhhqv.js → chunk-bzatg35k.js} +1 -1
  87. package/dist/{chunk-d6da7ykp.js → chunk-c4d52460.js} +4 -4
  88. package/dist/{chunk-cc8k9def.js → chunk-c5zkrd7r.js} +47 -46
  89. package/dist/{chunk-4140c8xy.js → chunk-c6hsz5ey.js} +20 -24
  90. package/dist/{chunk-c5fx8078.js → chunk-cay13mxk.js} +15 -31
  91. package/dist/{chunk-s3hsqf80.js → chunk-cexw1jmv.js} +30 -81
  92. package/dist/{chunk-cvm2tmwg.js → chunk-ckh4f9ry.js} +20 -24
  93. package/dist/{chunk-xsqhh4xq.js → chunk-cr1dv2js.js} +50 -48
  94. package/dist/{chunk-z0gsswja.js → chunk-d8z7pyrb.js} +47 -46
  95. package/dist/chunk-dexkgxt4.js +211 -0
  96. package/dist/{chunk-xxw9a0bq.js → chunk-dhwr4fz4.js} +2 -2
  97. package/dist/{chunk-0ym2z0c7.js → chunk-dj7d67ya.js} +1 -1
  98. package/dist/chunk-djfq8ws0.js +124 -0
  99. package/dist/{chunk-x2pvw7xw.js → chunk-dmyedkpw.js} +8 -8
  100. package/dist/{chunk-6byf11g1.js → chunk-dngfdsm9.js} +108 -102
  101. package/dist/{chunk-ans094d6.js → chunk-dt3epnwj.js} +9 -9
  102. package/dist/{chunk-11kx8pnj.js → chunk-dz6zxh89.js} +46 -45
  103. package/dist/{chunk-q638kksz.js → chunk-e7ag583m.js} +47 -46
  104. package/dist/{chunk-m2dfsbma.js → chunk-ec6ga5ey.js} +51 -50
  105. package/dist/{chunk-3t8dtbbb.js → chunk-ecbh4n6q.js} +46 -45
  106. package/dist/{chunk-1zg9pbp1.js → chunk-ecv9kbtk.js} +11 -9
  107. package/dist/{chunk-vk664f7z.js → chunk-ecvy1ng2.js} +49 -48
  108. package/dist/{chunk-wwy9zctx.js → chunk-ef2m4xyz.js} +46 -45
  109. package/dist/{chunk-8k18jq72.js → chunk-etbb3dss.js} +49 -48
  110. package/dist/{chunk-jgpmpgx6.js → chunk-etdt1xz3.js} +1 -1
  111. package/dist/{chunk-eynn8t6t.js → chunk-ev7h351p.js} +4 -4
  112. package/dist/{chunk-vz0s7fkr.js → chunk-ey0n4emm.js} +46 -45
  113. package/dist/{chunk-18brvww1.js → chunk-f4tdn7yr.js} +46 -45
  114. package/dist/{chunk-3dx0vvc1.js → chunk-f4v7t54y.js} +11 -11
  115. package/dist/{chunk-3xfnvwtv.js → chunk-fesvrjhd.js} +10 -10
  116. package/dist/{chunk-gmkdyx42.js → chunk-frm7mphm.js} +7 -11
  117. package/dist/{chunk-tjbyte0q.js → chunk-frwznxnf.js} +3 -3
  118. package/dist/{chunk-2cszsr9h.js → chunk-ftsdm7y7.js} +54 -53
  119. package/dist/{chunk-qq0qy55j.js → chunk-g597bz1j.js} +47 -46
  120. package/dist/chunk-g5pe8dew.js +25 -0
  121. package/dist/{chunk-7d4bfm01.js → chunk-g78fetxa.js} +46 -45
  122. package/dist/{chunk-ga86yjm1.js → chunk-gdwdqewd.js} +3 -3
  123. package/dist/{chunk-qqamxvfj.js → chunk-ghwvqhx9.js} +51 -50
  124. package/dist/chunk-gkn3jgqn.js +123 -0
  125. package/dist/{chunk-d78b9d2h.js → chunk-grqhgr2b.js} +3 -3
  126. package/dist/chunk-grqkx44z.js +90 -0
  127. package/dist/{chunk-aag7s0gz.js → chunk-gzj94jgg.js} +46 -45
  128. package/dist/{chunk-zy38jrvg.js → chunk-h3vyya5n.js} +20 -14
  129. package/dist/{chunk-3t9qyd5r.js → chunk-h4xfadhf.js} +1 -1
  130. package/dist/chunk-h61d4awv.js +95 -0
  131. package/dist/{chunk-eps7cerv.js → chunk-hae34yd0.js} +5 -9
  132. package/dist/{chunk-twj38872.js → chunk-hb1gr101.js} +6 -6
  133. package/dist/{chunk-t9h8qebb.js → chunk-hg45r671.js} +2 -2
  134. package/dist/{chunk-m50f6mp5.js → chunk-hg6fwhj1.js} +1 -1
  135. package/dist/{chunk-nywvvkpj.js → chunk-hgmhngje.js} +4 -4
  136. package/dist/{chunk-a6pw83yd.js → chunk-hparkfvt.js} +55 -51
  137. package/dist/{chunk-xhv69ftg.js → chunk-hqjdgc6c.js} +2 -2
  138. package/dist/{chunk-cha6rd4k.js → chunk-hrhp26d7.js} +55 -54
  139. package/dist/{chunk-rymqz9ma.js → chunk-hzbr9543.js} +4 -4
  140. package/dist/{chunk-hjzjr1y9.js → chunk-j0gke393.js} +46 -45
  141. package/dist/{chunk-yyf72f78.js → chunk-j35mw64g.js} +4 -2
  142. package/dist/{chunk-425w66ka.js → chunk-j99ms5ep.js} +4 -4
  143. package/dist/{chunk-ey4j1s04.js → chunk-jgvmjwnx.js} +46 -45
  144. package/dist/{chunk-t4tgbhrc.js → chunk-jj4zs4gr.js} +46 -45
  145. package/dist/{chunk-3k65t0n1.js → chunk-jjz3hs34.js} +56 -55
  146. package/dist/{chunk-68d5h34m.js → chunk-jksf0ax9.js} +51 -49
  147. package/dist/{chunk-gdhz1652.js → chunk-jqfrz5g9.js} +27 -30
  148. package/dist/{chunk-q7jnesv8.js → chunk-jsj3fx0g.js} +5 -5
  149. package/dist/{chunk-vawgyev5.js → chunk-jtgyzqbq.js} +3 -3
  150. package/dist/{chunk-pxr88dvt.js → chunk-jwpp2bq2.js} +1808 -1643
  151. package/dist/{chunk-fqy0ymjy.js → chunk-jwwpfq76.js} +49 -45
  152. package/dist/{chunk-t7vh489d.js → chunk-jxp2j9t5.js} +46 -45
  153. package/dist/{chunk-zctfbr1v.js → chunk-k7cw1a8a.js} +1 -1
  154. package/dist/chunk-k8jpbz31.js +62 -0
  155. package/dist/{chunk-tdbz9gbm.js → chunk-kjqyhxz7.js} +6 -6
  156. package/dist/{chunk-yc23zxmj.js → chunk-kxrrtr3p.js} +1 -1
  157. package/dist/chunk-m70n19dz.js +93 -0
  158. package/dist/{chunk-4nspekjp.js → chunk-mcws22k3.js} +1 -28
  159. package/dist/{chunk-5ywh2en2.js → chunk-mewywsar.js} +46 -45
  160. package/dist/{chunk-d3csdgaj.js → chunk-mmhkcj7c.js} +64 -58
  161. package/dist/{chunk-rm2vtv77.js → chunk-msxggy37.js} +22 -25
  162. package/dist/{chunk-qp9svhcd.js → chunk-njw0haha.js} +10 -8
  163. package/dist/{chunk-5rv9c8yd.js → chunk-nrjtxhyr.js} +1 -1
  164. package/dist/{chunk-nqn45znr.js → chunk-ns7x6xam.js} +9 -9
  165. package/dist/{chunk-jaaxk89e.js → chunk-nsc89h0n.js} +2 -22
  166. package/dist/{chunk-z19sd3bt.js → chunk-p4196wzm.js} +5 -5
  167. package/dist/{chunk-1dgdjrm1.js → chunk-p791ydbm.js} +4 -4
  168. package/dist/{chunk-4wjdcrjp.js → chunk-p9ny0p2a.js} +13 -13
  169. package/dist/{chunk-phd1qfpc.js → chunk-pd2vy8hx.js} +5 -5
  170. package/dist/{chunk-sctapt27.js → chunk-pddf0719.js} +49 -48
  171. package/dist/{chunk-31k5zj46.js → chunk-pfarypfq.js} +48 -46
  172. package/dist/{chunk-w4yn8cq7.js → chunk-psm26hv7.js} +8 -8
  173. package/dist/{chunk-hwn8vetn.js → chunk-pwpk3gm6.js} +10 -10
  174. package/dist/{chunk-kdtvndzg.js → chunk-q14wrksq.js} +48 -47
  175. package/dist/{chunk-6zagvgdx.js → chunk-q4f1g9y6.js} +31 -27
  176. package/dist/{chunk-23jzrwsw.js → chunk-q6tdxy8v.js} +5 -5
  177. package/dist/chunk-q8hxwh48.js +445 -0
  178. package/dist/{chunk-eenq3avg.js → chunk-qcrpqjya.js} +1 -1
  179. package/dist/{chunk-e7efcp3k.js → chunk-qctsv1d7.js} +257 -2857
  180. package/dist/{chunk-ck0ap688.js → chunk-qkczt8cr.js} +4 -4
  181. package/dist/{chunk-f81dwk5k.js → chunk-qkp4ygnk.js} +2 -2
  182. package/dist/{chunk-x968ydc6.js → chunk-qqs58ywv.js} +7 -7
  183. package/dist/{chunk-c5sd36sr.js → chunk-qxjhw1dt.js} +29 -30
  184. package/dist/{chunk-rkg741k3.js → chunk-qz0xdht6.js} +14 -14
  185. package/dist/chunk-r3ehjkj5.js +123 -0
  186. package/dist/{chunk-n404hpdz.js → chunk-r5nd93kc.js} +1 -1
  187. package/dist/{chunk-8ezp9zbc.js → chunk-r6nnp8mj.js} +46 -45
  188. package/dist/{chunk-k0kvs7dv.js → chunk-r7684mmh.js} +5 -5
  189. package/dist/chunk-ratnrv9v.js +517 -0
  190. package/dist/{chunk-2s9vbdg2.js → chunk-rfbbcx5s.js} +46 -45
  191. package/dist/{chunk-z9n0183s.js → chunk-rfq9kmsy.js} +9 -9
  192. package/dist/{chunk-9s563c87.js → chunk-rhvn1rqs.js} +2 -2
  193. package/dist/{chunk-gvrjgq1n.js → chunk-rjq5nf1c.js} +16 -20
  194. package/dist/{chunk-xp61y5ba.js → chunk-rkv8bdtr.js} +2 -2
  195. package/dist/{chunk-cb2vt4h9.js → chunk-rmpaj37q.js} +48 -47
  196. package/dist/{chunk-gx13py0x.js → chunk-rn1s097c.js} +46 -45
  197. package/dist/{chunk-3zs49z47.js → chunk-rnxpvm3m.js} +1 -1
  198. package/dist/{chunk-2fr1hsfn.js → chunk-rpsqtvkx.js} +46 -45
  199. package/dist/{chunk-1fyvnmsg.js → chunk-rx4mcfg1.js} +55 -54
  200. package/dist/{chunk-qpj44gjs.js → chunk-rygxwjtc.js} +47 -46
  201. package/dist/{chunk-jpc9zwsk.js → chunk-rz94yg8c.js} +3 -3
  202. package/dist/{chunk-wgcacskp.js → chunk-s19b0bc7.js} +46 -45
  203. package/dist/{chunk-wayfjcwt.js → chunk-sdfvr9ps.js} +4 -4
  204. package/dist/{chunk-w83b25cn.js → chunk-sh2v9ywv.js} +5 -3
  205. package/dist/{chunk-1avzakfd.js → chunk-sjpqw47t.js} +3 -3
  206. package/dist/{chunk-7mqab3z7.js → chunk-skp5w8bq.js} +1 -1
  207. package/dist/{chunk-76j2e9vy.js → chunk-snxp8mxj.js} +2 -2
  208. package/dist/{chunk-vsqwd13w.js → chunk-ssb4wba6.js} +17 -19
  209. package/dist/{chunk-rztjnjhv.js → chunk-szzff973.js} +7 -5
  210. package/dist/{chunk-x3brs7xp.js → chunk-t1pygy19.js} +47 -46
  211. package/dist/{chunk-jf493266.js → chunk-t1s91wrk.js} +1 -1
  212. package/dist/{chunk-h6zzdk99.js → chunk-t3gmfcy7.js} +47 -46
  213. package/dist/{chunk-5vmrxh5r.js → chunk-t9eeyrkn.js} +48 -47
  214. package/dist/{chunk-0jtbeesf.js → chunk-tf859h88.js} +16 -20
  215. package/dist/{chunk-0wextpj6.js → chunk-thenr6b3.js} +14 -12
  216. package/dist/{chunk-79vr8d0q.js → chunk-thmtkfgj.js} +5 -5
  217. package/dist/chunk-tj7v47cp.js +20 -0
  218. package/dist/{chunk-68ereakd.js → chunk-tpk67mjc.js} +3 -3
  219. package/dist/chunk-trvc6jh7.js +92 -0
  220. package/dist/{chunk-hr9zwhyh.js → chunk-ttyfhx12.js} +524 -195
  221. package/dist/{chunk-fg8sh9td.js → chunk-txgbs4hp.js} +49 -48
  222. package/dist/{chunk-ze3cbhkf.js → chunk-ty1cyqr7.js} +49 -48
  223. package/dist/{chunk-r6kaak61.js → chunk-v0tgjdx0.js} +16 -20
  224. package/dist/chunk-v3s93bzd.js +34 -0
  225. package/dist/{chunk-4cp6193g.js → chunk-v4t6dyyh.js} +2 -2
  226. package/dist/{chunk-msh77ewm.js → chunk-v4wba09w.js} +46 -45
  227. package/dist/{chunk-9nf2vp4m.js → chunk-v5g8nf5h.js} +8 -8
  228. package/dist/{chunk-at1nwv1b.js → chunk-v6hbqcmr.js} +44 -43
  229. package/dist/{chunk-21gmrwhs.js → chunk-vajsk9ya.js} +17 -21
  230. package/dist/{chunk-8hpq2659.js → chunk-vbtm9g57.js} +1 -1
  231. package/dist/{chunk-5n83ds1r.js → chunk-vk3nb2xe.js} +51 -56
  232. package/dist/{chunk-sm4a1dhp.js → chunk-vmbht6ec.js} +12 -12
  233. package/dist/{chunk-as5rvw4n.js → chunk-vmp5rk8q.js} +17 -21
  234. package/dist/{chunk-02hqbd8r.js → chunk-vtmxgm1m.js} +4 -4
  235. package/dist/{chunk-prxcckgh.js → chunk-vw5jzpcm.js} +6 -6
  236. package/dist/{chunk-76fnknvb.js → chunk-vyz3v0qx.js} +5 -5
  237. package/dist/{chunk-067nrwpq.js → chunk-w3782jck.js} +51 -50
  238. package/dist/{chunk-fxjhzm1r.js → chunk-w3gnkyfc.js} +57 -66
  239. package/dist/chunk-w6mcmmt5.js +1457 -0
  240. package/dist/chunk-wa0xgm6m.js +988 -0
  241. package/dist/{chunk-vrjbc8ap.js → chunk-wa8yn2p0.js} +1 -1
  242. package/dist/{chunk-y93xtfqa.js → chunk-wg47eg7y.js} +46 -45
  243. package/dist/{chunk-y7we499r.js → chunk-wgd4n1q7.js} +8 -8
  244. package/dist/{chunk-0g5cy3wj.js → chunk-wgk9sxk7.js} +4 -4
  245. package/dist/{chunk-wr3pd88n.js → chunk-wkt2q02c.js} +40 -9
  246. package/dist/{chunk-w22nawab.js → chunk-wm1zm5xj.js} +4 -2
  247. package/dist/{chunk-yd45cbwe.js → chunk-wtpgjmjd.js} +49 -46
  248. package/dist/{chunk-zrg1tbjz.js → chunk-wxkrq9eb.js} +46 -45
  249. package/dist/{chunk-st5zy0wn.js → chunk-x2bnzvd6.js} +46 -45
  250. package/dist/{chunk-80ajr65m.js → chunk-x3jthbjq.js} +47 -46
  251. package/dist/chunk-x7fdwq3d.js +33 -0
  252. package/dist/{chunk-1myhsm69.js → chunk-xcrzgyce.js} +46 -45
  253. package/dist/{chunk-chsyvavm.js → chunk-xeb6075z.js} +1 -1
  254. package/dist/{chunk-9ky3xjag.js → chunk-xffb3dsw.js} +1 -1
  255. package/dist/{chunk-k3vwp17j.js → chunk-xgbd6ec5.js} +47 -46
  256. package/dist/{chunk-n7pnyq43.js → chunk-xhfmdq1y.js} +16 -0
  257. package/dist/{chunk-96dakveq.js → chunk-xhn4ptjn.js} +51 -50
  258. package/dist/{chunk-rkf6m79g.js → chunk-xs7zsmzk.js} +46 -45
  259. package/dist/chunk-xswyz2es.js +118 -0
  260. package/dist/{chunk-ky39hkg1.js → chunk-xtdm6ejq.js} +9 -7
  261. package/dist/{chunk-hh3k5s1s.js → chunk-xvk90wpt.js} +3 -3
  262. package/dist/{chunk-tcsh7s9s.js → chunk-xw99fqv1.js} +14 -6
  263. package/dist/{chunk-xnv6kb39.js → chunk-y32em34x.js} +22 -23
  264. package/dist/chunk-y5wfy524.js +94 -0
  265. package/dist/{chunk-avddtws1.js → chunk-ya9dxex0.js} +48 -46
  266. package/dist/{chunk-97wgdsab.js → chunk-z16txqz0.js} +3 -3
  267. package/dist/{chunk-yvtzznds.js → chunk-z6wm96eh.js} +2 -2
  268. package/dist/{chunk-b7h31fmf.js → chunk-zcgprbyy.js} +29 -27
  269. package/dist/chunk-zqbnw3n2.js +197 -0
  270. package/dist/{chunk-d6rypdxt.js → chunk-zxywawr7.js} +1 -1
  271. package/dist/{chunk-3j5mbnax.js → chunk-zyjkg76f.js} +7 -7
  272. package/dist/cli.js +8 -8
  273. package/dist/gateway/index.js +326 -0
  274. package/dist/gateway/worker.js +482241 -0
  275. package/package.json +1 -1
  276. package/dist/chunk-02f1t77x.js +0 -73
  277. package/dist/chunk-0y3ae4ty.js +0 -116
  278. package/dist/chunk-1h11d405.js +0 -117
  279. package/dist/chunk-238bwjt4.js +0 -92
  280. package/dist/chunk-2n868zv8.js +0 -89
  281. package/dist/chunk-6ye0jmx5.js +0 -91
  282. package/dist/chunk-74c00z2d.js +0 -90
  283. package/dist/chunk-8xwx1xtg.js +0 -120
  284. package/dist/chunk-99ze7d94.js +0 -93
  285. package/dist/chunk-a3ce0rwj.js +0 -654
  286. package/dist/chunk-cfv996bs.js +0 -22
  287. package/dist/chunk-czdrs0bx.js +0 -516
  288. package/dist/chunk-dms7egdz.js +0 -111
  289. package/dist/chunk-e5t5eefc.js +0 -62
  290. package/dist/chunk-eq4cfq5r.js +0 -145
  291. package/dist/chunk-fg6ezbz3.js +0 -95
  292. package/dist/chunk-h4c232ns.js +0 -91
  293. package/dist/chunk-hmdxn1qn.js +0 -92
  294. package/dist/chunk-k9bmm1hz.js +0 -1003
  295. package/dist/chunk-kjftjh83.js +0 -86
  296. package/dist/chunk-kjkac4wp.js +0 -88
  297. package/dist/chunk-mqj8zx52.js +0 -116
  298. package/dist/chunk-mrhpct12.js +0 -95
  299. package/dist/chunk-njrt3tac.js +0 -640
  300. package/dist/chunk-qvh1w3t7.js +0 -157
  301. package/dist/chunk-qz2x630m.js +0 -49145
  302. package/dist/chunk-r6bex8wg.js +0 -40
  303. package/dist/chunk-rm40kgv5.js +0 -91
  304. package/dist/chunk-v0krc430.js +0 -436
  305. package/dist/chunk-v2cdga08.js +0 -93
  306. package/dist/chunk-waewz1gq.js +0 -94
  307. package/dist/chunk-wdgdax51.js +0 -91
  308. package/dist/chunk-x50zdpbb.js +0 -120
  309. package/dist/chunk-y0fhjxef.js +0 -276
  310. package/dist/chunk-ychc8xwz.js +0 -92
  311. package/dist/chunk-ymq56dxr.js +0 -87
  312. package/dist/chunk-zt62qnf5.js +0 -369
@@ -1,828 +1,430 @@
1
1
  // @bun
2
2
  import {
3
- __esm
3
+ createAssistantAPIErrorMessage,
4
+ createUserMessage,
5
+ extractDiscoveredToolNames,
6
+ getEmptyToolPermissionContext,
7
+ init_Tool,
8
+ init_api,
9
+ init_messages1 as init_messages,
10
+ init_toolSearch,
11
+ isDeferredToolsDeltaEnabled,
12
+ isToolSearchEnabled,
13
+ normalizeContentFromAPI,
14
+ normalizeMessagesForAPI,
15
+ toolMatchesName,
16
+ toolToAPISchema
17
+ } from "./chunk-93vwm44t.js";
18
+ import"./chunk-mcws22k3.js";
19
+ import"./chunk-jzthz1bx.js";
20
+ import"./chunk-rz94yg8c.js";
21
+ import"./chunk-hwfknpxv.js";
22
+ import"./chunk-1gx78081.js";
23
+ import"./chunk-ehtwnxpg.js";
24
+ import"./chunk-54wn2jdr.js";
25
+ import"./chunk-wkt2q02c.js";
26
+ import"./chunk-87xg6yb4.js";
27
+ import"./chunk-2yxqz99n.js";
28
+ import"./chunk-2gzv8nrw.js";
29
+ import"./chunk-sdfvr9ps.js";
30
+ import"./chunk-cgfdkzhb.js";
31
+ import"./chunk-xswyz2es.js";
32
+ import"./chunk-j5bth84e.js";
33
+ import"./chunk-b6prbsae.js";
34
+ import"./chunk-ps49ymvj.js";
35
+ import"./chunk-68ffk5qa.js";
36
+ import {
37
+ addToTotalSessionCost,
38
+ init_cost_tracker
39
+ } from "./chunk-ratnrv9v.js";
40
+ import {
41
+ calculateUSDCost,
42
+ getModelMaxOutputTokens,
43
+ init_context,
44
+ init_modelCost
45
+ } from "./chunk-7cje7scj.js";
46
+ import {
47
+ getProxyFetchOptions,
48
+ init_proxy
49
+ } from "./chunk-7krg0dkt.js";
50
+ import {
51
+ TOOL_SEARCH_TOOL_NAME,
52
+ formatDeferredToolLine,
53
+ init_prompt,
54
+ isDeferredTool
55
+ } from "./chunk-kxrrtr3p.js";
56
+ import"./chunk-p7vkh4wx.js";
57
+ import"./chunk-6wzg2hpc.js";
58
+ import"./chunk-9w114071.js";
59
+ import"./chunk-3pzwd6qq.js";
60
+ import"./chunk-2vteceqh.js";
61
+ import"./chunk-xeb6075z.js";
62
+ import"./chunk-nrjtxhyr.js";
63
+ import"./chunk-v4t6dyyh.js";
64
+ import"./chunk-2vbash3m.js";
65
+ import"./chunk-bzatg35k.js";
66
+ import"./chunk-qctsv1d7.js";
67
+ import"./chunk-p4196wzm.js";
68
+ import"./chunk-7hrmxpha.js";
69
+ import"./chunk-6nsd9606.js";
70
+ import"./chunk-rkv8bdtr.js";
71
+ import"./chunk-64c1avct.js";
72
+ import"./chunk-8g5pe1gr.js";
73
+ import"./chunk-4pbx3g7s.js";
74
+ import"./chunk-26wtxbdc.js";
75
+ import"./chunk-z6wm96eh.js";
76
+ import"./chunk-4jm600zv.js";
77
+ import"./chunk-1v01c96r.js";
78
+ import"./chunk-8b2y3x7a.js";
79
+ import"./chunk-3c25bcsw.js";
80
+ import"./chunk-cexw1jmv.js";
81
+ import"./chunk-j35mw64g.js";
82
+ import"./chunk-cdz5yb0r.js";
83
+ import"./chunk-c7jwbe76.js";
84
+ import"./chunk-0vkfrmqm.js";
85
+ import"./chunk-7sgtxrsc.js";
86
+ import"./chunk-0xjaqda8.js";
87
+ import"./chunk-x8d2ehd7.js";
88
+ import"./chunk-3e28fvn0.js";
89
+ import"./chunk-kjqyhxz7.js";
90
+ import"./chunk-4ayjwyqj.js";
91
+ import"./chunk-qnfx3qtx.js";
92
+ import"./chunk-40s88wdg.js";
93
+ import"./chunk-5cxjxxx8.js";
94
+ import"./chunk-s8kj6ajy.js";
95
+ import"./chunk-qcrpqjya.js";
96
+ import"./chunk-skp5w8bq.js";
97
+ import"./chunk-5z28bqne.js";
98
+ import"./chunk-qajrkk97.js";
99
+ import {
100
+ init_debug,
101
+ logForDebugging
102
+ } from "./chunk-pd2vy8hx.js";
103
+ import {
104
+ init_envUtils,
105
+ isEnvDefinedFalsy,
106
+ isEnvTruthy
107
+ } from "./chunk-nsc89h0n.js";
108
+ import"./chunk-fbv4apne.js";
109
+ import"./chunk-k8vp0atq.js";
110
+ import"./chunk-vf612n57.js";
111
+ import"./chunk-07069jq1.js";
112
+ import"./chunk-d4mdda98.js";
113
+ import"./chunk-55raexh7.js";
114
+ import"./chunk-v9smspw2.js";
115
+ import"./chunk-v1kzp02e.js";
116
+ import"./chunk-7wm5s02e.js";
117
+ import"./chunk-b0kf00ff.js";
118
+ import"./chunk-netzwgv1.js";
119
+ import {
120
+ __esm,
121
+ __require
4
122
  } from "./chunk-qp2qdcda.js";
5
123
 
6
- // src/services/api/openai/convertMessages.ts
7
- function anthropicMessagesToOpenAI(messages, systemPrompt, options) {
8
- const result = [];
9
- const enableThinking = options?.enableThinking ?? false;
10
- const systemText = systemPromptToText(systemPrompt);
11
- if (systemText) {
12
- result.push({
13
- role: "system",
14
- content: systemText
15
- });
16
- }
17
- const turnBoundaries = new Set;
18
- if (enableThinking) {
19
- let hasSeenAssistant = false;
20
- for (let i = 0;i < messages.length; i++) {
21
- const msg = messages[i];
22
- if (msg.type === "assistant") {
23
- hasSeenAssistant = true;
24
- }
25
- if (msg.type === "user" && hasSeenAssistant) {
26
- const content = msg.message.content;
27
- const startsNewUserTurn = typeof content === "string" ? content.length > 0 : Array.isArray(content) && content.some((b) => typeof b === "string" || b && typeof b === "object" && ("type" in b) && b.type !== "tool_result");
28
- if (startsNewUserTurn) {
29
- turnBoundaries.add(i);
30
- }
31
- }
32
- }
33
- }
34
- for (let i = 0;i < messages.length; i++) {
35
- const msg = messages[i];
36
- switch (msg.type) {
37
- case "user":
38
- result.push(...convertInternalUserMessage(msg));
39
- break;
40
- case "assistant":
41
- const preserveReasoning = enableThinking && !isBeforeAnyTurnBoundary(i, turnBoundaries);
42
- result.push(...convertInternalAssistantMessage(msg, preserveReasoning));
43
- break;
44
- default:
45
- break;
46
- }
47
- }
48
- return result;
124
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/tslib.mjs
125
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
126
+ if (kind === "m")
127
+ throw new TypeError("Private method is not writable");
128
+ if (kind === "a" && !f)
129
+ throw new TypeError("Private accessor was defined without a setter");
130
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
131
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
132
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
49
133
  }
50
- function systemPromptToText(systemPrompt) {
51
- if (!systemPrompt || systemPrompt.length === 0)
52
- return "";
53
- return systemPrompt.filter(Boolean).join(`
54
-
55
- `);
134
+ function __classPrivateFieldGet(receiver, state, kind, f) {
135
+ if (kind === "a" && !f)
136
+ throw new TypeError("Private accessor was defined without a getter");
137
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
138
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
139
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
56
140
  }
57
- function isBeforeAnyTurnBoundary(i, boundaries) {
58
- for (const b of boundaries) {
59
- if (i < b)
60
- return true;
141
+ var init_tslib = () => {};
142
+
143
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/utils/uuid.mjs
144
+ var uuid4 = function() {
145
+ const { crypto: crypto2 } = globalThis;
146
+ if (crypto2?.randomUUID) {
147
+ uuid4 = crypto2.randomUUID.bind(crypto2);
148
+ return crypto2.randomUUID();
61
149
  }
62
- return false;
150
+ const u8 = new Uint8Array(1);
151
+ const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
152
+ return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16));
153
+ };
154
+ var init_uuid = () => {};
155
+
156
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/errors.mjs
157
+ function isAbortError(err) {
158
+ return typeof err === "object" && err !== null && (("name" in err) && err.name === "AbortError" || ("message" in err) && String(err.message).includes("FetchRequestCanceledException"));
63
159
  }
64
- function convertInternalUserMessage(msg) {
65
- const result = [];
66
- const content = msg.message.content;
67
- if (typeof content === "string") {
68
- result.push({
69
- role: "user",
70
- content
71
- });
72
- } else if (Array.isArray(content)) {
73
- const textParts = [];
74
- const toolResults = [];
75
- const imageParts = [];
76
- for (const block of content) {
77
- if (typeof block === "string") {
78
- textParts.push(block);
79
- } else if (block.type === "text") {
80
- textParts.push(block.text);
81
- } else if (block.type === "tool_result") {
82
- toolResults.push(block);
83
- } else if (block.type === "image") {
84
- const imagePart = convertImageBlockToOpenAI(block);
85
- if (imagePart) {
86
- imageParts.push(imagePart);
87
- }
88
- }
89
- }
90
- for (const tr of toolResults) {
91
- result.push(convertToolResult(tr));
92
- }
93
- if (imageParts.length > 0) {
94
- const multiContent = [];
95
- if (textParts.length > 0) {
96
- multiContent.push({ type: "text", text: textParts.join(`
97
- `) });
160
+ var castToError = (err) => {
161
+ if (err instanceof Error)
162
+ return err;
163
+ if (typeof err === "object" && err !== null) {
164
+ try {
165
+ if (Object.prototype.toString.call(err) === "[object Error]") {
166
+ const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
167
+ if (err.stack)
168
+ error.stack = err.stack;
169
+ if (err.cause && !error.cause)
170
+ error.cause = err.cause;
171
+ if (err.name)
172
+ error.name = err.name;
173
+ return error;
98
174
  }
99
- multiContent.push(...imageParts);
100
- result.push({
101
- role: "user",
102
- content: multiContent
103
- });
104
- } else if (textParts.length > 0) {
105
- result.push({
106
- role: "user",
107
- content: textParts.join(`
108
- `)
109
- });
110
- }
111
- }
112
- return result;
113
- }
114
- function convertToolResult(block) {
115
- let content;
116
- if (typeof block.content === "string") {
117
- content = block.content;
118
- } else if (Array.isArray(block.content)) {
119
- content = block.content.map((c) => {
120
- if (typeof c === "string")
121
- return c;
122
- if ("text" in c)
123
- return c.text;
124
- return "";
125
- }).filter(Boolean).join(`
126
- `);
127
- } else {
128
- content = "";
175
+ } catch {}
176
+ try {
177
+ return new Error(JSON.stringify(err));
178
+ } catch {}
129
179
  }
130
- return {
131
- role: "tool",
132
- tool_call_id: block.tool_use_id,
133
- content
180
+ return new Error(err);
181
+ };
182
+ var init_errors = () => {};
183
+
184
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/core/error.mjs
185
+ var OpenAIError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError, LengthFinishReasonError, ContentFilterFinishReasonError, InvalidWebhookSignatureError;
186
+ var init_error = __esm(() => {
187
+ init_errors();
188
+ OpenAIError = class OpenAIError extends Error {
134
189
  };
135
- }
136
- function convertInternalAssistantMessage(msg, preserveReasoning = false) {
137
- const content = msg.message.content;
138
- if (typeof content === "string") {
139
- return [
140
- {
141
- role: "assistant",
142
- content
190
+ APIError = class APIError extends OpenAIError {
191
+ constructor(status, error, message, headers) {
192
+ super(`${APIError.makeMessage(status, error, message)}`);
193
+ this.status = status;
194
+ this.headers = headers;
195
+ this.requestID = headers?.get("x-request-id");
196
+ this.error = error;
197
+ const data = error;
198
+ this.code = data?.["code"];
199
+ this.param = data?.["param"];
200
+ this.type = data?.["type"];
201
+ }
202
+ static makeMessage(status, error, message) {
203
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
204
+ if (status && msg) {
205
+ return `${status} ${msg}`;
143
206
  }
144
- ];
145
- }
146
- if (!Array.isArray(content)) {
147
- return [
148
- {
149
- role: "assistant",
150
- content: ""
207
+ if (status) {
208
+ return `${status} status code (no body)`;
151
209
  }
152
- ];
153
- }
154
- const textParts = [];
155
- const toolCalls = [];
156
- const reasoningParts = [];
157
- for (const block of content) {
158
- if (typeof block === "string") {
159
- textParts.push(block);
160
- } else if (block.type === "text") {
161
- textParts.push(block.text);
162
- } else if (block.type === "tool_use") {
163
- const tu = block;
164
- toolCalls.push({
165
- id: tu.id,
166
- type: "function",
167
- function: {
168
- name: tu.name,
169
- arguments: typeof tu.input === "string" ? tu.input : JSON.stringify(tu.input)
170
- }
171
- });
172
- } else if (block.type === "thinking" && preserveReasoning) {
173
- const thinkingText = block.thinking;
174
- if (typeof thinkingText === "string" && thinkingText) {
175
- reasoningParts.push(thinkingText);
210
+ if (msg) {
211
+ return msg;
176
212
  }
213
+ return "(no status code or body)";
214
+ }
215
+ static generate(status, errorResponse, message, headers) {
216
+ if (!status || !headers) {
217
+ return new APIConnectionError({ message, cause: castToError(errorResponse) });
218
+ }
219
+ const error = errorResponse?.["error"];
220
+ if (status === 400) {
221
+ return new BadRequestError(status, error, message, headers);
222
+ }
223
+ if (status === 401) {
224
+ return new AuthenticationError(status, error, message, headers);
225
+ }
226
+ if (status === 403) {
227
+ return new PermissionDeniedError(status, error, message, headers);
228
+ }
229
+ if (status === 404) {
230
+ return new NotFoundError(status, error, message, headers);
231
+ }
232
+ if (status === 409) {
233
+ return new ConflictError(status, error, message, headers);
234
+ }
235
+ if (status === 422) {
236
+ return new UnprocessableEntityError(status, error, message, headers);
237
+ }
238
+ if (status === 429) {
239
+ return new RateLimitError(status, error, message, headers);
240
+ }
241
+ if (status >= 500) {
242
+ return new InternalServerError(status, error, message, headers);
243
+ }
244
+ return new APIError(status, error, message, headers);
177
245
  }
178
- }
179
- const result = {
180
- role: "assistant",
181
- content: textParts.length > 0 ? textParts.join(`
182
- `) : null,
183
- ...toolCalls.length > 0 && { tool_calls: toolCalls },
184
- ...reasoningParts.length > 0 && { reasoning_content: reasoningParts.join(`
185
- `) }
186
246
  };
187
- return [result];
247
+ APIUserAbortError = class APIUserAbortError extends APIError {
248
+ constructor({ message } = {}) {
249
+ super(undefined, undefined, message || "Request was aborted.", undefined);
250
+ }
251
+ };
252
+ APIConnectionError = class APIConnectionError extends APIError {
253
+ constructor({ message, cause }) {
254
+ super(undefined, undefined, message || "Connection error.", undefined);
255
+ if (cause)
256
+ this.cause = cause;
257
+ }
258
+ };
259
+ APIConnectionTimeoutError = class APIConnectionTimeoutError extends APIConnectionError {
260
+ constructor({ message } = {}) {
261
+ super({ message: message ?? "Request timed out." });
262
+ }
263
+ };
264
+ BadRequestError = class BadRequestError extends APIError {
265
+ };
266
+ AuthenticationError = class AuthenticationError extends APIError {
267
+ };
268
+ PermissionDeniedError = class PermissionDeniedError extends APIError {
269
+ };
270
+ NotFoundError = class NotFoundError extends APIError {
271
+ };
272
+ ConflictError = class ConflictError extends APIError {
273
+ };
274
+ UnprocessableEntityError = class UnprocessableEntityError extends APIError {
275
+ };
276
+ RateLimitError = class RateLimitError extends APIError {
277
+ };
278
+ InternalServerError = class InternalServerError extends APIError {
279
+ };
280
+ LengthFinishReasonError = class LengthFinishReasonError extends OpenAIError {
281
+ constructor() {
282
+ super(`Could not parse response content as the length limit was reached`);
283
+ }
284
+ };
285
+ ContentFilterFinishReasonError = class ContentFilterFinishReasonError extends OpenAIError {
286
+ constructor() {
287
+ super(`Could not parse response content as the request was rejected by the content filter`);
288
+ }
289
+ };
290
+ InvalidWebhookSignatureError = class InvalidWebhookSignatureError extends Error {
291
+ constructor(message) {
292
+ super(message);
293
+ }
294
+ };
295
+ });
296
+
297
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/utils/values.mjs
298
+ function maybeObj(x) {
299
+ if (typeof x !== "object") {
300
+ return {};
301
+ }
302
+ return x ?? {};
188
303
  }
189
- function convertImageBlockToOpenAI(block) {
190
- const source = block.source;
191
- if (!source)
304
+ function isEmptyObj(obj) {
305
+ if (!obj)
306
+ return true;
307
+ for (const _k in obj)
308
+ return false;
309
+ return true;
310
+ }
311
+ function hasOwn(obj, key) {
312
+ return Object.prototype.hasOwnProperty.call(obj, key);
313
+ }
314
+ function isObj(obj) {
315
+ return obj != null && typeof obj === "object" && !Array.isArray(obj);
316
+ }
317
+ var startsWithSchemeRegexp, isAbsoluteURL = (url) => {
318
+ return startsWithSchemeRegexp.test(url);
319
+ }, isArray = (val) => (isArray = Array.isArray, isArray(val)), isReadonlyArray, validatePositiveInteger = (name, n) => {
320
+ if (typeof n !== "number" || !Number.isInteger(n)) {
321
+ throw new OpenAIError(`${name} must be an integer`);
322
+ }
323
+ if (n < 0) {
324
+ throw new OpenAIError(`${name} must be a positive integer`);
325
+ }
326
+ return n;
327
+ }, safeJSON = (text) => {
328
+ try {
329
+ return JSON.parse(text);
330
+ } catch (err) {
331
+ return;
332
+ }
333
+ };
334
+ var init_values = __esm(() => {
335
+ init_error();
336
+ startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
337
+ isReadonlyArray = isArray;
338
+ });
339
+
340
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/utils/sleep.mjs
341
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
342
+ var init_sleep = () => {};
343
+
344
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/version.mjs
345
+ var VERSION = "6.33.0";
346
+ var init_version = () => {};
347
+
348
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/detect-platform.mjs
349
+ function getDetectedPlatform() {
350
+ if (typeof Deno !== "undefined" && Deno.build != null) {
351
+ return "deno";
352
+ }
353
+ if (typeof EdgeRuntime !== "undefined") {
354
+ return "edge";
355
+ }
356
+ if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
357
+ return "node";
358
+ }
359
+ return "unknown";
360
+ }
361
+ function getBrowserInfo() {
362
+ if (typeof navigator === "undefined" || !navigator) {
192
363
  return null;
193
- if (source.type === "base64" && typeof source.data === "string") {
194
- const mediaType = source.media_type || "image/png";
364
+ }
365
+ const browserPatterns = [
366
+ { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
367
+ { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
368
+ { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
369
+ { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
370
+ { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
371
+ { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
372
+ ];
373
+ for (const { key, pattern } of browserPatterns) {
374
+ const match = pattern.exec(navigator.userAgent);
375
+ if (match) {
376
+ const major = match[1] || 0;
377
+ const minor = match[2] || 0;
378
+ const patch = match[3] || 0;
379
+ return { browser: key, version: `${major}.${minor}.${patch}` };
380
+ }
381
+ }
382
+ return null;
383
+ }
384
+ var isRunningInBrowser = () => {
385
+ return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined";
386
+ }, getPlatformProperties = () => {
387
+ const detectedPlatform = getDetectedPlatform();
388
+ if (detectedPlatform === "deno") {
195
389
  return {
196
- type: "image_url",
197
- image_url: {
198
- url: `data:${mediaType};base64,${source.data}`
199
- }
390
+ "X-Stainless-Lang": "js",
391
+ "X-Stainless-Package-Version": VERSION,
392
+ "X-Stainless-OS": normalizePlatform(Deno.build.os),
393
+ "X-Stainless-Arch": normalizeArch(Deno.build.arch),
394
+ "X-Stainless-Runtime": "deno",
395
+ "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
200
396
  };
201
397
  }
202
- if (source.type === "url" && typeof source.url === "string") {
398
+ if (typeof EdgeRuntime !== "undefined") {
203
399
  return {
204
- type: "image_url",
205
- image_url: {
206
- url: source.url
207
- }
400
+ "X-Stainless-Lang": "js",
401
+ "X-Stainless-Package-Version": VERSION,
402
+ "X-Stainless-OS": "Unknown",
403
+ "X-Stainless-Arch": `other:${EdgeRuntime}`,
404
+ "X-Stainless-Runtime": "edge",
405
+ "X-Stainless-Runtime-Version": globalThis.process.version
208
406
  };
209
407
  }
210
- return null;
211
- }
212
- var init_convertMessages = () => {};
213
-
214
- // src/services/api/openai/convertTools.ts
215
- function anthropicToolsToOpenAI(tools) {
216
- return tools.filter((tool) => {
217
- const toolType = tool.type;
218
- return tool.type === "custom" || !("type" in tool) || toolType !== "server";
219
- }).map((tool) => {
220
- const anyTool = tool;
221
- const name = anyTool.name || "";
222
- const description = anyTool.description || "";
223
- const inputSchema = anyTool.input_schema;
408
+ if (detectedPlatform === "node") {
224
409
  return {
225
- type: "function",
226
- function: {
227
- name,
228
- description,
229
- parameters: sanitizeJsonSchema(inputSchema || { type: "object", properties: {} })
230
- }
410
+ "X-Stainless-Lang": "js",
411
+ "X-Stainless-Package-Version": VERSION,
412
+ "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"),
413
+ "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"),
414
+ "X-Stainless-Runtime": "node",
415
+ "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
231
416
  };
232
- });
233
- }
234
- function sanitizeJsonSchema(schema) {
235
- if (!schema || typeof schema !== "object")
236
- return schema;
237
- const result = { ...schema };
238
- if ("const" in result) {
239
- result.enum = [result.const];
240
- delete result.const;
241
417
  }
242
- const objectKeys = ["properties", "definitions", "$defs", "patternProperties"];
243
- for (const key of objectKeys) {
244
- const nested = result[key];
245
- if (nested && typeof nested === "object") {
246
- const sanitized = {};
247
- for (const [k, v] of Object.entries(nested)) {
248
- sanitized[k] = v && typeof v === "object" ? sanitizeJsonSchema(v) : v;
249
- }
250
- result[key] = sanitized;
251
- }
252
- }
253
- const singleKeys = ["items", "additionalProperties", "not", "if", "then", "else", "contains", "propertyNames"];
254
- for (const key of singleKeys) {
255
- const nested = result[key];
256
- if (nested && typeof nested === "object" && !Array.isArray(nested)) {
257
- result[key] = sanitizeJsonSchema(nested);
258
- }
259
- }
260
- const arrayKeys = ["anyOf", "oneOf", "allOf"];
261
- for (const key of arrayKeys) {
262
- const nested = result[key];
263
- if (Array.isArray(nested)) {
264
- result[key] = nested.map((item) => item && typeof item === "object" ? sanitizeJsonSchema(item) : item);
265
- }
266
- }
267
- return result;
268
- }
269
- function anthropicToolChoiceToOpenAI(toolChoice) {
270
- if (!toolChoice || typeof toolChoice !== "object")
271
- return;
272
- const tc = toolChoice;
273
- const type = tc.type;
274
- switch (type) {
275
- case "auto":
276
- return "auto";
277
- case "any":
278
- return "required";
279
- case "tool":
280
- return {
281
- type: "function",
282
- function: { name: tc.name }
283
- };
284
- default:
285
- return;
286
- }
287
- }
288
- var init_convertTools = () => {};
289
-
290
- // src/services/api/openai/streamAdapter.ts
291
- import { randomUUID } from "crypto";
292
- async function* adaptOpenAIStreamToAnthropic(stream, model) {
293
- const messageId = `msg_${randomUUID().replace(/-/g, "").slice(0, 24)}`;
294
- let started = false;
295
- let currentContentIndex = -1;
296
- const toolBlocks = new Map;
297
- let thinkingBlockOpen = false;
298
- let textBlockOpen = false;
299
- let inputTokens = 0;
300
- let outputTokens = 0;
301
- let cachedReadTokens = 0;
302
- const openBlockIndices = new Set;
303
- let pendingFinishReason = null;
304
- let pendingHasToolCalls = false;
305
- for await (const chunk of stream) {
306
- const choice = chunk.choices?.[0];
307
- const delta = choice?.delta;
308
- if (chunk.usage) {
309
- inputTokens = chunk.usage.prompt_tokens ?? inputTokens;
310
- outputTokens = chunk.usage.completion_tokens ?? outputTokens;
311
- const details = chunk.usage.prompt_tokens_details;
312
- if (details?.cached_tokens != null) {
313
- cachedReadTokens = details.cached_tokens;
314
- }
315
- }
316
- if (!started) {
317
- started = true;
318
- yield {
319
- type: "message_start",
320
- message: {
321
- id: messageId,
322
- type: "message",
323
- role: "assistant",
324
- content: [],
325
- model,
326
- stop_reason: null,
327
- stop_sequence: null,
328
- usage: {
329
- input_tokens: inputTokens,
330
- output_tokens: 0,
331
- cache_creation_input_tokens: 0,
332
- cache_read_input_tokens: cachedReadTokens
333
- }
334
- }
335
- };
336
- }
337
- if (!delta)
338
- continue;
339
- const reasoningContent = delta.reasoning_content;
340
- if (reasoningContent != null && reasoningContent !== "") {
341
- if (!thinkingBlockOpen) {
342
- currentContentIndex++;
343
- thinkingBlockOpen = true;
344
- openBlockIndices.add(currentContentIndex);
345
- yield {
346
- type: "content_block_start",
347
- index: currentContentIndex,
348
- content_block: {
349
- type: "thinking",
350
- thinking: "",
351
- signature: ""
352
- }
353
- };
354
- }
355
- yield {
356
- type: "content_block_delta",
357
- index: currentContentIndex,
358
- delta: {
359
- type: "thinking_delta",
360
- thinking: reasoningContent
361
- }
362
- };
363
- }
364
- if (delta.content != null && delta.content !== "") {
365
- if (!textBlockOpen) {
366
- if (thinkingBlockOpen) {
367
- yield {
368
- type: "content_block_stop",
369
- index: currentContentIndex
370
- };
371
- openBlockIndices.delete(currentContentIndex);
372
- thinkingBlockOpen = false;
373
- }
374
- currentContentIndex++;
375
- textBlockOpen = true;
376
- openBlockIndices.add(currentContentIndex);
377
- yield {
378
- type: "content_block_start",
379
- index: currentContentIndex,
380
- content_block: {
381
- type: "text",
382
- text: ""
383
- }
384
- };
385
- }
386
- yield {
387
- type: "content_block_delta",
388
- index: currentContentIndex,
389
- delta: {
390
- type: "text_delta",
391
- text: delta.content
392
- }
393
- };
394
- }
395
- if (delta.tool_calls) {
396
- for (const tc of delta.tool_calls) {
397
- const tcIndex = tc.index;
398
- if (!toolBlocks.has(tcIndex)) {
399
- if (thinkingBlockOpen) {
400
- yield {
401
- type: "content_block_stop",
402
- index: currentContentIndex
403
- };
404
- openBlockIndices.delete(currentContentIndex);
405
- thinkingBlockOpen = false;
406
- }
407
- if (textBlockOpen) {
408
- yield {
409
- type: "content_block_stop",
410
- index: currentContentIndex
411
- };
412
- openBlockIndices.delete(currentContentIndex);
413
- textBlockOpen = false;
414
- }
415
- currentContentIndex++;
416
- const toolId = tc.id || `toolu_${randomUUID().replace(/-/g, "").slice(0, 24)}`;
417
- const toolName = tc.function?.name || "";
418
- toolBlocks.set(tcIndex, {
419
- contentIndex: currentContentIndex,
420
- id: toolId,
421
- name: toolName,
422
- arguments: ""
423
- });
424
- openBlockIndices.add(currentContentIndex);
425
- yield {
426
- type: "content_block_start",
427
- index: currentContentIndex,
428
- content_block: {
429
- type: "tool_use",
430
- id: toolId,
431
- name: toolName,
432
- input: {}
433
- }
434
- };
435
- }
436
- const argFragment = tc.function?.arguments;
437
- if (argFragment) {
438
- toolBlocks.get(tcIndex).arguments += argFragment;
439
- yield {
440
- type: "content_block_delta",
441
- index: toolBlocks.get(tcIndex).contentIndex,
442
- delta: {
443
- type: "input_json_delta",
444
- partial_json: argFragment
445
- }
446
- };
447
- }
448
- }
449
- }
450
- if (choice?.finish_reason) {
451
- if (thinkingBlockOpen) {
452
- yield {
453
- type: "content_block_stop",
454
- index: currentContentIndex
455
- };
456
- openBlockIndices.delete(currentContentIndex);
457
- thinkingBlockOpen = false;
458
- }
459
- if (textBlockOpen) {
460
- yield {
461
- type: "content_block_stop",
462
- index: currentContentIndex
463
- };
464
- openBlockIndices.delete(currentContentIndex);
465
- textBlockOpen = false;
466
- }
467
- for (const [, block] of toolBlocks) {
468
- if (openBlockIndices.has(block.contentIndex)) {
469
- yield {
470
- type: "content_block_stop",
471
- index: block.contentIndex
472
- };
473
- openBlockIndices.delete(block.contentIndex);
474
- }
475
- }
476
- pendingFinishReason = choice.finish_reason;
477
- pendingHasToolCalls = toolBlocks.size > 0;
478
- }
479
- }
480
- for (const idx of openBlockIndices) {
481
- yield {
482
- type: "content_block_stop",
483
- index: idx
484
- };
485
- }
486
- if (pendingFinishReason !== null) {
487
- const stopReason = pendingFinishReason === "length" ? "max_tokens" : pendingHasToolCalls ? "tool_use" : mapFinishReason(pendingFinishReason);
488
- yield {
489
- type: "message_delta",
490
- delta: {
491
- stop_reason: stopReason,
492
- stop_sequence: null
493
- },
494
- usage: {
495
- input_tokens: inputTokens,
496
- output_tokens: outputTokens,
497
- cache_read_input_tokens: cachedReadTokens,
498
- cache_creation_input_tokens: 0
499
- }
500
- };
501
- yield {
502
- type: "message_stop"
503
- };
504
- }
505
- }
506
- function mapFinishReason(reason) {
507
- switch (reason) {
508
- case "stop":
509
- return "end_turn";
510
- case "tool_calls":
511
- return "tool_use";
512
- case "length":
513
- return "max_tokens";
514
- case "content_filter":
515
- return "end_turn";
516
- default:
517
- return "end_turn";
518
- }
519
- }
520
- var init_streamAdapter = () => {};
521
-
522
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/tslib.mjs
523
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
524
- if (kind === "m")
525
- throw new TypeError("Private method is not writable");
526
- if (kind === "a" && !f)
527
- throw new TypeError("Private accessor was defined without a setter");
528
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
529
- throw new TypeError("Cannot write private member to an object whose class did not declare it");
530
- return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
531
- }
532
- function __classPrivateFieldGet(receiver, state, kind, f) {
533
- if (kind === "a" && !f)
534
- throw new TypeError("Private accessor was defined without a getter");
535
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
536
- throw new TypeError("Cannot read private member from an object whose class did not declare it");
537
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
538
- }
539
- var init_tslib = () => {};
540
-
541
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/utils/uuid.mjs
542
- var uuid4 = function() {
543
- const { crypto: crypto2 } = globalThis;
544
- if (crypto2?.randomUUID) {
545
- uuid4 = crypto2.randomUUID.bind(crypto2);
546
- return crypto2.randomUUID();
547
- }
548
- const u8 = new Uint8Array(1);
549
- const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
550
- return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16));
551
- };
552
- var init_uuid = () => {};
553
-
554
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/errors.mjs
555
- function isAbortError(err) {
556
- return typeof err === "object" && err !== null && (("name" in err) && err.name === "AbortError" || ("message" in err) && String(err.message).includes("FetchRequestCanceledException"));
557
- }
558
- var castToError = (err) => {
559
- if (err instanceof Error)
560
- return err;
561
- if (typeof err === "object" && err !== null) {
562
- try {
563
- if (Object.prototype.toString.call(err) === "[object Error]") {
564
- const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
565
- if (err.stack)
566
- error.stack = err.stack;
567
- if (err.cause && !error.cause)
568
- error.cause = err.cause;
569
- if (err.name)
570
- error.name = err.name;
571
- return error;
572
- }
573
- } catch {}
574
- try {
575
- return new Error(JSON.stringify(err));
576
- } catch {}
577
- }
578
- return new Error(err);
579
- };
580
- var init_errors = () => {};
581
-
582
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/core/error.mjs
583
- var OpenAIError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError, LengthFinishReasonError, ContentFilterFinishReasonError, InvalidWebhookSignatureError;
584
- var init_error = __esm(() => {
585
- init_errors();
586
- OpenAIError = class OpenAIError extends Error {
587
- };
588
- APIError = class APIError extends OpenAIError {
589
- constructor(status, error, message, headers) {
590
- super(`${APIError.makeMessage(status, error, message)}`);
591
- this.status = status;
592
- this.headers = headers;
593
- this.requestID = headers?.get("x-request-id");
594
- this.error = error;
595
- const data = error;
596
- this.code = data?.["code"];
597
- this.param = data?.["param"];
598
- this.type = data?.["type"];
599
- }
600
- static makeMessage(status, error, message) {
601
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
602
- if (status && msg) {
603
- return `${status} ${msg}`;
604
- }
605
- if (status) {
606
- return `${status} status code (no body)`;
607
- }
608
- if (msg) {
609
- return msg;
610
- }
611
- return "(no status code or body)";
612
- }
613
- static generate(status, errorResponse, message, headers) {
614
- if (!status || !headers) {
615
- return new APIConnectionError({ message, cause: castToError(errorResponse) });
616
- }
617
- const error = errorResponse?.["error"];
618
- if (status === 400) {
619
- return new BadRequestError(status, error, message, headers);
620
- }
621
- if (status === 401) {
622
- return new AuthenticationError(status, error, message, headers);
623
- }
624
- if (status === 403) {
625
- return new PermissionDeniedError(status, error, message, headers);
626
- }
627
- if (status === 404) {
628
- return new NotFoundError(status, error, message, headers);
629
- }
630
- if (status === 409) {
631
- return new ConflictError(status, error, message, headers);
632
- }
633
- if (status === 422) {
634
- return new UnprocessableEntityError(status, error, message, headers);
635
- }
636
- if (status === 429) {
637
- return new RateLimitError(status, error, message, headers);
638
- }
639
- if (status >= 500) {
640
- return new InternalServerError(status, error, message, headers);
641
- }
642
- return new APIError(status, error, message, headers);
643
- }
644
- };
645
- APIUserAbortError = class APIUserAbortError extends APIError {
646
- constructor({ message } = {}) {
647
- super(undefined, undefined, message || "Request was aborted.", undefined);
648
- }
649
- };
650
- APIConnectionError = class APIConnectionError extends APIError {
651
- constructor({ message, cause }) {
652
- super(undefined, undefined, message || "Connection error.", undefined);
653
- if (cause)
654
- this.cause = cause;
655
- }
656
- };
657
- APIConnectionTimeoutError = class APIConnectionTimeoutError extends APIConnectionError {
658
- constructor({ message } = {}) {
659
- super({ message: message ?? "Request timed out." });
660
- }
661
- };
662
- BadRequestError = class BadRequestError extends APIError {
663
- };
664
- AuthenticationError = class AuthenticationError extends APIError {
665
- };
666
- PermissionDeniedError = class PermissionDeniedError extends APIError {
667
- };
668
- NotFoundError = class NotFoundError extends APIError {
669
- };
670
- ConflictError = class ConflictError extends APIError {
671
- };
672
- UnprocessableEntityError = class UnprocessableEntityError extends APIError {
673
- };
674
- RateLimitError = class RateLimitError extends APIError {
675
- };
676
- InternalServerError = class InternalServerError extends APIError {
677
- };
678
- LengthFinishReasonError = class LengthFinishReasonError extends OpenAIError {
679
- constructor() {
680
- super(`Could not parse response content as the length limit was reached`);
681
- }
682
- };
683
- ContentFilterFinishReasonError = class ContentFilterFinishReasonError extends OpenAIError {
684
- constructor() {
685
- super(`Could not parse response content as the request was rejected by the content filter`);
686
- }
687
- };
688
- InvalidWebhookSignatureError = class InvalidWebhookSignatureError extends Error {
689
- constructor(message) {
690
- super(message);
691
- }
692
- };
693
- });
694
-
695
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/utils/values.mjs
696
- function maybeObj(x) {
697
- if (typeof x !== "object") {
698
- return {};
699
- }
700
- return x ?? {};
701
- }
702
- function isEmptyObj(obj) {
703
- if (!obj)
704
- return true;
705
- for (const _k in obj)
706
- return false;
707
- return true;
708
- }
709
- function hasOwn(obj, key) {
710
- return Object.prototype.hasOwnProperty.call(obj, key);
711
- }
712
- function isObj(obj) {
713
- return obj != null && typeof obj === "object" && !Array.isArray(obj);
714
- }
715
- var startsWithSchemeRegexp, isAbsoluteURL = (url) => {
716
- return startsWithSchemeRegexp.test(url);
717
- }, isArray = (val) => (isArray = Array.isArray, isArray(val)), isReadonlyArray, validatePositiveInteger = (name, n) => {
718
- if (typeof n !== "number" || !Number.isInteger(n)) {
719
- throw new OpenAIError(`${name} must be an integer`);
720
- }
721
- if (n < 0) {
722
- throw new OpenAIError(`${name} must be a positive integer`);
723
- }
724
- return n;
725
- }, safeJSON = (text) => {
726
- try {
727
- return JSON.parse(text);
728
- } catch (err) {
729
- return;
730
- }
731
- };
732
- var init_values = __esm(() => {
733
- init_error();
734
- startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
735
- isReadonlyArray = isArray;
736
- });
737
-
738
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/utils/sleep.mjs
739
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
740
- var init_sleep = () => {};
741
-
742
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/version.mjs
743
- var VERSION = "6.33.0";
744
- var init_version = () => {};
745
-
746
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/internal/detect-platform.mjs
747
- function getDetectedPlatform() {
748
- if (typeof Deno !== "undefined" && Deno.build != null) {
749
- return "deno";
750
- }
751
- if (typeof EdgeRuntime !== "undefined") {
752
- return "edge";
753
- }
754
- if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
755
- return "node";
756
- }
757
- return "unknown";
758
- }
759
- function getBrowserInfo() {
760
- if (typeof navigator === "undefined" || !navigator) {
761
- return null;
762
- }
763
- const browserPatterns = [
764
- { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
765
- { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
766
- { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
767
- { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
768
- { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
769
- { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
770
- ];
771
- for (const { key, pattern } of browserPatterns) {
772
- const match = pattern.exec(navigator.userAgent);
773
- if (match) {
774
- const major = match[1] || 0;
775
- const minor = match[2] || 0;
776
- const patch = match[3] || 0;
777
- return { browser: key, version: `${major}.${minor}.${patch}` };
778
- }
779
- }
780
- return null;
781
- }
782
- var isRunningInBrowser = () => {
783
- return typeof window !== "undefined" && typeof window.document !== "undefined" && typeof navigator !== "undefined";
784
- }, getPlatformProperties = () => {
785
- const detectedPlatform = getDetectedPlatform();
786
- if (detectedPlatform === "deno") {
787
- return {
788
- "X-Stainless-Lang": "js",
789
- "X-Stainless-Package-Version": VERSION,
790
- "X-Stainless-OS": normalizePlatform(Deno.build.os),
791
- "X-Stainless-Arch": normalizeArch(Deno.build.arch),
792
- "X-Stainless-Runtime": "deno",
793
- "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
794
- };
795
- }
796
- if (typeof EdgeRuntime !== "undefined") {
797
- return {
798
- "X-Stainless-Lang": "js",
799
- "X-Stainless-Package-Version": VERSION,
800
- "X-Stainless-OS": "Unknown",
801
- "X-Stainless-Arch": `other:${EdgeRuntime}`,
802
- "X-Stainless-Runtime": "edge",
803
- "X-Stainless-Runtime-Version": globalThis.process.version
804
- };
805
- }
806
- if (detectedPlatform === "node") {
807
- return {
808
- "X-Stainless-Lang": "js",
809
- "X-Stainless-Package-Version": VERSION,
810
- "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"),
811
- "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"),
812
- "X-Stainless-Runtime": "node",
813
- "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
814
- };
815
- }
816
- const browserInfo = getBrowserInfo();
817
- if (browserInfo) {
818
- return {
819
- "X-Stainless-Lang": "js",
820
- "X-Stainless-Package-Version": VERSION,
821
- "X-Stainless-OS": "Unknown",
822
- "X-Stainless-Arch": "unknown",
823
- "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
824
- "X-Stainless-Runtime-Version": browserInfo.version
825
- };
418
+ const browserInfo = getBrowserInfo();
419
+ if (browserInfo) {
420
+ return {
421
+ "X-Stainless-Lang": "js",
422
+ "X-Stainless-Package-Version": VERSION,
423
+ "X-Stainless-OS": "Unknown",
424
+ "X-Stainless-Arch": "unknown",
425
+ "X-Stainless-Runtime": `browser:${browserInfo.browser}`,
426
+ "X-Stainless-Runtime-Version": browserInfo.version
427
+ };
826
428
  }
827
429
  return {
828
430
  "X-Stainless-Lang": "js",
@@ -2157,7 +1759,7 @@ var init_path = __esm(() => {
2157
1759
 
2158
1760
  // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/resources/chat/completions/messages.mjs
2159
1761
  var Messages;
2160
- var init_messages = __esm(() => {
1762
+ var init_messages2 = __esm(() => {
2161
1763
  init_resource();
2162
1764
  init_pagination();
2163
1765
  init_path();
@@ -3423,8 +3025,8 @@ var init_ChatCompletionStreamingRunner = __esm(() => {
3423
3025
  var Completions;
3424
3026
  var init_completions = __esm(() => {
3425
3027
  init_resource();
3426
- init_messages();
3427
- init_messages();
3028
+ init_messages2();
3029
+ init_messages2();
3428
3030
  init_pagination();
3429
3031
  init_path();
3430
3032
  init_ChatCompletionRunner();
@@ -3496,7 +3098,7 @@ var init_chat = __esm(() => {
3496
3098
  // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/resources/chat/completions/index.mjs
3497
3099
  var init_completions2 = __esm(() => {
3498
3100
  init_completions();
3499
- init_messages();
3101
+ init_messages2();
3500
3102
  init_completions();
3501
3103
  });
3502
3104
 
@@ -3838,7 +3440,7 @@ var init_chatkit = __esm(() => {
3838
3440
 
3839
3441
  // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/resources/beta/threads/messages.mjs
3840
3442
  var Messages2;
3841
- var init_messages2 = __esm(() => {
3443
+ var init_messages3 = __esm(() => {
3842
3444
  init_resource();
3843
3445
  init_pagination();
3844
3446
  init_headers();
@@ -4608,8 +4210,8 @@ var init_runs = __esm(() => {
4608
4210
  var Threads2;
4609
4211
  var init_threads2 = __esm(() => {
4610
4212
  init_resource();
4611
- init_messages2();
4612
- init_messages2();
4213
+ init_messages3();
4214
+ init_messages3();
4613
4215
  init_runs();
4614
4216
  init_runs();
4615
4217
  init_headers();
@@ -6247,649 +5849,1579 @@ var init_videos = __esm(() => {
6247
5849
  edit(body, options) {
6248
5850
  return this._client.post("/videos/edits", multipartFormRequestOptions({ body, ...options }, this._client));
6249
5851
  }
6250
- extend(body, options) {
6251
- return this._client.post("/videos/extensions", multipartFormRequestOptions({ body, ...options }, this._client));
5852
+ extend(body, options) {
5853
+ return this._client.post("/videos/extensions", multipartFormRequestOptions({ body, ...options }, this._client));
5854
+ }
5855
+ getCharacter(characterID, options) {
5856
+ return this._client.get(path`/videos/characters/${characterID}`, options);
5857
+ }
5858
+ remix(videoID, body, options) {
5859
+ return this._client.post(path`/videos/${videoID}/remix`, maybeMultipartFormRequestOptions({ body, ...options }, this._client));
5860
+ }
5861
+ };
5862
+ });
5863
+
5864
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/resources/webhooks/webhooks.mjs
5865
+ var _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader, Webhooks;
5866
+ var init_webhooks = __esm(() => {
5867
+ init_tslib();
5868
+ init_error2();
5869
+ init_resource();
5870
+ init_headers();
5871
+ Webhooks = class Webhooks extends APIResource {
5872
+ constructor() {
5873
+ super(...arguments);
5874
+ _Webhooks_instances.add(this);
5875
+ }
5876
+ async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
5877
+ await this.verifySignature(payload, headers, secret, tolerance);
5878
+ return JSON.parse(payload);
5879
+ }
5880
+ async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
5881
+ if (typeof crypto === "undefined" || typeof crypto.subtle.importKey !== "function" || typeof crypto.subtle.verify !== "function") {
5882
+ throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");
5883
+ }
5884
+ __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret);
5885
+ const headersObj = buildHeaders([headers]).values;
5886
+ const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature");
5887
+ const timestamp = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp");
5888
+ const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-id");
5889
+ const timestampSeconds = parseInt(timestamp, 10);
5890
+ if (isNaN(timestampSeconds)) {
5891
+ throw new InvalidWebhookSignatureError("Invalid webhook timestamp format");
5892
+ }
5893
+ const nowSeconds = Math.floor(Date.now() / 1000);
5894
+ if (nowSeconds - timestampSeconds > tolerance) {
5895
+ throw new InvalidWebhookSignatureError("Webhook timestamp is too old");
5896
+ }
5897
+ if (timestampSeconds > nowSeconds + tolerance) {
5898
+ throw new InvalidWebhookSignatureError("Webhook timestamp is too new");
5899
+ }
5900
+ const signatures = signatureHeader.split(" ").map((part) => part.startsWith("v1,") ? part.substring(3) : part);
5901
+ const decodedSecret = secret.startsWith("whsec_") ? Buffer.from(secret.replace("whsec_", ""), "base64") : Buffer.from(secret, "utf-8");
5902
+ const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`;
5903
+ const key = await crypto.subtle.importKey("raw", decodedSecret, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
5904
+ for (const signature of signatures) {
5905
+ try {
5906
+ const signatureBytes = Buffer.from(signature, "base64");
5907
+ const isValid = await crypto.subtle.verify("HMAC", key, signatureBytes, new TextEncoder().encode(signedPayload));
5908
+ if (isValid) {
5909
+ return;
5910
+ }
5911
+ } catch {
5912
+ continue;
5913
+ }
5914
+ }
5915
+ throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");
5916
+ }
5917
+ };
5918
+ _Webhooks_instances = new WeakSet, _Webhooks_validateSecret = function _Webhooks_validateSecret2(secret) {
5919
+ if (typeof secret !== "string" || secret.length === 0) {
5920
+ 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`);
5921
+ }
5922
+ }, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader2(headers, name) {
5923
+ if (!headers) {
5924
+ throw new Error(`Headers are required`);
5925
+ }
5926
+ const value = headers.get(name);
5927
+ if (value === null || value === undefined) {
5928
+ throw new Error(`Missing required header: ${name}`);
5929
+ }
5930
+ return value;
5931
+ };
5932
+ });
5933
+
5934
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/resources/webhooks/index.mjs
5935
+ var init_webhooks2 = __esm(() => {
5936
+ init_webhooks();
5937
+ });
5938
+
5939
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/resources/webhooks.mjs
5940
+ var init_webhooks3 = __esm(() => {
5941
+ init_webhooks2();
5942
+ });
5943
+
5944
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/resources/index.mjs
5945
+ var init_resources = __esm(() => {
5946
+ init_audio();
5947
+ init_batches();
5948
+ init_beta();
5949
+ init_completions3();
5950
+ init_containers();
5951
+ init_conversations();
5952
+ init_embeddings();
5953
+ init_evals();
5954
+ init_files2();
5955
+ init_fine_tuning();
5956
+ init_graders2();
5957
+ init_images();
5958
+ init_models();
5959
+ init_moderations();
5960
+ init_realtime2();
5961
+ init_responses();
5962
+ init_skills();
5963
+ init_uploads3();
5964
+ init_vector_stores();
5965
+ init_videos();
5966
+ init_webhooks3();
5967
+ init_chat2();
5968
+ init_shared();
5969
+ });
5970
+
5971
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/client.mjs
5972
+ class OpenAI {
5973
+ constructor({ baseURL = readEnv("OPENAI_BASE_URL"), apiKey = readEnv("OPENAI_API_KEY"), organization = readEnv("OPENAI_ORG_ID") ?? null, project = readEnv("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv("OPENAI_WEBHOOK_SECRET") ?? null, ...opts } = {}) {
5974
+ _OpenAI_instances.add(this);
5975
+ _OpenAI_encoder.set(this, undefined);
5976
+ this.completions = new Completions2(this);
5977
+ this.chat = new Chat(this);
5978
+ this.embeddings = new Embeddings(this);
5979
+ this.files = new Files2(this);
5980
+ this.images = new Images(this);
5981
+ this.audio = new Audio(this);
5982
+ this.moderations = new Moderations(this);
5983
+ this.models = new Models(this);
5984
+ this.fineTuning = new FineTuning(this);
5985
+ this.graders = new Graders2(this);
5986
+ this.vectorStores = new VectorStores(this);
5987
+ this.webhooks = new Webhooks(this);
5988
+ this.beta = new Beta(this);
5989
+ this.batches = new Batches(this);
5990
+ this.uploads = new Uploads(this);
5991
+ this.responses = new Responses(this);
5992
+ this.realtime = new Realtime2(this);
5993
+ this.conversations = new Conversations(this);
5994
+ this.evals = new Evals(this);
5995
+ this.containers = new Containers(this);
5996
+ this.skills = new Skills(this);
5997
+ this.videos = new Videos(this);
5998
+ if (apiKey === undefined) {
5999
+ throw new OpenAIError("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");
6000
+ }
6001
+ const options = {
6002
+ apiKey,
6003
+ organization,
6004
+ project,
6005
+ webhookSecret,
6006
+ ...opts,
6007
+ baseURL: baseURL || `https://api.openai.com/v1`
6008
+ };
6009
+ if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
6010
+ throw new OpenAIError(`It looks like you're running in a browser-like environment.
6011
+
6012
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
6013
+ If you understand the risks and have appropriate mitigations in place,
6014
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
6015
+
6016
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
6017
+
6018
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
6019
+ `);
6020
+ }
6021
+ this.baseURL = options.baseURL;
6022
+ this.timeout = options.timeout ?? _a2.DEFAULT_TIMEOUT;
6023
+ this.logger = options.logger ?? console;
6024
+ const defaultLogLevel = "warn";
6025
+ this.logLevel = defaultLogLevel;
6026
+ this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("OPENAI_LOG"), "process.env['OPENAI_LOG']", this) ?? defaultLogLevel;
6027
+ this.fetchOptions = options.fetchOptions;
6028
+ this.maxRetries = options.maxRetries ?? 2;
6029
+ this.fetch = options.fetch ?? getDefaultFetch();
6030
+ __classPrivateFieldSet(this, _OpenAI_encoder, FallbackEncoder, "f");
6031
+ this._options = options;
6032
+ this.apiKey = typeof apiKey === "string" ? apiKey : "Missing Key";
6033
+ this.organization = organization;
6034
+ this.project = project;
6035
+ this.webhookSecret = webhookSecret;
6036
+ }
6037
+ withOptions(options) {
6038
+ const client = new this.constructor({
6039
+ ...this._options,
6040
+ baseURL: this.baseURL,
6041
+ maxRetries: this.maxRetries,
6042
+ timeout: this.timeout,
6043
+ logger: this.logger,
6044
+ logLevel: this.logLevel,
6045
+ fetch: this.fetch,
6046
+ fetchOptions: this.fetchOptions,
6047
+ apiKey: this.apiKey,
6048
+ organization: this.organization,
6049
+ project: this.project,
6050
+ webhookSecret: this.webhookSecret,
6051
+ ...options
6052
+ });
6053
+ return client;
6054
+ }
6055
+ defaultQuery() {
6056
+ return this._options.defaultQuery;
6057
+ }
6058
+ validateHeaders({ values: values2, nulls }) {
6059
+ return;
6060
+ }
6061
+ async authHeaders(opts) {
6062
+ return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]);
6063
+ }
6064
+ stringifyQuery(query2) {
6065
+ return stringifyQuery(query2);
6066
+ }
6067
+ getUserAgent() {
6068
+ return `${this.constructor.name}/JS ${VERSION}`;
6069
+ }
6070
+ defaultIdempotencyKey() {
6071
+ return `stainless-node-retry-${uuid4()}`;
6072
+ }
6073
+ makeStatusError(status, error2, message, headers) {
6074
+ return APIError.generate(status, error2, message, headers);
6075
+ }
6076
+ async _callApiKey() {
6077
+ const apiKey = this._options.apiKey;
6078
+ if (typeof apiKey !== "function")
6079
+ return false;
6080
+ let token;
6081
+ try {
6082
+ token = await apiKey();
6083
+ } catch (err) {
6084
+ if (err instanceof OpenAIError)
6085
+ throw err;
6086
+ throw new OpenAIError(`Failed to get token from 'apiKey' function: ${err.message}`, { cause: err });
6087
+ }
6088
+ if (typeof token !== "string" || !token) {
6089
+ throw new OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`);
6252
6090
  }
6253
- getCharacter(characterID, options) {
6254
- return this._client.get(path`/videos/characters/${characterID}`, options);
6091
+ this.apiKey = token;
6092
+ return true;
6093
+ }
6094
+ buildURL(path2, query2, defaultBaseURL) {
6095
+ const baseURL = !__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
6096
+ const url = isAbsoluteURL(path2) ? new URL(path2) : new URL(baseURL + (baseURL.endsWith("/") && path2.startsWith("/") ? path2.slice(1) : path2));
6097
+ const defaultQuery = this.defaultQuery();
6098
+ const pathQuery = Object.fromEntries(url.searchParams);
6099
+ if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {
6100
+ query2 = { ...pathQuery, ...defaultQuery, ...query2 };
6255
6101
  }
6256
- remix(videoID, body, options) {
6257
- return this._client.post(path`/videos/${videoID}/remix`, maybeMultipartFormRequestOptions({ body, ...options }, this._client));
6102
+ if (typeof query2 === "object" && query2 && !Array.isArray(query2)) {
6103
+ url.search = this.stringifyQuery(query2);
6258
6104
  }
6259
- };
6260
- });
6261
-
6262
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/resources/webhooks/webhooks.mjs
6263
- var _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader, Webhooks;
6264
- var init_webhooks = __esm(() => {
6265
- init_tslib();
6266
- init_error2();
6267
- init_resource();
6268
- init_headers();
6269
- Webhooks = class Webhooks extends APIResource {
6270
- constructor() {
6271
- super(...arguments);
6272
- _Webhooks_instances.add(this);
6105
+ return url.toString();
6106
+ }
6107
+ async prepareOptions(options) {
6108
+ await this._callApiKey();
6109
+ }
6110
+ async prepareRequest(request, { url, options }) {}
6111
+ get(path2, opts) {
6112
+ return this.methodRequest("get", path2, opts);
6113
+ }
6114
+ post(path2, opts) {
6115
+ return this.methodRequest("post", path2, opts);
6116
+ }
6117
+ patch(path2, opts) {
6118
+ return this.methodRequest("patch", path2, opts);
6119
+ }
6120
+ put(path2, opts) {
6121
+ return this.methodRequest("put", path2, opts);
6122
+ }
6123
+ delete(path2, opts) {
6124
+ return this.methodRequest("delete", path2, opts);
6125
+ }
6126
+ methodRequest(method, path2, opts) {
6127
+ return this.request(Promise.resolve(opts).then((opts2) => {
6128
+ return { method, path: path2, ...opts2 };
6129
+ }));
6130
+ }
6131
+ request(options, remainingRetries = null) {
6132
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
6133
+ }
6134
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
6135
+ const options = await optionsInput;
6136
+ const maxRetries = options.maxRetries ?? this.maxRetries;
6137
+ if (retriesRemaining == null) {
6138
+ retriesRemaining = maxRetries;
6273
6139
  }
6274
- async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
6275
- await this.verifySignature(payload, headers, secret, tolerance);
6276
- return JSON.parse(payload);
6140
+ await this.prepareOptions(options);
6141
+ const { req, url, timeout } = await this.buildRequest(options, {
6142
+ retryCount: maxRetries - retriesRemaining
6143
+ });
6144
+ await this.prepareRequest(req, { url, options });
6145
+ const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
6146
+ const retryLogStr = retryOfRequestLogID === undefined ? "" : `, retryOf: ${retryOfRequestLogID}`;
6147
+ const startTime = Date.now();
6148
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
6149
+ retryOfRequestLogID,
6150
+ method: options.method,
6151
+ url,
6152
+ options,
6153
+ headers: req.headers
6154
+ }));
6155
+ if (options.signal?.aborted) {
6156
+ throw new APIUserAbortError;
6277
6157
  }
6278
- async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
6279
- if (typeof crypto === "undefined" || typeof crypto.subtle.importKey !== "function" || typeof crypto.subtle.verify !== "function") {
6280
- throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");
6158
+ const controller = new AbortController;
6159
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
6160
+ const headersTime = Date.now();
6161
+ if (response instanceof globalThis.Error) {
6162
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
6163
+ if (options.signal?.aborted) {
6164
+ throw new APIUserAbortError;
6281
6165
  }
6282
- __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret);
6283
- const headersObj = buildHeaders([headers]).values;
6284
- const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature");
6285
- const timestamp = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp");
6286
- const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-id");
6287
- const timestampSeconds = parseInt(timestamp, 10);
6288
- if (isNaN(timestampSeconds)) {
6289
- throw new InvalidWebhookSignatureError("Invalid webhook timestamp format");
6166
+ const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
6167
+ if (retriesRemaining) {
6168
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
6169
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
6170
+ retryOfRequestLogID,
6171
+ url,
6172
+ durationMs: headersTime - startTime,
6173
+ message: response.message
6174
+ }));
6175
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
6290
6176
  }
6291
- const nowSeconds = Math.floor(Date.now() / 1000);
6292
- if (nowSeconds - timestampSeconds > tolerance) {
6293
- throw new InvalidWebhookSignatureError("Webhook timestamp is too old");
6177
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
6178
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({
6179
+ retryOfRequestLogID,
6180
+ url,
6181
+ durationMs: headersTime - startTime,
6182
+ message: response.message
6183
+ }));
6184
+ if (isTimeout) {
6185
+ throw new APIConnectionTimeoutError;
6294
6186
  }
6295
- if (timestampSeconds > nowSeconds + tolerance) {
6296
- throw new InvalidWebhookSignatureError("Webhook timestamp is too new");
6187
+ throw new APIConnectionError({ cause: response });
6188
+ }
6189
+ const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "x-request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("");
6190
+ const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`;
6191
+ if (!response.ok) {
6192
+ const shouldRetry = await this.shouldRetry(response);
6193
+ if (retriesRemaining && shouldRetry) {
6194
+ const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
6195
+ await CancelReadableStream(response.body);
6196
+ loggerFor(this).info(`${responseInfo} - ${retryMessage2}`);
6197
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({
6198
+ retryOfRequestLogID,
6199
+ url: response.url,
6200
+ status: response.status,
6201
+ headers: response.headers,
6202
+ durationMs: headersTime - startTime
6203
+ }));
6204
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
6297
6205
  }
6298
- const signatures = signatureHeader.split(" ").map((part) => part.startsWith("v1,") ? part.substring(3) : part);
6299
- const decodedSecret = secret.startsWith("whsec_") ? Buffer.from(secret.replace("whsec_", ""), "base64") : Buffer.from(secret, "utf-8");
6300
- const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`;
6301
- const key = await crypto.subtle.importKey("raw", decodedSecret, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
6302
- for (const signature of signatures) {
6303
- try {
6304
- const signatureBytes = Buffer.from(signature, "base64");
6305
- const isValid = await crypto.subtle.verify("HMAC", key, signatureBytes, new TextEncoder().encode(signedPayload));
6306
- if (isValid) {
6307
- return;
6308
- }
6309
- } catch {
6310
- continue;
6311
- }
6206
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
6207
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
6208
+ const errText = await response.text().catch((err2) => castToError(err2).message);
6209
+ const errJSON = safeJSON(errText);
6210
+ const errMessage = errJSON ? undefined : errText;
6211
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
6212
+ retryOfRequestLogID,
6213
+ url: response.url,
6214
+ status: response.status,
6215
+ headers: response.headers,
6216
+ message: errMessage,
6217
+ durationMs: Date.now() - startTime
6218
+ }));
6219
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
6220
+ throw err;
6221
+ }
6222
+ loggerFor(this).info(responseInfo);
6223
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
6224
+ retryOfRequestLogID,
6225
+ url: response.url,
6226
+ status: response.status,
6227
+ headers: response.headers,
6228
+ durationMs: headersTime - startTime
6229
+ }));
6230
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
6231
+ }
6232
+ getAPIList(path2, Page2, opts) {
6233
+ return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path2, ...opts2 })) : { method: "get", path: path2, ...opts });
6234
+ }
6235
+ requestAPIList(Page2, options) {
6236
+ const request = this.makeRequest(options, null, undefined);
6237
+ return new PagePromise(this, request, Page2);
6238
+ }
6239
+ async fetchWithTimeout(url, init, ms, controller) {
6240
+ const { signal, method, ...options } = init || {};
6241
+ const abort = this._makeAbort(controller);
6242
+ if (signal)
6243
+ signal.addEventListener("abort", abort, { once: true });
6244
+ const timeout = setTimeout(abort, ms);
6245
+ const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body;
6246
+ const fetchOptions = {
6247
+ signal: controller.signal,
6248
+ ...isReadableBody ? { duplex: "half" } : {},
6249
+ method: "GET",
6250
+ ...options
6251
+ };
6252
+ if (method) {
6253
+ fetchOptions.method = method.toUpperCase();
6254
+ }
6255
+ try {
6256
+ return await this.fetch.call(undefined, url, fetchOptions);
6257
+ } finally {
6258
+ clearTimeout(timeout);
6259
+ }
6260
+ }
6261
+ async shouldRetry(response) {
6262
+ const shouldRetryHeader = response.headers.get("x-should-retry");
6263
+ if (shouldRetryHeader === "true")
6264
+ return true;
6265
+ if (shouldRetryHeader === "false")
6266
+ return false;
6267
+ if (response.status === 408)
6268
+ return true;
6269
+ if (response.status === 409)
6270
+ return true;
6271
+ if (response.status === 429)
6272
+ return true;
6273
+ if (response.status >= 500)
6274
+ return true;
6275
+ return false;
6276
+ }
6277
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
6278
+ let timeoutMillis;
6279
+ const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
6280
+ if (retryAfterMillisHeader) {
6281
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
6282
+ if (!Number.isNaN(timeoutMs)) {
6283
+ timeoutMillis = timeoutMs;
6312
6284
  }
6313
- throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");
6314
6285
  }
6315
- };
6316
- _Webhooks_instances = new WeakSet, _Webhooks_validateSecret = function _Webhooks_validateSecret2(secret) {
6317
- if (typeof secret !== "string" || secret.length === 0) {
6318
- 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`);
6286
+ const retryAfterHeader = responseHeaders?.get("retry-after");
6287
+ if (retryAfterHeader && !timeoutMillis) {
6288
+ const timeoutSeconds = parseFloat(retryAfterHeader);
6289
+ if (!Number.isNaN(timeoutSeconds)) {
6290
+ timeoutMillis = timeoutSeconds * 1000;
6291
+ } else {
6292
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
6293
+ }
6319
6294
  }
6320
- }, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader2(headers, name) {
6321
- if (!headers) {
6322
- throw new Error(`Headers are required`);
6295
+ if (timeoutMillis === undefined) {
6296
+ const maxRetries = options.maxRetries ?? this.maxRetries;
6297
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
6323
6298
  }
6324
- const value = headers.get(name);
6325
- if (value === null || value === undefined) {
6326
- throw new Error(`Missing required header: ${name}`);
6299
+ await sleep(timeoutMillis);
6300
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
6301
+ }
6302
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
6303
+ const initialRetryDelay = 0.5;
6304
+ const maxRetryDelay = 8;
6305
+ const numRetries = maxRetries - retriesRemaining;
6306
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
6307
+ const jitter = 1 - Math.random() * 0.25;
6308
+ return sleepSeconds * jitter * 1000;
6309
+ }
6310
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
6311
+ const options = { ...inputOptions };
6312
+ const { method, path: path2, query: query2, defaultBaseURL } = options;
6313
+ const url = this.buildURL(path2, query2, defaultBaseURL);
6314
+ if ("timeout" in options)
6315
+ validatePositiveInteger("timeout", options.timeout);
6316
+ options.timeout = options.timeout ?? this.timeout;
6317
+ const { bodyHeaders, body } = this.buildBody({ options });
6318
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
6319
+ const req = {
6320
+ method,
6321
+ headers: reqHeaders,
6322
+ ...options.signal && { signal: options.signal },
6323
+ ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
6324
+ ...body && { body },
6325
+ ...this.fetchOptions ?? {},
6326
+ ...options.fetchOptions ?? {}
6327
+ };
6328
+ return { req, url, timeout: options.timeout };
6329
+ }
6330
+ async buildHeaders({ options, method, bodyHeaders, retryCount }) {
6331
+ let idempotencyHeaders = {};
6332
+ if (this.idempotencyHeader && method !== "get") {
6333
+ if (!options.idempotencyKey)
6334
+ options.idempotencyKey = this.defaultIdempotencyKey();
6335
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
6327
6336
  }
6328
- return value;
6329
- };
6330
- });
6331
-
6332
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/resources/webhooks/index.mjs
6333
- var init_webhooks2 = __esm(() => {
6334
- init_webhooks();
6335
- });
6336
-
6337
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/resources/webhooks.mjs
6338
- var init_webhooks3 = __esm(() => {
6339
- init_webhooks2();
6340
- });
6341
-
6342
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/resources/index.mjs
6343
- var init_resources = __esm(() => {
6344
- init_audio();
6337
+ const headers = buildHeaders([
6338
+ idempotencyHeaders,
6339
+ {
6340
+ Accept: "application/json",
6341
+ "User-Agent": this.getUserAgent(),
6342
+ "X-Stainless-Retry-Count": String(retryCount),
6343
+ ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1000)) } : {},
6344
+ ...getPlatformHeaders(),
6345
+ "OpenAI-Organization": this.organization,
6346
+ "OpenAI-Project": this.project
6347
+ },
6348
+ await this.authHeaders(options),
6349
+ this._options.defaultHeaders,
6350
+ bodyHeaders,
6351
+ options.headers
6352
+ ]);
6353
+ this.validateHeaders(headers);
6354
+ return headers.values;
6355
+ }
6356
+ _makeAbort(controller) {
6357
+ return () => controller.abort();
6358
+ }
6359
+ buildBody({ options: { body, headers: rawHeaders } }) {
6360
+ if (!body) {
6361
+ return { bodyHeaders: undefined, body: undefined };
6362
+ }
6363
+ const headers = buildHeaders([rawHeaders]);
6364
+ if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && headers.values.has("content-type") || globalThis.Blob && body instanceof globalThis.Blob || body instanceof FormData || body instanceof URLSearchParams || globalThis.ReadableStream && body instanceof globalThis.ReadableStream) {
6365
+ return { bodyHeaders: undefined, body };
6366
+ } else if (typeof body === "object" && ((Symbol.asyncIterator in body) || (Symbol.iterator in body) && ("next" in body) && typeof body.next === "function")) {
6367
+ return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
6368
+ } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
6369
+ return {
6370
+ bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
6371
+ body: this.stringifyQuery(body)
6372
+ };
6373
+ } else {
6374
+ return __classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers });
6375
+ }
6376
+ }
6377
+ }
6378
+ var _OpenAI_instances, _a2, _OpenAI_encoder, _OpenAI_baseURLOverridden;
6379
+ var init_client = __esm(() => {
6380
+ init_tslib();
6381
+ init_uuid();
6382
+ init_values();
6383
+ init_sleep();
6384
+ init_errors();
6385
+ init_detect_platform();
6386
+ init_shims();
6387
+ init_request_options();
6388
+ init_query();
6389
+ init_version();
6390
+ init_error();
6391
+ init_pagination();
6392
+ init_uploads2();
6393
+ init_resources();
6394
+ init_api_promise();
6345
6395
  init_batches();
6346
- init_beta();
6347
6396
  init_completions3();
6348
- init_containers();
6349
- init_conversations();
6350
6397
  init_embeddings();
6351
- init_evals();
6352
6398
  init_files2();
6353
- init_fine_tuning();
6354
- init_graders2();
6355
6399
  init_images();
6356
6400
  init_models();
6357
6401
  init_moderations();
6402
+ init_videos();
6403
+ init_audio();
6404
+ init_beta();
6405
+ init_chat();
6406
+ init_containers();
6407
+ init_conversations();
6408
+ init_evals();
6409
+ init_fine_tuning();
6410
+ init_graders2();
6358
6411
  init_realtime2();
6359
6412
  init_responses();
6360
6413
  init_skills();
6361
6414
  init_uploads3();
6362
6415
  init_vector_stores();
6363
- init_videos();
6364
- init_webhooks3();
6365
- init_chat2();
6366
- init_shared();
6416
+ init_webhooks();
6417
+ init_detect_platform();
6418
+ init_headers();
6419
+ init_env();
6420
+ init_log();
6421
+ init_values();
6422
+ _a2 = OpenAI, _OpenAI_encoder = new WeakMap, _OpenAI_instances = new WeakSet, _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden2() {
6423
+ return this.baseURL !== "https://api.openai.com/v1";
6424
+ };
6425
+ OpenAI.OpenAI = _a2;
6426
+ OpenAI.DEFAULT_TIMEOUT = 600000;
6427
+ OpenAI.OpenAIError = OpenAIError;
6428
+ OpenAI.APIError = APIError;
6429
+ OpenAI.APIConnectionError = APIConnectionError;
6430
+ OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError;
6431
+ OpenAI.APIUserAbortError = APIUserAbortError;
6432
+ OpenAI.NotFoundError = NotFoundError;
6433
+ OpenAI.ConflictError = ConflictError;
6434
+ OpenAI.RateLimitError = RateLimitError;
6435
+ OpenAI.BadRequestError = BadRequestError;
6436
+ OpenAI.AuthenticationError = AuthenticationError;
6437
+ OpenAI.InternalServerError = InternalServerError;
6438
+ OpenAI.PermissionDeniedError = PermissionDeniedError;
6439
+ OpenAI.UnprocessableEntityError = UnprocessableEntityError;
6440
+ OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError;
6441
+ OpenAI.toFile = toFile;
6442
+ OpenAI.Completions = Completions2;
6443
+ OpenAI.Chat = Chat;
6444
+ OpenAI.Embeddings = Embeddings;
6445
+ OpenAI.Files = Files2;
6446
+ OpenAI.Images = Images;
6447
+ OpenAI.Audio = Audio;
6448
+ OpenAI.Moderations = Moderations;
6449
+ OpenAI.Models = Models;
6450
+ OpenAI.FineTuning = FineTuning;
6451
+ OpenAI.Graders = Graders2;
6452
+ OpenAI.VectorStores = VectorStores;
6453
+ OpenAI.Webhooks = Webhooks;
6454
+ OpenAI.Beta = Beta;
6455
+ OpenAI.Batches = Batches;
6456
+ OpenAI.Uploads = Uploads;
6457
+ OpenAI.Responses = Responses;
6458
+ OpenAI.Realtime = Realtime2;
6459
+ OpenAI.Conversations = Conversations;
6460
+ OpenAI.Evals = Evals;
6461
+ OpenAI.Containers = Containers;
6462
+ OpenAI.Skills = Skills;
6463
+ OpenAI.Videos = Videos;
6367
6464
  });
6368
6465
 
6369
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/client.mjs
6370
- class OpenAI {
6371
- constructor({ baseURL = readEnv("OPENAI_BASE_URL"), apiKey = readEnv("OPENAI_API_KEY"), organization = readEnv("OPENAI_ORG_ID") ?? null, project = readEnv("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv("OPENAI_WEBHOOK_SECRET") ?? null, ...opts } = {}) {
6372
- _OpenAI_instances.add(this);
6373
- _OpenAI_encoder.set(this, undefined);
6374
- this.completions = new Completions2(this);
6375
- this.chat = new Chat(this);
6376
- this.embeddings = new Embeddings(this);
6377
- this.files = new Files2(this);
6378
- this.images = new Images(this);
6379
- this.audio = new Audio(this);
6380
- this.moderations = new Moderations(this);
6381
- this.models = new Models(this);
6382
- this.fineTuning = new FineTuning(this);
6383
- this.graders = new Graders2(this);
6384
- this.vectorStores = new VectorStores(this);
6385
- this.webhooks = new Webhooks(this);
6386
- this.beta = new Beta(this);
6387
- this.batches = new Batches(this);
6388
- this.uploads = new Uploads(this);
6389
- this.responses = new Responses(this);
6390
- this.realtime = new Realtime2(this);
6391
- this.conversations = new Conversations(this);
6392
- this.evals = new Evals(this);
6393
- this.containers = new Containers(this);
6394
- this.skills = new Skills(this);
6395
- this.videos = new Videos(this);
6396
- if (apiKey === undefined) {
6397
- throw new OpenAIError("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");
6398
- }
6399
- const options = {
6400
- apiKey,
6401
- organization,
6402
- project,
6403
- webhookSecret,
6404
- ...opts,
6405
- baseURL: baseURL || `https://api.openai.com/v1`
6406
- };
6407
- if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
6408
- throw new OpenAIError(`It looks like you're running in a browser-like environment.
6409
-
6410
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
6411
- If you understand the risks and have appropriate mitigations in place,
6412
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
6466
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/azure.mjs
6467
+ var _deployments_endpoints;
6468
+ var init_azure = __esm(() => {
6469
+ init_headers();
6470
+ init_error2();
6471
+ init_utils2();
6472
+ init_client();
6473
+ _deployments_endpoints = new Set([
6474
+ "/completions",
6475
+ "/chat/completions",
6476
+ "/embeddings",
6477
+ "/audio/transcriptions",
6478
+ "/audio/translations",
6479
+ "/audio/speech",
6480
+ "/images/generations",
6481
+ "/batches",
6482
+ "/images/edits"
6483
+ ]);
6484
+ });
6413
6485
 
6414
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
6486
+ // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/index.mjs
6487
+ var init_openai = __esm(() => {
6488
+ init_client();
6489
+ init_uploads2();
6490
+ init_api_promise();
6491
+ init_client();
6492
+ init_pagination();
6493
+ init_error();
6494
+ init_azure();
6495
+ });
6415
6496
 
6416
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
6417
- `);
6418
- }
6419
- this.baseURL = options.baseURL;
6420
- this.timeout = options.timeout ?? _a2.DEFAULT_TIMEOUT;
6421
- this.logger = options.logger ?? console;
6422
- const defaultLogLevel = "warn";
6423
- this.logLevel = defaultLogLevel;
6424
- this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("OPENAI_LOG"), "process.env['OPENAI_LOG']", this) ?? defaultLogLevel;
6425
- this.fetchOptions = options.fetchOptions;
6426
- this.maxRetries = options.maxRetries ?? 2;
6427
- this.fetch = options.fetch ?? getDefaultFetch();
6428
- __classPrivateFieldSet(this, _OpenAI_encoder, FallbackEncoder, "f");
6429
- this._options = options;
6430
- this.apiKey = typeof apiKey === "string" ? apiKey : "Missing Key";
6431
- this.organization = organization;
6432
- this.project = project;
6433
- this.webhookSecret = webhookSecret;
6497
+ // src/services/api/openai/client.ts
6498
+ function getOpenAIClient(options) {
6499
+ if (cachedClient)
6500
+ return cachedClient;
6501
+ const apiKey = process.env.OPENAI_API_KEY || "";
6502
+ const baseURL = process.env.OPENAI_BASE_URL;
6503
+ const client = new OpenAI({
6504
+ apiKey,
6505
+ ...baseURL && { baseURL },
6506
+ maxRetries: options?.maxRetries ?? 0,
6507
+ timeout: parseInt(process.env.API_TIMEOUT_MS || String(600 * 1000), 10),
6508
+ dangerouslyAllowBrowser: true,
6509
+ ...process.env.OPENAI_ORG_ID && { organization: process.env.OPENAI_ORG_ID },
6510
+ ...process.env.OPENAI_PROJECT_ID && { project: process.env.OPENAI_PROJECT_ID },
6511
+ fetchOptions: getProxyFetchOptions({ forAnthropicAPI: false }),
6512
+ ...options?.fetchOverride && { fetch: options.fetchOverride }
6513
+ });
6514
+ if (!options?.fetchOverride) {
6515
+ cachedClient = client;
6434
6516
  }
6435
- withOptions(options) {
6436
- const client = new this.constructor({
6437
- ...this._options,
6438
- baseURL: this.baseURL,
6439
- maxRetries: this.maxRetries,
6440
- timeout: this.timeout,
6441
- logger: this.logger,
6442
- logLevel: this.logLevel,
6443
- fetch: this.fetch,
6444
- fetchOptions: this.fetchOptions,
6445
- apiKey: this.apiKey,
6446
- organization: this.organization,
6447
- project: this.project,
6448
- webhookSecret: this.webhookSecret,
6449
- ...options
6517
+ return client;
6518
+ }
6519
+ var cachedClient = null;
6520
+ var init_client2 = __esm(() => {
6521
+ init_openai();
6522
+ init_proxy();
6523
+ });
6524
+
6525
+ // src/services/api/openai/convertMessages.ts
6526
+ function anthropicMessagesToOpenAI(messages, systemPrompt, options) {
6527
+ const result = [];
6528
+ const enableThinking = options?.enableThinking ?? false;
6529
+ const systemText = systemPromptToText(systemPrompt);
6530
+ if (systemText) {
6531
+ result.push({
6532
+ role: "system",
6533
+ content: systemText
6450
6534
  });
6451
- return client;
6452
- }
6453
- defaultQuery() {
6454
- return this._options.defaultQuery;
6455
- }
6456
- validateHeaders({ values: values2, nulls }) {
6457
- return;
6458
6535
  }
6459
- async authHeaders(opts) {
6460
- return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]);
6461
- }
6462
- stringifyQuery(query2) {
6463
- return stringifyQuery(query2);
6464
- }
6465
- getUserAgent() {
6466
- return `${this.constructor.name}/JS ${VERSION}`;
6536
+ const turnBoundaries = new Set;
6537
+ if (enableThinking) {
6538
+ let hasSeenAssistant = false;
6539
+ for (let i = 0;i < messages.length; i++) {
6540
+ const msg = messages[i];
6541
+ if (msg.type === "assistant") {
6542
+ hasSeenAssistant = true;
6543
+ }
6544
+ if (msg.type === "user" && hasSeenAssistant) {
6545
+ const content = msg.message.content;
6546
+ const startsNewUserTurn = typeof content === "string" ? content.length > 0 : Array.isArray(content) && content.some((b) => typeof b === "string" || b && typeof b === "object" && ("type" in b) && b.type !== "tool_result");
6547
+ if (startsNewUserTurn) {
6548
+ turnBoundaries.add(i);
6549
+ }
6550
+ }
6551
+ }
6467
6552
  }
6468
- defaultIdempotencyKey() {
6469
- return `stainless-node-retry-${uuid4()}`;
6553
+ for (let i = 0;i < messages.length; i++) {
6554
+ const msg = messages[i];
6555
+ switch (msg.type) {
6556
+ case "user":
6557
+ result.push(...convertInternalUserMessage(msg));
6558
+ break;
6559
+ case "assistant":
6560
+ const preserveReasoning = enableThinking && !isBeforeAnyTurnBoundary(i, turnBoundaries);
6561
+ result.push(...convertInternalAssistantMessage(msg, preserveReasoning));
6562
+ break;
6563
+ default:
6564
+ break;
6565
+ }
6470
6566
  }
6471
- makeStatusError(status, error2, message, headers) {
6472
- return APIError.generate(status, error2, message, headers);
6567
+ return result;
6568
+ }
6569
+ function systemPromptToText(systemPrompt) {
6570
+ if (!systemPrompt || systemPrompt.length === 0)
6571
+ return "";
6572
+ return systemPrompt.filter(Boolean).join(`
6573
+
6574
+ `);
6575
+ }
6576
+ function isBeforeAnyTurnBoundary(i, boundaries) {
6577
+ for (const b of boundaries) {
6578
+ if (i < b)
6579
+ return true;
6473
6580
  }
6474
- async _callApiKey() {
6475
- const apiKey = this._options.apiKey;
6476
- if (typeof apiKey !== "function")
6477
- return false;
6478
- let token;
6479
- try {
6480
- token = await apiKey();
6481
- } catch (err) {
6482
- if (err instanceof OpenAIError)
6483
- throw err;
6484
- throw new OpenAIError(`Failed to get token from 'apiKey' function: ${err.message}`, { cause: err });
6485
- }
6486
- if (typeof token !== "string" || !token) {
6487
- throw new OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`);
6581
+ return false;
6582
+ }
6583
+ function convertInternalUserMessage(msg) {
6584
+ const result = [];
6585
+ const content = msg.message.content;
6586
+ if (typeof content === "string") {
6587
+ result.push({
6588
+ role: "user",
6589
+ content
6590
+ });
6591
+ } else if (Array.isArray(content)) {
6592
+ const textParts = [];
6593
+ const toolResults = [];
6594
+ const imageParts = [];
6595
+ for (const block of content) {
6596
+ if (typeof block === "string") {
6597
+ textParts.push(block);
6598
+ } else if (block.type === "text") {
6599
+ textParts.push(block.text);
6600
+ } else if (block.type === "tool_result") {
6601
+ toolResults.push(block);
6602
+ } else if (block.type === "image") {
6603
+ const imagePart = convertImageBlockToOpenAI(block);
6604
+ if (imagePart) {
6605
+ imageParts.push(imagePart);
6606
+ }
6607
+ }
6488
6608
  }
6489
- this.apiKey = token;
6490
- return true;
6491
- }
6492
- buildURL(path2, query2, defaultBaseURL) {
6493
- const baseURL = !__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
6494
- const url = isAbsoluteURL(path2) ? new URL(path2) : new URL(baseURL + (baseURL.endsWith("/") && path2.startsWith("/") ? path2.slice(1) : path2));
6495
- const defaultQuery = this.defaultQuery();
6496
- const pathQuery = Object.fromEntries(url.searchParams);
6497
- if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {
6498
- query2 = { ...pathQuery, ...defaultQuery, ...query2 };
6609
+ for (const tr of toolResults) {
6610
+ result.push(convertToolResult(tr));
6499
6611
  }
6500
- if (typeof query2 === "object" && query2 && !Array.isArray(query2)) {
6501
- url.search = this.stringifyQuery(query2);
6612
+ if (imageParts.length > 0) {
6613
+ const multiContent = [];
6614
+ if (textParts.length > 0) {
6615
+ multiContent.push({ type: "text", text: textParts.join(`
6616
+ `) });
6617
+ }
6618
+ multiContent.push(...imageParts);
6619
+ result.push({
6620
+ role: "user",
6621
+ content: multiContent
6622
+ });
6623
+ } else if (textParts.length > 0) {
6624
+ result.push({
6625
+ role: "user",
6626
+ content: textParts.join(`
6627
+ `)
6628
+ });
6502
6629
  }
6503
- return url.toString();
6504
- }
6505
- async prepareOptions(options) {
6506
- await this._callApiKey();
6507
- }
6508
- async prepareRequest(request, { url, options }) {}
6509
- get(path2, opts) {
6510
- return this.methodRequest("get", path2, opts);
6511
- }
6512
- post(path2, opts) {
6513
- return this.methodRequest("post", path2, opts);
6514
- }
6515
- patch(path2, opts) {
6516
- return this.methodRequest("patch", path2, opts);
6517
6630
  }
6518
- put(path2, opts) {
6519
- return this.methodRequest("put", path2, opts);
6520
- }
6521
- delete(path2, opts) {
6522
- return this.methodRequest("delete", path2, opts);
6631
+ return result;
6632
+ }
6633
+ function convertToolResult(block) {
6634
+ let content;
6635
+ if (typeof block.content === "string") {
6636
+ content = block.content;
6637
+ } else if (Array.isArray(block.content)) {
6638
+ content = block.content.map((c) => {
6639
+ if (typeof c === "string")
6640
+ return c;
6641
+ if ("text" in c)
6642
+ return c.text;
6643
+ return "";
6644
+ }).filter(Boolean).join(`
6645
+ `);
6646
+ } else {
6647
+ content = "";
6523
6648
  }
6524
- methodRequest(method, path2, opts) {
6525
- return this.request(Promise.resolve(opts).then((opts2) => {
6526
- return { method, path: path2, ...opts2 };
6527
- }));
6649
+ return {
6650
+ role: "tool",
6651
+ tool_call_id: block.tool_use_id,
6652
+ content
6653
+ };
6654
+ }
6655
+ function convertInternalAssistantMessage(msg, preserveReasoning = false) {
6656
+ const content = msg.message.content;
6657
+ if (typeof content === "string") {
6658
+ return [
6659
+ {
6660
+ role: "assistant",
6661
+ content
6662
+ }
6663
+ ];
6528
6664
  }
6529
- request(options, remainingRetries = null) {
6530
- return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
6665
+ if (!Array.isArray(content)) {
6666
+ return [
6667
+ {
6668
+ role: "assistant",
6669
+ content: ""
6670
+ }
6671
+ ];
6531
6672
  }
6532
- async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
6533
- const options = await optionsInput;
6534
- const maxRetries = options.maxRetries ?? this.maxRetries;
6535
- if (retriesRemaining == null) {
6536
- retriesRemaining = maxRetries;
6537
- }
6538
- await this.prepareOptions(options);
6539
- const { req, url, timeout } = await this.buildRequest(options, {
6540
- retryCount: maxRetries - retriesRemaining
6541
- });
6542
- await this.prepareRequest(req, { url, options });
6543
- const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
6544
- const retryLogStr = retryOfRequestLogID === undefined ? "" : `, retryOf: ${retryOfRequestLogID}`;
6545
- const startTime = Date.now();
6546
- loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
6547
- retryOfRequestLogID,
6548
- method: options.method,
6549
- url,
6550
- options,
6551
- headers: req.headers
6552
- }));
6553
- if (options.signal?.aborted) {
6554
- throw new APIUserAbortError;
6673
+ const textParts = [];
6674
+ const toolCalls = [];
6675
+ const reasoningParts = [];
6676
+ for (const block of content) {
6677
+ if (typeof block === "string") {
6678
+ textParts.push(block);
6679
+ } else if (block.type === "text") {
6680
+ textParts.push(block.text);
6681
+ } else if (block.type === "tool_use") {
6682
+ const tu = block;
6683
+ toolCalls.push({
6684
+ id: tu.id,
6685
+ type: "function",
6686
+ function: {
6687
+ name: tu.name,
6688
+ arguments: typeof tu.input === "string" ? tu.input : JSON.stringify(tu.input)
6689
+ }
6690
+ });
6691
+ } else if (block.type === "thinking" && preserveReasoning) {
6692
+ const thinkingText = block.thinking;
6693
+ if (typeof thinkingText === "string" && thinkingText) {
6694
+ reasoningParts.push(thinkingText);
6695
+ }
6555
6696
  }
6556
- const controller = new AbortController;
6557
- const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
6558
- const headersTime = Date.now();
6559
- if (response instanceof globalThis.Error) {
6560
- const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
6561
- if (options.signal?.aborted) {
6562
- throw new APIUserAbortError;
6697
+ }
6698
+ const result = {
6699
+ role: "assistant",
6700
+ content: textParts.length > 0 ? textParts.join(`
6701
+ `) : null,
6702
+ ...toolCalls.length > 0 && { tool_calls: toolCalls },
6703
+ ...reasoningParts.length > 0 && { reasoning_content: reasoningParts.join(`
6704
+ `) }
6705
+ };
6706
+ return [result];
6707
+ }
6708
+ function convertImageBlockToOpenAI(block) {
6709
+ const source = block.source;
6710
+ if (!source)
6711
+ return null;
6712
+ if (source.type === "base64" && typeof source.data === "string") {
6713
+ const mediaType = source.media_type || "image/png";
6714
+ return {
6715
+ type: "image_url",
6716
+ image_url: {
6717
+ url: `data:${mediaType};base64,${source.data}`
6563
6718
  }
6564
- const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
6565
- if (retriesRemaining) {
6566
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
6567
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
6568
- retryOfRequestLogID,
6569
- url,
6570
- durationMs: headersTime - startTime,
6571
- message: response.message
6572
- }));
6573
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
6719
+ };
6720
+ }
6721
+ if (source.type === "url" && typeof source.url === "string") {
6722
+ return {
6723
+ type: "image_url",
6724
+ image_url: {
6725
+ url: source.url
6574
6726
  }
6575
- loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
6576
- loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({
6577
- retryOfRequestLogID,
6578
- url,
6579
- durationMs: headersTime - startTime,
6580
- message: response.message
6581
- }));
6582
- if (isTimeout) {
6583
- throw new APIConnectionTimeoutError;
6727
+ };
6728
+ }
6729
+ return null;
6730
+ }
6731
+ var init_convertMessages = () => {};
6732
+
6733
+ // src/services/api/openai/convertTools.ts
6734
+ function anthropicToolsToOpenAI(tools) {
6735
+ return tools.filter((tool) => {
6736
+ const toolType = tool.type;
6737
+ return tool.type === "custom" || !("type" in tool) || toolType !== "server";
6738
+ }).map((tool) => {
6739
+ const anyTool = tool;
6740
+ const name = anyTool.name || "";
6741
+ const description = anyTool.description || "";
6742
+ const inputSchema = anyTool.input_schema;
6743
+ return {
6744
+ type: "function",
6745
+ function: {
6746
+ name,
6747
+ description,
6748
+ parameters: sanitizeJsonSchema(inputSchema || { type: "object", properties: {} })
6584
6749
  }
6585
- throw new APIConnectionError({ cause: response });
6586
- }
6587
- const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "x-request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("");
6588
- const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`;
6589
- if (!response.ok) {
6590
- const shouldRetry = await this.shouldRetry(response);
6591
- if (retriesRemaining && shouldRetry) {
6592
- const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
6593
- await CancelReadableStream(response.body);
6594
- loggerFor(this).info(`${responseInfo} - ${retryMessage2}`);
6595
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({
6596
- retryOfRequestLogID,
6597
- url: response.url,
6598
- status: response.status,
6599
- headers: response.headers,
6600
- durationMs: headersTime - startTime
6601
- }));
6602
- return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
6750
+ };
6751
+ });
6752
+ }
6753
+ function sanitizeJsonSchema(schema) {
6754
+ if (!schema || typeof schema !== "object")
6755
+ return schema;
6756
+ const result = { ...schema };
6757
+ if ("const" in result) {
6758
+ result.enum = [result.const];
6759
+ delete result.const;
6760
+ }
6761
+ const objectKeys = ["properties", "definitions", "$defs", "patternProperties"];
6762
+ for (const key of objectKeys) {
6763
+ const nested = result[key];
6764
+ if (nested && typeof nested === "object") {
6765
+ const sanitized = {};
6766
+ for (const [k, v] of Object.entries(nested)) {
6767
+ sanitized[k] = v && typeof v === "object" ? sanitizeJsonSchema(v) : v;
6603
6768
  }
6604
- const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
6605
- loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
6606
- const errText = await response.text().catch((err2) => castToError(err2).message);
6607
- const errJSON = safeJSON(errText);
6608
- const errMessage = errJSON ? undefined : errText;
6609
- loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
6610
- retryOfRequestLogID,
6611
- url: response.url,
6612
- status: response.status,
6613
- headers: response.headers,
6614
- message: errMessage,
6615
- durationMs: Date.now() - startTime
6616
- }));
6617
- const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
6618
- throw err;
6769
+ result[key] = sanitized;
6619
6770
  }
6620
- loggerFor(this).info(responseInfo);
6621
- loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
6622
- retryOfRequestLogID,
6623
- url: response.url,
6624
- status: response.status,
6625
- headers: response.headers,
6626
- durationMs: headersTime - startTime
6627
- }));
6628
- return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
6629
6771
  }
6630
- getAPIList(path2, Page2, opts) {
6631
- return this.requestAPIList(Page2, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path2, ...opts2 })) : { method: "get", path: path2, ...opts });
6772
+ const singleKeys = ["items", "additionalProperties", "not", "if", "then", "else", "contains", "propertyNames"];
6773
+ for (const key of singleKeys) {
6774
+ const nested = result[key];
6775
+ if (nested && typeof nested === "object" && !Array.isArray(nested)) {
6776
+ result[key] = sanitizeJsonSchema(nested);
6777
+ }
6632
6778
  }
6633
- requestAPIList(Page2, options) {
6634
- const request = this.makeRequest(options, null, undefined);
6635
- return new PagePromise(this, request, Page2);
6779
+ const arrayKeys = ["anyOf", "oneOf", "allOf"];
6780
+ for (const key of arrayKeys) {
6781
+ const nested = result[key];
6782
+ if (Array.isArray(nested)) {
6783
+ result[key] = nested.map((item) => item && typeof item === "object" ? sanitizeJsonSchema(item) : item);
6784
+ }
6636
6785
  }
6637
- async fetchWithTimeout(url, init, ms, controller) {
6638
- const { signal, method, ...options } = init || {};
6639
- const abort = this._makeAbort(controller);
6640
- if (signal)
6641
- signal.addEventListener("abort", abort, { once: true });
6642
- const timeout = setTimeout(abort, ms);
6643
- const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body;
6644
- const fetchOptions = {
6645
- signal: controller.signal,
6646
- ...isReadableBody ? { duplex: "half" } : {},
6647
- method: "GET",
6648
- ...options
6649
- };
6650
- if (method) {
6651
- fetchOptions.method = method.toUpperCase();
6786
+ return result;
6787
+ }
6788
+ function anthropicToolChoiceToOpenAI(toolChoice) {
6789
+ if (!toolChoice || typeof toolChoice !== "object")
6790
+ return;
6791
+ const tc = toolChoice;
6792
+ const type = tc.type;
6793
+ switch (type) {
6794
+ case "auto":
6795
+ return "auto";
6796
+ case "any":
6797
+ return "required";
6798
+ case "tool":
6799
+ return {
6800
+ type: "function",
6801
+ function: { name: tc.name }
6802
+ };
6803
+ default:
6804
+ return;
6805
+ }
6806
+ }
6807
+ var init_convertTools = () => {};
6808
+
6809
+ // src/services/api/openai/streamAdapter.ts
6810
+ import { randomUUID } from "crypto";
6811
+ async function* adaptOpenAIStreamToAnthropic(stream, model) {
6812
+ const messageId = `msg_${randomUUID().replace(/-/g, "").slice(0, 24)}`;
6813
+ let started = false;
6814
+ let currentContentIndex = -1;
6815
+ const toolBlocks = new Map;
6816
+ let thinkingBlockOpen = false;
6817
+ let textBlockOpen = false;
6818
+ let inputTokens = 0;
6819
+ let outputTokens = 0;
6820
+ let cachedReadTokens = 0;
6821
+ const openBlockIndices = new Set;
6822
+ let pendingFinishReason = null;
6823
+ let pendingHasToolCalls = false;
6824
+ for await (const chunk of stream) {
6825
+ const choice = chunk.choices?.[0];
6826
+ const delta = choice?.delta;
6827
+ if (chunk.usage) {
6828
+ inputTokens = chunk.usage.prompt_tokens ?? inputTokens;
6829
+ outputTokens = chunk.usage.completion_tokens ?? outputTokens;
6830
+ const details = chunk.usage.prompt_tokens_details;
6831
+ if (details?.cached_tokens != null) {
6832
+ cachedReadTokens = details.cached_tokens;
6833
+ }
6652
6834
  }
6653
- try {
6654
- return await this.fetch.call(undefined, url, fetchOptions);
6655
- } finally {
6656
- clearTimeout(timeout);
6835
+ if (!started) {
6836
+ started = true;
6837
+ yield {
6838
+ type: "message_start",
6839
+ message: {
6840
+ id: messageId,
6841
+ type: "message",
6842
+ role: "assistant",
6843
+ content: [],
6844
+ model,
6845
+ stop_reason: null,
6846
+ stop_sequence: null,
6847
+ usage: {
6848
+ input_tokens: inputTokens,
6849
+ output_tokens: 0,
6850
+ cache_creation_input_tokens: 0,
6851
+ cache_read_input_tokens: cachedReadTokens
6852
+ }
6853
+ }
6854
+ };
6657
6855
  }
6658
- }
6659
- async shouldRetry(response) {
6660
- const shouldRetryHeader = response.headers.get("x-should-retry");
6661
- if (shouldRetryHeader === "true")
6662
- return true;
6663
- if (shouldRetryHeader === "false")
6664
- return false;
6665
- if (response.status === 408)
6666
- return true;
6667
- if (response.status === 409)
6668
- return true;
6669
- if (response.status === 429)
6670
- return true;
6671
- if (response.status >= 500)
6672
- return true;
6673
- return false;
6674
- }
6675
- async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
6676
- let timeoutMillis;
6677
- const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
6678
- if (retryAfterMillisHeader) {
6679
- const timeoutMs = parseFloat(retryAfterMillisHeader);
6680
- if (!Number.isNaN(timeoutMs)) {
6681
- timeoutMillis = timeoutMs;
6856
+ if (!delta)
6857
+ continue;
6858
+ const reasoningContent = delta.reasoning_content;
6859
+ if (reasoningContent != null && reasoningContent !== "") {
6860
+ if (!thinkingBlockOpen) {
6861
+ currentContentIndex++;
6862
+ thinkingBlockOpen = true;
6863
+ openBlockIndices.add(currentContentIndex);
6864
+ yield {
6865
+ type: "content_block_start",
6866
+ index: currentContentIndex,
6867
+ content_block: {
6868
+ type: "thinking",
6869
+ thinking: "",
6870
+ signature: ""
6871
+ }
6872
+ };
6682
6873
  }
6874
+ yield {
6875
+ type: "content_block_delta",
6876
+ index: currentContentIndex,
6877
+ delta: {
6878
+ type: "thinking_delta",
6879
+ thinking: reasoningContent
6880
+ }
6881
+ };
6683
6882
  }
6684
- const retryAfterHeader = responseHeaders?.get("retry-after");
6685
- if (retryAfterHeader && !timeoutMillis) {
6686
- const timeoutSeconds = parseFloat(retryAfterHeader);
6687
- if (!Number.isNaN(timeoutSeconds)) {
6688
- timeoutMillis = timeoutSeconds * 1000;
6689
- } else {
6690
- timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
6883
+ if (delta.content != null && delta.content !== "") {
6884
+ if (!textBlockOpen) {
6885
+ if (thinkingBlockOpen) {
6886
+ yield {
6887
+ type: "content_block_stop",
6888
+ index: currentContentIndex
6889
+ };
6890
+ openBlockIndices.delete(currentContentIndex);
6891
+ thinkingBlockOpen = false;
6892
+ }
6893
+ currentContentIndex++;
6894
+ textBlockOpen = true;
6895
+ openBlockIndices.add(currentContentIndex);
6896
+ yield {
6897
+ type: "content_block_start",
6898
+ index: currentContentIndex,
6899
+ content_block: {
6900
+ type: "text",
6901
+ text: ""
6902
+ }
6903
+ };
6904
+ }
6905
+ yield {
6906
+ type: "content_block_delta",
6907
+ index: currentContentIndex,
6908
+ delta: {
6909
+ type: "text_delta",
6910
+ text: delta.content
6911
+ }
6912
+ };
6913
+ }
6914
+ if (delta.tool_calls) {
6915
+ for (const tc of delta.tool_calls) {
6916
+ const tcIndex = tc.index;
6917
+ if (!toolBlocks.has(tcIndex)) {
6918
+ if (thinkingBlockOpen) {
6919
+ yield {
6920
+ type: "content_block_stop",
6921
+ index: currentContentIndex
6922
+ };
6923
+ openBlockIndices.delete(currentContentIndex);
6924
+ thinkingBlockOpen = false;
6925
+ }
6926
+ if (textBlockOpen) {
6927
+ yield {
6928
+ type: "content_block_stop",
6929
+ index: currentContentIndex
6930
+ };
6931
+ openBlockIndices.delete(currentContentIndex);
6932
+ textBlockOpen = false;
6933
+ }
6934
+ currentContentIndex++;
6935
+ const toolId = tc.id || `toolu_${randomUUID().replace(/-/g, "").slice(0, 24)}`;
6936
+ const toolName = tc.function?.name || "";
6937
+ toolBlocks.set(tcIndex, {
6938
+ contentIndex: currentContentIndex,
6939
+ id: toolId,
6940
+ name: toolName,
6941
+ arguments: ""
6942
+ });
6943
+ openBlockIndices.add(currentContentIndex);
6944
+ yield {
6945
+ type: "content_block_start",
6946
+ index: currentContentIndex,
6947
+ content_block: {
6948
+ type: "tool_use",
6949
+ id: toolId,
6950
+ name: toolName,
6951
+ input: {}
6952
+ }
6953
+ };
6954
+ }
6955
+ const argFragment = tc.function?.arguments;
6956
+ if (argFragment) {
6957
+ toolBlocks.get(tcIndex).arguments += argFragment;
6958
+ yield {
6959
+ type: "content_block_delta",
6960
+ index: toolBlocks.get(tcIndex).contentIndex,
6961
+ delta: {
6962
+ type: "input_json_delta",
6963
+ partial_json: argFragment
6964
+ }
6965
+ };
6966
+ }
6691
6967
  }
6692
6968
  }
6693
- if (timeoutMillis === undefined) {
6694
- const maxRetries = options.maxRetries ?? this.maxRetries;
6695
- timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
6969
+ if (choice?.finish_reason) {
6970
+ if (thinkingBlockOpen) {
6971
+ yield {
6972
+ type: "content_block_stop",
6973
+ index: currentContentIndex
6974
+ };
6975
+ openBlockIndices.delete(currentContentIndex);
6976
+ thinkingBlockOpen = false;
6977
+ }
6978
+ if (textBlockOpen) {
6979
+ yield {
6980
+ type: "content_block_stop",
6981
+ index: currentContentIndex
6982
+ };
6983
+ openBlockIndices.delete(currentContentIndex);
6984
+ textBlockOpen = false;
6985
+ }
6986
+ for (const [, block] of toolBlocks) {
6987
+ if (openBlockIndices.has(block.contentIndex)) {
6988
+ yield {
6989
+ type: "content_block_stop",
6990
+ index: block.contentIndex
6991
+ };
6992
+ openBlockIndices.delete(block.contentIndex);
6993
+ }
6994
+ }
6995
+ pendingFinishReason = choice.finish_reason;
6996
+ pendingHasToolCalls = toolBlocks.size > 0;
6696
6997
  }
6697
- await sleep(timeoutMillis);
6698
- return this.makeRequest(options, retriesRemaining - 1, requestLogID);
6699
6998
  }
6700
- calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
6701
- const initialRetryDelay = 0.5;
6702
- const maxRetryDelay = 8;
6703
- const numRetries = maxRetries - retriesRemaining;
6704
- const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
6705
- const jitter = 1 - Math.random() * 0.25;
6706
- return sleepSeconds * jitter * 1000;
6999
+ for (const idx of openBlockIndices) {
7000
+ yield {
7001
+ type: "content_block_stop",
7002
+ index: idx
7003
+ };
6707
7004
  }
6708
- async buildRequest(inputOptions, { retryCount = 0 } = {}) {
6709
- const options = { ...inputOptions };
6710
- const { method, path: path2, query: query2, defaultBaseURL } = options;
6711
- const url = this.buildURL(path2, query2, defaultBaseURL);
6712
- if ("timeout" in options)
6713
- validatePositiveInteger("timeout", options.timeout);
6714
- options.timeout = options.timeout ?? this.timeout;
6715
- const { bodyHeaders, body } = this.buildBody({ options });
6716
- const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
6717
- const req = {
6718
- method,
6719
- headers: reqHeaders,
6720
- ...options.signal && { signal: options.signal },
6721
- ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
6722
- ...body && { body },
6723
- ...this.fetchOptions ?? {},
6724
- ...options.fetchOptions ?? {}
7005
+ if (pendingFinishReason !== null) {
7006
+ const stopReason = pendingFinishReason === "length" ? "max_tokens" : pendingHasToolCalls ? "tool_use" : mapFinishReason(pendingFinishReason);
7007
+ yield {
7008
+ type: "message_delta",
7009
+ delta: {
7010
+ stop_reason: stopReason,
7011
+ stop_sequence: null
7012
+ },
7013
+ usage: {
7014
+ input_tokens: inputTokens,
7015
+ output_tokens: outputTokens,
7016
+ cache_read_input_tokens: cachedReadTokens,
7017
+ cache_creation_input_tokens: 0
7018
+ }
7019
+ };
7020
+ yield {
7021
+ type: "message_stop"
6725
7022
  };
6726
- return { req, url, timeout: options.timeout };
6727
7023
  }
6728
- async buildHeaders({ options, method, bodyHeaders, retryCount }) {
6729
- let idempotencyHeaders = {};
6730
- if (this.idempotencyHeader && method !== "get") {
6731
- if (!options.idempotencyKey)
6732
- options.idempotencyKey = this.defaultIdempotencyKey();
6733
- idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
7024
+ }
7025
+ function mapFinishReason(reason) {
7026
+ switch (reason) {
7027
+ case "stop":
7028
+ return "end_turn";
7029
+ case "tool_calls":
7030
+ return "tool_use";
7031
+ case "length":
7032
+ return "max_tokens";
7033
+ case "content_filter":
7034
+ return "end_turn";
7035
+ default:
7036
+ return "end_turn";
7037
+ }
7038
+ }
7039
+ var init_streamAdapter = () => {};
7040
+
7041
+ // src/services/api/openai/modelMapping.ts
7042
+ function getModelFamily(model) {
7043
+ if (/haiku/i.test(model))
7044
+ return "haiku";
7045
+ if (/opus/i.test(model))
7046
+ return "opus";
7047
+ if (/sonnet/i.test(model))
7048
+ return "sonnet";
7049
+ return null;
7050
+ }
7051
+ function resolveOpenAIModel(anthropicModel) {
7052
+ if (process.env.OPENAI_MODEL) {
7053
+ return process.env.OPENAI_MODEL;
7054
+ }
7055
+ const cleanModel = anthropicModel.replace(/\[1m\]$/, "");
7056
+ const family = getModelFamily(cleanModel);
7057
+ if (family) {
7058
+ const openaiEnvVar = `OPENAI_DEFAULT_${family.toUpperCase()}_MODEL`;
7059
+ const openaiOverride = process.env[openaiEnvVar];
7060
+ if (openaiOverride)
7061
+ return openaiOverride;
7062
+ const anthropicEnvVar = `ANTHROPIC_DEFAULT_${family.toUpperCase()}_MODEL`;
7063
+ const anthropicOverride = process.env[anthropicEnvVar];
7064
+ if (anthropicOverride)
7065
+ return anthropicOverride;
7066
+ }
7067
+ return DEFAULT_MODEL_MAP[cleanModel] ?? cleanModel;
7068
+ }
7069
+ var DEFAULT_MODEL_MAP;
7070
+ var init_modelMapping = __esm(() => {
7071
+ DEFAULT_MODEL_MAP = {
7072
+ "claude-sonnet-4-20250514": "gpt-4o",
7073
+ "claude-sonnet-4-5-20250929": "gpt-4o",
7074
+ "claude-sonnet-4-6": "gpt-4o",
7075
+ "claude-opus-4-20250514": "o3",
7076
+ "claude-opus-4-1-20250805": "o3",
7077
+ "claude-opus-4-5-20251101": "o3",
7078
+ "claude-opus-4-6": "o3",
7079
+ "claude-haiku-4-5-20251001": "gpt-4o-mini",
7080
+ "claude-3-5-haiku-20241022": "gpt-4o-mini",
7081
+ "claude-3-7-sonnet-20250219": "gpt-4o",
7082
+ "claude-3-5-sonnet-20241022": "gpt-4o"
7083
+ };
7084
+ });
7085
+
7086
+ // src/services/api/openai/index.ts
7087
+ import { randomUUID as randomUUID2 } from "crypto";
7088
+ function isOpenAIThinkingEnabled(model) {
7089
+ if (isEnvDefinedFalsy(process.env.OPENAI_ENABLE_THINKING))
7090
+ return false;
7091
+ if (isEnvTruthy(process.env.OPENAI_ENABLE_THINKING))
7092
+ return true;
7093
+ const modelLower = model.toLowerCase();
7094
+ return modelLower.includes("deepseek");
7095
+ }
7096
+ function buildOpenAIRequestBody(params) {
7097
+ const { model, messages, tools, toolChoice, enableThinking, maxTokens, temperatureOverride } = params;
7098
+ return {
7099
+ model,
7100
+ messages,
7101
+ max_tokens: maxTokens,
7102
+ ...tools.length > 0 && {
7103
+ tools,
7104
+ ...toolChoice && { tool_choice: toolChoice }
7105
+ },
7106
+ stream: true,
7107
+ stream_options: { include_usage: true },
7108
+ ...enableThinking && {
7109
+ thinking: { type: "enabled" },
7110
+ enable_thinking: true,
7111
+ chat_template_kwargs: { thinking: true }
7112
+ },
7113
+ ...!enableThinking && temperatureOverride !== undefined && {
7114
+ temperature: temperatureOverride
6734
7115
  }
6735
- const headers = buildHeaders([
6736
- idempotencyHeaders,
6737
- {
6738
- Accept: "application/json",
6739
- "User-Agent": this.getUserAgent(),
6740
- "X-Stainless-Retry-Count": String(retryCount),
6741
- ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1000)) } : {},
6742
- ...getPlatformHeaders(),
6743
- "OpenAI-Organization": this.organization,
6744
- "OpenAI-Project": this.project
7116
+ };
7117
+ }
7118
+ function resolveOpenAIMaxTokens(upperLimit, maxOutputTokensOverride) {
7119
+ return maxOutputTokensOverride ?? (process.env.OPENAI_MAX_TOKENS ? parseInt(process.env.OPENAI_MAX_TOKENS, 10) || undefined : undefined) ?? (process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS ? parseInt(process.env.CLAUDE_CODE_MAX_OUTPUT_TOKENS, 10) || undefined : undefined) ?? upperLimit;
7120
+ }
7121
+ function prependDeferredToolListIfNeeded(messages, tools, deferredToolNames, useToolSearch) {
7122
+ if (!useToolSearch || isDeferredToolsDeltaEnabled())
7123
+ return messages;
7124
+ const deferredToolList = tools.filter((tool) => deferredToolNames.has(tool.name)).map(formatDeferredToolLine).sort().join(`
7125
+ `);
7126
+ if (!deferredToolList)
7127
+ return messages;
7128
+ return [
7129
+ createUserMessage({
7130
+ content: `<available-deferred-tools>
7131
+ ${deferredToolList}
7132
+ </available-deferred-tools>`,
7133
+ isMeta: true
7134
+ }),
7135
+ ...messages
7136
+ ];
7137
+ }
7138
+ function isOpenAIConvertibleMessage(msg) {
7139
+ return msg.type === "assistant" || msg.type === "user";
7140
+ }
7141
+ function assembleFinalAssistantOutputs(params) {
7142
+ const { partialMessage, contentBlocks, tools, agentId, usage, stopReason, maxTokens } = params;
7143
+ const outputs = [];
7144
+ const allBlocks = Object.keys(contentBlocks).sort((a, b) => Number(a) - Number(b)).map((k) => contentBlocks[Number(k)]).filter(Boolean);
7145
+ if (allBlocks.length > 0) {
7146
+ outputs.push({
7147
+ message: {
7148
+ ...partialMessage,
7149
+ content: normalizeContentFromAPI(allBlocks, tools, agentId),
7150
+ usage,
7151
+ stop_reason: stopReason,
7152
+ stop_sequence: null
6745
7153
  },
6746
- await this.authHeaders(options),
6747
- this._options.defaultHeaders,
6748
- bodyHeaders,
6749
- options.headers
6750
- ]);
6751
- this.validateHeaders(headers);
6752
- return headers.values;
7154
+ requestId: undefined,
7155
+ type: "assistant",
7156
+ uuid: randomUUID2(),
7157
+ timestamp: new Date().toISOString()
7158
+ });
6753
7159
  }
6754
- _makeAbort(controller) {
6755
- return () => controller.abort();
7160
+ if (stopReason === "max_tokens") {
7161
+ outputs.push(createAssistantAPIErrorMessage({
7162
+ content: `Output truncated: response exceeded the ${maxTokens} token limit. ` + `Set OPENAI_MAX_TOKENS or CLAUDE_CODE_MAX_OUTPUT_TOKENS to override.`,
7163
+ apiError: "max_output_tokens",
7164
+ error: "max_output_tokens"
7165
+ }));
6756
7166
  }
6757
- buildBody({ options: { body, headers: rawHeaders } }) {
6758
- if (!body) {
6759
- return { bodyHeaders: undefined, body: undefined };
7167
+ return outputs;
7168
+ }
7169
+ async function* queryModelOpenAI(messages, systemPrompt, tools, signal, options) {
7170
+ try {
7171
+ const openaiModel = resolveOpenAIModel(options.model);
7172
+ const messagesForAPI = normalizeMessagesForAPI(messages, tools);
7173
+ const useToolSearch = await isToolSearchEnabled(options.model, tools, options.getToolPermissionContext || (async () => getEmptyToolPermissionContext()), options.agents || [], options.querySource);
7174
+ const deferredToolNames = new Set;
7175
+ if (useToolSearch) {
7176
+ for (const t of tools) {
7177
+ if (isDeferredTool(t))
7178
+ deferredToolNames.add(t.name);
7179
+ }
7180
+ }
7181
+ let filteredTools = tools;
7182
+ if (useToolSearch && deferredToolNames.size > 0) {
7183
+ const discoveredToolNames = extractDiscoveredToolNames(messages);
7184
+ filteredTools = tools.filter((tool) => {
7185
+ if (!deferredToolNames.has(tool.name))
7186
+ return true;
7187
+ if (toolMatchesName(tool, TOOL_SEARCH_TOOL_NAME))
7188
+ return true;
7189
+ return discoveredToolNames.has(tool.name);
7190
+ });
6760
7191
  }
6761
- const headers = buildHeaders([rawHeaders]);
6762
- if (ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && headers.values.has("content-type") || globalThis.Blob && body instanceof globalThis.Blob || body instanceof FormData || body instanceof URLSearchParams || globalThis.ReadableStream && body instanceof globalThis.ReadableStream) {
6763
- return { bodyHeaders: undefined, body };
6764
- } else if (typeof body === "object" && ((Symbol.asyncIterator in body) || (Symbol.iterator in body) && ("next" in body) && typeof body.next === "function")) {
6765
- return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
6766
- } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
6767
- return {
6768
- bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
6769
- body: this.stringifyQuery(body)
6770
- };
7192
+ const toolSchemas = await Promise.all(filteredTools.map((tool) => toolToAPISchema(tool, {
7193
+ getToolPermissionContext: options.getToolPermissionContext,
7194
+ tools,
7195
+ agents: options.agents,
7196
+ allowedAgentTypes: options.allowedAgentTypes,
7197
+ model: options.model,
7198
+ deferLoading: useToolSearch && deferredToolNames.has(tool.name)
7199
+ })));
7200
+ const standardTools = toolSchemas.filter((t) => {
7201
+ const anyT = t;
7202
+ return anyT.type !== "advisor_20260301" && anyT.type !== "computer_20250124";
7203
+ });
7204
+ const enableThinking = isOpenAIThinkingEnabled(openaiModel);
7205
+ const openAIConvertibleMessages = messagesForAPI.filter(isOpenAIConvertibleMessage);
7206
+ const messagesWithDeferredToolList = prependDeferredToolListIfNeeded(openAIConvertibleMessages, tools, deferredToolNames, useToolSearch);
7207
+ const openaiMessages = anthropicMessagesToOpenAI(messagesWithDeferredToolList, systemPrompt, { enableThinking });
7208
+ const openaiTools = anthropicToolsToOpenAI(standardTools);
7209
+ const openaiToolChoice = anthropicToolChoiceToOpenAI(options.toolChoice);
7210
+ if (useToolSearch) {
7211
+ const includedDeferredTools = filteredTools.filter((t) => deferredToolNames.has(t.name)).length;
7212
+ logForDebugging(`[OpenAI] Tool search enabled: ${includedDeferredTools}/${deferredToolNames.size} deferred tools included, total tools=${openaiTools.length}`);
6771
7213
  } else {
6772
- return __classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers });
7214
+ logForDebugging(`[OpenAI] Tool search disabled, total tools=${openaiTools.length}`);
7215
+ }
7216
+ const { upperLimit } = getModelMaxOutputTokens(openaiModel);
7217
+ const maxTokens = resolveOpenAIMaxTokens(upperLimit, options.maxOutputTokensOverride);
7218
+ const client = getOpenAIClient({
7219
+ maxRetries: 0,
7220
+ fetchOverride: options.fetchOverride,
7221
+ source: options.querySource
7222
+ });
7223
+ const debugTimestamp = Date.now();
7224
+ const debugRequestData = {
7225
+ model: openaiModel,
7226
+ systemPrompt_text: systemPrompt.join(`
7227
+
7228
+ `),
7229
+ openai_messages_preview: openaiMessages.slice(0, 3).map((m) => ({
7230
+ role: m.role,
7231
+ content_preview: typeof m.content === "string" ? m.content.substring(0, 500) : JSON.stringify(m.content)?.substring(0, 500)
7232
+ })),
7233
+ tools_names: openaiTools.map((t) => t.function?.name ?? t.name)
7234
+ };
7235
+ logForDebugging(`[OpenAI] Calling model=${openaiModel}, messages=${openaiMessages.length}, tools=${openaiTools.length}, thinking=${enableThinking}`);
7236
+ const requestBody = buildOpenAIRequestBody({
7237
+ model: openaiModel,
7238
+ messages: openaiMessages,
7239
+ tools: openaiTools,
7240
+ toolChoice: openaiToolChoice,
7241
+ enableThinking,
7242
+ maxTokens,
7243
+ temperatureOverride: options.temperatureOverride
7244
+ });
7245
+ const stream = await client.chat.completions.create(requestBody, { signal });
7246
+ const adaptedStream = adaptOpenAIStreamToAnthropic(stream, openaiModel);
7247
+ const contentBlocks = {};
7248
+ const collectedMessages = [];
7249
+ let partialMessage;
7250
+ let stopReason = null;
7251
+ let usage = {
7252
+ input_tokens: 0,
7253
+ output_tokens: 0,
7254
+ cache_creation_input_tokens: 0,
7255
+ cache_read_input_tokens: 0
7256
+ };
7257
+ let ttftMs = 0;
7258
+ const start = Date.now();
7259
+ for await (const event of adaptedStream) {
7260
+ switch (event.type) {
7261
+ case "message_start": {
7262
+ partialMessage = event.message;
7263
+ ttftMs = Date.now() - start;
7264
+ if (event.message?.usage) {
7265
+ usage = {
7266
+ ...usage,
7267
+ ...event.message.usage
7268
+ };
7269
+ }
7270
+ break;
7271
+ }
7272
+ case "content_block_start": {
7273
+ const idx = event.index;
7274
+ const cb = event.content_block;
7275
+ if (cb.type === "tool_use") {
7276
+ contentBlocks[idx] = { ...cb, input: "" };
7277
+ } else if (cb.type === "text") {
7278
+ contentBlocks[idx] = { ...cb, text: "" };
7279
+ } else if (cb.type === "thinking") {
7280
+ contentBlocks[idx] = { ...cb, thinking: "", signature: "" };
7281
+ } else {
7282
+ contentBlocks[idx] = { ...cb };
7283
+ }
7284
+ break;
7285
+ }
7286
+ case "content_block_delta": {
7287
+ const idx = event.index;
7288
+ const delta = event.delta;
7289
+ const block = contentBlocks[idx];
7290
+ if (!block)
7291
+ break;
7292
+ if (delta.type === "text_delta") {
7293
+ block.text = (block.text || "") + delta.text;
7294
+ } else if (delta.type === "input_json_delta") {
7295
+ block.input = (block.input || "") + delta.partial_json;
7296
+ } else if (delta.type === "thinking_delta") {
7297
+ block.thinking = (block.thinking || "") + delta.thinking;
7298
+ } else if (delta.type === "signature_delta") {
7299
+ block.signature = delta.signature;
7300
+ }
7301
+ break;
7302
+ }
7303
+ case "content_block_stop": {
7304
+ break;
7305
+ }
7306
+ case "message_delta": {
7307
+ const deltaUsage = event.usage;
7308
+ if (deltaUsage) {
7309
+ usage = { ...usage, ...deltaUsage };
7310
+ }
7311
+ if (event.delta?.stop_reason != null) {
7312
+ stopReason = event.delta.stop_reason;
7313
+ }
7314
+ break;
7315
+ }
7316
+ case "message_stop": {
7317
+ if (partialMessage) {
7318
+ for (const output of assembleFinalAssistantOutputs({
7319
+ partialMessage,
7320
+ contentBlocks,
7321
+ tools,
7322
+ agentId: options.agentId,
7323
+ usage,
7324
+ stopReason,
7325
+ maxTokens
7326
+ })) {
7327
+ if (output.type === "assistant") {
7328
+ collectedMessages.push(output);
7329
+ }
7330
+ yield output;
7331
+ }
7332
+ partialMessage = null;
7333
+ }
7334
+ if (usage.input_tokens + usage.output_tokens > 0) {
7335
+ const costUSD = calculateUSDCost(openaiModel, usage);
7336
+ addToTotalSessionCost(costUSD, usage, options.model);
7337
+ }
7338
+ break;
7339
+ }
7340
+ }
7341
+ yield {
7342
+ type: "stream_event",
7343
+ event,
7344
+ ...event.type === "message_start" ? { ttftMs } : undefined
7345
+ };
7346
+ }
7347
+ if (partialMessage) {
7348
+ for (const output of assembleFinalAssistantOutputs({
7349
+ partialMessage,
7350
+ contentBlocks,
7351
+ tools,
7352
+ agentId: options.agentId,
7353
+ usage,
7354
+ stopReason,
7355
+ maxTokens
7356
+ })) {
7357
+ yield output;
7358
+ }
6773
7359
  }
7360
+ try {
7361
+ const { writeFileSync, mkdirSync } = await import("fs");
7362
+ const { join } = await import("path");
7363
+ const { tmpdir } = await import("os");
7364
+ const debugDir = join(tmpdir(), "claude-code-debug");
7365
+ mkdirSync(debugDir, { recursive: true });
7366
+ const debugFile = join(debugDir, `openai-${debugTimestamp}.json`);
7367
+ const allBlocks = Object.keys(contentBlocks).sort((a, b) => Number(a) - Number(b)).map((k) => contentBlocks[Number(k)]).filter(Boolean);
7368
+ const debugPayload = {
7369
+ timestamp: new Date(debugTimestamp).toISOString(),
7370
+ model: openaiModel,
7371
+ request: debugRequestData,
7372
+ response: {
7373
+ stop_reason: stopReason,
7374
+ usage,
7375
+ content_blocks: allBlocks.map((b) => {
7376
+ if (b.type === "text")
7377
+ return { type: "text", text: b.text };
7378
+ if (b.type === "thinking")
7379
+ return { type: "thinking", thinking_preview: b.thinking?.substring(0, 200) };
7380
+ if (b.type === "tool_use")
7381
+ return { type: "tool_use", name: b.name, input_preview: typeof b.input === "string" ? b.input.substring(0, 500) : b.input };
7382
+ return { type: b.type };
7383
+ }),
7384
+ duration_ms: Date.now() - start
7385
+ }
7386
+ };
7387
+ writeFileSync(debugFile, JSON.stringify(debugPayload, null, 2), "utf-8");
7388
+ logForDebugging(`[DEBUG] OpenAI request+response dumped to ${debugFile}`);
7389
+ } catch (e) {
7390
+ logForDebugging(`[DEBUG] Failed to dump OpenAI debug file: ${e}`);
7391
+ }
7392
+ } catch (error2) {
7393
+ const errorMessage = error2 instanceof Error ? error2.message : String(error2);
7394
+ logForDebugging(`[OpenAI] Error: ${errorMessage}`, { level: "error" });
7395
+ yield createAssistantAPIErrorMessage({
7396
+ content: `API Error: ${errorMessage}`,
7397
+ apiError: "api_error",
7398
+ error: error2 instanceof Error ? error2 : new Error(String(error2))
7399
+ });
6774
7400
  }
6775
7401
  }
6776
- var _OpenAI_instances, _a2, _OpenAI_encoder, _OpenAI_baseURLOverridden;
6777
- var init_client = __esm(() => {
6778
- init_tslib();
6779
- init_uuid();
6780
- init_values();
6781
- init_sleep();
6782
- init_errors();
6783
- init_detect_platform();
6784
- init_shims();
6785
- init_request_options();
6786
- init_query();
6787
- init_version();
6788
- init_error();
6789
- init_pagination();
6790
- init_uploads2();
6791
- init_resources();
6792
- init_api_promise();
6793
- init_batches();
6794
- init_completions3();
6795
- init_embeddings();
6796
- init_files2();
6797
- init_images();
6798
- init_models();
6799
- init_moderations();
6800
- init_videos();
6801
- init_audio();
6802
- init_beta();
6803
- init_chat();
6804
- init_containers();
6805
- init_conversations();
6806
- init_evals();
6807
- init_fine_tuning();
6808
- init_graders2();
6809
- init_realtime2();
6810
- init_responses();
6811
- init_skills();
6812
- init_uploads3();
6813
- init_vector_stores();
6814
- init_webhooks();
6815
- init_detect_platform();
6816
- init_headers();
6817
- init_env();
6818
- init_log();
6819
- init_values();
6820
- _a2 = OpenAI, _OpenAI_encoder = new WeakMap, _OpenAI_instances = new WeakSet, _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden2() {
6821
- return this.baseURL !== "https://api.openai.com/v1";
6822
- };
6823
- OpenAI.OpenAI = _a2;
6824
- OpenAI.DEFAULT_TIMEOUT = 600000;
6825
- OpenAI.OpenAIError = OpenAIError;
6826
- OpenAI.APIError = APIError;
6827
- OpenAI.APIConnectionError = APIConnectionError;
6828
- OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError;
6829
- OpenAI.APIUserAbortError = APIUserAbortError;
6830
- OpenAI.NotFoundError = NotFoundError;
6831
- OpenAI.ConflictError = ConflictError;
6832
- OpenAI.RateLimitError = RateLimitError;
6833
- OpenAI.BadRequestError = BadRequestError;
6834
- OpenAI.AuthenticationError = AuthenticationError;
6835
- OpenAI.InternalServerError = InternalServerError;
6836
- OpenAI.PermissionDeniedError = PermissionDeniedError;
6837
- OpenAI.UnprocessableEntityError = UnprocessableEntityError;
6838
- OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError;
6839
- OpenAI.toFile = toFile;
6840
- OpenAI.Completions = Completions2;
6841
- OpenAI.Chat = Chat;
6842
- OpenAI.Embeddings = Embeddings;
6843
- OpenAI.Files = Files2;
6844
- OpenAI.Images = Images;
6845
- OpenAI.Audio = Audio;
6846
- OpenAI.Moderations = Moderations;
6847
- OpenAI.Models = Models;
6848
- OpenAI.FineTuning = FineTuning;
6849
- OpenAI.Graders = Graders2;
6850
- OpenAI.VectorStores = VectorStores;
6851
- OpenAI.Webhooks = Webhooks;
6852
- OpenAI.Beta = Beta;
6853
- OpenAI.Batches = Batches;
6854
- OpenAI.Uploads = Uploads;
6855
- OpenAI.Responses = Responses;
6856
- OpenAI.Realtime = Realtime2;
6857
- OpenAI.Conversations = Conversations;
6858
- OpenAI.Evals = Evals;
6859
- OpenAI.Containers = Containers;
6860
- OpenAI.Skills = Skills;
6861
- OpenAI.Videos = Videos;
6862
- });
6863
-
6864
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/azure.mjs
6865
- var _deployments_endpoints;
6866
- var init_azure = __esm(() => {
6867
- init_headers();
6868
- init_error2();
6869
- init_utils2();
6870
- init_client();
6871
- _deployments_endpoints = new Set([
6872
- "/completions",
6873
- "/chat/completions",
6874
- "/embeddings",
6875
- "/audio/transcriptions",
6876
- "/audio/translations",
6877
- "/audio/speech",
6878
- "/images/generations",
6879
- "/batches",
6880
- "/images/edits"
6881
- ]);
6882
- });
6883
-
6884
- // node_modules/.bun/openai@6.33.0+e0f88c919211175f/node_modules/openai/index.mjs
6885
- var init_openai = __esm(() => {
6886
- init_client();
6887
- init_uploads2();
6888
- init_api_promise();
6889
- init_client();
6890
- init_pagination();
6891
- init_error();
6892
- init_azure();
7402
+ var init_openai2 = __esm(() => {
7403
+ init_client2();
7404
+ init_convertMessages();
7405
+ init_convertTools();
7406
+ init_streamAdapter();
7407
+ init_modelMapping();
7408
+ init_messages();
7409
+ init_api();
7410
+ init_Tool();
7411
+ init_debug();
7412
+ init_cost_tracker();
7413
+ init_modelCost();
7414
+ init_envUtils();
7415
+ init_context();
7416
+ init_messages();
7417
+ init_toolSearch();
7418
+ init_prompt();
6893
7419
  });
7420
+ init_openai2();
6894
7421
 
6895
- export { OpenAI, init_openai, anthropicMessagesToOpenAI, init_convertMessages, anthropicToolsToOpenAI, anthropicToolChoiceToOpenAI, init_convertTools, adaptOpenAIStreamToAnthropic, init_streamAdapter };
7422
+ export {
7423
+ resolveOpenAIMaxTokens,
7424
+ queryModelOpenAI,
7425
+ isOpenAIThinkingEnabled,
7426
+ buildOpenAIRequestBody
7427
+ };