byterover-cli 0.4.1 → 1.0.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 (474) hide show
  1. package/README.md +1 -9
  2. package/dist/commands/curate.d.ts +1 -3
  3. package/dist/commands/curate.js +14 -51
  4. package/dist/commands/main.d.ts +8 -0
  5. package/dist/commands/main.js +29 -8
  6. package/dist/commands/query.d.ts +1 -3
  7. package/dist/commands/query.js +8 -35
  8. package/dist/config/context-tree-domains.d.ts +5 -0
  9. package/dist/config/context-tree-domains.js +6 -1
  10. package/dist/config/environment.js +9 -9
  11. package/dist/constants.d.ts +14 -0
  12. package/dist/constants.js +18 -0
  13. package/dist/core/domain/cipher/agent/agent-info.d.ts +199 -0
  14. package/dist/core/domain/cipher/agent/agent-info.js +143 -0
  15. package/dist/core/domain/cipher/agent/agent-registry.d.ts +96 -0
  16. package/dist/core/domain/cipher/agent/agent-registry.js +254 -0
  17. package/dist/core/domain/cipher/agent/index.d.ts +4 -1
  18. package/dist/core/domain/cipher/agent/index.js +7 -1
  19. package/dist/core/domain/cipher/agent-events/types.d.ts +355 -2
  20. package/dist/core/domain/cipher/agent-events/types.js +11 -0
  21. package/dist/core/domain/cipher/errors/error-normalizer.d.ts +156 -0
  22. package/dist/core/domain/cipher/errors/error-normalizer.js +379 -0
  23. package/dist/core/domain/cipher/errors/file-system-error.d.ts +2 -1
  24. package/dist/core/domain/cipher/errors/file-system-error.js +3 -2
  25. package/dist/core/domain/cipher/errors/system-prompt-error-codes.d.ts +79 -0
  26. package/dist/core/domain/cipher/errors/system-prompt-error-codes.js +80 -0
  27. package/dist/core/domain/cipher/errors/system-prompt-error.d.ts +114 -0
  28. package/dist/core/domain/cipher/errors/system-prompt-error.js +144 -0
  29. package/dist/core/domain/cipher/file-system/types.d.ts +57 -0
  30. package/dist/core/domain/cipher/llm/error-codes.d.ts +51 -0
  31. package/dist/core/domain/cipher/llm/error-codes.js +51 -0
  32. package/dist/core/domain/cipher/llm/index.d.ts +9 -0
  33. package/dist/core/domain/cipher/llm/index.js +13 -0
  34. package/dist/core/domain/cipher/llm/registry.d.ts +113 -0
  35. package/dist/core/domain/cipher/llm/registry.js +244 -0
  36. package/dist/core/domain/cipher/llm/schemas.d.ts +155 -0
  37. package/dist/core/domain/cipher/llm/schemas.js +151 -0
  38. package/dist/core/domain/cipher/llm/types.d.ts +121 -0
  39. package/dist/core/domain/cipher/llm/types.js +60 -0
  40. package/dist/core/domain/cipher/storage/message-storage-types.d.ts +114 -5
  41. package/dist/core/domain/cipher/streaming/types.d.ts +119 -0
  42. package/dist/core/domain/cipher/streaming/types.js +16 -0
  43. package/dist/core/domain/cipher/system-prompt/types.d.ts +44 -0
  44. package/dist/core/domain/cipher/todos/types.d.ts +34 -0
  45. package/dist/core/domain/cipher/tools/constants.d.ts +5 -2
  46. package/dist/core/domain/cipher/tools/constants.js +5 -2
  47. package/dist/core/domain/cipher/tools/types.d.ts +31 -0
  48. package/dist/core/domain/errors/connection-error.d.ts +33 -0
  49. package/dist/core/domain/errors/connection-error.js +54 -0
  50. package/dist/core/domain/errors/core-process-error.d.ts +27 -0
  51. package/dist/core/domain/errors/core-process-error.js +43 -0
  52. package/dist/core/domain/errors/task-error.d.ts +64 -0
  53. package/dist/core/domain/errors/task-error.js +116 -0
  54. package/dist/core/domain/errors/transport-error.d.ts +72 -0
  55. package/dist/core/domain/errors/transport-error.js +114 -0
  56. package/dist/core/domain/instance/index.d.ts +1 -0
  57. package/dist/core/domain/instance/index.js +1 -0
  58. package/dist/core/domain/instance/types.d.ts +57 -0
  59. package/dist/core/domain/instance/types.js +72 -0
  60. package/dist/core/domain/knowledge/directory-manager.d.ts +16 -0
  61. package/dist/core/domain/knowledge/directory-manager.js +31 -0
  62. package/dist/core/domain/transport/index.d.ts +2 -0
  63. package/dist/core/domain/transport/index.js +2 -0
  64. package/dist/core/domain/transport/schemas.d.ts +1149 -0
  65. package/dist/core/domain/transport/schemas.js +554 -0
  66. package/dist/core/domain/transport/types.d.ts +67 -0
  67. package/dist/core/domain/transport/types.js +7 -0
  68. package/dist/core/interfaces/cipher/cipher-services.d.ts +15 -3
  69. package/dist/core/interfaces/cipher/i-chat-session.d.ts +47 -5
  70. package/dist/core/interfaces/cipher/i-cipher-agent.d.ts +39 -4
  71. package/dist/core/interfaces/cipher/i-content-generator.d.ts +3 -5
  72. package/dist/core/interfaces/cipher/i-file-system.d.ts +12 -1
  73. package/dist/core/interfaces/cipher/i-llm-service.d.ts +4 -5
  74. package/dist/core/interfaces/cipher/i-todo-storage.d.ts +24 -0
  75. package/dist/core/interfaces/cipher/i-todo-storage.js +1 -0
  76. package/dist/core/interfaces/cipher/i-tool-plugin.d.ts +90 -0
  77. package/dist/core/interfaces/cipher/i-tool-plugin.js +1 -0
  78. package/dist/core/interfaces/cipher/i-tool-provider.d.ts +3 -2
  79. package/dist/core/interfaces/cipher/i-tool-scheduler.d.ts +4 -0
  80. package/dist/core/interfaces/cipher/index.d.ts +35 -0
  81. package/dist/core/interfaces/cipher/index.js +11 -0
  82. package/dist/core/interfaces/cipher/message-factory.d.ts +155 -0
  83. package/dist/core/interfaces/cipher/message-factory.js +252 -0
  84. package/dist/core/interfaces/cipher/message-type-guards.d.ts +139 -0
  85. package/dist/core/interfaces/cipher/message-type-guards.js +173 -0
  86. package/dist/core/interfaces/cipher/message-types.d.ts +279 -5
  87. package/dist/core/interfaces/cipher/message-types.js +6 -0
  88. package/dist/core/interfaces/cipher/sanitization-types.d.ts +147 -0
  89. package/dist/core/interfaces/cipher/sanitization-types.js +46 -0
  90. package/dist/core/interfaces/executor/i-curate-executor.d.ts +34 -0
  91. package/dist/core/interfaces/executor/i-curate-executor.js +1 -0
  92. package/dist/core/interfaces/executor/i-query-executor.d.ts +32 -0
  93. package/dist/core/interfaces/executor/i-query-executor.js +1 -0
  94. package/dist/core/interfaces/executor/index.d.ts +2 -0
  95. package/dist/core/interfaces/executor/index.js +2 -0
  96. package/dist/core/interfaces/instance/i-instance-discovery.d.ts +45 -0
  97. package/dist/core/interfaces/instance/i-instance-discovery.js +1 -0
  98. package/dist/core/interfaces/instance/i-instance-manager.d.ts +58 -0
  99. package/dist/core/interfaces/instance/i-instance-manager.js +1 -0
  100. package/dist/core/interfaces/instance/index.d.ts +2 -0
  101. package/dist/core/interfaces/instance/index.js +2 -0
  102. package/dist/core/interfaces/noop-implementations.d.ts +53 -0
  103. package/dist/core/interfaces/noop-implementations.js +62 -0
  104. package/dist/core/interfaces/transport/i-transport-client.d.ts +97 -0
  105. package/dist/core/interfaces/transport/i-transport-client.js +1 -0
  106. package/dist/core/interfaces/transport/i-transport-server.d.ts +93 -0
  107. package/dist/core/interfaces/transport/i-transport-server.js +1 -0
  108. package/dist/core/interfaces/transport/index.d.ts +2 -0
  109. package/dist/core/interfaces/transport/index.js +2 -0
  110. package/dist/infra/cipher/agent/agent-error-codes.d.ts +16 -0
  111. package/dist/infra/cipher/agent/agent-error-codes.js +17 -0
  112. package/dist/infra/cipher/agent/agent-error.d.ts +54 -0
  113. package/dist/infra/cipher/agent/agent-error.js +79 -0
  114. package/dist/infra/cipher/agent/agent-schemas.d.ts +264 -0
  115. package/dist/infra/cipher/agent/agent-schemas.js +97 -0
  116. package/dist/infra/cipher/agent/agent-state-manager.d.ts +140 -0
  117. package/dist/infra/cipher/agent/agent-state-manager.js +275 -0
  118. package/dist/infra/cipher/agent/base-agent.d.ts +118 -0
  119. package/dist/infra/cipher/agent/base-agent.js +240 -0
  120. package/dist/infra/cipher/agent/cipher-agent.d.ts +165 -0
  121. package/dist/infra/cipher/agent/cipher-agent.js +546 -0
  122. package/dist/infra/cipher/agent/index.d.ts +22 -0
  123. package/dist/infra/cipher/agent/index.js +24 -0
  124. package/dist/infra/cipher/agent/service-initializer.d.ts +79 -0
  125. package/dist/infra/cipher/{agent-service-factory.js → agent/service-initializer.js} +117 -68
  126. package/dist/infra/cipher/agent/types.d.ts +35 -0
  127. package/dist/infra/cipher/agent/types.js +1 -0
  128. package/dist/infra/cipher/blob/blob-reference-resolver.d.ts +107 -0
  129. package/dist/infra/cipher/blob/blob-reference-resolver.js +228 -0
  130. package/dist/infra/cipher/blob/blob-reference-utils.d.ts +117 -0
  131. package/dist/infra/cipher/blob/blob-reference-utils.js +230 -0
  132. package/dist/infra/cipher/consumer/consumer-lock.js +1 -0
  133. package/dist/infra/cipher/consumer/consumer-service.js +1 -0
  134. package/dist/infra/cipher/consumer/execution-consumer.d.ts +6 -1
  135. package/dist/infra/cipher/consumer/execution-consumer.js +54 -16
  136. package/dist/infra/cipher/consumer/index.d.ts +1 -1
  137. package/dist/infra/cipher/consumer/index.js +2 -1
  138. package/dist/infra/cipher/consumer/queue-polling-service.js +1 -0
  139. package/dist/infra/cipher/file-system/binary-utils.d.ts +43 -0
  140. package/dist/infra/cipher/file-system/binary-utils.js +164 -0
  141. package/dist/infra/cipher/file-system/context-tree-file-system-factory.d.ts +9 -0
  142. package/dist/infra/cipher/file-system/context-tree-file-system-factory.js +24 -0
  143. package/dist/infra/cipher/file-system/file-system-service.d.ts +17 -1
  144. package/dist/infra/cipher/file-system/file-system-service.js +327 -36
  145. package/dist/infra/cipher/file-system/path-validator.d.ts +32 -0
  146. package/dist/infra/cipher/file-system/path-validator.js +111 -6
  147. package/dist/infra/cipher/interactive-loop.js +41 -33
  148. package/dist/infra/cipher/llm/capability-cache.d.ts +87 -0
  149. package/dist/infra/cipher/llm/capability-cache.js +125 -0
  150. package/dist/infra/cipher/llm/context/compaction/compaction-service.d.ts +32 -0
  151. package/dist/infra/cipher/llm/context/compaction/compaction-service.js +44 -3
  152. package/dist/infra/cipher/llm/context/compression/enhanced-compaction.d.ts +112 -0
  153. package/dist/infra/cipher/llm/context/compression/enhanced-compaction.js +175 -0
  154. package/dist/infra/cipher/llm/context/compression/filter-compacted.d.ts +83 -0
  155. package/dist/infra/cipher/llm/context/compression/filter-compacted.js +150 -0
  156. package/dist/infra/cipher/llm/context/compression/index.d.ts +5 -0
  157. package/dist/infra/cipher/llm/context/compression/index.js +6 -0
  158. package/dist/infra/cipher/llm/context/compression/reactive-overflow.d.ts +107 -0
  159. package/dist/infra/cipher/llm/context/compression/reactive-overflow.js +272 -0
  160. package/dist/infra/cipher/llm/context/context-manager.d.ts +47 -1
  161. package/dist/infra/cipher/llm/context/context-manager.js +129 -0
  162. package/dist/infra/cipher/llm/context/utils.js +17 -4
  163. package/dist/infra/cipher/llm/generators/byterover-content-generator.js +4 -2
  164. package/dist/infra/cipher/llm/internal-llm-service.d.ts +50 -17
  165. package/dist/infra/cipher/llm/internal-llm-service.js +273 -50
  166. package/dist/infra/cipher/llm/openrouter-llm-service.d.ts +6 -8
  167. package/dist/infra/cipher/llm/openrouter-llm-service.js +14 -16
  168. package/dist/infra/cipher/llm/retry/retry-policy.d.ts +1 -0
  169. package/dist/infra/cipher/llm/retry/retry-policy.js +11 -0
  170. package/dist/infra/cipher/llm/retry/retry-with-backoff.js +3 -2
  171. package/dist/infra/cipher/llm/sanitization/base64-utils.d.ts +102 -0
  172. package/dist/infra/cipher/llm/sanitization/base64-utils.js +182 -0
  173. package/dist/infra/cipher/llm/sanitization/index.d.ts +12 -0
  174. package/dist/infra/cipher/llm/sanitization/index.js +13 -0
  175. package/dist/infra/cipher/llm/sanitization/tool-sanitizer.d.ts +74 -0
  176. package/dist/infra/cipher/llm/sanitization/tool-sanitizer.js +398 -0
  177. package/dist/infra/cipher/llm/stream-processor.d.ts +158 -0
  178. package/dist/infra/cipher/llm/stream-processor.js +276 -0
  179. package/dist/infra/cipher/llm/tokenizers/claude-tokenizer.d.ts +13 -20
  180. package/dist/infra/cipher/llm/tokenizers/claude-tokenizer.js +17 -24
  181. package/dist/infra/cipher/llm/tokenizers/gemini-tokenizer.d.ts +12 -11
  182. package/dist/infra/cipher/llm/tokenizers/gemini-tokenizer.js +16 -15
  183. package/dist/infra/cipher/llm/tokenizers/openrouter-tokenizer.d.ts +15 -7
  184. package/dist/infra/cipher/llm/tokenizers/openrouter-tokenizer.js +22 -10
  185. package/dist/infra/cipher/llm/tool-output-processor.d.ts +51 -0
  186. package/dist/infra/cipher/llm/tool-output-processor.js +139 -0
  187. package/dist/infra/cipher/process/command-validator.d.ts +23 -0
  188. package/dist/infra/cipher/process/command-validator.js +75 -0
  189. package/dist/infra/cipher/process/path-utils.d.ts +66 -0
  190. package/dist/infra/cipher/process/path-utils.js +94 -0
  191. package/dist/infra/cipher/process/process-service.d.ts +32 -0
  192. package/dist/infra/cipher/process/process-service.js +98 -17
  193. package/dist/infra/cipher/session/chat-session.d.ts +56 -7
  194. package/dist/infra/cipher/session/chat-session.js +163 -13
  195. package/dist/infra/cipher/session/index.d.ts +1 -0
  196. package/dist/infra/cipher/session/index.js +2 -0
  197. package/dist/infra/cipher/session/message-queue.d.ts +65 -0
  198. package/dist/infra/cipher/session/message-queue.js +90 -0
  199. package/dist/infra/cipher/session/session-manager.d.ts +106 -5
  200. package/dist/infra/cipher/session/session-manager.js +254 -7
  201. package/dist/infra/cipher/session/session-status.d.ts +137 -0
  202. package/dist/infra/cipher/session/session-status.js +184 -0
  203. package/dist/infra/cipher/session/title-generator.d.ts +8 -0
  204. package/dist/infra/cipher/session/title-generator.js +31 -0
  205. package/dist/infra/cipher/storage/message-storage-service.d.ts +65 -2
  206. package/dist/infra/cipher/storage/message-storage-service.js +300 -54
  207. package/dist/infra/cipher/storage/tool-part-factory.d.ts +116 -0
  208. package/dist/infra/cipher/storage/tool-part-factory.js +197 -0
  209. package/dist/infra/cipher/system-prompt/contributor-schemas.d.ts +516 -0
  210. package/dist/infra/cipher/system-prompt/contributor-schemas.js +85 -0
  211. package/dist/infra/cipher/system-prompt/contributors/agent-prompt-contributor.d.ts +59 -0
  212. package/dist/infra/cipher/system-prompt/contributors/agent-prompt-contributor.js +131 -0
  213. package/dist/infra/cipher/system-prompt/contributors/companion-contributor.d.ts +54 -0
  214. package/dist/infra/cipher/system-prompt/contributors/companion-contributor.js +107 -0
  215. package/dist/infra/cipher/system-prompt/contributors/context-tree-structure-contributor.d.ts +68 -0
  216. package/dist/infra/cipher/system-prompt/contributors/context-tree-structure-contributor.js +179 -0
  217. package/dist/infra/cipher/system-prompt/contributors/datetime-contributor.d.ts +25 -0
  218. package/dist/infra/cipher/system-prompt/contributors/datetime-contributor.js +29 -0
  219. package/dist/infra/cipher/system-prompt/contributors/environment-contributor.d.ts +25 -0
  220. package/dist/infra/cipher/system-prompt/contributors/environment-contributor.js +54 -0
  221. package/dist/infra/cipher/system-prompt/contributors/file-contributor.d.ts +60 -0
  222. package/dist/infra/cipher/system-prompt/contributors/file-contributor.js +128 -0
  223. package/dist/infra/cipher/system-prompt/contributors/index.d.ts +13 -0
  224. package/dist/infra/cipher/system-prompt/contributors/index.js +8 -0
  225. package/dist/infra/cipher/system-prompt/contributors/memory-contributor.d.ts +40 -0
  226. package/dist/infra/cipher/system-prompt/contributors/memory-contributor.js +56 -0
  227. package/dist/infra/cipher/system-prompt/contributors/static-contributor.d.ts +26 -0
  228. package/dist/infra/cipher/system-prompt/contributors/static-contributor.js +31 -0
  229. package/dist/infra/cipher/system-prompt/environment-context-builder.d.ts +112 -0
  230. package/dist/infra/cipher/system-prompt/environment-context-builder.js +256 -0
  231. package/dist/infra/cipher/system-prompt/prompt-cache.d.ts +102 -0
  232. package/dist/infra/cipher/system-prompt/prompt-cache.js +156 -0
  233. package/dist/infra/cipher/system-prompt/schemas.d.ts +151 -0
  234. package/dist/infra/cipher/system-prompt/schemas.js +94 -0
  235. package/dist/infra/cipher/system-prompt/system-prompt-manager.d.ts +136 -0
  236. package/dist/infra/cipher/system-prompt/system-prompt-manager.js +307 -0
  237. package/dist/infra/cipher/todos/todo-storage-service.d.ts +26 -0
  238. package/dist/infra/cipher/todos/todo-storage-service.js +28 -0
  239. package/dist/infra/cipher/tools/core-tool-scheduler.js +5 -1
  240. package/dist/infra/cipher/tools/default-policy-rules.js +1 -1
  241. package/dist/infra/cipher/tools/implementations/bash-exec-tool.d.ts +1 -0
  242. package/dist/infra/cipher/tools/implementations/bash-exec-tool.js +27 -10
  243. package/dist/infra/cipher/tools/implementations/bash-output-tool.js +1 -5
  244. package/dist/infra/cipher/tools/implementations/batch-tool.d.ts +12 -0
  245. package/dist/infra/cipher/tools/implementations/batch-tool.js +142 -0
  246. package/dist/infra/cipher/tools/implementations/curate-tool.js +195 -68
  247. package/dist/infra/cipher/tools/implementations/list-directory-tool.d.ts +12 -0
  248. package/dist/infra/cipher/tools/implementations/list-directory-tool.js +52 -0
  249. package/dist/infra/cipher/tools/implementations/read-file-tool.d.ts +8 -1
  250. package/dist/infra/cipher/tools/implementations/read-file-tool.js +17 -7
  251. package/dist/infra/cipher/tools/implementations/read-todos-tool.d.ts +11 -0
  252. package/dist/infra/cipher/tools/implementations/read-todos-tool.js +39 -0
  253. package/dist/infra/cipher/tools/implementations/{detect-domains-tool.d.ts → spec-analyze-tool.d.ts} +1 -1
  254. package/dist/infra/cipher/tools/implementations/{detect-domains-tool.js → spec-analyze-tool.js} +9 -7
  255. package/dist/infra/cipher/tools/implementations/task-tool.d.ts +34 -0
  256. package/dist/infra/cipher/tools/implementations/task-tool.js +207 -0
  257. package/dist/infra/cipher/tools/implementations/write-todos-tool.d.ts +4 -1
  258. package/dist/infra/cipher/tools/implementations/write-todos-tool.js +19 -63
  259. package/dist/infra/cipher/tools/index.d.ts +1 -1
  260. package/dist/infra/cipher/tools/index.js +1 -1
  261. package/dist/infra/cipher/tools/plugins/index.d.ts +3 -0
  262. package/dist/infra/cipher/tools/plugins/index.js +2 -0
  263. package/dist/infra/cipher/tools/plugins/logging-plugin.d.ts +28 -0
  264. package/dist/infra/cipher/tools/plugins/logging-plugin.js +66 -0
  265. package/dist/infra/cipher/tools/plugins/plugin-manager.d.ts +81 -0
  266. package/dist/infra/cipher/tools/plugins/plugin-manager.js +122 -0
  267. package/dist/infra/cipher/tools/streaming/index.d.ts +1 -0
  268. package/dist/infra/cipher/tools/streaming/index.js +1 -0
  269. package/dist/infra/cipher/tools/streaming/metadata-handler.d.ts +31 -0
  270. package/dist/infra/cipher/tools/streaming/metadata-handler.js +39 -0
  271. package/dist/infra/cipher/tools/tool-description-loader.d.ts +57 -0
  272. package/dist/infra/cipher/tools/tool-description-loader.js +108 -0
  273. package/dist/infra/cipher/tools/tool-manager.d.ts +38 -4
  274. package/dist/infra/cipher/tools/tool-manager.js +107 -11
  275. package/dist/infra/cipher/tools/tool-provider-getter.d.ts +6 -0
  276. package/dist/infra/cipher/tools/tool-provider-getter.js +1 -0
  277. package/dist/infra/cipher/tools/tool-provider.d.ts +32 -7
  278. package/dist/infra/cipher/tools/tool-provider.js +81 -25
  279. package/dist/infra/cipher/tools/tool-registry.d.ts +23 -0
  280. package/dist/infra/cipher/tools/tool-registry.js +58 -16
  281. package/dist/infra/context-tree/file-context-tree-snapshot-service.js +10 -4
  282. package/dist/infra/context-tree/file-context-tree-writer-service.d.ts +4 -3
  283. package/dist/infra/context-tree/file-context-tree-writer-service.js +6 -4
  284. package/dist/infra/context-tree/path-utils.d.ts +7 -0
  285. package/dist/infra/context-tree/path-utils.js +7 -0
  286. package/dist/infra/core/executors/curate-executor.d.ts +35 -0
  287. package/dist/infra/core/executors/curate-executor.js +123 -0
  288. package/dist/infra/core/executors/index.d.ts +2 -0
  289. package/dist/infra/core/executors/index.js +2 -0
  290. package/dist/infra/core/executors/query-executor.d.ts +23 -0
  291. package/dist/infra/core/executors/query-executor.js +51 -0
  292. package/dist/infra/core/task-processor.d.ts +81 -0
  293. package/dist/infra/core/task-processor.js +115 -0
  294. package/dist/infra/instance/file-instance-discovery.d.ts +31 -0
  295. package/dist/infra/instance/file-instance-discovery.js +84 -0
  296. package/dist/infra/instance/file-instance-manager.d.ts +46 -0
  297. package/dist/infra/instance/file-instance-manager.js +123 -0
  298. package/dist/infra/instance/index.d.ts +3 -0
  299. package/dist/infra/instance/index.js +3 -0
  300. package/dist/infra/instance/process-utils.d.ts +14 -0
  301. package/dist/infra/instance/process-utils.js +39 -0
  302. package/dist/infra/process/agent-worker.d.ts +20 -0
  303. package/dist/infra/process/agent-worker.js +602 -0
  304. package/dist/infra/process/index.d.ts +12 -0
  305. package/dist/infra/process/index.js +11 -0
  306. package/dist/infra/process/ipc-types.d.ts +55 -0
  307. package/dist/infra/process/ipc-types.js +12 -0
  308. package/dist/infra/process/process-manager.d.ts +154 -0
  309. package/dist/infra/process/process-manager.js +471 -0
  310. package/dist/infra/process/task-queue-manager.d.ts +123 -0
  311. package/dist/infra/process/task-queue-manager.js +226 -0
  312. package/dist/infra/process/transport-handlers.d.ts +124 -0
  313. package/dist/infra/process/transport-handlers.js +348 -0
  314. package/dist/infra/process/transport-worker.d.ts +20 -0
  315. package/dist/infra/process/transport-worker.js +168 -0
  316. package/dist/infra/repl/commands/curate-command.js +0 -5
  317. package/dist/infra/repl/commands/query-command.js +0 -3
  318. package/dist/infra/repl/repl-startup.d.ts +4 -0
  319. package/dist/infra/repl/repl-startup.js +8 -1
  320. package/dist/infra/repl/transport-client-helper.d.ts +9 -0
  321. package/dist/infra/repl/transport-client-helper.js +96 -0
  322. package/dist/infra/transport/index.d.ts +4 -0
  323. package/dist/infra/transport/index.js +4 -0
  324. package/dist/infra/transport/port-utils.d.ts +42 -0
  325. package/dist/infra/transport/port-utils.js +84 -0
  326. package/dist/infra/transport/socket-io-transport-client.d.ts +45 -0
  327. package/dist/infra/transport/socket-io-transport-client.js +270 -0
  328. package/dist/infra/transport/socket-io-transport-server.d.ts +35 -0
  329. package/dist/infra/transport/socket-io-transport-server.js +207 -0
  330. package/dist/infra/transport/transport-client-factory.d.ts +76 -0
  331. package/dist/infra/transport/transport-client-factory.js +168 -0
  332. package/dist/infra/transport/transport-factory.d.ts +33 -0
  333. package/dist/infra/transport/transport-factory.js +59 -0
  334. package/dist/infra/usecase/curate-use-case.d.ts +8 -55
  335. package/dist/infra/usecase/curate-use-case.js +71 -262
  336. package/dist/infra/usecase/init-use-case.js +3 -2
  337. package/dist/infra/usecase/query-use-case.d.ts +18 -45
  338. package/dist/infra/usecase/query-use-case.js +250 -326
  339. package/dist/infra/usecase/status-use-case.js +1 -1
  340. package/dist/resources/prompts/{curate-context-tree-curation.yml → curate.yml} +25 -22
  341. package/dist/resources/prompts/explore.yml +78 -0
  342. package/dist/resources/prompts/plan.yml +114 -0
  343. package/dist/resources/prompts/reflection.yml +1 -1
  344. package/dist/resources/prompts/system-prompt.yml +15 -8
  345. package/dist/resources/prompts/tool-outputs.yml +0 -5
  346. package/dist/resources/tools/bash_exec.txt +98 -0
  347. package/dist/resources/tools/bash_output.txt +40 -0
  348. package/dist/resources/tools/batch.txt +28 -0
  349. package/dist/resources/tools/create_knowledge_topic.txt +23 -0
  350. package/dist/resources/tools/curate.txt +22 -0
  351. package/dist/resources/tools/delete_memory.txt +1 -0
  352. package/dist/resources/tools/detect_domains.txt +11 -0
  353. package/dist/resources/tools/edit_file.txt +1 -0
  354. package/dist/resources/tools/edit_memory.txt +1 -0
  355. package/dist/resources/tools/glob_files.txt +20 -0
  356. package/dist/resources/tools/grep_content.txt +18 -0
  357. package/dist/resources/tools/kill_process.txt +16 -0
  358. package/dist/resources/tools/list_directory.txt +16 -0
  359. package/dist/resources/tools/list_memories.txt +1 -0
  360. package/dist/resources/tools/read_file.txt +31 -0
  361. package/dist/resources/tools/read_memory.txt +1 -0
  362. package/dist/resources/tools/read_todos.txt +17 -0
  363. package/dist/resources/tools/search_history.txt +1 -0
  364. package/dist/resources/tools/task.txt +23 -0
  365. package/dist/resources/tools/write_file.txt +1 -0
  366. package/dist/resources/tools/write_memory.txt +1 -0
  367. package/dist/resources/tools/write_todos.txt +29 -0
  368. package/dist/tui/app.js +9 -13
  369. package/dist/tui/components/command-details.d.ts +14 -0
  370. package/dist/tui/components/command-details.js +35 -0
  371. package/dist/tui/components/execution/execution-changes.d.ts +5 -0
  372. package/dist/tui/components/execution/execution-changes.js +19 -4
  373. package/dist/tui/components/execution/execution-content.d.ts +4 -2
  374. package/dist/tui/components/execution/execution-content.js +26 -13
  375. package/dist/tui/components/execution/execution-input.js +3 -3
  376. package/dist/tui/components/execution/execution-progress.d.ts +2 -2
  377. package/dist/tui/components/execution/execution-progress.js +8 -6
  378. package/dist/tui/components/execution/log-item.d.ts +3 -4
  379. package/dist/tui/components/execution/log-item.js +2 -5
  380. package/dist/tui/components/footer.js +9 -4
  381. package/dist/tui/components/header.d.ts +3 -3
  382. package/dist/tui/components/header.js +5 -3
  383. package/dist/tui/components/index.d.ts +1 -0
  384. package/dist/tui/components/index.js +1 -0
  385. package/dist/tui/components/onboarding/copyable-prompt.d.ts +5 -3
  386. package/dist/tui/components/onboarding/copyable-prompt.js +7 -8
  387. package/dist/tui/components/onboarding/onboarding-flow.js +35 -25
  388. package/dist/tui/components/scrollable-list.js +12 -10
  389. package/dist/tui/components/suggestions.js +39 -41
  390. package/dist/tui/components/tab-bar.d.ts +2 -1
  391. package/dist/tui/components/tab-bar.js +3 -4
  392. package/dist/tui/constants.d.ts +0 -5
  393. package/dist/tui/constants.js +0 -5
  394. package/dist/tui/contexts/auth-context.js +9 -2
  395. package/dist/tui/contexts/{use-commands.js → commands-context.js} +3 -3
  396. package/dist/tui/contexts/index.d.ts +6 -1
  397. package/dist/tui/contexts/index.js +6 -1
  398. package/dist/tui/contexts/onboarding-context.d.ts +1 -1
  399. package/dist/tui/contexts/onboarding-context.js +9 -9
  400. package/dist/tui/contexts/tasks-context.d.ts +84 -0
  401. package/dist/tui/contexts/tasks-context.js +218 -0
  402. package/dist/tui/contexts/transport-context.d.ts +29 -0
  403. package/dist/tui/contexts/transport-context.js +82 -0
  404. package/dist/tui/hooks/index.d.ts +10 -6
  405. package/dist/tui/hooks/index.js +7 -6
  406. package/dist/tui/hooks/use-activity-logs.d.ts +3 -11
  407. package/dist/tui/hooks/use-activity-logs.js +87 -34
  408. package/dist/tui/hooks/use-auth-polling.d.ts +24 -0
  409. package/dist/tui/hooks/use-auth-polling.js +104 -0
  410. package/dist/tui/hooks/use-slash-command-processor.js +0 -1
  411. package/dist/tui/hooks/use-slash-completion.js +1 -1
  412. package/dist/tui/hooks/use-tab-navigation.d.ts +2 -1
  413. package/dist/tui/hooks/use-tab-navigation.js +16 -7
  414. package/dist/tui/hooks/use-terminal-breakpoint.d.ts +21 -0
  415. package/dist/tui/hooks/use-terminal-breakpoint.js +38 -0
  416. package/dist/tui/hooks/use-ui-heights.d.ts +120 -0
  417. package/dist/tui/hooks/use-ui-heights.js +88 -0
  418. package/dist/tui/providers/app-providers.js +2 -6
  419. package/dist/tui/types/commands.d.ts +0 -26
  420. package/dist/tui/types/index.d.ts +1 -1
  421. package/dist/tui/types/ui.d.ts +9 -4
  422. package/dist/tui/utils/line.d.ts +11 -0
  423. package/dist/tui/utils/line.js +16 -0
  424. package/dist/tui/utils/log.d.ts +27 -0
  425. package/dist/tui/utils/log.js +114 -0
  426. package/dist/tui/views/command-view.d.ts +7 -0
  427. package/dist/tui/views/command-view.js +103 -80
  428. package/dist/tui/views/login-view.js +7 -4
  429. package/dist/tui/views/logs-view.d.ts +13 -0
  430. package/dist/tui/views/logs-view.js +27 -52
  431. package/dist/utils/connection-error-handler.d.ts +16 -0
  432. package/dist/utils/connection-error-handler.js +49 -0
  433. package/dist/utils/crash-log.d.ts +14 -0
  434. package/dist/utils/crash-log.js +19 -0
  435. package/dist/utils/file-helpers.d.ts +14 -0
  436. package/dist/utils/file-helpers.js +21 -0
  437. package/dist/utils/global-logs-path.d.ts +11 -0
  438. package/dist/utils/global-logs-path.js +37 -0
  439. package/dist/utils/process-logger.d.ts +53 -0
  440. package/dist/utils/process-logger.js +253 -0
  441. package/dist/utils/sandbox-detector.d.ts +31 -0
  442. package/dist/utils/sandbox-detector.js +122 -0
  443. package/oclif.manifest.json +10 -198
  444. package/package.json +5 -1
  445. package/dist/commands/cipher-agent/run.d.ts +0 -142
  446. package/dist/commands/cipher-agent/run.js +0 -555
  447. package/dist/commands/cipher-agent/set-prompt.d.ts +0 -16
  448. package/dist/commands/cipher-agent/set-prompt.js +0 -58
  449. package/dist/commands/cipher-agent/show-prompt.d.ts +0 -13
  450. package/dist/commands/cipher-agent/show-prompt.js +0 -53
  451. package/dist/commands/foo.d.ts +0 -14
  452. package/dist/commands/foo.js +0 -66
  453. package/dist/infra/cipher/agent-service-factory.d.ts +0 -93
  454. package/dist/infra/cipher/cipher-agent-state-manager.d.ts +0 -63
  455. package/dist/infra/cipher/cipher-agent-state-manager.js +0 -108
  456. package/dist/infra/cipher/cipher-agent.d.ts +0 -182
  457. package/dist/infra/cipher/cipher-agent.js +0 -317
  458. package/dist/infra/cipher/system-prompt/simple-prompt-factory.d.ts +0 -106
  459. package/dist/infra/cipher/system-prompt/simple-prompt-factory.js +0 -297
  460. package/dist/infra/cipher/tools/implementations/find-knowledge-topics-tool.d.ts +0 -7
  461. package/dist/infra/cipher/tools/implementations/find-knowledge-topics-tool.js +0 -424
  462. package/dist/resources/prompts/modes/autonomous.yml +0 -9
  463. package/dist/resources/prompts/query-context-tree-retrieval.yml +0 -48
  464. package/dist/tui/contexts/consumer.d.ts +0 -31
  465. package/dist/tui/contexts/consumer.js +0 -56
  466. package/dist/tui/hooks/use-consumer.d.ts +0 -12
  467. package/dist/tui/hooks/use-consumer.js +0 -50
  468. package/dist/tui/hooks/use-queue-polling.d.ts +0 -31
  469. package/dist/tui/hooks/use-queue-polling.js +0 -90
  470. /package/dist/tui/contexts/{use-commands.d.ts → commands-context.d.ts} +0 -0
  471. /package/dist/tui/contexts/{use-mode.d.ts → mode-context.d.ts} +0 -0
  472. /package/dist/tui/contexts/{use-mode.js → mode-context.js} +0 -0
  473. /package/dist/tui/contexts/{use-theme.d.ts → theme-context.d.ts} +0 -0
  474. /package/dist/tui/contexts/{use-theme.js → theme-context.js} +0 -0
@@ -0,0 +1,602 @@
1
+ /**
2
+ * Agent Worker - Entry point for Agent Process.
3
+ *
4
+ * Architecture v0.5.0:
5
+ * - Connects to Transport as Socket.IO CLIENT
6
+ * - Contains TaskProcessor + UseCases + CipherAgent
7
+ * - Receives tasks via Socket.IO (task:execute)
8
+ * - Sends results back via Socket.IO (task:chunk, task:completed, etc.)
9
+ * - NO Socket.IO server (Transport is the only server)
10
+ *
11
+ * IPC messages:
12
+ * - Receives: 'ping', 'shutdown'
13
+ * - Sends: 'ready', 'pong', 'stopped', 'error'
14
+ *
15
+ * Socket.IO events (as client):
16
+ * - Sends: 'agent:register' (identify as Agent)
17
+ * - Receives: 'task:execute', 'task:cancel', 'shutdown'
18
+ * - Sends: 'task:started', 'task:chunk', 'task:completed', 'task:error', 'task:toolCall', 'task:toolResult'
19
+ */
20
+ import { randomUUID } from 'node:crypto';
21
+ import { getCurrentConfig } from '../../config/environment.js';
22
+ import { DEFAULT_LLM_MODEL, PROJECT } from '../../constants.js';
23
+ import { NotAuthenticatedError, ProcessorNotInitError, serializeTaskError } from '../../core/domain/errors/task-error.js';
24
+ import { agentLog } from '../../utils/process-logger.js';
25
+ import { CipherAgent } from '../cipher/agent/index.js';
26
+ import { ProjectConfigStore } from '../config/file-config-store.js';
27
+ import { CurateExecutor } from '../core/executors/curate-executor.js';
28
+ import { QueryExecutor } from '../core/executors/query-executor.js';
29
+ import { createTaskProcessor } from '../core/task-processor.js';
30
+ import { KeychainTokenStore } from '../storage/keychain-token-store.js';
31
+ import { createTransportClient } from '../transport/transport-factory.js';
32
+ import { TaskQueueManager } from './task-queue-manager.js';
33
+ // IPC types imported from ./ipc-types.ts
34
+ function sendToParent(message) {
35
+ process.send?.(message);
36
+ }
37
+ /**
38
+ * Log transport errors instead of silently swallowing them.
39
+ * Used for fire-and-forget transport calls where we don't want to crash
40
+ * but still want visibility into failures for debugging.
41
+ */
42
+ function logTransportError(error) {
43
+ const message = error instanceof Error ? error.message : String(error);
44
+ agentLog(`Transport error (non-fatal): ${message}`);
45
+ }
46
+ // Task types imported from core/domain/transport/schemas.ts:
47
+ // - TaskExecute: Transport → Agent (task:execute event)
48
+ // - TaskCancel: Transport → Agent (task:cancel event)
49
+ // ============================================================================
50
+ // Agent Process
51
+ // ============================================================================
52
+ let transportClient;
53
+ let taskProcessor;
54
+ let cipherAgent;
55
+ /** ChatSession ID - created once when agent starts, used for all tasks */
56
+ let chatSessionId;
57
+ /** Whether the agent is fully initialized (has auth + config) */
58
+ let isAgentInitialized = false;
59
+ /** Initialization error if agent couldn't be initialized */
60
+ let initializationError;
61
+ /** Guard: prevent concurrent initialization attempts */
62
+ let isInitializing = false;
63
+ /** Guard: prevent double cleanup */
64
+ let isCleaningUp = false;
65
+ let eventForwarders = [];
66
+ // ============================================================================
67
+ // Task Queue Manager (replaces inline queue logic)
68
+ // ============================================================================
69
+ /**
70
+ * Task queue manager handles:
71
+ * - Separate queues for curate and query tasks
72
+ * - Concurrency limits (max 2 concurrent per type)
73
+ * - Task deduplication (same taskId can't be queued twice)
74
+ * - Cancel tasks from queue before processing
75
+ * - FIFO processing order
76
+ */
77
+ const taskQueueManager = new TaskQueueManager({
78
+ curate: { maxConcurrent: 2 },
79
+ onExecutorError(taskId, error) {
80
+ agentLog(`Executor error for task ${taskId}: ${error}`);
81
+ },
82
+ query: { maxConcurrent: Infinity },
83
+ });
84
+ /**
85
+ * Get Transport port from environment.
86
+ */
87
+ function getTransportPort() {
88
+ const portStr = process.env.TRANSPORT_PORT;
89
+ if (!portStr) {
90
+ throw new Error('TRANSPORT_PORT environment variable not set');
91
+ }
92
+ const port = Number.parseInt(portStr, 10);
93
+ if (Number.isNaN(port)) {
94
+ throw new TypeError(`Invalid TRANSPORT_PORT: ${portStr}`);
95
+ }
96
+ return port;
97
+ }
98
+ /**
99
+ * Cleanup event forwarders from previous agent instance.
100
+ * Prevents memory leaks when agent is reinitialized.
101
+ */
102
+ function cleanupAgentEventForwarding() {
103
+ if (eventForwarders.length === 0) {
104
+ return;
105
+ }
106
+ // Get the old agent's event bus (if still available)
107
+ // Cast to CipherAgent to access agentEventBus property
108
+ const eventBus = cipherAgent?.agentEventBus;
109
+ if (eventBus) {
110
+ for (const { event, handler } of eventForwarders) {
111
+ eventBus.off(event, handler);
112
+ }
113
+ }
114
+ // Clear the stored references
115
+ eventForwarders = [];
116
+ agentLog('Event forwarders cleaned up');
117
+ }
118
+ /**
119
+ * Setup event forwarding from CipherAgent to Transport.
120
+ * agent-worker subscribes directly to agentEventBus (owns the agent).
121
+ * Events are forwarded with currentTaskId.
122
+ *
123
+ * IMPORTANT: This function now stores handler references and cleans up
124
+ * old handlers on reinit to prevent memory leaks.
125
+ */
126
+ function setupAgentEventForwarding(agent) {
127
+ // Clean up old forwarders first (prevents accumulation on reinit)
128
+ cleanupAgentEventForwarding();
129
+ const eventBus = agent.agentEventBus;
130
+ if (!eventBus) {
131
+ agentLog('No agentEventBus available for event forwarding');
132
+ return;
133
+ }
134
+ // Helper to register and track event forwarder
135
+ const registerForwarder = (event, handler) => {
136
+ eventBus.on(event, handler);
137
+ eventForwarders.push({ event, handler: handler });
138
+ };
139
+ // Forward llmservice:thinking
140
+ registerForwarder('llmservice:thinking', (payload) => {
141
+ if (payload.taskId) {
142
+ transportClient
143
+ ?.request('llmservice:thinking', { sessionId: payload.sessionId, taskId: payload.taskId })
144
+ .catch(logTransportError);
145
+ }
146
+ });
147
+ // Forward llmservice:chunk
148
+ registerForwarder('llmservice:chunk', (payload) => {
149
+ if (payload.taskId) {
150
+ transportClient
151
+ ?.request('llmservice:chunk', {
152
+ content: payload.content,
153
+ isComplete: payload.isComplete,
154
+ sessionId: payload.sessionId,
155
+ taskId: payload.taskId,
156
+ type: payload.type,
157
+ })
158
+ .catch(logTransportError);
159
+ }
160
+ });
161
+ // Forward llmservice:response
162
+ registerForwarder('llmservice:response', (payload) => {
163
+ if (payload.taskId && payload.content) {
164
+ transportClient
165
+ ?.request('llmservice:response', {
166
+ content: payload.content,
167
+ model: payload.model,
168
+ partial: payload.partial,
169
+ provider: payload.provider,
170
+ reasoning: payload.reasoning,
171
+ sessionId: payload.sessionId,
172
+ taskId: payload.taskId,
173
+ tokenUsage: payload.tokenUsage,
174
+ })
175
+ .catch(logTransportError);
176
+ }
177
+ });
178
+ // Forward llmservice:toolCall
179
+ registerForwarder('llmservice:toolCall', (payload) => {
180
+ if (payload.taskId && payload.callId) {
181
+ transportClient
182
+ ?.request('llmservice:toolCall', {
183
+ args: payload.args,
184
+ callId: payload.callId,
185
+ sessionId: payload.sessionId,
186
+ taskId: payload.taskId,
187
+ toolName: payload.toolName,
188
+ })
189
+ .catch(logTransportError);
190
+ }
191
+ });
192
+ // Forward llmservice:toolResult
193
+ registerForwarder('llmservice:toolResult', (payload) => {
194
+ if (payload.taskId && payload.callId) {
195
+ transportClient
196
+ ?.request('llmservice:toolResult', {
197
+ callId: payload.callId,
198
+ error: payload.error,
199
+ errorType: payload.errorType,
200
+ metadata: payload.metadata,
201
+ result: payload.result,
202
+ sessionId: payload.sessionId,
203
+ success: payload.success,
204
+ taskId: payload.taskId,
205
+ toolName: payload.toolName,
206
+ })
207
+ .catch(logTransportError);
208
+ }
209
+ });
210
+ // Forward llmservice:error
211
+ registerForwarder('llmservice:error', (payload) => {
212
+ if (payload.taskId) {
213
+ transportClient
214
+ ?.request('llmservice:error', {
215
+ code: payload.code,
216
+ error: payload.error,
217
+ sessionId: payload.sessionId,
218
+ taskId: payload.taskId,
219
+ })
220
+ .catch(logTransportError);
221
+ }
222
+ });
223
+ // Forward llmservice:unsupportedInput
224
+ registerForwarder('llmservice:unsupportedInput', (payload) => {
225
+ if (payload.taskId) {
226
+ transportClient
227
+ ?.request('llmservice:unsupportedInput', {
228
+ reason: payload.reason,
229
+ sessionId: payload.sessionId,
230
+ taskId: payload.taskId,
231
+ })
232
+ .catch(logTransportError);
233
+ }
234
+ });
235
+ agentLog(`Event forwarding setup complete (${eventForwarders.length} forwarders registered)`);
236
+ }
237
+ /** Task execution timeout: 5 minutes */
238
+ const TASK_EXECUTION_TIMEOUT_MS = 5 * 60 * 1000;
239
+ /**
240
+ * Setup the task executor for TaskQueueManager.
241
+ * Called after agent is initialized.
242
+ */
243
+ function setupTaskExecutor() {
244
+ taskQueueManager.setExecutor(async (task) => {
245
+ const { taskId, type } = task;
246
+ const stats = taskQueueManager.getStats(type);
247
+ agentLog(`Processing task ${taskId} (${type}), ${stats.queued} queued, ${stats.active} active`);
248
+ // Create timeout promise that rejects after 5 minutes
249
+ let timeoutId;
250
+ const timeoutPromise = new Promise((_, reject) => {
251
+ timeoutId = setTimeout(() => {
252
+ reject(new Error('TASK_TIMEOUT'));
253
+ }, TASK_EXECUTION_TIMEOUT_MS);
254
+ });
255
+ try {
256
+ // Race between task execution and timeout
257
+ await Promise.race([handleTaskExecute(task), timeoutPromise]);
258
+ }
259
+ catch (error) {
260
+ // Handle timeout specifically
261
+ if (error instanceof Error && error.message === 'TASK_TIMEOUT') {
262
+ agentLog(`Task ${taskId} timed out after 5 minutes`);
263
+ const errorData = serializeTaskError(new Error('Task exceeded 5 minute timeout'));
264
+ transportClient?.request('task:error', { error: errorData, taskId }).catch(logTransportError);
265
+ return;
266
+ }
267
+ // Handle other errors
268
+ agentLog(`Task execution failed: ${error}`);
269
+ const errorData = serializeTaskError(error);
270
+ transportClient?.request('task:error', { error: errorData, taskId }).catch(logTransportError);
271
+ }
272
+ finally {
273
+ // Always clear timeout to prevent memory leak
274
+ if (timeoutId) {
275
+ clearTimeout(timeoutId);
276
+ }
277
+ }
278
+ });
279
+ agentLog('Task executor setup complete');
280
+ }
281
+ /**
282
+ * Try to initialize/reinitialize the CipherAgent.
283
+ * Called on startup and lazily when tasks arrive but agent is not initialized.
284
+ * This handles the case where user completes onboarding after agent starts.
285
+ *
286
+ * @param forceReinit - Force reinitialization even if already initialized (for config reload)
287
+ */
288
+ async function tryInitializeAgent(forceReinit = false) {
289
+ // Guard: prevent concurrent initialization
290
+ if (isInitializing) {
291
+ agentLog('Initialization already in progress, skipping');
292
+ return false;
293
+ }
294
+ // Already initialized and not forcing reinit
295
+ if (!forceReinit && isAgentInitialized && cipherAgent && taskProcessor) {
296
+ return true;
297
+ }
298
+ isInitializing = true;
299
+ try {
300
+ // If forcing reinit, stop existing agent first
301
+ if (forceReinit && cipherAgent) {
302
+ agentLog('Reinitializing with new config...');
303
+ try {
304
+ await cipherAgent.stop();
305
+ }
306
+ catch (error) {
307
+ agentLog(`Error stopping previous agent: ${error}`);
308
+ }
309
+ cipherAgent = undefined;
310
+ taskProcessor = undefined;
311
+ isAgentInitialized = false;
312
+ }
313
+ const tokenStore = new KeychainTokenStore();
314
+ const configStore = new ProjectConfigStore();
315
+ const authToken = await tokenStore.load();
316
+ const brvConfig = await configStore.read();
317
+ // Need at least authToken to initialize
318
+ if (!authToken) {
319
+ initializationError = new NotAuthenticatedError();
320
+ agentLog('Cannot initialize - no auth token');
321
+ return false;
322
+ }
323
+ // Create Executors
324
+ const curateExecutor = new CurateExecutor();
325
+ const queryExecutor = new QueryExecutor();
326
+ // Initialize CipherAgent
327
+ const envConfig = getCurrentConfig();
328
+ const agentConfig = {
329
+ accessToken: authToken.accessToken,
330
+ apiBaseUrl: envConfig.llmApiBaseUrl,
331
+ fileSystem: { workingDirectory: process.cwd() },
332
+ llm: {
333
+ maxIterations: 10,
334
+ maxTokens: 4096,
335
+ temperature: 0.7,
336
+ topK: 10,
337
+ topP: 0.95,
338
+ verbose: false,
339
+ },
340
+ model: DEFAULT_LLM_MODEL,
341
+ projectId: PROJECT,
342
+ sessionKey: authToken.sessionKey,
343
+ };
344
+ const agent = new CipherAgent(agentConfig, brvConfig ?? undefined);
345
+ await agent.start();
346
+ agentLog('CipherAgent started');
347
+ // Create ChatSession
348
+ chatSessionId = `agent-session-${randomUUID()}`;
349
+ await agent.createSession(chatSessionId);
350
+ agentLog(`ChatSession created: ${chatSessionId}`);
351
+ // Setup event forwarding
352
+ setupAgentEventForwarding(agent);
353
+ cipherAgent = agent;
354
+ // Create TaskProcessor
355
+ taskProcessor = createTaskProcessor({
356
+ curateExecutor,
357
+ queryExecutor,
358
+ });
359
+ taskProcessor.setAgent(cipherAgent);
360
+ // Setup task executor for queue manager (enables processing)
361
+ setupTaskExecutor();
362
+ // Mark as initialized
363
+ isAgentInitialized = true;
364
+ initializationError = undefined;
365
+ if (brvConfig) {
366
+ agentLog(`Fully initialized with auth and config (team=${brvConfig.teamId}, space=${brvConfig.spaceId})`);
367
+ }
368
+ else {
369
+ agentLog('Initialized with auth only (no project config yet - will reinit when config available)');
370
+ }
371
+ return true;
372
+ }
373
+ finally {
374
+ isInitializing = false;
375
+ }
376
+ }
377
+ /**
378
+ * Handle task:execute from Transport.
379
+ */
380
+ async function handleTaskExecute(data) {
381
+ const { content, files, taskId, type } = data;
382
+ agentLog(`Processing task: ${taskId} (type=${type})`);
383
+ // If not initialized, try to initialize now (lazy init for post-onboarding)
384
+ if (!isAgentInitialized) {
385
+ agentLog('Not initialized, attempting lazy initialization...');
386
+ const initialized = await tryInitializeAgent();
387
+ if (!initialized) {
388
+ agentLog('Lazy initialization failed');
389
+ const error = serializeTaskError(initializationError ?? new ProcessorNotInitError());
390
+ transportClient?.request('task:error', { error, taskId }).catch(logTransportError);
391
+ return;
392
+ }
393
+ agentLog('Lazy initialization successful!');
394
+ }
395
+ // NOTE: Config change detection removed - use explicit agent:restart event instead
396
+ // (triggered by /init command via TransportHandlers)
397
+ if (!taskProcessor) {
398
+ agentLog('TaskProcessor not initialized');
399
+ const error = serializeTaskError(new ProcessorNotInitError());
400
+ transportClient?.request('task:error', { error, taskId }).catch(logTransportError);
401
+ return;
402
+ }
403
+ // Notify task started
404
+ transportClient?.request('task:started', { taskId }).catch(logTransportError);
405
+ try {
406
+ // Process task - events stream via agentEventBus subscription
407
+ // Response is forwarded via llmservice:response event (no manual send needed)
408
+ // Agent uses its default session (Single-Session pattern)
409
+ // File validation is handled by UseCase (business logic belongs there)
410
+ // Note: taskId is passed to UseCase → CipherAgent → ChatSession, which adds it to all events
411
+ const result = await taskProcessor.process({
412
+ content,
413
+ files,
414
+ taskId,
415
+ type,
416
+ });
417
+ // Notify completion with result (required by TaskCompletedEventSchema)
418
+ agentLog(`Task completed: ${taskId}`);
419
+ transportClient?.request('task:completed', { result, taskId }).catch(logTransportError);
420
+ }
421
+ catch (error) {
422
+ const errorData = serializeTaskError(error);
423
+ agentLog(`Task error: ${taskId} - [${errorData.name}] ${errorData.message}`);
424
+ transportClient?.request('task:error', { error: errorData, taskId }).catch(logTransportError);
425
+ }
426
+ }
427
+ /**
428
+ * Handle task:cancel from Transport.
429
+ * Uses TaskQueueManager to remove from queue or signal cancellation.
430
+ */
431
+ function handleTaskCancel(data) {
432
+ const { taskId } = data;
433
+ agentLog(`Cancelling task: ${taskId}`);
434
+ const result = taskQueueManager.cancel(taskId);
435
+ if (result.success) {
436
+ if (result.wasQueued) {
437
+ // Task was in queue, not yet processing - removed by queue manager
438
+ agentLog(`Task ${taskId} removed from ${result.taskType} queue (was waiting)`);
439
+ // Notify transport that task was cancelled
440
+ transportClient?.request('task:cancelled', { taskId }).catch(logTransportError);
441
+ }
442
+ else {
443
+ // Task is currently processing - cancel via taskProcessor
444
+ agentLog(`Task ${taskId} is processing, forwarding cancel to taskProcessor`);
445
+ taskProcessor?.cancel(taskId);
446
+ }
447
+ }
448
+ else {
449
+ agentLog(`Task ${taskId} not found in queue or processing`);
450
+ }
451
+ }
452
+ /**
453
+ * Start Agent Process.
454
+ */
455
+ async function startAgent() {
456
+ const port = getTransportPort();
457
+ agentLog(`Connecting to Transport on port ${port}`);
458
+ // Create Transport client
459
+ transportClient = createTransportClient();
460
+ // Connect to Transport
461
+ await transportClient.connect(`http://localhost:${port}`);
462
+ agentLog('Connected to Transport');
463
+ // Register as Agent
464
+ await transportClient.request('agent:register', {});
465
+ agentLog('Registered with Transport');
466
+ // Try to initialize agent (may fail if no auth yet - that's OK, will lazy init later)
467
+ const initialized = await tryInitializeAgent();
468
+ if (!initialized) {
469
+ agentLog('Initial setup incomplete - will retry when tasks arrive (lazy init)');
470
+ }
471
+ // Setup event handlers - TaskQueueManager handles queueing and deduplication
472
+ transportClient.on('task:execute', (data) => {
473
+ const result = taskQueueManager.enqueue(data);
474
+ if (result.success) {
475
+ const stats = taskQueueManager.getStats(data.type);
476
+ agentLog(`Task ${data.taskId} (${data.type}) queued at position ${result.position}, ${stats.queued} in queue`);
477
+ }
478
+ else if (result.reason === 'duplicate') {
479
+ agentLog(`Task ${data.taskId} already known (duplicate), ignoring`);
480
+ }
481
+ else {
482
+ agentLog(`Task ${data.taskId} rejected: ${result.reason}`);
483
+ }
484
+ });
485
+ transportClient.on('task:cancel', handleTaskCancel);
486
+ // Handle shutdown from Transport
487
+ transportClient.on('shutdown', () => {
488
+ agentLog('Received shutdown from Transport');
489
+ stopAgent().then(() => {
490
+ sendToParent({ type: 'stopped' });
491
+ // eslint-disable-next-line n/no-process-exit, unicorn/no-process-exit
492
+ process.exit(0);
493
+ });
494
+ });
495
+ // Handle agent:restart from Transport (triggered by client, e.g., after /init)
496
+ transportClient.on('agent:restart', async (data) => {
497
+ agentLog(`Agent restart requested: ${data.reason ?? 'no reason'}`);
498
+ try {
499
+ // Reinitialize agent with fresh config
500
+ const success = await tryInitializeAgent(true); // forceReinit = true
501
+ if (success) {
502
+ agentLog('Agent reinitialized successfully');
503
+ // Notify Transport that restart completed
504
+ await transportClient?.request('agent:restarted', { success: true });
505
+ }
506
+ else {
507
+ agentLog('Agent reinitialization failed - config incomplete');
508
+ await transportClient?.request('agent:restarted', {
509
+ error: 'Config incomplete (no auth token or config)',
510
+ success: false,
511
+ });
512
+ }
513
+ }
514
+ catch (error) {
515
+ const message = error instanceof Error ? error.message : String(error);
516
+ agentLog(`Agent reinitialization error: ${message}`);
517
+ await transportClient?.request('agent:restarted', { error: message, success: false });
518
+ }
519
+ });
520
+ agentLog('Ready to process tasks');
521
+ }
522
+ /**
523
+ * Stop Agent Process.
524
+ */
525
+ async function stopAgent() {
526
+ // Guard: prevent double cleanup
527
+ if (isCleaningUp) {
528
+ agentLog('Cleanup already in progress, skipping');
529
+ return;
530
+ }
531
+ isCleaningUp = true;
532
+ try {
533
+ // Clear task queue
534
+ taskQueueManager.clear();
535
+ // Cleanup event forwarders before stopping agent
536
+ cleanupAgentEventForwarding();
537
+ // Stop CipherAgent first
538
+ if (cipherAgent) {
539
+ await cipherAgent.stop();
540
+ cipherAgent = undefined;
541
+ agentLog('CipherAgent stopped');
542
+ }
543
+ if (transportClient) {
544
+ await transportClient.disconnect();
545
+ transportClient = undefined;
546
+ }
547
+ taskProcessor = undefined;
548
+ isAgentInitialized = false;
549
+ agentLog('Stopped');
550
+ }
551
+ finally {
552
+ isCleaningUp = false;
553
+ }
554
+ }
555
+ // ============================================================================
556
+ // Worker Entry Point
557
+ // ============================================================================
558
+ async function runWorker() {
559
+ try {
560
+ await startAgent();
561
+ sendToParent({ type: 'ready' });
562
+ }
563
+ catch (error) {
564
+ const message = error instanceof Error ? error.message : String(error);
565
+ agentLog(`Failed to start: ${message}`);
566
+ sendToParent({ error: message, type: 'error' });
567
+ // eslint-disable-next-line n/no-process-exit, unicorn/no-process-exit
568
+ process.exit(1);
569
+ }
570
+ // IPC message handler
571
+ process.on('message', async (msg) => {
572
+ if (msg.type === 'ping') {
573
+ sendToParent({ type: 'pong' });
574
+ }
575
+ else if (msg.type === 'shutdown') {
576
+ await stopAgent();
577
+ sendToParent({ type: 'stopped' });
578
+ // eslint-disable-next-line n/no-process-exit
579
+ process.exit(0);
580
+ }
581
+ });
582
+ // Signal handlers
583
+ const cleanup = async () => {
584
+ await stopAgent();
585
+ // eslint-disable-next-line n/no-process-exit, unicorn/no-process-exit
586
+ process.exit(0);
587
+ };
588
+ process.once('SIGTERM', cleanup);
589
+ process.once('SIGINT', cleanup);
590
+ process.once('disconnect', cleanup);
591
+ }
592
+ // ============================================================================
593
+ // Run
594
+ // ============================================================================
595
+ try {
596
+ await runWorker();
597
+ }
598
+ catch (error) {
599
+ agentLog(`Fatal error: ${error}`);
600
+ // eslint-disable-next-line n/no-process-exit, unicorn/no-process-exit
601
+ process.exit(1);
602
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Process module exports.
3
+ *
4
+ * Architecture v0.5.0:
5
+ * - ProcessManager: Spawns and manages Transport and Agent processes
6
+ * - transport-worker.ts: Transport Process entry point
7
+ * - agent-worker.ts: Agent Process entry point
8
+ * - TransportHandlers: Message routing in Transport Process
9
+ */
10
+ export { disposeProcessManager, getProcessManager, ProcessManager } from './process-manager.js';
11
+ export type { ProcessManagerConfig, ProcessState } from './process-manager.js';
12
+ export { TransportHandlers } from './transport-handlers.js';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Process module exports.
3
+ *
4
+ * Architecture v0.5.0:
5
+ * - ProcessManager: Spawns and manages Transport and Agent processes
6
+ * - transport-worker.ts: Transport Process entry point
7
+ * - agent-worker.ts: Agent Process entry point
8
+ * - TransportHandlers: Message routing in Transport Process
9
+ */
10
+ export { disposeProcessManager, getProcessManager, ProcessManager } from './process-manager.js';
11
+ export { TransportHandlers } from './transport-handlers.js';
@@ -0,0 +1,55 @@
1
+ /**
2
+ * IPC Types - Shared types for Node.js IPC between parent and child processes.
3
+ *
4
+ * Architecture v0.5.0:
5
+ * - IPC is used ONLY for process lifecycle (ready, ping/pong, shutdown, error)
6
+ * - Task communication uses Socket.IO (NOT IPC)
7
+ *
8
+ * Message flows:
9
+ * - Parent → Child: IPCCommand (ping, shutdown)
10
+ * - Child → Parent: IPCResponse variants (ready, pong, stopped, error)
11
+ */
12
+ /**
13
+ * Commands sent from parent (ProcessManager) to child processes.
14
+ */
15
+ export type IPCCommand = {
16
+ type: 'ping';
17
+ } | {
18
+ type: 'shutdown';
19
+ };
20
+ /**
21
+ * Base response types (shared by all child processes).
22
+ */
23
+ export type IPCPongResponse = {
24
+ type: 'pong';
25
+ };
26
+ export type IPCStoppedResponse = {
27
+ type: 'stopped';
28
+ };
29
+ export type IPCErrorResponse = {
30
+ error: string;
31
+ type: 'error';
32
+ };
33
+ /**
34
+ * Ready response variants.
35
+ * - Transport: includes port number
36
+ * - Agent: simple ready signal
37
+ */
38
+ export type IPCReadyResponse = {
39
+ type: 'ready';
40
+ };
41
+ export type IPCReadyWithPortResponse = {
42
+ port: number;
43
+ type: 'ready';
44
+ };
45
+ /**
46
+ * Composite response types for each process type.
47
+ */
48
+ export type TransportIPCResponse = IPCErrorResponse | IPCPongResponse | IPCReadyWithPortResponse | IPCStoppedResponse;
49
+ export type AgentIPCResponse = IPCErrorResponse | IPCPongResponse | IPCReadyResponse | IPCStoppedResponse;
50
+ /**
51
+ * Legacy aliases for gradual migration.
52
+ * @deprecated Use IPCCommand instead
53
+ */
54
+ export type IPCMessage = IPCCommand;
55
+ export type IPCMessageToChild = IPCCommand;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * IPC Types - Shared types for Node.js IPC between parent and child processes.
3
+ *
4
+ * Architecture v0.5.0:
5
+ * - IPC is used ONLY for process lifecycle (ready, ping/pong, shutdown, error)
6
+ * - Task communication uses Socket.IO (NOT IPC)
7
+ *
8
+ * Message flows:
9
+ * - Parent → Child: IPCCommand (ping, shutdown)
10
+ * - Child → Parent: IPCResponse variants (ready, pong, stopped, error)
11
+ */
12
+ export {};