@dexto/core 1.1.4 → 1.1.6

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 (597) hide show
  1. package/README.md +125 -0
  2. package/dist/agent/DextoAgent.cjs +793 -0
  3. package/dist/agent/DextoAgent.d.cts +473 -0
  4. package/dist/agent/DextoAgent.d.ts +473 -0
  5. package/dist/agent/DextoAgent.js +774 -0
  6. package/dist/agent/agentCard.cjs +44 -0
  7. package/dist/agent/agentCard.d.cts +20 -0
  8. package/dist/agent/agentCard.d.ts +20 -0
  9. package/dist/agent/agentCard.js +20 -0
  10. package/dist/agent/error-codes.cjs +35 -0
  11. package/dist/agent/error-codes.d.cts +14 -0
  12. package/dist/agent/error-codes.d.ts +14 -0
  13. package/dist/agent/error-codes.js +11 -0
  14. package/dist/agent/errors.cjs +84 -0
  15. package/dist/agent/errors.d.cts +40 -0
  16. package/dist/agent/errors.d.ts +40 -0
  17. package/dist/agent/errors.js +60 -0
  18. package/dist/agent/index.cjs +44 -0
  19. package/dist/agent/index.d.cts +60 -0
  20. package/dist/agent/index.d.ts +60 -0
  21. package/dist/agent/index.js +13 -0
  22. package/dist/agent/registry/error-codes.cjs +42 -0
  23. package/dist/agent/registry/error-codes.d.cts +20 -0
  24. package/dist/agent/registry/error-codes.d.ts +20 -0
  25. package/dist/agent/registry/error-codes.js +18 -0
  26. package/dist/agent/registry/errors.cjs +158 -0
  27. package/dist/agent/registry/errors.d.cts +67 -0
  28. package/dist/agent/registry/errors.d.ts +67 -0
  29. package/dist/{chunk-PI6XFMEW.js → agent/registry/errors.js} +43 -50
  30. package/dist/agent/registry/registry.cjs +291 -0
  31. package/dist/agent/registry/registry.d.cts +67 -0
  32. package/dist/agent/registry/registry.d.ts +67 -0
  33. package/dist/agent/registry/registry.js +256 -0
  34. package/dist/agent/registry/types.cjs +41 -0
  35. package/dist/agent/registry/types.d.cts +100 -0
  36. package/dist/agent/registry/types.d.ts +100 -0
  37. package/dist/agent/registry/types.js +16 -0
  38. package/dist/agent/schemas.cjs +113 -0
  39. package/dist/agent/schemas.d.cts +1502 -0
  40. package/dist/agent/schemas.d.ts +1502 -0
  41. package/dist/agent/schemas.js +88 -0
  42. package/dist/agent/state-manager.cjs +214 -0
  43. package/dist/agent/state-manager.d.cts +97 -0
  44. package/dist/agent/state-manager.d.ts +97 -0
  45. package/dist/agent/state-manager.js +190 -0
  46. package/dist/config/agent-resolver.cjs +153 -0
  47. package/dist/config/agent-resolver.d.cts +15 -0
  48. package/dist/config/agent-resolver.d.ts +15 -0
  49. package/dist/config/agent-resolver.js +122 -0
  50. package/dist/config/error-codes.cjs +39 -0
  51. package/dist/config/error-codes.d.cts +17 -0
  52. package/dist/config/error-codes.d.ts +17 -0
  53. package/dist/config/error-codes.js +15 -0
  54. package/dist/config/errors.cjs +126 -0
  55. package/dist/config/errors.d.cts +49 -0
  56. package/dist/config/errors.d.ts +49 -0
  57. package/dist/config/errors.js +102 -0
  58. package/dist/config/index.cjs +26 -0
  59. package/dist/config/index.d.cts +7 -0
  60. package/dist/config/index.d.ts +7 -0
  61. package/dist/config/index.js +3 -0
  62. package/dist/config/loader.cjs +119 -0
  63. package/dist/config/loader.d.cts +19 -0
  64. package/dist/config/loader.d.ts +19 -0
  65. package/dist/config/loader.js +85 -0
  66. package/dist/config/writer.cjs +182 -0
  67. package/dist/config/writer.d.cts +38 -0
  68. package/dist/config/writer.d.ts +38 -0
  69. package/dist/config/writer.js +146 -0
  70. package/dist/context/compression/middle-removal.cjs +95 -0
  71. package/dist/context/compression/middle-removal.d.cts +48 -0
  72. package/dist/context/compression/middle-removal.d.ts +48 -0
  73. package/dist/context/compression/middle-removal.js +71 -0
  74. package/dist/context/compression/oldest-removal.cjs +70 -0
  75. package/dist/context/compression/oldest-removal.d.cts +43 -0
  76. package/dist/context/compression/oldest-removal.d.ts +43 -0
  77. package/dist/context/compression/oldest-removal.js +46 -0
  78. package/dist/context/compression/types.cjs +16 -0
  79. package/dist/context/compression/types.d.cts +21 -0
  80. package/dist/context/compression/types.d.ts +21 -0
  81. package/dist/context/compression/types.js +0 -0
  82. package/dist/context/error-codes.cjs +41 -0
  83. package/dist/context/error-codes.d.cts +19 -0
  84. package/dist/context/error-codes.d.ts +19 -0
  85. package/dist/context/error-codes.js +17 -0
  86. package/dist/context/errors.cjs +146 -0
  87. package/dist/context/errors.d.cts +36 -0
  88. package/dist/context/errors.d.ts +36 -0
  89. package/dist/context/errors.js +122 -0
  90. package/dist/context/index.cjs +24 -0
  91. package/dist/context/index.d.cts +19 -0
  92. package/dist/context/index.d.ts +19 -0
  93. package/dist/context/index.js +2 -0
  94. package/dist/context/manager.cjs +516 -0
  95. package/dist/context/manager.d.cts +254 -0
  96. package/dist/context/manager.d.ts +254 -0
  97. package/dist/context/manager.js +492 -0
  98. package/dist/context/types.cjs +16 -0
  99. package/dist/context/types.d.cts +113 -0
  100. package/dist/context/types.d.ts +113 -0
  101. package/dist/context/types.js +0 -0
  102. package/dist/context/utils.cjs +406 -0
  103. package/dist/context/utils.d.cts +79 -0
  104. package/dist/context/utils.d.ts +79 -0
  105. package/dist/context/utils.js +374 -0
  106. package/dist/errors/DextoBaseError.cjs +36 -0
  107. package/dist/errors/DextoBaseError.d.cts +15 -0
  108. package/dist/errors/DextoBaseError.d.ts +15 -0
  109. package/dist/errors/DextoBaseError.js +12 -0
  110. package/dist/errors/DextoRuntimeError.cjs +50 -0
  111. package/dist/errors/DextoRuntimeError.d.cts +37 -0
  112. package/dist/errors/DextoRuntimeError.d.ts +37 -0
  113. package/dist/errors/DextoRuntimeError.js +26 -0
  114. package/dist/errors/DextoValidationError.cjs +118 -0
  115. package/dist/errors/DextoValidationError.d.cts +65 -0
  116. package/dist/errors/DextoValidationError.d.ts +65 -0
  117. package/dist/{chunk-XFQLRBHE.js → errors/DextoValidationError.js} +4 -32
  118. package/dist/errors/index.cjs +42 -0
  119. package/dist/errors/index.d.cts +18 -0
  120. package/dist/errors/index.d.ts +18 -0
  121. package/dist/errors/index.js +13 -0
  122. package/dist/errors/result-bridge.cjs +38 -0
  123. package/dist/errors/result-bridge.d.cts +39 -0
  124. package/dist/errors/result-bridge.d.ts +39 -0
  125. package/dist/errors/result-bridge.js +14 -0
  126. package/dist/errors/types.cjs +54 -0
  127. package/dist/errors/types.d.cts +62 -0
  128. package/dist/errors/types.d.ts +62 -0
  129. package/dist/errors/types.js +29 -0
  130. package/dist/events/index.cjs +169 -0
  131. package/dist/events/index.d.cts +272 -0
  132. package/dist/events/index.d.ts +272 -0
  133. package/dist/events/index.js +136 -0
  134. package/dist/index.browser.cjs +9 -220
  135. package/dist/index.browser.d.cts +53 -379
  136. package/dist/index.browser.d.ts +53 -379
  137. package/dist/index.browser.js +4 -210
  138. package/dist/index.cjs +31 -15266
  139. package/dist/index.d.cts +89 -6842
  140. package/dist/index.d.ts +89 -6842
  141. package/dist/index.js +14 -9914
  142. package/dist/llm/error-codes.cjs +48 -0
  143. package/dist/llm/error-codes.d.cts +26 -0
  144. package/dist/llm/error-codes.d.ts +26 -0
  145. package/dist/llm/error-codes.js +24 -0
  146. package/dist/llm/errors.cjs +108 -0
  147. package/dist/llm/errors.d.cts +58 -0
  148. package/dist/llm/errors.d.ts +58 -0
  149. package/dist/llm/errors.js +84 -0
  150. package/dist/llm/formatters/anthropic.cjs +246 -0
  151. package/dist/llm/formatters/anthropic.d.cts +45 -0
  152. package/dist/llm/formatters/anthropic.d.ts +45 -0
  153. package/dist/llm/formatters/anthropic.js +227 -0
  154. package/dist/llm/formatters/factory.cjs +51 -0
  155. package/dist/llm/formatters/factory.d.cts +12 -0
  156. package/dist/llm/formatters/factory.d.ts +12 -0
  157. package/dist/llm/formatters/factory.js +27 -0
  158. package/dist/llm/formatters/openai.cjs +167 -0
  159. package/dist/llm/formatters/openai.d.cts +38 -0
  160. package/dist/llm/formatters/openai.d.ts +38 -0
  161. package/dist/llm/formatters/openai.js +147 -0
  162. package/dist/llm/formatters/types.cjs +16 -0
  163. package/dist/llm/formatters/types.d.cts +43 -0
  164. package/dist/llm/formatters/types.d.ts +43 -0
  165. package/dist/llm/formatters/types.js +0 -0
  166. package/dist/llm/formatters/vercel.cjs +411 -0
  167. package/dist/llm/formatters/vercel.d.cts +48 -0
  168. package/dist/llm/formatters/vercel.d.ts +48 -0
  169. package/dist/llm/formatters/vercel.js +387 -0
  170. package/dist/llm/index.cjs +34 -0
  171. package/dist/llm/index.d.cts +39 -0
  172. package/dist/llm/index.d.ts +39 -0
  173. package/dist/llm/index.js +7 -0
  174. package/dist/llm/registry.cjs +881 -0
  175. package/dist/llm/registry.d.cts +176 -0
  176. package/dist/llm/registry.d.ts +176 -0
  177. package/dist/{chunk-J6AXCN3H.js → llm/registry.js} +25 -455
  178. package/dist/llm/resolver.cjs +154 -0
  179. package/dist/llm/resolver.d.cts +34 -0
  180. package/dist/llm/resolver.d.ts +34 -0
  181. package/dist/llm/resolver.js +136 -0
  182. package/dist/llm/schemas.cjs +188 -0
  183. package/dist/llm/schemas.d.cts +111 -0
  184. package/dist/llm/schemas.d.ts +111 -0
  185. package/dist/llm/schemas.js +172 -0
  186. package/dist/llm/services/anthropic.cjs +398 -0
  187. package/dist/llm/services/anthropic.d.cts +65 -0
  188. package/dist/llm/services/anthropic.d.ts +65 -0
  189. package/dist/llm/services/anthropic.js +374 -0
  190. package/dist/llm/services/factory.cjs +164 -0
  191. package/dist/llm/services/factory.d.cts +39 -0
  192. package/dist/llm/services/factory.d.ts +39 -0
  193. package/dist/llm/services/factory.js +130 -0
  194. package/dist/llm/services/index.cjs +22 -0
  195. package/dist/llm/services/index.d.cts +21 -0
  196. package/dist/llm/services/index.d.ts +21 -0
  197. package/dist/llm/services/index.js +1 -0
  198. package/dist/llm/services/openai.cjs +470 -0
  199. package/dist/llm/services/openai.d.cts +65 -0
  200. package/dist/llm/services/openai.d.ts +65 -0
  201. package/dist/llm/services/openai.js +446 -0
  202. package/dist/llm/services/test-utils.integration.cjs +169 -0
  203. package/dist/llm/services/test-utils.integration.d.cts +83 -0
  204. package/dist/llm/services/test-utils.integration.d.ts +83 -0
  205. package/dist/llm/services/test-utils.integration.js +142 -0
  206. package/dist/llm/services/types.cjs +16 -0
  207. package/dist/llm/services/types.d.cts +56 -0
  208. package/dist/llm/services/types.d.ts +56 -0
  209. package/dist/llm/services/types.js +0 -0
  210. package/dist/llm/services/vercel.cjs +525 -0
  211. package/dist/llm/services/vercel.d.cts +72 -0
  212. package/dist/llm/services/vercel.d.ts +72 -0
  213. package/dist/llm/services/vercel.js +506 -0
  214. package/dist/llm/tokenizer/anthropic.cjs +43 -0
  215. package/dist/llm/tokenizer/anthropic.d.cts +21 -0
  216. package/dist/llm/tokenizer/anthropic.d.ts +21 -0
  217. package/dist/llm/tokenizer/anthropic.js +19 -0
  218. package/dist/llm/tokenizer/default.cjs +41 -0
  219. package/dist/llm/tokenizer/default.d.cts +16 -0
  220. package/dist/llm/tokenizer/default.d.ts +16 -0
  221. package/dist/llm/tokenizer/default.js +17 -0
  222. package/dist/llm/tokenizer/factory.cjs +44 -0
  223. package/dist/llm/tokenizer/factory.d.cts +12 -0
  224. package/dist/llm/tokenizer/factory.d.ts +12 -0
  225. package/dist/llm/tokenizer/factory.js +20 -0
  226. package/dist/llm/tokenizer/google.cjs +52 -0
  227. package/dist/llm/tokenizer/google.d.cts +31 -0
  228. package/dist/llm/tokenizer/google.d.ts +31 -0
  229. package/dist/llm/tokenizer/google.js +28 -0
  230. package/dist/llm/tokenizer/openai.cjs +108 -0
  231. package/dist/llm/tokenizer/openai.d.cts +32 -0
  232. package/dist/llm/tokenizer/openai.d.ts +32 -0
  233. package/dist/llm/tokenizer/openai.js +83 -0
  234. package/dist/llm/tokenizer/types.cjs +33 -0
  235. package/dist/llm/tokenizer/types.d.cts +19 -0
  236. package/dist/llm/tokenizer/types.d.ts +19 -0
  237. package/dist/llm/tokenizer/types.js +9 -0
  238. package/dist/llm/types.cjs +42 -0
  239. package/dist/llm/types.d.cts +29 -0
  240. package/dist/llm/types.d.ts +29 -0
  241. package/dist/llm/types.js +16 -0
  242. package/dist/llm/validation.cjs +162 -0
  243. package/dist/llm/validation.d.cts +60 -0
  244. package/dist/llm/validation.d.ts +60 -0
  245. package/dist/llm/validation.js +138 -0
  246. package/dist/logger/browser.cjs +86 -0
  247. package/dist/logger/browser.d.cts +29 -0
  248. package/dist/logger/browser.d.ts +29 -0
  249. package/dist/logger/browser.js +61 -0
  250. package/dist/logger/index.cjs +22 -0
  251. package/dist/logger/index.d.cts +1 -0
  252. package/dist/logger/index.d.ts +1 -0
  253. package/dist/logger/index.js +1 -0
  254. package/dist/logger/logger.cjs +362 -0
  255. package/dist/logger/logger.d.cts +52 -0
  256. package/dist/logger/logger.d.ts +52 -0
  257. package/dist/logger/logger.js +327 -0
  258. package/dist/mcp/error-codes.cjs +38 -0
  259. package/dist/mcp/error-codes.d.cts +16 -0
  260. package/dist/mcp/error-codes.d.ts +16 -0
  261. package/dist/mcp/error-codes.js +14 -0
  262. package/dist/mcp/errors.cjs +131 -0
  263. package/dist/mcp/errors.d.cts +72 -0
  264. package/dist/mcp/errors.d.ts +72 -0
  265. package/dist/mcp/errors.js +107 -0
  266. package/dist/mcp/index.cjs +34 -0
  267. package/dist/mcp/index.d.cts +26 -0
  268. package/dist/mcp/index.d.ts +26 -0
  269. package/dist/mcp/index.js +7 -0
  270. package/dist/mcp/manager.cjs +473 -0
  271. package/dist/mcp/manager.d.cts +163 -0
  272. package/dist/mcp/manager.d.ts +163 -0
  273. package/dist/mcp/manager.js +449 -0
  274. package/dist/mcp/mcp-client.cjs +420 -0
  275. package/dist/mcp/mcp-client.d.cts +108 -0
  276. package/dist/mcp/mcp-client.d.ts +108 -0
  277. package/dist/mcp/mcp-client.js +396 -0
  278. package/dist/mcp/resolver.cjs +78 -0
  279. package/dist/mcp/resolver.d.cts +22 -0
  280. package/dist/mcp/resolver.d.ts +22 -0
  281. package/dist/mcp/resolver.js +56 -0
  282. package/dist/mcp/schemas.cjs +82 -0
  283. package/dist/mcp/schemas.d.cts +266 -0
  284. package/dist/mcp/schemas.d.ts +266 -0
  285. package/dist/mcp/schemas.js +54 -0
  286. package/dist/mcp/types.cjs +16 -0
  287. package/dist/mcp/types.d.cts +21 -0
  288. package/dist/mcp/types.d.ts +21 -0
  289. package/dist/mcp/types.js +0 -0
  290. package/dist/preferences/constants.cjs +28 -0
  291. package/dist/preferences/constants.d.cts +3 -0
  292. package/dist/preferences/constants.d.ts +3 -0
  293. package/dist/preferences/constants.js +4 -0
  294. package/dist/preferences/error-codes.cjs +35 -0
  295. package/dist/preferences/error-codes.d.cts +9 -0
  296. package/dist/preferences/error-codes.d.ts +9 -0
  297. package/dist/preferences/error-codes.js +11 -0
  298. package/dist/preferences/errors.cjs +75 -0
  299. package/dist/preferences/errors.d.cts +33 -0
  300. package/dist/preferences/errors.d.ts +33 -0
  301. package/dist/preferences/errors.js +50 -0
  302. package/dist/preferences/index.cjs +55 -0
  303. package/dist/preferences/index.d.cts +21 -0
  304. package/dist/preferences/index.d.ts +21 -0
  305. package/dist/preferences/index.js +31 -0
  306. package/dist/preferences/loader.cjs +136 -0
  307. package/dist/preferences/loader.d.cts +45 -0
  308. package/dist/preferences/loader.d.ts +45 -0
  309. package/dist/preferences/loader.js +107 -0
  310. package/dist/preferences/schemas.cjs +74 -0
  311. package/dist/preferences/schemas.d.cts +104 -0
  312. package/dist/preferences/schemas.d.ts +104 -0
  313. package/dist/preferences/schemas.js +47 -0
  314. package/dist/search/index.cjs +28 -0
  315. package/dist/search/index.d.cts +5 -0
  316. package/dist/search/index.d.ts +5 -0
  317. package/dist/search/index.js +4 -0
  318. package/dist/search/search-service.cjs +245 -0
  319. package/dist/search/search-service.d.cts +47 -0
  320. package/dist/search/search-service.d.ts +47 -0
  321. package/dist/search/search-service.js +221 -0
  322. package/dist/search/types.cjs +16 -0
  323. package/dist/search/types.d.cts +78 -0
  324. package/dist/search/types.d.ts +78 -0
  325. package/dist/search/types.js +0 -0
  326. package/dist/session/chat-session.cjs +354 -0
  327. package/dist/session/chat-session.d.cts +284 -0
  328. package/dist/session/chat-session.d.ts +284 -0
  329. package/dist/session/chat-session.js +333 -0
  330. package/dist/session/error-codes.cjs +35 -0
  331. package/dist/session/error-codes.d.cts +13 -0
  332. package/dist/session/error-codes.d.ts +13 -0
  333. package/dist/session/error-codes.js +11 -0
  334. package/dist/session/errors.cjs +93 -0
  335. package/dist/session/errors.d.cts +58 -0
  336. package/dist/session/errors.d.ts +58 -0
  337. package/dist/session/errors.js +69 -0
  338. package/dist/session/history/database.cjs +95 -0
  339. package/dist/session/history/database.d.cts +28 -0
  340. package/dist/session/history/database.d.ts +28 -0
  341. package/dist/session/history/database.js +71 -0
  342. package/dist/session/history/factory.cjs +31 -0
  343. package/dist/session/history/factory.d.cts +11 -0
  344. package/dist/session/history/factory.d.ts +11 -0
  345. package/dist/session/history/factory.js +7 -0
  346. package/dist/session/history/types.cjs +16 -0
  347. package/dist/session/history/types.d.cts +17 -0
  348. package/dist/session/history/types.d.ts +17 -0
  349. package/dist/session/history/types.js +0 -0
  350. package/dist/session/index.cjs +37 -0
  351. package/dist/session/index.d.cts +53 -0
  352. package/dist/session/index.d.ts +53 -0
  353. package/dist/session/index.js +10 -0
  354. package/dist/session/schemas.cjs +32 -0
  355. package/dist/session/schemas.d.cts +16 -0
  356. package/dist/session/schemas.d.ts +16 -0
  357. package/dist/session/schemas.js +8 -0
  358. package/dist/session/session-manager.cjs +481 -0
  359. package/dist/session/session-manager.d.cts +219 -0
  360. package/dist/session/session-manager.d.ts +219 -0
  361. package/dist/session/session-manager.js +457 -0
  362. package/dist/storage/backend/cache-backend.cjs +16 -0
  363. package/dist/storage/backend/cache-backend.d.cts +15 -0
  364. package/dist/storage/backend/cache-backend.d.ts +15 -0
  365. package/dist/storage/backend/cache-backend.js +0 -0
  366. package/dist/storage/backend/database-backend.cjs +16 -0
  367. package/dist/storage/backend/database-backend.d.cts +19 -0
  368. package/dist/storage/backend/database-backend.d.ts +19 -0
  369. package/dist/storage/backend/database-backend.js +0 -0
  370. package/dist/storage/backend/memory-backend.cjs +140 -0
  371. package/dist/storage/backend/memory-backend.d.cts +34 -0
  372. package/dist/storage/backend/memory-backend.d.ts +34 -0
  373. package/dist/storage/backend/memory-backend.js +116 -0
  374. package/dist/storage/backend/postgres-backend.cjs +231 -0
  375. package/dist/storage/backend/postgres-backend.d.cts +37 -0
  376. package/dist/storage/backend/postgres-backend.d.ts +37 -0
  377. package/dist/{postgres-backend-WMWS7RAT.js → storage/backend/postgres-backend.js} +3 -12
  378. package/dist/storage/backend/redis-backend.cjs +184 -0
  379. package/dist/storage/backend/redis-backend.d.cts +36 -0
  380. package/dist/storage/backend/redis-backend.d.ts +36 -0
  381. package/dist/{redis-backend-BNLN3XHX.js → storage/backend/redis-backend.js} +3 -12
  382. package/dist/storage/backend/sqlite-backend.cjs +271 -0
  383. package/dist/storage/backend/sqlite-backend.d.cts +35 -0
  384. package/dist/storage/backend/sqlite-backend.d.ts +35 -0
  385. package/dist/{sqlite-backend-AR6XNK2Q.js → storage/backend/sqlite-backend.js} +6 -17
  386. package/dist/storage/backend/types.cjs +16 -0
  387. package/dist/storage/backend/types.d.cts +14 -0
  388. package/dist/storage/backend/types.d.ts +14 -0
  389. package/dist/storage/backend/types.js +0 -0
  390. package/dist/storage/error-codes.cjs +36 -0
  391. package/dist/storage/error-codes.d.cts +14 -0
  392. package/dist/storage/error-codes.d.ts +14 -0
  393. package/dist/storage/error-codes.js +12 -0
  394. package/dist/storage/errors.cjs +104 -0
  395. package/dist/storage/errors.d.cts +63 -0
  396. package/dist/storage/errors.d.ts +63 -0
  397. package/dist/{chunk-F2QFAECT.js → storage/errors.js} +23 -30
  398. package/dist/storage/index.cjs +33 -0
  399. package/dist/storage/index.d.cts +7 -0
  400. package/dist/storage/index.d.ts +7 -0
  401. package/dist/storage/index.js +7 -0
  402. package/dist/storage/schemas.cjs +113 -0
  403. package/dist/storage/schemas.d.cts +856 -0
  404. package/dist/storage/schemas.d.ts +856 -0
  405. package/dist/storage/schemas.js +89 -0
  406. package/dist/storage/storage-manager.cjs +208 -0
  407. package/dist/storage/storage-manager.d.cts +52 -0
  408. package/dist/storage/storage-manager.d.ts +52 -0
  409. package/dist/storage/storage-manager.js +173 -0
  410. package/dist/storage/types.cjs +16 -0
  411. package/dist/storage/types.d.cts +5 -0
  412. package/dist/storage/types.d.ts +5 -0
  413. package/dist/storage/types.js +0 -0
  414. package/dist/systemPrompt/contributors.cjs +146 -0
  415. package/dist/systemPrompt/contributors.d.cts +44 -0
  416. package/dist/systemPrompt/contributors.d.ts +44 -0
  417. package/dist/systemPrompt/contributors.js +120 -0
  418. package/dist/systemPrompt/error-codes.cjs +35 -0
  419. package/dist/systemPrompt/error-codes.d.cts +13 -0
  420. package/dist/systemPrompt/error-codes.d.ts +13 -0
  421. package/dist/systemPrompt/error-codes.js +11 -0
  422. package/dist/systemPrompt/errors.cjs +93 -0
  423. package/dist/systemPrompt/errors.d.cts +55 -0
  424. package/dist/systemPrompt/errors.d.ts +55 -0
  425. package/dist/systemPrompt/errors.js +69 -0
  426. package/dist/systemPrompt/in-built-prompts.cjs +68 -0
  427. package/dist/systemPrompt/in-built-prompts.d.cts +28 -0
  428. package/dist/systemPrompt/in-built-prompts.d.ts +28 -0
  429. package/dist/systemPrompt/in-built-prompts.js +42 -0
  430. package/dist/systemPrompt/index.cjs +30 -0
  431. package/dist/systemPrompt/index.d.cts +14 -0
  432. package/dist/systemPrompt/index.d.ts +14 -0
  433. package/dist/systemPrompt/index.js +5 -0
  434. package/dist/systemPrompt/manager.cjs +93 -0
  435. package/dist/systemPrompt/manager.d.cts +31 -0
  436. package/dist/systemPrompt/manager.d.ts +31 -0
  437. package/dist/systemPrompt/manager.js +69 -0
  438. package/dist/systemPrompt/registry.cjs +51 -0
  439. package/dist/systemPrompt/registry.d.cts +20 -0
  440. package/dist/systemPrompt/registry.d.ts +20 -0
  441. package/dist/systemPrompt/registry.js +15 -0
  442. package/dist/systemPrompt/schemas.cjs +107 -0
  443. package/dist/systemPrompt/schemas.d.cts +401 -0
  444. package/dist/systemPrompt/schemas.d.ts +401 -0
  445. package/dist/systemPrompt/schemas.js +81 -0
  446. package/dist/systemPrompt/types.cjs +16 -0
  447. package/dist/systemPrompt/types.d.cts +19 -0
  448. package/dist/systemPrompt/types.d.ts +19 -0
  449. package/dist/systemPrompt/types.js +0 -0
  450. package/dist/tools/confirmation/allowed-tools-provider/factory.cjs +44 -0
  451. package/dist/tools/confirmation/allowed-tools-provider/factory.d.cts +19 -0
  452. package/dist/tools/confirmation/allowed-tools-provider/factory.d.ts +19 -0
  453. package/dist/tools/confirmation/allowed-tools-provider/factory.js +20 -0
  454. package/dist/tools/confirmation/allowed-tools-provider/in-memory.cjs +62 -0
  455. package/dist/tools/confirmation/allowed-tools-provider/in-memory.d.cts +17 -0
  456. package/dist/tools/confirmation/allowed-tools-provider/in-memory.d.ts +17 -0
  457. package/dist/tools/confirmation/allowed-tools-provider/in-memory.js +38 -0
  458. package/dist/tools/confirmation/allowed-tools-provider/storage.cjs +68 -0
  459. package/dist/tools/confirmation/allowed-tools-provider/storage.d.cts +26 -0
  460. package/dist/tools/confirmation/allowed-tools-provider/storage.d.ts +26 -0
  461. package/dist/tools/confirmation/allowed-tools-provider/storage.js +44 -0
  462. package/dist/tools/confirmation/allowed-tools-provider/types.cjs +16 -0
  463. package/dist/tools/confirmation/allowed-tools-provider/types.d.cts +35 -0
  464. package/dist/tools/confirmation/allowed-tools-provider/types.d.ts +35 -0
  465. package/dist/tools/confirmation/allowed-tools-provider/types.js +0 -0
  466. package/dist/tools/confirmation/event-based-confirmation-provider.cjs +158 -0
  467. package/dist/tools/confirmation/event-based-confirmation-provider.d.cts +41 -0
  468. package/dist/tools/confirmation/event-based-confirmation-provider.d.ts +41 -0
  469. package/dist/tools/confirmation/event-based-confirmation-provider.js +134 -0
  470. package/dist/tools/confirmation/factory.cjs +52 -0
  471. package/dist/tools/confirmation/factory.d.cts +37 -0
  472. package/dist/tools/confirmation/factory.d.ts +37 -0
  473. package/dist/tools/confirmation/factory.js +28 -0
  474. package/dist/tools/confirmation/noop-confirmation-provider.cjs +49 -0
  475. package/dist/tools/confirmation/noop-confirmation-provider.d.cts +22 -0
  476. package/dist/tools/confirmation/noop-confirmation-provider.d.ts +22 -0
  477. package/dist/tools/confirmation/noop-confirmation-provider.js +25 -0
  478. package/dist/tools/confirmation/types.cjs +16 -0
  479. package/dist/tools/confirmation/types.d.cts +46 -0
  480. package/dist/tools/confirmation/types.d.ts +46 -0
  481. package/dist/tools/confirmation/types.js +0 -0
  482. package/dist/tools/error-codes.cjs +40 -0
  483. package/dist/tools/error-codes.d.cts +18 -0
  484. package/dist/tools/error-codes.d.ts +18 -0
  485. package/dist/tools/error-codes.js +16 -0
  486. package/dist/tools/errors.cjs +164 -0
  487. package/dist/tools/errors.d.cts +97 -0
  488. package/dist/tools/errors.d.ts +97 -0
  489. package/dist/tools/errors.js +140 -0
  490. package/dist/tools/index.cjs +37 -0
  491. package/dist/tools/index.d.cts +19 -0
  492. package/dist/tools/index.d.ts +19 -0
  493. package/dist/tools/index.js +8 -0
  494. package/dist/tools/internal-tools/implementations/search-history-tool.cjs +61 -0
  495. package/dist/tools/internal-tools/implementations/search-history-tool.d.cts +15 -0
  496. package/dist/tools/internal-tools/implementations/search-history-tool.d.ts +15 -0
  497. package/dist/tools/internal-tools/implementations/search-history-tool.js +37 -0
  498. package/dist/tools/internal-tools/index.cjs +24 -0
  499. package/dist/tools/internal-tools/index.d.cts +13 -0
  500. package/dist/tools/internal-tools/index.d.ts +13 -0
  501. package/dist/tools/internal-tools/index.js +2 -0
  502. package/dist/tools/internal-tools/provider.cjs +159 -0
  503. package/dist/tools/internal-tools/provider.d.cts +66 -0
  504. package/dist/tools/internal-tools/provider.d.ts +66 -0
  505. package/dist/tools/internal-tools/provider.js +135 -0
  506. package/dist/tools/internal-tools/registry.cjs +43 -0
  507. package/dist/tools/internal-tools/registry.d.cts +45 -0
  508. package/dist/tools/internal-tools/registry.d.ts +45 -0
  509. package/dist/tools/internal-tools/registry.js +17 -0
  510. package/dist/tools/schemas.cjs +45 -0
  511. package/dist/tools/schemas.d.cts +21 -0
  512. package/dist/tools/schemas.d.ts +21 -0
  513. package/dist/tools/schemas.js +20 -0
  514. package/dist/tools/tool-manager.cjs +275 -0
  515. package/dist/tools/tool-manager.d.cts +106 -0
  516. package/dist/tools/tool-manager.d.ts +106 -0
  517. package/dist/tools/tool-manager.js +251 -0
  518. package/dist/tools/types.cjs +16 -0
  519. package/dist/tools/types.d.cts +66 -0
  520. package/dist/tools/types.d.ts +66 -0
  521. package/dist/tools/types.js +0 -0
  522. package/dist/utils/api-key-resolver.cjs +62 -0
  523. package/dist/utils/api-key-resolver.d.cts +23 -0
  524. package/dist/utils/api-key-resolver.d.ts +23 -0
  525. package/dist/utils/api-key-resolver.js +36 -0
  526. package/dist/utils/api-key-store.cjs +56 -0
  527. package/dist/utils/api-key-store.d.cts +26 -0
  528. package/dist/utils/api-key-store.d.ts +26 -0
  529. package/dist/utils/api-key-store.js +30 -0
  530. package/dist/utils/env.cjs +154 -0
  531. package/dist/utils/env.d.cts +29 -0
  532. package/dist/utils/env.d.ts +29 -0
  533. package/dist/utils/env.js +118 -0
  534. package/dist/utils/error-conversion.cjs +53 -0
  535. package/dist/utils/error-conversion.d.cts +13 -0
  536. package/dist/utils/error-conversion.d.ts +13 -0
  537. package/dist/utils/error-conversion.js +29 -0
  538. package/dist/utils/execution-context.cjs +85 -0
  539. package/dist/utils/execution-context.d.cts +21 -0
  540. package/dist/utils/execution-context.d.ts +21 -0
  541. package/dist/utils/execution-context.js +49 -0
  542. package/dist/{chunk-MVKLS3LM.js → utils/fs-walk.cjs} +27 -18
  543. package/dist/utils/fs-walk.d.cts +9 -0
  544. package/dist/utils/fs-walk.d.ts +9 -0
  545. package/dist/utils/fs-walk.js +18 -0
  546. package/dist/utils/index.cjs +44 -0
  547. package/dist/utils/index.d.cts +63 -0
  548. package/dist/utils/index.d.ts +63 -0
  549. package/dist/utils/index.js +12 -0
  550. package/dist/utils/path.cjs +197 -0
  551. package/dist/utils/path.d.cts +54 -0
  552. package/dist/utils/path.d.ts +54 -0
  553. package/dist/utils/path.js +159 -0
  554. package/dist/utils/port-utils.cjs +37 -0
  555. package/dist/utils/port-utils.d.cts +11 -0
  556. package/dist/utils/port-utils.d.ts +11 -0
  557. package/dist/utils/port-utils.js +13 -0
  558. package/dist/utils/port-utils.spec.cjs +26 -0
  559. package/dist/utils/port-utils.spec.d.cts +2 -0
  560. package/dist/utils/port-utils.spec.d.ts +2 -0
  561. package/dist/utils/port-utils.spec.js +25 -0
  562. package/dist/utils/redactor.cjs +105 -0
  563. package/dist/utils/redactor.d.cts +18 -0
  564. package/dist/utils/redactor.d.ts +18 -0
  565. package/dist/utils/redactor.js +81 -0
  566. package/dist/utils/result.cjs +115 -0
  567. package/dist/utils/result.d.cts +180 -0
  568. package/dist/utils/result.d.ts +180 -0
  569. package/dist/utils/result.js +82 -0
  570. package/dist/utils/safe-stringify.cjs +57 -0
  571. package/dist/utils/safe-stringify.d.cts +7 -0
  572. package/dist/utils/safe-stringify.d.ts +7 -0
  573. package/dist/utils/safe-stringify.js +33 -0
  574. package/dist/utils/schema.cjs +42 -0
  575. package/dist/utils/schema.d.cts +6 -0
  576. package/dist/utils/schema.d.ts +6 -0
  577. package/dist/utils/schema.js +18 -0
  578. package/dist/utils/service-initializer.cjs +119 -0
  579. package/dist/utils/service-initializer.d.cts +63 -0
  580. package/dist/utils/service-initializer.d.ts +63 -0
  581. package/dist/utils/service-initializer.js +95 -0
  582. package/dist/utils/user-info.cjs +30 -0
  583. package/dist/utils/user-info.d.cts +3 -0
  584. package/dist/utils/user-info.d.ts +3 -0
  585. package/dist/utils/user-info.js +6 -0
  586. package/dist/utils/zod-schema-converter.cjs +112 -0
  587. package/dist/utils/zod-schema-converter.d.cts +13 -0
  588. package/dist/utils/zod-schema-converter.d.ts +13 -0
  589. package/dist/utils/zod-schema-converter.js +87 -0
  590. package/package.json +2 -2
  591. package/dist/chunk-D62MHQBE.js +0 -2203
  592. package/dist/chunk-FCJVTIBV.js +0 -535
  593. package/dist/chunk-TPERKLLN.js +0 -75
  594. package/dist/errors-ZZ4Z3FKB.js +0 -10
  595. package/dist/loader-HBNEYPQZ.js +0 -20
  596. package/dist/path-TP7WBDED.js +0 -21
  597. package/dist/registry-Z4DFXODW.js +0 -14
@@ -0,0 +1,492 @@
1
+ import { MiddleRemovalStrategy } from "./compression/middle-removal.js";
2
+ import { OldestRemovalStrategy } from "./compression/oldest-removal.js";
3
+ import { logger } from "../logger/index.js";
4
+ import { countMessagesTokens, sanitizeToolResultToContent } from "./utils.js";
5
+ import { ContextError } from "./errors.js";
6
+ class ContextManager {
7
+ /**
8
+ * The validated LLM configuration.
9
+ */
10
+ llmConfig;
11
+ /**
12
+ * PromptManager used to generate/manage the system prompt
13
+ */
14
+ promptManager;
15
+ /**
16
+ * Formatter used to convert internal messages to LLM-specific format
17
+ */
18
+ formatter;
19
+ /**
20
+ * Maximum number of tokens allowed in the conversation (if specified)
21
+ */
22
+ maxInputTokens;
23
+ /**
24
+ * Actual token count from the last LLM response.
25
+ * Used for more accurate token estimation in hybrid approach.
26
+ */
27
+ lastActualTokenCount = 0;
28
+ /**
29
+ * Compression threshold as a percentage of maxInputTokens.
30
+ * When estimated tokens exceed (maxInputTokens * threshold), compression is triggered.
31
+ */
32
+ compressionThreshold = 0.8;
33
+ // 80% threshold
34
+ /**
35
+ * Tokenizer used for counting tokens and enabling compression (if specified)
36
+ */
37
+ tokenizer;
38
+ /**
39
+ * The sequence of compression strategies to apply when maxInputTokens is exceeded.
40
+ * The order in this array matters, as strategies are applied sequentially until
41
+ * the token count is within the limit.
42
+ */
43
+ compressionStrategies;
44
+ historyProvider;
45
+ sessionId;
46
+ /**
47
+ * Creates a new ContextManager instance
48
+ * @param llmConfig The validated LLM configuration.
49
+ * @param formatter Formatter implementation for the target LLM provider
50
+ * @param promptManager PromptManager instance for the conversation
51
+ * @param maxInputTokens Maximum token limit for the conversation history. Triggers compression if exceeded and a tokenizer is provided.
52
+ * @param tokenizer Tokenizer implementation used for counting tokens and enabling compression.
53
+ * @param historyProvider Session-scoped ConversationHistoryProvider instance for managing conversation history
54
+ * @param sessionId Unique identifier for the conversation session (readonly, for debugging)
55
+ * @param compressionStrategies Optional array of compression strategies to apply when token limits are exceeded
56
+ */
57
+ constructor(llmConfig, formatter, promptManager, maxInputTokens, tokenizer, historyProvider, sessionId, compressionStrategies = [
58
+ new MiddleRemovalStrategy(),
59
+ new OldestRemovalStrategy()
60
+ ]) {
61
+ this.llmConfig = llmConfig;
62
+ this.formatter = formatter;
63
+ this.promptManager = promptManager;
64
+ this.maxInputTokens = maxInputTokens;
65
+ this.tokenizer = tokenizer;
66
+ this.historyProvider = historyProvider;
67
+ this.sessionId = sessionId;
68
+ this.compressionStrategies = compressionStrategies;
69
+ logger.debug(
70
+ `ContextManager: Initialized for session ${sessionId} - history will be managed by ${historyProvider.constructor.name}`
71
+ );
72
+ }
73
+ /**
74
+ * Returns the current token count of the conversation history.
75
+ * @returns Promise that resolves to the number of tokens in the current history
76
+ */
77
+ async getTokenCount() {
78
+ const history = await this.historyProvider.getHistory();
79
+ return countMessagesTokens(history, this.tokenizer);
80
+ }
81
+ /**
82
+ * Returns the total token count that will be sent to the LLM provider,
83
+ * including system prompt, formatted messages, and provider-specific overhead.
84
+ * This provides a more accurate estimate than getTokenCount() alone.
85
+ *
86
+ * @param context The DynamicContributorContext for system prompt contributors
87
+ * @returns Promise that resolves to the total number of tokens that will be sent to the provider
88
+ */
89
+ async getTotalTokenCount(context) {
90
+ try {
91
+ const systemPrompt = await this.getSystemPrompt(context);
92
+ let history = await this.historyProvider.getHistory();
93
+ const systemPromptTokens = this.tokenizer.countTokens(systemPrompt);
94
+ history = await this.compressHistoryIfNeeded(history, systemPromptTokens);
95
+ const historyTokens = countMessagesTokens(history, this.tokenizer);
96
+ const formattingOverhead = Math.ceil((systemPromptTokens + historyTokens) * 0.05);
97
+ const totalTokens = systemPromptTokens + historyTokens + formattingOverhead;
98
+ logger.debug(
99
+ `Token breakdown - System: ${systemPromptTokens}, History: ${historyTokens}, Overhead: ${formattingOverhead}, Total: ${totalTokens}`
100
+ );
101
+ return totalTokens;
102
+ } catch (error) {
103
+ logger.error("Error calculating total token count:", error);
104
+ return this.getTokenCount();
105
+ }
106
+ }
107
+ /**
108
+ * Returns the configured maximum number of input tokens for the conversation.
109
+ */
110
+ getMaxInputTokens() {
111
+ return this.maxInputTokens;
112
+ }
113
+ /**
114
+ * Updates the ContextManager configuration when LLM config changes.
115
+ * This is called when DextoAgent.switchLLM() updates the LLM configuration.
116
+ *
117
+ * @param newMaxInputTokens New maximum token limit
118
+ * @param newTokenizer Optional new tokenizer if provider changed
119
+ * @param newFormatter Optional new formatter if provider/router changed
120
+ */
121
+ updateConfig(newMaxInputTokens, newTokenizer, newFormatter) {
122
+ const oldMaxInputTokens = this.maxInputTokens;
123
+ this.maxInputTokens = newMaxInputTokens;
124
+ if (newTokenizer) {
125
+ this.tokenizer = newTokenizer;
126
+ }
127
+ if (newFormatter) {
128
+ this.formatter = newFormatter;
129
+ }
130
+ logger.debug(
131
+ `ContextManager config updated: maxInputTokens ${oldMaxInputTokens} -> ${newMaxInputTokens}`
132
+ );
133
+ }
134
+ /**
135
+ * Updates the actual token count from the last LLM response.
136
+ * This enables hybrid token counting for more accurate estimates.
137
+ *
138
+ * @param actualTokens The actual token count reported by the LLM provider
139
+ */
140
+ updateActualTokenCount(actualTokens) {
141
+ this.lastActualTokenCount = actualTokens;
142
+ logger.debug(`Updated actual token count to: ${actualTokens}`);
143
+ }
144
+ /**
145
+ * Estimates if new input would trigger compression using hybrid approach.
146
+ * Combines actual tokens from last response with estimated tokens for new input.
147
+ *
148
+ * @param newInputTokens Estimated tokens for the new user input
149
+ * @returns True if compression should be triggered
150
+ */
151
+ shouldCompress(newInputTokens) {
152
+ const estimatedTotal = this.lastActualTokenCount + newInputTokens;
153
+ const compressionTrigger = this.maxInputTokens * this.compressionThreshold;
154
+ logger.debug(
155
+ `Compression check: actual=${this.lastActualTokenCount}, newInput=${newInputTokens}, total=${estimatedTotal}, trigger=${compressionTrigger}`
156
+ );
157
+ return estimatedTotal > compressionTrigger;
158
+ }
159
+ /**
160
+ * Assembles and returns the current system prompt by invoking the PromptManager.
161
+ */
162
+ async getSystemPrompt(context) {
163
+ const prompt = await this.promptManager.build(context);
164
+ logger.debug(`[SystemPrompt] Built system prompt:
165
+ ${prompt}`);
166
+ return prompt;
167
+ }
168
+ /**
169
+ * Gets the raw conversation history
170
+ * Returns a defensive copy to prevent modification
171
+ *
172
+ * @returns Promise that resolves to a read-only copy of the conversation history
173
+ */
174
+ async getHistory() {
175
+ const history = await this.historyProvider.getHistory();
176
+ return [...history];
177
+ }
178
+ /**
179
+ * Adds a message to the conversation history.
180
+ * Performs validation based on message role and required fields.
181
+ * Note: Compression based on token limits is applied lazily when calling `getFormattedMessages`, not immediately upon adding.
182
+ *
183
+ * @param message The message to add to the history
184
+ * @throws Error if message validation fails
185
+ */
186
+ async addMessage(message) {
187
+ switch (message.role) {
188
+ case "user":
189
+ if (
190
+ // Allow array content for user messages
191
+ !(Array.isArray(message.content) && message.content.length > 0) && (typeof message.content !== "string" || message.content.trim() === "")
192
+ ) {
193
+ throw ContextError.userMessageContentInvalid();
194
+ }
195
+ break;
196
+ case "assistant":
197
+ if (message.content === null && (!message.toolCalls || message.toolCalls.length === 0)) {
198
+ throw ContextError.assistantMessageContentOrToolsRequired();
199
+ }
200
+ if (message.toolCalls) {
201
+ if (!Array.isArray(message.toolCalls) || message.toolCalls.some(
202
+ (tc) => !tc.id || !tc.function?.name || !tc.function?.arguments
203
+ )) {
204
+ throw ContextError.assistantMessageToolCallsInvalid();
205
+ }
206
+ }
207
+ message.provider = this.llmConfig.provider;
208
+ message.router = this.llmConfig.router;
209
+ message.model = this.llmConfig.model;
210
+ break;
211
+ case "tool":
212
+ if (!message.toolCallId || !message.name || message.content === null) {
213
+ throw ContextError.toolMessageFieldsMissing();
214
+ }
215
+ break;
216
+ case "system":
217
+ logger.warn(
218
+ "ContextManager: Adding system message directly to history. Use setSystemPrompt instead."
219
+ );
220
+ if (typeof message.content !== "string" || message.content.trim() === "") {
221
+ throw ContextError.systemMessageContentInvalid();
222
+ }
223
+ break;
224
+ }
225
+ logger.debug(
226
+ `ContextManager: Adding message to history provider: ${JSON.stringify(message, null, 2)}`
227
+ );
228
+ await this.historyProvider.saveMessage(message);
229
+ const history = await this.historyProvider.getHistory();
230
+ logger.debug(`ContextManager: History now contains ${history.length} messages`);
231
+ }
232
+ /**
233
+ * Adds a user message to the conversation
234
+ * Can include image data for multimodal input
235
+ *
236
+ * @param textContent The user message content
237
+ * @param imageData Optional image data for multimodal input
238
+ * @param fileData Optional file data for file input
239
+ * @throws Error if content is empty or not a string
240
+ */
241
+ async addUserMessage(textContent, imageData, fileData) {
242
+ if (typeof textContent !== "string" || textContent.trim() === "" && !imageData && !fileData) {
243
+ throw ContextError.userMessageContentEmpty();
244
+ }
245
+ const finalTextContent = textContent.trim() || (imageData || fileData ? "" : textContent);
246
+ const messageParts = [];
247
+ if (finalTextContent) {
248
+ messageParts.push({ type: "text", text: finalTextContent });
249
+ }
250
+ if (imageData) {
251
+ messageParts.push({
252
+ type: "image",
253
+ image: imageData.image,
254
+ mimeType: imageData.mimeType || "image/jpeg"
255
+ });
256
+ }
257
+ if (fileData) {
258
+ messageParts.push({
259
+ type: "file",
260
+ data: fileData.data,
261
+ mimeType: fileData.mimeType,
262
+ ...fileData.filename && { filename: fileData.filename }
263
+ });
264
+ }
265
+ if (messageParts.length === 0) {
266
+ messageParts.push({ type: "text", text: finalTextContent });
267
+ }
268
+ logger.debug(
269
+ `ContextManager: Adding user message: ${JSON.stringify(messageParts, null, 2)}`
270
+ );
271
+ await this.addMessage({ role: "user", content: messageParts });
272
+ }
273
+ /**
274
+ * Adds an assistant message to the conversation
275
+ * Can include tool calls if the assistant is requesting tool execution
276
+ *
277
+ * @param content The assistant's response text (can be null if only tool calls)
278
+ * @param toolCalls Optional tool calls requested by the assistant
279
+ * @param metadata Optional metadata including token usage, reasoning, and model info
280
+ * @throws Error if neither content nor toolCalls are provided
281
+ */
282
+ async addAssistantMessage(content, toolCalls, metadata) {
283
+ if (content === null && (!toolCalls || toolCalls.length === 0)) {
284
+ throw ContextError.assistantMessageContentOrToolsRequired();
285
+ }
286
+ await this.addMessage({
287
+ role: "assistant",
288
+ content,
289
+ ...toolCalls && toolCalls.length > 0 && { toolCalls },
290
+ ...metadata?.tokenUsage && { tokenUsage: metadata.tokenUsage },
291
+ ...metadata?.reasoning && { reasoning: metadata.reasoning }
292
+ });
293
+ }
294
+ /**
295
+ * Adds a tool result message to the conversation
296
+ *
297
+ * @param toolCallId ID of the tool call this result is responding to
298
+ * @param name Name of the tool that executed
299
+ * @param result The result returned by the tool
300
+ * @throws Error if required parameters are missing
301
+ */
302
+ async addToolResult(toolCallId, name, result) {
303
+ if (!toolCallId || !name) {
304
+ throw ContextError.toolCallIdNameRequired();
305
+ }
306
+ let content;
307
+ content = sanitizeToolResultToContent(result);
308
+ if (typeof content === "string") {
309
+ const preview = content.slice(0, 200);
310
+ logger.debug(
311
+ `ContextManager: Storing tool result (text) for ${name} (len=${content.length}): ${preview}${content.length > 200 ? "..." : ""}`
312
+ );
313
+ } else if (Array.isArray(content)) {
314
+ const summary = content.map(
315
+ (p) => p.type === "text" ? `text(${p.text.length})` : p.type === "image" ? `image(${p.mimeType || "image"})` : `file(${p.mimeType || "file"})`
316
+ ).join(", ");
317
+ logger.debug(`ContextManager: Storing tool result (parts) for ${name}: [${summary}]`);
318
+ }
319
+ await this.addMessage({ role: "tool", content, toolCallId, name });
320
+ }
321
+ /**
322
+ * Sets the system prompt for the conversation
323
+ *
324
+ * @param prompt The system prompt text
325
+ */
326
+ setSystemPrompt(_prompt) {
327
+ }
328
+ /**
329
+ * Gets the conversation history formatted for the target LLM provider.
330
+ * Applies compression strategies sequentially if the manager is configured with a `maxInputTokens` limit
331
+ * and a `tokenizer`, and the current token count exceeds the limit. Compression happens *before* formatting.
332
+ * Uses the injected formatter to convert internal messages (potentially compressed) to the provider's format.
333
+ *
334
+ * @param contributorContext The DynamicContributorContext for system prompt contributors and formatting
335
+ * @param llmContext The llmContext for the formatter to decide which messages to include based on the model's capabilities
336
+ * @param systemPrompt (Optional) Precomputed system prompt string. If provided, it will be used instead of recomputing the system prompt. Useful for avoiding duplicate computation when both the formatted messages and the raw system prompt are needed in the same request.
337
+ * @param history (Optional) Pre-fetched and potentially compressed history. If not provided, will fetch from history provider.
338
+ * @returns Formatted messages ready to send to the LLM provider API
339
+ * @throws Error if formatting or compression fails critically
340
+ */
341
+ async getFormattedMessages(contributorContext, llmContext, systemPrompt, history) {
342
+ const messageHistory = history ?? await this.historyProvider.getHistory();
343
+ const prompt = systemPrompt ?? await this.getSystemPrompt(contributorContext);
344
+ return this.formatter.format([...messageHistory], llmContext, prompt);
345
+ }
346
+ /**
347
+ * Gets the conversation ready for LLM consumption with proper flow:
348
+ * 1. Get system prompt
349
+ * 2. Get history and compress if needed
350
+ * 3. Format messages
351
+ * This method implements the correct ordering to avoid circular dependencies.
352
+ *
353
+ * @param contributorContext The DynamicContributorContext for system prompt contributors and formatting
354
+ * @param llmContext The llmContext for the formatter to decide which messages to include based on the model's capabilities
355
+ * @returns Object containing formatted messages and system prompt
356
+ */
357
+ async getFormattedMessagesWithCompression(contributorContext, llmContext) {
358
+ const systemPrompt = await this.getSystemPrompt(contributorContext);
359
+ const systemPromptTokens = this.tokenizer.countTokens(systemPrompt);
360
+ let history = await this.historyProvider.getHistory();
361
+ history = await this.compressHistoryIfNeeded(history, systemPromptTokens);
362
+ const formattedMessages = await this.getFormattedMessages(
363
+ contributorContext,
364
+ llmContext,
365
+ systemPrompt,
366
+ history
367
+ );
368
+ const historyTokens = countMessagesTokens(history, this.tokenizer);
369
+ const formattingOverhead = Math.ceil((systemPromptTokens + historyTokens) * 0.05);
370
+ const tokensUsed = systemPromptTokens + historyTokens + formattingOverhead;
371
+ logger.debug(
372
+ `Final token breakdown - System: ${systemPromptTokens}, History: ${historyTokens}, Overhead: ${formattingOverhead}, Total: ${tokensUsed}`
373
+ );
374
+ return {
375
+ formattedMessages,
376
+ systemPrompt,
377
+ tokensUsed
378
+ };
379
+ }
380
+ /**
381
+ * Gets the system prompt formatted for the target LLM provider
382
+ * Some providers handle system prompts differently
383
+ *
384
+ * @returns Formatted system prompt or null/undefined based on formatter implementation
385
+ * @throws Error if formatting fails
386
+ */
387
+ async getFormattedSystemPrompt(context) {
388
+ const systemPrompt = await this.getSystemPrompt(context);
389
+ return this.formatter.formatSystemPrompt?.(systemPrompt);
390
+ }
391
+ /**
392
+ * Resets the conversation history
393
+ * Does not reset the system prompt
394
+ */
395
+ async resetConversation() {
396
+ await this.historyProvider.clearHistory();
397
+ logger.debug(`ContextManager: Conversation history cleared for session ${this.sessionId}`);
398
+ }
399
+ /**
400
+ * Checks if history compression is needed based on token count and applies strategies.
401
+ *
402
+ * @param history The conversation history to potentially compress
403
+ * @param systemPromptTokens The actual token count of the system prompt
404
+ * @returns The potentially compressed history
405
+ */
406
+ async compressHistoryIfNeeded(history, systemPromptTokens) {
407
+ let currentTotalTokens = countMessagesTokens(history, this.tokenizer);
408
+ currentTotalTokens += systemPromptTokens;
409
+ logger.debug(`ContextManager: Checking if history compression is needed.`);
410
+ logger.debug(
411
+ `History tokens: ${countMessagesTokens(history, this.tokenizer)}, System prompt tokens: ${systemPromptTokens}, Total: ${currentTotalTokens}`
412
+ );
413
+ if (currentTotalTokens <= this.maxInputTokens) {
414
+ logger.debug(
415
+ `ContextManager: History compression not needed. Total token count: ${currentTotalTokens}, Max tokens: ${this.maxInputTokens}`
416
+ );
417
+ return history;
418
+ }
419
+ logger.info(
420
+ `ContextManager: History exceeds token limit (${currentTotalTokens} > ${this.maxInputTokens}). Applying compression strategies sequentially.`
421
+ );
422
+ const initialLength = history.length;
423
+ let workingHistory = [...history];
424
+ const targetHistoryTokens = this.maxInputTokens - systemPromptTokens;
425
+ for (const strategy of this.compressionStrategies) {
426
+ const strategyName = strategy.constructor.name;
427
+ logger.debug(`ContextManager: Applying ${strategyName}...`);
428
+ try {
429
+ workingHistory = strategy.compress(
430
+ [...workingHistory],
431
+ this.tokenizer,
432
+ targetHistoryTokens
433
+ // Use target tokens that account for system prompt
434
+ );
435
+ } catch (error) {
436
+ logger.error(`ContextManager: Error applying ${strategyName}:`, error);
437
+ break;
438
+ }
439
+ const historyTokens = countMessagesTokens(workingHistory, this.tokenizer);
440
+ currentTotalTokens = historyTokens + systemPromptTokens;
441
+ const messagesRemoved = initialLength - workingHistory.length;
442
+ if (currentTotalTokens <= this.maxInputTokens) {
443
+ logger.debug(
444
+ `ContextManager: Compression successful after ${strategyName}. New total count: ${currentTotalTokens}, messages removed: ${messagesRemoved}`
445
+ );
446
+ break;
447
+ }
448
+ }
449
+ return workingHistory;
450
+ }
451
+ /**
452
+ * Parses a raw LLM stream response, converts it into internal messages and adds them to the history.
453
+ *
454
+ * @param response The stream response from the LLM provider
455
+ */
456
+ async processLLMStreamResponse(response) {
457
+ if (this.formatter.parseStreamResponse) {
458
+ const msgs = await this.formatter.parseStreamResponse(response) ?? [];
459
+ for (const msg of msgs) {
460
+ try {
461
+ await this.addMessage(msg);
462
+ } catch (error) {
463
+ logger.error(
464
+ `ContextManager: Failed to process LLM stream response message for session ${this.sessionId}: ${error instanceof Error ? error.message : String(error)}`
465
+ );
466
+ }
467
+ }
468
+ } else {
469
+ await this.processLLMResponse(response);
470
+ }
471
+ }
472
+ /**
473
+ * Parses a raw LLM response, converts it into internal messages and adds them to the history.
474
+ *
475
+ * @param response The response from the LLM provider
476
+ */
477
+ async processLLMResponse(response) {
478
+ const msgs = this.formatter.parseResponse(response) ?? [];
479
+ for (const msg of msgs) {
480
+ try {
481
+ await this.addMessage(msg);
482
+ } catch (error) {
483
+ logger.error(
484
+ `ContextManager: Failed to process LLM response message for session ${this.sessionId}: ${error instanceof Error ? error.message : String(error)}`
485
+ );
486
+ }
487
+ }
488
+ }
489
+ }
490
+ export {
491
+ ContextManager
492
+ };
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var types_exports = {};
16
+ module.exports = __toCommonJS(types_exports);
@@ -0,0 +1,113 @@
1
+ import { LLMProvider, LLMRouter } from '../llm/types.cjs';
2
+
3
+ /**
4
+ * Internal representation of a message in a conversation.
5
+ * Standardizes message format across different LLM providers.
6
+ */
7
+ interface ImageData {
8
+ image: string | Uint8Array | Buffer | ArrayBuffer | URL;
9
+ mimeType?: string;
10
+ }
11
+ interface FileData {
12
+ data: string | Uint8Array | Buffer | ArrayBuffer | URL;
13
+ mimeType: string;
14
+ filename?: string;
15
+ }
16
+ interface TextPart {
17
+ type: 'text';
18
+ text: string;
19
+ }
20
+ interface ImagePart extends ImageData {
21
+ type: 'image';
22
+ }
23
+ interface FilePart extends FileData {
24
+ type: 'file';
25
+ }
26
+ interface InternalMessage {
27
+ /**
28
+ * The role of the entity sending the message.
29
+ * - 'system': System instructions or context
30
+ * - 'user': End-user input
31
+ * - 'assistant': LLM response
32
+ * - 'tool': Result from a tool execution
33
+ */
34
+ role: 'system' | 'user' | 'assistant' | 'tool';
35
+ /**
36
+ * Timestamp when the message was created (Unix timestamp in milliseconds).
37
+ * TODO: Populate this field when messages are created. Currently not implemented.
38
+ * @see https://github.com/truffle-ai/dexto/issues/XXX
39
+ */
40
+ timestamp?: number;
41
+ /**
42
+ * The content of the message.
43
+ * - String for system, assistant (text only), and tool messages.
44
+ * - Array of parts for user messages (can include text, images, and files).
45
+ * - null if an assistant message only contains tool calls.
46
+ */
47
+ content: string | null | Array<TextPart | ImagePart | FilePart>;
48
+ /**
49
+ * Optional model reasoning text associated with an assistant response.
50
+ * Present when the provider supports reasoning and returns a final reasoning trace.
51
+ */
52
+ reasoning?: string;
53
+ /**
54
+ * Optional token usage accounting for this assistant response.
55
+ */
56
+ tokenUsage?: {
57
+ inputTokens?: number;
58
+ outputTokens?: number;
59
+ reasoningTokens?: number;
60
+ totalTokens?: number;
61
+ };
62
+ /**
63
+ * Optional model identifier for assistant messages.
64
+ * Indicates which LLM model generated this response.
65
+ */
66
+ model?: string;
67
+ /** Optional provider identifier for assistant messages. */
68
+ provider?: LLMProvider;
69
+ /**
70
+ * Optional router metadata for assistant messages.
71
+ * Indicates which router was used to route the request.
72
+ */
73
+ router?: LLMRouter;
74
+ /**
75
+ * Tool calls made by the assistant.
76
+ * Only present in assistant messages when the LLM requests tool execution.
77
+ */
78
+ toolCalls?: Array<{
79
+ /**
80
+ * Unique identifier for this tool call
81
+ */
82
+ id: string;
83
+ /**
84
+ * The type of tool call (currently only 'function' is supported)
85
+ */
86
+ type: 'function';
87
+ /**
88
+ * Function call details
89
+ */
90
+ function: {
91
+ /**
92
+ * Name of the function to call
93
+ */
94
+ name: string;
95
+ /**
96
+ * Arguments for the function in JSON string format
97
+ */
98
+ arguments: string;
99
+ };
100
+ }>;
101
+ /**
102
+ * ID of the tool call this message is responding to.
103
+ * Only present in tool messages.
104
+ */
105
+ toolCallId?: string;
106
+ /**
107
+ * Name of the tool that produced this result.
108
+ * Only present in tool messages.
109
+ */
110
+ name?: string;
111
+ }
112
+
113
+ export type { FileData, FilePart, ImageData, ImagePart, InternalMessage, TextPart };