@dexto/core 1.2.6 → 1.4.0

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 (515) hide show
  1. package/README.md +55 -13
  2. package/dist/agent/DextoAgent.cjs +627 -228
  3. package/dist/agent/DextoAgent.d.ts +157 -34
  4. package/dist/agent/DextoAgent.d.ts.map +1 -1
  5. package/dist/agent/DextoAgent.js +625 -227
  6. package/dist/agent/agentCard.js +1 -1
  7. package/dist/agent/error-codes.cjs +1 -0
  8. package/dist/agent/error-codes.d.ts +2 -1
  9. package/dist/agent/error-codes.d.ts.map +1 -1
  10. package/dist/agent/error-codes.js +2 -1
  11. package/dist/agent/errors.cjs +13 -0
  12. package/dist/agent/errors.d.ts +4 -0
  13. package/dist/agent/errors.d.ts.map +1 -1
  14. package/dist/agent/errors.js +14 -1
  15. package/dist/agent/index.d.ts +1 -1
  16. package/dist/agent/index.d.ts.map +1 -1
  17. package/dist/agent/index.js +1 -1
  18. package/dist/agent/schemas.cjs +4 -1
  19. package/dist/agent/schemas.d.ts +92 -55
  20. package/dist/agent/schemas.d.ts.map +1 -1
  21. package/dist/agent/schemas.js +7 -3
  22. package/dist/agent/state-manager.cjs +5 -5
  23. package/dist/agent/state-manager.d.ts +4 -4
  24. package/dist/agent/state-manager.js +6 -6
  25. package/dist/agent/types.d.ts +24 -11
  26. package/dist/agent/types.d.ts.map +1 -1
  27. package/dist/approval/error-codes.js +1 -1
  28. package/dist/approval/errors.js +1 -1
  29. package/dist/approval/factory.js +1 -1
  30. package/dist/approval/index.js +1 -1
  31. package/dist/approval/manager.cjs +69 -3
  32. package/dist/approval/manager.d.ts +41 -3
  33. package/dist/approval/manager.d.ts.map +1 -1
  34. package/dist/approval/manager.js +70 -4
  35. package/dist/approval/schemas.cjs +20 -5
  36. package/dist/approval/schemas.d.ts +127 -52
  37. package/dist/approval/schemas.d.ts.map +1 -1
  38. package/dist/approval/schemas.js +21 -6
  39. package/dist/approval/types.d.ts +6 -0
  40. package/dist/approval/types.d.ts.map +1 -1
  41. package/dist/approval/types.js +1 -1
  42. package/dist/{chunk-C6A6W6XS.js → chunk-PTJYTZNU.js} +44 -1
  43. package/dist/{llm/tokenizer/factory.cjs → context/compression/overflow.cjs} +20 -21
  44. package/dist/context/compression/overflow.d.ts +33 -0
  45. package/dist/context/compression/overflow.d.ts.map +1 -0
  46. package/dist/context/compression/overflow.js +19 -0
  47. package/dist/context/compression/reactive-overflow.cjs +201 -0
  48. package/dist/context/compression/reactive-overflow.d.ts +81 -0
  49. package/dist/context/compression/reactive-overflow.d.ts.map +1 -0
  50. package/dist/context/compression/reactive-overflow.js +178 -0
  51. package/dist/context/compression/types.d.ts +9 -7
  52. package/dist/context/compression/types.d.ts.map +1 -1
  53. package/dist/context/error-codes.cjs +3 -0
  54. package/dist/context/error-codes.d.ts +4 -1
  55. package/dist/context/error-codes.d.ts.map +1 -1
  56. package/dist/context/error-codes.js +4 -1
  57. package/dist/context/errors.cjs +28 -0
  58. package/dist/context/errors.d.ts +7 -0
  59. package/dist/context/errors.d.ts.map +1 -1
  60. package/dist/context/errors.js +29 -1
  61. package/dist/context/index.js +1 -1
  62. package/dist/context/manager.cjs +287 -323
  63. package/dist/context/manager.d.ts +65 -111
  64. package/dist/context/manager.d.ts.map +1 -1
  65. package/dist/context/manager.js +287 -328
  66. package/dist/context/media-helpers.js +1 -1
  67. package/dist/context/types.cjs +49 -0
  68. package/dist/context/types.d.ts +185 -72
  69. package/dist/context/types.d.ts.map +1 -1
  70. package/dist/context/types.js +35 -0
  71. package/dist/context/utils.cjs +266 -283
  72. package/dist/context/utils.d.ts +32 -18
  73. package/dist/context/utils.d.ts.map +1 -1
  74. package/dist/context/utils.js +266 -283
  75. package/dist/errors/DextoBaseError.js +1 -1
  76. package/dist/errors/DextoRuntimeError.js +1 -1
  77. package/dist/errors/DextoValidationError.js +1 -1
  78. package/dist/errors/index.js +1 -1
  79. package/dist/errors/result-bridge.js +1 -1
  80. package/dist/errors/types.cjs +1 -0
  81. package/dist/errors/types.d.ts +4 -2
  82. package/dist/errors/types.d.ts.map +1 -1
  83. package/dist/errors/types.js +2 -1
  84. package/dist/events/index.cjs +22 -2
  85. package/dist/events/index.d.ts +170 -62
  86. package/dist/events/index.d.ts.map +1 -1
  87. package/dist/events/index.js +23 -3
  88. package/dist/filesystem/error-codes.js +1 -1
  89. package/dist/filesystem/errors.js +1 -1
  90. package/dist/filesystem/filesystem-service.js +1 -1
  91. package/dist/filesystem/index.js +1 -1
  92. package/dist/filesystem/path-validator.js +1 -1
  93. package/dist/index.browser.cjs +23 -8
  94. package/dist/index.browser.d.ts +4 -3
  95. package/dist/index.browser.d.ts.map +1 -1
  96. package/dist/index.browser.js +20 -3
  97. package/dist/index.js +1 -1
  98. package/dist/llm/error-codes.cjs +0 -1
  99. package/dist/llm/error-codes.d.ts +0 -1
  100. package/dist/llm/error-codes.d.ts.map +1 -1
  101. package/dist/llm/error-codes.js +1 -2
  102. package/dist/llm/errors.cjs +10 -10
  103. package/dist/llm/errors.d.ts +5 -6
  104. package/dist/llm/errors.d.ts.map +1 -1
  105. package/dist/llm/errors.js +12 -12
  106. package/dist/llm/executor/stream-processor.cjs +367 -0
  107. package/dist/llm/executor/stream-processor.d.ts +55 -0
  108. package/dist/llm/executor/stream-processor.d.ts.map +1 -0
  109. package/dist/llm/executor/stream-processor.js +344 -0
  110. package/dist/llm/executor/tool-output-truncator.cjs +75 -0
  111. package/dist/llm/executor/tool-output-truncator.d.ts +27 -0
  112. package/dist/llm/executor/tool-output-truncator.d.ts.map +1 -0
  113. package/dist/llm/executor/tool-output-truncator.js +48 -0
  114. package/dist/llm/executor/turn-executor.cjs +753 -0
  115. package/dist/llm/executor/turn-executor.d.ts +166 -0
  116. package/dist/llm/executor/turn-executor.d.ts.map +1 -0
  117. package/dist/llm/executor/turn-executor.js +684 -0
  118. package/dist/llm/executor/types.d.ts +27 -0
  119. package/dist/llm/executor/types.d.ts.map +1 -0
  120. package/dist/llm/formatters/vercel.cjs +20 -186
  121. package/dist/llm/formatters/vercel.d.ts +2 -14
  122. package/dist/llm/formatters/vercel.d.ts.map +1 -1
  123. package/dist/llm/formatters/vercel.js +19 -185
  124. package/dist/llm/registry.cjs +36 -45
  125. package/dist/llm/registry.d.ts +53 -39
  126. package/dist/llm/registry.d.ts.map +1 -1
  127. package/dist/llm/registry.js +34 -42
  128. package/dist/llm/resolver.cjs +1 -31
  129. package/dist/llm/resolver.d.ts.map +1 -1
  130. package/dist/llm/resolver.js +2 -34
  131. package/dist/llm/schemas.cjs +2 -17
  132. package/dist/llm/schemas.d.ts +10 -23
  133. package/dist/llm/schemas.d.ts.map +1 -1
  134. package/dist/llm/schemas.js +5 -22
  135. package/dist/llm/services/factory.cjs +3 -92
  136. package/dist/llm/services/factory.d.ts +14 -4
  137. package/dist/llm/services/factory.d.ts.map +1 -1
  138. package/dist/llm/services/factory.js +4 -83
  139. package/dist/llm/services/test-utils.integration.cjs +6 -8
  140. package/dist/llm/services/test-utils.integration.d.ts.map +1 -1
  141. package/dist/llm/services/test-utils.integration.js +7 -9
  142. package/dist/llm/services/types.d.ts +1 -28
  143. package/dist/llm/services/types.d.ts.map +1 -1
  144. package/dist/llm/services/vercel.cjs +54 -468
  145. package/dist/llm/services/vercel.d.ts +38 -21
  146. package/dist/llm/services/vercel.d.ts.map +1 -1
  147. package/dist/llm/services/vercel.js +56 -475
  148. package/dist/llm/types.cjs +0 -3
  149. package/dist/llm/types.d.ts +8 -8
  150. package/dist/llm/types.d.ts.map +1 -1
  151. package/dist/llm/types.js +1 -3
  152. package/dist/llm/validation.js +1 -1
  153. package/dist/logger/browser.js +1 -1
  154. package/dist/logger/factory.js +1 -1
  155. package/dist/logger/index.js +1 -1
  156. package/dist/logger/logger.js +1 -1
  157. package/dist/logger/v2/dexto-logger.cjs +34 -6
  158. package/dist/logger/v2/dexto-logger.d.ts +20 -2
  159. package/dist/logger/v2/dexto-logger.d.ts.map +1 -1
  160. package/dist/logger/v2/dexto-logger.js +35 -7
  161. package/dist/logger/v2/error-codes.js +1 -1
  162. package/dist/logger/v2/errors.js +1 -1
  163. package/dist/logger/v2/schemas.cjs +1 -1
  164. package/dist/logger/v2/schemas.js +2 -2
  165. package/dist/logger/v2/test-utils.cjs +70 -0
  166. package/dist/logger/v2/test-utils.d.ts +17 -0
  167. package/dist/logger/v2/test-utils.d.ts.map +1 -0
  168. package/dist/logger/v2/test-utils.js +46 -0
  169. package/dist/logger/v2/transport-factory.js +1 -1
  170. package/dist/logger/v2/transports/console-transport.js +1 -1
  171. package/dist/logger/v2/transports/file-transport.cjs +6 -0
  172. package/dist/logger/v2/transports/file-transport.d.ts +4 -0
  173. package/dist/logger/v2/transports/file-transport.d.ts.map +1 -1
  174. package/dist/logger/v2/transports/file-transport.js +7 -1
  175. package/dist/logger/v2/types.cjs +1 -0
  176. package/dist/logger/v2/types.d.ts +18 -2
  177. package/dist/logger/v2/types.d.ts.map +1 -1
  178. package/dist/logger/v2/types.js +2 -1
  179. package/dist/mcp/error-codes.cjs +1 -0
  180. package/dist/mcp/error-codes.d.ts +1 -0
  181. package/dist/mcp/error-codes.d.ts.map +1 -1
  182. package/dist/mcp/error-codes.js +2 -1
  183. package/dist/mcp/errors.cjs +13 -0
  184. package/dist/mcp/errors.d.ts +7 -0
  185. package/dist/mcp/errors.d.ts.map +1 -1
  186. package/dist/mcp/errors.js +14 -1
  187. package/dist/mcp/manager.cjs +4 -0
  188. package/dist/mcp/manager.d.ts.map +1 -1
  189. package/dist/mcp/manager.js +5 -1
  190. package/dist/mcp/mcp-client.js +1 -1
  191. package/dist/mcp/resolver.js +1 -1
  192. package/dist/mcp/schemas.cjs +6 -0
  193. package/dist/mcp/schemas.d.ts +52 -0
  194. package/dist/mcp/schemas.d.ts.map +1 -1
  195. package/dist/mcp/schemas.js +6 -1
  196. package/dist/memory/error-codes.js +1 -1
  197. package/dist/memory/errors.js +1 -1
  198. package/dist/memory/index.js +1 -1
  199. package/dist/memory/manager.js +1 -1
  200. package/dist/memory/schemas.d.ts +2 -2
  201. package/dist/memory/schemas.js +1 -1
  202. package/dist/plugins/builtins/content-policy.js +1 -1
  203. package/dist/plugins/builtins/response-sanitizer.js +1 -1
  204. package/dist/plugins/error-codes.cjs +1 -0
  205. package/dist/plugins/error-codes.d.ts +3 -1
  206. package/dist/plugins/error-codes.d.ts.map +1 -1
  207. package/dist/plugins/error-codes.js +2 -1
  208. package/dist/plugins/index.js +1 -1
  209. package/dist/plugins/loader.cjs +25 -5
  210. package/dist/plugins/loader.d.ts.map +1 -1
  211. package/dist/plugins/loader.js +26 -6
  212. package/dist/plugins/manager.js +1 -1
  213. package/dist/plugins/registrations/builtins.js +1 -1
  214. package/dist/plugins/schemas.d.ts +3 -3
  215. package/dist/plugins/schemas.js +1 -1
  216. package/dist/plugins/types.d.ts +0 -1
  217. package/dist/plugins/types.d.ts.map +1 -1
  218. package/dist/process/command-validator.js +1 -1
  219. package/dist/process/error-codes.js +1 -1
  220. package/dist/process/errors.js +1 -1
  221. package/dist/process/index.js +1 -1
  222. package/dist/process/process-service.cjs +78 -26
  223. package/dist/process/process-service.d.ts +6 -1
  224. package/dist/process/process-service.d.ts.map +1 -1
  225. package/dist/process/process-service.js +79 -27
  226. package/dist/process/types.d.ts +2 -2
  227. package/dist/process/types.d.ts.map +1 -1
  228. package/dist/prompts/error-codes.cjs +1 -0
  229. package/dist/prompts/error-codes.d.ts +2 -1
  230. package/dist/prompts/error-codes.d.ts.map +1 -1
  231. package/dist/prompts/error-codes.js +2 -1
  232. package/dist/prompts/errors.cjs +15 -0
  233. package/dist/prompts/errors.d.ts +4 -0
  234. package/dist/prompts/errors.d.ts.map +1 -1
  235. package/dist/prompts/errors.js +16 -1
  236. package/dist/prompts/index.js +1 -1
  237. package/dist/prompts/name-validation.js +1 -1
  238. package/dist/prompts/prompt-manager.cjs +13 -2
  239. package/dist/prompts/prompt-manager.d.ts +7 -0
  240. package/dist/prompts/prompt-manager.d.ts.map +1 -1
  241. package/dist/prompts/prompt-manager.js +14 -3
  242. package/dist/prompts/providers/config-prompt-provider.cjs +12 -3
  243. package/dist/prompts/providers/config-prompt-provider.d.ts +2 -1
  244. package/dist/prompts/providers/config-prompt-provider.d.ts.map +1 -1
  245. package/dist/prompts/providers/config-prompt-provider.js +13 -4
  246. package/dist/prompts/providers/custom-prompt-provider.cjs +2 -2
  247. package/dist/prompts/providers/custom-prompt-provider.d.ts +1 -1
  248. package/dist/prompts/providers/custom-prompt-provider.d.ts.map +1 -1
  249. package/dist/prompts/providers/custom-prompt-provider.js +3 -3
  250. package/dist/prompts/providers/mcp-prompt-provider.js +1 -1
  251. package/dist/prompts/schemas.d.ts +12 -0
  252. package/dist/prompts/schemas.d.ts.map +1 -1
  253. package/dist/prompts/schemas.js +1 -1
  254. package/dist/prompts/types.d.ts +2 -0
  255. package/dist/prompts/types.d.ts.map +1 -1
  256. package/dist/prompts/utils.js +1 -1
  257. package/dist/resources/error-codes.js +1 -1
  258. package/dist/resources/errors.js +1 -1
  259. package/dist/resources/handlers/blob-handler.js +1 -1
  260. package/dist/resources/handlers/factory.js +1 -1
  261. package/dist/resources/handlers/filesystem-handler.js +1 -1
  262. package/dist/resources/index.js +1 -1
  263. package/dist/resources/internal-provider.js +1 -1
  264. package/dist/resources/manager.js +1 -1
  265. package/dist/resources/reference-parser.js +1 -1
  266. package/dist/resources/schemas.js +1 -1
  267. package/dist/search/index.js +1 -1
  268. package/dist/search/search-service.js +1 -1
  269. package/dist/session/chat-session.cjs +149 -51
  270. package/dist/session/chat-session.d.ts +69 -29
  271. package/dist/session/chat-session.d.ts.map +1 -1
  272. package/dist/session/chat-session.js +150 -52
  273. package/dist/session/error-codes.js +1 -1
  274. package/dist/session/errors.js +1 -1
  275. package/dist/session/history/database.cjs +134 -21
  276. package/dist/session/history/database.d.ts +37 -8
  277. package/dist/session/history/database.d.ts.map +1 -1
  278. package/dist/session/history/database.js +135 -22
  279. package/dist/session/history/factory.js +1 -1
  280. package/dist/session/history/memory.cjs +18 -0
  281. package/dist/session/history/memory.d.ts +8 -0
  282. package/dist/session/history/memory.d.ts.map +1 -1
  283. package/dist/session/history/memory.js +19 -1
  284. package/dist/session/history/types.d.ts +13 -1
  285. package/dist/session/history/types.d.ts.map +1 -1
  286. package/dist/session/index.cjs +3 -0
  287. package/dist/session/index.d.ts +3 -0
  288. package/dist/session/index.d.ts.map +1 -1
  289. package/dist/session/index.js +3 -1
  290. package/dist/session/message-queue.cjs +201 -0
  291. package/dist/session/message-queue.d.ts +114 -0
  292. package/dist/session/message-queue.d.ts.map +1 -0
  293. package/dist/session/message-queue.js +178 -0
  294. package/dist/session/schemas.js +1 -1
  295. package/dist/session/session-manager.cjs +57 -7
  296. package/dist/session/session-manager.d.ts +18 -0
  297. package/dist/session/session-manager.d.ts.map +1 -1
  298. package/dist/session/session-manager.js +58 -8
  299. package/dist/session/title-generator.cjs +4 -8
  300. package/dist/session/title-generator.d.ts +1 -2
  301. package/dist/session/title-generator.d.ts.map +1 -1
  302. package/dist/session/title-generator.js +5 -9
  303. package/dist/session/types.cjs +16 -0
  304. package/dist/session/types.d.ts +14 -0
  305. package/dist/session/types.d.ts.map +1 -0
  306. package/dist/session/types.js +0 -0
  307. package/dist/storage/blob/factory.js +1 -1
  308. package/dist/storage/blob/local-blob-store.js +1 -1
  309. package/dist/storage/blob/memory-blob-store.js +1 -1
  310. package/dist/storage/blob/schemas.js +1 -1
  311. package/dist/storage/cache/factory.cjs +6 -2
  312. package/dist/storage/cache/factory.d.ts +2 -1
  313. package/dist/storage/cache/factory.d.ts.map +1 -1
  314. package/dist/storage/cache/factory.js +7 -3
  315. package/dist/storage/cache/memory-cache-store.js +1 -1
  316. package/dist/storage/cache/redis-store.js +1 -1
  317. package/dist/storage/cache/schemas.js +1 -1
  318. package/dist/storage/database/factory.cjs +11 -17
  319. package/dist/storage/database/factory.d.ts +2 -1
  320. package/dist/storage/database/factory.d.ts.map +1 -1
  321. package/dist/storage/database/factory.js +12 -18
  322. package/dist/storage/database/memory-database-store.js +1 -1
  323. package/dist/storage/database/postgres-store.cjs +12 -0
  324. package/dist/storage/database/postgres-store.d.ts.map +1 -1
  325. package/dist/storage/database/postgres-store.js +13 -1
  326. package/dist/storage/database/schemas.js +1 -1
  327. package/dist/storage/database/sqlite-store.cjs +8 -0
  328. package/dist/storage/database/sqlite-store.d.ts.map +1 -1
  329. package/dist/storage/database/sqlite-store.js +9 -1
  330. package/dist/storage/error-codes.cjs +1 -0
  331. package/dist/storage/error-codes.d.ts +1 -0
  332. package/dist/storage/error-codes.d.ts.map +1 -1
  333. package/dist/storage/error-codes.js +2 -1
  334. package/dist/storage/errors.cjs +17 -0
  335. package/dist/storage/errors.d.ts +9 -0
  336. package/dist/storage/errors.d.ts.map +1 -1
  337. package/dist/storage/errors.js +18 -1
  338. package/dist/storage/index.js +1 -1
  339. package/dist/storage/schemas.js +1 -1
  340. package/dist/storage/storage-manager.js +1 -1
  341. package/dist/systemPrompt/contributors.js +1 -1
  342. package/dist/systemPrompt/error-codes.js +1 -1
  343. package/dist/systemPrompt/errors.js +1 -1
  344. package/dist/systemPrompt/in-built-prompts.js +1 -1
  345. package/dist/systemPrompt/index.js +1 -1
  346. package/dist/systemPrompt/manager.js +1 -1
  347. package/dist/systemPrompt/registry.js +1 -1
  348. package/dist/systemPrompt/schemas.d.ts +5 -5
  349. package/dist/systemPrompt/schemas.js +1 -1
  350. package/dist/telemetry/decorators.js +1 -1
  351. package/dist/{llm/tokenizer/default.cjs → telemetry/error-codes.cjs} +14 -19
  352. package/dist/telemetry/error-codes.d.ts +13 -0
  353. package/dist/telemetry/error-codes.d.ts.map +1 -0
  354. package/dist/telemetry/error-codes.js +13 -0
  355. package/dist/telemetry/errors.cjs +105 -0
  356. package/dist/telemetry/errors.d.ts +28 -0
  357. package/dist/telemetry/errors.d.ts.map +1 -0
  358. package/dist/telemetry/errors.js +82 -0
  359. package/dist/telemetry/exporters.js +1 -1
  360. package/dist/telemetry/index.js +1 -1
  361. package/dist/telemetry/schemas.js +1 -1
  362. package/dist/telemetry/telemetry.cjs +92 -26
  363. package/dist/telemetry/telemetry.d.ts +1 -1
  364. package/dist/telemetry/telemetry.d.ts.map +1 -1
  365. package/dist/telemetry/telemetry.js +75 -19
  366. package/dist/telemetry/utils.js +1 -1
  367. package/dist/tools/bash-pattern-utils.cjs +91 -0
  368. package/dist/tools/bash-pattern-utils.d.ts +58 -0
  369. package/dist/tools/bash-pattern-utils.d.ts.map +1 -0
  370. package/dist/tools/bash-pattern-utils.js +64 -0
  371. package/dist/tools/confirmation/allowed-tools-provider/factory.js +1 -1
  372. package/dist/tools/confirmation/allowed-tools-provider/in-memory.js +1 -1
  373. package/dist/tools/confirmation/allowed-tools-provider/storage.js +1 -1
  374. package/dist/tools/display-types.cjs +60 -0
  375. package/dist/tools/display-types.d.ts +133 -0
  376. package/dist/tools/display-types.d.ts.map +1 -0
  377. package/dist/tools/display-types.js +32 -0
  378. package/dist/tools/error-codes.cjs +2 -0
  379. package/dist/tools/error-codes.d.ts +3 -1
  380. package/dist/tools/error-codes.d.ts.map +1 -1
  381. package/dist/tools/error-codes.js +3 -1
  382. package/dist/tools/errors.cjs +30 -0
  383. package/dist/tools/errors.d.ts +16 -0
  384. package/dist/tools/errors.d.ts.map +1 -1
  385. package/dist/tools/errors.js +31 -1
  386. package/dist/tools/index.cjs +2 -0
  387. package/dist/tools/index.d.ts +1 -0
  388. package/dist/tools/index.d.ts.map +1 -1
  389. package/dist/tools/index.js +2 -1
  390. package/dist/tools/internal-tools/constants.js +1 -1
  391. package/dist/tools/internal-tools/implementations/ask-user-tool.cjs +1 -1
  392. package/dist/tools/internal-tools/implementations/ask-user-tool.js +2 -2
  393. package/dist/tools/internal-tools/implementations/bash-exec-tool.cjs +42 -18
  394. package/dist/tools/internal-tools/implementations/bash-exec-tool.d.ts +3 -3
  395. package/dist/tools/internal-tools/implementations/bash-exec-tool.d.ts.map +1 -1
  396. package/dist/tools/internal-tools/implementations/bash-exec-tool.js +43 -19
  397. package/dist/tools/internal-tools/implementations/bash-output-tool.js +1 -1
  398. package/dist/tools/internal-tools/implementations/delegate-to-url-tool.js +1 -1
  399. package/dist/tools/internal-tools/implementations/edit-file-tool.cjs +66 -1
  400. package/dist/tools/internal-tools/implementations/edit-file-tool.d.ts.map +1 -1
  401. package/dist/tools/internal-tools/implementations/edit-file-tool.js +67 -2
  402. package/dist/tools/internal-tools/implementations/glob-files-tool.cjs +14 -1
  403. package/dist/tools/internal-tools/implementations/glob-files-tool.d.ts.map +1 -1
  404. package/dist/tools/internal-tools/implementations/glob-files-tool.js +15 -2
  405. package/dist/tools/internal-tools/implementations/grep-content-tool.cjs +16 -1
  406. package/dist/tools/internal-tools/implementations/grep-content-tool.d.ts.map +1 -1
  407. package/dist/tools/internal-tools/implementations/grep-content-tool.js +17 -2
  408. package/dist/tools/internal-tools/implementations/kill-process-tool.js +1 -1
  409. package/dist/tools/internal-tools/implementations/read-file-tool.cjs +9 -1
  410. package/dist/tools/internal-tools/implementations/read-file-tool.d.ts.map +1 -1
  411. package/dist/tools/internal-tools/implementations/read-file-tool.js +10 -2
  412. package/dist/tools/internal-tools/implementations/search-history-tool.js +1 -1
  413. package/dist/tools/internal-tools/implementations/write-file-tool.cjs +69 -1
  414. package/dist/tools/internal-tools/implementations/write-file-tool.d.ts.map +1 -1
  415. package/dist/tools/internal-tools/implementations/write-file-tool.js +72 -2
  416. package/dist/tools/internal-tools/provider.cjs +27 -10
  417. package/dist/tools/internal-tools/provider.d.ts +8 -5
  418. package/dist/tools/internal-tools/provider.d.ts.map +1 -1
  419. package/dist/tools/internal-tools/provider.js +28 -11
  420. package/dist/tools/internal-tools/registry.cjs +4 -3
  421. package/dist/tools/internal-tools/registry.d.ts +28 -7
  422. package/dist/tools/internal-tools/registry.d.ts.map +1 -1
  423. package/dist/tools/internal-tools/registry.js +5 -4
  424. package/dist/tools/schemas.cjs +17 -7
  425. package/dist/tools/schemas.d.ts +31 -4
  426. package/dist/tools/schemas.d.ts.map +1 -1
  427. package/dist/tools/schemas.js +15 -7
  428. package/dist/tools/tool-manager.cjs +140 -18
  429. package/dist/tools/tool-manager.d.ts +23 -1
  430. package/dist/tools/tool-manager.d.ts.map +1 -1
  431. package/dist/tools/tool-manager.js +145 -19
  432. package/dist/tools/types.d.ts +20 -11
  433. package/dist/tools/types.d.ts.map +1 -1
  434. package/dist/utils/api-key-resolver.js +1 -1
  435. package/dist/utils/async-context.js +1 -1
  436. package/dist/utils/debug.js +1 -1
  437. package/dist/{llm/tokenizer/types.cjs → utils/defer.cjs} +19 -10
  438. package/dist/utils/defer.d.ts +63 -0
  439. package/dist/utils/defer.d.ts.map +1 -0
  440. package/dist/utils/defer.js +19 -0
  441. package/dist/utils/env-file.js +1 -1
  442. package/dist/utils/error-conversion.js +1 -1
  443. package/dist/utils/execution-context.js +1 -1
  444. package/dist/utils/fs-walk.js +1 -1
  445. package/dist/utils/index.cjs +3 -1
  446. package/dist/utils/index.d.ts +1 -0
  447. package/dist/utils/index.d.ts.map +1 -1
  448. package/dist/utils/index.js +1 -0
  449. package/dist/utils/path.js +1 -1
  450. package/dist/utils/redactor.js +1 -1
  451. package/dist/utils/result.js +1 -1
  452. package/dist/utils/safe-stringify.js +1 -1
  453. package/dist/utils/schema-metadata.js +1 -1
  454. package/dist/utils/schema.d.ts +6 -0
  455. package/dist/utils/schema.d.ts.map +1 -1
  456. package/dist/utils/schema.js +1 -1
  457. package/dist/utils/service-initializer.cjs +6 -2
  458. package/dist/utils/service-initializer.d.ts.map +1 -1
  459. package/dist/utils/service-initializer.js +7 -3
  460. package/dist/utils/user-info.js +1 -1
  461. package/dist/utils/zod-schema-converter.js +1 -1
  462. package/package.json +54 -17
  463. package/dist/context/compression/middle-removal.cjs +0 -95
  464. package/dist/context/compression/middle-removal.d.ts +0 -47
  465. package/dist/context/compression/middle-removal.d.ts.map +0 -1
  466. package/dist/context/compression/middle-removal.js +0 -72
  467. package/dist/context/compression/oldest-removal.cjs +0 -83
  468. package/dist/context/compression/oldest-removal.d.ts +0 -42
  469. package/dist/context/compression/oldest-removal.d.ts.map +0 -1
  470. package/dist/context/compression/oldest-removal.js +0 -60
  471. package/dist/llm/formatters/anthropic.cjs +0 -257
  472. package/dist/llm/formatters/anthropic.d.ts +0 -46
  473. package/dist/llm/formatters/anthropic.d.ts.map +0 -1
  474. package/dist/llm/formatters/anthropic.js +0 -239
  475. package/dist/llm/formatters/factory.cjs +0 -50
  476. package/dist/llm/formatters/factory.d.ts +0 -10
  477. package/dist/llm/formatters/factory.d.ts.map +0 -1
  478. package/dist/llm/formatters/factory.js +0 -27
  479. package/dist/llm/formatters/openai.cjs +0 -196
  480. package/dist/llm/formatters/openai.d.ts +0 -39
  481. package/dist/llm/formatters/openai.d.ts.map +0 -1
  482. package/dist/llm/formatters/openai.js +0 -177
  483. package/dist/llm/formatters/types.d.ts +0 -41
  484. package/dist/llm/formatters/types.d.ts.map +0 -1
  485. package/dist/llm/services/anthropic.cjs +0 -511
  486. package/dist/llm/services/anthropic.d.ts +0 -48
  487. package/dist/llm/services/anthropic.d.ts.map +0 -1
  488. package/dist/llm/services/anthropic.js +0 -447
  489. package/dist/llm/services/openai.cjs +0 -611
  490. package/dist/llm/services/openai.d.ts +0 -48
  491. package/dist/llm/services/openai.d.ts.map +0 -1
  492. package/dist/llm/services/openai.js +0 -547
  493. package/dist/llm/tokenizer/anthropic.cjs +0 -43
  494. package/dist/llm/tokenizer/anthropic.d.ts +0 -19
  495. package/dist/llm/tokenizer/anthropic.d.ts.map +0 -1
  496. package/dist/llm/tokenizer/anthropic.js +0 -20
  497. package/dist/llm/tokenizer/default.d.ts +0 -14
  498. package/dist/llm/tokenizer/default.d.ts.map +0 -1
  499. package/dist/llm/tokenizer/default.js +0 -18
  500. package/dist/llm/tokenizer/factory.d.ts +0 -12
  501. package/dist/llm/tokenizer/factory.d.ts.map +0 -1
  502. package/dist/llm/tokenizer/factory.js +0 -21
  503. package/dist/llm/tokenizer/google.cjs +0 -52
  504. package/dist/llm/tokenizer/google.d.ts +0 -29
  505. package/dist/llm/tokenizer/google.d.ts.map +0 -1
  506. package/dist/llm/tokenizer/google.js +0 -29
  507. package/dist/llm/tokenizer/openai.cjs +0 -115
  508. package/dist/llm/tokenizer/openai.d.ts +0 -33
  509. package/dist/llm/tokenizer/openai.d.ts.map +0 -1
  510. package/dist/llm/tokenizer/openai.js +0 -91
  511. package/dist/llm/tokenizer/types.d.ts +0 -18
  512. package/dist/llm/tokenizer/types.d.ts.map +0 -1
  513. package/dist/llm/tokenizer/types.js +0 -10
  514. /package/dist/llm/{formatters → executor}/types.cjs +0 -0
  515. /package/dist/llm/{formatters → executor}/types.js +0 -0
@@ -31,9 +31,9 @@ __export(manager_exports, {
31
31
  ContextManager: () => ContextManager
32
32
  });
33
33
  module.exports = __toCommonJS(manager_exports);
34
- var import_middle_removal = require("./compression/middle-removal.js");
35
- var import_oldest_removal = require("./compression/oldest-removal.js");
36
- var import_types6 = require("../logger/v2/types.js");
34
+ var import_crypto = require("crypto");
35
+ var import_types2 = require("./types.js");
36
+ var import_types3 = require("../logger/v2/types.js");
37
37
  var import_events = require("../events/index.js");
38
38
  var import_utils = require("./utils.js");
39
39
  var import_errors = require("./errors.js");
@@ -54,27 +54,6 @@ class ContextManager {
54
54
  * Maximum number of tokens allowed in the conversation (if specified)
55
55
  */
56
56
  maxInputTokens;
57
- /**
58
- * Actual token count from the last LLM response.
59
- * Used for more accurate token estimation in hybrid approach.
60
- */
61
- lastActualTokenCount = 0;
62
- /**
63
- * Compression threshold as a percentage of maxInputTokens.
64
- * When estimated tokens exceed (maxInputTokens * threshold), compression is triggered.
65
- */
66
- compressionThreshold = 0.8;
67
- // 80% threshold
68
- /**
69
- * Tokenizer used for counting tokens and enabling compression (if specified)
70
- */
71
- tokenizer;
72
- /**
73
- * The sequence of compression strategies to apply when maxInputTokens is exceeded.
74
- * The order in this array matters, as strategies are applied sequentially until
75
- * the token count is within the limit.
76
- */
77
- compressionStrategies;
78
57
  historyProvider;
79
58
  sessionId;
80
59
  /**
@@ -89,28 +68,21 @@ class ContextManager {
89
68
  * @param llmConfig The validated LLM configuration.
90
69
  * @param formatter Formatter implementation for the target LLM provider
91
70
  * @param systemPromptManager SystemPromptManager instance for the conversation
92
- * @param maxInputTokens Maximum token limit for the conversation history. Triggers compression if exceeded and a tokenizer is provided.
93
- * @param tokenizer Tokenizer implementation used for counting tokens and enabling compression.
71
+ * @param maxInputTokens Maximum token limit for the conversation history.
94
72
  * @param historyProvider Session-scoped ConversationHistoryProvider instance for managing conversation history
95
73
  * @param sessionId Unique identifier for the conversation session (readonly, for debugging)
96
- * @param compressionStrategies Optional array of compression strategies to apply when token limits are exceeded
97
- * @param resourceManager Optional ResourceManager for resolving blob references in messages
74
+ * @param resourceManager ResourceManager for resolving blob references in messages
98
75
  * @param logger Logger instance for logging
99
76
  */
100
- constructor(llmConfig, formatter, systemPromptManager, maxInputTokens, tokenizer, historyProvider, sessionId, resourceManager, logger, compressionStrategies = [
101
- new import_middle_removal.MiddleRemovalStrategy({}, logger),
102
- new import_oldest_removal.OldestRemovalStrategy({}, logger)
103
- ]) {
77
+ constructor(llmConfig, formatter, systemPromptManager, maxInputTokens, historyProvider, sessionId, resourceManager, logger) {
104
78
  this.llmConfig = llmConfig;
105
79
  this.formatter = formatter;
106
80
  this.systemPromptManager = systemPromptManager;
107
81
  this.maxInputTokens = maxInputTokens;
108
- this.tokenizer = tokenizer;
109
82
  this.historyProvider = historyProvider;
110
83
  this.sessionId = sessionId;
111
- this.compressionStrategies = compressionStrategies;
112
84
  this.resourceManager = resourceManager;
113
- this.logger = logger.createChild(import_types6.DextoLogComponent.CONTEXT);
85
+ this.logger = logger.createChild(import_types3.DextoLogComponent.CONTEXT);
114
86
  this.logger.debug(
115
87
  `ContextManager: Initialized for session ${sessionId} - history will be managed by ${historyProvider.constructor.name}`
116
88
  );
@@ -175,117 +147,177 @@ class ContextManager {
175
147
  return data;
176
148
  }
177
149
  /**
178
- * Returns the current token count of the conversation history.
179
- * @returns Promise that resolves to the number of tokens in the current history
150
+ * Returns the configured maximum number of input tokens for the conversation.
180
151
  */
181
- async getTokenCount() {
182
- const history = await this.historyProvider.getHistory();
183
- return (0, import_utils.countMessagesTokens)(history, this.tokenizer, void 0, this.logger);
152
+ getMaxInputTokens() {
153
+ return this.maxInputTokens;
184
154
  }
185
155
  /**
186
- * Returns the total token count that will be sent to the LLM provider,
187
- * including system prompt, formatted messages, and provider-specific overhead.
188
- * This provides a more accurate estimate than getTokenCount() alone.
156
+ * Assembles and returns the current system prompt by invoking the SystemPromptManager.
157
+ */
158
+ async getSystemPrompt(context) {
159
+ const prompt = await this.systemPromptManager.build(context);
160
+ this.logger.debug(`[SystemPrompt] Built system prompt:
161
+ ${prompt}`);
162
+ return prompt;
163
+ }
164
+ /**
165
+ * Gets the raw conversation history
166
+ * Returns a defensive copy to prevent modification
189
167
  *
190
- * @param context The DynamicContributorContext for system prompt contributors
191
- * @returns Promise that resolves to the total number of tokens that will be sent to the provider
168
+ * @returns Promise that resolves to a read-only copy of the conversation history
192
169
  */
193
- async getTotalTokenCount(context) {
194
- try {
195
- const systemPrompt = await this.getSystemPrompt(context);
196
- let history = await this.historyProvider.getHistory();
197
- const systemPromptTokens = this.tokenizer.countTokens(systemPrompt);
198
- history = await this.compressHistoryIfNeeded(history, systemPromptTokens);
199
- const historyTokens = (0, import_utils.countMessagesTokens)(
200
- history,
201
- this.tokenizer,
202
- void 0,
203
- this.logger
204
- );
205
- const formattingOverhead = Math.ceil((systemPromptTokens + historyTokens) * 0.05);
206
- const totalTokens = systemPromptTokens + historyTokens + formattingOverhead;
207
- this.logger.debug(
208
- `Token breakdown - System: ${systemPromptTokens}, History: ${historyTokens}, Overhead: ${formattingOverhead}, Total: ${totalTokens}`
209
- );
210
- return totalTokens;
211
- } catch (error) {
212
- this.logger.error(
213
- `Error calculating total token count: ${error instanceof Error ? error.message : String(error)}`,
214
- { error }
215
- );
216
- return this.getTokenCount();
217
- }
170
+ async getHistory() {
171
+ const history = await this.historyProvider.getHistory();
172
+ return [...history];
218
173
  }
219
174
  /**
220
- * Returns the configured maximum number of input tokens for the conversation.
175
+ * Flush any pending history updates to durable storage.
176
+ * Should be called at turn boundaries (after streaming completes, on cancel, on error).
177
+ * This ensures all message updates are persisted before returning control to the caller.
221
178
  */
222
- getMaxInputTokens() {
223
- return this.maxInputTokens;
179
+ async flush() {
180
+ await this.historyProvider.flush();
224
181
  }
225
182
  /**
226
- * Updates the ContextManager configuration when LLM config changes.
227
- * This is called when DextoAgent.switchLLM() updates the LLM configuration.
183
+ * Clears the context window without deleting history.
184
+ *
185
+ * This adds a "context clear" marker to the conversation history. When the
186
+ * context is loaded for LLM via getFormattedMessagesWithCompression(),
187
+ * filterCompacted() excludes all messages before this marker.
228
188
  *
229
- * @param newMaxInputTokens New maximum token limit
230
- * @param newTokenizer Optional new tokenizer if provider changed
231
- * @param newFormatter Optional new formatter if provider/router changed
189
+ * The full history remains in the database for review via /resume or session history.
232
190
  */
233
- updateConfig(newMaxInputTokens, newTokenizer, newFormatter) {
234
- const oldMaxInputTokens = this.maxInputTokens;
235
- this.maxInputTokens = newMaxInputTokens;
236
- if (newTokenizer) {
237
- this.tokenizer = newTokenizer;
238
- }
239
- if (newFormatter) {
240
- this.formatter = newFormatter;
241
- }
242
- this.logger.debug(
243
- `ContextManager config updated: maxInputTokens ${oldMaxInputTokens} -> ${newMaxInputTokens}`
244
- );
191
+ async clearContext() {
192
+ const clearMarker = {
193
+ id: `clear-${Date.now()}`,
194
+ role: "assistant",
195
+ content: [{ type: "text", text: "[Context cleared]" }],
196
+ timestamp: Date.now(),
197
+ metadata: {
198
+ isSummary: true,
199
+ clearedAt: Date.now()
200
+ }
201
+ };
202
+ await this.addMessage(clearMarker);
203
+ this.logger.debug(`Context cleared for session: ${this.sessionId}`);
245
204
  }
246
205
  /**
247
- * Updates the actual token count from the last LLM response.
248
- * This enables hybrid token counting for more accurate estimates.
249
- *
250
- * @param actualTokens The actual token count reported by the LLM provider
206
+ * Appends text to an existing assistant message.
207
+ * Used for streaming responses.
251
208
  */
252
- updateActualTokenCount(actualTokens) {
253
- this.lastActualTokenCount = actualTokens;
254
- this.logger.debug(`Updated actual token count to: ${actualTokens}`);
209
+ async appendAssistantText(messageId, text) {
210
+ const history = await this.historyProvider.getHistory();
211
+ const messageIndex = history.findIndex((m) => m.id === messageId);
212
+ if (messageIndex === -1) {
213
+ throw import_errors.ContextError.messageNotFound(messageId);
214
+ }
215
+ const message = history[messageIndex];
216
+ if (!message) {
217
+ throw import_errors.ContextError.messageNotFound(messageId);
218
+ }
219
+ if (message.role !== "assistant") {
220
+ throw import_errors.ContextError.messageNotAssistant(messageId);
221
+ }
222
+ if (message.content === null) {
223
+ message.content = [{ type: "text", text }];
224
+ } else if (Array.isArray(message.content)) {
225
+ const lastPart = message.content[message.content.length - 1];
226
+ if (lastPart && lastPart.type === "text") {
227
+ lastPart.text += text;
228
+ } else {
229
+ message.content.push({ type: "text", text });
230
+ }
231
+ }
232
+ await this.historyProvider.updateMessage(message);
255
233
  }
256
234
  /**
257
- * Estimates if new input would trigger compression using hybrid approach.
258
- * Combines actual tokens from last response with estimated tokens for new input.
259
- *
260
- * @param newInputTokens Estimated tokens for the new user input
261
- * @returns True if compression should be triggered
235
+ * Adds a tool call to an existing assistant message.
236
+ * Used for streaming responses.
262
237
  */
263
- shouldCompress(newInputTokens) {
264
- const estimatedTotal = this.lastActualTokenCount + newInputTokens;
265
- const compressionTrigger = this.maxInputTokens * this.compressionThreshold;
266
- this.logger.debug(
267
- `Compression check: actual=${this.lastActualTokenCount}, newInput=${newInputTokens}, total=${estimatedTotal}, trigger=${compressionTrigger}`
268
- );
269
- return estimatedTotal > compressionTrigger;
238
+ async addToolCall(messageId, toolCall) {
239
+ const history = await this.historyProvider.getHistory();
240
+ const messageIndex = history.findIndex((m) => m.id === messageId);
241
+ if (messageIndex === -1) {
242
+ throw import_errors.ContextError.messageNotFound(messageId);
243
+ }
244
+ const message = history[messageIndex];
245
+ if (!message) {
246
+ throw import_errors.ContextError.messageNotFound(messageId);
247
+ }
248
+ if (message.role !== "assistant") {
249
+ throw import_errors.ContextError.messageNotAssistant(messageId);
250
+ }
251
+ if (!message.toolCalls) {
252
+ message.toolCalls = [];
253
+ }
254
+ message.toolCalls.push(toolCall);
255
+ await this.historyProvider.updateMessage(message);
270
256
  }
271
257
  /**
272
- * Assembles and returns the current system prompt by invoking the SystemPromptManager.
258
+ * Updates an existing assistant message with new properties.
259
+ * Used for finalizing streaming responses (e.g. adding token usage).
273
260
  */
274
- async getSystemPrompt(context) {
275
- const prompt = await this.systemPromptManager.build(context);
276
- this.logger.debug(`[SystemPrompt] Built system prompt:
277
- ${prompt}`);
278
- return prompt;
261
+ async updateAssistantMessage(messageId, updates) {
262
+ const history = await this.historyProvider.getHistory();
263
+ const messageIndex = history.findIndex((m) => m.id === messageId);
264
+ if (messageIndex === -1) {
265
+ throw import_errors.ContextError.messageNotFound(messageId);
266
+ }
267
+ const message = history[messageIndex];
268
+ if (!message) {
269
+ throw import_errors.ContextError.messageNotFound(messageId);
270
+ }
271
+ if (message.role !== "assistant") {
272
+ throw import_errors.ContextError.messageNotAssistant(messageId);
273
+ }
274
+ Object.assign(message, updates);
275
+ await this.historyProvider.updateMessage(message);
279
276
  }
280
277
  /**
281
- * Gets the raw conversation history
282
- * Returns a defensive copy to prevent modification
278
+ * Marks tool messages as compacted (pruned).
279
+ * Sets the compactedAt timestamp - content transformation happens at format time
280
+ * in getFormattedMessagesWithCompression(). Original content is preserved in
281
+ * storage for debugging/audit.
283
282
  *
284
- * @returns Promise that resolves to a read-only copy of the conversation history
283
+ * Used by TurnExecutor's pruneOldToolOutputs() to reclaim token space
284
+ * by marking old tool outputs that are no longer needed for context.
285
+ *
286
+ * @param messageIds Array of message IDs to mark as compacted
287
+ * @returns Number of messages successfully marked
285
288
  */
286
- async getHistory() {
289
+ async markMessagesAsCompacted(messageIds) {
290
+ if (messageIds.length === 0) {
291
+ return 0;
292
+ }
287
293
  const history = await this.historyProvider.getHistory();
288
- return [...history];
294
+ const timestamp = Date.now();
295
+ let markedCount = 0;
296
+ for (const messageId of messageIds) {
297
+ const message = history.find((m) => m.id === messageId);
298
+ if (!message) {
299
+ this.logger.warn(`markMessagesAsCompacted: Message ${messageId} not found`);
300
+ continue;
301
+ }
302
+ if (message.role !== "tool") {
303
+ this.logger.warn(
304
+ `markMessagesAsCompacted: Message ${messageId} is not a tool message (role=${message.role})`
305
+ );
306
+ continue;
307
+ }
308
+ if (message.compactedAt) {
309
+ continue;
310
+ }
311
+ message.compactedAt = timestamp;
312
+ await this.historyProvider.updateMessage(message);
313
+ markedCount++;
314
+ }
315
+ if (markedCount > 0) {
316
+ this.logger.debug(
317
+ `markMessagesAsCompacted: Marked ${markedCount} messages as compacted`
318
+ );
319
+ }
320
+ return markedCount;
289
321
  }
290
322
  /**
291
323
  * Adds a message to the conversation history.
@@ -298,10 +330,7 @@ ${prompt}`);
298
330
  async addMessage(message) {
299
331
  switch (message.role) {
300
332
  case "user":
301
- if (
302
- // Allow array content for user messages
303
- !(Array.isArray(message.content) && message.content.length > 0) && (typeof message.content !== "string" || message.content.trim() === "")
304
- ) {
333
+ if (!Array.isArray(message.content) || message.content.length === 0) {
305
334
  throw import_errors.ContextError.userMessageContentInvalid();
306
335
  }
307
336
  break;
@@ -317,7 +346,6 @@ ${prompt}`);
317
346
  }
318
347
  }
319
348
  message.provider = this.llmConfig.provider;
320
- message.router = this.llmConfig.router;
321
349
  message.model = this.llmConfig.model;
322
350
  break;
323
351
  case "tool":
@@ -325,14 +353,22 @@ ${prompt}`);
325
353
  throw import_errors.ContextError.toolMessageFieldsMissing();
326
354
  }
327
355
  break;
328
- case "system":
356
+ case "system": {
329
357
  this.logger.warn(
330
- "ContextManager: Adding system message directly to history. Use setSystemPrompt instead."
358
+ "ContextManager: Adding system message directly to history. Use SystemPromptManager instead."
331
359
  );
332
- if (typeof message.content !== "string" || message.content.trim() === "") {
360
+ const textContent = message.content?.filter((p) => p.type === "text").map((p) => p.text).join("");
361
+ if (!textContent || textContent.trim() === "") {
333
362
  throw import_errors.ContextError.systemMessageContentInvalid();
334
363
  }
335
364
  break;
365
+ }
366
+ }
367
+ if (!message.id) {
368
+ message.id = (0, import_crypto.randomUUID)();
369
+ }
370
+ if (!message.timestamp) {
371
+ message.timestamp = Date.now();
336
372
  }
337
373
  this.logger.debug(
338
374
  `ContextManager: Adding message to history provider: ${JSON.stringify(message, null, 2)}`
@@ -342,57 +378,64 @@ ${prompt}`);
342
378
  this.logger.debug(`ContextManager: History now contains ${history.length} messages`);
343
379
  }
344
380
  /**
345
- * Adds a user message to the conversation
346
- * Can include image data for multimodal input
381
+ * Adds a user message to the conversation.
382
+ * Supports multiple images and files via ContentPart[].
347
383
  *
348
- * @param textContent The user message content
349
- * @param imageData Optional image data for multimodal input
350
- * @param fileData Optional file data for file input
351
- * @throws Error if content is empty or not a string
384
+ * @param content Array of content parts (text, images, files)
385
+ * @throws Error if content is empty or invalid
352
386
  */
353
- async addUserMessage(textContent, imageData, fileData) {
354
- if (typeof textContent !== "string" || textContent.trim() === "" && !imageData && !fileData) {
387
+ async addUserMessage(content) {
388
+ if (!Array.isArray(content) || content.length === 0) {
355
389
  throw import_errors.ContextError.userMessageContentEmpty();
356
390
  }
357
- const finalTextContent = textContent.trim() || (imageData || fileData ? "" : textContent);
358
- const messageParts = [];
359
- if (finalTextContent) {
360
- messageParts.push({ type: "text", text: finalTextContent });
361
- }
362
- if (imageData) {
363
- const processedImage = await this.processUserInput(imageData.image, {
364
- mimeType: imageData.mimeType || "image/jpeg",
365
- source: "user"
366
- });
367
- messageParts.push({
368
- type: "image",
369
- image: processedImage,
370
- mimeType: imageData.mimeType || "image/jpeg"
371
- });
391
+ const hasText = content.some((p) => p.type === "text" && p.text.trim() !== "");
392
+ const hasAttachment = content.some((p) => p.type === "image" || p.type === "file");
393
+ if (!hasText && !hasAttachment) {
394
+ throw import_errors.ContextError.userMessageContentEmpty();
372
395
  }
373
- if (fileData) {
374
- const metadata = {
375
- mimeType: fileData.mimeType,
376
- source: "user"
377
- };
378
- if (fileData.filename) {
379
- metadata.originalName = fileData.filename;
396
+ const processedParts = [];
397
+ for (const part of content) {
398
+ if (part.type === "text") {
399
+ if (part.text.trim()) {
400
+ processedParts.push({ type: "text", text: part.text });
401
+ }
402
+ } else if (part.type === "image") {
403
+ const processedImage = await this.processUserInput(part.image, {
404
+ mimeType: part.mimeType || "image/jpeg",
405
+ source: "user"
406
+ });
407
+ processedParts.push({
408
+ type: "image",
409
+ image: processedImage,
410
+ mimeType: part.mimeType || "image/jpeg"
411
+ });
412
+ } else if (part.type === "file") {
413
+ const metadata = {
414
+ mimeType: part.mimeType,
415
+ source: "user"
416
+ };
417
+ if (part.filename) {
418
+ metadata.originalName = part.filename;
419
+ }
420
+ const processedData = await this.processUserInput(part.data, metadata);
421
+ processedParts.push({
422
+ type: "file",
423
+ data: processedData,
424
+ mimeType: part.mimeType,
425
+ ...part.filename && { filename: part.filename }
426
+ });
380
427
  }
381
- const processedData = await this.processUserInput(fileData.data, metadata);
382
- messageParts.push({
383
- type: "file",
384
- data: processedData,
385
- mimeType: fileData.mimeType,
386
- ...fileData.filename && { filename: fileData.filename }
387
- });
388
- }
389
- if (messageParts.length === 0) {
390
- messageParts.push({ type: "text", text: finalTextContent });
391
428
  }
392
- this.logger.debug(
393
- `ContextManager: Adding user message: ${JSON.stringify(messageParts, null, 2)}`
394
- );
395
- await this.addMessage({ role: "user", content: messageParts });
429
+ const textParts = processedParts.filter((p) => p.type === "text");
430
+ const imageParts = processedParts.filter((p) => p.type === "image");
431
+ const fileParts = processedParts.filter((p) => p.type === "file");
432
+ this.logger.info("User message received", {
433
+ textParts: textParts.length,
434
+ imageParts: imageParts.length,
435
+ fileParts: fileParts.length,
436
+ totalParts: processedParts.length
437
+ });
438
+ await this.addMessage({ role: "user", content: processedParts });
396
439
  }
397
440
  /**
398
441
  * Adds an assistant message to the conversation
@@ -407,54 +450,50 @@ ${prompt}`);
407
450
  if (content === null && (!toolCalls || toolCalls.length === 0)) {
408
451
  throw import_errors.ContextError.assistantMessageContentOrToolsRequired();
409
452
  }
453
+ const contentArray = content !== null ? [{ type: "text", text: content }] : null;
410
454
  await this.addMessage({
411
455
  role: "assistant",
412
- content,
456
+ content: contentArray,
413
457
  ...toolCalls && toolCalls.length > 0 && { toolCalls },
414
458
  ...metadata?.tokenUsage && { tokenUsage: metadata.tokenUsage },
415
459
  ...metadata?.reasoning && { reasoning: metadata.reasoning }
416
460
  });
417
461
  }
418
462
  /**
419
- * Adds a tool result message to the conversation
463
+ * Adds a tool result message to the conversation.
464
+ * The result must already be sanitized - this method only persists it.
465
+ *
466
+ * Success status is read from sanitizedResult.meta.success (single source of truth).
420
467
  *
421
468
  * @param toolCallId ID of the tool call this result is responding to
422
469
  * @param name Name of the tool that executed
423
- * @param result The result returned by the tool
470
+ * @param sanitizedResult The already-sanitized result to store (includes success in meta)
471
+ * @param metadata Optional approval-related metadata
424
472
  * @throws Error if required parameters are missing
425
473
  */
426
- async addToolResult(toolCallId, name, result, options) {
474
+ async addToolResult(toolCallId, name, sanitizedResult, metadata) {
427
475
  if (!toolCallId || !name) {
428
476
  throw import_errors.ContextError.toolCallIdNameRequired();
429
477
  }
430
- const blobService = this.resourceManager.getBlobStore();
431
- const sanitizeOptions = {
432
- blobStore: blobService,
433
- toolName: name,
434
- toolCallId
435
- };
436
- if (options?.success !== void 0) {
437
- sanitizeOptions.success = options.success;
438
- }
439
- const sanitized = await (0, import_utils.sanitizeToolResult)(result, sanitizeOptions, this.logger);
440
- const summary = sanitized.content.map(
441
- (p) => p.type === "text" ? `text(${p.text.length})` : p.type === "image" ? `image(${p.mimeType || "image"})` : `file(${p.mimeType || "file"})`
478
+ const summary = sanitizedResult.content.map(
479
+ (p) => p.type === "text" ? `text(${p.text.length})` : p.type === "image" ? `image(${p.mimeType || "image"})` : p.type === "ui-resource" ? `ui-resource(${p.uri})` : `file(${p.mimeType || "file"})`
442
480
  ).join(", ");
443
481
  this.logger.debug(`ContextManager: Storing tool result (parts) for ${name}: [${summary}]`);
444
482
  await this.addMessage({
445
483
  role: "tool",
446
- content: sanitized.content,
484
+ content: sanitizedResult.content,
447
485
  toolCallId,
448
- name
486
+ name,
487
+ // Success status comes from sanitizedResult.meta (single source of truth)
488
+ success: sanitizedResult.meta.success,
489
+ // Persist approval metadata for frontend display after reload
490
+ ...metadata?.requireApproval !== void 0 && {
491
+ requireApproval: metadata.requireApproval
492
+ },
493
+ ...metadata?.approvalStatus !== void 0 && {
494
+ approvalStatus: metadata.approvalStatus
495
+ }
449
496
  });
450
- return sanitized;
451
- }
452
- /**
453
- * Sets the system prompt for the conversation
454
- *
455
- * @param prompt The system prompt text
456
- */
457
- setSystemPrompt(_prompt) {
458
497
  }
459
498
  /**
460
499
  * Gets the conversation history formatted for the target LLM provider.
@@ -498,13 +537,28 @@ ${prompt}`);
498
537
  this.logger.debug("Resolving blob references in message history before formatting");
499
538
  messageHistory = await Promise.all(
500
539
  messageHistory.map(async (message) => {
501
- const expandedContent = await (0, import_utils.expandBlobReferences)(
502
- message.content,
503
- this.resourceManager,
504
- this.logger,
505
- allowedMediaTypes
506
- );
507
- return { ...message, content: expandedContent };
540
+ if ((0, import_types2.isSystemMessage)(message) || (0, import_types2.isAssistantMessage)(message)) {
541
+ return message;
542
+ }
543
+ if ((0, import_types2.isUserMessage)(message)) {
544
+ const expandedContent = await (0, import_utils.expandBlobReferences)(
545
+ message.content,
546
+ this.resourceManager,
547
+ this.logger,
548
+ allowedMediaTypes
549
+ );
550
+ return { ...message, content: expandedContent };
551
+ }
552
+ if ((0, import_types2.isToolMessage)(message)) {
553
+ const expandedContent = await (0, import_utils.expandBlobReferences)(
554
+ message.content,
555
+ this.resourceManager,
556
+ this.logger,
557
+ allowedMediaTypes
558
+ );
559
+ return { ...message, content: expandedContent };
560
+ }
561
+ return message;
508
562
  })
509
563
  );
510
564
  const prompt = systemPrompt ?? await this.getSystemPrompt(contributorContext);
@@ -513,7 +567,7 @@ ${prompt}`);
513
567
  /**
514
568
  * Gets the conversation ready for LLM consumption with proper flow:
515
569
  * 1. Get system prompt
516
- * 2. Get history and compress if needed
570
+ * 2. Get history and filter (exclude pre-summary messages)
517
571
  * 3. Format messages
518
572
  * This method implements the correct ordering to avoid circular dependencies.
519
573
  *
@@ -523,25 +577,39 @@ ${prompt}`);
523
577
  */
524
578
  async getFormattedMessagesWithCompression(contributorContext, llmContext) {
525
579
  const systemPrompt = await this.getSystemPrompt(contributorContext);
526
- const systemPromptTokens = this.tokenizer.countTokens(systemPrompt);
527
- let history = await this.historyProvider.getHistory();
528
- history = await this.compressHistoryIfNeeded(history, systemPromptTokens);
580
+ const fullHistory = await this.historyProvider.getHistory();
581
+ let history = (0, import_utils.filterCompacted)(fullHistory);
582
+ if (history.length < fullHistory.length) {
583
+ this.logger.debug(
584
+ `filterCompacted: Reduced history from ${fullHistory.length} to ${history.length} messages (summary present)`
585
+ );
586
+ }
587
+ const compactedCount = history.filter((m) => m.role === "tool" && m.compactedAt).length;
588
+ if (compactedCount > 0) {
589
+ history = history.map((msg) => {
590
+ if (msg.role === "tool" && msg.compactedAt) {
591
+ return {
592
+ ...msg,
593
+ content: [
594
+ { type: "text", text: "[Old tool result content cleared]" }
595
+ ]
596
+ };
597
+ }
598
+ return msg;
599
+ });
600
+ this.logger.debug(
601
+ `Transformed ${compactedCount} compacted tool messages to placeholders`
602
+ );
603
+ }
529
604
  const formattedMessages = await this.getFormattedMessages(
530
605
  contributorContext,
531
606
  llmContext,
532
607
  systemPrompt,
533
608
  history
534
609
  );
535
- const historyTokens = (0, import_utils.countMessagesTokens)(history, this.tokenizer, void 0, this.logger);
536
- const formattingOverhead = Math.ceil((systemPromptTokens + historyTokens) * 0.05);
537
- const tokensUsed = systemPromptTokens + historyTokens + formattingOverhead;
538
- this.logger.debug(
539
- `Final token breakdown - System: ${systemPromptTokens}, History: ${historyTokens}, Overhead: ${formattingOverhead}, Total: ${tokensUsed}`
540
- );
541
610
  return {
542
611
  formattedMessages,
543
- systemPrompt,
544
- tokensUsed
612
+ systemPrompt
545
613
  };
546
614
  }
547
615
  /**
@@ -551,9 +619,8 @@ ${prompt}`);
551
619
  * @returns Formatted system prompt or null/undefined based on formatter implementation
552
620
  * @throws Error if formatting fails
553
621
  */
554
- async getFormattedSystemPrompt(context) {
555
- const systemPrompt = await this.getSystemPrompt(context);
556
- return this.formatter.formatSystemPrompt?.(systemPrompt);
622
+ async getFormattedSystemPrompt(_context) {
623
+ return this.formatter.formatSystemPrompt?.();
557
624
  }
558
625
  /**
559
626
  * Resets the conversation history
@@ -565,109 +632,6 @@ ${prompt}`);
565
632
  `ContextManager: Conversation history cleared for session ${this.sessionId}`
566
633
  );
567
634
  }
568
- /**
569
- * Checks if history compression is needed based on token count and applies strategies.
570
- *
571
- * @param history The conversation history to potentially compress
572
- * @param systemPromptTokens The actual token count of the system prompt
573
- * @returns The potentially compressed history
574
- */
575
- async compressHistoryIfNeeded(history, systemPromptTokens) {
576
- let currentTotalTokens = (0, import_utils.countMessagesTokens)(
577
- history,
578
- this.tokenizer,
579
- void 0,
580
- this.logger
581
- );
582
- currentTotalTokens += systemPromptTokens;
583
- this.logger.debug(`ContextManager: Checking if history compression is needed.`);
584
- this.logger.debug(
585
- `History tokens: ${(0, import_utils.countMessagesTokens)(history, this.tokenizer, void 0, this.logger)}, System prompt tokens: ${systemPromptTokens}, Total: ${currentTotalTokens}`
586
- );
587
- if (currentTotalTokens <= this.maxInputTokens) {
588
- this.logger.debug(
589
- `ContextManager: History compression not needed. Total token count: ${currentTotalTokens}, Max tokens: ${this.maxInputTokens}`
590
- );
591
- return history;
592
- }
593
- this.logger.info(
594
- `ContextManager: History exceeds token limit (${currentTotalTokens} > ${this.maxInputTokens}). Applying compression strategies sequentially.`
595
- );
596
- const initialLength = history.length;
597
- let workingHistory = [...history];
598
- const targetHistoryTokens = this.maxInputTokens - systemPromptTokens;
599
- for (const strategy of this.compressionStrategies) {
600
- const strategyName = strategy.constructor.name;
601
- this.logger.debug(`ContextManager: Applying ${strategyName}...`);
602
- try {
603
- workingHistory = strategy.compress(
604
- [...workingHistory],
605
- this.tokenizer,
606
- targetHistoryTokens
607
- // Use target tokens that account for system prompt
608
- );
609
- } catch (error) {
610
- this.logger.error(
611
- `ContextManager: Error applying ${strategyName}: ${error instanceof Error ? error.message : String(error)}`,
612
- { error }
613
- );
614
- break;
615
- }
616
- const historyTokens = (0, import_utils.countMessagesTokens)(
617
- workingHistory,
618
- this.tokenizer,
619
- void 0,
620
- this.logger
621
- );
622
- currentTotalTokens = historyTokens + systemPromptTokens;
623
- const messagesRemoved = initialLength - workingHistory.length;
624
- if (currentTotalTokens <= this.maxInputTokens) {
625
- this.logger.debug(
626
- `ContextManager: Compression successful after ${strategyName}. New total count: ${currentTotalTokens}, messages removed: ${messagesRemoved}`
627
- );
628
- break;
629
- }
630
- }
631
- return workingHistory;
632
- }
633
- /**
634
- * Parses a raw LLM stream response, converts it into internal messages and adds them to the history.
635
- *
636
- * @param response The stream response from the LLM provider
637
- */
638
- async processLLMStreamResponse(response) {
639
- if (this.formatter.parseStreamResponse) {
640
- const msgs = await this.formatter.parseStreamResponse(response) ?? [];
641
- for (const msg of msgs) {
642
- try {
643
- await this.addMessage(msg);
644
- } catch (error) {
645
- this.logger.error(
646
- `ContextManager: Failed to process LLM stream response message for session ${this.sessionId}: ${error instanceof Error ? error.message : String(error)}`
647
- );
648
- }
649
- }
650
- } else {
651
- await this.processLLMResponse(response);
652
- }
653
- }
654
- /**
655
- * Parses a raw LLM response, converts it into internal messages and adds them to the history.
656
- *
657
- * @param response The response from the LLM provider
658
- */
659
- async processLLMResponse(response) {
660
- const msgs = this.formatter.parseResponse(response) ?? [];
661
- for (const msg of msgs) {
662
- try {
663
- await this.addMessage(msg);
664
- } catch (error) {
665
- this.logger.error(
666
- `ContextManager: Failed to process LLM response message for session ${this.sessionId}: ${error instanceof Error ? error.message : String(error)}`
667
- );
668
- }
669
- }
670
- }
671
635
  }
672
636
  // Annotate the CommonJS export names for ESM import in node:
673
637
  0 && (module.exports = {