@fraziym/axoniz 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (512) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +76 -0
  3. package/dist/agents/definition.d.ts +15 -0
  4. package/dist/agents/definition.d.ts.map +1 -0
  5. package/dist/agents/definition.js +41 -0
  6. package/dist/agents/definition.js.map +1 -0
  7. package/dist/agents/index.d.ts +12 -0
  8. package/dist/agents/index.d.ts.map +1 -0
  9. package/dist/agents/index.js +11 -0
  10. package/dist/agents/index.js.map +1 -0
  11. package/dist/agents/registry.d.ts +17 -0
  12. package/dist/agents/registry.d.ts.map +1 -0
  13. package/dist/agents/registry.js +23 -0
  14. package/dist/agents/registry.js.map +1 -0
  15. package/dist/agents/specialized.d.ts +31 -0
  16. package/dist/agents/specialized.d.ts.map +1 -0
  17. package/dist/agents/specialized.js +75 -0
  18. package/dist/agents/specialized.js.map +1 -0
  19. package/dist/awareness/index.d.ts +14 -0
  20. package/dist/awareness/index.d.ts.map +1 -0
  21. package/dist/awareness/index.js +22 -0
  22. package/dist/awareness/index.js.map +1 -0
  23. package/dist/awareness/service.d.ts +180 -0
  24. package/dist/awareness/service.d.ts.map +1 -0
  25. package/dist/awareness/service.js +789 -0
  26. package/dist/awareness/service.js.map +1 -0
  27. package/dist/cli/entry.d.ts +13 -0
  28. package/dist/cli/entry.d.ts.map +1 -0
  29. package/dist/cli/entry.js +35 -0
  30. package/dist/cli/entry.js.map +1 -0
  31. package/dist/comms/telegram.d.ts +41 -0
  32. package/dist/comms/telegram.d.ts.map +1 -0
  33. package/dist/comms/telegram.js +332 -0
  34. package/dist/comms/telegram.js.map +1 -0
  35. package/dist/core/agent.d.ts +252 -0
  36. package/dist/core/agent.d.ts.map +1 -0
  37. package/dist/core/agent.js +1399 -0
  38. package/dist/core/agent.js.map +1 -0
  39. package/dist/core/auth.d.ts +23 -0
  40. package/dist/core/auth.d.ts.map +1 -0
  41. package/dist/core/auth.js +113 -0
  42. package/dist/core/auth.js.map +1 -0
  43. package/dist/core/authority.d.ts +118 -0
  44. package/dist/core/authority.d.ts.map +1 -0
  45. package/dist/core/authority.js +402 -0
  46. package/dist/core/authority.js.map +1 -0
  47. package/dist/core/backend/async_queue.d.ts +17 -0
  48. package/dist/core/backend/async_queue.d.ts.map +1 -0
  49. package/dist/core/backend/async_queue.js +66 -0
  50. package/dist/core/backend/async_queue.js.map +1 -0
  51. package/dist/core/backend/index.d.ts +24 -0
  52. package/dist/core/backend/index.d.ts.map +1 -0
  53. package/dist/core/backend/index.js +128 -0
  54. package/dist/core/backend/index.js.map +1 -0
  55. package/dist/core/backend/llama_server.d.ts +39 -0
  56. package/dist/core/backend/llama_server.d.ts.map +1 -0
  57. package/dist/core/backend/llama_server.js +182 -0
  58. package/dist/core/backend/llama_server.js.map +1 -0
  59. package/dist/core/backend/llamacpp.d.ts +40 -0
  60. package/dist/core/backend/llamacpp.d.ts.map +1 -0
  61. package/dist/core/backend/llamacpp.js +200 -0
  62. package/dist/core/backend/llamacpp.js.map +1 -0
  63. package/dist/core/backend/lmstudio.d.ts +53 -0
  64. package/dist/core/backend/lmstudio.d.ts.map +1 -0
  65. package/dist/core/backend/lmstudio.js +274 -0
  66. package/dist/core/backend/lmstudio.js.map +1 -0
  67. package/dist/core/backend/ollama.d.ts +25 -0
  68. package/dist/core/backend/ollama.d.ts.map +1 -0
  69. package/dist/core/backend/ollama.js +86 -0
  70. package/dist/core/backend/ollama.js.map +1 -0
  71. package/dist/core/backend/openai.d.ts +27 -0
  72. package/dist/core/backend/openai.d.ts.map +1 -0
  73. package/dist/core/backend/openai.js +84 -0
  74. package/dist/core/backend/openai.js.map +1 -0
  75. package/dist/core/backend/types.d.ts +73 -0
  76. package/dist/core/backend/types.d.ts.map +1 -0
  77. package/dist/core/backend/types.js +137 -0
  78. package/dist/core/backend/types.js.map +1 -0
  79. package/dist/core/chat_store.d.ts +77 -0
  80. package/dist/core/chat_store.d.ts.map +1 -0
  81. package/dist/core/chat_store.js +332 -0
  82. package/dist/core/chat_store.js.map +1 -0
  83. package/dist/core/cli.d.ts +82 -0
  84. package/dist/core/cli.d.ts.map +1 -0
  85. package/dist/core/cli.js +602 -0
  86. package/dist/core/cli.js.map +1 -0
  87. package/dist/core/config.d.ts +127 -0
  88. package/dist/core/config.d.ts.map +1 -0
  89. package/dist/core/config.js +295 -0
  90. package/dist/core/config.js.map +1 -0
  91. package/dist/core/debug.d.ts +8 -0
  92. package/dist/core/debug.d.ts.map +1 -0
  93. package/dist/core/debug.js +8 -0
  94. package/dist/core/debug.js.map +1 -0
  95. package/dist/core/downloader.d.ts +31 -0
  96. package/dist/core/downloader.d.ts.map +1 -0
  97. package/dist/core/downloader.js +180 -0
  98. package/dist/core/downloader.js.map +1 -0
  99. package/dist/core/errors.d.ts +80 -0
  100. package/dist/core/errors.d.ts.map +1 -0
  101. package/dist/core/errors.js +134 -0
  102. package/dist/core/errors.js.map +1 -0
  103. package/dist/core/extras.d.ts +160 -0
  104. package/dist/core/extras.d.ts.map +1 -0
  105. package/dist/core/extras.js +553 -0
  106. package/dist/core/extras.js.map +1 -0
  107. package/dist/core/health.d.ts +27 -0
  108. package/dist/core/health.d.ts.map +1 -0
  109. package/dist/core/health.js +96 -0
  110. package/dist/core/health.js.map +1 -0
  111. package/dist/core/history.d.ts +50 -0
  112. package/dist/core/history.d.ts.map +1 -0
  113. package/dist/core/history.js +276 -0
  114. package/dist/core/history.js.map +1 -0
  115. package/dist/core/index.d.ts +6 -0
  116. package/dist/core/index.d.ts.map +1 -0
  117. package/dist/core/index.js +6 -0
  118. package/dist/core/index.js.map +1 -0
  119. package/dist/core/intelligence/ast_index.d.ts +255 -0
  120. package/dist/core/intelligence/ast_index.d.ts.map +1 -0
  121. package/dist/core/intelligence/ast_index.js +1369 -0
  122. package/dist/core/intelligence/ast_index.js.map +1 -0
  123. package/dist/core/intelligence/confidence.d.ts +113 -0
  124. package/dist/core/intelligence/confidence.d.ts.map +1 -0
  125. package/dist/core/intelligence/confidence.js +298 -0
  126. package/dist/core/intelligence/confidence.js.map +1 -0
  127. package/dist/core/intelligence/context_compressor.d.ts +80 -0
  128. package/dist/core/intelligence/context_compressor.d.ts.map +1 -0
  129. package/dist/core/intelligence/context_compressor.js +245 -0
  130. package/dist/core/intelligence/context_compressor.js.map +1 -0
  131. package/dist/core/intelligence/daemon.d.ts +247 -0
  132. package/dist/core/intelligence/daemon.d.ts.map +1 -0
  133. package/dist/core/intelligence/daemon.js +842 -0
  134. package/dist/core/intelligence/daemon.js.map +1 -0
  135. package/dist/core/intelligence/index.d.ts +60 -0
  136. package/dist/core/intelligence/index.d.ts.map +1 -0
  137. package/dist/core/intelligence/index.js +101 -0
  138. package/dist/core/intelligence/index.js.map +1 -0
  139. package/dist/core/intelligence/predictor.d.ts +246 -0
  140. package/dist/core/intelligence/predictor.d.ts.map +1 -0
  141. package/dist/core/intelligence/predictor.js +590 -0
  142. package/dist/core/intelligence/predictor.js.map +1 -0
  143. package/dist/core/intelligence/reflex.d.ts +84 -0
  144. package/dist/core/intelligence/reflex.d.ts.map +1 -0
  145. package/dist/core/intelligence/reflex.js +344 -0
  146. package/dist/core/intelligence/reflex.js.map +1 -0
  147. package/dist/core/intelligence/self_correction.d.ts +121 -0
  148. package/dist/core/intelligence/self_correction.d.ts.map +1 -0
  149. package/dist/core/intelligence/self_correction.js +327 -0
  150. package/dist/core/intelligence/self_correction.js.map +1 -0
  151. package/dist/core/intelligence/skill_distiller.d.ts +100 -0
  152. package/dist/core/intelligence/skill_distiller.d.ts.map +1 -0
  153. package/dist/core/intelligence/skill_distiller.js +246 -0
  154. package/dist/core/intelligence/skill_distiller.js.map +1 -0
  155. package/dist/core/intelligence/swarm.d.ts +330 -0
  156. package/dist/core/intelligence/swarm.d.ts.map +1 -0
  157. package/dist/core/intelligence/swarm.js +1064 -0
  158. package/dist/core/intelligence/swarm.js.map +1 -0
  159. package/dist/core/intelligence/trajectory.d.ts +107 -0
  160. package/dist/core/intelligence/trajectory.d.ts.map +1 -0
  161. package/dist/core/intelligence/trajectory.js +330 -0
  162. package/dist/core/intelligence/trajectory.js.map +1 -0
  163. package/dist/core/logger.d.ts +111 -0
  164. package/dist/core/logger.d.ts.map +1 -0
  165. package/dist/core/logger.js +640 -0
  166. package/dist/core/logger.js.map +1 -0
  167. package/dist/core/loop.d.ts +123 -0
  168. package/dist/core/loop.d.ts.map +1 -0
  169. package/dist/core/loop.js +423 -0
  170. package/dist/core/loop.js.map +1 -0
  171. package/dist/core/memory.d.ts +81 -0
  172. package/dist/core/memory.d.ts.map +1 -0
  173. package/dist/core/memory.js +328 -0
  174. package/dist/core/memory.js.map +1 -0
  175. package/dist/core/metrics.d.ts +29 -0
  176. package/dist/core/metrics.d.ts.map +1 -0
  177. package/dist/core/metrics.js +109 -0
  178. package/dist/core/metrics.js.map +1 -0
  179. package/dist/core/models.d.ts +51 -0
  180. package/dist/core/models.d.ts.map +1 -0
  181. package/dist/core/models.js +146 -0
  182. package/dist/core/models.js.map +1 -0
  183. package/dist/core/optimizer.d.ts +34 -0
  184. package/dist/core/optimizer.d.ts.map +1 -0
  185. package/dist/core/optimizer.js +131 -0
  186. package/dist/core/optimizer.js.map +1 -0
  187. package/dist/core/persona.d.ts +35 -0
  188. package/dist/core/persona.d.ts.map +1 -0
  189. package/dist/core/persona.js +126 -0
  190. package/dist/core/persona.js.map +1 -0
  191. package/dist/core/rate_limit.d.ts +23 -0
  192. package/dist/core/rate_limit.d.ts.map +1 -0
  193. package/dist/core/rate_limit.js +62 -0
  194. package/dist/core/rate_limit.js.map +1 -0
  195. package/dist/core/runner.d.ts +63 -0
  196. package/dist/core/runner.d.ts.map +1 -0
  197. package/dist/core/runner.js +671 -0
  198. package/dist/core/runner.js.map +1 -0
  199. package/dist/core/stream_parser.d.ts +43 -0
  200. package/dist/core/stream_parser.d.ts.map +1 -0
  201. package/dist/core/stream_parser.js +140 -0
  202. package/dist/core/stream_parser.js.map +1 -0
  203. package/dist/core/tool_schemas.d.ts +26 -0
  204. package/dist/core/tool_schemas.d.ts.map +1 -0
  205. package/dist/core/tool_schemas.js +124 -0
  206. package/dist/core/tool_schemas.js.map +1 -0
  207. package/dist/core/which.d.ts +2 -0
  208. package/dist/core/which.d.ts.map +1 -0
  209. package/dist/core/which.js +35 -0
  210. package/dist/core/which.js.map +1 -0
  211. package/dist/goals/index.d.ts +9 -0
  212. package/dist/goals/index.d.ts.map +1 -0
  213. package/dist/goals/index.js +17 -0
  214. package/dist/goals/index.js.map +1 -0
  215. package/dist/goals/service.d.ts +115 -0
  216. package/dist/goals/service.d.ts.map +1 -0
  217. package/dist/goals/service.js +415 -0
  218. package/dist/goals/service.js.map +1 -0
  219. package/dist/goals/types.d.ts +47 -0
  220. package/dist/goals/types.d.ts.map +1 -0
  221. package/dist/goals/types.js +66 -0
  222. package/dist/goals/types.js.map +1 -0
  223. package/dist/index.d.ts +22 -0
  224. package/dist/index.d.ts.map +1 -0
  225. package/dist/index.js +22 -0
  226. package/dist/index.js.map +1 -0
  227. package/dist/integrations/autonomous_startup.d.ts +51 -0
  228. package/dist/integrations/autonomous_startup.d.ts.map +1 -0
  229. package/dist/integrations/autonomous_startup.js +419 -0
  230. package/dist/integrations/autonomous_startup.js.map +1 -0
  231. package/dist/integrations/goose.d.ts +105 -0
  232. package/dist/integrations/goose.d.ts.map +1 -0
  233. package/dist/integrations/goose.js +408 -0
  234. package/dist/integrations/goose.js.map +1 -0
  235. package/dist/integrations/index.d.ts +21 -0
  236. package/dist/integrations/index.d.ts.map +1 -0
  237. package/dist/integrations/index.js +17 -0
  238. package/dist/integrations/index.js.map +1 -0
  239. package/dist/integrations/mcp.d.ts +73 -0
  240. package/dist/integrations/mcp.d.ts.map +1 -0
  241. package/dist/integrations/mcp.js +307 -0
  242. package/dist/integrations/mcp.js.map +1 -0
  243. package/dist/integrations/mempalace.d.ts +18 -0
  244. package/dist/integrations/mempalace.d.ts.map +1 -0
  245. package/dist/integrations/mempalace.js +25 -0
  246. package/dist/integrations/mempalace.js.map +1 -0
  247. package/dist/integrations/multi_agent.d.ts +82 -0
  248. package/dist/integrations/multi_agent.d.ts.map +1 -0
  249. package/dist/integrations/multi_agent.js +280 -0
  250. package/dist/integrations/multi_agent.js.map +1 -0
  251. package/dist/integrations/unified_memory.d.ts +415 -0
  252. package/dist/integrations/unified_memory.d.ts.map +1 -0
  253. package/dist/integrations/unified_memory.js +1489 -0
  254. package/dist/integrations/unified_memory.js.map +1 -0
  255. package/dist/roles/beru.yaml +48 -0
  256. package/dist/sidecar/client.d.ts +63 -0
  257. package/dist/sidecar/client.d.ts.map +1 -0
  258. package/dist/sidecar/client.js +222 -0
  259. package/dist/sidecar/client.js.map +1 -0
  260. package/dist/sidecar/index.d.ts +7 -0
  261. package/dist/sidecar/index.d.ts.map +1 -0
  262. package/dist/sidecar/index.js +6 -0
  263. package/dist/sidecar/index.js.map +1 -0
  264. package/dist/startup.d.ts +22 -0
  265. package/dist/startup.d.ts.map +1 -0
  266. package/dist/startup.js +194 -0
  267. package/dist/startup.js.map +1 -0
  268. package/dist/tools/_internal.d.ts +90 -0
  269. package/dist/tools/_internal.d.ts.map +1 -0
  270. package/dist/tools/_internal.js +375 -0
  271. package/dist/tools/_internal.js.map +1 -0
  272. package/dist/tools/_smoke.d.ts +2 -0
  273. package/dist/tools/_smoke.d.ts.map +1 -0
  274. package/dist/tools/_smoke.js +203 -0
  275. package/dist/tools/_smoke.js.map +1 -0
  276. package/dist/tools/axodex_tools.d.ts +51 -0
  277. package/dist/tools/axodex_tools.d.ts.map +1 -0
  278. package/dist/tools/axodex_tools.js +181 -0
  279. package/dist/tools/axodex_tools.js.map +1 -0
  280. package/dist/tools/code_tools.d.ts +33 -0
  281. package/dist/tools/code_tools.d.ts.map +1 -0
  282. package/dist/tools/code_tools.js +191 -0
  283. package/dist/tools/code_tools.js.map +1 -0
  284. package/dist/tools/computer_tools.d.ts +59 -0
  285. package/dist/tools/computer_tools.d.ts.map +1 -0
  286. package/dist/tools/computer_tools.js +348 -0
  287. package/dist/tools/computer_tools.js.map +1 -0
  288. package/dist/tools/file_tools.d.ts +51 -0
  289. package/dist/tools/file_tools.d.ts.map +1 -0
  290. package/dist/tools/file_tools.js +424 -0
  291. package/dist/tools/file_tools.js.map +1 -0
  292. package/dist/tools/index.d.ts +13 -0
  293. package/dist/tools/index.d.ts.map +1 -0
  294. package/dist/tools/index.js +13 -0
  295. package/dist/tools/index.js.map +1 -0
  296. package/dist/tools/shell_tools.d.ts +39 -0
  297. package/dist/tools/shell_tools.d.ts.map +1 -0
  298. package/dist/tools/shell_tools.js +163 -0
  299. package/dist/tools/shell_tools.js.map +1 -0
  300. package/dist/tools/web_tools.d.ts +31 -0
  301. package/dist/tools/web_tools.d.ts.map +1 -0
  302. package/dist/tools/web_tools.js +117 -0
  303. package/dist/tools/web_tools.js.map +1 -0
  304. package/dist/voice/index.d.ts +41 -0
  305. package/dist/voice/index.d.ts.map +1 -0
  306. package/dist/voice/index.js +58 -0
  307. package/dist/voice/index.js.map +1 -0
  308. package/dist/voice/light_daemon.d.ts +197 -0
  309. package/dist/voice/light_daemon.d.ts.map +1 -0
  310. package/dist/voice/light_daemon.js +746 -0
  311. package/dist/voice/light_daemon.js.map +1 -0
  312. package/dist/voice/setup.d.ts +63 -0
  313. package/dist/voice/setup.d.ts.map +1 -0
  314. package/dist/voice/setup.js +443 -0
  315. package/dist/voice/setup.js.map +1 -0
  316. package/dist/voice/stt.d.ts +148 -0
  317. package/dist/voice/stt.d.ts.map +1 -0
  318. package/dist/voice/stt.js +361 -0
  319. package/dist/voice/stt.js.map +1 -0
  320. package/dist/voice/tts.d.ts +168 -0
  321. package/dist/voice/tts.d.ts.map +1 -0
  322. package/dist/voice/tts.js +698 -0
  323. package/dist/voice/tts.js.map +1 -0
  324. package/dist/voice/voice_loop.d.ts +101 -0
  325. package/dist/voice/voice_loop.d.ts.map +1 -0
  326. package/dist/voice/voice_loop.js +463 -0
  327. package/dist/voice/voice_loop.js.map +1 -0
  328. package/dist/voice/wake_word.d.ts +153 -0
  329. package/dist/voice/wake_word.d.ts.map +1 -0
  330. package/dist/voice/wake_word.js +458 -0
  331. package/dist/voice/wake_word.js.map +1 -0
  332. package/dist/voice/wav.d.ts +99 -0
  333. package/dist/voice/wav.d.ts.map +1 -0
  334. package/dist/voice/wav.js +306 -0
  335. package/dist/voice/wav.js.map +1 -0
  336. package/dist/web/broker.d.ts +33 -0
  337. package/dist/web/broker.d.ts.map +1 -0
  338. package/dist/web/broker.js +58 -0
  339. package/dist/web/broker.js.map +1 -0
  340. package/dist/web/open_browser.d.ts +2 -0
  341. package/dist/web/open_browser.d.ts.map +1 -0
  342. package/dist/web/open_browser.js +42 -0
  343. package/dist/web/open_browser.js.map +1 -0
  344. package/dist/web/server.d.ts +54 -0
  345. package/dist/web/server.d.ts.map +1 -0
  346. package/dist/web/server.js +831 -0
  347. package/dist/web/server.js.map +1 -0
  348. package/dist/web/static/app.js +4121 -0
  349. package/dist/web/static/index.html +2281 -0
  350. package/dist/web/static/js/MODULE_SUMMARY.md +124 -0
  351. package/dist/web/static/js/a11y.js +165 -0
  352. package/dist/web/static/js/admin.js +2145 -0
  353. package/dist/web/static/js/assistant.js +475 -0
  354. package/dist/web/static/js/calendar/reminders.js +114 -0
  355. package/dist/web/static/js/calendar/utils.js +166 -0
  356. package/dist/web/static/js/calendar.js +3348 -0
  357. package/dist/web/static/js/censor.js +356 -0
  358. package/dist/web/static/js/chat.js +4546 -0
  359. package/dist/web/static/js/chatRenderer.js +2294 -0
  360. package/dist/web/static/js/chatStream.js +276 -0
  361. package/dist/web/static/js/codeRunner.js +398 -0
  362. package/dist/web/static/js/color/hex.js +14 -0
  363. package/dist/web/static/js/colorPicker.js +453 -0
  364. package/dist/web/static/js/compare/icons.js +77 -0
  365. package/dist/web/static/js/compare/index.js +1482 -0
  366. package/dist/web/static/js/compare/models.js +104 -0
  367. package/dist/web/static/js/compare/panes.js +817 -0
  368. package/dist/web/static/js/compare/probe.js +78 -0
  369. package/dist/web/static/js/compare/scoreboard.js +223 -0
  370. package/dist/web/static/js/compare/selector.js +1335 -0
  371. package/dist/web/static/js/compare/state.js +58 -0
  372. package/dist/web/static/js/compare/stream.js +695 -0
  373. package/dist/web/static/js/compare/vote.js +254 -0
  374. package/dist/web/static/js/cookbook-diagnosis.js +694 -0
  375. package/dist/web/static/js/cookbook-hwfit.js +1888 -0
  376. package/dist/web/static/js/cookbook.js +2093 -0
  377. package/dist/web/static/js/cookbookDownload.js +633 -0
  378. package/dist/web/static/js/cookbookProgressSignal.js +29 -0
  379. package/dist/web/static/js/cookbookRunning.js +3506 -0
  380. package/dist/web/static/js/cookbookServe.js +2128 -0
  381. package/dist/web/static/js/document.js +9731 -0
  382. package/dist/web/static/js/documentLibrary.js +3376 -0
  383. package/dist/web/static/js/dragSort.js +265 -0
  384. package/dist/web/static/js/editor/ai-inpaint.js +374 -0
  385. package/dist/web/static/js/editor/ai-models.js +273 -0
  386. package/dist/web/static/js/editor/ai-rembg.js +230 -0
  387. package/dist/web/static/js/editor/ai-tool-runner.js +147 -0
  388. package/dist/web/static/js/editor/ai-tools-misc.js +216 -0
  389. package/dist/web/static/js/editor/build/controls.js +366 -0
  390. package/dist/web/static/js/editor/build/popups.js +112 -0
  391. package/dist/web/static/js/editor/build/right-panel.js +200 -0
  392. package/dist/web/static/js/editor/build/toolbar.js +73 -0
  393. package/dist/web/static/js/editor/build/topbar.js +131 -0
  394. package/dist/web/static/js/editor/build/transform-popup.js +109 -0
  395. package/dist/web/static/js/editor/canvas-coords.js +21 -0
  396. package/dist/web/static/js/editor/canvas-events.js +197 -0
  397. package/dist/web/static/js/editor/canvas-transforms.js +132 -0
  398. package/dist/web/static/js/editor/checkerboard.js +24 -0
  399. package/dist/web/static/js/editor/clipboard-and-drop.js +133 -0
  400. package/dist/web/static/js/editor/composite-helpers.js +83 -0
  401. package/dist/web/static/js/editor/filters/blur.js +118 -0
  402. package/dist/web/static/js/editor/filters/edge-feather.js +70 -0
  403. package/dist/web/static/js/editor/fx/adj-popup.js +677 -0
  404. package/dist/web/static/js/editor/fx/filter-string.js +38 -0
  405. package/dist/web/static/js/editor/fx/histogram.js +67 -0
  406. package/dist/web/static/js/editor/fx/pixel-pass.js +249 -0
  407. package/dist/web/static/js/editor/harmonize-masks.js +116 -0
  408. package/dist/web/static/js/editor/history-panel.js +176 -0
  409. package/dist/web/static/js/editor/keyboard-shortcuts.js +271 -0
  410. package/dist/web/static/js/editor/layer-helpers.js +131 -0
  411. package/dist/web/static/js/editor/layer-panel.js +600 -0
  412. package/dist/web/static/js/editor/mask-utils.js +91 -0
  413. package/dist/web/static/js/editor/shortcuts-popover.js +149 -0
  414. package/dist/web/static/js/editor/slider-ux.js +191 -0
  415. package/dist/web/static/js/editor/snap.js +107 -0
  416. package/dist/web/static/js/editor/state.js +257 -0
  417. package/dist/web/static/js/editor/stroke-pipeline.js +162 -0
  418. package/dist/web/static/js/editor/stroke-tool-sliders.js +64 -0
  419. package/dist/web/static/js/editor/tools/clone.js +81 -0
  420. package/dist/web/static/js/editor/tools/crop.js +137 -0
  421. package/dist/web/static/js/editor/tools/flood-fill.js +72 -0
  422. package/dist/web/static/js/editor/tools/lasso-mask.js +171 -0
  423. package/dist/web/static/js/editor/tools/lasso.js +65 -0
  424. package/dist/web/static/js/editor/tools/move.js +79 -0
  425. package/dist/web/static/js/editor/tools/stroke.js +123 -0
  426. package/dist/web/static/js/editor/tools/transform-drag.js +174 -0
  427. package/dist/web/static/js/editor/tools/transform-handles.js +271 -0
  428. package/dist/web/static/js/editor/tools/transform-session.js +381 -0
  429. package/dist/web/static/js/editor/tools/wand.js +46 -0
  430. package/dist/web/static/js/editor/wire-import.js +148 -0
  431. package/dist/web/static/js/editor/wire-inpaint-controls.js +164 -0
  432. package/dist/web/static/js/editor/wire-merge-buttons.js +103 -0
  433. package/dist/web/static/js/editor/wire-selection-controls.js +170 -0
  434. package/dist/web/static/js/editor/wire-topbar-menus.js +174 -0
  435. package/dist/web/static/js/editor/wire-topbar-overflow.js +49 -0
  436. package/dist/web/static/js/editor/wire-topbar.js +188 -0
  437. package/dist/web/static/js/emailInbox.js +1245 -0
  438. package/dist/web/static/js/emailLibrary/replyRecipients.js +27 -0
  439. package/dist/web/static/js/emailLibrary/signatureFold.js +339 -0
  440. package/dist/web/static/js/emailLibrary/state.js +34 -0
  441. package/dist/web/static/js/emailLibrary/utils.js +202 -0
  442. package/dist/web/static/js/emailLibrary.js +5217 -0
  443. package/dist/web/static/js/emojiPicker.js +311 -0
  444. package/dist/web/static/js/escMenuStack.js +102 -0
  445. package/dist/web/static/js/fileHandler.js +295 -0
  446. package/dist/web/static/js/gallery.js +2835 -0
  447. package/dist/web/static/js/galleryEditor.js +3798 -0
  448. package/dist/web/static/js/group.js +955 -0
  449. package/dist/web/static/js/init.js +405 -0
  450. package/dist/web/static/js/keyboard-shortcuts.js +292 -0
  451. package/dist/web/static/js/langIcons.js +187 -0
  452. package/dist/web/static/js/markdown/tableRow.js +19 -0
  453. package/dist/web/static/js/markdown.js +806 -0
  454. package/dist/web/static/js/memory.js +1418 -0
  455. package/dist/web/static/js/modalManager.js +1552 -0
  456. package/dist/web/static/js/modalSnap.js +782 -0
  457. package/dist/web/static/js/model/matchKey.js +19 -0
  458. package/dist/web/static/js/modelPicker.js +695 -0
  459. package/dist/web/static/js/modelSort.js +33 -0
  460. package/dist/web/static/js/models.js +642 -0
  461. package/dist/web/static/js/notes.js +5054 -0
  462. package/dist/web/static/js/package.json +1 -0
  463. package/dist/web/static/js/platform.js +47 -0
  464. package/dist/web/static/js/presets.js +1110 -0
  465. package/dist/web/static/js/providers.js +93 -0
  466. package/dist/web/static/js/rag.js +177 -0
  467. package/dist/web/static/js/research/jobs.js +335 -0
  468. package/dist/web/static/js/research/panel.js +1233 -0
  469. package/dist/web/static/js/researchSynapse.js +225 -0
  470. package/dist/web/static/js/search-chat.js +201 -0
  471. package/dist/web/static/js/search.js +52 -0
  472. package/dist/web/static/js/section-management.js +260 -0
  473. package/dist/web/static/js/sessions.js +3108 -0
  474. package/dist/web/static/js/settings.js +4991 -0
  475. package/dist/web/static/js/sidebar-layout.js +573 -0
  476. package/dist/web/static/js/signature.js +504 -0
  477. package/dist/web/static/js/skills.js +1908 -0
  478. package/dist/web/static/js/slashAutocomplete.js +267 -0
  479. package/dist/web/static/js/slashCommands.js +6099 -0
  480. package/dist/web/static/js/spinner.js +406 -0
  481. package/dist/web/static/js/storage.js +123 -0
  482. package/dist/web/static/js/tasks.js +2699 -0
  483. package/dist/web/static/js/theme.js +2086 -0
  484. package/dist/web/static/js/tileManager.js +386 -0
  485. package/dist/web/static/js/tourAutoplay.js +133 -0
  486. package/dist/web/static/js/tourHints.js +179 -0
  487. package/dist/web/static/js/tts-ai.js +521 -0
  488. package/dist/web/static/js/ui.js +1288 -0
  489. package/dist/web/static/js/util/ordinal.js +13 -0
  490. package/dist/web/static/js/voiceRecorder.js +283 -0
  491. package/dist/web/static/js/windowDrag.js +326 -0
  492. package/dist/web/static/js/windowResize.js +233 -0
  493. package/dist/web/static/landing.html +824 -0
  494. package/dist/web/static/lib/docx.umd.min.js +20116 -0
  495. package/dist/web/static/lib/highlight.min.js +1213 -0
  496. package/dist/web/static/lib/html2pdf.bundle.min.js +3 -0
  497. package/dist/web/static/lib/mammoth.browser.min.js +21 -0
  498. package/dist/web/static/lib/qrcode.min.js +8 -0
  499. package/dist/web/static/lib/xlsx.full.min.js +24 -0
  500. package/dist/web/static/login.html +582 -0
  501. package/dist/web/static/manifest.json +15 -0
  502. package/dist/web/static/style.css +35733 -0
  503. package/dist/web/static/sw.js +144 -0
  504. package/dist/workflows/engine.d.ts +162 -0
  505. package/dist/workflows/engine.d.ts.map +1 -0
  506. package/dist/workflows/engine.js +625 -0
  507. package/dist/workflows/engine.js.map +1 -0
  508. package/dist/workflows/index.d.ts +8 -0
  509. package/dist/workflows/index.d.ts.map +1 -0
  510. package/dist/workflows/index.js +14 -0
  511. package/dist/workflows/index.js.map +1 -0
  512. package/package.json +112 -0
@@ -0,0 +1,1399 @@
1
+ /**
2
+ * BERU — The Ant King — Agent Core v7
3
+ * =====================================
4
+ * Phase 1: TrajectoryStore, ConfidenceScorer, SelfCorrector — wired into exec()
5
+ * Phase 2: SwarmOrchestrator — parallel sub-agent (shadow army) execution
6
+ * Phase 3: ASTIndexer — real AST codebase understanding
7
+ * Phase 4: axonizDaemon — background file watcher + scheduled tasks
8
+ * Phase 5: PredictiveEngine — intent modeling from behavioral history
9
+ * Phase 6+: Persona engine (beru.yaml), authority engine
10
+ *
11
+ * Port of axoniz/core/agent.py. All tool invocations are awaited, so the agent
12
+ * loop, exec(), chat() and run() are async in this port.
13
+ */
14
+ import path from "node:path";
15
+ import crypto from "node:crypto";
16
+ import { ChatHistory } from "./history.js";
17
+ import { debug, error, info, warn, getLogger } from "./debug.js";
18
+ import { WorkspaceIndexer, GitTools, TokenCounter, ContextCompressor } from "./extras.js";
19
+ import { FileTools } from "../tools/file_tools.js";
20
+ import { ShellTools } from "../tools/shell_tools.js";
21
+ import { WebTools } from "../tools/web_tools.js";
22
+ import { CodeTools } from "../tools/code_tools.js";
23
+ import { AxodexTools } from "../tools/axodex_tools.js";
24
+ import { ComputerTools } from "../tools/computer_tools.js";
25
+ import { UnifiedMemory } from "../integrations/unified_memory.js";
26
+ import { getStore, ConfidenceScorer, SelfCorrector, SwarmOrchestrator, ASTIndexer, axonizDaemon, PredictiveEngine, SkillDistiller, } from "./intelligence/index.js";
27
+ import { ShadowGuardReflex } from "./intelligence/reflex.js";
28
+ import { SemanticMemory as Memory } from "./memory.js";
29
+ import { getPersona } from "./persona.js";
30
+ import { TOOL_SCHEMAS } from "./tool_schemas.js";
31
+ import { getBackend, isToolCallResponse, } from "./backend/index.js";
32
+ export { Memory };
33
+ /* ── Phase 7 lazy singletons: Authority / Workflows / Awareness / TTS / Goals ── */
34
+ let authorityEngine = null;
35
+ let workflowEngine = null;
36
+ let awarenessSvc = null;
37
+ let ttsEngine = null;
38
+ let goalService = null;
39
+ void awarenessSvc;
40
+ async function getAuthority() {
41
+ if (authorityEngine === null) {
42
+ try {
43
+ const m = (await import("./authority.js"));
44
+ authorityEngine = m.getEngine();
45
+ }
46
+ catch {
47
+ authorityEngine = false;
48
+ }
49
+ }
50
+ return authorityEngine === false ? null : authorityEngine;
51
+ }
52
+ async function getWorkflows() {
53
+ if (workflowEngine === null) {
54
+ try {
55
+ const m = (await import("../workflows/engine.js"));
56
+ workflowEngine = m.getWorkflowEngine();
57
+ }
58
+ catch {
59
+ workflowEngine = false;
60
+ }
61
+ }
62
+ return workflowEngine === false ? null : workflowEngine;
63
+ }
64
+ async function getTts() {
65
+ if (ttsEngine === null) {
66
+ try {
67
+ const m = (await import("../voice/tts.js"));
68
+ ttsEngine = m.getTts();
69
+ }
70
+ catch {
71
+ ttsEngine = false;
72
+ }
73
+ }
74
+ return ttsEngine === false ? null : ttsEngine;
75
+ }
76
+ async function getGoals() {
77
+ if (goalService === null) {
78
+ try {
79
+ const m = (await import("../goals/service.js"));
80
+ goalService = m.getGoalService();
81
+ }
82
+ catch {
83
+ goalService = false;
84
+ }
85
+ }
86
+ return goalService === false ? null : goalService;
87
+ }
88
+ /* ── Fallback system prompt (only if persona YAML fails to load) ──────────── */
89
+ const FALLBACK_SYSTEM_PROMPT = "You are FRAZIYM AI, a local-first AI agent.\n" +
90
+ "Execute tasks with tools. Never guess. Read before editing. Verify after changes.\n" +
91
+ "When done, call done() with a concise summary.";
92
+ /* ── Fallback tool-call parsing ───────────────────────────────────────────── */
93
+ const TOOL_RE = /<tool>([\s\S]*?)<\/tool>/g;
94
+ const JSON_FENCE_RE = /```(?:json)?\s*([\s\S]*?)```/g;
95
+ /** Aggressive cleanup for 3B hallucinations (trailing commas, extra braces). */
96
+ function cleanupJson(content) {
97
+ let text = content.replace(/,(\s*[}\]])/g, "$1");
98
+ if (text.startsWith("{")) {
99
+ let count = 0;
100
+ let endIdx = -1;
101
+ for (let i = 0; i < text.length; i++) {
102
+ if (text[i] === "{")
103
+ count++;
104
+ else if (text[i] === "}")
105
+ count--;
106
+ if (count === 0) {
107
+ endIdx = i;
108
+ break;
109
+ }
110
+ }
111
+ if (endIdx !== -1)
112
+ text = text.slice(0, endIdx + 1);
113
+ }
114
+ return text;
115
+ }
116
+ function coerceArgs(raw) {
117
+ if (typeof raw === "string") {
118
+ try {
119
+ const parsed = JSON.parse(raw);
120
+ return parsed && typeof parsed === "object" ? parsed : {};
121
+ }
122
+ catch {
123
+ return {};
124
+ }
125
+ }
126
+ return raw && typeof raw === "object" ? raw : {};
127
+ }
128
+ function callFromObject(obj) {
129
+ const name = obj.name ?? obj.tool ?? obj.function;
130
+ if (!name)
131
+ return null;
132
+ return { name: String(name), args: coerceArgs(obj.args ?? obj.arguments ?? obj.parameters ?? {}) };
133
+ }
134
+ export function parseFallbackCalls(text) {
135
+ const calls = [];
136
+ // 1. Primary: <tool>{...}</tool>
137
+ for (const m of text.matchAll(TOOL_RE)) {
138
+ const content = cleanupJson((m[1] ?? "").trim());
139
+ try {
140
+ const obj = JSON.parse(content);
141
+ const call = callFromObject(obj);
142
+ if (call)
143
+ calls.push(call);
144
+ }
145
+ catch {
146
+ const fnMatch = content.match(/"(?:name|tool|function)"\s*:\s*"(\w+)"/);
147
+ if (fnMatch)
148
+ calls.push({ name: fnMatch[1], args: {} });
149
+ }
150
+ }
151
+ if (calls.length > 0)
152
+ return calls;
153
+ // 2. ```json fenced blocks
154
+ for (const m of text.matchAll(JSON_FENCE_RE)) {
155
+ try {
156
+ const obj = JSON.parse((m[1] ?? "").trim());
157
+ const name = obj.name ?? obj.tool;
158
+ if (name)
159
+ calls.push({ name: String(name), args: coerceArgs(obj.args ?? obj.arguments ?? {}) });
160
+ }
161
+ catch {
162
+ /* ignore */
163
+ }
164
+ }
165
+ if (calls.length > 0)
166
+ return calls;
167
+ // 3. Bare {"name": "...", ...} objects
168
+ for (const m of text.matchAll(/\{[^{}]*"name"\s*:\s*"(\w+)"[^{}]*\}/g)) {
169
+ try {
170
+ const obj = JSON.parse(m[0]);
171
+ const name = obj.name ?? obj.tool;
172
+ if (name)
173
+ calls.push({ name: String(name), args: coerceArgs(obj.args ?? obj.arguments ?? {}) });
174
+ }
175
+ catch {
176
+ /* ignore */
177
+ }
178
+ }
179
+ return calls;
180
+ }
181
+ const DONE_MARKERS = [
182
+ "task complete",
183
+ "task is complete",
184
+ "all done",
185
+ "i have completed",
186
+ "i've completed",
187
+ "finished.",
188
+ "the task has been",
189
+ "<endofop>",
190
+ "i have finished",
191
+ "successfully completed",
192
+ "no more steps",
193
+ "everything is done",
194
+ "task accomplished",
195
+ ];
196
+ export function isDone(text) {
197
+ const t = text.toLowerCase();
198
+ return DONE_MARKERS.some((s) => t.includes(s));
199
+ }
200
+ /** Simple abort signal wrapper mirroring Python's threading.Event. */
201
+ export class AbortFlag {
202
+ flag = false;
203
+ set() {
204
+ this.flag = true;
205
+ }
206
+ clear() {
207
+ this.flag = false;
208
+ }
209
+ isSet() {
210
+ return this.flag;
211
+ }
212
+ }
213
+ export class Agent {
214
+ config;
215
+ workspace;
216
+ /* Core tools */
217
+ fileTools;
218
+ shellTools;
219
+ webTools;
220
+ codeTools;
221
+ computerTools;
222
+ reflex;
223
+ history;
224
+ gitTools;
225
+ indexer;
226
+ astIndex;
227
+ axodex;
228
+ /* Intelligence */
229
+ compressor;
230
+ memory;
231
+ persona;
232
+ trajectory;
233
+ confidence;
234
+ corrector;
235
+ daemon;
236
+ predictor;
237
+ distiller;
238
+ standby;
239
+ llm = null;
240
+ backend = null;
241
+ llmLoaded = false;
242
+ useNative = true;
243
+ toolMap = new Map();
244
+ trajSessionId = null;
245
+ finished = false;
246
+ finalResult = null;
247
+ abortFlag = null;
248
+ stepCounter = 0;
249
+ taskText = "";
250
+ /** Structured log of every tool invocation in this session. */
251
+ observations = [];
252
+ onStep = null;
253
+ onToken = null;
254
+ onThought = null;
255
+ onToolCall = null;
256
+ onToolResult = null;
257
+ onDone = null;
258
+ constructor(kwargs = {}) {
259
+ const drop = new Set(["web_port", "_home", "_models_dir"]);
260
+ this.config = Object.fromEntries(Object.entries(kwargs).filter(([k]) => !drop.has(k)));
261
+ this.workspace = path.resolve(String(kwargs.workspace ?? "."));
262
+ // ── Core tools ──
263
+ this.fileTools = new FileTools(this.workspace);
264
+ this.shellTools = new ShellTools(this.workspace);
265
+ this.webTools = new WebTools(this.workspace);
266
+ this.codeTools = new CodeTools(this.workspace);
267
+ this.computerTools = new ComputerTools(this.workspace);
268
+ this.reflex = new ShadowGuardReflex(this);
269
+ this.history = new ChatHistory();
270
+ this.gitTools = new GitTools(this.workspace);
271
+ this.indexer = new WorkspaceIndexer(this.workspace);
272
+ this.astIndex = new ASTIndexer(this.workspace);
273
+ this.axodex = new AxodexTools(this.workspace);
274
+ // ── Context compression (Phase 6+) ──
275
+ // NOTE: ContextCompressor lives in extras.ts (ported with the core utilities).
276
+ // Its constructor is positional: (maxTokens, keepTail).
277
+ this.compressor = new ContextCompressor(Math.max(1000, Math.floor(Number(this.config.n_ctx ?? 32768) * 0.4)), 6);
278
+ // Standby mode — don't load LLM weights on startup
279
+ this.standby = Boolean(kwargs.standby ?? false);
280
+ // Unified memory (TF-IDF + Palace + KG + Diary)
281
+ this.memory = new UnifiedMemory({
282
+ agent_name: String(kwargs.agent_name ?? "beru"),
283
+ });
284
+ // ── Persona (BERU identity + role system) ──
285
+ this.persona = getPersona(String(kwargs.role ?? "beru"));
286
+ // ── Phase 1: self-aware execution intelligence ──
287
+ this.trajectory = getStore();
288
+ this.confidence = new ConfidenceScorer({
289
+ risk_threshold: Number(kwargs.risk_threshold ?? 0.75),
290
+ trajectory_store: this.trajectory,
291
+ });
292
+ this.corrector = new SelfCorrector();
293
+ // ── Phase 4: background daemon — always on ──
294
+ this.daemon = new axonizDaemon({
295
+ agent: this,
296
+ workspace: this.workspace,
297
+ on_event: (e) => this.onDaemonEvent(e),
298
+ });
299
+ try {
300
+ this.daemon.start();
301
+ }
302
+ catch (e) {
303
+ warn(`[Daemon] failed to start: ${errText(e)}`);
304
+ }
305
+ // ── Phase 5 + 11 ──
306
+ this.predictor = new PredictiveEngine(this);
307
+ this.distiller = new SkillDistiller(this);
308
+ // ── Tool map ──
309
+ this.registerTools();
310
+ if (!this.standby)
311
+ this.buildLlm();
312
+ }
313
+ /* ── Tool registration ─────────────────────────────────────────────────── */
314
+ registerTools() {
315
+ const t = this.toolMap;
316
+ t.set("file_read", (a) => this.fileTools.read(String(a?.path ?? "")));
317
+ t.set("file_write", (a) => this.fileTools.write(String(a?.path ?? ""), String(a?.content ?? "")));
318
+ t.set("file_edit", (a) => this.fileTools.edit(String(a?.path ?? ""), String(a?.old ?? ""), String(a?.new ?? "")));
319
+ t.set("file_delete", (a) => this.fileTools.delete(String(a?.path ?? "")));
320
+ t.set("file_list", (a) => this.fileTools.listDir(String(a?.path ?? ".")));
321
+ t.set("file_search", (a) => this.fileTools.search(String(a?.path ?? "."), String(a?.pattern ?? "*")));
322
+ t.set("file_append", (a) => this.fileTools.append(String(a?.path ?? ""), String(a?.content ?? "")));
323
+ t.set("shell_run", (a) => this.shellTools.run(String(a?.command ?? "")));
324
+ t.set("shell_python", (a) => this.shellTools.runPython(String(a?.code ?? "")));
325
+ t.set("web_get", (a) => this.webTools.get(String(a?.url ?? "")));
326
+ t.set("web_search", (a) => this.webTools.search(String(a?.query ?? "")));
327
+ t.set("war_room", () => this.toolWarRoom());
328
+ t.set("code_lint", (a) => this.codeTools.lint(String(a?.path ?? "")));
329
+ t.set("code_format", (a) => this.codeTools.formatCode(String(a?.path ?? "")));
330
+ t.set("code_tree", (a) => this.codeTools.tree(String(a?.path ?? ".")));
331
+ t.set("code_analyze", (a) => this.codeTools.analyze(String(a?.path ?? ".")));
332
+ t.set("done", (a) => this.done(String(a?.result ?? "")));
333
+ t.set("get_time", (a) => this.toolGetTime(String(a?.query ?? "all")));
334
+ t.set("optimize_hardware", () => this.toolOptimizeHardware());
335
+ // Injected sub-system tool maps
336
+ for (const [k, v] of Object.entries(this.computerTools.asToolMap()))
337
+ t.set(k, adapt(v));
338
+ for (const [k, v] of Object.entries(this.memory.asToolMap()))
339
+ t.set(k, adapt(v));
340
+ for (const [k, v] of Object.entries(this.gitTools.asToolMap()))
341
+ t.set(k, adapt(v));
342
+ t.set("absolute_query", (a) => this.toolAbsoluteQuery(String(a?.query ?? "")));
343
+ // Swarm (The Shadow Army)
344
+ t.set("swarm_spawn", (a) => this.toolSwarmSpawn(String(a?.task ?? ""), Number(a?.workers ?? 4)));
345
+ t.set("shadow_step", (a) => this.toolShadowStep(String(a?.task ?? ""), String(a?.test_cmd ?? "npm test")));
346
+ // Axodex (The Marshal's Eye)
347
+ t.set("axodex_query", (a) => this.axodex.query(String(a?.query ?? ""), Number(a?.limit ?? 10)));
348
+ t.set("axodex_context", (a) => this.axodex.context(String(a?.name ?? "")));
349
+ t.set("axodex_smart_read", (a) => this.axodex.smart_read(String(a?.symbol_name ?? "")));
350
+ t.set("axodex_impact", (a) => this.axodex.impact(String(a?.target ?? ""), String(a?.direction ?? "upstream")));
351
+ t.set("axodex_detect_changes", () => this.axodex.detect_changes());
352
+ t.set("axodex_status", () => this.axodex.status());
353
+ t.set("axodex_analyze", () => this.axodex.analyze());
354
+ // Goals (Phase 11)
355
+ t.set("goal_create", (a) => this.toolGoalCreate(String(a?.title ?? ""), String(a?.description ?? ""), String(a?.deadline ?? ""), String(a?.priority ?? "high")));
356
+ t.set("goal_list", (a) => this.toolGoalList(String(a?.status ?? "active")));
357
+ t.set("goal_kr_add", (a) => this.toolGoalKrAdd(String(a?.goal_id ?? ""), String(a?.title ?? ""), String(a?.target ?? ""), String(a?.deadline ?? "")));
358
+ t.set("goal_action_add", (a) => this.toolGoalActionAdd(String(a?.kr_id ?? ""), String(a?.title ?? ""), String(a?.scheduled_date ?? "")));
359
+ t.set("goal_update_score", (a) => this.toolGoalUpdateScore(String(a?.goal_id ?? ""), Number(a?.score ?? 0), a?.kr_id === undefined || a?.kr_id === null ? null : String(a.kr_id)));
360
+ t.set("goal_action_complete", (a) => this.toolGoalActionComplete(String(a?.action_id ?? "")));
361
+ t.set("goal_report", () => this.toolGoalReport());
362
+ }
363
+ /** Names of every registered tool (used for prompt rendering). */
364
+ toolNames() {
365
+ return [...this.toolMap.keys()];
366
+ }
367
+ hasTool(name) {
368
+ return this.toolMap.has(name);
369
+ }
370
+ /** The most recent observation, or null if none recorded. */
371
+ get lastObservation() {
372
+ return this.observations.length > 0 ? this.observations[this.observations.length - 1] : null;
373
+ }
374
+ /** Summary stats for all observations in this session. */
375
+ observationStats() {
376
+ let succeeded = 0;
377
+ let failed = 0;
378
+ let total_ms = 0;
379
+ for (const o of this.observations) {
380
+ if (o.success)
381
+ succeeded++;
382
+ else
383
+ failed++;
384
+ total_ms += o.duration_ms;
385
+ }
386
+ return { total: this.observations.length, succeeded, failed, total_ms };
387
+ }
388
+ /* ── Daemon event handler ──────────────────────────────────────────────── */
389
+ onDaemonEvent(event) {
390
+ const { kind, payload } = event;
391
+ if (kind === "syntax_error") {
392
+ warn(`[Daemon] Syntax error in ${payload.file}: ${payload.error}`);
393
+ this.onToken?.(`\n[\u26a1 Daemon] Syntax error detected in ${payload.file}: ${payload.error}\n`);
394
+ }
395
+ else if (kind === "git_uncommitted") {
396
+ debug(`[Daemon] ${payload.count} uncommitted file(s)`);
397
+ }
398
+ else if (kind === "daily_audit") {
399
+ info(`[Daemon] Audit: ${payload.files_checked} files, ${payload.syntax_errors} errors`);
400
+ }
401
+ }
402
+ /* ── Phase 2: Swarm ────────────────────────────────────────────────────── */
403
+ /**
404
+ * Run a task using the domain-expert swarm. Progress events are broadcast over
405
+ * the SSE broker so the UI can display live swarm status.
406
+ */
407
+ async runSwarm(task, maxWorkers = 4, onProgress) {
408
+ let progress = onProgress;
409
+ try {
410
+ const { broker } = (await import("../web/broker.js"));
411
+ progress = (event) => {
412
+ broker.broadcast("swarm_event", event);
413
+ const ev = String(event.event ?? "");
414
+ const name = String(event.model ?? event.desc ?? "");
415
+ this.onToken?.(name ? `\n[\u26a1 Swarm:${ev}] ${name}\n` : `\n[\u26a1 Swarm] ${ev}\n`);
416
+ };
417
+ }
418
+ catch {
419
+ progress = onProgress ?? (this.onToken ? (e) => this.onToken?.(JSON.stringify(e)) : undefined);
420
+ }
421
+ const swarm = new SwarmOrchestrator({
422
+ agent: this,
423
+ max_workers: maxWorkers,
424
+ on_progress: progress,
425
+ });
426
+ const result = await swarm.run(task);
427
+ info(`[Swarm] \u2713 Done: ${result.total_ms}ms | ${result.parallelism.toFixed(1)}x speedup`);
428
+ return result.merged;
429
+ }
430
+ /* ── Abort ─────────────────────────────────────────────────────────────── */
431
+ setAbortEvent(ev) {
432
+ this.abortFlag = ev;
433
+ }
434
+ aborted() {
435
+ return this.abortFlag !== null && this.abortFlag.isSet();
436
+ }
437
+ /** Alias matching the Python name. */
438
+ set_abort_event(ev) {
439
+ this.setAbortEvent(ev);
440
+ }
441
+ /* ── LLM lifecycle ─────────────────────────────────────────────────────── */
442
+ ensureLlm() {
443
+ if (this.llm === null || !this.llmLoaded) {
444
+ info("[Agent] Deploying heavy model weights...");
445
+ this.buildLlm();
446
+ this.llmLoaded = true;
447
+ return true;
448
+ }
449
+ return false;
450
+ }
451
+ ensure_llm() {
452
+ return this.ensureLlm();
453
+ }
454
+ unloadLlm() {
455
+ if (!this.llm)
456
+ return false;
457
+ info("[Agent] Unloading model weights to free RAM...");
458
+ try {
459
+ this.llm.unload();
460
+ }
461
+ catch {
462
+ /* ignore */
463
+ }
464
+ this.llm = null;
465
+ this.backend = null;
466
+ this.llmLoaded = false;
467
+ return true;
468
+ }
469
+ unload_llm() {
470
+ return this.unloadLlm();
471
+ }
472
+ async authoritySummary() {
473
+ const ae = await getAuthority();
474
+ if (!ae)
475
+ return { status: "disabled" };
476
+ return {
477
+ status: "active",
478
+ summary: ae.summary(),
479
+ stats: ae.audit.stats(),
480
+ max_auto_level: ae.max_auto_level,
481
+ };
482
+ }
483
+ async authorityAudit(limit = 20) {
484
+ const ae = await getAuthority();
485
+ if (!ae)
486
+ return [];
487
+ return ae.audit.recent(limit);
488
+ }
489
+ get availableTools() {
490
+ const def = this.config.definition;
491
+ if (!def || !def.tool_config || !def.tool_config.tool_names) {
492
+ return TOOL_SCHEMAS;
493
+ }
494
+ const allowed = new Set(def.tool_config.tool_names);
495
+ return TOOL_SCHEMAS.filter(t => allowed.has(t.function.name));
496
+ }
497
+ buildLlm() {
498
+ // llama.cpp supports tool calling natively via model templates.
499
+ this.useNative = true;
500
+ this.llm = getBackend(this.config, this.availableTools);
501
+ this.backend = this.llm; // Sovereign alias
502
+ this.llmLoaded = true;
503
+ info(`[Agent] backend=${this.llm.name}`);
504
+ }
505
+ rebuildLlm() {
506
+ this.buildLlm();
507
+ }
508
+ /** Public rebuild hook for the web server's config/model-switch routes. */
509
+ rebuildLlmPublic() {
510
+ this.rebuildLlm();
511
+ }
512
+ /** Public wrapper for the War Room summary (used by GET /api/war_room). */
513
+ warRoom() {
514
+ return this.toolWarRoom();
515
+ }
516
+ /** Public wrapper for the absolute query tool (used by GET /api/absolute_query). */
517
+ absoluteQuery(query) {
518
+ return this.toolAbsoluteQuery(query);
519
+ }
520
+ /** Effective configured model path, for the UI. */
521
+ modelPath() {
522
+ const llm = this.config.llm;
523
+ const prov = llm?.active_provider ?? String(this.config.provider ?? "llamacpp");
524
+ return String(llm?.providers?.[prov]?.model_path ?? this.config.model_path ?? "");
525
+ }
526
+ /** Replace the live config (used after /api/config/save). */
527
+ applyConfig(cfg) {
528
+ Object.assign(this.config, cfg);
529
+ this.rebuildLlm();
530
+ }
531
+ /** Run a task with an abort flag, so the UI's Stop button works. */
532
+ async runAbortable(task, flag) {
533
+ this.setAbortEvent(flag);
534
+ try {
535
+ return await this.run(task);
536
+ }
537
+ finally {
538
+ this.setAbortEvent(null);
539
+ }
540
+ }
541
+ /* ── Compound tools ────────────────────────────────────────────────────── */
542
+ /** Queries BOTH the code graph and semantic memory. */
543
+ async toolAbsoluteQuery(query) {
544
+ let axRes = await this.axodex.query(query);
545
+ if (axRes.includes("[AXODEX ERROR] No index found")) {
546
+ axRes += "\n\u{1F4A1} HINT: Call 'axodex_analyze' to build the first graph for this workspace.";
547
+ }
548
+ const palRes = (await this.memory.palace.search(query, { limit: 5 }));
549
+ const palLines = (palRes.results ?? []).map((h) => ` [${h.wing}/${h.room}] ${h.text.slice(0, 200)}`);
550
+ return (`--- AXODEX (Code Graph) ---\n${axRes}\n\n` +
551
+ `--- MEMPALACE (Long-term) ---\n` +
552
+ (palLines.length > 0 ? palLines.join("\n") : "No memory found."));
553
+ }
554
+ /** Decompose a complex task and execute it in parallel using a swarm. */
555
+ async toolSwarmSpawn(task, workers = 4) {
556
+ const swarm = new SwarmOrchestrator({ agent: this, max_workers: workers });
557
+ const result = await swarm.run(task);
558
+ if (result.success) {
559
+ return (`[SWARM SUCCESS] Parallelized task complete in ${result.total_ms}ms ` +
560
+ `(${result.parallelism}x speedup).\n\n${result.merged}`);
561
+ }
562
+ return `[SWARM FAILED] Swarm could not complete task: ${result.merged}`;
563
+ }
564
+ /** Speculative execution in a shadow branch. */
565
+ async toolShadowStep(task, testCmd = "npm test") {
566
+ const branchId = crypto.randomBytes(6).toString("hex").slice(0, 6);
567
+ const shadowBranch = `shadow/${branchId}`;
568
+ const originalBranch = await this.gitTools.currentBranch();
569
+ info(`[Shadow-Step] Stepping into shadow: ${shadowBranch}`);
570
+ try {
571
+ await this.gitTools.checkout(shadowBranch, true);
572
+ const res = await this.run(task);
573
+ const testRes = await this.shellTools.run(testCmd);
574
+ const lower = testRes.toLowerCase();
575
+ if (!lower.includes("failed") && !lower.includes("error")) {
576
+ await this.gitTools.checkout(originalBranch);
577
+ return (`[SHADOW SUCCESS] Task completed and verified in ${shadowBranch}.\n` +
578
+ `Tests: ${testRes.slice(0, 500)}\n` +
579
+ `Action: You can now 'git merge ${shadowBranch}' to apply changes.`);
580
+ }
581
+ warn(`[Shadow-Step] Shadow verification FAILED. Retracting to ${originalBranch}`);
582
+ await this.gitTools.checkout(originalBranch);
583
+ return `[SHADOW FAILED] Speculative execution failed tests:\n${testRes.slice(0, 500)}`;
584
+ }
585
+ catch (e) {
586
+ error(`[Shadow-Step] Shadow failed: ${errText(e)}`);
587
+ try {
588
+ await this.gitTools.checkout(originalBranch);
589
+ }
590
+ catch {
591
+ /* ignore */
592
+ }
593
+ return `[SHADOW ERROR] ${errText(e)}`;
594
+ }
595
+ finally {
596
+ try {
597
+ if ((await this.gitTools.currentBranch()) !== originalBranch) {
598
+ await this.gitTools.checkout(originalBranch);
599
+ }
600
+ }
601
+ catch {
602
+ /* ignore */
603
+ }
604
+ }
605
+ }
606
+ /** Summary of background daemon events, audits, and uncommitted changes. */
607
+ toolWarRoom() {
608
+ const st = this.daemon.status();
609
+ const events = this.daemon.getRecentEvents(10);
610
+ const lines = [`[War Room] Status: ${st.running ? "ACTIVE" : "INACTIVE"}`];
611
+ lines.push(` Pending lints: ${st.pending_lint}`);
612
+ if (events.length > 0) {
613
+ lines.push(" Recent background events:");
614
+ for (const ev of events) {
615
+ const ts = new Date((ev.ts ?? 0) * 1000).toTimeString().slice(0, 8);
616
+ lines.push(` [${ts}] ${ev.kind}: ${JSON.stringify(ev.payload).slice(0, 100)}...`);
617
+ }
618
+ }
619
+ else {
620
+ lines.push(" No recent background events.");
621
+ }
622
+ return lines.join("\n");
623
+ }
624
+ /** Return current time/date info. Fast — no LLM needed. */
625
+ toolGetTime(query = "all") {
626
+ const now = new Date();
627
+ const q = query.toLowerCase();
628
+ const dayName = WEEKDAYS[now.getDay()];
629
+ const monthName = MONTHS[now.getMonth()];
630
+ const h12 = now.getHours() % 12 || 12;
631
+ const ampm = now.getHours() < 12 ? "AM" : "PM";
632
+ const timeStr = `${h12}:${pad2(now.getMinutes())} ${ampm}`;
633
+ const dateStr = `${dayName}, ${monthName} ${pad2(now.getDate())} ${now.getFullYear()}`;
634
+ if (q.includes("time") && !q.includes("date") && q !== "all")
635
+ return timeStr;
636
+ if (q.includes("date") && !q.includes("time"))
637
+ return dateStr;
638
+ if (q.includes("day"))
639
+ return dayName;
640
+ if (q.includes("year"))
641
+ return String(now.getFullYear());
642
+ const offsetMin = -now.getTimezoneOffset();
643
+ const sign = offsetMin >= 0 ? "+" : "-";
644
+ const abs = Math.abs(offsetMin);
645
+ const offset = `${sign}${pad2(Math.floor(abs / 60))}${pad2(abs % 60)}`;
646
+ return `${dateStr} ${timeStr} (UTC offset: ${offset})`;
647
+ }
648
+ done(result = "") {
649
+ this.finished = true;
650
+ this.finalResult = result;
651
+ return `[DONE] ${result}`;
652
+ }
653
+ /** Benchmark and optimize the backend for local hardware. */
654
+ async toolOptimizeHardware() {
655
+ try {
656
+ const m = (await import("./optimizer.js"));
657
+ const optimized = await m.applyOptimizations(this);
658
+ return `[OK] Hardware optimized: ${JSON.stringify(optimized, null, 2)}`;
659
+ }
660
+ catch (e) {
661
+ return `[ERROR] Optimization failed: ${errText(e)}`;
662
+ }
663
+ }
664
+ /* ── Goal tools (Phase 11) ─────────────────────────────────────────────── */
665
+ async toolGoalCreate(title, description = "", deadline = "", priority = "high") {
666
+ const gs = await getGoals();
667
+ if (!gs)
668
+ return "[ERROR] Goal service unavailable";
669
+ const g = gs.create_goal(title, description, deadline, priority);
670
+ return `[OK] Goal created: ${g.title} (id=${g.id})`;
671
+ }
672
+ async toolGoalList(status = "active") {
673
+ const gs = await getGoals();
674
+ if (!gs)
675
+ return "[ERROR] Goal service unavailable";
676
+ const goals = gs.list_goals(status);
677
+ if (goals.length === 0)
678
+ return "No goals found.";
679
+ return goals
680
+ .map((g) => {
681
+ const prio = typeof g.priority === "string" ? g.priority : g.priority.value;
682
+ return `[${g.id}] ${g.title} | score: ${Math.round(g.score * 100)}% | priority: ${prio}`;
683
+ })
684
+ .join("\n");
685
+ }
686
+ async toolGoalKrAdd(goalId, title, target = "", deadline = "") {
687
+ const gs = await getGoals();
688
+ if (!gs)
689
+ return "[ERROR] Goal service unavailable";
690
+ const kr = gs.add_key_result(goalId, title, target, deadline);
691
+ return `[OK] Key Result added: ${kr.title} (id=${kr.id})`;
692
+ }
693
+ async toolGoalActionAdd(krId, title, scheduledDate = "") {
694
+ const gs = await getGoals();
695
+ if (!gs)
696
+ return "[ERROR] Goal service unavailable";
697
+ const da = gs.add_daily_action(krId, title, scheduledDate);
698
+ return `[OK] Daily Action added: ${da.title} (id=${da.id})`;
699
+ }
700
+ async toolGoalUpdateScore(goalId, score, krId = null) {
701
+ const gs = await getGoals();
702
+ if (!gs)
703
+ return "[ERROR] Goal service unavailable";
704
+ return `[OK] ${gs.update_score(goalId, score, krId)}`;
705
+ }
706
+ async toolGoalActionComplete(actionId) {
707
+ const gs = await getGoals();
708
+ if (!gs)
709
+ return "[ERROR] Goal service unavailable";
710
+ return `[OK] ${gs.complete_action(actionId)}`;
711
+ }
712
+ async toolGoalReport() {
713
+ const gs = await getGoals();
714
+ if (!gs)
715
+ return "[ERROR] Goal service unavailable";
716
+ return gs.daily_report();
717
+ }
718
+ /* ── Tool execution — the core of Phase 1 ──────────────────────────────── */
719
+ /**
720
+ * Execute a tool with:
721
+ * 0. Authority engine gate
722
+ * 1. Confidence/risk gate
723
+ * 2. Timed execution
724
+ * 3. Trajectory recording
725
+ * 4. Self-correction analysis
726
+ */
727
+ async exec(name, args) {
728
+ const fn = this.toolMap.get(name);
729
+ if (!fn)
730
+ return `[ERROR] Unknown tool '${name}'`;
731
+ const def = this.config.definition;
732
+ if (def && def.tool_config && def.tool_config.tool_names) {
733
+ if (!def.tool_config.tool_names.includes(name)) {
734
+ return `[ERROR] Tool '${name}' is not available to this agent role.`;
735
+ }
736
+ }
737
+ // 0. Authority engine gate
738
+ const authority = await getAuthority();
739
+ if (authority && !["done", "memory_get", "memory_list"].includes(name)) {
740
+ const decision = authority.check(name, args, this.trajSessionId ?? "");
741
+ if (!decision.approved) {
742
+ const blocked = `[AUTHORITY BLOCKED] '${name}' denied: ${decision.reason}`;
743
+ this.onToolResult?.(name, blocked);
744
+ return blocked;
745
+ }
746
+ }
747
+ // 1a. Axodex guard — record impact context before mutating files
748
+ if (["file_edit", "file_write", "file_delete"].includes(name) && "path" in args) {
749
+ try {
750
+ const impact = await this.axodex.impact(String(args.path));
751
+ if (!impact.includes("[AXODEX ERROR]")) {
752
+ debug(`[Guard] Impact for ${String(args.path)}: ${impact.slice(0, 100)}...`);
753
+ }
754
+ }
755
+ catch {
756
+ /* guard is advisory */
757
+ }
758
+ }
759
+ // 1b. Confidence / risk gate
760
+ const check = await this.confidence.check({
761
+ tool_name: name,
762
+ args,
763
+ task: this.taskText,
764
+ session_id: this.trajSessionId ?? "",
765
+ });
766
+ if (!check.allow) {
767
+ const warningMsg = this.confidence.formatWarning(check, name, args);
768
+ const blockedMsg = `[BLOCKED BY CONFIDENCE SCORER]\n${warningMsg}\n` +
769
+ `Risk ${Math.round(check.risk * 100)}% exceeds threshold ` +
770
+ `${Math.round(this.confidence.risk_threshold * 100)}%. Choose a safer approach.`;
771
+ if (this.trajSessionId) {
772
+ this.trajectory.recordStep({
773
+ session_id: this.trajSessionId,
774
+ step_num: this.stepCounter,
775
+ tool_name: name,
776
+ args,
777
+ result: blockedMsg,
778
+ success: false,
779
+ duration_ms: 0,
780
+ notes: `BLOCKED: ${check.reason}`,
781
+ });
782
+ }
783
+ this.onToolResult?.(name, blockedMsg);
784
+ return blockedMsg;
785
+ }
786
+ // 2. Execute with timing
787
+ const t0 = Date.now();
788
+ let result;
789
+ let success;
790
+ try {
791
+ const raw = await fn(args);
792
+ result = raw === null || raw === undefined ? "OK" : String(raw);
793
+ // Phase 8: high-precision truncation
794
+ if (result.length > 2000) {
795
+ result =
796
+ `${result.slice(0, 1000)}\n\n` +
797
+ `... [TRUNCATED ${result.length - 2000} characters to prevent context drowning] ...\n\n` +
798
+ `${result.slice(-1000)}\n` +
799
+ `HINT: Use 'axodex_smart_read' for architectural context or 'file_read' with line ranges.`;
800
+ }
801
+ success = true;
802
+ }
803
+ catch (e) {
804
+ if (e instanceof TypeError) {
805
+ result = `[ERROR] Bad args for '${name}': ${errText(e)}`;
806
+ }
807
+ else {
808
+ result = `[ERROR] '${name}' failed: ${errText(e)}`;
809
+ }
810
+ success = false;
811
+ }
812
+ const durationMs = Date.now() - t0;
813
+ // 3. Record to trajectory
814
+ if (this.trajSessionId) {
815
+ this.trajectory.recordStep({
816
+ session_id: this.trajSessionId,
817
+ step_num: this.stepCounter,
818
+ tool_name: name,
819
+ args,
820
+ result,
821
+ success,
822
+ duration_ms: durationMs,
823
+ });
824
+ }
825
+ this.stepCounter += 1;
826
+ // 4. Self-correction analysis
827
+ const analysis = this.corrector.analyze(name, args, result, this.stepCounter);
828
+ if (analysis.has_error) {
829
+ const correctionMsg = this.corrector.buildCorrectionMessage(analysis, name);
830
+ result = `${result}\n\n${correctionMsg}`;
831
+ }
832
+ // 5. Record structured observation
833
+ this.observations.push({ tool: name, args, result, success, duration_ms: durationMs });
834
+ return result;
835
+ }
836
+ /* ── System prompt ─────────────────────────────────────────────────────── */
837
+ sysPrompt() {
838
+ const now = new Date();
839
+ const dayName = WEEKDAYS[now.getDay()];
840
+ const monthName = MONTHS[now.getMonth()];
841
+ const h12 = now.getHours() % 12 || 12;
842
+ const ampm = now.getHours() < 12 ? "AM" : "PM";
843
+ const nowStr = `${dayName}, ${monthName} ${pad2(now.getDate())} ${now.getFullYear()} \u2014 ${h12}:${pad2(now.getMinutes())} ${ampm}`;
844
+ const override = String(this.config.agent?.persona_override ?? "");
845
+ let base;
846
+ if (override) {
847
+ base = override;
848
+ }
849
+ else {
850
+ try {
851
+ base = this.persona.buildSystemPrompt(this.workspace, this.toolNames(), this.trajSessionId ?? "");
852
+ }
853
+ catch {
854
+ base = FALLBACK_SYSTEM_PROMPT;
855
+ }
856
+ }
857
+ return `${base}\n\nMARSHAL'S CLOCK: ${nowStr}\n`;
858
+ }
859
+ memFence(query) {
860
+ return this.memory.getRelevantContext(query);
861
+ }
862
+ currentTask() {
863
+ return this.taskText;
864
+ }
865
+ /* ── Chat ──────────────────────────────────────────────────────────────── */
866
+ async chat(message) {
867
+ // ShadowGuard reflexes are instant and need no LLM.
868
+ const reflexResponse = await this.reflex.process(message);
869
+ if (reflexResponse) {
870
+ info(`[ShadowGuard] Reflex: ${reflexResponse}`);
871
+ this.onToken?.(`[ShadowGuard] ${reflexResponse}`);
872
+ await this.speak(reflexResponse);
873
+ return reflexResponse;
874
+ }
875
+ this.ensureLlm();
876
+ this.history.append("user", message, { mode: "chat" });
877
+ this.history.appendSession({ role: "user", content: message });
878
+ let full = "";
879
+ for await (const tok of this.llm.streamText([
880
+ { role: "system", content: this.sysPrompt() },
881
+ { role: "user", content: message },
882
+ ])) {
883
+ full += tok;
884
+ this.onToken?.(tok);
885
+ }
886
+ this.history.append("assistant", full, { mode: "chat" });
887
+ this.history.appendSession({ role: "assistant", content: full });
888
+ this.memory.syncTurn(message, full);
889
+ this.memory.auto_extract_and_save(message, "chat");
890
+ return full;
891
+ }
892
+ async *chatStream(message) {
893
+ this.history.append("user", message, { mode: "chat" });
894
+ const msgs = [
895
+ { role: "system", content: this.sysPrompt() },
896
+ { role: "user", content: message },
897
+ ];
898
+ let full = "";
899
+ for await (const tok of this.llm.streamText(msgs)) {
900
+ if (this.aborted())
901
+ break;
902
+ full += tok;
903
+ yield tok;
904
+ }
905
+ this.history.append("assistant", full, { mode: "chat" });
906
+ this.history.appendSession({ role: "assistant", content: full });
907
+ this.memory.syncTurn(message, full);
908
+ this.memory.auto_extract_and_save(message, "chat");
909
+ }
910
+ chat_stream(message) {
911
+ return this.chatStream(message);
912
+ }
913
+ /* ── Marshal's scan ────────────────────────────────────────────────────── */
914
+ /** The 'Marshal's Ritual': one-shot analysis of workspace health, index, memory. */
915
+ async marshalScan() {
916
+ const axStatus = await this.axodex.status();
917
+ const axState = axStatus.includes("[AXODEX ERROR] No index found")
918
+ ? "\u26a0 UNINDEXED (Run 'axodex_analyze' for graph vision)"
919
+ : `\u2713 ${axStatus.slice(0, 60)}`;
920
+ const gitRes = await this.gitTools.status();
921
+ let palCount = 0;
922
+ try {
923
+ palCount = Number(this.memory.palace.status().total_drawers ?? 0);
924
+ }
925
+ catch {
926
+ /* palace optional */
927
+ }
928
+ return (`[MARSHAL'S SCAN: ${path.basename(this.workspace)}]\n` +
929
+ `- Graph Vision: ${axState}\n` +
930
+ `- Tactical Memory: ${palCount} facts stored\n` +
931
+ `- Workspace State: ${gitRes ? gitRes.split("\n")[0] : "Ready"}\n`);
932
+ }
933
+ /* ── Agent run ─────────────────────────────────────────────────────────── */
934
+ async run(task) {
935
+ debug(`run() task=${task.slice(0, 80)}`);
936
+ // Step 0: Ritual — proactive awareness
937
+ const scanReport = await this.marshalScan();
938
+ debug(`[Ritual] ${scanReport.split("\n")[0]}`);
939
+ // ShadowGuard reflexes (instant, no LLM)
940
+ const reflexResponse = await this.reflex.process(task);
941
+ if (reflexResponse) {
942
+ info(`[ShadowGuard] Reflex: ${reflexResponse}`);
943
+ this.onToken?.(`[ShadowGuard] ${reflexResponse}`);
944
+ await this.speak(reflexResponse);
945
+ return reflexResponse;
946
+ }
947
+ this.finished = false;
948
+ this.finalResult = null;
949
+ this.taskText = task;
950
+ this.stepCounter = 0;
951
+ this.corrector.reset();
952
+ this.history.append("user", task, { mode: "agent" });
953
+ this.ensureLlm();
954
+ this.backend = this.llm; // Sovereign alias
955
+ this.trajSessionId = this.trajectory.beginSession(task, this.workspace);
956
+ // Phase 8: sovereign injection — multi-stage context rather than one dump.
957
+ const msgs = [{ role: "system", content: this.sysPrompt() }];
958
+ msgs.push({
959
+ role: "user",
960
+ content: `OBSERVATION: ${scanReport}\n\nUse your armory tools if more detail is needed.`,
961
+ });
962
+ msgs.push({
963
+ role: "assistant",
964
+ content: "Acknowledged. Marshal's scan completed. I have absolute awareness of the workspace state. Awaiting your command.",
965
+ });
966
+ // Project Atlas as a one-time background observation
967
+ const atlas = await this.axodex.status();
968
+ if (!atlas.includes("[AXODEX ERROR]")) {
969
+ msgs.push({
970
+ role: "user",
971
+ content: `OBSERVATION (Project Atlas):\n${atlas}\n\nUse your armory tools to explore further.`,
972
+ });
973
+ msgs.push({
974
+ role: "assistant",
975
+ content: "Acknowledged. I have indexed the project structure. Awaiting task details.",
976
+ });
977
+ }
978
+ // Add history if this is a continuation
979
+ const historyMsgs = this.history.getSession();
980
+ if (historyMsgs.length > 0) {
981
+ msgs.push(...historyMsgs.map((m) => ({ role: m.role, content: m.content })));
982
+ }
983
+ else {
984
+ msgs.push({ role: "user", content: task });
985
+ }
986
+ const result = this.useNative ? await this.runNative(msgs) : await this.runFallback(msgs);
987
+ this.trajectory.endSession(this.trajSessionId, result ? result.slice(0, 300) : "completed");
988
+ this.trajSessionId = null;
989
+ return result;
990
+ }
991
+ /* ── Native tool loop ──────────────────────────────────────────────────── */
992
+ async runNative(messages) {
993
+ const agentCfg = this.config.agent;
994
+ const maxSteps = Number(agentCfg?.max_steps ?? this.config.max_steps ?? 30);
995
+ const seen = [];
996
+ let msgs = messages;
997
+ for (let step = 1; step <= maxSteps; step++) {
998
+ if (this.aborted())
999
+ return "[Stopped by user]";
1000
+ this.onStep?.(step, maxSteps);
1001
+ getLogger().logAgentStep(step, maxSteps);
1002
+ // Phase 8: cognitive distillation
1003
+ if (this.history.getSession().length > 8) {
1004
+ debug("[Cognitive] Distilling history...");
1005
+ try {
1006
+ await this.history.distill(this.backend);
1007
+ }
1008
+ catch (e) {
1009
+ debug(`[Cognitive] Distillation skipped: ${errText(e)}`);
1010
+ }
1011
+ }
1012
+ // Context compression (Phase 6+)
1013
+ const curTokens = TokenCounter.countMessages(msgs);
1014
+ if (curTokens > this.compressor.max_tokens) {
1015
+ msgs = (await this.compressor.compress(msgs, this.summarizer()));
1016
+ }
1017
+ let response;
1018
+ try {
1019
+ response = await this.llm.complete(msgs);
1020
+ }
1021
+ catch (e) {
1022
+ const { classifyApiError, APIFailoverReason } = (await import("./intelligence/self_correction.js"));
1023
+ const reason = classifyApiError(e);
1024
+ error(`[Agent] API Error: ${reason.value} | ${errText(e)}`);
1025
+ if (reason.value === APIFailoverReason.CONTEXT_OVERFLOW) {
1026
+ msgs = (await this.compressor.compress(msgs, this.summarizer()));
1027
+ try {
1028
+ response = await this.llm.complete(msgs);
1029
+ }
1030
+ catch (e2) {
1031
+ return `[ERROR] Context overflow persistent after compression: ${errText(e2)}`;
1032
+ }
1033
+ }
1034
+ else {
1035
+ return `[ERROR] Backend (${reason.value}): ${errText(e)}`;
1036
+ }
1037
+ }
1038
+ if (isToolCallResponse(response)) {
1039
+ for (const tc of response.calls) {
1040
+ if (this.aborted())
1041
+ return "[Stopped by user]";
1042
+ const name = tc.name;
1043
+ const args = tc.args ?? {};
1044
+ const sig = `${name}::${stableStringify(args)}`;
1045
+ seen.push(sig);
1046
+ if (seen.filter((s) => s === sig).length >= 5)
1047
+ return `[ERROR] Loop on '${name}'.`;
1048
+ this.onToolCall?.(name, args);
1049
+ const result = await this.exec(name, args);
1050
+ this.onToolResult?.(name, result);
1051
+ if (this.finished) {
1052
+ const final = this.finalResult ?? result;
1053
+ this.syncDone(final);
1054
+ return final;
1055
+ }
1056
+ msgs.push({ role: "assistant", content: "" });
1057
+ msgs.push({ role: "tool", name, content: result });
1058
+ }
1059
+ continue;
1060
+ }
1061
+ // TextResponse
1062
+ const text = response.text ?? "";
1063
+ this.history.append("assistant", text, { step });
1064
+ this.onToken?.(text);
1065
+ if (isDone(text) || this.finished) {
1066
+ const final = this.finalResult ?? text;
1067
+ this.syncDone(final);
1068
+ await this.speak(final);
1069
+ return final;
1070
+ }
1071
+ const fb = parseFallbackCalls(text);
1072
+ if (fb.length > 0) {
1073
+ msgs.push({ role: "assistant", content: text });
1074
+ for (const fc of fb) {
1075
+ if (this.aborted())
1076
+ return "[Stopped by user]";
1077
+ this.onToolCall?.(fc.name, fc.args);
1078
+ const result = await this.exec(fc.name, fc.args);
1079
+ this.onToolResult?.(fc.name, result);
1080
+ if (this.finished) {
1081
+ const final = this.finalResult ?? result;
1082
+ this.syncDone(final);
1083
+ return final;
1084
+ }
1085
+ msgs.push({ role: "user", content: `Tool '${fc.name}' returned:\n${result}` });
1086
+ }
1087
+ continue;
1088
+ }
1089
+ msgs.push({ role: "assistant", content: text });
1090
+ const nudges = msgs
1091
+ .slice(-6)
1092
+ .filter((m) => m.role === "user" && m.content.toLowerCase().includes("continue")).length;
1093
+ if (nudges >= 3)
1094
+ return text;
1095
+ msgs.push({ role: "user", content: "Continue. Use a tool, or call done() if finished." });
1096
+ }
1097
+ return "Reached maximum steps.";
1098
+ }
1099
+ /* ── Fallback text-parsing loop ────────────────────────────────────────── */
1100
+ async runFallback(messages) {
1101
+ const names = this.availableTools.map((s) => s.function.name).join(", ");
1102
+ const instructions = "\n\nTo call a tool:\n" +
1103
+ '<tool>{"name": "tool_name", "args": {"param": "value"}}</tool>\n\n' +
1104
+ `Tools: ${names}\n\n` +
1105
+ "RULES:\n" +
1106
+ "1. Session start: axodex_status \u2192 palace_context \u2192 kg_query('user') \u2192 diary_read\n" +
1107
+ "2. Code Intelligence: ALWAYS use axodex_context to understand symbols and flows.\n" +
1108
+ "3. Safety: ALWAYS run axodex_impact BEFORE modifying any function or class.\n" +
1109
+ "4. Verification: Run axodex_detect_changes BEFORE committing to verify blast radius.\n" +
1110
+ "5. After tasks: palace_store + diary_write\n" +
1111
+ '6. Finish: <tool>{"name": "done", "args": {"result": "summary"}}</tool>';
1112
+ let msgs = messages;
1113
+ if (msgs.length > 0 && msgs[0].role === "system") {
1114
+ msgs = [{ ...msgs[0], content: msgs[0].content + instructions }, ...msgs.slice(1)];
1115
+ }
1116
+ else {
1117
+ msgs = [{ role: "system", content: FALLBACK_SYSTEM_PROMPT + instructions }, ...msgs];
1118
+ }
1119
+ const agentCfg = this.config.agent;
1120
+ const maxSteps = Number(agentCfg?.max_steps ?? this.config.max_steps ?? 30);
1121
+ const seen = [];
1122
+ let nudge = 0;
1123
+ for (let step = 1; step <= maxSteps; step++) {
1124
+ if (this.aborted())
1125
+ return "[Stopped by user]";
1126
+ this.onStep?.(step, maxSteps);
1127
+ const curTokens = TokenCounter.countMessages(msgs);
1128
+ if (curTokens > this.compressor.max_tokens) {
1129
+ msgs = (await this.compressor.compress(msgs, this.summarizer()));
1130
+ }
1131
+ const tokens = [];
1132
+ try {
1133
+ for await (const tok of this.llm.streamText(msgs)) {
1134
+ if (this.aborted())
1135
+ break;
1136
+ tokens.push(tok);
1137
+ this.onToken?.(tok);
1138
+ }
1139
+ }
1140
+ catch (e) {
1141
+ return `[ERROR] Stream: ${errText(e)}`;
1142
+ }
1143
+ if (this.aborted())
1144
+ return "[Stopped by user]";
1145
+ const full = tokens.join("");
1146
+ this.history.append("assistant", full, { step });
1147
+ const calls = parseFallbackCalls(full);
1148
+ if (calls.length > 0) {
1149
+ nudge = 0;
1150
+ msgs.push({ role: "assistant", content: full });
1151
+ for (const fc of calls) {
1152
+ if (this.aborted())
1153
+ return "[Stopped by user]";
1154
+ const sig = `${fc.name}::${stableStringify(fc.args)}`;
1155
+ seen.push(sig);
1156
+ if (seen.filter((s) => s === sig).length >= 5)
1157
+ return `[ERROR] Loop on '${fc.name}'.`;
1158
+ this.onToolCall?.(fc.name, fc.args);
1159
+ const result = await this.exec(fc.name, fc.args);
1160
+ this.onToolResult?.(fc.name, result);
1161
+ if (this.finished) {
1162
+ const final = this.finalResult ?? result;
1163
+ this.syncDone(final);
1164
+ return final;
1165
+ }
1166
+ msgs.push({
1167
+ role: "user",
1168
+ content: `Tool '${fc.name}' returned:\n${result}\n\nContinue or call done() if complete.`,
1169
+ });
1170
+ }
1171
+ continue;
1172
+ }
1173
+ if (isDone(full)) {
1174
+ this.syncDone(full);
1175
+ return full;
1176
+ }
1177
+ nudge += 1;
1178
+ msgs.push({ role: "assistant", content: full });
1179
+ if (nudge >= 4) {
1180
+ warn("Model not calling tools after 4 nudges.");
1181
+ return full;
1182
+ }
1183
+ msgs.push({
1184
+ role: "user",
1185
+ content: "Use a tool to continue. Output a <tool> block, or call done() if fully complete.",
1186
+ });
1187
+ }
1188
+ return "Reached maximum steps.";
1189
+ }
1190
+ /* ── Post-task sync ────────────────────────────────────────────────────── */
1191
+ /** Speak the first sentence of a response if TTS is enabled. */
1192
+ async speak(text) {
1193
+ const tts = await getTts();
1194
+ if (!tts)
1195
+ return;
1196
+ const available = Boolean(tts.is_available ?? tts.isAvailable);
1197
+ if (!available)
1198
+ return;
1199
+ try {
1200
+ const first = text.split(".")[0].slice(0, 120).trim();
1201
+ if (first && first.length > 10) {
1202
+ const fn = tts.speak_async ?? tts.speakAsync;
1203
+ fn?.call(tts, first);
1204
+ }
1205
+ }
1206
+ catch {
1207
+ /* TTS is best-effort */
1208
+ }
1209
+ }
1210
+ syncDone(summary) {
1211
+ if (!summary || summary.length < 20)
1212
+ return;
1213
+ const corrSummary = this.corrector.sessionSummary();
1214
+ const sessionId = this.trajSessionId;
1215
+ // Marshal's Archive + skill distillation, off the critical path.
1216
+ void (async () => {
1217
+ try {
1218
+ const axStatus = await this.axodex.status();
1219
+ const archiveContent = `TASK: ${this.taskText}\n` +
1220
+ `SUMMARY: ${summary}\n` +
1221
+ `ERRORS: ${corrSummary}\n` +
1222
+ `ARCH_SCAN: ${axStatus}`;
1223
+ await this.memory.palace.store("wing_axoniz", "marshal-archives", archiveContent, "agent");
1224
+ const proposal = await this.distiller.analyzeSession(sessionId ?? "");
1225
+ if (proposal) {
1226
+ const name = String(proposal.name ?? proposal.title ?? "unnamed_skill");
1227
+ info(`[Evolution] New skill proposed: ${name}`);
1228
+ this.distiller.propose(proposal);
1229
+ }
1230
+ }
1231
+ catch (e) {
1232
+ debug(`[Archive] sync failed: ${errText(e)}`);
1233
+ }
1234
+ })();
1235
+ }
1236
+ /* ── Session management ────────────────────────────────────────────────── */
1237
+ reset() {
1238
+ this.finished = false;
1239
+ this.finalResult = null;
1240
+ this.abortFlag = null;
1241
+ this.trajSessionId = null;
1242
+ this.stepCounter = 0;
1243
+ this.corrector.reset();
1244
+ this.history.clearSession();
1245
+ }
1246
+ async runGoal(goal, maxCycles = 5, maxRetries = 3) {
1247
+ const { LoopEngine } = (await import("./loop.js"));
1248
+ return new LoopEngine(this, { maxCycles, maxRetries }).runGoal(goal);
1249
+ }
1250
+ run_goal(goal, maxCycles = 5, maxRetries = 3) {
1251
+ return this.runGoal(goal, maxCycles, maxRetries);
1252
+ }
1253
+ switchModel(modelName) {
1254
+ this.config.model_name = modelName;
1255
+ this.rebuildLlm();
1256
+ return `[OK] Switched to ${modelName}`;
1257
+ }
1258
+ switch_model(modelName) {
1259
+ return this.switchModel(modelName);
1260
+ }
1261
+ switchBackend(provider, extra = {}) {
1262
+ this.config.provider = provider;
1263
+ this.config.backend = provider;
1264
+ Object.assign(this.config, extra);
1265
+ this.rebuildLlm();
1266
+ return `[OK] Switched to ${provider}`;
1267
+ }
1268
+ switch_backend(provider, extra = {}) {
1269
+ return this.switchBackend(provider, extra);
1270
+ }
1271
+ updateModelParams(params) {
1272
+ Object.assign(this.config, params);
1273
+ this.rebuildLlm();
1274
+ return "[OK] Params updated.";
1275
+ }
1276
+ update_model_params(params) {
1277
+ return this.updateModelParams(params);
1278
+ }
1279
+ async loadModel() {
1280
+ if (this.llm === null)
1281
+ this.buildLlm();
1282
+ return this.llm.load();
1283
+ }
1284
+ load_model() {
1285
+ return this.loadModel();
1286
+ }
1287
+ async health() {
1288
+ if (this.llm === null)
1289
+ this.buildLlm();
1290
+ return this.llm.healthCheck();
1291
+ }
1292
+ /** Helper for context compression — calls the LLM with a summarization prompt. */
1293
+ async generateSummary(prompt) {
1294
+ this.ensureLlm();
1295
+ try {
1296
+ const resp = await this.llm.complete([{ role: "user", content: prompt }]);
1297
+ return resp.kind === "text" ? resp.text : JSON.stringify(resp);
1298
+ }
1299
+ catch (e) {
1300
+ error(`[Agent] generate_summary failed: ${errText(e)}`);
1301
+ return `Error: ${errText(e)}`;
1302
+ }
1303
+ }
1304
+ generate_summary(prompt) {
1305
+ return this.generateSummary(prompt);
1306
+ }
1307
+ /**
1308
+ * Adapter exposing the LLM as `ChatLike` (a `.chat(messages)` surface) for
1309
+ * ContextCompressor's optional LLM-driven summarisation.
1310
+ */
1311
+ summarizer() {
1312
+ return {
1313
+ chat: async (messages) => {
1314
+ const resp = await this.llm.complete(messages);
1315
+ return resp.kind === "text" ? resp.text : JSON.stringify(resp);
1316
+ },
1317
+ };
1318
+ }
1319
+ async integrationStatus() {
1320
+ const st = this.memory.palace.status();
1321
+ const trajStats = this.trajectory.tool_stats();
1322
+ const astStats = this.astIndex.stats();
1323
+ const predStats = this.predictor.get_stats();
1324
+ return {
1325
+ phase: 6,
1326
+ palace_available: this.memory.palace.is_available(),
1327
+ palace_drawers: st.total_drawers ?? 0,
1328
+ palace_wings: st.wings ?? {},
1329
+ kg_stats: this.memory.kg.stats(),
1330
+ trajectory_tools: trajStats.length,
1331
+ risk_threshold: this.confidence.risk_threshold,
1332
+ ast_files: astStats.files_indexed ?? 0,
1333
+ ast_symbols: astStats.symbols ?? 0,
1334
+ daemon_running: this.daemon.is_running(),
1335
+ predictor_calls: predStats.total_calls ?? 0,
1336
+ predictor_errors: `${Math.round(Number(predStats.error_rate ?? 0) * 100)}%`,
1337
+ };
1338
+ }
1339
+ sessionMessages() {
1340
+ return [{ role: "system", content: this.sysPrompt() }];
1341
+ }
1342
+ _session_messages() {
1343
+ return this.sessionMessages();
1344
+ }
1345
+ }
1346
+ /* ── Helpers ──────────────────────────────────────────────────────────────── */
1347
+ const WEEKDAYS = [
1348
+ "Sunday",
1349
+ "Monday",
1350
+ "Tuesday",
1351
+ "Wednesday",
1352
+ "Thursday",
1353
+ "Friday",
1354
+ "Saturday",
1355
+ ];
1356
+ const MONTHS = [
1357
+ "January",
1358
+ "February",
1359
+ "March",
1360
+ "April",
1361
+ "May",
1362
+ "June",
1363
+ "July",
1364
+ "August",
1365
+ "September",
1366
+ "October",
1367
+ "November",
1368
+ "December",
1369
+ ];
1370
+ function pad2(n) {
1371
+ return String(n).padStart(2, "0");
1372
+ }
1373
+ function errText(e) {
1374
+ return e instanceof Error ? e.message : String(e);
1375
+ }
1376
+ /** Deterministic JSON with sorted keys (mirrors json.dumps(sort_keys=True)). */
1377
+ function stableStringify(v) {
1378
+ if (v === null || typeof v !== "object")
1379
+ return JSON.stringify(v);
1380
+ if (Array.isArray(v))
1381
+ return `[${v.map(stableStringify).join(",")}]`;
1382
+ const obj = v;
1383
+ const keys = Object.keys(obj).sort();
1384
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`;
1385
+ }
1386
+ /**
1387
+ * Adapt a sub-system tool-map entry (which may take positional args or none)
1388
+ * into the uniform `(args) => string | Promise<string>` shape.
1389
+ */
1390
+ function adapt(fn) {
1391
+ const f = fn;
1392
+ return (args) => {
1393
+ const a = args ?? {};
1394
+ // Tool maps built by sub-systems follow the Python kwargs convention and
1395
+ // accept a single options object.
1396
+ return Promise.resolve(f(a));
1397
+ };
1398
+ }
1399
+ //# sourceMappingURL=agent.js.map