@cortex-agent/server 2026.5.25-1 → 2026.6.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (354) hide show
  1. package/defaults/config/thread-templates.json +28 -1
  2. package/defaults/hooks/cortex-md-injector.mjs +47 -31
  3. package/defaults/hooks/post-task-hook.mjs +6 -0
  4. package/defaults/hooks/task-status-check.mjs +8 -0
  5. package/defaults/mcp-config-slack.json +11 -0
  6. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +18 -0
  7. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +5 -6
  8. package/defaults/prompts/directives/manager.md +67 -0
  9. package/dist/agent-adapter/claude/adapter-tui.d.ts +35 -3
  10. package/dist/agent-adapter/claude/adapter-tui.js +91 -12
  11. package/dist/agent-adapter/claude/adapter.js +11 -0
  12. package/dist/agent-adapter/claude/defaults.d.ts +30 -0
  13. package/dist/agent-adapter/claude/defaults.js +30 -0
  14. package/dist/agent-adapter/claude/jsonl-tail.d.ts +2 -2
  15. package/dist/agent-adapter/claude/jsonl-tail.js +25 -20
  16. package/dist/agent-adapter/claude/spawn-args.d.ts +11 -0
  17. package/dist/agent-adapter/claude/spawn-args.js +49 -7
  18. package/dist/agent-adapter/claude/tmux-control.d.ts +20 -0
  19. package/dist/agent-adapter/claude/tmux-control.js +54 -8
  20. package/dist/agent-adapter/codex/adapter.js +1 -1
  21. package/dist/agent-adapter/normalize/event-types.d.ts +1 -0
  22. package/dist/agent-adapter/pi/adapter.js +46 -19
  23. package/dist/agent-adapter/pi/agent-dir.d.ts +21 -0
  24. package/dist/agent-adapter/pi/agent-dir.js +53 -2
  25. package/dist/agent-adapter/pi/event-parser.js +13 -1
  26. package/dist/agent-adapter/pi/mcp-bridge.d.ts +12 -0
  27. package/dist/agent-adapter/pi/mcp-bridge.js +47 -9
  28. package/dist/agent-adapter/pi/tool-shims.d.ts +14 -0
  29. package/dist/agent-adapter/pi/tool-shims.js +167 -140
  30. package/dist/agent-adapter/types.d.ts +7 -2
  31. package/dist/core/atomic-write.js +21 -0
  32. package/dist/core/config-generator.d.ts +10 -0
  33. package/dist/core/config-generator.js +28 -0
  34. package/dist/core/gateway-generator.d.ts +77 -7
  35. package/dist/core/gateway-generator.js +301 -29
  36. package/dist/core/icons.d.ts +68 -0
  37. package/dist/core/icons.js +67 -0
  38. package/dist/core/profile-generator.d.ts +6 -0
  39. package/dist/core/profile-generator.js +35 -7
  40. package/dist/core/running-executions.d.ts +51 -41
  41. package/dist/core/running-executions.js +120 -73
  42. package/dist/core/status-format.js +3 -2
  43. package/dist/core/task-parser.d.ts +3 -0
  44. package/dist/core/task-parser.js +3 -1
  45. package/dist/core/types/thread-types.d.ts +54 -8
  46. package/dist/domain/agents/facade.d.ts +18 -0
  47. package/dist/domain/agents/facade.js +26 -3
  48. package/dist/domain/agents/profile-manager.d.ts +11 -0
  49. package/dist/domain/agents/profile-manager.js +21 -2
  50. package/dist/domain/costs/codex-usage-monitor.js +2 -1
  51. package/dist/domain/costs/rate-limit-throttle.js +14 -2
  52. package/dist/domain/executions/registry.d.ts +24 -0
  53. package/dist/domain/executions/registry.js +38 -0
  54. package/dist/domain/mcp/core-server.js +15 -3
  55. package/dist/domain/mcp/feishu/bitable.d.ts +3 -0
  56. package/dist/domain/mcp/feishu/bitable.js +168 -0
  57. package/dist/domain/mcp/feishu/block-types.d.ts +44 -0
  58. package/dist/domain/mcp/feishu/block-types.js +127 -0
  59. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +19 -0
  60. package/dist/domain/mcp/feishu/blocks-to-text.js +43 -0
  61. package/dist/domain/mcp/feishu/client.d.ts +46 -0
  62. package/dist/domain/mcp/feishu/client.js +87 -0
  63. package/dist/domain/mcp/feishu/docx.d.ts +3 -0
  64. package/dist/domain/mcp/feishu/docx.js +163 -0
  65. package/dist/domain/mcp/feishu/drive.d.ts +23 -0
  66. package/dist/domain/mcp/feishu/drive.js +66 -0
  67. package/dist/domain/mcp/feishu/file.d.ts +14 -0
  68. package/dist/domain/mcp/feishu/file.js +107 -0
  69. package/dist/domain/mcp/feishu/index.d.ts +6 -0
  70. package/dist/domain/mcp/feishu/index.js +61 -0
  71. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +40 -0
  72. package/dist/domain/mcp/feishu/markdown-to-blocks.js +191 -0
  73. package/dist/domain/mcp/feishu/sheets.d.ts +3 -0
  74. package/dist/domain/mcp/feishu/sheets.js +119 -0
  75. package/dist/domain/mcp/feishu/types.d.ts +26 -0
  76. package/dist/domain/mcp/feishu/types.js +38 -0
  77. package/dist/domain/mcp/feishu/user-auth.d.ts +140 -0
  78. package/dist/domain/mcp/feishu/user-auth.js +286 -0
  79. package/dist/domain/mcp/feishu/wiki.d.ts +3 -0
  80. package/dist/domain/mcp/feishu/wiki.js +77 -0
  81. package/dist/domain/mcp/feishu-server.d.ts +2 -0
  82. package/dist/domain/mcp/feishu-server.js +33 -0
  83. package/dist/domain/mcp/server.d.ts +0 -1
  84. package/dist/domain/mcp/server.js +6 -25
  85. package/dist/domain/mcp/slack-server.d.ts +3 -0
  86. package/dist/domain/mcp/slack-server.js +46 -0
  87. package/dist/domain/mcp/tools/context.js +1 -1
  88. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  89. package/dist/domain/mcp/tools/schedule.js +6 -20
  90. package/dist/domain/mcp/tools/slack.js +20 -7
  91. package/dist/domain/mcp/tools/thread-ops.d.ts +2 -0
  92. package/dist/domain/mcp/tools/thread-ops.js +121 -0
  93. package/dist/domain/mcp/tools/time.d.ts +2 -0
  94. package/dist/domain/mcp/tools/time.js +66 -0
  95. package/dist/domain/mcp/tools/tui-ask.js +1 -1
  96. package/dist/domain/mcp/tools/tui-plan.js +2 -2
  97. package/dist/domain/mcp/tui-server.js +1 -0
  98. package/dist/domain/monitor/disk-monitor.js +2 -1
  99. package/dist/domain/monitor/gpu-monitor.js +2 -1
  100. package/dist/domain/remote/client-hot-reload.js +3 -2
  101. package/dist/domain/remote/client-manager.js +8 -6
  102. package/dist/domain/scheduling/job-registry.d.ts +4 -0
  103. package/dist/domain/scheduling/job-registry.js +1 -0
  104. package/dist/domain/scheduling/jobs/_shared.js +2 -1
  105. package/dist/domain/scheduling/jobs/memory-index-regen.js +3 -2
  106. package/dist/domain/scheduling/jobs/scheduled-task.js +9 -23
  107. package/dist/domain/scheduling/jobs/sync-public.js +4 -3
  108. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +1 -8
  109. package/dist/domain/scheduling/jobs/target-dispatch.js +0 -7
  110. package/dist/domain/scheduling/jobs/task-archive.js +3 -2
  111. package/dist/domain/scheduling/jobs/task-dispatch.js +120 -10
  112. package/dist/domain/scheduling/schedule-command.js +16 -15
  113. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  114. package/dist/domain/scheduling/scheduler.js +2 -1
  115. package/dist/domain/sessions/session-hooks.d.ts +2 -2
  116. package/dist/domain/sessions/session-hooks.js +19 -18
  117. package/dist/domain/sessions/session-lifecycle.d.ts +38 -0
  118. package/dist/domain/sessions/session-lifecycle.js +44 -0
  119. package/dist/domain/system/install-cli.d.ts +7 -0
  120. package/dist/domain/system/install-cli.js +106 -0
  121. package/dist/domain/tasks/dispatch-utils.d.ts +58 -1
  122. package/dist/domain/tasks/dispatch-utils.js +53 -4
  123. package/dist/domain/tasks/dispatcher.js +26 -0
  124. package/dist/domain/tasks/lint.js +28 -0
  125. package/dist/domain/tasks/mutator.d.ts +16 -3
  126. package/dist/domain/tasks/mutator.js +41 -12
  127. package/dist/domain/tasks/pending-tracker.js +6 -5
  128. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  129. package/dist/domain/tasks/system/task-cli.js +37 -6
  130. package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
  131. package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
  132. package/dist/domain/tasks/system/task-mutations.js +166 -8
  133. package/dist/domain/threads/contract.d.ts +17 -0
  134. package/dist/domain/threads/contract.js +59 -0
  135. package/dist/domain/threads/hook-runner.js +7 -6
  136. package/dist/domain/threads/index.d.ts +2 -0
  137. package/dist/domain/threads/index.js +3 -1
  138. package/dist/domain/threads/prompt-builder.d.ts +15 -1
  139. package/dist/domain/threads/prompt-builder.js +41 -2
  140. package/dist/domain/threads/runner.d.ts +6 -5
  141. package/dist/domain/threads/runner.js +128 -79
  142. package/dist/domain/threads/state-machine.d.ts +23 -21
  143. package/dist/domain/threads/state-machine.js +113 -54
  144. package/dist/domain/threads/template-loader.js +3 -2
  145. package/dist/domain/threads/tree.d.ts +45 -0
  146. package/dist/domain/threads/tree.js +171 -0
  147. package/dist/domain/tui-session/index.d.ts +2 -0
  148. package/dist/domain/tui-session/index.js +3 -0
  149. package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
  150. package/dist/domain/tui-session/tui-session-service.js +103 -0
  151. package/dist/domain/tui-session/types.d.ts +67 -0
  152. package/dist/domain/tui-session/types.js +4 -0
  153. package/dist/domain/ui-service/index.d.ts +5 -0
  154. package/dist/domain/ui-service/index.js +3 -0
  155. package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
  156. package/dist/domain/ui-service/mutate/executions.js +15 -0
  157. package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
  158. package/dist/domain/ui-service/mutate/schedules.js +39 -0
  159. package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
  160. package/dist/domain/ui-service/mutate/tasks.js +59 -0
  161. package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
  162. package/dist/domain/ui-service/mutate/threads.js +21 -0
  163. package/dist/domain/ui-service/query/cost.d.ts +3 -0
  164. package/dist/domain/ui-service/query/cost.js +6 -0
  165. package/dist/domain/ui-service/query/executions.d.ts +2 -0
  166. package/dist/domain/ui-service/query/executions.js +35 -0
  167. package/dist/domain/ui-service/query/projects.d.ts +2 -0
  168. package/dist/domain/ui-service/query/projects.js +30 -0
  169. package/dist/domain/ui-service/query/schedules.d.ts +2 -0
  170. package/dist/domain/ui-service/query/schedules.js +23 -0
  171. package/dist/domain/ui-service/query/sessions.d.ts +2 -0
  172. package/dist/domain/ui-service/query/sessions.js +35 -0
  173. package/dist/domain/ui-service/query/tasks.d.ts +2 -0
  174. package/dist/domain/ui-service/query/tasks.js +30 -0
  175. package/dist/domain/ui-service/query/threads.d.ts +2 -0
  176. package/dist/domain/ui-service/query/threads.js +27 -0
  177. package/dist/domain/ui-service/subscribe.d.ts +5 -0
  178. package/dist/domain/ui-service/subscribe.js +118 -0
  179. package/dist/domain/ui-service/types.d.ts +237 -0
  180. package/dist/domain/ui-service/types.js +5 -0
  181. package/dist/domain/ui-service/ui-service.d.ts +2 -0
  182. package/dist/domain/ui-service/ui-service.js +83 -0
  183. package/dist/entry/app.js +94 -5
  184. package/dist/entry/cli.d.ts +12 -0
  185. package/dist/entry/cli.js +122 -12
  186. package/dist/entry/feishu-login.d.ts +28 -0
  187. package/dist/entry/feishu-login.js +218 -0
  188. package/dist/entry/init.d.ts +25 -2
  189. package/dist/entry/init.js +211 -64
  190. package/dist/events/event-types.d.ts +14 -0
  191. package/dist/hooks/cortex-md-injector.mjs +47 -31
  192. package/dist/hooks/post-task-hook.mjs +6 -0
  193. package/dist/hooks/task-status-check.mjs +8 -0
  194. package/dist/orchestration/agent-runner.d.ts +2 -1
  195. package/dist/orchestration/agent-runner.js +55 -55
  196. package/dist/orchestration/conduit-queue.d.ts +18 -0
  197. package/dist/orchestration/conduit-queue.js +32 -0
  198. package/dist/orchestration/conversation-runner.d.ts +48 -0
  199. package/dist/orchestration/conversation-runner.js +109 -0
  200. package/dist/orchestration/dispatch-reconciler.js +8 -1
  201. package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
  202. package/dist/orchestration/interactions/ask-user-question.js +3 -3
  203. package/dist/orchestration/interactions/interaction-handlers.js +48 -17
  204. package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
  205. package/dist/orchestration/interactions/plan-handler.js +4 -3
  206. package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
  207. package/dist/orchestration/interactions/update-prompt.js +100 -0
  208. package/dist/orchestration/lifecycle.d.ts +4 -4
  209. package/dist/orchestration/lifecycle.js +24 -22
  210. package/dist/orchestration/orchestrator.d.ts +1 -1
  211. package/dist/orchestration/routing/commands/cancel.js +39 -47
  212. package/dist/orchestration/routing/commands/channel.js +24 -11
  213. package/dist/orchestration/routing/commands/cost.js +2 -1
  214. package/dist/orchestration/routing/commands/device.js +3 -2
  215. package/dist/orchestration/routing/commands/dispatch.js +6 -5
  216. package/dist/orchestration/routing/commands/index.d.ts +1 -1
  217. package/dist/orchestration/routing/commands/index.js +11 -10
  218. package/dist/orchestration/routing/commands/mode.js +19 -18
  219. package/dist/orchestration/routing/commands/nvtop.js +10 -9
  220. package/dist/orchestration/routing/commands/sendfile.js +7 -6
  221. package/dist/orchestration/routing/commands/session.d.ts +1 -1
  222. package/dist/orchestration/routing/commands/session.js +17 -33
  223. package/dist/orchestration/routing/commands/tail.js +4 -3
  224. package/dist/orchestration/routing/commands/task.js +4 -3
  225. package/dist/orchestration/routing/commands/thread-handlers.js +16 -6
  226. package/dist/orchestration/routing/edit-handler.js +8 -7
  227. package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
  228. package/dist/orchestration/routing/message-router.d.ts +1 -1
  229. package/dist/orchestration/routing/message-router.js +9 -9
  230. package/dist/orchestration/routing/webhook.js +233 -2
  231. package/dist/orchestration/status-helpers.d.ts +5 -1
  232. package/dist/orchestration/status-helpers.js +7 -6
  233. package/dist/orchestration/thread-callback.d.ts +67 -0
  234. package/dist/orchestration/thread-callback.js +465 -0
  235. package/dist/orchestration/thread-executor.d.ts +22 -1
  236. package/dist/orchestration/thread-executor.js +85 -36
  237. package/dist/platform/adapter.d.ts +6 -2
  238. package/dist/platform/adapters/composite-adapter.d.ts +89 -0
  239. package/dist/platform/adapters/composite-adapter.js +318 -0
  240. package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
  241. package/dist/platform/adapters/feishu-output-stream.js +274 -36
  242. package/dist/platform/adapters/feishu.d.ts +50 -5
  243. package/dist/platform/adapters/feishu.js +370 -116
  244. package/dist/platform/adapters/index.d.ts +24 -3
  245. package/dist/platform/adapters/index.js +89 -11
  246. package/dist/platform/adapters/project-conduits.d.ts +9 -0
  247. package/dist/platform/adapters/project-conduits.js +42 -0
  248. package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
  249. package/dist/platform/adapters/slack-project-conduits.js +6 -40
  250. package/dist/platform/adapters/slack.d.ts +9 -2
  251. package/dist/platform/adapters/slack.js +83 -39
  252. package/dist/platform/adapters/tui/index.d.ts +9 -0
  253. package/dist/platform/adapters/tui/index.js +10 -0
  254. package/dist/platform/adapters/tui/ports.d.ts +20 -0
  255. package/dist/platform/adapters/tui/ports.js +4 -0
  256. package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
  257. package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
  258. package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
  259. package/dist/platform/adapters/tui/tui-connection.js +53 -0
  260. package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
  261. package/dist/platform/adapters/tui/tui-gateway.js +919 -0
  262. package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
  263. package/dist/platform/adapters/tui/tui-notifications.js +60 -0
  264. package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
  265. package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
  266. package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
  267. package/dist/platform/adapters/tui/tui-transcript.js +56 -0
  268. package/dist/platform/index.d.ts +1 -0
  269. package/dist/platform/index.js +2 -1
  270. package/dist/platform/interactive-builder.js +3 -2
  271. package/dist/platform/output-stream.d.ts +5 -0
  272. package/dist/platform/testing.d.ts +7 -11
  273. package/dist/platform/testing.js +18 -15
  274. package/dist/platform/tool-trace.js +15 -5
  275. package/dist/platform/tui/protocol.d.ts +355 -0
  276. package/dist/platform/tui/protocol.js +199 -0
  277. package/dist/platform/types.d.ts +12 -3
  278. package/dist/store/execution-repo.d.ts +6 -1
  279. package/dist/store/execution-repo.js +13 -3
  280. package/dist/store/hook-sync.d.ts +18 -0
  281. package/dist/store/hook-sync.js +92 -0
  282. package/dist/store/outbound-queue.js +2 -2
  283. package/dist/store/profile-repo.js +3 -2
  284. package/dist/store/schedule-repo.d.ts +1 -8
  285. package/dist/store/session-registry-repo.d.ts +9 -1
  286. package/dist/store/session-registry-repo.js +19 -3
  287. package/dist/store/session-repo.d.ts +14 -0
  288. package/dist/store/session-repo.js +23 -0
  289. package/dist/store/thread-repo.d.ts +3 -0
  290. package/dist/store/thread-repo.js +49 -2
  291. package/dist/store/version-migrations.js +95 -0
  292. package/dist/tui/App.d.ts +27 -0
  293. package/dist/tui/App.js +219 -0
  294. package/dist/tui/components/AskUserModal.d.ts +11 -0
  295. package/dist/tui/components/AskUserModal.js +364 -0
  296. package/dist/tui/components/ConfirmModal.d.ts +12 -0
  297. package/dist/tui/components/ConfirmModal.js +31 -0
  298. package/dist/tui/components/Dashboard.d.ts +23 -0
  299. package/dist/tui/components/Dashboard.js +80 -0
  300. package/dist/tui/components/DashboardCostTab.d.ts +7 -0
  301. package/dist/tui/components/DashboardCostTab.js +16 -0
  302. package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
  303. package/dist/tui/components/DashboardExecutionsTab.js +94 -0
  304. package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
  305. package/dist/tui/components/DashboardSchedulesTab.js +124 -0
  306. package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
  307. package/dist/tui/components/DashboardTasksTab.js +200 -0
  308. package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
  309. package/dist/tui/components/DashboardThreadsTab.js +81 -0
  310. package/dist/tui/components/Header.d.ts +11 -0
  311. package/dist/tui/components/Header.js +5 -0
  312. package/dist/tui/components/InputBox.d.ts +10 -0
  313. package/dist/tui/components/InputBox.js +19 -0
  314. package/dist/tui/components/MessageRow.d.ts +7 -0
  315. package/dist/tui/components/MessageRow.js +10 -0
  316. package/dist/tui/components/Notifications.d.ts +19 -0
  317. package/dist/tui/components/Notifications.js +72 -0
  318. package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
  319. package/dist/tui/components/PlanFeedbackModal.js +161 -0
  320. package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
  321. package/dist/tui/components/ProjectSwitcher.js +43 -0
  322. package/dist/tui/components/SessionPicker.d.ts +14 -0
  323. package/dist/tui/components/SessionPicker.js +34 -0
  324. package/dist/tui/components/SidePanel.d.ts +19 -0
  325. package/dist/tui/components/SidePanel.js +8 -0
  326. package/dist/tui/components/StatusLine.d.ts +10 -0
  327. package/dist/tui/components/StatusLine.js +29 -0
  328. package/dist/tui/components/Transcript.d.ts +13 -0
  329. package/dist/tui/components/Transcript.js +56 -0
  330. package/dist/tui/hooks/useDashboardData.d.ts +32 -0
  331. package/dist/tui/hooks/useDashboardData.js +104 -0
  332. package/dist/tui/hooks/useKeybindings.d.ts +19 -0
  333. package/dist/tui/hooks/useKeybindings.js +87 -0
  334. package/dist/tui/hooks/useMutate.d.ts +22 -0
  335. package/dist/tui/hooks/useMutate.js +56 -0
  336. package/dist/tui/hooks/useNotifications.d.ts +28 -0
  337. package/dist/tui/hooks/useNotifications.js +70 -0
  338. package/dist/tui/hooks/useTranscript.d.ts +39 -0
  339. package/dist/tui/hooks/useTranscript.js +265 -0
  340. package/dist/tui/hooks/useWsClient.d.ts +29 -0
  341. package/dist/tui/hooks/useWsClient.js +69 -0
  342. package/dist/tui/index.d.ts +2 -0
  343. package/dist/tui/index.js +210 -0
  344. package/dist/tui/logic.d.ts +16 -0
  345. package/dist/tui/logic.js +49 -0
  346. package/dist/tui/render/markdown.d.ts +10 -0
  347. package/dist/tui/render/markdown.js +38 -0
  348. package/dist/tui/render/rich-blocks.d.ts +11 -0
  349. package/dist/tui/render/rich-blocks.js +24 -0
  350. package/dist/tui/ws-client.d.ts +44 -0
  351. package/dist/tui/ws-client.js +157 -0
  352. package/package.json +11 -3
  353. package/dist/orchestration/channel-queue.d.ts +0 -18
  354. package/dist/orchestration/channel-queue.js +0 -32
@@ -5,6 +5,7 @@ import { readFileSync, writeFileSync, existsSync, mkdirSync, watch } from 'fs';
5
5
  import * as path from 'path';
6
6
  import { CONFIG_DIR, DATA_DIR, PROMPTS_DIR } from '../../core/utils.js';
7
7
  import { createLogger } from '../../core/log.js';
8
+ import { Icons } from '../../core/icons.js';
8
9
  import { resolveTemplate } from './template-resolver.js';
9
10
  const log = createLogger('thread-manager');
10
11
  const CONFIG_FILE = path.join(CONFIG_DIR, 'thread-templates.json');
@@ -170,7 +171,7 @@ function scheduleConfigReload() {
170
171
  _reloadTimer = setTimeout(() => {
171
172
  _reloadTimer = null;
172
173
  log.info('Detected change in thread-templates.json, reloading...');
173
- _adminNotifier?.(':arrows_counterclockwise: `thread-templates.json` hot-reloaded');
174
+ _adminNotifier?.(`${Icons.refresh} \`thread-templates.json\` hot-reloaded`);
174
175
  loadConfig();
175
176
  }, 300);
176
177
  }
@@ -205,7 +206,7 @@ function startPromptsWatcher() {
205
206
  _promptsReloadTimer = setTimeout(() => {
206
207
  _promptsReloadTimer = null;
207
208
  log.info(`Detected change in prompts/${rel}/${filename || '?'}, reloading config...`);
208
- _adminNotifier?.(`:arrows_counterclockwise: prompts/\`${rel}/${filename || '?'}\` changed — thread-templates reloaded`);
209
+ _adminNotifier?.(`${Icons.refresh} prompts/\`${rel}/${filename || '?'}\` changed — thread-templates reloaded`);
209
210
  loadConfig();
210
211
  }, 300);
211
212
  });
@@ -0,0 +1,45 @@
1
+ import type { ThreadRecord, ThreadStatus } from '../../core/types/thread-types.js';
2
+ export declare function isTerminalStatus(status: ThreadStatus): boolean;
3
+ /** Tree identity: a thread's root is its metadata.rootThreadId, falling back to itself. */
4
+ export declare function getRootThreadId(t: ThreadRecord): string;
5
+ /** All threads belonging to the tree rooted at rootId (root included). threads.json is
6
+ * fully in-memory and small, so a full scan is fine. */
7
+ export declare function getTreeThreads(rootId: string): ThreadRecord[];
8
+ export interface TreeSummary {
9
+ nodeCount: number;
10
+ totalCostUsd: number;
11
+ byStatus: Record<string, number>;
12
+ }
13
+ export declare function summarizeTree(rootId: string): TreeSummary;
14
+ export type SpawnGuardResult = {
15
+ ok: true;
16
+ } | {
17
+ ok: false;
18
+ reason: string;
19
+ };
20
+ /** Resource guards evaluated before spawning a child thread under `parent`.
21
+ * Three checks: width (children per thread), tree node count, and budget
22
+ * (each ancestor's contract.budgetUsd against its subtree's actual cost,
23
+ * plus a global per-tree cost ceiling). A failed guard should lead the agent
24
+ * to escalate ([ABORT]) or re-plan — not to retry the spawn. */
25
+ export declare function checkSpawnGuards(parent: ThreadRecord | null): SpawnGuardResult;
26
+ /** Record a freshly spawned child on its parent: always into childThreadIds (width/rework
27
+ * counter); into waitingOn only when the parent intends to suspend on it (wait=true). */
28
+ export declare function registerChildSpawn(parentThreadId: string, childThreadId: string, wait: boolean): Promise<void>;
29
+ export interface ThreadTreeNode {
30
+ threadId: string;
31
+ status: ThreadStatus;
32
+ templateName: string | null;
33
+ activeAgent: string | null;
34
+ costUsd: number;
35
+ depth: number;
36
+ createdAt: string;
37
+ children: ThreadTreeNode[];
38
+ /** Present on root nodes only. */
39
+ rollup?: TreeSummary & {
40
+ maxDepth: number;
41
+ };
42
+ }
43
+ /** Group the given threads into nested trees by metadata.parentThreadId.
44
+ * Nodes whose parent is outside the set become roots. Root nodes carry a rollup. */
45
+ export declare function buildThreadTree(threads: ThreadRecord[]): ThreadTreeNode[];
@@ -0,0 +1,171 @@
1
+ // input: threadStore, thread-types
2
+ // output: getRootThreadId / getTreeThreads / summarizeTree / checkSpawnGuards / buildThreadTree
3
+ // pos: Recursive thread-tree infrastructure (DR-0014) — tree identity, resource guards, tree view
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { threadStore } from '../../store/thread-repo.js';
6
+ const TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled', 'aborted']);
7
+ export function isTerminalStatus(status) {
8
+ return TERMINAL_STATUSES.has(status);
9
+ }
10
+ function envInt(name, fallback) {
11
+ const v = parseInt(process.env[name] || '', 10);
12
+ return Number.isFinite(v) && v > 0 ? v : fallback;
13
+ }
14
+ function envFloat(name, fallback) {
15
+ const v = parseFloat(process.env[name] || '');
16
+ return Number.isFinite(v) && v > 0 ? v : fallback;
17
+ }
18
+ /** Tree identity: a thread's root is its metadata.rootThreadId, falling back to itself. */
19
+ export function getRootThreadId(t) {
20
+ return t.metadata?.rootThreadId ?? t.id;
21
+ }
22
+ /** All threads belonging to the tree rooted at rootId (root included). threads.json is
23
+ * fully in-memory and small, so a full scan is fine. */
24
+ export function getTreeThreads(rootId) {
25
+ return threadStore.getAll().filter(t => getRootThreadId(t) === rootId);
26
+ }
27
+ export function summarizeTree(rootId) {
28
+ const threads = getTreeThreads(rootId);
29
+ const byStatus = {};
30
+ let totalCostUsd = 0;
31
+ for (const t of threads) {
32
+ totalCostUsd += t.totalCostUsd || 0;
33
+ byStatus[t.status] = (byStatus[t.status] || 0) + 1;
34
+ }
35
+ return { nodeCount: threads.length, totalCostUsd, byStatus };
36
+ }
37
+ /** Sum of totalCostUsd over `ancestor` and all its transitive descendants within the tree. */
38
+ function subtreeCost(ancestor, treeThreads) {
39
+ const byParent = new Map();
40
+ for (const t of treeThreads) {
41
+ const pid = t.metadata?.parentThreadId;
42
+ if (pid) {
43
+ const arr = byParent.get(pid) || [];
44
+ arr.push(t);
45
+ byParent.set(pid, arr);
46
+ }
47
+ }
48
+ let sum = 0;
49
+ const stack = [ancestor];
50
+ const seen = new Set();
51
+ while (stack.length) {
52
+ const cur = stack.pop();
53
+ if (seen.has(cur.id))
54
+ continue;
55
+ seen.add(cur.id);
56
+ sum += cur.totalCostUsd || 0;
57
+ for (const c of byParent.get(cur.id) || [])
58
+ stack.push(c);
59
+ }
60
+ return sum;
61
+ }
62
+ /** Resource guards evaluated before spawning a child thread under `parent`.
63
+ * Three checks: width (children per thread), tree node count, and budget
64
+ * (each ancestor's contract.budgetUsd against its subtree's actual cost,
65
+ * plus a global per-tree cost ceiling). A failed guard should lead the agent
66
+ * to escalate ([ABORT]) or re-plan — not to retry the spawn. */
67
+ export function checkSpawnGuards(parent) {
68
+ if (!parent)
69
+ return { ok: true };
70
+ const maxChildren = envInt('CORTEX_THREAD_MAX_CHILDREN', 8);
71
+ const childCount = parent.metadata?.childThreadIds?.length ?? 0;
72
+ if (childCount >= maxChildren) {
73
+ return { ok: false, reason: `parent ${parent.id} already spawned ${childCount} children (max ${maxChildren}) — escalate or re-plan instead of spawning more` };
74
+ }
75
+ const rootId = getRootThreadId(parent);
76
+ const treeThreads = getTreeThreads(rootId);
77
+ const maxNodes = envInt('CORTEX_TREE_MAX_NODES', 32);
78
+ if (treeThreads.length >= maxNodes) {
79
+ return { ok: false, reason: `thread tree ${rootId} already has ${treeThreads.length} nodes (max ${maxNodes})` };
80
+ }
81
+ // Budget: walk the ancestor chain from parent upward; any ancestor whose contract
82
+ // budget is exhausted by its subtree's actual cost blocks further growth beneath it.
83
+ const byId = new Map(treeThreads.map(t => [t.id, t]));
84
+ let cursor = parent;
85
+ const visited = new Set();
86
+ while (cursor && !visited.has(cursor.id)) {
87
+ visited.add(cursor.id);
88
+ const budget = cursor.metadata?.contract?.budgetUsd;
89
+ if (budget != null) {
90
+ const spent = subtreeCost(cursor, treeThreads);
91
+ if (spent >= budget) {
92
+ return { ok: false, reason: `budget exhausted: subtree of ${cursor.id} spent $${spent.toFixed(2)} of $${budget.toFixed(2)} budget` };
93
+ }
94
+ }
95
+ const pid = cursor.metadata?.parentThreadId;
96
+ cursor = pid ? (byId.get(pid) ?? threadStore.get(pid)) : null;
97
+ }
98
+ const maxTreeCost = envFloat('CORTEX_TREE_MAX_COST_USD', 50);
99
+ const treeCost = treeThreads.reduce((s, t) => s + (t.totalCostUsd || 0), 0);
100
+ if (treeCost >= maxTreeCost) {
101
+ return { ok: false, reason: `tree cost limit hit: tree ${rootId} spent $${treeCost.toFixed(2)} (max $${maxTreeCost.toFixed(2)})` };
102
+ }
103
+ return { ok: true };
104
+ }
105
+ /** Record a freshly spawned child on its parent: always into childThreadIds (width/rework
106
+ * counter); into waitingOn only when the parent intends to suspend on it (wait=true). */
107
+ export async function registerChildSpawn(parentThreadId, childThreadId, wait) {
108
+ await threadStore.mutate(parentThreadId, (t) => {
109
+ const m = (t.metadata ??= {});
110
+ (m.childThreadIds ??= []).push(childThreadId);
111
+ if (wait)
112
+ (m.waitingOn ??= []).push(childThreadId);
113
+ });
114
+ }
115
+ /** Group the given threads into nested trees by metadata.parentThreadId.
116
+ * Nodes whose parent is outside the set become roots. Root nodes carry a rollup. */
117
+ export function buildThreadTree(threads) {
118
+ const byId = new Map(threads.map(t => [t.id, t]));
119
+ const childrenOf = new Map();
120
+ const roots = [];
121
+ for (const t of threads) {
122
+ const pid = t.metadata?.parentThreadId;
123
+ if (pid && byId.has(pid)) {
124
+ const arr = childrenOf.get(pid) || [];
125
+ arr.push(t);
126
+ childrenOf.set(pid, arr);
127
+ }
128
+ else {
129
+ roots.push(t);
130
+ }
131
+ }
132
+ function toNode(t, depth) {
133
+ const kids = (childrenOf.get(t.id) || [])
134
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
135
+ .map(c => toNode(c, depth + 1));
136
+ return {
137
+ threadId: t.id,
138
+ status: t.status,
139
+ templateName: t.templateName,
140
+ activeAgent: t.activeAgent || null,
141
+ costUsd: t.totalCostUsd || 0,
142
+ depth,
143
+ createdAt: t.createdAt,
144
+ children: kids,
145
+ };
146
+ }
147
+ function collectRollup(node) {
148
+ let nodeCount = 0;
149
+ let totalCostUsd = 0;
150
+ let maxDepth = 0;
151
+ const byStatus = {};
152
+ const stack = [node];
153
+ while (stack.length) {
154
+ const cur = stack.pop();
155
+ nodeCount++;
156
+ totalCostUsd += cur.costUsd;
157
+ maxDepth = Math.max(maxDepth, cur.depth);
158
+ byStatus[cur.status] = (byStatus[cur.status] || 0) + 1;
159
+ for (const c of cur.children)
160
+ stack.push(c);
161
+ }
162
+ return { nodeCount, totalCostUsd, byStatus, maxDepth };
163
+ }
164
+ return roots
165
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
166
+ .map(r => {
167
+ const node = toNode(r, 0);
168
+ node.rollup = collectRollup(node);
169
+ return node;
170
+ });
171
+ }
@@ -0,0 +1,2 @@
1
+ export { createTuiSessionService } from './tui-session-service.js';
2
+ export type { TuiSessionService, TuiSessionDeps, HandshakeResolution, SwitchResolution } from './types.js';
@@ -0,0 +1,3 @@
1
+ // input: tui-session module
2
+ // output: barrel for tui-session — TuiSessionService, createTuiSessionService, types
3
+ export { createTuiSessionService } from './tui-session-service.js';
@@ -0,0 +1,2 @@
1
+ import type { TuiSessionDeps, TuiSessionService } from './types.js';
2
+ export declare function createTuiSessionService(deps: TuiSessionDeps): TuiSessionService;
@@ -0,0 +1,103 @@
1
+ // input: TuiSessionDeps
2
+ // output: createTuiSessionService(deps): TuiSessionService — transport-agnostic TUI session lifecycle
3
+ // pos: owns session handshake/resume/switch logic formerly in tui-gateway.ts
4
+ import * as crypto from 'node:crypto';
5
+ import { registerNamedSession } from '../sessions/session-lifecycle.js';
6
+ // ── Internal helpers ─────────────────────────────────────────────
7
+ async function createFresh(deps, conduitId, projectId) {
8
+ const sessionId = crypto.randomUUID();
9
+ const sessionName = await registerNamedSession(deps.sessionStore, {
10
+ sessionId,
11
+ channel: conduitId,
12
+ backend: 'tui',
13
+ projectId,
14
+ });
15
+ await deps.conversationLedger.initConversation(conduitId, {
16
+ sessionId,
17
+ sessionName,
18
+ backend: 'tui',
19
+ });
20
+ return { sessionId, sessionName, projectId, isFresh: true, transcript: null };
21
+ }
22
+ async function assembleTranscript(deps, sessionId) {
23
+ const sessionName = await deps.sessionStore.lookupBySessionId(sessionId);
24
+ if (!sessionName)
25
+ return null;
26
+ const session = await deps.sessionStore.getById(sessionId);
27
+ if (!session)
28
+ return null;
29
+ const channel = session.channel;
30
+ const conv = await deps.conversationLedger.getConversation(channel);
31
+ if (!conv || conv.turns.length === 0)
32
+ return null;
33
+ const turns = conv.turns.map((turn) => ({
34
+ userMessageTs: turn.userMessageTs,
35
+ userMessageText: turn.userMessageText,
36
+ responseMessageTimestamps: turn.responseMessageTimestamps,
37
+ status: turn.status,
38
+ }));
39
+ return { sessionId, channel, turns };
40
+ }
41
+ // ── Factory ──────────────────────────────────────────────────────
42
+ export function createTuiSessionService(deps) {
43
+ return {
44
+ async resolveHandshake({ conduitId, projectId, resumeSessionId }) {
45
+ if (resumeSessionId) {
46
+ const sessionName = await deps.sessionStore.lookupBySessionId(resumeSessionId);
47
+ if (sessionName) {
48
+ // Session found — attach with replay
49
+ const session = await deps.sessionStore.getById(resumeSessionId);
50
+ const activeProjectId = session?.projectId ?? projectId;
51
+ const transcript = await assembleTranscript(deps, resumeSessionId);
52
+ return {
53
+ sessionId: resumeSessionId,
54
+ sessionName,
55
+ projectId: activeProjectId,
56
+ isFresh: false,
57
+ emitNotFoundError: false,
58
+ transcript,
59
+ };
60
+ }
61
+ else {
62
+ // Session not found — fresh fallback with error
63
+ const fresh = await createFresh(deps, conduitId, projectId);
64
+ return { ...fresh, emitNotFoundError: true };
65
+ }
66
+ }
67
+ // Fresh session
68
+ const fresh = await createFresh(deps, conduitId, projectId);
69
+ return { ...fresh, emitNotFoundError: false };
70
+ },
71
+ async switchSession({ conduitId, projectId, sessionId }) {
72
+ if (sessionId) {
73
+ const sessionName = await deps.sessionStore.lookupBySessionId(sessionId);
74
+ const session = await deps.sessionStore.getById(sessionId);
75
+ const resolvedProjectId = session?.projectId ?? projectId;
76
+ if (sessionName) {
77
+ // Attach to existing session — switch clears turns before assemble
78
+ await deps.conversationLedger.switchSession(conduitId, {
79
+ sessionId,
80
+ sessionName,
81
+ backend: 'tui',
82
+ });
83
+ const transcript = await assembleTranscript(deps, sessionId);
84
+ return {
85
+ sessionId,
86
+ sessionName,
87
+ projectId: resolvedProjectId,
88
+ isFresh: false,
89
+ transcript,
90
+ };
91
+ }
92
+ else {
93
+ // Session not found — create fresh (uses incoming projectId, not resolvedProjectId)
94
+ const fresh = await createFresh(deps, conduitId, projectId);
95
+ return { ...fresh };
96
+ }
97
+ }
98
+ // No sessionId — fresh
99
+ const fresh = await createFresh(deps, conduitId, projectId);
100
+ return { ...fresh };
101
+ },
102
+ };
103
+ }
@@ -0,0 +1,67 @@
1
+ import type { TranscriptData } from '../../platform/adapters/tui/ports.js';
2
+ export interface HandshakeResolution {
3
+ sessionId: string;
4
+ sessionName: string;
5
+ projectId: string;
6
+ isFresh: boolean;
7
+ emitNotFoundError: boolean;
8
+ transcript: TranscriptData | null;
9
+ }
10
+ export interface SwitchResolution {
11
+ sessionId: string;
12
+ sessionName: string;
13
+ projectId: string;
14
+ isFresh: boolean;
15
+ transcript: TranscriptData | null;
16
+ }
17
+ export interface TuiSessionService {
18
+ resolveHandshake(opts: {
19
+ conduitId: string;
20
+ projectId: string;
21
+ resumeSessionId?: string | null;
22
+ }): Promise<HandshakeResolution>;
23
+ switchSession(opts: {
24
+ conduitId: string;
25
+ projectId: string;
26
+ sessionId?: string | null;
27
+ }): Promise<SwitchResolution>;
28
+ }
29
+ export interface TuiSessionDeps {
30
+ sessionStore: {
31
+ lookupBySessionId(id: string): Promise<string | null>;
32
+ getById(id: string): Promise<{
33
+ channel: string;
34
+ projectId: string;
35
+ } | null>;
36
+ generateSessionName(): Promise<string>;
37
+ registerSession(name: string, opts: {
38
+ sessionId: string;
39
+ channel: string;
40
+ backend: string;
41
+ kind: 'local' | 'scheduled';
42
+ projectId: string;
43
+ label?: string | null;
44
+ profileName?: string | null;
45
+ }): Promise<void>;
46
+ };
47
+ conversationLedger: {
48
+ initConversation(channel: string, opts: {
49
+ sessionId: string;
50
+ sessionName: string;
51
+ backend: string;
52
+ }): Promise<unknown>;
53
+ switchSession(channel: string, opts: {
54
+ sessionId: string;
55
+ sessionName: string;
56
+ backend: string;
57
+ }): Promise<unknown>;
58
+ getConversation(channel: string): Promise<{
59
+ turns: Array<{
60
+ userMessageTs: string;
61
+ userMessageText: string;
62
+ responseMessageTimestamps: string[];
63
+ status: 'processing' | 'completed' | 'superseded';
64
+ }>;
65
+ } | null>;
66
+ };
67
+ }
@@ -0,0 +1,4 @@
1
+ // input: nothing (leaf module)
2
+ // output: TuiSessionDeps, TuiSessionService, HandshakeResolution, SwitchResolution
3
+ // pos: leaf types module, depends only on @platform/adapters/tui/ports.js (TranscriptData)
4
+ export {};
@@ -0,0 +1,5 @@
1
+ export { createUiService } from './ui-service.js';
2
+ export type { UiService, UiServiceDeps } from './types.js';
3
+ export type { QueryScope, MutateOp, SubscribeFilter, UiEvent } from './types.js';
4
+ export type { Result, Ok, Err } from './types.js';
5
+ export type { ProjectConduitInfo, SessionInfo, ThreadInfo, TaskInfo, ScheduleInfo, ExecutionInfo, } from './types.js';
@@ -0,0 +1,3 @@
1
+ // input: ui-service module
2
+ // output: barrel for ui-service — UiService, createUiService, types
3
+ export { createUiService } from './ui-service.js';
@@ -0,0 +1,4 @@
1
+ import type { UiServiceDeps, Result, ExecutionsCancelReturn } from '../types.js';
2
+ export declare function handleCancelExecution(deps: UiServiceDeps, args: {
3
+ executionId: string;
4
+ }): Promise<Result<ExecutionsCancelReturn>>;
@@ -0,0 +1,15 @@
1
+ // input: UiServiceDeps + { executionId }
2
+ // output: cancelExecution handler → Ok<{cancelled:boolean}> | Err
3
+ // pos: mutate handler for 'executions.cancel'
4
+ export async function handleCancelExecution(deps, args) {
5
+ try {
6
+ const record = deps.executionRegistry.cancelExecution(args.executionId);
7
+ if (!record) {
8
+ return { ok: false, code: 'not-found', message: `Execution not found: ${args.executionId}` };
9
+ }
10
+ return { ok: true, data: { cancelled: true } };
11
+ }
12
+ catch (err) {
13
+ return { ok: false, code: 'internal', message: err?.message || String(err) };
14
+ }
15
+ }
@@ -0,0 +1,10 @@
1
+ import type { UiServiceDeps, Result } from '../types.js';
2
+ export declare function handlePauseSchedule(deps: UiServiceDeps, args: {
3
+ scheduleId: string;
4
+ }): Promise<Result<void>>;
5
+ export declare function handleResumeSchedule(deps: UiServiceDeps, args: {
6
+ scheduleId: string;
7
+ }): Promise<Result<void>>;
8
+ export declare function handleRemoveSchedule(deps: UiServiceDeps, args: {
9
+ scheduleId: string;
10
+ }): Promise<Result<void>>;
@@ -0,0 +1,39 @@
1
+ // input: UiServiceDeps + { scheduleId }
2
+ // output: pause/resume/remove schedule handlers → Ok<void> | Err
3
+ // pos: mutate handlers for 'schedules.{pause,resume,remove}'
4
+ export async function handlePauseSchedule(deps, args) {
5
+ try {
6
+ const updated = await deps.scheduler.pause(args.scheduleId);
7
+ if (!updated) {
8
+ return { ok: false, code: 'not-found', message: `Schedule not found: ${args.scheduleId}` };
9
+ }
10
+ return { ok: true, data: undefined };
11
+ }
12
+ catch (err) {
13
+ return { ok: false, code: 'internal', message: err?.message || String(err) };
14
+ }
15
+ }
16
+ export async function handleResumeSchedule(deps, args) {
17
+ try {
18
+ const updated = await deps.scheduler.resume(args.scheduleId);
19
+ if (!updated) {
20
+ return { ok: false, code: 'not-found', message: `Schedule not found: ${args.scheduleId}` };
21
+ }
22
+ return { ok: true, data: undefined };
23
+ }
24
+ catch (err) {
25
+ return { ok: false, code: 'internal', message: err?.message || String(err) };
26
+ }
27
+ }
28
+ export async function handleRemoveSchedule(deps, args) {
29
+ try {
30
+ const removed = await deps.scheduler.remove(args.scheduleId);
31
+ if (!removed) {
32
+ return { ok: false, code: 'not-found', message: `Schedule not found: ${args.scheduleId}` };
33
+ }
34
+ return { ok: true, data: undefined };
35
+ }
36
+ catch (err) {
37
+ return { ok: false, code: 'internal', message: err?.message || String(err) };
38
+ }
39
+ }
@@ -0,0 +1,23 @@
1
+ import type { UiServiceDeps, Result } from '../types.js';
2
+ export declare function handleClaimTask(deps: UiServiceDeps, args: {
3
+ projectId: string;
4
+ taskId: string;
5
+ }): Promise<Result<void>>;
6
+ export declare function handleUnclaimTask(deps: UiServiceDeps, args: {
7
+ projectId: string;
8
+ taskId: string;
9
+ }): Promise<Result<void>>;
10
+ export declare function handleCompleteTask(deps: UiServiceDeps, args: {
11
+ projectId: string;
12
+ taskId: string;
13
+ note?: string;
14
+ }): Promise<Result<void>>;
15
+ export declare function handleBlockTask(deps: UiServiceDeps, args: {
16
+ projectId: string;
17
+ taskId: string;
18
+ reason: string;
19
+ }): Promise<Result<void>>;
20
+ export declare function handleUnblockTask(deps: UiServiceDeps, args: {
21
+ projectId: string;
22
+ taskId: string;
23
+ }): Promise<Result<void>>;
@@ -0,0 +1,59 @@
1
+ // input: UiServiceDeps + task action args
2
+ // output: claim/unclaim/complete/block/unblock handlers → Ok<void> | Err
3
+ // pos: mutate handlers for 'tasks.{claim,unclaim,complete,block,unblock}'
4
+ import { taskMutator } from '../../tasks/mutator.js';
5
+ import { acquireLock, releaseLock, getOwnerIdentity } from '../../tasks/system/task-lock.js';
6
+ async function withTaskLock(deps, projectId, fn) {
7
+ const owner = getOwnerIdentity();
8
+ const acq = acquireLock(projectId, { owner });
9
+ if (!acq.acquired) {
10
+ return { ok: false, code: 'task-lock-busy', message: acq.message || 'Task lock is busy' };
11
+ }
12
+ try {
13
+ const result = await fn();
14
+ return { ok: true, data: result };
15
+ }
16
+ finally {
17
+ releaseLock(projectId, owner);
18
+ }
19
+ }
20
+ export async function handleClaimTask(deps, args) {
21
+ return withTaskLock(deps, args.projectId, async () => {
22
+ const result = await taskMutator.claim(args.taskId, getOwnerIdentity());
23
+ if (!result.success) {
24
+ throw new Error(result.message || 'Claim failed');
25
+ }
26
+ });
27
+ }
28
+ export async function handleUnclaimTask(deps, args) {
29
+ return withTaskLock(deps, args.projectId, async () => {
30
+ const result = await taskMutator.unclaim(args.taskId);
31
+ if (!result.success) {
32
+ throw new Error(result.message || 'Unclaim failed');
33
+ }
34
+ });
35
+ }
36
+ export async function handleCompleteTask(deps, args) {
37
+ return withTaskLock(deps, args.projectId, async () => {
38
+ const result = await taskMutator.complete(args.taskId, args.note);
39
+ if (!result.success) {
40
+ throw new Error(result.message || 'Complete failed');
41
+ }
42
+ });
43
+ }
44
+ export async function handleBlockTask(deps, args) {
45
+ return withTaskLock(deps, args.projectId, async () => {
46
+ const result = await taskMutator.block(args.taskId, args.reason);
47
+ if (!result.success) {
48
+ throw new Error(result.message || 'Block failed');
49
+ }
50
+ });
51
+ }
52
+ export async function handleUnblockTask(deps, args) {
53
+ return withTaskLock(deps, args.projectId, async () => {
54
+ const result = await taskMutator.unblock(args.taskId);
55
+ if (!result.success) {
56
+ throw new Error(result.message || 'Unblock failed');
57
+ }
58
+ });
59
+ }
@@ -0,0 +1,4 @@
1
+ import type { UiServiceDeps, Result, ThreadsCancelReturn } from '../types.js';
2
+ export declare function handleCancelThread(deps: UiServiceDeps, args: {
3
+ threadId: string;
4
+ }): Promise<Result<ThreadsCancelReturn>>;
@@ -0,0 +1,21 @@
1
+ // input: UiServiceDeps + { threadId }
2
+ // output: cancelThread handler → Ok<{cancelled:boolean}> | Err
3
+ // pos: mutate handler for 'threads.cancel'
4
+ import { cancelThread } from '../../threads/index.js';
5
+ export async function handleCancelThread(deps, args) {
6
+ try {
7
+ const cancelled = await cancelThread(args.threadId);
8
+ if (!cancelled) {
9
+ // thread not found or already terminal
10
+ const thread = deps.threadStore.get(args.threadId);
11
+ if (!thread) {
12
+ return { ok: false, code: 'not-found', message: `Thread not found: ${args.threadId}` };
13
+ }
14
+ return { ok: false, code: 'already-terminal', message: `Thread ${args.threadId} is already in terminal state` };
15
+ }
16
+ return { ok: true, data: { cancelled: true } };
17
+ }
18
+ catch (err) {
19
+ return { ok: false, code: 'internal', message: err?.message || String(err) };
20
+ }
21
+ }
@@ -0,0 +1,3 @@
1
+ import type { UiServiceDeps, CostSummaryParams } from '../types.js';
2
+ import type { CostSummary } from '../../costs/cost-tracker.js';
3
+ export declare function handleCostSummary(deps: UiServiceDeps, params: CostSummaryParams): Promise<CostSummary>;
@@ -0,0 +1,6 @@
1
+ // input: UiServiceDeps + CostSummaryParams
2
+ // output: handleCostSummary → CostSummary
3
+ // pos: query handler for 'cost.summary'
4
+ export async function handleCostSummary(deps, params) {
5
+ return deps.costSummary(params.projectId ?? null);
6
+ }
@@ -0,0 +1,2 @@
1
+ import type { UiServiceDeps, ExecutionInfo, ExecutionsListParams } from '../types.js';
2
+ export declare function handleExecutionsList(deps: UiServiceDeps, params: ExecutionsListParams): Promise<ExecutionInfo[]>;