@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,21 +1,23 @@
1
- // input: orch/busy-tracker(trackPendingTask), orch/channel-queue, orch/interactions/plan-approvals, ask-user-question, hook-bridge, adapter
1
+ // input: orch/busy-tracker(trackPendingTask), orch/conduit-queue, orch/interactions/plan-approvals, ask-user-question, hook-bridge, adapter
2
2
  // output: registerInteractionHandlers(adapter)
3
3
  // pos: AskUserQuestion + ExitPlanMode interaction handler registration
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { buildPlanFeedbackModal } from '../../platform/index.js';
6
6
  import { trackPendingTask } from '../busy-tracker.js';
7
- import { enqueue } from '../channel-queue.js';
7
+ import { enqueue } from '../conduit-queue.js';
8
8
  import * as askUserQuestion from './ask-user-question.js';
9
9
  import { resolveRequest as resolveHookRequest, getStreamingCallback } from '../routing/hook-bridge.js';
10
10
  import { resumeAskUserQuestionGroup } from '../lifecycle.js';
11
11
  import { planApprovals } from './plan-approvals.js';
12
12
  import { runningExecutions } from '../../core/running-executions.js';
13
- import { channelQueues } from '../channel-queue.js';
13
+ import * as executionRegistry from '../../domain/executions/registry.js';
14
+ import { conduitQueues } from '../conduit-queue.js';
14
15
  import { setSessionAsync, deleteSessionAsync } from '../../domain/sessions/session.js';
15
16
  import { sessionStore } from '../../store/session-registry-repo.js';
16
17
  import { conversationLedger } from '../../store/conversation-ledger-repo.js';
17
18
  import { closeSession, getActiveBackend, getActiveProfile, setActiveProfile, resolveBackendForChannel } from '../../domain/agents/index.js';
18
19
  import { fireAndForgetPreCloseHook } from '../../domain/sessions/session-hooks.js';
20
+ import { Icons } from '../../core/icons.js';
19
21
  import * as sessionBackup from '../../domain/sessions/session-backup.js';
20
22
  import { cancelThread as cancelThreadById } from '../../domain/threads/index.js';
21
23
  import { createLogger } from '../../core/log.js';
@@ -45,8 +47,9 @@ async function handleOpenModal(ctx) {
45
47
  if (group && askUserQuestion.isExpired(group))
46
48
  askUserQuestion.deleteGroup(group.groupId);
47
49
  const msg = group ? 'This AskUserQuestion prompt has expired. Please ask again if you still need it.' : 'This AskUserQuestion prompt is no longer active.';
48
- if (ctx.channelId && ctx.userId) {
49
- await _adapter.postEphemeral(ctx.channelId, ctx.userId, msg).catch(() => { });
50
+ if (ctx.channelId) {
51
+ const expiredDest = { type: 'interactive-reply', conduit: ctx.channelId, sessionId: '' };
52
+ await _adapter.postMessage(expiredDest, { text: msg }).catch(() => { });
50
53
  }
51
54
  return;
52
55
  }
@@ -133,7 +136,7 @@ function collectModalAnswers(group, values) {
133
136
  async function updateQuestionMessage(group) {
134
137
  if (!group.responseMessageTs || !_adapter)
135
138
  return;
136
- await _adapter.updateMessage({ channel: group.channel, messageId: group.responseMessageTs }, {
139
+ await _adapter.updateMessage({ conduit: group.channel, messageId: group.responseMessageTs }, {
137
140
  text: `Questions (${group.answers.size}/${group.questions.length} answered)`,
138
141
  richBlocks: askUserQuestion.buildQuestionGroupBlocks(group),
139
142
  }).catch(() => { });
@@ -161,7 +164,7 @@ function dispatchAskUserQuestionResume(group) {
161
164
  function tryResolvePIPlan(pending, value) {
162
165
  if (!pending.extensionUiId)
163
166
  return false;
164
- const exec = runningExecutions.getByKey(pending.channel);
167
+ const exec = runningExecutions.getByChannel(pending.channel).find(e => e.agentProcess) ?? null;
165
168
  if (!exec?.agentProcess)
166
169
  return false;
167
170
  const proc = exec.agentProcess;
@@ -187,8 +190,8 @@ function registerExitPlanModeHandlers(adapter) {
187
190
  }
188
191
  if (ctx.messageRef) {
189
192
  await adapter.updateMessage(ctx.messageRef, {
190
- text: ':white_check_mark: Plan approved \u2014 Cortex will proceed.',
191
- richBlocks: [{ type: 'section', text: ':white_check_mark: *Plan approved* \u2014 Cortex will proceed.' }],
193
+ text: `${Icons.ok} Plan approved \u2014 Cortex will proceed.`,
194
+ richBlocks: [{ type: 'section', text: `${Icons.ok} *Plan approved* \u2014 Cortex will proceed.` }],
192
195
  }).catch(() => { });
193
196
  }
194
197
  });
@@ -209,7 +212,7 @@ function registerExitPlanModeHandlers(adapter) {
209
212
  if (!tryResolvePIPlan(pending, feedback)) {
210
213
  resolveHookRequest(requestId, { approved: false, reason: feedback });
211
214
  }
212
- const feedbackText = `:pencil2: Plan feedback sent \u2014 Cortex will revise.\n> ${feedback}`;
215
+ const feedbackText = `${Icons.edit} Plan feedback sent \u2014 Cortex will revise.\n> ${feedback}`;
213
216
  const streamingCb = getStreamingCallback(pending.channel);
214
217
  const feedbackDest = { type: 'interactive-reply', conduit: pending.channel, sessionId: '' };
215
218
  if (streamingCb) {
@@ -231,16 +234,39 @@ async function handleStatusCancel(ctx) {
231
234
  return;
232
235
  let channel;
233
236
  let threadId;
237
+ let executionId;
234
238
  try {
235
239
  const parsed = JSON.parse(ctx.value);
236
240
  channel = parsed.channel;
237
241
  threadId = parsed.threadId ?? null;
242
+ executionId = parsed.executionId ?? null;
238
243
  }
239
244
  catch {
240
245
  return;
241
246
  }
247
+ // Conversation path: plain user messages are no longer wrapped in a thread, so the
248
+ // Cancel button carries an executionId. Resolve and kill via the execution index;
249
+ // there is no thread to cancel.
250
+ if (!threadId && executionId) {
251
+ const exec = runningExecutions.getById(executionId);
252
+ if (!exec) {
253
+ log.warn('Cancel button clicked but no running execution for executionId', { channel, executionId });
254
+ return;
255
+ }
256
+ if (exec.sessionId)
257
+ await setSessionAsync(exec.channel ?? channel, exec.sessionId, getActiveBackend()).catch(() => { });
258
+ // teardownExecution(cancelled): record→cancelled, kill the handle, publish a balanced event.
259
+ executionRegistry.teardownExecution({ executionId, status: 'cancelled', durationS: 0 });
260
+ conduitQueues.delete(exec.channel ?? channel);
261
+ if (ctx.messageRef) {
262
+ await _adapter.updateMessage(ctx.messageRef, {
263
+ text: `${Icons.stopped} Cancelled. Session preserved — next message will resume.`,
264
+ }).catch(() => { });
265
+ }
266
+ return;
267
+ }
242
268
  if (!threadId) {
243
- log.warn('Cancel button clicked but threadId missing in value', { channel });
269
+ log.warn('Cancel button clicked but threadId/executionId missing in value', { channel });
244
270
  return;
245
271
  }
246
272
  const exec = runningExecutions.getByThreadId(threadId);
@@ -251,11 +277,16 @@ async function handleStatusCancel(ctx) {
251
277
  await cancelThreadById(threadId).catch(() => { });
252
278
  if (exec.sessionId)
253
279
  await setSessionAsync(exec.channel ?? channel, exec.sessionId, getActiveBackend()).catch(() => { });
254
- runningExecutions.killByThreadId(threadId);
255
- channelQueues.delete(exec.channel ?? channel);
280
+ if (exec.executionId) {
281
+ executionRegistry.teardownExecution({ executionId: exec.executionId, status: 'cancelled', durationS: 0 });
282
+ }
283
+ else {
284
+ runningExecutions.killByThreadId(threadId);
285
+ }
286
+ conduitQueues.delete(exec.channel ?? channel);
256
287
  if (ctx.messageRef) {
257
288
  await _adapter.updateMessage(ctx.messageRef, {
258
- text: ':octagonal_sign: Cancelled. Session preserved — next message will resume.',
289
+ text: `${Icons.stopped} Cancelled. Session preserved — next message will resume.`,
259
290
  }).catch(() => { });
260
291
  }
261
292
  }
@@ -275,7 +306,7 @@ async function handleStatusResume(ctx) {
275
306
  const profileNote = record.profileName ? ` (profile: ${record.profileName})` : '';
276
307
  const resumeDest = { type: 'interactive-reply', conduit: ctx.channelId, sessionId: record.sessionId ?? '' };
277
308
  await _adapter.postMessage(resumeDest, {
278
- text: `:arrows_counterclockwise: Session \`${sessionName}\` active — send your message below.${profileNote}`,
309
+ text: `${Icons.refresh} Session \`${sessionName}\` active — send your message below.${profileNote}`,
279
310
  }).catch(() => { });
280
311
  }
281
312
  async function handleStatusNew(ctx) {
@@ -284,9 +315,9 @@ async function handleStatusNew(ctx) {
284
315
  const channel = ctx.value;
285
316
  // Status message IS the thread parent (no thread_ts on it) — use its messageId
286
317
  // as the thread context so hook messages land in the session's thread.
287
- const threadTs = ctx.messageRef?.threadId || ctx.messageRef?.messageId;
318
+ const threadAnchorId = ctx.messageRef?.threadId || ctx.messageRef?.messageId;
288
319
  // Fire-and-forget: hook starts, session closes immediately without waiting
289
- void fireAndForgetPreCloseHook(channel, _adapter, threadTs);
320
+ void fireAndForgetPreCloseHook(channel, _adapter, threadAnchorId);
290
321
  closeSession(channel);
291
322
  const conv = await conversationLedger.getConversation(channel);
292
323
  const profileName = getActiveProfile(channel) || 'default';
@@ -1,6 +1,6 @@
1
1
  import type { PlatformAdapter } from '../../platform/index.js';
2
- declare function sendPlanToSlack(planContent: string | null, channel: string, adapter: PlatformAdapter, { machine, threadTs }?: {
2
+ declare function sendPlanToSlack(planContent: string | null, channel: string, adapter: PlatformAdapter, { machine, threadAnchorId }?: {
3
3
  machine?: string;
4
- threadTs?: string | null;
4
+ threadAnchorId?: string | null;
5
5
  }): Promise<void>;
6
6
  export { sendPlanToSlack };
@@ -1,12 +1,13 @@
1
1
  import { postOnce } from '../../platform/index.js';
2
- async function sendPlanToSlack(planContent, channel, adapter, { machine, threadTs } = {}) {
2
+ import { Icons } from '../../core/icons.js';
3
+ async function sendPlanToSlack(planContent, channel, adapter, { machine, threadAnchorId } = {}) {
3
4
  if (!planContent) {
4
5
  const label = machine ? `**[PLAN: ${machine}]**` : '**[PLAN]**';
5
- await postOnce(adapter, { type: 'interactive-reply', conduit: channel, sessionId: '' }, `:memo: ${label} Plan generated but no content found.`, { threadId: threadTs });
6
+ await postOnce(adapter, { type: 'interactive-reply', conduit: channel, sessionId: '' }, `${Icons.memo} ${label} Plan generated but no content found.`, { threadId: threadAnchorId });
6
7
  return;
7
8
  }
8
9
  const label = '**[PLAN]**';
9
10
  const prompt = 'Generated plan — use the buttons below to approve or provide feedback:';
10
- await postOnce(adapter, { type: 'interactive-reply', conduit: channel, sessionId: '' }, `:memo: ${label} ${prompt}\n${planContent}`, { threadId: threadTs });
11
+ await postOnce(adapter, { type: 'interactive-reply', conduit: channel, sessionId: '' }, `${Icons.memo} ${label} ${prompt}\n${planContent}`, { threadId: threadAnchorId });
11
12
  }
12
13
  export { sendPlanToSlack };
@@ -0,0 +1,6 @@
1
+ import type { PlatformAdapter } from '../../platform/index.js';
2
+ import type { CommandActionRouter } from '../interactions/command-action-router.js';
3
+ import type { UpdatePrompt } from '../../domain/system/update-prompt.js';
4
+ export declare function createUpdatePrompt(adapter: PlatformAdapter, router: CommandActionRouter, opts?: {
5
+ timeoutMs?: number;
6
+ }): UpdatePrompt;
@@ -0,0 +1,100 @@
1
+ // input: @platform/index.js + @orch/interactions/command-action-router.js + @domain/system/update-prompt.js
2
+ // output: createUpdatePrompt(adapter, router, opts?) => UpdatePrompt
3
+ // pos: Platform-neutral UpdatePrompt implementation — pre-registers three actionIds on router,
4
+ // posts interactive message to system-notice, resolves ask() promise on button click.
5
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
+ const DEFAULT_TIMEOUT_MS = 86_400_000; // 24h
7
+ // --- Factory ---
8
+ export function createUpdatePrompt(adapter, router, opts) {
9
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
10
+ let pending = null;
11
+ let timerHandle;
12
+ // --- Internal helpers ---
13
+ const clearPending = () => {
14
+ if (timerHandle !== undefined) {
15
+ clearTimeout(timerHandle);
16
+ timerHandle = undefined;
17
+ }
18
+ pending = null;
19
+ };
20
+ const resolveText = (choice, version) => {
21
+ switch (choice) {
22
+ case 'apply':
23
+ return `Installing @cortex-agent/server@${version}... daemon will restart shortly.`;
24
+ case 'skip':
25
+ return `Skipped version ${version}.`;
26
+ case 'cancel':
27
+ return `Update cancelled. Will check again at next interval.`;
28
+ }
29
+ };
30
+ // --- Build click handlers ---
31
+ const buildHandler = (choice) => {
32
+ return async (ctx) => {
33
+ if (!pending)
34
+ return; // stale click — no pending prompt
35
+ const p = pending;
36
+ const version = p.latestVersion;
37
+ clearPending();
38
+ p.resolve(choice);
39
+ if (ctx.messageRef) {
40
+ await adapter.updateMessage(ctx.messageRef, { text: resolveText(choice, version) }).catch(() => { });
41
+ }
42
+ };
43
+ };
44
+ // --- Pre-register three actionIds on router ---
45
+ router.registerCommand('update', {
46
+ actions: [
47
+ { actionId: 'apply', handler: buildHandler('apply') },
48
+ { actionId: 'skip', handler: buildHandler('skip') },
49
+ { actionId: 'cancel', handler: buildHandler('cancel') },
50
+ ],
51
+ });
52
+ // --- Button templates (value filled in at ask time) ---
53
+ const buttonTemplates = [
54
+ { type: 'button', text: 'Update', actionId: 'cmd:update:apply', value: '', style: 'primary' },
55
+ { type: 'button', text: 'Skip this version', actionId: 'cmd:update:skip', value: '' },
56
+ { type: 'button', text: 'Cancel', actionId: 'cmd:update:cancel', value: '', style: 'danger' },
57
+ ];
58
+ // --- Return the UpdatePrompt implementation ---
59
+ return {
60
+ async ask(spec) {
61
+ // Resolve any existing pending prompt
62
+ if (pending) {
63
+ const old = pending;
64
+ clearPending();
65
+ old.resolve(null);
66
+ if (old.messageRef) {
67
+ await adapter.updateMessage(old.messageRef, { text: 'Superseded by a newer update prompt.' }).catch(() => { });
68
+ }
69
+ }
70
+ // Stamp version onto buttons
71
+ const versionedButtons = buttonTemplates.map(b => ({ ...b, value: spec.latestVersion }));
72
+ // Post interactive message to admin DM.
73
+ // Convention: richBlocks contains content-only sections; buttons go in the
74
+ // top-level `actions` field. The Slack adapter's postInteractive
75
+ // (adapters/slack.ts:434-440) appends an actions block from content.actions,
76
+ // so embedding another actions block inside richBlocks would duplicate the
77
+ // button row. Pattern follows buildPlanApprovalContent
78
+ // (platform/interactive-builder.ts:117-127).
79
+ const messageRef = await adapter.postInteractive({ type: 'system-notice' }, {
80
+ text: `Cortex Server v${spec.latestVersion} is available. Update now?`,
81
+ richBlocks: [
82
+ { type: 'section', text: `Cortex Server v${spec.latestVersion} is available.` },
83
+ ],
84
+ actions: versionedButtons,
85
+ });
86
+ // Create new pending promise
87
+ return new Promise((resolve) => {
88
+ pending = { resolve, messageRef, latestVersion: spec.latestVersion };
89
+ timerHandle = setTimeout(() => {
90
+ if (!pending || pending.resolve !== resolve)
91
+ return; // already handled
92
+ const ref = pending.messageRef;
93
+ clearPending();
94
+ resolve(null);
95
+ adapter.updateMessage(ref, { text: 'Update prompt timed out.' }).catch(() => { });
96
+ }, timeoutMs).unref();
97
+ });
98
+ },
99
+ };
100
+ }
@@ -1,6 +1,6 @@
1
1
  import type { PlatformAdapter, MessageRef } from '../platform/index.js';
2
2
  import type { AgentResult } from '../core/types/agent-types.js';
3
- export declare function handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger, sessionName, threadTs, userMessageTs, onAssistantMessage }: {
3
+ export declare function handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger, sessionName, threadAnchorId, userMessageTs, onAssistantMessage }: {
4
4
  result: AgentResult;
5
5
  channel: string;
6
6
  adapter: PlatformAdapter;
@@ -10,11 +10,11 @@ export declare function handleAgentSuccess({ result, channel, adapter, statusMsg
10
10
  executionId: string | null;
11
11
  trigger?: string;
12
12
  sessionName?: string | null;
13
- threadTs?: string | null;
13
+ threadAnchorId?: string | null;
14
14
  userMessageTs?: string | null;
15
15
  onAssistantMessage?: ((text: string) => void) | null;
16
16
  }): Promise<void>;
17
- export declare function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName, sessionId, effectiveSessionId, threadTs, userMessageTs }: {
17
+ export declare function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName, sessionId, effectiveSessionId, threadAnchorId, userMessageTs }: {
18
18
  error: {
19
19
  message: string;
20
20
  cancelled?: boolean;
@@ -27,7 +27,7 @@ export declare function handleAgentError({ error, channel, adapter, statusMsg, s
27
27
  sessionName?: string | null;
28
28
  sessionId?: string | null;
29
29
  effectiveSessionId?: string | null;
30
- threadTs?: string | null;
30
+ threadAnchorId?: string | null;
31
31
  userMessageTs?: string | null;
32
32
  }): Promise<void>;
33
33
  export declare function resumeAskUserQuestionGroup({ adapter, group, responseText }: {
@@ -3,8 +3,9 @@
3
3
  // pos: Agent runtime lifecycle handling (success/failure/approval/resume)
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { createLogger } from '../core/log.js';
6
+ import { Icons } from '../core/icons.js';
6
7
  import { trackPendingTask } from './busy-tracker.js';
7
- import { enqueue } from './channel-queue.js';
8
+ import { enqueue } from './conduit-queue.js';
8
9
  import { supersededEdits } from './superseded-edits.js';
9
10
  import { runningExecutions } from '../core/running-executions.js';
10
11
  import { finalizeLocalExecution, buildSessionTag, buildUserProcessingMessage, makeFallbackNotifier, makeStreamingMessageCallback, computeElapsed, formatMetricsSuffix, writeStatus, sealStatus, buildStatusActionBlocks, buildSealedStatusActionBlocks, initStatusBlocks } from './status-helpers.js';
@@ -24,7 +25,7 @@ import { getOutboundQueue } from '../store/outbound-queue.js';
24
25
  import { buildDurableHooks, durablePost } from './durable-helpers.js';
25
26
  const log = createLogger('lifecycle');
26
27
  // --- Agent success handler ---
27
- export async function handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger = 'user', sessionName = null, threadTs = null, userMessageTs = null, onAssistantMessage = null }) {
28
+ export async function handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger = 'user', sessionName = null, threadAnchorId = null, userMessageTs = null, onAssistantMessage = null }) {
28
29
  if (result?.sessionId)
29
30
  await setSessionAsync(channel, result.sessionId, resolveBackendForChannel(channel));
30
31
  await registerOrUpdateSession(result, sessionName, channel, trigger, projectStore.resolveFromMessage(userMessage)?.id ?? 'general');
@@ -34,10 +35,10 @@ export async function handleAgentSuccess({ result, channel, adapter, statusMsg,
34
35
  const metrics = formatMetricsSuffix({ costUsd: result?.total_cost_usd ?? null, numTurns: result?.num_turns ?? null });
35
36
  const sessionTag = buildSessionTag(sessionName, result?.sessionId);
36
37
  const stream = onAssistantMessage?.stream ?? null;
37
- const askCount = await askUserQuestion.sendMessages(result, channel, adapter, statusMsg.messageId, threadTs, stream);
38
+ const askCount = await askUserQuestion.sendMessages(result, channel, adapter, statusMsg.messageId, threadAnchorId, stream);
38
39
  const statusText = askCount > 0
39
- ? `:speech_balloon: ${sessionTag}Waiting for user input (${elapsedStr}${metrics})`
40
- : `:white_check_mark: Done | ${sessionTag}(${elapsedStr}${metrics})`;
40
+ ? `${Icons.waiting} ${sessionTag}Waiting for user input (${elapsedStr}${metrics})`
41
+ : `${Icons.ok} Done | ${sessionTag}(${elapsedStr}${metrics})`;
41
42
  await sealStatus(adapter, statusMsg, statusText, buildSealedStatusActionBlocks(statusText, { channel, sessionName, isDm: true }));
42
43
  if (userMessageTs) {
43
44
  await conversationLedger.completeTurn(channel, userMessageTs, { executionId });
@@ -100,15 +101,16 @@ async function backfillLedgerSessionId(result, channel) {
100
101
  }
101
102
  }
102
103
  // --- Agent error handler ---
103
- export async function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName = null, sessionId = null, effectiveSessionId = null, threadTs = null, userMessageTs = null }) {
104
- runningExecutions.fail(channel, error.message);
104
+ export async function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName = null, sessionId = null, effectiveSessionId = null, threadAnchorId = null, userMessageTs = null }) {
105
+ if (executionId)
106
+ runningExecutions.fail(executionId, error.message);
105
107
  const resolvedSessionId = effectiveSessionId || sessionId;
106
108
  const sessionTag = buildSessionTag(sessionName, resolvedSessionId);
107
109
  const { elapsedStr, elapsedS } = computeElapsed(startTime);
108
110
  if (error?.cancelled && supersededEdits.check(channel)) {
109
111
  supersededEdits.clear(channel);
110
112
  finalizeLocalExecution({ executionId, status: 'cancelled', error, durationS: elapsedS });
111
- const supersededText = `:fast_forward: ${sessionTag}Superseded by edit (${elapsedStr})`;
113
+ const supersededText = `${Icons.superseded} ${sessionTag}Superseded by edit (${elapsedStr})`;
112
114
  await sealStatus(adapter, statusMsg, supersededText, buildSealedStatusActionBlocks(supersededText, { channel, sessionName, isDm: true }));
113
115
  return;
114
116
  }
@@ -117,21 +119,21 @@ export async function handleAgentError({ error, channel, adapter, statusMsg, sta
117
119
  await conversationLedger.completeTurn(channel, userMessageTs, { executionId });
118
120
  if (error?.cancelled) {
119
121
  finalizeLocalExecution({ executionId, status: 'failed', error, durationS: elapsedS });
120
- const cancelledText = `:octagonal_sign: ${sessionTag}Cancelled (${elapsedStr})`;
122
+ const cancelledText = `${Icons.stopped} ${sessionTag}Cancelled (${elapsedStr})`;
121
123
  await sealStatus(adapter, statusMsg, cancelledText, buildSealedStatusActionBlocks(cancelledText, { channel, sessionName, isDm: true }));
122
124
  return;
123
125
  }
124
126
  log.error('Agent error:', error.message);
125
127
  finalizeLocalExecution({ executionId, status: 'failed', error, durationS: elapsedS });
126
- const errorText = `:x: ${sessionTag}Error (${elapsedStr})`;
128
+ const errorText = `${Icons.error} ${sessionTag}Error (${elapsedStr})`;
127
129
  await sealStatus(adapter, statusMsg, errorText, buildSealedStatusActionBlocks(errorText, { channel, sessionName, isDm: true }));
128
130
  const errorDest = { type: 'interactive-reply', conduit: channel, sessionId: resolvedSessionId ?? '' };
129
131
  const queue = getOutboundQueue();
130
132
  if (queue) {
131
- await durablePost(queue, adapter, errorDest, { text: `Error: ${error.message}` }, threadTs ? { threadId: threadTs } : undefined);
133
+ await durablePost(queue, adapter, errorDest, { text: `Error: ${error.message}` }, threadAnchorId ? { threadId: threadAnchorId } : undefined);
132
134
  }
133
135
  else {
134
- await adapter.postMessage(errorDest, { text: `Error: ${error.message}` }, threadTs ? { threadId: threadTs } : undefined);
136
+ await adapter.postMessage(errorDest, { text: `Error: ${error.message}` }, threadAnchorId ? { threadId: threadAnchorId } : undefined);
135
137
  }
136
138
  }
137
139
  async function persistErrorSession(resolvedSessionId, sessionName, channel, adapter) {
@@ -150,7 +152,7 @@ async function persistErrorSession(resolvedSessionId, sessionName, channel, adap
150
152
  // --- AskUserQuestion resume ---
151
153
  export async function resumeAskUserQuestionGroup({ adapter, group, responseText }) {
152
154
  const askDest = { type: 'interactive-reply', conduit: group.channel, sessionId: group.sessionId };
153
- const statusMsg = await adapter.postMessage(askDest, { text: ':hourglass_flowing_sand: Processing AskUserQuestion response...' });
155
+ const statusMsg = await adapter.postMessage(askDest, { text: `${Icons.processing} Processing AskUserQuestion response...` });
154
156
  const startTime = Date.now();
155
157
  let executionId = null;
156
158
  let handle;
@@ -168,9 +170,9 @@ export async function resumeAskUserQuestionGroup({ adapter, group, responseText
168
170
  const askDurable = askQueue ? buildDurableHooks(askQueue) : null;
169
171
  const onAssistantMsg = makeStreamingMessageCallback(adapter, askDest, null, null, askDurable);
170
172
  handle = runAgent(responseText, { channel: group.channel, sessionId: group.sessionId, files: [], project: projectStore.resolveFromMessage(responseText)?.id ?? 'general', trigger: 'ask-user-question', onAssistantMessage: onAssistantMsg });
171
- runningExecutions.register(group.channel, { threadId: group.threadId ?? null, channel: group.channel, agentSlotId: null, executionId, kill: () => handle.kill(), backend: askBackend });
173
+ runningExecutions.register({ threadId: group.threadId ?? null, channel: group.channel, agentSlotId: null, executionId, kill: () => handle.kill(), backend: askBackend });
172
174
  const result = await handle.promise;
173
- runningExecutions.complete(group.channel, result?.total_cost_usd ?? 0);
175
+ runningExecutions.complete(executionId, result?.total_cost_usd ?? 0);
174
176
  await maybeNotifyCodexLowUsage({ adapter, result });
175
177
  await handleAgentSuccess({ result, channel: group.channel, adapter, statusMsg, startTime, userMessage: responseText, executionId, trigger: 'ask-user-question', onAssistantMessage: onAssistantMsg });
176
178
  }
@@ -199,7 +201,7 @@ async function executeRetry(channel, text, adapter, opts) {
199
201
  const sessionName = opts.sessionName || await sessionStore.generateSessionName();
200
202
  const userMessageTs = opts.originalTs;
201
203
  const retryDest = { type: 'interactive-reply', conduit: channel, sessionId: sessionId ?? '' };
202
- const retryPrefix = ':arrows_counterclockwise: Retry (edited) | ';
204
+ const retryPrefix = `${Icons.refresh} Retry (edited) | `;
203
205
  const retryStatusText = retryPrefix + buildUserProcessingMessage({ startTime, profileName: getActiveProfile(channel), sessionName, sessionId });
204
206
  const retryBlocksTemplate = { channel, sessionName, isDm: true };
205
207
  const statusMsg = await adapter.postMessage(retryDest, {
@@ -233,14 +235,14 @@ async function runRetryAgent({ channel, text, adapter, statusMsg, startTime, ses
233
235
  isUserInitiated: true, onAssistantMessage: onAssistantMsg,
234
236
  onProgress: buildRetryProgressUpdater(adapter, channel, statusMsg, retryPrefix, startTime, sessionName, sessionId),
235
237
  });
236
- runningExecutions.register(channel, { threadId: null /* A5: edit-retry — threadId not yet wired; Cancel button will warn */, channel, agentSlotId: null, executionId, kill: () => handle.kill(), backend: retryBackend });
238
+ runningExecutions.register({ threadId: null /* A5: edit-retry — threadId not yet wired; Cancel button will warn */, channel, agentSlotId: null, executionId, kill: () => handle.kill(), backend: retryBackend });
237
239
  const result = await handle.promise;
238
- runningExecutions.complete(channel, result?.total_cost_usd ?? 0);
240
+ runningExecutions.complete(executionId, result?.total_cost_usd ?? 0);
239
241
  clearStreamingCallback(channel);
240
242
  await maybeNotifyCodexLowUsage({ adapter, result });
241
243
  if (result?.rateLimited) {
242
244
  const { elapsedStr } = computeElapsed(startTime);
243
- const rateLimitText = `:warning: ${buildSessionTag(sessionName, sessionId)}Rate limited \u2014 all fallbacks exhausted (${elapsedStr})`;
245
+ const rateLimitText = `${Icons.warning} ${buildSessionTag(sessionName, sessionId)}Rate limited \u2014 all fallbacks exhausted (${elapsedStr})`;
244
246
  await sealStatus(adapter, statusMsg, rateLimitText, buildSealedStatusActionBlocks(rateLimitText, { channel, sessionName, isDm: true }));
245
247
  }
246
248
  else {
@@ -263,17 +265,17 @@ function buildRetryProgressUpdater(adapter, channel, statusMsg, retryPrefix, sta
263
265
  }
264
266
  // --- Internal helpers ---
265
267
  function updateRetryPermalinks(adapter, channel, userMessageTs, statusMsg, supersededTimestamps, retryPrefix, startTime, sessionName, sessionId) {
266
- const userPermalinkP = adapter.getPermalink({ channel, messageId: userMessageTs }).catch(() => null);
268
+ const userPermalinkP = adapter.getPermalink({ conduit: channel, messageId: userMessageTs }).catch(() => null);
267
269
  const statusPermalinkP = supersededTimestamps?.length
268
270
  ? adapter.getPermalink(statusMsg).catch(() => null)
269
271
  : Promise.resolve(null);
270
272
  Promise.all([userPermalinkP, statusPermalinkP]).then(([userPermalink, statusPermalink]) => {
271
273
  if (userPermalink) {
272
- writeStatus(adapter, statusMsg, `:arrows_counterclockwise: Retry (<${userPermalink}|edited>) | ` + buildUserProcessingMessage({ startTime, profileName: getActiveProfile(channel), sessionName, sessionId }));
274
+ writeStatus(adapter, statusMsg, `${Icons.refresh} Retry (<${userPermalink}|edited>) | ` + buildUserProcessingMessage({ startTime, profileName: getActiveProfile(channel), sessionName, sessionId }));
273
275
  }
274
276
  if (statusPermalink && supersededTimestamps?.length) {
275
277
  for (const oldTs of supersededTimestamps) {
276
- adapter.updateMessage({ channel, messageId: oldTs }, { text: `:fast_forward: Superseded by edit \u2014 <${statusPermalink}|see new reply>` }).catch(() => { });
278
+ adapter.updateMessage({ conduit: channel, messageId: oldTs }, { text: `${Icons.superseded} Superseded by edit \u2014 <${statusPermalink}|see new reply>` }).catch(() => { });
277
279
  }
278
280
  }
279
281
  }).catch(() => { });
@@ -3,7 +3,7 @@ export interface OrchMessageContext {
3
3
  message: IncomingMessage;
4
4
  channel: string;
5
5
  adapter: PlatformAdapter;
6
- threadTs: string | null;
6
+ threadAnchorId: string | null;
7
7
  hasFiles: boolean;
8
8
  userMessage: string;
9
9
  agentMessage: string;
@@ -1,9 +1,27 @@
1
1
  import { createLogger } from '../../../core/log.js';
2
+ import { Icons } from '../../../core/icons.js';
2
3
  import { runningExecutions } from '../../../core/running-executions.js';
3
- import { channelQueues } from '../../channel-queue.js';
4
+ import { conduitQueues } from '../../conduit-queue.js';
4
5
  import { cancelThread as cancelThreadById } from '../../../domain/threads/index.js';
5
6
  import { setSessionAsync } from '../../../domain/sessions/session.js';
6
7
  import { getActiveBackend } from '../../../domain/agents/index.js';
8
+ import * as executionRegistry from '../../../domain/executions/registry.js';
9
+ /** Cancel one live execution: preserve its session, cancel its thread record, then tear it down as
10
+ * 'cancelled'. teardownExecution sets the persistent record cancelled BEFORE killing the handle, so
11
+ * the kill-error path's failExecution is a terminal no-op — and it publishes a balanced terminal
12
+ * event so agent.started is not left dangling. */
13
+ async function cancelLive(exec, channel) {
14
+ if (exec.sessionId)
15
+ await setSessionAsync(channel, exec.sessionId, getActiveBackend()).catch(() => { });
16
+ if (exec.threadId)
17
+ await cancelThreadById(exec.threadId).catch(() => { });
18
+ if (exec.executionId) {
19
+ executionRegistry.teardownExecution({ executionId: exec.executionId, status: 'cancelled', durationS: 0 });
20
+ }
21
+ else {
22
+ runningExecutions.killById(exec.registryKey);
23
+ }
24
+ }
7
25
  /** Matches thread IDs like `thr_a1b2c3d4`. */
8
26
  const THREAD_ID_RE = /^thr_[0-9a-f]{8}$/;
9
27
  const log = createLogger('cancel');
@@ -11,29 +29,19 @@ const MAX_CANCEL_BUTTONS = 10;
11
29
  export function createCancelHandler(cancelDispatchedTask, router) {
12
30
  if (router) {
13
31
  const cancelHandler = async (ctx) => {
14
- const { threadId, registryKey } = JSON.parse(ctx.value);
32
+ const { threadId, executionId } = JSON.parse(ctx.value);
15
33
  const adapter = router.getAdapter();
16
34
  if (!adapter)
17
35
  return;
18
- if (threadId) {
19
- const exec = runningExecutions.getByThreadId(threadId);
20
- runningExecutions.killByThreadId(threadId);
21
- await cancelThreadById(threadId).catch(() => { });
22
- if (exec?.sessionId) {
23
- await setSessionAsync(ctx.channelId, exec.sessionId, getActiveBackend()).catch(() => { });
24
- }
25
- }
26
- else if (registryKey) {
27
- const exec = runningExecutions.getByKey(registryKey);
28
- if (exec?.sessionId) {
29
- await setSessionAsync(ctx.channelId, exec.sessionId, getActiveBackend()).catch(() => { });
30
- }
31
- runningExecutions.killByKey(registryKey);
32
- }
33
- channelQueues.delete(registryKey || threadId || ctx.channelId);
36
+ const exec = threadId
37
+ ? runningExecutions.getByThreadId(threadId)
38
+ : (executionId ? runningExecutions.getById(executionId) : null);
39
+ if (exec)
40
+ await cancelLive(exec, ctx.channelId);
41
+ conduitQueues.delete(ctx.channelId);
34
42
  if (ctx.messageRef) {
35
43
  await adapter.updateMessage(ctx.messageRef, {
36
- text: `:octagonal_sign: Cancelled (${threadId || registryKey})`,
44
+ text: `${Icons.stopped} Cancelled (${threadId || executionId})`,
37
45
  }).catch(() => { });
38
46
  }
39
47
  };
@@ -51,34 +59,25 @@ export function createCancelHandler(cancelDispatchedTask, router) {
51
59
  const firstArg = args[0];
52
60
  // --all: kill all running executions in the current channel
53
61
  if (firstArg === '--all') {
54
- const executions = runningExecutions.getAll().filter(e => e.channel === channel);
62
+ const executions = runningExecutions.getByChannel(channel);
55
63
  if (executions.length === 0) {
56
64
  await adapter.postMessage(dest, { text: 'Nothing running to cancel.' });
57
65
  return;
58
66
  }
59
67
  for (const exec of executions) {
60
- if (exec.threadId) {
61
- await cancelThreadById(exec.threadId).catch(() => { });
62
- }
63
- if (exec.sessionId) {
64
- await setSessionAsync(channel, exec.sessionId, getActiveBackend()).catch(() => { });
65
- }
66
- runningExecutions.killByKey(exec.registryKey);
68
+ await cancelLive(exec, channel);
67
69
  }
68
- channelQueues.delete(channel);
69
- await adapter.postMessage(dest, { text: `:octagonal_sign: Cancelled ${executions.length} execution(s).` });
70
+ conduitQueues.delete(channel);
71
+ await adapter.postMessage(dest, { text: `${Icons.stopped} Cancelled ${executions.length} execution(s).` });
70
72
  return;
71
73
  }
72
74
  // Thread ID pattern: kill by threadId + cancel thread store record
73
75
  if (THREAD_ID_RE.test(firstArg)) {
74
76
  const exec = runningExecutions.getByThreadId(firstArg);
75
- if (runningExecutions.killByThreadId(firstArg)) {
76
- await cancelThreadById(firstArg).catch(() => { });
77
- if (exec?.sessionId) {
78
- await setSessionAsync(channel, exec.sessionId, getActiveBackend()).catch(() => { });
79
- }
77
+ if (exec) {
78
+ await cancelLive(exec, channel);
80
79
  log.info('Cancel requested for thread:', firstArg);
81
- await adapter.postMessage(dest, { text: `:octagonal_sign: Thread \`${firstArg}\` cancelled.` });
80
+ await adapter.postMessage(dest, { text: `${Icons.stopped} Thread \`${firstArg}\` cancelled.` });
82
81
  }
83
82
  else {
84
83
  await adapter.postMessage(dest, { text: `No running thread \`${firstArg}\` found to cancel.` });
@@ -95,7 +94,7 @@ export function createCancelHandler(cancelDispatchedTask, router) {
95
94
  return;
96
95
  }
97
96
  // No args: check how many executions are running on this channel
98
- const executions = runningExecutions.getAll().filter(e => e.channel === channel);
97
+ const executions = runningExecutions.getByChannel(channel);
99
98
  // 0 executions: nothing to cancel
100
99
  if (executions.length === 0) {
101
100
  await adapter.postMessage(dest, { text: 'Nothing running to cancel.' });
@@ -103,16 +102,9 @@ export function createCancelHandler(cancelDispatchedTask, router) {
103
102
  }
104
103
  // 1 execution: cancel directly (existing default behavior)
105
104
  if (executions.length === 1) {
106
- const exec = executions[0];
107
- if (exec.threadId) {
108
- await cancelThreadById(exec.threadId).catch(() => { });
109
- }
110
- runningExecutions.killByKey(exec.registryKey);
111
- if (exec.sessionId) {
112
- await setSessionAsync(channel, exec.sessionId, getActiveBackend()).catch(() => { });
113
- }
114
- channelQueues.delete(channel);
115
- await adapter.postMessage(dest, { text: ':octagonal_sign: Cancelled. Session preserved — next message will resume.' });
105
+ await cancelLive(executions[0], channel);
106
+ conduitQueues.delete(channel);
107
+ await adapter.postMessage(dest, { text: `${Icons.stopped} Cancelled. Session preserved — next message will resume.` });
116
108
  return;
117
109
  }
118
110
  // 2+ executions: show interactive list with cancel buttons
@@ -128,7 +120,7 @@ export function createCancelHandler(cancelDispatchedTask, router) {
128
120
  actionId: `cmd:cancel:exec-${i}`,
129
121
  value: JSON.stringify({
130
122
  threadId: exec.threadId,
131
- registryKey: exec.registryKey,
123
+ executionId: exec.executionId,
132
124
  }),
133
125
  style: 'danger',
134
126
  })),