@cortex-agent/server 2026.5.19-1

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 (503) hide show
  1. package/defaults/.claude/settings.json +13 -0
  2. package/defaults/CORTEX.md +15 -0
  3. package/defaults/config/budget.json +4 -0
  4. package/defaults/config/session-hooks.json +7 -0
  5. package/defaults/config/thread-templates.json +528 -0
  6. package/defaults/context/CORTEX.md +40 -0
  7. package/defaults/context/decisions/DR-0012.md +54 -0
  8. package/defaults/context/ideas/CORTEX.md +10 -0
  9. package/defaults/context/projects/CORTEX.md +25 -0
  10. package/defaults/context/scans/CORTEX.md +13 -0
  11. package/defaults/context/user/CORTEX.md +21 -0
  12. package/defaults/data/schedules.json +52 -0
  13. package/defaults/gitignore +44 -0
  14. package/defaults/hooks/ask-user-question-hook.mjs +66 -0
  15. package/defaults/hooks/cortex-md-injector.mjs +237 -0
  16. package/defaults/hooks/exit-plan-mode-hook.mjs +84 -0
  17. package/defaults/hooks/memory-ref-tracker.mjs +154 -0
  18. package/defaults/hooks/new-session-hook.mjs +83 -0
  19. package/defaults/hooks/post-task-hook.mjs +63 -0
  20. package/defaults/hooks/rules-loader.mjs +212 -0
  21. package/defaults/hooks/sensitive-file-edit.mjs +84 -0
  22. package/defaults/hooks/session-activity-tracker.mjs +254 -0
  23. package/defaults/hooks/task-status-check.mjs +218 -0
  24. package/defaults/hooks/tasks-yaml-guard.mjs +230 -0
  25. package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +5 -0
  26. package/defaults/plugins/cortex-coder/skills/cli-standards/SKILL.md +208 -0
  27. package/defaults/plugins/cortex-coder/skills/code-standards/SKILL.md +146 -0
  28. package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +164 -0
  29. package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +5 -0
  30. package/defaults/plugins/cortex-common/skills/compound/SKILL.md +349 -0
  31. package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +104 -0
  32. package/defaults/plugins/cortex-common/skills/critique/SKILL.md +88 -0
  33. package/defaults/plugins/cortex-common/skills/debug-campaign/SKILL.md +508 -0
  34. package/defaults/plugins/cortex-common/skills/diagnose/SKILL.md +169 -0
  35. package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +135 -0
  36. package/defaults/plugins/cortex-common/skills/solution-design/SKILL.md +183 -0
  37. package/defaults/plugins/cortex-common/skills/synthesize/SKILL.md +120 -0
  38. package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +5 -0
  39. package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +89 -0
  40. package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +163 -0
  41. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +425 -0
  42. package/defaults/plugins/cortex-system/.claude-plugin/plugin.json +5 -0
  43. package/defaults/plugins/cortex-system/skills/approval/SKILL.md +84 -0
  44. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +199 -0
  45. package/defaults/plugins/cortex-system/skills/deep-retrospective/CORTEX.md +8 -0
  46. package/defaults/plugins/cortex-system/skills/deep-retrospective/SKILL.md +201 -0
  47. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/CORTEX.md +8 -0
  48. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/extract_session.py +165 -0
  49. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/scan_logs.py +402 -0
  50. package/defaults/plugins/cortex-system/skills/evolve/SKILL.md +115 -0
  51. package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +262 -0
  52. package/defaults/plugins/cortex-system/skills/gravity/SKILL.md +125 -0
  53. package/defaults/plugins/cortex-system/skills/orient/SKILL.md +310 -0
  54. package/defaults/plugins/cortex-system/skills/orient-project/SKILL.md +85 -0
  55. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +167 -0
  56. package/defaults/plugins/cortex-system/skills/refresh-skills/SKILL.md +153 -0
  57. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +209 -0
  58. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +478 -0
  59. package/defaults/plugins/cortex-system/skills/user-learn/SKILL.md +95 -0
  60. package/defaults/prompts/directives/coder-reviewer.md +106 -0
  61. package/defaults/prompts/directives/coder.md +90 -0
  62. package/defaults/prompts/directives/director.md +97 -0
  63. package/defaults/prompts/directives/doc-reviewer.md +93 -0
  64. package/defaults/prompts/directives/doc-writer.md +85 -0
  65. package/defaults/prompts/directives/executor-reviewer.md +96 -0
  66. package/defaults/prompts/directives/executor.md +85 -0
  67. package/defaults/prompts/directives/milestone-executor.md +119 -0
  68. package/defaults/prompts/directives/milestone-reviewer.md +108 -0
  69. package/defaults/prompts/directives/plan-executor.md +121 -0
  70. package/defaults/prompts/directives/plan-reviewer.md +99 -0
  71. package/defaults/prompts/systemPrompts/coder.md +64 -0
  72. package/defaults/prompts/systemPrompts/direct.md +92 -0
  73. package/defaults/prompts/systemPrompts/web-opus-4-6.md +68 -0
  74. package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +76 -0
  75. package/defaults/prompts/systemPrompts/web.md +50 -0
  76. package/defaults/prompts/systemPrompts/worker.md +67 -0
  77. package/defaults/rules/correction-propagation.md +31 -0
  78. package/defaults/rules/decision-records.md +49 -0
  79. package/defaults/rules/experiment-format.md +165 -0
  80. package/defaults/rules/issues-md.md +37 -0
  81. package/defaults/rules/meta-conventions.md +45 -0
  82. package/defaults/rules/mission-md.md +47 -0
  83. package/defaults/rules/overview-md.md +41 -0
  84. package/defaults/rules/roadmap-md.md +55 -0
  85. package/defaults/rules/status-md.md +49 -0
  86. package/defaults/rules/task-system.md +53 -0
  87. package/dist/agent-adapter/capabilities.d.ts +12 -0
  88. package/dist/agent-adapter/capabilities.js +52 -0
  89. package/dist/agent-adapter/claude/adapter-tui.d.ts +140 -0
  90. package/dist/agent-adapter/claude/adapter-tui.js +422 -0
  91. package/dist/agent-adapter/claude/adapter.d.ts +85 -0
  92. package/dist/agent-adapter/claude/adapter.js +771 -0
  93. package/dist/agent-adapter/claude/cost-from-usage.d.ts +62 -0
  94. package/dist/agent-adapter/claude/cost-from-usage.js +97 -0
  95. package/dist/agent-adapter/claude/defaults.d.ts +30 -0
  96. package/dist/agent-adapter/claude/defaults.js +49 -0
  97. package/dist/agent-adapter/claude/event-parser.d.ts +28 -0
  98. package/dist/agent-adapter/claude/event-parser.js +173 -0
  99. package/dist/agent-adapter/claude/hooks-builder.d.ts +36 -0
  100. package/dist/agent-adapter/claude/hooks-builder.js +57 -0
  101. package/dist/agent-adapter/claude/jsonl-tail.d.ts +68 -0
  102. package/dist/agent-adapter/claude/jsonl-tail.js +344 -0
  103. package/dist/agent-adapter/claude/spawn-args.d.ts +38 -0
  104. package/dist/agent-adapter/claude/spawn-args.js +83 -0
  105. package/dist/agent-adapter/claude/tmux-control.d.ts +69 -0
  106. package/dist/agent-adapter/claude/tmux-control.js +127 -0
  107. package/dist/agent-adapter/claude/tool-summarizers.d.ts +2 -0
  108. package/dist/agent-adapter/claude/tool-summarizers.js +24 -0
  109. package/dist/agent-adapter/codex/adapter.d.ts +42 -0
  110. package/dist/agent-adapter/codex/adapter.js +916 -0
  111. package/dist/agent-adapter/codex/event-parser.d.ts +17 -0
  112. package/dist/agent-adapter/codex/event-parser.js +41 -0
  113. package/dist/agent-adapter/codex/spawn-args.d.ts +6 -0
  114. package/dist/agent-adapter/codex/spawn-args.js +30 -0
  115. package/dist/agent-adapter/index.d.ts +8 -0
  116. package/dist/agent-adapter/index.js +33 -0
  117. package/dist/agent-adapter/normalize/event-stream.d.ts +6 -0
  118. package/dist/agent-adapter/normalize/event-stream.js +47 -0
  119. package/dist/agent-adapter/normalize/event-types.d.ts +58 -0
  120. package/dist/agent-adapter/normalize/event-types.js +5 -0
  121. package/dist/agent-adapter/normalize/hooks.d.ts +26 -0
  122. package/dist/agent-adapter/normalize/hooks.js +5 -0
  123. package/dist/agent-adapter/normalize/prompt-builder.d.ts +6 -0
  124. package/dist/agent-adapter/normalize/prompt-builder.js +23 -0
  125. package/dist/agent-adapter/normalize/tool-names.d.ts +6 -0
  126. package/dist/agent-adapter/normalize/tool-names.js +73 -0
  127. package/dist/agent-adapter/pi/adapter.d.ts +60 -0
  128. package/dist/agent-adapter/pi/adapter.js +626 -0
  129. package/dist/agent-adapter/pi/agent-dir.d.ts +11 -0
  130. package/dist/agent-adapter/pi/agent-dir.js +34 -0
  131. package/dist/agent-adapter/pi/event-parser.d.ts +26 -0
  132. package/dist/agent-adapter/pi/event-parser.js +313 -0
  133. package/dist/agent-adapter/pi/framing.d.ts +6 -0
  134. package/dist/agent-adapter/pi/framing.js +35 -0
  135. package/dist/agent-adapter/pi/hook-bridge.d.ts +59 -0
  136. package/dist/agent-adapter/pi/hook-bridge.js +233 -0
  137. package/dist/agent-adapter/pi/mcp-bridge.d.ts +26 -0
  138. package/dist/agent-adapter/pi/mcp-bridge.js +140 -0
  139. package/dist/agent-adapter/pi/pi-ext-types.d.ts +90 -0
  140. package/dist/agent-adapter/pi/pi-ext-types.js +5 -0
  141. package/dist/agent-adapter/pi/spawn-args.d.ts +20 -0
  142. package/dist/agent-adapter/pi/spawn-args.js +54 -0
  143. package/dist/agent-adapter/pi/tool-shims.d.ts +2 -0
  144. package/dist/agent-adapter/pi/tool-shims.js +181 -0
  145. package/dist/agent-adapter/types.d.ts +94 -0
  146. package/dist/agent-adapter/types.js +5 -0
  147. package/dist/core/async-mutex.d.ts +6 -0
  148. package/dist/core/async-mutex.js +36 -0
  149. package/dist/core/cli-utils.d.ts +37 -0
  150. package/dist/core/cli-utils.js +69 -0
  151. package/dist/core/config-generator.d.ts +9 -0
  152. package/dist/core/config-generator.js +58 -0
  153. package/dist/core/gateway-generator.d.ts +46 -0
  154. package/dist/core/gateway-generator.js +336 -0
  155. package/dist/core/log.d.ts +7 -0
  156. package/dist/core/log.js +103 -0
  157. package/dist/core/paths.d.ts +32 -0
  158. package/dist/core/paths.js +49 -0
  159. package/dist/core/profile-generator.d.ts +65 -0
  160. package/dist/core/profile-generator.js +310 -0
  161. package/dist/core/running-executions.d.ts +88 -0
  162. package/dist/core/running-executions.js +186 -0
  163. package/dist/core/status-format.d.ts +18 -0
  164. package/dist/core/status-format.js +31 -0
  165. package/dist/core/task-parser.d.ts +69 -0
  166. package/dist/core/task-parser.js +423 -0
  167. package/dist/core/types/agent-types.d.ts +31 -0
  168. package/dist/core/types/agent-types.js +5 -0
  169. package/dist/core/types/thread-types.d.ts +261 -0
  170. package/dist/core/types/thread-types.js +5 -0
  171. package/dist/core/utils.d.ts +29 -0
  172. package/dist/core/utils.js +98 -0
  173. package/dist/core/version.d.ts +3 -0
  174. package/dist/core/version.js +12 -0
  175. package/dist/domain/agents/config.d.ts +58 -0
  176. package/dist/domain/agents/config.js +313 -0
  177. package/dist/domain/agents/facade.d.ts +52 -0
  178. package/dist/domain/agents/facade.js +264 -0
  179. package/dist/domain/agents/index.d.ts +2 -0
  180. package/dist/domain/agents/index.js +4 -0
  181. package/dist/domain/agents/profile-manager.d.ts +54 -0
  182. package/dist/domain/agents/profile-manager.js +161 -0
  183. package/dist/domain/costs/codex-event-format.d.ts +4 -0
  184. package/dist/domain/costs/codex-event-format.js +66 -0
  185. package/dist/domain/costs/codex-usage-monitor.d.ts +7 -0
  186. package/dist/domain/costs/codex-usage-monitor.js +72 -0
  187. package/dist/domain/costs/cost-tracker.d.ts +115 -0
  188. package/dist/domain/costs/cost-tracker.js +327 -0
  189. package/dist/domain/costs/gateway-manager.d.ts +6 -0
  190. package/dist/domain/costs/gateway-manager.js +228 -0
  191. package/dist/domain/costs/rate-limit-parser.d.ts +11 -0
  192. package/dist/domain/costs/rate-limit-parser.js +87 -0
  193. package/dist/domain/costs/rate-limit-throttle.d.ts +32 -0
  194. package/dist/domain/costs/rate-limit-throttle.js +129 -0
  195. package/dist/domain/executions/registry.d.ts +20 -0
  196. package/dist/domain/executions/registry.js +124 -0
  197. package/dist/domain/mcp/core-server.d.ts +2 -0
  198. package/dist/domain/mcp/core-server.js +34 -0
  199. package/dist/domain/mcp/server.d.ts +3 -0
  200. package/dist/domain/mcp/server.js +78 -0
  201. package/dist/domain/mcp/tools/context.d.ts +23 -0
  202. package/dist/domain/mcp/tools/context.js +51 -0
  203. package/dist/domain/mcp/tools/cortex-md.d.ts +17 -0
  204. package/dist/domain/mcp/tools/cortex-md.js +36 -0
  205. package/dist/domain/mcp/tools/cost.d.ts +2 -0
  206. package/dist/domain/mcp/tools/cost.js +54 -0
  207. package/dist/domain/mcp/tools/executions.d.ts +2 -0
  208. package/dist/domain/mcp/tools/executions.js +94 -0
  209. package/dist/domain/mcp/tools/schedule.d.ts +23 -0
  210. package/dist/domain/mcp/tools/schedule.js +245 -0
  211. package/dist/domain/mcp/tools/slack.d.ts +21 -0
  212. package/dist/domain/mcp/tools/slack.js +124 -0
  213. package/dist/domain/mcp/tools/task-ops.d.ts +2 -0
  214. package/dist/domain/mcp/tools/task-ops.js +509 -0
  215. package/dist/domain/mcp/tools/tui-ask.d.ts +31 -0
  216. package/dist/domain/mcp/tools/tui-ask.js +108 -0
  217. package/dist/domain/mcp/tools/tui-plan.d.ts +28 -0
  218. package/dist/domain/mcp/tools/tui-plan.js +118 -0
  219. package/dist/domain/mcp/tui-server.d.ts +2 -0
  220. package/dist/domain/mcp/tui-server.js +69 -0
  221. package/dist/domain/memory/consolidate.d.ts +55 -0
  222. package/dist/domain/memory/consolidate.js +471 -0
  223. package/dist/domain/memory/cortex-md-injector.d.ts +30 -0
  224. package/dist/domain/memory/cortex-md-injector.js +123 -0
  225. package/dist/domain/memory/cortex-md-scanner.d.ts +9 -0
  226. package/dist/domain/memory/cortex-md-scanner.js +67 -0
  227. package/dist/domain/memory/index-regen.d.ts +19 -0
  228. package/dist/domain/memory/index-regen.js +398 -0
  229. package/dist/domain/memory/rules-loader.d.ts +27 -0
  230. package/dist/domain/memory/rules-loader.js +97 -0
  231. package/dist/domain/memory/skill-scanner.d.ts +5 -0
  232. package/dist/domain/memory/skill-scanner.js +132 -0
  233. package/dist/domain/memory/user-context.d.ts +5 -0
  234. package/dist/domain/memory/user-context.js +34 -0
  235. package/dist/domain/memory/watcher.d.ts +2 -0
  236. package/dist/domain/memory/watcher.js +81 -0
  237. package/dist/domain/monitor/disk-monitor.d.ts +20 -0
  238. package/dist/domain/monitor/disk-monitor.js +97 -0
  239. package/dist/domain/monitor/gpu-monitor.d.ts +26 -0
  240. package/dist/domain/monitor/gpu-monitor.js +135 -0
  241. package/dist/domain/remote/client-bootstrap.d.ts +1 -0
  242. package/dist/domain/remote/client-bootstrap.js +139 -0
  243. package/dist/domain/remote/client-hot-reload.d.ts +18 -0
  244. package/dist/domain/remote/client-hot-reload.js +142 -0
  245. package/dist/domain/remote/client-manager.d.ts +50 -0
  246. package/dist/domain/remote/client-manager.js +452 -0
  247. package/dist/domain/remote/cortex-client.d.ts +1 -0
  248. package/dist/domain/remote/cortex-client.js +704 -0
  249. package/dist/domain/scheduling/job-registry.d.ts +31 -0
  250. package/dist/domain/scheduling/job-registry.js +34 -0
  251. package/dist/domain/scheduling/jobs/_shared.d.ts +14 -0
  252. package/dist/domain/scheduling/jobs/_shared.js +45 -0
  253. package/dist/domain/scheduling/jobs/memory-index-regen.d.ts +1 -0
  254. package/dist/domain/scheduling/jobs/memory-index-regen.js +16 -0
  255. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +11 -0
  256. package/dist/domain/scheduling/jobs/scheduled-task.js +186 -0
  257. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +41 -0
  258. package/dist/domain/scheduling/jobs/target-dispatch.js +48 -0
  259. package/dist/domain/scheduling/jobs/task-archive.d.ts +1 -0
  260. package/dist/domain/scheduling/jobs/task-archive.js +19 -0
  261. package/dist/domain/scheduling/jobs/task-dispatch.d.ts +12 -0
  262. package/dist/domain/scheduling/jobs/task-dispatch.js +214 -0
  263. package/dist/domain/scheduling/runner.d.ts +13 -0
  264. package/dist/domain/scheduling/runner.js +24 -0
  265. package/dist/domain/scheduling/schedule-cli.d.ts +16 -0
  266. package/dist/domain/scheduling/schedule-cli.js +268 -0
  267. package/dist/domain/scheduling/schedule-command.d.ts +4 -0
  268. package/dist/domain/scheduling/schedule-command.js +274 -0
  269. package/dist/domain/scheduling/scheduler.d.ts +86 -0
  270. package/dist/domain/scheduling/scheduler.js +544 -0
  271. package/dist/domain/sessions/session-backup.d.ts +49 -0
  272. package/dist/domain/sessions/session-backup.js +217 -0
  273. package/dist/domain/sessions/session-hooks.d.ts +103 -0
  274. package/dist/domain/sessions/session-hooks.js +311 -0
  275. package/dist/domain/sessions/session-registry.d.ts +21 -0
  276. package/dist/domain/sessions/session-registry.js +31 -0
  277. package/dist/domain/sessions/session.d.ts +3 -0
  278. package/dist/domain/sessions/session.js +14 -0
  279. package/dist/domain/tasks/archiver.d.ts +9 -0
  280. package/dist/domain/tasks/archiver.js +123 -0
  281. package/dist/domain/tasks/dispatch-utils.d.ts +37 -0
  282. package/dist/domain/tasks/dispatch-utils.js +143 -0
  283. package/dist/domain/tasks/dispatcher.d.ts +48 -0
  284. package/dist/domain/tasks/dispatcher.js +285 -0
  285. package/dist/domain/tasks/lint.d.ts +12 -0
  286. package/dist/domain/tasks/lint.js +102 -0
  287. package/dist/domain/tasks/mutator.d.ts +21 -0
  288. package/dist/domain/tasks/mutator.js +208 -0
  289. package/dist/domain/tasks/parser.d.ts +1 -0
  290. package/dist/domain/tasks/parser.js +6 -0
  291. package/dist/domain/tasks/pending-tracker.d.ts +67 -0
  292. package/dist/domain/tasks/pending-tracker.js +163 -0
  293. package/dist/domain/tasks/recommendation/extractor.d.ts +12 -0
  294. package/dist/domain/tasks/recommendation/extractor.js +563 -0
  295. package/dist/domain/tasks/recommendation/patterns.d.ts +11 -0
  296. package/dist/domain/tasks/recommendation/patterns.js +99 -0
  297. package/dist/domain/tasks/recommendation/types.d.ts +67 -0
  298. package/dist/domain/tasks/recommendation/types.js +5 -0
  299. package/dist/domain/tasks/store.d.ts +1 -0
  300. package/dist/domain/tasks/store.js +3 -0
  301. package/dist/domain/tasks/system/cortex-run.d.ts +24 -0
  302. package/dist/domain/tasks/system/cortex-run.js +342 -0
  303. package/dist/domain/tasks/system/task-cli.d.ts +49 -0
  304. package/dist/domain/tasks/system/task-cli.js +664 -0
  305. package/dist/domain/tasks/system/task-completion.d.ts +22 -0
  306. package/dist/domain/tasks/system/task-completion.js +89 -0
  307. package/dist/domain/tasks/system/task-id-utils.d.ts +24 -0
  308. package/dist/domain/tasks/system/task-id-utils.js +84 -0
  309. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +34 -0
  310. package/dist/domain/tasks/system/task-lifecycle-edit.js +208 -0
  311. package/dist/domain/tasks/system/task-lock.d.ts +25 -0
  312. package/dist/domain/tasks/system/task-lock.js +139 -0
  313. package/dist/domain/tasks/system/task-mutations.d.ts +31 -0
  314. package/dist/domain/tasks/system/task-mutations.js +110 -0
  315. package/dist/domain/tasks/system/task-process.d.ts +37 -0
  316. package/dist/domain/tasks/system/task-process.js +119 -0
  317. package/dist/domain/tasks/system/task-state.d.ts +70 -0
  318. package/dist/domain/tasks/system/task-state.js +176 -0
  319. package/dist/domain/threads/artifact-io.d.ts +18 -0
  320. package/dist/domain/threads/artifact-io.js +182 -0
  321. package/dist/domain/threads/auto-thread.d.ts +3 -0
  322. package/dist/domain/threads/auto-thread.js +19 -0
  323. package/dist/domain/threads/hook-runner.d.ts +4 -0
  324. package/dist/domain/threads/hook-runner.js +250 -0
  325. package/dist/domain/threads/index.d.ts +5 -0
  326. package/dist/domain/threads/index.js +7 -0
  327. package/dist/domain/threads/prompt-builder.d.ts +25 -0
  328. package/dist/domain/threads/prompt-builder.js +176 -0
  329. package/dist/domain/threads/runner.d.ts +83 -0
  330. package/dist/domain/threads/runner.js +434 -0
  331. package/dist/domain/threads/state-machine.d.ts +61 -0
  332. package/dist/domain/threads/state-machine.js +440 -0
  333. package/dist/domain/threads/template-loader.d.ts +20 -0
  334. package/dist/domain/threads/template-loader.js +189 -0
  335. package/dist/domain/threads/template-resolver.d.ts +1 -0
  336. package/dist/domain/threads/template-resolver.js +95 -0
  337. package/dist/domain/threads/utils.d.ts +19 -0
  338. package/dist/domain/threads/utils.js +49 -0
  339. package/dist/entry/app.d.ts +1 -0
  340. package/dist/entry/app.js +234 -0
  341. package/dist/entry/cli.d.ts +12 -0
  342. package/dist/entry/cli.js +254 -0
  343. package/dist/entry/daemon.d.ts +11 -0
  344. package/dist/entry/daemon.js +521 -0
  345. package/dist/entry/init.d.ts +93 -0
  346. package/dist/entry/init.js +1299 -0
  347. package/dist/entry/startup-helpers.d.ts +2 -0
  348. package/dist/entry/startup-helpers.js +56 -0
  349. package/dist/entry/startup-notify.d.ts +10 -0
  350. package/dist/entry/startup-notify.js +20 -0
  351. package/dist/events/event-bus.d.ts +42 -0
  352. package/dist/events/event-bus.js +84 -0
  353. package/dist/events/event-logger.d.ts +12 -0
  354. package/dist/events/event-logger.js +135 -0
  355. package/dist/events/event-replay.d.ts +1 -0
  356. package/dist/events/event-replay.js +51 -0
  357. package/dist/events/event-types.d.ts +145 -0
  358. package/dist/events/event-types.js +5 -0
  359. package/dist/events/index.d.ts +5 -0
  360. package/dist/events/index.js +6 -0
  361. package/dist/hooks/ask-user-question-hook.mjs +66 -0
  362. package/dist/hooks/cortex-md-injector.mjs +237 -0
  363. package/dist/hooks/exit-plan-mode-hook.mjs +84 -0
  364. package/dist/hooks/memory-ref-tracker.mjs +154 -0
  365. package/dist/hooks/new-session-hook.mjs +83 -0
  366. package/dist/hooks/post-task-hook.mjs +63 -0
  367. package/dist/hooks/rules-loader.mjs +212 -0
  368. package/dist/hooks/sensitive-file-edit.mjs +84 -0
  369. package/dist/hooks/session-activity-tracker.mjs +254 -0
  370. package/dist/hooks/task-status-check.mjs +218 -0
  371. package/dist/hooks/tasks-yaml-guard.mjs +230 -0
  372. package/dist/orchestration/agent-runner.d.ts +72 -0
  373. package/dist/orchestration/agent-runner.js +289 -0
  374. package/dist/orchestration/busy-tracker.d.ts +12 -0
  375. package/dist/orchestration/busy-tracker.js +35 -0
  376. package/dist/orchestration/channel-queue.d.ts +18 -0
  377. package/dist/orchestration/channel-queue.js +32 -0
  378. package/dist/orchestration/dispatch-reconciler.d.ts +1 -0
  379. package/dist/orchestration/dispatch-reconciler.js +16 -0
  380. package/dist/orchestration/durable-helpers.d.ts +4 -0
  381. package/dist/orchestration/durable-helpers.js +42 -0
  382. package/dist/orchestration/interactions/ask-user-question.d.ts +32 -0
  383. package/dist/orchestration/interactions/ask-user-question.js +182 -0
  384. package/dist/orchestration/interactions/command-action-router.d.ts +47 -0
  385. package/dist/orchestration/interactions/command-action-router.js +91 -0
  386. package/dist/orchestration/interactions/interaction-handlers.d.ts +5 -0
  387. package/dist/orchestration/interactions/interaction-handlers.js +279 -0
  388. package/dist/orchestration/interactions/plan-approvals.d.ts +47 -0
  389. package/dist/orchestration/interactions/plan-approvals.js +77 -0
  390. package/dist/orchestration/interactions/plan-handler.d.ts +6 -0
  391. package/dist/orchestration/interactions/plan-handler.js +12 -0
  392. package/dist/orchestration/lifecycle.d.ts +50 -0
  393. package/dist/orchestration/lifecycle.js +308 -0
  394. package/dist/orchestration/orchestrator.d.ts +29 -0
  395. package/dist/orchestration/orchestrator.js +25 -0
  396. package/dist/orchestration/routing/commands/cancel.d.ts +10 -0
  397. package/dist/orchestration/routing/commands/cancel.js +136 -0
  398. package/dist/orchestration/routing/commands/channel.d.ts +11 -0
  399. package/dist/orchestration/routing/commands/channel.js +219 -0
  400. package/dist/orchestration/routing/commands/command-context.d.ts +29 -0
  401. package/dist/orchestration/routing/commands/command-context.js +4 -0
  402. package/dist/orchestration/routing/commands/cost.d.ts +3 -0
  403. package/dist/orchestration/routing/commands/cost.js +22 -0
  404. package/dist/orchestration/routing/commands/device.d.ts +6 -0
  405. package/dist/orchestration/routing/commands/device.js +83 -0
  406. package/dist/orchestration/routing/commands/dispatch.d.ts +2 -0
  407. package/dist/orchestration/routing/commands/dispatch.js +49 -0
  408. package/dist/orchestration/routing/commands/index.d.ts +15 -0
  409. package/dist/orchestration/routing/commands/index.js +130 -0
  410. package/dist/orchestration/routing/commands/mode.d.ts +13 -0
  411. package/dist/orchestration/routing/commands/mode.js +290 -0
  412. package/dist/orchestration/routing/commands/nvtop.d.ts +3 -0
  413. package/dist/orchestration/routing/commands/nvtop.js +103 -0
  414. package/dist/orchestration/routing/commands/orient.d.ts +2 -0
  415. package/dist/orchestration/routing/commands/orient.js +3 -0
  416. package/dist/orchestration/routing/commands/schedule.d.ts +4 -0
  417. package/dist/orchestration/routing/commands/schedule.js +132 -0
  418. package/dist/orchestration/routing/commands/sendfile.d.ts +2 -0
  419. package/dist/orchestration/routing/commands/sendfile.js +92 -0
  420. package/dist/orchestration/routing/commands/session.d.ts +9 -0
  421. package/dist/orchestration/routing/commands/session.js +153 -0
  422. package/dist/orchestration/routing/commands/status.d.ts +7 -0
  423. package/dist/orchestration/routing/commands/status.js +180 -0
  424. package/dist/orchestration/routing/commands/tail.d.ts +2 -0
  425. package/dist/orchestration/routing/commands/tail.js +73 -0
  426. package/dist/orchestration/routing/commands/task.d.ts +6 -0
  427. package/dist/orchestration/routing/commands/task.js +142 -0
  428. package/dist/orchestration/routing/commands/thread-handlers.d.ts +2 -0
  429. package/dist/orchestration/routing/commands/thread-handlers.js +138 -0
  430. package/dist/orchestration/routing/commands/thread.d.ts +2 -0
  431. package/dist/orchestration/routing/commands/thread.js +2 -0
  432. package/dist/orchestration/routing/edit-handler.d.ts +24 -0
  433. package/dist/orchestration/routing/edit-handler.js +161 -0
  434. package/dist/orchestration/routing/file-handler.d.ts +6 -0
  435. package/dist/orchestration/routing/file-handler.js +23 -0
  436. package/dist/orchestration/routing/hook-bridge-subscribers.d.ts +4 -0
  437. package/dist/orchestration/routing/hook-bridge-subscribers.js +79 -0
  438. package/dist/orchestration/routing/hook-bridge.d.ts +30 -0
  439. package/dist/orchestration/routing/hook-bridge.js +112 -0
  440. package/dist/orchestration/routing/message-router.d.ts +6 -0
  441. package/dist/orchestration/routing/message-router.js +70 -0
  442. package/dist/orchestration/routing/webhook.d.ts +10 -0
  443. package/dist/orchestration/routing/webhook.js +239 -0
  444. package/dist/orchestration/status-helpers.d.ts +66 -0
  445. package/dist/orchestration/status-helpers.js +222 -0
  446. package/dist/orchestration/superseded-edits.d.ts +22 -0
  447. package/dist/orchestration/superseded-edits.js +31 -0
  448. package/dist/orchestration/thread-executor.d.ts +31 -0
  449. package/dist/orchestration/thread-executor.js +234 -0
  450. package/dist/platform/adapter.d.ts +28 -0
  451. package/dist/platform/adapter.js +5 -0
  452. package/dist/platform/adapters/feishu.d.ts +66 -0
  453. package/dist/platform/adapters/feishu.js +558 -0
  454. package/dist/platform/adapters/index.d.ts +16 -0
  455. package/dist/platform/adapters/index.js +65 -0
  456. package/dist/platform/adapters/slack.d.ts +90 -0
  457. package/dist/platform/adapters/slack.js +630 -0
  458. package/dist/platform/index.d.ts +12 -0
  459. package/dist/platform/index.js +10 -0
  460. package/dist/platform/interactive-builder.d.ts +27 -0
  461. package/dist/platform/interactive-builder.js +120 -0
  462. package/dist/platform/testing.d.ts +100 -0
  463. package/dist/platform/testing.js +190 -0
  464. package/dist/platform/tool-trace.d.ts +33 -0
  465. package/dist/platform/tool-trace.js +165 -0
  466. package/dist/platform/types.d.ts +176 -0
  467. package/dist/platform/types.js +5 -0
  468. package/dist/platform/utils/rate-limiter.d.ts +92 -0
  469. package/dist/platform/utils/rate-limiter.js +213 -0
  470. package/dist/platform/virtual-message.d.ts +68 -0
  471. package/dist/platform/virtual-message.js +464 -0
  472. package/dist/store/atomic-write.d.ts +6 -0
  473. package/dist/store/atomic-write.js +18 -0
  474. package/dist/store/channel-repo.d.ts +21 -0
  475. package/dist/store/channel-repo.js +55 -0
  476. package/dist/store/conversation-ledger-repo.d.ts +86 -0
  477. package/dist/store/conversation-ledger-repo.js +220 -0
  478. package/dist/store/cost-repo.d.ts +57 -0
  479. package/dist/store/cost-repo.js +135 -0
  480. package/dist/store/execution-repo.d.ts +172 -0
  481. package/dist/store/execution-repo.js +343 -0
  482. package/dist/store/in-memory-repository.d.ts +14 -0
  483. package/dist/store/in-memory-repository.js +31 -0
  484. package/dist/store/json-repository.d.ts +51 -0
  485. package/dist/store/json-repository.js +118 -0
  486. package/dist/store/outbound-queue.d.ts +65 -0
  487. package/dist/store/outbound-queue.js +269 -0
  488. package/dist/store/profile-repo.d.ts +36 -0
  489. package/dist/store/profile-repo.js +144 -0
  490. package/dist/store/project-dir-repo.d.ts +22 -0
  491. package/dist/store/project-dir-repo.js +60 -0
  492. package/dist/store/schedule-repo.d.ts +92 -0
  493. package/dist/store/schedule-repo.js +88 -0
  494. package/dist/store/session-registry-repo.d.ts +38 -0
  495. package/dist/store/session-registry-repo.js +96 -0
  496. package/dist/store/session-repo.d.ts +14 -0
  497. package/dist/store/session-repo.js +56 -0
  498. package/dist/store/task-repo.d.ts +41 -0
  499. package/dist/store/task-repo.js +137 -0
  500. package/dist/store/thread-repo.d.ts +50 -0
  501. package/dist/store/thread-repo.js +190 -0
  502. package/package.json +58 -0
  503. package/scripts/postinstall-restart-trigger.mjs +39 -0
@@ -0,0 +1,95 @@
1
+ // input: raw prompt file content, template directory path
2
+ // output: prompt content with vars/blocks/conditionals expanded
3
+ // pos: pure parsing layer for prompts/ templates
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { readFileSync } from 'fs';
6
+ import * as path from 'path';
7
+ import { createLogger } from '../../core/log.js';
8
+ const log = createLogger('template-resolver');
9
+ function parseFrontmatter(content) {
10
+ const trimmed = content.trimStart();
11
+ if (!trimmed.startsWith('---'))
12
+ return { frontmatter: null, body: content };
13
+ const endIdx = trimmed.indexOf('\n---', 3);
14
+ if (endIdx === -1)
15
+ return { frontmatter: null, body: content };
16
+ const yamlBlock = trimmed.slice(3, endIdx).trim();
17
+ const body = trimmed.slice(endIdx + 4).replace(/^\n/, '');
18
+ const vars = {};
19
+ let extendsValue;
20
+ for (const line of yamlBlock.split('\n')) {
21
+ const match = line.match(/^(\w[\w-]*)\s*:\s*(.*)$/);
22
+ if (!match)
23
+ continue;
24
+ const [, key, rawValue] = match;
25
+ const value = rawValue.trim().replace(/^["'](.*)["']$/, '$1');
26
+ if (key === 'extends') {
27
+ extendsValue = value;
28
+ }
29
+ else {
30
+ vars[key] = value;
31
+ }
32
+ }
33
+ return {
34
+ frontmatter: { extends: extendsValue, vars },
35
+ body,
36
+ };
37
+ }
38
+ function parseFillBlocks(body) {
39
+ const fills = [];
40
+ const re = /^@fill\((\w[\w-]*)\)\s*\n([\s\S]*?)^@endfill\s*$/gm;
41
+ let match;
42
+ while ((match = re.exec(body)) !== null) {
43
+ fills.push({ name: match[1], content: match[2].replace(/\n$/, '') });
44
+ }
45
+ return fills;
46
+ }
47
+ function resolveBlocks(template, fills) {
48
+ const fillMap = new Map(fills.map(f => [f.name, f.content]));
49
+ return template.replace(/^@block\((\w[\w-]*)\)\s*\n([\s\S]*?)^@endblock\s*$/gm, (_match, name, defaultContent) => {
50
+ const fill = fillMap.get(name);
51
+ return fill !== undefined ? fill : defaultContent.replace(/\n$/, '');
52
+ });
53
+ }
54
+ function resolveVariables(text, vars) {
55
+ return text.replace(/\$\{(\w[\w-]*)(?::-([^}]*))?\}/g, (_match, name, defaultVal) => {
56
+ if (name in vars)
57
+ return vars[name];
58
+ if (defaultVal !== undefined)
59
+ return defaultVal;
60
+ return '';
61
+ });
62
+ }
63
+ function resolveConditionals(text, vars) {
64
+ // @if(!var)...@endif
65
+ text = text.replace(/^@if\(!(\w[\w-]*)\)\s*\n([\s\S]*?)^@endif\s*\n?/gm, (_match, name, content) => {
66
+ const hasValue = name in vars && vars[name] !== '';
67
+ return hasValue ? '' : content;
68
+ });
69
+ // @if(var)...@endif
70
+ text = text.replace(/^@if\((\w[\w-]*)\)\s*\n([\s\S]*?)^@endif\s*\n?/gm, (_match, name, content) => {
71
+ const hasValue = name in vars && vars[name] !== '';
72
+ return hasValue ? content : '';
73
+ });
74
+ return text;
75
+ }
76
+ export function resolveTemplate(content, templateDir) {
77
+ const { frontmatter, body } = parseFrontmatter(content);
78
+ if (!frontmatter || !frontmatter.extends) {
79
+ return frontmatter ? body : content;
80
+ }
81
+ const templatePath = path.join(templateDir, frontmatter.extends);
82
+ let template;
83
+ try {
84
+ template = readFileSync(templatePath, 'utf8');
85
+ }
86
+ catch (e) {
87
+ log.error(`Failed to read template "${frontmatter.extends}": ${e.message}`);
88
+ return body;
89
+ }
90
+ const fills = parseFillBlocks(body);
91
+ let result = resolveBlocks(template, fills);
92
+ result = resolveConditionals(result, frontmatter.vars);
93
+ result = resolveVariables(result, frontmatter.vars);
94
+ return result;
95
+ }
@@ -0,0 +1,19 @@
1
+ import type { AgentDefinition, AgentSlotConfig, AgentSlotId } from '../../core/types/thread-types.js';
2
+ /** Check if a thread is using the default single-agent template */
3
+ export declare function isDefaultThread(threadId: string): boolean;
4
+ /** Check if a thread is ad-hoc (no template) */
5
+ export declare function isAdHocThread(threadId: string): boolean;
6
+ /** Get the session key for a specific agent slot in a thread */
7
+ export declare function getSessionKey(threadId: string, slotId: AgentSlotId): string;
8
+ /** Parse a transition endpoint string — either `"agent"` or `"agent:stage"` — into its components.
9
+ * When the stage suffix is absent, resolve to the agent's `entryStage` (or the first declared
10
+ * stage, or null for agents with no `stages` map). The agent itself need not be loaded to parse;
11
+ * `getStageEntry` on the returned shape handles unknown agents gracefully. */
12
+ export declare function parseTarget(endpoint: string): {
13
+ agent: string;
14
+ stage: string | null;
15
+ };
16
+ /** Resolve the stage name that should actually run for an agent given an explicit stage or null.
17
+ * Returns null for single-stage agents (no `stages` map). Falls back to entryStage, then to
18
+ * the first declared stage name. */
19
+ export declare function resolveStageName(agentDef: AgentDefinition | AgentSlotConfig | null, explicit: string | null): string | null;
@@ -0,0 +1,49 @@
1
+ // Pure thread utility helpers — no I/O, no config.
2
+ // input: thread-store, thread-types
3
+ // output: isDefaultThread / isAdHocThread / getSessionKey / parseTarget / resolveStageName
4
+ import { threadStore } from '../../store/thread-repo.js';
5
+ /** Check if a thread is using the default single-agent template */
6
+ export function isDefaultThread(threadId) {
7
+ const thread = threadStore.get(threadId);
8
+ if (!thread)
9
+ return false;
10
+ return thread.templateName === 'default';
11
+ }
12
+ /** Check if a thread is ad-hoc (no template) */
13
+ export function isAdHocThread(threadId) {
14
+ const thread = threadStore.get(threadId);
15
+ if (!thread)
16
+ return false;
17
+ return thread.templateName === null;
18
+ }
19
+ /** Get the session key for a specific agent slot in a thread */
20
+ export function getSessionKey(threadId, slotId) {
21
+ return `thr:${threadId}:${slotId}`;
22
+ }
23
+ /** Parse a transition endpoint string — either `"agent"` or `"agent:stage"` — into its components.
24
+ * When the stage suffix is absent, resolve to the agent's `entryStage` (or the first declared
25
+ * stage, or null for agents with no `stages` map). The agent itself need not be loaded to parse;
26
+ * `getStageEntry` on the returned shape handles unknown agents gracefully. */
27
+ export function parseTarget(endpoint) {
28
+ const colon = endpoint.indexOf(':');
29
+ if (colon < 0)
30
+ return { agent: endpoint, stage: null };
31
+ const agent = endpoint.slice(0, colon);
32
+ const stage = endpoint.slice(colon + 1);
33
+ return { agent, stage: stage.length > 0 ? stage : null };
34
+ }
35
+ /** Resolve the stage name that should actually run for an agent given an explicit stage or null.
36
+ * Returns null for single-stage agents (no `stages` map). Falls back to entryStage, then to
37
+ * the first declared stage name. */
38
+ export function resolveStageName(agentDef, explicit) {
39
+ if (!agentDef || !agentDef.stages)
40
+ return null;
41
+ const stageNames = Object.keys(agentDef.stages);
42
+ if (stageNames.length === 0)
43
+ return null;
44
+ if (explicit && agentDef.stages[explicit])
45
+ return explicit;
46
+ if (agentDef.entryStage && agentDef.stages[agentDef.entryStage])
47
+ return agentDef.entryStage;
48
+ return stageNames[0];
49
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,234 @@
1
+ // input: .env, PlatformAdapter, all extracted modules
2
+ // output: Cortex agent server main entry — composition root only
3
+ // pos: agent-server main entry and wiring hub (S13: composition root, business branches in orchestration/)
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import * as dotenv from 'dotenv';
6
+ import { mkdirSync } from 'fs';
7
+ import * as path from 'path';
8
+ import { createAdapterFromEnv } from '../platform/index.js';
9
+ import { WORKSPACE_DIR, CONFIG_DIR } from '../core/utils.js';
10
+ import { closeAllSessions, closeSession as closeClaudePooledSession, shutdownCodex } from '../domain/agents/index.js';
11
+ import { closeAllAdapters } from '../agent-adapter/index.js';
12
+ import { recoverTuiOrphans } from '../agent-adapter/claude/adapter.js';
13
+ import { startWebhookServer } from '../orchestration/routing/webhook.js';
14
+ import * as pendingTaskTracker from '../domain/tasks/pending-tracker.js';
15
+ import * as executionRegistry from '../domain/executions/registry.js';
16
+ import { initHookBridge } from '../orchestration/routing/hook-bridge.js';
17
+ import { registerCommands } from '../orchestration/routing/commands/index.js';
18
+ import { taskStore } from '../domain/tasks/store.js';
19
+ import { channelRepo } from '../store/channel-repo.js';
20
+ import { projectDirRepo } from '../store/project-dir-repo.js';
21
+ import { sendStartupDmIfConfigured } from './startup-notify.js';
22
+ import { startGateway, stopGateway } from '../domain/costs/gateway-manager.js';
23
+ import { startClientManager, stopClientManager, startAllRemoteClients } from '../domain/remote/client-manager.js';
24
+ import { checkAndUpdateClients, formatUpdateSlackMessage } from '../domain/remote/client-hot-reload.js';
25
+ import { threadStore } from '../store/thread-repo.js';
26
+ import { sessionRepo } from '../store/session-repo.js';
27
+ import { conversationLedger } from '../store/conversation-ledger-repo.js';
28
+ import { executionRepo } from '../store/execution-repo.js';
29
+ import { loadConfig as loadThreadConfig, startConfigWatcher as startThreadConfigWatcher, setAdminNotifier as setConfigNotifier } from '../domain/threads/index.js';
30
+ import { startMemoryWatcher } from '../domain/memory/watcher.js';
31
+ import { getActiveBackend } from '../domain/agents/index.js';
32
+ import { createEditHandler } from '../orchestration/routing/edit-handler.js';
33
+ // Extracted modules
34
+ import { cleanupLogs, ensureMcpConfig } from './startup-helpers.js';
35
+ import { createLogger } from '../core/log.js';
36
+ import { runningExecutions } from '../core/running-executions.js';
37
+ import { planApprovals } from '../orchestration/interactions/plan-approvals.js';
38
+ import { busyTracker } from '../orchestration/busy-tracker.js';
39
+ import { buildExecutionStatusReport } from '../orchestration/status-helpers.js';
40
+ import { reprocessMessage } from '../orchestration/lifecycle.js';
41
+ import { initScheduledRunner, createScheduler, setSchedulerRef, setBus, setInteractiveCallbacksFactory, cancelDispatchedTask } from '../domain/scheduling/runner.js';
42
+ import { buildInteractiveCallbacks } from '../orchestration/agent-runner.js';
43
+ import { registerInteractionHandlers, initInteractionHandlers } from '../orchestration/interactions/interaction-handlers.js';
44
+ import { CommandActionRouter } from '../orchestration/interactions/command-action-router.js';
45
+ import { registerMessageHandler } from '../orchestration/routing/message-router.js';
46
+ import { initRateLimitThrottle } from '../domain/costs/rate-limit-throttle.js';
47
+ import { scheduleRepo } from '../store/schedule-repo.js';
48
+ import { costRepo } from '../store/cost-repo.js';
49
+ import { profileRepo, startProfileWatcher, setAdminNotifier as setProfileNotifier } from '../store/profile-repo.js';
50
+ import { sessionRegistryRepo } from '../store/session-registry-repo.js';
51
+ import { initDiskMonitor, stopDiskMonitor } from '../domain/monitor/disk-monitor.js';
52
+ import { loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, setAdminNotifier as setMachineNotifier } from '../domain/tasks/dispatch-utils.js';
53
+ import { EventBus, createEventLogger } from '../events/index.js';
54
+ import { registerHookBridgeSubscribers } from '../orchestration/routing/hook-bridge-subscribers.js';
55
+ import { startDispatchReconciler } from '../orchestration/dispatch-reconciler.js';
56
+ import { ensurePIAgentDirs } from '../agent-adapter/pi/agent-dir.js';
57
+ import { initOutboundQueue } from '../store/outbound-queue.js';
58
+ dotenv.config({ path: path.join(CONFIG_DIR, '.env') });
59
+ const log = createLogger('app');
60
+ // --- EventBus + logger ---
61
+ const bus = new EventBus();
62
+ createEventLogger(bus);
63
+ initHookBridge(bus); // S5: wire hook-bridge to publish ask-user.requested / plan.submitted
64
+ runningExecutions.setBus(bus); // S6-A: wire lifecycle events
65
+ planApprovals.setBus(bus); // S6-A: wire plan.approved events
66
+ busyTracker.setBus(bus); // S6-C: wire busy/idle IPC through event bus
67
+ initInteractionHandlers(bus); // BLK-1: wire ask-user.answered publisher
68
+ const TEMP_DIR = WORKSPACE_DIR;
69
+ mkdirSync(TEMP_DIR, { recursive: true });
70
+ mkdirSync(path.join(TEMP_DIR, 'threads'), { recursive: true });
71
+ ensurePIAgentDirs();
72
+ // --- Load machine registry (must happen before any module that uses getMachineRegistry()) ---
73
+ loadMachinesFromFile();
74
+ startMachineRegistryWatcher();
75
+ // --- Create platform adapter (replaces direct Slack App instantiation) ---
76
+ const adapter = createAdapterFromEnv();
77
+ // --- Wire hot-reload admin notifiers ---
78
+ const notifyAdmin = (text) => {
79
+ const ch = adapter.getAdminChannel();
80
+ if (ch)
81
+ adapter.postMessage(ch, { text }).catch(() => { });
82
+ };
83
+ setProfileNotifier(notifyAdmin);
84
+ setConfigNotifier(notifyAdmin);
85
+ setMachineNotifier(notifyAdmin);
86
+ // --- Init outbound message queue (WAL-based, survives restarts) ---
87
+ const oq = initOutboundQueue(adapter);
88
+ // --- Init extracted modules ---
89
+ initScheduledRunner(adapter);
90
+ setBus(bus);
91
+ setInteractiveCallbacksFactory(buildInteractiveCallbacks);
92
+ const scheduler = createScheduler();
93
+ scheduler.setAdminNotifier(notifyAdmin);
94
+ setSchedulerRef(scheduler);
95
+ initRateLimitThrottle(adapter, {
96
+ save: (state) => scheduleRepo.setRateLimitThrottle(state),
97
+ load: () => scheduleRepo.getRateLimitThrottle(),
98
+ }).catch(e => log.error(`initRateLimitThrottle failed: ${e.message}`));
99
+ initDiskMonitor(adapter);
100
+ const commandRouter = new CommandActionRouter();
101
+ const dispatchCommand = registerCommands({
102
+ scheduler,
103
+ cancelDispatchedTask,
104
+ getExecutionStatusReport: buildExecutionStatusReport,
105
+ commandRouter,
106
+ });
107
+ // Bind command action handlers (buttons, modals) to the platform adapter
108
+ commandRouter.bindToAdapter(adapter);
109
+ const handleMessageEdit = createEditHandler({
110
+ activeAgents: runningExecutions,
111
+ reprocessMessage,
112
+ // Claude CLI runs in stream-json mode and pools the subprocess per channel; an alive
113
+ // pooled process keeps the conversation history in memory and ignores the rolled-back
114
+ // JSONL on disk. Close it here so the next runAgent spawns a fresh process with
115
+ // `--resume <sessionId>`. PI/codex spawn fresh subprocesses per turn, so the close is
116
+ // a no-op for them (we still call through for symmetry — adapter exits early when
117
+ // there's nothing to close).
118
+ closePooledSession: (channel, backend) => {
119
+ if (backend === 'claude')
120
+ closeClaudePooledSession(channel);
121
+ },
122
+ });
123
+ // --- Register interaction handlers ---
124
+ registerInteractionHandlers(adapter);
125
+ // --- Register message handler ---
126
+ registerMessageHandler(adapter, { dispatchCommand, handleMessageEdit });
127
+ // --- Profile watcher (hot-reload profiles.json without restart) ---
128
+ let _stopProfileWatcher = null;
129
+ // --- Graceful shutdown ---
130
+ process.on('SIGTERM', async () => {
131
+ closeAllSessions();
132
+ shutdownCodex();
133
+ closeAllAdapters().catch(() => { });
134
+ stopClientManager();
135
+ stopMachineRegistryWatcher();
136
+ _stopProfileWatcher?.();
137
+ stopDiskMonitor();
138
+ // Stop scheduler timers BEFORE draining repo writes — otherwise a late-firing
139
+ // timer can enqueue a mutate() after scheduleRepo.flush() resolves, losing that write.
140
+ scheduler.stop();
141
+ // Stop outbound queue drain loop (pending WAL entries survive on disk for next startup).
142
+ await oq.stop();
143
+ // Drain in-flight atomic writes before exiting. Without this, SIGTERM landing between
144
+ // `writeFile(tmp)` and `rename(tmp, target)` in atomic-write.ts leaves orphan .tmp.* siblings.
145
+ // Daemon gives 5s before SIGKILL — well over the time needed to flush a few MB of JSON.
146
+ try {
147
+ await Promise.allSettled([bus.close(), oq.flush(), threadStore.flush(), sessionRepo.flush(), conversationLedger.flush(), taskStore.flush(), executionRepo.flush(), channelRepo.flush(), projectDirRepo.flush(), scheduleRepo.flush(), costRepo.flush(), profileRepo.flush(), sessionRegistryRepo.flush()]);
148
+ }
149
+ catch { }
150
+ await stopGateway();
151
+ process.exit(0);
152
+ });
153
+ // --- Start ---
154
+ (async () => {
155
+ cleanupLogs();
156
+ ensureMcpConfig();
157
+ // DR-0012 §3.6: clean up orphan TUI tmux sessions from a previous agent-server lifetime.
158
+ // We can't re-adopt them (sessionKey↔tmux mapping was never persisted) so the honest move
159
+ // is to kill any leftovers — otherwise a later session that reuses the same sessionId will
160
+ // collide with `tmux new-session -s <name>` (which fails on duplicates).
161
+ try {
162
+ const { found, killed } = recoverTuiOrphans();
163
+ if (found.length > 0) {
164
+ log.info(`Startup: swept ${killed.length}/${found.length} orphan TUI tmux session(s)`);
165
+ }
166
+ }
167
+ catch (e) {
168
+ log.warn(`Startup: recoverTuiOrphans failed: ${e.message}`);
169
+ }
170
+ executionRepo.load();
171
+ await executionRegistry.markMissingRunningExecutionsStale((record) => record.kind === 'dispatch');
172
+ await adapter.start();
173
+ try {
174
+ const notified = await sendStartupDmIfConfigured(adapter, {
175
+ machine: process.env.CORTEX_MACHINE,
176
+ restartReason: process.env.CORTEX_RESTART_REASON,
177
+ });
178
+ if (!notified)
179
+ log.info('Startup DM skipped: no admin channel configured.');
180
+ }
181
+ catch (error) {
182
+ log.warn(`Failed to send startup DM: ${error.message}`);
183
+ }
184
+ // Recover unsent messages from WAL and start drain loop
185
+ const recoveredCount = await oq.recover();
186
+ if (recoveredCount > 0) {
187
+ log.info(`OutboundQueue: recovered ${recoveredCount} pending messages from WAL`);
188
+ oq.drain().catch(e => log.error(`OutboundQueue drain failed: ${e.message}`));
189
+ }
190
+ oq.startDrainLoop();
191
+ pendingTaskTracker.init(adapter);
192
+ taskStore.load();
193
+ loadThreadConfig();
194
+ startThreadConfigWatcher();
195
+ _stopProfileWatcher = startProfileWatcher();
196
+ threadStore.load();
197
+ await threadStore.markRunningAsFailedOnStartup();
198
+ await threadStore.cleanup();
199
+ startGateway();
200
+ startClientManager(parseInt(process.env.CORTEX_CLIENT_PORT || '3002', 10));
201
+ setTimeout(async () => {
202
+ try {
203
+ const updateResult = await checkAndUpdateClients();
204
+ if (updateResult) {
205
+ log.info(`Client hot-reload: ${updateResult.devices.length} devices updated in ${updateResult.duration}ms`);
206
+ const adminChannel = adapter.getAdminChannel();
207
+ if (adminChannel) {
208
+ await adapter.postMessage(adminChannel, { text: formatUpdateSlackMessage(updateResult) }).catch((e) => log.warn(`Hot-reload DM failed: ${e.message}`));
209
+ }
210
+ }
211
+ }
212
+ catch (e) {
213
+ log.error(`Client hot-reload check failed: ${e.message}`);
214
+ }
215
+ await startAllRemoteClients();
216
+ }, 2000);
217
+ await scheduler.start();
218
+ // One-time migration: resume tasks left paused by the old scheduler-based rate-limit mechanism.
219
+ // The new provider-aware rate-limit-throttle no longer pauses tasks via the scheduler guard.
220
+ // Any tasks paused with pausedBy='rate-limit' by the old mechanism will never be resumed
221
+ // unless we do it here on startup. Idempotent — on subsequent restarts no such tasks remain.
222
+ for (const t of await scheduler.list()) {
223
+ if (t.isPaused && t.pausedBy === 'rate-limit') {
224
+ log.info(`Migration: resuming task ${t.id} ("${t.message}") paused by old rate-limit mechanism`);
225
+ await scheduler.resume(t.id);
226
+ }
227
+ }
228
+ startWebhookServer();
229
+ // S13: register hook-bridge event subscribers (bodies extracted to orch/routing/hook-bridge-subscribers.ts)
230
+ registerHookBridgeSubscribers(bus, adapter, planApprovals);
231
+ startMemoryWatcher();
232
+ startDispatchReconciler();
233
+ log.info(`Cortex agent is running (${adapter.name}) — backend: ${getActiveBackend()}`);
234
+ })();
@@ -0,0 +1,12 @@
1
+ export declare function getInitHelp(): string;
2
+ export declare function getSetupGatewayHelp(): string;
3
+ export declare function getCliHelp(): string;
4
+ export declare function getConfigOutput(): string;
5
+ export interface CliResult {
6
+ exitCode: number;
7
+ stdout: string;
8
+ stderr: string;
9
+ }
10
+ export declare function runCli(argv: string[]): Promise<CliResult>;
11
+ declare function main(): void;
12
+ export { main };
@@ -0,0 +1,254 @@
1
+ #!/usr/bin/env node
2
+ // input: process argv, child_process, @core/paths, @core/cli-utils, ./init, @domain/tasks/system/task-cli
3
+ // output: CLI dispatcher: cortex {init,start,daemon,task,config}
4
+ // pos: Bin entry point (`cortex`). Dispatches to:
5
+ // init [--home <path>] — interactive init (async, runInit)
6
+ // start — fork app.js
7
+ // daemon — fork daemon.js
8
+ // task <subcommand> — delegate to task-cli
9
+ // config — show resolved paths
10
+ // Packaged as dist/entry/cli.js, registered in package.json bin.
11
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
12
+ import { fork } from 'child_process';
13
+ import * as path from 'path';
14
+ import { fileURLToPath } from 'url';
15
+ import { existsSync, readdirSync, mkdirSync, writeFileSync, utimesSync } from 'fs';
16
+ import { INSTALL_ROOT, DATA_DIR, STORE_DIR, isMainModule } from '../core/utils.js';
17
+ import { formatHelp } from '../core/cli-utils.js';
18
+ import { createLogger } from '../core/log.js';
19
+ import { runCli as taskRunCli } from '../domain/tasks/system/task-cli.js';
20
+ import { getResolvedPaths, formatConfigOutput, runInit, } from './init.js';
21
+ import { discoverEndpoints, generateGatewayYaml, writeGatewayYaml, dryRunGatewayYaml } from '../core/gateway-generator.js';
22
+ import { generateProfiles, writeProfilesJson } from '../core/profile-generator.js';
23
+ // ─── Paths ──────────────────────────────────────────────────────
24
+ const log = createLogger('cli');
25
+ const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
26
+ const APP_JS = path.join(MODULE_DIR, 'app.js');
27
+ const DAEMON_JS = path.join(MODULE_DIR, 'daemon.js');
28
+ // ─── Help ───────────────────────────────────────────────────────
29
+ export function getInitHelp() {
30
+ return [
31
+ 'Initialize Cortex data directory',
32
+ '',
33
+ 'Usage: cortex init [--home <path>] [--gateway-config-dir <path>]',
34
+ '',
35
+ 'Creates the CORTEX_HOME directory structure, prompts for backends,',
36
+ 'interaction platform (Slack / Feishu), gateway usage, and system service.',
37
+ 'Generates .env with platform tokens, copies default configs, and',
38
+ 'auto-generates mcp-config.json and mode.json.',
39
+ '',
40
+ 'Options:',
41
+ ' --home <path> Set CORTEX_HOME (default: $CORTEX_HOME or ~/.cortex/)',
42
+ ' --gateway-config-dir <path> Gateway config output directory (default: ~/.aistatus/)',
43
+ ' --force Overwrite existing configs (.env, budget.json, mode.json, etc.)',
44
+ ' --help, -h Show this help',
45
+ ].join('\n');
46
+ }
47
+ export function getSetupGatewayHelp() {
48
+ return [
49
+ 'Auto-detect Claude Code / PI configurations and generate gateway.yaml + profiles.json',
50
+ '',
51
+ 'Usage: cortex setup-gateway [--dry-run] [--output-dir <path>]',
52
+ '',
53
+ 'Discovers backend endpoints from local Claude Code and PI configs, then',
54
+ 'writes ~/.aistatus/gateway.yaml (with backup) and $CORTEX_HOME/config/profiles.json.',
55
+ 'Without flags, this command writes files in place.',
56
+ '',
57
+ 'Options:',
58
+ ' --dry-run Print the generated gateway.yaml to stdout without writing anything',
59
+ ' --output-dir <path> Write gateway.yaml and profiles.json under <path> instead of the defaults',
60
+ ' --help, -h Show this help',
61
+ ].join('\n');
62
+ }
63
+ export function getCliHelp() {
64
+ return formatHelp({
65
+ name: 'cortex',
66
+ description: 'Cortex CLI — server management and initialization',
67
+ usage: 'cortex <command> [options]',
68
+ commands: [
69
+ { name: 'init', description: 'Initialize CORTEX_HOME directory with configs and API keys' },
70
+ { name: 'start', description: 'Start the Cortex server (node dist/entry/app.js)' },
71
+ { name: 'daemon', description: 'Daemon mode with file watching and auto-restart' },
72
+ { name: 'restart', description: 'Signal a running daemon to drain and respawn app.js (touches $STORE_DIR/.restart)' },
73
+ { name: 'task', description: 'Task system CLI (delegate to cortex-task)' },
74
+ { name: 'config', description: 'Show resolved paths and initialization status' },
75
+ { name: 'setup-gateway', description: 'Auto-detect Claude/PI configs and generate gateway.yaml + profiles.json' },
76
+ ],
77
+ options: [
78
+ { flag: '--help, -h', description: 'Show this help' },
79
+ ],
80
+ examples: [
81
+ { description: 'Interactive init', command: 'cortex init' },
82
+ { description: 'Init to custom directory', command: 'cortex init --home /tmp/my-cortex' },
83
+ { description: 'Show resolved paths', command: 'cortex config' },
84
+ { description: 'Re-generate gateway config', command: 'cortex setup-gateway' },
85
+ { description: 'Start the server', command: 'cortex start' },
86
+ ],
87
+ });
88
+ }
89
+ // ─── Config output ──────────────────────────────────────────────
90
+ export function getConfigOutput() {
91
+ const paths = {
92
+ INSTALL_ROOT,
93
+ ...getResolvedPaths(),
94
+ };
95
+ const dotEnvPath = path.join(paths.CONFIG_DIR, '.env');
96
+ const mcpConfigPath = path.join(paths.CONFIG_DIR, 'mcp-config.json');
97
+ const modeJsonPath = path.join(paths.STORE_DIR, 'mode.json');
98
+ let storeFileCount = 0;
99
+ try {
100
+ storeFileCount = readdirSync(paths.STORE_DIR).length;
101
+ }
102
+ catch { }
103
+ const status = {
104
+ dataDirExists: existsSync(paths.DATA_DIR) && storeFileCount > 0,
105
+ dotEnvExists: existsSync(dotEnvPath),
106
+ mcpConfigExists: existsSync(mcpConfigPath),
107
+ modeJsonExists: existsSync(modeJsonPath),
108
+ };
109
+ return formatConfigOutput(paths, status);
110
+ }
111
+ // ─── runCli (synchronous/async commands) ────────────────────────
112
+ export async function runCli(argv) {
113
+ if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h') {
114
+ return { exitCode: 0, stdout: getCliHelp(), stderr: '' };
115
+ }
116
+ const cmd = argv[0];
117
+ const rest = argv.slice(1);
118
+ switch (cmd) {
119
+ case 'init': {
120
+ if (rest.includes('--help') || rest.includes('-h')) {
121
+ return { exitCode: 0, stdout: getInitHelp(), stderr: '' };
122
+ }
123
+ const homeIndex = rest.indexOf('--home');
124
+ const homeDir = homeIndex !== -1 && rest[homeIndex + 1] ? rest[homeIndex + 1] : undefined;
125
+ const gatewayIndex = rest.indexOf('--gateway-config-dir');
126
+ const gatewayConfigDir = gatewayIndex !== -1 && rest[gatewayIndex + 1] ? rest[gatewayIndex + 1] : undefined;
127
+ const force = rest.includes('--force');
128
+ try {
129
+ await runInit({ homeDir, force, gatewayConfigDir });
130
+ return { exitCode: 0, stdout: '', stderr: '' };
131
+ }
132
+ catch (err) {
133
+ return { exitCode: 1, stdout: '', stderr: err.message || String(err) };
134
+ }
135
+ }
136
+ case 'config':
137
+ return { exitCode: 0, stdout: getConfigOutput(), stderr: '' };
138
+ case 'restart': {
139
+ const trigger = path.join(STORE_DIR, '.restart');
140
+ try {
141
+ mkdirSync(STORE_DIR, { recursive: true });
142
+ if (existsSync(trigger)) {
143
+ const now = new Date();
144
+ utimesSync(trigger, now, now);
145
+ }
146
+ else {
147
+ writeFileSync(trigger, '');
148
+ }
149
+ return { exitCode: 0, stdout: `Restart trigger touched: ${trigger}\nIf a daemon is running it will drain and respawn app.js.\n`, stderr: '' };
150
+ }
151
+ catch (err) {
152
+ return { exitCode: 1, stdout: '', stderr: `Could not write ${trigger}: ${err.message || String(err)}` };
153
+ }
154
+ }
155
+ case 'setup-gateway': {
156
+ if (rest.includes('--help') || rest.includes('-h')) {
157
+ return { exitCode: 0, stdout: getSetupGatewayHelp(), stderr: '' };
158
+ }
159
+ const dryRun = rest.includes('--dry-run');
160
+ const outDirIndex = rest.indexOf('--output-dir');
161
+ const outputDir = outDirIndex !== -1 && rest[outDirIndex + 1] ? rest[outDirIndex + 1] : undefined;
162
+ try {
163
+ if (dryRun) {
164
+ const yaml = dryRunGatewayYaml();
165
+ return { exitCode: 0, stdout: yaml, stderr: '' };
166
+ }
167
+ const endpoints = discoverEndpoints();
168
+ if (endpoints.length === 0) {
169
+ return { exitCode: 0, stdout: 'No backends discovered. Log into Claude Code and/or PI first.\n', stderr: '' };
170
+ }
171
+ const yaml = generateGatewayYaml(endpoints);
172
+ const gatewayPath = writeGatewayYaml(yaml, outputDir);
173
+ const profilesPath = writeProfilesJson(endpoints, outputDir);
174
+ const profiles = generateProfiles(endpoints);
175
+ const profileNames = Object.keys(profiles.profiles).join(', ');
176
+ return {
177
+ exitCode: 0,
178
+ stdout: [
179
+ outputDir ? `[TEST MODE] Output directory: ${outputDir}` : '',
180
+ `Gateway config: ${gatewayPath}`,
181
+ `Profiles: ${profilesPath}`,
182
+ `Discovered ${endpoints.length} endpoint modes`,
183
+ `Generated profiles: ${profileNames} (default: ${profiles.defaultProfile})`,
184
+ ].filter(Boolean).join('\n'),
185
+ stderr: '',
186
+ };
187
+ }
188
+ catch (err) {
189
+ return { exitCode: 1, stdout: '', stderr: err.message || String(err) };
190
+ }
191
+ }
192
+ case 'task': {
193
+ const result = taskRunCli(rest.length > 0 ? rest : ['list']);
194
+ return result;
195
+ }
196
+ case 'start':
197
+ case 'daemon':
198
+ return { exitCode: 0, stdout: '', stderr: `'${cmd}' must be run from the main entry point, not imported.\nUse: node dist/entry/cli.js ${cmd}` };
199
+ default:
200
+ return { exitCode: 1, stdout: '', stderr: `Unknown command: '${cmd}'. Use --help to see available commands.` };
201
+ }
202
+ }
203
+ // ─── Main entry point (bin invocation) ─────────────────────────
204
+ function main() {
205
+ const args = process.argv.slice(2);
206
+ if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
207
+ console.log(getCliHelp());
208
+ process.exit(0);
209
+ }
210
+ const cmd = args[0];
211
+ const rest = args.slice(1);
212
+ // ── Subcommands that replace the process (fork + wait) ──
213
+ if (cmd === 'start') {
214
+ if (!existsSync(APP_JS)) {
215
+ log.error(`Entry not found: ${APP_JS}`);
216
+ log.error('Run `npm run build` first.');
217
+ process.exit(1);
218
+ }
219
+ const child = fork(APP_JS, [], {
220
+ cwd: DATA_DIR,
221
+ stdio: 'inherit',
222
+ env: { ...process.env },
223
+ });
224
+ child.on('exit', (code) => process.exit(code ?? 0));
225
+ return; // let the event loop keep the process alive
226
+ }
227
+ if (cmd === 'daemon') {
228
+ if (!existsSync(DAEMON_JS)) {
229
+ log.error(`Entry not found: ${DAEMON_JS}`);
230
+ log.error('Run `npm run build` first.');
231
+ process.exit(1);
232
+ }
233
+ const child = fork(DAEMON_JS, [], {
234
+ cwd: DATA_DIR,
235
+ stdio: 'inherit',
236
+ env: { ...process.env },
237
+ });
238
+ child.on('exit', (code) => process.exit(code ?? 0));
239
+ return; // let the event loop keep the process alive
240
+ }
241
+ // ── Subcommands that return results ──
242
+ runCli(args).then((result) => {
243
+ if (result.stdout)
244
+ console.log(result.stdout);
245
+ if (result.stderr)
246
+ console.error(result.stderr);
247
+ process.exit(result.exitCode);
248
+ });
249
+ }
250
+ // ─── Export for testing & reuse ─────────────────────────────────
251
+ export { main };
252
+ if (isMainModule(import.meta.url)) {
253
+ main();
254
+ }