@aigne/core 1.72.0 → 1.74.0-beta

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 (827) hide show
  1. package/README.md +11 -11
  2. package/dist/_virtual/rolldown_runtime.cjs +29 -0
  3. package/dist/agents/agent.cjs +874 -0
  4. package/dist/agents/agent.d.cts +967 -0
  5. package/dist/agents/agent.d.cts.map +1 -0
  6. package/dist/agents/agent.d.mts +967 -0
  7. package/dist/agents/agent.d.mts.map +1 -0
  8. package/dist/agents/agent.mjs +863 -0
  9. package/dist/agents/agent.mjs.map +1 -0
  10. package/dist/agents/ai-agent.cjs +524 -0
  11. package/dist/agents/ai-agent.d.cts +401 -0
  12. package/dist/agents/ai-agent.d.cts.map +1 -0
  13. package/dist/agents/ai-agent.d.mts +401 -0
  14. package/dist/agents/ai-agent.d.mts.map +1 -0
  15. package/dist/agents/ai-agent.mjs +519 -0
  16. package/dist/agents/ai-agent.mjs.map +1 -0
  17. package/dist/agents/chat-model.cjs +397 -0
  18. package/dist/agents/chat-model.d.cts +674 -0
  19. package/dist/agents/chat-model.d.cts.map +1 -0
  20. package/dist/agents/chat-model.d.mts +674 -0
  21. package/dist/agents/chat-model.d.mts.map +1 -0
  22. package/dist/agents/chat-model.mjs +391 -0
  23. package/dist/agents/chat-model.mjs.map +1 -0
  24. package/dist/agents/guide-rail-agent.cjs +17 -0
  25. package/dist/agents/guide-rail-agent.d.cts +67 -0
  26. package/dist/agents/guide-rail-agent.d.cts.map +1 -0
  27. package/dist/agents/guide-rail-agent.d.mts +67 -0
  28. package/dist/agents/guide-rail-agent.d.mts.map +1 -0
  29. package/dist/agents/guide-rail-agent.mjs +17 -0
  30. package/dist/agents/guide-rail-agent.mjs.map +1 -0
  31. package/dist/agents/image-agent.cjs +74 -0
  32. package/dist/agents/image-agent.d.cts +44 -0
  33. package/dist/agents/image-agent.d.cts.map +1 -0
  34. package/dist/agents/image-agent.d.mts +44 -0
  35. package/dist/agents/image-agent.d.mts.map +1 -0
  36. package/dist/agents/image-agent.mjs +72 -0
  37. package/dist/agents/image-agent.mjs.map +1 -0
  38. package/dist/agents/image-model.cjs +83 -0
  39. package/dist/agents/image-model.d.cts +276 -0
  40. package/dist/agents/image-model.d.cts.map +1 -0
  41. package/dist/agents/image-model.d.mts +276 -0
  42. package/dist/agents/image-model.d.mts.map +1 -0
  43. package/dist/agents/image-model.mjs +81 -0
  44. package/dist/agents/image-model.mjs.map +1 -0
  45. package/dist/agents/mcp-agent.cjs +307 -0
  46. package/dist/agents/mcp-agent.d.cts +235 -0
  47. package/dist/agents/mcp-agent.d.cts.map +1 -0
  48. package/dist/agents/mcp-agent.d.mts +235 -0
  49. package/dist/agents/mcp-agent.d.mts.map +1 -0
  50. package/dist/agents/mcp-agent.mjs +303 -0
  51. package/dist/agents/mcp-agent.mjs.map +1 -0
  52. package/dist/agents/model.cjs +143 -0
  53. package/dist/agents/model.d.cts +257 -0
  54. package/dist/agents/model.d.cts.map +1 -0
  55. package/dist/agents/model.d.mts +257 -0
  56. package/dist/agents/model.d.mts.map +1 -0
  57. package/dist/agents/model.mjs +136 -0
  58. package/dist/agents/model.mjs.map +1 -0
  59. package/dist/agents/team-agent.cjs +342 -0
  60. package/dist/agents/team-agent.d.cts +390 -0
  61. package/dist/agents/team-agent.d.cts.map +1 -0
  62. package/dist/agents/team-agent.d.mts +390 -0
  63. package/dist/agents/team-agent.d.mts.map +1 -0
  64. package/dist/agents/team-agent.mjs +339 -0
  65. package/dist/agents/team-agent.mjs.map +1 -0
  66. package/dist/agents/transform-agent.cjs +77 -0
  67. package/dist/agents/transform-agent.d.cts +99 -0
  68. package/dist/agents/transform-agent.d.cts.map +1 -0
  69. package/dist/agents/transform-agent.d.mts +99 -0
  70. package/dist/agents/transform-agent.d.mts.map +1 -0
  71. package/dist/agents/transform-agent.mjs +76 -0
  72. package/dist/agents/transform-agent.mjs.map +1 -0
  73. package/dist/agents/types.cjs +30 -0
  74. package/dist/agents/types.d.cts +34 -0
  75. package/dist/agents/types.d.cts.map +1 -0
  76. package/dist/agents/types.d.mts +34 -0
  77. package/dist/agents/types.d.mts.map +1 -0
  78. package/dist/agents/types.mjs +25 -0
  79. package/dist/agents/types.mjs.map +1 -0
  80. package/dist/agents/user-agent.cjs +87 -0
  81. package/dist/agents/user-agent.d.cts +32 -0
  82. package/dist/agents/user-agent.d.cts.map +1 -0
  83. package/dist/agents/user-agent.d.mts +32 -0
  84. package/dist/agents/user-agent.d.mts.map +1 -0
  85. package/dist/agents/user-agent.mjs +88 -0
  86. package/dist/agents/user-agent.mjs.map +1 -0
  87. package/dist/agents/video-model.cjs +66 -0
  88. package/dist/agents/video-model.d.cts +286 -0
  89. package/dist/agents/video-model.d.cts.map +1 -0
  90. package/dist/agents/video-model.d.mts +286 -0
  91. package/dist/agents/video-model.d.mts.map +1 -0
  92. package/dist/agents/video-model.mjs +64 -0
  93. package/dist/agents/video-model.mjs.map +1 -0
  94. package/dist/aigne/aigne.cjs +235 -0
  95. package/dist/aigne/aigne.d.cts +340 -0
  96. package/dist/aigne/aigne.d.cts.map +1 -0
  97. package/dist/aigne/aigne.d.mts +340 -0
  98. package/dist/aigne/aigne.d.mts.map +1 -0
  99. package/dist/aigne/aigne.mjs +235 -0
  100. package/dist/aigne/aigne.mjs.map +1 -0
  101. package/dist/aigne/context.cjs +377 -0
  102. package/dist/aigne/context.d.cts +226 -0
  103. package/dist/aigne/context.d.cts.map +1 -0
  104. package/dist/aigne/context.d.mts +226 -0
  105. package/dist/aigne/context.d.mts.map +1 -0
  106. package/dist/aigne/context.mjs +376 -0
  107. package/dist/aigne/context.mjs.map +1 -0
  108. package/dist/aigne/index.cjs +4 -0
  109. package/dist/aigne/index.d.mts +5 -0
  110. package/dist/aigne/index.mjs +6 -0
  111. package/dist/aigne/message-queue.cjs +102 -0
  112. package/dist/aigne/message-queue.d.cts +52 -0
  113. package/dist/aigne/message-queue.d.cts.map +1 -0
  114. package/dist/aigne/message-queue.d.mts +52 -0
  115. package/dist/aigne/message-queue.d.mts.map +1 -0
  116. package/dist/aigne/message-queue.mjs +99 -0
  117. package/dist/aigne/message-queue.mjs.map +1 -0
  118. package/dist/aigne/type.d.cts +32 -0
  119. package/dist/aigne/type.d.cts.map +1 -0
  120. package/dist/aigne/type.d.mts +32 -0
  121. package/dist/aigne/type.d.mts.map +1 -0
  122. package/dist/aigne/usage.cjs +29 -0
  123. package/dist/aigne/usage.d.cts +32 -0
  124. package/dist/aigne/usage.d.cts.map +1 -0
  125. package/dist/aigne/usage.d.mts +32 -0
  126. package/dist/aigne/usage.d.mts.map +1 -0
  127. package/dist/aigne/usage.mjs +28 -0
  128. package/dist/aigne/usage.mjs.map +1 -0
  129. package/dist/index.cjs +142 -0
  130. package/dist/index.d.cts +29 -0
  131. package/dist/index.d.mts +31 -0
  132. package/dist/index.mjs +31 -0
  133. package/dist/loader/agent-js.cjs +23 -0
  134. package/dist/loader/agent-js.d.cts +9 -0
  135. package/dist/loader/agent-js.d.cts.map +1 -0
  136. package/dist/loader/agent-js.d.mts +10 -0
  137. package/dist/loader/agent-js.d.mts.map +1 -0
  138. package/dist/loader/agent-js.mjs +23 -0
  139. package/dist/loader/agent-js.mjs.map +1 -0
  140. package/dist/loader/agent-yaml.cjs +109 -0
  141. package/dist/loader/agent-yaml.d.cts +87 -0
  142. package/dist/loader/agent-yaml.d.cts.map +1 -0
  143. package/dist/loader/agent-yaml.d.mts +87 -0
  144. package/dist/loader/agent-yaml.d.mts.map +1 -0
  145. package/dist/loader/agent-yaml.mjs +106 -0
  146. package/dist/loader/agent-yaml.mjs.map +1 -0
  147. package/dist/loader/agents.cjs +19 -0
  148. package/dist/loader/agents.d.cts +9 -0
  149. package/dist/loader/agents.d.cts.map +1 -0
  150. package/dist/loader/agents.d.mts +9 -0
  151. package/dist/loader/agents.d.mts.map +1 -0
  152. package/dist/loader/agents.mjs +20 -0
  153. package/dist/loader/agents.mjs.map +1 -0
  154. package/dist/loader/error.cjs +6 -0
  155. package/dist/loader/error.d.cts +5 -0
  156. package/dist/loader/error.d.cts.map +1 -0
  157. package/dist/loader/error.d.mts +5 -0
  158. package/dist/loader/error.d.mts.map +1 -0
  159. package/dist/loader/error.mjs +6 -0
  160. package/dist/loader/error.mjs.map +1 -0
  161. package/dist/loader/function-agent.cjs +9 -0
  162. package/dist/loader/function-agent.d.cts +7 -0
  163. package/dist/loader/function-agent.d.cts.map +1 -0
  164. package/dist/loader/function-agent.d.mts +7 -0
  165. package/dist/loader/function-agent.d.mts.map +1 -0
  166. package/dist/loader/function-agent.mjs +9 -0
  167. package/dist/loader/function-agent.mjs.map +1 -0
  168. package/dist/loader/index.cjs +233 -0
  169. package/dist/loader/index.d.cts +255 -0
  170. package/dist/loader/index.d.cts.map +1 -0
  171. package/dist/loader/index.d.mts +255 -0
  172. package/dist/loader/index.d.mts.map +1 -0
  173. package/dist/loader/index.mjs +228 -0
  174. package/dist/loader/index.mjs.map +1 -0
  175. package/dist/loader/schema.cjs +135 -0
  176. package/dist/loader/schema.d.cts +177 -0
  177. package/dist/loader/schema.d.cts.map +1 -0
  178. package/dist/loader/schema.d.mts +177 -0
  179. package/dist/loader/schema.d.mts.map +1 -0
  180. package/dist/loader/schema.mjs +127 -0
  181. package/dist/loader/schema.mjs.map +1 -0
  182. package/dist/memory/index.cjs +3 -0
  183. package/dist/memory/index.d.mts +3 -0
  184. package/dist/memory/index.mjs +5 -0
  185. package/dist/memory/memory.cjs +134 -0
  186. package/dist/memory/memory.d.cts +103 -0
  187. package/dist/memory/memory.d.cts.map +1 -0
  188. package/dist/memory/memory.d.mts +103 -0
  189. package/dist/memory/memory.d.mts.map +1 -0
  190. package/dist/memory/memory.mjs +133 -0
  191. package/dist/memory/memory.mjs.map +1 -0
  192. package/dist/memory/recorder.cjs +61 -0
  193. package/dist/memory/recorder.d.cts +98 -0
  194. package/dist/memory/recorder.d.cts.map +1 -0
  195. package/dist/memory/recorder.d.mts +98 -0
  196. package/dist/memory/recorder.d.mts.map +1 -0
  197. package/dist/memory/recorder.mjs +59 -0
  198. package/dist/memory/recorder.mjs.map +1 -0
  199. package/dist/memory/retriever.cjs +60 -0
  200. package/dist/memory/retriever.d.cts +111 -0
  201. package/dist/memory/retriever.d.cts.map +1 -0
  202. package/dist/memory/retriever.d.mts +111 -0
  203. package/dist/memory/retriever.d.mts.map +1 -0
  204. package/dist/memory/retriever.mjs +58 -0
  205. package/dist/memory/retriever.mjs.map +1 -0
  206. package/dist/prompt/agent-session.cjs +700 -0
  207. package/dist/prompt/agent-session.d.cts +167 -0
  208. package/dist/prompt/agent-session.d.cts.map +1 -0
  209. package/dist/prompt/agent-session.d.mts +167 -0
  210. package/dist/prompt/agent-session.d.mts.map +1 -0
  211. package/dist/prompt/agent-session.mjs +700 -0
  212. package/dist/prompt/agent-session.mjs.map +1 -0
  213. package/dist/prompt/compact/compactor.cjs +50 -0
  214. package/dist/prompt/compact/compactor.mjs +50 -0
  215. package/dist/prompt/compact/compactor.mjs.map +1 -0
  216. package/dist/prompt/compact/session-memory-extractor.cjs +137 -0
  217. package/dist/prompt/compact/session-memory-extractor.mjs +137 -0
  218. package/dist/prompt/compact/session-memory-extractor.mjs.map +1 -0
  219. package/dist/prompt/compact/types.cjs +59 -0
  220. package/dist/prompt/compact/types.d.cts +341 -0
  221. package/dist/prompt/compact/types.d.cts.map +1 -0
  222. package/dist/prompt/compact/types.d.mts +341 -0
  223. package/dist/prompt/compact/types.d.mts.map +1 -0
  224. package/dist/prompt/compact/types.mjs +49 -0
  225. package/dist/prompt/compact/types.mjs.map +1 -0
  226. package/dist/prompt/compact/user-memory-extractor.cjs +118 -0
  227. package/dist/prompt/compact/user-memory-extractor.mjs +118 -0
  228. package/dist/prompt/compact/user-memory-extractor.mjs.map +1 -0
  229. package/dist/prompt/context/afs/history.cjs +30 -0
  230. package/dist/prompt/context/afs/history.mjs +30 -0
  231. package/dist/prompt/context/afs/history.mjs.map +1 -0
  232. package/dist/prompt/context/afs/index.cjs +60 -0
  233. package/dist/prompt/context/afs/index.mjs +61 -0
  234. package/dist/prompt/context/afs/index.mjs.map +1 -0
  235. package/dist/prompt/context/index.cjs +18 -0
  236. package/dist/prompt/context/index.mjs +19 -0
  237. package/dist/prompt/context/index.mjs.map +1 -0
  238. package/dist/prompt/filters/index.cjs +22 -0
  239. package/dist/prompt/filters/index.mjs +21 -0
  240. package/dist/prompt/filters/index.mjs.map +1 -0
  241. package/dist/prompt/prompt-builder.cjs +291 -0
  242. package/dist/prompt/prompt-builder.d.cts +57 -0
  243. package/dist/prompt/prompt-builder.d.cts.map +1 -0
  244. package/dist/prompt/prompt-builder.d.mts +57 -0
  245. package/dist/prompt/prompt-builder.d.mts.map +1 -0
  246. package/dist/prompt/prompt-builder.mjs +291 -0
  247. package/dist/prompt/prompt-builder.mjs.map +1 -0
  248. package/dist/prompt/prompts/afs-builtin-prompt.cjs +12 -0
  249. package/dist/prompt/prompts/afs-builtin-prompt.mjs +13 -0
  250. package/dist/prompt/prompts/afs-builtin-prompt.mjs.map +1 -0
  251. package/dist/prompt/prompts/memory-message-template.cjs +10 -0
  252. package/dist/prompt/prompts/memory-message-template.mjs +10 -0
  253. package/dist/prompt/prompts/memory-message-template.mjs.map +1 -0
  254. package/dist/prompt/prompts/structured-stream-instructions.cjs +30 -0
  255. package/dist/prompt/prompts/structured-stream-instructions.mjs +30 -0
  256. package/dist/prompt/prompts/structured-stream-instructions.mjs.map +1 -0
  257. package/dist/prompt/skills/afs/agent-skill/agent-skill.cjs +66 -0
  258. package/dist/prompt/skills/afs/agent-skill/agent-skill.mjs +66 -0
  259. package/dist/prompt/skills/afs/agent-skill/agent-skill.mjs.map +1 -0
  260. package/dist/prompt/skills/afs/agent-skill/skill-loader.cjs +42 -0
  261. package/dist/prompt/skills/afs/agent-skill/skill-loader.mjs +41 -0
  262. package/dist/prompt/skills/afs/agent-skill/skill-loader.mjs.map +1 -0
  263. package/dist/prompt/skills/afs/base.cjs +9 -0
  264. package/dist/prompt/skills/afs/base.mjs +10 -0
  265. package/dist/prompt/skills/afs/base.mjs.map +1 -0
  266. package/dist/prompt/skills/afs/delete.cjs +50 -0
  267. package/dist/prompt/skills/afs/delete.mjs +50 -0
  268. package/dist/prompt/skills/afs/delete.mjs.map +1 -0
  269. package/dist/prompt/skills/afs/edit.cjs +92 -0
  270. package/dist/prompt/skills/afs/edit.mjs +92 -0
  271. package/dist/prompt/skills/afs/edit.mjs.map +1 -0
  272. package/dist/prompt/skills/afs/exec.cjs +36 -0
  273. package/dist/prompt/skills/afs/exec.mjs +36 -0
  274. package/dist/prompt/skills/afs/exec.mjs.map +1 -0
  275. package/dist/prompt/skills/afs/index.cjs +28 -0
  276. package/dist/prompt/skills/afs/index.mjs +29 -0
  277. package/dist/prompt/skills/afs/index.mjs.map +1 -0
  278. package/dist/prompt/skills/afs/list.cjs +69 -0
  279. package/dist/prompt/skills/afs/list.mjs +69 -0
  280. package/dist/prompt/skills/afs/list.mjs.map +1 -0
  281. package/dist/prompt/skills/afs/read.cjs +86 -0
  282. package/dist/prompt/skills/afs/read.mjs +86 -0
  283. package/dist/prompt/skills/afs/read.mjs.map +1 -0
  284. package/dist/prompt/skills/afs/rename.cjs +53 -0
  285. package/dist/prompt/skills/afs/rename.mjs +53 -0
  286. package/dist/prompt/skills/afs/rename.mjs.map +1 -0
  287. package/dist/prompt/skills/afs/search.cjs +63 -0
  288. package/dist/prompt/skills/afs/search.mjs +63 -0
  289. package/dist/prompt/skills/afs/search.mjs.map +1 -0
  290. package/dist/prompt/skills/afs/write.cjs +51 -0
  291. package/dist/prompt/skills/afs/write.mjs +51 -0
  292. package/dist/prompt/skills/afs/write.mjs.map +1 -0
  293. package/dist/prompt/template.cjs +229 -0
  294. package/dist/prompt/template.d.cts +247 -0
  295. package/dist/prompt/template.d.cts.map +1 -0
  296. package/dist/prompt/template.d.mts +247 -0
  297. package/dist/prompt/template.d.mts.map +1 -0
  298. package/dist/prompt/template.mjs +219 -0
  299. package/dist/prompt/template.mjs.map +1 -0
  300. package/dist/utils/agent-utils.cjs +49 -0
  301. package/dist/utils/agent-utils.d.cts +22 -0
  302. package/dist/utils/agent-utils.d.cts.map +1 -0
  303. package/dist/utils/agent-utils.d.mts +22 -0
  304. package/dist/utils/agent-utils.d.mts.map +1 -0
  305. package/dist/utils/agent-utils.mjs +46 -0
  306. package/dist/utils/agent-utils.mjs.map +1 -0
  307. package/dist/utils/camelize.cjs +34 -0
  308. package/dist/utils/camelize.d.cts +9 -0
  309. package/dist/utils/camelize.d.cts.map +1 -0
  310. package/dist/utils/camelize.d.mts +9 -0
  311. package/dist/utils/camelize.d.mts.map +1 -0
  312. package/dist/utils/camelize.mjs +33 -0
  313. package/dist/utils/camelize.mjs.map +1 -0
  314. package/dist/utils/event-stream.cjs +136 -0
  315. package/dist/utils/event-stream.d.cts +20 -0
  316. package/dist/utils/event-stream.d.cts.map +1 -0
  317. package/dist/utils/event-stream.d.mts +20 -0
  318. package/dist/utils/event-stream.d.mts.map +1 -0
  319. package/dist/utils/event-stream.mjs +133 -0
  320. package/dist/utils/event-stream.mjs.map +1 -0
  321. package/dist/utils/fetch.cjs +32 -0
  322. package/dist/utils/fetch.d.cts +8 -0
  323. package/dist/utils/fetch.d.cts.map +1 -0
  324. package/dist/utils/fetch.d.mts +8 -0
  325. package/dist/utils/fetch.d.mts.map +1 -0
  326. package/dist/utils/fetch.mjs +32 -0
  327. package/dist/utils/fetch.mjs.map +1 -0
  328. package/dist/utils/json-schema.cjs +107 -0
  329. package/dist/utils/json-schema.d.cts +20 -0
  330. package/dist/utils/json-schema.d.cts.map +1 -0
  331. package/dist/utils/json-schema.d.mts +20 -0
  332. package/dist/utils/json-schema.d.mts.map +1 -0
  333. package/dist/utils/json-schema.mjs +102 -0
  334. package/dist/utils/json-schema.mjs.map +1 -0
  335. package/dist/utils/json-utils.cjs +46 -0
  336. package/dist/utils/json-utils.d.cts +28 -0
  337. package/dist/utils/json-utils.d.cts.map +1 -0
  338. package/dist/utils/json-utils.d.mts +28 -0
  339. package/dist/utils/json-utils.d.mts.map +1 -0
  340. package/dist/utils/json-utils.mjs +44 -0
  341. package/dist/utils/json-utils.mjs.map +1 -0
  342. package/dist/utils/logger.cjs +72 -0
  343. package/dist/utils/logger.d.cts +41 -0
  344. package/dist/utils/logger.d.cts.map +1 -0
  345. package/dist/utils/logger.d.mts +41 -0
  346. package/dist/utils/logger.d.mts.map +1 -0
  347. package/dist/utils/logger.mjs +68 -0
  348. package/dist/utils/logger.mjs.map +1 -0
  349. package/dist/utils/mcp-utils.cjs +53 -0
  350. package/dist/utils/mcp-utils.d.cts +10 -0
  351. package/dist/utils/mcp-utils.d.cts.map +1 -0
  352. package/dist/utils/mcp-utils.d.mts +10 -0
  353. package/dist/utils/mcp-utils.d.mts.map +1 -0
  354. package/dist/utils/mcp-utils.mjs +51 -0
  355. package/dist/utils/mcp-utils.mjs.map +1 -0
  356. package/dist/utils/model-utils.cjs +12 -0
  357. package/dist/utils/model-utils.d.cts +8 -0
  358. package/dist/utils/model-utils.d.cts.map +1 -0
  359. package/dist/utils/model-utils.d.mts +8 -0
  360. package/dist/utils/model-utils.d.mts.map +1 -0
  361. package/dist/utils/model-utils.mjs +12 -0
  362. package/dist/utils/model-utils.mjs.map +1 -0
  363. package/dist/utils/promise.cjs +17 -0
  364. package/dist/utils/promise.d.cts +10 -0
  365. package/dist/utils/promise.d.cts.map +1 -0
  366. package/dist/utils/promise.d.mts +10 -0
  367. package/dist/utils/promise.d.mts.map +1 -0
  368. package/dist/utils/promise.mjs +17 -0
  369. package/dist/utils/promise.mjs.map +1 -0
  370. package/dist/utils/prompts.cjs +19 -0
  371. package/dist/utils/prompts.d.cts +6 -0
  372. package/dist/utils/prompts.d.cts.map +1 -0
  373. package/dist/utils/prompts.d.mts +6 -0
  374. package/dist/utils/prompts.d.mts.map +1 -0
  375. package/dist/utils/prompts.mjs +18 -0
  376. package/dist/utils/prompts.mjs.map +1 -0
  377. package/dist/utils/queue.cjs +273 -0
  378. package/dist/utils/queue.d.cts +60 -0
  379. package/dist/utils/queue.d.cts.map +1 -0
  380. package/dist/utils/queue.d.mts +60 -0
  381. package/dist/utils/queue.d.mts.map +1 -0
  382. package/dist/utils/queue.mjs +271 -0
  383. package/dist/utils/queue.mjs.map +1 -0
  384. package/dist/utils/role-utils.cjs +40 -0
  385. package/dist/utils/role-utils.d.cts +32 -0
  386. package/dist/utils/role-utils.d.cts.map +1 -0
  387. package/dist/utils/role-utils.d.mts +32 -0
  388. package/dist/utils/role-utils.d.mts.map +1 -0
  389. package/dist/utils/role-utils.mjs +38 -0
  390. package/dist/utils/role-utils.mjs.map +1 -0
  391. package/dist/utils/stream-polyfill.cjs +37 -0
  392. package/dist/utils/stream-polyfill.d.cts +1 -0
  393. package/dist/utils/stream-polyfill.d.mts +1 -0
  394. package/dist/utils/stream-polyfill.mjs +38 -0
  395. package/dist/utils/stream-polyfill.mjs.map +1 -0
  396. package/dist/utils/stream-utils.cjs +187 -0
  397. package/dist/utils/stream-utils.d.cts +30 -0
  398. package/dist/utils/stream-utils.d.cts.map +1 -0
  399. package/dist/utils/stream-utils.d.mts +30 -0
  400. package/dist/utils/stream-utils.d.mts.map +1 -0
  401. package/dist/utils/stream-utils.mjs +174 -0
  402. package/dist/utils/stream-utils.mjs.map +1 -0
  403. package/dist/utils/structured-stream-extractor.cjs +63 -0
  404. package/dist/utils/structured-stream-extractor.d.cts +23 -0
  405. package/dist/utils/structured-stream-extractor.d.cts.map +1 -0
  406. package/dist/utils/structured-stream-extractor.d.mts +23 -0
  407. package/dist/utils/structured-stream-extractor.d.mts.map +1 -0
  408. package/dist/utils/structured-stream-extractor.mjs +64 -0
  409. package/dist/utils/structured-stream-extractor.mjs.map +1 -0
  410. package/dist/utils/test/agent-response.cjs +16 -0
  411. package/dist/utils/test/agent-response.d.cts +12 -0
  412. package/dist/utils/test/agent-response.d.cts.map +1 -0
  413. package/dist/utils/test/agent-response.d.mts +13 -0
  414. package/dist/utils/test/agent-response.d.mts.map +1 -0
  415. package/dist/utils/test/agent-response.mjs +17 -0
  416. package/dist/utils/test/agent-response.mjs.map +1 -0
  417. package/dist/utils/test/openai-like-utils.cjs +73 -0
  418. package/dist/utils/test/openai-like-utils.d.cts +13 -0
  419. package/dist/utils/test/openai-like-utils.d.cts.map +1 -0
  420. package/dist/utils/test/openai-like-utils.d.mts +14 -0
  421. package/dist/utils/test/openai-like-utils.d.mts.map +1 -0
  422. package/dist/utils/test/openai-like-utils.mjs +68 -0
  423. package/dist/utils/test/openai-like-utils.mjs.map +1 -0
  424. package/dist/utils/token-estimator.cjs +57 -0
  425. package/dist/utils/token-estimator.d.cts +13 -0
  426. package/dist/utils/token-estimator.d.cts.map +1 -0
  427. package/dist/utils/token-estimator.d.mts +13 -0
  428. package/dist/utils/token-estimator.d.mts.map +1 -0
  429. package/dist/utils/token-estimator.mjs +57 -0
  430. package/dist/utils/token-estimator.mjs.map +1 -0
  431. package/dist/utils/type-utils.cjs +159 -0
  432. package/dist/utils/type-utils.d.cts +32 -0
  433. package/dist/utils/type-utils.d.cts.map +1 -0
  434. package/dist/utils/type-utils.d.mts +32 -0
  435. package/dist/utils/type-utils.d.mts.map +1 -0
  436. package/dist/utils/type-utils.mjs +141 -0
  437. package/dist/utils/type-utils.mjs.map +1 -0
  438. package/dist/utils/typed-event-emitter.cjs +0 -0
  439. package/dist/utils/typed-event-emitter.d.cts +13 -0
  440. package/dist/utils/typed-event-emitter.d.cts.map +1 -0
  441. package/dist/utils/typed-event-emitter.d.mts +13 -0
  442. package/dist/utils/typed-event-emitter.d.mts.map +1 -0
  443. package/dist/utils/typed-event-emitter.mjs +1 -0
  444. package/package.json +143 -62
  445. package/CHANGELOG.md +0 -2584
  446. package/lib/cjs/agents/agent.d.ts +0 -961
  447. package/lib/cjs/agents/agent.js +0 -961
  448. package/lib/cjs/agents/ai-agent.d.ts +0 -395
  449. package/lib/cjs/agents/ai-agent.js +0 -572
  450. package/lib/cjs/agents/chat-model.d.ts +0 -672
  451. package/lib/cjs/agents/chat-model.js +0 -457
  452. package/lib/cjs/agents/guide-rail-agent.d.ts +0 -62
  453. package/lib/cjs/agents/guide-rail-agent.js +0 -14
  454. package/lib/cjs/agents/image-agent.d.ts +0 -38
  455. package/lib/cjs/agents/image-agent.js +0 -71
  456. package/lib/cjs/agents/image-model.d.ts +0 -270
  457. package/lib/cjs/agents/image-model.js +0 -91
  458. package/lib/cjs/agents/mcp-agent.d.ts +0 -231
  459. package/lib/cjs/agents/mcp-agent.js +0 -366
  460. package/lib/cjs/agents/model.d.ts +0 -252
  461. package/lib/cjs/agents/model.js +0 -180
  462. package/lib/cjs/agents/team-agent.d.ts +0 -382
  463. package/lib/cjs/agents/team-agent.js +0 -386
  464. package/lib/cjs/agents/transform-agent.d.ts +0 -94
  465. package/lib/cjs/agents/transform-agent.js +0 -80
  466. package/lib/cjs/agents/types.d.ts +0 -31
  467. package/lib/cjs/agents/types.js +0 -40
  468. package/lib/cjs/agents/user-agent.d.ts +0 -27
  469. package/lib/cjs/agents/user-agent.js +0 -90
  470. package/lib/cjs/agents/video-model.d.ts +0 -280
  471. package/lib/cjs/agents/video-model.js +0 -67
  472. package/lib/cjs/aigne/aigne.d.ts +0 -335
  473. package/lib/cjs/aigne/aigne.js +0 -248
  474. package/lib/cjs/aigne/context.d.ts +0 -220
  475. package/lib/cjs/aigne/context.js +0 -423
  476. package/lib/cjs/aigne/index.d.ts +0 -4
  477. package/lib/cjs/aigne/index.js +0 -20
  478. package/lib/cjs/aigne/message-queue.d.ts +0 -48
  479. package/lib/cjs/aigne/message-queue.js +0 -109
  480. package/lib/cjs/aigne/type.d.ts +0 -26
  481. package/lib/cjs/aigne/type.js +0 -2
  482. package/lib/cjs/aigne/usage.d.ts +0 -28
  483. package/lib/cjs/aigne/usage.js +0 -34
  484. package/lib/cjs/index.d.ts +0 -21
  485. package/lib/cjs/index.js +0 -37
  486. package/lib/cjs/loader/agent-js.d.ts +0 -2
  487. package/lib/cjs/loader/agent-js.js +0 -21
  488. package/lib/cjs/loader/agent-yaml.d.ts +0 -78
  489. package/lib/cjs/loader/agent-yaml.js +0 -120
  490. package/lib/cjs/loader/agents.d.ts +0 -4
  491. package/lib/cjs/loader/agents.js +0 -17
  492. package/lib/cjs/loader/error.d.ts +0 -2
  493. package/lib/cjs/loader/error.js +0 -6
  494. package/lib/cjs/loader/function-agent.d.ts +0 -2
  495. package/lib/cjs/loader/function-agent.js +0 -7
  496. package/lib/cjs/loader/index.d.ts +0 -247
  497. package/lib/cjs/loader/index.js +0 -266
  498. package/lib/cjs/loader/schema.d.ts +0 -167
  499. package/lib/cjs/loader/schema.js +0 -162
  500. package/lib/cjs/memory/index.d.ts +0 -3
  501. package/lib/cjs/memory/index.js +0 -19
  502. package/lib/cjs/memory/memory.d.ts +0 -93
  503. package/lib/cjs/memory/memory.js +0 -147
  504. package/lib/cjs/memory/recorder.d.ts +0 -93
  505. package/lib/cjs/memory/recorder.js +0 -63
  506. package/lib/cjs/memory/retriever.d.ts +0 -106
  507. package/lib/cjs/memory/retriever.js +0 -60
  508. package/lib/cjs/package.json +0 -3
  509. package/lib/cjs/prompt/agent-session.d.ts +0 -163
  510. package/lib/cjs/prompt/agent-session.js +0 -1008
  511. package/lib/cjs/prompt/compact/compactor.d.ts +0 -7
  512. package/lib/cjs/prompt/compact/compactor.js +0 -52
  513. package/lib/cjs/prompt/compact/session-memory-extractor.d.ts +0 -7
  514. package/lib/cjs/prompt/compact/session-memory-extractor.js +0 -143
  515. package/lib/cjs/prompt/compact/types.d.ts +0 -336
  516. package/lib/cjs/prompt/compact/types.js +0 -53
  517. package/lib/cjs/prompt/compact/user-memory-extractor.d.ts +0 -7
  518. package/lib/cjs/prompt/compact/user-memory-extractor.js +0 -124
  519. package/lib/cjs/prompt/context/afs/history.d.ts +0 -9
  520. package/lib/cjs/prompt/context/afs/history.js +0 -33
  521. package/lib/cjs/prompt/context/afs/index.d.ts +0 -20
  522. package/lib/cjs/prompt/context/afs/index.js +0 -54
  523. package/lib/cjs/prompt/context/index.d.ts +0 -31
  524. package/lib/cjs/prompt/context/index.js +0 -18
  525. package/lib/cjs/prompt/filters/index.d.ts +0 -2
  526. package/lib/cjs/prompt/filters/index.js +0 -51
  527. package/lib/cjs/prompt/prompt-builder.d.ts +0 -50
  528. package/lib/cjs/prompt/prompt-builder.js +0 -352
  529. package/lib/cjs/prompt/prompts/afs-builtin-prompt.d.ts +0 -4
  530. package/lib/cjs/prompt/prompts/afs-builtin-prompt.js +0 -36
  531. package/lib/cjs/prompt/prompts/memory-message-template.d.ts +0 -1
  532. package/lib/cjs/prompt/prompts/memory-message-template.js +0 -8
  533. package/lib/cjs/prompt/prompts/structured-stream-instructions.d.ts +0 -7
  534. package/lib/cjs/prompt/prompts/structured-stream-instructions.js +0 -27
  535. package/lib/cjs/prompt/skills/afs/agent-skill/agent-skill.d.ts +0 -19
  536. package/lib/cjs/prompt/skills/afs/agent-skill/agent-skill.js +0 -69
  537. package/lib/cjs/prompt/skills/afs/agent-skill/skill-loader.d.ts +0 -12
  538. package/lib/cjs/prompt/skills/afs/agent-skill/skill-loader.js +0 -50
  539. package/lib/cjs/prompt/skills/afs/base.d.ts +0 -4
  540. package/lib/cjs/prompt/skills/afs/base.js +0 -8
  541. package/lib/cjs/prompt/skills/afs/delete.d.ts +0 -19
  542. package/lib/cjs/prompt/skills/afs/delete.js +0 -54
  543. package/lib/cjs/prompt/skills/afs/edit.d.ts +0 -24
  544. package/lib/cjs/prompt/skills/afs/edit.js +0 -124
  545. package/lib/cjs/prompt/skills/afs/exec.d.ts +0 -16
  546. package/lib/cjs/prompt/skills/afs/exec.js +0 -43
  547. package/lib/cjs/prompt/skills/afs/index.d.ts +0 -3
  548. package/lib/cjs/prompt/skills/afs/index.js +0 -26
  549. package/lib/cjs/prompt/skills/afs/list.d.ts +0 -24
  550. package/lib/cjs/prompt/skills/afs/list.js +0 -81
  551. package/lib/cjs/prompt/skills/afs/read.d.ts +0 -28
  552. package/lib/cjs/prompt/skills/afs/read.js +0 -105
  553. package/lib/cjs/prompt/skills/afs/rename.d.ts +0 -21
  554. package/lib/cjs/prompt/skills/afs/rename.js +0 -59
  555. package/lib/cjs/prompt/skills/afs/search.d.ts +0 -24
  556. package/lib/cjs/prompt/skills/afs/search.js +0 -71
  557. package/lib/cjs/prompt/skills/afs/write.d.ts +0 -20
  558. package/lib/cjs/prompt/skills/afs/write.js +0 -59
  559. package/lib/cjs/prompt/template.d.ts +0 -243
  560. package/lib/cjs/prompt/template.js +0 -265
  561. package/lib/cjs/utils/agent-utils.d.ts +0 -13
  562. package/lib/cjs/utils/agent-utils.js +0 -60
  563. package/lib/cjs/utils/camelize.d.ts +0 -7
  564. package/lib/cjs/utils/camelize.js +0 -38
  565. package/lib/cjs/utils/event-stream.d.ts +0 -15
  566. package/lib/cjs/utils/event-stream.js +0 -158
  567. package/lib/cjs/utils/fetch.d.ts +0 -4
  568. package/lib/cjs/utils/fetch.js +0 -36
  569. package/lib/cjs/utils/json-schema.d.ts +0 -15
  570. package/lib/cjs/utils/json-schema.js +0 -123
  571. package/lib/cjs/utils/json-utils.d.ts +0 -24
  572. package/lib/cjs/utils/json-utils.js +0 -48
  573. package/lib/cjs/utils/logger.d.ts +0 -39
  574. package/lib/cjs/utils/logger.js +0 -81
  575. package/lib/cjs/utils/mcp-utils.d.ts +0 -5
  576. package/lib/cjs/utils/mcp-utils.js +0 -52
  577. package/lib/cjs/utils/model-utils.d.ts +0 -3
  578. package/lib/cjs/utils/model-utils.js +0 -10
  579. package/lib/cjs/utils/promise.d.ts +0 -6
  580. package/lib/cjs/utils/promise.js +0 -12
  581. package/lib/cjs/utils/prompts.d.ts +0 -2
  582. package/lib/cjs/utils/prompts.js +0 -22
  583. package/lib/cjs/utils/queue.d.ts +0 -57
  584. package/lib/cjs/utils/queue.js +0 -318
  585. package/lib/cjs/utils/role-utils.d.ts +0 -31
  586. package/lib/cjs/utils/role-utils.js +0 -37
  587. package/lib/cjs/utils/stream-polyfill.d.ts +0 -1
  588. package/lib/cjs/utils/stream-polyfill.js +0 -38
  589. package/lib/cjs/utils/stream-utils.d.ts +0 -26
  590. package/lib/cjs/utils/stream-utils.js +0 -235
  591. package/lib/cjs/utils/structured-stream-extractor.d.ts +0 -14
  592. package/lib/cjs/utils/structured-stream-extractor.js +0 -68
  593. package/lib/cjs/utils/token-estimator.d.ts +0 -9
  594. package/lib/cjs/utils/token-estimator.js +0 -66
  595. package/lib/cjs/utils/type-utils.d.ts +0 -31
  596. package/lib/cjs/utils/type-utils.js +0 -202
  597. package/lib/cjs/utils/typed-event-emitter.d.ts +0 -10
  598. package/lib/cjs/utils/typed-event-emitter.js +0 -2
  599. package/lib/dts/agents/agent.d.ts +0 -961
  600. package/lib/dts/agents/ai-agent.d.ts +0 -395
  601. package/lib/dts/agents/chat-model.d.ts +0 -672
  602. package/lib/dts/agents/guide-rail-agent.d.ts +0 -62
  603. package/lib/dts/agents/image-agent.d.ts +0 -38
  604. package/lib/dts/agents/image-model.d.ts +0 -270
  605. package/lib/dts/agents/mcp-agent.d.ts +0 -231
  606. package/lib/dts/agents/model.d.ts +0 -252
  607. package/lib/dts/agents/team-agent.d.ts +0 -382
  608. package/lib/dts/agents/transform-agent.d.ts +0 -94
  609. package/lib/dts/agents/types.d.ts +0 -31
  610. package/lib/dts/agents/user-agent.d.ts +0 -27
  611. package/lib/dts/agents/video-model.d.ts +0 -280
  612. package/lib/dts/aigne/aigne.d.ts +0 -335
  613. package/lib/dts/aigne/context.d.ts +0 -220
  614. package/lib/dts/aigne/index.d.ts +0 -4
  615. package/lib/dts/aigne/message-queue.d.ts +0 -48
  616. package/lib/dts/aigne/type.d.ts +0 -26
  617. package/lib/dts/aigne/usage.d.ts +0 -28
  618. package/lib/dts/index.d.ts +0 -21
  619. package/lib/dts/loader/agent-js.d.ts +0 -2
  620. package/lib/dts/loader/agent-yaml.d.ts +0 -78
  621. package/lib/dts/loader/agents.d.ts +0 -4
  622. package/lib/dts/loader/error.d.ts +0 -2
  623. package/lib/dts/loader/function-agent.d.ts +0 -2
  624. package/lib/dts/loader/index.d.ts +0 -247
  625. package/lib/dts/loader/schema.d.ts +0 -167
  626. package/lib/dts/memory/index.d.ts +0 -3
  627. package/lib/dts/memory/memory.d.ts +0 -93
  628. package/lib/dts/memory/recorder.d.ts +0 -93
  629. package/lib/dts/memory/retriever.d.ts +0 -106
  630. package/lib/dts/prompt/agent-session.d.ts +0 -163
  631. package/lib/dts/prompt/compact/compactor.d.ts +0 -7
  632. package/lib/dts/prompt/compact/session-memory-extractor.d.ts +0 -7
  633. package/lib/dts/prompt/compact/types.d.ts +0 -336
  634. package/lib/dts/prompt/compact/user-memory-extractor.d.ts +0 -7
  635. package/lib/dts/prompt/context/afs/history.d.ts +0 -9
  636. package/lib/dts/prompt/context/afs/index.d.ts +0 -20
  637. package/lib/dts/prompt/context/index.d.ts +0 -31
  638. package/lib/dts/prompt/filters/index.d.ts +0 -2
  639. package/lib/dts/prompt/prompt-builder.d.ts +0 -50
  640. package/lib/dts/prompt/prompts/afs-builtin-prompt.d.ts +0 -4
  641. package/lib/dts/prompt/prompts/memory-message-template.d.ts +0 -1
  642. package/lib/dts/prompt/prompts/structured-stream-instructions.d.ts +0 -7
  643. package/lib/dts/prompt/skills/afs/agent-skill/agent-skill.d.ts +0 -19
  644. package/lib/dts/prompt/skills/afs/agent-skill/skill-loader.d.ts +0 -12
  645. package/lib/dts/prompt/skills/afs/base.d.ts +0 -4
  646. package/lib/dts/prompt/skills/afs/delete.d.ts +0 -19
  647. package/lib/dts/prompt/skills/afs/edit.d.ts +0 -24
  648. package/lib/dts/prompt/skills/afs/exec.d.ts +0 -16
  649. package/lib/dts/prompt/skills/afs/index.d.ts +0 -3
  650. package/lib/dts/prompt/skills/afs/list.d.ts +0 -24
  651. package/lib/dts/prompt/skills/afs/read.d.ts +0 -28
  652. package/lib/dts/prompt/skills/afs/rename.d.ts +0 -21
  653. package/lib/dts/prompt/skills/afs/search.d.ts +0 -24
  654. package/lib/dts/prompt/skills/afs/write.d.ts +0 -20
  655. package/lib/dts/prompt/template.d.ts +0 -243
  656. package/lib/dts/utils/agent-utils.d.ts +0 -13
  657. package/lib/dts/utils/camelize.d.ts +0 -7
  658. package/lib/dts/utils/event-stream.d.ts +0 -15
  659. package/lib/dts/utils/fetch.d.ts +0 -4
  660. package/lib/dts/utils/json-schema.d.ts +0 -15
  661. package/lib/dts/utils/json-utils.d.ts +0 -24
  662. package/lib/dts/utils/logger.d.ts +0 -39
  663. package/lib/dts/utils/mcp-utils.d.ts +0 -5
  664. package/lib/dts/utils/model-utils.d.ts +0 -3
  665. package/lib/dts/utils/promise.d.ts +0 -6
  666. package/lib/dts/utils/prompts.d.ts +0 -2
  667. package/lib/dts/utils/queue.d.ts +0 -57
  668. package/lib/dts/utils/role-utils.d.ts +0 -31
  669. package/lib/dts/utils/stream-polyfill.d.ts +0 -1
  670. package/lib/dts/utils/stream-utils.d.ts +0 -26
  671. package/lib/dts/utils/structured-stream-extractor.d.ts +0 -14
  672. package/lib/dts/utils/token-estimator.d.ts +0 -9
  673. package/lib/dts/utils/type-utils.d.ts +0 -31
  674. package/lib/dts/utils/typed-event-emitter.d.ts +0 -10
  675. package/lib/esm/agents/agent.d.ts +0 -961
  676. package/lib/esm/agents/agent.js +0 -911
  677. package/lib/esm/agents/ai-agent.d.ts +0 -395
  678. package/lib/esm/agents/ai-agent.js +0 -535
  679. package/lib/esm/agents/chat-model.d.ts +0 -672
  680. package/lib/esm/agents/chat-model.js +0 -419
  681. package/lib/esm/agents/guide-rail-agent.d.ts +0 -62
  682. package/lib/esm/agents/guide-rail-agent.js +0 -11
  683. package/lib/esm/agents/image-agent.d.ts +0 -38
  684. package/lib/esm/agents/image-agent.js +0 -64
  685. package/lib/esm/agents/image-model.d.ts +0 -270
  686. package/lib/esm/agents/image-model.js +0 -87
  687. package/lib/esm/agents/mcp-agent.d.ts +0 -231
  688. package/lib/esm/agents/mcp-agent.js +0 -325
  689. package/lib/esm/agents/model.d.ts +0 -252
  690. package/lib/esm/agents/model.js +0 -143
  691. package/lib/esm/agents/team-agent.d.ts +0 -382
  692. package/lib/esm/agents/team-agent.js +0 -346
  693. package/lib/esm/agents/transform-agent.d.ts +0 -94
  694. package/lib/esm/agents/transform-agent.js +0 -73
  695. package/lib/esm/agents/types.d.ts +0 -31
  696. package/lib/esm/agents/types.js +0 -30
  697. package/lib/esm/agents/user-agent.d.ts +0 -27
  698. package/lib/esm/agents/user-agent.js +0 -86
  699. package/lib/esm/agents/video-model.d.ts +0 -280
  700. package/lib/esm/agents/video-model.js +0 -63
  701. package/lib/esm/aigne/aigne.d.ts +0 -335
  702. package/lib/esm/aigne/aigne.js +0 -244
  703. package/lib/esm/aigne/context.d.ts +0 -220
  704. package/lib/esm/aigne/context.js +0 -416
  705. package/lib/esm/aigne/index.d.ts +0 -4
  706. package/lib/esm/aigne/index.js +0 -4
  707. package/lib/esm/aigne/message-queue.d.ts +0 -48
  708. package/lib/esm/aigne/message-queue.js +0 -104
  709. package/lib/esm/aigne/type.d.ts +0 -26
  710. package/lib/esm/aigne/type.js +0 -1
  711. package/lib/esm/aigne/usage.d.ts +0 -28
  712. package/lib/esm/aigne/usage.js +0 -30
  713. package/lib/esm/index.d.ts +0 -21
  714. package/lib/esm/index.js +0 -21
  715. package/lib/esm/loader/agent-js.d.ts +0 -2
  716. package/lib/esm/loader/agent-js.js +0 -18
  717. package/lib/esm/loader/agent-yaml.d.ts +0 -78
  718. package/lib/esm/loader/agent-yaml.js +0 -113
  719. package/lib/esm/loader/agents.d.ts +0 -4
  720. package/lib/esm/loader/agents.js +0 -14
  721. package/lib/esm/loader/error.d.ts +0 -2
  722. package/lib/esm/loader/error.js +0 -2
  723. package/lib/esm/loader/function-agent.d.ts +0 -2
  724. package/lib/esm/loader/function-agent.js +0 -4
  725. package/lib/esm/loader/index.d.ts +0 -247
  726. package/lib/esm/loader/index.js +0 -258
  727. package/lib/esm/loader/schema.d.ts +0 -167
  728. package/lib/esm/loader/schema.js +0 -153
  729. package/lib/esm/memory/index.d.ts +0 -3
  730. package/lib/esm/memory/index.js +0 -3
  731. package/lib/esm/memory/memory.d.ts +0 -93
  732. package/lib/esm/memory/memory.js +0 -142
  733. package/lib/esm/memory/recorder.d.ts +0 -93
  734. package/lib/esm/memory/recorder.js +0 -59
  735. package/lib/esm/memory/retriever.d.ts +0 -106
  736. package/lib/esm/memory/retriever.js +0 -56
  737. package/lib/esm/package.json +0 -3
  738. package/lib/esm/prompt/agent-session.d.ts +0 -163
  739. package/lib/esm/prompt/agent-session.js +0 -968
  740. package/lib/esm/prompt/compact/compactor.d.ts +0 -7
  741. package/lib/esm/prompt/compact/compactor.js +0 -48
  742. package/lib/esm/prompt/compact/session-memory-extractor.d.ts +0 -7
  743. package/lib/esm/prompt/compact/session-memory-extractor.js +0 -139
  744. package/lib/esm/prompt/compact/types.d.ts +0 -336
  745. package/lib/esm/prompt/compact/types.js +0 -50
  746. package/lib/esm/prompt/compact/user-memory-extractor.d.ts +0 -7
  747. package/lib/esm/prompt/compact/user-memory-extractor.js +0 -120
  748. package/lib/esm/prompt/context/afs/history.d.ts +0 -9
  749. package/lib/esm/prompt/context/afs/history.js +0 -30
  750. package/lib/esm/prompt/context/afs/index.d.ts +0 -20
  751. package/lib/esm/prompt/context/afs/index.js +0 -51
  752. package/lib/esm/prompt/context/index.d.ts +0 -31
  753. package/lib/esm/prompt/context/index.js +0 -15
  754. package/lib/esm/prompt/filters/index.d.ts +0 -2
  755. package/lib/esm/prompt/filters/index.js +0 -15
  756. package/lib/esm/prompt/prompt-builder.d.ts +0 -50
  757. package/lib/esm/prompt/prompt-builder.js +0 -348
  758. package/lib/esm/prompt/prompts/afs-builtin-prompt.d.ts +0 -4
  759. package/lib/esm/prompt/prompts/afs-builtin-prompt.js +0 -32
  760. package/lib/esm/prompt/prompts/memory-message-template.d.ts +0 -1
  761. package/lib/esm/prompt/prompts/memory-message-template.js +0 -5
  762. package/lib/esm/prompt/prompts/structured-stream-instructions.d.ts +0 -7
  763. package/lib/esm/prompt/prompts/structured-stream-instructions.js +0 -24
  764. package/lib/esm/prompt/skills/afs/agent-skill/agent-skill.d.ts +0 -19
  765. package/lib/esm/prompt/skills/afs/agent-skill/agent-skill.js +0 -65
  766. package/lib/esm/prompt/skills/afs/agent-skill/skill-loader.d.ts +0 -12
  767. package/lib/esm/prompt/skills/afs/agent-skill/skill-loader.js +0 -43
  768. package/lib/esm/prompt/skills/afs/base.d.ts +0 -4
  769. package/lib/esm/prompt/skills/afs/base.js +0 -4
  770. package/lib/esm/prompt/skills/afs/delete.d.ts +0 -19
  771. package/lib/esm/prompt/skills/afs/delete.js +0 -50
  772. package/lib/esm/prompt/skills/afs/edit.d.ts +0 -24
  773. package/lib/esm/prompt/skills/afs/edit.js +0 -120
  774. package/lib/esm/prompt/skills/afs/exec.d.ts +0 -16
  775. package/lib/esm/prompt/skills/afs/exec.js +0 -39
  776. package/lib/esm/prompt/skills/afs/index.d.ts +0 -3
  777. package/lib/esm/prompt/skills/afs/index.js +0 -23
  778. package/lib/esm/prompt/skills/afs/list.d.ts +0 -24
  779. package/lib/esm/prompt/skills/afs/list.js +0 -77
  780. package/lib/esm/prompt/skills/afs/read.d.ts +0 -28
  781. package/lib/esm/prompt/skills/afs/read.js +0 -101
  782. package/lib/esm/prompt/skills/afs/rename.d.ts +0 -21
  783. package/lib/esm/prompt/skills/afs/rename.js +0 -55
  784. package/lib/esm/prompt/skills/afs/search.d.ts +0 -24
  785. package/lib/esm/prompt/skills/afs/search.js +0 -67
  786. package/lib/esm/prompt/skills/afs/write.d.ts +0 -20
  787. package/lib/esm/prompt/skills/afs/write.js +0 -55
  788. package/lib/esm/prompt/template.d.ts +0 -243
  789. package/lib/esm/prompt/template.js +0 -249
  790. package/lib/esm/utils/agent-utils.d.ts +0 -13
  791. package/lib/esm/utils/agent-utils.js +0 -54
  792. package/lib/esm/utils/camelize.d.ts +0 -7
  793. package/lib/esm/utils/camelize.js +0 -34
  794. package/lib/esm/utils/event-stream.d.ts +0 -15
  795. package/lib/esm/utils/event-stream.js +0 -151
  796. package/lib/esm/utils/fetch.d.ts +0 -4
  797. package/lib/esm/utils/fetch.js +0 -33
  798. package/lib/esm/utils/json-schema.d.ts +0 -15
  799. package/lib/esm/utils/json-schema.js +0 -114
  800. package/lib/esm/utils/json-utils.d.ts +0 -24
  801. package/lib/esm/utils/json-utils.js +0 -41
  802. package/lib/esm/utils/logger.d.ts +0 -39
  803. package/lib/esm/utils/logger.js +0 -73
  804. package/lib/esm/utils/mcp-utils.d.ts +0 -5
  805. package/lib/esm/utils/mcp-utils.js +0 -47
  806. package/lib/esm/utils/model-utils.d.ts +0 -3
  807. package/lib/esm/utils/model-utils.js +0 -7
  808. package/lib/esm/utils/promise.d.ts +0 -6
  809. package/lib/esm/utils/promise.js +0 -9
  810. package/lib/esm/utils/prompts.d.ts +0 -2
  811. package/lib/esm/utils/prompts.js +0 -18
  812. package/lib/esm/utils/queue.d.ts +0 -57
  813. package/lib/esm/utils/queue.js +0 -315
  814. package/lib/esm/utils/role-utils.d.ts +0 -31
  815. package/lib/esm/utils/role-utils.js +0 -33
  816. package/lib/esm/utils/stream-polyfill.d.ts +0 -1
  817. package/lib/esm/utils/stream-polyfill.js +0 -37
  818. package/lib/esm/utils/stream-utils.d.ts +0 -26
  819. package/lib/esm/utils/stream-utils.js +0 -217
  820. package/lib/esm/utils/structured-stream-extractor.d.ts +0 -14
  821. package/lib/esm/utils/structured-stream-extractor.js +0 -64
  822. package/lib/esm/utils/token-estimator.d.ts +0 -9
  823. package/lib/esm/utils/token-estimator.js +0 -63
  824. package/lib/esm/utils/type-utils.d.ts +0 -31
  825. package/lib/esm/utils/type-utils.js +0 -181
  826. package/lib/esm/utils/typed-event-emitter.d.ts +0 -10
  827. package/lib/esm/utils/typed-event-emitter.js +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-session.mjs","names":[],"sources":["../../src/prompt/agent-session.ts"],"sourcesContent":["import type { AFS, AFSEntry } from \"@aigne/afs\";\nimport { AFSHistory } from \"@aigne/afs-history\";\nimport { v7 } from \"@aigne/uuid\";\nimport { joinURL } from \"ufo\";\nimport { stringify } from \"yaml\";\nimport type { AgentInvokeOptions } from \"../agents/agent.js\";\nimport type { ChatModelInputMessage } from \"../agents/chat-model.js\";\nimport { logger } from \"../utils/logger.js\";\nimport { estimateTokens } from \"../utils/token-estimator.js\";\nimport { isNonNullable } from \"../utils/type-utils.js\";\nimport {\n type CompactConfig,\n type CompactContent,\n DEFAULT_COMPACT_ASYNC,\n DEFAULT_COMPACT_MODE,\n DEFAULT_KEEP_RECENT_RATIO,\n DEFAULT_MAX_TOKENS,\n DEFAULT_MEMORY_QUERY_LIMIT,\n DEFAULT_MEMORY_RATIO,\n DEFAULT_SESSION_MEMORY_ASYNC,\n DEFAULT_SESSION_MEMORY_MODE,\n DEFAULT_SESSION_MODE,\n DEFAULT_USER_MEMORY_ASYNC,\n DEFAULT_USER_MEMORY_MODE,\n type EntryContent,\n type MemoryFact,\n type SessionMemoryConfig,\n type SessionMode,\n type UserMemoryConfig,\n} from \"./compact/types.js\";\n\nexport * from \"./compact/types.js\";\n\nexport interface AgentSessionOptions {\n sessionId: string;\n userId?: string;\n agentId?: string;\n afs?: AFS;\n\n /**\n * Session mode\n * - \"auto\": Enable history recording, compaction, and memory extraction\n * - \"disabled\": Disable all session features (history, compaction, memory)\n *\n * **Should be \"disabled\" for internal utility agents** (extractors, compactors, etc.)\n * to avoid recursive memory extraction and unnecessary overhead.\n *\n * @default DEFAULT_SESSION_MODE (\"auto\")\n */\n mode?: SessionMode;\n\n /**\n * Compaction configuration\n */\n compact?: CompactConfig;\n\n /**\n * Session memory configuration\n */\n sessionMemory?: SessionMemoryConfig;\n\n /**\n * User memory configuration\n */\n userMemory?: UserMemoryConfig;\n}\n\ninterface RuntimeState {\n systemMessages?: ChatModelInputMessage[];\n sessionMemory?: AFSEntry<MemoryFact>[];\n userMemory?: AFSEntry<MemoryFact>[];\n historyCompact?: CompactContent;\n historyEntries: AFSEntry<EntryContent>[];\n currentEntry: EntryContent | null;\n currentEntryCompact?: CompactContent & {\n compressedCount: number;\n };\n}\n\nexport class AgentSession {\n readonly sessionId: string;\n readonly userId?: string;\n readonly agentId?: string;\n\n private afs?: AFS;\n private historyModulePath?: string;\n private mode: SessionMode;\n private compactConfig: CompactConfig;\n private sessionMemoryConfig: SessionMemoryConfig;\n private userMemoryConfig: UserMemoryConfig;\n private runtimeState: RuntimeState;\n private initialized?: Promise<void>;\n private compactionPromise?: Promise<void>;\n private sessionMemoryUpdatePromise?: Promise<void>;\n private userMemoryUpdatePromise?: Promise<void>;\n\n constructor(options: AgentSessionOptions) {\n this.sessionId = options.sessionId;\n this.userId = options.userId;\n this.agentId = options.agentId;\n this.afs = options.afs;\n this.mode = options.mode ?? DEFAULT_SESSION_MODE;\n this.compactConfig = options.compact ?? {};\n this.sessionMemoryConfig = options.sessionMemory ?? {};\n this.userMemoryConfig = options.userMemory ?? {};\n\n this.runtimeState = {\n historyEntries: [],\n currentEntry: null,\n };\n }\n\n /**\n * Check if memory extraction is enabled\n * Memory extraction requires mode to be \"auto\" AND AFS history module to be available\n */\n private get isMemoryEnabled(): boolean {\n return this.mode === \"auto\" && !!this.afs && !!this.historyModulePath;\n }\n\n async setSystemMessages(...messages: ChatModelInputMessage[]): Promise<void> {\n await this.ensureInitialized();\n\n this.runtimeState.systemMessages = messages;\n }\n\n async getMessages(): Promise<ChatModelInputMessage[]> {\n await this.ensureInitialized();\n\n const {\n systemMessages,\n userMemory,\n sessionMemory,\n historyCompact,\n historyEntries,\n currentEntry,\n currentEntryCompact,\n } = this.runtimeState;\n\n let currentMessages: ChatModelInputMessage[] = [];\n if (currentEntry?.messages?.length) {\n if (currentEntryCompact) {\n const { compressedCount, summary } = currentEntryCompact;\n\n const summaryMessage = {\n role: \"user\" as const,\n content: `[Earlier messages in this conversation (${compressedCount} messages compressed)]\\n${summary}`,\n };\n const remainingMessages = currentEntry.messages.slice(compressedCount);\n\n currentMessages = [summaryMessage, ...remainingMessages];\n } else {\n currentMessages = currentEntry.messages;\n }\n }\n\n // Flatten history entries messages once\n const historyMessages = historyEntries.flatMap((entry) => entry.content?.messages ?? []);\n\n // Check if there's an Agent Skill in current uncompressed messages\n const hasSkillInCurrentMessages = [...historyMessages, ...currentMessages].some(\n (msg) =>\n msg.role === \"user\" &&\n Array.isArray(msg.content) &&\n msg.content.some((block) => block.type === \"text\" && block.isAgentSkill === true),\n );\n\n // Prefer currentEntryCompact's lastAgentSkill over historyCompact's (newer takes priority)\n const lastAgentSkillToInject =\n currentEntryCompact?.lastAgentSkill ?? historyCompact?.lastAgentSkill;\n\n const messages = [\n ...(systemMessages ?? []),\n ...(userMemory && userMemory.length > 0 ? [this.formatUserMemory(userMemory)] : []),\n ...(sessionMemory && sessionMemory.length > 0\n ? [this.formatSessionMemory(sessionMemory)]\n : []),\n ...(historyCompact?.summary\n ? [\n {\n role: \"system\" as const,\n content: `Previous conversation summary:\\n${historyCompact.summary}`,\n },\n ]\n : []),\n // Only inject lastAgentSkill if there's no skill in current messages\n ...(lastAgentSkillToInject && !hasSkillInCurrentMessages\n ? [\n {\n role: \"user\" as const,\n content: [\n {\n type: \"text\" as const,\n text: lastAgentSkillToInject.content,\n },\n ],\n },\n ]\n : []),\n ...historyMessages,\n ...currentMessages,\n ];\n\n // Filter out thinking messages and truncate large messages\n return messages\n .map((msg) => {\n if (!msg.content || typeof msg.content === \"string\") {\n return msg;\n }\n // Filter out thinking from UnionContent[]\n const filteredContent = msg.content.filter((c) => !(c.type === \"text\" && c.isThinking));\n if (filteredContent.length === 0) return null;\n return { ...msg, content: filteredContent };\n })\n .filter(isNonNullable)\n .map((msg) => this.truncateLargeMessage(msg));\n }\n\n /**\n * Format user memory facts into a system message\n * Applies token budget limit to ensure memory injection fits within constraints\n */\n private formatUserMemory(memoryEntries: AFSEntry<MemoryFact>[]): ChatModelInputMessage {\n const memoryRatio = this.userMemoryConfig.memoryRatio ?? DEFAULT_MEMORY_RATIO;\n const maxTokens = Math.floor(\n (this.compactConfig.maxTokens ?? DEFAULT_MAX_TOKENS) * memoryRatio,\n );\n const header = \"[User Memory Facts]\";\n let currentTokens = estimateTokens(header);\n\n const facts: string[] = [];\n\n for (const entry of memoryEntries) {\n const fact = entry.content?.fact;\n if (!fact) continue;\n\n const factTokens = estimateTokens(fact);\n\n // Check if adding this fact would exceed token budget\n if (currentTokens + factTokens > maxTokens) {\n break; // Stop adding facts\n }\n\n facts.push(fact);\n currentTokens += factTokens;\n }\n\n return {\n role: \"system\",\n content: this.formatMemoryTemplate({ header, data: facts }),\n };\n }\n\n /**\n * Format session memory facts into a system message\n * Applies token budget limit to ensure memory injection fits within constraints\n */\n private formatSessionMemory(memoryEntries: AFSEntry<MemoryFact>[]): ChatModelInputMessage {\n const memoryRatio = this.sessionMemoryConfig.memoryRatio ?? DEFAULT_MEMORY_RATIO;\n const maxTokens = Math.floor(\n (this.compactConfig.maxTokens ?? DEFAULT_MAX_TOKENS) * memoryRatio,\n );\n const header = \"[Session Memory Facts]\";\n let currentTokens = estimateTokens(header);\n\n const facts: string[] = [];\n\n for (const entry of memoryEntries) {\n const fact = entry.content?.fact;\n if (!fact) continue;\n\n const factTokens = estimateTokens(fact);\n\n // Check if adding this fact would exceed token budget\n if (currentTokens + factTokens > maxTokens) {\n break; // Stop adding facts\n }\n\n facts.push(fact);\n currentTokens += factTokens;\n }\n\n return {\n role: \"system\",\n content: this.formatMemoryTemplate({ header, data: facts }),\n };\n }\n\n private formatMemoryTemplate({ header, data }: { header: string; data: unknown }): string {\n return `\\\n${header}\n\n${\"```yaml\"}\n${stringify(data)}\n${\"```\"}\n`;\n }\n\n async startMessage(\n input: unknown,\n message: ChatModelInputMessage,\n options: AgentInvokeOptions,\n ): Promise<void> {\n await this.ensureInitialized();\n\n // Only run compact if mode is not disabled\n if (this.mode !== \"disabled\") {\n await this.maybeAutoCompact(options);\n\n // Always wait for compaction to complete before starting a new message\n // This ensures data consistency even in async compact mode\n if (this.compactionPromise) await this.compactionPromise;\n }\n\n this.runtimeState.currentEntryCompact = undefined;\n this.runtimeState.currentEntry = { input, messages: [message] };\n }\n\n async endMessage(\n output: unknown,\n message: ChatModelInputMessage | undefined,\n options: AgentInvokeOptions,\n ): Promise<void> {\n await this.ensureInitialized();\n\n if (\n !this.runtimeState.currentEntry?.input ||\n !this.runtimeState.currentEntry.messages?.length\n ) {\n throw new Error(\"No current entry to end. Call startMessage() first.\");\n }\n\n if (message) this.runtimeState.currentEntry.messages.push(message);\n this.runtimeState.currentEntry.output = output;\n\n let newEntry: AFSEntry<EntryContent>;\n\n // Only persist to AFS if mode is not disabled\n if (this.mode !== \"disabled\" && this.afs && this.historyModulePath) {\n newEntry = (\n await this.afs.write(joinURL(this.historyModulePath, \"by-session\", this.sessionId, \"new\"), {\n userId: this.userId,\n sessionId: this.sessionId,\n agentId: this.agentId,\n content: this.runtimeState.currentEntry,\n })\n ).data;\n } else {\n // Create in-memory entry for runtime state\n const id = v7();\n\n newEntry = {\n id,\n path: `/history/${id}`,\n userId: this.userId,\n sessionId: this.sessionId,\n agentId: this.agentId,\n content: this.runtimeState.currentEntry,\n };\n }\n\n this.runtimeState.historyEntries.push(newEntry);\n this.runtimeState.currentEntry = null;\n this.runtimeState.currentEntryCompact = undefined;\n\n // Only run compact and memory extraction if mode is not disabled\n if (this.mode !== \"disabled\") {\n await Promise.all([\n // Check if auto-compact should be triggered\n this.maybeAutoCompact(options),\n // Check if auto-update session memory should be triggered\n this.maybeAutoUpdateSessionMemory(options),\n ]);\n }\n }\n\n /**\n * Manually trigger compaction\n */\n async compact(options: AgentInvokeOptions): Promise<void> {\n await this.ensureInitialized();\n\n // If compaction is already in progress, wait for it to complete\n if (this.compactionPromise) {\n return this.compactionPromise;\n }\n\n // Start new compaction task\n this.compactionPromise = this.doCompact(options).finally(() => {\n this.compactionPromise = undefined;\n });\n\n const isAsync = this.compactConfig.async ?? DEFAULT_COMPACT_ASYNC;\n\n if (!isAsync) await this.compactionPromise;\n }\n\n /**\n * Internal method that performs the actual compaction\n */\n private async doCompact(options: AgentInvokeOptions): Promise<void> {\n const { compactor } = this.compactConfig ?? {};\n if (!compactor) {\n throw new Error(\"Cannot compact without a compactor agent configured.\");\n }\n\n const historyEntries = this.runtimeState.historyEntries;\n if (historyEntries.length === 0) return;\n\n const maxTokens = this.maxTokens;\n\n // Target to keep only 50% of keepRecentTokens to leave buffer room\n // This avoids triggering compression again shortly after compaction\n // Similar to compactCurrentEntry, we compress more aggressively to leave headroom\n //\n // Note: We don't subtract systemTokens or currentEntry tokens because:\n // 1. keepRecentTokens is already a relative ratio (e.g., 50% of maxTokens)\n // 2. systemTokens overhead is typically small (~1-2k, ~1-2% of maxTokens)\n // 3. currentEntry is still being constructed (not yet added to history)\n // 4. In tool use scenarios, currentEntry can be very large (many tool calls)\n // 5. Subtracting them would complicate logic without significant benefit\n // 6. Total token limit is enforced by maybeAutoCompact trigger condition\n const keepRecentTokens = this.keepRecentTokens * 0.5;\n\n // Find split point by iterating backwards from most recent entry\n // The split point divides history into: [compact] | [keep]\n let splitIndex = historyEntries.length; // Default: keep all (no compaction)\n let accumulatedTokens = 0;\n\n for (let i = historyEntries.length - 1; i >= 0; i--) {\n const entry = historyEntries[i];\n if (!entry) continue;\n\n const entryTokens = this.estimateMessagesTokens(entry.content?.messages ?? []);\n\n // Check if adding this entry would exceed token budget\n if (accumulatedTokens + entryTokens > keepRecentTokens) {\n // Would exceed budget, split here (this entry and earlier ones will be compacted)\n splitIndex = i + 1;\n break;\n }\n\n // Can keep this entry, accumulate and continue\n accumulatedTokens += entryTokens;\n splitIndex = i;\n }\n\n // Split history at the found point\n const entriesToCompact = historyEntries.slice(0, splitIndex);\n const entriesToKeep = historyEntries.slice(splitIndex);\n\n // If nothing to compact, return\n if (entriesToCompact.length === 0) {\n return;\n }\n\n const latestCompactedEntry = entriesToCompact.at(-1);\n if (!latestCompactedEntry) return;\n\n // Split into batches to avoid context overflow\n const batches = this.splitIntoBatches(entriesToCompact, maxTokens);\n\n // Process batches incrementally, each summary becomes input for the next\n let currentSummary = this.runtimeState.historyCompact?.summary;\n for (const batch of batches) {\n const messages = batch\n .flatMap((e) => e.content?.messages ?? [])\n .filter(isNonNullable)\n .map((msg) => this.truncateLargeMessage(msg));\n\n const result = await options.context.invoke(compactor, {\n previousSummary: [currentSummary].filter(isNonNullable),\n messages,\n });\n currentSummary = result.summary;\n }\n\n // Extract last Agent Skill from entries to compact\n let lastAgentSkill = this.findLastAgentSkill(entriesToCompact);\n\n // If no skill found in entries to compact, inherit from previous compact\n if (!lastAgentSkill && this.runtimeState.historyCompact?.lastAgentSkill) {\n lastAgentSkill = this.runtimeState.historyCompact.lastAgentSkill;\n }\n\n // Create compact content\n const historyCompact: CompactContent = {\n summary: currentSummary ?? \"\",\n lastAgentSkill,\n };\n\n // Write compact entry to AFS\n if (this.afs && this.historyModulePath) {\n await this.afs.write(\n joinURL(this.historyModulePath, \"by-session\", this.sessionId, \"@metadata/compact/new\"),\n {\n userId: this.userId,\n agentId: this.agentId,\n content: historyCompact,\n metadata: {\n latestEntryId: latestCompactedEntry.id,\n },\n },\n );\n }\n\n // Update runtime state: keep the summary and recent entries\n this.runtimeState.historyCompact = historyCompact;\n this.runtimeState.historyEntries = entriesToKeep;\n }\n\n private async compactCurrentEntry(options: AgentInvokeOptions): Promise<void> {\n const { compactor } = this.compactConfig ?? {};\n if (!compactor) return;\n\n const currentEntry = this.runtimeState.currentEntry;\n if (!currentEntry?.messages?.length) return;\n\n const alreadyCompressedCount = this.runtimeState.currentEntryCompact?.compressedCount ?? 0;\n const uncompressedMessages = currentEntry.messages.slice(alreadyCompressedCount);\n\n if (uncompressedMessages.length === 0) return;\n\n // Target to keep only 50% of keepTokenBudget to leave buffer room\n // This avoids frequent small-batch compressions in tool use scenarios\n const keepTokenBudget = this.keepRecentTokens * 0.5;\n\n let splitIndex = uncompressedMessages.length;\n let accumulatedTokens = 0;\n\n for (let i = uncompressedMessages.length - 1; i >= 0; i--) {\n const msg = uncompressedMessages[i];\n if (!msg) continue;\n\n const msgTokens = this.estimateMessagesTokens([msg]);\n\n if (accumulatedTokens + msgTokens > keepTokenBudget) {\n splitIndex = i + 1;\n break;\n }\n\n accumulatedTokens += msgTokens;\n splitIndex = i;\n }\n\n const keptMessages = uncompressedMessages.slice(splitIndex);\n const requiredToolCallIds = new Set<string>();\n\n for (const msg of keptMessages) {\n if (msg.role === \"tool\" && msg.toolCallId) {\n requiredToolCallIds.add(msg.toolCallId);\n }\n }\n\n if (requiredToolCallIds.size > 0) {\n for (let i = splitIndex - 1; i >= 0; i--) {\n const msg = uncompressedMessages[i];\n if (!msg?.toolCalls) continue;\n\n for (const toolCall of msg.toolCalls) {\n if (requiredToolCallIds.has(toolCall.id)) {\n splitIndex = i;\n break;\n }\n }\n }\n }\n\n const messagesToCompact = uncompressedMessages\n .slice(0, splitIndex)\n .map((msg) => this.truncateLargeMessage(msg));\n\n if (messagesToCompact.length === 0) return;\n\n const result = await options.context.invoke(compactor, {\n previousSummary: this.runtimeState.currentEntryCompact?.summary\n ? [this.runtimeState.currentEntryCompact.summary]\n : undefined,\n messages: messagesToCompact,\n });\n\n // Find last Agent Skill from messages being compacted\n const lastAgentSkill =\n this.findLastAgentSkillFromMessages(messagesToCompact) ??\n this.runtimeState.currentEntryCompact?.lastAgentSkill;\n\n this.runtimeState.currentEntryCompact = {\n summary: result.summary,\n lastAgentSkill,\n compressedCount: alreadyCompressedCount + messagesToCompact.length,\n };\n }\n\n private async maybeCompactCurrentEntry(options: AgentInvokeOptions): Promise<void> {\n const currentEntry = this.runtimeState.currentEntry;\n if (!currentEntry?.messages?.length) return;\n\n const compressedCount = this.runtimeState.currentEntryCompact?.compressedCount ?? 0;\n const uncompressedMessages = currentEntry.messages.slice(compressedCount);\n\n const threshold = this.keepRecentTokens;\n const currentTokens = this.estimateMessagesTokens(uncompressedMessages);\n\n if (currentTokens > threshold) {\n await this.compactCurrentEntry(options);\n }\n }\n\n private async maybeAutoCompact(options: AgentInvokeOptions): Promise<void> {\n if (this.compactionPromise) await this.compactionPromise;\n\n const mode = this.compactConfig.mode ?? DEFAULT_COMPACT_MODE;\n if (mode === \"disabled\") return;\n\n const { compactor } = this.compactConfig;\n if (!compactor) return;\n\n const maxTokens = this.maxTokens;\n\n const messages = await this.getMessages();\n const currentTokens = this.estimateMessagesTokens(messages);\n\n if (currentTokens >= maxTokens) {\n await this.compact(options);\n }\n }\n\n /**\n * Estimate token count for messages\n * Applies singleMessageLimit to each text block individually\n * Non-text tokens (images, tool calls) are always counted in full\n */\n private estimateMessagesTokens(\n messages: ChatModelInputMessage[],\n singleMessageLimit: number = this.singleMessageLimit,\n ): number {\n let totalTokens = 0;\n\n for (const msg of messages) {\n // 1. Estimate content tokens\n if (typeof msg.content === \"string\") {\n const textTokens = estimateTokens(msg.content);\n const effectiveTokens = textTokens > singleMessageLimit ? singleMessageLimit : textTokens;\n totalTokens += effectiveTokens;\n } else if (Array.isArray(msg.content)) {\n for (const block of msg.content) {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n // Text tokens (can be truncated) - apply limit to each block individually\n const textTokens = estimateTokens(block.text);\n const effectiveTokens =\n textTokens > singleMessageLimit ? singleMessageLimit : textTokens;\n totalTokens += effectiveTokens;\n } else {\n // Non-text blocks - always counted in full\n totalTokens += 1000;\n }\n }\n }\n\n // 2. Estimate tool calls tokens (cannot be truncated)\n if (msg.toolCalls && msg.toolCalls.length > 0) {\n for (const toolCall of msg.toolCalls) {\n // Function name + arguments + overhead\n totalTokens += estimateTokens(toolCall.function.name);\n totalTokens += estimateTokens(\n stringify(toolCall.function.arguments).replace(/\\s+/g, \" \"),\n );\n totalTokens += 10; // Structure overhead\n }\n }\n }\n\n return totalTokens;\n }\n\n /**\n * Split entries into batches based on token limit\n * Each batch will not exceed the specified maxTokens\n */\n private splitIntoBatches(\n entries: AFSEntry<EntryContent>[],\n maxTokens: number,\n ): AFSEntry<EntryContent>[][] {\n const batches: AFSEntry<EntryContent>[][] = [];\n let currentBatch: AFSEntry<EntryContent>[] = [];\n let currentTokens = 0;\n\n for (const entry of entries) {\n const entryTokens = this.estimateMessagesTokens(entry.content?.messages ?? []);\n\n // If adding this entry exceeds limit and we have entries in current batch, start new batch\n if (currentTokens + entryTokens > maxTokens && currentBatch.length > 0) {\n batches.push(currentBatch);\n currentBatch = [entry];\n currentTokens = entryTokens;\n } else {\n currentBatch.push(entry);\n currentTokens += entryTokens;\n }\n }\n\n // Add remaining entries\n if (currentBatch.length > 0) {\n batches.push(currentBatch);\n }\n\n return batches;\n }\n\n async appendCurrentMessages(\n messages: ChatModelInputMessage | ChatModelInputMessage[],\n options: AgentInvokeOptions,\n ): Promise<void> {\n await this.ensureInitialized();\n\n if (!this.runtimeState.currentEntry || !this.runtimeState.currentEntry.messages?.length) {\n throw new Error(\"No current entry to append messages. Call startMessage() first.\");\n }\n\n this.runtimeState.currentEntry.messages.push(...[messages].flat());\n\n await this.maybeCompactCurrentEntry(options);\n }\n\n /**\n * Truncate text content to fit within target token limit\n * @param text The text to truncate\n * @param currentTokens Current token count of the text\n * @param targetTokens Target token count after truncation\n * @returns Truncated text\n */\n private truncateText(text: string, currentTokens: number, targetTokens: number): string {\n if (currentTokens <= targetTokens) return text;\n\n const keepRatio = (targetTokens / currentTokens) * 0.9;\n const keepLength = Math.floor(text.length * keepRatio);\n const headLength = Math.floor(keepLength * 0.7);\n const tailLength = Math.floor(keepLength * 0.3);\n\n return (\n text.slice(0, headLength) +\n `\\n\\n[... truncated ${currentTokens - targetTokens} tokens ...]\\n\\n` +\n text.slice(-tailLength)\n );\n }\n\n private truncateLargeMessage(msg: ChatModelInputMessage): ChatModelInputMessage {\n const singleMessageLimit = this.singleMessageLimit;\n\n // Handle string content\n if (typeof msg.content === \"string\") {\n const tokens = estimateTokens(msg.content);\n if (tokens <= singleMessageLimit) return msg;\n\n const truncated = this.truncateText(msg.content, tokens, singleMessageLimit);\n return { ...msg, content: truncated };\n }\n\n // Handle array content (UnionContent[])\n if (Array.isArray(msg.content)) {\n // Truncate each text block individually if it exceeds the limit\n const truncatedContent = msg.content.map((block) => {\n // Keep non-text blocks unchanged\n if (block.type !== \"text\" || typeof block.text !== \"string\") {\n return block;\n }\n\n // Check if this text block needs truncation\n const blockTokens = estimateTokens(block.text);\n if (blockTokens <= singleMessageLimit) {\n return block;\n }\n\n // Truncate this text block independently\n const truncatedText = this.truncateText(block.text, blockTokens, singleMessageLimit);\n return { ...block, text: truncatedText };\n });\n\n return { ...msg, content: truncatedContent };\n }\n\n // Unknown content type, return as-is\n return msg;\n }\n\n private async ensureInitialized(): Promise<void> {\n this.initialized ??= this.initialize();\n await this.initialized;\n }\n\n private async initialize(): Promise<void> {\n if (this.initialized) return;\n\n await this.initializeDefaultCompactor();\n await this.initializeDefaultSessionMemoryExtractor();\n await this.initializeDefaultUserMemoryExtractor();\n\n const historyModule = (await this.afs?.listModules())?.find(\n (m) => m.module instanceof AFSHistory,\n );\n\n this.historyModulePath = historyModule?.path;\n\n if (this.afs && this.historyModulePath) {\n // Load user memory, session memory, and session history in parallel\n const [userMemory, sessionMemory, sessionHistory] = await Promise.all([\n this.loadUserMemory(),\n this.loadSessionMemory(),\n this.loadSessionHistory(),\n ]);\n\n // Update runtime state with loaded data\n this.runtimeState.userMemory = userMemory;\n this.runtimeState.sessionMemory = sessionMemory;\n this.runtimeState.historyCompact = sessionHistory.historyCompact;\n this.runtimeState.historyEntries = sessionHistory.historyEntries;\n }\n }\n\n /**\n * Load session memory facts\n * @returns Array of memory fact entries for the current session\n */\n private async loadSessionMemory(): Promise<AFSEntry<MemoryFact>[]> {\n if (!this.afs || !this.historyModulePath) return [];\n\n // Check if session memory is disabled\n const mode = this.sessionMemoryConfig.mode ?? DEFAULT_SESSION_MEMORY_MODE;\n if (mode === \"disabled\") return [];\n\n const sessionMemoryPath = joinURL(\n this.historyModulePath,\n \"by-session\",\n this.sessionId,\n \"@metadata/memory\",\n );\n\n const queryLimit = this.sessionMemoryConfig.queryLimit ?? DEFAULT_MEMORY_QUERY_LIMIT;\n\n const memoryResult = await this.afs.list(sessionMemoryPath, {\n filter: { userId: this.userId, agentId: this.agentId },\n orderBy: [[\"updatedAt\", \"desc\"]],\n limit: queryLimit,\n });\n\n // Filter out entries without content\n const facts = memoryResult.data\n .reverse()\n .filter((entry: AFSEntry) => isNonNullable(entry.content)) as AFSEntry<MemoryFact>[];\n\n return facts;\n }\n\n /**\n * Load user memory facts\n * @returns Array of memory fact entries for the current user\n */\n private async loadUserMemory(): Promise<AFSEntry<MemoryFact>[]> {\n if (!this.afs || !this.historyModulePath || !this.userId) return [];\n\n // Check if user memory is disabled\n const mode = this.userMemoryConfig.mode ?? DEFAULT_USER_MEMORY_MODE;\n if (mode === \"disabled\") return [];\n\n const userMemoryPath = joinURL(\n this.historyModulePath,\n \"by-user\",\n this.userId,\n \"@metadata/memory\",\n );\n\n const queryLimit = this.userMemoryConfig.queryLimit ?? DEFAULT_MEMORY_QUERY_LIMIT;\n\n const memoryResult = await this.afs.list(userMemoryPath, {\n filter: { userId: this.userId, agentId: this.agentId },\n orderBy: [[\"updatedAt\", \"desc\"]],\n limit: queryLimit,\n });\n\n // Filter out entries without content\n const facts = memoryResult.data\n .reverse()\n .filter((entry: AFSEntry) => isNonNullable(entry.content)) as AFSEntry<MemoryFact>[];\n\n return facts;\n }\n\n /**\n * Load session history including compact content and history entries\n * @returns Object containing history compact and history entries\n */\n private async loadSessionHistory(): Promise<{\n historyCompact?: CompactContent;\n historyEntries: AFSEntry<EntryContent>[];\n }> {\n if (!this.afs || !this.historyModulePath) {\n return { historyEntries: [] };\n }\n\n // Load latest compact entry if exists\n const compactPath = joinURL(\n this.historyModulePath,\n \"by-session\",\n this.sessionId,\n \"@metadata/compact\",\n );\n\n const compactResult = await this.afs.list(compactPath, {\n filter: { userId: this.userId, agentId: this.agentId },\n orderBy: [[\"createdAt\", \"desc\"]],\n limit: 1,\n });\n\n const latestCompact = compactResult.data[0] as\n | (AFSEntry & { content?: CompactContent; metadata?: { latestEntryId?: string } })\n | undefined;\n\n const historyCompact = latestCompact?.content;\n\n // Load history entries (after compact point if exists)\n const afsEntries: AFSEntry[] = (\n await this.afs.list(joinURL(this.historyModulePath, \"by-session\", this.sessionId), {\n filter: {\n userId: this.userId,\n agentId: this.agentId,\n // Only load entries after the latest compact\n after: latestCompact?.createdAt?.toISOString(),\n },\n orderBy: [[\"createdAt\", \"desc\"]],\n // Set a very large limit to load all history entries\n // The default limit is 10 which would cause history truncation\n limit: 10000,\n })\n ).data;\n\n const historyEntries = afsEntries.reverse().filter((entry) => isNonNullable(entry.content));\n\n return {\n historyCompact,\n historyEntries,\n };\n }\n\n /**\n * Manually trigger session memory update\n */\n async updateSessionMemory(options: AgentInvokeOptions): Promise<void> {\n await this.ensureInitialized();\n\n this.sessionMemoryUpdatePromise ??= this.doUpdateSessionMemory(options)\n .then(() => {\n // After session memory update succeeds, potentially trigger user memory consolidation\n this.maybeAutoUpdateUserMemory(options).catch((err) => {\n logger.error(\"User memory update failed:\", err);\n });\n })\n .finally(() => {\n this.sessionMemoryUpdatePromise = undefined;\n });\n\n return this.sessionMemoryUpdatePromise;\n }\n\n private async maybeAutoUpdateSessionMemory(options: AgentInvokeOptions): Promise<void> {\n // Check if memory extraction is enabled (requires AFS history module)\n if (!this.isMemoryEnabled) return;\n\n // Check if mode is disabled\n const mode = this.sessionMemoryConfig.mode ?? DEFAULT_SESSION_MEMORY_MODE;\n if (mode === \"disabled\") return;\n\n // Trigger session memory update\n this.updateSessionMemory(options).catch((err) => {\n logger.error(\"Session memory update failed:\", err);\n });\n\n const isAsync = this.sessionMemoryConfig.async ?? DEFAULT_SESSION_MEMORY_ASYNC;\n\n if (!isAsync) await this.sessionMemoryUpdatePromise;\n }\n\n private async maybeAutoUpdateUserMemory(options: AgentInvokeOptions): Promise<void> {\n // Check if memory extraction is enabled (requires AFS history module)\n if (!this.isMemoryEnabled || !this.userId) return;\n\n // Check if mode is disabled\n const mode = this.userMemoryConfig.mode ?? DEFAULT_USER_MEMORY_MODE;\n if (mode === \"disabled\") return;\n\n // Trigger user memory consolidation\n this.updateUserMemory(options).catch((err) => {\n logger.error(\"User memory update failed:\", err);\n });\n\n const isAsync = this.userMemoryConfig.async ?? DEFAULT_USER_MEMORY_ASYNC;\n\n if (!isAsync) await this.userMemoryUpdatePromise;\n }\n\n /**\n * Internal method that performs the actual session memory update\n */\n private async doUpdateSessionMemory(options: AgentInvokeOptions): Promise<void> {\n const { extractor } = this.sessionMemoryConfig ?? {};\n if (!extractor) {\n throw new Error(\"Cannot update session memory without an extractor agent configured.\");\n }\n\n // Get latestEntryId from the most recent memory entry's metadata\n // This tells us which history entries have already been processed\n const latestEntryId = this.runtimeState.sessionMemory?.at(-1)?.metadata?.latestEntryId as\n | string\n | undefined;\n\n // Filter unextracted entries based on latestEntryId\n // Similar to compact mechanism, we find the position of the last extracted entry\n // and only process entries after that point\n const lastExtractedIndex = latestEntryId\n ? this.runtimeState.historyEntries.findIndex((e) => e.id === latestEntryId)\n : -1;\n\n const unextractedEntries =\n lastExtractedIndex >= 0\n ? this.runtimeState.historyEntries.slice(lastExtractedIndex + 1)\n : this.runtimeState.historyEntries;\n\n if (unextractedEntries.length === 0) return;\n\n // Get recent conversation messages for extraction\n const recentMessages = unextractedEntries\n .flatMap((entry) => entry.content?.messages ?? [])\n .filter(isNonNullable);\n\n if (recentMessages.length === 0) return;\n\n // Get existing session memory facts for context\n const existingFacts =\n this.runtimeState.sessionMemory?.map((entry) => entry.content).filter(isNonNullable) ?? [];\n\n // Get user memory facts to avoid duplication\n const existingUserFacts =\n this.runtimeState.userMemory?.map((entry) => entry.content).filter(isNonNullable) ?? [];\n\n // Extract new facts from conversation\n const result = await options.context.invoke(extractor, {\n existingUserFacts,\n existingFacts,\n messages: recentMessages,\n });\n\n // If no changes, nothing to do\n if (!result.newFacts.length && !result.removeFacts?.length) {\n return;\n }\n\n // Get the last entry to record its ID for metadata\n const latestExtractedEntry = unextractedEntries.at(-1);\n\n if (this.afs && this.historyModulePath) {\n // Handle fact removal\n if (result.removeFacts?.length && this.runtimeState.sessionMemory) {\n const entriesToRemove: AFSEntry<MemoryFact>[] = [];\n\n for (const label of result.removeFacts) {\n const entry = this.runtimeState.sessionMemory.find((e) => e.content?.label === label);\n if (entry) entriesToRemove.push(entry);\n }\n\n // Remove from AFS storage and runtime state\n for (const entryToRemove of entriesToRemove) {\n // Delete from AFS storage\n const memoryEntryPath = joinURL(\n this.historyModulePath,\n \"by-session\",\n this.sessionId,\n \"@metadata/memory\",\n entryToRemove.id,\n );\n await this.afs.delete(memoryEntryPath);\n\n // Remove from runtime state\n const index = this.runtimeState.sessionMemory.indexOf(entryToRemove);\n if (index !== -1) {\n this.runtimeState.sessionMemory.splice(index, 1);\n }\n }\n }\n\n // Handle new facts\n if (result.newFacts.length) {\n const sessionMemoryPath = joinURL(\n this.historyModulePath,\n \"by-session\",\n this.sessionId,\n \"@metadata/memory/new\",\n );\n\n for (const fact of result.newFacts) {\n const newEntry = await this.afs.write(sessionMemoryPath, {\n userId: this.userId,\n sessionId: this.sessionId,\n agentId: this.agentId,\n content: fact,\n metadata: {\n latestEntryId: latestExtractedEntry?.id,\n },\n });\n\n // Add to runtime state\n this.runtimeState.sessionMemory ??= [];\n this.runtimeState.sessionMemory.push(newEntry.data);\n }\n }\n }\n }\n\n /**\n * Manually trigger user memory update\n */\n async updateUserMemory(options: AgentInvokeOptions): Promise<void> {\n await this.ensureInitialized();\n\n // Start new user memory update task\n this.userMemoryUpdatePromise ??= this.doUpdateUserMemory(options).finally(() => {\n this.userMemoryUpdatePromise = undefined;\n });\n\n return this.userMemoryUpdatePromise;\n }\n\n /**\n * Internal method that performs the actual user memory extraction\n */\n private async doUpdateUserMemory(options: AgentInvokeOptions): Promise<void> {\n const { extractor } = this.userMemoryConfig ?? {};\n if (!extractor) {\n throw new Error(\"Cannot update user memory without an extractor agent configured.\");\n }\n\n // Get session memory facts as the source for consolidation\n const sessionFacts =\n this.runtimeState.sessionMemory?.map((entry) => entry.content).filter(isNonNullable) ?? [];\n\n if (sessionFacts.length === 0) return;\n\n // Get existing user memory facts for context and deduplication\n const existingUserFacts =\n this.runtimeState.userMemory?.map((entry) => entry.content).filter(isNonNullable) ?? [];\n\n // Extract user memory facts from session memory\n const result = await options.context.invoke(extractor, {\n sessionFacts,\n existingUserFacts,\n });\n\n // If no changes, nothing to do\n if (!result.newFacts.length && !result.removeFacts?.length) {\n return;\n }\n\n if (this.afs && this.historyModulePath && this.userId) {\n // Handle fact removal\n if (result.removeFacts?.length && this.runtimeState.userMemory) {\n const entriesToRemove: AFSEntry<MemoryFact>[] = [];\n\n for (const label of result.removeFacts) {\n const entry = this.runtimeState.userMemory.find((e) => e.content?.label === label);\n if (entry) entriesToRemove.push(entry);\n }\n\n // Remove from AFS storage and runtime state\n for (const entryToRemove of entriesToRemove) {\n const memoryEntryPath = joinURL(\n this.historyModulePath,\n \"by-user\",\n this.userId,\n \"@metadata/memory\",\n entryToRemove.id,\n );\n await this.afs.delete(memoryEntryPath);\n\n const index = this.runtimeState.userMemory.indexOf(entryToRemove);\n if (index !== -1) {\n this.runtimeState.userMemory.splice(index, 1);\n }\n }\n }\n\n // Handle new/updated facts\n // For user memory, labels are unique - replace existing facts with same label\n if (result.newFacts.length) {\n const userMemoryPath = joinURL(\n this.historyModulePath,\n \"by-user\",\n this.userId,\n \"@metadata/memory/new\",\n );\n\n for (const fact of result.newFacts) {\n // Check if fact with same label already exists\n const existingEntry = this.runtimeState.userMemory?.find(\n (e) => e.content?.label === fact.label,\n );\n\n if (existingEntry) {\n // Delete old entry\n const oldEntryPath = joinURL(\n this.historyModulePath,\n \"by-user\",\n this.userId,\n \"@metadata/memory\",\n existingEntry.id,\n );\n await this.afs.delete(oldEntryPath);\n\n // Remove from runtime state\n if (this.runtimeState.userMemory) {\n const index = this.runtimeState.userMemory.indexOf(existingEntry);\n if (index !== -1) {\n this.runtimeState.userMemory.splice(index, 1);\n }\n }\n }\n\n // Create new entry\n const newEntry = await this.afs.write(userMemoryPath, {\n userId: this.userId,\n agentId: this.agentId,\n content: fact,\n });\n\n // Add to runtime state\n this.runtimeState.userMemory ??= [];\n this.runtimeState.userMemory.push(newEntry.data);\n }\n }\n }\n }\n\n /**\n * Find Agent Skill content from a single message\n * @param msg - Message to search in\n * @returns The skill content text if found, undefined otherwise\n */\n private findSkillContentInMessage(msg: ChatModelInputMessage): string | undefined {\n if (msg.role === \"user\" && Array.isArray(msg.content)) {\n const skillBlock = msg.content.find(\n (block) => block.type === \"text\" && block.isAgentSkill === true,\n );\n\n if (skillBlock && skillBlock.type === \"text\") {\n return skillBlock.text;\n }\n }\n return undefined;\n }\n\n /**\n * Find the last Agent Skill from a list of messages\n * @param messages - Messages to search through\n * @returns The last Agent Skill found, or undefined if none found\n */\n private findLastAgentSkillFromMessages(\n messages: ChatModelInputMessage[],\n ): CompactContent[\"lastAgentSkill\"] | undefined {\n // Search backwards through messages to find the last Agent Skill\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (!msg) continue;\n\n const skillContent = this.findSkillContentInMessage(msg);\n if (skillContent) {\n return {\n content: skillContent,\n };\n }\n }\n\n return undefined;\n }\n\n /**\n * Find the last Agent Skill from a list of history entries\n * @param entries - History entries to search through\n * @returns The last Agent Skill found, or undefined if none found\n */\n private findLastAgentSkill(\n entries: AFSEntry<EntryContent>[],\n ): CompactContent[\"lastAgentSkill\"] | undefined {\n // Flatten all messages from entries\n const allMessages = entries.flatMap((entry) => entry.content?.messages ?? []);\n return this.findLastAgentSkillFromMessages(allMessages);\n }\n\n private async initializeDefaultCompactor() {\n this.compactConfig.compactor ??= await import(\"./compact/compactor.js\").then(\n (m) => new m.AISessionCompactor(),\n );\n }\n\n private async initializeDefaultSessionMemoryExtractor() {\n this.sessionMemoryConfig.extractor ??= await import(\n \"./compact/session-memory-extractor.js\"\n ).then((m) => new m.AISessionMemoryExtractor());\n }\n\n private async initializeDefaultUserMemoryExtractor() {\n this.userMemoryConfig.extractor ??= await import(\"./compact/user-memory-extractor.js\").then(\n (m) => new m.AIUserMemoryExtractor(),\n );\n }\n\n private get maxTokens(): number {\n return this.compactConfig?.maxTokens ?? DEFAULT_MAX_TOKENS;\n }\n\n private get keepRecentRatio(): number {\n return this.compactConfig?.keepRecentRatio ?? DEFAULT_KEEP_RECENT_RATIO;\n }\n\n private get keepRecentTokens(): number {\n return Math.floor(this.maxTokens * this.keepRecentRatio);\n }\n\n private get singleMessageLimit(): number {\n return this.keepRecentTokens * 0.5;\n }\n}\n"],"mappings":";;;;;;;;;;AA+EA,IAAa,eAAb,MAA0B;CACxB,AAAS;CACT,AAAS;CACT,AAAS;CAET,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,SAA8B;AACxC,OAAK,YAAY,QAAQ;AACzB,OAAK,SAAS,QAAQ;AACtB,OAAK,UAAU,QAAQ;AACvB,OAAK,MAAM,QAAQ;AACnB,OAAK,OAAO,QAAQ,QAAQ;AAC5B,OAAK,gBAAgB,QAAQ,WAAW,EAAE;AAC1C,OAAK,sBAAsB,QAAQ,iBAAiB,EAAE;AACtD,OAAK,mBAAmB,QAAQ,cAAc,EAAE;AAEhD,OAAK,eAAe;GAClB,gBAAgB,EAAE;GAClB,cAAc;GACf;;;;;;CAOH,IAAY,kBAA2B;AACrC,SAAO,KAAK,SAAS,UAAU,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,KAAK;;CAGtD,MAAM,kBAAkB,GAAG,UAAkD;AAC3E,QAAM,KAAK,mBAAmB;AAE9B,OAAK,aAAa,iBAAiB;;CAGrC,MAAM,cAAgD;AACpD,QAAM,KAAK,mBAAmB;EAE9B,MAAM,EACJ,gBACA,YACA,eACA,gBACA,gBACA,cACA,wBACE,KAAK;EAET,IAAI,kBAA2C,EAAE;AACjD,MAAI,cAAc,UAAU,OAC1B,KAAI,qBAAqB;GACvB,MAAM,EAAE,iBAAiB,YAAY;AAQrC,qBAAkB,CANK;IACrB,MAAM;IACN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AO,KAAK,eAAe,mBAAmB;;CAGhD,IAAY,mBAA2B;AACrC,SAAO,KAAK,MAAM,KAAK,YAAY,KAAK,gBAAgB;;CAG1D,IAAY,qBAA6B;AACvC,SAAO,KAAK,mBAAmB"}
@@ -0,0 +1,50 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ const require_utils_type_utils = require('../../utils/type-utils.cjs');
3
+ const require_ai_agent = require('../../agents/ai-agent.cjs');
4
+ let zod = require("zod");
5
+
6
+ //#region src/prompt/compact/compactor.ts
7
+ const COMPACTOR_INSTRUCTIONS = `\
8
+ You are a conversation summarizer. Your task is to create a concise but comprehensive summary of the conversation history provided.
9
+
10
+ ## Conversation history
11
+
12
+ \`\`\`yaml alt="previous-summary"
13
+ {{ previousSummary | yaml.stringify }}
14
+ \`\`\`
15
+
16
+
17
+ \`\`\`yaml alt="conversation-histories"
18
+ {{ messages | yaml.stringify }}
19
+ \`\`\`
20
+
21
+ ## Guidelines
22
+
23
+ 1. Preserve key information, decisions, and context that would be needed for future conversation continuity
24
+ 2. Include important facts, names, dates, and specific details mentioned
25
+ 3. Summarize the user's goals and preferences expressed in the conversation
26
+ 4. Note any pending tasks or follow-up items
27
+ 5. Keep the summary focused and avoid unnecessary verbosity
28
+ 6. Write in a neutral, factual tone
29
+
30
+ Output a single summary that captures the essence of the conversation.`;
31
+ var AISessionCompactor = class extends require_ai_agent.AIAgent {
32
+ constructor(options) {
33
+ super({
34
+ name: "SessionCompactor",
35
+ description: "Generates conversation summaries for session compaction",
36
+ inputSchema: zod.z.object({
37
+ previousSummary: (0, zod.optional)(zod.z.array(zod.z.string()).describe("List of previous conversation summaries")),
38
+ messages: zod.z.array(zod.z.any())
39
+ }),
40
+ outputSchema: zod.z.object({ summary: zod.z.string().describe("A comprehensive summary of the conversation history") }),
41
+ instructions: COMPACTOR_INSTRUCTIONS,
42
+ taskRenderMode: "hide",
43
+ ...require_utils_type_utils.omitBy(options ?? {}, (v) => require_utils_type_utils.isNil(v)),
44
+ session: { mode: "disabled" }
45
+ });
46
+ }
47
+ };
48
+
49
+ //#endregion
50
+ exports.AISessionCompactor = AISessionCompactor;
@@ -0,0 +1,50 @@
1
+ import { isNil, omitBy } from "../../utils/type-utils.mjs";
2
+ import { AIAgent } from "../../agents/ai-agent.mjs";
3
+ import { optional, z as z$1 } from "zod";
4
+
5
+ //#region src/prompt/compact/compactor.ts
6
+ const COMPACTOR_INSTRUCTIONS = `\
7
+ You are a conversation summarizer. Your task is to create a concise but comprehensive summary of the conversation history provided.
8
+
9
+ ## Conversation history
10
+
11
+ \`\`\`yaml alt="previous-summary"
12
+ {{ previousSummary | yaml.stringify }}
13
+ \`\`\`
14
+
15
+
16
+ \`\`\`yaml alt="conversation-histories"
17
+ {{ messages | yaml.stringify }}
18
+ \`\`\`
19
+
20
+ ## Guidelines
21
+
22
+ 1. Preserve key information, decisions, and context that would be needed for future conversation continuity
23
+ 2. Include important facts, names, dates, and specific details mentioned
24
+ 3. Summarize the user's goals and preferences expressed in the conversation
25
+ 4. Note any pending tasks or follow-up items
26
+ 5. Keep the summary focused and avoid unnecessary verbosity
27
+ 6. Write in a neutral, factual tone
28
+
29
+ Output a single summary that captures the essence of the conversation.`;
30
+ var AISessionCompactor = class extends AIAgent {
31
+ constructor(options) {
32
+ super({
33
+ name: "SessionCompactor",
34
+ description: "Generates conversation summaries for session compaction",
35
+ inputSchema: z$1.object({
36
+ previousSummary: optional(z$1.array(z$1.string()).describe("List of previous conversation summaries")),
37
+ messages: z$1.array(z$1.any())
38
+ }),
39
+ outputSchema: z$1.object({ summary: z$1.string().describe("A comprehensive summary of the conversation history") }),
40
+ instructions: COMPACTOR_INSTRUCTIONS,
41
+ taskRenderMode: "hide",
42
+ ...omitBy(options ?? {}, (v) => isNil(v)),
43
+ session: { mode: "disabled" }
44
+ });
45
+ }
46
+ };
47
+
48
+ //#endregion
49
+ export { AISessionCompactor };
50
+ //# sourceMappingURL=compactor.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compactor.mjs","names":["z"],"sources":["../../../src/prompt/compact/compactor.ts"],"sourcesContent":["import { optional, z } from \"zod\";\nimport { AIAgent, type AIAgentOptions } from \"../../agents/ai-agent.js\";\nimport { isNil, omitBy } from \"../../utils/type-utils.js\";\nimport type { CompactContent, CompactorInput } from \"./types.js\";\n\nconst COMPACTOR_INSTRUCTIONS = `\\\nYou are a conversation summarizer. Your task is to create a concise but comprehensive summary of the conversation history provided.\n\n## Conversation history\n\n${\"```\"}yaml alt=\"previous-summary\"\n{{ previousSummary | yaml.stringify }}\n${\"```\"}\n\n\n${\"```\"}yaml alt=\"conversation-histories\"\n{{ messages | yaml.stringify }}\n${\"```\"}\n\n## Guidelines\n\n1. Preserve key information, decisions, and context that would be needed for future conversation continuity\n2. Include important facts, names, dates, and specific details mentioned\n3. Summarize the user's goals and preferences expressed in the conversation\n4. Note any pending tasks or follow-up items\n5. Keep the summary focused and avoid unnecessary verbosity\n6. Write in a neutral, factual tone\n\nOutput a single summary that captures the essence of the conversation.`;\n\nexport interface CreateCompactorOptions extends AIAgentOptions<CompactorInput, CompactContent> {}\n\nexport class AISessionCompactor extends AIAgent<CompactorInput, CompactContent> {\n constructor(options?: CreateCompactorOptions) {\n super({\n name: \"SessionCompactor\",\n description: \"Generates conversation summaries for session compaction\",\n inputSchema: z.object({\n previousSummary: optional(\n z.array(z.string()).describe(\"List of previous conversation summaries\"),\n ),\n messages: z.array(z.any()),\n }),\n outputSchema: z.object({\n summary: z.string().describe(\"A comprehensive summary of the conversation history\"),\n }),\n instructions: COMPACTOR_INSTRUCTIONS,\n taskRenderMode: \"hide\",\n ...omitBy(options ?? {}, (v) => isNil(v)),\n session: {\n mode: \"disabled\",\n },\n });\n }\n}\n"],"mappings":";;;;;AAKA,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;AA2B/B,IAAa,qBAAb,cAAwC,QAAwC;CAC9E,YAAY,SAAkC;AAC5C,QAAM;GACJ,MAAM;GACN,aAAa;GACb,aAAaA,IAAE,OAAO;IACpB,iBAAiB,SACfA,IAAE,MAAMA,IAAE,QAAQ,CAAC,CAAC,SAAS,0CAA0C,CACxE;IACD,UAAUA,IAAE,MAAMA,IAAE,KAAK,CAAC;IAC3B,CAAC;GACF,cAAcA,IAAE,OAAO,EACrB,SAASA,IAAE,QAAQ,CAAC,SAAS,sDAAsD,EACpF,CAAC;GACF,cAAc;GACd,gBAAgB;GAChB,GAAG,OAAO,WAAW,EAAE,GAAG,MAAM,MAAM,EAAE,CAAC;GACzC,SAAS,EACP,MAAM,YACP;GACF,CAAC"}
@@ -0,0 +1,137 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ const require_utils_type_utils = require('../../utils/type-utils.cjs');
3
+ const require_ai_agent = require('../../agents/ai-agent.cjs');
4
+ let zod = require("zod");
5
+
6
+ //#region src/prompt/compact/session-memory-extractor.ts
7
+ const EXTRACTOR_INSTRUCTIONS = `\
8
+ You are a session memory fact extractor. Your task is to extract facts that help continue THIS SESSION's work.
9
+
10
+ **Key Principle**: Extract WORK CONTEXT (tasks, decisions, blockers), NOT PROJECT DOCUMENTATION (tech stack, code structure, implementation details).
11
+
12
+ Session memory is for remembering:
13
+ - What we're trying to accomplish
14
+ - Why we made certain choices
15
+ - What problems we encountered
16
+ - Important context for continuing the work
17
+
18
+ Session memory is NOT for documenting:
19
+ - What the code does (visible in code)
20
+ - How the project is structured (can explore directly)
21
+ - What technologies are used (obvious from files)
22
+
23
+ ## User Memory Facts (Long-term, cross-session)
24
+
25
+ \`\`\`yaml alt="user-memory-facts"
26
+ {{ existingUserFacts | yaml.stringify }}
27
+ \`\`\`
28
+
29
+ ## Existing Session Memory Facts
30
+
31
+ \`\`\`yaml alt="existing-facts"
32
+ {{ existingFacts | yaml.stringify }}
33
+ \`\`\`
34
+
35
+ ## Recent Conversation
36
+
37
+ \`\`\`yaml alt="recent-messages"
38
+ {{ messages | yaml.stringify }}
39
+ \`\`\`
40
+
41
+ ## Guidelines
42
+
43
+ 1. **Avoid duplicating User Memory (CRITICAL)**:
44
+ - User Memory contains long-term, cross-session facts about the user
45
+ - DO NOT extract facts that are already covered in User Memory
46
+ - Focus on session-specific information that User Memory doesn't capture
47
+ - Example: If User Memory has "User prefers TypeScript", don't add "User is using TypeScript" to session memory
48
+
49
+ 2. **Output only changes (CRITICAL)**:
50
+ - Only output facts that need to be added or updated
51
+ - DO NOT output facts that already exist and don't need changes
52
+ - Each label in newFacts must be unique
53
+ - When a label already exists in session memory:
54
+ - Include it in newFacts ONLY if conversation provides new information to update it
55
+ - Omit it from newFacts if it doesn't need changes
56
+
57
+ 3. **What to extract** (Session context, NOT project documentation):
58
+ - **Current tasks and goals**: What the user is trying to accomplish in this session
59
+ - **Important decisions**: Key choices made and WHY (not just WHAT was chosen)
60
+ - **Session-specific constraints**: Temporary requirements or limitations for this work
61
+ - **Blockers and context**: Issues encountered and relevant background
62
+ - **Session-specific user preferences**: Only if different from User Memory for this session
63
+
64
+ 4. **What NOT to extract** (Can be inferred from code or documentation):
65
+ - ❌ Tech stack details (e.g., "Project uses React") - obvious from package.json
66
+ - ❌ Code structure facts (e.g., "Code is in /src") - can be seen directly
67
+ - ❌ Implementation details (e.g., "Function X does Y") - visible in code
68
+ - ❌ Architecture documentation - should be in actual docs, not memory
69
+ - ❌ Generic project facts that don't help with current work
70
+
71
+ 5. **When to output a fact in newFacts**:
72
+ - **New fact**: Learning something new about current work context not in existing session memory
73
+ - **Updated fact**: New information about current tasks or decisions
74
+ - **DO NOT output**: Facts already in session memory, facts covered by User Memory, or obvious code facts
75
+ - Example: Extract "User is fixing the memory duplication bug to optimize token usage" ✓
76
+ - Example: Don't extract "Project uses TypeScript" ❌ (obvious from code)
77
+
78
+ 6. **Remove outdated facts** by including their labels in removeFacts:
79
+ - Facts that are no longer relevant to current session
80
+ - Facts that have been superseded by new information
81
+
82
+ 7. **Label naming conventions**:
83
+ - Use short, descriptive, kebab-case labels
84
+ - Focus on: "task-*" (current tasks), "decision-*" (key decisions), "ctx-*" (context), "blocker-*" (blockers)
85
+ - Examples: "task-fix-memory-bug", "decision-use-incremental-updates", "ctx-working-on-compact-module", "blocker-type-error"
86
+
87
+ 8. **Fact content guidelines**:
88
+ - Write concise, actionable facts (1-2 sentences max)
89
+ - Focus on WHY and WHAT (goals, decisions, context), not HOW (implementation details)
90
+ - Information should help continue the work, not document the codebase
91
+
92
+ 9. **Extraction criteria**:
93
+ - Only extract if there's clear, explicit information in the conversation
94
+ - The information should be useful for continuing the current work
95
+ - Don't make assumptions or infer beyond what's stated
96
+ - When in doubt about whether something changed, don't output it
97
+
98
+ Output only the new or updated facts in newFacts, and any labels to remove in removeFacts.`;
99
+ var AISessionMemoryExtractor = class extends require_ai_agent.AIAgent {
100
+ constructor(options) {
101
+ super({
102
+ name: "SessionMemoryExtractor",
103
+ description: "Extracts and maintains session memory facts from conversations",
104
+ inputSchema: zod.z.object({
105
+ existingUserFacts: (0, zod.optional)(zod.z.array(zod.z.object({
106
+ label: zod.z.string(),
107
+ fact: zod.z.string(),
108
+ confidence: (0, zod.optional)(zod.z.number()),
109
+ tags: (0, zod.optional)(zod.z.array(zod.z.string()))
110
+ })).describe("User memory facts (long-term, cross-session) to avoid duplication")),
111
+ existingFacts: (0, zod.optional)(zod.z.array(zod.z.object({
112
+ label: zod.z.string(),
113
+ fact: zod.z.string(),
114
+ confidence: (0, zod.optional)(zod.z.number()),
115
+ tags: (0, zod.optional)(zod.z.array(zod.z.string()))
116
+ })).describe("Existing session memory facts for context and deduplication")),
117
+ messages: zod.z.array(zod.z.any()).describe("Recent conversation messages")
118
+ }),
119
+ outputSchema: zod.z.object({
120
+ newFacts: zod.z.array(zod.z.object({
121
+ label: zod.z.string().describe("Short, semantic label for the fact"),
122
+ fact: zod.z.string().describe("The fact content"),
123
+ confidence: (0, zod.optional)(zod.z.number().min(0).max(1).describe("Confidence score (0-1)")),
124
+ tags: (0, zod.optional)(zod.z.array(zod.z.string()).describe("Classification tags"))
125
+ })).describe("Facts to add or update in session memory. Only include facts that are new or need updates. Do not include unchanged facts."),
126
+ removeFacts: (0, zod.optional)(zod.z.array(zod.z.string()).describe("Labels of facts to remove from memory"))
127
+ }),
128
+ instructions: EXTRACTOR_INSTRUCTIONS,
129
+ taskRenderMode: "hide",
130
+ ...require_utils_type_utils.omitBy(options ?? {}, (v) => require_utils_type_utils.isNil(v)),
131
+ session: { mode: "disabled" }
132
+ });
133
+ }
134
+ };
135
+
136
+ //#endregion
137
+ exports.AISessionMemoryExtractor = AISessionMemoryExtractor;
@@ -0,0 +1,137 @@
1
+ import { isNil, omitBy } from "../../utils/type-utils.mjs";
2
+ import { AIAgent } from "../../agents/ai-agent.mjs";
3
+ import { optional, z as z$1 } from "zod";
4
+
5
+ //#region src/prompt/compact/session-memory-extractor.ts
6
+ const EXTRACTOR_INSTRUCTIONS = `\
7
+ You are a session memory fact extractor. Your task is to extract facts that help continue THIS SESSION's work.
8
+
9
+ **Key Principle**: Extract WORK CONTEXT (tasks, decisions, blockers), NOT PROJECT DOCUMENTATION (tech stack, code structure, implementation details).
10
+
11
+ Session memory is for remembering:
12
+ - What we're trying to accomplish
13
+ - Why we made certain choices
14
+ - What problems we encountered
15
+ - Important context for continuing the work
16
+
17
+ Session memory is NOT for documenting:
18
+ - What the code does (visible in code)
19
+ - How the project is structured (can explore directly)
20
+ - What technologies are used (obvious from files)
21
+
22
+ ## User Memory Facts (Long-term, cross-session)
23
+
24
+ \`\`\`yaml alt="user-memory-facts"
25
+ {{ existingUserFacts | yaml.stringify }}
26
+ \`\`\`
27
+
28
+ ## Existing Session Memory Facts
29
+
30
+ \`\`\`yaml alt="existing-facts"
31
+ {{ existingFacts | yaml.stringify }}
32
+ \`\`\`
33
+
34
+ ## Recent Conversation
35
+
36
+ \`\`\`yaml alt="recent-messages"
37
+ {{ messages | yaml.stringify }}
38
+ \`\`\`
39
+
40
+ ## Guidelines
41
+
42
+ 1. **Avoid duplicating User Memory (CRITICAL)**:
43
+ - User Memory contains long-term, cross-session facts about the user
44
+ - DO NOT extract facts that are already covered in User Memory
45
+ - Focus on session-specific information that User Memory doesn't capture
46
+ - Example: If User Memory has "User prefers TypeScript", don't add "User is using TypeScript" to session memory
47
+
48
+ 2. **Output only changes (CRITICAL)**:
49
+ - Only output facts that need to be added or updated
50
+ - DO NOT output facts that already exist and don't need changes
51
+ - Each label in newFacts must be unique
52
+ - When a label already exists in session memory:
53
+ - Include it in newFacts ONLY if conversation provides new information to update it
54
+ - Omit it from newFacts if it doesn't need changes
55
+
56
+ 3. **What to extract** (Session context, NOT project documentation):
57
+ - **Current tasks and goals**: What the user is trying to accomplish in this session
58
+ - **Important decisions**: Key choices made and WHY (not just WHAT was chosen)
59
+ - **Session-specific constraints**: Temporary requirements or limitations for this work
60
+ - **Blockers and context**: Issues encountered and relevant background
61
+ - **Session-specific user preferences**: Only if different from User Memory for this session
62
+
63
+ 4. **What NOT to extract** (Can be inferred from code or documentation):
64
+ - ❌ Tech stack details (e.g., "Project uses React") - obvious from package.json
65
+ - ❌ Code structure facts (e.g., "Code is in /src") - can be seen directly
66
+ - ❌ Implementation details (e.g., "Function X does Y") - visible in code
67
+ - ❌ Architecture documentation - should be in actual docs, not memory
68
+ - ❌ Generic project facts that don't help with current work
69
+
70
+ 5. **When to output a fact in newFacts**:
71
+ - **New fact**: Learning something new about current work context not in existing session memory
72
+ - **Updated fact**: New information about current tasks or decisions
73
+ - **DO NOT output**: Facts already in session memory, facts covered by User Memory, or obvious code facts
74
+ - Example: Extract "User is fixing the memory duplication bug to optimize token usage" ✓
75
+ - Example: Don't extract "Project uses TypeScript" ❌ (obvious from code)
76
+
77
+ 6. **Remove outdated facts** by including their labels in removeFacts:
78
+ - Facts that are no longer relevant to current session
79
+ - Facts that have been superseded by new information
80
+
81
+ 7. **Label naming conventions**:
82
+ - Use short, descriptive, kebab-case labels
83
+ - Focus on: "task-*" (current tasks), "decision-*" (key decisions), "ctx-*" (context), "blocker-*" (blockers)
84
+ - Examples: "task-fix-memory-bug", "decision-use-incremental-updates", "ctx-working-on-compact-module", "blocker-type-error"
85
+
86
+ 8. **Fact content guidelines**:
87
+ - Write concise, actionable facts (1-2 sentences max)
88
+ - Focus on WHY and WHAT (goals, decisions, context), not HOW (implementation details)
89
+ - Information should help continue the work, not document the codebase
90
+
91
+ 9. **Extraction criteria**:
92
+ - Only extract if there's clear, explicit information in the conversation
93
+ - The information should be useful for continuing the current work
94
+ - Don't make assumptions or infer beyond what's stated
95
+ - When in doubt about whether something changed, don't output it
96
+
97
+ Output only the new or updated facts in newFacts, and any labels to remove in removeFacts.`;
98
+ var AISessionMemoryExtractor = class extends AIAgent {
99
+ constructor(options) {
100
+ super({
101
+ name: "SessionMemoryExtractor",
102
+ description: "Extracts and maintains session memory facts from conversations",
103
+ inputSchema: z$1.object({
104
+ existingUserFacts: optional(z$1.array(z$1.object({
105
+ label: z$1.string(),
106
+ fact: z$1.string(),
107
+ confidence: optional(z$1.number()),
108
+ tags: optional(z$1.array(z$1.string()))
109
+ })).describe("User memory facts (long-term, cross-session) to avoid duplication")),
110
+ existingFacts: optional(z$1.array(z$1.object({
111
+ label: z$1.string(),
112
+ fact: z$1.string(),
113
+ confidence: optional(z$1.number()),
114
+ tags: optional(z$1.array(z$1.string()))
115
+ })).describe("Existing session memory facts for context and deduplication")),
116
+ messages: z$1.array(z$1.any()).describe("Recent conversation messages")
117
+ }),
118
+ outputSchema: z$1.object({
119
+ newFacts: z$1.array(z$1.object({
120
+ label: z$1.string().describe("Short, semantic label for the fact"),
121
+ fact: z$1.string().describe("The fact content"),
122
+ confidence: optional(z$1.number().min(0).max(1).describe("Confidence score (0-1)")),
123
+ tags: optional(z$1.array(z$1.string()).describe("Classification tags"))
124
+ })).describe("Facts to add or update in session memory. Only include facts that are new or need updates. Do not include unchanged facts."),
125
+ removeFacts: optional(z$1.array(z$1.string()).describe("Labels of facts to remove from memory"))
126
+ }),
127
+ instructions: EXTRACTOR_INSTRUCTIONS,
128
+ taskRenderMode: "hide",
129
+ ...omitBy(options ?? {}, (v) => isNil(v)),
130
+ session: { mode: "disabled" }
131
+ });
132
+ }
133
+ };
134
+
135
+ //#endregion
136
+ export { AISessionMemoryExtractor };
137
+ //# sourceMappingURL=session-memory-extractor.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-memory-extractor.mjs","names":["z"],"sources":["../../../src/prompt/compact/session-memory-extractor.ts"],"sourcesContent":["import { optional, z } from \"zod\";\nimport { AIAgent, type AIAgentOptions } from \"../../agents/ai-agent.js\";\nimport { isNil, omitBy } from \"../../utils/type-utils.js\";\nimport type { MemoryExtractorInput, MemoryExtractorOutput } from \"./types.js\";\n\nconst EXTRACTOR_INSTRUCTIONS = `\\\nYou are a session memory fact extractor. Your task is to extract facts that help continue THIS SESSION's work.\n\n**Key Principle**: Extract WORK CONTEXT (tasks, decisions, blockers), NOT PROJECT DOCUMENTATION (tech stack, code structure, implementation details).\n\nSession memory is for remembering:\n- What we're trying to accomplish\n- Why we made certain choices\n- What problems we encountered\n- Important context for continuing the work\n\nSession memory is NOT for documenting:\n- What the code does (visible in code)\n- How the project is structured (can explore directly)\n- What technologies are used (obvious from files)\n\n## User Memory Facts (Long-term, cross-session)\n\n${\"```\"}yaml alt=\"user-memory-facts\"\n{{ existingUserFacts | yaml.stringify }}\n${\"```\"}\n\n## Existing Session Memory Facts\n\n${\"```\"}yaml alt=\"existing-facts\"\n{{ existingFacts | yaml.stringify }}\n${\"```\"}\n\n## Recent Conversation\n\n${\"```\"}yaml alt=\"recent-messages\"\n{{ messages | yaml.stringify }}\n${\"```\"}\n\n## Guidelines\n\n1. **Avoid duplicating User Memory (CRITICAL)**:\n - User Memory contains long-term, cross-session facts about the user\n - DO NOT extract facts that are already covered in User Memory\n - Focus on session-specific information that User Memory doesn't capture\n - Example: If User Memory has \"User prefers TypeScript\", don't add \"User is using TypeScript\" to session memory\n\n2. **Output only changes (CRITICAL)**:\n - Only output facts that need to be added or updated\n - DO NOT output facts that already exist and don't need changes\n - Each label in newFacts must be unique\n - When a label already exists in session memory:\n - Include it in newFacts ONLY if conversation provides new information to update it\n - Omit it from newFacts if it doesn't need changes\n\n3. **What to extract** (Session context, NOT project documentation):\n - **Current tasks and goals**: What the user is trying to accomplish in this session\n - **Important decisions**: Key choices made and WHY (not just WHAT was chosen)\n - **Session-specific constraints**: Temporary requirements or limitations for this work\n - **Blockers and context**: Issues encountered and relevant background\n - **Session-specific user preferences**: Only if different from User Memory for this session\n\n4. **What NOT to extract** (Can be inferred from code or documentation):\n - ❌ Tech stack details (e.g., \"Project uses React\") - obvious from package.json\n - ❌ Code structure facts (e.g., \"Code is in /src\") - can be seen directly\n - ❌ Implementation details (e.g., \"Function X does Y\") - visible in code\n - ❌ Architecture documentation - should be in actual docs, not memory\n - ❌ Generic project facts that don't help with current work\n\n5. **When to output a fact in newFacts**:\n - **New fact**: Learning something new about current work context not in existing session memory\n - **Updated fact**: New information about current tasks or decisions\n - **DO NOT output**: Facts already in session memory, facts covered by User Memory, or obvious code facts\n - Example: Extract \"User is fixing the memory duplication bug to optimize token usage\" ✓\n - Example: Don't extract \"Project uses TypeScript\" ❌ (obvious from code)\n\n6. **Remove outdated facts** by including their labels in removeFacts:\n - Facts that are no longer relevant to current session\n - Facts that have been superseded by new information\n\n7. **Label naming conventions**:\n - Use short, descriptive, kebab-case labels\n - Focus on: \"task-*\" (current tasks), \"decision-*\" (key decisions), \"ctx-*\" (context), \"blocker-*\" (blockers)\n - Examples: \"task-fix-memory-bug\", \"decision-use-incremental-updates\", \"ctx-working-on-compact-module\", \"blocker-type-error\"\n\n8. **Fact content guidelines**:\n - Write concise, actionable facts (1-2 sentences max)\n - Focus on WHY and WHAT (goals, decisions, context), not HOW (implementation details)\n - Information should help continue the work, not document the codebase\n\n9. **Extraction criteria**:\n - Only extract if there's clear, explicit information in the conversation\n - The information should be useful for continuing the current work\n - Don't make assumptions or infer beyond what's stated\n - When in doubt about whether something changed, don't output it\n\nOutput only the new or updated facts in newFacts, and any labels to remove in removeFacts.`;\n\nexport interface CreateSessionMemoryExtractorOptions\n extends AIAgentOptions<MemoryExtractorInput, MemoryExtractorOutput> {}\n\nexport class AISessionMemoryExtractor extends AIAgent<MemoryExtractorInput, MemoryExtractorOutput> {\n constructor(options?: CreateSessionMemoryExtractorOptions) {\n super({\n name: \"SessionMemoryExtractor\",\n description: \"Extracts and maintains session memory facts from conversations\",\n inputSchema: z.object({\n existingUserFacts: optional(\n z\n .array(\n z.object({\n label: z.string(),\n fact: z.string(),\n confidence: optional(z.number()),\n tags: optional(z.array(z.string())),\n }),\n )\n .describe(\"User memory facts (long-term, cross-session) to avoid duplication\"),\n ),\n existingFacts: optional(\n z\n .array(\n z.object({\n label: z.string(),\n fact: z.string(),\n confidence: optional(z.number()),\n tags: optional(z.array(z.string())),\n }),\n )\n .describe(\"Existing session memory facts for context and deduplication\"),\n ),\n messages: z.array(z.any()).describe(\"Recent conversation messages\"),\n }),\n outputSchema: z.object({\n newFacts: z\n .array(\n z.object({\n label: z.string().describe(\"Short, semantic label for the fact\"),\n fact: z.string().describe(\"The fact content\"),\n confidence: optional(z.number().min(0).max(1).describe(\"Confidence score (0-1)\")),\n tags: optional(z.array(z.string()).describe(\"Classification tags\")),\n }),\n )\n .describe(\n \"Facts to add or update in session memory. Only include facts that are new or need updates. Do not include unchanged facts.\",\n ),\n removeFacts: optional(\n z.array(z.string()).describe(\"Labels of facts to remove from memory\"),\n ),\n }),\n instructions: EXTRACTOR_INSTRUCTIONS,\n taskRenderMode: \"hide\",\n ...omitBy(options ?? {}, (v) => isNil(v)),\n session: {\n mode: \"disabled\",\n },\n });\n }\n}\n"],"mappings":";;;;;AAKA,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgG/B,IAAa,2BAAb,cAA8C,QAAqD;CACjG,YAAY,SAA+C;AACzD,QAAM;GACJ,MAAM;GACN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SION_MODE = "auto";
7
+ /**
8
+ * Default compaction mode
9
+ */
10
+ const DEFAULT_COMPACT_MODE = "auto";
11
+ /**
12
+ * Default maximum tokens before triggering compaction
13
+ */
14
+ const DEFAULT_MAX_TOKENS = 8e4;
15
+ /**
16
+ * Default ratio of maxTokens to reserve for keeping recent messages
17
+ */
18
+ const DEFAULT_KEEP_RECENT_RATIO = .5;
19
+ /**
20
+ * Default async mode for compaction
21
+ */
22
+ const DEFAULT_COMPACT_ASYNC = true;
23
+ /**
24
+ * Default ratio of maxTokens to allocate for user memory
25
+ */
26
+ const DEFAULT_MEMORY_RATIO = .04;
27
+ /**
28
+ * Default query limit for loading memory facts
29
+ */
30
+ const DEFAULT_MEMORY_QUERY_LIMIT = 200;
31
+ /**
32
+ * Default session memory mode
33
+ */
34
+ const DEFAULT_SESSION_MEMORY_MODE = "auto";
35
+ /**
36
+ * Default async mode for session memory extraction
37
+ */
38
+ const DEFAULT_SESSION_MEMORY_ASYNC = true;
39
+ /**
40
+ * Default user memory mode
41
+ */
42
+ const DEFAULT_USER_MEMORY_MODE = "auto";
43
+ /**
44
+ * Default async mode for user memory consolidation
45
+ */
46
+ const DEFAULT_USER_MEMORY_ASYNC = true;
47
+
48
+ //#endregion
49
+ exports.DEFAULT_COMPACT_ASYNC = DEFAULT_COMPACT_ASYNC;
50
+ exports.DEFAULT_COMPACT_MODE = DEFAULT_COMPACT_MODE;
51
+ exports.DEFAULT_KEEP_RECENT_RATIO = DEFAULT_KEEP_RECENT_RATIO;
52
+ exports.DEFAULT_MAX_TOKENS = DEFAULT_MAX_TOKENS;
53
+ exports.DEFAULT_MEMORY_QUERY_LIMIT = DEFAULT_MEMORY_QUERY_LIMIT;
54
+ exports.DEFAULT_MEMORY_RATIO = DEFAULT_MEMORY_RATIO;
55
+ exports.DEFAULT_SESSION_MEMORY_ASYNC = DEFAULT_SESSION_MEMORY_ASYNC;
56
+ exports.DEFAULT_SESSION_MEMORY_MODE = DEFAULT_SESSION_MEMORY_MODE;
57
+ exports.DEFAULT_SESSION_MODE = DEFAULT_SESSION_MODE;
58
+ exports.DEFAULT_USER_MEMORY_ASYNC = DEFAULT_USER_MEMORY_ASYNC;
59
+ exports.DEFAULT_USER_MEMORY_MODE = DEFAULT_USER_MEMORY_MODE;