abtars 0.1.0-alpha.2 → 0.1.0-alpha.21

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 (386) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/bundle/_registry.generated-KQODGKTQ.js +36 -0
  3. package/bundle/{_registry.generated-M4WY2MMI.js.map → _registry.generated-KQODGKTQ.js.map} +1 -1
  4. package/bundle/abtars-browser.js +8 -7
  5. package/bundle/abtars-browser.js.map +1 -1
  6. package/bundle/abtars-cli.js +646 -73
  7. package/bundle/abtars-cli.js.map +4 -4
  8. package/bundle/abtars-restart.js +7 -6
  9. package/bundle/abtars-rss.js +2 -1
  10. package/bundle/abtars-rss.js.map +1 -1
  11. package/bundle/abtars-task.js +9 -8
  12. package/bundle/abtars-task.js.map +1 -1
  13. package/bundle/abtars.js +103 -96
  14. package/bundle/abtars.js.map +2 -2
  15. package/bundle/{agent-api-rate-limit-OQNFMXTZ.js → agent-api-rate-limit-7R5TX2F2.js} +7 -6
  16. package/bundle/{agent-api-rate-limit-OQNFMXTZ.js.map → agent-api-rate-limit-7R5TX2F2.js.map} +1 -1
  17. package/bundle/agent-registry-5M77ZOMV.js +19 -0
  18. package/bundle/agent-registry-VJMNIQ5W.js +19 -0
  19. package/bundle/{anthropic-adapter-2APTH3LA.js → anthropic-adapter-IBY3NPXW.js} +4 -3
  20. package/bundle/{anthropic-adapter-2APTH3LA.js.map → anthropic-adapter-IBY3NPXW.js.map} +1 -1
  21. package/bundle/{bridge-lock-transport-4AC2G5G6.js → bridge-lock-transport-HO545SBK.js} +9 -8
  22. package/bundle/browse-delivery-64GQIUHG.js +18 -0
  23. package/bundle/browser-EXR5OQGK.js +19 -0
  24. package/bundle/capability-HIE7UGFU.js +18 -0
  25. package/bundle/{chunk-BUUVFUPO.js → chunk-2BY6I4P5.js} +5 -4
  26. package/bundle/{chunk-BUUVFUPO.js.map → chunk-2BY6I4P5.js.map} +1 -1
  27. package/bundle/{chunk-Y6XAEX2Q.js → chunk-2F6XKG7Y.js} +15 -9
  28. package/bundle/chunk-2F6XKG7Y.js.map +7 -0
  29. package/bundle/{chunk-V76TVMCM.js → chunk-3MO2MDXJ.js} +5 -4
  30. package/bundle/{chunk-V76TVMCM.js.map → chunk-3MO2MDXJ.js.map} +1 -1
  31. package/bundle/{chunk-6UCRKRWR.js → chunk-6XX4OAAM.js} +22 -21
  32. package/bundle/chunk-6XX4OAAM.js.map +7 -0
  33. package/bundle/{chunk-XREWVCUO.js → chunk-7CHLS36W.js} +16 -148
  34. package/bundle/chunk-7CHLS36W.js.map +7 -0
  35. package/bundle/{chunk-NWDBD4PA.js → chunk-7K2YZTLD.js} +3 -2
  36. package/bundle/{chunk-JCJS4ZIB.js → chunk-AQVOAQQI.js} +5 -4
  37. package/bundle/{chunk-JCJS4ZIB.js.map → chunk-AQVOAQQI.js.map} +1 -1
  38. package/bundle/chunk-AUQD2PKM.js +136 -0
  39. package/bundle/chunk-AUQD2PKM.js.map +7 -0
  40. package/bundle/{chunk-YOCTDKKL.js → chunk-BYDUMHXT.js} +4 -3
  41. package/bundle/{chunk-YOCTDKKL.js.map → chunk-BYDUMHXT.js.map} +1 -1
  42. package/bundle/{chunk-RVE2N7FA.js → chunk-CELR236Q.js} +5 -4
  43. package/bundle/{chunk-RVE2N7FA.js.map → chunk-CELR236Q.js.map} +1 -1
  44. package/bundle/{chunk-2XU2X4OI.js → chunk-CUQA2AJT.js} +3 -2
  45. package/bundle/{chunk-2XU2X4OI.js.map → chunk-CUQA2AJT.js.map} +1 -1
  46. package/bundle/chunk-DMPR5MYT.js +183 -0
  47. package/bundle/chunk-DMPR5MYT.js.map +7 -0
  48. package/bundle/{chunk-BHMZ4RCC.js → chunk-DY3R7LDW.js} +55 -54
  49. package/bundle/{chunk-BHMZ4RCC.js.map → chunk-DY3R7LDW.js.map} +1 -1
  50. package/bundle/{chunk-AR6GO6YC.js → chunk-ELRAH7VL.js} +5 -4
  51. package/bundle/{chunk-AR6GO6YC.js.map → chunk-ELRAH7VL.js.map} +1 -1
  52. package/bundle/{chunk-FMWKEPM7.js → chunk-EX2SRTUE.js} +5 -4
  53. package/bundle/{chunk-FMWKEPM7.js.map → chunk-EX2SRTUE.js.map} +1 -1
  54. package/bundle/{chunk-JW6RU47G.js → chunk-FVQGP5YO.js} +8 -7
  55. package/bundle/{chunk-JW6RU47G.js.map → chunk-FVQGP5YO.js.map} +1 -1
  56. package/bundle/{chunk-GRNENTPA.js → chunk-G6IXMYIO.js} +4 -3
  57. package/bundle/{chunk-GRNENTPA.js.map → chunk-G6IXMYIO.js.map} +1 -1
  58. package/bundle/{chunk-6NR3OHEW.js → chunk-H2RZ4NEJ.js} +6 -5
  59. package/bundle/{chunk-6NR3OHEW.js.map → chunk-H2RZ4NEJ.js.map} +1 -1
  60. package/bundle/chunk-HVKJN3AG.js +189 -0
  61. package/bundle/chunk-HVKJN3AG.js.map +7 -0
  62. package/bundle/{chunk-265TPOPC.js → chunk-HXJRZWKA.js} +3 -2
  63. package/bundle/{chunk-265TPOPC.js.map → chunk-HXJRZWKA.js.map} +1 -1
  64. package/bundle/chunk-IU3RI5E4.js +645 -0
  65. package/bundle/chunk-IU3RI5E4.js.map +7 -0
  66. package/bundle/{chunk-GST5T3WZ.js → chunk-J5YIMCLT.js} +6 -5
  67. package/bundle/{chunk-GST5T3WZ.js.map → chunk-J5YIMCLT.js.map} +1 -1
  68. package/bundle/chunk-JAJ3DUQ2.js +30 -0
  69. package/bundle/{chunk-OP7BTAWY.js.map → chunk-JAJ3DUQ2.js.map} +1 -1
  70. package/bundle/chunk-JHF25OOG.js +645 -0
  71. package/bundle/chunk-JHF25OOG.js.map +7 -0
  72. package/bundle/{chunk-MPX525QO.js → chunk-JRG4EFMP.js} +5 -4
  73. package/bundle/{chunk-MPX525QO.js.map → chunk-JRG4EFMP.js.map} +1 -1
  74. package/bundle/{chunk-VVEDVGCR.js → chunk-JU3UBWLN.js} +17 -16
  75. package/bundle/{chunk-VVEDVGCR.js.map → chunk-JU3UBWLN.js.map} +1 -1
  76. package/bundle/{chunk-QBGBT5QS.js → chunk-JX3ZZU3O.js} +5 -4
  77. package/bundle/{chunk-QBGBT5QS.js.map → chunk-JX3ZZU3O.js.map} +1 -1
  78. package/bundle/{chunk-6SETMHNN.js → chunk-K7P74UNQ.js} +8 -7
  79. package/bundle/{chunk-6SETMHNN.js.map → chunk-K7P74UNQ.js.map} +1 -1
  80. package/bundle/{chunk-AZJIODTQ.js → chunk-KED3G7HS.js} +6 -5
  81. package/bundle/{chunk-AZJIODTQ.js.map → chunk-KED3G7HS.js.map} +1 -1
  82. package/bundle/chunk-KI2ROWAH.js +3707 -0
  83. package/bundle/chunk-KI2ROWAH.js.map +7 -0
  84. package/bundle/{chunk-UHRP745J.js → chunk-L7YHV5DL.js} +6 -5
  85. package/bundle/{chunk-UHRP745J.js.map → chunk-L7YHV5DL.js.map} +1 -1
  86. package/bundle/{chunk-BSSBCSCL.js → chunk-LD5BMLHG.js} +11 -10
  87. package/bundle/{chunk-BSSBCSCL.js.map → chunk-LD5BMLHG.js.map} +1 -1
  88. package/bundle/{chunk-2UPU3OW6.js → chunk-LYEAHE5V.js} +5 -4
  89. package/bundle/{chunk-2UPU3OW6.js.map → chunk-LYEAHE5V.js.map} +1 -1
  90. package/bundle/{chunk-3B7BBE4F.js → chunk-MCGEXAG5.js} +8 -7
  91. package/bundle/{chunk-3B7BBE4F.js.map → chunk-MCGEXAG5.js.map} +1 -1
  92. package/bundle/{chunk-X76UX47U.js → chunk-MJ6PHMOK.js} +4 -3
  93. package/bundle/{chunk-X76UX47U.js.map → chunk-MJ6PHMOK.js.map} +1 -1
  94. package/bundle/{chunk-LSPKJQCI.js → chunk-MV6CJFWR.js} +3 -2
  95. package/bundle/{chunk-LSPKJQCI.js.map → chunk-MV6CJFWR.js.map} +1 -1
  96. package/bundle/chunk-MZWMYN4O.js +17 -0
  97. package/bundle/{chunk-M6VBAPNT.js.map → chunk-MZWMYN4O.js.map} +1 -1
  98. package/bundle/{chunk-HX7Y7EYP.js → chunk-NIRYBWUW.js} +4 -3
  99. package/bundle/{chunk-HX7Y7EYP.js.map → chunk-NIRYBWUW.js.map} +1 -1
  100. package/bundle/{chunk-3E545J66.js → chunk-OW64RUE5.js} +3 -2
  101. package/bundle/{chunk-3E545J66.js.map → chunk-OW64RUE5.js.map} +1 -1
  102. package/bundle/chunk-P56PLAIC.js +126 -0
  103. package/bundle/chunk-P56PLAIC.js.map +7 -0
  104. package/bundle/{chunk-TZHIDLDS.js → chunk-P6PN34XD.js} +5 -4
  105. package/bundle/{chunk-TZHIDLDS.js.map → chunk-P6PN34XD.js.map} +1 -1
  106. package/bundle/{chunk-2UENBO6M.js → chunk-PF5UQ64X.js} +9 -8
  107. package/bundle/{chunk-2UENBO6M.js.map → chunk-PF5UQ64X.js.map} +1 -1
  108. package/bundle/{chunk-6CPN4IGS.js → chunk-PQ62LZNA.js} +9 -8
  109. package/bundle/{chunk-6CPN4IGS.js.map → chunk-PQ62LZNA.js.map} +1 -1
  110. package/bundle/{chunk-UCQ2WC3B.js → chunk-PQW5QBPY.js} +15 -8
  111. package/bundle/chunk-PQW5QBPY.js.map +7 -0
  112. package/bundle/{chunk-D2DCBO6M.js → chunk-R36WIOYX.js} +3 -2
  113. package/bundle/{chunk-D2DCBO6M.js.map → chunk-R36WIOYX.js.map} +1 -1
  114. package/bundle/chunk-RB3X66KM.js +386 -0
  115. package/bundle/chunk-RB3X66KM.js.map +7 -0
  116. package/bundle/{chunk-GUQVJC3U.js → chunk-RE3F3CFW.js} +7 -6
  117. package/bundle/{chunk-GUQVJC3U.js.map → chunk-RE3F3CFW.js.map} +1 -1
  118. package/bundle/chunk-RWUINZUQ.js +19 -0
  119. package/bundle/chunk-RWUINZUQ.js.map +7 -0
  120. package/bundle/{chunk-NT3OBORC.js → chunk-S54DBUZ4.js} +10 -9
  121. package/bundle/{chunk-NT3OBORC.js.map → chunk-S54DBUZ4.js.map} +1 -1
  122. package/bundle/{chunk-CWOHNFUV.js → chunk-SY67HM2Y.js} +3 -2
  123. package/bundle/{chunk-CWOHNFUV.js.map → chunk-SY67HM2Y.js.map} +1 -1
  124. package/bundle/{chunk-BQ2L4GMG.js → chunk-TBLYGCPQ.js} +4 -3
  125. package/bundle/{chunk-BQ2L4GMG.js.map → chunk-TBLYGCPQ.js.map} +1 -1
  126. package/bundle/chunk-TCBMBX3Z.js +183 -0
  127. package/bundle/chunk-TCBMBX3Z.js.map +7 -0
  128. package/bundle/chunk-TXRWQIQQ.js +3707 -0
  129. package/bundle/chunk-TXRWQIQQ.js.map +7 -0
  130. package/bundle/chunk-U34CSHFS.js +645 -0
  131. package/bundle/chunk-U34CSHFS.js.map +7 -0
  132. package/bundle/{chunk-CEVRHKJY.js → chunk-UDZIZB5F.js} +6 -5
  133. package/bundle/{chunk-CEVRHKJY.js.map → chunk-UDZIZB5F.js.map} +1 -1
  134. package/bundle/{chunk-W6FAL35D.js → chunk-VA5WKN3Z.js} +7 -6
  135. package/bundle/{chunk-W6FAL35D.js.map → chunk-VA5WKN3Z.js.map} +1 -1
  136. package/bundle/{chunk-X6TERNVJ.js → chunk-WX7GHGFX.js} +10 -9
  137. package/bundle/{chunk-X6TERNVJ.js.map → chunk-WX7GHGFX.js.map} +1 -1
  138. package/bundle/{chunk-PNEDC45Y.js → chunk-XETTJVEU.js} +4 -3
  139. package/bundle/{chunk-PNEDC45Y.js.map → chunk-XETTJVEU.js.map} +1 -1
  140. package/bundle/{chunk-PLCY3GFH.js → chunk-XLLSPBBT.js} +5 -4
  141. package/bundle/{chunk-PLCY3GFH.js.map → chunk-XLLSPBBT.js.map} +1 -1
  142. package/bundle/{chunk-ZXPXCDA6.js → chunk-XOCP5BMO.js} +6 -5
  143. package/bundle/{chunk-ZXPXCDA6.js.map → chunk-XOCP5BMO.js.map} +1 -1
  144. package/bundle/chunk-ZEY6YZAB.js +138 -0
  145. package/bundle/chunk-ZEY6YZAB.js.map +7 -0
  146. package/bundle/{chunk-MW6WDLU7.js → chunk-ZZR3JZHR.js} +10 -9
  147. package/bundle/{chunk-MW6WDLU7.js.map → chunk-ZZR3JZHR.js.map} +1 -1
  148. package/bundle/commands-AIL4XOIZ.js +33 -0
  149. package/bundle/commands-K77NVSXZ.js +32 -0
  150. package/bundle/commands-V6RSVC4Y.js +32 -0
  151. package/bundle/completion-buffer-S3LXDZG2.js +14 -0
  152. package/bundle/config-C6VHRJQ7.js +20 -0
  153. package/bundle/{config-show-ERTATR6E.js → config-show-ZTXX27FW.js} +4 -3
  154. package/bundle/{config-show-ERTATR6E.js.map → config-show-ZTXX27FW.js.map} +1 -1
  155. package/bundle/{context-HCEGZNDC.js → context-OCS7HLJP.js} +5 -4
  156. package/bundle/{context-HCEGZNDC.js.map → context-OCS7HLJP.js.map} +1 -1
  157. package/bundle/daemon-NPKYZ3CJ.js +292 -0
  158. package/bundle/daemon-NPKYZ3CJ.js.map +7 -0
  159. package/bundle/delegation-tools-PF7RD2RW.js +28 -0
  160. package/bundle/{deploy-lib-import-32ZFKHWP.js → deploy-lib-import-ODLDL2DB.js} +5 -4
  161. package/bundle/digital-signature-PNY4TR2W.js +14 -0
  162. package/bundle/{direct-api-transport-YR7SXXNN.js → direct-api-transport-EADHM67Z.js} +21 -20
  163. package/bundle/{direct-api-transport-YR7SXXNN.js.map → direct-api-transport-EADHM67Z.js.map} +1 -1
  164. package/bundle/direct-api-transport-SLJ2Z6NX.js +861 -0
  165. package/bundle/direct-api-transport-SLJ2Z6NX.js.map +7 -0
  166. package/bundle/{discord-adapter-YYWVMPPU.js → discord-adapter-FBJOJSTW.js} +25 -24
  167. package/bundle/{discord-adapter-YYWVMPPU.js.map → discord-adapter-FBJOJSTW.js.map} +1 -1
  168. package/bundle/discord-adapter-IJISVHUE.js +585 -0
  169. package/bundle/discord-adapter-IJISVHUE.js.map +7 -0
  170. package/bundle/discord-adapter-UYOCKRDF.js +586 -0
  171. package/bundle/discord-adapter-UYOCKRDF.js.map +7 -0
  172. package/bundle/{dist-MTMKARCP.js → dist-J3T4XVKX.js} +4 -3
  173. package/bundle/{dist-MTMKARCP.js.map → dist-J3T4XVKX.js.map} +1 -1
  174. package/bundle/{dns-wakeup-27M7D2MR.js → dns-wakeup-RYOCQ6GR.js} +6 -5
  175. package/bundle/{dns-wakeup-27M7D2MR.js.map → dns-wakeup-RYOCQ6GR.js.map} +1 -1
  176. package/bundle/{doctor-QNUSDY73.js → doctor-R54GZPKL.js} +10 -9
  177. package/bundle/{doctor-QNUSDY73.js.map → doctor-R54GZPKL.js.map} +1 -1
  178. package/bundle/{ensure-invariants-NMXNS476.js → ensure-invariants-K2ZUZ6NR.js} +7 -6
  179. package/bundle/{ensure-invariants-NMXNS476.js.map → ensure-invariants-K2ZUZ6NR.js.map} +1 -1
  180. package/bundle/ensure-invariants-KUXIW73S.js +50 -0
  181. package/bundle/ensure-invariants-KUXIW73S.js.map +7 -0
  182. package/bundle/env-schema-DGD6QWPA.js +20 -0
  183. package/bundle/{esm-DDP6NCZG.js → esm-PFOJARXA.js} +5 -4
  184. package/bundle/{esm-DDP6NCZG.js.map → esm-PFOJARXA.js.map} +1 -1
  185. package/bundle/{fallback-policy-L4QV2PEJ.js → fallback-policy-SR6ED5I3.js} +4 -3
  186. package/bundle/{fallback-policy-L4QV2PEJ.js.map → fallback-policy-SR6ED5I3.js.map} +1 -1
  187. package/bundle/{health-check-SPA7NT6N.js → health-check-RJ2SUJYL.js} +4 -3
  188. package/bundle/{health-check-SPA7NT6N.js.map → health-check-RJ2SUJYL.js.map} +1 -1
  189. package/bundle/hook-system-POI5VRIX.js +18 -0
  190. package/bundle/hotskills-6ECHLXTJ.js +13 -0
  191. package/bundle/install-24XR5FO5.js +13 -0
  192. package/bundle/install-AJ7VW76P.js +13 -0
  193. package/bundle/{install-log-IAPHYKD4.js → install-log-Q6RUHKWC.js} +4 -3
  194. package/bundle/{install-log-IAPHYKD4.js.map → install-log-Q6RUHKWC.js.map} +1 -1
  195. package/bundle/{install-manifest-SPQRUNXL.js → install-manifest-MCJCAYSR.js} +9 -7
  196. package/bundle/install-manifest-MCJCAYSR.js.map +7 -0
  197. package/bundle/install-manifest-ZETY4AFS.js +104 -0
  198. package/bundle/install-manifest-ZETY4AFS.js.map +7 -0
  199. package/bundle/{install-validate-PVLZXYLQ.js → install-validate-H74LUCE2.js} +4 -3
  200. package/bundle/{install-validate-PVLZXYLQ.js.map → install-validate-H74LUCE2.js.map} +1 -1
  201. package/bundle/{irc-adapter-OI5UZSQF.js → irc-adapter-RKRUSZXB.js} +7 -6
  202. package/bundle/{irc-adapter-OI5UZSQF.js.map → irc-adapter-RKRUSZXB.js.map} +1 -1
  203. package/bundle/{irc-config-55YO6EGB.js → irc-config-6VY67UPQ.js} +8 -7
  204. package/bundle/{irc-config-55YO6EGB.js.map → irc-config-6VY67UPQ.js.map} +1 -1
  205. package/bundle/{logs-ZNYXX5PA.js → logs-EK4HYRKR.js} +4 -3
  206. package/bundle/{logs-ZNYXX5PA.js.map → logs-EK4HYRKR.js.map} +1 -1
  207. package/bundle/{media-utils-XNNDTYFI.js → media-utils-QBY5WBF3.js} +8 -7
  208. package/bundle/{media-utils-XNNDTYFI.js.map → media-utils-QBY5WBF3.js.map} +1 -1
  209. package/bundle/message-pipeline-ANSMPK5O.js +34 -0
  210. package/bundle/message-pipeline-HXZMRGXZ.js +34 -0
  211. package/bundle/message-pipeline-XUUTGPFH.js +35 -0
  212. package/bundle/meta.json +1828 -1650
  213. package/bundle/model-health-registry-7ECZFCW4.js +12 -0
  214. package/bundle/model-health-registry-LDC76RPP.js +12 -0
  215. package/bundle/notification-OJ4YE4VG.js +14 -0
  216. package/bundle/{openrouter-credits-EDY7ETAU.js → openrouter-credits-L45SYKT3.js} +7 -6
  217. package/bundle/{openrouter-credits-EDY7ETAU.js.map → openrouter-credits-L45SYKT3.js.map} +1 -1
  218. package/bundle/{passwd-RRFV4CC5.js → passwd-QSHZJ2CG.js} +4 -3
  219. package/bundle/{passwd-RRFV4CC5.js.map → passwd-QSHZJ2CG.js.map} +1 -1
  220. package/bundle/paths-ZJYIDND2.js +18 -0
  221. package/bundle/{peer-client-52XYMNI7.js → peer-client-T44VI7NB.js} +13 -12
  222. package/bundle/{peer-client-52XYMNI7.js.map → peer-client-T44VI7NB.js.map} +1 -1
  223. package/bundle/peer-config-D5A4454H.js +17 -0
  224. package/bundle/{peer-sessions-EAXTNQ36.js → peer-sessions-MY2YVXHC.js} +4 -3
  225. package/bundle/{peer-sessions-EAXTNQ36.js.map → peer-sessions-MY2YVXHC.js.map} +1 -1
  226. package/bundle/{pending-callback-RIMQZ7FJ.js → pending-callback-6KLBSHLX.js} +4 -3
  227. package/bundle/{pending-callback-RIMQZ7FJ.js.map → pending-callback-6KLBSHLX.js.map} +1 -1
  228. package/bundle/phase-transport-43NP5XBK.js +23 -0
  229. package/bundle/phase-transport-GNUZI6EW.js +23 -0
  230. package/bundle/phase-transport-Q7K6V3VZ.js +23 -0
  231. package/bundle/phase-transport-SLJXIAY5.js +23 -0
  232. package/bundle/{responses-adapter-AAQTY3K4.js → responses-adapter-DAV2JUL7.js} +4 -3
  233. package/bundle/{responses-adapter-AAQTY3K4.js.map → responses-adapter-DAV2JUL7.js.map} +1 -1
  234. package/bundle/{restore-ZE3SEPSS.js → restore-ROJF22R2.js} +5 -4
  235. package/bundle/{restore-ZE3SEPSS.js.map → restore-ROJF22R2.js.map} +1 -1
  236. package/bundle/{self-healer-utils-DMUUXC47.js → self-healer-utils-7NFH22VJ.js} +7 -6
  237. package/bundle/{self-healer-utils-DMUUXC47.js.map → self-healer-utils-7NFH22VJ.js.map} +1 -1
  238. package/bundle/skill-stats-IPVKMWN3.js +23 -0
  239. package/bundle/sleep-4NVWZHVN.js +20 -0
  240. package/bundle/soul-bundle-7EYTEKFE.js +15 -0
  241. package/bundle/soul-loader-7FN7WDHM.js +18 -0
  242. package/bundle/soul-loader-K237NP4T.js +17 -0
  243. package/bundle/soul-loader-K237NP4T.js.map +7 -0
  244. package/bundle/soul-loader-UVJ6HZM3.js +17 -0
  245. package/bundle/soul-loader-UVJ6HZM3.js.map +7 -0
  246. package/bundle/src-Z3WR7SRT.js +9 -0
  247. package/bundle/src-Z3WR7SRT.js.map +7 -0
  248. package/bundle/{sse-parser-anthropic-P7CE2MH2.js → sse-parser-anthropic-H42TTLBD.js} +7 -6
  249. package/bundle/{sse-parser-anthropic-P7CE2MH2.js.map → sse-parser-anthropic-H42TTLBD.js.map} +1 -1
  250. package/bundle/{sse-parser-responses-EQQA5FWN.js → sse-parser-responses-WG2LY2ML.js} +7 -6
  251. package/bundle/{sse-parser-responses-EQQA5FWN.js.map → sse-parser-responses-WG2LY2ML.js.map} +1 -1
  252. package/bundle/{ssrf-guard-FZCBYIVW.js → ssrf-guard-E2KBBC5E.js} +7 -6
  253. package/bundle/{ssrf-guard-FZCBYIVW.js.map → ssrf-guard-E2KBBC5E.js.map} +1 -1
  254. package/bundle/{start-FH3GRMJ4.js → start-4IWBKLWO.js} +4 -3
  255. package/bundle/{start-FH3GRMJ4.js.map → start-4IWBKLWO.js.map} +1 -1
  256. package/bundle/{stream-single-WSG4D53C.js → stream-single-RFJNUTL6.js} +4 -3
  257. package/bundle/{stream-single-WSG4D53C.js.map → stream-single-RFJNUTL6.js.map} +1 -1
  258. package/bundle/stt-CF3CPFDC.js +15 -0
  259. package/bundle/stt-CF3CPFDC.js.map +7 -0
  260. package/bundle/subagent-runtime-P7GCFBM3.js +13 -0
  261. package/bundle/subagent-runtime-P7GCFBM3.js.map +7 -0
  262. package/bundle/subagent-runtime-USNPO4WF.js +13 -0
  263. package/bundle/subagent-runtime-USNPO4WF.js.map +7 -0
  264. package/bundle/subagent-runtime-XS2ZXYOZ.js +13 -0
  265. package/bundle/subagent-runtime-XS2ZXYOZ.js.map +7 -0
  266. package/bundle/{system-message-T5R3EYYN.js → system-message-TALP6GP2.js} +6 -5
  267. package/bundle/{system-message-T5R3EYYN.js.map → system-message-TALP6GP2.js.map} +1 -1
  268. package/bundle/{system-status-KQ6KHFJ6.js → system-status-2CR5OUDY.js} +10 -9
  269. package/bundle/{system-status-KQ6KHFJ6.js.map → system-status-2CR5OUDY.js.map} +1 -1
  270. package/bundle/task-store-KIBFZL5A.js +23 -0
  271. package/bundle/task-store-KIBFZL5A.js.map +7 -0
  272. package/bundle/{telegram-adapter-2V3XUMT5.js → telegram-adapter-ISQRW7PN.js} +34 -33
  273. package/bundle/{telegram-adapter-2V3XUMT5.js.map → telegram-adapter-ISQRW7PN.js.map} +1 -1
  274. package/bundle/telegram-adapter-QCD7AG5D.js +1062 -0
  275. package/bundle/telegram-adapter-QCD7AG5D.js.map +7 -0
  276. package/bundle/telegram-adapter-Y3PVA25S.js +1061 -0
  277. package/bundle/telegram-adapter-Y3PVA25S.js.map +7 -0
  278. package/bundle/telegram-adapter-YAXSK2RT.js +1062 -0
  279. package/bundle/telegram-adapter-YAXSK2RT.js.map +7 -0
  280. package/bundle/tool-registry-DFCCGZCB.js +39 -0
  281. package/bundle/tool-registry-DFCCGZCB.js.map +7 -0
  282. package/bundle/tool-sandbox-OZMXJZLQ.js +21 -0
  283. package/bundle/tool-sandbox-OZMXJZLQ.js.map +7 -0
  284. package/bundle/{transport-config-YLXU33RO.js → transport-config-ANPS2RYT.js} +11 -10
  285. package/bundle/transport-config-ANPS2RYT.js.map +7 -0
  286. package/bundle/update-check-O5MS6B3L.js +13 -0
  287. package/bundle/update-check-O5MS6B3L.js.map +7 -0
  288. package/bundle/usage-tracker-S4Z2G2K5.js +18 -0
  289. package/bundle/usage-tracker-S4Z2G2K5.js.map +7 -0
  290. package/bundle/user-registry-GTAJIW6E.js +17 -0
  291. package/bundle/user-registry-GTAJIW6E.js.map +7 -0
  292. package/config/.env +2 -0
  293. package/config/auto-fix.json +14 -0
  294. package/config/irc.json.example +30 -0
  295. package/config/models.json.example +229 -0
  296. package/config/peers.json.example +12 -0
  297. package/config/schemas/irc.schema.json +42 -0
  298. package/config/schemas/models.schema.json +17 -0
  299. package/config/schemas/peers.schema.json +35 -0
  300. package/config/schemas/transport.schema.json +35 -0
  301. package/config/schemas/users.schema.json +22 -0
  302. package/config/transport.default.json +30 -0
  303. package/config/transport.json.example +102 -0
  304. package/config/users.json.example +11 -0
  305. package/install-manifest.json +148 -0
  306. package/package.json +4 -2
  307. package/scripts/abtars-daemon.service +1 -0
  308. package/scripts/watchdog.sh +1 -1
  309. package/bundle/_registry.generated-M4WY2MMI.js +0 -35
  310. package/bundle/agent-registry-LT4JNQH6.js +0 -18
  311. package/bundle/browse-delivery-JXBY36GK.js +0 -17
  312. package/bundle/browser-ELNDVPLC.js +0 -18
  313. package/bundle/capability-CIL3G4FI.js +0 -17
  314. package/bundle/chunk-5R2ANXQ7.js +0 -510
  315. package/bundle/chunk-5R2ANXQ7.js.map +0 -7
  316. package/bundle/chunk-6UCRKRWR.js.map +0 -7
  317. package/bundle/chunk-M6VBAPNT.js +0 -16
  318. package/bundle/chunk-OP7BTAWY.js +0 -29
  319. package/bundle/chunk-UCQ2WC3B.js.map +0 -7
  320. package/bundle/chunk-XREWVCUO.js.map +0 -7
  321. package/bundle/chunk-Y6XAEX2Q.js.map +0 -7
  322. package/bundle/commands-BHVUOU3V.js +0 -31
  323. package/bundle/completion-buffer-P253ONKF.js +0 -13
  324. package/bundle/config-RGSDAPZN.js +0 -19
  325. package/bundle/delegation-tools-GYTS2D6A.js +0 -27
  326. package/bundle/digital-signature-OFCGSHWO.js +0 -13
  327. package/bundle/env-schema-2KBHBDGN.js +0 -19
  328. package/bundle/hook-system-6Q5YTR53.js +0 -17
  329. package/bundle/hotskills-K7BM4YLB.js +0 -12
  330. package/bundle/install-6HRZVKUM.js +0 -15
  331. package/bundle/install-manifest-SPQRUNXL.js.map +0 -7
  332. package/bundle/message-pipeline-LLH5SYMO.js +0 -33
  333. package/bundle/model-health-registry-35LQNVQR.js +0 -11
  334. package/bundle/notification-Y5S5MMLV.js +0 -13
  335. package/bundle/paths-G33RZWZ7.js +0 -17
  336. package/bundle/peer-config-VK6EDLN5.js +0 -16
  337. package/bundle/phase-transport-KYERDL2O.js +0 -22
  338. package/bundle/skill-stats-LLEXEXLR.js +0 -22
  339. package/bundle/sleep-OYIUOVQD.js +0 -19
  340. package/bundle/soul-loader-54WCVNLJ.js +0 -16
  341. package/bundle/src-JL4PVO23.js +0 -8
  342. package/bundle/stt-2UH3RITX.js +0 -14
  343. package/bundle/subagent-runtime-LE2ZXH3G.js +0 -12
  344. package/bundle/task-store-K7CQDEPI.js +0 -22
  345. package/bundle/tool-registry-MU3OX4UI.js +0 -38
  346. package/bundle/tool-sandbox-VYOK4ZOA.js +0 -20
  347. package/bundle/update-QCW5LXRN.js +0 -13
  348. package/bundle/update-check-27KZSAP6.js +0 -12
  349. package/bundle/usage-tracker-OVVEVMOY.js +0 -17
  350. package/bundle/user-registry-D4SD73UV.js +0 -16
  351. /package/bundle/{agent-registry-LT4JNQH6.js.map → agent-registry-5M77ZOMV.js.map} +0 -0
  352. /package/bundle/{bridge-lock-transport-4AC2G5G6.js.map → agent-registry-VJMNIQ5W.js.map} +0 -0
  353. /package/bundle/{browse-delivery-JXBY36GK.js.map → bridge-lock-transport-HO545SBK.js.map} +0 -0
  354. /package/bundle/{browser-ELNDVPLC.js.map → browse-delivery-64GQIUHG.js.map} +0 -0
  355. /package/bundle/{capability-CIL3G4FI.js.map → browser-EXR5OQGK.js.map} +0 -0
  356. /package/bundle/{chunk-NWDBD4PA.js.map → capability-HIE7UGFU.js.map} +0 -0
  357. /package/bundle/{commands-BHVUOU3V.js.map → chunk-7K2YZTLD.js.map} +0 -0
  358. /package/bundle/{completion-buffer-P253ONKF.js.map → commands-AIL4XOIZ.js.map} +0 -0
  359. /package/bundle/{config-RGSDAPZN.js.map → commands-K77NVSXZ.js.map} +0 -0
  360. /package/bundle/{delegation-tools-GYTS2D6A.js.map → commands-V6RSVC4Y.js.map} +0 -0
  361. /package/bundle/{deploy-lib-import-32ZFKHWP.js.map → completion-buffer-S3LXDZG2.js.map} +0 -0
  362. /package/bundle/{digital-signature-OFCGSHWO.js.map → config-C6VHRJQ7.js.map} +0 -0
  363. /package/bundle/{env-schema-2KBHBDGN.js.map → delegation-tools-PF7RD2RW.js.map} +0 -0
  364. /package/bundle/{hook-system-6Q5YTR53.js.map → deploy-lib-import-ODLDL2DB.js.map} +0 -0
  365. /package/bundle/{hotskills-K7BM4YLB.js.map → digital-signature-PNY4TR2W.js.map} +0 -0
  366. /package/bundle/{install-6HRZVKUM.js.map → env-schema-DGD6QWPA.js.map} +0 -0
  367. /package/bundle/{message-pipeline-LLH5SYMO.js.map → hook-system-POI5VRIX.js.map} +0 -0
  368. /package/bundle/{model-health-registry-35LQNVQR.js.map → hotskills-6ECHLXTJ.js.map} +0 -0
  369. /package/bundle/{notification-Y5S5MMLV.js.map → install-24XR5FO5.js.map} +0 -0
  370. /package/bundle/{paths-G33RZWZ7.js.map → install-AJ7VW76P.js.map} +0 -0
  371. /package/bundle/{peer-config-VK6EDLN5.js.map → message-pipeline-ANSMPK5O.js.map} +0 -0
  372. /package/bundle/{phase-transport-KYERDL2O.js.map → message-pipeline-HXZMRGXZ.js.map} +0 -0
  373. /package/bundle/{skill-stats-LLEXEXLR.js.map → message-pipeline-XUUTGPFH.js.map} +0 -0
  374. /package/bundle/{sleep-OYIUOVQD.js.map → model-health-registry-7ECZFCW4.js.map} +0 -0
  375. /package/bundle/{soul-loader-54WCVNLJ.js.map → model-health-registry-LDC76RPP.js.map} +0 -0
  376. /package/bundle/{src-JL4PVO23.js.map → notification-OJ4YE4VG.js.map} +0 -0
  377. /package/bundle/{stt-2UH3RITX.js.map → paths-ZJYIDND2.js.map} +0 -0
  378. /package/bundle/{subagent-runtime-LE2ZXH3G.js.map → peer-config-D5A4454H.js.map} +0 -0
  379. /package/bundle/{task-store-K7CQDEPI.js.map → phase-transport-43NP5XBK.js.map} +0 -0
  380. /package/bundle/{tool-registry-MU3OX4UI.js.map → phase-transport-GNUZI6EW.js.map} +0 -0
  381. /package/bundle/{tool-sandbox-VYOK4ZOA.js.map → phase-transport-Q7K6V3VZ.js.map} +0 -0
  382. /package/bundle/{transport-config-YLXU33RO.js.map → phase-transport-SLJXIAY5.js.map} +0 -0
  383. /package/bundle/{update-QCW5LXRN.js.map → skill-stats-IPVKMWN3.js.map} +0 -0
  384. /package/bundle/{update-check-27KZSAP6.js.map → sleep-4NVWZHVN.js.map} +0 -0
  385. /package/bundle/{usage-tracker-OVVEVMOY.js.map → soul-bundle-7EYTEKFE.js.map} +0 -0
  386. /package/bundle/{user-registry-D4SD73UV.js.map → soul-loader-7FN7WDHM.js.map} +0 -0
@@ -0,0 +1,861 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __bundleCreateRequire } from 'node:module'; import { fileURLToPath as __bundleFileURLToPath } from 'node:url'; import { dirname as __bundleDirname } from 'node:path'; const require = __bundleCreateRequire(import.meta.url); const __chunk_filename = __bundleFileURLToPath(import.meta.url); const __chunk_dirname = __bundleDirname(__chunk_filename);
3
+ import {
4
+ classifyError
5
+ } from "./chunk-ZEY6YZAB.js";
6
+ import {
7
+ recordUsage
8
+ } from "./chunk-OW64RUE5.js";
9
+ import {
10
+ executeToolCall,
11
+ getToolSchemas
12
+ } from "./chunk-JU3UBWLN.js";
13
+ import "./chunk-JAJ3DUQ2.js";
14
+ import "./chunk-JRG4EFMP.js";
15
+ import "./chunk-ELRAH7VL.js";
16
+ import "./chunk-L7YHV5DL.js";
17
+ import "./chunk-MV6CJFWR.js";
18
+ import {
19
+ init_log_and_swallow,
20
+ logAndSwallow
21
+ } from "./chunk-EX2SRTUE.js";
22
+ import {
23
+ getEnv,
24
+ init_env_schema
25
+ } from "./chunk-AQVOAQQI.js";
26
+ import {
27
+ init_logger,
28
+ logDebug,
29
+ logInfo,
30
+ logTrace,
31
+ logWarn
32
+ } from "./chunk-2BY6I4P5.js";
33
+ import "./chunk-MJ6PHMOK.js";
34
+ import "./chunk-7K2YZTLD.js";
35
+
36
+ // src/components/transport/direct-api-transport.ts
37
+ init_env_schema();
38
+ init_logger();
39
+ init_log_and_swallow();
40
+
41
+ // src/components/retry.ts
42
+ var DEFAULTS = { attempts: 3, minDelayMs: 300, maxDelayMs: 3e4, jitter: 0.1 };
43
+ var FATAL_PATTERNS = [
44
+ /auth.*fail|invalid.*key|unauthorized/i,
45
+ /model.*not found|not supported/i,
46
+ /account.*suspended|quota.*exceeded/i,
47
+ /bot was blocked/i
48
+ ];
49
+ function isFatal(err) {
50
+ const msg = err instanceof Error ? err.message : String(err);
51
+ return FATAL_PATTERNS.some((p) => p.test(msg));
52
+ }
53
+ async function withRetry(fn, policy) {
54
+ const attempts = Math.max(1, policy?.attempts ?? DEFAULTS.attempts);
55
+ const minDelay = Math.max(0, policy?.minDelayMs ?? DEFAULTS.minDelayMs);
56
+ const maxDelay = Math.max(minDelay, policy?.maxDelayMs ?? DEFAULTS.maxDelayMs);
57
+ const jitter = Math.max(0, Math.min(1, policy?.jitter ?? DEFAULTS.jitter));
58
+ const isRecoverable = policy?.isRecoverable ?? ((err) => !isFatal(err));
59
+ let lastErr;
60
+ for (let i = 0; i < attempts; i++) {
61
+ try {
62
+ return await fn();
63
+ } catch (err) {
64
+ lastErr = err;
65
+ if (i === attempts - 1) break;
66
+ if (!isRecoverable(err)) break;
67
+ const hint = policy?.getDelayHint?.(err);
68
+ const baseDelay = hint ?? Math.min(maxDelay, minDelay * Math.pow(2, i));
69
+ const offset = jitter > 0 ? (Math.random() * 2 - 1) * jitter * baseDelay : 0;
70
+ const delayMs = Math.max(0, Math.round(baseDelay + offset));
71
+ policy?.onAttempt?.({ attempt: i + 1, maxAttempts: attempts, err, delayMs });
72
+ await new Promise((r) => setTimeout(r, delayMs));
73
+ }
74
+ }
75
+ throw lastErr;
76
+ }
77
+
78
+ // src/components/transport/conversation-session.ts
79
+ var ConversationSession = class {
80
+ messages = [];
81
+ totalPromptTokens = 0;
82
+ maxContext;
83
+ constructor(systemPrompt, maxContext) {
84
+ this.maxContext = maxContext;
85
+ this.messages.push({ role: "system", content: systemPrompt });
86
+ }
87
+ addUser(content, image) {
88
+ if (image) {
89
+ this.messages.push({ role: "user", content: [
90
+ { type: "image_url", image_url: { url: `data:${image.mime};base64,${image.base64}` } },
91
+ { type: "text", text: content }
92
+ ] });
93
+ } else {
94
+ this.messages.push({ role: "user", content });
95
+ }
96
+ }
97
+ addAssistant(content, toolCalls) {
98
+ const msg = { role: "assistant", content };
99
+ if (toolCalls?.length) msg.tool_calls = toolCalls;
100
+ this.messages.push(msg);
101
+ }
102
+ addToolResult(toolCallId, name, content) {
103
+ this.messages.push({ role: "tool", content, tool_call_id: toolCallId, name });
104
+ }
105
+ updateTokens(promptTokens) {
106
+ this.totalPromptTokens = promptTokens;
107
+ }
108
+ get contextPercent() {
109
+ if (this.maxContext <= 0) return 0;
110
+ return Math.round(this.totalPromptTokens / this.maxContext * 100);
111
+ }
112
+ reset(systemPrompt) {
113
+ this.messages = [{ role: "system", content: systemPrompt }];
114
+ this.totalPromptTokens = 0;
115
+ }
116
+ /** Roll back to last user message — remove everything after it for clean fallback. */
117
+ rollbackToLastUser() {
118
+ for (let i = this.messages.length - 1; i >= 0; i--) {
119
+ if (this.messages[i].role === "user") {
120
+ this.messages.splice(i + 1);
121
+ return;
122
+ }
123
+ }
124
+ }
125
+ /** Rough token estimate: ~4 chars per token. */
126
+ estimateTokens() {
127
+ return Math.round(this.messages.reduce((sum, m) => sum + (typeof m.content === "string" ? m.content.length : 0), 0) / 4);
128
+ }
129
+ /** Drop oldest non-system messages until estimated tokens fit within limit. */
130
+ truncateToFit(maxTokens) {
131
+ while (this.messages.length > 2 && this.estimateTokens() > maxTokens * 0.85) {
132
+ this.messages.splice(1, 1);
133
+ }
134
+ this.totalPromptTokens = this.estimateTokens();
135
+ }
136
+ /** #621: Replace a literal secret value with [REDACTED] across all messages. */
137
+ scrubFromHistory(value) {
138
+ for (const msg of this.messages) {
139
+ if (typeof msg.content === "string" && msg.content.includes(value)) {
140
+ msg.content = msg.content.replaceAll(value, "[REDACTED]");
141
+ }
142
+ }
143
+ }
144
+ };
145
+
146
+ // src/components/transport/sse-parser.ts
147
+ init_log_and_swallow();
148
+ var TAG = "sse_parser";
149
+ var STALE_TIMEOUT_MS = 9e4;
150
+ async function* parseSSEStream(response, signal) {
151
+ const reader = response.body?.getReader();
152
+ if (!reader) throw new Error("Response body is not readable");
153
+ const decoder = new TextDecoder();
154
+ let buffer = "";
155
+ let lastChunkAt = Date.now();
156
+ let staleTimer = null;
157
+ const resetStaleTimer = () => {
158
+ lastChunkAt = Date.now();
159
+ if (staleTimer) clearTimeout(staleTimer);
160
+ staleTimer = setTimeout(() => {
161
+ if (Date.now() - lastChunkAt >= STALE_TIMEOUT_MS) {
162
+ reader.cancel("stale stream").catch((err) => logAndSwallow(TAG, "reader.cancel stale", err));
163
+ }
164
+ }, STALE_TIMEOUT_MS);
165
+ };
166
+ try {
167
+ resetStaleTimer();
168
+ while (true) {
169
+ if (signal.aborted) break;
170
+ const { done, value } = await reader.read();
171
+ if (done) break;
172
+ resetStaleTimer();
173
+ buffer += decoder.decode(value, { stream: true });
174
+ const lines = buffer.split("\n");
175
+ buffer = lines.pop() ?? "";
176
+ for (const line of lines) {
177
+ if (!line.startsWith("data: ")) continue;
178
+ const data = line.slice(6).trim();
179
+ if (data === "[DONE]") return;
180
+ let parsed;
181
+ try {
182
+ parsed = JSON.parse(data);
183
+ } catch (err) {
184
+ logAndSwallow(TAG, "JSON.parse SSE chunk", err);
185
+ continue;
186
+ }
187
+ if (parsed["usage"]) {
188
+ const u = parsed["usage"];
189
+ yield { type: "done", usage: { prompt_tokens: u["prompt_tokens"] ?? 0, completion_tokens: u["completion_tokens"] ?? 0 } };
190
+ }
191
+ const choices = parsed["choices"];
192
+ if (!choices?.length) continue;
193
+ const delta = choices[0]["delta"];
194
+ if (!delta) continue;
195
+ if (typeof delta["content"] === "string" && delta["content"]) {
196
+ yield { type: "chunk", content: delta["content"] };
197
+ }
198
+ const toolCalls = delta["tool_calls"];
199
+ if (toolCalls) {
200
+ for (const tc of toolCalls) {
201
+ const fn = tc["function"];
202
+ yield {
203
+ type: "tool_call_delta",
204
+ index: tc["index"] ?? 0,
205
+ id: tc["id"],
206
+ name: fn?.["name"],
207
+ arguments: fn?.["arguments"]
208
+ };
209
+ }
210
+ }
211
+ }
212
+ }
213
+ } finally {
214
+ if (staleTimer) clearTimeout(staleTimer);
215
+ reader.releaseLock();
216
+ }
217
+ }
218
+
219
+ // src/components/transport/transport-utils.ts
220
+ init_logger();
221
+ var TAG2 = "direct-api";
222
+ function normalizeToolCalls(raw) {
223
+ if (raw.length <= 1) return raw;
224
+ const result = [];
225
+ for (let i = 0; i < raw.length; i++) {
226
+ const tc = raw[i];
227
+ if (tc.function.name) {
228
+ if (!tc.function.arguments || tc.function.arguments === "{}") {
229
+ for (let j = i + 1; j < raw.length; j++) {
230
+ const next = raw[j];
231
+ if (next.function.name) break;
232
+ if (next.function.arguments && next.function.arguments !== "{}") {
233
+ tc.function.arguments = next.function.arguments;
234
+ i = j;
235
+ break;
236
+ }
237
+ }
238
+ }
239
+ result.push(tc);
240
+ }
241
+ }
242
+ if (result.length !== raw.length) {
243
+ logWarn(TAG2, `Normalized ${raw.length} tool call entries \u2192 ${result.length} (model fragmentation): ${raw.map((tc) => `${tc.function.name || "(unnamed)"}(${tc.function.arguments.slice(0, 60)})`).join(", ")}`);
244
+ }
245
+ return result;
246
+ }
247
+ function parseErrorStatus(err) {
248
+ const msg = err instanceof Error ? err.message : String(err);
249
+ const m = /API error (\d+)/.exec(msg);
250
+ return m ? parseInt(m[1], 10) : 0;
251
+ }
252
+ function parseRetryAfter(err) {
253
+ const msg = err instanceof Error ? err.message : String(err);
254
+ const jsonMatch = /retry[_-]after["\s:]+(\d+(?:\.\d+)?)/i.exec(msg);
255
+ if (jsonMatch) return Math.ceil(parseFloat(jsonMatch[1]) * 1e3);
256
+ const resetMatch = /x-ratelimit-reset["\s:]+(\d{10,13})/i.exec(msg);
257
+ if (resetMatch) {
258
+ const ts = parseInt(resetMatch[1], 10);
259
+ const ms = ts < 1e12 ? ts * 1e3 : ts;
260
+ const delta = ms - Date.now();
261
+ return delta > 0 ? delta : void 0;
262
+ }
263
+ return void 0;
264
+ }
265
+ function parseUsageLimitCooldown(message) {
266
+ const lower = message.toLowerCase();
267
+ if (!lower.includes("limit")) return void 0;
268
+ if (lower.includes("day")) {
269
+ const tomorrow = /* @__PURE__ */ new Date();
270
+ tomorrow.setDate(tomorrow.getDate() + 1);
271
+ tomorrow.setHours(0, 0, 0, 0);
272
+ return tomorrow.getTime() - Date.now();
273
+ }
274
+ if (lower.includes("week")) {
275
+ const now = /* @__PURE__ */ new Date();
276
+ const daysUntilMonday = (8 - now.getDay()) % 7 || 7;
277
+ const monday = new Date(now);
278
+ monday.setDate(monday.getDate() + daysUntilMonday);
279
+ monday.setHours(0, 0, 0, 0);
280
+ return monday.getTime() - Date.now();
281
+ }
282
+ if (lower.includes("month")) {
283
+ const now = /* @__PURE__ */ new Date();
284
+ const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
285
+ return nextMonth.getTime() - Date.now();
286
+ }
287
+ return void 0;
288
+ }
289
+
290
+ // src/components/transport/direct-api-transport.ts
291
+ var TAG3 = "direct-api";
292
+ var DirectApiTransport = class {
293
+ config;
294
+ sessions = /* @__PURE__ */ new Map();
295
+ abortControllers = /* @__PURE__ */ new Map();
296
+ systemPrompt = "";
297
+ _contextPercent = -1;
298
+ _lastAnswer = "";
299
+ _timeoutOverrideMs = null;
300
+ _toolCallsSucceeded = 0;
301
+ _intermediateText = "";
302
+ _promptStartedAt = null;
303
+ _lastActivityAt = null;
304
+ activeEndpoint;
305
+ activeApiKey;
306
+ activeModel;
307
+ _lastPromptTokens = 0;
308
+ _activeSessionKey = "";
309
+ _activeUserId = "master";
310
+ /** Currently active model (may differ from config if on fallback). */
311
+ get currentModel() {
312
+ return this.activeModel;
313
+ }
314
+ onIntermediateResponse;
315
+ onToolCallStart;
316
+ onSegmentBreak;
317
+ /** Sandbox policy for tool access control (#681). Set by pipeline before prompt. */
318
+ sandboxPolicy;
319
+ /** Called when fallback model is selected — send notification before response. */
320
+ onFallback;
321
+ /** Cooperative pause check — if returns true, agent loop breaks between tool calls. */
322
+ isPaused;
323
+ /** Returns a pending instruction from parent, if any. Consumed once. */
324
+ getPendingInstruction;
325
+ /** Context orchestrator — when set, messages are built from DB instead of in-memory session. */
326
+ contextOrchestrator;
327
+ policy;
328
+ emergencyOverride = null;
329
+ /** Activate emergency (hailMary) mode — next prompts bypass the fallback policy. */
330
+ setEmergencyMode(override) {
331
+ if (!override && !this.emergencyOverride) return;
332
+ this.emergencyOverride = override;
333
+ if (override) logWarn(TAG3, `\u{1F6A8} EMERGENCY MODE: using ${override.model} (paid) \u2014 bypassing fallback chain`);
334
+ else {
335
+ this.activeModel = this.config.model;
336
+ logInfo(TAG3, `Emergency mode cleared \u2014 restored ${this.config.model}`);
337
+ }
338
+ }
339
+ /** True if emergency (hailMary) mode is active. */
340
+ get isEmergencyMode() {
341
+ return this.emergencyOverride !== null;
342
+ }
343
+ constructor(config, policy) {
344
+ this.config = config;
345
+ this.activeEndpoint = config.endpoint;
346
+ this.activeApiKey = config.apiKey;
347
+ this.activeModel = config.model;
348
+ this.policy = policy ?? null;
349
+ }
350
+ async initialize() {
351
+ const count = this.policy ? this.policy.candidates.length : (this.config.fallbacks?.length ?? 0) + 1;
352
+ const fb = count > 1 ? ` (+${count - 1} fallback${count > 2 ? "s" : ""})` : "";
353
+ logInfo(TAG3, `\u{1F50C} Direct API transport (${this.config.endpoint}, model: ${this.config.model}${fb})`);
354
+ }
355
+ setSystemPrompt(prompt) {
356
+ this.systemPrompt = prompt;
357
+ }
358
+ async sendPrompt(sessionKey, message, image, userId) {
359
+ const session = this.getOrCreateSession(sessionKey);
360
+ this._activeSessionKey = sessionKey;
361
+ this._activeUserId = userId || "master";
362
+ if (this.contextOrchestrator) {
363
+ try {
364
+ const ctx = await this.contextOrchestrator.getContext(sessionKey, this.config.maxContext);
365
+ session.messages = [
366
+ { role: "system", content: this.systemPrompt },
367
+ ...ctx.messages.map((m) => ({ role: m.role, content: m.content }))
368
+ ];
369
+ if (ctx.compacted) logDebug(TAG3, `Context compacted for ${sessionKey}`);
370
+ } catch (err) {
371
+ logWarn(TAG3, `Context engine failed, falling back to in-memory: ${err}`);
372
+ }
373
+ }
374
+ session.addUser(message, image);
375
+ this._lastAnswer = "";
376
+ this._toolCallsSucceeded = 0;
377
+ this._intermediateText = "";
378
+ this._promptStartedAt = Date.now();
379
+ this._lastActivityAt = Date.now();
380
+ const ac = new AbortController();
381
+ this.abortControllers.set(sessionKey, ac);
382
+ try {
383
+ if (this.emergencyOverride) return await this.sendEmergency(session, ac.signal);
384
+ if (!this.policy) throw new Error("DirectApiTransport requires a FallbackPolicy");
385
+ return await this.sendWithPolicy(session, ac.signal);
386
+ } finally {
387
+ const durationMs = Date.now() - (this._promptStartedAt ?? Date.now());
388
+ import("./hook-system-POI5VRIX.js").then(({ hasHooks, fire }) => {
389
+ if (!hasHooks("AfterPrompt")) return;
390
+ fire("AfterPrompt", {
391
+ event: "AfterPrompt",
392
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
393
+ sessionKey,
394
+ platform: "",
395
+ userId: "",
396
+ model: this.activeModel,
397
+ durationMs,
398
+ inputTokens: this._lastPromptTokens || null,
399
+ outputTokens: null
400
+ // not tracked per-prompt in DirectApi
401
+ }).catch((err) => logAndSwallow(TAG3, "fire AfterPrompt", err));
402
+ }).catch((err) => logAndSwallow(TAG3, "import hook-system", err));
403
+ this._promptStartedAt = null;
404
+ this.abortControllers.delete(sessionKey);
405
+ }
406
+ }
407
+ async sendEmergency(session, signal) {
408
+ const em = this.emergencyOverride;
409
+ this.activeEndpoint = em.endpoint;
410
+ this.activeApiKey = em.apiKey;
411
+ this.activeModel = em.model;
412
+ this._lastActivityAt = Date.now();
413
+ logWarn(TAG3, `\u{1F6A8} Emergency mode: using ${em.model}`);
414
+ const result = await this.agentLoop(session, signal);
415
+ this._lastAnswer = result;
416
+ return result;
417
+ }
418
+ async sendWithPolicy(session, signal) {
419
+ const policy = this.policy;
420
+ const failedAttempts = [];
421
+ const isPrimary = (m) => m === this.config.model;
422
+ let candidate = policy.selectModel(this._lastPromptTokens);
423
+ while (candidate) {
424
+ this.activeEndpoint = candidate.endpoint;
425
+ this.activeApiKey = candidate.apiKey;
426
+ this.activeModel = candidate.model;
427
+ this._lastActivityAt = Date.now();
428
+ logDebug(TAG3, `Trying model: ${candidate.model}`);
429
+ if (!isPrimary(candidate.model) && this.onFallback) {
430
+ const ctxPct = candidate.maxContext > 0 ? Math.round(this._lastPromptTokens / candidate.maxContext * 100) : -1;
431
+ const lastFail = failedAttempts[failedAttempts.length - 1];
432
+ this.onFallback(candidate.model, ctxPct, lastFail?.kind);
433
+ }
434
+ try {
435
+ const result = await this.agentLoop(session, signal);
436
+ this._lastAnswer = result;
437
+ if (!result || !result.trim()) {
438
+ policy.recordError(candidate, "empty");
439
+ } else {
440
+ policy.recordSuccess(candidate);
441
+ }
442
+ return result;
443
+ } catch (err) {
444
+ if (signal.aborted) {
445
+ session.rollbackToLastUser();
446
+ throw err;
447
+ }
448
+ const errMsg = err instanceof Error ? err.message : String(err);
449
+ if (errMsg.includes("does not support image input") || errMsg.includes("No endpoints found that support image")) {
450
+ session.rollbackToLastUser();
451
+ for (const m of session.messages) {
452
+ if (Array.isArray(m.content)) {
453
+ const textParts = m.content.filter((p) => p.type === "text");
454
+ m.content = textParts.map((p) => p.text ?? "").join("\n") || "User sent an image (not supported by this model).";
455
+ }
456
+ }
457
+ logWarn(TAG3, `${candidate.model} doesn't support images \u2014 retrying text-only`);
458
+ if (this.onIntermediateResponse) this.onIntermediateResponse("\u26A0\uFE0F Model doesn't support images via this provider. Sending text-only.\n");
459
+ try {
460
+ const result = await this.agentLoop(session, signal);
461
+ this._lastAnswer = result;
462
+ policy.recordSuccess(candidate);
463
+ return result;
464
+ } catch (retryErr) {
465
+ const retryStatus = this.parseErrorStatus(retryErr);
466
+ const retryMsg = retryErr instanceof Error ? retryErr.message : String(retryErr);
467
+ policy.recordError(candidate, classifyError(retryStatus, retryMsg));
468
+ session.rollbackToLastUser();
469
+ throw retryErr;
470
+ }
471
+ }
472
+ const status = this.parseErrorStatus(err);
473
+ const kind = classifyError(status, errMsg);
474
+ const retryAfterMs = this.parseRetryAfter(err) ?? parseUsageLimitCooldown(errMsg);
475
+ policy.recordError(candidate, kind, retryAfterMs);
476
+ const bucket = policy.registry.getBucketLevel(candidate.model, candidate.endpoint);
477
+ failedAttempts.push({ model: candidate.model, kind, bucket });
478
+ session.rollbackToLastUser();
479
+ logWarn(TAG3, `${candidate.model} failed (${kind}, bucket: ${bucket}%${retryAfterMs ? `, retry-after: ${Math.round(retryAfterMs / 1e3)}s` : ""}): ${errMsg.slice(0, 100)}`);
480
+ }
481
+ candidate = policy.selectModel(this._lastPromptTokens);
482
+ }
483
+ const surviving = policy.survivingCandidates().filter((c) => c.maxContext > 0).sort((a, b) => a.maxContext - b.maxContext);
484
+ const smallest = surviving[0];
485
+ if (smallest && this._lastPromptTokens > smallest.maxContext * 0.95) {
486
+ logWarn(TAG3, `Compacting session to fit ${smallest.model} (${smallest.maxContext} tokens)`);
487
+ session.truncateToFit(smallest.maxContext);
488
+ this.activeEndpoint = smallest.endpoint;
489
+ this.activeApiKey = smallest.apiKey;
490
+ this.activeModel = smallest.model;
491
+ if (this.onFallback) {
492
+ this.onFallback(`${smallest.model} (compacted)`, Math.round(session.estimateTokens() / smallest.maxContext * 100));
493
+ }
494
+ try {
495
+ const result = await this.agentLoop(session, signal);
496
+ this._lastAnswer = result;
497
+ if (!result || !result.trim()) policy.recordError(smallest, "empty");
498
+ else policy.recordSuccess(smallest);
499
+ return result;
500
+ } catch (err) {
501
+ const status = this.parseErrorStatus(err);
502
+ const errMsg2 = err instanceof Error ? err.message : String(err);
503
+ policy.recordError(smallest, classifyError(status, errMsg2));
504
+ failedAttempts.push({ model: smallest.model, kind: classifyError(status, errMsg2), bucket: policy.registry.getBucketLevel(smallest.model, smallest.endpoint) });
505
+ }
506
+ }
507
+ const summary = failedAttempts.map((a) => ` - ${a.model}: ${a.kind} (bucket: ${a.bucket}%)`).join("\n");
508
+ if (policy.lastDecision) {
509
+ logDebug(TAG3, `Last decision: ${JSON.stringify(policy.lastDecision)}`);
510
+ }
511
+ throw new Error(`All models exhausted:
512
+ ${summary}`);
513
+ }
514
+ async agentLoop(session, signal) {
515
+ let zeroTokenRetries = 0;
516
+ const loopStart = Date.now();
517
+ for (let turn = 0; turn < this.config.maxTurns; turn++) {
518
+ if (signal.aborted) throw new Error("Aborted");
519
+ if (this.isPaused?.()) return "\u23F8 Session paused. Use `/session resume` to continue.";
520
+ const pendingInstruction = this.getPendingInstruction?.();
521
+ if (pendingInstruction) session.addUser(pendingInstruction);
522
+ const { content, toolCalls, usage } = await this.streamCompletion(session, signal);
523
+ if (usage) {
524
+ session.updateTokens(usage.prompt_tokens);
525
+ this._contextPercent = session.contextPercent;
526
+ this._lastPromptTokens = usage.prompt_tokens;
527
+ this.contextOrchestrator?.onApiResponse(this._activeSessionKey, usage.prompt_tokens, this.config.maxContext);
528
+ logTrace(TAG3, `${this.activeModel} \u2014 ${usage.prompt_tokens}\u2192${usage.completion_tokens ?? 0} tokens, ${Date.now() - (this._lastActivityAt ?? Date.now())}ms`);
529
+ recordUsage(this.activeModel, usage.prompt_tokens, usage.completion_tokens ?? 0);
530
+ }
531
+ if (toolCalls.length > 0) {
532
+ session.addAssistant(content, toolCalls);
533
+ logDebug(TAG3, `Tool calls: ${toolCalls.map((tc) => tc.function.name).join(", ")}`);
534
+ logTrace(TAG3, `Tool args: ${toolCalls.map((tc) => {
535
+ if ((tc.function.name === "abmind_store" || tc.function.name === "memory_store") && /class(?:ification)?[":\s]+[23]/.test(tc.function.arguments)) {
536
+ return `${tc.function.name}([REDACTED])`;
537
+ }
538
+ return `${tc.function.name}(${tc.function.arguments})`;
539
+ }).join(", ")}`);
540
+ if (content?.trim()) {
541
+ this.onSegmentBreak?.(content.trim());
542
+ }
543
+ for (const tc of toolCalls) {
544
+ if (signal.aborted) throw new Error("Aborted");
545
+ this._lastActivityAt = Date.now();
546
+ this.onToolCallStart?.(tc.function.name ?? "tool");
547
+ let args;
548
+ try {
549
+ args = JSON.parse(tc.function.arguments);
550
+ } catch (err) {
551
+ logAndSwallow(TAG3, "JSON.parse tool args", err);
552
+ args = {};
553
+ }
554
+ const result = await executeToolCall(tc.function.name, args, { userId: this._activeUserId, signal, sandboxPolicy: this.sandboxPolicy });
555
+ session.addToolResult(tc.id, tc.function.name, result);
556
+ if ((tc.function.name === "abmind_store" || tc.function.name === "memory_store") && parseInt(args.classification ?? args.class ?? "1", 10) >= 2) {
557
+ const secretValue = args.content ?? args.value ?? args.translated;
558
+ if (secretValue && secretValue.length > 4) {
559
+ session.scrubFromHistory(secretValue);
560
+ }
561
+ }
562
+ try {
563
+ if (!JSON.parse(result).error) this._toolCallsSucceeded++;
564
+ } catch (err) {
565
+ logAndSwallow(TAG3, "JSON.parse tool result", err);
566
+ this._toolCallsSucceeded++;
567
+ }
568
+ }
569
+ continue;
570
+ }
571
+ const answer = content ?? "";
572
+ if (!answer && usage && usage.prompt_tokens === 0) {
573
+ const elapsed = Date.now() - loopStart;
574
+ const remaining = (this._timeoutOverrideMs ?? 6e4) - elapsed;
575
+ const retryDelay = 5e3 + zeroTokenRetries * 3e3;
576
+ if (remaining > retryDelay + 5e3) {
577
+ zeroTokenRetries++;
578
+ logWarn(TAG3, `API returned 0 tokens \u2014 retry #${zeroTokenRetries} after ${retryDelay / 1e3}s (${Math.round(remaining / 1e3)}s left)`);
579
+ await new Promise((r) => setTimeout(r, retryDelay));
580
+ continue;
581
+ }
582
+ }
583
+ session.addAssistant(answer);
584
+ return answer;
585
+ }
586
+ logWarn(TAG3, `Max turns (${this.config.maxTurns}) reached`);
587
+ const last = session.messages.at(-1)?.content;
588
+ return (typeof last === "string" ? last : null) ?? "(max turns reached)";
589
+ }
590
+ parseErrorStatus(err) {
591
+ return parseErrorStatus(err);
592
+ }
593
+ /** Extract Retry-After from error (seconds or date). Returns ms or undefined. */
594
+ parseRetryAfter(err) {
595
+ return parseRetryAfter(err);
596
+ }
597
+ async streamCompletion(session, signal) {
598
+ const timeoutCtrl = new AbortController();
599
+ const timer = setTimeout(() => timeoutCtrl.abort(new Error("model API timeout")), this._timeoutOverrideMs ?? getEnv().modelApiTimeoutMs);
600
+ const composed = AbortSignal.any([signal, timeoutCtrl.signal]);
601
+ try {
602
+ if (this.config.apiFormat === "responses") {
603
+ const { toResponsesRequest } = await import("./responses-adapter-DAV2JUL7.js");
604
+ const { parseResponsesSSE } = await import("./sse-parser-responses-WG2LY2ML.js");
605
+ const msgs = session.messages.map((m) => ({ role: m.role, content: m.content ?? "" }));
606
+ const reqBody = { ...toResponsesRequest(this.activeModel, msgs, getToolSchemas(this.sandboxPolicy), this.config.maxOutput), stream: true };
607
+ const hdrs = { "Content-Type": "application/json" };
608
+ if (this.activeApiKey) hdrs["Authorization"] = `Bearer ${this.activeApiKey}`;
609
+ const res = await fetch(`${this.activeEndpoint}/responses`, {
610
+ method: "POST",
611
+ headers: hdrs,
612
+ body: JSON.stringify(reqBody),
613
+ signal: composed
614
+ });
615
+ if (!res.ok) {
616
+ const text = await res.text().catch((err) => {
617
+ logAndSwallow(TAG3, "read error body", err);
618
+ return "";
619
+ });
620
+ throw new Error(`API error ${res.status}: ${text.slice(0, 500)}`);
621
+ }
622
+ let content2 = "";
623
+ let usage2 = null;
624
+ const toolCallAcc = /* @__PURE__ */ new Map();
625
+ for await (const event of parseResponsesSSE(res, composed)) {
626
+ this._lastActivityAt = Date.now();
627
+ if (event.type === "chunk") {
628
+ content2 += event.content;
629
+ this._intermediateText += event.content;
630
+ this.onIntermediateResponse?.(event.content);
631
+ } else if (event.type === "tool_call_delta") {
632
+ this.accumulateToolCall(toolCallAcc, event);
633
+ } else if (event.type === "done") {
634
+ usage2 = event.usage;
635
+ }
636
+ }
637
+ clearTimeout(timer);
638
+ const toolCalls2 = this.finalizeToolCalls(toolCallAcc);
639
+ return { content: content2 || null, toolCalls: toolCalls2, usage: usage2 };
640
+ }
641
+ if (this.config.apiFormat === "anthropic") {
642
+ const { toAnthropicRequest, buildAnthropicHeaders } = await import("./anthropic-adapter-IBY3NPXW.js");
643
+ const { parseAnthropicSSE } = await import("./sse-parser-anthropic-H42TTLBD.js");
644
+ const msgs = session.messages.map((m) => ({ role: m.role, content: m.content ?? "", tool_call_id: m.tool_call_id }));
645
+ const reqBody = { ...toAnthropicRequest(this.activeModel, msgs, this.config.maxOutput, getToolSchemas(this.sandboxPolicy)), stream: true };
646
+ const hdrs = buildAnthropicHeaders(this.activeApiKey ?? "");
647
+ const res = await fetch(`${this.activeEndpoint}/messages`, {
648
+ method: "POST",
649
+ headers: hdrs,
650
+ body: JSON.stringify(reqBody),
651
+ signal: composed
652
+ });
653
+ if (!res.ok) {
654
+ const text = await res.text().catch((err) => {
655
+ logAndSwallow(TAG3, "read error body", err);
656
+ return "";
657
+ });
658
+ throw new Error(`API error ${res.status}: ${text.slice(0, 500)}`);
659
+ }
660
+ let content2 = "";
661
+ let usage2 = null;
662
+ const toolCallAcc = /* @__PURE__ */ new Map();
663
+ for await (const event of parseAnthropicSSE(res, composed)) {
664
+ this._lastActivityAt = Date.now();
665
+ if (event.type === "chunk") {
666
+ content2 += event.content;
667
+ this._intermediateText += event.content;
668
+ this.onIntermediateResponse?.(event.content);
669
+ } else if (event.type === "tool_call_delta") {
670
+ this.accumulateToolCall(toolCallAcc, event);
671
+ } else if (event.type === "done") {
672
+ usage2 = event.usage;
673
+ }
674
+ }
675
+ clearTimeout(timer);
676
+ const toolCalls2 = this.finalizeToolCalls(toolCallAcc);
677
+ return { content: content2 || null, toolCalls: toolCalls2, usage: usage2 };
678
+ }
679
+ const body = {
680
+ model: this.activeModel,
681
+ messages: session.messages,
682
+ tools: getToolSchemas(this.sandboxPolicy),
683
+ max_tokens: this.config.maxOutput,
684
+ stream: true,
685
+ stream_options: { include_usage: true }
686
+ };
687
+ if (this.config.thinking) {
688
+ if (this.config.thinking.style === "effort") {
689
+ body.reasoning_effort = this.config.thinking.default;
690
+ } else if (this.config.thinking.style === "extended") {
691
+ body.thinking = { type: "enabled", budget_tokens: this.config.thinking.default };
692
+ }
693
+ }
694
+ const headers = { "Content-Type": "application/json" };
695
+ if (this.activeApiKey) headers["Authorization"] = `Bearer ${this.activeApiKey}`;
696
+ const response = await withRetry(
697
+ async () => {
698
+ const res = await fetch(`${this.activeEndpoint}/chat/completions`, {
699
+ method: "POST",
700
+ headers,
701
+ body: JSON.stringify(body),
702
+ signal: composed
703
+ });
704
+ if (!res.ok) {
705
+ const text = await res.text().catch((err) => {
706
+ logAndSwallow(TAG3, "read error body", err);
707
+ return "";
708
+ });
709
+ throw new Error(`API error ${res.status}: ${text.slice(0, 500)}`);
710
+ }
711
+ return res;
712
+ },
713
+ {
714
+ attempts: 3,
715
+ minDelayMs: 3e3,
716
+ isRecoverable: (err) => {
717
+ const msg = err instanceof Error ? err.message : String(err);
718
+ if (/model API timeout/.test(msg)) return false;
719
+ if (/API error (429|401|402|403)/.test(msg)) return false;
720
+ return !isFatal(err);
721
+ }
722
+ }
723
+ );
724
+ let content = "";
725
+ const toolCallAccumulator = /* @__PURE__ */ new Map();
726
+ let usage = null;
727
+ for await (const event of parseSSEStream(response, composed)) {
728
+ this._lastActivityAt = Date.now();
729
+ switch (event.type) {
730
+ case "chunk":
731
+ content += event.content;
732
+ this._intermediateText += event.content;
733
+ this.onIntermediateResponse?.(event.content);
734
+ break;
735
+ case "tool_call_delta":
736
+ this.accumulateToolCall(toolCallAccumulator, event);
737
+ break;
738
+ case "done":
739
+ usage = event.usage;
740
+ break;
741
+ }
742
+ }
743
+ const toolCalls = this.finalizeToolCalls(toolCallAccumulator);
744
+ return { content: content || null, toolCalls, usage };
745
+ } finally {
746
+ clearTimeout(timer);
747
+ }
748
+ }
749
+ /** Accumulate streaming tool call deltas by ID (Ollama-safe: tracks by ID not index). */
750
+ accumulateToolCall(acc, delta) {
751
+ const key = delta.id ?? `idx:${delta.index}`;
752
+ const existing = acc.get(key);
753
+ if (existing) {
754
+ if (delta.arguments) existing.arguments += delta.arguments;
755
+ } else {
756
+ acc.set(key, { id: delta.id ?? `call_${acc.size}`, name: delta.name ?? "", arguments: delta.arguments ?? "" });
757
+ }
758
+ }
759
+ /**
760
+ * Convert accumulated tool call map → normalized ToolCall array.
761
+ * Handles model fragmentation: some models (nemotron, mistral-free) split a
762
+ * single tool call across multiple SSE entries with different indices/IDs.
763
+ * Pattern: [name="execute_bash" args="{}"], [name="" args=""], [name="" args='{"command":"..."}']
764
+ * Fix: merge adjacent unnamed entries' args into the preceding named entry.
765
+ */
766
+ finalizeToolCalls(acc) {
767
+ const raw = [...acc.values()].map((tc) => ({
768
+ id: tc.id,
769
+ type: "function",
770
+ function: { name: tc.name, arguments: tc.arguments }
771
+ }));
772
+ return normalizeToolCalls(raw);
773
+ }
774
+ getOrCreateSession(sessionKey) {
775
+ let session = this.sessions.get(sessionKey);
776
+ if (!session) {
777
+ session = new ConversationSession(this.systemPrompt, this.config.maxContext);
778
+ this.sessions.set(sessionKey, session);
779
+ }
780
+ return session;
781
+ }
782
+ async resetSession(sessionKey) {
783
+ const session = this.sessions.get(sessionKey);
784
+ if (session) session.reset(this.systemPrompt);
785
+ else this.sessions.delete(sessionKey);
786
+ logInfo(TAG3, `Session ${sessionKey} reset`);
787
+ }
788
+ async sendInterrupt() {
789
+ for (const ac of this.abortControllers.values()) ac.abort();
790
+ }
791
+ destroy() {
792
+ for (const ac of this.abortControllers.values()) ac.abort();
793
+ this.sessions.clear();
794
+ this.abortControllers.clear();
795
+ }
796
+ get isReady() {
797
+ return true;
798
+ }
799
+ get contextPercent() {
800
+ return this._contextPercent;
801
+ }
802
+ get answerOnly() {
803
+ return this._lastAnswer;
804
+ }
805
+ get toolCallsSucceeded() {
806
+ return this._toolCallsSucceeded;
807
+ }
808
+ /** Hot-swap the active model. Takes effect on next API call. */
809
+ setModel(model) {
810
+ this.activeModel = model;
811
+ this.config.model = model;
812
+ logInfo(TAG3, `Model switched (user): ${model}`);
813
+ }
814
+ /** Hot-swap provider+model+policy. Rejects if prompt is in flight. */
815
+ switchProvider(opts) {
816
+ if (this._promptStartedAt !== null) {
817
+ throw new Error("Cannot switch provider while a prompt is in progress \u2014 try after the response");
818
+ }
819
+ this.activeEndpoint = opts.endpoint;
820
+ this.activeApiKey = opts.apiKey;
821
+ this.activeModel = opts.model;
822
+ this.config.model = opts.model;
823
+ this.config.maxContext = opts.maxContext;
824
+ this.policy = opts.policy;
825
+ logInfo(TAG3, `Provider switched: ${opts.model} @ ${opts.endpoint} (maxCtx=${opts.maxContext})`);
826
+ }
827
+ /** Get current active model name. */
828
+ getModel() {
829
+ return this.activeModel;
830
+ }
831
+ get intermediateDeliveredText() {
832
+ return this._intermediateText;
833
+ }
834
+ get transportCommands() {
835
+ return [];
836
+ }
837
+ // Watchdog support
838
+ get promptStartedAt() {
839
+ return this._promptStartedAt;
840
+ }
841
+ setTimeoutOverride(ms) {
842
+ this._timeoutOverrideMs = ms;
843
+ }
844
+ get lastActivityAt() {
845
+ return this._lastActivityAt;
846
+ }
847
+ _stuckTimeout = getEnv().watchdogSilentSec * 1e3;
848
+ async healthCheck() {
849
+ if (!this._promptStartedAt) return;
850
+ const idle = Date.now() - (this._lastActivityAt ?? this._promptStartedAt);
851
+ if (idle > this._stuckTimeout) {
852
+ logWarn(TAG3, `[transport-health] Prompt stuck (${Math.round(idle / 1e3)}s idle) \u2014 aborting`);
853
+ await this.sendInterrupt();
854
+ }
855
+ }
856
+ };
857
+ export {
858
+ DirectApiTransport,
859
+ normalizeToolCalls
860
+ };
861
+ //# sourceMappingURL=direct-api-transport-SLJ2Z6NX.js.map