@anvia/core 1.1.2 → 1.2.1

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 (598) hide show
  1. package/README.md +226 -0
  2. package/dist/agent/agent-stream.js +7 -0
  3. package/dist/agent/agent-stream.js.map +1 -0
  4. package/dist/agent/agent-tool.js +24 -0
  5. package/dist/agent/agent-tool.js.map +1 -0
  6. package/dist/agent/agent.js +89 -0
  7. package/dist/agent/agent.js.map +1 -0
  8. package/dist/agent/errors.js +17 -0
  9. package/dist/agent/errors.js.map +1 -0
  10. package/dist/agent/ids.js +7 -0
  11. package/dist/agent/ids.js.map +1 -0
  12. package/dist/agent/index.d.ts +127 -9
  13. package/dist/agent/index.js +103 -21
  14. package/dist/agent/interactions/index.js +2 -2
  15. package/dist/agent/interactions.js +22 -0
  16. package/dist/agent/interactions.js.map +1 -0
  17. package/dist/agent/lifecycle.js +9 -0
  18. package/dist/agent/lifecycle.js.map +1 -0
  19. package/dist/agent/output-schema.js +10 -0
  20. package/dist/agent/output-schema.js.map +1 -0
  21. package/dist/agent/resolve-options.js +46 -0
  22. package/dist/agent/resolve-options.js.map +1 -0
  23. package/dist/agent/resolved-agent.js +92 -0
  24. package/dist/agent/resolved-agent.js.map +1 -0
  25. package/dist/agent/run-types.js +1 -0
  26. package/dist/agent/run-types.js.map +1 -0
  27. package/dist/agent/snapshot.js +17 -0
  28. package/dist/agent/snapshot.js.map +1 -0
  29. package/dist/agent/team/agent-team.js +98 -0
  30. package/dist/agent/team/agent-team.js.map +1 -0
  31. package/dist/agent/team/errors.js +9 -0
  32. package/dist/agent/team/errors.js.map +1 -0
  33. package/dist/agent/team/index.js +104 -0
  34. package/dist/agent/team/index.js.map +1 -0
  35. package/dist/agent/team/types.js +1 -0
  36. package/dist/agent/team/types.js.map +1 -0
  37. package/dist/agent/tool-catalog.js +37 -0
  38. package/dist/agent/tool-catalog.js.map +1 -0
  39. package/dist/agent/tool-state.js +11 -0
  40. package/dist/agent/tool-state.js.map +1 -0
  41. package/dist/agent/types.js +1 -0
  42. package/dist/agent/types.js.map +1 -0
  43. package/dist/agent/vector-context.js +10 -0
  44. package/dist/agent/vector-context.js.map +1 -0
  45. package/dist/{agent-DTmzs1Qr.d.ts → agent-C9VhENdj.d.ts} +2 -3
  46. package/dist/{chunk-I3Q7XSBB.js → chunk-23LRXKQX.js} +6 -4
  47. package/dist/{chunk-I3Q7XSBB.js.map → chunk-23LRXKQX.js.map} +1 -1
  48. package/dist/{chunk-YK4WAAS4.js → chunk-2NLINXRF.js} +1 -1
  49. package/dist/{chunk-SPD4XVR7.js → chunk-2XSMGVBG.js} +1 -1
  50. package/dist/chunk-3J2CSVPR.js +1 -0
  51. package/dist/chunk-3J2CSVPR.js.map +1 -0
  52. package/dist/chunk-3P3YVJ7V.js +1 -0
  53. package/dist/chunk-3P3YVJ7V.js.map +1 -0
  54. package/dist/chunk-3TAQXJBC.js +107 -0
  55. package/dist/chunk-3TAQXJBC.js.map +1 -0
  56. package/dist/chunk-47NTHIVB.js +76 -0
  57. package/dist/chunk-47NTHIVB.js.map +1 -0
  58. package/dist/chunk-4AW2633B.js +9 -0
  59. package/dist/chunk-4AW2633B.js.map +1 -0
  60. package/dist/{chunk-3XQGVDU5.js → chunk-4C7AXYOM.js} +1 -1
  61. package/dist/{chunk-IZNOP6JG.js → chunk-4FIVU53H.js} +1 -1
  62. package/dist/chunk-4ITAV7YA.js +1 -0
  63. package/dist/chunk-4ITAV7YA.js.map +1 -0
  64. package/dist/{chunk-7JLAIN6E.js → chunk-4ONUNWGC.js} +2 -2
  65. package/dist/chunk-4S4OECPW.js +158 -0
  66. package/dist/chunk-4S4OECPW.js.map +1 -0
  67. package/dist/chunk-4UUIGAIX.js +1 -0
  68. package/dist/chunk-4UUIGAIX.js.map +1 -0
  69. package/dist/chunk-53TPAXYR.js +1 -0
  70. package/dist/chunk-53TPAXYR.js.map +1 -0
  71. package/dist/chunk-54ZZJRP2.js +57 -0
  72. package/dist/chunk-54ZZJRP2.js.map +1 -0
  73. package/dist/chunk-5FCZ64HM.js +112 -0
  74. package/dist/chunk-5FCZ64HM.js.map +1 -0
  75. package/dist/chunk-5I2NVRHC.js +146 -0
  76. package/dist/chunk-5I2NVRHC.js.map +1 -0
  77. package/dist/chunk-5IURMWFN.js +53 -0
  78. package/dist/chunk-5IURMWFN.js.map +1 -0
  79. package/dist/chunk-5M6GTA3T.js +1 -0
  80. package/dist/chunk-5M6GTA3T.js.map +1 -0
  81. package/dist/chunk-5N5W7CX7.js +18 -0
  82. package/dist/chunk-5N5W7CX7.js.map +1 -0
  83. package/dist/chunk-5S7T2URX.js +1 -0
  84. package/dist/chunk-5S7T2URX.js.map +1 -0
  85. package/dist/chunk-5V533R7F.js +19 -0
  86. package/dist/chunk-5V533R7F.js.map +1 -0
  87. package/dist/chunk-5WLIHNNJ.js +56 -0
  88. package/dist/chunk-5WLIHNNJ.js.map +1 -0
  89. package/dist/chunk-6BTJC3ES.js +37 -0
  90. package/dist/chunk-6BTJC3ES.js.map +1 -0
  91. package/dist/chunk-6N4ENZO4.js +24 -0
  92. package/dist/chunk-6N4ENZO4.js.map +1 -0
  93. package/dist/{chunk-4UQALF5Y.js → chunk-6RQYWZI3.js} +2 -36
  94. package/dist/chunk-6RQYWZI3.js.map +1 -0
  95. package/dist/chunk-6TAWRKFK.js +86 -0
  96. package/dist/chunk-6TAWRKFK.js.map +1 -0
  97. package/dist/chunk-72LBHKYP.js +236 -0
  98. package/dist/chunk-72LBHKYP.js.map +1 -0
  99. package/dist/chunk-7F53DOML.js +53 -0
  100. package/dist/chunk-7F53DOML.js.map +1 -0
  101. package/dist/chunk-7LBPRXZP.js +1 -0
  102. package/dist/chunk-7LBPRXZP.js.map +1 -0
  103. package/dist/chunk-A7BXVZXZ.js +25 -0
  104. package/dist/chunk-A7BXVZXZ.js.map +1 -0
  105. package/dist/chunk-AOG6KSV4.js +107 -0
  106. package/dist/chunk-AOG6KSV4.js.map +1 -0
  107. package/dist/chunk-B47EXUHL.js +67 -0
  108. package/dist/chunk-B47EXUHL.js.map +1 -0
  109. package/dist/chunk-B5JQDR33.js +14 -0
  110. package/dist/chunk-B5JQDR33.js.map +1 -0
  111. package/dist/chunk-BDDC72GF.js +189 -0
  112. package/dist/chunk-BDDC72GF.js.map +1 -0
  113. package/dist/chunk-BDKFFFVX.js +342 -0
  114. package/dist/chunk-BDKFFFVX.js.map +1 -0
  115. package/dist/{chunk-QGX73TSQ.js → chunk-BONQTXRQ.js} +3 -12
  116. package/dist/chunk-BONQTXRQ.js.map +1 -0
  117. package/dist/chunk-BUPC72Y2.js +1007 -0
  118. package/dist/chunk-BUPC72Y2.js.map +1 -0
  119. package/dist/chunk-CKKNO4XB.js +70 -0
  120. package/dist/chunk-CKKNO4XB.js.map +1 -0
  121. package/dist/chunk-CX7ZVTO5.js +22 -0
  122. package/dist/chunk-CX7ZVTO5.js.map +1 -0
  123. package/dist/chunk-DU4WA6LQ.js +1 -0
  124. package/dist/chunk-DU4WA6LQ.js.map +1 -0
  125. package/dist/chunk-EJR6VVB3.js +63 -0
  126. package/dist/chunk-EJR6VVB3.js.map +1 -0
  127. package/dist/chunk-EKZRAWBP.js +110 -0
  128. package/dist/chunk-EKZRAWBP.js.map +1 -0
  129. package/dist/chunk-ENZ2XX27.js +26 -0
  130. package/dist/chunk-ENZ2XX27.js.map +1 -0
  131. package/dist/chunk-EOAJBBII.js +1 -0
  132. package/dist/chunk-EOAJBBII.js.map +1 -0
  133. package/dist/chunk-ERN7P6Q4.js +1 -0
  134. package/dist/chunk-ERN7P6Q4.js.map +1 -0
  135. package/dist/chunk-ESOFEAYK.js +57 -0
  136. package/dist/chunk-ESOFEAYK.js.map +1 -0
  137. package/dist/chunk-ETYB5JO6.js +175 -0
  138. package/dist/chunk-ETYB5JO6.js.map +1 -0
  139. package/dist/chunk-EZR5AV3J.js +74 -0
  140. package/dist/chunk-EZR5AV3J.js.map +1 -0
  141. package/dist/chunk-F2OKLHGB.js +9 -0
  142. package/dist/chunk-F2OKLHGB.js.map +1 -0
  143. package/dist/chunk-F3E2RLC7.js +342 -0
  144. package/dist/chunk-F3E2RLC7.js.map +1 -0
  145. package/dist/chunk-FAPIZJS2.js +54 -0
  146. package/dist/chunk-FAPIZJS2.js.map +1 -0
  147. package/dist/{chunk-2QZJTG2E.js → chunk-G336L2IE.js} +11 -71
  148. package/dist/chunk-G336L2IE.js.map +1 -0
  149. package/dist/chunk-GDJNOZ47.js +1 -0
  150. package/dist/chunk-GDJNOZ47.js.map +1 -0
  151. package/dist/chunk-GDY2Z2SZ.js +83 -0
  152. package/dist/chunk-GDY2Z2SZ.js.map +1 -0
  153. package/dist/chunk-GLMYZ6OA.js +20 -0
  154. package/dist/chunk-GLMYZ6OA.js.map +1 -0
  155. package/dist/{chunk-XEVOC433.js → chunk-GPVXCY5I.js} +2 -73
  156. package/dist/chunk-GPVXCY5I.js.map +1 -0
  157. package/dist/{chunk-KSKST3KP.js → chunk-H3H74RWJ.js} +1 -1
  158. package/dist/chunk-HAAGSIZH.js +89 -0
  159. package/dist/chunk-HAAGSIZH.js.map +1 -0
  160. package/dist/{chunk-K5L7R7XM.js → chunk-HHMLE3TZ.js} +6 -54
  161. package/dist/chunk-HHMLE3TZ.js.map +1 -0
  162. package/dist/{chunk-JLJMVRRE.js → chunk-HP34GRQX.js} +10 -83
  163. package/dist/chunk-HP34GRQX.js.map +1 -0
  164. package/dist/chunk-HTI343NP.js +1 -0
  165. package/dist/chunk-HTI343NP.js.map +1 -0
  166. package/dist/{chunk-T2C3CGDQ.js → chunk-HTI7DZJM.js} +6 -4
  167. package/dist/{chunk-T2C3CGDQ.js.map → chunk-HTI7DZJM.js.map} +1 -1
  168. package/dist/chunk-IDNL6IH4.js +294 -0
  169. package/dist/chunk-IDNL6IH4.js.map +1 -0
  170. package/dist/chunk-IV6YQTY2.js +47 -0
  171. package/dist/chunk-IV6YQTY2.js.map +1 -0
  172. package/dist/chunk-J4SINPUA.js +939 -0
  173. package/dist/chunk-J4SINPUA.js.map +1 -0
  174. package/dist/chunk-J6S6MT7O.js +32 -0
  175. package/dist/chunk-J6S6MT7O.js.map +1 -0
  176. package/dist/chunk-JBQNCUXA.js +34 -0
  177. package/dist/chunk-JBQNCUXA.js.map +1 -0
  178. package/dist/chunk-JMJFK3A4.js +1 -0
  179. package/dist/chunk-JMJFK3A4.js.map +1 -0
  180. package/dist/chunk-JMMZICU7.js +74 -0
  181. package/dist/chunk-JMMZICU7.js.map +1 -0
  182. package/dist/chunk-K4IBS7VB.js +55 -0
  183. package/dist/chunk-K4IBS7VB.js.map +1 -0
  184. package/dist/chunk-KBBQSP4M.js +16 -0
  185. package/dist/chunk-KBBQSP4M.js.map +1 -0
  186. package/dist/chunk-KFAVEL5F.js +68 -0
  187. package/dist/chunk-KFAVEL5F.js.map +1 -0
  188. package/dist/chunk-KITX3HDN.js +17 -0
  189. package/dist/chunk-KITX3HDN.js.map +1 -0
  190. package/dist/chunk-KO5NMTAM.js +1 -0
  191. package/dist/chunk-KO5NMTAM.js.map +1 -0
  192. package/dist/chunk-KY4VXIN2.js +118 -0
  193. package/dist/chunk-KY4VXIN2.js.map +1 -0
  194. package/dist/chunk-KZGSXJKU.js +29 -0
  195. package/dist/chunk-KZGSXJKU.js.map +1 -0
  196. package/dist/chunk-LAIATEUB.js +24 -0
  197. package/dist/chunk-LAIATEUB.js.map +1 -0
  198. package/dist/{chunk-OJBFDBLG.js → chunk-LBYJPMHC.js} +2 -2
  199. package/dist/chunk-LKIABZNR.js +49 -0
  200. package/dist/chunk-LKIABZNR.js.map +1 -0
  201. package/dist/chunk-LQJ4KHMY.js +23 -0
  202. package/dist/chunk-LQJ4KHMY.js.map +1 -0
  203. package/dist/chunk-MEN4AFDZ.js +1 -0
  204. package/dist/chunk-MEN4AFDZ.js.map +1 -0
  205. package/dist/chunk-MHOJJYDK.js +93 -0
  206. package/dist/chunk-MHOJJYDK.js.map +1 -0
  207. package/dist/chunk-MJCMKZFP.js +30 -0
  208. package/dist/chunk-MJCMKZFP.js.map +1 -0
  209. package/dist/chunk-MNYMLWWA.js +168 -0
  210. package/dist/chunk-MNYMLWWA.js.map +1 -0
  211. package/dist/chunk-MT3BLVYN.js +31 -0
  212. package/dist/chunk-MT3BLVYN.js.map +1 -0
  213. package/dist/chunk-NF6WBPFG.js +37 -0
  214. package/dist/chunk-NF6WBPFG.js.map +1 -0
  215. package/dist/chunk-NNEKBZSM.js +66 -0
  216. package/dist/chunk-NNEKBZSM.js.map +1 -0
  217. package/dist/chunk-NPJ2T3L5.js +19 -0
  218. package/dist/chunk-NPJ2T3L5.js.map +1 -0
  219. package/dist/chunk-NVALGVQG.js +150 -0
  220. package/dist/chunk-NVALGVQG.js.map +1 -0
  221. package/dist/chunk-O6DTOCBM.js +355 -0
  222. package/dist/chunk-O6DTOCBM.js.map +1 -0
  223. package/dist/chunk-OJF67RNM.js +1 -0
  224. package/dist/chunk-OJF67RNM.js.map +1 -0
  225. package/dist/chunk-PHLGGRHC.js +89 -0
  226. package/dist/chunk-PHLGGRHC.js.map +1 -0
  227. package/dist/chunk-PIMD4DYG.js +104 -0
  228. package/dist/chunk-PIMD4DYG.js.map +1 -0
  229. package/dist/chunk-PJNE75WC.js +1 -0
  230. package/dist/chunk-PJNE75WC.js.map +1 -0
  231. package/dist/{chunk-J6LVLV6P.js → chunk-PLDJCCVL.js} +1 -1
  232. package/dist/{chunk-3RWESPUG.js → chunk-POXHJF3H.js} +6 -51
  233. package/dist/chunk-POXHJF3H.js.map +1 -0
  234. package/dist/chunk-PPJ7SYQL.js +81 -0
  235. package/dist/chunk-PPJ7SYQL.js.map +1 -0
  236. package/dist/chunk-QHGYCYV6.js +91 -0
  237. package/dist/chunk-QHGYCYV6.js.map +1 -0
  238. package/dist/chunk-QUS6S2NB.js +663 -0
  239. package/dist/chunk-QUS6S2NB.js.map +1 -0
  240. package/dist/chunk-R6722CIU.js +28 -0
  241. package/dist/chunk-R6722CIU.js.map +1 -0
  242. package/dist/chunk-RA4YVN43.js +1 -0
  243. package/dist/chunk-RA4YVN43.js.map +1 -0
  244. package/dist/chunk-RT5LUEO3.js +2339 -0
  245. package/dist/chunk-RT5LUEO3.js.map +1 -0
  246. package/dist/chunk-SC4SUIEY.js +1 -0
  247. package/dist/chunk-SC4SUIEY.js.map +1 -0
  248. package/dist/chunk-SIYZDPVH.js +613 -0
  249. package/dist/chunk-SIYZDPVH.js.map +1 -0
  250. package/dist/chunk-SQAAVYJG.js +12 -0
  251. package/dist/chunk-SQAAVYJG.js.map +1 -0
  252. package/dist/chunk-SXE4J43E.js +59 -0
  253. package/dist/chunk-SXE4J43E.js.map +1 -0
  254. package/dist/{chunk-EFLT7XZD.js → chunk-SYULMZGL.js} +6 -4
  255. package/dist/{chunk-EFLT7XZD.js.map → chunk-SYULMZGL.js.map} +1 -1
  256. package/dist/chunk-T4IAJJUU.js +48 -0
  257. package/dist/chunk-T4IAJJUU.js.map +1 -0
  258. package/dist/chunk-T4KS577P.js +58 -0
  259. package/dist/chunk-T4KS577P.js.map +1 -0
  260. package/dist/chunk-TFIOU6UR.js +78 -0
  261. package/dist/chunk-TFIOU6UR.js.map +1 -0
  262. package/dist/chunk-TIZGADU4.js +375 -0
  263. package/dist/chunk-TIZGADU4.js.map +1 -0
  264. package/dist/chunk-TP3MCUXS.js +1 -0
  265. package/dist/chunk-TP3MCUXS.js.map +1 -0
  266. package/dist/{chunk-JTJU56ZV.js → chunk-UOGM62JL.js} +11 -7
  267. package/dist/{chunk-JTJU56ZV.js.map → chunk-UOGM62JL.js.map} +1 -1
  268. package/dist/chunk-USRKPEQN.js +55 -0
  269. package/dist/chunk-USRKPEQN.js.map +1 -0
  270. package/dist/chunk-UTAB3XQI.js +667 -0
  271. package/dist/chunk-UTAB3XQI.js.map +1 -0
  272. package/dist/chunk-V3FFZWF3.js +182 -0
  273. package/dist/chunk-V3FFZWF3.js.map +1 -0
  274. package/dist/chunk-V4OZ7ISA.js +9 -0
  275. package/dist/chunk-V4OZ7ISA.js.map +1 -0
  276. package/dist/chunk-VZ5ZZBNX.js +139 -0
  277. package/dist/chunk-VZ5ZZBNX.js.map +1 -0
  278. package/dist/{chunk-AHLKV6KP.js → chunk-WN6AVBO4.js} +1 -1
  279. package/dist/chunk-WXR5CWSC.js +1 -0
  280. package/dist/chunk-WXR5CWSC.js.map +1 -0
  281. package/dist/chunk-X6WS3XWL.js +36 -0
  282. package/dist/chunk-X6WS3XWL.js.map +1 -0
  283. package/dist/{chunk-Q5BCNYED.js → chunk-XJRNBTIV.js} +7 -4
  284. package/dist/chunk-XQV3XNVT.js +225 -0
  285. package/dist/chunk-XQV3XNVT.js.map +1 -0
  286. package/dist/chunk-XV3DH5GC.js +58 -0
  287. package/dist/chunk-XV3DH5GC.js.map +1 -0
  288. package/dist/chunk-Y7JTHNCU.js +318 -0
  289. package/dist/chunk-Y7JTHNCU.js.map +1 -0
  290. package/dist/chunk-YWRXOPHC.js +43 -0
  291. package/dist/chunk-YWRXOPHC.js.map +1 -0
  292. package/dist/chunk-YZVFIW5D.js +27 -0
  293. package/dist/chunk-YZVFIW5D.js.map +1 -0
  294. package/dist/chunk-ZHC5CD6J.js +33 -0
  295. package/dist/chunk-ZHC5CD6J.js.map +1 -0
  296. package/dist/chunk-ZPJFXRQZ.js +23 -0
  297. package/dist/chunk-ZPJFXRQZ.js.map +1 -0
  298. package/dist/chunk-ZPXOBQDS.js +57 -0
  299. package/dist/chunk-ZPXOBQDS.js.map +1 -0
  300. package/dist/chunk-ZUFS6R7L.js +155 -0
  301. package/dist/chunk-ZUFS6R7L.js.map +1 -0
  302. package/dist/chunk-ZXLCTQUX.js +62 -0
  303. package/dist/chunk-ZXLCTQUX.js.map +1 -0
  304. package/dist/chunk-ZYXMWEL4.js +59 -0
  305. package/dist/chunk-ZYXMWEL4.js.map +1 -0
  306. package/dist/completion/controls.js +11 -0
  307. package/dist/completion/controls.js.map +1 -0
  308. package/dist/completion/documents.js +9 -0
  309. package/dist/completion/documents.js.map +1 -0
  310. package/dist/completion/generate-completion.js +23 -0
  311. package/dist/completion/generate-completion.js.map +1 -0
  312. package/dist/completion/index.js +23 -12
  313. package/dist/completion/json.js +7 -0
  314. package/dist/completion/json.js.map +1 -0
  315. package/dist/completion/message-schema.js +18 -0
  316. package/dist/completion/message-schema.js.map +1 -0
  317. package/dist/completion/provider-output-error.js +12 -0
  318. package/dist/completion/provider-output-error.js.map +1 -0
  319. package/dist/completion/stream-accumulator.js +10 -0
  320. package/dist/completion/stream-accumulator.js.map +1 -0
  321. package/dist/completion/types.js +28 -0
  322. package/dist/completion/types.js.map +1 -0
  323. package/dist/documents/chunk-text.js +7 -0
  324. package/dist/documents/chunk-text.js.map +1 -0
  325. package/dist/documents/index.js +5 -2
  326. package/dist/documents/text-document.js +8 -0
  327. package/dist/documents/text-document.js.map +1 -0
  328. package/dist/embeddings/distance.js +17 -0
  329. package/dist/embeddings/distance.js.map +1 -0
  330. package/dist/embeddings/embed.js +18 -0
  331. package/dist/embeddings/embed.js.map +1 -0
  332. package/dist/embeddings/index.js +11 -6
  333. package/dist/embeddings/types.js +2 -0
  334. package/dist/embeddings/types.js.map +1 -0
  335. package/dist/evals/advanced-metrics.js +46 -0
  336. package/dist/evals/advanced-metrics.js.map +1 -0
  337. package/dist/evals/agent-target.js +10 -0
  338. package/dist/evals/agent-target.js.map +1 -0
  339. package/dist/evals/cli.js +40 -0
  340. package/dist/evals/cli.js.map +1 -0
  341. package/dist/evals/execution.js +15 -0
  342. package/dist/evals/execution.js.map +1 -0
  343. package/dist/evals/format.js +13 -0
  344. package/dist/evals/format.js.map +1 -0
  345. package/dist/evals/index.d.ts +4 -4
  346. package/dist/evals/index.js +87 -2660
  347. package/dist/evals/index.js.map +1 -1
  348. package/dist/evals/judge.js +27 -0
  349. package/dist/evals/judge.js.map +1 -0
  350. package/dist/evals/metric.js +7 -0
  351. package/dist/evals/metric.js.map +1 -0
  352. package/dist/evals/metrics.js +53 -0
  353. package/dist/evals/metrics.js.map +1 -0
  354. package/dist/evals/outcome.js +7 -0
  355. package/dist/evals/outcome.js.map +1 -0
  356. package/dist/evals/reporting.js +11 -0
  357. package/dist/evals/reporting.js.map +1 -0
  358. package/dist/evals/runner.js +29 -0
  359. package/dist/evals/runner.js.map +1 -0
  360. package/dist/evals/selectors.js +18 -0
  361. package/dist/evals/selectors.js.map +1 -0
  362. package/dist/evals/suite.js +11 -0
  363. package/dist/evals/suite.js.map +1 -0
  364. package/dist/evals/types.js +1 -0
  365. package/dist/evals/types.js.map +1 -0
  366. package/dist/extractor/extractor.js +23 -0
  367. package/dist/extractor/extractor.js.map +1 -0
  368. package/dist/extractor/index.js +16 -7
  369. package/dist/guardrails/actions.js +13 -0
  370. package/dist/guardrails/actions.js.map +1 -0
  371. package/dist/guardrails/index.d.ts +3 -4
  372. package/dist/guardrails/index.js +15 -7
  373. package/dist/guardrails/message.js +9 -0
  374. package/dist/guardrails/message.js.map +1 -0
  375. package/dist/guardrails/policy.js +17 -0
  376. package/dist/guardrails/policy.js.map +1 -0
  377. package/dist/guardrails/runtime.js +11 -0
  378. package/dist/guardrails/runtime.js.map +1 -0
  379. package/dist/guardrails/text.js +9 -0
  380. package/dist/guardrails/text.js.map +1 -0
  381. package/dist/guardrails/types.js +1 -0
  382. package/dist/guardrails/types.js.map +1 -0
  383. package/dist/hooks/control.js +17 -0
  384. package/dist/hooks/control.js.map +1 -0
  385. package/dist/hooks/index.js +19 -0
  386. package/dist/hooks/index.js.map +1 -0
  387. package/dist/hooks/types.js +2 -0
  388. package/dist/hooks/types.js.map +1 -0
  389. package/dist/image-generation/generate-image.js +11 -0
  390. package/dist/image-generation/generate-image.js.map +1 -0
  391. package/dist/image-generation/index.js +7 -4
  392. package/dist/image-generation/types.js +2 -0
  393. package/dist/image-generation/types.js.map +1 -0
  394. package/dist/index.d.ts +5 -7
  395. package/dist/index.js +163 -57
  396. package/dist/internal/abort.js +13 -0
  397. package/dist/internal/abort.js.map +1 -0
  398. package/dist/internal/agent-runtime/agent-run.js +81 -0
  399. package/dist/internal/agent-runtime/agent-run.js.map +1 -0
  400. package/dist/internal/agent-runtime/approval-request.js +1 -0
  401. package/dist/internal/agent-runtime/approval-request.js.map +1 -0
  402. package/dist/internal/agent-runtime/approval-requirement.js +9 -0
  403. package/dist/internal/agent-runtime/approval-requirement.js.map +1 -0
  404. package/dist/internal/agent-runtime/continuation-state.js +26 -0
  405. package/dist/internal/agent-runtime/continuation-state.js.map +1 -0
  406. package/dist/internal/agent-runtime/interaction-suspension.js +25 -0
  407. package/dist/internal/agent-runtime/interaction-suspension.js.map +1 -0
  408. package/dist/internal/agent-runtime/memory-scope.js +8 -0
  409. package/dist/internal/agent-runtime/memory-scope.js.map +1 -0
  410. package/dist/internal/agent-runtime/memory.js +24 -0
  411. package/dist/internal/agent-runtime/memory.js.map +1 -0
  412. package/dist/internal/agent-runtime/prepared-tool-call.js +19 -0
  413. package/dist/internal/agent-runtime/prepared-tool-call.js.map +1 -0
  414. package/dist/internal/agent-runtime/retrieval.js +35 -0
  415. package/dist/internal/agent-runtime/retrieval.js.map +1 -0
  416. package/dist/internal/agent-runtime/run-options.js +9 -0
  417. package/dist/internal/agent-runtime/run-options.js.map +1 -0
  418. package/dist/internal/agent-runtime/run-validation.js +9 -0
  419. package/dist/internal/agent-runtime/run-validation.js.map +1 -0
  420. package/dist/internal/agent-runtime/stream-events.js +11 -0
  421. package/dist/internal/agent-runtime/stream-events.js.map +1 -0
  422. package/dist/internal/agent-runtime/structured-output.js +13 -0
  423. package/dist/internal/agent-runtime/structured-output.js.map +1 -0
  424. package/dist/internal/agent-runtime/tool-execution.js +55 -0
  425. package/dist/internal/agent-runtime/tool-execution.js.map +1 -0
  426. package/dist/internal/agent.d.ts +5 -5
  427. package/dist/internal/agent.js +93 -57
  428. package/dist/internal/agent.js.map +1 -1
  429. package/dist/internal/async-queue.js +7 -0
  430. package/dist/internal/async-queue.js.map +1 -0
  431. package/dist/internal/completion-request.js +11 -0
  432. package/dist/internal/completion-request.js.map +1 -0
  433. package/dist/internal/concurrency.js +7 -0
  434. package/dist/internal/concurrency.js.map +1 -0
  435. package/dist/internal/json-object.js +8 -0
  436. package/dist/internal/json-object.js.map +1 -0
  437. package/dist/internal/rag-text.js +7 -0
  438. package/dist/internal/rag-text.js.map +1 -0
  439. package/dist/internal/record.js +7 -0
  440. package/dist/internal/record.js.map +1 -0
  441. package/dist/internal/team-runtime/coordination.js +12 -0
  442. package/dist/internal/team-runtime/coordination.js.map +1 -0
  443. package/dist/internal/team-runtime/member.js +26 -0
  444. package/dist/internal/team-runtime/member.js.map +1 -0
  445. package/dist/internal/team-runtime/policy.js +7 -0
  446. package/dist/internal/team-runtime/policy.js.map +1 -0
  447. package/dist/internal/team-runtime/run.js +95 -0
  448. package/dist/internal/team-runtime/run.js.map +1 -0
  449. package/dist/internal/team-runtime/stream.js +9 -0
  450. package/dist/internal/team-runtime/stream.js.map +1 -0
  451. package/dist/internal/team-runtime/tools.js +17 -0
  452. package/dist/internal/team-runtime/tools.js.map +1 -0
  453. package/dist/internal/type-utils.js +1 -0
  454. package/dist/internal/type-utils.js.map +1 -0
  455. package/dist/internal/vector-search-options.js +9 -0
  456. package/dist/internal/vector-search-options.js.map +1 -0
  457. package/dist/mcp/index.js +3 -1
  458. package/dist/mcp/tool.js +7 -0
  459. package/dist/mcp/tool.js.map +1 -0
  460. package/dist/mcp/types.js +2 -0
  461. package/dist/mcp/types.js.map +1 -0
  462. package/dist/memory/assert.js +11 -0
  463. package/dist/memory/assert.js.map +1 -0
  464. package/dist/memory/compaction.js +26 -0
  465. package/dist/memory/compaction.js.map +1 -0
  466. package/dist/memory/errors.js +9 -0
  467. package/dist/memory/errors.js.map +1 -0
  468. package/dist/memory/index.js +23 -10
  469. package/dist/memory/options.js +10 -0
  470. package/dist/memory/options.js.map +1 -0
  471. package/dist/memory/scope-key.js +7 -0
  472. package/dist/memory/scope-key.js.map +1 -0
  473. package/dist/memory/types.js +2 -0
  474. package/dist/memory/types.js.map +1 -0
  475. package/dist/{types-CRda8x7p.d.ts → middleware-CWjnMbiH.d.ts} +64 -5
  476. package/dist/model-call-options.js +1 -0
  477. package/dist/model-call-options.js.map +1 -0
  478. package/dist/model-listing/errors.js +7 -0
  479. package/dist/model-listing/errors.js.map +1 -0
  480. package/dist/model-listing/index.js +4 -13
  481. package/dist/model-listing/index.js.map +1 -1
  482. package/dist/model-listing/types.js +2 -0
  483. package/dist/model-listing/types.js.map +1 -0
  484. package/dist/observability/group.js +30 -0
  485. package/dist/observability/group.js.map +1 -0
  486. package/dist/observability/index.d.ts +4 -6
  487. package/dist/observability/index.js +16 -8
  488. package/dist/observability/snapshot.js +7 -0
  489. package/dist/observability/snapshot.js.map +1 -0
  490. package/dist/observability/types.js +1 -0
  491. package/dist/observability/types.js.map +1 -0
  492. package/dist/pipeline/errors.js +9 -0
  493. package/dist/pipeline/errors.js.map +1 -0
  494. package/dist/pipeline/graph.js +21 -0
  495. package/dist/pipeline/graph.js.map +1 -0
  496. package/dist/pipeline/index.d.ts +4 -6
  497. package/dist/pipeline/index.js +27 -805
  498. package/dist/pipeline/index.js.map +1 -1
  499. package/dist/pipeline/observability.js +15 -0
  500. package/dist/pipeline/observability.js.map +1 -0
  501. package/dist/pipeline/pipeline.js +30 -0
  502. package/dist/pipeline/pipeline.js.map +1 -0
  503. package/dist/pipeline/runtime.js +17 -0
  504. package/dist/pipeline/runtime.js.map +1 -0
  505. package/dist/pipeline/types.js +1 -0
  506. package/dist/pipeline/types.js.map +1 -0
  507. package/dist/retry.js +20 -0
  508. package/dist/retry.js.map +1 -0
  509. package/dist/schema/index.js +1 -0
  510. package/dist/schema/index.js.map +1 -0
  511. package/dist/schema/zod-schema.js +7 -0
  512. package/dist/schema/zod-schema.js.map +1 -0
  513. package/dist/skills/index.js +41 -12
  514. package/dist/skills/instructions.js +7 -0
  515. package/dist/skills/instructions.js.map +1 -0
  516. package/dist/skills/load.js +39 -0
  517. package/dist/skills/load.js.map +1 -0
  518. package/dist/skills/local.js +9 -0
  519. package/dist/skills/local.js.map +1 -0
  520. package/dist/skills/tools.js +37 -0
  521. package/dist/skills/tools.js.map +1 -0
  522. package/dist/skills/types.js +7 -0
  523. package/dist/skills/types.js.map +1 -0
  524. package/dist/speech-generation/generate-speech.js +11 -0
  525. package/dist/speech-generation/generate-speech.js.map +1 -0
  526. package/dist/speech-generation/index.js +7 -4
  527. package/dist/speech-generation/types.js +2 -0
  528. package/dist/speech-generation/types.js.map +1 -0
  529. package/dist/streaming/index.js +4 -37
  530. package/dist/streaming/index.js.map +1 -1
  531. package/dist/streaming/readable-stream.js +8 -0
  532. package/dist/streaming/readable-stream.js.map +1 -0
  533. package/dist/{text-CmjXxakS.d.ts → text-GbW4WYMg.d.ts} +1 -1
  534. package/dist/tool/create-tool.js +14 -0
  535. package/dist/tool/create-tool.js.map +1 -0
  536. package/dist/tool/dynamic-tools.js +35 -0
  537. package/dist/tool/dynamic-tools.js.map +1 -0
  538. package/dist/tool/errors.js +11 -0
  539. package/dist/tool/errors.js.map +1 -0
  540. package/dist/tool/index.d.ts +3 -2
  541. package/dist/tool/index.js +41 -15
  542. package/dist/tool/middleware.js +7 -0
  543. package/dist/tool/middleware.js.map +1 -0
  544. package/dist/tool/question-tool.js +17 -0
  545. package/dist/tool/question-tool.js.map +1 -0
  546. package/dist/tool/skill-tool-marker.js +9 -0
  547. package/dist/tool/skill-tool-marker.js.map +1 -0
  548. package/dist/tool/think-tool.js +15 -0
  549. package/dist/tool/think-tool.js.map +1 -0
  550. package/dist/tool/tool.js +17 -0
  551. package/dist/tool/tool.js.map +1 -0
  552. package/dist/transcription/index.js +7 -4
  553. package/dist/transcription/transcribe.js +11 -0
  554. package/dist/transcription/transcribe.js.map +1 -0
  555. package/dist/transcription/types.js +2 -0
  556. package/dist/transcription/types.js.map +1 -0
  557. package/dist/{types-h0EL6Xn0.d.ts → types-Bqw0AuFl.d.ts} +6 -2
  558. package/dist/vector-store/filter.js +9 -0
  559. package/dist/vector-store/filter.js.map +1 -0
  560. package/dist/vector-store/index.js +31 -11
  561. package/dist/vector-store/ingest.js +19 -0
  562. package/dist/vector-store/ingest.js.map +1 -0
  563. package/dist/vector-store/lsh.js +7 -0
  564. package/dist/vector-store/lsh.js.map +1 -0
  565. package/dist/vector-store/retrieve.js +15 -0
  566. package/dist/vector-store/retrieve.js.map +1 -0
  567. package/dist/vector-store/types.js +1 -0
  568. package/dist/vector-store/types.js.map +1 -0
  569. package/package.json +2 -2
  570. package/dist/chunk-2QZJTG2E.js.map +0 -1
  571. package/dist/chunk-3RWESPUG.js.map +0 -1
  572. package/dist/chunk-4UQALF5Y.js.map +0 -1
  573. package/dist/chunk-AZB6N7P4.js +0 -320
  574. package/dist/chunk-AZB6N7P4.js.map +0 -1
  575. package/dist/chunk-JLJMVRRE.js.map +0 -1
  576. package/dist/chunk-K5L7R7XM.js.map +0 -1
  577. package/dist/chunk-OI3LSMJG.js +0 -1545
  578. package/dist/chunk-OI3LSMJG.js.map +0 -1
  579. package/dist/chunk-QGX73TSQ.js.map +0 -1
  580. package/dist/chunk-XC3LVC4K.js +0 -753
  581. package/dist/chunk-XC3LVC4K.js.map +0 -1
  582. package/dist/chunk-XEVOC433.js.map +0 -1
  583. package/dist/chunk-XSV5C4R5.js +0 -400
  584. package/dist/chunk-XSV5C4R5.js.map +0 -1
  585. package/dist/chunk-XU54PLSD.js +0 -4786
  586. package/dist/chunk-XU54PLSD.js.map +0 -1
  587. package/dist/middleware-mY_lpjDp.d.ts +0 -59
  588. package/dist/type-utils-CtHVDRn_.d.ts +0 -6
  589. /package/dist/{chunk-YK4WAAS4.js.map → chunk-2NLINXRF.js.map} +0 -0
  590. /package/dist/{chunk-SPD4XVR7.js.map → chunk-2XSMGVBG.js.map} +0 -0
  591. /package/dist/{chunk-3XQGVDU5.js.map → chunk-4C7AXYOM.js.map} +0 -0
  592. /package/dist/{chunk-IZNOP6JG.js.map → chunk-4FIVU53H.js.map} +0 -0
  593. /package/dist/{chunk-7JLAIN6E.js.map → chunk-4ONUNWGC.js.map} +0 -0
  594. /package/dist/{chunk-KSKST3KP.js.map → chunk-H3H74RWJ.js.map} +0 -0
  595. /package/dist/{chunk-OJBFDBLG.js.map → chunk-LBYJPMHC.js.map} +0 -0
  596. /package/dist/{chunk-J6LVLV6P.js.map → chunk-PLDJCCVL.js.map} +0 -0
  597. /package/dist/{chunk-AHLKV6KP.js.map → chunk-WN6AVBO4.js.map} +0 -0
  598. /package/dist/{chunk-Q5BCNYED.js.map → chunk-XJRNBTIV.js.map} +0 -0
@@ -1,1545 +0,0 @@
1
- import {
2
- assertJsonObject
3
- } from "./chunk-7JLAIN6E.js";
4
- import {
5
- parseMessage,
6
- parseMessages,
7
- toProviderJsonSchema
8
- } from "./chunk-QGX73TSQ.js";
9
- import {
10
- isJsonValue
11
- } from "./chunk-3XQGVDU5.js";
12
- import {
13
- abortError,
14
- completionProviderOutputErrorUsage,
15
- resolveRetryOptions,
16
- retryDelayMs,
17
- retryOptionsForFailure,
18
- throwIfAborted,
19
- waitForRetry
20
- } from "./chunk-3RWESPUG.js";
21
-
22
- // src/completion/types.ts
23
- function reasoningDisplayText(reasoning) {
24
- const details = "type" in reasoning ? reasoning.details : reasoning;
25
- if (details === void 0) {
26
- return "type" in reasoning ? reasoning.text : "";
27
- }
28
- return details.flatMap((item) => {
29
- if (item.type === "text" || item.type === "summary") {
30
- return [item.text];
31
- }
32
- return [];
33
- }).join("");
34
- }
35
- function isProviderTool(value) {
36
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
37
- return false;
38
- }
39
- const candidate = value;
40
- return candidate.kind === "provider" && typeof candidate.provider === "string" && candidate.provider.trim().length > 0 && typeof candidate.name === "string" && candidate.name.trim().length > 0 && (candidate.configuration === void 0 || typeof candidate.configuration === "object" && candidate.configuration !== null && !Array.isArray(candidate.configuration) && isJsonValue(candidate.configuration));
41
- }
42
- function calculateContextUsage(usage, model) {
43
- if (model === void 0 || !Number.isFinite(usage.inputTokens) || usage.inputTokens <= 0 || !Number.isFinite(model.context.contextWindow) || model.context.contextWindow <= 0) {
44
- return void 0;
45
- }
46
- const usedTokens = Math.max(0, usage.inputTokens);
47
- const remainingTokens = Math.max(0, model.context.contextWindow - usedTokens);
48
- const usedPercent = Math.min(100, usedTokens / model.context.contextWindow * 100);
49
- return {
50
- model,
51
- usedTokens,
52
- remainingTokens,
53
- usedPercent,
54
- remainingPercent: 100 - usedPercent
55
- };
56
- }
57
- function withContextUsage(response, model) {
58
- const contextUsage = calculateContextUsage(response.usage, model);
59
- return contextUsage === void 0 ? response : { ...response, contextUsage };
60
- }
61
- function resolveModelContextLimits(modelId, catalog, override) {
62
- return override ?? catalog[modelId];
63
- }
64
- var Usage = {
65
- empty() {
66
- return {
67
- inputTokens: 0,
68
- outputTokens: 0,
69
- totalTokens: 0,
70
- cachedInputTokens: 0,
71
- cacheCreationInputTokens: 0
72
- };
73
- },
74
- add(left, right) {
75
- const result = {
76
- inputTokens: left.inputTokens + right.inputTokens,
77
- outputTokens: left.outputTokens + right.outputTokens,
78
- totalTokens: left.totalTokens + right.totalTokens,
79
- cachedInputTokens: left.cachedInputTokens + right.cachedInputTokens,
80
- cacheCreationInputTokens: left.cacheCreationInputTokens + right.cacheCreationInputTokens
81
- };
82
- const details = addUsageDetails(left, right);
83
- if (details !== void 0) {
84
- result.details = details;
85
- }
86
- return result;
87
- },
88
- isEmpty(usage) {
89
- return isEmptyUsage(usage) && (usage.details === void 0 || Object.values(usage.details).every((value) => value === 0));
90
- }
91
- };
92
- function addUsageDetails(left, right) {
93
- if (isEmptyUsage(left) && left.details === void 0) {
94
- return right.details === void 0 ? void 0 : { ...right.details };
95
- }
96
- if (isEmptyUsage(right) && right.details === void 0) {
97
- return left.details === void 0 ? void 0 : { ...left.details };
98
- }
99
- if (left.details === void 0 || right.details === void 0) {
100
- return void 0;
101
- }
102
- const details = { ...left.details };
103
- for (const [key, value] of Object.entries(right.details)) {
104
- details[key] = (details[key] ?? 0) + value;
105
- }
106
- return details;
107
- }
108
- function isEmptyUsage(usage) {
109
- return usage.inputTokens === 0 && usage.outputTokens === 0 && usage.totalTokens === 0 && usage.cachedInputTokens === 0 && usage.cacheCreationInputTokens === 0;
110
- }
111
- function getAssistantGenerationMetadata(message) {
112
- if (message.role !== "assistant" || !isJsonObjectValue(message.metadata)) {
113
- return void 0;
114
- }
115
- const frameworkMetadata = message.metadata.anvia;
116
- if (!isJsonObjectValue(frameworkMetadata)) {
117
- return void 0;
118
- }
119
- const generation = frameworkMetadata.generation;
120
- if (!isJsonObjectValue(generation) || typeof generation.provider !== "string" || typeof generation.modelId !== "string" || !isUsageValue(generation.usage)) {
121
- return void 0;
122
- }
123
- let usage = { ...generation.usage };
124
- if (generation.usage.details !== void 0) {
125
- usage = { ...usage, details: { ...generation.usage.details } };
126
- }
127
- const metadata = {
128
- provider: generation.provider,
129
- modelId: generation.modelId,
130
- usage
131
- };
132
- if (isCompletionFinishReason(generation.finishReason)) {
133
- metadata.finishReason = generation.finishReason;
134
- }
135
- if (typeof generation.providerFinishReason === "string") {
136
- metadata.providerFinishReason = generation.providerFinishReason;
137
- }
138
- if (isContextUsageValue(generation.contextUsage)) {
139
- metadata.contextUsage = {
140
- ...generation.contextUsage,
141
- model: {
142
- ...generation.contextUsage.model,
143
- context: { ...generation.contextUsage.model.context }
144
- }
145
- };
146
- }
147
- if (isCompletionSourceArray(generation.sources)) {
148
- metadata.sources = generation.sources.map((source) => ({ ...source }));
149
- }
150
- if (isProviderToolCallArray(generation.providerToolCalls)) {
151
- metadata.providerToolCalls = generation.providerToolCalls.map((toolCall) => {
152
- let copy = { ...toolCall };
153
- if (toolCall.details !== void 0) {
154
- copy = { ...copy, details: { ...toolCall.details } };
155
- }
156
- return copy;
157
- });
158
- }
159
- return metadata;
160
- }
161
- function isJsonObjectValue(value) {
162
- return typeof value === "object" && value !== null && !Array.isArray(value);
163
- }
164
- function isContextUsageValue(value) {
165
- if (!isJsonObjectValue(value) || !isJsonObjectValue(value.model)) {
166
- return false;
167
- }
168
- const context = value.model.context;
169
- if (typeof value.model.modelId === "string" && isJsonObjectValue(context) && isPositiveFiniteNumber(context.contextWindow) && isOptionalPositiveFiniteNumber(context.maxInputTokens) && isOptionalPositiveFiniteNumber(context.maxOutputTokens) && isNonnegativeFiniteNumber(value.usedTokens) && isNonnegativeFiniteNumber(value.remainingTokens) && isPercentage(value.usedPercent) && isPercentage(value.remainingPercent)) {
170
- const contextWindow = context.contextWindow;
171
- const remainingTokens = Math.max(0, contextWindow - value.usedTokens);
172
- const usedPercent = Math.min(100, value.usedTokens / contextWindow * 100);
173
- const remainingPercent = remainingTokens / contextWindow * 100;
174
- return value.remainingTokens === remainingTokens && approximatelyEqual(value.usedPercent, usedPercent) && approximatelyEqual(value.remainingPercent, remainingPercent);
175
- }
176
- return false;
177
- }
178
- function approximatelyEqual(left, right) {
179
- const scale = Math.max(1, Math.abs(left), Math.abs(right));
180
- return Math.abs(left - right) <= Number.EPSILON * scale * 8;
181
- }
182
- function isPositiveFiniteNumber(value) {
183
- return isNonnegativeFiniteNumber(value) && value > 0;
184
- }
185
- function isOptionalPositiveFiniteNumber(value) {
186
- return value === void 0 || isPositiveFiniteNumber(value);
187
- }
188
- function isPercentage(value) {
189
- return isNonnegativeFiniteNumber(value) && value <= 100;
190
- }
191
- function isUsageValue(value) {
192
- if (!isJsonObjectValue(value)) {
193
- return false;
194
- }
195
- return isNonnegativeFiniteNumber(value.inputTokens) && isNonnegativeFiniteNumber(value.outputTokens) && isNonnegativeFiniteNumber(value.totalTokens) && isNonnegativeFiniteNumber(value.cachedInputTokens) && isNonnegativeFiniteNumber(value.cacheCreationInputTokens) && isUsageDetailsValue(value.details);
196
- }
197
- function isNonnegativeFiniteNumber(value) {
198
- return typeof value === "number" && Number.isFinite(value) && value >= 0;
199
- }
200
- function isUsageDetailsValue(value) {
201
- if (value === void 0) {
202
- return true;
203
- }
204
- if (!isJsonObjectValue(value)) {
205
- return false;
206
- }
207
- let total;
208
- let bucketSum = 0;
209
- for (const [key, detail] of Object.entries(value)) {
210
- if (detail === void 0 || !isNonnegativeFiniteNumber(detail)) {
211
- return false;
212
- }
213
- if (key === "total") {
214
- total = detail;
215
- } else {
216
- bucketSum += detail;
217
- }
218
- }
219
- return total !== void 0 && total === bucketSum;
220
- }
221
- function isCompletionSourceArray(value) {
222
- return Array.isArray(value) && value.every(
223
- (source) => isJsonObjectValue(source) && source.type === "url" && typeof source.url === "string" && (source.title === void 0 || typeof source.title === "string") && (source.id === void 0 || typeof source.id === "string") && (source.startIndex === void 0 || typeof source.startIndex === "number") && (source.endIndex === void 0 || typeof source.endIndex === "number")
224
- );
225
- }
226
- function isProviderToolCallArray(value) {
227
- return Array.isArray(value) && value.every(
228
- (toolCall) => isJsonObjectValue(toolCall) && typeof toolCall.id === "string" && typeof toolCall.name === "string" && (toolCall.status === void 0 || typeof toolCall.status === "string") && (toolCall.details === void 0 || isJsonObjectValue(toolCall.details))
229
- );
230
- }
231
- function isCompletionFinishReason(value) {
232
- return value === "stop" || value === "length" || value === "content-filter" || value === "tool-calls" || value === "other";
233
- }
234
- var CompletionCapabilityError = class extends Error {
235
- constructor(message) {
236
- super(message);
237
- this.name = "CompletionCapabilityError";
238
- }
239
- };
240
- function assertCompletionRequestSupported(model, request, options = {}) {
241
- const modelLabel = `${model.provider}:${model.modelId}`;
242
- const capabilities = model.capabilities;
243
- assertCompletionControlsSupported(model, request.controls);
244
- if (options.streaming === true && !capabilities.streaming) {
245
- throw new CompletionCapabilityError(`${modelLabel} does not support streaming completions.`);
246
- }
247
- if (request.tools.length > 0 && !capabilities.tools) {
248
- throw new CompletionCapabilityError(`${modelLabel} does not support tool definitions.`);
249
- }
250
- if ((request.providerTools?.length ?? 0) > 0 && capabilities.providerTools !== true) {
251
- throw new CompletionCapabilityError(`${modelLabel} does not support provider-executed tools.`);
252
- }
253
- if (request.toolChoice !== void 0 && !capabilities.toolChoice) {
254
- throw new CompletionCapabilityError(`${modelLabel} does not support tool choice.`);
255
- }
256
- if (request.outputSchema !== void 0 && !capabilities.outputSchema) {
257
- throw new CompletionCapabilityError(`${modelLabel} does not support output schemas.`);
258
- }
259
- if (!capabilities.imageInput && requestHasImageInput(request)) {
260
- throw new CompletionCapabilityError(`${modelLabel} does not support image input.`);
261
- }
262
- if (!capabilities.documentInput && requestHasFileDocumentInput(request)) {
263
- throw new CompletionCapabilityError(`${modelLabel} does not support document file input.`);
264
- }
265
- }
266
- function assertCompletionControlsSupported(model, controls) {
267
- const modelLabel = `${model.provider}:${model.modelId}`;
268
- for (const [controlId, value] of Object.entries(controls ?? {})) {
269
- if (value === void 0) continue;
270
- const modelControls = model.controls;
271
- const control = modelControls !== void 0 && Object.hasOwn(modelControls, controlId) ? modelControls[controlId] : void 0;
272
- if (control === void 0) {
273
- throw new CompletionCapabilityError(
274
- `${modelLabel} does not support completion control "${controlId}".`
275
- );
276
- }
277
- if (!control.options.includes(value)) {
278
- throw new CompletionCapabilityError(
279
- `${modelLabel} completion control "${controlId}" does not support value "${value}".`
280
- );
281
- }
282
- }
283
- }
284
- function textFromAssistantContent(content) {
285
- return content.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n");
286
- }
287
- function requestHasImageInput(request) {
288
- return request.chatHistory.some(
289
- (message) => message.role === "system" || typeof message.content === "string" ? false : message.content.some((content) => content.type === "image")
290
- );
291
- }
292
- function requestHasFileDocumentInput(request) {
293
- return request.chatHistory.some(
294
- (message) => message.role === "user" && typeof message.content !== "string" ? message.content.some((content) => content.type === "file" && content.data.type !== "text") : false
295
- );
296
- }
297
-
298
- // src/completion/provider-output-error.ts
299
- var COMPLETION_PROVIDER_OUTPUT_ERROR_CODE = "ANVIA_COMPLETION_PROVIDER_OUTPUT";
300
- var PROVIDER_OUTPUT_ERROR_KINDS = /* @__PURE__ */ new Set([
301
- "malformed-tool-arguments",
302
- "invalid-tool-arguments",
303
- "invalid-stream-event",
304
- "invalid-response",
305
- "incomplete-stream",
306
- "incomplete-tool-call",
307
- "invalid-tool-call",
308
- "truncated-tool-call",
309
- "filtered-tool-call"
310
- ]);
311
- var CompletionProviderOutputError = class extends Error {
312
- code = COMPLETION_PROVIDER_OUTPUT_ERROR_CODE;
313
- kind;
314
- toolCallId;
315
- finishReason;
316
- usage;
317
- constructor(options) {
318
- assertProviderOutputErrorOptions(options);
319
- super(providerOutputErrorMessage(options.kind, options.toolCallId));
320
- this.name = "CompletionProviderOutputError";
321
- this.kind = options.kind;
322
- this.toolCallId = options.toolCallId;
323
- this.finishReason = options.finishReason;
324
- this.usage = options.usage === void 0 ? void 0 : copyUsage(options.usage);
325
- }
326
- };
327
- function assertCompletionResponseIntegrity(options) {
328
- const { response } = options;
329
- const toolCalls = response.choice.filter(
330
- (content) => content.type === "tool-call"
331
- );
332
- if (toolCalls.length > 0) {
333
- if (response.finishReason !== void 0 && !isCompletionFinishReason2(response.finishReason)) {
334
- throw new CompletionProviderOutputError({
335
- kind: "invalid-tool-call",
336
- usage: response.usage
337
- });
338
- }
339
- if (response.finishReason === "length") {
340
- throw new CompletionProviderOutputError({
341
- kind: "truncated-tool-call",
342
- finishReason: response.finishReason,
343
- usage: response.usage
344
- });
345
- }
346
- if (response.finishReason === "content-filter") {
347
- throw new CompletionProviderOutputError({
348
- kind: "filtered-tool-call",
349
- finishReason: response.finishReason,
350
- usage: response.usage
351
- });
352
- }
353
- if (response.finishReason === "other") {
354
- throw new CompletionProviderOutputError({
355
- kind: "invalid-tool-call",
356
- finishReason: response.finishReason,
357
- usage: response.usage
358
- });
359
- }
360
- } else if (response.finishReason === "tool-calls") {
361
- throw new CompletionProviderOutputError({
362
- kind: "invalid-tool-call",
363
- finishReason: response.finishReason,
364
- usage: response.usage
365
- });
366
- }
367
- const toolCallIds = /* @__PURE__ */ new Set();
368
- const callIds = /* @__PURE__ */ new Set();
369
- for (const toolCall of toolCalls) {
370
- if (!isNonblankString(toolCall.toolCallId) || !isNonblankString(toolCall.toolName)) {
371
- throw invalidToolCall(toolCall.toolCallId, response.usage);
372
- }
373
- if (toolCall.callId !== void 0 && !isNonblankString(toolCall.callId)) {
374
- throw invalidToolCall(toolCall.toolCallId, response.usage);
375
- }
376
- if (toolCallIds.has(toolCall.toolCallId)) {
377
- throw invalidToolCall(toolCall.toolCallId, response.usage);
378
- }
379
- toolCallIds.add(toolCall.toolCallId);
380
- if (toolCall.callId !== void 0) {
381
- if (callIds.has(toolCall.callId)) {
382
- throw invalidToolCall(toolCall.toolCallId, response.usage);
383
- }
384
- callIds.add(toolCall.callId);
385
- }
386
- if (!isJsonValue(toolCall.input)) {
387
- throw new CompletionProviderOutputError({
388
- kind: "invalid-tool-arguments",
389
- toolCallId: toolCall.toolCallId,
390
- usage: response.usage
391
- });
392
- }
393
- }
394
- }
395
- function invalidToolCall(toolCallId, usage) {
396
- return new CompletionProviderOutputError({
397
- kind: "invalid-tool-call",
398
- toolCallId: isNonblankString(toolCallId) ? toolCallId : void 0,
399
- usage
400
- });
401
- }
402
- function assertProviderOutputErrorOptions(options) {
403
- if (typeof options !== "object" || options === null) {
404
- throw new TypeError("CompletionProviderOutputError options must be an object.");
405
- }
406
- if (!PROVIDER_OUTPUT_ERROR_KINDS.has(options.kind)) {
407
- throw new TypeError("CompletionProviderOutputError kind is invalid.");
408
- }
409
- if (options.toolCallId !== void 0 && !isNonblankString(options.toolCallId)) {
410
- throw new TypeError("CompletionProviderOutputError toolCallId must be a non-empty string.");
411
- }
412
- if (options.finishReason !== void 0 && !isCompletionFinishReason2(options.finishReason)) {
413
- throw new TypeError("CompletionProviderOutputError finishReason is invalid.");
414
- }
415
- if (options.kind === "truncated-tool-call" && options.finishReason !== "length") {
416
- throw new TypeError('CompletionProviderOutputError truncated-tool-call requires "length".');
417
- }
418
- if (options.kind === "filtered-tool-call" && options.finishReason !== "content-filter") {
419
- throw new TypeError(
420
- 'CompletionProviderOutputError filtered-tool-call requires "content-filter".'
421
- );
422
- }
423
- if (options.finishReason === "length" && options.kind !== "truncated-tool-call") {
424
- throw new TypeError(
425
- 'CompletionProviderOutputError finishReason "length" requires truncated-tool-call.'
426
- );
427
- }
428
- if (options.finishReason === "content-filter" && options.kind !== "filtered-tool-call") {
429
- throw new TypeError(
430
- 'CompletionProviderOutputError finishReason "content-filter" requires filtered-tool-call.'
431
- );
432
- }
433
- if (options.usage !== void 0) {
434
- assertUsage(options.usage);
435
- }
436
- }
437
- function providerOutputErrorMessage(kind, toolCallId) {
438
- const toolCall = toolCallId === void 0 ? "tool call" : `tool call ${JSON.stringify(displayId(toolCallId))}`;
439
- if (kind === "malformed-tool-arguments") {
440
- return `Completion provider returned ${toolCall} with malformed JSON arguments.`;
441
- }
442
- if (kind === "invalid-tool-arguments") {
443
- return `Completion provider returned ${toolCall} with arguments that are not a JSON value.`;
444
- }
445
- if (kind === "invalid-stream-event") {
446
- return "Completion provider returned an invalid stream event.";
447
- }
448
- if (kind === "invalid-response") {
449
- return "Completion provider returned a response that cannot be consumed safely.";
450
- }
451
- if (kind === "incomplete-tool-call") {
452
- return "Completion provider stream ended before its tool call was complete.";
453
- }
454
- if (kind === "incomplete-stream") {
455
- return "Completion provider stream ended without a terminal response.";
456
- }
457
- if (kind === "truncated-tool-call") {
458
- return "Completion provider stopped at its output limit before a tool call could be consumed safely.";
459
- }
460
- if (kind === "filtered-tool-call") {
461
- return "Completion provider content filtering prevented a tool call from being consumed safely.";
462
- }
463
- return `Completion provider returned an invalid ${toolCall}.`;
464
- }
465
- function displayId(value) {
466
- let sanitized = "";
467
- for (const character of value) {
468
- const code = character.charCodeAt(0);
469
- sanitized += code <= 31 || code === 127 ? "\uFFFD" : character;
470
- }
471
- return sanitized.length <= 128 ? sanitized : `${sanitized.slice(0, 127)}\u2026`;
472
- }
473
- function isNonblankString(value) {
474
- return typeof value === "string" && value.trim().length > 0;
475
- }
476
- function isCompletionFinishReason2(value) {
477
- return value === "stop" || value === "length" || value === "content-filter" || value === "tool-calls" || value === "other";
478
- }
479
- function assertUsage(usage) {
480
- for (const value of [
481
- usage.inputTokens,
482
- usage.outputTokens,
483
- usage.totalTokens,
484
- usage.cachedInputTokens,
485
- usage.cacheCreationInputTokens
486
- ]) {
487
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
488
- throw new TypeError("CompletionProviderOutputError usage must contain finite token counts.");
489
- }
490
- }
491
- if (usage.details !== void 0) {
492
- for (const value of Object.values(usage.details)) {
493
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
494
- throw new TypeError(
495
- "CompletionProviderOutputError usage details must contain finite token counts."
496
- );
497
- }
498
- }
499
- }
500
- }
501
- function copyUsage(usage) {
502
- const copied = {
503
- inputTokens: usage.inputTokens,
504
- outputTokens: usage.outputTokens,
505
- totalTokens: usage.totalTokens,
506
- cachedInputTokens: usage.cachedInputTokens,
507
- cacheCreationInputTokens: usage.cacheCreationInputTokens
508
- };
509
- if (usage.details !== void 0) copied.details = { ...usage.details };
510
- return copied;
511
- }
512
-
513
- // src/internal/completion-request.ts
514
- function createCompletionRequest(input, options) {
515
- const configuredTools = options.tools ?? [];
516
- const chatHistory = messagesFromInput(input);
517
- assertNoAgentInteractionParts(chatHistory);
518
- const request = {
519
- chatHistory,
520
- documents: [...options.documents ?? []],
521
- tools: configuredTools.filter((tool) => !isProviderTool(tool))
522
- };
523
- const providerTools = configuredTools.filter(isProviderTool);
524
- if (providerTools.length > 0) request.providerTools = providerTools;
525
- if (options.instructions !== void 0 && options.instructions.length > 0) {
526
- request.instructions = options.instructions;
527
- }
528
- if (options.temperature !== void 0) request.temperature = options.temperature;
529
- if (options.maxTokens !== void 0) request.maxTokens = options.maxTokens;
530
- if (options.toolChoice !== void 0) request.toolChoice = options.toolChoice;
531
- if (options.outputSchema !== void 0) request.outputSchema = options.outputSchema;
532
- if (options.controls !== void 0) {
533
- const controls = Object.fromEntries(
534
- Object.entries(options.controls).filter(
535
- (entry) => typeof entry[1] === "string"
536
- )
537
- );
538
- if (Object.keys(controls).length > 0) request.controls = Object.freeze(controls);
539
- }
540
- if (options.providerOptions !== void 0) {
541
- assertJsonObject(options.providerOptions, "providerOptions");
542
- request.providerOptions = options.providerOptions;
543
- }
544
- return request;
545
- }
546
- function assertNoAgentInteractionParts(messages) {
547
- for (const message of messages) {
548
- if (message.role === "tool" && message.content.some((part) => part.type !== "tool-result")) {
549
- throw new TypeError(
550
- "Completion messages contain an unresolved Agent interaction response. Resume the Agent with its continuation instead of sending interaction parts directly to a provider."
551
- );
552
- }
553
- }
554
- }
555
- function messagesFromInput(input) {
556
- if (typeof input === "string") {
557
- return [{ role: "user", content: input }];
558
- }
559
- if (Array.isArray(input)) {
560
- if (input.length === 0) {
561
- throw new Error("input must contain at least one Message.");
562
- }
563
- return parseMessages(input);
564
- }
565
- return [parseMessage(input)];
566
- }
567
-
568
- // src/completion/stream-accumulator.ts
569
- var CompletionStreamAccumulator = class {
570
- orderedParts = [];
571
- textParts = /* @__PURE__ */ new Map();
572
- reasoningByKey = /* @__PURE__ */ new Map();
573
- reasoningKeyById = /* @__PURE__ */ new Map();
574
- toolCalls = /* @__PURE__ */ new Map();
575
- sources = /* @__PURE__ */ new Map();
576
- providerToolCalls = /* @__PURE__ */ new Map();
577
- finalResponse;
578
- messageId;
579
- nextTextKey = 0;
580
- nextReasoningKey = 0;
581
- accept(event) {
582
- if (event.type === "text_delta") {
583
- if (typeof event.delta !== "string") {
584
- throw new CompletionProviderOutputError({ kind: "invalid-stream-event" });
585
- }
586
- this.appendText(event.delta);
587
- return { type: "text_delta", delta: event.delta };
588
- }
589
- if (event.type === "reasoning_delta") {
590
- if (typeof event.delta !== "string" || event.id !== void 0 && !isNonblankString2(event.id) || event.signature !== void 0 && !isNonblankString2(event.signature) || event.contentType !== void 0 && !isReasoningContentType(event.contentType)) {
591
- throw new CompletionProviderOutputError({ kind: "invalid-stream-event" });
592
- }
593
- const reasoning = this.reasoningStateForEvent(event);
594
- this.appendReasoning(reasoning, event);
595
- return reasoningDeltaEvent(event);
596
- }
597
- if (event.type === "tool_call_delta") {
598
- if (!isNonblankString2(event.id)) {
599
- throw new CompletionProviderOutputError({ kind: "invalid-tool-call" });
600
- }
601
- const toolCall = this.toolCallStateForId(event.id);
602
- if (toolCall.fullCallSeen) {
603
- throw new CompletionProviderOutputError({
604
- kind: "invalid-tool-call",
605
- toolCallId: toolCall.id
606
- });
607
- }
608
- if (event.callId !== void 0) {
609
- if (!isNonblankString2(event.callId)) {
610
- throw new CompletionProviderOutputError({
611
- kind: "invalid-tool-call",
612
- toolCallId: toolCall.id
613
- });
614
- }
615
- if (toolCall.callId !== void 0 && toolCall.callId !== event.callId) {
616
- throw new CompletionProviderOutputError({
617
- kind: "invalid-tool-call",
618
- toolCallId: toolCall.id
619
- });
620
- }
621
- toolCall.callId = event.callId;
622
- }
623
- if (event.name !== void 0) {
624
- if (!isNonblankString2(event.name)) {
625
- throw new CompletionProviderOutputError({
626
- kind: "invalid-tool-call",
627
- toolCallId: toolCall.id
628
- });
629
- }
630
- if (toolCall.name.length > 0 && toolCall.name !== event.name) {
631
- throw new CompletionProviderOutputError({
632
- kind: "invalid-tool-call",
633
- toolCallId: toolCall.id
634
- });
635
- }
636
- toolCall.name = event.name;
637
- }
638
- if (event.signature !== void 0) {
639
- if (!isNonblankString2(event.signature) || toolCall.signature !== void 0 && toolCall.signature !== event.signature) {
640
- throw new CompletionProviderOutputError({
641
- kind: "invalid-tool-call",
642
- toolCallId: toolCall.id
643
- });
644
- }
645
- toolCall.signature = event.signature;
646
- }
647
- if (event.argumentsMode !== void 0 && event.argumentsMode !== "append" && event.argumentsMode !== "replace") {
648
- throw new CompletionProviderOutputError({
649
- kind: "invalid-stream-event",
650
- toolCallId: toolCall.id
651
- });
652
- }
653
- if (event.argumentsMode !== void 0 && event.argumentsDelta === void 0) {
654
- throw new CompletionProviderOutputError({
655
- kind: "invalid-stream-event",
656
- toolCallId: toolCall.id
657
- });
658
- }
659
- if (event.argumentsDelta !== void 0) {
660
- if (typeof event.argumentsDelta !== "string") {
661
- throw new CompletionProviderOutputError({
662
- kind: "invalid-tool-arguments",
663
- toolCallId: toolCall.id
664
- });
665
- }
666
- if (event.argumentsMode === "replace") {
667
- if (toolCall.argumentsText.length > 0 && toolCall.argumentsText !== event.argumentsDelta && (toolCall.argumentsSnapshotSeen || !event.argumentsDelta.startsWith(toolCall.argumentsText))) {
668
- throw new CompletionProviderOutputError({
669
- kind: "invalid-tool-call",
670
- toolCallId: toolCall.id
671
- });
672
- }
673
- toolCall.argumentsText = event.argumentsDelta;
674
- toolCall.argumentsSnapshotSeen = true;
675
- } else {
676
- if (toolCall.argumentsSnapshotSeen) {
677
- throw new CompletionProviderOutputError({
678
- kind: "invalid-tool-call",
679
- toolCallId: toolCall.id
680
- });
681
- }
682
- toolCall.argumentsText += event.argumentsDelta;
683
- }
684
- }
685
- return void 0;
686
- }
687
- if (event.type === "tool_call") {
688
- this.upsertToolCall(event.toolCall);
689
- return { type: "tool_call", toolCall: event.toolCall };
690
- }
691
- if (event.type === "source") {
692
- this.sources.set(sourceKey(event.source), event.source);
693
- return { type: "source", source: event.source };
694
- }
695
- if (event.type === "provider_tool_call") {
696
- this.providerToolCalls.set(event.toolCall.id, event.toolCall);
697
- return { type: "provider_tool_call", toolCall: event.toolCall };
698
- }
699
- if (event.type === "message_id") {
700
- if (!isNonblankString2(event.id)) {
701
- throw new CompletionProviderOutputError({ kind: "invalid-stream-event" });
702
- }
703
- this.messageId = event.id;
704
- return void 0;
705
- }
706
- if (event.type === "final") {
707
- this.finalResponse = event.response;
708
- return void 0;
709
- }
710
- return void 0;
711
- }
712
- response() {
713
- this.assertAccumulatedFinishReason();
714
- let accumulatedResponse;
715
- try {
716
- accumulatedResponse = this.buildAccumulatedResponse();
717
- } catch (error) {
718
- if (error instanceof CompletionProviderOutputError && this.finalResponse !== void 0) {
719
- throw providerOutputErrorWithUsage(error, this.finalResponse.usage);
720
- }
721
- throw error;
722
- }
723
- if (this.finalResponse !== void 0) {
724
- if (accumulatedResponse.choice.length === 0) {
725
- return this.withAccumulatedArtifacts(this.finalResponse, accumulatedResponse);
726
- }
727
- return this.mergeFinalResponse(accumulatedResponse, this.finalResponse);
728
- }
729
- return accumulatedResponse;
730
- }
731
- assertAccumulatedFinishReason() {
732
- if (this.finalResponse === void 0) {
733
- if (this.toolCalls.size === 0) {
734
- throw new CompletionProviderOutputError({ kind: "incomplete-stream" });
735
- }
736
- const toolCallId = this.toolCalls.size === 1 ? this.toolCalls.keys().next().value : void 0;
737
- throw new CompletionProviderOutputError({
738
- kind: "incomplete-tool-call",
739
- toolCallId
740
- });
741
- }
742
- if (this.toolCalls.size === 0) return;
743
- const finishReason = this.finalResponse.finishReason;
744
- if (finishReason === "length") {
745
- throw new CompletionProviderOutputError({
746
- kind: "truncated-tool-call",
747
- finishReason,
748
- usage: this.finalResponse.usage
749
- });
750
- }
751
- if (finishReason === "content-filter") {
752
- throw new CompletionProviderOutputError({
753
- kind: "filtered-tool-call",
754
- finishReason,
755
- usage: this.finalResponse.usage
756
- });
757
- }
758
- if (finishReason !== void 0 && finishReason !== "stop" && finishReason !== "tool-calls") {
759
- throw new CompletionProviderOutputError({
760
- kind: "invalid-tool-call",
761
- usage: this.finalResponse.usage
762
- });
763
- }
764
- }
765
- buildAccumulatedResponse() {
766
- const choice = [];
767
- for (const part of this.orderedParts) {
768
- if (part.type === "text") {
769
- const text = this.textParts.get(part.key) ?? "";
770
- if (text.length > 0) {
771
- choice.push({ type: "text", text });
772
- }
773
- continue;
774
- }
775
- if (part.type === "reasoning") {
776
- const reasoning = this.reasoningByKey.get(part.key);
777
- if (reasoning !== void 0) {
778
- choice.push(reasoningContent(reasoning));
779
- }
780
- continue;
781
- }
782
- const toolCall = this.toolCalls.get(part.key);
783
- if (toolCall !== void 0) {
784
- choice.push(toolCallContent(toolCall));
785
- }
786
- }
787
- const response = {
788
- choice,
789
- usage: Usage.empty(),
790
- rawResponse: void 0
791
- };
792
- if (this.messageId !== void 0) {
793
- response.messageId = this.messageId;
794
- }
795
- const sources = [...this.sources.values()];
796
- if (sources.length > 0) {
797
- response.sources = sources;
798
- }
799
- const providerToolCalls = [...this.providerToolCalls.values()];
800
- if (providerToolCalls.length > 0) {
801
- response.providerToolCalls = providerToolCalls;
802
- }
803
- return response;
804
- }
805
- upsertToolCall(toolCall) {
806
- if (!isNonblankString2(toolCall.toolCallId) || !isNonblankString2(toolCall.toolName) || toolCall.callId !== void 0 && !isNonblankString2(toolCall.callId) || toolCall.signature !== void 0 && !isNonblankString2(toolCall.signature)) {
807
- throw new CompletionProviderOutputError({
808
- kind: "invalid-tool-call",
809
- toolCallId: isNonblankString2(toolCall.toolCallId) ? toolCall.toolCallId : void 0
810
- });
811
- }
812
- if (!isJsonValue(toolCall.input)) {
813
- throw new CompletionProviderOutputError({
814
- kind: "invalid-tool-arguments",
815
- toolCallId: toolCall.toolCallId
816
- });
817
- }
818
- const existing = this.toolCalls.get(toolCall.toolCallId);
819
- if (existing !== void 0) {
820
- if (existing.fullCallSeen) {
821
- throw new CompletionProviderOutputError({
822
- kind: "invalid-tool-call",
823
- toolCallId: toolCall.toolCallId
824
- });
825
- }
826
- if (existing.name.length > 0 && existing.name !== toolCall.toolName || existing.callId !== void 0 && existing.callId !== toolCall.callId || existing.signature !== void 0 && toolCall.signature !== void 0 && existing.signature !== toolCall.signature) {
827
- throw new CompletionProviderOutputError({
828
- kind: "invalid-tool-call",
829
- toolCallId: toolCall.toolCallId
830
- });
831
- }
832
- if (existing.argumentsText.length > 0) {
833
- const accumulatedInput = parseToolArguments(existing.id, existing.argumentsText);
834
- if (!jsonValuesEqual(accumulatedInput, toolCall.input)) {
835
- throw new CompletionProviderOutputError({
836
- kind: "invalid-tool-call",
837
- toolCallId: toolCall.toolCallId
838
- });
839
- }
840
- }
841
- }
842
- if (!this.toolCalls.has(toolCall.toolCallId)) {
843
- this.orderedParts.push({ type: "tool_call", key: toolCall.toolCallId });
844
- }
845
- const partial = {
846
- id: toolCall.toolCallId,
847
- name: toolCall.toolName,
848
- argumentsText: JSON.stringify(toolCall.input),
849
- argumentsSnapshotSeen: true,
850
- fullCallSeen: true
851
- };
852
- if (toolCall.callId !== void 0) {
853
- partial.callId = toolCall.callId;
854
- }
855
- const signature = toolCall.signature ?? existing?.signature;
856
- if (signature !== void 0) {
857
- partial.signature = signature;
858
- }
859
- this.toolCalls.set(toolCall.toolCallId, partial);
860
- }
861
- mergeFinalResponse(accumulatedResponse, finalResponse) {
862
- if (finalResponse.choice.length === 0) {
863
- const mergedResponse = {
864
- ...accumulatedResponse,
865
- usage: finalResponse.usage,
866
- rawResponse: finalResponse.rawResponse
867
- };
868
- if (finalResponse.finishReason !== void 0) {
869
- mergedResponse.finishReason = finalResponse.finishReason;
870
- }
871
- if (finalResponse.providerFinishReason !== void 0) {
872
- mergedResponse.providerFinishReason = finalResponse.providerFinishReason;
873
- }
874
- if (finalResponse.messageId !== void 0) {
875
- mergedResponse.messageId = finalResponse.messageId;
876
- }
877
- return this.withAccumulatedArtifacts(mergedResponse, accumulatedResponse);
878
- }
879
- const accumulatedNonTool = accumulatedResponse.choice.filter(
880
- (content) => content.type !== "tool-call"
881
- );
882
- const finalNonTool = finalResponse.choice.filter((content) => content.type !== "tool-call");
883
- if (accumulatedNonTool.length > 0 && !nonToolPartsEqual(accumulatedNonTool, finalNonTool)) {
884
- throw new CompletionProviderOutputError({
885
- kind: "invalid-stream-event",
886
- usage: finalResponse.usage
887
- });
888
- }
889
- const accumulatedById = /* @__PURE__ */ new Map();
890
- const accumulatedByCallId = /* @__PURE__ */ new Map();
891
- for (const content of accumulatedResponse.choice) {
892
- if (content.type !== "tool-call") continue;
893
- accumulatedById.set(content.toolCallId, content);
894
- if (content.callId !== void 0) accumulatedByCallId.set(content.callId, content);
895
- }
896
- const matchedAccumulatedToolCalls = /* @__PURE__ */ new Set();
897
- const choice = finalResponse.choice.map((content) => {
898
- if (content.type !== "tool-call") return content;
899
- const accumulated = accumulatedById.get(content.toolCallId);
900
- if (accumulated === void 0) {
901
- const changedIdentity = content.callId === void 0 ? void 0 : accumulatedByCallId.get(content.callId);
902
- if (changedIdentity !== void 0) {
903
- throw new CompletionProviderOutputError({
904
- kind: "invalid-tool-call",
905
- toolCallId: changedIdentity.toolCallId,
906
- usage: finalResponse.usage
907
- });
908
- }
909
- return content;
910
- }
911
- matchedAccumulatedToolCalls.add(accumulated);
912
- return mergeFinalToolCall(accumulated, content, finalResponse.usage);
913
- });
914
- for (const accumulated of accumulatedById.values()) {
915
- if (!matchedAccumulatedToolCalls.has(accumulated)) {
916
- throw new CompletionProviderOutputError({
917
- kind: "invalid-tool-call",
918
- toolCallId: accumulated.toolCallId,
919
- usage: finalResponse.usage
920
- });
921
- }
922
- }
923
- return this.withAccumulatedArtifacts({ ...finalResponse, choice }, accumulatedResponse);
924
- }
925
- appendText(delta) {
926
- const lastPart = this.orderedParts.at(-1);
927
- const key = lastPart?.type === "text" ? lastPart.key : this.createTextKey();
928
- if (lastPart?.type !== "text") {
929
- this.orderedParts.push({ type: "text", key });
930
- }
931
- this.textParts.set(key, `${this.textParts.get(key) ?? ""}${delta}`);
932
- }
933
- reasoningStateForEvent(event) {
934
- if (event.id !== void 0) {
935
- const existingKey = this.reasoningKeyById.get(event.id);
936
- if (existingKey !== void 0) {
937
- const existing = this.reasoningByKey.get(existingKey);
938
- if (existing !== void 0) {
939
- return existing;
940
- }
941
- }
942
- const key2 = this.createReasoningKey();
943
- const reasoning2 = { id: event.id, text: "" };
944
- this.reasoningKeyById.set(event.id, key2);
945
- this.reasoningByKey.set(key2, reasoning2);
946
- this.orderedParts.push({ type: "reasoning", key: key2 });
947
- return reasoning2;
948
- }
949
- const lastPart = this.orderedParts.at(-1);
950
- if (lastPart?.type === "reasoning") {
951
- const lastReasoning = this.reasoningByKey.get(lastPart.key);
952
- if (lastReasoning !== void 0 && lastReasoning.id === void 0) {
953
- return lastReasoning;
954
- }
955
- }
956
- const key = this.createReasoningKey();
957
- const reasoning = { text: "" };
958
- this.reasoningByKey.set(key, reasoning);
959
- this.orderedParts.push({ type: "reasoning", key });
960
- return reasoning;
961
- }
962
- toolCallStateForId(id) {
963
- const existing = this.toolCalls.get(id);
964
- if (existing !== void 0) {
965
- return existing;
966
- }
967
- const toolCall = {
968
- id,
969
- name: "",
970
- argumentsText: "",
971
- argumentsSnapshotSeen: false,
972
- fullCallSeen: false
973
- };
974
- this.toolCalls.set(id, toolCall);
975
- this.orderedParts.push({ type: "tool_call", key: id });
976
- return toolCall;
977
- }
978
- withMessageIdFallback(response, accumulatedResponse) {
979
- if (response.messageId !== void 0 || accumulatedResponse.messageId === void 0) {
980
- return response;
981
- }
982
- return { ...response, messageId: accumulatedResponse.messageId };
983
- }
984
- withAccumulatedArtifacts(response, accumulatedResponse) {
985
- const withMessageId = this.withMessageIdFallback(response, accumulatedResponse);
986
- const sources = mergeSources(accumulatedResponse.sources, response.sources);
987
- const providerToolCalls = mergeProviderToolCalls(
988
- accumulatedResponse.providerToolCalls,
989
- response.providerToolCalls
990
- );
991
- let accumulated = { ...withMessageId };
992
- if (sources.length > 0) accumulated = { ...accumulated, sources };
993
- if (providerToolCalls.length > 0) {
994
- accumulated = { ...accumulated, providerToolCalls };
995
- }
996
- return accumulated;
997
- }
998
- createTextKey() {
999
- this.nextTextKey += 1;
1000
- return `text_${this.nextTextKey.toString()}`;
1001
- }
1002
- createReasoningKey() {
1003
- this.nextReasoningKey += 1;
1004
- return `reasoning_${this.nextReasoningKey.toString()}`;
1005
- }
1006
- appendReasoning(reasoning, event) {
1007
- const contentType = event.contentType ?? "text";
1008
- if (contentType === "text" || contentType === "summary") {
1009
- reasoning.text += event.delta;
1010
- }
1011
- if (event.contentType === void 0 && event.signature === void 0) {
1012
- return;
1013
- }
1014
- reasoning.details ??= [];
1015
- const last = reasoning.details.at(-1);
1016
- if (contentType === "text") {
1017
- if (last?.type === "text") {
1018
- let detail = {
1019
- ...last,
1020
- text: `${last.text}${event.delta}`
1021
- };
1022
- if (event.signature !== void 0) detail = { ...detail, signature: event.signature };
1023
- reasoning.details[reasoning.details.length - 1] = detail;
1024
- } else {
1025
- reasoning.details.push(
1026
- event.signature === void 0 ? { type: "text", text: event.delta } : { type: "text", text: event.delta, signature: event.signature }
1027
- );
1028
- }
1029
- return;
1030
- }
1031
- if (contentType === "summary") {
1032
- if (last?.type === "summary") {
1033
- reasoning.details[reasoning.details.length - 1] = {
1034
- ...last,
1035
- text: `${last.text}${event.delta}`
1036
- };
1037
- } else {
1038
- reasoning.details.push({ type: "summary", text: event.delta });
1039
- }
1040
- return;
1041
- }
1042
- if (contentType === "encrypted") {
1043
- reasoning.details.push({ type: "encrypted", data: event.delta });
1044
- return;
1045
- }
1046
- reasoning.details.push({ type: "redacted", data: event.delta });
1047
- }
1048
- };
1049
- function sourceKey(source) {
1050
- return `${source.url}\0${source.startIndex ?? ""}\0${source.endIndex ?? ""}`;
1051
- }
1052
- function mergeSources(accumulated, final) {
1053
- const sources = /* @__PURE__ */ new Map();
1054
- for (const source of [...accumulated ?? [], ...final ?? []]) {
1055
- sources.set(sourceKey(source), source);
1056
- }
1057
- return [...sources.values()];
1058
- }
1059
- function mergeProviderToolCalls(accumulated, final) {
1060
- const toolCalls = /* @__PURE__ */ new Map();
1061
- for (const toolCall of [...accumulated ?? [], ...final ?? []]) {
1062
- toolCalls.set(toolCall.id, toolCall);
1063
- }
1064
- return [...toolCalls.values()];
1065
- }
1066
- function reasoningContent(reasoning) {
1067
- const content = reasoning.details === void 0 ? { type: "reasoning", text: reasoning.text } : { type: "reasoning", text: reasoning.text, details: reasoning.details };
1068
- return reasoning.id === void 0 ? content : { ...content, id: reasoning.id };
1069
- }
1070
- function toolCallContent(toolCall) {
1071
- const argumentsValue = parseToolArguments(toolCall.id, toolCall.argumentsText);
1072
- let content = {
1073
- type: "tool-call",
1074
- toolCallId: toolCall.id,
1075
- toolName: toolCall.name,
1076
- input: argumentsValue
1077
- };
1078
- if (toolCall.callId !== void 0) content = { ...content, callId: toolCall.callId };
1079
- if (toolCall.signature !== void 0) content = { ...content, signature: toolCall.signature };
1080
- return content;
1081
- }
1082
- function mergeFinalToolCall(accumulated, finalToolCall, usage) {
1083
- if (finalToolCall.toolCallId !== accumulated.toolCallId || finalToolCall.toolName !== accumulated.toolName || accumulated.callId !== void 0 && finalToolCall.callId !== accumulated.callId || accumulated.signature !== void 0 && finalToolCall.signature !== void 0 && finalToolCall.signature !== accumulated.signature) {
1084
- throw new CompletionProviderOutputError({
1085
- kind: "invalid-tool-call",
1086
- toolCallId: accumulated.toolCallId,
1087
- usage
1088
- });
1089
- }
1090
- if (!isJsonValue(finalToolCall.input)) {
1091
- throw new CompletionProviderOutputError({
1092
- kind: "invalid-tool-arguments",
1093
- toolCallId: accumulated.toolCallId,
1094
- usage
1095
- });
1096
- }
1097
- if (!jsonValuesEqual(accumulated.input, finalToolCall.input)) {
1098
- throw new CompletionProviderOutputError({
1099
- kind: "invalid-tool-call",
1100
- toolCallId: accumulated.toolCallId,
1101
- usage
1102
- });
1103
- }
1104
- let merged = {
1105
- type: "tool-call",
1106
- toolCallId: finalToolCall.toolCallId,
1107
- toolName: finalToolCall.toolName,
1108
- input: accumulated.input
1109
- };
1110
- const callId = finalToolCall.callId ?? accumulated.callId;
1111
- if (callId !== void 0) merged = { ...merged, callId };
1112
- const signature = finalToolCall.signature ?? accumulated.signature;
1113
- if (signature !== void 0) merged = { ...merged, signature };
1114
- return merged;
1115
- }
1116
- function reasoningDeltaEvent(event) {
1117
- const mapped = { type: "reasoning_delta", delta: event.delta };
1118
- if (event.id !== void 0) mapped.id = event.id;
1119
- if (event.contentType !== void 0) mapped.contentType = event.contentType;
1120
- if (event.signature !== void 0) mapped.signature = event.signature;
1121
- return mapped;
1122
- }
1123
- function parseToolArguments(toolCallId, text) {
1124
- let value;
1125
- try {
1126
- value = JSON.parse(text);
1127
- } catch {
1128
- throw new CompletionProviderOutputError({
1129
- kind: "malformed-tool-arguments",
1130
- toolCallId
1131
- });
1132
- }
1133
- if (!isJsonValue(value)) {
1134
- throw new CompletionProviderOutputError({
1135
- kind: "invalid-tool-arguments",
1136
- toolCallId
1137
- });
1138
- }
1139
- return value;
1140
- }
1141
- function jsonValuesEqual(left, right) {
1142
- if (left === right) {
1143
- return true;
1144
- }
1145
- if (left === null || right === null || typeof left !== "object" || typeof right !== "object") {
1146
- return false;
1147
- }
1148
- if (isJsonArray(left) || isJsonArray(right)) {
1149
- if (!isJsonArray(left) || !isJsonArray(right) || left.length !== right.length) {
1150
- return false;
1151
- }
1152
- return left.every((value, index) => {
1153
- const rightValue = right[index];
1154
- return rightValue !== void 0 && jsonValuesEqual(value, rightValue);
1155
- });
1156
- }
1157
- const leftKeys = Object.keys(left);
1158
- const rightKeys = Object.keys(right);
1159
- if (leftKeys.length !== rightKeys.length) {
1160
- return false;
1161
- }
1162
- for (const key of leftKeys) {
1163
- if (!Object.hasOwn(right, key)) {
1164
- return false;
1165
- }
1166
- const leftValue = left[key];
1167
- const rightValue = right[key];
1168
- if (leftValue === void 0 || rightValue === void 0 || !jsonValuesEqual(leftValue, rightValue)) {
1169
- return false;
1170
- }
1171
- }
1172
- return true;
1173
- }
1174
- function nonToolPartsEqual(accumulated, final) {
1175
- if (accumulated.length !== final.length) return false;
1176
- if (!isJsonValue(accumulated) || !isJsonValue(final)) return false;
1177
- const unmatched = [...final];
1178
- for (const part of accumulated) {
1179
- const index = unmatched.findIndex((candidate) => jsonValuesEqual(part, candidate));
1180
- if (index < 0) return false;
1181
- unmatched.splice(index, 1);
1182
- }
1183
- return true;
1184
- }
1185
- function isJsonArray(value) {
1186
- return Array.isArray(value);
1187
- }
1188
- function providerOutputErrorWithUsage(error, usage) {
1189
- const shared = { usage };
1190
- if (error.toolCallId !== void 0) shared.toolCallId = error.toolCallId;
1191
- if (error.kind === "truncated-tool-call") {
1192
- return new CompletionProviderOutputError({
1193
- ...shared,
1194
- kind: error.kind,
1195
- finishReason: "length"
1196
- });
1197
- }
1198
- if (error.kind === "filtered-tool-call") {
1199
- return new CompletionProviderOutputError({
1200
- ...shared,
1201
- kind: error.kind,
1202
- finishReason: "content-filter"
1203
- });
1204
- }
1205
- if (error.finishReason === "length" || error.finishReason === "content-filter") {
1206
- throw error;
1207
- }
1208
- return new CompletionProviderOutputError({
1209
- ...shared,
1210
- kind: error.kind,
1211
- finishReason: error.finishReason
1212
- });
1213
- }
1214
- function isNonblankString2(value) {
1215
- return typeof value === "string" && value.trim().length > 0;
1216
- }
1217
- function isReasoningContentType(value) {
1218
- return value === "text" || value === "summary" || value === "encrypted" || value === "redacted";
1219
- }
1220
-
1221
- // src/completion/generate-completion.ts
1222
- var CompletionStructuredOutputError = class extends Error {
1223
- phase;
1224
- outputLength;
1225
- usage;
1226
- finishReason;
1227
- providerFinishReason;
1228
- constructor(options) {
1229
- const failure = options.phase === "truncated" ? "because the provider reached its output limit" : options.phase === "content-filter" ? "because the provider filtered the response" : options.phase === "parse" ? "during JSON parsing" : "during schema validation";
1230
- super(`Structured completion output failed ${failure}.`, { cause: options.cause });
1231
- this.name = "CompletionStructuredOutputError";
1232
- this.phase = options.phase;
1233
- this.outputLength = options.outputLength;
1234
- this.usage = options.usage;
1235
- this.finishReason = options.finishReason;
1236
- this.providerFinishReason = options.providerFinishReason;
1237
- }
1238
- };
1239
- async function generateCompletion(options) {
1240
- throwIfAborted(options.abortSignal);
1241
- const request = requestFromOptions(options);
1242
- assertCompletionRequestSupported(options.model, request);
1243
- const retries = resolveOptionalRetries(options.retries);
1244
- const response = await sendCompletion(options.model, request, retries, options.abortSignal);
1245
- return resultFromResponse(response, structuredOutputSchema(options));
1246
- }
1247
- function streamCompletion(options) {
1248
- throwIfAborted(options.abortSignal);
1249
- const request = requestFromOptions(options);
1250
- if (!isStreamingCompletionModel(options.model) || !options.model.capabilities.streaming) {
1251
- throw new Error("This completion model does not support streaming");
1252
- }
1253
- assertCompletionRequestSupported(options.model, request, { streaming: true });
1254
- const retries = resolveOptionalRetries(options.retries);
1255
- return streamCompletionWithRetries(
1256
- options.model,
1257
- request,
1258
- retries,
1259
- options.abortSignal,
1260
- structuredOutputSchema(options)
1261
- );
1262
- }
1263
- async function sendCompletion(model, request, retries, abortSignal) {
1264
- const callOptions = modelCallOptions(abortSignal);
1265
- let attempt = 1;
1266
- let failedUsage = Usage.empty();
1267
- while (true) {
1268
- try {
1269
- throwIfAborted(abortSignal);
1270
- const response = await model.completion(request, callOptions);
1271
- assertCompletionResponseIntegrity({ response });
1272
- return Usage.isEmpty(failedUsage) ? response : { ...response, usage: Usage.add(failedUsage, response.usage) };
1273
- } catch (error) {
1274
- const normalizedError = abortSignal?.aborted === true ? abortError(abortSignal.reason) : error;
1275
- const attemptUsage = completionProviderOutputErrorUsage(normalizedError);
1276
- if (attemptUsage !== void 0) failedUsage = Usage.add(failedUsage, attemptUsage);
1277
- const retryOptions = retryOptionsForFailure(retries, {
1278
- error: normalizedError,
1279
- attempt,
1280
- streaming: false
1281
- });
1282
- if (retryOptions === void 0) throw normalizedError;
1283
- await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);
1284
- attempt += 1;
1285
- }
1286
- }
1287
- }
1288
- function resolveOptionalRetries(setting) {
1289
- return setting === void 0 || setting === false ? void 0 : resolveRetryOptions(setting);
1290
- }
1291
- async function* streamCompletionWithRetries(model, request, retries, abortSignal, outputSchema) {
1292
- let attempt = 1;
1293
- let swallowedUsage = Usage.empty();
1294
- const callOptions = modelCallOptions(abortSignal);
1295
- attemptLoop: while (true) {
1296
- let exposedProgress = false;
1297
- let retryDelay;
1298
- const accumulator = new CompletionStreamAccumulator();
1299
- try {
1300
- throwIfAborted(abortSignal);
1301
- const events = model.streamCompletion(request, callOptions);
1302
- for await (const event of events) {
1303
- if (event.type === "error" && !exposedProgress) {
1304
- const eventError = abortSignal?.aborted === true ? abortError(abortSignal.reason) : event.error;
1305
- const eventUsage = event.usage ?? completionProviderOutputErrorUsage(eventError) ?? Usage.empty();
1306
- const retryOptions = retryOptionsForFailure(retries, {
1307
- error: eventError,
1308
- attempt,
1309
- streaming: true
1310
- });
1311
- if (retryOptions !== void 0) {
1312
- swallowedUsage = Usage.add(swallowedUsage, eventUsage);
1313
- retryDelay = retryDelayMs(retryOptions, attempt);
1314
- break;
1315
- }
1316
- }
1317
- if (event.type === "error") {
1318
- const eventError = abortSignal?.aborted === true ? abortError(abortSignal.reason) : event.error;
1319
- const eventUsage = event.usage ?? completionProviderOutputErrorUsage(eventError) ?? Usage.empty();
1320
- yield {
1321
- type: "error",
1322
- error: eventError,
1323
- usage: Usage.add(swallowedUsage, eventUsage)
1324
- };
1325
- return;
1326
- }
1327
- if (event.type === "final") {
1328
- const cumulativeUsage = Usage.add(swallowedUsage, event.response.usage);
1329
- try {
1330
- accumulator.accept(event);
1331
- const accumulatedResponse = accumulator.response();
1332
- const response = Usage.isEmpty(swallowedUsage) ? accumulatedResponse : { ...accumulatedResponse, usage: cumulativeUsage };
1333
- assertCompletionResponseIntegrity({ response });
1334
- yield {
1335
- type: "final",
1336
- result: resultFromResponse(response, outputSchema)
1337
- };
1338
- } catch (error) {
1339
- const retryOptions = exposedProgress ? void 0 : retryOptionsForFailure(retries, {
1340
- error,
1341
- attempt,
1342
- streaming: true
1343
- });
1344
- if (retryOptions !== void 0) {
1345
- swallowedUsage = cumulativeUsage;
1346
- await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);
1347
- attempt += 1;
1348
- continue attemptLoop;
1349
- }
1350
- yield { type: "error", error, usage: cumulativeUsage };
1351
- }
1352
- return;
1353
- }
1354
- accumulator.accept(event);
1355
- exposedProgress = true;
1356
- yield event;
1357
- }
1358
- if (retryDelay !== void 0) {
1359
- await waitForRetry(retryDelay, abortSignal);
1360
- attempt += 1;
1361
- continue;
1362
- }
1363
- let incomplete;
1364
- try {
1365
- accumulator.response();
1366
- incomplete = new CompletionProviderOutputError({ kind: "incomplete-stream" });
1367
- } catch (error) {
1368
- incomplete = error;
1369
- }
1370
- if (!exposedProgress) {
1371
- const retryOptions = retryOptionsForFailure(retries, {
1372
- error: incomplete,
1373
- attempt,
1374
- streaming: true
1375
- });
1376
- if (retryOptions !== void 0) {
1377
- await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);
1378
- attempt += 1;
1379
- continue;
1380
- }
1381
- }
1382
- yield { type: "error", error: incomplete, usage: swallowedUsage };
1383
- return;
1384
- } catch (error) {
1385
- const normalizedError = abortSignal?.aborted === true ? abortError(abortSignal.reason) : error;
1386
- const attemptUsage = completionProviderOutputErrorUsage(normalizedError);
1387
- const cumulativeUsage = attemptUsage === void 0 ? swallowedUsage : Usage.add(swallowedUsage, attemptUsage);
1388
- if (!exposedProgress) {
1389
- const retryOptions = retryOptionsForFailure(retries, {
1390
- error: normalizedError,
1391
- attempt,
1392
- streaming: true
1393
- });
1394
- if (retryOptions !== void 0) {
1395
- try {
1396
- swallowedUsage = cumulativeUsage;
1397
- await waitForRetry(retryDelayMs(retryOptions, attempt), abortSignal);
1398
- attempt += 1;
1399
- continue;
1400
- } catch (waitError) {
1401
- yield { type: "error", error: waitError, usage: cumulativeUsage };
1402
- return;
1403
- }
1404
- }
1405
- }
1406
- yield { type: "error", error: normalizedError, usage: cumulativeUsage };
1407
- return;
1408
- }
1409
- }
1410
- }
1411
- function requestFromOptions(options) {
1412
- const input = inputFromOptions(options);
1413
- return createCompletionRequest(input, {
1414
- instructions: options.instructions,
1415
- documents: options.documents,
1416
- tools: options.tools,
1417
- temperature: options.temperature,
1418
- maxTokens: options.maxTokens,
1419
- toolChoice: options.toolChoice,
1420
- controls: options.controls,
1421
- providerOptions: options.providerOptions,
1422
- outputSchema: "outputSchema" in options && options.outputSchema !== void 0 ? toProviderJsonSchema(options.outputSchema) : void 0
1423
- });
1424
- }
1425
- function inputFromOptions(options) {
1426
- const prompt = options.prompt;
1427
- const messages = options.messages;
1428
- const hasPrompt = prompt !== void 0;
1429
- const hasMessages = messages !== void 0;
1430
- if (hasPrompt === hasMessages) {
1431
- throw new TypeError("Exactly one of prompt or messages must be provided.");
1432
- }
1433
- if (hasPrompt) {
1434
- if (typeof prompt !== "string" || prompt.trim().length === 0) {
1435
- throw new TypeError("Completion prompt must be a non-empty string.");
1436
- }
1437
- return prompt;
1438
- }
1439
- if (!Array.isArray(messages)) {
1440
- throw new TypeError("Completion messages must be an array of Message values.");
1441
- }
1442
- return messages;
1443
- }
1444
- function structuredOutputSchema(options) {
1445
- return options.outputSchema;
1446
- }
1447
- function resultFromResponse(response, outputSchema) {
1448
- const text = textFromAssistantContent(response.choice);
1449
- const result = {
1450
- output: outputSchema === void 0 ? text : parseCompletionOutput(text, outputSchema, response),
1451
- text,
1452
- content: [...response.choice],
1453
- usage: response.usage,
1454
- rawResponse: response.rawResponse
1455
- };
1456
- if (response.finishReason !== void 0) result.finishReason = response.finishReason;
1457
- if (response.providerFinishReason !== void 0) {
1458
- result.providerFinishReason = response.providerFinishReason;
1459
- }
1460
- if (response.contextUsage !== void 0) result.contextUsage = response.contextUsage;
1461
- if (response.messageId !== void 0) result.messageId = response.messageId;
1462
- if (response.sources !== void 0) result.sources = [...response.sources];
1463
- if (response.providerToolCalls !== void 0) {
1464
- result.providerToolCalls = [...response.providerToolCalls];
1465
- }
1466
- return result;
1467
- }
1468
- function parseCompletionOutput(text, schema, response) {
1469
- if (response.finishReason === "content-filter") {
1470
- throw new CompletionStructuredOutputError({
1471
- phase: "content-filter",
1472
- outputLength: text.length,
1473
- usage: response.usage,
1474
- finishReason: response.finishReason,
1475
- providerFinishReason: response.providerFinishReason
1476
- });
1477
- }
1478
- if (response.finishReason === "length") {
1479
- throw new CompletionStructuredOutputError({
1480
- phase: "truncated",
1481
- outputLength: text.length,
1482
- usage: response.usage,
1483
- finishReason: response.finishReason,
1484
- providerFinishReason: response.providerFinishReason
1485
- });
1486
- }
1487
- let json;
1488
- try {
1489
- json = JSON.parse(text);
1490
- if (!isJsonValue(json)) {
1491
- throw new TypeError("Structured completion output is not a JSON value.");
1492
- }
1493
- } catch (error) {
1494
- throw new CompletionStructuredOutputError({
1495
- phase: "parse",
1496
- outputLength: text.length,
1497
- usage: response.usage,
1498
- finishReason: response.finishReason,
1499
- providerFinishReason: response.providerFinishReason,
1500
- cause: error
1501
- });
1502
- }
1503
- try {
1504
- return schema.parse(json);
1505
- } catch (error) {
1506
- throw new CompletionStructuredOutputError({
1507
- phase: "schema",
1508
- outputLength: text.length,
1509
- usage: response.usage,
1510
- finishReason: response.finishReason,
1511
- providerFinishReason: response.providerFinishReason,
1512
- cause: error
1513
- });
1514
- }
1515
- }
1516
- function modelCallOptions(abortSignal) {
1517
- return abortSignal === void 0 ? void 0 : { abortSignal };
1518
- }
1519
- function isStreamingCompletionModel(model) {
1520
- return typeof model.streamCompletion === "function";
1521
- }
1522
-
1523
- export {
1524
- reasoningDisplayText,
1525
- isProviderTool,
1526
- calculateContextUsage,
1527
- withContextUsage,
1528
- resolveModelContextLimits,
1529
- Usage,
1530
- getAssistantGenerationMetadata,
1531
- CompletionCapabilityError,
1532
- assertCompletionRequestSupported,
1533
- assertCompletionControlsSupported,
1534
- textFromAssistantContent,
1535
- createCompletionRequest,
1536
- COMPLETION_PROVIDER_OUTPUT_ERROR_CODE,
1537
- CompletionProviderOutputError,
1538
- assertCompletionResponseIntegrity,
1539
- CompletionStreamAccumulator,
1540
- CompletionStructuredOutputError,
1541
- generateCompletion,
1542
- streamCompletion,
1543
- isStreamingCompletionModel
1544
- };
1545
- //# sourceMappingURL=chunk-OI3LSMJG.js.map