kagent-ts 0.1.4 → 0.1.5

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 (341) hide show
  1. package/LICENSE +68 -21
  2. package/README.md +27 -371
  3. package/dist/compression/progressive-compressor.d.ts +66 -0
  4. package/dist/compression/progressive-compressor.d.ts.map +1 -0
  5. package/dist/compression/progressive-compressor.js +367 -0
  6. package/dist/compression/progressive-compressor.js.map +1 -0
  7. package/dist/compression/types.d.ts +1 -5
  8. package/dist/compression/types.d.ts.map +1 -1
  9. package/dist/context/context-manager.d.ts +34 -15
  10. package/dist/context/context-manager.d.ts.map +1 -1
  11. package/dist/context/context-manager.js +78 -28
  12. package/dist/context/context-manager.js.map +1 -1
  13. package/dist/context/types.d.ts +20 -4
  14. package/dist/context/types.d.ts.map +1 -1
  15. package/dist/core/agent.d.ts +354 -25
  16. package/dist/core/agent.d.ts.map +1 -1
  17. package/dist/core/agent.js +646 -64
  18. package/dist/core/agent.js.map +1 -1
  19. package/dist/core/fusion-agent.d.ts +207 -0
  20. package/dist/core/fusion-agent.d.ts.map +1 -0
  21. package/dist/core/fusion-agent.js +769 -0
  22. package/dist/core/fusion-agent.js.map +1 -0
  23. package/dist/core/hooks.d.ts +19 -7
  24. package/dist/core/hooks.d.ts.map +1 -1
  25. package/dist/core/plan-solve-agent.d.ts +1 -15
  26. package/dist/core/plan-solve-agent.d.ts.map +1 -1
  27. package/dist/core/plan-solve-agent.js +142 -117
  28. package/dist/core/plan-solve-agent.js.map +1 -1
  29. package/dist/core/react-agent.d.ts +0 -13
  30. package/dist/core/react-agent.d.ts.map +1 -1
  31. package/dist/core/react-agent.js +127 -102
  32. package/dist/core/react-agent.js.map +1 -1
  33. package/dist/core/response-schema.d.ts +65 -0
  34. package/dist/core/response-schema.d.ts.map +1 -1
  35. package/dist/core/response-schema.js +174 -1
  36. package/dist/core/response-schema.js.map +1 -1
  37. package/dist/core/system-prompts.d.ts +27 -0
  38. package/dist/core/system-prompts.d.ts.map +1 -0
  39. package/dist/core/system-prompts.js +112 -0
  40. package/dist/core/system-prompts.js.map +1 -0
  41. package/dist/eval/benchmark.d.ts +81 -0
  42. package/dist/eval/benchmark.d.ts.map +1 -0
  43. package/dist/eval/benchmark.js +292 -0
  44. package/dist/eval/benchmark.js.map +1 -0
  45. package/dist/eval/eval-runner.d.ts +79 -0
  46. package/dist/eval/eval-runner.d.ts.map +1 -0
  47. package/dist/eval/eval-runner.js +252 -0
  48. package/dist/eval/eval-runner.js.map +1 -0
  49. package/dist/eval/index.d.ts +7 -0
  50. package/dist/eval/index.d.ts.map +1 -0
  51. package/dist/eval/index.js +13 -0
  52. package/dist/eval/index.js.map +1 -0
  53. package/dist/eval/tool-call-evaluator.d.ts +72 -0
  54. package/dist/eval/tool-call-evaluator.d.ts.map +1 -0
  55. package/dist/eval/tool-call-evaluator.js +265 -0
  56. package/dist/eval/tool-call-evaluator.js.map +1 -0
  57. package/dist/eval/types.d.ts +219 -0
  58. package/dist/eval/types.d.ts.map +1 -0
  59. package/dist/eval/types.js +3 -0
  60. package/dist/eval/types.js.map +1 -0
  61. package/dist/index.d.ts +58 -14
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +116 -8
  64. package/dist/index.js.map +1 -1
  65. package/dist/llm/anthropic-provider.d.ts +141 -0
  66. package/dist/llm/anthropic-provider.d.ts.map +1 -0
  67. package/dist/llm/anthropic-provider.js +486 -0
  68. package/dist/llm/anthropic-provider.js.map +1 -0
  69. package/dist/llm/errors.d.ts +26 -0
  70. package/dist/llm/errors.d.ts.map +1 -0
  71. package/dist/llm/errors.js +19 -0
  72. package/dist/llm/errors.js.map +1 -0
  73. package/dist/llm/factory.d.ts +73 -0
  74. package/dist/llm/factory.d.ts.map +1 -0
  75. package/dist/llm/factory.js +77 -0
  76. package/dist/llm/factory.js.map +1 -0
  77. package/dist/llm/fallback-provider.d.ts +47 -0
  78. package/dist/llm/fallback-provider.d.ts.map +1 -0
  79. package/dist/llm/fallback-provider.js +91 -0
  80. package/dist/llm/fallback-provider.js.map +1 -0
  81. package/dist/llm/interface.d.ts +54 -11
  82. package/dist/llm/interface.d.ts.map +1 -1
  83. package/dist/llm/interface.js +34 -0
  84. package/dist/llm/interface.js.map +1 -1
  85. package/dist/llm/model-router.d.ts +126 -0
  86. package/dist/llm/model-router.d.ts.map +1 -0
  87. package/dist/llm/model-router.js +178 -0
  88. package/dist/llm/model-router.js.map +1 -0
  89. package/dist/llm/openai-provider.d.ts +8 -32
  90. package/dist/llm/openai-provider.d.ts.map +1 -1
  91. package/dist/llm/openai-provider.js +27 -60
  92. package/dist/llm/openai-provider.js.map +1 -1
  93. package/dist/llm/rate-limiter.d.ts +41 -0
  94. package/dist/llm/rate-limiter.d.ts.map +1 -0
  95. package/dist/llm/rate-limiter.js +93 -0
  96. package/dist/llm/rate-limiter.js.map +1 -0
  97. package/dist/llm/retry.d.ts +26 -0
  98. package/dist/llm/retry.d.ts.map +1 -0
  99. package/dist/llm/retry.js +44 -0
  100. package/dist/llm/retry.js.map +1 -0
  101. package/dist/llm/token-budget.d.ts +97 -0
  102. package/dist/llm/token-budget.d.ts.map +1 -0
  103. package/dist/llm/token-budget.js +115 -0
  104. package/dist/llm/token-budget.js.map +1 -0
  105. package/dist/logging/index.d.ts +2 -0
  106. package/dist/logging/index.d.ts.map +1 -0
  107. package/dist/logging/index.js +7 -0
  108. package/dist/logging/index.js.map +1 -0
  109. package/dist/logging/logger.d.ts +38 -0
  110. package/dist/logging/logger.d.ts.map +1 -0
  111. package/dist/logging/logger.js +34 -0
  112. package/dist/logging/logger.js.map +1 -0
  113. package/dist/mcp/mcp-client-manager.d.ts +10 -2
  114. package/dist/mcp/mcp-client-manager.d.ts.map +1 -1
  115. package/dist/mcp/mcp-client-manager.js +20 -9
  116. package/dist/mcp/mcp-client-manager.js.map +1 -1
  117. package/dist/memory/index.d.ts +3 -0
  118. package/dist/memory/index.d.ts.map +1 -0
  119. package/dist/memory/index.js +6 -0
  120. package/dist/memory/index.js.map +1 -0
  121. package/dist/memory/memory-manager.d.ts +119 -0
  122. package/dist/memory/memory-manager.d.ts.map +1 -0
  123. package/dist/memory/memory-manager.js +334 -0
  124. package/dist/memory/memory-manager.js.map +1 -0
  125. package/dist/messages/types.d.ts +2 -0
  126. package/dist/messages/types.d.ts.map +1 -1
  127. package/dist/orchestrator/index.d.ts +5 -0
  128. package/dist/orchestrator/index.d.ts.map +1 -0
  129. package/dist/orchestrator/index.js +13 -0
  130. package/dist/orchestrator/index.js.map +1 -0
  131. package/dist/orchestrator/json-extractor.d.ts +18 -0
  132. package/dist/orchestrator/json-extractor.d.ts.map +1 -0
  133. package/dist/orchestrator/json-extractor.js +111 -0
  134. package/dist/orchestrator/json-extractor.js.map +1 -0
  135. package/dist/orchestrator/orchestrator-agent.d.ts +152 -0
  136. package/dist/orchestrator/orchestrator-agent.d.ts.map +1 -0
  137. package/dist/orchestrator/orchestrator-agent.js +675 -0
  138. package/dist/orchestrator/orchestrator-agent.js.map +1 -0
  139. package/dist/orchestrator/orchestrator-response.d.ts +40 -0
  140. package/dist/orchestrator/orchestrator-response.d.ts.map +1 -0
  141. package/dist/orchestrator/orchestrator-response.js +275 -0
  142. package/dist/orchestrator/orchestrator-response.js.map +1 -0
  143. package/dist/orchestrator/orchestrator-types.d.ts +116 -0
  144. package/dist/orchestrator/orchestrator-types.d.ts.map +1 -0
  145. package/dist/orchestrator/orchestrator-types.js +3 -0
  146. package/dist/orchestrator/orchestrator-types.js.map +1 -0
  147. package/dist/preferences/preference-manager.d.ts +8 -3
  148. package/dist/preferences/preference-manager.d.ts.map +1 -1
  149. package/dist/preferences/preference-manager.js +17 -4
  150. package/dist/preferences/preference-manager.js.map +1 -1
  151. package/dist/rag/chroma-store.d.ts +52 -0
  152. package/dist/rag/chroma-store.d.ts.map +1 -0
  153. package/dist/rag/chroma-store.js +110 -0
  154. package/dist/rag/chroma-store.js.map +1 -0
  155. package/dist/rag/document-loader.d.ts +21 -0
  156. package/dist/rag/document-loader.d.ts.map +1 -0
  157. package/dist/rag/document-loader.js +129 -0
  158. package/dist/rag/document-loader.js.map +1 -0
  159. package/dist/rag/embedding-provider.d.ts +36 -0
  160. package/dist/rag/embedding-provider.d.ts.map +1 -0
  161. package/dist/rag/embedding-provider.js +74 -0
  162. package/dist/rag/embedding-provider.js.map +1 -0
  163. package/dist/rag/index.d.ts +17 -0
  164. package/dist/rag/index.d.ts.map +1 -0
  165. package/dist/rag/index.js +27 -0
  166. package/dist/rag/index.js.map +1 -0
  167. package/dist/rag/keyword-index.d.ts +53 -0
  168. package/dist/rag/keyword-index.d.ts.map +1 -0
  169. package/dist/rag/keyword-index.js +161 -0
  170. package/dist/rag/keyword-index.js.map +1 -0
  171. package/dist/rag/llm-reranker.d.ts +36 -0
  172. package/dist/rag/llm-reranker.d.ts.map +1 -0
  173. package/dist/rag/llm-reranker.js +95 -0
  174. package/dist/rag/llm-reranker.js.map +1 -0
  175. package/dist/rag/rag-manager.d.ts +54 -0
  176. package/dist/rag/rag-manager.d.ts.map +1 -0
  177. package/dist/rag/rag-manager.js +179 -0
  178. package/dist/rag/rag-manager.js.map +1 -0
  179. package/dist/rag/rag-types.d.ts +143 -0
  180. package/dist/rag/rag-types.d.ts.map +1 -0
  181. package/dist/rag/rag-types.js +9 -0
  182. package/dist/rag/rag-types.js.map +1 -0
  183. package/dist/rag/rrf.d.ts +47 -0
  184. package/dist/rag/rrf.d.ts.map +1 -0
  185. package/dist/rag/rrf.js +70 -0
  186. package/dist/rag/rrf.js.map +1 -0
  187. package/dist/rag/search-knowledge.d.ts +24 -0
  188. package/dist/rag/search-knowledge.d.ts.map +1 -0
  189. package/dist/rag/search-knowledge.js +86 -0
  190. package/dist/rag/search-knowledge.js.map +1 -0
  191. package/dist/rag/text-splitter.d.ts +25 -0
  192. package/dist/rag/text-splitter.d.ts.map +1 -0
  193. package/dist/rag/text-splitter.js +136 -0
  194. package/dist/rag/text-splitter.js.map +1 -0
  195. package/dist/rag/vector-store.d.ts +34 -0
  196. package/dist/rag/vector-store.d.ts.map +1 -0
  197. package/dist/rag/vector-store.js +73 -0
  198. package/dist/rag/vector-store.js.map +1 -0
  199. package/dist/reflection/error-notebook.d.ts +125 -0
  200. package/dist/reflection/error-notebook.d.ts.map +1 -0
  201. package/dist/reflection/error-notebook.js +368 -0
  202. package/dist/reflection/error-notebook.js.map +1 -0
  203. package/dist/reflection/index.d.ts +8 -0
  204. package/dist/reflection/index.d.ts.map +1 -0
  205. package/dist/reflection/index.js +12 -0
  206. package/dist/reflection/index.js.map +1 -0
  207. package/dist/reflection/memory-reflector.d.ts +97 -0
  208. package/dist/reflection/memory-reflector.d.ts.map +1 -0
  209. package/dist/reflection/memory-reflector.js +215 -0
  210. package/dist/reflection/memory-reflector.js.map +1 -0
  211. package/dist/reflection/reflection-agent.d.ts +105 -0
  212. package/dist/reflection/reflection-agent.d.ts.map +1 -0
  213. package/dist/reflection/reflection-agent.js +234 -0
  214. package/dist/reflection/reflection-agent.js.map +1 -0
  215. package/dist/reflection/reflection-hook.d.ts +50 -0
  216. package/dist/reflection/reflection-hook.d.ts.map +1 -0
  217. package/dist/reflection/reflection-hook.js +108 -0
  218. package/dist/reflection/reflection-hook.js.map +1 -0
  219. package/dist/rules/project-rules.d.ts +47 -0
  220. package/dist/rules/project-rules.d.ts.map +1 -0
  221. package/dist/rules/project-rules.js +166 -0
  222. package/dist/rules/project-rules.js.map +1 -0
  223. package/dist/security/boundaries.d.ts +81 -0
  224. package/dist/security/boundaries.d.ts.map +1 -0
  225. package/dist/security/boundaries.js +158 -0
  226. package/dist/security/boundaries.js.map +1 -0
  227. package/dist/security/index.d.ts +2 -0
  228. package/dist/security/index.d.ts.map +1 -0
  229. package/dist/security/index.js +11 -0
  230. package/dist/security/index.js.map +1 -0
  231. package/dist/session/session-types.d.ts +25 -4
  232. package/dist/session/session-types.d.ts.map +1 -1
  233. package/dist/skills/file-skill-loader.d.ts +4 -6
  234. package/dist/skills/file-skill-loader.d.ts.map +1 -1
  235. package/dist/skills/file-skill-loader.js +8 -19
  236. package/dist/skills/file-skill-loader.js.map +1 -1
  237. package/dist/skills/index.d.ts +1 -1
  238. package/dist/skills/index.d.ts.map +1 -1
  239. package/dist/skills/index.js +1 -2
  240. package/dist/skills/index.js.map +1 -1
  241. package/dist/skills/skill-manager.d.ts +18 -8
  242. package/dist/skills/skill-manager.d.ts.map +1 -1
  243. package/dist/skills/skill-manager.js +58 -36
  244. package/dist/skills/skill-manager.js.map +1 -1
  245. package/dist/skills/types.d.ts +3 -8
  246. package/dist/skills/types.d.ts.map +1 -1
  247. package/dist/subagent/index.d.ts +4 -0
  248. package/dist/subagent/index.d.ts.map +1 -0
  249. package/dist/subagent/index.js +8 -0
  250. package/dist/subagent/index.js.map +1 -0
  251. package/dist/subagent/subagent-loader.d.ts +53 -0
  252. package/dist/subagent/subagent-loader.d.ts.map +1 -0
  253. package/dist/subagent/subagent-loader.js +155 -0
  254. package/dist/subagent/subagent-loader.js.map +1 -0
  255. package/dist/subagent/subagent-manager.d.ts +161 -0
  256. package/dist/subagent/subagent-manager.d.ts.map +1 -0
  257. package/dist/subagent/subagent-manager.js +468 -0
  258. package/dist/subagent/subagent-manager.js.map +1 -0
  259. package/dist/subagent/subagent-types.d.ts +77 -0
  260. package/dist/subagent/subagent-types.d.ts.map +1 -0
  261. package/dist/subagent/subagent-types.js +3 -0
  262. package/dist/subagent/subagent-types.js.map +1 -0
  263. package/dist/tools/builtin/bash.d.ts +3 -0
  264. package/dist/tools/builtin/bash.d.ts.map +1 -0
  265. package/dist/tools/builtin/bash.js +87 -0
  266. package/dist/tools/builtin/bash.js.map +1 -0
  267. package/dist/tools/builtin/edit-file.d.ts.map +1 -1
  268. package/dist/tools/builtin/edit-file.js +1 -0
  269. package/dist/tools/builtin/edit-file.js.map +1 -1
  270. package/dist/tools/builtin/index.d.ts +14 -0
  271. package/dist/tools/builtin/index.d.ts.map +1 -1
  272. package/dist/tools/builtin/index.js +45 -1
  273. package/dist/tools/builtin/index.js.map +1 -1
  274. package/dist/tools/builtin/list-errors.d.ts +7 -0
  275. package/dist/tools/builtin/list-errors.d.ts.map +1 -0
  276. package/dist/tools/builtin/list-errors.js +64 -0
  277. package/dist/tools/builtin/list-errors.js.map +1 -0
  278. package/dist/tools/builtin/list-subagents.d.ts +7 -0
  279. package/dist/tools/builtin/list-subagents.d.ts.map +1 -0
  280. package/dist/tools/builtin/list-subagents.js +21 -0
  281. package/dist/tools/builtin/list-subagents.js.map +1 -0
  282. package/dist/tools/builtin/recall.d.ts +11 -0
  283. package/dist/tools/builtin/recall.d.ts.map +1 -0
  284. package/dist/tools/builtin/recall.js +60 -0
  285. package/dist/tools/builtin/recall.js.map +1 -0
  286. package/dist/tools/builtin/remember.d.ts +12 -0
  287. package/dist/tools/builtin/remember.d.ts.map +1 -0
  288. package/dist/tools/builtin/remember.js +72 -0
  289. package/dist/tools/builtin/remember.js.map +1 -0
  290. package/dist/tools/builtin/skill.d.ts +14 -0
  291. package/dist/tools/builtin/skill.d.ts.map +1 -0
  292. package/dist/tools/builtin/skill.js +71 -0
  293. package/dist/tools/builtin/skill.js.map +1 -0
  294. package/dist/tools/builtin/spawn-subagent.d.ts +7 -0
  295. package/dist/tools/builtin/spawn-subagent.d.ts.map +1 -0
  296. package/dist/tools/builtin/spawn-subagent.js +43 -0
  297. package/dist/tools/builtin/spawn-subagent.js.map +1 -0
  298. package/dist/tools/builtin/web-fetch.d.ts +3 -0
  299. package/dist/tools/builtin/web-fetch.d.ts.map +1 -0
  300. package/dist/tools/builtin/web-fetch.js +101 -0
  301. package/dist/tools/builtin/web-fetch.js.map +1 -0
  302. package/dist/tools/builtin/write-file.d.ts.map +1 -1
  303. package/dist/tools/builtin/write-file.js +1 -0
  304. package/dist/tools/builtin/write-file.js.map +1 -1
  305. package/dist/tools/circuit-breaker.d.ts +19 -10
  306. package/dist/tools/circuit-breaker.d.ts.map +1 -1
  307. package/dist/tools/circuit-breaker.js +22 -11
  308. package/dist/tools/circuit-breaker.js.map +1 -1
  309. package/dist/tools/error-tracker.d.ts +28 -44
  310. package/dist/tools/error-tracker.d.ts.map +1 -1
  311. package/dist/tools/error-tracker.js +39 -156
  312. package/dist/tools/error-tracker.js.map +1 -1
  313. package/dist/tools/tool-filter.d.ts +70 -0
  314. package/dist/tools/tool-filter.d.ts.map +1 -0
  315. package/dist/tools/tool-filter.js +92 -0
  316. package/dist/tools/tool-filter.js.map +1 -0
  317. package/dist/tools/tool-output-truncator.d.ts +36 -0
  318. package/dist/tools/tool-output-truncator.d.ts.map +1 -0
  319. package/dist/tools/tool-output-truncator.js +117 -0
  320. package/dist/tools/tool-output-truncator.js.map +1 -0
  321. package/dist/tools/tool-registry.d.ts +25 -9
  322. package/dist/tools/tool-registry.d.ts.map +1 -1
  323. package/dist/tools/tool-registry.js +77 -28
  324. package/dist/tools/tool-registry.js.map +1 -1
  325. package/dist/tools/tool-validator.d.ts +13 -0
  326. package/dist/tools/tool-validator.d.ts.map +1 -0
  327. package/dist/tools/tool-validator.js +116 -0
  328. package/dist/tools/tool-validator.js.map +1 -0
  329. package/dist/tools/types.d.ts +86 -3
  330. package/dist/tools/types.d.ts.map +1 -1
  331. package/dist/tools/types.js +51 -2
  332. package/dist/tools/types.js.map +1 -1
  333. package/dist/trace/trace-logger.d.ts +30 -4
  334. package/dist/trace/trace-logger.d.ts.map +1 -1
  335. package/dist/trace/trace-logger.js +82 -6
  336. package/dist/trace/trace-logger.js.map +1 -1
  337. package/package.json +13 -4
  338. package/dist/compression/sliding-window.d.ts +0 -21
  339. package/dist/compression/sliding-window.d.ts.map +0 -1
  340. package/dist/compression/sliding-window.js +0 -44
  341. package/dist/compression/sliding-window.js.map +0 -1
@@ -0,0 +1,97 @@
1
+ import { LLMProvider } from "../llm/interface";
2
+ import { MessageData } from "../messages/types";
3
+ import { MemoryManager, Memory, MemoryType } from "../memory/memory-manager";
4
+ /**
5
+ * Input provided to the MemoryReflector for analysis.
6
+ */
7
+ export interface MemoryReflectionInput {
8
+ /** The original user query. */
9
+ userQuery: string;
10
+ /** The final answer produced by the agent. */
11
+ finalAnswer: string;
12
+ /** The full conversation messages (for context). */
13
+ conversation: MessageData[];
14
+ /** Session identifier. */
15
+ sessionId: string;
16
+ }
17
+ /**
18
+ * A single memory extracted from the session.
19
+ */
20
+ export interface ExtractedMemory {
21
+ /** Slug (kebab-case, used as filename). */
22
+ name: string;
23
+ /** One-line summary shown in the index. */
24
+ description: string;
25
+ /** Memory type. */
26
+ type: MemoryType;
27
+ /** Markdown body with why + how to apply. */
28
+ content: string;
29
+ }
30
+ /**
31
+ * Configuration for the MemoryReflector.
32
+ */
33
+ export interface MemoryReflectorConfig {
34
+ /** LLM provider (shared with the main agent). */
35
+ llm: LLMProvider;
36
+ /** MemoryManager for checking existing memories and persisting new ones. */
37
+ memoryManager: MemoryManager;
38
+ /**
39
+ * Maximum ReAct iterations for the sub-agent (default: 5).
40
+ * Memory extraction requires more context reading than error reflection.
41
+ */
42
+ maxIterations?: number;
43
+ }
44
+ /**
45
+ * MemoryReflector — post-execution memory extraction via a forked sub-agent.
46
+ *
47
+ * After the main agent finishes, the MemoryReflector forks a lightweight
48
+ * ReActAgent to review the session and extract lasting memories: user
49
+ * preferences, project decisions, constraints, and workflow patterns.
50
+ *
51
+ * The fork runs in its own context with read-only tools (read_file, grep_search)
52
+ * so it can verify context against the codebase before recording a memory.
53
+ *
54
+ * Usage:
55
+ * ```ts
56
+ * const memManager = new MemoryManager({ storageDir: ".memory" });
57
+ * const reflector = new MemoryReflector({ llm, memoryManager: memManager });
58
+ * const memories = await reflector.reflect({
59
+ * userQuery: input,
60
+ * finalAnswer: answer,
61
+ * conversation: contextMessages,
62
+ * sessionId: "sess_123",
63
+ * });
64
+ * ```
65
+ */
66
+ export declare class MemoryReflector {
67
+ private llm;
68
+ private memoryManager;
69
+ private maxIterations;
70
+ constructor(config: MemoryReflectorConfig);
71
+ /**
72
+ * Fork a sub-agent to extract memories from the session.
73
+ *
74
+ * @returns The list of new memories written to the MemoryManager.
75
+ */
76
+ reflect(input: MemoryReflectionInput): Promise<Memory[]>;
77
+ /**
78
+ * Fork a minimal ReActAgent and run it to completion.
79
+ * Returns the agent's final answer string.
80
+ */
81
+ private forkAndRun;
82
+ /**
83
+ * Build the task prompt for the sub-agent from the reflection input.
84
+ */
85
+ private buildTaskPrompt;
86
+ /**
87
+ * Format the conversation for the memory extraction prompt.
88
+ * Truncates very long tool results for readability.
89
+ */
90
+ private formatConversation;
91
+ /**
92
+ * Parse the sub-agent's final answer into a list of ExtractedMemories.
93
+ * Returns an empty array if parsing fails (best-effort).
94
+ */
95
+ private parseMemories;
96
+ }
97
+ //# sourceMappingURL=memory-reflector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-reflector.d.ts","sourceRoot":"","sources":["../../src/reflection/memory-reflector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAQ,MAAM,mBAAmB,CAAC;AAMtD,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAI7E;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,+BAA+B;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,oDAAoD;IACpD,YAAY,EAAE,WAAW,EAAE,CAAC;IAC5B,0BAA0B;IAC1B,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,2CAA2C;IAC3C,IAAI,EAAE,MAAM,CAAC;IACb,2CAA2C;IAC3C,WAAW,EAAE,MAAM,CAAC;IACpB,mBAAmB;IACnB,IAAI,EAAE,UAAU,CAAC;IACjB,6CAA6C;IAC7C,OAAO,EAAE,MAAM,CAAC;CACjB;AAyDD;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,iDAAiD;IACjD,GAAG,EAAE,WAAW,CAAC;IACjB,4EAA4E;IAC5E,aAAa,EAAE,aAAa,CAAC;IAC7B;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,GAAG,CAAc;IACzB,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,aAAa,CAAS;gBAElB,MAAM,EAAE,qBAAqB;IAQzC;;;;OAIG;IACG,OAAO,CAAC,KAAK,EAAE,qBAAqB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAgC9D;;;OAGG;YACW,UAAU;IAiBxB;;OAEG;IACH,OAAO,CAAC,eAAe;IAmCvB;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAwB1B;;;OAGG;IACH,OAAO,CAAC,aAAa;CAqCtB"}
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MemoryReflector = void 0;
4
+ const types_1 = require("../messages/types");
5
+ const react_agent_1 = require("../core/react-agent");
6
+ const tool_registry_1 = require("../tools/tool-registry");
7
+ const read_file_1 = require("../tools/builtin/read-file");
8
+ const grep_search_1 = require("../tools/builtin/grep-search");
9
+ const response_schema_1 = require("../core/response-schema");
10
+ // ─── System Prompt ───────────────────────────────────────────────────────────
11
+ const MEMORY_EXTRACTION_SYSTEM_PROMPT = `You are a memory extraction agent. Your job is to review a completed agent session
12
+ and identify facts, preferences, constraints, and decisions worth remembering for future sessions.
13
+
14
+ You have access to read_file and grep_search tools to verify context against the codebase.
15
+
16
+ Categories of memory to extract:
17
+ - **rule**: A constraint the user set — why they required it, and when it takes effect.
18
+ Example: "Always use kebab-case for file names."
19
+ - **project**: A fact or decision about the project — what happened, why (constraint / deadline
20
+ that drove it), and how the agent should apply it.
21
+ Example: "We switched from MySQL to PostgreSQL because of JSONB support."
22
+
23
+ What to look for:
24
+ - User preferences (language, coding style, naming conventions, tool preferences)
25
+ - Project decisions (architecture choices, tool/library selections, migration decisions)
26
+ - Constraints (deadlines, limitations, requirements, "must not" rules)
27
+ - Patterns worth repeating or avoiding (successful or failed approaches)
28
+ - Workflow preferences (how the user likes to work, communication style)
29
+
30
+ An existing memories list is provided below — do NOT duplicate any existing memory name.
31
+ Only output genuinely new, useful memories. An empty list is fine if nothing new is found.
32
+
33
+ In your final answer, output a JSON object with this structure:
34
+ {
35
+ "memories": [
36
+ {
37
+ "name": "kebab-case-slug",
38
+ "description": "one-line summary",
39
+ "type": "rule | project",
40
+ "content": "The fact.\\n\\n**Why:** ...\\n\\n**How to apply:** ..."
41
+ }
42
+ ]
43
+ }
44
+
45
+ Rules:
46
+ - "name" must be a kebab-case slug (lowercase letters, digits, dashes).
47
+ - "description" must be a concise one-line summary (~5-15 words).
48
+ - "type" must be either "rule" or "project".
49
+ - "content" should include **Why:** and **How to apply:** sections for project memories,
50
+ or **Why:** and **When:** sections for rule memories.
51
+ - Only output memories that provide lasting value across sessions.
52
+ - Be specific and actionable — avoid vague statements.
53
+ - Do NOT duplicate existing memory names.${response_schema_1.STRUCTURED_OUTPUT_INSTRUCTIONS}`;
54
+ /**
55
+ * MemoryReflector — post-execution memory extraction via a forked sub-agent.
56
+ *
57
+ * After the main agent finishes, the MemoryReflector forks a lightweight
58
+ * ReActAgent to review the session and extract lasting memories: user
59
+ * preferences, project decisions, constraints, and workflow patterns.
60
+ *
61
+ * The fork runs in its own context with read-only tools (read_file, grep_search)
62
+ * so it can verify context against the codebase before recording a memory.
63
+ *
64
+ * Usage:
65
+ * ```ts
66
+ * const memManager = new MemoryManager({ storageDir: ".memory" });
67
+ * const reflector = new MemoryReflector({ llm, memoryManager: memManager });
68
+ * const memories = await reflector.reflect({
69
+ * userQuery: input,
70
+ * finalAnswer: answer,
71
+ * conversation: contextMessages,
72
+ * sessionId: "sess_123",
73
+ * });
74
+ * ```
75
+ */
76
+ class MemoryReflector {
77
+ llm;
78
+ memoryManager;
79
+ maxIterations;
80
+ constructor(config) {
81
+ this.llm = config.llm;
82
+ this.memoryManager = config.memoryManager;
83
+ this.maxIterations = config.maxIterations ?? 5;
84
+ }
85
+ // ─── Public API ────────────────────────────────────────────────────────
86
+ /**
87
+ * Fork a sub-agent to extract memories from the session.
88
+ *
89
+ * @returns The list of new memories written to the MemoryManager.
90
+ */
91
+ async reflect(input) {
92
+ const existingNames = this.memoryManager.getAll().map((m) => ({
93
+ name: m.name,
94
+ description: m.description,
95
+ }));
96
+ const taskPrompt = this.buildTaskPrompt(input, existingNames);
97
+ const answer = await this.forkAndRun(taskPrompt);
98
+ const extracted = this.parseMemories(answer);
99
+ // Persist to MemoryManager (add() handles upsert by name)
100
+ const saved = [];
101
+ for (const m of extracted) {
102
+ const memory = {
103
+ name: m.name,
104
+ description: m.description,
105
+ type: m.type,
106
+ content: m.content,
107
+ };
108
+ // Skip if name already exists (defensive — sub-agent should avoid this)
109
+ if (this.memoryManager.has(m.name))
110
+ continue;
111
+ this.memoryManager.add(memory);
112
+ saved.push(memory);
113
+ }
114
+ return saved;
115
+ }
116
+ // ─── Private: Fork ─────────────────────────────────────────────────────
117
+ /**
118
+ * Fork a minimal ReActAgent and run it to completion.
119
+ * Returns the agent's final answer string.
120
+ */
121
+ async forkAndRun(userPrompt) {
122
+ const tools = new tool_registry_1.ToolRegistry();
123
+ tools.register(read_file_1.ReadFileTool);
124
+ tools.register(grep_search_1.GrepSearchTool);
125
+ const agent = new react_agent_1.ReActAgent({
126
+ llm: this.llm,
127
+ systemPrompt: MEMORY_EXTRACTION_SYSTEM_PROMPT,
128
+ toolRegistry: tools,
129
+ maxIterations: this.maxIterations,
130
+ });
131
+ return agent.run(userPrompt);
132
+ }
133
+ // ─── Private: Prompt Building ──────────────────────────────────────────
134
+ /**
135
+ * Build the task prompt for the sub-agent from the reflection input.
136
+ */
137
+ buildTaskPrompt(input, existing) {
138
+ let context = [
139
+ "Review this agent session and extract any memories worth keeping for future sessions.",
140
+ "",
141
+ "=== Existing Memories (do NOT duplicate these names) ===",
142
+ ];
143
+ if (existing.length === 0) {
144
+ context.push("(no existing memories)");
145
+ }
146
+ else {
147
+ for (const m of existing) {
148
+ context.push(`- ${m.name}: ${m.description}`);
149
+ }
150
+ }
151
+ context.push("", "=== User Query ===", input.userQuery, "", "=== Final Answer ===", input.finalAnswer, "", "=== Conversation ===", ...this.formatConversation(input.conversation), "", "Analyze the session and output extracted memories as JSON in your final answer.");
152
+ return context.join("\n");
153
+ }
154
+ /**
155
+ * Format the conversation for the memory extraction prompt.
156
+ * Truncates very long tool results for readability.
157
+ */
158
+ formatConversation(messages) {
159
+ const lines = [];
160
+ for (const msg of messages) {
161
+ const role = msg.role.toUpperCase();
162
+ let content = msg.content;
163
+ // Truncate long tool results
164
+ if (msg.role === types_1.Role.Tool && content.length > 1000) {
165
+ content = content.slice(0, 500) + "\n... (truncated, " + content.length + " chars total)";
166
+ }
167
+ lines.push(`[${role}] ${content}`);
168
+ if (msg.tool_calls && msg.tool_calls.length > 0) {
169
+ for (const tc of msg.tool_calls) {
170
+ lines.push(` → tool_call: ${tc.function.name}(${tc.function.arguments})`);
171
+ }
172
+ }
173
+ }
174
+ return lines;
175
+ }
176
+ // ─── Private: Parsing ──────────────────────────────────────────────────
177
+ /**
178
+ * Parse the sub-agent's final answer into a list of ExtractedMemories.
179
+ * Returns an empty array if parsing fails (best-effort).
180
+ */
181
+ parseMemories(answer) {
182
+ try {
183
+ // Extract JSON from the answer (may be wrapped in ```json fences)
184
+ let raw = answer.trim();
185
+ const fenceMatch = raw.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
186
+ if (fenceMatch)
187
+ raw = fenceMatch[1];
188
+ const parsed = JSON.parse(raw);
189
+ if (!Array.isArray(parsed.memories))
190
+ return [];
191
+ const validTypes = new Set(["rule", "project"]);
192
+ const memories = [];
193
+ for (const m of parsed.memories) {
194
+ if (typeof m.name !== "string" || !m.name ||
195
+ typeof m.description !== "string" || !m.description ||
196
+ typeof m.type !== "string" || !validTypes.has(m.type) ||
197
+ typeof m.content !== "string" || !m.content) {
198
+ continue;
199
+ }
200
+ memories.push({
201
+ name: m.name,
202
+ description: m.description,
203
+ type: m.type,
204
+ content: m.content,
205
+ });
206
+ }
207
+ return memories;
208
+ }
209
+ catch {
210
+ return [];
211
+ }
212
+ }
213
+ }
214
+ exports.MemoryReflector = MemoryReflector;
215
+ //# sourceMappingURL=memory-reflector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-reflector.js","sourceRoot":"","sources":["../../src/reflection/memory-reflector.ts"],"names":[],"mappings":";;;AACA,6CAAsD;AACtD,qDAAiD;AACjD,0DAAsD;AACtD,0DAA0D;AAC1D,8DAA8D;AAC9D,6DAAyE;AAwCzE,gFAAgF;AAEhF,MAAM,+BAA+B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA0CG,gDAA8B,EAAE,CAAC;AAmB5E;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAa,eAAe;IAClB,GAAG,CAAc;IACjB,aAAa,CAAgB;IAC7B,aAAa,CAAS;IAE9B,YAAY,MAA6B;QACvC,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC;QACtB,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC,aAAa,CAAC;QAC1C,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC,aAAa,IAAI,CAAC,CAAC;IACjD,CAAC;IAED,0EAA0E;IAE1E;;;;OAIG;IACH,KAAK,CAAC,OAAO,CAAC,KAA4B;QACxC,MAAM,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YAC5D,IAAI,EAAE,CAAC,CAAC,IAAI;YACZ,WAAW,EAAE,CAAC,CAAC,WAAW;SAC3B,CAAC,CAAC,CAAC;QAEJ,MAAM,UAAU,GAAG,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,a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G,CAAC,CAAC,CAAC,IAAI,CAAC;oBACrD,OAAO,CAAC,CAAC,OAAO,KAAK,QAAQ,IAAI,CAAC,CAAC,CAAC,OAAO,EAC3C,CAAC;oBACD,SAAS;gBACX,CAAC;gBAED,QAAQ,CAAC,IAAI,CAAC;oBACZ,IAAI,EAAE,CAAC,CAAC,IAAI;oBACZ,WAAW,EAAE,CAAC,CAAC,WAAW;oBAC1B,IAAI,EAAE,CAAC,CAAC,IAAkB;oBAC1B,OAAO,EAAE,CAAC,CAAC,OAAO;iBACnB,CAAC,CAAC;YACL,CAAC;YAED,OAAO,QAAQ,CAAC;QAClB,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,EAAE,CAAC;QACZ,CAAC;IACH,CAAC;CACF;AAlLD,0CAkLC"}
@@ -0,0 +1,105 @@
1
+ import { LLMProvider } from "../llm/interface";
2
+ import { MessageData } from "../messages/types";
3
+ import { ErrorNotebook, ErrorNotebookEntry, ReflectionErrorCategory } from "./error-notebook";
4
+ import type { ToolErrorTrace } from "../tools/types";
5
+ /**
6
+ * Input provided to the ReflectionAgent for analysis.
7
+ */
8
+ export interface ReflectionInput {
9
+ /** The original user query. */
10
+ userQuery: string;
11
+ /** The final answer produced by the agent. */
12
+ finalAnswer: string;
13
+ /** The full conversation messages (for context). */
14
+ conversation: MessageData[];
15
+ /** Tool error traces from the session (if any). */
16
+ errorTraces?: ToolErrorTrace[];
17
+ /** Session identifier for notebook entries. */
18
+ sessionId: string;
19
+ }
20
+ /**
21
+ * A single finding produced by the ReflectionAgent.
22
+ */
23
+ export interface ReflectionFinding {
24
+ /** Error category. */
25
+ category: ReflectionErrorCategory;
26
+ /** What went wrong. */
27
+ description: string;
28
+ /** Root cause. */
29
+ cause: string;
30
+ /** How to avoid it next time. */
31
+ suggestion: string;
32
+ /** Related tool trace IDs (if applicable). */
33
+ relatedTraceIds?: string[];
34
+ }
35
+ /**
36
+ * Configuration for the ReflectionAgent.
37
+ */
38
+ export interface ReflectionAgentConfig {
39
+ /** LLM provider (shared with the main agent). */
40
+ llm: LLMProvider;
41
+ /** ErrorNotebook for persisting findings. */
42
+ notebook: ErrorNotebook;
43
+ /**
44
+ * Maximum ReAct iterations for the sub-agent (default: 4).
45
+ */
46
+ maxIterations?: number;
47
+ }
48
+ /**
49
+ * ReflectionAgent — post-execution self-reflection via a forked sub-agent.
50
+ *
51
+ * After the main agent finishes, the ReflectionAgent forks a lightweight
52
+ * ReActAgent to review the full session trace. The fork runs in its own
53
+ * context with read-only tools (read_file, grep_search) so it can verify
54
+ * findings against the codebase.
55
+ *
56
+ * Findings are persisted to an ErrorNotebook (错题本) for future learning.
57
+ *
58
+ * Usage:
59
+ * ```ts
60
+ * const notebook = new ErrorNotebook({ storageDir: ".error-notebook" });
61
+ * const reflector = new ReflectionAgent({ llm, notebook, maxIterations: 4 });
62
+ * const entries = await reflector.reflect({
63
+ * userQuery: input,
64
+ * finalAnswer: answer,
65
+ * conversation: contextMessages,
66
+ * sessionId: "sess_123",
67
+ * });
68
+ * ```
69
+ */
70
+ export declare class ReflectionAgent {
71
+ private llm;
72
+ private notebook;
73
+ private maxIterations;
74
+ constructor(config: ReflectionAgentConfig);
75
+ /**
76
+ * Fork a sub-agent to review the session and persist findings.
77
+ *
78
+ * @returns The final list of findings written to the notebook.
79
+ */
80
+ reflect(input: ReflectionInput): Promise<ErrorNotebookEntry[]>;
81
+ /**
82
+ * Fork a minimal ReActAgent and run it to completion.
83
+ * Returns the agent's final answer string.
84
+ */
85
+ private forkAndRun;
86
+ /**
87
+ * Build the task prompt for the sub-agent from the reflection input.
88
+ */
89
+ private buildTaskPrompt;
90
+ /**
91
+ * Format the conversation for the reflection prompt.
92
+ * Truncates very long tool results for readability.
93
+ */
94
+ private formatConversation;
95
+ /**
96
+ * Format error traces for the reflection prompt.
97
+ */
98
+ private formatErrorTraces;
99
+ /**
100
+ * Parse the sub-agent's final answer into a list of ReflectionFindings.
101
+ * Returns an empty array if parsing fails (best-effort).
102
+ */
103
+ private parseFindings;
104
+ }
105
+ //# sourceMappingURL=reflection-agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reflection-agent.d.ts","sourceRoot":"","sources":["../../src/reflection/reflection-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAQ,MAAM,mBAAmB,CAAC;AAMtD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC9F,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAIrD;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,+BAA+B;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,WAAW,EAAE,MAAM,CAAC;IACpB,oDAAoD;IACpD,YAAY,EAAE,WAAW,EAAE,CAAC;IAC5B,mDAAmD;IACnD,WAAW,CAAC,EAAE,cAAc,EAAE,CAAC;IAC/B,+CAA+C;IAC/C,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,sBAAsB;IACtB,QAAQ,EAAE,uBAAuB,CAAC;IAClC,uBAAuB;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,kBAAkB;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,iCAAiC;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,8CAA8C;IAC9C,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC5B;AAmDD;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,iDAAiD;IACjD,GAAG,EAAE,WAAW,CAAC;IACjB,6CAA6C;IAC7C,QAAQ,EAAE,aAAa,CAAC;IACxB;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,GAAG,CAAc;IACzB,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,aAAa,CAAS;gBAElB,MAAM,EAAE,qBAAqB;IAQzC;;;;OAIG;IACG,OAAO,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC;IAoCpE;;;OAGG;YACW,UAAU;IAiBxB;;OAEG;IACH,OAAO,CAAC,eAAe;IAsBvB;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAsB1B;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAWzB;;;OAGG;IACH,OAAO,CAAC,aAAa;CA2CtB"}
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ReflectionAgent = void 0;
4
+ const types_1 = require("../messages/types");
5
+ const react_agent_1 = require("../core/react-agent");
6
+ const tool_registry_1 = require("../tools/tool-registry");
7
+ const read_file_1 = require("../tools/builtin/read-file");
8
+ const grep_search_1 = require("../tools/builtin/grep-search");
9
+ const response_schema_1 = require("../core/response-schema");
10
+ // ─── System Prompt ───────────────────────────────────────────────────────────
11
+ const ERROR_REFLECTION_SYSTEM_PROMPT = `You are a reflective quality-assurance agent. Your job is to review a completed
12
+ agent session and identify mistakes, missed opportunities, and improvement suggestions.
13
+
14
+ You have access to read_file and grep_search tools to verify your findings against the actual codebase.
15
+
16
+ Analyze the session across these dimensions:
17
+ - **Reasoning**: Was the agent's logic sound? Any flawed deductions?
18
+ - **Tool use**: Were the right tools used with correct parameters? Any misuse?
19
+ - **Efficiency**: Could the task have been completed faster or with fewer steps?
20
+ - **Completeness**: Does the answer fully address the user's query? Any missing information?
21
+ - **Context**: Was the context window managed well? Any irrelevant noise?
22
+
23
+ In your final answer, output a JSON object with this structure:
24
+ {
25
+ "analysis": "overall assessment (2-4 sentences)",
26
+ "score": 85,
27
+ "findings": [
28
+ {
29
+ "category": "reasoning_error | tool_misuse | missed_optimization | incomplete_answer | hallucination | context_mismanagement | other",
30
+ "description": "concise description of what went wrong",
31
+ "cause": "root cause — why did this happen?",
32
+ "suggestion": "how to avoid this next time",
33
+ "relatedTraceIds": ["trace_abc123"]
34
+ }
35
+ ]
36
+ }
37
+
38
+ Rules:
39
+ - Score 0-100 where 100 = flawless execution.
40
+ - Only include findings for actual issues — do NOT fabricate problems.
41
+ - If the session was perfect, return an empty findings array and score 100.
42
+ - Group related findings; don't duplicate.
43
+ - Be specific: cite exact tool names, file paths, reasoning steps where applicable.
44
+ - Use your tools to verify findings against the actual codebase before reporting them.
45
+ ${response_schema_1.STRUCTURED_OUTPUT_INSTRUCTIONS}`;
46
+ /**
47
+ * ReflectionAgent — post-execution self-reflection via a forked sub-agent.
48
+ *
49
+ * After the main agent finishes, the ReflectionAgent forks a lightweight
50
+ * ReActAgent to review the full session trace. The fork runs in its own
51
+ * context with read-only tools (read_file, grep_search) so it can verify
52
+ * findings against the codebase.
53
+ *
54
+ * Findings are persisted to an ErrorNotebook (错题本) for future learning.
55
+ *
56
+ * Usage:
57
+ * ```ts
58
+ * const notebook = new ErrorNotebook({ storageDir: ".error-notebook" });
59
+ * const reflector = new ReflectionAgent({ llm, notebook, maxIterations: 4 });
60
+ * const entries = await reflector.reflect({
61
+ * userQuery: input,
62
+ * finalAnswer: answer,
63
+ * conversation: contextMessages,
64
+ * sessionId: "sess_123",
65
+ * });
66
+ * ```
67
+ */
68
+ class ReflectionAgent {
69
+ llm;
70
+ notebook;
71
+ maxIterations;
72
+ constructor(config) {
73
+ this.llm = config.llm;
74
+ this.notebook = config.notebook;
75
+ this.maxIterations = config.maxIterations ?? 4;
76
+ }
77
+ // ─── Public API ────────────────────────────────────────────────────────
78
+ /**
79
+ * Fork a sub-agent to review the session and persist findings.
80
+ *
81
+ * @returns The final list of findings written to the notebook.
82
+ */
83
+ async reflect(input) {
84
+ const taskPrompt = this.buildTaskPrompt(input);
85
+ const answer = await this.forkAndRun(taskPrompt);
86
+ const findings = this.parseFindings(answer);
87
+ // Deduplicate by category + description before persisting
88
+ const seen = new Set();
89
+ const unique = [];
90
+ for (const f of findings) {
91
+ const key = `${f.category}::${f.description.toLowerCase()}`;
92
+ if (!seen.has(key)) {
93
+ seen.add(key);
94
+ unique.push(f);
95
+ }
96
+ }
97
+ // Persist to ErrorNotebook
98
+ const entries = [];
99
+ for (const f of unique) {
100
+ const entry = this.notebook.add({
101
+ sessionId: input.sessionId,
102
+ category: f.category,
103
+ description: f.description,
104
+ cause: f.cause,
105
+ suggestion: f.suggestion,
106
+ userQuery: input.userQuery,
107
+ relatedTraceIds: f.relatedTraceIds,
108
+ });
109
+ entries.push(entry);
110
+ }
111
+ return entries;
112
+ }
113
+ // ─── Private: Fork ─────────────────────────────────────────────────────
114
+ /**
115
+ * Fork a minimal ReActAgent and run it to completion.
116
+ * Returns the agent's final answer string.
117
+ */
118
+ async forkAndRun(userPrompt) {
119
+ const tools = new tool_registry_1.ToolRegistry();
120
+ tools.register(read_file_1.ReadFileTool);
121
+ tools.register(grep_search_1.GrepSearchTool);
122
+ const agent = new react_agent_1.ReActAgent({
123
+ llm: this.llm,
124
+ systemPrompt: ERROR_REFLECTION_SYSTEM_PROMPT,
125
+ toolRegistry: tools,
126
+ maxIterations: this.maxIterations,
127
+ });
128
+ return agent.run(userPrompt);
129
+ }
130
+ // ─── Private: Prompt Building ──────────────────────────────────────────
131
+ /**
132
+ * Build the task prompt for the sub-agent from the reflection input.
133
+ */
134
+ buildTaskPrompt(input) {
135
+ const context = [
136
+ "Please review this agent session and identify any issues.",
137
+ "",
138
+ "=== User Query ===",
139
+ input.userQuery,
140
+ "",
141
+ "=== Final Answer ===",
142
+ input.finalAnswer,
143
+ "",
144
+ "=== Conversation ===",
145
+ ...this.formatConversation(input.conversation),
146
+ "",
147
+ "=== Tool Error Traces ===",
148
+ ...this.formatErrorTraces(input.errorTraces),
149
+ "",
150
+ "Analyze the session and output your findings as JSON in your final answer.",
151
+ ].join("\n");
152
+ return context;
153
+ }
154
+ /**
155
+ * Format the conversation for the reflection prompt.
156
+ * Truncates very long tool results for readability.
157
+ */
158
+ formatConversation(messages) {
159
+ const lines = [];
160
+ for (const msg of messages) {
161
+ const role = msg.role.toUpperCase();
162
+ let content = msg.content;
163
+ // Truncate long tool results
164
+ if (msg.role === types_1.Role.Tool && content.length > 1000) {
165
+ content = content.slice(0, 500) + "\n... (truncated, " + content.length + " chars total)";
166
+ }
167
+ lines.push(`[${role}] ${content}`);
168
+ if (msg.tool_calls && msg.tool_calls.length > 0) {
169
+ for (const tc of msg.tool_calls) {
170
+ lines.push(` → tool_call: ${tc.function.name}(${tc.function.arguments})`);
171
+ }
172
+ }
173
+ }
174
+ return lines;
175
+ }
176
+ /**
177
+ * Format error traces for the reflection prompt.
178
+ */
179
+ formatErrorTraces(traces) {
180
+ if (!traces || traces.length === 0)
181
+ return ["(no tool errors recorded)"];
182
+ const lines = [];
183
+ for (const t of traces) {
184
+ lines.push(`- ${t.traceId}: ${t.toolName} — ${t.resolved ? "resolved" : "unresolved"} (${t.events.length} events)`);
185
+ }
186
+ return lines;
187
+ }
188
+ // ─── Private: Parsing ──────────────────────────────────────────────────
189
+ /**
190
+ * Parse the sub-agent's final answer into a list of ReflectionFindings.
191
+ * Returns an empty array if parsing fails (best-effort).
192
+ */
193
+ parseFindings(answer) {
194
+ try {
195
+ // Extract JSON from the answer (may be wrapped in ```json fences)
196
+ let raw = answer.trim();
197
+ const fenceMatch = raw.match(/```(?:json)?\s*([\s\S]*?)\s*```/);
198
+ if (fenceMatch)
199
+ raw = fenceMatch[1];
200
+ const parsed = JSON.parse(raw);
201
+ if (!Array.isArray(parsed.findings))
202
+ return [];
203
+ const validCategories = new Set([
204
+ "reasoning_error", "tool_misuse", "missed_optimization",
205
+ "incomplete_answer", "hallucination", "context_mismanagement", "other",
206
+ ]);
207
+ const findings = [];
208
+ for (const f of parsed.findings) {
209
+ if (typeof f.category !== "string" ||
210
+ !validCategories.has(f.category) ||
211
+ typeof f.description !== "string" ||
212
+ typeof f.cause !== "string" ||
213
+ typeof f.suggestion !== "string") {
214
+ continue;
215
+ }
216
+ findings.push({
217
+ category: f.category,
218
+ description: f.description,
219
+ cause: f.cause,
220
+ suggestion: f.suggestion,
221
+ relatedTraceIds: Array.isArray(f.relatedTraceIds)
222
+ ? f.relatedTraceIds.filter((id) => typeof id === "string")
223
+ : undefined,
224
+ });
225
+ }
226
+ return findings;
227
+ }
228
+ catch {
229
+ return [];
230
+ }
231
+ }
232
+ }
233
+ exports.ReflectionAgent = ReflectionAgent;
234
+ //# sourceMappingURL=reflection-agent.js.map