@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
@@ -1,8 +1,9 @@
1
1
  // input: @clack/prompts, fs, path, os, yaml, @core/config-generator
2
2
  // output: runInit — interactive CORTEX_HOME initialization
3
- // pos: cortex init subcommand — backend selection & install, gateway usage opt-in,
4
- // creates directory structure, generates .env, copies default configs,
5
- // auto-generates mcp-config.json and mode.json
3
+ // pos: cortex init subcommand — backend selection & install, multi-select interaction
4
+ // platforms (Slack/Feishu, walked one-by-one), gateway usage opt-in,
5
+ // creates directory structure, generates .env (CORTEX_PLATFORM as a comma list),
6
+ // copies default configs, auto-generates mcp-config.json and mode.json
6
7
  //
7
8
  // INSTALL_ROOT is computed from import.meta.url (agent-server dir, 2 levels up from dist/entry/).
8
9
  // DATA_DIR is resolved via the --home arg, $CORTEX_HOME env, or ~/.cortex/ default.
@@ -17,11 +18,12 @@ import { stdin as processStdin } from 'process';
17
18
  import * as clack from '@clack/prompts';
18
19
  import * as yaml from 'yaml';
19
20
  import { buildFullConfig, buildCoreConfig, buildTuiConfig } from '../core/config-generator.js';
20
- import { discoverEndpoints, generateGatewayYaml, writeGatewayYaml } from '../core/gateway-generator.js';
21
+ import { discoverEndpoints, writeMergedGatewayYaml, validateProfilesAgainstGateway } from '../core/gateway-generator.js';
21
22
  import { generateProfiles, writeProfilesJson, listChoices } from '../core/profile-generator.js';
22
23
  import { mergeThreadTemplates } from '../domain/threads/index.js';
23
24
  import { createLogger } from '../core/log.js';
24
25
  import { INSTALL_ROOT, DEFAULTS_DIR } from '../core/utils.js';
26
+ import { cmdFeishu } from './feishu-login.js';
25
27
  // ─── Path computation (DATA_DIR resolved locally to support --home override) ──
26
28
  const log = createLogger('init');
27
29
  // MODULE_DIR kept for any consumers that still derive paths locally; the canonical roots
@@ -61,6 +63,21 @@ function parseChoiceLine(raw) {
61
63
  model: trimmed.substring(colonIdx + 1).trim(),
62
64
  };
63
65
  }
66
+ /** Parse comma-separated "mode:model" pairs for extra profiles. Returns undefined for empty. */
67
+ function parseExtraProfilesLine(raw) {
68
+ if (!raw)
69
+ return undefined;
70
+ const trimmed = raw.trim();
71
+ if (!trimmed)
72
+ return undefined;
73
+ const choices = [];
74
+ for (const part of trimmed.split(',')) {
75
+ const choice = parseChoiceLine(part.trim());
76
+ if (choice)
77
+ choices.push(choice);
78
+ }
79
+ return choices.length > 0 ? choices : undefined;
80
+ }
64
81
  // ─── Dot env generation ──────────────────────────────────────────
65
82
  /** Generate .env content — includes CORTEX_MACHINE, CORTEX_PLATFORM, and platform-specific tokens. */
66
83
  export function generateDotEnvContent(answers) {
@@ -70,10 +87,13 @@ export function generateDotEnvContent(answers) {
70
87
  '',
71
88
  `CORTEX_MACHINE=${answers.machineName}`,
72
89
  ];
73
- if (answers.platform && answers.platform !== 'none') {
74
- lines.push(`CORTEX_PLATFORM=${answers.platform}`);
90
+ // CORTEX_PLATFORM is a comma-separated list (runtime composes adapters via CompositeAdapter).
91
+ // Each platform's token block is emitted independently when its config is present, so a
92
+ // multi-select (e.g. slack + feishu) produces both blocks.
93
+ if (answers.platforms.length > 0) {
94
+ lines.push(`CORTEX_PLATFORM=${answers.platforms.join(',')}`);
75
95
  lines.push('');
76
- if (answers.platform === 'slack' && answers.slackConfig) {
96
+ if (answers.slackConfig) {
77
97
  lines.push('# Slack configuration');
78
98
  lines.push(`SLACK_BOT_TOKEN=${answers.slackConfig.botToken}`);
79
99
  lines.push(`SLACK_SIGNING_SECRET=${answers.slackConfig.signingSecret}`);
@@ -81,8 +101,9 @@ export function generateDotEnvContent(answers) {
81
101
  if (answers.slackConfig.adminChannel) {
82
102
  lines.push(`CORTEX_ADMIN_CHANNEL=${answers.slackConfig.adminChannel}`);
83
103
  }
104
+ lines.push('');
84
105
  }
85
- else if (answers.platform === 'feishu' && answers.feishuConfig) {
106
+ if (answers.feishuConfig) {
86
107
  lines.push('# Feishu configuration');
87
108
  lines.push(`FEISHU_APP_ID=${answers.feishuConfig.appId}`);
88
109
  lines.push(`FEISHU_APP_SECRET=${answers.feishuConfig.appSecret}`);
@@ -95,6 +116,9 @@ export function generateDotEnvContent(answers) {
95
116
  if (answers.feishuConfig.domain) {
96
117
  lines.push(`FEISHU_DOMAIN=${answers.feishuConfig.domain}`);
97
118
  }
119
+ // Identity for MCP doc operations (binary, no fallback). Messaging is always bot.
120
+ // user mode authorizes via `cortex feishu login` (OAuth device flow) — no redirect URI.
121
+ lines.push(`FEISHU_AUTH_MODE=${answers.feishuConfig.authMode ?? 'bot'}`);
98
122
  }
99
123
  }
100
124
  lines.push('');
@@ -642,10 +666,14 @@ async function collectFeishuConfig() {
642
666
  'To set up Feishu (飞书), create a Feishu app:',
643
667
  '',
644
668
  '1. Go to https://open.feishu.cn/app',
645
- '2. Create a new app with bot capability enabled',
646
- '3. Get App ID and App Secret from "Credentials & Basic Info"',
647
- '4. Enable bot events and subscribe to: im.message.receive_v1',
648
- '5. Publish the app and get it approved by your admin',
669
+ '2. Click "Create Agentic App" (创建agentic应用)',
670
+ '3. Enter agent name (e.g. CortexAgent), select an avatar, and click Create',
671
+ '4. After creation, the page will display App ID and App Secret — copy them directly',
672
+ '5. Enable bot events and subscribe to: im.message.receive_v1',
673
+ '',
674
+ 'Identity for MCP document operations (docx/wiki/bitable/sheets/drive):',
675
+ ' - bot: documents are created/owned by the app (default)',
676
+ ' - user: documents are created/owned by YOUR Feishu account (Recommended)',
649
677
  ].join('\n'), 'Feishu App Setup Guide');
650
678
  const appId = await clack.text({
651
679
  message: 'FEISHU_APP_ID:',
@@ -682,14 +710,52 @@ async function collectFeishuConfig() {
682
710
  const domain = (domainVal === 'feishu' || domainVal === 'lark')
683
711
  ? domainVal
684
712
  : undefined;
713
+ const authMode = await clack.select({
714
+ message: 'Identity for MCP document operations:',
715
+ options: [
716
+ { value: 'bot', label: 'bot', hint: 'documents owned by the app' },
717
+ { value: 'user', label: 'user (Recommended)', hint: 'documents owned by your Feishu account' },
718
+ ],
719
+ initialValue: 'user',
720
+ });
721
+ handleCancel(authMode);
685
722
  return {
686
723
  appId: appId,
687
724
  appSecret: appSecret,
688
725
  encryptKey: encryptKeyRaw.trim() || undefined,
689
726
  verificationToken: verificationTokenRaw.trim() || undefined,
690
727
  domain,
728
+ authMode: authMode,
691
729
  };
692
730
  }
731
+ /**
732
+ * Run the Feishu user-identity login inline during init (OAuth device-authorization flow).
733
+ * Invoked right after the operator selects authMode='user' so they authorize in one sitting
734
+ * instead of having to run `cortex feishu login` afterwards.
735
+ *
736
+ * Credentials are passed via deps.env (no .env on disk yet at questionnaire time), and the token
737
+ * is written next to the .env (CONFIG_DIR/feishu-user-token.json) so it matches the --home target
738
+ * even when that differs from the module-level CONFIG_DIR. Best-effort: returns the CliResult and
739
+ * never throws, so a failed/abandoned login does not abort init — the operator can retry later.
740
+ */
741
+ export async function runFeishuUserLogin(config, configDir, deps = {}) {
742
+ const cmd = deps.cmdFeishuImpl ?? cmdFeishu;
743
+ const out = deps.stdout ?? ((s) => process.stdout.write(s));
744
+ const env = {
745
+ ...process.env,
746
+ FEISHU_APP_ID: config.appId,
747
+ FEISHU_APP_SECRET: config.appSecret,
748
+ };
749
+ if (config.domain)
750
+ env.FEISHU_DOMAIN = config.domain;
751
+ const tokenFile = path.join(configDir, 'feishu-user-token.json');
752
+ const result = await cmd(['login'], { env, tokenFile, loadDotenv: false });
753
+ if (result.stdout)
754
+ out(result.stdout);
755
+ if (result.exitCode !== 0 && result.stderr)
756
+ out(result.stderr);
757
+ return result;
758
+ }
693
759
  async function collectAnswersInteractive(paths) {
694
760
  clack.intro('Cortex Setup');
695
761
  // Step 1: Backend selection
@@ -703,25 +769,42 @@ async function collectAnswersInteractive(paths) {
703
769
  required: true,
704
770
  });
705
771
  handleCancel(backends);
706
- // Step 2: Platform selection
707
- const platform = await clack.select({
708
- message: 'Which interaction platform would you like to use?',
772
+ // Step 2: Platform selection (multi-select — Slack and Feishu can run simultaneously).
773
+ // Leave empty to skip and configure platforms later by editing .env manually.
774
+ const platformsSel = await clack.multiselect({
775
+ message: 'Which interaction platform(s) would you like to use? (space to toggle, enter to confirm, leave empty to skip)',
709
776
  options: [
710
777
  { value: 'slack', label: 'Slack', hint: 'recommended' },
711
- { value: 'none', label: 'Skip — configure later manually' },
778
+ { value: 'feishu', label: 'Feishu (飞书)' },
712
779
  ],
780
+ required: false,
713
781
  });
714
- handleCancel(platform);
715
- // Step 2b: Platform-specific token input
782
+ handleCancel(platformsSel);
783
+ const platforms = platformsSel;
784
+ // Step 2b: Platform-specific setup & token input — walk each selected platform in turn,
785
+ // showing its creation guide and collecting its credentials one at a time.
716
786
  let slackConfig;
717
787
  let feishuConfig;
718
- if (platform === 'slack') {
788
+ if (platforms.includes('slack')) {
719
789
  const envPath = path.join(paths.CONFIG_DIR, '.env');
720
790
  const existingSlackConfig = parseExistingEnvSlackConfig(envPath);
721
791
  slackConfig = await collectSlackConfig(existingSlackConfig ?? undefined);
722
792
  }
723
- else if (platform === 'feishu') {
793
+ if (platforms.includes('feishu')) {
724
794
  feishuConfig = await collectFeishuConfig();
795
+ // user identity → continue straight into the device-flow login (rather than only printing a
796
+ // hint to run `cortex feishu login` later). Best-effort: a failed/abandoned login won't abort
797
+ // init — credentials are already captured in feishuConfig and the operator can retry.
798
+ if (feishuConfig.authMode === 'user') {
799
+ clack.log.info('Starting Feishu user login (OAuth device flow)...');
800
+ const res = await runFeishuUserLogin(feishuConfig, paths.CONFIG_DIR);
801
+ if (res.exitCode === 0) {
802
+ clack.log.success('Feishu user login complete.');
803
+ }
804
+ else {
805
+ clack.log.warn('Feishu user login did not complete. Retry later with `cortex feishu login`.');
806
+ }
807
+ }
725
808
  }
726
809
  // Step 3: Machine identity
727
810
  const hostname = os.hostname();
@@ -784,7 +867,7 @@ async function collectAnswersInteractive(paths) {
784
867
  backends: backends,
785
868
  machineName: machineName,
786
869
  gpuCount,
787
- platform: platform,
870
+ platforms,
788
871
  slackConfig,
789
872
  feishuConfig,
790
873
  gatewayUsage,
@@ -800,55 +883,64 @@ async function collectAnswersNonInteractive() {
800
883
  }
801
884
  // Line format:
802
885
  // backends, platform, gatewayEnabled, name, org, email, installService
803
- // [+ platform-specific tokens: signingSecret, appToken, botToken, adminChannel (slack)]
886
+ // [+ platform-specific token blocks, concatenated in fixed order: slack first, then feishu]
887
+ // `platform` is a comma-separated list (e.g. "slack,feishu"); single values are back-compat.
804
888
  const [backendsRaw, platformRaw, gatewayEnabledRaw, name, org, email, installServiceRaw] = lines;
805
889
  const backends = (backendsRaw || 'claude')
806
890
  .split(',')
807
891
  .map(s => s.trim())
808
892
  .filter((s) => s === 'claude' || s === 'pi');
809
- const platform = (platformRaw && ['slack', 'feishu'].includes(platformRaw))
810
- ? platformRaw
811
- : 'none';
893
+ // Parse the platform list, keeping valid values in order and de-duplicating.
894
+ const platforms = [];
895
+ const seenPlatforms = new Set();
896
+ for (const raw of (platformRaw || '').split(',')) {
897
+ const p = raw.trim().toLowerCase();
898
+ if ((p === 'slack' || p === 'feishu') && !seenPlatforms.has(p)) {
899
+ seenPlatforms.add(p);
900
+ platforms.push(p);
901
+ }
902
+ }
812
903
  const gatewayEnabled = gatewayEnabledRaw?.toLowerCase() === 'y';
813
904
  log.info('Cortex Initialization (non-interactive)');
814
- // Parse platform-specific tokens from remaining lines (starting at index 7).
815
- // After platform tokens, optional planChoice and executeChoice lines (format "mode:model";
816
- // empty string → auto-infer). Index varies by platform:
817
- // none → planChoice at 7, executeChoice at 8
818
- // slack → planChoice at 11, executeChoice at 12
819
- // feishu → planChoice at 12, executeChoice at 13
905
+ // Parse platform token blocks from remaining lines (starting at index 7). Blocks are
906
+ // concatenated in fixed order — slack (4 lines), then feishu (5 lines) — regardless of the
907
+ // order given in the platform list. The profile-choice lines (optional "mode:model"; empty
908
+ // → auto-infer) follow whatever token lines were consumed. Single-platform layouts are
909
+ // back-compatible: slack-only → choices at 11; feishu-only → choices at 12.
820
910
  let slackConfig;
821
911
  let feishuConfig;
822
- let profileChoiceStart = 7;
823
- if (platform === 'slack' && lines.length >= 11) {
912
+ let cursor = 7;
913
+ if (platforms.includes('slack') && lines.length >= cursor + 4) {
824
914
  slackConfig = {
825
- signingSecret: lines[7] || '',
826
- appToken: lines[8] || '',
827
- botToken: lines[9] || '',
828
- adminChannel: lines[10]?.trim() || undefined,
915
+ signingSecret: lines[cursor] || '',
916
+ appToken: lines[cursor + 1] || '',
917
+ botToken: lines[cursor + 2] || '',
918
+ adminChannel: lines[cursor + 3]?.trim() || undefined,
829
919
  };
830
- profileChoiceStart = 11;
920
+ cursor += 4;
831
921
  }
832
- else if (platform === 'feishu' && lines.length >= 12) {
833
- const domainVal = (lines[11] || '').trim().toLowerCase();
922
+ if (platforms.includes('feishu') && lines.length >= cursor + 5) {
923
+ const domainVal = (lines[cursor + 4] || '').trim().toLowerCase();
834
924
  feishuConfig = {
835
- appId: lines[7] || '',
836
- appSecret: lines[8] || '',
837
- encryptKey: lines[9]?.trim() || undefined,
838
- verificationToken: lines[10]?.trim() || undefined,
925
+ appId: lines[cursor] || '',
926
+ appSecret: lines[cursor + 1] || '',
927
+ encryptKey: lines[cursor + 2]?.trim() || undefined,
928
+ verificationToken: lines[cursor + 3]?.trim() || undefined,
839
929
  domain: (domainVal === 'feishu' || domainVal === 'lark')
840
930
  ? domainVal
841
931
  : undefined,
842
932
  };
843
- profileChoiceStart = 12;
933
+ cursor += 5;
844
934
  }
935
+ const profileChoiceStart = cursor;
845
936
  const planChoice = parseChoiceLine(lines[profileChoiceStart]);
846
937
  const executeChoice = parseChoiceLine(lines[profileChoiceStart + 1]);
938
+ const extraProfiles = parseExtraProfilesLine(lines[profileChoiceStart + 2]);
847
939
  return {
848
940
  backends: backends.length > 0 ? backends : ['claude'],
849
941
  machineName: os.hostname(),
850
942
  gpuCount: detectGpuCount(),
851
- platform,
943
+ platforms,
852
944
  slackConfig,
853
945
  feishuConfig,
854
946
  gatewayUsage: gatewayEnabled
@@ -857,6 +949,7 @@ async function collectAnswersNonInteractive() {
857
949
  installService: installServiceRaw?.toLowerCase() === 'y',
858
950
  planChoice,
859
951
  executeChoice,
952
+ extraProfiles,
860
953
  };
861
954
  }
862
955
  // ─── Directory creation ─────────────────────────────────────────
@@ -1222,17 +1315,32 @@ async function pickPlanExecuteInteractive(endpoints, configDir) {
1222
1315
  if (arr.length > 0)
1223
1316
  executeFallback = arr.map(parseValue);
1224
1317
  }
1318
+ // ── Extra profiles: additional models to register as standalone named profiles ──
1319
+ let extraProfiles;
1320
+ if (options.length > 0) {
1321
+ const sel = await clack.multiselect({
1322
+ message: 'Pick additional models to register as standalone profiles (profile name = model name, space to toggle, enter to confirm, leave empty to skip):',
1323
+ options,
1324
+ required: false,
1325
+ initialValues: [],
1326
+ });
1327
+ handleCancel(sel);
1328
+ const arr = sel;
1329
+ if (arr.length > 0)
1330
+ extraProfiles = arr.map(parseValue);
1331
+ }
1225
1332
  return {
1226
1333
  planChoice,
1227
1334
  executeChoice: execChoice,
1228
1335
  planFallback,
1229
1336
  executeFallback,
1337
+ extraProfiles,
1230
1338
  overwrite: true,
1231
1339
  };
1232
1340
  }
1233
1341
  async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1234
- // Discover endpoints from Claude/PI local configs
1235
- const endpoints = discoverEndpoints();
1342
+ // Discover endpoints from Claude/PI local configs — filtered by user-selected backends
1343
+ const endpoints = discoverEndpoints(backends);
1236
1344
  if (endpoints.length === 0) {
1237
1345
  clack.log.warn('No backends discovered. Make sure you have logged into Claude Code and/or PI first.');
1238
1346
  clack.log.info('You can re-run detection later with: cortex setup-gateway');
@@ -1242,15 +1350,22 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1242
1350
  const summary = endpoints.map(ep => ` ${ep.mode}/${ep.endpoint}: ${ep.models.slice(0, 3).join(', ')}${ep.models.length > 3 ? ', ...' : ''} (${ep.keys.length > 0 ? 'with key' : 'passthrough'})`).join('\n');
1243
1351
  clack.log.success(`Discovered ${endpoints.length} endpoint modes:\n${summary}`);
1244
1352
  // Generate gateway.yaml — scoped to gatewayConfigDir when provided (test/alt env),
1245
- // otherwise defaults to ~/.aistatus/gateway.yaml (production).
1246
- const yamlContent = generateGatewayYaml(endpoints);
1247
- const gatewayPath = writeGatewayYaml(yamlContent, gatewayConfigDir);
1353
+ // otherwise defaults to ~/.aistatus/gateway.yaml (production). Merge-aware: preserves
1354
+ // hand-maintained modes/keys and never drops previously-configured modes if discovery
1355
+ // under-reports (e.g. a transient `pi --list-models` failure).
1356
+ const { path: gatewayPath, result: mergeResult } = writeMergedGatewayYaml(endpoints, gatewayConfigDir);
1248
1357
  clack.log.success(`Gateway config written to ${gatewayPath}`);
1249
- // Resolve plan/execute choices + fallback chains + overwrite intent.
1358
+ if (mergeResult.droppedFromDiscovery.length > 0) {
1359
+ const list = mergeResult.droppedFromDiscovery.map(p => `${p.mode}/${p.endpoint}`).join(', ');
1360
+ clack.log.warn(`Preserved ${mergeResult.droppedFromDiscovery.length} existing gateway mode(s) that discovery did not report: ${list}`);
1361
+ clack.log.info('If these should have been auto-detected, check `pi /login` / `pi --list-models` and re-run.');
1362
+ }
1363
+ // Resolve plan/execute choices + fallback chains + extra profiles + overwrite intent.
1250
1364
  let planChoice = answers?.planChoice;
1251
1365
  let executeChoice = answers?.executeChoice;
1252
1366
  let planFallback;
1253
1367
  let executeFallback;
1368
+ let extraProfiles = answers?.extraProfiles;
1254
1369
  let overwrite;
1255
1370
  if (processStdin.isTTY) {
1256
1371
  // Interactive: prompt for selection (with overwrite confirmation if needed)
@@ -1259,6 +1374,7 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1259
1374
  executeChoice = picked.executeChoice ?? executeChoice;
1260
1375
  planFallback = picked.planFallback;
1261
1376
  executeFallback = picked.executeFallback;
1377
+ extraProfiles = picked.extraProfiles ?? extraProfiles;
1262
1378
  overwrite = picked.overwrite;
1263
1379
  }
1264
1380
  else {
@@ -1274,13 +1390,22 @@ async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
1274
1390
  executeChoice,
1275
1391
  planFallback,
1276
1392
  executeFallback,
1393
+ extraProfiles,
1277
1394
  overwrite,
1278
1395
  });
1279
1396
  clack.log.success(`Profiles written to ${profilesPath}`);
1280
1397
  // Show profile summary (reflects what was actually generated, not what was merged)
1281
- const profiles = generateProfiles(endpoints, { planChoice, executeChoice, planFallback, executeFallback });
1398
+ const profiles = generateProfiles(endpoints, { planChoice, executeChoice, planFallback, executeFallback, extraProfiles });
1282
1399
  const profileNames = Object.keys(profiles.profiles).join(', ');
1283
1400
  clack.log.info(`Generated profiles: ${profileNames} (default: ${profiles.defaultProfile})`);
1401
+ // Validate profile ↔ gateway mode coupling. A profile referencing a non-existent gateway mode is
1402
+ // exactly what produces a silent `400 Unknown mode: <x>` at runtime. Non-fatal — warn only.
1403
+ const issues = validateProfilesAgainstGateway(mergeResult.endpoints, paths.CONFIG_DIR);
1404
+ if (issues.length > 0) {
1405
+ const lines = issues.map(i => ` - ${i.profile}: ${i.reason}`).join('\n');
1406
+ clack.log.warn(`${issues.length} profile(s) reference a gateway mode that is not configured:\n${lines}`);
1407
+ clack.log.info('These would fail at runtime with "Unknown mode". Add the mode to gateway.yaml or fix the profile.');
1408
+ }
1284
1409
  }
1285
1410
  export async function runInit(options = {}) {
1286
1411
  const paths = getResolvedPaths(options.homeDir);
@@ -1309,23 +1434,45 @@ export async function runInit(options = {}) {
1309
1434
  }
1310
1435
  // 7. Gateway & profile auto-setup (detect from Claude/PI local configs)
1311
1436
  if (processStdin.isTTY) {
1437
+ const loginHints = answers.backends.map(b => {
1438
+ const info = BACKEND_INFO[b];
1439
+ return ` • ${info.label}: ${info.loginHint.replace(/^Run /, '').replace(/\.$/, '')}`;
1440
+ }).join('\n');
1312
1441
  clack.note([
1313
1442
  'Cortex can auto-detect your Claude Code and PI configurations',
1314
1443
  'to generate gateway.yaml and profiles.json automatically.',
1315
1444
  '',
1316
1445
  'Make sure you have logged into:',
1317
- ' • Claude Code: claude login',
1318
- ' • PI: pi login (if using PI)',
1446
+ loginHints,
1319
1447
  ].join('\n'), 'Gateway & Profile Setup');
1320
- const ready = await clack.confirm({
1321
- message: 'Have you logged into Claude Code and/or PI? Ready to auto-detect?',
1322
- initialValue: true,
1323
- });
1324
- if (!clack.isCancel(ready) && ready) {
1325
- await runGatewaySetup(answers.backends, paths, options.gatewayConfigDir, answers);
1326
- }
1327
- else {
1328
- clack.log.info('Skipped. Run `cortex setup-gateway` later to auto-configure.');
1448
+ let gatewayDone = false;
1449
+ while (!gatewayDone) {
1450
+ const ready = await clack.confirm({
1451
+ message: 'Have you logged in and are ready to auto-detect?',
1452
+ initialValue: true,
1453
+ });
1454
+ handleCancel(ready);
1455
+ if (ready) {
1456
+ await runGatewaySetup(answers.backends, paths, options.gatewayConfigDir, answers);
1457
+ gatewayDone = true;
1458
+ }
1459
+ else {
1460
+ // User hasn't logged in yet — let them choose to go log in or skip entirely
1461
+ clack.log.info(`Please log in now. Once done, come back and select "Yes".\n${loginHints}`);
1462
+ const action = await clack.select({
1463
+ message: 'What would you like to do?',
1464
+ options: [
1465
+ { value: 'retry', label: 'I\'ve logged in, retry detection' },
1466
+ { value: 'skip', label: 'Skip for now (run `cortex setup-gateway` later)' },
1467
+ ],
1468
+ });
1469
+ handleCancel(action);
1470
+ if (action === 'skip') {
1471
+ clack.log.info('Skipped. Run `cortex setup-gateway` later to auto-configure.');
1472
+ gatewayDone = true;
1473
+ }
1474
+ // action === 'retry' → loop continues, re-prompt the confirm
1475
+ }
1329
1476
  }
1330
1477
  }
1331
1478
  else {
@@ -111,6 +111,11 @@ export type CortexEvent = {
111
111
  ts: string;
112
112
  taskId: string;
113
113
  machine: string;
114
+ } | {
115
+ type: 'task.blocked';
116
+ ts: string;
117
+ taskId: string;
118
+ reason: string;
114
119
  } | {
115
120
  type: 'llm.active-count-delta';
116
121
  ts: string;
@@ -124,6 +129,15 @@ export type CortexEvent = {
124
129
  ts: string;
125
130
  provider: string;
126
131
  percent: number;
132
+ } | {
133
+ type: 'ui.mutate-invoked';
134
+ ts: string;
135
+ op: string;
136
+ args: unknown;
137
+ result: {
138
+ ok: boolean;
139
+ code?: string;
140
+ } | null;
127
141
  } | {
128
142
  type: 'event-bus.handler-failed';
129
143
  ts: string;
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.4 ← set to the current release version (agent-server/package.json) whenever you change this hook; syncManagedHooks then refreshes deployed installs
2
3
  // input: stdin JSON — Claude Code hook event or PI hook-bridge payload
3
4
  // output: { hookSpecificOutput: { hookEventName, additionalContext, matched } }
4
5
  // pos: Inject CORTEX.md / CORTEX.local.md ancestor chain into agent context
@@ -6,8 +7,11 @@
6
7
  // PostToolUse (Read) — from tool_input.file_path/path
7
8
  // SessionStart (startup|resume|clear|compact) — from payload.cwd
8
9
  // Per-session disk-backed dedup cache (~/.cortex/tmp/cortexmd-cache/<sessionId>.json)
10
+ // — only files actually injected are marked seen; truncated files stay eligible so
11
+ // a later Read re-attempts them (they are never silently suppressed)
9
12
  // markOnlyPaths: tool operating on a CORTEX.md itself → cache update only, no inject
10
- // Total length guard at 9,500 chars with truncated annotation
13
+ // Total length guard at 9,500 chars; files that overflow the budget are turned into an
14
+ // explicit "Read EACH of these files now" instruction instead of a silent drop
11
15
  // >>> If I am updated, be sure to update my header comment and the CORTEX.md in the same folder <<<
12
16
 
13
17
  import { readFileSync, statSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'fs';
@@ -123,35 +127,44 @@ function saveCache(sessionId, cache) {
123
127
  // ── context builder ──
124
128
 
125
129
  function buildContext(entries) {
126
- if (entries.length === 0) return '';
127
-
128
- // Build blocks in original order (leaf→root)
129
- const blocks = entries.map(e =>
130
- `<system-reminder>\nAuto-loaded CORTEX.md from ${HOSTNAME}:${e.path} (ancestor of accessed path). These instructions apply to files under this directory.\n\n${e.content}\n</system-reminder>`
131
- );
132
-
133
- const included = [];
130
+ if (entries.length === 0) return { text: '', includedPaths: [] };
131
+
132
+ // Walk entries in original order (leaf→root), inlining each as a block until the char
133
+ // budget is exhausted. Once exhausted, the remaining entries are NOT inlined — instead
134
+ // they are turned into an explicit read-instruction below, so their rules are never
135
+ // silently dropped (e.g. a root-level CORTEX.local.md carrying dev/safety rules).
136
+ const includedBlocks = [];
137
+ const includedPaths = [];
138
+ const truncated = [];
134
139
  let totalLen = 0;
135
-
136
- for (const block of blocks) {
137
- if (totalLen + block.length > MAX_CONTEXT_CHARS) break;
138
- included.push(block);
140
+ let budgetExhausted = false;
141
+
142
+ for (const e of entries) {
143
+ const block = `<system-reminder>\nAuto-loaded CORTEX.md from ${HOSTNAME}:${e.path} (ancestor of accessed path). These instructions apply to files under this directory.\n\n${e.content}\n</system-reminder>`;
144
+ if (budgetExhausted || totalLen + block.length > MAX_CONTEXT_CHARS) {
145
+ budgetExhausted = true; // match prior behavior: stop inlining at the first overflow
146
+ truncated.push(e);
147
+ continue;
148
+ }
149
+ includedBlocks.push(block);
150
+ includedPaths.push(e.path);
139
151
  totalLen += block.length;
140
152
  }
141
153
 
142
- const remaining = entries.length - included.length;
154
+ const parts = [...includedBlocks];
143
155
 
144
- // No block fit within the limit — return empty rather than
145
- // emitting a bare "[truncated, N more files at root]" message.
146
- if (included.length === 0) return '';
147
-
148
- let context = included.join('\n\n');
149
-
150
- if (remaining > 0) {
151
- context += `\n\n[truncated, ${remaining} more files at root]`;
156
+ // Overflow → actionable instruction. Reading these files delivers their content via the
157
+ // Read tool result; the markOnlyPaths branch then suppresses a duplicate inject.
158
+ if (truncated.length > 0) {
159
+ const list = truncated.map(e => `- ${e.path}`).join('\n');
160
+ parts.push(
161
+ `<system-reminder>\n⚠️ ${truncated.length} CORTEX rule file(s) were too large to inline here. ` +
162
+ `Read EACH of the following files now to load their rules before proceeding:\n${list}\n</system-reminder>`
163
+ );
152
164
  }
153
165
 
154
- return context;
166
+ if (parts.length === 0) return { text: '', includedPaths: [] };
167
+ return { text: parts.join('\n\n'), includedPaths };
155
168
  }
156
169
 
157
170
  // ── main ──
@@ -213,23 +226,26 @@ function main() {
213
226
  const cache = loadCache(sessionId);
214
227
  const newEntries = entries.filter(e => cache.get(e.path) !== e.mtimeMs);
215
228
 
216
- // Update cache with all scanned entries
217
- for (const entry of entries) {
218
- cache.set(entry.path, entry.mtimeMs);
219
- }
220
- saveCache(sessionId, cache);
221
-
222
229
  if (newEntries.length === 0) return;
223
230
 
224
231
  // Build context with truncation guard
225
- const additionalContext = buildContext(newEntries);
232
+ const { text: additionalContext, includedPaths } = buildContext(newEntries);
226
233
  if (!additionalContext) return;
227
234
 
235
+ // Mark as seen ONLY the entries actually injected. Truncated entries stay "unseen" so a
236
+ // later Read re-attempts their injection (or re-emits the read-instruction) — they must
237
+ // never be silently suppressed by being cached before the truncation filter runs.
238
+ const injected = new Set(includedPaths);
239
+ for (const entry of entries) {
240
+ if (injected.has(entry.path)) cache.set(entry.path, entry.mtimeMs);
241
+ }
242
+ saveCache(sessionId, cache);
243
+
228
244
  process.stdout.write(JSON.stringify({
229
245
  hookSpecificOutput: {
230
246
  hookEventName,
231
247
  additionalContext,
232
- matched: newEntries.map(e => e.path),
248
+ matched: includedPaths,
233
249
  },
234
250
  }));
235
251
  }
@@ -50,6 +50,12 @@ async function main() {
50
50
  parts.push('After completing the task, run `git status` to check for your uncommitted changes. If there are changes, commit them with an appropriate commit message. Do not commit changes that are not made by you.');
51
51
  }
52
52
 
53
+ // Worktree integration reminder (concurrent-safe code isolation). Piggybacks on the
54
+ // turn we are already injecting, so it costs no extra agent step. Self-gates: a no-op
55
+ // for tasks that never created a worktree.
56
+ const threadId = context.threadId || '$CORTEX_THREAD_ID';
57
+ parts.push(`If you created a git worktree for this task (branch cortex/${threadId}), integrate it back now before finishing: pull the latest main branch, merge your branch into it, resolve conflicts, push, then \`git worktree remove\` and delete the branch. On remote machines run these commands via remote_bash on the device you worked on. If conflicts cannot be resolved automatically, stop and report it — never force-overwrite another thread's work. If you did NOT create a worktree, ignore this.`);
58
+
53
59
  console.log(JSON.stringify({
54
60
  insertAgent: false,
55
61
  targetAgent,
@@ -119,6 +119,14 @@ async function main() {
119
119
 
120
120
  if (!project || !taskId) { noop(); return; }
121
121
 
122
+ // [SPLIT] decomposition proposal (DR-0014): the task is INTENTIONALLY not done — the
123
+ // dispatcher decomposes it keep-parent and unclaims. Don't burn an agent turn nagging.
124
+ if ((ctx.artifactContent || '').includes('[SPLIT]')) { noop(); return; }
125
+
126
+ // [ABORT] worker escalation (DR-0014 §8): the dispatcher blocks the task with the abort
127
+ // reason right after this hook returns — the task is intentionally not done.
128
+ if (/\[ABORT(?::|\])/.test(ctx.artifactContent || '')) { noop(); return; }
129
+
122
130
  const tasksPath = path.join(PROJECTS_DIR, project, 'TASKS.yaml');
123
131
  if (!existsSync(tasksPath)) { noop(); return; }
124
132