@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,11 +1,34 @@
1
1
  // input: PI ExtensionAPI, @sinclair/typebox
2
- // output: Register ask_user_question / enter_plan_mode / exit_plan_mode / todo_write pseudo-tools
2
+ // output: Register ask_user_question / enter_plan_mode / exit_plan_mode / todo_write pseudo-tools,
3
+ // gated by the agent's tool allowlist (CORTEX_PI_ALLOWED_TOOLS env) via makeToolGate
3
4
  // pos: PI --extension bridge that exposes Cortex interaction flow to the LLM
4
5
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
6
  import { Type } from '@sinclair/typebox';
6
7
  import * as path from 'path';
7
8
  import { mkdirSync } from 'fs';
9
+ /**
10
+ * Build a predicate that decides whether a pseudo-tool (identified by its Claude-native label,
11
+ * e.g. "ExitPlanMode") may be registered, given the agent's tool allowlist.
12
+ *
13
+ * `allowedToolsEnv` mirrors the agent's `tools` config in Claude-native, comma-separated form —
14
+ * the PI adapter forwards it via the CORTEX_PI_ALLOWED_TOOLS env var, exactly the same allowlist
15
+ * the Claude backend passes to `--tools`. When unset/empty (interactive sessions, or callers that
16
+ * don't constrain tools) ALL pseudo-tools are allowed, preserving prior behavior.
17
+ *
18
+ * This is what stops thread-dispatched agents (coder, reviewer, …) from being handed
19
+ * AskUserQuestion / EnterPlanMode / ExitPlanMode — interaction tools that deadlock a headless
20
+ * thread because no human can ever answer the approval prompt.
21
+ */
22
+ export function makeToolGate(allowedToolsEnv) {
23
+ if (!allowedToolsEnv || allowedToolsEnv.trim() === '')
24
+ return () => true;
25
+ const allowed = new Set(allowedToolsEnv.split(',').map((t) => t.trim()).filter((t) => t.length > 0));
26
+ return (label) => allowed.has(label);
27
+ }
8
28
  export default function toolShims(pi) {
29
+ // Gate pseudo-tool registration on the agent's tool allowlist (Claude-native labels).
30
+ // Mirrors the Claude backend's `--tools` allowlist so PI honors the same per-agent tool scoping.
31
+ const allowed = makeToolGate(process.env.CORTEX_PI_ALLOWED_TOOLS);
9
32
  // ---------------------------------------------------------------------------
10
33
  // ask_user_question
11
34
  // ---------------------------------------------------------------------------
@@ -14,34 +37,35 @@ export default function toolShims(pi) {
14
37
  // blocking primitive; the Cortex adapter posts all questions to Slack from the
15
38
  // tool_use event (which carries the full input), then unblocks via
16
39
  // sendExtensionUiResponse when the user answers.
17
- pi.registerTool({
18
- name: 'ask_user_question',
19
- label: 'AskUserQuestion',
20
- description: 'Ask the user one or more questions and wait for their responses before proceeding. ' +
21
- 'Use this when you need clarification, a decision, or a choice from the user.',
22
- parameters: Type.Object({
23
- questions: Type.Array(Type.Object({
24
- question: Type.String({ description: 'The complete question to ask the user.' }),
25
- header: Type.String({ description: 'Very short label (max 12 chars), e.g. "Auth method", "Library".' }),
26
- options: Type.Array(Type.Object({
27
- label: Type.String({ description: 'The display text for this option.' }),
28
- description: Type.String({ description: 'Explanation of what this option means.' }),
29
- }), { description: 'Available choices. Must have 2-4 options.' }),
30
- multiSelect: Type.Boolean({
31
- default: false,
32
- description: 'If true, the user may select multiple options.',
33
- }),
34
- }), { description: 'Questions to ask (1-4 questions).' }),
35
- }),
36
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
37
- // Block once via ctx.ui.input — Cortex adapter handles multi-question
38
- // display and answer collection through Slack, then unblocks this call
39
- // with the combined answers via sendExtensionUiResponse.
40
- const summary = params.questions.map((q) => q.header || q.question).join(', ');
41
- const answer = await ctx.ui.input(`Waiting for user: ${summary}`);
42
- return { content: [{ type: 'text', text: answer || '(no answer provided)' }] };
43
- },
44
- });
40
+ if (allowed('AskUserQuestion'))
41
+ pi.registerTool({
42
+ name: 'ask_user_question',
43
+ label: 'AskUserQuestion',
44
+ description: 'Ask the user one or more questions and wait for their responses before proceeding. ' +
45
+ 'Use this when you need clarification, a decision, or a choice from the user.',
46
+ parameters: Type.Object({
47
+ questions: Type.Array(Type.Object({
48
+ question: Type.String({ description: 'The complete question to ask the user.' }),
49
+ header: Type.String({ description: 'Very short label (max 12 chars), e.g. "Auth method", "Library".' }),
50
+ options: Type.Array(Type.Object({
51
+ label: Type.String({ description: 'The display text for this option.' }),
52
+ description: Type.String({ description: 'Explanation of what this option means.' }),
53
+ }), { description: 'Available choices. Must have 2-4 options.' }),
54
+ multiSelect: Type.Boolean({
55
+ default: false,
56
+ description: 'If true, the user may select multiple options.',
57
+ }),
58
+ }), { description: 'Questions to ask (1-4 questions).' }),
59
+ }),
60
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
61
+ // Block once via ctx.ui.input — Cortex adapter handles multi-question
62
+ // display and answer collection through Slack, then unblocks this call
63
+ // with the combined answers via sendExtensionUiResponse.
64
+ const summary = params.questions.map((q) => q.header || q.question).join(', ');
65
+ const answer = await ctx.ui.input(`Waiting for user: ${summary}`);
66
+ return { content: [{ type: 'text', text: answer || '(no answer provided)' }] };
67
+ },
68
+ });
45
69
  // ---------------------------------------------------------------------------
46
70
  // enter_plan_mode
47
71
  // ---------------------------------------------------------------------------
@@ -50,61 +74,62 @@ export default function toolShims(pi) {
50
74
  // tools, write the plan to a designated file, then call exit_plan_mode.
51
75
  // Non-interactive: returns the plan-mode instructions immediately.
52
76
  // The event-parser emits a plan_mode_entered NormalizedEvent for observability.
53
- pi.registerTool({
54
- name: 'enter_plan_mode',
55
- label: 'EnterPlanMode',
56
- description: 'Use this tool proactively when you are about to start a non-trivial implementation task. ' +
57
- 'Getting user sign-off on your approach before writing code prevents wasted effort and ensures alignment. ' +
58
- 'This tool transitions you into plan mode where you explore the codebase and design an implementation approach for user approval.\n\n' +
59
- '## When to Use This Tool\n\n' +
60
- 'Use when ANY of these conditions apply:\n' +
61
- '1. New Feature Implementation — adding meaningful new functionality\n' +
62
- '2. Multiple Valid Approaches — the task can be solved in several different ways\n' +
63
- '3. Code Modifications — changes that affect existing behavior or structure\n' +
64
- '4. Architectural Decisions — choosing between patterns or technologies\n' +
65
- '5. Multi-File Changes — the task will likely touch more than 2-3 files\n' +
66
- '6. Unclear Requirements — you need to explore before understanding the full scope\n' +
67
- '7. User Preferences Matter — the implementation could reasonably go multiple ways\n\n' +
68
- '## When NOT to Use This Tool\n\n' +
69
- 'Skip for simple tasks: single-line or few-line fixes, adding a single function with clear requirements, ' +
70
- 'tasks where the user has given very specific detailed instructions, or pure research/exploration tasks.',
71
- parameters: Type.Object({}),
72
- async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
73
- // Generate a plan file path under plan/ with a timestamp.
74
- const planDir = path.join(process.cwd(), 'plan');
75
- try {
76
- mkdirSync(planDir, { recursive: true });
77
- }
78
- catch { }
79
- const planFileName = `plan-${Date.now()}.md`;
80
- const planFilePath = path.join(planDir, planFileName);
81
- const instructions = [
82
- 'You are now in plan mode. Your goal is to explore the codebase and design an implementation approach before making any changes.',
83
- '',
84
- `Plan file: ${planFilePath}`,
85
- '',
86
- '## Rules',
87
- '',
88
- '1. Do NOT use Edit, Write, or Bash to modify any files or run destructive commands.',
89
- '2. Use ONLY read-only tools to explore the codebase: Read, Grep, Glob, Bash (read-only commands like ls, git log, etc.), WebSearch, WebFetch.',
90
- '3. Use the Agent tool with subagent_type "Explore" for broader codebase exploration if needed.',
91
- '4. Use AskUserQuestion if you need to clarify requirements or choose between approaches.',
92
- '5. Once you have a complete plan, write it to the plan file above using the Write tool.',
93
- '6. After writing the plan file, call ExitPlanMode to submit it for user approval.',
94
- '',
95
- '## What Your Plan Should Include',
96
- '',
97
- '- Summary of the task and your understanding of requirements',
98
- '- Key files and components that will be affected',
99
- '- Step-by-step implementation approach',
100
- '- Any risks, trade-offs, or alternatives considered',
101
- '- Test plan (if applicable)',
102
- '',
103
- 'Begin by exploring the codebase to understand the relevant code and architecture.',
104
- ].join('\n');
105
- return { content: [{ type: 'text', text: instructions }] };
106
- },
107
- });
77
+ if (allowed('EnterPlanMode'))
78
+ pi.registerTool({
79
+ name: 'enter_plan_mode',
80
+ label: 'EnterPlanMode',
81
+ description: 'Use this tool proactively when you are about to start a non-trivial implementation task. ' +
82
+ 'Getting user sign-off on your approach before writing code prevents wasted effort and ensures alignment. ' +
83
+ 'This tool transitions you into plan mode where you explore the codebase and design an implementation approach for user approval.\n\n' +
84
+ '## When to Use This Tool\n\n' +
85
+ 'Use when ANY of these conditions apply:\n' +
86
+ '1. New Feature Implementation — adding meaningful new functionality\n' +
87
+ '2. Multiple Valid Approaches — the task can be solved in several different ways\n' +
88
+ '3. Code Modifications — changes that affect existing behavior or structure\n' +
89
+ '4. Architectural Decisions — choosing between patterns or technologies\n' +
90
+ '5. Multi-File Changes — the task will likely touch more than 2-3 files\n' +
91
+ '6. Unclear Requirements — you need to explore before understanding the full scope\n' +
92
+ '7. User Preferences Matter — the implementation could reasonably go multiple ways\n\n' +
93
+ '## When NOT to Use This Tool\n\n' +
94
+ 'Skip for simple tasks: single-line or few-line fixes, adding a single function with clear requirements, ' +
95
+ 'tasks where the user has given very specific detailed instructions, or pure research/exploration tasks.',
96
+ parameters: Type.Object({}),
97
+ async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
98
+ // Generate a plan file path under plan/ with a timestamp.
99
+ const planDir = path.join(process.cwd(), 'plan');
100
+ try {
101
+ mkdirSync(planDir, { recursive: true });
102
+ }
103
+ catch { }
104
+ const planFileName = `plan-${Date.now()}.md`;
105
+ const planFilePath = path.join(planDir, planFileName);
106
+ const instructions = [
107
+ 'You are now in plan mode. Your goal is to explore the codebase and design an implementation approach before making any changes.',
108
+ '',
109
+ `Plan file: ${planFilePath}`,
110
+ '',
111
+ '## Rules',
112
+ '',
113
+ '1. Do NOT use Edit, Write, or Bash to modify any files or run destructive commands.',
114
+ '2. Use ONLY read-only tools to explore the codebase: Read, Grep, Glob, Bash (read-only commands like ls, git log, etc.), WebSearch, WebFetch.',
115
+ '3. Use the Agent tool with subagent_type "Explore" for broader codebase exploration if needed.',
116
+ '4. Use AskUserQuestion if you need to clarify requirements or choose between approaches.',
117
+ '5. Once you have a complete plan, write it to the plan file above using the Write tool.',
118
+ '6. After writing the plan file, call ExitPlanMode to submit it for user approval.',
119
+ '',
120
+ '## What Your Plan Should Include',
121
+ '',
122
+ '- Summary of the task and your understanding of requirements',
123
+ '- Key files and components that will be affected',
124
+ '- Step-by-step implementation approach',
125
+ '- Any risks, trade-offs, or alternatives considered',
126
+ '- Test plan (if applicable)',
127
+ '',
128
+ 'Begin by exploring the codebase to understand the relevant code and architecture.',
129
+ ].join('\n');
130
+ return { content: [{ type: 'text', text: instructions }] };
131
+ },
132
+ });
108
133
  // ---------------------------------------------------------------------------
109
134
  // exit_plan_mode
110
135
  // ---------------------------------------------------------------------------
@@ -115,30 +140,31 @@ export default function toolShims(pi) {
115
140
  // user's approval (value='__APPROVED__') or rejection (value=<feedback> / cancelled).
116
141
  // On approval, PI is unblocked and continues to the implementation phase.
117
142
  // On rejection, returns a rejection message so PI can revise the plan.
118
- pi.registerTool({
119
- name: 'exit_plan_mode',
120
- label: 'ExitPlanMode',
121
- description: 'Signal that you have finished planning and are ready to submit the plan for user approval. ' +
122
- 'Call this after writing your plan to a file. Execution will pause until the user approves.',
123
- parameters: Type.Object({
124
- plan: Type.Optional(Type.String({ description: 'Summary of the plan content (also written to file).' })),
125
- }),
126
- async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
127
- // Block until the user approves or rejects the plan via Cortex approval UI.
128
- // The Cortex adapter responds with sendExtensionUiResponse({ value: '__APPROVED__' }) for approval, or { value: '<feedback>' } / { cancelled: true } for rejection.
129
- const response = await ctx.ui.input('Plan review — type "__APPROVED__" to proceed or provide feedback.');
130
- if (response === '__APPROVED__') {
131
- return { content: [{ type: 'text', text: 'Plan approved. Proceeding with implementation.' }] };
132
- }
133
- if (response) {
134
- return { content: [{ type: 'text', text: `Plan needs revision. User feedback:\n"""\n${response}\n"""` }] };
135
- }
136
- // null / undefined (cancelled) treated as rejected without feedback.
137
- return {
138
- content: [{ type: 'text', text: 'Plan rejected. Please revise the plan and try again.' }],
139
- };
140
- },
141
- });
143
+ if (allowed('ExitPlanMode'))
144
+ pi.registerTool({
145
+ name: 'exit_plan_mode',
146
+ label: 'ExitPlanMode',
147
+ description: 'Signal that you have finished planning and are ready to submit the plan for user approval. ' +
148
+ 'Call this after writing your plan to a file. Execution will pause until the user approves.',
149
+ parameters: Type.Object({
150
+ plan: Type.Optional(Type.String({ description: 'Summary of the plan content (also written to file).' })),
151
+ }),
152
+ async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
153
+ // Block until the user approves or rejects the plan via Cortex approval UI.
154
+ // The Cortex adapter responds with sendExtensionUiResponse({ value: '__APPROVED__' }) for approval, or { value: '<feedback>' } / { cancelled: true } for rejection.
155
+ const response = await ctx.ui.input('Plan review — type "__APPROVED__" to proceed or provide feedback.');
156
+ if (response === '__APPROVED__') {
157
+ return { content: [{ type: 'text', text: 'Plan approved. Proceeding with implementation.' }] };
158
+ }
159
+ if (response) {
160
+ return { content: [{ type: 'text', text: `Plan needs revision. User feedback:\n"""\n${response}\n"""` }] };
161
+ }
162
+ // null / undefined (cancelled) treated as rejected without feedback.
163
+ return {
164
+ content: [{ type: 'text', text: 'Plan rejected. Please revise the plan and try again.' }],
165
+ };
166
+ },
167
+ });
142
168
  // ---------------------------------------------------------------------------
143
169
  // todo_write
144
170
  // ---------------------------------------------------------------------------
@@ -146,36 +172,37 @@ export default function toolShims(pi) {
146
172
  // Non-interactive: just acknowledges the update and returns. The event-parser
147
173
  // emits a regular tool_use NormalizedEvent (no special NormalizedEvent type).
148
174
  // The LLM uses this to visibly manage its work checklist across steps.
149
- pi.registerTool({
150
- name: 'todo_write',
151
- label: 'TodoWrite',
152
- description: 'Create and manage a structured task list for the current session. ' +
153
- 'Use this to track progress across multi-step tasks.',
154
- parameters: Type.Object({
155
- todos: Type.Array(Type.Object({
156
- content: Type.String({ description: 'Task description (imperative form).' }),
157
- status: Type.Union([
158
- Type.Literal('pending'),
159
- Type.Literal('in_progress'),
160
- Type.Literal('completed'),
161
- ]),
162
- activeForm: Type.String({
163
- description: 'Present-continuous form shown when the task is in progress.',
164
- }),
165
- })),
166
- }),
167
- async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
168
- const total = params.todos.length;
169
- const done = params.todos.filter((t) => t.status === 'completed').length;
170
- const inProgress = params.todos.filter((t) => t.status === 'in_progress').length;
171
- return {
172
- content: [
173
- {
174
- type: 'text',
175
- text: `Todos updated: ${total} total, ${done} completed, ${inProgress} in progress.`,
176
- },
177
- ],
178
- };
179
- },
180
- });
175
+ if (allowed('TodoWrite'))
176
+ pi.registerTool({
177
+ name: 'todo_write',
178
+ label: 'TodoWrite',
179
+ description: 'Create and manage a structured task list for the current session. ' +
180
+ 'Use this to track progress across multi-step tasks.',
181
+ parameters: Type.Object({
182
+ todos: Type.Array(Type.Object({
183
+ content: Type.String({ description: 'Task description (imperative form).' }),
184
+ status: Type.Union([
185
+ Type.Literal('pending'),
186
+ Type.Literal('in_progress'),
187
+ Type.Literal('completed'),
188
+ ]),
189
+ activeForm: Type.String({
190
+ description: 'Present-continuous form shown when the task is in progress.',
191
+ }),
192
+ })),
193
+ }),
194
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
195
+ const total = params.todos.length;
196
+ const done = params.todos.filter((t) => t.status === 'completed').length;
197
+ const inProgress = params.todos.filter((t) => t.status === 'in_progress').length;
198
+ return {
199
+ content: [
200
+ {
201
+ type: 'text',
202
+ text: `Todos updated: ${total} total, ${done} completed, ${inProgress} in progress.`,
203
+ },
204
+ ],
205
+ };
206
+ },
207
+ });
181
208
  }
@@ -52,9 +52,14 @@ export interface AgentSpawnConfig {
52
52
  rawTools?: string;
53
53
  /** DR-0008 Phase 3 cleanup target. Per-request ANTHROPIC_BASE_URL override (gateway-routed mode URL). */
54
54
  anthropicBaseUrl?: string;
55
- /** PI provider name (e.g. "anthropic", "deepseek", "openai-codex"). Sourced from the active
56
- * cortex profile's `mode` field. PI adapter passes it to the subprocess as `--provider <name>`. */
55
+ /** PI provider name / protocol (e.g. "anthropic", "deepseek", "openai-codex"). Sourced from the
56
+ * active cortex profile's `provider` field (defaults to "anthropic"). PI adapter passes it to the
57
+ * subprocess as `--provider <name>`. */
57
58
  piProvider?: string;
59
+ /** Gateway sub-path for `piProvider`'s models.json override, derived in code as `/m/<mode>/<provider>`
60
+ * from the profile's logical `mode` (gateway.yaml owns the route → upstream + keys). Decouples the
61
+ * gateway route from the provider name. Omitted (no mode) → adapter defaults to `/<piProvider>`. */
62
+ piGatewayPath?: string;
58
63
  /** Base URL of the cortex local gateway (e.g. "http://127.0.0.1:9880"). PI adapter writes a
59
64
  * multi-provider models.json overriding every discovered provider's baseUrl to land on this
60
65
  * gateway, so PI traffic is monitored / cost-tracked rather than going direct to upstreams. */
@@ -4,12 +4,33 @@
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import fs from 'node:fs/promises';
6
6
  import path from 'node:path';
7
+ import * as os from 'node:os';
8
+ /** The operator's real data home. A test process must never write here — it would race the
9
+ * running daemon and leak fixtures into the live store (this happened: tests polluted
10
+ * ~/.cortex/data/threads.json). Tests isolate via tests/_test-home.ts, which repoints
11
+ * CORTEX_HOME at a temp dir, so legitimate test writes land elsewhere and pass this guard. */
12
+ const REAL_HOME_CORTEX = path.join(os.homedir(), '.cortex');
13
+ /** True only inside `node --test` / `tsx --test` worker processes (env set by the runner). */
14
+ function inTestProcess() {
15
+ return !!process.env.NODE_TEST_CONTEXT;
16
+ }
7
17
  /**
8
18
  * Write `data` to `filePath` atomically via a sibling tmp file + fs.rename.
9
19
  * The original file is never in a partially-written state: either the rename
10
20
  * succeeds (new content visible) or it does not (original intact, tmp left on disk).
11
21
  */
12
22
  export async function atomicWrite(filePath, data) {
23
+ // Test-isolation tripwire: refuse (before writing anything) to mutate the real ~/.cortex from a
24
+ // test process. Converts silent production corruption into a loud failure. No-op in production
25
+ // (NODE_TEST_CONTEXT unset) and for temp-isolated test homes (path not under the real home).
26
+ if (inTestProcess()) {
27
+ const resolved = path.resolve(filePath);
28
+ if (resolved === REAL_HOME_CORTEX || resolved.startsWith(REAL_HOME_CORTEX + path.sep)) {
29
+ throw new Error(`atomicWrite blocked: test process attempted to write under the real ~/.cortex (${resolved}). `
30
+ + `Isolate state first: import './_test-home.js' as the FIRST line of the test, or run via `
31
+ + `\`npm test\` / \`npm run test:file <file>\` (both set an isolated CORTEX_HOME).`);
32
+ }
33
+ }
13
34
  await fs.mkdir(path.dirname(filePath), { recursive: true });
14
35
  const rnd = Math.random().toString(36).slice(2, 8);
15
36
  const tmp = `${filePath}.tmp.${process.pid}.${Date.now()}.${rnd}`;
@@ -6,4 +6,14 @@ export declare function buildCoreConfig(serverRoot: string): object;
6
6
  * cortex_plan_enter / cortex_plan_exit / cortex_ask_user replace the native
7
7
  * EnterPlanMode / ExitPlanMode / AskUserQuestion tools, which are excluded from --tools in TUI mode. */
8
8
  export declare function buildTuiConfig(serverRoot: string): object;
9
+ /** Slack MCP config — layered ON TOP of the full config (via the variadic `--mcp-config`) only for
10
+ * sessions that originate from Slack (channel carries the `slack:` prefix). Isolated to the single
11
+ * cortex-slack server so it can be added/removed independently of the base config; the Claude adapter
12
+ * and the PI mcp-bridge each decide whether to load it based on the session's source channel. */
13
+ export declare function buildSlackConfig(serverRoot: string): object;
14
+ /** Feishu MCP config — layered ON TOP of the full config (via the variadic `--mcp-config`) only for
15
+ * sessions that originate from Feishu (channel carries the `feishu:` prefix). Isolated to the single
16
+ * cortex-feishu server so it can be added/removed independently of the base config; the Claude adapter
17
+ * and the PI mcp-bridge each decide whether to load it based on the session's source channel. */
18
+ export declare function buildFeishuConfig(serverRoot: string): object;
9
19
  export declare function generateMcpConfig(): void;
@@ -9,6 +9,8 @@ const log = createLogger('config-generator');
9
9
  const MCP_CONFIG_PATH = path.join(CONFIG_DIR, 'mcp-config.json');
10
10
  const CORE_MCP_CONFIG_PATH = path.join(CONFIG_DIR, 'mcp-config-core.json');
11
11
  const TUI_MCP_CONFIG_PATH = path.join(CONFIG_DIR, 'mcp-config-tui.json');
12
+ const SLACK_MCP_CONFIG_PATH = path.join(CONFIG_DIR, 'mcp-config-slack.json');
13
+ const FEISHU_MCP_CONFIG_PATH = path.join(CONFIG_DIR, 'mcp-config-feishu.json');
12
14
  /**
13
15
  * Build a MCP server entry. Uses absolute path in args as a workaround for
14
16
  * Claude Code 2.1.123: the `cwd` field in MCP config is NOT inherited by the
@@ -48,6 +50,28 @@ export function buildTuiConfig(serverRoot) {
48
50
  },
49
51
  };
50
52
  }
53
+ /** Slack MCP config — layered ON TOP of the full config (via the variadic `--mcp-config`) only for
54
+ * sessions that originate from Slack (channel carries the `slack:` prefix). Isolated to the single
55
+ * cortex-slack server so it can be added/removed independently of the base config; the Claude adapter
56
+ * and the PI mcp-bridge each decide whether to load it based on the session's source channel. */
57
+ export function buildSlackConfig(serverRoot) {
58
+ return {
59
+ mcpServers: {
60
+ 'cortex-slack': serverEntry('dist/domain/mcp/slack-server.js', serverRoot),
61
+ },
62
+ };
63
+ }
64
+ /** Feishu MCP config — layered ON TOP of the full config (via the variadic `--mcp-config`) only for
65
+ * sessions that originate from Feishu (channel carries the `feishu:` prefix). Isolated to the single
66
+ * cortex-feishu server so it can be added/removed independently of the base config; the Claude adapter
67
+ * and the PI mcp-bridge each decide whether to load it based on the session's source channel. */
68
+ export function buildFeishuConfig(serverRoot) {
69
+ return {
70
+ mcpServers: {
71
+ 'cortex-feishu': serverEntry('dist/domain/mcp/feishu-server.js', serverRoot),
72
+ },
73
+ };
74
+ }
51
75
  export function generateMcpConfig() {
52
76
  writeFileSync(MCP_CONFIG_PATH, JSON.stringify(buildFullConfig(SERVER_ROOT), null, 2));
53
77
  log.info(`Generated full MCP config at ${MCP_CONFIG_PATH}`);
@@ -55,4 +79,8 @@ export function generateMcpConfig() {
55
79
  log.info(`Generated core MCP config at ${CORE_MCP_CONFIG_PATH}`);
56
80
  writeFileSync(TUI_MCP_CONFIG_PATH, JSON.stringify(buildTuiConfig(SERVER_ROOT), null, 2));
57
81
  log.info(`Generated TUI MCP config at ${TUI_MCP_CONFIG_PATH}`);
82
+ writeFileSync(SLACK_MCP_CONFIG_PATH, JSON.stringify(buildSlackConfig(SERVER_ROOT), null, 2));
83
+ log.info(`Generated Slack MCP config at ${SLACK_MCP_CONFIG_PATH}`);
84
+ writeFileSync(FEISHU_MCP_CONFIG_PATH, JSON.stringify(buildFeishuConfig(SERVER_ROOT), null, 2));
85
+ log.info(`Generated Feishu MCP config at ${FEISHU_MCP_CONFIG_PATH}`);
58
86
  }
@@ -1,3 +1,32 @@
1
+ /** endpoint name → mode name → raw endpoint config object. */
2
+ export type EndpointMap = Record<string, Record<string, Record<string, unknown>>>;
3
+ /** Parsed existing gateway.yaml split into reserved top-level fields and the endpoint/mode tree. */
4
+ export interface ParsedGateway {
5
+ /** Reserved top-level keys preserved verbatim: port, mode, status_check, auth, host, endpoint_modes, endpoints. */
6
+ top: Record<string, unknown>;
7
+ endpoints: EndpointMap;
8
+ }
9
+ export interface MergeGatewayResult {
10
+ endpoints: EndpointMap;
11
+ top: Record<string, unknown>;
12
+ /** Existing (endpoint, mode) pairs NOT produced by this discovery — kept verbatim. */
13
+ preservedCustom: Array<{
14
+ endpoint: string;
15
+ mode: string;
16
+ }>;
17
+ /** Subset of preservedCustom that looks like it should have been rediscovered (i.e. not
18
+ * anthropic/plan|api) — surfaced as a warning so a failed `pi --list-models` is visible. */
19
+ droppedFromDiscovery: Array<{
20
+ endpoint: string;
21
+ mode: string;
22
+ }>;
23
+ }
24
+ export interface GatewayValidationIssue {
25
+ profile: string;
26
+ mode: string;
27
+ provider?: string;
28
+ reason: string;
29
+ }
1
30
  export interface DiscoveredEndpoint {
2
31
  /** Mode key in gateway.yaml + cortex profile (e.g. "plan", "deepseek", "openai-codex") */
3
32
  mode: string;
@@ -30,14 +59,17 @@ export declare function parsePiListModelsOutput(stdout: string): PiDiscoveredMod
30
59
  /**
31
60
  * Scan Claude Code and PI configurations and return discovered endpoints.
32
61
  *
33
- * - Claude Code plan mode: always generated if logged in (OAuth bearer passthrough).
34
- * - Claude Code api mode: generated only if ANTHROPIC_API_KEY env var is set.
35
- * - PI providers: discovered via `pi --list-models`. Each provider becomes one endpoint with
36
- * `mode = endpoint = provider name`. `gatewayManaged` is true only if the provider has a known
37
- * upstream URL in PI_PROVIDER_UPSTREAM (otherwise profile is generated but gateway.yaml entry
38
- * is skipped).
62
+ * @param backends - Optional filter: when provided, only discover endpoints for the listed backends
63
+ * (e.g. `['claude']`, `['pi']`, `['claude', 'pi']`). When omitted, all backends are discovered.
64
+ *
65
+ * - Claude Code plan mode: generated when 'claude' is in backends (or backends is omitted).
66
+ * - Claude Code api mode: generated only if ANTHROPIC_API_KEY env var is set and 'claude' is included.
67
+ * - PI providers: discovered via `pi --list-models` when 'pi' is in backends (or backends is omitted).
68
+ * Each provider becomes one endpoint with `mode = endpoint = provider name`. `gatewayManaged`
69
+ * is true only if the provider has a known upstream URL in PI_PROVIDER_UPSTREAM (otherwise profile
70
+ * is generated but gateway.yaml entry is skipped).
39
71
  */
40
- export declare function discoverEndpoints(): DiscoveredEndpoint[];
72
+ export declare function discoverEndpoints(backends?: string[]): DiscoveredEndpoint[];
41
73
  /**
42
74
  * Generate gateway.yaml content from discovered endpoints.
43
75
  * Outputs a formatted YAML string with comments explaining each mode.
@@ -50,8 +82,46 @@ export declare function generateGatewayYaml(endpoints: DiscoveredEndpoint[], def
50
82
  * Write gateway.yaml to the specified path or ~/.aistatus/gateway.yaml.
51
83
  * If file already exists and outputDir is not specified, backs it up as gateway.yaml.bak before overwriting.
52
84
  * When outputDir is provided, writes to <outputDir>/gateway.yaml without backup.
85
+ *
86
+ * @deprecated Use writeMergedGatewayYaml — full overwrite drops hand-maintained custom modes.
53
87
  */
54
88
  export declare function writeGatewayYaml(yamlContent: string, outputDir?: string): string;
89
+ /**
90
+ * Parse an existing gateway.yaml into reserved top-level fields + the endpoint/mode tree.
91
+ * Returns null if the file is absent or unparseable (caller degrades to full generation).
92
+ */
93
+ export declare function readGatewayYaml(filePath: string): ParsedGateway | null;
94
+ /** Build an endpoint/mode tree from freshly discovered endpoints (gatewayManaged only). */
95
+ export declare function discoveredToEndpointMap(endpoints: DiscoveredEndpoint[]): EndpointMap;
96
+ /**
97
+ * Merge freshly discovered endpoints over an existing gateway config.
98
+ *
99
+ * Add-only at the (endpoint, mode) PAIR level (mirrors mergeProfilesJson overwrite=false): a pair
100
+ * absent from the existing file is added from discovery; any pair that already exists is preserved
101
+ * verbatim — its base_url, auth_style and (critically) managed keys are never clobbered. This both
102
+ * fixes the original bug (a missing mode gets added) and protects hand-customized routes, e.g. a
103
+ * `deepseek` mode pointed at a private relay with a secret key, even though `pi --list-models`
104
+ * reports the canonical upstream for that provider. A failed/empty discovery therefore can never
105
+ * drop or alter previously-configured modes. To intentionally update an existing route's URL/keys,
106
+ * edit gateway.yaml directly.
107
+ */
108
+ export declare function mergeGatewayConfig(discovered: DiscoveredEndpoint[], existing: ParsedGateway | null, defaultMode?: string): MergeGatewayResult;
109
+ /** Serialize a merged gateway config back to YAML (re-serializes; inline comments in custom blocks are not retained). */
110
+ export declare function serializeGatewayYaml(result: MergeGatewayResult): string;
111
+ /**
112
+ * Read existing gateway.yaml, merge discovery over it, and write the result. Always backs up an
113
+ * existing file to .bak first (including when outputDir is given, since merge now touches real data).
114
+ */
115
+ export declare function writeMergedGatewayYaml(discovered: DiscoveredEndpoint[], outputDir?: string, defaultMode?: string): {
116
+ path: string;
117
+ result: MergeGatewayResult;
118
+ };
119
+ /**
120
+ * Validate that every profile (and its fallback chain) in profiles.json references a gateway mode
121
+ * that actually exists in the merged endpoint map. Pure + non-fatal — returns the list of problems
122
+ * so the caller can warn loudly. This is what catches the `400 Unknown mode: <x>` class of bug.
123
+ */
124
+ export declare function validateProfilesAgainstGateway(mergedEndpoints: EndpointMap, profilesConfigDir?: string): GatewayValidationIssue[];
55
125
  /**
56
126
  * Run discovery and return the YAML string (without writing to disk).
57
127
  * Useful for dry-run / preview.