@cortex-agent/server 2026.5.25 → 2026.6.15

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 (395) 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 +323 -30
  36. package/dist/core/i18n.d.ts +19 -0
  37. package/dist/core/i18n.js +46 -0
  38. package/dist/core/icons.d.ts +68 -0
  39. package/dist/core/icons.js +67 -0
  40. package/dist/core/locales/en.d.ts +438 -0
  41. package/dist/core/locales/en.js +24 -0
  42. package/dist/core/locales/slices/commands.d.ts +214 -0
  43. package/dist/core/locales/slices/commands.js +462 -0
  44. package/dist/core/locales/slices/init.d.ts +121 -0
  45. package/dist/core/locales/slices/init.js +380 -0
  46. package/dist/core/locales/slices/interactions.d.ts +47 -0
  47. package/dist/core/locales/slices/interactions.js +102 -0
  48. package/dist/core/locales/slices/lang.d.ts +8 -0
  49. package/dist/core/locales/slices/lang.js +18 -0
  50. package/dist/core/locales/slices/scheduling.d.ts +36 -0
  51. package/dist/core/locales/slices/scheduling.js +74 -0
  52. package/dist/core/locales/slices/startup.d.ts +6 -0
  53. package/dist/core/locales/slices/startup.js +14 -0
  54. package/dist/core/locales/slices/status.d.ts +20 -0
  55. package/dist/core/locales/slices/status.js +48 -0
  56. package/dist/core/locales/zh.d.ts +5 -0
  57. package/dist/core/locales/zh.js +23 -0
  58. package/dist/core/profile-generator.d.ts +6 -0
  59. package/dist/core/profile-generator.js +35 -7
  60. package/dist/core/running-executions.d.ts +51 -41
  61. package/dist/core/running-executions.js +120 -73
  62. package/dist/core/singleton-lock.d.ts +23 -0
  63. package/dist/core/singleton-lock.js +53 -0
  64. package/dist/core/status-format.js +4 -2
  65. package/dist/core/task-parser.d.ts +3 -0
  66. package/dist/core/task-parser.js +3 -1
  67. package/dist/core/types/thread-types.d.ts +54 -8
  68. package/dist/core/utils.d.ts +9 -1
  69. package/dist/core/utils.js +9 -1
  70. package/dist/domain/agents/config.d.ts +2 -1
  71. package/dist/domain/agents/config.js +25 -6
  72. package/dist/domain/agents/facade.d.ts +18 -0
  73. package/dist/domain/agents/facade.js +26 -3
  74. package/dist/domain/agents/profile-manager.d.ts +11 -0
  75. package/dist/domain/agents/profile-manager.js +21 -2
  76. package/dist/domain/costs/codex-usage-monitor.js +2 -1
  77. package/dist/domain/costs/rate-limit-throttle.js +14 -2
  78. package/dist/domain/executions/registry.d.ts +24 -0
  79. package/dist/domain/executions/registry.js +38 -0
  80. package/dist/domain/mcp/core-server.js +15 -3
  81. package/dist/domain/mcp/feishu/bitable.d.ts +3 -0
  82. package/dist/domain/mcp/feishu/bitable.js +168 -0
  83. package/dist/domain/mcp/feishu/block-types.d.ts +44 -0
  84. package/dist/domain/mcp/feishu/block-types.js +127 -0
  85. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +19 -0
  86. package/dist/domain/mcp/feishu/blocks-to-text.js +43 -0
  87. package/dist/domain/mcp/feishu/client.d.ts +46 -0
  88. package/dist/domain/mcp/feishu/client.js +87 -0
  89. package/dist/domain/mcp/feishu/docx.d.ts +3 -0
  90. package/dist/domain/mcp/feishu/docx.js +163 -0
  91. package/dist/domain/mcp/feishu/drive.d.ts +23 -0
  92. package/dist/domain/mcp/feishu/drive.js +66 -0
  93. package/dist/domain/mcp/feishu/file.d.ts +14 -0
  94. package/dist/domain/mcp/feishu/file.js +107 -0
  95. package/dist/domain/mcp/feishu/index.d.ts +6 -0
  96. package/dist/domain/mcp/feishu/index.js +61 -0
  97. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +40 -0
  98. package/dist/domain/mcp/feishu/markdown-to-blocks.js +191 -0
  99. package/dist/domain/mcp/feishu/sheets.d.ts +3 -0
  100. package/dist/domain/mcp/feishu/sheets.js +119 -0
  101. package/dist/domain/mcp/feishu/types.d.ts +26 -0
  102. package/dist/domain/mcp/feishu/types.js +38 -0
  103. package/dist/domain/mcp/feishu/user-auth.d.ts +140 -0
  104. package/dist/domain/mcp/feishu/user-auth.js +286 -0
  105. package/dist/domain/mcp/feishu/wiki.d.ts +3 -0
  106. package/dist/domain/mcp/feishu/wiki.js +77 -0
  107. package/dist/domain/mcp/feishu-server.d.ts +2 -0
  108. package/dist/domain/mcp/feishu-server.js +33 -0
  109. package/dist/domain/mcp/server.d.ts +0 -1
  110. package/dist/domain/mcp/server.js +6 -25
  111. package/dist/domain/mcp/slack-server.d.ts +3 -0
  112. package/dist/domain/mcp/slack-server.js +46 -0
  113. package/dist/domain/mcp/tools/context.js +1 -1
  114. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  115. package/dist/domain/mcp/tools/schedule.js +6 -20
  116. package/dist/domain/mcp/tools/slack.js +20 -7
  117. package/dist/domain/mcp/tools/thread-ops.d.ts +2 -0
  118. package/dist/domain/mcp/tools/thread-ops.js +121 -0
  119. package/dist/domain/mcp/tools/time.d.ts +2 -0
  120. package/dist/domain/mcp/tools/time.js +66 -0
  121. package/dist/domain/mcp/tools/tui-ask.js +1 -1
  122. package/dist/domain/mcp/tools/tui-plan.js +2 -2
  123. package/dist/domain/mcp/tui-server.js +1 -0
  124. package/dist/domain/monitor/disk-monitor.js +2 -1
  125. package/dist/domain/monitor/gpu-monitor.js +2 -1
  126. package/dist/domain/remote/client-hot-reload.js +3 -2
  127. package/dist/domain/remote/client-manager.js +8 -6
  128. package/dist/domain/scheduling/job-registry.d.ts +4 -0
  129. package/dist/domain/scheduling/job-registry.js +1 -0
  130. package/dist/domain/scheduling/jobs/_shared.js +2 -1
  131. package/dist/domain/scheduling/jobs/memory-index-regen.js +3 -2
  132. package/dist/domain/scheduling/jobs/scheduled-task.js +9 -23
  133. package/dist/domain/scheduling/jobs/sync-public.js +4 -3
  134. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +1 -8
  135. package/dist/domain/scheduling/jobs/target-dispatch.js +0 -7
  136. package/dist/domain/scheduling/jobs/task-archive.js +3 -2
  137. package/dist/domain/scheduling/jobs/task-dispatch.js +126 -20
  138. package/dist/domain/scheduling/schedule-command.js +45 -43
  139. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  140. package/dist/domain/scheduling/scheduler.js +2 -1
  141. package/dist/domain/sessions/session-hooks.d.ts +2 -2
  142. package/dist/domain/sessions/session-hooks.js +19 -18
  143. package/dist/domain/sessions/session-lifecycle.d.ts +38 -0
  144. package/dist/domain/sessions/session-lifecycle.js +44 -0
  145. package/dist/domain/system/github-release.d.ts +18 -0
  146. package/dist/domain/system/github-release.js +106 -0
  147. package/dist/domain/system/install-cli.d.ts +7 -0
  148. package/dist/domain/system/install-cli.js +106 -0
  149. package/dist/domain/system/preferences.d.ts +12 -0
  150. package/dist/domain/system/preferences.js +36 -0
  151. package/dist/domain/system/server-update-check.js +2 -2
  152. package/dist/domain/tasks/dispatch-utils.d.ts +58 -1
  153. package/dist/domain/tasks/dispatch-utils.js +53 -4
  154. package/dist/domain/tasks/dispatcher.d.ts +11 -2
  155. package/dist/domain/tasks/dispatcher.js +63 -7
  156. package/dist/domain/tasks/lint.js +28 -0
  157. package/dist/domain/tasks/mutator.d.ts +16 -3
  158. package/dist/domain/tasks/mutator.js +41 -12
  159. package/dist/domain/tasks/pending-tracker.js +6 -5
  160. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  161. package/dist/domain/tasks/system/task-cli.js +37 -6
  162. package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
  163. package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
  164. package/dist/domain/tasks/system/task-mutations.js +166 -8
  165. package/dist/domain/threads/contract.d.ts +17 -0
  166. package/dist/domain/threads/contract.js +59 -0
  167. package/dist/domain/threads/hook-runner.js +7 -6
  168. package/dist/domain/threads/index.d.ts +2 -0
  169. package/dist/domain/threads/index.js +3 -1
  170. package/dist/domain/threads/prompt-builder.d.ts +21 -1
  171. package/dist/domain/threads/prompt-builder.js +60 -4
  172. package/dist/domain/threads/runner.d.ts +6 -5
  173. package/dist/domain/threads/runner.js +128 -79
  174. package/dist/domain/threads/state-machine.d.ts +23 -21
  175. package/dist/domain/threads/state-machine.js +113 -54
  176. package/dist/domain/threads/template-loader.js +3 -2
  177. package/dist/domain/threads/tree.d.ts +45 -0
  178. package/dist/domain/threads/tree.js +171 -0
  179. package/dist/domain/tui-session/index.d.ts +2 -0
  180. package/dist/domain/tui-session/index.js +3 -0
  181. package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
  182. package/dist/domain/tui-session/tui-session-service.js +103 -0
  183. package/dist/domain/tui-session/types.d.ts +67 -0
  184. package/dist/domain/tui-session/types.js +4 -0
  185. package/dist/domain/ui-service/index.d.ts +5 -0
  186. package/dist/domain/ui-service/index.js +3 -0
  187. package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
  188. package/dist/domain/ui-service/mutate/executions.js +15 -0
  189. package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
  190. package/dist/domain/ui-service/mutate/schedules.js +39 -0
  191. package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
  192. package/dist/domain/ui-service/mutate/tasks.js +59 -0
  193. package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
  194. package/dist/domain/ui-service/mutate/threads.js +21 -0
  195. package/dist/domain/ui-service/query/cost.d.ts +3 -0
  196. package/dist/domain/ui-service/query/cost.js +6 -0
  197. package/dist/domain/ui-service/query/executions.d.ts +2 -0
  198. package/dist/domain/ui-service/query/executions.js +35 -0
  199. package/dist/domain/ui-service/query/projects.d.ts +2 -0
  200. package/dist/domain/ui-service/query/projects.js +30 -0
  201. package/dist/domain/ui-service/query/schedules.d.ts +2 -0
  202. package/dist/domain/ui-service/query/schedules.js +23 -0
  203. package/dist/domain/ui-service/query/sessions.d.ts +2 -0
  204. package/dist/domain/ui-service/query/sessions.js +35 -0
  205. package/dist/domain/ui-service/query/tasks.d.ts +2 -0
  206. package/dist/domain/ui-service/query/tasks.js +30 -0
  207. package/dist/domain/ui-service/query/threads.d.ts +2 -0
  208. package/dist/domain/ui-service/query/threads.js +27 -0
  209. package/dist/domain/ui-service/subscribe.d.ts +5 -0
  210. package/dist/domain/ui-service/subscribe.js +118 -0
  211. package/dist/domain/ui-service/types.d.ts +237 -0
  212. package/dist/domain/ui-service/types.js +5 -0
  213. package/dist/domain/ui-service/ui-service.d.ts +2 -0
  214. package/dist/domain/ui-service/ui-service.js +83 -0
  215. package/dist/entry/app.js +130 -8
  216. package/dist/entry/cli.d.ts +12 -0
  217. package/dist/entry/cli.js +122 -12
  218. package/dist/entry/daemon.js +12 -30
  219. package/dist/entry/feishu-login.d.ts +28 -0
  220. package/dist/entry/feishu-login.js +218 -0
  221. package/dist/entry/init.d.ts +29 -5
  222. package/dist/entry/init.js +323 -233
  223. package/dist/entry/startup-notify.js +6 -3
  224. package/dist/events/event-types.d.ts +14 -0
  225. package/dist/hooks/cortex-md-injector.mjs +47 -31
  226. package/dist/hooks/post-task-hook.mjs +6 -0
  227. package/dist/hooks/task-status-check.mjs +8 -0
  228. package/dist/orchestration/agent-runner.d.ts +2 -1
  229. package/dist/orchestration/agent-runner.js +55 -55
  230. package/dist/orchestration/conduit-queue.d.ts +18 -0
  231. package/dist/orchestration/conduit-queue.js +32 -0
  232. package/dist/orchestration/conversation-runner.d.ts +48 -0
  233. package/dist/orchestration/conversation-runner.js +109 -0
  234. package/dist/orchestration/dispatch-reconciler.js +8 -1
  235. package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
  236. package/dist/orchestration/interactions/ask-user-question.js +3 -3
  237. package/dist/orchestration/interactions/interaction-handlers.js +55 -23
  238. package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
  239. package/dist/orchestration/interactions/plan-handler.js +4 -3
  240. package/dist/orchestration/interactions/update-prompt-slack.js +11 -10
  241. package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
  242. package/dist/orchestration/interactions/update-prompt.js +155 -0
  243. package/dist/orchestration/lifecycle.d.ts +4 -4
  244. package/dist/orchestration/lifecycle.js +25 -22
  245. package/dist/orchestration/orchestrator.d.ts +1 -1
  246. package/dist/orchestration/routing/commands/cancel.js +45 -52
  247. package/dist/orchestration/routing/commands/channel.js +41 -27
  248. package/dist/orchestration/routing/commands/cost.js +11 -2
  249. package/dist/orchestration/routing/commands/device.js +12 -9
  250. package/dist/orchestration/routing/commands/dispatch.js +11 -10
  251. package/dist/orchestration/routing/commands/index.d.ts +1 -1
  252. package/dist/orchestration/routing/commands/index.js +15 -10
  253. package/dist/orchestration/routing/commands/lang.d.ts +3 -0
  254. package/dist/orchestration/routing/commands/lang.js +31 -0
  255. package/dist/orchestration/routing/commands/mode.js +32 -30
  256. package/dist/orchestration/routing/commands/nvtop.js +15 -13
  257. package/dist/orchestration/routing/commands/orient.js +2 -1
  258. package/dist/orchestration/routing/commands/schedule.js +23 -22
  259. package/dist/orchestration/routing/commands/sendfile.js +9 -7
  260. package/dist/orchestration/routing/commands/session.d.ts +1 -1
  261. package/dist/orchestration/routing/commands/session.js +24 -39
  262. package/dist/orchestration/routing/commands/status.js +78 -71
  263. package/dist/orchestration/routing/commands/tail.js +7 -5
  264. package/dist/orchestration/routing/commands/task.js +25 -23
  265. package/dist/orchestration/routing/commands/thread-handlers.js +55 -44
  266. package/dist/orchestration/routing/edit-handler.js +8 -7
  267. package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
  268. package/dist/orchestration/routing/message-router.d.ts +1 -1
  269. package/dist/orchestration/routing/message-router.js +9 -9
  270. package/dist/orchestration/routing/webhook.js +233 -2
  271. package/dist/orchestration/status-helpers.d.ts +5 -1
  272. package/dist/orchestration/status-helpers.js +13 -11
  273. package/dist/orchestration/thread-callback.d.ts +67 -0
  274. package/dist/orchestration/thread-callback.js +465 -0
  275. package/dist/orchestration/thread-executor.d.ts +22 -1
  276. package/dist/orchestration/thread-executor.js +85 -36
  277. package/dist/platform/adapter.d.ts +6 -2
  278. package/dist/platform/adapters/composite-adapter.d.ts +89 -0
  279. package/dist/platform/adapters/composite-adapter.js +318 -0
  280. package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
  281. package/dist/platform/adapters/feishu-output-stream.js +274 -36
  282. package/dist/platform/adapters/feishu.d.ts +50 -5
  283. package/dist/platform/adapters/feishu.js +370 -116
  284. package/dist/platform/adapters/index.d.ts +24 -3
  285. package/dist/platform/adapters/index.js +89 -11
  286. package/dist/platform/adapters/project-conduits.d.ts +9 -0
  287. package/dist/platform/adapters/project-conduits.js +42 -0
  288. package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
  289. package/dist/platform/adapters/slack-project-conduits.js +6 -40
  290. package/dist/platform/adapters/slack.d.ts +9 -2
  291. package/dist/platform/adapters/slack.js +83 -39
  292. package/dist/platform/adapters/tui/index.d.ts +9 -0
  293. package/dist/platform/adapters/tui/index.js +10 -0
  294. package/dist/platform/adapters/tui/ports.d.ts +20 -0
  295. package/dist/platform/adapters/tui/ports.js +4 -0
  296. package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
  297. package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
  298. package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
  299. package/dist/platform/adapters/tui/tui-connection.js +53 -0
  300. package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
  301. package/dist/platform/adapters/tui/tui-gateway.js +919 -0
  302. package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
  303. package/dist/platform/adapters/tui/tui-notifications.js +60 -0
  304. package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
  305. package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
  306. package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
  307. package/dist/platform/adapters/tui/tui-transcript.js +56 -0
  308. package/dist/platform/index.d.ts +1 -0
  309. package/dist/platform/index.js +2 -1
  310. package/dist/platform/interactive-builder.js +21 -19
  311. package/dist/platform/output-stream.d.ts +5 -0
  312. package/dist/platform/testing.d.ts +7 -11
  313. package/dist/platform/testing.js +18 -15
  314. package/dist/platform/tool-trace.js +15 -5
  315. package/dist/platform/tui/protocol.d.ts +355 -0
  316. package/dist/platform/tui/protocol.js +199 -0
  317. package/dist/platform/types.d.ts +12 -3
  318. package/dist/store/execution-repo.d.ts +6 -1
  319. package/dist/store/execution-repo.js +13 -3
  320. package/dist/store/hook-sync.d.ts +18 -0
  321. package/dist/store/hook-sync.js +92 -0
  322. package/dist/store/outbound-queue.js +2 -2
  323. package/dist/store/profile-repo.js +3 -2
  324. package/dist/store/schedule-repo.d.ts +1 -8
  325. package/dist/store/session-registry-repo.d.ts +9 -1
  326. package/dist/store/session-registry-repo.js +19 -3
  327. package/dist/store/session-repo.d.ts +14 -0
  328. package/dist/store/session-repo.js +23 -0
  329. package/dist/store/thread-repo.d.ts +3 -0
  330. package/dist/store/thread-repo.js +49 -2
  331. package/dist/store/version-migrations.d.ts +7 -0
  332. package/dist/store/version-migrations.js +183 -0
  333. package/dist/tui/App.d.ts +27 -0
  334. package/dist/tui/App.js +219 -0
  335. package/dist/tui/components/AskUserModal.d.ts +11 -0
  336. package/dist/tui/components/AskUserModal.js +364 -0
  337. package/dist/tui/components/ConfirmModal.d.ts +12 -0
  338. package/dist/tui/components/ConfirmModal.js +31 -0
  339. package/dist/tui/components/Dashboard.d.ts +23 -0
  340. package/dist/tui/components/Dashboard.js +80 -0
  341. package/dist/tui/components/DashboardCostTab.d.ts +7 -0
  342. package/dist/tui/components/DashboardCostTab.js +16 -0
  343. package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
  344. package/dist/tui/components/DashboardExecutionsTab.js +94 -0
  345. package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
  346. package/dist/tui/components/DashboardSchedulesTab.js +124 -0
  347. package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
  348. package/dist/tui/components/DashboardTasksTab.js +200 -0
  349. package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
  350. package/dist/tui/components/DashboardThreadsTab.js +81 -0
  351. package/dist/tui/components/Header.d.ts +11 -0
  352. package/dist/tui/components/Header.js +5 -0
  353. package/dist/tui/components/InputBox.d.ts +10 -0
  354. package/dist/tui/components/InputBox.js +19 -0
  355. package/dist/tui/components/MessageRow.d.ts +7 -0
  356. package/dist/tui/components/MessageRow.js +10 -0
  357. package/dist/tui/components/Notifications.d.ts +19 -0
  358. package/dist/tui/components/Notifications.js +72 -0
  359. package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
  360. package/dist/tui/components/PlanFeedbackModal.js +161 -0
  361. package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
  362. package/dist/tui/components/ProjectSwitcher.js +43 -0
  363. package/dist/tui/components/SessionPicker.d.ts +14 -0
  364. package/dist/tui/components/SessionPicker.js +34 -0
  365. package/dist/tui/components/SidePanel.d.ts +19 -0
  366. package/dist/tui/components/SidePanel.js +8 -0
  367. package/dist/tui/components/StatusLine.d.ts +10 -0
  368. package/dist/tui/components/StatusLine.js +29 -0
  369. package/dist/tui/components/Transcript.d.ts +13 -0
  370. package/dist/tui/components/Transcript.js +56 -0
  371. package/dist/tui/hooks/useDashboardData.d.ts +32 -0
  372. package/dist/tui/hooks/useDashboardData.js +104 -0
  373. package/dist/tui/hooks/useKeybindings.d.ts +19 -0
  374. package/dist/tui/hooks/useKeybindings.js +87 -0
  375. package/dist/tui/hooks/useMutate.d.ts +22 -0
  376. package/dist/tui/hooks/useMutate.js +56 -0
  377. package/dist/tui/hooks/useNotifications.d.ts +28 -0
  378. package/dist/tui/hooks/useNotifications.js +70 -0
  379. package/dist/tui/hooks/useTranscript.d.ts +39 -0
  380. package/dist/tui/hooks/useTranscript.js +265 -0
  381. package/dist/tui/hooks/useWsClient.d.ts +29 -0
  382. package/dist/tui/hooks/useWsClient.js +69 -0
  383. package/dist/tui/index.d.ts +2 -0
  384. package/dist/tui/index.js +210 -0
  385. package/dist/tui/logic.d.ts +16 -0
  386. package/dist/tui/logic.js +49 -0
  387. package/dist/tui/render/markdown.d.ts +10 -0
  388. package/dist/tui/render/markdown.js +38 -0
  389. package/dist/tui/render/rich-blocks.d.ts +11 -0
  390. package/dist/tui/render/rich-blocks.js +24 -0
  391. package/dist/tui/ws-client.d.ts +44 -0
  392. package/dist/tui/ws-client.js +157 -0
  393. package/package.json +11 -3
  394. package/dist/orchestration/channel-queue.d.ts +0 -18
  395. package/dist/orchestration/channel-queue.js +0 -32
@@ -3,28 +3,31 @@
3
3
  // pos: !thread sub-command family handlers
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';
7
+ import { t } from '../../../core/i18n.js';
6
8
  import { threadStore } from '../../../store/thread-repo.js';
7
9
  import { listTemplates, listAgents } from '../../../domain/threads/index.js';
8
10
  import { runningExecutions } from '../../../core/running-executions.js';
9
- import { channelQueues } from '../../channel-queue.js';
11
+ import * as executionRegistry from '../../../domain/executions/registry.js';
12
+ import { conduitQueues } from '../../conduit-queue.js';
10
13
  const log = createLogger('thread-handlers');
11
14
  async function handleThreadStatus(channel, adapter) {
12
15
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
13
16
  const active = threadStore.findActive(channel);
14
17
  if (!active) {
15
- await adapter.postMessage(dest, { text: 'No active thread in this channel.' });
18
+ await adapter.postMessage(dest, { text: t('cmd.thread.noActive') });
16
19
  return;
17
20
  }
18
21
  const agents = Object.keys(active.agents).join(', ');
19
- const modeLabel = active.templateName ? active.templateName : 'ad-hoc';
22
+ const modeLabel = active.templateName ? active.templateName : t('cmd.thread.adHoc');
20
23
  const lines = [
21
- `*Active Thread* \`${active.id}\` (${modeLabel})`,
22
- `Status: ${active.status} | Active agent: ${active.activeAgent}`,
23
- `Steps: ${active.steps.length} | Cost: $${active.totalCostUsd.toFixed(4)}`,
24
- `Agents: ${agents}`,
24
+ t('cmd.thread.activeHeader', { id: active.id, mode: modeLabel }),
25
+ t('cmd.thread.statusLine', { status: active.status, agent: active.activeAgent }),
26
+ t('cmd.thread.stepsLine', { steps: active.steps.length, cost: active.totalCostUsd.toFixed(4) }),
27
+ t('cmd.thread.agentsLine', { agents }),
25
28
  ];
26
29
  if (active.status === 'aborted' && active.abortReason) {
27
- lines.push(`Abort reason: ${active.abortReason}`);
30
+ lines.push(t('cmd.thread.abortLine', { reason: active.abortReason }));
28
31
  }
29
32
  await adapter.postMessage(dest, { text: lines.join('\n') });
30
33
  }
@@ -32,13 +35,13 @@ async function handleThreadTemplates(channel, adapter) {
32
35
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
33
36
  const templates = listTemplates();
34
37
  if (templates.length === 0) {
35
- await adapter.postMessage(dest, { text: 'No thread templates configured.' });
38
+ await adapter.postMessage(dest, { text: t('cmd.thread.noTemplates') });
36
39
  return;
37
40
  }
38
- const lines = ['*Available Thread Templates*'];
39
- for (const t of templates) {
40
- const agentList = t.agents.map(a => typeof a === 'string' ? a : a.ref).join(', ');
41
- lines.push(`• \`${t.name}\` — ${t.description} [agents: ${agentList}]`);
41
+ const lines = [t('cmd.thread.templatesHeader')];
42
+ for (const tpl of templates) {
43
+ const agentList = tpl.agents.map(a => typeof a === 'string' ? a : a.ref).join(', ');
44
+ lines.push(`• ${t('cmd.thread.templateLine', { name: tpl.name, description: tpl.description, agents: agentList })}`);
42
45
  }
43
46
  await adapter.postMessage(dest, { text: lines.join('\n') });
44
47
  }
@@ -47,49 +50,57 @@ async function handleThreadAgents(channel, adapter) {
47
50
  const agentDefs = listAgents();
48
51
  const lines = [];
49
52
  if (agentDefs.length > 0) {
50
- lines.push('*Available Agents*');
53
+ lines.push(t('cmd.thread.agentsTitle'));
51
54
  for (const a of agentDefs) {
52
- lines.push(`• \`${a.name}\` (${a.profile}) — ${a.description || ''}`);
55
+ lines.push(`• ${t('cmd.thread.agentLine', { name: a.name, profile: a.profile, description: a.description || '' })}`);
53
56
  }
54
57
  }
55
58
  else {
56
- lines.push('No agents configured.');
59
+ lines.push(t('cmd.thread.noAgents'));
57
60
  }
58
61
  const active = threadStore.findActive(channel);
59
62
  if (active) {
60
63
  lines.push('');
61
- lines.push(`*Active Thread* \`${active.id}\``);
64
+ lines.push(t('cmd.thread.activeThreadHeader', { id: active.id }));
62
65
  for (const [slotId, slot] of Object.entries(active.agents)) {
63
- const isActiveAgent = slotId === active.activeAgent ? ' :arrow_left:' : '';
64
- const sessionStr = slot.sessionName || 'no session';
65
- lines.push(` • *${slotId}* (${slot.profile}) — ${slot.status} | ${sessionStr}${isActiveAgent}`);
66
+ const isActiveAgent = slotId === active.activeAgent ? ` ${Icons.arrowLeft}` : '';
67
+ const sessionStr = slot.sessionName || t('cmd.thread.noSession');
68
+ lines.push(` • ${t('cmd.thread.slotLine', { slotId, profile: slot.profile, status: slot.status, session: sessionStr })}${isActiveAgent}`);
66
69
  }
67
70
  }
68
71
  await adapter.postMessage(dest, { text: lines.join('\n') });
69
72
  }
70
73
  async function handleThreadCancelAlias(channel, adapter) {
71
74
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
72
- // Alias for !cancel — delegate to the same killByKey behavior
73
- if (runningExecutions.killByKey(channel)) {
75
+ // Alias for !cancel — tear down every live execution on the channel as 'cancelled'
76
+ // (record→cancelled, kill the handle, balanced event), matching the !cancel path.
77
+ const execs = runningExecutions.getByChannel(channel);
78
+ for (const e of execs) {
79
+ if (e.executionId)
80
+ executionRegistry.teardownExecution({ executionId: e.executionId, status: 'cancelled', durationS: 0 });
81
+ else
82
+ runningExecutions.killById(e.registryKey);
83
+ }
84
+ if (execs.length > 0) {
74
85
  log.info('Cancel requested for channel:', channel);
75
- channelQueues.delete(channel);
76
- await adapter.postMessage(dest, { text: ':octagonal_sign: Cancelled. Session preserved — next message will resume.' });
86
+ conduitQueues.delete(channel);
87
+ await adapter.postMessage(dest, { text: `${Icons.stopped} ${t('cmd.thread.cancelledSessionPreserved')}` });
77
88
  }
78
89
  else {
79
- await adapter.postMessage(dest, { text: 'Nothing running to cancel.' });
90
+ await adapter.postMessage(dest, { text: t('cmd.thread.nothingRunning') });
80
91
  }
81
92
  }
82
93
  async function handleThreadList(channel, adapter) {
83
94
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
84
95
  const threads = threadStore.findByChannel(channel).slice(0, 10);
85
96
  if (threads.length === 0) {
86
- await adapter.postMessage(dest, { text: 'No threads found for this channel.' });
97
+ await adapter.postMessage(dest, { text: t('cmd.thread.noThreadsChannel') });
87
98
  return;
88
99
  }
89
- const lines = ['*Recent Threads*'];
90
- for (const t of threads) {
91
- const modeLabel = t.templateName || 'ad-hoc';
92
- lines.push(`• \`${t.id}\` ${modeLabel} — ${t.status} | ${t.steps.length} steps | $${t.totalCostUsd.toFixed(4)}`);
100
+ const lines = [t('cmd.thread.recentHeader')];
101
+ for (const thr of threads) {
102
+ const modeLabel = thr.templateName || t('cmd.thread.adHoc');
103
+ lines.push(`• ${t('cmd.thread.recentLine', { id: thr.id, mode: modeLabel, status: thr.status, steps: thr.steps.length, cost: thr.totalCostUsd.toFixed(4) })}`);
93
104
  }
94
105
  await adapter.postMessage(dest, { text: lines.join('\n') });
95
106
  }
@@ -97,16 +108,16 @@ async function handleThreadListRunning(channel, adapter) {
97
108
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
98
109
  const executions = runningExecutions.getAll().filter(e => e.threadId);
99
110
  if (executions.length === 0) {
100
- await adapter.postMessage(dest, { text: 'No running threads.' });
111
+ await adapter.postMessage(dest, { text: t('cmd.thread.noRunning') });
101
112
  return;
102
113
  }
103
- const lines = ['*Running Threads*'];
114
+ const lines = [t('cmd.thread.runningHeader')];
104
115
  for (const exec of executions) {
105
116
  const thread = exec.threadId ? threadStore.get(exec.threadId) : null;
106
- const modeLabel = thread?.templateName || 'ad-hoc';
117
+ const modeLabel = thread?.templateName || t('cmd.thread.adHoc');
107
118
  const stepCount = thread?.steps.length ?? 0;
108
119
  const cost = thread?.totalCostUsd ?? 0;
109
- lines.push(`• \`${exec.threadId}\` — ${exec.channel || '?'} | ${modeLabel} | ${stepCount} step(s) | $${cost.toFixed(4)}`);
120
+ lines.push(`• ${t('cmd.thread.runningLine', { id: exec.threadId ?? '', channel: exec.channel || '?', mode: modeLabel, steps: stepCount, cost: cost.toFixed(4) })}`);
110
121
  }
111
122
  await adapter.postMessage(dest, { text: lines.join('\n') });
112
123
  }
@@ -114,16 +125,16 @@ async function sendThreadUsage(channel, adapter) {
114
125
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
115
126
  await adapter.postMessage(dest, {
116
127
  text: [
117
- '*Thread Commands*',
118
- '`!thread` — show active thread status',
119
- '`!thread agents` — list available agents',
120
- '`!thread templates` — list available templates',
121
- '`!thread <agent> <message>` — start ad-hoc thread with one agent',
122
- '`!thread <template> <message>` — start template-based thread',
123
- '`!thread add <agent> [message]` — add agent to current thread',
124
- '`!cancel` — cancel active thread (also `!thread cancel`)',
125
- '`!thread list` — list recent threads',
126
- '`!thread list --running` — list running threads across channels',
128
+ t('cmd.thread.usageHeader'),
129
+ t('cmd.thread.usageStatus'),
130
+ t('cmd.thread.usageAgents'),
131
+ t('cmd.thread.usageTemplates'),
132
+ t('cmd.thread.usageAdHoc'),
133
+ t('cmd.thread.usageTemplate'),
134
+ t('cmd.thread.usageAdd'),
135
+ t('cmd.thread.usageCancel'),
136
+ t('cmd.thread.usageList'),
137
+ t('cmd.thread.usageListRunning'),
127
138
  ].join('\n'),
128
139
  });
129
140
  }
@@ -1,9 +1,10 @@
1
1
  import { createLogger } from '../../core/log.js';
2
+ import { Icons } from '../../core/icons.js';
2
3
  import { conversationLedger } from '../../store/conversation-ledger-repo.js';
3
4
  import * as sessionBackup from '../../domain/sessions/session-backup.js';
4
5
  import { deleteSessionAsync } from '../../domain/sessions/session.js';
5
6
  import { resolveBackendForChannel } from '../../domain/agents/index.js';
6
- import { channelQueues } from '../channel-queue.js';
7
+ import { conduitQueues } from '../conduit-queue.js';
7
8
  import { supersededEdits } from '../superseded-edits.js';
8
9
  const log = createLogger('edit-handler');
9
10
  const DEBOUNCE_MS = 500;
@@ -22,7 +23,7 @@ const pendingEdits = new Map();
22
23
  function createEditHandler(deps) {
23
24
  return async function handleMessageEdit(ctx, adapter) {
24
25
  const { originalRef, newText } = ctx;
25
- const channel = originalRef.channel;
26
+ const channel = originalRef.conduit;
26
27
  const originalTs = originalRef.messageId;
27
28
  log.info('Message edited:', { channel, ts: originalTs, new: newText?.substring(0, 40) });
28
29
  // Look up the original processing record
@@ -64,10 +65,10 @@ async function processEdit({ channel, adapter, originalTs, newText, turnIndex, c
64
65
  // resolveBackendForChannel reads the channel's profile and falls back to global if absent.
65
66
  const backend = resolveBackendForChannel(channel) || conversation.backend;
66
67
  // Step 1: Cancel any active processing on this channel
67
- if (activeAgents.has(channel)) {
68
+ if (activeAgents.hasChannel(channel)) {
68
69
  supersededEdits.mark(channel);
69
- activeAgents.supersede(channel, 'edit');
70
- channelQueues.delete(channel);
70
+ activeAgents.supersedeByChannel(channel, 'edit');
71
+ conduitQueues.delete(channel);
71
72
  log.info('Killed active process for edit retry');
72
73
  }
73
74
  // Step 2: Rollback — mark all turns from editedTurnIndex onward as superseded
@@ -146,13 +147,13 @@ async function cleanupSupersededMessages(supersededTurns, channel, adapter) {
146
147
  const supersededStatusTimestamps = [];
147
148
  for (const turn of supersededTurns) {
148
149
  for (const ts of turn.responseMessageTimestamps) {
149
- promises.push(adapter.deleteMessage({ channel, messageId: ts }).catch((e) => {
150
+ promises.push(adapter.deleteMessage({ conduit: channel, messageId: ts }).catch((e) => {
150
151
  log.warn('Failed to delete message:', ts, e.message);
151
152
  }));
152
153
  }
153
154
  if (turn.statusMessageTs) {
154
155
  supersededStatusTimestamps.push(turn.statusMessageTs);
155
- promises.push(adapter.updateMessage({ channel, messageId: turn.statusMessageTs }, { text: `:fast_forward: Superseded by edit` }).catch(() => { }));
156
+ promises.push(adapter.updateMessage({ conduit: channel, messageId: turn.statusMessageTs }, { text: `${Icons.superseded} Superseded by edit` }).catch(() => { }));
156
157
  }
157
158
  }
158
159
  await Promise.allSettled(promises);
@@ -17,6 +17,19 @@ export function registerHookBridgeSubscribers(bus, adapter, planApprovals) {
17
17
  try {
18
18
  const group = askUserQuestion.createHookGroup(ev.requestId, ev.channel, ev.sessionId, ev.questions, ev.extensionUiId, ev.threadId ?? null);
19
19
  askUserQuestion.registerHookResolver(ev.requestId, (data) => resolveHookRequest(ev.requestId, data));
20
+ // Inline-modal platforms (Feishu) render the question form as an inline card,
21
+ // so the intermediate "Answer" summary card + click is redundant — post the
22
+ // form directly. Slack requires a user click (trigger_id) to open a modal, so
23
+ // it keeps the summary card + Answer button below. The conduit prefix is the
24
+ // reliable per-channel signal under a multi-platform CompositeAdapter (merged
25
+ // capabilities can't distinguish channels).
26
+ if (ev.channel.startsWith('feishu:')) {
27
+ // Flush any pending streamed text so the form lands after it, in order.
28
+ const fstream = getStreamingCallback(ev.channel)?.stream;
29
+ await fstream?.flush?.().catch(() => { });
30
+ await adapter.openModal(ev.channel, askUserQuestion.buildQuestionModalDefinition(group));
31
+ return;
32
+ }
20
33
  // streamingCb is fetched only to extract the stream reference — not invoked directly for AskUser
21
34
  const streamingCb = getStreamingCallback(ev.channel);
22
35
  const stream = streamingCb?.stream;
@@ -67,10 +80,13 @@ export function registerHookBridgeSubscribers(bus, adapter, planApprovals) {
67
80
  });
68
81
  }
69
82
  else {
83
+ // Fallback path (stream already finalized after the turn): pass threadId
84
+ // explicitly so the approval card lands inside the conversation topic via
85
+ // message.reply instead of being posted as a standalone message.
70
86
  await adapter.postInteractive(planDest, {
71
87
  text: 'Plan approval',
72
88
  ...planApproval,
73
- });
89
+ }, { threadId: ev.threadId ?? undefined });
74
90
  }
75
91
  }
76
92
  catch (e) {
@@ -1,6 +1,6 @@
1
1
  import type { PlatformAdapter, MessageEditContext } from '../../platform/index.js';
2
2
  export interface MessageHandlerDeps {
3
- dispatchCommand: (text: string | undefined, channel: string, adapter: PlatformAdapter, threadTs?: string | null) => boolean;
3
+ dispatchCommand: (text: string | undefined, channel: string, adapter: PlatformAdapter, threadAnchorId?: string | null) => boolean;
4
4
  handleMessageEdit: (ctx: MessageEditContext, adapter: PlatformAdapter) => void;
5
5
  }
6
6
  export declare function registerMessageHandler(adapter: PlatformAdapter, deps: MessageHandlerDeps): void;
@@ -13,11 +13,11 @@ export function registerMessageHandler(adapter, deps) {
13
13
  });
14
14
  adapter.onMessage(async (ctx) => {
15
15
  const message = ctx.message;
16
- log.info('Message event:', JSON.stringify({ subtype: message.subtype, isBot: message.isBot, text: message.text?.substring(0, 50), files: message.files?.length, threadId: message.ref.threadId }));
16
+ log.info('Message event:', JSON.stringify({ kind: message.kind, isBot: message.isBot, text: message.text?.substring(0, 50), files: message.files?.length, threadId: message.ref.threadId }));
17
17
  if (routeBotMessage(message)) { /* stripped BRANCH_CALLBACK prefix, continue */ }
18
18
  else if (message.isBot)
19
19
  return;
20
- if (message.subtype && message.subtype !== 'file_share')
20
+ if (message.kind === 'system')
21
21
  return;
22
22
  const hasFiles = (message.files?.length || 0) > 0;
23
23
  const userMessage = message.text;
@@ -25,20 +25,20 @@ export function registerMessageHandler(adapter, deps) {
25
25
  const forwardedContent = extractForwardedContent(message);
26
26
  if (!userMessage && !hasFiles && !forwardedContent)
27
27
  return;
28
- const threadTs = message.ref.threadId || null;
29
- if (shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, message.ref.channel, adapter, threadTs))
28
+ const threadAnchorId = message.ref.threadId || null;
29
+ if (shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, message.ref.conduit, adapter, threadAnchorId))
30
30
  return;
31
- const channel = message.ref.channel;
31
+ const channel = message.ref.conduit;
32
32
  let agentMessage = normalizeSkillCommandPrefix(userMessage || '');
33
33
  if (forwardedContent) {
34
34
  agentMessage = `[Forwarded message]\n${forwardedContent}\n[End forwarded message]\n\n${agentMessage || 'The user forwarded the above message to you.'}`;
35
35
  }
36
36
  const threadAddMatch = trimmedMessage?.match(/^!thread\s+add\s+(\S+)(?:\s+([\s\S]+))?$/) ?? null;
37
37
  const threadStartMatch = trimmedMessage?.match(/^!thread\s+(\S+)\s+([\s\S]+)/) ?? null;
38
- const existingThread = threadTs ? threadStore.findByPlatformThread(channel, threadTs) : null;
38
+ const existingThread = threadAnchorId ? threadStore.findByPlatformThread(channel, threadAnchorId) : null;
39
39
  const isActiveThread = !!(existingThread && (existingThread.status === 'running' || existingThread.status === 'waiting'));
40
40
  await orchestrator.handleMessage({
41
- message, channel, adapter, threadTs, hasFiles,
41
+ message, channel, adapter, threadAnchorId, hasFiles,
42
42
  userMessage: userMessage || '', agentMessage,
43
43
  threadAddMatch, threadStartMatch, existingThread, isActiveThread,
44
44
  });
@@ -56,7 +56,7 @@ function routeBotMessage(message) {
56
56
  return false;
57
57
  }
58
58
  // --- Command dispatch check ---
59
- function shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, channel, adapter, threadTs) {
59
+ function shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, channel, adapter, threadAnchorId) {
60
60
  const threadAddMatch = trimmedMessage?.match(/^!thread\s+add\s+(\S+)(?:\s+([\s\S]+))?$/);
61
61
  const isThreadExecCmd = (() => {
62
62
  if (threadAddMatch)
@@ -66,5 +66,5 @@ function shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, channel,
66
66
  return false;
67
67
  return getTemplate(m[1]) != null || getAgent(m[1]) != null;
68
68
  })();
69
- return !isThreadExecCmd && dispatchCommand(trimmedMessage, channel, adapter, threadTs);
69
+ return !isThreadExecCmd && dispatchCommand(trimmedMessage, channel, adapter, threadAnchorId);
70
70
  }
@@ -1,6 +1,6 @@
1
- // input: GitHub push, task-op, remote cmd, hook HTTP events
1
+ // input: GitHub push, task-op, thread-op, remote cmd, hook HTTP events
2
2
  // output: startWebhookServer
3
- // pos: GitHub/task-op/hook webhook HTTP entry point
3
+ // pos: GitHub/task-op/thread-op/hook webhook HTTP entry point
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
6
  import * as http from 'http';
@@ -10,6 +10,14 @@ import { taskMutator } from '../../domain/tasks/mutator.js';
10
10
  import { sendCommand, isDeviceOnline, getOnlineDevices } from '../../domain/remote/client-manager.js';
11
11
  import { registerAskQuestion, registerPlanApproval } from './hook-bridge.js';
12
12
  import { getCurrentPlanFilePath } from '../../domain/agents/index.js';
13
+ import { ctx as jobCtx } from '../../domain/scheduling/job-registry.js';
14
+ import { createThread, cancelThread, readArtifact, listTemplates, listAgents, checkSpawnGuards, getRootThreadId, registerChildSpawn, buildThreadTree, getTreeThreads, buildContractPrompt, buildMissionChain } from '../../domain/threads/index.js';
15
+ import { runThreadDetached } from '../thread-executor.js';
16
+ import { buildThreadSummary } from '../../domain/threads/runner.js';
17
+ import { Icons } from '../../core/icons.js';
18
+ import { buildStatusActionBlocks, buildSealedStatusActionBlocks, initStatusBlocks } from '../status-helpers.js';
19
+ import { threadStore } from '../../store/thread-repo.js';
20
+ import { fireThreadCallback } from '../thread-callback.js';
13
21
  const log = createLogger('webhook');
14
22
  const PORT = parseInt(process.env.WEBHOOK_PORT || '3001', 10);
15
23
  // Read at call time, not import time — dotenv.config() in app.ts runs AFTER ESM imports
@@ -133,6 +141,229 @@ function createWebhookHandler({ secret = getSecret(), } = {}) {
133
141
  });
134
142
  return;
135
143
  }
144
+ // --- Thread operation (from MCP sidecar → thread system) ---
145
+ // Local-only, no secret (same trust model as /webhook/remote-command). thread_start is
146
+ // fire-and-forget: createThread + runThread().catch() without await, returning the threadId.
147
+ if (req.method === 'POST' && req.url === '/webhook/thread-op') {
148
+ readJsonBody(req, async (error, _body, data) => {
149
+ if (error) {
150
+ res.writeHead(400);
151
+ res.end('Bad JSON');
152
+ return;
153
+ }
154
+ const reply = (obj) => {
155
+ res.writeHead(200, { 'Content-Type': 'application/json' });
156
+ res.end(JSON.stringify(obj));
157
+ };
158
+ try {
159
+ const action = data.action;
160
+ if (action === 'start') {
161
+ const { template, agent, message } = data;
162
+ if ((template && agent) || (!template && !agent)) {
163
+ return reply({ success: false, error: 'provide exactly one of template or agent' });
164
+ }
165
+ if (!message)
166
+ return reply({ success: false, error: 'message required' });
167
+ const maxDepth = parseInt(process.env.CORTEX_THREAD_MAX_DEPTH || '5', 10) || 5;
168
+ const curDepth = Number(data.depth) || 0;
169
+ if (curDepth >= maxDepth) {
170
+ return reply({ success: false, error: `max thread depth (${maxDepth}) reached — cannot spawn nested thread at depth ${curDepth}` });
171
+ }
172
+ if (!jobCtx.adapter) {
173
+ return reply({ success: false, error: 'no platform adapter available (daemon not fully initialized)' });
174
+ }
175
+ // Tree resource guards (DR-0014): width / node count / budget. A rejection is a
176
+ // signal to escalate or re-plan — the error text says so to the calling agent.
177
+ const parentThread = data.parentThreadId ? threadStore.get(String(data.parentThreadId)) : null;
178
+ const guard = checkSpawnGuards(parentThread);
179
+ if (guard.ok === false) {
180
+ return reply({ success: false, error: `${guard.reason}. Do NOT retry this spawn — fold the remaining work into your own step, or escalate via [ABORT: <diagnosis>].` });
181
+ }
182
+ const projectId = data.projectId || 'general';
183
+ // The originating conduit (the starter agent's SLACK_CHANNEL, forwarded by thread-ops.ts).
184
+ // When present we route output back to that channel with a live status message, mirroring
185
+ // the Slack `!thread` path (thread-executor handleThreadStart). When absent (non-Slack /
186
+ // channel-less context) we fall back to project-report routing (project conduit → admin DM).
187
+ const haveChannel = typeof data.channel === 'string' && data.channel.length > 0;
188
+ const channel = data.channel || projectId;
189
+ // Structured delegation contract (DR-0014): optional thread_start params compose
190
+ // into a contract prompt; the ancestor goal chain rides along to prevent drift.
191
+ const contract = (data.goal || data.done_when || data.context_files || data.deliverable_path || data.budget_usd != null)
192
+ ? {
193
+ goal: String(data.goal || message).slice(0, 500),
194
+ doneWhen: data.done_when ? String(data.done_when) : null,
195
+ contextFiles: Array.isArray(data.context_files) ? data.context_files.map(String) : undefined,
196
+ deliverablePath: data.deliverable_path ? String(data.deliverable_path) : null,
197
+ budgetUsd: data.budget_usd != null ? Number(data.budget_usd) : null,
198
+ }
199
+ : null;
200
+ const missionChain = buildMissionChain(parentThread);
201
+ const thread = createThread(channel, {
202
+ templateName: template || null,
203
+ agentName: agent || null,
204
+ userMessage: buildContractPrompt({ message, contract, missionChain }),
205
+ userMessageTs: `mcp_${Date.now()}`,
206
+ projectId,
207
+ metadata: {
208
+ trigger: 'mcp-thread',
209
+ depth: curDepth + 1,
210
+ parentSessionId: data.parentSessionId || null,
211
+ parentThreadId: data.parentThreadId || null,
212
+ parentChannel: data.parentChannel || null,
213
+ parentProfile: data.parentProfile || null,
214
+ rootThreadId: parentThread ? getRootThreadId(parentThread) : null,
215
+ resumeDest: haveChannel ? 'interactive-reply' : 'project-report',
216
+ contract,
217
+ missionChain,
218
+ },
219
+ });
220
+ // Register the child on its thread parent: childThreadIds always (width counter),
221
+ // waitingOn when the parent intends to suspend on it (wait defaults to true for
222
+ // thread parents — the [WAIT_CHILDREN] protocol).
223
+ if (parentThread) {
224
+ await registerChildSpawn(parentThread.id, thread.id, data.wait !== false);
225
+ }
226
+ let dest;
227
+ let statusMsg = null;
228
+ if (haveChannel) {
229
+ dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
230
+ const label = template || agent;
231
+ const startText = `${Icons.processing} Starting thread (${template ? label : `agent:${label}`})...`;
232
+ try {
233
+ statusMsg = await jobCtx.adapter.postMessage(dest, { text: startText });
234
+ const blocksTemplate = { channel, sessionName: null, isDm: false, threadId: thread.id };
235
+ await jobCtx.adapter.updateMessage(statusMsg, {
236
+ text: startText,
237
+ richBlocks: buildStatusActionBlocks(startText, blocksTemplate),
238
+ }).catch(() => { });
239
+ initStatusBlocks(statusMsg, blocksTemplate);
240
+ }
241
+ catch (e) {
242
+ log.warn(`thread-op start: status message post failed: ${e.message}`);
243
+ statusMsg = null;
244
+ }
245
+ }
246
+ else {
247
+ dest = { type: 'project-report', projectId, trigger: 'mcp-thread', sessionId: '' };
248
+ }
249
+ const runOpts = {
250
+ adapter: jobCtx.adapter,
251
+ channel,
252
+ destination: dest,
253
+ threadAnchorId: statusMsg ? statusMsg.messageId : null,
254
+ statusMsg,
255
+ startTime: Date.now(),
256
+ onProgress: null,
257
+ onToolUse: null,
258
+ };
259
+ // Hold the daemon busy gate for the WHOLE pipeline so a deferred rebuild/restart can't
260
+ // SIGTERM app.ts mid-thread and stamp it "Interrupted by server restart". (Bare runThread
261
+ // here was invisible to the busy/idle gate — see runThreadDetached.)
262
+ runThreadDetached(thread.id, runOpts, {
263
+ onSettled: (id) => {
264
+ // Seal the live status message with a summary (interactive path only).
265
+ // A suspended parent ([WAIT_CHILDREN] → status 'waiting') is NOT sealed:
266
+ // it will resume; the message just reflects the suspension.
267
+ if (statusMsg) {
268
+ const t = threadStore.get(id);
269
+ if (t && t.status === 'waiting') {
270
+ const n = (t.metadata?.waitingOn?.length ?? 0) + (t.metadata?.waitingOnTasks?.length ?? 0);
271
+ // Persist the ref so the post-resume settle can refresh this message.
272
+ void threadStore.mutate(t.id, (r) => { (r.metadata ??= {}).statusMsgRef = statusMsg; }).catch(() => { });
273
+ void jobCtx.adapter.updateMessage(statusMsg, {
274
+ text: `${Icons.processing} Thread suspended — waiting on ${n} child(ren)`,
275
+ }).catch(() => { });
276
+ }
277
+ else if (t) {
278
+ const totalNumTurns = t.steps.reduce((s, st) => s + (st.numTurns || 0), 0);
279
+ const summaryText = buildThreadSummary({ thread: t, totalCostUsd: t.totalCostUsd, totalNumTurns, finalOutput: null, lastAgentResult: null, executionId: null });
280
+ void jobCtx.adapter.updateMessage(statusMsg, {
281
+ text: summaryText,
282
+ richBlocks: buildSealedStatusActionBlocks(summaryText, { channel, sessionName: null, isDm: false, threadId: t.id }),
283
+ }).catch(() => { });
284
+ }
285
+ }
286
+ // Return the promise so runThreadDetached holds the busy gate across this callback —
287
+ // it wakes the parent agent for a full turn, and a deferred restart firing mid-wake
288
+ // would drop the notification. The .catch keeps the returned promise non-rejecting.
289
+ return fireThreadCallback(id).catch((e) => log.error(`thread-callback ${id}: ${e.message}`));
290
+ },
291
+ });
292
+ log.info(`thread-op start ${thread.id} (${template || agent}, depth ${curDepth + 1})`);
293
+ return reply({ success: true, data: { threadId: thread.id, status: 'running' } });
294
+ }
295
+ if (action === 'status') {
296
+ const t = threadStore.get(data.threadId);
297
+ if (!t)
298
+ return reply({ success: false, error: 'thread not found' });
299
+ return reply({ success: true, data: {
300
+ threadId: t.id, status: t.status, activeAgent: t.activeAgent, stepCount: t.steps.length,
301
+ totalCostUsd: t.totalCostUsd, abortReason: t.abortReason, artifactPath: t.artifactPath,
302
+ createdAt: t.createdAt, updatedAt: t.updatedAt, endedAt: t.endedAt, error: t.error,
303
+ } });
304
+ }
305
+ if (action === 'result') {
306
+ const t = threadStore.get(data.threadId);
307
+ if (!t)
308
+ return reply({ success: false, error: 'thread not found' });
309
+ const terminal = ['completed', 'failed', 'cancelled', 'aborted'].includes(t.status);
310
+ const artifact = readArtifact(t.id);
311
+ const finalOutput = t.steps.length ? t.steps[t.steps.length - 1].output : null;
312
+ return reply({ success: true, data: {
313
+ threadId: t.id, status: t.status, terminal,
314
+ ...(terminal ? {} : { note: 'thread still running — result is partial' }),
315
+ artifact, finalOutput,
316
+ } });
317
+ }
318
+ if (action === 'list') {
319
+ return reply({ success: true, data: {
320
+ templates: listTemplates().map((t) => ({ name: t.name, description: t.description })),
321
+ agents: listAgents().map((a) => ({ name: a.name, description: a.description })),
322
+ } });
323
+ }
324
+ if (action === 'list-threads') {
325
+ const scope = data.scope || 'mine';
326
+ let threads = threadStore.getAll();
327
+ if (scope === 'project') {
328
+ const pid = data.projectId || 'general';
329
+ threads = threads.filter((t) => t.projectId === pid);
330
+ }
331
+ else {
332
+ // 'mine': threads spawned from the caller's session
333
+ const sid = data.parentSessionId || null;
334
+ threads = sid ? threads.filter((t) => t.metadata?.parentSessionId === sid) : [];
335
+ }
336
+ // Tree view (DR-0014): expand the matched threads to their full trees and
337
+ // return nested nodes with per-root rollups (nodeCount/cost/byStatus/maxDepth).
338
+ if (data.view === 'tree') {
339
+ const rootIds = new Set(threads.map((t) => getRootThreadId(t)));
340
+ const treeThreads = [...rootIds].flatMap((rid) => getTreeThreads(rid));
341
+ const trees = buildThreadTree(treeThreads);
342
+ return reply({ success: true, data: { scope, view: 'tree', count: trees.length, trees } });
343
+ }
344
+ threads = threads.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
345
+ const limit = Number(data.limit) || 50;
346
+ const out = threads.slice(0, limit).map((t) => ({
347
+ threadId: t.id, status: t.status, templateName: t.templateName, activeAgent: t.activeAgent,
348
+ stepCount: t.steps.length, totalCostUsd: t.totalCostUsd,
349
+ createdAt: t.createdAt, updatedAt: t.updatedAt,
350
+ trigger: t.metadata?.trigger ?? null, depth: t.metadata?.depth ?? null,
351
+ }));
352
+ return reply({ success: true, data: { scope, count: out.length, threads: out } });
353
+ }
354
+ if (action === 'cancel') {
355
+ const cancelled = await cancelThread(data.threadId);
356
+ return reply({ success: true, data: { cancelled } });
357
+ }
358
+ return reply({ success: false, error: `unknown action: ${action}` });
359
+ }
360
+ catch (e) {
361
+ log.error(`thread-op error: ${e.message}`);
362
+ reply({ success: false, error: e.message });
363
+ }
364
+ });
365
+ return;
366
+ }
136
367
  // --- PreToolUse hook: AskUserQuestion ---
137
368
  if (req.method === 'POST' && req.url === '/hook/ask-user-question') {
138
369
  readJsonBody(req, async (error, _body, data) => {
@@ -33,7 +33,7 @@ export declare function runAutoCompoundForScheduledTask({ baseResult, channel, p
33
33
  onAssistantMessage?: ((text: string) => void) | null;
34
34
  }): Promise<AgentResult>;
35
35
  /** Build a streaming callback that aggregates assistant messages via OutputStream. */
36
- export declare function makeStreamingMessageCallback(adapter: PlatformAdapter, destination: Destination, threadTs?: string | null, onMessagePosted?: ((ref: MessageRef) => void) | null, durable?: import('../platform/types.js').DurableHooks | null): ((text: string) => void) & {
36
+ export declare function makeStreamingMessageCallback(adapter: PlatformAdapter, destination: Destination, threadAnchorId?: string | null, onMessagePosted?: ((ref: MessageRef) => void) | null, durable?: import('../platform/types.js').DurableHooks | null): ((text: string) => void) & {
37
37
  stream: OutputStream;
38
38
  };
39
39
  /** Extract text content from forwarded messages (attachments marked isForwarded by the platform adapter). */
@@ -45,6 +45,10 @@ export interface StatusBlocksTemplate {
45
45
  sessionName: string | null;
46
46
  isDm: boolean;
47
47
  threadId?: string | null;
48
+ /** Execution-scoped Cancel target for the conversation path (plain user messages that
49
+ * are no longer wrapped in a thread). When set, the Cancel handler resolves the running
50
+ * execution via executionId instead of threadId. */
51
+ executionId?: string | null;
48
52
  }
49
53
  /** Build richBlocks for the initial "Processing" message (Cancel button included). */
50
54
  export declare function buildStatusActionBlocks(text: string, template: StatusBlocksTemplate): RichBlock[];