@cortex-agent/server 2026.5.25 → 2026.6.11

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 (355) 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 +301 -29
  36. package/dist/core/icons.d.ts +68 -0
  37. package/dist/core/icons.js +67 -0
  38. package/dist/core/profile-generator.d.ts +6 -0
  39. package/dist/core/profile-generator.js +35 -7
  40. package/dist/core/running-executions.d.ts +51 -41
  41. package/dist/core/running-executions.js +120 -73
  42. package/dist/core/status-format.js +3 -2
  43. package/dist/core/task-parser.d.ts +3 -0
  44. package/dist/core/task-parser.js +3 -1
  45. package/dist/core/types/thread-types.d.ts +54 -8
  46. package/dist/domain/agents/facade.d.ts +18 -0
  47. package/dist/domain/agents/facade.js +26 -3
  48. package/dist/domain/agents/profile-manager.d.ts +11 -0
  49. package/dist/domain/agents/profile-manager.js +21 -2
  50. package/dist/domain/costs/codex-usage-monitor.js +2 -1
  51. package/dist/domain/costs/rate-limit-throttle.js +14 -2
  52. package/dist/domain/executions/registry.d.ts +24 -0
  53. package/dist/domain/executions/registry.js +38 -0
  54. package/dist/domain/mcp/core-server.js +15 -3
  55. package/dist/domain/mcp/feishu/bitable.d.ts +3 -0
  56. package/dist/domain/mcp/feishu/bitable.js +168 -0
  57. package/dist/domain/mcp/feishu/block-types.d.ts +44 -0
  58. package/dist/domain/mcp/feishu/block-types.js +127 -0
  59. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +19 -0
  60. package/dist/domain/mcp/feishu/blocks-to-text.js +43 -0
  61. package/dist/domain/mcp/feishu/client.d.ts +46 -0
  62. package/dist/domain/mcp/feishu/client.js +87 -0
  63. package/dist/domain/mcp/feishu/docx.d.ts +3 -0
  64. package/dist/domain/mcp/feishu/docx.js +163 -0
  65. package/dist/domain/mcp/feishu/drive.d.ts +23 -0
  66. package/dist/domain/mcp/feishu/drive.js +66 -0
  67. package/dist/domain/mcp/feishu/file.d.ts +14 -0
  68. package/dist/domain/mcp/feishu/file.js +107 -0
  69. package/dist/domain/mcp/feishu/index.d.ts +6 -0
  70. package/dist/domain/mcp/feishu/index.js +61 -0
  71. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +40 -0
  72. package/dist/domain/mcp/feishu/markdown-to-blocks.js +191 -0
  73. package/dist/domain/mcp/feishu/sheets.d.ts +3 -0
  74. package/dist/domain/mcp/feishu/sheets.js +119 -0
  75. package/dist/domain/mcp/feishu/types.d.ts +26 -0
  76. package/dist/domain/mcp/feishu/types.js +38 -0
  77. package/dist/domain/mcp/feishu/user-auth.d.ts +140 -0
  78. package/dist/domain/mcp/feishu/user-auth.js +286 -0
  79. package/dist/domain/mcp/feishu/wiki.d.ts +3 -0
  80. package/dist/domain/mcp/feishu/wiki.js +77 -0
  81. package/dist/domain/mcp/feishu-server.d.ts +2 -0
  82. package/dist/domain/mcp/feishu-server.js +33 -0
  83. package/dist/domain/mcp/server.d.ts +0 -1
  84. package/dist/domain/mcp/server.js +6 -25
  85. package/dist/domain/mcp/slack-server.d.ts +3 -0
  86. package/dist/domain/mcp/slack-server.js +46 -0
  87. package/dist/domain/mcp/tools/context.js +1 -1
  88. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  89. package/dist/domain/mcp/tools/schedule.js +6 -20
  90. package/dist/domain/mcp/tools/slack.js +20 -7
  91. package/dist/domain/mcp/tools/thread-ops.d.ts +2 -0
  92. package/dist/domain/mcp/tools/thread-ops.js +121 -0
  93. package/dist/domain/mcp/tools/time.d.ts +2 -0
  94. package/dist/domain/mcp/tools/time.js +66 -0
  95. package/dist/domain/mcp/tools/tui-ask.js +1 -1
  96. package/dist/domain/mcp/tools/tui-plan.js +2 -2
  97. package/dist/domain/mcp/tui-server.js +1 -0
  98. package/dist/domain/monitor/disk-monitor.js +2 -1
  99. package/dist/domain/monitor/gpu-monitor.js +2 -1
  100. package/dist/domain/remote/client-hot-reload.js +3 -2
  101. package/dist/domain/remote/client-manager.js +8 -6
  102. package/dist/domain/scheduling/job-registry.d.ts +4 -0
  103. package/dist/domain/scheduling/job-registry.js +1 -0
  104. package/dist/domain/scheduling/jobs/_shared.js +2 -1
  105. package/dist/domain/scheduling/jobs/memory-index-regen.js +3 -2
  106. package/dist/domain/scheduling/jobs/scheduled-task.js +9 -23
  107. package/dist/domain/scheduling/jobs/sync-public.js +4 -3
  108. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +1 -8
  109. package/dist/domain/scheduling/jobs/target-dispatch.js +0 -7
  110. package/dist/domain/scheduling/jobs/task-archive.js +3 -2
  111. package/dist/domain/scheduling/jobs/task-dispatch.js +120 -10
  112. package/dist/domain/scheduling/schedule-command.js +16 -15
  113. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  114. package/dist/domain/scheduling/scheduler.js +2 -1
  115. package/dist/domain/sessions/session-hooks.d.ts +2 -2
  116. package/dist/domain/sessions/session-hooks.js +19 -18
  117. package/dist/domain/sessions/session-lifecycle.d.ts +38 -0
  118. package/dist/domain/sessions/session-lifecycle.js +44 -0
  119. package/dist/domain/system/install-cli.d.ts +7 -0
  120. package/dist/domain/system/install-cli.js +106 -0
  121. package/dist/domain/system/server-update-check.js +2 -2
  122. package/dist/domain/tasks/dispatch-utils.d.ts +58 -1
  123. package/dist/domain/tasks/dispatch-utils.js +53 -4
  124. package/dist/domain/tasks/dispatcher.js +26 -0
  125. package/dist/domain/tasks/lint.js +28 -0
  126. package/dist/domain/tasks/mutator.d.ts +16 -3
  127. package/dist/domain/tasks/mutator.js +41 -12
  128. package/dist/domain/tasks/pending-tracker.js +6 -5
  129. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  130. package/dist/domain/tasks/system/task-cli.js +37 -6
  131. package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
  132. package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
  133. package/dist/domain/tasks/system/task-mutations.js +166 -8
  134. package/dist/domain/threads/contract.d.ts +17 -0
  135. package/dist/domain/threads/contract.js +59 -0
  136. package/dist/domain/threads/hook-runner.js +7 -6
  137. package/dist/domain/threads/index.d.ts +2 -0
  138. package/dist/domain/threads/index.js +3 -1
  139. package/dist/domain/threads/prompt-builder.d.ts +15 -1
  140. package/dist/domain/threads/prompt-builder.js +41 -2
  141. package/dist/domain/threads/runner.d.ts +6 -5
  142. package/dist/domain/threads/runner.js +128 -79
  143. package/dist/domain/threads/state-machine.d.ts +23 -21
  144. package/dist/domain/threads/state-machine.js +113 -54
  145. package/dist/domain/threads/template-loader.js +3 -2
  146. package/dist/domain/threads/tree.d.ts +45 -0
  147. package/dist/domain/threads/tree.js +171 -0
  148. package/dist/domain/tui-session/index.d.ts +2 -0
  149. package/dist/domain/tui-session/index.js +3 -0
  150. package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
  151. package/dist/domain/tui-session/tui-session-service.js +103 -0
  152. package/dist/domain/tui-session/types.d.ts +67 -0
  153. package/dist/domain/tui-session/types.js +4 -0
  154. package/dist/domain/ui-service/index.d.ts +5 -0
  155. package/dist/domain/ui-service/index.js +3 -0
  156. package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
  157. package/dist/domain/ui-service/mutate/executions.js +15 -0
  158. package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
  159. package/dist/domain/ui-service/mutate/schedules.js +39 -0
  160. package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
  161. package/dist/domain/ui-service/mutate/tasks.js +59 -0
  162. package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
  163. package/dist/domain/ui-service/mutate/threads.js +21 -0
  164. package/dist/domain/ui-service/query/cost.d.ts +3 -0
  165. package/dist/domain/ui-service/query/cost.js +6 -0
  166. package/dist/domain/ui-service/query/executions.d.ts +2 -0
  167. package/dist/domain/ui-service/query/executions.js +35 -0
  168. package/dist/domain/ui-service/query/projects.d.ts +2 -0
  169. package/dist/domain/ui-service/query/projects.js +30 -0
  170. package/dist/domain/ui-service/query/schedules.d.ts +2 -0
  171. package/dist/domain/ui-service/query/schedules.js +23 -0
  172. package/dist/domain/ui-service/query/sessions.d.ts +2 -0
  173. package/dist/domain/ui-service/query/sessions.js +35 -0
  174. package/dist/domain/ui-service/query/tasks.d.ts +2 -0
  175. package/dist/domain/ui-service/query/tasks.js +30 -0
  176. package/dist/domain/ui-service/query/threads.d.ts +2 -0
  177. package/dist/domain/ui-service/query/threads.js +27 -0
  178. package/dist/domain/ui-service/subscribe.d.ts +5 -0
  179. package/dist/domain/ui-service/subscribe.js +118 -0
  180. package/dist/domain/ui-service/types.d.ts +237 -0
  181. package/dist/domain/ui-service/types.js +5 -0
  182. package/dist/domain/ui-service/ui-service.d.ts +2 -0
  183. package/dist/domain/ui-service/ui-service.js +83 -0
  184. package/dist/entry/app.js +94 -5
  185. package/dist/entry/cli.d.ts +12 -0
  186. package/dist/entry/cli.js +122 -12
  187. package/dist/entry/feishu-login.d.ts +28 -0
  188. package/dist/entry/feishu-login.js +218 -0
  189. package/dist/entry/init.d.ts +25 -2
  190. package/dist/entry/init.js +211 -64
  191. package/dist/events/event-types.d.ts +14 -0
  192. package/dist/hooks/cortex-md-injector.mjs +47 -31
  193. package/dist/hooks/post-task-hook.mjs +6 -0
  194. package/dist/hooks/task-status-check.mjs +8 -0
  195. package/dist/orchestration/agent-runner.d.ts +2 -1
  196. package/dist/orchestration/agent-runner.js +55 -55
  197. package/dist/orchestration/conduit-queue.d.ts +18 -0
  198. package/dist/orchestration/conduit-queue.js +32 -0
  199. package/dist/orchestration/conversation-runner.d.ts +48 -0
  200. package/dist/orchestration/conversation-runner.js +109 -0
  201. package/dist/orchestration/dispatch-reconciler.js +8 -1
  202. package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
  203. package/dist/orchestration/interactions/ask-user-question.js +3 -3
  204. package/dist/orchestration/interactions/interaction-handlers.js +48 -17
  205. package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
  206. package/dist/orchestration/interactions/plan-handler.js +4 -3
  207. package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
  208. package/dist/orchestration/interactions/update-prompt.js +100 -0
  209. package/dist/orchestration/lifecycle.d.ts +4 -4
  210. package/dist/orchestration/lifecycle.js +24 -22
  211. package/dist/orchestration/orchestrator.d.ts +1 -1
  212. package/dist/orchestration/routing/commands/cancel.js +39 -47
  213. package/dist/orchestration/routing/commands/channel.js +24 -11
  214. package/dist/orchestration/routing/commands/cost.js +2 -1
  215. package/dist/orchestration/routing/commands/device.js +3 -2
  216. package/dist/orchestration/routing/commands/dispatch.js +6 -5
  217. package/dist/orchestration/routing/commands/index.d.ts +1 -1
  218. package/dist/orchestration/routing/commands/index.js +11 -10
  219. package/dist/orchestration/routing/commands/mode.js +19 -18
  220. package/dist/orchestration/routing/commands/nvtop.js +10 -9
  221. package/dist/orchestration/routing/commands/sendfile.js +7 -6
  222. package/dist/orchestration/routing/commands/session.d.ts +1 -1
  223. package/dist/orchestration/routing/commands/session.js +17 -33
  224. package/dist/orchestration/routing/commands/tail.js +4 -3
  225. package/dist/orchestration/routing/commands/task.js +4 -3
  226. package/dist/orchestration/routing/commands/thread-handlers.js +16 -6
  227. package/dist/orchestration/routing/edit-handler.js +8 -7
  228. package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
  229. package/dist/orchestration/routing/message-router.d.ts +1 -1
  230. package/dist/orchestration/routing/message-router.js +9 -9
  231. package/dist/orchestration/routing/webhook.js +233 -2
  232. package/dist/orchestration/status-helpers.d.ts +5 -1
  233. package/dist/orchestration/status-helpers.js +7 -6
  234. package/dist/orchestration/thread-callback.d.ts +67 -0
  235. package/dist/orchestration/thread-callback.js +465 -0
  236. package/dist/orchestration/thread-executor.d.ts +22 -1
  237. package/dist/orchestration/thread-executor.js +85 -36
  238. package/dist/platform/adapter.d.ts +6 -2
  239. package/dist/platform/adapters/composite-adapter.d.ts +89 -0
  240. package/dist/platform/adapters/composite-adapter.js +318 -0
  241. package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
  242. package/dist/platform/adapters/feishu-output-stream.js +274 -36
  243. package/dist/platform/adapters/feishu.d.ts +50 -5
  244. package/dist/platform/adapters/feishu.js +370 -116
  245. package/dist/platform/adapters/index.d.ts +24 -3
  246. package/dist/platform/adapters/index.js +89 -11
  247. package/dist/platform/adapters/project-conduits.d.ts +9 -0
  248. package/dist/platform/adapters/project-conduits.js +42 -0
  249. package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
  250. package/dist/platform/adapters/slack-project-conduits.js +6 -40
  251. package/dist/platform/adapters/slack.d.ts +9 -2
  252. package/dist/platform/adapters/slack.js +83 -39
  253. package/dist/platform/adapters/tui/index.d.ts +9 -0
  254. package/dist/platform/adapters/tui/index.js +10 -0
  255. package/dist/platform/adapters/tui/ports.d.ts +20 -0
  256. package/dist/platform/adapters/tui/ports.js +4 -0
  257. package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
  258. package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
  259. package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
  260. package/dist/platform/adapters/tui/tui-connection.js +53 -0
  261. package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
  262. package/dist/platform/adapters/tui/tui-gateway.js +919 -0
  263. package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
  264. package/dist/platform/adapters/tui/tui-notifications.js +60 -0
  265. package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
  266. package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
  267. package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
  268. package/dist/platform/adapters/tui/tui-transcript.js +56 -0
  269. package/dist/platform/index.d.ts +1 -0
  270. package/dist/platform/index.js +2 -1
  271. package/dist/platform/interactive-builder.js +3 -2
  272. package/dist/platform/output-stream.d.ts +5 -0
  273. package/dist/platform/testing.d.ts +7 -11
  274. package/dist/platform/testing.js +18 -15
  275. package/dist/platform/tool-trace.js +15 -5
  276. package/dist/platform/tui/protocol.d.ts +355 -0
  277. package/dist/platform/tui/protocol.js +199 -0
  278. package/dist/platform/types.d.ts +12 -3
  279. package/dist/store/execution-repo.d.ts +6 -1
  280. package/dist/store/execution-repo.js +13 -3
  281. package/dist/store/hook-sync.d.ts +18 -0
  282. package/dist/store/hook-sync.js +92 -0
  283. package/dist/store/outbound-queue.js +2 -2
  284. package/dist/store/profile-repo.js +3 -2
  285. package/dist/store/schedule-repo.d.ts +1 -8
  286. package/dist/store/session-registry-repo.d.ts +9 -1
  287. package/dist/store/session-registry-repo.js +19 -3
  288. package/dist/store/session-repo.d.ts +14 -0
  289. package/dist/store/session-repo.js +23 -0
  290. package/dist/store/thread-repo.d.ts +3 -0
  291. package/dist/store/thread-repo.js +49 -2
  292. package/dist/store/version-migrations.js +95 -0
  293. package/dist/tui/App.d.ts +27 -0
  294. package/dist/tui/App.js +219 -0
  295. package/dist/tui/components/AskUserModal.d.ts +11 -0
  296. package/dist/tui/components/AskUserModal.js +364 -0
  297. package/dist/tui/components/ConfirmModal.d.ts +12 -0
  298. package/dist/tui/components/ConfirmModal.js +31 -0
  299. package/dist/tui/components/Dashboard.d.ts +23 -0
  300. package/dist/tui/components/Dashboard.js +80 -0
  301. package/dist/tui/components/DashboardCostTab.d.ts +7 -0
  302. package/dist/tui/components/DashboardCostTab.js +16 -0
  303. package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
  304. package/dist/tui/components/DashboardExecutionsTab.js +94 -0
  305. package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
  306. package/dist/tui/components/DashboardSchedulesTab.js +124 -0
  307. package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
  308. package/dist/tui/components/DashboardTasksTab.js +200 -0
  309. package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
  310. package/dist/tui/components/DashboardThreadsTab.js +81 -0
  311. package/dist/tui/components/Header.d.ts +11 -0
  312. package/dist/tui/components/Header.js +5 -0
  313. package/dist/tui/components/InputBox.d.ts +10 -0
  314. package/dist/tui/components/InputBox.js +19 -0
  315. package/dist/tui/components/MessageRow.d.ts +7 -0
  316. package/dist/tui/components/MessageRow.js +10 -0
  317. package/dist/tui/components/Notifications.d.ts +19 -0
  318. package/dist/tui/components/Notifications.js +72 -0
  319. package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
  320. package/dist/tui/components/PlanFeedbackModal.js +161 -0
  321. package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
  322. package/dist/tui/components/ProjectSwitcher.js +43 -0
  323. package/dist/tui/components/SessionPicker.d.ts +14 -0
  324. package/dist/tui/components/SessionPicker.js +34 -0
  325. package/dist/tui/components/SidePanel.d.ts +19 -0
  326. package/dist/tui/components/SidePanel.js +8 -0
  327. package/dist/tui/components/StatusLine.d.ts +10 -0
  328. package/dist/tui/components/StatusLine.js +29 -0
  329. package/dist/tui/components/Transcript.d.ts +13 -0
  330. package/dist/tui/components/Transcript.js +56 -0
  331. package/dist/tui/hooks/useDashboardData.d.ts +32 -0
  332. package/dist/tui/hooks/useDashboardData.js +104 -0
  333. package/dist/tui/hooks/useKeybindings.d.ts +19 -0
  334. package/dist/tui/hooks/useKeybindings.js +87 -0
  335. package/dist/tui/hooks/useMutate.d.ts +22 -0
  336. package/dist/tui/hooks/useMutate.js +56 -0
  337. package/dist/tui/hooks/useNotifications.d.ts +28 -0
  338. package/dist/tui/hooks/useNotifications.js +70 -0
  339. package/dist/tui/hooks/useTranscript.d.ts +39 -0
  340. package/dist/tui/hooks/useTranscript.js +265 -0
  341. package/dist/tui/hooks/useWsClient.d.ts +29 -0
  342. package/dist/tui/hooks/useWsClient.js +69 -0
  343. package/dist/tui/index.d.ts +2 -0
  344. package/dist/tui/index.js +210 -0
  345. package/dist/tui/logic.d.ts +16 -0
  346. package/dist/tui/logic.js +49 -0
  347. package/dist/tui/render/markdown.d.ts +10 -0
  348. package/dist/tui/render/markdown.js +38 -0
  349. package/dist/tui/render/rich-blocks.d.ts +11 -0
  350. package/dist/tui/render/rich-blocks.js +24 -0
  351. package/dist/tui/ws-client.d.ts +44 -0
  352. package/dist/tui/ws-client.js +157 -0
  353. package/package.json +11 -3
  354. package/dist/orchestration/channel-queue.d.ts +0 -18
  355. package/dist/orchestration/channel-queue.js +0 -32
package/dist/entry/app.js CHANGED
@@ -5,7 +5,7 @@
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';
8
+ import { createAdapterFromEnv, extractTuiAdapter } from '../platform/index.js';
9
9
  import { WORKSPACE_DIR, CONFIG_DIR } from '../core/utils.js';
10
10
  import { closeAllSessions, closeSession as closeClaudePooledSession, shutdownCodex } from '../domain/agents/index.js';
11
11
  import { closeAllAdapters } from '../agent-adapter/index.js';
@@ -16,6 +16,7 @@ import * as executionRegistry from '../domain/executions/registry.js';
16
16
  import { initHookBridge } from '../orchestration/routing/hook-bridge.js';
17
17
  import { registerCommands } from '../orchestration/routing/commands/index.js';
18
18
  import { taskStore } from '../domain/tasks/store.js';
19
+ import { taskMutator } from '../domain/tasks/mutator.js';
19
20
  import { projectDirRepo } from '../store/project-dir-repo.js';
20
21
  import { projectStore } from '../domain/projects/index.js';
21
22
  import { sendStartupDmIfConfigured } from './startup-notify.js';
@@ -24,7 +25,7 @@ import { startClientManager, stopClientManager, startAllRemoteClients } from '..
24
25
  import { checkAndUpdateClients, formatUpdateSlackMessage } from '../domain/remote/client-hot-reload.js';
25
26
  import { checkServerUpdate } from '../domain/system/server-update-check.js';
26
27
  import { threadStore } from '../store/thread-repo.js';
27
- import { sessionRepo } from '../store/session-repo.js';
28
+ import { sessionRepo, registerConduitProvider } from '../store/session-repo.js';
28
29
  import { conversationLedger } from '../store/conversation-ledger-repo.js';
29
30
  import { executionRepo } from '../store/execution-repo.js';
30
31
  import { loadConfig as loadThreadConfig, startConfigWatcher as startThreadConfigWatcher, setAdminNotifier as setConfigNotifier } from '../domain/threads/index.js';
@@ -40,14 +41,17 @@ import { busyTracker } from '../orchestration/busy-tracker.js';
40
41
  import { buildExecutionStatusReport } from '../orchestration/status-helpers.js';
41
42
  import { reprocessMessage } from '../orchestration/lifecycle.js';
42
43
  import { initScheduledRunner, createScheduler, setSchedulerRef, setBus, setInteractiveCallbacksFactory, cancelDispatchedTask } from '../domain/scheduling/runner.js';
44
+ import { recoverWaitingThreads, registerTaskTreeSubscribers, reconcileWaitingTasks } from '../orchestration/thread-callback.js';
45
+ import { ctx as jobCtx } from '../domain/scheduling/job-registry.js';
43
46
  import { buildInteractiveCallbacks } from '../orchestration/agent-runner.js';
44
47
  import { registerInteractionHandlers, initInteractionHandlers } from '../orchestration/interactions/interaction-handlers.js';
45
48
  import { CommandActionRouter } from '../orchestration/interactions/command-action-router.js';
46
- import { createSlackUpdatePrompt } from '../orchestration/interactions/update-prompt-slack.js';
49
+ import { createUpdatePrompt } from '../orchestration/interactions/update-prompt.js';
47
50
  import { registerMessageHandler } from '../orchestration/routing/message-router.js';
48
51
  import { initRateLimitThrottle } from '../domain/costs/rate-limit-throttle.js';
49
52
  import { scheduleRepo } from '../store/schedule-repo.js';
50
53
  import { runMigrations } from '../store/version-migrations.js';
54
+ import { syncManagedHooks } from '../store/hook-sync.js';
51
55
  import { costRepo } from '../store/cost-repo.js';
52
56
  import { profileRepo, startProfileWatcher, setAdminNotifier as setProfileNotifier } from '../store/profile-repo.js';
53
57
  import { sessionStore } from '../store/session-registry-repo.js';
@@ -59,8 +63,44 @@ import { registerHookBridgeSubscribers } from '../orchestration/routing/hook-bri
59
63
  import { startDispatchReconciler } from '../orchestration/dispatch-reconciler.js';
60
64
  import { ensurePIAgentDirs } from '../agent-adapter/pi/agent-dir.js';
61
65
  import { initOutboundQueue } from '../store/outbound-queue.js';
66
+ import { createUiService } from '../domain/ui-service/index.js';
67
+ import { createTuiSessionService } from '../domain/tui-session/index.js';
68
+ import { enqueue, conduitQueues } from '../orchestration/conduit-queue.js';
69
+ import { getCostSummary } from '../domain/costs/cost-tracker.js';
62
70
  dotenv.config({ path: path.join(CONFIG_DIR, '.env') });
63
71
  const log = createLogger('app');
72
+ // --- Crash safety net ---
73
+ // A single failed outbound post while handling an inbound message must never take
74
+ // down the whole server. Detached per-conduit queue work (conduit-queue.ts) and
75
+ // platform-adapter callbacks can reject without an observer; without these
76
+ // handlers an unhandled rejection terminates the process (exit code 1). Log the
77
+ // full stack and keep running. Mirrors the daemon's own guards (daemon.ts).
78
+ // Re-entrancy guard prevents an infinite loop if log.error() itself throws.
79
+ let _inExceptionHandler = false;
80
+ process.on('unhandledRejection', (reason) => {
81
+ if (_inExceptionHandler)
82
+ return;
83
+ _inExceptionHandler = true;
84
+ try {
85
+ log.error(`unhandledRejection: ${reason instanceof Error ? reason.stack : String(reason)}`);
86
+ }
87
+ catch { /* swallow secondary failure */ }
88
+ finally {
89
+ _inExceptionHandler = false;
90
+ }
91
+ });
92
+ process.on('uncaughtException', (err) => {
93
+ if (_inExceptionHandler)
94
+ return;
95
+ _inExceptionHandler = true;
96
+ try {
97
+ log.error(`uncaughtException: ${err?.stack ?? err}`);
98
+ }
99
+ catch { /* swallow secondary failure */ }
100
+ finally {
101
+ _inExceptionHandler = false;
102
+ }
103
+ });
64
104
  // --- EventBus + logger ---
65
105
  const bus = new EventBus();
66
106
  createEventLogger(bus);
@@ -68,6 +108,7 @@ initHookBridge(bus); // S5: wire hook-bridge to publish ask-user.requested / pla
68
108
  runningExecutions.setBus(bus); // S6-A: wire lifecycle events
69
109
  planApprovals.setBus(bus); // S6-A: wire plan.approved events
70
110
  busyTracker.setBus(bus); // S6-C: wire busy/idle IPC through event bus
111
+ taskMutator.setBus(bus); // c39d: wire task lifecycle events
71
112
  initInteractionHandlers(bus); // BLK-1: wire ask-user.answered publisher
72
113
  const TEMP_DIR = WORKSPACE_DIR;
73
114
  mkdirSync(TEMP_DIR, { recursive: true });
@@ -78,6 +119,20 @@ loadMachinesFromFile();
78
119
  startMachineRegistryWatcher();
79
120
  // --- Create platform adapter (replaces direct Slack App instantiation) ---
80
121
  const adapter = createAdapterFromEnv();
122
+ // Wire EventBus + injected dependencies into the TUI gateway before start() so it can
123
+ // subscribe to bus events and resolve sessions during its own start()/handshake lifecycle.
124
+ const tuiGateway = extractTuiAdapter(adapter);
125
+ if (tuiGateway) {
126
+ tuiGateway.setBus(bus);
127
+ // Session lifecycle service (transport-agnostic; gateway delegates handshake/switch to it).
128
+ tuiGateway.setSessionService(createTuiSessionService({ sessionStore, conversationLedger }));
129
+ // Conduit-queue port — MUST wrap the shared @orch/conduit-queue singletons so TUI message
130
+ // work serializes with the rest of the pipeline on the same conduit key.
131
+ tuiGateway.setConduitQueue({ enqueue, remove: (id) => conduitQueues.delete(id) });
132
+ // Conduit provider inversion: store-layer session lookup resolves ephemeral TUI conduits
133
+ // via the gateway's in-memory state (previously the gateway imported the store directly).
134
+ registerConduitProvider((conduitId) => tuiGateway.lookupConduit(conduitId));
135
+ }
81
136
  // --- Wire hot-reload admin notifiers ---
82
137
  const notifyAdmin = (text) => {
83
138
  adapter.postMessage({ type: 'system-notice' }, { text }).catch(() => { });
@@ -107,7 +162,7 @@ const dispatchCommand = registerCommands({
107
162
  commandRouter,
108
163
  });
109
164
  // DR-0013: wire Slack update prompt BEFORE bindToAdapter (router has no unregister API)
110
- const updatePrompt = createSlackUpdatePrompt(adapter, commandRouter);
165
+ const updatePrompt = createUpdatePrompt(adapter, commandRouter);
111
166
  // Bind command action handlers (buttons, modals) to the platform adapter
112
167
  commandRouter.bindToAdapter(adapter);
113
168
  const handleMessageEdit = createEditHandler({
@@ -159,6 +214,9 @@ process.on('SIGTERM', async () => {
159
214
  cleanupLogs();
160
215
  ensureMcpConfig();
161
216
  await runMigrations();
217
+ // Refresh version-stamped hooks in DATA_DIR/hooks from the shipped defaults. init's deployHooks
218
+ // only copies-if-missing, so without this an existing install never picks up hook code fixes.
219
+ await syncManagedHooks();
162
220
  // DR-0012 §3.6: clean up orphan TUI tmux sessions from a previous agent-server lifetime.
163
221
  // We can't re-adopt them (sessionKey↔tmux mapping was never persisted) so the honest move
164
222
  // is to kill any leftovers — otherwise a later session that reuses the same sessionId will
@@ -173,7 +231,28 @@ process.on('SIGTERM', async () => {
173
231
  log.warn(`Startup: recoverTuiOrphans failed: ${e.message}`);
174
232
  }
175
233
  executionRepo.load();
176
- await executionRegistry.markMissingRunningExecutionsStale((record) => record.kind === 'dispatch');
234
+ // Keep only REMOTE dispatch running across restart (it runs on another machine/tmux and
235
+ // survives). An in-process dispatch (dispatch=null / machine 'local') dies with the server, so
236
+ // stale it immediately — otherwise its 'running' record poisons a dispatch concurrency slot
237
+ // until the reconciler's next tick.
238
+ await executionRegistry.markMissingRunningExecutionsStale((record) => record.kind === 'dispatch' && !!record.dispatch?.machine && record.dispatch.machine !== 'local');
239
+ // ── Wire UI service into the TUI gateway ────────────────────────────────
240
+ //
241
+ // UI service (M3) provides store-backed query/mutate/subscribe capabilities
242
+ // to the TUI gateway via a transport-agnostic facade.
243
+ const uiService = createUiService({
244
+ projectStore,
245
+ sessionStore,
246
+ threadStore,
247
+ taskStore,
248
+ scheduler,
249
+ executionRegistry,
250
+ runningExecutions,
251
+ costSummary: getCostSummary,
252
+ bus,
253
+ adapter,
254
+ });
255
+ extractTuiAdapter(adapter)?.setUiService(uiService);
177
256
  await adapter.start();
178
257
  try {
179
258
  const notified = await sendStartupDmIfConfigured(adapter, {
@@ -273,5 +352,15 @@ process.on('SIGTERM', async () => {
273
352
  registerHookBridgeSubscribers(bus, adapter, planApprovals);
274
353
  startMemoryWatcher();
275
354
  startDispatchReconciler();
355
+ // DR-0014: re-deliver child results that turned terminal while the server was down and
356
+ // DR-0014 §8: wake suspended manager threads on child-task terminal events, and let the
357
+ // dispatch path close the suspension race window without a domain→orchestration import.
358
+ registerTaskTreeSubscribers(bus);
359
+ jobCtx.onThreadSuspended = (threadId) => reconcileWaitingTasks(threadId);
360
+ // resume suspended parents. Runs last — needs jobCtx.adapter and the thread system ready.
361
+ // (markRunningAsFailedOnStartup above already failed all in-flight children, so every
362
+ // awaited child THREAD is terminal or missing by now; child TASKS are reconciled
363
+ // against disk and stay awaited while open.)
364
+ recoverWaitingThreads().catch((e) => log.error(`recoverWaitingThreads failed: ${e.message}`));
276
365
  log.info(`Cortex agent is running (${adapter.name}) — backend: ${getActiveBackend()}`);
277
366
  })();
@@ -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)
@@ -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>;