@cortex-agent/server 2026.5.25-1 → 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 (354) 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/tasks/dispatch-utils.d.ts +58 -1
  122. package/dist/domain/tasks/dispatch-utils.js +53 -4
  123. package/dist/domain/tasks/dispatcher.js +26 -0
  124. package/dist/domain/tasks/lint.js +28 -0
  125. package/dist/domain/tasks/mutator.d.ts +16 -3
  126. package/dist/domain/tasks/mutator.js +41 -12
  127. package/dist/domain/tasks/pending-tracker.js +6 -5
  128. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  129. package/dist/domain/tasks/system/task-cli.js +37 -6
  130. package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
  131. package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
  132. package/dist/domain/tasks/system/task-mutations.js +166 -8
  133. package/dist/domain/threads/contract.d.ts +17 -0
  134. package/dist/domain/threads/contract.js +59 -0
  135. package/dist/domain/threads/hook-runner.js +7 -6
  136. package/dist/domain/threads/index.d.ts +2 -0
  137. package/dist/domain/threads/index.js +3 -1
  138. package/dist/domain/threads/prompt-builder.d.ts +15 -1
  139. package/dist/domain/threads/prompt-builder.js +41 -2
  140. package/dist/domain/threads/runner.d.ts +6 -5
  141. package/dist/domain/threads/runner.js +128 -79
  142. package/dist/domain/threads/state-machine.d.ts +23 -21
  143. package/dist/domain/threads/state-machine.js +113 -54
  144. package/dist/domain/threads/template-loader.js +3 -2
  145. package/dist/domain/threads/tree.d.ts +45 -0
  146. package/dist/domain/threads/tree.js +171 -0
  147. package/dist/domain/tui-session/index.d.ts +2 -0
  148. package/dist/domain/tui-session/index.js +3 -0
  149. package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
  150. package/dist/domain/tui-session/tui-session-service.js +103 -0
  151. package/dist/domain/tui-session/types.d.ts +67 -0
  152. package/dist/domain/tui-session/types.js +4 -0
  153. package/dist/domain/ui-service/index.d.ts +5 -0
  154. package/dist/domain/ui-service/index.js +3 -0
  155. package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
  156. package/dist/domain/ui-service/mutate/executions.js +15 -0
  157. package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
  158. package/dist/domain/ui-service/mutate/schedules.js +39 -0
  159. package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
  160. package/dist/domain/ui-service/mutate/tasks.js +59 -0
  161. package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
  162. package/dist/domain/ui-service/mutate/threads.js +21 -0
  163. package/dist/domain/ui-service/query/cost.d.ts +3 -0
  164. package/dist/domain/ui-service/query/cost.js +6 -0
  165. package/dist/domain/ui-service/query/executions.d.ts +2 -0
  166. package/dist/domain/ui-service/query/executions.js +35 -0
  167. package/dist/domain/ui-service/query/projects.d.ts +2 -0
  168. package/dist/domain/ui-service/query/projects.js +30 -0
  169. package/dist/domain/ui-service/query/schedules.d.ts +2 -0
  170. package/dist/domain/ui-service/query/schedules.js +23 -0
  171. package/dist/domain/ui-service/query/sessions.d.ts +2 -0
  172. package/dist/domain/ui-service/query/sessions.js +35 -0
  173. package/dist/domain/ui-service/query/tasks.d.ts +2 -0
  174. package/dist/domain/ui-service/query/tasks.js +30 -0
  175. package/dist/domain/ui-service/query/threads.d.ts +2 -0
  176. package/dist/domain/ui-service/query/threads.js +27 -0
  177. package/dist/domain/ui-service/subscribe.d.ts +5 -0
  178. package/dist/domain/ui-service/subscribe.js +118 -0
  179. package/dist/domain/ui-service/types.d.ts +237 -0
  180. package/dist/domain/ui-service/types.js +5 -0
  181. package/dist/domain/ui-service/ui-service.d.ts +2 -0
  182. package/dist/domain/ui-service/ui-service.js +83 -0
  183. package/dist/entry/app.js +94 -5
  184. package/dist/entry/cli.d.ts +12 -0
  185. package/dist/entry/cli.js +122 -12
  186. package/dist/entry/feishu-login.d.ts +28 -0
  187. package/dist/entry/feishu-login.js +218 -0
  188. package/dist/entry/init.d.ts +25 -2
  189. package/dist/entry/init.js +211 -64
  190. package/dist/events/event-types.d.ts +14 -0
  191. package/dist/hooks/cortex-md-injector.mjs +47 -31
  192. package/dist/hooks/post-task-hook.mjs +6 -0
  193. package/dist/hooks/task-status-check.mjs +8 -0
  194. package/dist/orchestration/agent-runner.d.ts +2 -1
  195. package/dist/orchestration/agent-runner.js +55 -55
  196. package/dist/orchestration/conduit-queue.d.ts +18 -0
  197. package/dist/orchestration/conduit-queue.js +32 -0
  198. package/dist/orchestration/conversation-runner.d.ts +48 -0
  199. package/dist/orchestration/conversation-runner.js +109 -0
  200. package/dist/orchestration/dispatch-reconciler.js +8 -1
  201. package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
  202. package/dist/orchestration/interactions/ask-user-question.js +3 -3
  203. package/dist/orchestration/interactions/interaction-handlers.js +48 -17
  204. package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
  205. package/dist/orchestration/interactions/plan-handler.js +4 -3
  206. package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
  207. package/dist/orchestration/interactions/update-prompt.js +100 -0
  208. package/dist/orchestration/lifecycle.d.ts +4 -4
  209. package/dist/orchestration/lifecycle.js +24 -22
  210. package/dist/orchestration/orchestrator.d.ts +1 -1
  211. package/dist/orchestration/routing/commands/cancel.js +39 -47
  212. package/dist/orchestration/routing/commands/channel.js +24 -11
  213. package/dist/orchestration/routing/commands/cost.js +2 -1
  214. package/dist/orchestration/routing/commands/device.js +3 -2
  215. package/dist/orchestration/routing/commands/dispatch.js +6 -5
  216. package/dist/orchestration/routing/commands/index.d.ts +1 -1
  217. package/dist/orchestration/routing/commands/index.js +11 -10
  218. package/dist/orchestration/routing/commands/mode.js +19 -18
  219. package/dist/orchestration/routing/commands/nvtop.js +10 -9
  220. package/dist/orchestration/routing/commands/sendfile.js +7 -6
  221. package/dist/orchestration/routing/commands/session.d.ts +1 -1
  222. package/dist/orchestration/routing/commands/session.js +17 -33
  223. package/dist/orchestration/routing/commands/tail.js +4 -3
  224. package/dist/orchestration/routing/commands/task.js +4 -3
  225. package/dist/orchestration/routing/commands/thread-handlers.js +16 -6
  226. package/dist/orchestration/routing/edit-handler.js +8 -7
  227. package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
  228. package/dist/orchestration/routing/message-router.d.ts +1 -1
  229. package/dist/orchestration/routing/message-router.js +9 -9
  230. package/dist/orchestration/routing/webhook.js +233 -2
  231. package/dist/orchestration/status-helpers.d.ts +5 -1
  232. package/dist/orchestration/status-helpers.js +7 -6
  233. package/dist/orchestration/thread-callback.d.ts +67 -0
  234. package/dist/orchestration/thread-callback.js +465 -0
  235. package/dist/orchestration/thread-executor.d.ts +22 -1
  236. package/dist/orchestration/thread-executor.js +85 -36
  237. package/dist/platform/adapter.d.ts +6 -2
  238. package/dist/platform/adapters/composite-adapter.d.ts +89 -0
  239. package/dist/platform/adapters/composite-adapter.js +318 -0
  240. package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
  241. package/dist/platform/adapters/feishu-output-stream.js +274 -36
  242. package/dist/platform/adapters/feishu.d.ts +50 -5
  243. package/dist/platform/adapters/feishu.js +370 -116
  244. package/dist/platform/adapters/index.d.ts +24 -3
  245. package/dist/platform/adapters/index.js +89 -11
  246. package/dist/platform/adapters/project-conduits.d.ts +9 -0
  247. package/dist/platform/adapters/project-conduits.js +42 -0
  248. package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
  249. package/dist/platform/adapters/slack-project-conduits.js +6 -40
  250. package/dist/platform/adapters/slack.d.ts +9 -2
  251. package/dist/platform/adapters/slack.js +83 -39
  252. package/dist/platform/adapters/tui/index.d.ts +9 -0
  253. package/dist/platform/adapters/tui/index.js +10 -0
  254. package/dist/platform/adapters/tui/ports.d.ts +20 -0
  255. package/dist/platform/adapters/tui/ports.js +4 -0
  256. package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
  257. package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
  258. package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
  259. package/dist/platform/adapters/tui/tui-connection.js +53 -0
  260. package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
  261. package/dist/platform/adapters/tui/tui-gateway.js +919 -0
  262. package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
  263. package/dist/platform/adapters/tui/tui-notifications.js +60 -0
  264. package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
  265. package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
  266. package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
  267. package/dist/platform/adapters/tui/tui-transcript.js +56 -0
  268. package/dist/platform/index.d.ts +1 -0
  269. package/dist/platform/index.js +2 -1
  270. package/dist/platform/interactive-builder.js +3 -2
  271. package/dist/platform/output-stream.d.ts +5 -0
  272. package/dist/platform/testing.d.ts +7 -11
  273. package/dist/platform/testing.js +18 -15
  274. package/dist/platform/tool-trace.js +15 -5
  275. package/dist/platform/tui/protocol.d.ts +355 -0
  276. package/dist/platform/tui/protocol.js +199 -0
  277. package/dist/platform/types.d.ts +12 -3
  278. package/dist/store/execution-repo.d.ts +6 -1
  279. package/dist/store/execution-repo.js +13 -3
  280. package/dist/store/hook-sync.d.ts +18 -0
  281. package/dist/store/hook-sync.js +92 -0
  282. package/dist/store/outbound-queue.js +2 -2
  283. package/dist/store/profile-repo.js +3 -2
  284. package/dist/store/schedule-repo.d.ts +1 -8
  285. package/dist/store/session-registry-repo.d.ts +9 -1
  286. package/dist/store/session-registry-repo.js +19 -3
  287. package/dist/store/session-repo.d.ts +14 -0
  288. package/dist/store/session-repo.js +23 -0
  289. package/dist/store/thread-repo.d.ts +3 -0
  290. package/dist/store/thread-repo.js +49 -2
  291. package/dist/store/version-migrations.js +95 -0
  292. package/dist/tui/App.d.ts +27 -0
  293. package/dist/tui/App.js +219 -0
  294. package/dist/tui/components/AskUserModal.d.ts +11 -0
  295. package/dist/tui/components/AskUserModal.js +364 -0
  296. package/dist/tui/components/ConfirmModal.d.ts +12 -0
  297. package/dist/tui/components/ConfirmModal.js +31 -0
  298. package/dist/tui/components/Dashboard.d.ts +23 -0
  299. package/dist/tui/components/Dashboard.js +80 -0
  300. package/dist/tui/components/DashboardCostTab.d.ts +7 -0
  301. package/dist/tui/components/DashboardCostTab.js +16 -0
  302. package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
  303. package/dist/tui/components/DashboardExecutionsTab.js +94 -0
  304. package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
  305. package/dist/tui/components/DashboardSchedulesTab.js +124 -0
  306. package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
  307. package/dist/tui/components/DashboardTasksTab.js +200 -0
  308. package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
  309. package/dist/tui/components/DashboardThreadsTab.js +81 -0
  310. package/dist/tui/components/Header.d.ts +11 -0
  311. package/dist/tui/components/Header.js +5 -0
  312. package/dist/tui/components/InputBox.d.ts +10 -0
  313. package/dist/tui/components/InputBox.js +19 -0
  314. package/dist/tui/components/MessageRow.d.ts +7 -0
  315. package/dist/tui/components/MessageRow.js +10 -0
  316. package/dist/tui/components/Notifications.d.ts +19 -0
  317. package/dist/tui/components/Notifications.js +72 -0
  318. package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
  319. package/dist/tui/components/PlanFeedbackModal.js +161 -0
  320. package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
  321. package/dist/tui/components/ProjectSwitcher.js +43 -0
  322. package/dist/tui/components/SessionPicker.d.ts +14 -0
  323. package/dist/tui/components/SessionPicker.js +34 -0
  324. package/dist/tui/components/SidePanel.d.ts +19 -0
  325. package/dist/tui/components/SidePanel.js +8 -0
  326. package/dist/tui/components/StatusLine.d.ts +10 -0
  327. package/dist/tui/components/StatusLine.js +29 -0
  328. package/dist/tui/components/Transcript.d.ts +13 -0
  329. package/dist/tui/components/Transcript.js +56 -0
  330. package/dist/tui/hooks/useDashboardData.d.ts +32 -0
  331. package/dist/tui/hooks/useDashboardData.js +104 -0
  332. package/dist/tui/hooks/useKeybindings.d.ts +19 -0
  333. package/dist/tui/hooks/useKeybindings.js +87 -0
  334. package/dist/tui/hooks/useMutate.d.ts +22 -0
  335. package/dist/tui/hooks/useMutate.js +56 -0
  336. package/dist/tui/hooks/useNotifications.d.ts +28 -0
  337. package/dist/tui/hooks/useNotifications.js +70 -0
  338. package/dist/tui/hooks/useTranscript.d.ts +39 -0
  339. package/dist/tui/hooks/useTranscript.js +265 -0
  340. package/dist/tui/hooks/useWsClient.d.ts +29 -0
  341. package/dist/tui/hooks/useWsClient.js +69 -0
  342. package/dist/tui/index.d.ts +2 -0
  343. package/dist/tui/index.js +210 -0
  344. package/dist/tui/logic.d.ts +16 -0
  345. package/dist/tui/logic.js +49 -0
  346. package/dist/tui/render/markdown.d.ts +10 -0
  347. package/dist/tui/render/markdown.js +38 -0
  348. package/dist/tui/render/rich-blocks.d.ts +11 -0
  349. package/dist/tui/render/rich-blocks.js +24 -0
  350. package/dist/tui/ws-client.d.ts +44 -0
  351. package/dist/tui/ws-client.js +157 -0
  352. package/package.json +11 -3
  353. package/dist/orchestration/channel-queue.d.ts +0 -18
  354. package/dist/orchestration/channel-queue.js +0 -32
@@ -0,0 +1,919 @@
1
+ // input: ws, protocol.ts, PlatformAdapter, TuiConnection, TuiOutputStream, conduit-state, conduit-queue
2
+ // output: TuiGatewayAdapter (PlatformAdapter v2 + TuiAdapterControls) + WebSocket server
3
+ // pos: TUI adapter — bridges WS connections to PlatformAdapter interface
4
+ // >>> If I am updated, update the folder's CORTEX.md <<<
5
+ import { WebSocketServer } from 'ws';
6
+ import * as crypto from 'crypto';
7
+ import { PROTOCOL_VERSION, isHandshakeHello, isSessionSwitch, isMsgUser, isMsgEdit, isActionClick, isModalSubmit, isPing, isClose, isUiQuery, isUiMutate, isUiSubscribe, isUiUnsubscribe, parseFrame, } from '../../tui/protocol.js';
8
+ import { TuiConnection } from './tui-connection.js';
9
+ import { TuiOutputStream } from './tui-output-stream.js';
10
+ import { tuiConduitStates, getConduitState, setConduitState, deleteConduitState, } from './tui-conduit-state.js';
11
+ import { buildTranscriptReplay } from './tui-transcript.js';
12
+ import { createLogger } from '../../../core/log.js';
13
+ const log = createLogger('tui-gateway');
14
+ // ── Constants ─────
15
+ const KEEPALIVE_TIMEOUT_MS = 90_000;
16
+ const KEEPALIVE_CHECK_INTERVAL = 30_000;
17
+ const HANDSHAKE_TIMEOUT_MS = 5_000;
18
+ function makeTriggerId(conduitId) {
19
+ return `tui:${conduitId}:${crypto.randomUUID()}`;
20
+ }
21
+ function makeMessageId() {
22
+ return crypto.randomUUID();
23
+ }
24
+ export class TuiGatewayAdapter {
25
+ name = 'tui';
26
+ capabilities = {
27
+ threads: false,
28
+ messageEdit: true,
29
+ modals: true,
30
+ reactions: false,
31
+ fileUpload: true,
32
+ richFormatting: true,
33
+ maxMessageLength: 100_000,
34
+ maxThreadDepth: 0,
35
+ };
36
+ _wss = null;
37
+ _port;
38
+ _host;
39
+ _noopOutbound = false;
40
+ _connections = new Map();
41
+ _bus = null;
42
+ _uiService = null;
43
+ _sessionService = null;
44
+ _conduitQueue = null;
45
+ _busSubscriptions = [];
46
+ // PlatformAdapter handler registrations
47
+ _messageHandler = null;
48
+ _editHandler = null;
49
+ _actionHandlers = new Map();
50
+ _modalHandlers = new Map();
51
+ constructor(opts) {
52
+ this._port = opts?.port ?? parseInt(process.env.CORTEX_TUI_PORT ?? '3003', 10);
53
+ this._host = opts?.host ?? '127.0.0.1';
54
+ }
55
+ // ── TuiAdapterControls ──────────────────────────────────────────
56
+ setBus(bus) {
57
+ this._bus = bus;
58
+ }
59
+ setUiService(service) {
60
+ this._uiService = service;
61
+ }
62
+ setSessionService(service) {
63
+ this._sessionService = service;
64
+ }
65
+ setConduitQueue(queue) {
66
+ this._conduitQueue = queue;
67
+ }
68
+ /**
69
+ * Resolve in-memory session/project binding for a TUI conduit. Registered as a
70
+ * conduit provider by app.ts so session lookups can resolve ephemeral TUI conduits.
71
+ */
72
+ lookupConduit(conduitId) {
73
+ const state = getConduitState(conduitId);
74
+ if (!state)
75
+ return null;
76
+ return { sessionId: state.sessionId ?? '', projectId: state.projectId };
77
+ }
78
+ // ── Lifecycle ───────────────────────────────────────────────────
79
+ async start() {
80
+ // Bind WebSocket server — listen on 'listening' / 'error' for async binding
81
+ this._wss = new WebSocketServer({ port: this._port, host: this._host });
82
+ try {
83
+ await new Promise((resolve, reject) => {
84
+ this._wss.once('listening', () => resolve());
85
+ this._wss.once('error', (err) => reject(err));
86
+ });
87
+ }
88
+ catch (err) {
89
+ this._wss = null;
90
+ if (err.code === 'EADDRINUSE' || err.message?.includes('EADDRINUSE') || err.message?.includes('in use')) {
91
+ log.warn(`TUI port ${this._port} in use — adapter is no-op outbound`);
92
+ this._noopOutbound = true;
93
+ return;
94
+ }
95
+ throw err;
96
+ }
97
+ this._wss.on('connection', (ws, req) => {
98
+ this._handleConnection(ws, req);
99
+ });
100
+ this._wss.on('error', (err) => {
101
+ log.error('WebSocket server error:', err.message);
102
+ });
103
+ log.info(`TUI gateway listening on ws://${this._host}:${this._port}`);
104
+ // Subscribe to scheduler.tick for active conduit status
105
+ if (this._bus) {
106
+ this._busSubscriptions.push(this._bus.subscribe('scheduler.tick', (_e) => {
107
+ // Optionally push status updates to connections whose project matches
108
+ }));
109
+ }
110
+ }
111
+ async stop() {
112
+ // Unsubscribe from event bus
113
+ for (const sub of this._busSubscriptions) {
114
+ sub.unsubscribe();
115
+ }
116
+ this._busSubscriptions = [];
117
+ // Close all connections
118
+ for (const conn of this._connections.values()) {
119
+ conn.close(1001, 'server shutdown');
120
+ }
121
+ this._connections.clear();
122
+ // Close server
123
+ if (this._wss) {
124
+ await new Promise((resolve) => {
125
+ this._wss.close(() => resolve());
126
+ });
127
+ this._wss = null;
128
+ }
129
+ }
130
+ // ── Event registration (PlatformAdapter) ────────────────────────
131
+ onMessage(handler) {
132
+ this._messageHandler = handler;
133
+ }
134
+ onMessageEdit(handler) {
135
+ this._editHandler = handler;
136
+ }
137
+ onAction(actionId, handler) {
138
+ this._actionHandlers.set(actionId, handler);
139
+ }
140
+ onModalSubmit(callbackId, handler) {
141
+ this._modalHandlers.set(callbackId, handler);
142
+ }
143
+ // ── Outbound messaging ──────────────────────────────────────────
144
+ async postMessage(destination, content, opts) {
145
+ if (this._noopOutbound) {
146
+ return { conduit: '', messageId: '' };
147
+ }
148
+ if (destination.type === 'project-report') {
149
+ // 1. chat.post to matching project connections (preserves ref for updates)
150
+ const matchingConns = this._resolveTargetConnections(destination);
151
+ let primaryRef = { conduit: '', messageId: '' };
152
+ if (matchingConns.length > 0) {
153
+ const conn = matchingConns[0];
154
+ primaryRef = {
155
+ conduit: conn.conduitId,
156
+ messageId: makeMessageId(),
157
+ threadId: opts?.threadId || null,
158
+ };
159
+ conn.send({
160
+ type: 'chat.post',
161
+ ref: primaryRef,
162
+ content,
163
+ seq: 0,
164
+ });
165
+ }
166
+ else {
167
+ log.warn('postMessage: no matching connection for project-report destination', destination);
168
+ }
169
+ // 2. Notification frames to ALL connections (cross-project fan-out)
170
+ const matchingIds = new Set(matchingConns.map(c => c.conduitId));
171
+ for (const conn of this._connections.values()) {
172
+ if (matchingIds.has(conn.conduitId))
173
+ continue;
174
+ conn.send({
175
+ type: 'notification',
176
+ kind: 'project-report',
177
+ projectId: destination.projectId,
178
+ sessionId: destination.sessionId ?? '',
179
+ title: `Report: ${destination.projectId}`,
180
+ body: content.text,
181
+ seq: 0,
182
+ });
183
+ }
184
+ return primaryRef;
185
+ }
186
+ const conns = this._resolveTargetConnections(destination);
187
+ if (conns.length === 0) {
188
+ log.warn('postMessage: no matching connection for destination', destination);
189
+ return { conduit: '', messageId: '' };
190
+ }
191
+ // Send to the first matching connection
192
+ const conn = conns[0];
193
+ const ref = {
194
+ conduit: conn.conduitId,
195
+ messageId: makeMessageId(),
196
+ threadId: opts?.threadId || null,
197
+ };
198
+ conn.send({
199
+ type: 'chat.post',
200
+ ref,
201
+ content,
202
+ seq: 0,
203
+ });
204
+ return ref;
205
+ }
206
+ async updateMessage(ref, content) {
207
+ if (this._noopOutbound)
208
+ return;
209
+ const conn = this._connections.get(ref.conduit);
210
+ if (!conn) {
211
+ log.warn('updateMessage: unknown conduit', ref.conduit);
212
+ return;
213
+ }
214
+ conn.send({
215
+ type: 'chat.update',
216
+ ref,
217
+ content,
218
+ seq: 0,
219
+ });
220
+ }
221
+ async deleteMessage(ref) {
222
+ if (this._noopOutbound)
223
+ return;
224
+ const conn = this._connections.get(ref.conduit);
225
+ if (!conn) {
226
+ log.warn('deleteMessage: unknown conduit', ref.conduit);
227
+ return;
228
+ }
229
+ conn.send({
230
+ type: 'chat.delete',
231
+ ref,
232
+ seq: 0,
233
+ });
234
+ }
235
+ async postInteractive(destination, content, opts) {
236
+ if (this._noopOutbound) {
237
+ return { conduit: '', messageId: '' };
238
+ }
239
+ const conns = this._resolveTargetConnections(destination);
240
+ if (conns.length === 0) {
241
+ log.warn('postInteractive: no matching connection for destination', destination);
242
+ return { conduit: '', messageId: '' };
243
+ }
244
+ const conn = conns[0];
245
+ const ref = {
246
+ conduit: conn.conduitId,
247
+ messageId: makeMessageId(),
248
+ threadId: opts?.threadId || null,
249
+ };
250
+ conn.send({
251
+ type: 'interactive.post',
252
+ ref,
253
+ content: { text: content.text, richBlocks: content.richBlocks },
254
+ actions: content.actions,
255
+ seq: 0,
256
+ });
257
+ return ref;
258
+ }
259
+ async openModal(triggerId, modal) {
260
+ if (this._noopOutbound)
261
+ return;
262
+ const conn = this._resolveConnectionByTriggerId(triggerId);
263
+ if (!conn) {
264
+ log.warn('openModal: no connection for triggerId', triggerId);
265
+ return;
266
+ }
267
+ conn.send({
268
+ type: 'modal.open',
269
+ triggerId,
270
+ modal,
271
+ seq: 0,
272
+ });
273
+ }
274
+ async markQueued(ref) {
275
+ if (this._noopOutbound)
276
+ return;
277
+ const conn = this._connections.get(ref.conduit);
278
+ if (!conn) {
279
+ log.warn('markQueued: unknown conduit', ref.conduit);
280
+ return;
281
+ }
282
+ conn.send({
283
+ type: 'chat.markQueued',
284
+ ref,
285
+ seq: 0,
286
+ });
287
+ }
288
+ async uploadFile(destination, filePath, _opts) {
289
+ if (this._noopOutbound)
290
+ return;
291
+ const conns = this._resolveTargetConnections(destination);
292
+ if (conns.length === 0) {
293
+ log.warn('uploadFile: no matching connection for destination', destination);
294
+ return;
295
+ }
296
+ const conn = conns[0];
297
+ conn.send({
298
+ type: 'notification',
299
+ kind: 'system-notice',
300
+ projectId: conn.activeProjectId,
301
+ title: 'File available',
302
+ body: `Absolute path: ${filePath}`,
303
+ seq: 0,
304
+ });
305
+ }
306
+ async downloadFile(fileRef, destDir) {
307
+ // TUI files are already local — just copy the path reference
308
+ return {
309
+ localPath: fileRef.url, // url field doubles as local path for TUI
310
+ mimetype: fileRef.mimetype,
311
+ name: fileRef.name,
312
+ };
313
+ }
314
+ async getPermalink(ref) {
315
+ // No permalink concept in TUI
316
+ return null;
317
+ }
318
+ // ── Output stream ───────────────────────────────────────────────
319
+ openOutputStream(destination, opts) {
320
+ const conns = this._resolveTargetConnections(destination);
321
+ const conn = conns[0];
322
+ if (!conn) {
323
+ // Return a no-op output stream if no matching connection
324
+ return this._createNoopOutputStream();
325
+ }
326
+ return new TuiOutputStream(conn, destination, this, opts);
327
+ }
328
+ _createNoopOutputStream() {
329
+ const noopRefs = [];
330
+ return {
331
+ emitText: () => { },
332
+ openMutable: () => ({ update: () => { } }),
333
+ postInteractive: async () => null,
334
+ flush: async () => { },
335
+ getRefs: () => noopRefs,
336
+ getParentRef: () => null,
337
+ };
338
+ }
339
+ // ── Project conduit mapping ─────────────────────────────────────
340
+ async bindProjectConduit(projectId, conduitHint) {
341
+ // TUI conduits are already project-bound via activeProjectId
342
+ // conduitHint is the tui conduitId
343
+ const state = getConduitState(conduitHint);
344
+ if (state) {
345
+ setConduitState(conduitHint, { ...state, projectId });
346
+ }
347
+ }
348
+ async unbindProjectConduit(projectId) {
349
+ // Remove project binding from all conduits matching this project
350
+ for (const [conduitId, state] of tuiConduitStates) {
351
+ if (state.projectId === projectId) {
352
+ setConduitState(conduitId, { ...state, projectId: 'general' });
353
+ }
354
+ }
355
+ }
356
+ async getProjectConduits() {
357
+ const result = {};
358
+ for (const [conduitId, state] of tuiConduitStates) {
359
+ if (!result[state.projectId]) {
360
+ result[state.projectId] = conduitId;
361
+ }
362
+ }
363
+ return result;
364
+ }
365
+ async resolveInboundProject(conduit) {
366
+ const state = getConduitState(conduit);
367
+ return state?.projectId ?? null;
368
+ }
369
+ /** TUI conduits are `tui-<uuid>` and triggerIds are `tui:<conduitId>:<uuid>`. */
370
+ ownsConduit(conduit) {
371
+ return conduit.startsWith('tui-') || conduit.startsWith('tui:');
372
+ }
373
+ // ── Helpers: utilities ──────────────────────────────────────────
374
+ /** Expose connections for testing and notification routing. */
375
+ get connections() {
376
+ return this._connections;
377
+ }
378
+ /** Expose noop flag for testing. */
379
+ get noopOutbound() {
380
+ return this._noopOutbound;
381
+ }
382
+ // ── Private: connection lifecycle ───────────────────────────────
383
+ _handleConnection(ws, _req) {
384
+ const conduitId = `tui-${crypto.randomUUID().slice(0, 8)}`;
385
+ const projectId = 'general';
386
+ const conn = new TuiConnection(conduitId, ws, projectId);
387
+ this._connections.set(conduitId, conn);
388
+ setConduitState(conduitId, { sessionId: null, projectId, backend: 'tui' });
389
+ log.info(`New TUI connection: ${conduitId}`);
390
+ // Handshake timeout
391
+ let handshakeReceived = false;
392
+ const handshakeTimer = setTimeout(() => {
393
+ if (!handshakeReceived) {
394
+ conn.close(4001, 'handshake timeout');
395
+ this._cleanupConnection(conduitId);
396
+ }
397
+ }, HANDSHAKE_TIMEOUT_MS);
398
+ // Keepalive tracking
399
+ let lastPing = Date.now();
400
+ const keepaliveTimer = setInterval(() => {
401
+ if (conn.closed) {
402
+ clearInterval(keepaliveTimer);
403
+ return;
404
+ }
405
+ if (Date.now() - lastPing > KEEPALIVE_TIMEOUT_MS) {
406
+ log.warn(`Keepalive timeout for conduit ${conduitId}`);
407
+ conn.close(4001, 'keepalive-timeout');
408
+ this._cleanupConnection(conduitId);
409
+ clearInterval(keepaliveTimer);
410
+ }
411
+ }, KEEPALIVE_CHECK_INTERVAL);
412
+ // Message handler
413
+ ws.on('message', (data) => {
414
+ const raw = data.toString('utf8');
415
+ const frame = parseFrame(raw);
416
+ if (!frame) {
417
+ // Check if raw JSON parses to an object with an unknown type string
418
+ let parsed;
419
+ try {
420
+ parsed = JSON.parse(raw);
421
+ }
422
+ catch {
423
+ parsed = null;
424
+ }
425
+ if (parsed && typeof parsed?.type === 'string') {
426
+ // Valid JSON, unknown type → error 4002 (no close)
427
+ conn.send({
428
+ type: 'error',
429
+ code: 4002,
430
+ message: `Unknown frame type: ${parsed.type}`,
431
+ refId: parsed.id,
432
+ });
433
+ return;
434
+ }
435
+ // Invalid JSON / missing type → parse error 4001
436
+ conn.send({
437
+ type: 'error',
438
+ code: 4001,
439
+ message: 'Failed to parse frame',
440
+ });
441
+ return;
442
+ }
443
+ // Handshake gate: only handshake.hello is accepted before handshake
444
+ if (!handshakeReceived) {
445
+ if (isHandshakeHello(frame)) {
446
+ handshakeReceived = true;
447
+ clearTimeout(handshakeTimer);
448
+ this._handleHandshake(conn, frame);
449
+ }
450
+ else {
451
+ conn.send({
452
+ type: 'error',
453
+ code: 4001,
454
+ message: 'Expected handshake.hello first',
455
+ closeAfter: true,
456
+ });
457
+ conn.close(4001, 'expected handshake.hello');
458
+ this._cleanupConnection(conduitId);
459
+ }
460
+ return;
461
+ }
462
+ // Dispatch by type
463
+ this._dispatchInboundFrame(conn, frame);
464
+ });
465
+ // Handle close
466
+ ws.on('close', () => {
467
+ clearTimeout(handshakeTimer);
468
+ clearInterval(keepaliveTimer);
469
+ this._cleanupConnection(conduitId);
470
+ });
471
+ ws.on('error', (err) => {
472
+ log.warn(`WebSocket error for conduit ${conduitId}:`, err.message);
473
+ clearTimeout(handshakeTimer);
474
+ clearInterval(keepaliveTimer);
475
+ this._cleanupConnection(conduitId);
476
+ });
477
+ }
478
+ _dispatchInboundFrame(conn, frame) {
479
+ if (isSessionSwitch(frame)) {
480
+ this._handleSessionSwitch(conn, frame);
481
+ }
482
+ else if (isMsgUser(frame)) {
483
+ this._handleMsgUser(conn, frame);
484
+ }
485
+ else if (isMsgEdit(frame)) {
486
+ this._handleMsgEdit(conn, frame);
487
+ }
488
+ else if (isActionClick(frame)) {
489
+ this._handleActionClick(conn, frame);
490
+ }
491
+ else if (isModalSubmit(frame)) {
492
+ this._handleModalSubmit(conn, frame);
493
+ }
494
+ else if (isPing(frame)) {
495
+ // Respond with pong
496
+ conn.send({ type: 'pong', ts: Date.now() });
497
+ }
498
+ else if (isClose(frame)) {
499
+ conn.close(1000, frame.reason || 'client close');
500
+ this._cleanupConnection(conn.conduitId);
501
+ }
502
+ else if (isUiQuery(frame)) {
503
+ this._handleUiQuery(conn, frame);
504
+ }
505
+ else if (isUiMutate(frame)) {
506
+ this._handleUiMutate(conn, frame);
507
+ }
508
+ else if (isUiSubscribe(frame)) {
509
+ this._handleUiSubscribe(conn, frame);
510
+ }
511
+ else if (isUiUnsubscribe(frame)) {
512
+ this._handleUiUnsubscribe(conn, frame);
513
+ }
514
+ else {
515
+ // Unknown frame type
516
+ conn.send({
517
+ type: 'error',
518
+ code: 4002,
519
+ message: `Unknown frame type: ${frame.type}`,
520
+ refId: frame.id,
521
+ });
522
+ }
523
+ }
524
+ // ── Private: handshake ──────────────────────────────────────────
525
+ async _handleHandshake(conn, frame) {
526
+ if (!isHandshakeHello(frame))
527
+ return;
528
+ // Protocol version check
529
+ if (frame.protocolVersion !== PROTOCOL_VERSION) {
530
+ conn.send({
531
+ type: 'error',
532
+ code: 4000,
533
+ message: `Protocol version mismatch: expected ${PROTOCOL_VERSION}, got ${frame.protocolVersion}`,
534
+ closeAfter: true,
535
+ });
536
+ conn.close(4000, 'protocol version mismatch');
537
+ return;
538
+ }
539
+ // Send handshake ack
540
+ conn.send({
541
+ type: 'handshake.ack',
542
+ protocolVersion: PROTOCOL_VERSION,
543
+ serverVersion: process.env.CORTEX_VERSION || 'dev',
544
+ conduitId: conn.conduitId,
545
+ defaultProjectId: frame.project ?? 'general',
546
+ seq: 0,
547
+ });
548
+ // Resolve initial project
549
+ const projectId = frame.project ?? 'general';
550
+ conn.activeProjectId = projectId;
551
+ setConduitState(conn.conduitId, { sessionId: null, projectId, backend: 'tui' });
552
+ // Handle session resume or fresh — delegated to the injected session service
553
+ if (!this._sessionService) {
554
+ conn.send({ type: 'error', code: 4500, message: 'Session service unavailable' });
555
+ return;
556
+ }
557
+ const res = await this._sessionService.resolveHandshake({
558
+ conduitId: conn.conduitId,
559
+ projectId,
560
+ resumeSessionId: frame.resume?.sessionId ?? null,
561
+ });
562
+ if (res.emitNotFoundError) {
563
+ conn.send({
564
+ type: 'error',
565
+ code: 4003,
566
+ message: `Session ${frame.resume?.sessionId} not found, creating fresh session`,
567
+ });
568
+ }
569
+ conn.activeSessionId = res.sessionId;
570
+ conn.activeProjectId = res.projectId;
571
+ setConduitState(conn.conduitId, { sessionId: res.sessionId, projectId: res.projectId, backend: 'tui' });
572
+ conn.send({
573
+ type: 'session.switched',
574
+ id: '',
575
+ projectId: res.projectId,
576
+ sessionId: res.sessionId,
577
+ sessionName: res.sessionName,
578
+ isFresh: res.isFresh,
579
+ seq: 1,
580
+ });
581
+ if (res.transcript) {
582
+ const replay = buildTranscriptReplay(res.transcript);
583
+ if (replay)
584
+ conn.send(replay);
585
+ }
586
+ }
587
+ // ── Private: session switch ─────────────────────────────────────
588
+ async _handleSessionSwitch(conn, frame) {
589
+ if (!isSessionSwitch(frame))
590
+ return;
591
+ const { id, projectId, sessionId } = frame;
592
+ if (!this._sessionService) {
593
+ conn.send({ type: 'error', code: 4500, message: 'Session service unavailable', refId: id });
594
+ return;
595
+ }
596
+ const res = await this._sessionService.switchSession({
597
+ conduitId: conn.conduitId,
598
+ projectId,
599
+ sessionId: sessionId ?? null,
600
+ });
601
+ conn.activeSessionId = res.sessionId;
602
+ conn.activeProjectId = res.projectId;
603
+ setConduitState(conn.conduitId, { sessionId: res.sessionId, projectId: res.projectId, backend: 'tui' });
604
+ conn.send({
605
+ type: 'session.switched',
606
+ id,
607
+ projectId: res.projectId,
608
+ sessionId: res.sessionId,
609
+ sessionName: res.sessionName,
610
+ isFresh: res.isFresh,
611
+ seq: 1,
612
+ });
613
+ if (res.transcript) {
614
+ const replay = buildTranscriptReplay(res.transcript);
615
+ if (replay)
616
+ conn.send(replay);
617
+ }
618
+ }
619
+ // ── Private: inbound message handling ───────────────────────────
620
+ async _handleMsgUser(conn, frame) {
621
+ if (!isMsgUser(frame) || !this._messageHandler)
622
+ return;
623
+ const { id, text, threadAnchorId, attachments } = frame;
624
+ // Build incoming message
625
+ const ref = {
626
+ conduit: conn.conduitId,
627
+ messageId: makeMessageId(),
628
+ threadId: threadAnchorId || null,
629
+ };
630
+ const files = attachments?.map((a, i) => ({
631
+ id: `tui-file-${i}`,
632
+ name: a.name,
633
+ mimetype: a.mimeType,
634
+ url: a.path,
635
+ conduit: conn.conduitId,
636
+ raw: a,
637
+ }));
638
+ const incoming = {
639
+ ref,
640
+ text,
641
+ senderId: 'tui-user',
642
+ isBot: false,
643
+ files,
644
+ kind: 'user',
645
+ raw: frame,
646
+ };
647
+ // Enqueue into per-conduit serial queue (injected port wraps the shared singleton)
648
+ const run = async () => {
649
+ const adapter = this;
650
+ await this._messageHandler({
651
+ message: incoming,
652
+ async reply(content, replyOpts) {
653
+ return adapter.postMessage({ type: 'interactive-reply', conduit: conn.conduitId, sessionId: conn.activeSessionId ?? '' }, content, { threadId: replyOpts?.threadId || ref.threadId });
654
+ },
655
+ });
656
+ };
657
+ if (this._conduitQueue)
658
+ this._conduitQueue.enqueue(conn.conduitId, run);
659
+ else
660
+ void run();
661
+ }
662
+ async _handleMsgEdit(conn, frame) {
663
+ if (!isMsgEdit(frame) || !this._editHandler)
664
+ return;
665
+ await this._editHandler({
666
+ originalRef: frame.ref,
667
+ newText: frame.newText,
668
+ raw: frame,
669
+ });
670
+ }
671
+ async _handleActionClick(conn, frame) {
672
+ if (!isActionClick(frame))
673
+ return;
674
+ const { actionId, value, triggerId, messageRef, userId } = frame;
675
+ const handler = this._actionHandlers.get(actionId);
676
+ if (!handler) {
677
+ log.warn(`No action handler for "${actionId}"`);
678
+ return;
679
+ }
680
+ await handler({
681
+ actionId,
682
+ value,
683
+ triggerId,
684
+ messageRef,
685
+ userId,
686
+ channelId: conn.conduitId,
687
+ });
688
+ }
689
+ async _handleModalSubmit(conn, frame) {
690
+ if (!isModalSubmit(frame))
691
+ return;
692
+ const { id, callbackId, privateMetadata, values, userId } = frame;
693
+ const handler = this._modalHandlers.get(callbackId);
694
+ if (!handler) {
695
+ log.warn(`No modal submit handler for "${callbackId}"`);
696
+ return;
697
+ }
698
+ let acked = false;
699
+ await handler({
700
+ callbackId,
701
+ privateMetadata,
702
+ values,
703
+ userId,
704
+ async ack(response) {
705
+ if (acked)
706
+ return;
707
+ acked = true;
708
+ conn.send({
709
+ type: 'modal.ack',
710
+ id,
711
+ errors: response?.errors,
712
+ seq: 0,
713
+ });
714
+ },
715
+ });
716
+ if (!acked) {
717
+ conn.send({
718
+ type: 'modal.ack',
719
+ id,
720
+ seq: 0,
721
+ });
722
+ }
723
+ }
724
+ // ── Private: UI side-channel ────────────────────────────────────
725
+ async _handleUiQuery(conn, frame) {
726
+ if (!isUiQuery(frame))
727
+ return;
728
+ if (!this._uiService) {
729
+ conn.send({
730
+ type: 'ui.queryResult',
731
+ id: frame.id,
732
+ ok: false,
733
+ error: { code: 'ui-service-unavailable', message: 'UI service not yet available (M3)' },
734
+ });
735
+ return;
736
+ }
737
+ try {
738
+ const uiService = this._uiService;
739
+ const result = await uiService.query(frame.scope, frame.params ?? {});
740
+ if (result.ok) {
741
+ conn.send({
742
+ type: 'ui.queryResult',
743
+ id: frame.id,
744
+ ok: true,
745
+ data: result.data,
746
+ });
747
+ }
748
+ else {
749
+ conn.send({
750
+ type: 'ui.queryResult',
751
+ id: frame.id,
752
+ ok: false,
753
+ error: { code: result.code ?? 'unknown', message: result.message ?? '' },
754
+ });
755
+ }
756
+ }
757
+ catch (err) {
758
+ conn.send({
759
+ type: 'ui.queryResult',
760
+ id: frame.id,
761
+ ok: false,
762
+ error: { code: 'internal', message: err?.message || String(err) },
763
+ });
764
+ }
765
+ }
766
+ async _handleUiMutate(conn, frame) {
767
+ if (!isUiMutate(frame))
768
+ return;
769
+ if (!this._uiService) {
770
+ conn.send({
771
+ type: 'ui.mutateResult',
772
+ id: frame.id,
773
+ ok: false,
774
+ error: { code: 'ui-service-unavailable', message: 'UI service not yet available (M3)' },
775
+ });
776
+ return;
777
+ }
778
+ try {
779
+ const uiService = this._uiService;
780
+ const result = await uiService.mutate(frame.op, frame.args ?? {});
781
+ if (result.ok) {
782
+ conn.send({ type: 'ui.mutateResult', id: frame.id, ok: true });
783
+ }
784
+ else {
785
+ conn.send({
786
+ type: 'ui.mutateResult',
787
+ id: frame.id,
788
+ ok: false,
789
+ error: { code: result.code ?? 'unknown', message: result.message ?? '' },
790
+ });
791
+ }
792
+ }
793
+ catch (err) {
794
+ conn.send({
795
+ type: 'ui.mutateResult',
796
+ id: frame.id,
797
+ ok: false,
798
+ error: { code: 'internal', message: err?.message || String(err) },
799
+ });
800
+ }
801
+ }
802
+ _handleUiSubscribe(conn, frame) {
803
+ if (!isUiSubscribe(frame))
804
+ return;
805
+ if (!this._uiService) {
806
+ conn.send({
807
+ type: 'error',
808
+ code: 4100,
809
+ message: 'UI service not yet available (M3)',
810
+ refId: frame.id,
811
+ });
812
+ return;
813
+ }
814
+ const uiService = this._uiService;
815
+ // Close existing subscription with same id if any
816
+ const existing = conn.activeSubscriptions.get(frame.id);
817
+ if (existing) {
818
+ existing.close();
819
+ conn.activeSubscriptions.delete(frame.id);
820
+ }
821
+ conn.uiSubscriptions.add(frame.id);
822
+ const subscription = uiService.subscribe(frame.filter);
823
+ conn.activeSubscriptions.set(frame.id, subscription);
824
+ // Forward subscription events to connection in background
825
+ this._forwardSubscriptionEvents(conn, frame.id, subscription);
826
+ }
827
+ async _forwardSubscriptionEvents(conn, subscribeId, subscription) {
828
+ try {
829
+ for await (const event of subscription) {
830
+ if (conn.closed)
831
+ break;
832
+ conn.send({
833
+ type: 'ui.event',
834
+ id: subscribeId,
835
+ event,
836
+ seq: 0,
837
+ });
838
+ }
839
+ }
840
+ catch (err) {
841
+ log.warn(`Subscription ${subscribeId} error:`, err?.message || err);
842
+ }
843
+ finally {
844
+ conn.activeSubscriptions.delete(subscribeId);
845
+ }
846
+ }
847
+ _handleUiUnsubscribe(conn, frame) {
848
+ if (!isUiUnsubscribe(frame))
849
+ return;
850
+ conn.uiSubscriptions.delete(frame.id);
851
+ const sub = conn.activeSubscriptions.get(frame.id);
852
+ if (sub) {
853
+ sub.close();
854
+ conn.activeSubscriptions.delete(frame.id);
855
+ }
856
+ }
857
+ // ── Private: target resolution ──────────────────────────────────
858
+ _resolveTargetConnections(destination) {
859
+ switch (destination.type) {
860
+ case 'interactive-reply': {
861
+ if (destination.sessionId) {
862
+ const conn = this._findConnectionBySessionId(destination.sessionId);
863
+ return conn ? [conn] : [];
864
+ }
865
+ // Fall back to conduit lookup
866
+ const conn = this._connections.get(destination.conduit);
867
+ return conn ? [conn] : [];
868
+ }
869
+ case 'project-report': {
870
+ // Fan-out to connections whose project matches
871
+ const matching = [];
872
+ for (const conn of this._connections.values()) {
873
+ if (conn.activeProjectId === destination.projectId) {
874
+ matching.push(conn);
875
+ }
876
+ }
877
+ return matching;
878
+ }
879
+ case 'system-notice':
880
+ return Array.from(this._connections.values());
881
+ default:
882
+ return [];
883
+ }
884
+ }
885
+ _findConnectionBySessionId(sessionId) {
886
+ for (const conn of this._connections.values()) {
887
+ if (conn.activeSessionId === sessionId)
888
+ return conn;
889
+ }
890
+ return undefined;
891
+ }
892
+ _resolveConnectionByTriggerId(triggerId) {
893
+ // Format: tui:<conduitId>:<uuid>
894
+ const parts = triggerId.split(':');
895
+ if (parts.length >= 3 && parts[0] === 'tui') {
896
+ return this._connections.get(parts[1]);
897
+ }
898
+ return undefined;
899
+ }
900
+ // ── Private: cleanup ────────────────────────────────────────────
901
+ _cleanupConnection(conduitId) {
902
+ const conn = this._connections.get(conduitId);
903
+ if (!conn)
904
+ return;
905
+ // Unsubscribe all UI subscriptions — close active subscription handles first
906
+ for (const [, sub] of conn.activeSubscriptions) {
907
+ sub.close();
908
+ }
909
+ conn.activeSubscriptions.clear();
910
+ conn.uiSubscriptions.clear();
911
+ conn.pendingActions.clear();
912
+ conn.pendingModalAcks.clear();
913
+ // Drop from registry
914
+ this._connections.delete(conduitId);
915
+ deleteConduitState(conduitId);
916
+ this._conduitQueue?.remove(conduitId);
917
+ log.info(`TUI connection cleaned up: ${conduitId}`);
918
+ }
919
+ }