@cortex-agent/server 2026.5.25 → 2026.6.15

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 (395) hide show
  1. package/defaults/config/thread-templates.json +28 -1
  2. package/defaults/hooks/cortex-md-injector.mjs +47 -31
  3. package/defaults/hooks/post-task-hook.mjs +6 -0
  4. package/defaults/hooks/task-status-check.mjs +8 -0
  5. package/defaults/mcp-config-slack.json +11 -0
  6. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +18 -0
  7. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +5 -6
  8. package/defaults/prompts/directives/manager.md +67 -0
  9. package/dist/agent-adapter/claude/adapter-tui.d.ts +35 -3
  10. package/dist/agent-adapter/claude/adapter-tui.js +91 -12
  11. package/dist/agent-adapter/claude/adapter.js +11 -0
  12. package/dist/agent-adapter/claude/defaults.d.ts +30 -0
  13. package/dist/agent-adapter/claude/defaults.js +30 -0
  14. package/dist/agent-adapter/claude/jsonl-tail.d.ts +2 -2
  15. package/dist/agent-adapter/claude/jsonl-tail.js +25 -20
  16. package/dist/agent-adapter/claude/spawn-args.d.ts +11 -0
  17. package/dist/agent-adapter/claude/spawn-args.js +49 -7
  18. package/dist/agent-adapter/claude/tmux-control.d.ts +20 -0
  19. package/dist/agent-adapter/claude/tmux-control.js +54 -8
  20. package/dist/agent-adapter/codex/adapter.js +1 -1
  21. package/dist/agent-adapter/normalize/event-types.d.ts +1 -0
  22. package/dist/agent-adapter/pi/adapter.js +46 -19
  23. package/dist/agent-adapter/pi/agent-dir.d.ts +21 -0
  24. package/dist/agent-adapter/pi/agent-dir.js +53 -2
  25. package/dist/agent-adapter/pi/event-parser.js +13 -1
  26. package/dist/agent-adapter/pi/mcp-bridge.d.ts +12 -0
  27. package/dist/agent-adapter/pi/mcp-bridge.js +47 -9
  28. package/dist/agent-adapter/pi/tool-shims.d.ts +14 -0
  29. package/dist/agent-adapter/pi/tool-shims.js +167 -140
  30. package/dist/agent-adapter/types.d.ts +7 -2
  31. package/dist/core/atomic-write.js +21 -0
  32. package/dist/core/config-generator.d.ts +10 -0
  33. package/dist/core/config-generator.js +28 -0
  34. package/dist/core/gateway-generator.d.ts +77 -7
  35. package/dist/core/gateway-generator.js +323 -30
  36. package/dist/core/i18n.d.ts +19 -0
  37. package/dist/core/i18n.js +46 -0
  38. package/dist/core/icons.d.ts +68 -0
  39. package/dist/core/icons.js +67 -0
  40. package/dist/core/locales/en.d.ts +438 -0
  41. package/dist/core/locales/en.js +24 -0
  42. package/dist/core/locales/slices/commands.d.ts +214 -0
  43. package/dist/core/locales/slices/commands.js +462 -0
  44. package/dist/core/locales/slices/init.d.ts +121 -0
  45. package/dist/core/locales/slices/init.js +380 -0
  46. package/dist/core/locales/slices/interactions.d.ts +47 -0
  47. package/dist/core/locales/slices/interactions.js +102 -0
  48. package/dist/core/locales/slices/lang.d.ts +8 -0
  49. package/dist/core/locales/slices/lang.js +18 -0
  50. package/dist/core/locales/slices/scheduling.d.ts +36 -0
  51. package/dist/core/locales/slices/scheduling.js +74 -0
  52. package/dist/core/locales/slices/startup.d.ts +6 -0
  53. package/dist/core/locales/slices/startup.js +14 -0
  54. package/dist/core/locales/slices/status.d.ts +20 -0
  55. package/dist/core/locales/slices/status.js +48 -0
  56. package/dist/core/locales/zh.d.ts +5 -0
  57. package/dist/core/locales/zh.js +23 -0
  58. package/dist/core/profile-generator.d.ts +6 -0
  59. package/dist/core/profile-generator.js +35 -7
  60. package/dist/core/running-executions.d.ts +51 -41
  61. package/dist/core/running-executions.js +120 -73
  62. package/dist/core/singleton-lock.d.ts +23 -0
  63. package/dist/core/singleton-lock.js +53 -0
  64. package/dist/core/status-format.js +4 -2
  65. package/dist/core/task-parser.d.ts +3 -0
  66. package/dist/core/task-parser.js +3 -1
  67. package/dist/core/types/thread-types.d.ts +54 -8
  68. package/dist/core/utils.d.ts +9 -1
  69. package/dist/core/utils.js +9 -1
  70. package/dist/domain/agents/config.d.ts +2 -1
  71. package/dist/domain/agents/config.js +25 -6
  72. package/dist/domain/agents/facade.d.ts +18 -0
  73. package/dist/domain/agents/facade.js +26 -3
  74. package/dist/domain/agents/profile-manager.d.ts +11 -0
  75. package/dist/domain/agents/profile-manager.js +21 -2
  76. package/dist/domain/costs/codex-usage-monitor.js +2 -1
  77. package/dist/domain/costs/rate-limit-throttle.js +14 -2
  78. package/dist/domain/executions/registry.d.ts +24 -0
  79. package/dist/domain/executions/registry.js +38 -0
  80. package/dist/domain/mcp/core-server.js +15 -3
  81. package/dist/domain/mcp/feishu/bitable.d.ts +3 -0
  82. package/dist/domain/mcp/feishu/bitable.js +168 -0
  83. package/dist/domain/mcp/feishu/block-types.d.ts +44 -0
  84. package/dist/domain/mcp/feishu/block-types.js +127 -0
  85. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +19 -0
  86. package/dist/domain/mcp/feishu/blocks-to-text.js +43 -0
  87. package/dist/domain/mcp/feishu/client.d.ts +46 -0
  88. package/dist/domain/mcp/feishu/client.js +87 -0
  89. package/dist/domain/mcp/feishu/docx.d.ts +3 -0
  90. package/dist/domain/mcp/feishu/docx.js +163 -0
  91. package/dist/domain/mcp/feishu/drive.d.ts +23 -0
  92. package/dist/domain/mcp/feishu/drive.js +66 -0
  93. package/dist/domain/mcp/feishu/file.d.ts +14 -0
  94. package/dist/domain/mcp/feishu/file.js +107 -0
  95. package/dist/domain/mcp/feishu/index.d.ts +6 -0
  96. package/dist/domain/mcp/feishu/index.js +61 -0
  97. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +40 -0
  98. package/dist/domain/mcp/feishu/markdown-to-blocks.js +191 -0
  99. package/dist/domain/mcp/feishu/sheets.d.ts +3 -0
  100. package/dist/domain/mcp/feishu/sheets.js +119 -0
  101. package/dist/domain/mcp/feishu/types.d.ts +26 -0
  102. package/dist/domain/mcp/feishu/types.js +38 -0
  103. package/dist/domain/mcp/feishu/user-auth.d.ts +140 -0
  104. package/dist/domain/mcp/feishu/user-auth.js +286 -0
  105. package/dist/domain/mcp/feishu/wiki.d.ts +3 -0
  106. package/dist/domain/mcp/feishu/wiki.js +77 -0
  107. package/dist/domain/mcp/feishu-server.d.ts +2 -0
  108. package/dist/domain/mcp/feishu-server.js +33 -0
  109. package/dist/domain/mcp/server.d.ts +0 -1
  110. package/dist/domain/mcp/server.js +6 -25
  111. package/dist/domain/mcp/slack-server.d.ts +3 -0
  112. package/dist/domain/mcp/slack-server.js +46 -0
  113. package/dist/domain/mcp/tools/context.js +1 -1
  114. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  115. package/dist/domain/mcp/tools/schedule.js +6 -20
  116. package/dist/domain/mcp/tools/slack.js +20 -7
  117. package/dist/domain/mcp/tools/thread-ops.d.ts +2 -0
  118. package/dist/domain/mcp/tools/thread-ops.js +121 -0
  119. package/dist/domain/mcp/tools/time.d.ts +2 -0
  120. package/dist/domain/mcp/tools/time.js +66 -0
  121. package/dist/domain/mcp/tools/tui-ask.js +1 -1
  122. package/dist/domain/mcp/tools/tui-plan.js +2 -2
  123. package/dist/domain/mcp/tui-server.js +1 -0
  124. package/dist/domain/monitor/disk-monitor.js +2 -1
  125. package/dist/domain/monitor/gpu-monitor.js +2 -1
  126. package/dist/domain/remote/client-hot-reload.js +3 -2
  127. package/dist/domain/remote/client-manager.js +8 -6
  128. package/dist/domain/scheduling/job-registry.d.ts +4 -0
  129. package/dist/domain/scheduling/job-registry.js +1 -0
  130. package/dist/domain/scheduling/jobs/_shared.js +2 -1
  131. package/dist/domain/scheduling/jobs/memory-index-regen.js +3 -2
  132. package/dist/domain/scheduling/jobs/scheduled-task.js +9 -23
  133. package/dist/domain/scheduling/jobs/sync-public.js +4 -3
  134. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +1 -8
  135. package/dist/domain/scheduling/jobs/target-dispatch.js +0 -7
  136. package/dist/domain/scheduling/jobs/task-archive.js +3 -2
  137. package/dist/domain/scheduling/jobs/task-dispatch.js +126 -20
  138. package/dist/domain/scheduling/schedule-command.js +45 -43
  139. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  140. package/dist/domain/scheduling/scheduler.js +2 -1
  141. package/dist/domain/sessions/session-hooks.d.ts +2 -2
  142. package/dist/domain/sessions/session-hooks.js +19 -18
  143. package/dist/domain/sessions/session-lifecycle.d.ts +38 -0
  144. package/dist/domain/sessions/session-lifecycle.js +44 -0
  145. package/dist/domain/system/github-release.d.ts +18 -0
  146. package/dist/domain/system/github-release.js +106 -0
  147. package/dist/domain/system/install-cli.d.ts +7 -0
  148. package/dist/domain/system/install-cli.js +106 -0
  149. package/dist/domain/system/preferences.d.ts +12 -0
  150. package/dist/domain/system/preferences.js +36 -0
  151. package/dist/domain/system/server-update-check.js +2 -2
  152. package/dist/domain/tasks/dispatch-utils.d.ts +58 -1
  153. package/dist/domain/tasks/dispatch-utils.js +53 -4
  154. package/dist/domain/tasks/dispatcher.d.ts +11 -2
  155. package/dist/domain/tasks/dispatcher.js +63 -7
  156. package/dist/domain/tasks/lint.js +28 -0
  157. package/dist/domain/tasks/mutator.d.ts +16 -3
  158. package/dist/domain/tasks/mutator.js +41 -12
  159. package/dist/domain/tasks/pending-tracker.js +6 -5
  160. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  161. package/dist/domain/tasks/system/task-cli.js +37 -6
  162. package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
  163. package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
  164. package/dist/domain/tasks/system/task-mutations.js +166 -8
  165. package/dist/domain/threads/contract.d.ts +17 -0
  166. package/dist/domain/threads/contract.js +59 -0
  167. package/dist/domain/threads/hook-runner.js +7 -6
  168. package/dist/domain/threads/index.d.ts +2 -0
  169. package/dist/domain/threads/index.js +3 -1
  170. package/dist/domain/threads/prompt-builder.d.ts +21 -1
  171. package/dist/domain/threads/prompt-builder.js +60 -4
  172. package/dist/domain/threads/runner.d.ts +6 -5
  173. package/dist/domain/threads/runner.js +128 -79
  174. package/dist/domain/threads/state-machine.d.ts +23 -21
  175. package/dist/domain/threads/state-machine.js +113 -54
  176. package/dist/domain/threads/template-loader.js +3 -2
  177. package/dist/domain/threads/tree.d.ts +45 -0
  178. package/dist/domain/threads/tree.js +171 -0
  179. package/dist/domain/tui-session/index.d.ts +2 -0
  180. package/dist/domain/tui-session/index.js +3 -0
  181. package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
  182. package/dist/domain/tui-session/tui-session-service.js +103 -0
  183. package/dist/domain/tui-session/types.d.ts +67 -0
  184. package/dist/domain/tui-session/types.js +4 -0
  185. package/dist/domain/ui-service/index.d.ts +5 -0
  186. package/dist/domain/ui-service/index.js +3 -0
  187. package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
  188. package/dist/domain/ui-service/mutate/executions.js +15 -0
  189. package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
  190. package/dist/domain/ui-service/mutate/schedules.js +39 -0
  191. package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
  192. package/dist/domain/ui-service/mutate/tasks.js +59 -0
  193. package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
  194. package/dist/domain/ui-service/mutate/threads.js +21 -0
  195. package/dist/domain/ui-service/query/cost.d.ts +3 -0
  196. package/dist/domain/ui-service/query/cost.js +6 -0
  197. package/dist/domain/ui-service/query/executions.d.ts +2 -0
  198. package/dist/domain/ui-service/query/executions.js +35 -0
  199. package/dist/domain/ui-service/query/projects.d.ts +2 -0
  200. package/dist/domain/ui-service/query/projects.js +30 -0
  201. package/dist/domain/ui-service/query/schedules.d.ts +2 -0
  202. package/dist/domain/ui-service/query/schedules.js +23 -0
  203. package/dist/domain/ui-service/query/sessions.d.ts +2 -0
  204. package/dist/domain/ui-service/query/sessions.js +35 -0
  205. package/dist/domain/ui-service/query/tasks.d.ts +2 -0
  206. package/dist/domain/ui-service/query/tasks.js +30 -0
  207. package/dist/domain/ui-service/query/threads.d.ts +2 -0
  208. package/dist/domain/ui-service/query/threads.js +27 -0
  209. package/dist/domain/ui-service/subscribe.d.ts +5 -0
  210. package/dist/domain/ui-service/subscribe.js +118 -0
  211. package/dist/domain/ui-service/types.d.ts +237 -0
  212. package/dist/domain/ui-service/types.js +5 -0
  213. package/dist/domain/ui-service/ui-service.d.ts +2 -0
  214. package/dist/domain/ui-service/ui-service.js +83 -0
  215. package/dist/entry/app.js +130 -8
  216. package/dist/entry/cli.d.ts +12 -0
  217. package/dist/entry/cli.js +122 -12
  218. package/dist/entry/daemon.js +12 -30
  219. package/dist/entry/feishu-login.d.ts +28 -0
  220. package/dist/entry/feishu-login.js +218 -0
  221. package/dist/entry/init.d.ts +29 -5
  222. package/dist/entry/init.js +323 -233
  223. package/dist/entry/startup-notify.js +6 -3
  224. package/dist/events/event-types.d.ts +14 -0
  225. package/dist/hooks/cortex-md-injector.mjs +47 -31
  226. package/dist/hooks/post-task-hook.mjs +6 -0
  227. package/dist/hooks/task-status-check.mjs +8 -0
  228. package/dist/orchestration/agent-runner.d.ts +2 -1
  229. package/dist/orchestration/agent-runner.js +55 -55
  230. package/dist/orchestration/conduit-queue.d.ts +18 -0
  231. package/dist/orchestration/conduit-queue.js +32 -0
  232. package/dist/orchestration/conversation-runner.d.ts +48 -0
  233. package/dist/orchestration/conversation-runner.js +109 -0
  234. package/dist/orchestration/dispatch-reconciler.js +8 -1
  235. package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
  236. package/dist/orchestration/interactions/ask-user-question.js +3 -3
  237. package/dist/orchestration/interactions/interaction-handlers.js +55 -23
  238. package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
  239. package/dist/orchestration/interactions/plan-handler.js +4 -3
  240. package/dist/orchestration/interactions/update-prompt-slack.js +11 -10
  241. package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
  242. package/dist/orchestration/interactions/update-prompt.js +155 -0
  243. package/dist/orchestration/lifecycle.d.ts +4 -4
  244. package/dist/orchestration/lifecycle.js +25 -22
  245. package/dist/orchestration/orchestrator.d.ts +1 -1
  246. package/dist/orchestration/routing/commands/cancel.js +45 -52
  247. package/dist/orchestration/routing/commands/channel.js +41 -27
  248. package/dist/orchestration/routing/commands/cost.js +11 -2
  249. package/dist/orchestration/routing/commands/device.js +12 -9
  250. package/dist/orchestration/routing/commands/dispatch.js +11 -10
  251. package/dist/orchestration/routing/commands/index.d.ts +1 -1
  252. package/dist/orchestration/routing/commands/index.js +15 -10
  253. package/dist/orchestration/routing/commands/lang.d.ts +3 -0
  254. package/dist/orchestration/routing/commands/lang.js +31 -0
  255. package/dist/orchestration/routing/commands/mode.js +32 -30
  256. package/dist/orchestration/routing/commands/nvtop.js +15 -13
  257. package/dist/orchestration/routing/commands/orient.js +2 -1
  258. package/dist/orchestration/routing/commands/schedule.js +23 -22
  259. package/dist/orchestration/routing/commands/sendfile.js +9 -7
  260. package/dist/orchestration/routing/commands/session.d.ts +1 -1
  261. package/dist/orchestration/routing/commands/session.js +24 -39
  262. package/dist/orchestration/routing/commands/status.js +78 -71
  263. package/dist/orchestration/routing/commands/tail.js +7 -5
  264. package/dist/orchestration/routing/commands/task.js +25 -23
  265. package/dist/orchestration/routing/commands/thread-handlers.js +55 -44
  266. package/dist/orchestration/routing/edit-handler.js +8 -7
  267. package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
  268. package/dist/orchestration/routing/message-router.d.ts +1 -1
  269. package/dist/orchestration/routing/message-router.js +9 -9
  270. package/dist/orchestration/routing/webhook.js +233 -2
  271. package/dist/orchestration/status-helpers.d.ts +5 -1
  272. package/dist/orchestration/status-helpers.js +13 -11
  273. package/dist/orchestration/thread-callback.d.ts +67 -0
  274. package/dist/orchestration/thread-callback.js +465 -0
  275. package/dist/orchestration/thread-executor.d.ts +22 -1
  276. package/dist/orchestration/thread-executor.js +85 -36
  277. package/dist/platform/adapter.d.ts +6 -2
  278. package/dist/platform/adapters/composite-adapter.d.ts +89 -0
  279. package/dist/platform/adapters/composite-adapter.js +318 -0
  280. package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
  281. package/dist/platform/adapters/feishu-output-stream.js +274 -36
  282. package/dist/platform/adapters/feishu.d.ts +50 -5
  283. package/dist/platform/adapters/feishu.js +370 -116
  284. package/dist/platform/adapters/index.d.ts +24 -3
  285. package/dist/platform/adapters/index.js +89 -11
  286. package/dist/platform/adapters/project-conduits.d.ts +9 -0
  287. package/dist/platform/adapters/project-conduits.js +42 -0
  288. package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
  289. package/dist/platform/adapters/slack-project-conduits.js +6 -40
  290. package/dist/platform/adapters/slack.d.ts +9 -2
  291. package/dist/platform/adapters/slack.js +83 -39
  292. package/dist/platform/adapters/tui/index.d.ts +9 -0
  293. package/dist/platform/adapters/tui/index.js +10 -0
  294. package/dist/platform/adapters/tui/ports.d.ts +20 -0
  295. package/dist/platform/adapters/tui/ports.js +4 -0
  296. package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
  297. package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
  298. package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
  299. package/dist/platform/adapters/tui/tui-connection.js +53 -0
  300. package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
  301. package/dist/platform/adapters/tui/tui-gateway.js +919 -0
  302. package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
  303. package/dist/platform/adapters/tui/tui-notifications.js +60 -0
  304. package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
  305. package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
  306. package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
  307. package/dist/platform/adapters/tui/tui-transcript.js +56 -0
  308. package/dist/platform/index.d.ts +1 -0
  309. package/dist/platform/index.js +2 -1
  310. package/dist/platform/interactive-builder.js +21 -19
  311. package/dist/platform/output-stream.d.ts +5 -0
  312. package/dist/platform/testing.d.ts +7 -11
  313. package/dist/platform/testing.js +18 -15
  314. package/dist/platform/tool-trace.js +15 -5
  315. package/dist/platform/tui/protocol.d.ts +355 -0
  316. package/dist/platform/tui/protocol.js +199 -0
  317. package/dist/platform/types.d.ts +12 -3
  318. package/dist/store/execution-repo.d.ts +6 -1
  319. package/dist/store/execution-repo.js +13 -3
  320. package/dist/store/hook-sync.d.ts +18 -0
  321. package/dist/store/hook-sync.js +92 -0
  322. package/dist/store/outbound-queue.js +2 -2
  323. package/dist/store/profile-repo.js +3 -2
  324. package/dist/store/schedule-repo.d.ts +1 -8
  325. package/dist/store/session-registry-repo.d.ts +9 -1
  326. package/dist/store/session-registry-repo.js +19 -3
  327. package/dist/store/session-repo.d.ts +14 -0
  328. package/dist/store/session-repo.js +23 -0
  329. package/dist/store/thread-repo.d.ts +3 -0
  330. package/dist/store/thread-repo.js +49 -2
  331. package/dist/store/version-migrations.d.ts +7 -0
  332. package/dist/store/version-migrations.js +183 -0
  333. package/dist/tui/App.d.ts +27 -0
  334. package/dist/tui/App.js +219 -0
  335. package/dist/tui/components/AskUserModal.d.ts +11 -0
  336. package/dist/tui/components/AskUserModal.js +364 -0
  337. package/dist/tui/components/ConfirmModal.d.ts +12 -0
  338. package/dist/tui/components/ConfirmModal.js +31 -0
  339. package/dist/tui/components/Dashboard.d.ts +23 -0
  340. package/dist/tui/components/Dashboard.js +80 -0
  341. package/dist/tui/components/DashboardCostTab.d.ts +7 -0
  342. package/dist/tui/components/DashboardCostTab.js +16 -0
  343. package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
  344. package/dist/tui/components/DashboardExecutionsTab.js +94 -0
  345. package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
  346. package/dist/tui/components/DashboardSchedulesTab.js +124 -0
  347. package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
  348. package/dist/tui/components/DashboardTasksTab.js +200 -0
  349. package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
  350. package/dist/tui/components/DashboardThreadsTab.js +81 -0
  351. package/dist/tui/components/Header.d.ts +11 -0
  352. package/dist/tui/components/Header.js +5 -0
  353. package/dist/tui/components/InputBox.d.ts +10 -0
  354. package/dist/tui/components/InputBox.js +19 -0
  355. package/dist/tui/components/MessageRow.d.ts +7 -0
  356. package/dist/tui/components/MessageRow.js +10 -0
  357. package/dist/tui/components/Notifications.d.ts +19 -0
  358. package/dist/tui/components/Notifications.js +72 -0
  359. package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
  360. package/dist/tui/components/PlanFeedbackModal.js +161 -0
  361. package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
  362. package/dist/tui/components/ProjectSwitcher.js +43 -0
  363. package/dist/tui/components/SessionPicker.d.ts +14 -0
  364. package/dist/tui/components/SessionPicker.js +34 -0
  365. package/dist/tui/components/SidePanel.d.ts +19 -0
  366. package/dist/tui/components/SidePanel.js +8 -0
  367. package/dist/tui/components/StatusLine.d.ts +10 -0
  368. package/dist/tui/components/StatusLine.js +29 -0
  369. package/dist/tui/components/Transcript.d.ts +13 -0
  370. package/dist/tui/components/Transcript.js +56 -0
  371. package/dist/tui/hooks/useDashboardData.d.ts +32 -0
  372. package/dist/tui/hooks/useDashboardData.js +104 -0
  373. package/dist/tui/hooks/useKeybindings.d.ts +19 -0
  374. package/dist/tui/hooks/useKeybindings.js +87 -0
  375. package/dist/tui/hooks/useMutate.d.ts +22 -0
  376. package/dist/tui/hooks/useMutate.js +56 -0
  377. package/dist/tui/hooks/useNotifications.d.ts +28 -0
  378. package/dist/tui/hooks/useNotifications.js +70 -0
  379. package/dist/tui/hooks/useTranscript.d.ts +39 -0
  380. package/dist/tui/hooks/useTranscript.js +265 -0
  381. package/dist/tui/hooks/useWsClient.d.ts +29 -0
  382. package/dist/tui/hooks/useWsClient.js +69 -0
  383. package/dist/tui/index.d.ts +2 -0
  384. package/dist/tui/index.js +210 -0
  385. package/dist/tui/logic.d.ts +16 -0
  386. package/dist/tui/logic.js +49 -0
  387. package/dist/tui/render/markdown.d.ts +10 -0
  388. package/dist/tui/render/markdown.js +38 -0
  389. package/dist/tui/render/rich-blocks.d.ts +11 -0
  390. package/dist/tui/render/rich-blocks.js +24 -0
  391. package/dist/tui/ws-client.d.ts +44 -0
  392. package/dist/tui/ws-client.js +157 -0
  393. package/package.json +11 -3
  394. package/dist/orchestration/channel-queue.d.ts +0 -18
  395. package/dist/orchestration/channel-queue.js +0 -32
package/dist/entry/app.js CHANGED
@@ -5,8 +5,9 @@
5
5
  import * as dotenv from 'dotenv';
6
6
  import { mkdirSync } from 'fs';
7
7
  import * as path from 'path';
8
- import { createAdapterFromEnv } from '../platform/index.js';
9
- import { WORKSPACE_DIR, CONFIG_DIR } from '../core/utils.js';
8
+ import { createAdapterFromEnv, extractTuiAdapter } from '../platform/index.js';
9
+ import { WORKSPACE_DIR, CONFIG_DIR, DATA_DIR, STORE_DIR } from '../core/utils.js';
10
+ import { tryAcquireSingletonLock, releaseSingletonLock } from '../core/singleton-lock.js';
10
11
  import { closeAllSessions, closeSession as closeClaudePooledSession, shutdownCodex } from '../domain/agents/index.js';
11
12
  import { closeAllAdapters } from '../agent-adapter/index.js';
12
13
  import { recoverTuiOrphans } from '../agent-adapter/claude/adapter.js';
@@ -16,6 +17,7 @@ import * as executionRegistry from '../domain/executions/registry.js';
16
17
  import { initHookBridge } from '../orchestration/routing/hook-bridge.js';
17
18
  import { registerCommands } from '../orchestration/routing/commands/index.js';
18
19
  import { taskStore } from '../domain/tasks/store.js';
20
+ import { taskMutator } from '../domain/tasks/mutator.js';
19
21
  import { projectDirRepo } from '../store/project-dir-repo.js';
20
22
  import { projectStore } from '../domain/projects/index.js';
21
23
  import { sendStartupDmIfConfigured } from './startup-notify.js';
@@ -24,13 +26,15 @@ import { startClientManager, stopClientManager, startAllRemoteClients } from '..
24
26
  import { checkAndUpdateClients, formatUpdateSlackMessage } from '../domain/remote/client-hot-reload.js';
25
27
  import { checkServerUpdate } from '../domain/system/server-update-check.js';
26
28
  import { threadStore } from '../store/thread-repo.js';
27
- import { sessionRepo } from '../store/session-repo.js';
29
+ import { sessionRepo, registerConduitProvider } from '../store/session-repo.js';
28
30
  import { conversationLedger } from '../store/conversation-ledger-repo.js';
29
31
  import { executionRepo } from '../store/execution-repo.js';
30
32
  import { loadConfig as loadThreadConfig, startConfigWatcher as startThreadConfigWatcher, setAdminNotifier as setConfigNotifier } from '../domain/threads/index.js';
31
33
  import { startMemoryWatcher } from '../domain/memory/watcher.js';
32
- import { getActiveBackend } from '../domain/agents/index.js';
34
+ import { getActiveBackend, configureEnvForMode, loadMode } from '../domain/agents/index.js';
33
35
  import { createEditHandler } from '../orchestration/routing/edit-handler.js';
36
+ import { setLocale, normalizeLocale } from '../core/i18n.js';
37
+ import { loadLang } from '../domain/system/preferences.js';
34
38
  // Extracted modules
35
39
  import { cleanupLogs, ensureMcpConfig } from './startup-helpers.js';
36
40
  import { createLogger } from '../core/log.js';
@@ -40,14 +44,17 @@ import { busyTracker } from '../orchestration/busy-tracker.js';
40
44
  import { buildExecutionStatusReport } from '../orchestration/status-helpers.js';
41
45
  import { reprocessMessage } from '../orchestration/lifecycle.js';
42
46
  import { initScheduledRunner, createScheduler, setSchedulerRef, setBus, setInteractiveCallbacksFactory, cancelDispatchedTask } from '../domain/scheduling/runner.js';
47
+ import { recoverWaitingThreads, registerTaskTreeSubscribers, reconcileWaitingTasks } from '../orchestration/thread-callback.js';
48
+ import { ctx as jobCtx } from '../domain/scheduling/job-registry.js';
43
49
  import { buildInteractiveCallbacks } from '../orchestration/agent-runner.js';
44
50
  import { registerInteractionHandlers, initInteractionHandlers } from '../orchestration/interactions/interaction-handlers.js';
45
51
  import { CommandActionRouter } from '../orchestration/interactions/command-action-router.js';
46
- import { createSlackUpdatePrompt } from '../orchestration/interactions/update-prompt-slack.js';
52
+ import { createUpdatePrompt } from '../orchestration/interactions/update-prompt.js';
47
53
  import { registerMessageHandler } from '../orchestration/routing/message-router.js';
48
54
  import { initRateLimitThrottle } from '../domain/costs/rate-limit-throttle.js';
49
55
  import { scheduleRepo } from '../store/schedule-repo.js';
50
- import { runMigrations } from '../store/version-migrations.js';
56
+ import { runMigrations, migrateAistatusConfigLocation } from '../store/version-migrations.js';
57
+ import { syncManagedHooks } from '../store/hook-sync.js';
51
58
  import { costRepo } from '../store/cost-repo.js';
52
59
  import { profileRepo, startProfileWatcher, setAdminNotifier as setProfileNotifier } from '../store/profile-repo.js';
53
60
  import { sessionStore } from '../store/session-registry-repo.js';
@@ -59,8 +66,72 @@ import { registerHookBridgeSubscribers } from '../orchestration/routing/hook-bri
59
66
  import { startDispatchReconciler } from '../orchestration/dispatch-reconciler.js';
60
67
  import { ensurePIAgentDirs } from '../agent-adapter/pi/agent-dir.js';
61
68
  import { initOutboundQueue } from '../store/outbound-queue.js';
69
+ import { createUiService } from '../domain/ui-service/index.js';
70
+ import { createTuiSessionService } from '../domain/tui-session/index.js';
71
+ import { enqueue, conduitQueues } from '../orchestration/conduit-queue.js';
72
+ import { getCostSummary } from '../domain/costs/cost-tracker.js';
62
73
  dotenv.config({ path: path.join(CONFIG_DIR, '.env') });
74
+ // Apply the persisted mode to env now that .env is loaded. This used to be an import-time
75
+ // side effect inside domain/agents/config.ts; it is explicit here so that CLI processes
76
+ // (cortex init / setup-gateway) importing that module don't get their env mutated.
77
+ configureEnvForMode(loadMode());
78
+ // Resolve the UI language for all system-generated user-facing text. Precedence:
79
+ // CORTEX_LANG env (escape hatch, now that .env is loaded) > config/preferences.json > 'en'.
80
+ // The !lang command switches this live at runtime via setLocale().
81
+ setLocale(process.env.CORTEX_LANG ? normalizeLocale(process.env.CORTEX_LANG) : loadLang());
63
82
  const log = createLogger('app');
83
+ // --- Singleton lock ---
84
+ // app.js owns ports 3001 (webhook) / 3002 (client-manager); a second instance would
85
+ // crash-loop on EADDRINUSE. The daemon's own daemon.pid lock only guards the supervisor
86
+ // layer and does nothing for `cortex start` (which forks app.js directly, bypassing the
87
+ // daemon). Acquire our own app.pid lock here, as early as possible, to fail fast before
88
+ // any heavy initialization or port binding. Stale locks (previous owner SIGKILL'd / crashed)
89
+ // are reclaimed automatically. Released on process exit (covers SIGTERM→exit(0) and Ctrl+C).
90
+ const APP_PID_FILE = path.join(STORE_DIR, 'app.pid');
91
+ const appLock = tryAcquireSingletonLock(APP_PID_FILE);
92
+ if (appLock.acquired) {
93
+ if (appLock.stale)
94
+ log.info(`Reclaimed stale app.pid lock for PID ${process.pid}`);
95
+ }
96
+ else {
97
+ log.error(`Another Cortex app.js is already running (PID ${appLock.holderPid}, lockfile ${APP_PID_FILE}).\n` +
98
+ ` Refusing to start a second instance — it already holds ports 3001/3002; this process would crash on EADDRINUSE.\n` +
99
+ ` Inspect with \`cortex daemon status\`, or stop the running instance before retrying.`);
100
+ process.exit(1);
101
+ }
102
+ process.on('exit', () => releaseSingletonLock(APP_PID_FILE));
103
+ // --- Crash safety net ---
104
+ // A single failed outbound post while handling an inbound message must never take
105
+ // down the whole server. Detached per-conduit queue work (conduit-queue.ts) and
106
+ // platform-adapter callbacks can reject without an observer; without these
107
+ // handlers an unhandled rejection terminates the process (exit code 1). Log the
108
+ // full stack and keep running. Mirrors the daemon's own guards (daemon.ts).
109
+ // Re-entrancy guard prevents an infinite loop if log.error() itself throws.
110
+ let _inExceptionHandler = false;
111
+ process.on('unhandledRejection', (reason) => {
112
+ if (_inExceptionHandler)
113
+ return;
114
+ _inExceptionHandler = true;
115
+ try {
116
+ log.error(`unhandledRejection: ${reason instanceof Error ? reason.stack : String(reason)}`);
117
+ }
118
+ catch { /* swallow secondary failure */ }
119
+ finally {
120
+ _inExceptionHandler = false;
121
+ }
122
+ });
123
+ process.on('uncaughtException', (err) => {
124
+ if (_inExceptionHandler)
125
+ return;
126
+ _inExceptionHandler = true;
127
+ try {
128
+ log.error(`uncaughtException: ${err?.stack ?? err}`);
129
+ }
130
+ catch { /* swallow secondary failure */ }
131
+ finally {
132
+ _inExceptionHandler = false;
133
+ }
134
+ });
64
135
  // --- EventBus + logger ---
65
136
  const bus = new EventBus();
66
137
  createEventLogger(bus);
@@ -68,6 +139,7 @@ initHookBridge(bus); // S5: wire hook-bridge to publish ask-user.requested / pla
68
139
  runningExecutions.setBus(bus); // S6-A: wire lifecycle events
69
140
  planApprovals.setBus(bus); // S6-A: wire plan.approved events
70
141
  busyTracker.setBus(bus); // S6-C: wire busy/idle IPC through event bus
142
+ taskMutator.setBus(bus); // c39d: wire task lifecycle events
71
143
  initInteractionHandlers(bus); // BLK-1: wire ask-user.answered publisher
72
144
  const TEMP_DIR = WORKSPACE_DIR;
73
145
  mkdirSync(TEMP_DIR, { recursive: true });
@@ -78,6 +150,20 @@ loadMachinesFromFile();
78
150
  startMachineRegistryWatcher();
79
151
  // --- Create platform adapter (replaces direct Slack App instantiation) ---
80
152
  const adapter = createAdapterFromEnv();
153
+ // Wire EventBus + injected dependencies into the TUI gateway before start() so it can
154
+ // subscribe to bus events and resolve sessions during its own start()/handshake lifecycle.
155
+ const tuiGateway = extractTuiAdapter(adapter);
156
+ if (tuiGateway) {
157
+ tuiGateway.setBus(bus);
158
+ // Session lifecycle service (transport-agnostic; gateway delegates handshake/switch to it).
159
+ tuiGateway.setSessionService(createTuiSessionService({ sessionStore, conversationLedger }));
160
+ // Conduit-queue port — MUST wrap the shared @orch/conduit-queue singletons so TUI message
161
+ // work serializes with the rest of the pipeline on the same conduit key.
162
+ tuiGateway.setConduitQueue({ enqueue, remove: (id) => conduitQueues.delete(id) });
163
+ // Conduit provider inversion: store-layer session lookup resolves ephemeral TUI conduits
164
+ // via the gateway's in-memory state (previously the gateway imported the store directly).
165
+ registerConduitProvider((conduitId) => tuiGateway.lookupConduit(conduitId));
166
+ }
81
167
  // --- Wire hot-reload admin notifiers ---
82
168
  const notifyAdmin = (text) => {
83
169
  adapter.postMessage({ type: 'system-notice' }, { text }).catch(() => { });
@@ -107,7 +193,7 @@ const dispatchCommand = registerCommands({
107
193
  commandRouter,
108
194
  });
109
195
  // DR-0013: wire Slack update prompt BEFORE bindToAdapter (router has no unregister API)
110
- const updatePrompt = createSlackUpdatePrompt(adapter, commandRouter);
196
+ const updatePrompt = createUpdatePrompt(adapter, commandRouter);
111
197
  // Bind command action handlers (buttons, modals) to the platform adapter
112
198
  commandRouter.bindToAdapter(adapter);
113
199
  const handleMessageEdit = createEditHandler({
@@ -159,6 +245,11 @@ process.on('SIGTERM', async () => {
159
245
  cleanupLogs();
160
246
  ensureMcpConfig();
161
247
  await runMigrations();
248
+ // Migrate old aistatus config from wrong location (CORTEX_HOME/config) to correct location (~/.aistatus)
249
+ await migrateAistatusConfigLocation(DATA_DIR);
250
+ // Refresh version-stamped hooks in DATA_DIR/hooks from the shipped defaults. init's deployHooks
251
+ // only copies-if-missing, so without this an existing install never picks up hook code fixes.
252
+ await syncManagedHooks();
162
253
  // DR-0012 §3.6: clean up orphan TUI tmux sessions from a previous agent-server lifetime.
163
254
  // We can't re-adopt them (sessionKey↔tmux mapping was never persisted) so the honest move
164
255
  // is to kill any leftovers — otherwise a later session that reuses the same sessionId will
@@ -173,7 +264,28 @@ process.on('SIGTERM', async () => {
173
264
  log.warn(`Startup: recoverTuiOrphans failed: ${e.message}`);
174
265
  }
175
266
  executionRepo.load();
176
- await executionRegistry.markMissingRunningExecutionsStale((record) => record.kind === 'dispatch');
267
+ // Keep only REMOTE dispatch running across restart (it runs on another machine/tmux and
268
+ // survives). An in-process dispatch (dispatch=null / machine 'local') dies with the server, so
269
+ // stale it immediately — otherwise its 'running' record poisons a dispatch concurrency slot
270
+ // until the reconciler's next tick.
271
+ await executionRegistry.markMissingRunningExecutionsStale((record) => record.kind === 'dispatch' && !!record.dispatch?.machine && record.dispatch.machine !== 'local');
272
+ // ── Wire UI service into the TUI gateway ────────────────────────────────
273
+ //
274
+ // UI service (M3) provides store-backed query/mutate/subscribe capabilities
275
+ // to the TUI gateway via a transport-agnostic facade.
276
+ const uiService = createUiService({
277
+ projectStore,
278
+ sessionStore,
279
+ threadStore,
280
+ taskStore,
281
+ scheduler,
282
+ executionRegistry,
283
+ runningExecutions,
284
+ costSummary: getCostSummary,
285
+ bus,
286
+ adapter,
287
+ });
288
+ extractTuiAdapter(adapter)?.setUiService(uiService);
177
289
  await adapter.start();
178
290
  try {
179
291
  const notified = await sendStartupDmIfConfigured(adapter, {
@@ -273,5 +385,15 @@ process.on('SIGTERM', async () => {
273
385
  registerHookBridgeSubscribers(bus, adapter, planApprovals);
274
386
  startMemoryWatcher();
275
387
  startDispatchReconciler();
388
+ // DR-0014: re-deliver child results that turned terminal while the server was down and
389
+ // DR-0014 §8: wake suspended manager threads on child-task terminal events, and let the
390
+ // dispatch path close the suspension race window without a domain→orchestration import.
391
+ registerTaskTreeSubscribers(bus);
392
+ jobCtx.onThreadSuspended = (threadId) => reconcileWaitingTasks(threadId);
393
+ // resume suspended parents. Runs last — needs jobCtx.adapter and the thread system ready.
394
+ // (markRunningAsFailedOnStartup above already failed all in-flight children, so every
395
+ // awaited child THREAD is terminal or missing by now; child TASKS are reconciled
396
+ // against disk and stay awaited while open.)
397
+ recoverWaitingThreads().catch((e) => log.error(`recoverWaitingThreads failed: ${e.message}`));
276
398
  log.info(`Cortex agent is running (${adapter.name}) — backend: ${getActiveBackend()}`);
277
399
  })();
@@ -1,5 +1,17 @@
1
1
  export declare function getInitHelp(): string;
2
2
  export declare function getSetupGatewayHelp(): string;
3
+ export interface TuiCliOptions {
4
+ resume: boolean;
5
+ project?: string;
6
+ port?: number;
7
+ }
8
+ /** Parse arguments for the `cortex tui` subcommand. */
9
+ export declare function parseTuiArgs(args: string[]): TuiCliOptions;
10
+ /** Check whether a TCP server is listening on 127.0.0.1:port (500ms timeout). */
11
+ export declare function tuiPortListening(port: number): Promise<boolean>;
12
+ export declare function getTuiHelp(): string;
13
+ /** Execute the `cortex tui` subcommand: check daemon liveness, fork Ink client. */
14
+ export declare function cmdTui(args: string[]): Promise<void>;
3
15
  export declare function getCliHelp(): string;
4
16
  export declare function getConfigOutput(): string;
5
17
  export interface CliResult {
package/dist/entry/cli.js CHANGED
@@ -1,6 +1,6 @@
1
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}
2
+ // input: process argv, child_process, net, @core/paths, @core/cli-utils, ./init, @domain/tasks/system/task-cli, @domain/system/install-cli
3
+ // output: CLI dispatcher: cortex {init,start,daemon,task,config,install,setup-gateway,tui}
4
4
  // pos: Bin entry point (`cortex`). Dispatches to:
5
5
  // init [--home <path>] — interactive init (async, runInit)
6
6
  // start — fork app.js
@@ -12,19 +12,24 @@
12
12
  // daemon restart --force— force: send SIGKILL immediately to app.js
13
13
  // daemon restart-self — stop daemon, then re-fork daemon.js
14
14
  // task <subcommand> — delegate to task-cli
15
+ // install latest — install latest Cortex from npm
15
16
  // config — show resolved paths
17
+ // tui [options] — start Terminal UI client (forks dist/tui/index.js)
16
18
  // Packaged as dist/entry/cli.js, registered in package.json bin.
17
19
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
18
20
  import { fork } from 'child_process';
19
21
  import * as path from 'path';
22
+ import * as net from 'net';
20
23
  import { fileURLToPath } from 'url';
21
24
  import { existsSync, readdirSync, mkdirSync, writeFileSync, utimesSync, readFileSync, unlinkSync } from 'fs';
22
25
  import { INSTALL_ROOT, DATA_DIR, STORE_DIR, isMainModule } from '../core/utils.js';
23
26
  import { formatHelp } from '../core/cli-utils.js';
24
27
  import { createLogger } from '../core/log.js';
25
28
  import { runCli as taskRunCli } from '../domain/tasks/system/task-cli.js';
29
+ import { runCli as installRunCli, getInstallHelp } from '../domain/system/install-cli.js';
26
30
  import { getResolvedPaths, formatConfigOutput, runInit, } from './init.js';
27
- import { discoverEndpoints, generateGatewayYaml, writeGatewayYaml, dryRunGatewayYaml } from '../core/gateway-generator.js';
31
+ import { cmdFeishu } from './feishu-login.js';
32
+ import { discoverEndpoints, writeMergedGatewayYaml, validateProfilesAgainstGateway, dryRunGatewayYaml } from '../core/gateway-generator.js';
28
33
  import { generateProfiles, writeProfilesJson } from '../core/profile-generator.js';
29
34
  import { CORTEX_VERSION } from '../core/version.js';
30
35
  // ─── Paths ──────────────────────────────────────────────────────
@@ -32,6 +37,7 @@ const log = createLogger('cli');
32
37
  const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
33
38
  const APP_JS = path.join(MODULE_DIR, 'app.js');
34
39
  const DAEMON_JS = path.join(MODULE_DIR, 'daemon.js');
40
+ const TUI_JS = path.join(MODULE_DIR, '..', 'tui', 'index.js');
35
41
  // ─── Help ───────────────────────────────────────────────────────
36
42
  export function getInitHelp() {
37
43
  return [
@@ -67,6 +73,79 @@ export function getSetupGatewayHelp() {
67
73
  ' --help, -h Show this help',
68
74
  ].join('\n');
69
75
  }
76
+ /** Parse arguments for the `cortex tui` subcommand. */
77
+ export function parseTuiArgs(args) {
78
+ const opts = { resume: false };
79
+ for (let i = 0; i < args.length; i++) {
80
+ switch (args[i]) {
81
+ case '--resume':
82
+ opts.resume = true;
83
+ break;
84
+ case '--project':
85
+ opts.project = args[++i];
86
+ break;
87
+ case '--port':
88
+ opts.port = Number(args[++i]);
89
+ break;
90
+ }
91
+ }
92
+ return opts;
93
+ }
94
+ /** Check whether a TCP server is listening on 127.0.0.1:port (500ms timeout). */
95
+ export function tuiPortListening(port) {
96
+ return new Promise(resolve => {
97
+ const sock = net.connect({ host: '127.0.0.1', port }, () => {
98
+ sock.end();
99
+ resolve(true);
100
+ });
101
+ sock.setTimeout(500);
102
+ sock.on('timeout', () => { sock.destroy(); resolve(false); });
103
+ sock.on('error', () => resolve(false));
104
+ });
105
+ }
106
+ export function getTuiHelp() {
107
+ return [
108
+ 'Start the Cortex TUI (terminal UI) client',
109
+ '',
110
+ 'Usage: cortex tui [options]',
111
+ '',
112
+ 'Connects to a running Cortex daemon via WebSocket and opens',
113
+ 'a terminal-based chat interface.',
114
+ '',
115
+ 'Options:',
116
+ ' --resume Open the resume-session picker on connect',
117
+ ' --project <id> Start a fresh session in the named project',
118
+ ' --port <n> Override TUI port (default: 3003, or CORTEX_TUI_PORT)',
119
+ ' --help, -h Show this help',
120
+ ].join('\n');
121
+ }
122
+ /** Execute the `cortex tui` subcommand: check daemon liveness, fork Ink client. */
123
+ export async function cmdTui(args) {
124
+ const opts = parseTuiArgs(args);
125
+ const port = opts.port ?? (Number(process.env.CORTEX_TUI_PORT) || 3003);
126
+ if (!await tuiPortListening(port)) {
127
+ process.stderr.write(`Cortex daemon is not running on port ${port}.\n` +
128
+ `Start it with: cortex daemon\n`);
129
+ process.exit(1);
130
+ }
131
+ if (!existsSync(TUI_JS)) {
132
+ log.error(`TUI entry not found: ${TUI_JS}`);
133
+ log.error('Run `npm run build` first.');
134
+ process.exit(1);
135
+ }
136
+ const childArgs = [];
137
+ if (opts.resume)
138
+ childArgs.push('--resume');
139
+ if (opts.project) {
140
+ childArgs.push('--project', opts.project);
141
+ }
142
+ const child = fork(TUI_JS, childArgs, {
143
+ stdio: 'inherit',
144
+ env: { ...process.env, CORTEX_TUI_PORT: String(port) },
145
+ });
146
+ child.on('exit', code => process.exit(code ?? 0));
147
+ await new Promise(() => { }); // keep alive until child exits
148
+ }
70
149
  export function getCliHelp() {
71
150
  return formatHelp({
72
151
  name: 'cortex',
@@ -84,8 +163,11 @@ export function getCliHelp() {
84
163
  { name: 'daemon restart-self', description: 'Stop and restart the daemon process itself' },
85
164
  { name: 'restart', description: 'Legacy alias for daemon restart (touches $STORE_DIR/.restart)' },
86
165
  { name: 'task', description: 'Task system CLI (delegate to cortex-task)' },
166
+ { name: 'install latest', description: 'Install the latest version of Cortex from npm' },
87
167
  { name: 'config', description: 'Show resolved paths and initialization status' },
168
+ { name: 'feishu', description: 'Manage Feishu user-identity login (login / status / logout)' },
88
169
  { name: 'setup-gateway', description: 'Auto-detect Claude/PI configs and generate gateway.yaml + profiles.json' },
170
+ { name: 'tui', description: 'Start the Terminal UI (TUI) client for local interaction' },
89
171
  ],
90
172
  options: [
91
173
  { flag: '--help, -h', description: 'Show this help' },
@@ -469,6 +551,8 @@ export async function runCli(argv) {
469
551
  }
470
552
  case 'config':
471
553
  return { exitCode: 0, stdout: getConfigOutput(), stderr: '' };
554
+ case 'feishu':
555
+ return cmdFeishu(rest);
472
556
  case 'restart': {
473
557
  const trigger = path.join(STORE_DIR, '.restart');
474
558
  try {
@@ -502,20 +586,31 @@ export async function runCli(argv) {
502
586
  if (endpoints.length === 0) {
503
587
  return { exitCode: 0, stdout: 'No backends discovered. Log into Claude Code and/or PI first.\n', stderr: '' };
504
588
  }
505
- const yaml = generateGatewayYaml(endpoints);
506
- const gatewayPath = writeGatewayYaml(yaml, outputDir);
589
+ const { path: gatewayPath, result: mergeResult } = writeMergedGatewayYaml(endpoints, outputDir);
507
590
  const profilesPath = writeProfilesJson(endpoints, outputDir);
508
591
  const profiles = generateProfiles(endpoints);
509
592
  const profileNames = Object.keys(profiles.profiles).join(', ');
593
+ const issues = validateProfilesAgainstGateway(mergeResult.endpoints, outputDir);
594
+ const stdoutLines = [
595
+ outputDir ? `[TEST MODE] Output directory: ${outputDir}` : '',
596
+ `Gateway config: ${gatewayPath}`,
597
+ `Profiles: ${profilesPath}`,
598
+ `Discovered ${endpoints.length} endpoint modes`,
599
+ `Generated profiles: ${profileNames} (default: ${profiles.defaultProfile})`,
600
+ ];
601
+ if (mergeResult.droppedFromDiscovery.length > 0) {
602
+ const list = mergeResult.droppedFromDiscovery.map(p => `${p.mode}/${p.endpoint}`).join(', ');
603
+ stdoutLines.push(`WARNING: preserved ${mergeResult.droppedFromDiscovery.length} existing gateway mode(s) not reported by discovery: ${list}`);
604
+ stdoutLines.push(' (if these should auto-detect, check `pi /login` / `pi --list-models`)');
605
+ }
606
+ if (issues.length > 0) {
607
+ stdoutLines.push(`WARNING: ${issues.length} profile(s) reference an unconfigured gateway mode (would fail with "Unknown mode"):`);
608
+ for (const i of issues)
609
+ stdoutLines.push(` - ${i.profile}: ${i.reason}`);
610
+ }
510
611
  return {
511
612
  exitCode: 0,
512
- stdout: [
513
- outputDir ? `[TEST MODE] Output directory: ${outputDir}` : '',
514
- `Gateway config: ${gatewayPath}`,
515
- `Profiles: ${profilesPath}`,
516
- `Discovered ${endpoints.length} endpoint modes`,
517
- `Generated profiles: ${profileNames} (default: ${profiles.defaultProfile})`,
518
- ].filter(Boolean).join('\n'),
613
+ stdout: stdoutLines.filter(Boolean).join('\n'),
519
614
  stderr: '',
520
615
  };
521
616
  }
@@ -527,6 +622,12 @@ export async function runCli(argv) {
527
622
  const result = taskRunCli(rest.length > 0 ? rest : ['list']);
528
623
  return result;
529
624
  }
625
+ case 'install': {
626
+ if (rest.includes('--help') || rest.includes('-h')) {
627
+ return { exitCode: 0, stdout: getInstallHelp(), stderr: '' };
628
+ }
629
+ return installRunCli(rest);
630
+ }
530
631
  case 'start':
531
632
  return { exitCode: 0, stdout: '', stderr: `'start' must be run from the main entry point, not imported.\nUse: node dist/entry/cli.js start` };
532
633
  case 'daemon': {
@@ -574,6 +675,10 @@ function main() {
574
675
  console.log(getCliHelp());
575
676
  process.exit(0);
576
677
  }
678
+ if (cmd === 'tui') {
679
+ console.log(getTuiHelp());
680
+ process.exit(0);
681
+ }
577
682
  // Other subcommands (init, task, config, setup-gateway) handle --help internally via runCli()
578
683
  }
579
684
  // Handle --version / -V for subcommands
@@ -649,6 +754,11 @@ function main() {
649
754
  });
650
755
  process.exit(0);
651
756
  }
757
+ // ── Subcommands that fork with stdio: 'inherit' ──
758
+ if (cmd === 'tui') {
759
+ cmdTui(rest);
760
+ return;
761
+ }
652
762
  // ── Subcommands that return results ──
653
763
  runCli(args).then((result) => {
654
764
  if (result.stdout)
@@ -36,10 +36,11 @@
36
36
  */
37
37
  import * as dotenv from 'dotenv';
38
38
  import { fork, spawn } from 'child_process';
39
- import { watch, existsSync, unlinkSync, statSync, readFileSync, writeFileSync, readdirSync } from 'fs';
39
+ import { watch, existsSync, unlinkSync, statSync, writeFileSync, readdirSync } from 'fs';
40
40
  import * as path from 'path';
41
41
  import { createLogger } from '../core/log.js';
42
42
  import { isMainModule, moduleDir, DATA_DIR, CONFIG_DIR, STORE_DIR } from '../core/utils.js';
43
+ import { tryAcquireSingletonLock, releaseSingletonLock as releaseLock } from '../core/singleton-lock.js';
43
44
  // Load .env BEFORE reading any CORTEX_* env vars below. Mirrors app.ts §61 — the
44
45
  // daemon needs CORTEX_REPO (and potentially other vars) from .env, not just from
45
46
  // the OS shell env. Must be sync and before the `CORTEX_REPO` constant below.
@@ -479,39 +480,20 @@ function setupShutdown() {
479
480
  process.on('SIGTERM', () => shutdown('SIGTERM'));
480
481
  }
481
482
  function acquireSingletonLock() {
482
- if (existsSync(PID_FILE)) {
483
- const raw = readFileSync(PID_FILE, 'utf8').trim();
484
- const otherPid = Number(raw);
485
- if (Number.isFinite(otherPid) && otherPid > 0) {
486
- let alive = false;
487
- try {
488
- process.kill(otherPid, 0);
489
- alive = true;
490
- }
491
- catch {
492
- alive = false;
493
- }
494
- if (alive) {
495
- log.error(`Another Cortex daemon is already running (PID ${otherPid}, lockfile ${PID_FILE}).\n` +
496
- ` Refusing to start a second instance — its app.ts already holds ports 3001/3002 and your child would crash-loop on EADDRINUSE.\n` +
497
- ` To restart the running daemon: \`touch agent-server/.restart\` (hot reload), or send SIGTERM to PID ${otherPid} and rerun.`);
498
- process.exit(1);
499
- }
500
- }
483
+ const result = tryAcquireSingletonLock(PID_FILE);
484
+ if (result.acquired) {
501
485
  // Stale lock — previous daemon died without cleanup
502
- log.info(`Removing stale PID file (PID ${raw} not running)`);
486
+ if (result.stale)
487
+ log.info(`Removed stale PID file and reclaimed lock for PID ${process.pid}`);
488
+ return;
503
489
  }
504
- writeFileSync(PID_FILE, String(process.pid), 'utf8');
490
+ log.error(`Another Cortex daemon is already running (PID ${result.holderPid}, lockfile ${PID_FILE}).\n` +
491
+ ` Refusing to start a second instance — its app.ts already holds ports 3001/3002 and your child would crash-loop on EADDRINUSE.\n` +
492
+ ` To restart the running daemon: \`touch agent-server/.restart\` (hot reload), or send SIGTERM to PID ${result.holderPid} and rerun.`);
493
+ process.exit(1);
505
494
  }
506
495
  function releaseSingletonLock() {
507
- try {
508
- if (!existsSync(PID_FILE))
509
- return;
510
- const raw = readFileSync(PID_FILE, 'utf8').trim();
511
- if (Number(raw) === process.pid)
512
- unlinkSync(PID_FILE);
513
- }
514
- catch { }
496
+ releaseLock(PID_FILE);
515
497
  try {
516
498
  if (existsSync(CHILD_PID_FILE))
517
499
  unlinkSync(CHILD_PID_FILE);
@@ -0,0 +1,28 @@
1
+ import { type FetchLike } from '../domain/mcp/feishu/user-auth.js';
2
+ export interface CliResult {
3
+ exitCode: number;
4
+ stdout: string;
5
+ stderr: string;
6
+ }
7
+ /** Injectable seams so the dispatcher is testable without real stdin/network/CONFIG_DIR. */
8
+ export interface FeishuCliDeps {
9
+ env?: NodeJS.ProcessEnv;
10
+ prompt?: (question: string) => Promise<string>;
11
+ now?: () => number;
12
+ tokenFile?: string;
13
+ fetchImpl?: FetchLike;
14
+ /** Injectable wait used by the device-flow poll (defaults to setTimeout). */
15
+ sleep?: (ms: number) => Promise<void>;
16
+ /** When true (default), merge CONFIG_DIR/.env into env so credentials are available. */
17
+ loadDotenv?: boolean;
18
+ /** dotenv file that a successful login flips to FEISHU_AUTH_MODE=user (default: CONFIG_DIR/.env). */
19
+ envFile?: string;
20
+ }
21
+ /**
22
+ * Idempotently set KEY=value in a dotenv file: rewrite the line if KEY already
23
+ * exists, append it otherwise, creating the file (and parent dir) when missing.
24
+ * The rest of the file is preserved so hand-written credentials stay intact.
25
+ */
26
+ export declare function upsertEnvVar(file: string, key: string, value: string): void;
27
+ export declare function getFeishuHelp(): string;
28
+ export declare function cmdFeishu(args: string[], deps?: FeishuCliDeps): Promise<CliResult>;