@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
@@ -1,10 +1,11 @@
1
1
  // input: domain/threads, mode-manager, hook-runner, handles
2
- // output: runThread / continueThread / buildThreadSummary
2
+ // output: runThread / continueThread / resumeThread / buildThreadSummary
3
3
  // pos: runtime execution engine for the Thread system
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { threadStore } from '../../store/thread-repo.js';
6
- import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions, completeThread, failThread, abortThread, detectAbortMarker, isDefaultThread, isAdHocThread, getSessionKey, getTemplate, readArtifact, resolveSystemVars, } from './index.js';
6
+ import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions, completeThread, failThread, abortThread, detectAbortMarker, detectWaitMarker, tryEnterWaiting, checkContractBudget, isAdHocThread, getSessionKey, getTemplate, readArtifact, resolveSystemVars, } from './index.js';
7
7
  import { runAgent, getClaudeMode, getActiveBackend, getActiveProfile } from '../agents/index.js';
8
+ import { Icons } from '../../core/icons.js';
8
9
  import { closeSessionsByPrefix } from '../agents/index.js';
9
10
  import * as executionRegistry from '../executions/registry.js';
10
11
  import { sessionStore } from '../../store/session-registry-repo.js';
@@ -22,13 +23,13 @@ function initThreadContext(threadId, opts) {
22
23
  const thread = threadStore.get(threadId);
23
24
  if (!thread)
24
25
  throw new Error(`Thread not found: ${threadId}`);
25
- const isDefault = isDefaultThread(threadId);
26
26
  const template = thread.templateName ? (getTemplate(thread.templateName) || null) : null;
27
- // For all non-default threads, aggregate output into an OutputStream.
28
- // Default template passes through opts.onAssistantMessage from app.ts (backward compat).
29
- // The caller supplies the Destination (interactive-reply or project-report).
30
- const stream = !isDefault ? opts.adapter.openOutputStream(opts.destination, { threadId: opts.threadTs }) : null;
31
- return { thread, isDefault, template, meta: thread.metadata, stream, lastAgentResult: null, totalNumTurns: 0 };
27
+ // Aggregate agent output into an OutputStream. The caller supplies the Destination
28
+ // (interactive-reply or project-report).
29
+ // Pass the full statusMsg as anchorRef so CompositeAdapter can resolve a per-platform
30
+ // thread anchor for each sub-stream (a Slack ts must not be used as a Feishu message_id).
31
+ const stream = opts.adapter.openOutputStream(opts.destination, { threadId: opts.threadAnchorId, anchorRef: opts.statusMsg });
32
+ return { thread, template, meta: thread.metadata, stream, lastAgentResult: null, totalNumTurns: 0 };
32
33
  }
33
34
  /** Resolve next step, post boundary notifications, update the status message.
34
35
  * Returns null if the loop should break (cancelled, no next step). */
@@ -51,12 +52,12 @@ async function resolveAndNotifyStep(threadId, ctx, opts) {
51
52
  if (ctx.stream && multiAgent && !isFirstStep) {
52
53
  const prevStep = threadRecord.steps[threadRecord.steps.length - 1];
53
54
  const prevLabel = prevStep ? formatAgentStageLabel(prevStep.agentSlotId, prevStep.stage) : '?';
54
- ctx.stream.emitText(`:arrow_right: Step ${threadRecord.currentStepIndex + 1}: *${label}* starting (prev: ${prevLabel})`);
55
+ ctx.stream.emitText(`${Icons.arrowRight} Step ${threadRecord.currentStepIndex + 1}: *${label}* starting (prev: ${prevLabel})`);
55
56
  }
56
57
  // Update status message (multi-agent thread format; skip if caller provides onProgress)
57
58
  if (ctx.stream && multiAgent && !opts.onProgress) {
58
59
  const elapsed = (Date.now() - opts.startTime) / 1000;
59
- const statusText = `:hourglass_flowing_sand: Thread ${threadRecord.id.substring(0, 12)} | Step ${threadRecord.currentStepIndex + 1}: *${label}* | :stopwatch: ${formatDurationCompact(elapsed)}`;
60
+ const statusText = `${Icons.processing} Thread ${threadRecord.id.substring(0, 12)} | Step ${threadRecord.currentStepIndex + 1}: *${label}* | ${Icons.stopwatch} ${formatDurationCompact(elapsed)}`;
60
61
  try {
61
62
  if (opts.statusMsg) {
62
63
  await opts.adapter.updateMessage(opts.statusMsg, { text: statusText });
@@ -73,20 +74,10 @@ async function buildStepConfig(threadId, stepInfo, ctx, opts) {
73
74
  const slot = threadStore.get(threadId).agents[agentSlotId];
74
75
  // Build prompt for this step — pass the stage so stage-aware agents send their stage-specific
75
76
  // prompt (and, in incremental mode on session resume, skip directive + preamble + auto previousOutput).
76
- const prompt = buildStepPrompt(threadId, agentConfig, stage, opts.isUserInitiated);
77
- // Determine session configuration
78
- let sessionId = null;
79
- let sessionKey = null;
80
- if (ctx.isDefault) {
81
- // Default template: use existing channel session (backward compatible)
82
- sessionId = opts.existingSessionId;
83
- sessionKey = null; // falls back to channel key in claude-bridge
84
- }
85
- else {
86
- // Multi-agent: use thread-specific session key
87
- sessionKey = getSessionKey(threadId, agentSlotId);
88
- sessionId = slot.persistSession ? slot.sessionId : null;
89
- }
77
+ const prompt = buildStepPrompt(threadId, agentConfig, stage);
78
+ // Determine session configuration — thread steps use a thread-scoped session key.
79
+ const sessionKey = getSessionKey(threadId, agentSlotId);
80
+ const sessionId = slot.persistSession ? slot.sessionId : null;
90
81
  // Resolve profile: agents with a hardcoded profile always use their own declaration.
91
82
  // metadata.profileOverride only applies to __active__ agents (default/main/scheduler-main),
92
83
  // letting scheduler/dispatch inject a concrete profile without overriding research-pipeline agents.
@@ -97,7 +88,7 @@ async function buildStepConfig(threadId, stepInfo, ctx, opts) {
97
88
  const executionKind = ctx.meta?.trigger === 'task-dispatch' ? 'dispatch'
98
89
  : ctx.meta?.trigger === 'scheduled' ? 'scheduled'
99
90
  : 'local';
100
- const executionTrigger = ctx.meta?.trigger || (ctx.isDefault ? 'user' : 'thread-step');
91
+ const executionTrigger = ctx.meta?.trigger || 'thread-step';
101
92
  const label = formatAgentStageLabel(agentSlotId, stage);
102
93
  const execution = executionRegistry.startLocalExecution({
103
94
  kind: executionKind,
@@ -107,7 +98,7 @@ async function buildStepConfig(threadId, stepInfo, ctx, opts) {
107
98
  backend: getActiveBackend(),
108
99
  billingMode: getClaudeMode(),
109
100
  sessionId,
110
- label: ctx.isDefault ? prompt.substring(0, 60) : `[${label}] ${prompt.substring(0, 40)}`,
101
+ label: `[${label}] ${prompt.substring(0, 40)}`,
111
102
  scheduleTaskId: ctx.meta?.scheduleTaskId || null,
112
103
  threadId,
113
104
  agentSlotId,
@@ -115,7 +106,7 @@ async function buildStepConfig(threadId, stepInfo, ctx, opts) {
115
106
  return {
116
107
  agentSlotId, agentConfig, isFirstStep, multiAgent, stage,
117
108
  prompt, sessionId, sessionKey,
118
- sessionName: (ctx.isDefault && opts.sessionName) ? opts.sessionName : await sessionStore.generateSessionName(),
109
+ sessionName: await sessionStore.generateSessionName(),
119
110
  profileName, execution,
120
111
  stepStartTime: new Date().toISOString(),
121
112
  };
@@ -128,18 +119,14 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
128
119
  const slot = threadRecord.agents[agentSlotId];
129
120
  const stream = ctx.stream;
130
121
  const label = formatAgentStageLabel(agentSlotId, stage);
131
- // Determine callbacks:
132
- // - default: pass through from opts (app.ts OutputStream)
133
- // - non-default: aggregate into thread-runner's stream; prefix only for multi-agent
122
+ // Aggregate assistant output into the thread-runner's OutputStream; prefix only for multi-agent.
134
123
  const slotPrefix = multiAgent ? `*[${label}]*` : null;
135
- const baseAssistantMessage = stream
136
- ? (text) => { stream.emitText(slotPrefix ? `${slotPrefix} ${text}` : text); }
137
- : opts.onAssistantMessage;
138
- // Tool trace (env-gated): caller-supplied onToolUse takes precedence (default-thread path —
139
- // agent-runner owns the stream). Otherwise build one bound to the runner's own stream.
124
+ const baseAssistantMessage = (text) => { stream.emitText(slotPrefix ? `${slotPrefix} ${text}` : text); };
125
+ // Tool trace (env-gated): caller-supplied onToolUse takes precedence. Otherwise build one bound
126
+ // to the runner's own stream.
140
127
  const callerOnToolUse = opts.onToolUse ?? null;
141
128
  const toolTrace = callerOnToolUse ? null : createToolTrace(stream, { slotPrefix });
142
- const onAssistantMessage = toolTrace && baseAssistantMessage
129
+ const onAssistantMessage = toolTrace
143
130
  ? (text) => { toolTrace.flush(); baseAssistantMessage(text); }
144
131
  : baseAssistantMessage;
145
132
  const onToolUse = callerOnToolUse
@@ -147,12 +134,12 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
147
134
  // onProgress: caller override (e.g. scheduler's buildUserProcessingMessage) takes precedence;
148
135
  // fallback to thread-specific status format for multi-agent pipelines
149
136
  const onProgress = opts.onProgress
150
- || (stream && multiAgent
137
+ || (multiAgent
151
138
  ? (progress) => {
152
139
  const elapsed = (Date.now() - opts.startTime) / 1000;
153
140
  if (opts.statusMsg) {
154
141
  opts.adapter.updateMessage(opts.statusMsg, {
155
- text: `:hourglass_flowing_sand: Thread ${threadRecord.id.substring(0, 12)} | Step ${threadRecord.currentStepIndex + 1}: *${label}* (${progress?.num_turns || '?'} turns) | :stopwatch: ${formatDurationCompact(elapsed)}`,
142
+ text: `${Icons.processing} Thread ${threadRecord.id.substring(0, 12)} | Step ${threadRecord.currentStepIndex + 1}: *${label}* (${progress?.num_turns || '?'} turns) | ${Icons.stopwatch} ${formatDurationCompact(elapsed)}`,
156
143
  }).catch(() => { });
157
144
  }
158
145
  }
@@ -177,15 +164,16 @@ async function executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts) {
177
164
  project: threadStore.get(threadId)?.projectId,
178
165
  trigger: meta?.trigger || undefined,
179
166
  threadId,
180
- useCoreMcp: !ctx.isDefault,
167
+ threadDepth: meta?.depth ?? 0,
168
+ useCoreMcp: true,
181
169
  sessionName: stepCtx.sessionName,
182
170
  claudeAgent: agentConfig.claudeAgent || null,
183
171
  systemPrompt: agentConfig.systemPrompt ? resolveSystemVars(agentConfig.systemPrompt) : null,
184
172
  outputStyle: agentConfig.outputStyle || null,
185
173
  tools: agentConfig.tools || null,
186
174
  pluginDirs: agentConfig.pluginDirs || null,
187
- onFallback: ctx.isDefault ? opts.onFallback : null,
188
- isUserInitiated: ctx.isDefault ? (opts.isUserInitiated || false) : false,
175
+ onFallback: null,
176
+ isUserInitiated: false,
189
177
  onAssistantMessage: callbacks.onAssistantMessage,
190
178
  onProgress: callbacks.onProgress,
191
179
  onToolUse: callbacks.onToolUse,
@@ -193,31 +181,34 @@ async function executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts) {
193
181
  onAskUserQuestion: opts.onAskUserQuestion ?? null,
194
182
  });
195
183
  // Track handle for cancellation
196
- runningExecutions.register(opts.channel, {
184
+ runningExecutions.register({
197
185
  threadId,
198
186
  channel: opts.channel,
199
187
  agentSlotId: stepCtx.agentSlotId,
200
188
  executionId: stepCtx.execution.id,
189
+ kind: stepCtx.execution.kind,
201
190
  kill: () => handle.kill(),
202
191
  backend: getActiveBackend(),
203
192
  agentProcess: handle.agentProcess,
204
193
  sessionId: handle.sessionId,
205
194
  });
206
195
  try {
196
+ // On success the registry entry stays live until recordStepOutcome tears it down
197
+ // (so the agent.completed event fires there). On error we tear down here.
207
198
  return await handle.promise;
208
199
  }
209
200
  catch (agentError) {
210
- // Finalize execution as failed so it doesn't stay stuck in 'running'
201
+ // Finalize execution as failed (persistent record + registry + agent.failed event)
202
+ // so it doesn't stay stuck in 'running' and the dashboards see a balanced lifecycle.
211
203
  const failDurationS = (Date.now() - new Date(stepStartTime).getTime()) / 1000;
212
- executionRegistry.failExecution(execution.id, {
204
+ executionRegistry.teardownExecution({
205
+ executionId: execution.id,
206
+ status: 'failed',
213
207
  durationS: failDurationS,
214
- error: agentError?.message || 'Agent process error',
208
+ error: { message: agentError?.message || 'Agent process error' },
215
209
  });
216
210
  throw agentError;
217
211
  }
218
- finally {
219
- runningExecutions.remove(opts.channel);
220
- }
221
212
  }
222
213
  /** Record step result, register session, finalize execution; update aggregate counters. */
223
214
  async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
@@ -252,28 +243,22 @@ async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
252
243
  projectId: currentThread.projectId,
253
244
  });
254
245
  }
255
- // Finalize execution
246
+ // Finalize execution: persistent record + registry teardown + balanced agent.* event.
256
247
  if (result?.rateLimited) {
257
- executionRegistry.failExecution(execution.id, {
258
- durationS: stepDurationS,
259
- error: 'Rate limited',
248
+ executionRegistry.teardownExecution({
249
+ executionId: execution.id, status: 'failed', durationS: stepDurationS,
250
+ error: { message: 'Rate limited' },
260
251
  });
261
252
  }
262
253
  else {
263
- executionRegistry.completeExecution(execution.id, {
264
- costUsd: result?.total_cost_usd,
265
- numTurns: result?.num_turns,
266
- durationS: stepDurationS,
267
- finalOutput: result?.finalOutput || null,
254
+ executionRegistry.teardownExecution({
255
+ executionId: execution.id, status: 'completed', durationS: stepDurationS, result,
268
256
  });
269
257
  }
270
258
  }
271
259
  /** Decide whether the loop continues; run onTransition hook when transitioning.
272
260
  * Returns false to break the loop. */
273
261
  async function evaluateAndTransition(threadId, stepCtx, ctx, opts) {
274
- // For default template, we only run one step
275
- if (ctx.isDefault)
276
- return false;
277
262
  // Ad-hoc threads: run one agent per invocation, then stop
278
263
  if (isAdHocThread(threadId))
279
264
  return false;
@@ -308,20 +293,18 @@ async function finalizeThread(threadId, ctx) {
308
293
  finalOutput,
309
294
  totalCostUsd: finalThread.totalCostUsd,
310
295
  totalNumTurns: ctx.totalNumTurns,
311
- isDefault: ctx.isDefault,
312
296
  lastAgentResult: ctx.lastAgentResult,
313
297
  executionId: finalThread.steps[finalThread.steps.length - 1]?.executionId ?? null,
314
298
  };
315
299
  }
316
300
  async function runThread(threadId, opts) {
317
301
  const ctx = initThreadContext(threadId, opts);
302
+ let enteredWaiting = false;
318
303
  try {
319
304
  // --- onStart hook (before first step) ---
320
305
  // Template hook first, then per-call extraHooks (see note at onTransition).
321
- if (!ctx.isDefault) {
322
- await executeLifecycleHook(threadId, 'start', ctx.template?.hooks?.onStart, opts);
323
- await executeLifecycleHook(threadId, 'start', opts.extraHooks?.onStart, opts);
324
- }
306
+ await executeLifecycleHook(threadId, 'start', ctx.template?.hooks?.onStart, opts);
307
+ await executeLifecycleHook(threadId, 'start', opts.extraHooks?.onStart, opts);
325
308
  while (true) {
326
309
  const stepInfo = await resolveAndNotifyStep(threadId, ctx, opts);
327
310
  if (!stepInfo)
@@ -338,16 +321,47 @@ async function runThread(threadId, opts) {
338
321
  if (ctx.stream) {
339
322
  const reasonStr = abortCheck.reason ? `: ${abortCheck.reason}` : '';
340
323
  const abortLabel = formatAgentStageLabel(stepCtx.agentSlotId, stepCtx.stage);
341
- ctx.stream.emitText(`:octagonal_sign: Thread aborted by *${abortLabel}*${reasonStr}`);
324
+ ctx.stream.emitText(`${Icons.stopped} Thread aborted by *${abortLabel}*${reasonStr}`);
342
325
  }
343
326
  break;
344
327
  }
328
+ // Parent suspension (DR-0014): [WAIT_CHILDREN] marker in last step output / artifact.
329
+ // Checked after abort, before transitions. Three outcomes:
330
+ // - live awaited children remain → thread enters 'waiting' (resumed by thread-callback
331
+ // when the last child turns terminal); skip onEnd — it fires once, at true termination.
332
+ // - all awaited children already terminal (callback won the race) and their results sit
333
+ // in pendingMessages → re-enter the loop immediately so the same agent processes them.
334
+ // - marker but nothing to wait on or process → fall through to normal transitions.
335
+ if (detectWaitMarker(threadId)) {
336
+ if (await tryEnterWaiting(threadId)) {
337
+ enteredWaiting = true;
338
+ const n = threadStore.get(threadId)?.metadata?.waitingOn?.length ?? 0;
339
+ if (ctx.stream)
340
+ ctx.stream.emitText(`${Icons.processing} Thread suspended — waiting on ${n} child thread(s)`);
341
+ break;
342
+ }
343
+ const t = threadStore.get(threadId);
344
+ if (t?.metadata?.pendingMessages?.length) {
345
+ // Ad-hoc parents bypass transition evaluation, so the contract budget breaker
346
+ // must gate the re-entry loop here (template threads get it in checkTemplateLimits).
347
+ if (t && checkContractBudget(t)) {
348
+ if (ctx.stream)
349
+ ctx.stream.emitText(`${Icons.warning} Contract budget exhausted — not re-entering wait loop`);
350
+ }
351
+ else {
352
+ continue;
353
+ }
354
+ }
355
+ }
345
356
  if (!await evaluateAndTransition(threadId, stepCtx, ctx, opts))
346
357
  break;
347
358
  }
348
359
  // --- onEnd hook (after main loop) ---
349
360
  // Template hook first, then per-call extraHooks (see note at onTransition).
350
- if (!ctx.isDefault) {
361
+ // Skipped on suspension: onEnd semantics are "thread truly finished" (e.g. the dispatch
362
+ // task-status-check hook must not nag while children are still working). The re-entry
363
+ // path re-runs runThread, so onEnd still fires exactly once at final termination.
364
+ if (!enteredWaiting) {
351
365
  const threadForEnd = threadStore.get(threadId);
352
366
  const lastStep = threadForEnd.steps[threadForEnd.steps.length - 1];
353
367
  await executeLifecycleHook(threadId, 'end', ctx.template?.hooks?.onEnd, opts, lastStep?.agentSlotId);
@@ -367,8 +381,25 @@ async function runThread(threadId, opts) {
367
381
  throw error;
368
382
  }
369
383
  finally {
370
- runningExecutions.remove(opts.channel);
371
- // Cleanup thread-specific sessions
384
+ // Defensive: the per-step path finalizes each execution on success (recordStepOutcome) and on
385
+ // error (executeAndAwaitAgent). If the loop threw AFTER an agent result but BEFORE the step was
386
+ // finalized, the step's execution can still be registered and its persistent record still
387
+ // 'running' — finalize it as failed across both ledgers so it neither leaks a 'running' record
388
+ // nor poisons a dispatch slot. Scope to THIS thread's entries so a concurrent run on the same
389
+ // channel is never touched.
390
+ for (const e of runningExecutions.getByChannel(opts.channel)) {
391
+ if (e.threadId !== threadId)
392
+ continue;
393
+ if (e.executionId) {
394
+ executionRegistry.teardownExecution({ executionId: e.executionId, status: 'failed', durationS: 0, error: { message: 'thread ended before step finalized' } });
395
+ }
396
+ else {
397
+ runningExecutions.remove(e.registryKey);
398
+ }
399
+ }
400
+ // Cleanup thread-specific sessions. Intentionally also runs on suspension (DR-0014):
401
+ // a waiting parent holds no live session — the artifact is its durable memory, and
402
+ // persistSession slots keep their sessionId so re-entry resumes via --resume.
372
403
  closeSessionsByPrefix(`thr:${threadId}:`);
373
404
  }
374
405
  return finalizeThread(threadId, ctx);
@@ -388,6 +419,22 @@ async function continueThread(threadId, userMessage, opts) {
388
419
  });
389
420
  return runThread(threadId, opts);
390
421
  }
422
+ // --- Resume a suspended parent thread (DR-0014) ---
423
+ /** Re-enter a parent thread that was suspended via [WAIT_CHILDREN]. Unlike continueThread,
424
+ * the userMessage is NOT overwritten — the original contract stays in {{input}}; the child
425
+ * results arrive through metadata.pendingMessages (injected by the prompt builder). */
426
+ async function resumeThread(threadId, opts) {
427
+ const thread = threadStore.get(threadId);
428
+ if (!thread)
429
+ throw new Error(`Thread not found: ${threadId}`);
430
+ if (thread.status !== 'waiting') {
431
+ throw new Error(`Thread ${threadId} is ${thread.status}, cannot resume`);
432
+ }
433
+ await threadStore.mutate(threadId, (t) => {
434
+ t.status = 'running';
435
+ });
436
+ return runThread(threadId, opts);
437
+ }
391
438
  // --- Thread summary for Slack ---
392
439
  function buildThreadSummary(result) {
393
440
  const { thread, totalCostUsd, totalNumTurns } = result;
@@ -395,13 +442,15 @@ function buildThreadSummary(result) {
395
442
  const elapsed = thread.endedAt && thread.createdAt
396
443
  ? (new Date(thread.endedAt).getTime() - new Date(thread.createdAt).getTime()) / 1000
397
444
  : 0;
398
- const statusEmoji = thread.status === 'completed' ? ':white_check_mark:'
399
- : thread.status === 'cancelled' ? ':no_entry_sign:'
400
- : thread.status === 'aborted' ? ':octagonal_sign:'
401
- : ':x:';
402
- const lines = [
403
- `${statusEmoji} Thread complete | ${steps.length} steps | $${totalCostUsd.toFixed(4)} | ${formatDurationCompact(elapsed)}`,
404
- ];
445
+ const statusEmoji = thread.status === 'completed' ? Icons.ok
446
+ : thread.status === 'cancelled' ? Icons.blocked
447
+ : thread.status === 'aborted' ? Icons.stopped
448
+ : thread.status === 'waiting' ? Icons.processing
449
+ : Icons.error;
450
+ const headline = thread.status === 'waiting'
451
+ ? `${statusEmoji} Thread suspended — waiting on ${(thread.metadata?.waitingOn?.length ?? 0) + (thread.metadata?.waitingOnTasks?.length ?? 0)} child(ren) | ${steps.length} steps | $${totalCostUsd.toFixed(4)}`
452
+ : `${statusEmoji} Thread complete | ${steps.length} steps | $${totalCostUsd.toFixed(4)} | ${formatDurationCompact(elapsed)}`;
453
+ const lines = [headline];
405
454
  if (steps.length > 1) {
406
455
  for (const step of steps) {
407
456
  const costStr = step.costUsd != null ? `$${step.costUsd.toFixed(4)}` : '?';
@@ -425,12 +474,12 @@ function buildThreadSummary(result) {
425
474
  // Proxy functions to support existing callers that import cancelActiveThread / getActiveHandle from runner.ts.
426
475
  // These delegate to the unified RunningExecutions singleton.
427
476
  function cancelActiveThread(channel) {
428
- return runningExecutions.killByKey(channel);
477
+ return runningExecutions.killByChannel(channel) > 0;
429
478
  }
430
479
  function getActiveHandle(channel) {
431
- return runningExecutions.getByKey(channel);
480
+ return runningExecutions.getByChannel(channel)[0] ?? null;
432
481
  }
433
- export { runThread, continueThread, buildThreadSummary, cancelActiveThread, getActiveHandle,
482
+ export { runThread, continueThread, resumeThread, buildThreadSummary, cancelActiveThread, getActiveHandle,
434
483
  // Internal helpers — exported to support focused unit tests from agent-server/tests/thread-runner.test.ts.
435
484
  // Not part of the public API; callers outside the test harness should continue to use runThread().
436
485
  initThreadContext, resolveAndNotifyStep, buildStepConfig, setupStepCallbacks, executeAndAwaitAgent, recordStepOutcome, evaluateAndTransition, finalizeThread, };
@@ -8,27 +8,6 @@ export declare function createThread(channel: string, options: {
8
8
  projectId?: string;
9
9
  metadata?: import('../../core/types/thread-types.js').ThreadMetadata | null;
10
10
  }): ThreadRecord;
11
- /** Create a lightweight completed thread record (no filesystem workspace).
12
- * Used to track single-agent path executions so !thread add can chain off them. */
13
- export declare function createAutoThreadRecord(channel: string, options: {
14
- agentName: string;
15
- userMessage: string;
16
- userMessageTs: string;
17
- platformThreadId?: string | null;
18
- projectId?: string;
19
- }): ThreadRecord;
20
- /** Create a thread record that uses the 'default' template (single-step, single-agent with workspace).
21
- * Used by the agent-runner wrapper to create a thread BEFORE execution, so that isDefaultThread()
22
- * returns true and the thread runner uses default-path semantics.
23
- * Unlike createAutoThreadRecord (post-hoc, templateName=null, no workspace), this sets
24
- * templateName='default' and creates a workspace so it is detected as a default thread. */
25
- export declare function createDefaultThread(channel: string, options: {
26
- agentName: string;
27
- userMessage: string;
28
- userMessageTs: string;
29
- platformThreadId?: string | null;
30
- projectId?: string;
31
- }): ThreadRecord;
32
11
  export declare function addAgentToThread(threadId: string, agentName: string, userMessage?: string | null): Promise<ThreadRecord>;
33
12
  interface NextStepInfo {
34
13
  agentSlotId: AgentSlotId;
@@ -57,6 +36,29 @@ export declare function detectAbortMarker(threadId: string): {
57
36
  aborted: boolean;
58
37
  reason: string | null;
59
38
  };
39
+ /** Detect `[WAIT_CHILDREN]` in the last step's output or in the artifact. The marker alone
40
+ * does not suspend the thread — tryEnterWaiting() additionally requires live children. */
41
+ export declare function detectWaitMarker(threadId: string): boolean;
42
+ /** Try to suspend the thread until its waited-on children finish. Inside a single mutate
43
+ * (serialized with the callback side via the store mutex), filter waitingOn down to
44
+ * children that still exist and are non-terminal; additionally (DR-0014 §8) snapshot live
45
+ * child TASKS (parent === metadata.taskId) into waitingOnTasks. If either list is
46
+ * non-empty, set status='waiting'. Returns true iff the thread entered waiting.
47
+ * Either interleaving with the completion callback converges: callback-first → nothing
48
+ * left to wait on (results already in pendingMessages); runner-first → callback sees
49
+ * waiting and resumes when both lists empty. The task-side race (a child completing
50
+ * between the snapshot and the waiting persist, its event missed) is closed by
51
+ * reconcileWaitingTasks right after suspension. */
52
+ export declare function tryEnterWaiting(threadId: string): Promise<boolean>;
53
+ export interface SplitDetection {
54
+ split: boolean;
55
+ subtasks: any[] | null;
56
+ error: string | null;
57
+ }
58
+ /** Detect a `[SPLIT]` decomposition proposal in the artifact: the marker followed by a
59
+ * ```json fenced block containing `{ "subtasks": [...] }`. Parse failures are surfaced
60
+ * (not swallowed) so the dispatch path can report them instead of silently dropping. */
61
+ export declare function detectSplitMarker(threadId: string): SplitDetection;
60
62
  /** Terminate the thread with status='aborted'. Idempotent — returns false if thread is already terminal. */
61
63
  export declare function abortThread(threadId: string, reason: string | null): Promise<boolean>;
62
64
  export declare function completeThread(threadId: string): Promise<boolean>;
@@ -1,8 +1,9 @@
1
1
  // Thread lifecycle state machine.
2
2
  // input: thread-store, template-loader, prompt-builder, utils, artifact-io
3
- // output: createThread / createAutoThreadRecord / createDefaultThread / addAgentToThread /
3
+ // output: createThread / addAgentToThread /
4
4
  // resolveNextStep / evaluateTransitions / recordStepResult / completeThread /
5
- // failThread / cancelThread / abortThread / detectAbortMarker
5
+ // failThread / cancelThread / abortThread / detectAbortMarker /
6
+ // detectWaitMarker / tryEnterWaiting / detectSplitMarker (DR-0014)
6
7
  import { mkdirSync, writeFileSync, readFileSync } from 'fs';
7
8
  import * as path from 'path';
8
9
  import { WORKSPACE_DIR } from '../../core/utils.js';
@@ -13,6 +14,8 @@ import { getTemplate, getAgent } from './template-loader.js';
13
14
  import { resolveAgentSlotConfigByName, resolveTemplateAgents, resolveActiveAgentName } from './prompt-builder.js';
14
15
  import { resolveStageName, parseTarget } from './utils.js';
15
16
  import { readArtifact } from './artifact-io.js';
17
+ import { checkContractBudget } from './contract.js';
18
+ import { scanAllTasks } from '../../core/task-parser.js';
16
19
  // --- Agent slot helpers ---
17
20
  function newAgentSlot(config) {
18
21
  return {
@@ -101,58 +104,6 @@ export function createThread(channel, options) {
101
104
  log.info(`Created thread ${id} (${mode}, workspace=${workspacePath})`);
102
105
  return thread;
103
106
  }
104
- /** Create a lightweight completed thread record (no filesystem workspace).
105
- * Used to track single-agent path executions so !thread add can chain off them. */
106
- export function createAutoThreadRecord(channel, options) {
107
- const agentConfig = resolveAgentSlotConfigByName(options.agentName);
108
- if (!agentConfig)
109
- throw new Error(`Unknown agent: ${options.agentName}`);
110
- const id = threadStore.generateId();
111
- const thread = makeThreadRecord({
112
- id, channel,
113
- projectId: options.projectId,
114
- templateName: null,
115
- platformThreadId: options.platformThreadId || null,
116
- userMessage: options.userMessage,
117
- userMessageTs: options.userMessageTs,
118
- workspacePath: '', artifactPath: '',
119
- agents: { [agentConfig.slotId]: newAgentSlot(agentConfig) },
120
- activeAgent: agentConfig.slotId,
121
- activeStage: resolveStageName(agentConfig, null),
122
- metadata: null,
123
- });
124
- threadStore.set(thread);
125
- log.info(`Created auto thread record ${id} (agent=${options.agentName})`);
126
- return thread;
127
- }
128
- /** Create a thread record that uses the 'default' template (single-step, single-agent with workspace).
129
- * Used by the agent-runner wrapper to create a thread BEFORE execution, so that isDefaultThread()
130
- * returns true and the thread runner uses default-path semantics.
131
- * Unlike createAutoThreadRecord (post-hoc, templateName=null, no workspace), this sets
132
- * templateName='default' and creates a workspace so it is detected as a default thread. */
133
- export function createDefaultThread(channel, options) {
134
- const agentConfig = resolveAgentSlotConfigByName(options.agentName);
135
- if (!agentConfig)
136
- throw new Error(`Unknown agent: ${options.agentName}`);
137
- const id = threadStore.generateId();
138
- const { workspacePath, artifactPath } = createWorkspace(id);
139
- const thread = makeThreadRecord({
140
- id, channel,
141
- projectId: options.projectId,
142
- templateName: 'default',
143
- platformThreadId: options.platformThreadId || null,
144
- userMessage: options.userMessage,
145
- userMessageTs: options.userMessageTs,
146
- workspacePath, artifactPath,
147
- agents: { [agentConfig.slotId]: newAgentSlot(agentConfig) },
148
- activeAgent: agentConfig.slotId,
149
- activeStage: resolveStageName(agentConfig, null),
150
- metadata: null,
151
- });
152
- threadStore.set(thread);
153
- log.info(`Created default thread ${id} (agent=${options.agentName})`);
154
- return thread;
155
- }
156
107
  // --- Add agent to existing thread ---
157
108
  /** Lazy workspace creation for auto-records that started without a filesystem workspace. */
158
109
  function ensureThreadWorkspace(thread) {
@@ -272,6 +223,11 @@ function checkTemplateLimits(thread, template) {
272
223
  if (template.maxTotalCostUsd != null && thread.totalCostUsd >= template.maxTotalCostUsd) {
273
224
  return { shouldTransition: false, reason: 'cost_limit' };
274
225
  }
226
+ // DR-0014: per-thread delegation-contract budget (second gate after the spawn-time
227
+ // tree guards — catches a single thread burning through its allowance step by step).
228
+ if (checkContractBudget(thread)) {
229
+ return { shouldTransition: false, reason: 'cost_limit' };
230
+ }
275
231
  return null;
276
232
  }
277
233
  function applyTransition(thread, rule, result) {
@@ -402,6 +358,109 @@ export function detectAbortMarker(threadId) {
402
358
  const raw = m[1] != null ? m[1].trim() : '';
403
359
  return { aborted: true, reason: raw.length > 0 ? raw : null };
404
360
  }
361
+ // --- Wait-on-children + split markers (DR-0014) ---
362
+ const WAIT_MARKER_RE = /\[WAIT_CHILDREN\]/;
363
+ /** Detect `[WAIT_CHILDREN]` in the last step's output or in the artifact. The marker alone
364
+ * does not suspend the thread — tryEnterWaiting() additionally requires live children. */
365
+ export function detectWaitMarker(threadId) {
366
+ const thread = threadStore.get(threadId);
367
+ if (!thread)
368
+ return false;
369
+ const lastStep = thread.steps[thread.steps.length - 1];
370
+ if (lastStep?.output && WAIT_MARKER_RE.test(lastStep.output))
371
+ return true;
372
+ const content = readArtifact(threadId);
373
+ return !!content && WAIT_MARKER_RE.test(content);
374
+ }
375
+ function isTerminal(status) {
376
+ return status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'aborted';
377
+ }
378
+ /** Live (open, unblocked) child tasks of the given task, read straight from TASKS.yaml via
379
+ * the zero-dependency core parser — no domain/tasks import (avoids a layer cycle).
380
+ * Wait set = UNION of parent-linked children and the task's own unmet depends_on: any
381
+ * not-done dependency at manager runtime was added by the manager itself (pre-existing
382
+ * deps were cleared before dispatch by the actionability filter), so suspension stays
383
+ * correct even when the manager created children without the parent field (bulk-add +
384
+ * edit --add-depends-on instead of decompose --keep-parent — 2026-06-11 incident
385
+ * thr_6faa13a1: [WAIT_CHILDREN] emitted, suspension found no children, thread completed). */
386
+ function liveChildTaskIds(taskId, taskProject) {
387
+ try {
388
+ const tasks = scanAllTasks(taskProject);
389
+ const own = tasks.find((t) => t.id === taskId);
390
+ const depIds = new Set(own?.depends_on ?? []);
391
+ return tasks
392
+ .filter((t) => t.id && t.id !== taskId
393
+ && (t.parent === taskId || depIds.has(t.id))
394
+ && t.status !== 'done' && !t.blocked_by)
395
+ .map((t) => t.id);
396
+ }
397
+ catch {
398
+ return [];
399
+ }
400
+ }
401
+ /** Try to suspend the thread until its waited-on children finish. Inside a single mutate
402
+ * (serialized with the callback side via the store mutex), filter waitingOn down to
403
+ * children that still exist and are non-terminal; additionally (DR-0014 §8) snapshot live
404
+ * child TASKS (parent === metadata.taskId) into waitingOnTasks. If either list is
405
+ * non-empty, set status='waiting'. Returns true iff the thread entered waiting.
406
+ * Either interleaving with the completion callback converges: callback-first → nothing
407
+ * left to wait on (results already in pendingMessages); runner-first → callback sees
408
+ * waiting and resumes when both lists empty. The task-side race (a child completing
409
+ * between the snapshot and the waiting persist, its event missed) is closed by
410
+ * reconcileWaitingTasks right after suspension. */
411
+ export async function tryEnterWaiting(threadId) {
412
+ const thread = threadStore.get(threadId);
413
+ if (!thread)
414
+ return false;
415
+ const hasThreadChildren = !!thread.metadata?.waitingOn?.length;
416
+ const taskId = thread.metadata?.taskId;
417
+ const taskProject = thread.metadata?.taskProject;
418
+ if (!hasThreadChildren && !(taskId && taskProject))
419
+ return false;
420
+ const taskChildren = taskId && taskProject ? liveChildTaskIds(taskId, taskProject) : [];
421
+ let entered = false;
422
+ await threadStore.mutate(threadId, (t) => {
423
+ const m = (t.metadata ??= {});
424
+ const live = (m.waitingOn || []).filter((id) => {
425
+ const child = threadStore.get(id);
426
+ return !!child && !isTerminal(child.status);
427
+ });
428
+ m.waitingOn = live;
429
+ m.waitingOnTasks = taskChildren;
430
+ if (live.length > 0 || taskChildren.length > 0) {
431
+ t.status = 'waiting';
432
+ entered = true;
433
+ }
434
+ });
435
+ if (entered) {
436
+ const m = threadStore.get(threadId).metadata;
437
+ log.info(`Thread ${threadId} suspended, waiting on ${m.waitingOn.length} thread children + ${m.waitingOnTasks.length} task children`);
438
+ }
439
+ return entered;
440
+ }
441
+ const SPLIT_MARKER_RE = /\[SPLIT\]/;
442
+ const SPLIT_JSON_FENCE_RE = /\[SPLIT\][\s\S]*?```json\s*\n([\s\S]*?)\n\s*```/;
443
+ /** Detect a `[SPLIT]` decomposition proposal in the artifact: the marker followed by a
444
+ * ```json fenced block containing `{ "subtasks": [...] }`. Parse failures are surfaced
445
+ * (not swallowed) so the dispatch path can report them instead of silently dropping. */
446
+ export function detectSplitMarker(threadId) {
447
+ const content = readArtifact(threadId) || '';
448
+ if (!SPLIT_MARKER_RE.test(content))
449
+ return { split: false, subtasks: null, error: null };
450
+ const fence = SPLIT_JSON_FENCE_RE.exec(content);
451
+ if (!fence)
452
+ return { split: true, subtasks: null, error: '[SPLIT] marker present but no ```json fenced block follows' };
453
+ try {
454
+ const parsed = JSON.parse(fence[1]);
455
+ if (!parsed || !Array.isArray(parsed.subtasks) || parsed.subtasks.length === 0) {
456
+ return { split: true, subtasks: null, error: '[SPLIT] JSON must be an object with a non-empty "subtasks" array' };
457
+ }
458
+ return { split: true, subtasks: parsed.subtasks, error: null };
459
+ }
460
+ catch (e) {
461
+ return { split: true, subtasks: null, error: `[SPLIT] JSON parse failed: ${e?.message || e}` };
462
+ }
463
+ }
405
464
  /** Terminate the thread with status='aborted'. Idempotent — returns false if thread is already terminal. */
406
465
  export async function abortThread(threadId, reason) {
407
466
  const thread = threadStore.get(threadId);