attocode 0.2.4 → 0.2.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 (577) hide show
  1. package/CHANGELOG.md +56 -1
  2. package/dist/src/adapters.d.ts +2 -1
  3. package/dist/src/adapters.d.ts.map +1 -1
  4. package/dist/src/adapters.js +60 -2
  5. package/dist/src/adapters.js.map +1 -1
  6. package/dist/src/agent/agent-builder.d.ts +117 -0
  7. package/dist/src/agent/agent-builder.d.ts.map +1 -0
  8. package/dist/src/agent/agent-builder.js +204 -0
  9. package/dist/src/agent/agent-builder.js.map +1 -0
  10. package/dist/src/agent/feature-initializer.d.ts +80 -0
  11. package/dist/src/agent/feature-initializer.d.ts.map +1 -0
  12. package/dist/src/agent/feature-initializer.js +677 -0
  13. package/dist/src/agent/feature-initializer.js.map +1 -0
  14. package/dist/src/agent/index.d.ts +13 -0
  15. package/dist/src/agent/index.d.ts.map +1 -0
  16. package/dist/src/agent/index.js +13 -0
  17. package/dist/src/agent/index.js.map +1 -0
  18. package/dist/src/agent/message-builder.d.ts +50 -0
  19. package/dist/src/agent/message-builder.d.ts.map +1 -0
  20. package/dist/src/agent/message-builder.js +173 -0
  21. package/dist/src/agent/message-builder.js.map +1 -0
  22. package/dist/src/agent/session-api.d.ts +94 -0
  23. package/dist/src/agent/session-api.d.ts.map +1 -0
  24. package/dist/src/agent/session-api.js +262 -0
  25. package/dist/src/agent/session-api.js.map +1 -0
  26. package/dist/src/agent-tools/lsp-file-tools.d.ts +1 -1
  27. package/dist/src/agent-tools/lsp-file-tools.d.ts.map +1 -1
  28. package/dist/src/agent.d.ts +14 -115
  29. package/dist/src/agent.d.ts.map +1 -1
  30. package/dist/src/agent.js +36 -1177
  31. package/dist/src/agent.js.map +1 -1
  32. package/dist/src/cli.js +1 -1
  33. package/dist/src/cli.js.map +1 -1
  34. package/dist/src/commands/handler.d.ts.map +1 -1
  35. package/dist/src/commands/handler.js +8 -7
  36. package/dist/src/commands/handler.js.map +1 -1
  37. package/dist/src/commands/init.js +1 -1
  38. package/dist/src/commands/init.js.map +1 -1
  39. package/dist/src/config/schema.d.ts +6 -6
  40. package/dist/src/core/execution-loop.d.ts.map +1 -1
  41. package/dist/src/core/execution-loop.js +155 -16
  42. package/dist/src/core/execution-loop.js.map +1 -1
  43. package/dist/src/core/response-handler.d.ts.map +1 -1
  44. package/dist/src/core/response-handler.js +3 -2
  45. package/dist/src/core/response-handler.js.map +1 -1
  46. package/dist/src/core/subagent-spawner.d.ts.map +1 -1
  47. package/dist/src/core/subagent-spawner.js +13 -6
  48. package/dist/src/core/subagent-spawner.js.map +1 -1
  49. package/dist/src/core/tool-executor.d.ts.map +1 -1
  50. package/dist/src/core/tool-executor.js +7 -2
  51. package/dist/src/core/tool-executor.js.map +1 -1
  52. package/dist/src/core/types.d.ts +1 -0
  53. package/dist/src/core/types.d.ts.map +1 -1
  54. package/dist/src/core/types.js.map +1 -1
  55. package/dist/src/integrations/agents/agent-registry.d.ts +262 -0
  56. package/dist/src/integrations/agents/agent-registry.d.ts.map +1 -0
  57. package/dist/src/integrations/agents/agent-registry.js +686 -0
  58. package/dist/src/integrations/agents/agent-registry.js.map +1 -0
  59. package/dist/src/integrations/agents/async-subagent.d.ts +135 -0
  60. package/dist/src/integrations/agents/async-subagent.d.ts.map +1 -0
  61. package/dist/src/integrations/agents/async-subagent.js +213 -0
  62. package/dist/src/integrations/agents/async-subagent.js.map +1 -0
  63. package/dist/src/integrations/agents/complexity-classifier.d.ts +86 -0
  64. package/dist/src/integrations/agents/complexity-classifier.d.ts.map +1 -0
  65. package/dist/src/integrations/agents/complexity-classifier.js +233 -0
  66. package/dist/src/integrations/agents/complexity-classifier.js.map +1 -0
  67. package/dist/src/integrations/agents/delegation-protocol.d.ts +86 -0
  68. package/dist/src/integrations/agents/delegation-protocol.d.ts.map +1 -0
  69. package/dist/src/integrations/agents/delegation-protocol.js +127 -0
  70. package/dist/src/integrations/agents/delegation-protocol.js.map +1 -0
  71. package/dist/src/integrations/agents/multi-agent.d.ts +150 -0
  72. package/dist/src/integrations/agents/multi-agent.d.ts.map +1 -0
  73. package/dist/src/integrations/agents/multi-agent.js +306 -0
  74. package/dist/src/integrations/agents/multi-agent.js.map +1 -0
  75. package/dist/src/integrations/agents/result-synthesizer.d.ts +389 -0
  76. package/dist/src/integrations/agents/result-synthesizer.d.ts.map +1 -0
  77. package/dist/src/integrations/agents/result-synthesizer.js +951 -0
  78. package/dist/src/integrations/agents/result-synthesizer.js.map +1 -0
  79. package/dist/src/integrations/agents/shared-blackboard.d.ts +406 -0
  80. package/dist/src/integrations/agents/shared-blackboard.d.ts.map +1 -0
  81. package/dist/src/integrations/agents/shared-blackboard.js +757 -0
  82. package/dist/src/integrations/agents/shared-blackboard.js.map +1 -0
  83. package/dist/src/integrations/agents/subagent-output-store.d.ts +91 -0
  84. package/dist/src/integrations/agents/subagent-output-store.d.ts.map +1 -0
  85. package/dist/src/integrations/agents/subagent-output-store.js +257 -0
  86. package/dist/src/integrations/agents/subagent-output-store.js.map +1 -0
  87. package/dist/src/integrations/budget/budget-pool.d.ts +115 -0
  88. package/dist/src/integrations/budget/budget-pool.d.ts.map +1 -0
  89. package/dist/src/integrations/budget/budget-pool.js +205 -0
  90. package/dist/src/integrations/budget/budget-pool.js.map +1 -0
  91. package/dist/src/integrations/budget/cancellation.d.ts +229 -0
  92. package/dist/src/integrations/budget/cancellation.d.ts.map +1 -0
  93. package/dist/src/integrations/budget/cancellation.js +520 -0
  94. package/dist/src/integrations/budget/cancellation.js.map +1 -0
  95. package/dist/src/integrations/budget/dynamic-budget.d.ts +81 -0
  96. package/dist/src/integrations/budget/dynamic-budget.d.ts.map +1 -0
  97. package/dist/src/integrations/budget/dynamic-budget.js +151 -0
  98. package/dist/src/integrations/budget/dynamic-budget.js.map +1 -0
  99. package/dist/src/integrations/budget/economics.d.ts +435 -0
  100. package/dist/src/integrations/budget/economics.d.ts.map +1 -0
  101. package/dist/src/integrations/budget/economics.js +1007 -0
  102. package/dist/src/integrations/budget/economics.js.map +1 -0
  103. package/dist/src/integrations/budget/injection-budget.d.ts +71 -0
  104. package/dist/src/integrations/budget/injection-budget.d.ts.map +1 -0
  105. package/dist/src/integrations/budget/injection-budget.js +137 -0
  106. package/dist/src/integrations/budget/injection-budget.js.map +1 -0
  107. package/dist/src/integrations/budget/loop-detector.d.ts +105 -0
  108. package/dist/src/integrations/budget/loop-detector.d.ts.map +1 -0
  109. package/dist/src/integrations/budget/loop-detector.js +287 -0
  110. package/dist/src/integrations/budget/loop-detector.js.map +1 -0
  111. package/dist/src/integrations/budget/phase-tracker.d.ts +114 -0
  112. package/dist/src/integrations/budget/phase-tracker.d.ts.map +1 -0
  113. package/dist/src/integrations/budget/phase-tracker.js +262 -0
  114. package/dist/src/integrations/budget/phase-tracker.js.map +1 -0
  115. package/dist/src/integrations/budget/resources.d.ts +182 -0
  116. package/dist/src/integrations/budget/resources.d.ts.map +1 -0
  117. package/dist/src/integrations/budget/resources.js +318 -0
  118. package/dist/src/integrations/budget/resources.js.map +1 -0
  119. package/dist/src/integrations/context/auto-compaction.d.ts +210 -0
  120. package/dist/src/integrations/context/auto-compaction.d.ts.map +1 -0
  121. package/dist/src/integrations/context/auto-compaction.js +477 -0
  122. package/dist/src/integrations/context/auto-compaction.js.map +1 -0
  123. package/dist/src/integrations/context/code-analyzer.d.ts +71 -0
  124. package/dist/src/integrations/context/code-analyzer.d.ts.map +1 -0
  125. package/dist/src/integrations/context/code-analyzer.js +448 -0
  126. package/dist/src/integrations/context/code-analyzer.js.map +1 -0
  127. package/dist/src/integrations/context/code-selector.d.ts +78 -0
  128. package/dist/src/integrations/context/code-selector.d.ts.map +1 -0
  129. package/dist/src/integrations/context/code-selector.js +649 -0
  130. package/dist/src/integrations/context/code-selector.js.map +1 -0
  131. package/dist/src/integrations/context/codebase-ast.d.ts +138 -0
  132. package/dist/src/integrations/context/codebase-ast.d.ts.map +1 -0
  133. package/dist/src/integrations/context/codebase-ast.js +818 -0
  134. package/dist/src/integrations/context/codebase-ast.js.map +1 -0
  135. package/dist/src/integrations/context/codebase-context.d.ts +473 -0
  136. package/dist/src/integrations/context/codebase-context.d.ts.map +1 -0
  137. package/dist/src/integrations/context/codebase-context.js +685 -0
  138. package/dist/src/integrations/context/codebase-context.js.map +1 -0
  139. package/dist/src/integrations/context/compaction.d.ts +191 -0
  140. package/dist/src/integrations/context/compaction.d.ts.map +1 -0
  141. package/dist/src/integrations/context/compaction.js +384 -0
  142. package/dist/src/integrations/context/compaction.js.map +1 -0
  143. package/dist/src/integrations/context/context-engineering.d.ts +274 -0
  144. package/dist/src/integrations/context/context-engineering.d.ts.map +1 -0
  145. package/dist/src/integrations/context/context-engineering.js +437 -0
  146. package/dist/src/integrations/context/context-engineering.js.map +1 -0
  147. package/dist/src/integrations/context/file-cache.d.ts +97 -0
  148. package/dist/src/integrations/context/file-cache.d.ts.map +1 -0
  149. package/dist/src/integrations/context/file-cache.js +218 -0
  150. package/dist/src/integrations/context/file-cache.js.map +1 -0
  151. package/dist/src/integrations/context/semantic-cache.d.ts +178 -0
  152. package/dist/src/integrations/context/semantic-cache.d.ts.map +1 -0
  153. package/dist/src/integrations/context/semantic-cache.js +372 -0
  154. package/dist/src/integrations/context/semantic-cache.js.map +1 -0
  155. package/dist/src/integrations/index.d.ts +72 -68
  156. package/dist/src/integrations/index.d.ts.map +1 -1
  157. package/dist/src/integrations/index.js +76 -68
  158. package/dist/src/integrations/index.js.map +1 -1
  159. package/dist/src/integrations/lsp/lsp.d.ts +196 -0
  160. package/dist/src/integrations/lsp/lsp.d.ts.map +1 -0
  161. package/dist/src/integrations/lsp/lsp.js +583 -0
  162. package/dist/src/integrations/lsp/lsp.js.map +1 -0
  163. package/dist/src/integrations/mcp/mcp-client.d.ts +279 -0
  164. package/dist/src/integrations/mcp/mcp-client.d.ts.map +1 -0
  165. package/dist/src/integrations/mcp/mcp-client.js +755 -0
  166. package/dist/src/integrations/mcp/mcp-client.js.map +1 -0
  167. package/dist/src/integrations/mcp/mcp-custom-tools.d.ts +102 -0
  168. package/dist/src/integrations/mcp/mcp-custom-tools.d.ts.map +1 -0
  169. package/dist/src/integrations/mcp/mcp-custom-tools.js +232 -0
  170. package/dist/src/integrations/mcp/mcp-custom-tools.js.map +1 -0
  171. package/dist/src/integrations/mcp/mcp-tool-search.d.ts +77 -0
  172. package/dist/src/integrations/mcp/mcp-tool-search.d.ts.map +1 -0
  173. package/dist/src/integrations/mcp/mcp-tool-search.js +220 -0
  174. package/dist/src/integrations/mcp/mcp-tool-search.js.map +1 -0
  175. package/dist/src/integrations/mcp/mcp-tool-validator.d.ts +60 -0
  176. package/dist/src/integrations/mcp/mcp-tool-validator.d.ts.map +1 -0
  177. package/dist/src/integrations/mcp/mcp-tool-validator.js +141 -0
  178. package/dist/src/integrations/mcp/mcp-tool-validator.js.map +1 -0
  179. package/dist/src/integrations/persistence/codebase-repository.d.ts +45 -0
  180. package/dist/src/integrations/persistence/codebase-repository.d.ts.map +1 -0
  181. package/dist/src/integrations/persistence/codebase-repository.js +81 -0
  182. package/dist/src/integrations/persistence/codebase-repository.js.map +1 -0
  183. package/dist/src/integrations/persistence/goal-repository.d.ts +71 -0
  184. package/dist/src/integrations/persistence/goal-repository.d.ts.map +1 -0
  185. package/dist/src/integrations/persistence/goal-repository.js +184 -0
  186. package/dist/src/integrations/persistence/goal-repository.js.map +1 -0
  187. package/dist/src/integrations/persistence/history.d.ts +72 -0
  188. package/dist/src/integrations/persistence/history.d.ts.map +1 -0
  189. package/dist/src/integrations/persistence/history.js +165 -0
  190. package/dist/src/integrations/persistence/history.js.map +1 -0
  191. package/dist/src/integrations/persistence/persistence.d.ts +49 -0
  192. package/dist/src/integrations/persistence/persistence.d.ts.map +1 -0
  193. package/dist/src/integrations/persistence/persistence.js +197 -0
  194. package/dist/src/integrations/persistence/persistence.js.map +1 -0
  195. package/dist/src/integrations/persistence/session-repository.d.ts +212 -0
  196. package/dist/src/integrations/persistence/session-repository.d.ts.map +1 -0
  197. package/dist/src/integrations/persistence/session-repository.js +770 -0
  198. package/dist/src/integrations/persistence/session-repository.js.map +1 -0
  199. package/dist/src/integrations/persistence/session-store.d.ts +184 -0
  200. package/dist/src/integrations/persistence/session-store.d.ts.map +1 -0
  201. package/dist/src/integrations/persistence/session-store.js +346 -0
  202. package/dist/src/integrations/persistence/session-store.js.map +1 -0
  203. package/dist/src/integrations/persistence/sqlite-store.d.ts +453 -0
  204. package/dist/src/integrations/persistence/sqlite-store.d.ts.map +1 -0
  205. package/dist/src/integrations/persistence/sqlite-store.js +676 -0
  206. package/dist/src/integrations/persistence/sqlite-store.js.map +1 -0
  207. package/dist/src/integrations/persistence/worker-repository.d.ts +65 -0
  208. package/dist/src/integrations/persistence/worker-repository.d.ts.map +1 -0
  209. package/dist/src/integrations/persistence/worker-repository.js +183 -0
  210. package/dist/src/integrations/persistence/worker-repository.js.map +1 -0
  211. package/dist/src/integrations/quality/auto-checkpoint.d.ts +98 -0
  212. package/dist/src/integrations/quality/auto-checkpoint.d.ts.map +1 -0
  213. package/dist/src/integrations/quality/auto-checkpoint.js +252 -0
  214. package/dist/src/integrations/quality/auto-checkpoint.js.map +1 -0
  215. package/dist/src/integrations/quality/dead-letter-queue.d.ts +233 -0
  216. package/dist/src/integrations/quality/dead-letter-queue.d.ts.map +1 -0
  217. package/dist/src/integrations/quality/dead-letter-queue.js +543 -0
  218. package/dist/src/integrations/quality/dead-letter-queue.js.map +1 -0
  219. package/dist/src/integrations/quality/health-check.d.ts +218 -0
  220. package/dist/src/integrations/quality/health-check.d.ts.map +1 -0
  221. package/dist/src/integrations/quality/health-check.js +415 -0
  222. package/dist/src/integrations/quality/health-check.js.map +1 -0
  223. package/dist/src/integrations/quality/learning-store.d.ts +291 -0
  224. package/dist/src/integrations/quality/learning-store.d.ts.map +1 -0
  225. package/dist/src/integrations/quality/learning-store.js +646 -0
  226. package/dist/src/integrations/quality/learning-store.js.map +1 -0
  227. package/dist/src/integrations/quality/self-improvement.d.ts +90 -0
  228. package/dist/src/integrations/quality/self-improvement.d.ts.map +1 -0
  229. package/dist/src/integrations/quality/self-improvement.js +229 -0
  230. package/dist/src/integrations/quality/self-improvement.js.map +1 -0
  231. package/dist/src/integrations/quality/tool-recommendation.d.ts +61 -0
  232. package/dist/src/integrations/quality/tool-recommendation.d.ts.map +1 -0
  233. package/dist/src/integrations/quality/tool-recommendation.js +268 -0
  234. package/dist/src/integrations/quality/tool-recommendation.js.map +1 -0
  235. package/dist/src/integrations/safety/bash-policy.d.ts +33 -0
  236. package/dist/src/integrations/safety/bash-policy.d.ts.map +1 -0
  237. package/dist/src/integrations/safety/bash-policy.js +144 -0
  238. package/dist/src/integrations/safety/bash-policy.js.map +1 -0
  239. package/dist/src/integrations/safety/edit-validator.d.ts +30 -0
  240. package/dist/src/integrations/safety/edit-validator.d.ts.map +1 -0
  241. package/dist/src/integrations/safety/edit-validator.js +87 -0
  242. package/dist/src/integrations/safety/edit-validator.js.map +1 -0
  243. package/dist/src/integrations/safety/execution-policy.d.ts +189 -0
  244. package/dist/src/integrations/safety/execution-policy.d.ts.map +1 -0
  245. package/dist/src/integrations/safety/execution-policy.js +352 -0
  246. package/dist/src/integrations/safety/execution-policy.js.map +1 -0
  247. package/dist/src/integrations/safety/policy-engine.d.ts +55 -0
  248. package/dist/src/integrations/safety/policy-engine.d.ts.map +1 -0
  249. package/dist/src/integrations/safety/policy-engine.js +247 -0
  250. package/dist/src/integrations/safety/policy-engine.js.map +1 -0
  251. package/dist/src/integrations/safety/safety.d.ts +174 -0
  252. package/dist/src/integrations/safety/safety.d.ts.map +1 -0
  253. package/dist/src/integrations/safety/safety.js +470 -0
  254. package/dist/src/integrations/safety/safety.js.map +1 -0
  255. package/dist/src/integrations/safety/sandbox/basic.d.ts +81 -0
  256. package/dist/src/integrations/safety/sandbox/basic.d.ts.map +1 -0
  257. package/dist/src/integrations/safety/sandbox/basic.js +335 -0
  258. package/dist/src/integrations/safety/sandbox/basic.js.map +1 -0
  259. package/dist/src/integrations/safety/sandbox/docker.d.ts +94 -0
  260. package/dist/src/integrations/safety/sandbox/docker.d.ts.map +1 -0
  261. package/dist/src/integrations/safety/sandbox/docker.js +294 -0
  262. package/dist/src/integrations/safety/sandbox/docker.js.map +1 -0
  263. package/dist/src/integrations/safety/sandbox/index.d.ts +188 -0
  264. package/dist/src/integrations/safety/sandbox/index.d.ts.map +1 -0
  265. package/dist/src/integrations/safety/sandbox/index.js +386 -0
  266. package/dist/src/integrations/safety/sandbox/index.js.map +1 -0
  267. package/dist/src/integrations/safety/sandbox/landlock.d.ts +59 -0
  268. package/dist/src/integrations/safety/sandbox/landlock.d.ts.map +1 -0
  269. package/dist/src/integrations/safety/sandbox/landlock.js +329 -0
  270. package/dist/src/integrations/safety/sandbox/landlock.js.map +1 -0
  271. package/dist/src/integrations/safety/sandbox/seatbelt.d.ts +68 -0
  272. package/dist/src/integrations/safety/sandbox/seatbelt.d.ts.map +1 -0
  273. package/dist/src/integrations/safety/sandbox/seatbelt.js +298 -0
  274. package/dist/src/integrations/safety/sandbox/seatbelt.js.map +1 -0
  275. package/dist/src/integrations/safety/type-checker.d.ts +53 -0
  276. package/dist/src/integrations/safety/type-checker.d.ts.map +1 -0
  277. package/dist/src/integrations/safety/type-checker.js +142 -0
  278. package/dist/src/integrations/safety/type-checker.js.map +1 -0
  279. package/dist/src/integrations/skills/skill-executor.d.ts +113 -0
  280. package/dist/src/integrations/skills/skill-executor.d.ts.map +1 -0
  281. package/dist/src/integrations/skills/skill-executor.js +270 -0
  282. package/dist/src/integrations/skills/skill-executor.js.map +1 -0
  283. package/dist/src/integrations/skills/skills.d.ts +262 -0
  284. package/dist/src/integrations/skills/skills.d.ts.map +1 -0
  285. package/dist/src/integrations/skills/skills.js +602 -0
  286. package/dist/src/integrations/skills/skills.js.map +1 -0
  287. package/dist/src/integrations/streaming/pty-shell.d.ts +169 -0
  288. package/dist/src/integrations/streaming/pty-shell.d.ts.map +1 -0
  289. package/dist/src/integrations/streaming/pty-shell.js +367 -0
  290. package/dist/src/integrations/streaming/pty-shell.js.map +1 -0
  291. package/dist/src/integrations/streaming/streaming.d.ts +102 -0
  292. package/dist/src/integrations/streaming/streaming.d.ts.map +1 -0
  293. package/dist/src/integrations/streaming/streaming.js +362 -0
  294. package/dist/src/integrations/streaming/streaming.js.map +1 -0
  295. package/dist/src/integrations/swarm/index.d.ts +2 -1
  296. package/dist/src/integrations/swarm/index.d.ts.map +1 -1
  297. package/dist/src/integrations/swarm/index.js +2 -0
  298. package/dist/src/integrations/swarm/index.js.map +1 -1
  299. package/dist/src/integrations/swarm/model-selector.js +1 -1
  300. package/dist/src/integrations/swarm/model-selector.js.map +1 -1
  301. package/dist/src/integrations/swarm/swarm-budget.d.ts +1 -1
  302. package/dist/src/integrations/swarm/swarm-budget.d.ts.map +1 -1
  303. package/dist/src/integrations/swarm/swarm-budget.js +1 -1
  304. package/dist/src/integrations/swarm/swarm-budget.js.map +1 -1
  305. package/dist/src/integrations/swarm/swarm-config-loader.d.ts.map +1 -1
  306. package/dist/src/integrations/swarm/swarm-config-loader.js +7 -0
  307. package/dist/src/integrations/swarm/swarm-config-loader.js.map +1 -1
  308. package/dist/src/integrations/swarm/swarm-events.d.ts +1 -1
  309. package/dist/src/integrations/swarm/swarm-events.d.ts.map +1 -1
  310. package/dist/src/integrations/swarm/swarm-execution.d.ts +27 -0
  311. package/dist/src/integrations/swarm/swarm-execution.d.ts.map +1 -0
  312. package/dist/src/integrations/swarm/swarm-execution.js +1021 -0
  313. package/dist/src/integrations/swarm/swarm-execution.js.map +1 -0
  314. package/dist/src/integrations/swarm/swarm-helpers.d.ts +26 -0
  315. package/dist/src/integrations/swarm/swarm-helpers.d.ts.map +1 -0
  316. package/dist/src/integrations/swarm/swarm-helpers.js +95 -0
  317. package/dist/src/integrations/swarm/swarm-helpers.js.map +1 -0
  318. package/dist/src/integrations/swarm/swarm-lifecycle.d.ts +100 -0
  319. package/dist/src/integrations/swarm/swarm-lifecycle.d.ts.map +1 -0
  320. package/dist/src/integrations/swarm/swarm-lifecycle.js +922 -0
  321. package/dist/src/integrations/swarm/swarm-lifecycle.js.map +1 -0
  322. package/dist/src/integrations/swarm/swarm-orchestrator.d.ts +84 -203
  323. package/dist/src/integrations/swarm/swarm-orchestrator.d.ts.map +1 -1
  324. package/dist/src/integrations/swarm/swarm-orchestrator.js +251 -2870
  325. package/dist/src/integrations/swarm/swarm-orchestrator.js.map +1 -1
  326. package/dist/src/integrations/swarm/swarm-quality-gate.js +1 -1
  327. package/dist/src/integrations/swarm/swarm-quality-gate.js.map +1 -1
  328. package/dist/src/integrations/swarm/swarm-recovery.d.ts +75 -0
  329. package/dist/src/integrations/swarm/swarm-recovery.d.ts.map +1 -0
  330. package/dist/src/integrations/swarm/swarm-recovery.js +550 -0
  331. package/dist/src/integrations/swarm/swarm-recovery.js.map +1 -0
  332. package/dist/src/integrations/swarm/swarm-state-store.d.ts.map +1 -1
  333. package/dist/src/integrations/swarm/swarm-state-store.js +6 -0
  334. package/dist/src/integrations/swarm/swarm-state-store.js.map +1 -1
  335. package/dist/src/integrations/swarm/task-queue.d.ts +1 -1
  336. package/dist/src/integrations/swarm/task-queue.d.ts.map +1 -1
  337. package/dist/src/integrations/swarm/task-queue.js +28 -1
  338. package/dist/src/integrations/swarm/task-queue.js.map +1 -1
  339. package/dist/src/integrations/swarm/types.d.ts +17 -5
  340. package/dist/src/integrations/swarm/types.d.ts.map +1 -1
  341. package/dist/src/integrations/swarm/types.js.map +1 -1
  342. package/dist/src/integrations/swarm/worker-pool.d.ts +1 -1
  343. package/dist/src/integrations/swarm/worker-pool.d.ts.map +1 -1
  344. package/dist/src/integrations/swarm/worker-pool.js +13 -9
  345. package/dist/src/integrations/swarm/worker-pool.js.map +1 -1
  346. package/dist/src/integrations/tasks/dependency-analyzer.d.ts +34 -0
  347. package/dist/src/integrations/tasks/dependency-analyzer.d.ts.map +1 -0
  348. package/dist/src/integrations/tasks/dependency-analyzer.js +232 -0
  349. package/dist/src/integrations/tasks/dependency-analyzer.js.map +1 -0
  350. package/dist/src/integrations/tasks/interactive-planning.d.ts +322 -0
  351. package/dist/src/integrations/tasks/interactive-planning.d.ts.map +1 -0
  352. package/dist/src/integrations/tasks/interactive-planning.js +655 -0
  353. package/dist/src/integrations/tasks/interactive-planning.js.map +1 -0
  354. package/dist/src/integrations/tasks/pending-plan.d.ts +196 -0
  355. package/dist/src/integrations/tasks/pending-plan.d.ts.map +1 -0
  356. package/dist/src/integrations/tasks/pending-plan.js +431 -0
  357. package/dist/src/integrations/tasks/pending-plan.js.map +1 -0
  358. package/dist/src/integrations/tasks/planning.d.ts +115 -0
  359. package/dist/src/integrations/tasks/planning.d.ts.map +1 -0
  360. package/dist/src/integrations/tasks/planning.js +413 -0
  361. package/dist/src/integrations/tasks/planning.js.map +1 -0
  362. package/dist/src/integrations/tasks/smart-decomposer.d.ts +316 -0
  363. package/dist/src/integrations/tasks/smart-decomposer.d.ts.map +1 -0
  364. package/dist/src/integrations/tasks/smart-decomposer.js +661 -0
  365. package/dist/src/integrations/tasks/smart-decomposer.js.map +1 -0
  366. package/dist/src/integrations/tasks/task-manager.d.ts +164 -0
  367. package/dist/src/integrations/tasks/task-manager.d.ts.map +1 -0
  368. package/dist/src/integrations/tasks/task-manager.js +383 -0
  369. package/dist/src/integrations/tasks/task-manager.js.map +1 -0
  370. package/dist/src/integrations/tasks/task-splitter.d.ts +56 -0
  371. package/dist/src/integrations/tasks/task-splitter.d.ts.map +1 -0
  372. package/dist/src/integrations/tasks/task-splitter.js +537 -0
  373. package/dist/src/integrations/tasks/task-splitter.js.map +1 -0
  374. package/dist/src/integrations/tasks/verification-gate.d.ts +103 -0
  375. package/dist/src/integrations/tasks/verification-gate.d.ts.map +1 -0
  376. package/dist/src/integrations/tasks/verification-gate.js +193 -0
  377. package/dist/src/integrations/tasks/verification-gate.js.map +1 -0
  378. package/dist/src/integrations/tasks/work-log.d.ts +87 -0
  379. package/dist/src/integrations/tasks/work-log.d.ts.map +1 -0
  380. package/dist/src/integrations/tasks/work-log.js +275 -0
  381. package/dist/src/integrations/tasks/work-log.js.map +1 -0
  382. package/dist/src/integrations/utilities/capabilities.d.ts +160 -0
  383. package/dist/src/integrations/utilities/capabilities.d.ts.map +1 -0
  384. package/dist/src/integrations/utilities/capabilities.js +426 -0
  385. package/dist/src/integrations/utilities/capabilities.js.map +1 -0
  386. package/dist/src/integrations/utilities/diff-utils.d.ts +105 -0
  387. package/dist/src/integrations/utilities/diff-utils.d.ts.map +1 -0
  388. package/dist/src/integrations/utilities/diff-utils.js +497 -0
  389. package/dist/src/integrations/utilities/diff-utils.js.map +1 -0
  390. package/dist/src/integrations/utilities/environment-facts.d.ts +52 -0
  391. package/dist/src/integrations/utilities/environment-facts.d.ts.map +1 -0
  392. package/dist/src/integrations/utilities/environment-facts.js +84 -0
  393. package/dist/src/integrations/utilities/environment-facts.js.map +1 -0
  394. package/dist/src/integrations/utilities/file-change-tracker.d.ts +162 -0
  395. package/dist/src/integrations/utilities/file-change-tracker.d.ts.map +1 -0
  396. package/dist/src/integrations/utilities/file-change-tracker.js +538 -0
  397. package/dist/src/integrations/utilities/file-change-tracker.js.map +1 -0
  398. package/dist/src/integrations/utilities/graph-visualization.d.ts +72 -0
  399. package/dist/src/integrations/utilities/graph-visualization.d.ts.map +1 -0
  400. package/dist/src/integrations/utilities/graph-visualization.js +383 -0
  401. package/dist/src/integrations/utilities/graph-visualization.js.map +1 -0
  402. package/dist/src/integrations/utilities/hierarchical-config.d.ts +215 -0
  403. package/dist/src/integrations/utilities/hierarchical-config.d.ts.map +1 -0
  404. package/dist/src/integrations/utilities/hierarchical-config.js +504 -0
  405. package/dist/src/integrations/utilities/hierarchical-config.js.map +1 -0
  406. package/dist/src/integrations/utilities/hooks.d.ts +116 -0
  407. package/dist/src/integrations/utilities/hooks.d.ts.map +1 -0
  408. package/dist/src/integrations/utilities/hooks.js +410 -0
  409. package/dist/src/integrations/utilities/hooks.js.map +1 -0
  410. package/dist/src/integrations/utilities/ignore.d.ts +143 -0
  411. package/dist/src/integrations/utilities/ignore.d.ts.map +1 -0
  412. package/dist/src/integrations/utilities/ignore.js +417 -0
  413. package/dist/src/integrations/utilities/ignore.js.map +1 -0
  414. package/dist/src/integrations/utilities/image-renderer.d.ts +119 -0
  415. package/dist/src/integrations/utilities/image-renderer.d.ts.map +1 -0
  416. package/dist/src/integrations/utilities/image-renderer.js +306 -0
  417. package/dist/src/integrations/utilities/image-renderer.js.map +1 -0
  418. package/dist/src/integrations/utilities/logger.d.ts +104 -0
  419. package/dist/src/integrations/utilities/logger.d.ts.map +1 -0
  420. package/dist/src/integrations/utilities/logger.js +219 -0
  421. package/dist/src/integrations/utilities/logger.js.map +1 -0
  422. package/dist/src/integrations/utilities/memory.d.ts +116 -0
  423. package/dist/src/integrations/utilities/memory.d.ts.map +1 -0
  424. package/dist/src/integrations/utilities/memory.js +311 -0
  425. package/dist/src/integrations/utilities/memory.js.map +1 -0
  426. package/dist/src/integrations/utilities/observability.d.ts +162 -0
  427. package/dist/src/integrations/utilities/observability.d.ts.map +1 -0
  428. package/dist/src/integrations/utilities/observability.js +407 -0
  429. package/dist/src/integrations/utilities/observability.js.map +1 -0
  430. package/dist/src/integrations/utilities/openrouter-pricing.d.ts +67 -0
  431. package/dist/src/integrations/utilities/openrouter-pricing.d.ts.map +1 -0
  432. package/dist/src/integrations/utilities/openrouter-pricing.js +166 -0
  433. package/dist/src/integrations/utilities/openrouter-pricing.js.map +1 -0
  434. package/dist/src/integrations/utilities/react.d.ts +139 -0
  435. package/dist/src/integrations/utilities/react.d.ts.map +1 -0
  436. package/dist/src/integrations/utilities/react.js +273 -0
  437. package/dist/src/integrations/utilities/react.js.map +1 -0
  438. package/dist/src/integrations/utilities/retry.d.ts +132 -0
  439. package/dist/src/integrations/utilities/retry.d.ts.map +1 -0
  440. package/dist/src/integrations/utilities/retry.js +233 -0
  441. package/dist/src/integrations/utilities/retry.js.map +1 -0
  442. package/dist/src/integrations/utilities/routing.d.ts +118 -0
  443. package/dist/src/integrations/utilities/routing.d.ts.map +1 -0
  444. package/dist/src/integrations/utilities/routing.js +348 -0
  445. package/dist/src/integrations/utilities/routing.js.map +1 -0
  446. package/dist/src/integrations/utilities/rules.d.ts +131 -0
  447. package/dist/src/integrations/utilities/rules.d.ts.map +1 -0
  448. package/dist/src/integrations/utilities/rules.js +284 -0
  449. package/dist/src/integrations/utilities/rules.js.map +1 -0
  450. package/dist/src/integrations/utilities/sourcegraph.d.ts +169 -0
  451. package/dist/src/integrations/utilities/sourcegraph.d.ts.map +1 -0
  452. package/dist/src/integrations/utilities/sourcegraph.js +379 -0
  453. package/dist/src/integrations/utilities/sourcegraph.js.map +1 -0
  454. package/dist/src/integrations/utilities/thinking-strategy.d.ts +52 -0
  455. package/dist/src/integrations/utilities/thinking-strategy.d.ts.map +1 -0
  456. package/dist/src/integrations/utilities/thinking-strategy.js +129 -0
  457. package/dist/src/integrations/utilities/thinking-strategy.js.map +1 -0
  458. package/dist/src/integrations/utilities/thread-manager.d.ts +199 -0
  459. package/dist/src/integrations/utilities/thread-manager.d.ts.map +1 -0
  460. package/dist/src/integrations/utilities/thread-manager.js +357 -0
  461. package/dist/src/integrations/utilities/thread-manager.js.map +1 -0
  462. package/dist/src/integrations/utilities/token-estimate.d.ts +11 -0
  463. package/dist/src/integrations/utilities/token-estimate.d.ts.map +1 -0
  464. package/dist/src/integrations/utilities/token-estimate.js +14 -0
  465. package/dist/src/integrations/utilities/token-estimate.js.map +1 -0
  466. package/dist/src/main.js +10 -4
  467. package/dist/src/main.js.map +1 -1
  468. package/dist/src/modes/repl.d.ts.map +1 -1
  469. package/dist/src/modes/repl.js +22 -5
  470. package/dist/src/modes/repl.js.map +1 -1
  471. package/dist/src/modes/tui.d.ts.map +1 -1
  472. package/dist/src/modes/tui.js +23 -6
  473. package/dist/src/modes/tui.js.map +1 -1
  474. package/dist/src/modes.js +1 -1
  475. package/dist/src/modes.js.map +1 -1
  476. package/dist/src/observability/tracer.js +1 -1
  477. package/dist/src/observability/tracer.js.map +1 -1
  478. package/dist/src/persistence/schema.d.ts +2 -0
  479. package/dist/src/persistence/schema.d.ts.map +1 -1
  480. package/dist/src/persistence/schema.js +31 -0
  481. package/dist/src/persistence/schema.js.map +1 -1
  482. package/dist/src/providers/adapters/anthropic.d.ts +6 -0
  483. package/dist/src/providers/adapters/anthropic.d.ts.map +1 -1
  484. package/dist/src/providers/adapters/anthropic.js +99 -15
  485. package/dist/src/providers/adapters/anthropic.js.map +1 -1
  486. package/dist/src/providers/adapters/azure.d.ts +74 -0
  487. package/dist/src/providers/adapters/azure.d.ts.map +1 -0
  488. package/dist/src/providers/adapters/azure.js +354 -0
  489. package/dist/src/providers/adapters/azure.js.map +1 -0
  490. package/dist/src/providers/adapters/mock.d.ts +16 -2
  491. package/dist/src/providers/adapters/mock.d.ts.map +1 -1
  492. package/dist/src/providers/adapters/mock.js +44 -3
  493. package/dist/src/providers/adapters/mock.js.map +1 -1
  494. package/dist/src/providers/adapters/openai.d.ts +6 -1
  495. package/dist/src/providers/adapters/openai.d.ts.map +1 -1
  496. package/dist/src/providers/adapters/openai.js +39 -8
  497. package/dist/src/providers/adapters/openai.js.map +1 -1
  498. package/dist/src/providers/adapters/openrouter.d.ts +6 -0
  499. package/dist/src/providers/adapters/openrouter.d.ts.map +1 -1
  500. package/dist/src/providers/adapters/openrouter.js +73 -3
  501. package/dist/src/providers/adapters/openrouter.js.map +1 -1
  502. package/dist/src/providers/provider.js +1 -1
  503. package/dist/src/providers/provider.js.map +1 -1
  504. package/dist/src/providers/resilient-provider.js +1 -1
  505. package/dist/src/providers/resilient-provider.js.map +1 -1
  506. package/dist/src/providers/types.d.ts +23 -2
  507. package/dist/src/providers/types.d.ts.map +1 -1
  508. package/dist/src/session-picker.d.ts +1 -1
  509. package/dist/src/session-picker.d.ts.map +1 -1
  510. package/dist/src/session-picker.js +1 -1
  511. package/dist/src/session-picker.js.map +1 -1
  512. package/dist/src/shared/budget-tracker.js +1 -1
  513. package/dist/src/shared/budget-tracker.js.map +1 -1
  514. package/dist/src/tools/agent.d.ts +1 -1
  515. package/dist/src/tools/agent.d.ts.map +1 -1
  516. package/dist/src/tools/bash.js +1 -1
  517. package/dist/src/tools/bash.js.map +1 -1
  518. package/dist/src/tools/file.js +1 -1
  519. package/dist/src/tools/file.js.map +1 -1
  520. package/dist/src/tools/permission.js +2 -2
  521. package/dist/src/tools/permission.js.map +1 -1
  522. package/dist/src/tools/registry.d.ts +1 -1
  523. package/dist/src/tools/registry.d.ts.map +1 -1
  524. package/dist/src/tools/registry.js +1 -1
  525. package/dist/src/tools/registry.js.map +1 -1
  526. package/dist/src/tools/tasks.d.ts +1 -1
  527. package/dist/src/tools/tasks.d.ts.map +1 -1
  528. package/dist/src/tools/undo.d.ts +1 -1
  529. package/dist/src/tools/undo.d.ts.map +1 -1
  530. package/dist/src/tracing/cache-boundary-tracker.d.ts.map +1 -1
  531. package/dist/src/tracing/cache-boundary-tracker.js +2 -2
  532. package/dist/src/tracing/cache-boundary-tracker.js.map +1 -1
  533. package/dist/src/tracing/trace-collector.d.ts +22 -0
  534. package/dist/src/tracing/trace-collector.d.ts.map +1 -1
  535. package/dist/src/tracing/trace-collector.js +27 -3
  536. package/dist/src/tracing/trace-collector.js.map +1 -1
  537. package/dist/src/tracing/types.d.ts +17 -1
  538. package/dist/src/tracing/types.d.ts.map +1 -1
  539. package/dist/src/tracing/types.js.map +1 -1
  540. package/dist/src/tricks/failure-evidence.js +1 -1
  541. package/dist/src/tricks/failure-evidence.js.map +1 -1
  542. package/dist/src/tricks/recitation.d.ts.map +1 -1
  543. package/dist/src/tricks/recitation.js +2 -1
  544. package/dist/src/tricks/recitation.js.map +1 -1
  545. package/dist/src/tricks/recursive-context.d.ts.map +1 -1
  546. package/dist/src/tricks/recursive-context.js +2 -2
  547. package/dist/src/tricks/recursive-context.js.map +1 -1
  548. package/dist/src/tricks/reversible-compaction.d.ts.map +1 -1
  549. package/dist/src/tricks/reversible-compaction.js +6 -2
  550. package/dist/src/tricks/reversible-compaction.js.map +1 -1
  551. package/dist/src/tui/app.d.ts +3 -3
  552. package/dist/src/tui/app.d.ts.map +1 -1
  553. package/dist/src/tui/app.js +86 -14
  554. package/dist/src/tui/app.js.map +1 -1
  555. package/dist/src/tui/components/CollapsibleDiffView.d.ts +1 -1
  556. package/dist/src/tui/components/CollapsibleDiffView.d.ts.map +1 -1
  557. package/dist/src/tui/components/DiagnosticsPanel.d.ts +24 -0
  558. package/dist/src/tui/components/DiagnosticsPanel.d.ts.map +1 -0
  559. package/dist/src/tui/components/DiagnosticsPanel.js +47 -0
  560. package/dist/src/tui/components/DiagnosticsPanel.js.map +1 -0
  561. package/dist/src/tui/components/DiffView.d.ts +1 -1
  562. package/dist/src/tui/components/DiffView.d.ts.map +1 -1
  563. package/dist/src/tui/components/ErrorBoundary.js +1 -1
  564. package/dist/src/tui/components/ErrorBoundary.js.map +1 -1
  565. package/dist/src/tui/components/TasksPanel.d.ts +1 -1
  566. package/dist/src/tui/components/TasksPanel.d.ts.map +1 -1
  567. package/dist/src/tui/event-display.js +1 -1
  568. package/dist/src/tui/event-display.js.map +1 -1
  569. package/dist/src/tui/index.js +1 -1
  570. package/dist/src/tui/index.js.map +1 -1
  571. package/dist/src/tui/transparency-aggregator.d.ts +13 -0
  572. package/dist/src/tui/transparency-aggregator.d.ts.map +1 -1
  573. package/dist/src/tui/transparency-aggregator.js +21 -0
  574. package/dist/src/tui/transparency-aggregator.js.map +1 -1
  575. package/dist/src/types.d.ts +27 -2
  576. package/dist/src/types.d.ts.map +1 -1
  577. package/package.json +1 -1
package/dist/src/agent.js CHANGED
@@ -19,19 +19,13 @@
19
19
  * - Thread Management (Lesson 24)
20
20
  */
21
21
  import * as path from 'node:path';
22
- import { buildConfig, isFeatureEnabled, getEnabledFeatures, } from './defaults.js';
22
+ import { buildConfig, isFeatureEnabled, } from './defaults.js';
23
23
  import { createModeManager, formatModeList, parseMode, } from './modes.js';
24
24
  import { createLSPFileTools, } from './agent-tools/index.js';
25
- import { HookManager, MemoryManager, PlanningManager, ObservabilityManager, SafetyManager, RoutingManager, MultiAgentManager, ReActManager, ExecutionPolicyManager, ThreadManager, RulesManager, DEFAULT_RULE_SOURCES, ExecutionEconomicsManager, STANDARD_BUDGET, AgentRegistry, formatAgentList, createCancellationManager, isCancellationError, createResourceManager, createLSPManager, createSemanticCacheManager, createSkillManager, formatSkillList, createContextEngineering, createCodebaseContext, buildContextFromChunks, generateLightweightRepoMap, createSharedFileCache, createBudgetPool, createPendingPlanManager, createInteractivePlanner, createRecursiveContext, createLearningStore, createCompactor, createAutoCompactionManager, createFileChangeTracker, createCapabilitiesRegistry, createSharedBlackboard, createTaskManager, createSwarmOrchestrator, createThrottledProvider, FREE_TIER_THROTTLE, PAID_TIER_THROTTLE, createWorkLog, createVerificationGate, classifyComplexity, getScalingGuidance, createToolRecommendationEngine, createInjectionBudgetManager, getThinkingSystemPrompt, createSelfImprovementProtocol, createSubagentOutputStore, createSerperSearchTool, getEnvironmentFacts, formatFactsBlock, createAutoCheckpointManager, } from './integrations/index.js';
26
- import { resolvePolicyProfile, } from './integrations/policy-engine.js';
27
- import { createTraceCollector } from './tracing/trace-collector.js';
25
+ import { STANDARD_BUDGET, formatAgentList, isCancellationError, formatSkillList, createSharedFileCache, createBudgetPool, createPendingPlanManager, createFileChangeTracker, createCapabilitiesRegistry, createSharedBlackboard, classifyComplexity, } from './integrations/index.js';
28
26
  import { modelRegistry } from './costs/index.js';
29
- import { getModelContextLength } from './integrations/openrouter-pricing.js';
30
- import { createComponentLogger } from './integrations/logger.js';
31
- // Spawn agent tools for LLM-driven subagent delegation
32
- import { createBoundSpawnAgentTool, createBoundSpawnAgentsParallelTool, } from './tools/agent.js';
33
- // Task tools for Claude Code-style task management
34
- import { createTaskTools, } from './tools/tasks.js';
27
+ import { getModelContextLength } from './integrations/utilities/openrouter-pricing.js';
28
+ import { createComponentLogger } from './integrations/utilities/logger.js';
35
29
  // =============================================================================
36
30
  // PRODUCTION AGENT
37
31
  // =============================================================================
@@ -45,9 +39,13 @@ import { PARALLELIZABLE_TOOLS, CONDITIONALLY_PARALLEL_TOOLS, extractToolFilePath
45
39
  export { PARALLELIZABLE_TOOLS, CONDITIONALLY_PARALLEL_TOOLS, extractToolFilePath, groupToolCallsIntoBatches };
46
40
  // Extracted core modules (Phase 2.1 — thin orchestrator delegates)
47
41
  import { executeDirectly as coreExecuteDirectly, spawnAgent as coreSpawnAgent, spawnAgentsParallel as coreSpawnAgentsParallel, } from './core/index.js';
48
- // Phase 2.2: Agent State Machine
49
- import { createAgentStateMachine } from './core/agent-state-machine.js';
50
42
  import { detectIncompleteActionResponse } from './core/completion-analyzer.js';
43
+ // Feature initialization (extracted from initializeFeatures method)
44
+ import { initializeFeatures as doInitializeFeatures } from './agent/feature-initializer.js';
45
+ // Message builder (extracted from buildMessages method)
46
+ import { buildMessages as doBuildMessages } from './agent/message-builder.js';
47
+ // Session/checkpoint/file-change API (extracted from ProductionAgent methods)
48
+ import { trackFileChange as doTrackFileChange, undoLastFileChange as doUndoLastFileChange, undoCurrentTurn as doUndoCurrentTurn, reset as doReset, loadMessages as doLoadMessages, getSerializableState as doGetSerializableState, validateCheckpoint as doValidateCheckpoint, loadState as doLoadState, } from './agent/session-api.js';
51
49
  /**
52
50
  * Production-ready agent that composes all features.
53
51
  */
@@ -99,6 +97,7 @@ export class ProductionAgent {
99
97
  swarmOrchestrator = null;
100
98
  workLog = null;
101
99
  verificationGate = null;
100
+ typeCheckerState = null;
102
101
  // Phase 2-4 integration modules
103
102
  injectionBudget = null;
104
103
  selfImprovement = null;
@@ -209,638 +208,10 @@ export class ProductionAgent {
209
208
  }
210
209
  /**
211
210
  * Initialize all enabled features.
211
+ * Delegates to the extracted feature-initializer module.
212
212
  */
213
213
  initializeFeatures() {
214
- // Debug output only when DEBUG env var is set
215
- if (process.env.DEBUG) {
216
- const features = getEnabledFeatures(this.config);
217
- log.debug('Initializing with features', { features: features.join(', ') });
218
- }
219
- // Hooks & Plugins
220
- if (isFeatureEnabled(this.config.hooks) && isFeatureEnabled(this.config.plugins)) {
221
- this.hooks = new HookManager(this.config.hooks, this.config.plugins);
222
- }
223
- // Memory
224
- if (isFeatureEnabled(this.config.memory)) {
225
- this.memory = new MemoryManager(this.config.memory);
226
- }
227
- // Planning & Reflection
228
- if (isFeatureEnabled(this.config.planning) && isFeatureEnabled(this.config.reflection)) {
229
- this.planning = new PlanningManager(this.config.planning, this.config.reflection);
230
- }
231
- // Observability
232
- if (isFeatureEnabled(this.config.observability)) {
233
- this.observability = new ObservabilityManager(this.config.observability);
234
- // Lesson 26: Full trace capture
235
- const traceCaptureConfig = this.config.observability.traceCapture;
236
- if (traceCaptureConfig?.enabled) {
237
- this.traceCollector = createTraceCollector({
238
- enabled: true,
239
- outputDir: traceCaptureConfig.outputDir ?? '.traces',
240
- captureMessageContent: traceCaptureConfig.captureMessageContent ?? true,
241
- captureToolResults: traceCaptureConfig.captureToolResults ?? true,
242
- analyzeCacheBoundaries: traceCaptureConfig.analyzeCacheBoundaries ?? true,
243
- filePattern: traceCaptureConfig.filePattern ?? 'trace-{sessionId}-{timestamp}.jsonl',
244
- enableConsoleOutput: false,
245
- });
246
- }
247
- }
248
- // Safety (Sandbox + Human-in-Loop)
249
- if (isFeatureEnabled(this.config.sandbox) || isFeatureEnabled(this.config.humanInLoop)) {
250
- this.safety = new SafetyManager(isFeatureEnabled(this.config.sandbox) ? this.config.sandbox : false, isFeatureEnabled(this.config.humanInLoop) ? this.config.humanInLoop : false, isFeatureEnabled(this.config.policyEngine) ? this.config.policyEngine : false);
251
- }
252
- if (isFeatureEnabled(this.config.policyEngine)) {
253
- const rootPolicy = resolvePolicyProfile({
254
- policyEngine: this.config.policyEngine,
255
- sandboxConfig: isFeatureEnabled(this.config.sandbox) ? this.config.sandbox : undefined,
256
- });
257
- this.emit({
258
- type: 'policy.profile.resolved',
259
- profile: rootPolicy.profileName,
260
- context: 'root',
261
- selectionSource: rootPolicy.metadata.selectionSource,
262
- usedLegacyMappings: rootPolicy.metadata.usedLegacyMappings,
263
- legacySources: rootPolicy.metadata.legacyMappingSources,
264
- });
265
- if (rootPolicy.metadata.usedLegacyMappings) {
266
- this.emit({
267
- type: 'policy.legacy.fallback.used',
268
- profile: rootPolicy.profileName,
269
- sources: rootPolicy.metadata.legacyMappingSources,
270
- warnings: rootPolicy.metadata.warnings,
271
- });
272
- }
273
- }
274
- // Routing
275
- if (isFeatureEnabled(this.config.routing)) {
276
- this.routing = new RoutingManager(this.config.routing);
277
- }
278
- // Multi-Agent (Lesson 17)
279
- if (isFeatureEnabled(this.config.multiAgent)) {
280
- const roles = (this.config.multiAgent.roles || []).map((r) => ({
281
- name: r.name,
282
- description: r.description,
283
- systemPrompt: r.systemPrompt,
284
- capabilities: r.capabilities,
285
- authority: r.authority,
286
- model: r.model,
287
- }));
288
- this.multiAgent = new MultiAgentManager(this.provider, Array.from(this.tools.values()), roles);
289
- }
290
- // ReAct (Lesson 18)
291
- if (isFeatureEnabled(this.config.react)) {
292
- this.react = new ReActManager(this.provider, Array.from(this.tools.values()), {
293
- maxSteps: this.config.react.maxSteps,
294
- stopOnAnswer: this.config.react.stopOnAnswer,
295
- includeReasoning: this.config.react.includeReasoning,
296
- });
297
- }
298
- // Execution Policies (Lesson 23)
299
- if (isFeatureEnabled(this.config.executionPolicy)) {
300
- this.executionPolicy = new ExecutionPolicyManager({
301
- defaultPolicy: this.config.executionPolicy.defaultPolicy,
302
- toolPolicies: this.config.executionPolicy.toolPolicies,
303
- intentAware: this.config.executionPolicy.intentAware,
304
- intentConfidenceThreshold: this.config.executionPolicy.intentConfidenceThreshold,
305
- });
306
- }
307
- // Thread Management (Lesson 24)
308
- if (isFeatureEnabled(this.config.threads)) {
309
- this.threadManager = new ThreadManager();
310
- }
311
- // Rules System (Lesson 12)
312
- if (isFeatureEnabled(this.config.rules)) {
313
- const ruleSources = this.config.rules.sources || DEFAULT_RULE_SOURCES;
314
- this.rules = new RulesManager({
315
- enabled: true,
316
- sources: ruleSources,
317
- watch: this.config.rules.watch,
318
- });
319
- // Load rules asynchronously - tracked for ensureReady()
320
- this.initPromises.push(this.rules.loadRules().catch(err => {
321
- log.warn('Failed to load rules', { error: String(err) });
322
- }));
323
- }
324
- // Economics System (Token Budget) - always enabled
325
- // Use custom budget if provided (subagents use SUBAGENT_BUDGET), otherwise STANDARD_BUDGET
326
- const baseBudget = this.config.budget ?? STANDARD_BUDGET;
327
- this.economics = new ExecutionEconomicsManager({
328
- ...baseBudget,
329
- // Use maxIterations from config as absolute safety cap
330
- maxIterations: this.config.maxIterations,
331
- targetIterations: Math.min(baseBudget.targetIterations ?? 20, this.config.maxIterations),
332
- }, this._sharedEconomicsState ?? undefined, this.agentId);
333
- // Phase 2.2: Agent State Machine - formalizes phase tracking
334
- // Always enabled - provides structured phase transitions with metrics
335
- this.stateMachine = createAgentStateMachine();
336
- // Forward state machine phase transitions as subagent.phase events
337
- const phaseMap = {
338
- exploring: 'exploring', planning: 'planning', acting: 'executing', verifying: 'completing',
339
- };
340
- const unsubStateMachine = this.stateMachine.subscribe(event => {
341
- if (event.type === 'phase.changed') {
342
- this.emit({
343
- type: 'subagent.phase',
344
- agentId: this.agentId,
345
- phase: phaseMap[event.transition.to] ?? 'exploring',
346
- });
347
- }
348
- });
349
- this.unsubscribers.push(unsubStateMachine);
350
- // Work Log - compaction-resilient summary of agent work
351
- // Always enabled - minimal overhead and critical for long-running tasks
352
- this.workLog = createWorkLog();
353
- // Verification Gate - opt-in completion verification
354
- if (this.config.verificationCriteria) {
355
- this.verificationGate = createVerificationGate(this.config.verificationCriteria);
356
- }
357
- // Phase 2-4: Orchestration & Advanced modules (always enabled, lightweight)
358
- this.injectionBudget = createInjectionBudgetManager();
359
- this.selfImprovement = createSelfImprovementProtocol(undefined, this.learningStore ?? undefined);
360
- this.subagentOutputStore = createSubagentOutputStore({ persistToFile: false });
361
- this.autoCheckpointManager = createAutoCheckpointManager({ enabled: true });
362
- this.toolRecommendation = createToolRecommendationEngine();
363
- // Agent Registry - always enabled for subagent support
364
- this.agentRegistry = new AgentRegistry();
365
- // Load user agents asynchronously - tracked for ensureReady()
366
- this.initPromises.push(this.agentRegistry.loadUserAgents().catch(err => {
367
- log.warn('Failed to load user agents', { error: String(err) });
368
- }));
369
- // Register spawn_agent tool so LLM can delegate to subagents
370
- const boundSpawnTool = createBoundSpawnAgentTool((name, task, constraints) => this.spawnAgent(name, task, constraints));
371
- this.tools.set(boundSpawnTool.name, boundSpawnTool);
372
- // Register spawn_agents_parallel tool for parallel subagent execution
373
- const boundParallelSpawnTool = createBoundSpawnAgentsParallelTool((tasks) => this.spawnAgentsParallel(tasks));
374
- this.tools.set(boundParallelSpawnTool.name, boundParallelSpawnTool);
375
- // Task Manager - Claude Code-style task system for coordination
376
- this.taskManager = createTaskManager();
377
- // Forward task events (with cleanup tracking for EventEmitter-based managers)
378
- const taskCreatedHandler = (data) => {
379
- this.emit({ type: 'task.created', task: data.task });
380
- };
381
- this.taskManager.on('task.created', taskCreatedHandler);
382
- this.unsubscribers.push(() => this.taskManager?.off('task.created', taskCreatedHandler));
383
- const taskUpdatedHandler = (data) => {
384
- this.emit({ type: 'task.updated', task: data.task });
385
- };
386
- this.taskManager.on('task.updated', taskUpdatedHandler);
387
- this.unsubscribers.push(() => this.taskManager?.off('task.updated', taskUpdatedHandler));
388
- // Register task tools
389
- const taskTools = createTaskTools(this.taskManager);
390
- for (const tool of taskTools) {
391
- this.tools.set(tool.name, tool);
392
- }
393
- // Built-in web search (Serper API) — gracefully handles missing API key
394
- const serperCustomTool = createSerperSearchTool();
395
- this.tools.set('web_search', {
396
- name: serperCustomTool.name,
397
- description: serperCustomTool.description,
398
- parameters: serperCustomTool.inputSchema,
399
- execute: serperCustomTool.execute,
400
- dangerLevel: 'safe',
401
- });
402
- // Swarm Mode (experimental)
403
- if (this.config.swarm) {
404
- const swarmConfig = this.config.swarm;
405
- // Wrap provider with request throttle to prevent 429 rate limiting.
406
- // All subagents share this.provider by reference (line 4398),
407
- // so wrapping here throttles ALL downstream LLM calls.
408
- if (swarmConfig.throttle !== false) {
409
- const throttleConfig = swarmConfig.throttle === 'paid'
410
- ? PAID_TIER_THROTTLE
411
- : swarmConfig.throttle === 'free' || swarmConfig.throttle === undefined
412
- ? FREE_TIER_THROTTLE
413
- : swarmConfig.throttle;
414
- this.provider = createThrottledProvider(this.provider, throttleConfig);
415
- }
416
- // Pass codebaseContext so the decomposer can ground tasks in actual project files
417
- swarmConfig.codebaseContext = this.codebaseContext ?? undefined;
418
- this.swarmOrchestrator = createSwarmOrchestrator(swarmConfig, this.provider, this.agentRegistry, (name, task) => this.spawnAgent(name, task), this.blackboard ?? undefined);
419
- // Override parent budget pool with swarm's much larger pool so spawnAgent()
420
- // allocates from the swarm budget (e.g. 10M tokens) instead of the parent's
421
- // generic pool (200K tokens). Without this, workers get 5K emergency budget.
422
- this.budgetPool = this.swarmOrchestrator.getBudgetPool().pool;
423
- // Phase 3.1+3.2: Set shared state so workers inherit it via buildContext()
424
- this._sharedContextState = this.swarmOrchestrator.getSharedContextState();
425
- this._sharedEconomicsState = this.swarmOrchestrator.getSharedEconomicsState();
426
- }
427
- // Cancellation Support
428
- if (isFeatureEnabled(this.config.cancellation)) {
429
- this.cancellation = createCancellationManager();
430
- // Forward cancellation events (with cleanup tracking)
431
- const unsubCancellation = this.cancellation.subscribe(event => {
432
- if (event.type === 'cancellation.requested') {
433
- this.emit({ type: 'cancellation.requested', reason: event.reason });
434
- }
435
- });
436
- this.unsubscribers.push(unsubCancellation);
437
- }
438
- // Resource Monitoring
439
- if (isFeatureEnabled(this.config.resources)) {
440
- this.resourceManager = createResourceManager({
441
- enabled: this.config.resources.enabled,
442
- maxMemoryMB: this.config.resources.maxMemoryMB,
443
- maxCpuTimeSec: this.config.resources.maxCpuTimeSec,
444
- maxConcurrentOps: this.config.resources.maxConcurrentOps,
445
- warnThreshold: this.config.resources.warnThreshold,
446
- criticalThreshold: this.config.resources.criticalThreshold,
447
- });
448
- }
449
- // LSP (Language Server Protocol) Support
450
- if (isFeatureEnabled(this.config.lsp)) {
451
- this.lspManager = createLSPManager({
452
- enabled: this.config.lsp.enabled,
453
- autoDetect: this.config.lsp.autoDetect,
454
- servers: this.config.lsp.servers,
455
- timeout: this.config.lsp.timeout,
456
- });
457
- // Auto-start is done lazily on first use to avoid startup delays
458
- }
459
- // Semantic Cache Support
460
- if (isFeatureEnabled(this.config.semanticCache)) {
461
- this.semanticCache = createSemanticCacheManager({
462
- enabled: this.config.semanticCache.enabled,
463
- threshold: this.config.semanticCache.threshold,
464
- maxSize: this.config.semanticCache.maxSize,
465
- ttl: this.config.semanticCache.ttl,
466
- });
467
- // Forward cache events (with cleanup tracking)
468
- const unsubSemanticCache = this.semanticCache.subscribe(event => {
469
- if (event.type === 'cache.hit') {
470
- this.emit({ type: 'cache.hit', query: event.query, similarity: event.similarity });
471
- }
472
- else if (event.type === 'cache.miss') {
473
- this.emit({ type: 'cache.miss', query: event.query });
474
- }
475
- else if (event.type === 'cache.set') {
476
- this.emit({ type: 'cache.set', query: event.query });
477
- }
478
- });
479
- this.unsubscribers.push(unsubSemanticCache);
480
- }
481
- // Skills Support
482
- if (isFeatureEnabled(this.config.skills)) {
483
- this.skillManager = createSkillManager({
484
- enabled: this.config.skills.enabled,
485
- directories: this.config.skills.directories,
486
- loadBuiltIn: this.config.skills.loadBuiltIn,
487
- autoActivate: this.config.skills.autoActivate,
488
- });
489
- // Load skills asynchronously - tracked for ensureReady()
490
- this.initPromises.push(this.skillManager.loadSkills()
491
- .then(() => { }) // Convert to void
492
- .catch(err => {
493
- log.warn('Failed to load skills', { error: String(err) });
494
- }));
495
- }
496
- // Context Engineering (Manus-inspired tricks P, Q, R, S, T)
497
- // Always enabled - these are performance optimizations
498
- this.contextEngineering = createContextEngineering({
499
- enableCacheOptimization: true,
500
- enableRecitation: true,
501
- enableReversibleCompaction: true,
502
- enableFailureTracking: true,
503
- enableDiversity: false, // Off by default - can cause unexpected behavior
504
- staticPrefix: this.config.systemPrompt,
505
- recitationFrequency: 5,
506
- maxFailures: 30,
507
- maxReferences: 50,
508
- });
509
- // Bind shared context state for cross-worker failure learning (swarm workers only)
510
- if (this._sharedContextState) {
511
- this.contextEngineering.setSharedState(this._sharedContextState);
512
- }
513
- // Codebase Context - intelligent code selection for context management
514
- // Analyzes repo structure and selects relevant code within token budgets
515
- if (this.config.codebaseContext !== false) {
516
- const codebaseConfig = typeof this.config.codebaseContext === 'object'
517
- ? this.config.codebaseContext
518
- : {};
519
- this.codebaseContext = createCodebaseContext({
520
- root: codebaseConfig.root ?? process.cwd(),
521
- includePatterns: codebaseConfig.includePatterns,
522
- excludePatterns: codebaseConfig.excludePatterns,
523
- maxFileSize: codebaseConfig.maxFileSize ?? 100 * 1024, // 100KB
524
- tokensPerChar: 0.25,
525
- analyzeDependencies: true,
526
- cacheResults: true,
527
- cacheTTL: 5 * 60 * 1000, // 5 minutes
528
- });
529
- // Forward trace collector so codebase analysis can emit codebase.map entries.
530
- if (this.traceCollector) {
531
- this.codebaseContext.traceCollector = this.traceCollector;
532
- }
533
- // Connect LSP manager to codebase context for enhanced code selection
534
- // This enables LSP-based relevance boosting (Phase 4.1)
535
- if (this.lspManager) {
536
- this.codebaseContext.setLSPManager(this.lspManager);
537
- }
538
- }
539
- // Forward context engineering events (with cleanup tracking)
540
- const unsubContextEngineering = this.contextEngineering.on(event => {
541
- switch (event.type) {
542
- case 'failure.recorded':
543
- this.observability?.logger?.warn('Failure recorded', {
544
- action: event.failure.action,
545
- category: event.failure.category,
546
- });
547
- break;
548
- case 'failure.pattern':
549
- this.observability?.logger?.warn('Failure pattern detected', {
550
- type: event.pattern.type,
551
- description: event.pattern.description,
552
- });
553
- this.emit({ type: 'error', error: `Pattern: ${event.pattern.description}` });
554
- break;
555
- case 'recitation.injected':
556
- this.observability?.logger?.debug('Recitation injected', {
557
- iteration: event.iteration,
558
- });
559
- break;
560
- }
561
- });
562
- this.unsubscribers.push(unsubContextEngineering);
563
- // Interactive Planning (conversational + editable planning)
564
- if (isFeatureEnabled(this.config.interactivePlanning)) {
565
- const interactiveConfig = typeof this.config.interactivePlanning === 'object'
566
- ? this.config.interactivePlanning
567
- : {};
568
- this.interactivePlanner = createInteractivePlanner({
569
- autoCheckpoint: interactiveConfig.enableCheckpoints ?? true,
570
- confirmBeforeExecute: interactiveConfig.requireApproval ?? true,
571
- maxCheckpoints: 20,
572
- autoPauseAtDecisions: true,
573
- });
574
- // Forward planner events to observability (with cleanup tracking)
575
- const unsubInteractivePlanner = this.interactivePlanner.on(event => {
576
- switch (event.type) {
577
- case 'plan.created':
578
- this.observability?.logger?.info('Interactive plan created', {
579
- planId: event.plan.id,
580
- stepCount: event.plan.steps.length,
581
- });
582
- break;
583
- case 'step.completed':
584
- this.observability?.logger?.debug('Plan step completed', {
585
- stepId: event.step.id,
586
- status: event.step.status,
587
- });
588
- break;
589
- case 'plan.cancelled':
590
- this.observability?.logger?.info('Plan cancelled', { reason: event.reason });
591
- break;
592
- case 'checkpoint.created':
593
- this.observability?.logger?.debug('Plan checkpoint created', {
594
- checkpointId: event.checkpoint.id,
595
- });
596
- break;
597
- }
598
- });
599
- this.unsubscribers.push(unsubInteractivePlanner);
600
- }
601
- // Recursive Context (RLM - Recursive Language Models)
602
- // Enables on-demand context exploration for large codebases
603
- if (isFeatureEnabled(this.config.recursiveContext)) {
604
- const recursiveConfig = typeof this.config.recursiveContext === 'object'
605
- ? this.config.recursiveContext
606
- : {};
607
- this.recursiveContext = createRecursiveContext({
608
- maxDepth: recursiveConfig.maxRecursionDepth ?? 5,
609
- snippetTokens: recursiveConfig.maxSnippetTokens ?? 2000,
610
- synthesisTokens: 1000,
611
- totalBudget: 50000,
612
- cacheResults: recursiveConfig.cacheNavigationResults ?? true,
613
- });
614
- // Note: File system source should be registered when needed with proper glob/readFile functions
615
- // This is deferred to allow flexible configuration
616
- // Forward RLM events (with cleanup tracking)
617
- const unsubRecursiveContext = this.recursiveContext.on(event => {
618
- switch (event.type) {
619
- case 'process.started':
620
- this.observability?.logger?.debug('RLM process started', {
621
- query: event.query,
622
- depth: event.depth,
623
- });
624
- break;
625
- case 'navigation.command':
626
- this.observability?.logger?.debug('RLM navigation command', {
627
- command: event.command,
628
- depth: event.depth,
629
- });
630
- break;
631
- case 'process.completed':
632
- this.observability?.logger?.debug('RLM process completed', {
633
- stats: event.stats,
634
- });
635
- break;
636
- case 'budget.warning':
637
- this.observability?.logger?.warn('RLM budget warning', {
638
- remaining: event.remaining,
639
- total: event.total,
640
- });
641
- break;
642
- }
643
- });
644
- this.unsubscribers.push(unsubRecursiveContext);
645
- }
646
- // Learning Store (cross-session learning from failures)
647
- // Connects to the failure tracker in contextEngineering for automatic learning extraction
648
- if (isFeatureEnabled(this.config.learningStore)) {
649
- const learningConfig = typeof this.config.learningStore === 'object'
650
- ? this.config.learningStore
651
- : {};
652
- this.learningStore = createLearningStore({
653
- dbPath: learningConfig.dbPath ?? '.agent/learnings.db',
654
- requireValidation: learningConfig.requireValidation ?? true,
655
- autoValidateThreshold: learningConfig.autoValidateThreshold ?? 0.9,
656
- maxLearnings: learningConfig.maxLearnings ?? 500,
657
- });
658
- // Connect to the failure tracker if available
659
- if (this.contextEngineering) {
660
- const failureTracker = this.contextEngineering.getFailureTracker();
661
- if (failureTracker) {
662
- this.learningStore.connectFailureTracker(failureTracker);
663
- }
664
- }
665
- // Forward learning events to observability (with cleanup tracking)
666
- const unsubLearningStore = this.learningStore.on(event => {
667
- switch (event.type) {
668
- case 'learning.proposed':
669
- this.observability?.logger?.info('Learning proposed', {
670
- learningId: event.learning.id,
671
- description: event.learning.description,
672
- });
673
- this.emit({
674
- type: 'learning.proposed',
675
- learningId: event.learning.id,
676
- description: event.learning.description,
677
- });
678
- break;
679
- case 'learning.validated':
680
- this.observability?.logger?.info('Learning validated', {
681
- learningId: event.learningId,
682
- });
683
- this.emit({ type: 'learning.validated', learningId: event.learningId });
684
- break;
685
- case 'learning.applied':
686
- this.observability?.logger?.debug('Learning applied', {
687
- learningId: event.learningId,
688
- context: event.context,
689
- });
690
- this.emit({
691
- type: 'learning.applied',
692
- learningId: event.learningId,
693
- context: event.context,
694
- });
695
- break;
696
- case 'pattern.extracted':
697
- this.observability?.logger?.info('Pattern extracted as learning', {
698
- pattern: event.pattern.description,
699
- learningId: event.learning.id,
700
- });
701
- break;
702
- }
703
- });
704
- this.unsubscribers.push(unsubLearningStore);
705
- }
706
- // Auto-Compaction Manager (sophisticated context compaction)
707
- // Uses the Compactor for LLM-based summarization with threshold monitoring
708
- if (isFeatureEnabled(this.config.compaction)) {
709
- const compactionConfig = typeof this.config.compaction === 'object'
710
- ? this.config.compaction
711
- : {};
712
- // Create the compactor (requires provider for LLM summarization)
713
- this.compactor = createCompactor(this.provider, {
714
- enabled: true,
715
- tokenThreshold: compactionConfig.tokenThreshold ?? 80000,
716
- preserveRecentCount: compactionConfig.preserveRecentCount ?? 10,
717
- preserveToolResults: compactionConfig.preserveToolResults ?? true,
718
- summaryMaxTokens: compactionConfig.summaryMaxTokens ?? 2000,
719
- summaryModel: compactionConfig.summaryModel,
720
- });
721
- // Create the auto-compaction manager with threshold monitoring
722
- // Wire reversible compaction through contextEngineering when available
723
- const compactHandler = this.contextEngineering
724
- ? async (messages) => {
725
- // Use contextEngineering's reversible compaction to preserve references
726
- const summarize = async (msgs) => {
727
- // Use the basic compactor's summarization capability
728
- const result = await this.compactor.compact(msgs);
729
- return result.summary;
730
- };
731
- const contextMsgs = messages.map(m => ({
732
- role: m.role,
733
- content: typeof m.content === 'string' ? m.content : JSON.stringify(m.content),
734
- }));
735
- const result = await this.contextEngineering.compact(contextMsgs, summarize);
736
- const tokensBefore = this.compactor.estimateTokens(messages);
737
- const tokensAfter = this.compactor.estimateTokens([{ role: 'assistant', content: result.summary }]);
738
- return {
739
- summary: result.summary + (result.reconstructionPrompt ? `\n\n${result.reconstructionPrompt}` : ''),
740
- tokensBefore,
741
- tokensAfter,
742
- preservedMessages: [{ role: 'assistant', content: result.summary }],
743
- references: result.references,
744
- };
745
- }
746
- : undefined;
747
- // Get model's actual context window - try OpenRouter first (real API data),
748
- // then fall back to hardcoded ModelRegistry, then config, then default
749
- const openRouterContext = getModelContextLength(this.config.model || '');
750
- const registryInfo = modelRegistry.getModel(this.config.model || '');
751
- const registryContext = registryInfo?.capabilities?.maxContextTokens;
752
- const maxContextTokens = this.config.maxContextTokens
753
- ?? openRouterContext // From OpenRouter API (e.g., GLM-4.7 = 202752)
754
- ?? registryContext // From hardcoded registry (Claude, GPT-4o, etc.)
755
- ?? 200000; // Fallback to 200K
756
- this.autoCompactionManager = createAutoCompactionManager(this.compactor, {
757
- mode: compactionConfig.mode ?? 'auto',
758
- warningThreshold: 0.70, // Warn at 70% of model's context
759
- autoCompactThreshold: 0.80, // Compact at 80% (changed from 0.90)
760
- hardLimitThreshold: 0.95, // Hard limit at 95%
761
- preserveRecentUserMessages: Math.ceil((compactionConfig.preserveRecentCount ?? 10) / 2),
762
- preserveRecentAssistantMessages: Math.ceil((compactionConfig.preserveRecentCount ?? 10) / 2),
763
- cooldownMs: 60000, // 1 minute cooldown
764
- maxContextTokens, // Dynamic from model registry or config
765
- compactHandler, // Use reversible compaction when contextEngineering is available
766
- });
767
- // Forward compactor events to observability (with cleanup tracking)
768
- const unsubCompactor = this.compactor.on(event => {
769
- switch (event.type) {
770
- case 'compaction.start':
771
- this.observability?.logger?.info('Compaction started', {
772
- messageCount: event.messageCount,
773
- });
774
- break;
775
- case 'compaction.complete':
776
- this.observability?.logger?.info('Compaction complete', {
777
- tokensBefore: event.result.tokensBefore,
778
- tokensAfter: event.result.tokensAfter,
779
- compactedCount: event.result.compactedCount,
780
- });
781
- break;
782
- case 'compaction.error':
783
- this.observability?.logger?.error('Compaction error', {
784
- error: event.error,
785
- });
786
- break;
787
- }
788
- });
789
- this.unsubscribers.push(unsubCompactor);
790
- // Forward auto-compaction events (with cleanup tracking)
791
- const unsubAutoCompaction = this.autoCompactionManager.on((event) => {
792
- switch (event.type) {
793
- case 'autocompaction.warning':
794
- this.observability?.logger?.warn('Context approaching limit', {
795
- currentTokens: event.currentTokens,
796
- ratio: event.ratio,
797
- });
798
- this.emit({
799
- type: 'compaction.warning',
800
- currentTokens: event.currentTokens,
801
- threshold: Math.round(event.ratio * (this.config.maxContextTokens ?? 200000)),
802
- });
803
- break;
804
- case 'autocompaction.triggered':
805
- this.observability?.logger?.info('Auto-compaction triggered', {
806
- mode: event.mode,
807
- currentTokens: event.currentTokens,
808
- });
809
- break;
810
- case 'autocompaction.completed':
811
- this.observability?.logger?.info('Auto-compaction completed', {
812
- tokensBefore: event.tokensBefore,
813
- tokensAfter: event.tokensAfter,
814
- reduction: event.reduction,
815
- });
816
- this.emit({
817
- type: 'compaction.auto',
818
- tokensBefore: event.tokensBefore,
819
- tokensAfter: event.tokensAfter,
820
- messagesCompacted: event.tokensBefore - event.tokensAfter,
821
- });
822
- break;
823
- case 'autocompaction.hard_limit':
824
- this.observability?.logger?.error('Context hard limit reached', {
825
- currentTokens: event.currentTokens,
826
- ratio: event.ratio,
827
- });
828
- break;
829
- case 'autocompaction.emergency_truncate':
830
- this.observability?.logger?.warn('Emergency truncation performed', {
831
- reason: event.reason,
832
- messagesBefore: event.messagesBefore,
833
- messagesAfter: event.messagesAfter,
834
- });
835
- break;
836
- }
837
- });
838
- this.unsubscribers.push(unsubAutoCompaction);
839
- }
840
- // Note: FileChangeTracker requires a database instance which is not
841
- // available at this point. Use initFileChangeTracker() to enable it
842
- // after the agent is constructed with a database reference.
843
- // This allows the feature to be optional and not require SQLite at all times.
214
+ doInitializeFeatures(this);
844
215
  }
845
216
  /**
846
217
  * Initialize the file change tracker with a database instance.
@@ -1548,157 +919,7 @@ export class ProductionAgent {
1548
919
  * is available, ensuring static content is ordered for optimal KV-cache reuse.
1549
920
  */
1550
921
  async buildMessages(task) {
1551
- const messages = [];
1552
- // Gather all context components
1553
- const rulesContent = this.rules?.getRulesContent() ?? '';
1554
- const skillsPrompt = this.skillManager?.getActiveSkillsPrompt() ?? '';
1555
- const memoryContext = this.memory?.getContextStrings(task) ?? [];
1556
- // Get relevant learnings from past sessions
1557
- const learningsContext = this.learningStore?.getLearningContext({
1558
- query: task,
1559
- maxLearnings: 5,
1560
- }) ?? '';
1561
- // Budget-aware codebase context selection
1562
- let codebaseContextStr = '';
1563
- if (this.codebaseContext) {
1564
- // Calculate available budget for codebase context
1565
- // Reserve tokens for: rules (~2000), tools (~2500), memory (~1000), conversation (~5000)
1566
- const reservedTokens = 10500;
1567
- const maxContextTokens = (this.config.maxContextTokens ?? 80000) - reservedTokens;
1568
- const codebaseBudget = Math.min(maxContextTokens * 0.3, 15000); // Up to 30% or 15K tokens
1569
- // Synchronous analysis on first system prompt build so context is available immediately
1570
- if (!this.codebaseContext.getRepoMap() && !this.codebaseAnalysisTriggered) {
1571
- this.codebaseAnalysisTriggered = true;
1572
- try {
1573
- await this.codebaseContext.analyze();
1574
- }
1575
- catch {
1576
- // non-fatal — agent can still work without codebase context
1577
- }
1578
- }
1579
- // Get repo map AFTER analysis so we have fresh data on first prompt
1580
- const repoMap = this.codebaseContext.getRepoMap();
1581
- if (repoMap) {
1582
- try {
1583
- const selection = this.selectRelevantCodeSync(task, codebaseBudget);
1584
- if (selection.chunks.length > 0) {
1585
- codebaseContextStr = buildContextFromChunks(selection.chunks, {
1586
- includeFilePaths: true,
1587
- includeSeparators: true,
1588
- maxTotalTokens: codebaseBudget,
1589
- });
1590
- }
1591
- else {
1592
- // Fallback: lightweight repo map when task-specific selection finds nothing
1593
- codebaseContextStr = generateLightweightRepoMap(repoMap, codebaseBudget);
1594
- }
1595
- }
1596
- catch {
1597
- // Selection error — skip
1598
- }
1599
- }
1600
- }
1601
- // Build tool descriptions
1602
- let toolDescriptions = '';
1603
- if (this.tools.size > 0) {
1604
- const toolLines = [];
1605
- for (const tool of this.tools.values()) {
1606
- toolLines.push(`- ${tool.name}: ${tool.description}`);
1607
- }
1608
- toolDescriptions = toolLines.join('\n');
1609
- }
1610
- // Add MCP tool summaries
1611
- if (this.config.mcpToolSummaries && this.config.mcpToolSummaries.length > 0) {
1612
- const mcpLines = this.config.mcpToolSummaries.map(s => `- ${s.name}: ${s.description}`);
1613
- if (toolDescriptions) {
1614
- toolDescriptions += '\n\nMCP tools (call directly, they auto-load):\n' + mcpLines.join('\n');
1615
- }
1616
- else {
1617
- toolDescriptions = 'MCP tools (call directly, they auto-load):\n' + mcpLines.join('\n');
1618
- }
1619
- }
1620
- // Build system prompt using cache-aware builder if available (Trick P)
1621
- // Combine memory, learnings, codebase context, and environment facts
1622
- const combinedContextParts = [
1623
- // Environment facts — temporal/platform grounding (prevents stale date hallucinations)
1624
- formatFactsBlock(getEnvironmentFacts()),
1625
- ...(memoryContext.length > 0 ? memoryContext : []),
1626
- ...(learningsContext ? [learningsContext] : []),
1627
- ...(codebaseContextStr ? [`\n## Relevant Code\n${codebaseContextStr}`] : []),
1628
- ];
1629
- // Inject thinking directives and scaling guidance for non-simple tasks
1630
- if (this.lastComplexityAssessment) {
1631
- const thinkingPrompt = getThinkingSystemPrompt(this.lastComplexityAssessment.tier);
1632
- if (thinkingPrompt) {
1633
- combinedContextParts.push(thinkingPrompt);
1634
- }
1635
- if (this.lastComplexityAssessment.tier !== 'simple') {
1636
- combinedContextParts.push(getScalingGuidance(this.lastComplexityAssessment));
1637
- }
1638
- }
1639
- const combinedContext = combinedContextParts.join('\n');
1640
- const promptOptions = {
1641
- rules: rulesContent + (skillsPrompt ? '\n\n' + skillsPrompt : ''),
1642
- tools: toolDescriptions,
1643
- memory: combinedContext.length > 0 ? combinedContext : undefined,
1644
- dynamic: {
1645
- mode: this.modeManager?.getMode() ?? 'default',
1646
- },
1647
- };
1648
- if (this.contextEngineering) {
1649
- // Build cache-aware system prompt with cache_control markers (Improvement P1).
1650
- // Store structured blocks for callLLM() to inject as MessageWithContent.
1651
- // The string version is still used for token estimation and debugging.
1652
- const cacheableBlocks = this.contextEngineering.buildCacheableSystemPrompt(promptOptions);
1653
- // Safety check: ensure we have content (empty array = no cache context configured)
1654
- if (cacheableBlocks.length === 0 || cacheableBlocks.every(b => b.text.trim().length === 0)) {
1655
- this.cacheableSystemBlocks = null;
1656
- messages.push({ role: 'system', content: this.config.systemPrompt || 'You are a helpful AI assistant.' });
1657
- }
1658
- else {
1659
- // Store cacheable blocks for provider injection
1660
- this.cacheableSystemBlocks = cacheableBlocks;
1661
- // Push a regular string Message for backward compatibility (token estimation, etc.)
1662
- const flatPrompt = cacheableBlocks.map(b => b.text).join('');
1663
- messages.push({ role: 'system', content: flatPrompt });
1664
- }
1665
- }
1666
- else {
1667
- // Fallback: manual concatenation (original behavior) — no cache markers
1668
- this.cacheableSystemBlocks = null;
1669
- let systemPrompt = this.config.systemPrompt;
1670
- if (rulesContent)
1671
- systemPrompt += '\n\n' + rulesContent;
1672
- if (skillsPrompt)
1673
- systemPrompt += skillsPrompt;
1674
- if (combinedContext.length > 0) {
1675
- systemPrompt += '\n\nRelevant context:\n' + combinedContext;
1676
- }
1677
- if (toolDescriptions) {
1678
- systemPrompt += '\n\nAvailable tools:\n' + toolDescriptions;
1679
- }
1680
- // Safety check: ensure system prompt is not empty
1681
- if (!systemPrompt || systemPrompt.trim().length === 0) {
1682
- log.warn('Empty system prompt detected, using fallback');
1683
- systemPrompt = this.config.systemPrompt || 'You are a helpful AI assistant.';
1684
- }
1685
- messages.push({ role: 'system', content: systemPrompt });
1686
- }
1687
- // Add existing conversation
1688
- for (const msg of this.state.messages) {
1689
- if (msg.role !== 'system') {
1690
- messages.push(msg);
1691
- }
1692
- }
1693
- // Add current task
1694
- messages.push({ role: 'user', content: task });
1695
- // Track system prompt length for context % estimation
1696
- const sysMsg = messages.find(m => m.role === 'system');
1697
- if (sysMsg) {
1698
- const content = typeof sysMsg.content === 'string' ? sysMsg.content : JSON.stringify(sysMsg.content);
1699
- this.lastSystemPromptLength = content.length;
1700
- }
1701
- return messages;
922
+ return doBuildMessages(this, task);
1702
923
  }
1703
924
  // ===========================================================================
1704
925
  // CONTEXT BUILDERS — Bridge private fields to extracted core modules
@@ -1724,7 +945,8 @@ export class ProductionAgent {
1724
945
  skillManager: this.skillManager, semanticCache: this.semanticCache,
1725
946
  lspManager: this.lspManager, threadManager: this.threadManager,
1726
947
  interactivePlanner: this.interactivePlanner, recursiveContext: this.recursiveContext,
1727
- fileChangeTracker: this.fileChangeTracker, capabilitiesRegistry: this.capabilitiesRegistry,
948
+ fileChangeTracker: this.fileChangeTracker, typeCheckerState: this.typeCheckerState,
949
+ capabilitiesRegistry: this.capabilitiesRegistry,
1728
950
  rules: this.rules, stateMachine: this.stateMachine,
1729
951
  lastComplexityAssessment: this.lastComplexityAssessment,
1730
952
  cacheableSystemBlocks: this.cacheableSystemBlocks,
@@ -2026,37 +1248,21 @@ export class ProductionAgent {
2026
1248
  * @returns Change ID if tracked, -1 otherwise
2027
1249
  */
2028
1250
  async trackFileChange(params) {
2029
- if (!this.fileChangeTracker) {
2030
- return -1;
2031
- }
2032
- return this.fileChangeTracker.recordChange({
2033
- filePath: params.filePath,
2034
- operation: params.operation,
2035
- contentBefore: params.contentBefore,
2036
- contentAfter: params.contentAfter,
2037
- turnNumber: this.state.iteration,
2038
- toolCallId: params.toolCallId,
2039
- });
1251
+ return doTrackFileChange(this, params);
2040
1252
  }
2041
1253
  /**
2042
1254
  * Undo the last change to a specific file.
2043
1255
  * Returns null if file change tracking is not enabled.
2044
1256
  */
2045
1257
  async undoLastFileChange(filePath) {
2046
- if (!this.fileChangeTracker) {
2047
- return null;
2048
- }
2049
- return this.fileChangeTracker.undoLastChange(filePath);
1258
+ return doUndoLastFileChange(this, filePath);
2050
1259
  }
2051
1260
  /**
2052
1261
  * Undo all changes in the current turn.
2053
1262
  * Returns null if file change tracking is not enabled.
2054
1263
  */
2055
1264
  async undoCurrentTurn() {
2056
- if (!this.fileChangeTracker) {
2057
- return null;
2058
- }
2059
- return this.fileChangeTracker.undoTurn(this.state.iteration);
1265
+ return doUndoCurrentTurn(this);
2060
1266
  }
2061
1267
  /**
2062
1268
  * Subscribe to events.
@@ -2071,131 +1277,27 @@ export class ProductionAgent {
2071
1277
  * Reset agent state.
2072
1278
  */
2073
1279
  reset() {
2074
- this.state = {
2075
- status: 'idle',
2076
- messages: [],
2077
- plan: undefined,
2078
- memoryContext: [],
2079
- metrics: {
2080
- totalTokens: 0,
2081
- inputTokens: 0,
2082
- outputTokens: 0,
2083
- estimatedCost: 0,
2084
- llmCalls: 0,
2085
- toolCalls: 0,
2086
- duration: 0,
2087
- successCount: 0,
2088
- failureCount: 0,
2089
- cancelCount: 0,
2090
- retryCount: 0,
2091
- },
2092
- iteration: 0,
2093
- };
2094
- this.memory?.clear();
2095
- this.observability?.metrics?.reset();
2096
- this.planning?.clearPlan();
2097
- this.observability?.logger?.info('Agent state reset');
1280
+ doReset(this);
2098
1281
  }
2099
1282
  /**
2100
1283
  * Load messages from a previous session.
2101
1284
  * @deprecated Use loadState() for full state restoration
2102
1285
  */
2103
1286
  loadMessages(messages) {
2104
- this.state.messages = [...messages];
2105
- // Sync to threadManager if enabled
2106
- if (this.threadManager) {
2107
- const thread = this.threadManager.getActiveThread();
2108
- thread.messages = [...messages];
2109
- }
2110
- this.observability?.logger?.info('Messages loaded', { count: messages.length });
1287
+ doLoadMessages(this, messages);
2111
1288
  }
2112
1289
  /**
2113
1290
  * Serializable state for checkpoints (excludes non-serializable fields).
2114
1291
  */
2115
1292
  getSerializableState() {
2116
- return {
2117
- messages: this.state.messages,
2118
- iteration: this.state.iteration,
2119
- metrics: { ...this.state.metrics },
2120
- plan: this.state.plan ? { ...this.state.plan } : undefined,
2121
- memoryContext: this.state.memoryContext ? [...this.state.memoryContext] : undefined,
2122
- };
1293
+ return doGetSerializableState(this);
2123
1294
  }
2124
1295
  /**
2125
1296
  * Validate checkpoint data before loading.
2126
1297
  * Returns validation result with errors and warnings.
2127
1298
  */
2128
1299
  validateCheckpoint(data) {
2129
- const errors = [];
2130
- const warnings = [];
2131
- // Check if data is an object
2132
- if (!data || typeof data !== 'object') {
2133
- errors.push('Checkpoint data must be an object');
2134
- return { valid: false, errors, warnings, sanitized: null };
2135
- }
2136
- const checkpoint = data;
2137
- // Validate messages array (required)
2138
- if (!checkpoint.messages) {
2139
- errors.push('Checkpoint missing required "messages" field');
2140
- }
2141
- else if (!Array.isArray(checkpoint.messages)) {
2142
- errors.push('Checkpoint "messages" must be an array');
2143
- }
2144
- else {
2145
- // Validate each message has required fields
2146
- for (let i = 0; i < checkpoint.messages.length; i++) {
2147
- const msg = checkpoint.messages[i];
2148
- if (!msg || typeof msg !== 'object') {
2149
- errors.push(`Message at index ${i} is not an object`);
2150
- continue;
2151
- }
2152
- if (!msg.role || typeof msg.role !== 'string') {
2153
- errors.push(`Message at index ${i} missing valid "role" field`);
2154
- }
2155
- if (msg.content !== undefined && msg.content !== null && typeof msg.content !== 'string') {
2156
- // Content can be undefined for tool call messages
2157
- warnings.push(`Message at index ${i} has non-string content (type: ${typeof msg.content})`);
2158
- }
2159
- }
2160
- }
2161
- // Validate iteration (optional but should be non-negative number)
2162
- if (checkpoint.iteration !== undefined) {
2163
- if (typeof checkpoint.iteration !== 'number' || checkpoint.iteration < 0) {
2164
- warnings.push(`Invalid iteration value: ${checkpoint.iteration}, will use default`);
2165
- }
2166
- }
2167
- // Validate metrics (optional)
2168
- if (checkpoint.metrics !== undefined && checkpoint.metrics !== null) {
2169
- if (typeof checkpoint.metrics !== 'object') {
2170
- warnings.push('Metrics field is not an object, will be ignored');
2171
- }
2172
- }
2173
- // Validate memoryContext (optional)
2174
- if (checkpoint.memoryContext !== undefined && checkpoint.memoryContext !== null) {
2175
- if (!Array.isArray(checkpoint.memoryContext)) {
2176
- warnings.push('memoryContext is not an array, will be ignored');
2177
- }
2178
- }
2179
- // If we have critical errors, fail validation
2180
- if (errors.length > 0) {
2181
- return { valid: false, errors, warnings, sanitized: null };
2182
- }
2183
- // Build sanitized checkpoint
2184
- const messages = checkpoint.messages.filter((msg) => msg && typeof msg === 'object' && typeof msg.role === 'string');
2185
- const sanitized = {
2186
- messages,
2187
- iteration: typeof checkpoint.iteration === 'number' && checkpoint.iteration >= 0
2188
- ? checkpoint.iteration
2189
- : Math.floor(messages.length / 2),
2190
- metrics: typeof checkpoint.metrics === 'object' && checkpoint.metrics !== null
2191
- ? checkpoint.metrics
2192
- : undefined,
2193
- plan: checkpoint.plan,
2194
- memoryContext: Array.isArray(checkpoint.memoryContext)
2195
- ? checkpoint.memoryContext
2196
- : undefined,
2197
- };
2198
- return { valid: true, errors, warnings, sanitized };
1300
+ return doValidateCheckpoint(data);
2199
1301
  }
2200
1302
  /**
2201
1303
  * Load full state from a checkpoint.
@@ -2203,65 +1305,7 @@ export class ProductionAgent {
2203
1305
  * Validates checkpoint data before loading to prevent corrupted state.
2204
1306
  */
2205
1307
  loadState(savedState) {
2206
- // Validate checkpoint data
2207
- const validation = this.validateCheckpoint(savedState);
2208
- // Log warnings
2209
- for (const warning of validation.warnings) {
2210
- log.warn('Checkpoint validation warning', { warning });
2211
- this.observability?.logger?.warn('Checkpoint validation warning', { warning });
2212
- }
2213
- // Fail on validation errors
2214
- if (!validation.valid || !validation.sanitized) {
2215
- const errorMsg = `Invalid checkpoint: ${validation.errors.join('; ')}`;
2216
- this.observability?.logger?.error('Checkpoint validation failed', { errors: validation.errors });
2217
- throw new Error(errorMsg);
2218
- }
2219
- // Use sanitized data
2220
- const sanitized = validation.sanitized;
2221
- // Restore messages
2222
- this.state.messages = [...sanitized.messages];
2223
- // Restore iteration (already validated/defaulted in sanitized)
2224
- this.state.iteration = sanitized.iteration;
2225
- // Restore metrics (merge with defaults)
2226
- if (sanitized.metrics) {
2227
- this.state.metrics = {
2228
- totalTokens: sanitized.metrics.totalTokens ?? 0,
2229
- inputTokens: sanitized.metrics.inputTokens ?? 0,
2230
- outputTokens: sanitized.metrics.outputTokens ?? 0,
2231
- estimatedCost: sanitized.metrics.estimatedCost ?? 0,
2232
- llmCalls: sanitized.metrics.llmCalls ?? 0,
2233
- toolCalls: sanitized.metrics.toolCalls ?? 0,
2234
- duration: sanitized.metrics.duration ?? 0,
2235
- reflectionAttempts: sanitized.metrics.reflectionAttempts,
2236
- successCount: sanitized.metrics.successCount ?? 0,
2237
- failureCount: sanitized.metrics.failureCount ?? 0,
2238
- cancelCount: sanitized.metrics.cancelCount ?? 0,
2239
- retryCount: sanitized.metrics.retryCount ?? 0,
2240
- };
2241
- }
2242
- // Restore plan if present
2243
- if (sanitized.plan) {
2244
- this.state.plan = { ...sanitized.plan };
2245
- // Sync with planning manager if enabled
2246
- if (this.planning) {
2247
- this.planning.loadPlan(sanitized.plan);
2248
- }
2249
- }
2250
- // Restore memory context if present
2251
- if (sanitized.memoryContext) {
2252
- this.state.memoryContext = [...sanitized.memoryContext];
2253
- }
2254
- // Sync to threadManager if enabled
2255
- if (this.threadManager) {
2256
- const thread = this.threadManager.getActiveThread();
2257
- thread.messages = [...sanitized.messages];
2258
- }
2259
- this.observability?.logger?.info('State loaded', {
2260
- messageCount: sanitized.messages.length,
2261
- iteration: this.state.iteration,
2262
- hasPlan: !!sanitized.plan,
2263
- hasMemoryContext: !!sanitized.memoryContext,
2264
- });
1308
+ doLoadState(this, savedState);
2265
1309
  }
2266
1310
  /**
2267
1311
  * Add a tool dynamically.
@@ -3169,6 +2213,10 @@ If the task is a simple question or doesn't need specialized handling, set bestA
3169
2213
  */
3170
2214
  setStore(store) {
3171
2215
  this.store = store;
2216
+ // Wire persistence to codebase context for warm startup across sessions
2217
+ if (this.codebaseContext) {
2218
+ this.codebaseContext.setPersistenceStore(store);
2219
+ }
3172
2220
  }
3173
2221
  /**
3174
2222
  * Check if external cancellation has been requested.
@@ -3199,6 +2247,12 @@ If the task is a simple question or doesn't need specialized handling, set bestA
3199
2247
  cycleMode() {
3200
2248
  return this.modeManager.cycleMode();
3201
2249
  }
2250
+ /**
2251
+ * Get type checker state for TUI diagnostics display.
2252
+ */
2253
+ getTypeCheckerState() {
2254
+ return this.typeCheckerState;
2255
+ }
3202
2256
  /**
3203
2257
  * Get all registered tools.
3204
2258
  */
@@ -3505,202 +2559,7 @@ If the task is a simple question or doesn't need specialized handling, set bestA
3505
2559
  }
3506
2560
  }
3507
2561
  // =============================================================================
3508
- // FACTORY
3509
- // =============================================================================
3510
- /**
3511
- * Create a production agent with the given configuration.
3512
- */
3513
- export function createProductionAgent(config) {
3514
- return new ProductionAgent(config);
3515
- }
3516
- // =============================================================================
3517
- // BUILDER PATTERN
3518
- // =============================================================================
3519
- /**
3520
- * Builder for creating customized production agents.
3521
- */
3522
- export class ProductionAgentBuilder {
3523
- config = {};
3524
- /**
3525
- * Set the LLM provider.
3526
- */
3527
- provider(provider) {
3528
- this.config.provider = provider;
3529
- return this;
3530
- }
3531
- /**
3532
- * Set the model.
3533
- */
3534
- model(model) {
3535
- this.config.model = model;
3536
- return this;
3537
- }
3538
- /**
3539
- * Set the system prompt.
3540
- */
3541
- systemPrompt(prompt) {
3542
- this.config.systemPrompt = prompt;
3543
- return this;
3544
- }
3545
- /**
3546
- * Add tools.
3547
- */
3548
- tools(tools) {
3549
- this.config.tools = tools;
3550
- return this;
3551
- }
3552
- /**
3553
- * Configure hooks.
3554
- */
3555
- hooks(config) {
3556
- this.config.hooks = config;
3557
- return this;
3558
- }
3559
- /**
3560
- * Configure plugins.
3561
- */
3562
- plugins(config) {
3563
- this.config.plugins = config;
3564
- return this;
3565
- }
3566
- /**
3567
- * Configure memory.
3568
- */
3569
- memory(config) {
3570
- this.config.memory = config;
3571
- return this;
3572
- }
3573
- /**
3574
- * Configure planning.
3575
- */
3576
- planning(config) {
3577
- this.config.planning = config;
3578
- return this;
3579
- }
3580
- /**
3581
- * Configure reflection.
3582
- */
3583
- reflection(config) {
3584
- this.config.reflection = config;
3585
- return this;
3586
- }
3587
- /**
3588
- * Configure observability.
3589
- */
3590
- observability(config) {
3591
- this.config.observability = config;
3592
- return this;
3593
- }
3594
- /**
3595
- * Configure sandbox.
3596
- */
3597
- sandbox(config) {
3598
- this.config.sandbox = config;
3599
- return this;
3600
- }
3601
- /**
3602
- * Configure human-in-the-loop.
3603
- */
3604
- humanInLoop(config) {
3605
- this.config.humanInLoop = config;
3606
- return this;
3607
- }
3608
- /**
3609
- * Configure routing.
3610
- */
3611
- routing(config) {
3612
- this.config.routing = config;
3613
- return this;
3614
- }
3615
- /**
3616
- * Configure multi-agent coordination (Lesson 17).
3617
- */
3618
- multiAgent(config) {
3619
- this.config.multiAgent = config;
3620
- return this;
3621
- }
3622
- /**
3623
- * Add a role to multi-agent config.
3624
- */
3625
- addRole(role) {
3626
- // Handle undefined, false, or disabled config
3627
- if (!this.config.multiAgent) {
3628
- this.config.multiAgent = { enabled: true, roles: [] };
3629
- }
3630
- // Ensure roles array exists
3631
- const multiAgentConfig = this.config.multiAgent;
3632
- if (!multiAgentConfig.roles) {
3633
- multiAgentConfig.roles = [];
3634
- }
3635
- multiAgentConfig.roles.push(role);
3636
- return this;
3637
- }
3638
- /**
3639
- * Configure ReAct pattern (Lesson 18).
3640
- */
3641
- react(config) {
3642
- this.config.react = config;
3643
- return this;
3644
- }
3645
- /**
3646
- * Configure execution policies (Lesson 23).
3647
- */
3648
- executionPolicy(config) {
3649
- this.config.executionPolicy = config;
3650
- return this;
3651
- }
3652
- /**
3653
- * Configure thread management (Lesson 24).
3654
- */
3655
- threads(config) {
3656
- this.config.threads = config;
3657
- return this;
3658
- }
3659
- /**
3660
- * Configure skills system.
3661
- */
3662
- skills(config) {
3663
- this.config.skills = config;
3664
- return this;
3665
- }
3666
- /**
3667
- * Set max iterations.
3668
- */
3669
- maxIterations(max) {
3670
- this.config.maxIterations = max;
3671
- return this;
3672
- }
3673
- /**
3674
- * Set timeout.
3675
- */
3676
- timeout(ms) {
3677
- this.config.timeout = ms;
3678
- return this;
3679
- }
3680
- /**
3681
- * Disable a feature.
3682
- */
3683
- disable(feature) {
3684
- this.config[feature] = false;
3685
- return this;
3686
- }
3687
- /**
3688
- * Build the agent.
3689
- */
3690
- build() {
3691
- if (!this.config.provider) {
3692
- throw new Error('Provider is required');
3693
- }
3694
- return new ProductionAgent(this.config);
3695
- }
3696
- }
3697
- /**
3698
- * Start building a production agent.
3699
- */
3700
- export function buildAgent() {
3701
- return new ProductionAgentBuilder();
3702
- }
3703
- // =============================================================================
3704
- // Re-export from core for backward compatibility
2562
+ // Re-exports for backward compatibility
3705
2563
  export { parseStructuredClosureReport } from './core/index.js';
2564
+ export { buildAgent, ProductionAgentBuilder, createProductionAgent } from './agent/index.js';
3706
2565
  //# sourceMappingURL=agent.js.map