@cortex-agent/server 2026.10.2 → 2026.10.6

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 (574) hide show
  1. package/README.md +31 -31
  2. package/defaults/AGENTS.md +3 -3
  3. package/defaults/config/{thread-templates/agents/direct.json → environments/main.json} +2 -2
  4. package/defaults/context/AGENTS.md +0 -2
  5. package/defaults/context/projects/AGENTS.md +0 -2
  6. package/defaults/context/user/AGENTS.md +1 -1
  7. package/defaults/hooks/cortex-hook-api.mjs +1 -3
  8. package/defaults/hooks/new-session-hook.mjs +2 -3
  9. package/defaults/hooks/status-md-guard.mjs +5 -5
  10. package/defaults/plugins/cortex-system/.claude-plugin/plugin.json +2 -2
  11. package/defaults/plugins/cortex-system/plugin.json +2 -2
  12. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  13. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +11 -13
  14. package/defaults/plugins/cortex-system/skills/user-learn/SKILL.md +1 -1
  15. package/defaults/prompts/systemPrompts/web-opus-4-6.md +2 -2
  16. package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +2 -2
  17. package/defaults/rules/issues-md.md +2 -2
  18. package/defaults/rules/meta-conventions.md +1 -2
  19. package/defaults/rules/mission-md.md +1 -1
  20. package/defaults/rules/overview-md.md +1 -1
  21. package/defaults/rules/roadmap-md.md +1 -1
  22. package/defaults/rules/status-md.md +4 -4
  23. package/dist/agent-adapter/claude/adapter.d.ts +6 -1
  24. package/dist/agent-adapter/claude/adapter.js +15 -4
  25. package/dist/agent-adapter/claude/compact-window.d.ts +11 -3
  26. package/dist/agent-adapter/claude/compact-window.js +12 -3
  27. package/dist/agent-adapter/claude/defaults.d.ts +0 -1
  28. package/dist/agent-adapter/claude/defaults.js +0 -1
  29. package/dist/agent-adapter/claude/event-translator.d.ts +2 -2
  30. package/dist/agent-adapter/claude/event-translator.js +2 -1
  31. package/dist/agent-adapter/claude/hooks-builder.d.ts +0 -5
  32. package/dist/agent-adapter/claude/hooks-builder.js +0 -13
  33. package/dist/agent-adapter/claude/spawn-args.d.ts +5 -12
  34. package/dist/agent-adapter/claude/spawn-args.js +45 -38
  35. package/dist/agent-adapter/claude/turn-machine.d.ts +2 -2
  36. package/dist/agent-adapter/claude/turn-machine.js +6 -3
  37. package/dist/agent-adapter/continuation-phase.js +2 -1
  38. package/dist/agent-adapter/normalize/event-types.d.ts +4 -1
  39. package/dist/agent-adapter/normalize/tool-result-images.d.ts +11 -0
  40. package/dist/agent-adapter/normalize/tool-result-images.js +32 -0
  41. package/dist/agent-adapter/pi/child-events.js +3 -0
  42. package/dist/agent-adapter/pi/child-runner.d.ts +1 -2
  43. package/dist/agent-adapter/pi/child-runner.js +6 -6
  44. package/dist/agent-adapter/pi/child-session.d.ts +1 -1
  45. package/dist/agent-adapter/pi/event-parser.d.ts +13 -2
  46. package/dist/agent-adapter/pi/event-parser.js +38 -11
  47. package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +0 -1
  48. package/dist/agent-adapter/pi/mcp-bridge-logic.js +0 -3
  49. package/dist/agent-adapter/pi/mcp-bridge.js +4 -4
  50. package/dist/agent-adapter/pi/pi-session.d.ts +4 -2
  51. package/dist/agent-adapter/pi/pi-session.js +18 -9
  52. package/dist/agent-adapter/pi/runtime-settings.d.ts +7 -0
  53. package/dist/agent-adapter/pi/runtime-settings.js +23 -0
  54. package/dist/agent-adapter/pi/runtime.d.ts +2 -3
  55. package/dist/agent-adapter/pi/session-options.d.ts +4 -1
  56. package/dist/agent-adapter/pi/session-options.js +13 -21
  57. package/dist/agent-adapter/pi/session-support.d.ts +2 -0
  58. package/dist/agent-adapter/run-events.d.ts +3 -1
  59. package/dist/agent-adapter/types.d.ts +6 -12
  60. package/dist/agent-adapter/types.js +2 -4
  61. package/dist/core/agents/roles.d.ts +1 -1
  62. package/dist/core/agents/subagent/attribution.js +1 -0
  63. package/dist/core/agents/subagent/catalog.d.ts +8 -0
  64. package/dist/core/agents/subagent/catalog.js +21 -10
  65. package/dist/core/agents/subagent/types.d.ts +4 -1
  66. package/dist/core/config-generator.d.ts +0 -6
  67. package/dist/core/config-generator.js +1 -35
  68. package/dist/core/icons.d.ts +33 -33
  69. package/dist/core/locales/en.d.ts +863 -1030
  70. package/dist/core/locales/slices/commands.d.ts +282 -349
  71. package/dist/core/locales/slices/commands.js +20 -160
  72. package/dist/core/locales/slices/init.d.ts +152 -152
  73. package/dist/core/locales/slices/interactions.d.ts +44 -45
  74. package/dist/core/locales/slices/interactions.js +0 -4
  75. package/dist/core/locales/slices/lang.d.ts +5 -5
  76. package/dist/core/locales/slices/notices.d.ts +75 -118
  77. package/dist/core/locales/slices/notices.js +13 -99
  78. package/dist/core/locales/slices/scheduling.d.ts +31 -31
  79. package/dist/core/locales/slices/startup.d.ts +5 -5
  80. package/dist/core/locales/slices/status.d.ts +43 -43
  81. package/dist/core/locales/slices/tui.d.ts +91 -114
  82. package/dist/core/locales/slices/tui.js +0 -46
  83. package/dist/core/locales/slices/uiextra.d.ts +41 -61
  84. package/dist/core/locales/slices/uiextra.js +11 -51
  85. package/dist/core/locales/slices/uimsg.d.ts +86 -99
  86. package/dist/core/locales/slices/uimsg.js +6 -32
  87. package/dist/core/mcp-bundles.d.ts +1 -1
  88. package/dist/core/mcp-bundles.js +7 -5
  89. package/dist/core/mcp-tool-gate.js +8 -5
  90. package/dist/core/platform-settings-spec.d.ts +3 -3
  91. package/dist/core/production-benchmark-evidence.d.ts +1 -9
  92. package/dist/core/production-benchmark-evidence.js +0 -22
  93. package/dist/core/rebuild-progress.d.ts +3 -2
  94. package/dist/core/rebuild-progress.js +5 -2
  95. package/dist/core/run-registry.d.ts +7 -28
  96. package/dist/core/run-registry.js +6 -51
  97. package/dist/core/session-retention-liveness.d.ts +0 -2
  98. package/dist/core/session-retention-liveness.js +0 -13
  99. package/dist/core/session-state.d.ts +1 -2
  100. package/dist/core/session-state.js +2 -3
  101. package/dist/core/settings-spec.d.ts +19 -60
  102. package/dist/core/settings-spec.js +30 -60
  103. package/dist/core/status-format.d.ts +0 -14
  104. package/dist/core/status-format.js +2 -24
  105. package/dist/core/types/agent-types.d.ts +26 -9
  106. package/dist/core/types/benchmark-types.d.ts +17 -0
  107. package/dist/core/types/environment-types.d.ts +64 -0
  108. package/dist/core/types/environment-types.js +1 -0
  109. package/dist/core/utils.d.ts +14 -4
  110. package/dist/core/utils.js +32 -6
  111. package/dist/domain/agents/agent-switch.js +2 -4
  112. package/dist/domain/agents/config.js +1 -1
  113. package/dist/domain/agents/environments/entities.d.ts +49 -0
  114. package/dist/domain/agents/environments/entities.js +94 -0
  115. package/dist/domain/agents/environments/file-refs.d.ts +19 -0
  116. package/dist/domain/agents/environments/file-refs.js +48 -0
  117. package/dist/domain/agents/environments/index.d.ts +6 -0
  118. package/dist/domain/agents/environments/index.js +8 -0
  119. package/dist/domain/agents/environments/paths.d.ts +7 -0
  120. package/dist/domain/agents/environments/paths.js +9 -0
  121. package/dist/domain/{threads/template-resolver.js → agents/environments/prompt-includes.js} +2 -2
  122. package/dist/domain/agents/environments/registry.d.ts +17 -0
  123. package/dist/domain/agents/environments/registry.js +159 -0
  124. package/dist/domain/agents/environments/schema.d.ts +68 -0
  125. package/dist/domain/agents/environments/schema.js +111 -0
  126. package/dist/domain/agents/environments/schema.parity.d.ts +1 -0
  127. package/dist/domain/agents/environments/schema.parity.js +7 -0
  128. package/dist/domain/agents/environments/slot-config.d.ts +14 -0
  129. package/dist/domain/agents/environments/slot-config.js +78 -0
  130. package/dist/domain/agents/model-selection.d.ts +3 -0
  131. package/dist/domain/agents/model-selection.js +1 -1
  132. package/dist/domain/agents/subagent/runner.js +3 -2
  133. package/dist/domain/benchmark/accounting-reconciliation.d.ts +1 -1
  134. package/dist/domain/benchmark/atif.d.ts +4 -4
  135. package/dist/domain/benchmark/atif.js +7 -7
  136. package/dist/domain/benchmark/attempt-record.d.ts +16 -55
  137. package/dist/domain/benchmark/attempt-record.js +3 -17
  138. package/dist/domain/benchmark/composite-manifest.d.ts +4 -4
  139. package/dist/domain/benchmark/composite-manifest.js +5 -11
  140. package/dist/domain/benchmark/journal.d.ts +6 -4
  141. package/dist/domain/benchmark/journal.js +6 -4
  142. package/dist/domain/benchmark/manifest-contract.d.ts +1 -1
  143. package/dist/domain/benchmark/production-attempt-identity.d.ts +11 -16
  144. package/dist/domain/benchmark/production-attempt-identity.js +31 -94
  145. package/dist/domain/benchmark/production-attempt-journal.js +14 -7
  146. package/dist/domain/benchmark/production-evidence-journal.js +8 -6
  147. package/dist/domain/benchmark/production-evidence-projection.d.ts +1 -11
  148. package/dist/domain/benchmark/production-evidence-projection.js +32 -143
  149. package/dist/domain/benchmark/session-evidence.d.ts +6 -0
  150. package/dist/domain/benchmark/session-evidence.js +27 -0
  151. package/dist/domain/costs/cost-tracker.d.ts +1 -7
  152. package/dist/domain/costs/cost-tracker.js +0 -4
  153. package/dist/domain/costs/resume-registry.d.ts +9 -20
  154. package/dist/domain/costs/resume-registry.js +24 -39
  155. package/dist/domain/executions/registry.d.ts +3 -18
  156. package/dist/domain/executions/registry.js +4 -158
  157. package/dist/domain/mcp/bundled-server.js +20 -27
  158. package/dist/domain/mcp/tools/commission-tools.js +0 -1
  159. package/dist/domain/mcp/tools/context.d.ts +2 -9
  160. package/dist/domain/mcp/tools/context.js +2 -7
  161. package/dist/domain/mcp/tools/executions.js +6 -19
  162. package/dist/domain/mcp/tools/interaction-ask.js +0 -1
  163. package/dist/domain/mcp/tools/interaction-plan.d.ts +0 -1
  164. package/dist/domain/mcp/tools/interaction-plan.js +0 -2
  165. package/dist/domain/mcp/tools/{task-ops.d.ts → remote-ops.d.ts} +1 -1
  166. package/dist/domain/mcp/tools/{task-ops.js → remote-ops.js} +1 -1
  167. package/dist/domain/mcp/tools/schedule.d.ts +3 -3
  168. package/dist/domain/mcp/tools/schedule.js +10 -32
  169. package/dist/domain/mcp/tools/subagent.d.ts +4 -0
  170. package/dist/domain/mcp/tools/subagent.js +10 -8
  171. package/dist/domain/mcp/tools/ui-view.js +3 -2
  172. package/dist/domain/mcp/tools/waitpoint.js +2 -3
  173. package/dist/domain/mcp/tools/{thread-ops.d.ts → workers.d.ts} +1 -1
  174. package/dist/domain/mcp/tools/workers.js +84 -0
  175. package/dist/domain/memory/user-context.d.ts +2 -3
  176. package/dist/domain/memory/user-context.js +2 -3
  177. package/dist/domain/monitor/gpu-monitor.js +1 -1
  178. package/dist/domain/pi-providers/custom-provider-model.d.ts +1 -1
  179. package/dist/domain/projects/project-store.d.ts +1 -2
  180. package/dist/domain/projects/project-store.js +1 -9
  181. package/dist/domain/remote/client-manager.d.ts +1 -1
  182. package/dist/domain/remote/client-manager.js +1 -1
  183. package/dist/domain/remote/client-remove.d.ts +1 -1
  184. package/dist/domain/remote/machine-registry.d.ts +54 -0
  185. package/dist/domain/{tasks/dispatch-utils.js → remote/machine-registry.js} +1 -61
  186. package/dist/domain/runs/attempt.js +3 -8
  187. package/dist/domain/runs/builders.d.ts +2 -3
  188. package/dist/domain/runs/builders.js +2 -3
  189. package/dist/domain/runs/engine-spec.js +3 -10
  190. package/dist/domain/runs/fallback.d.ts +1 -3
  191. package/dist/domain/runs/fallback.js +1 -3
  192. package/dist/domain/runs/observers/resume-recorder.d.ts +0 -15
  193. package/dist/domain/runs/observers/resume-recorder.js +0 -17
  194. package/dist/domain/runs/prompt.d.ts +23 -8
  195. package/dist/domain/runs/prompt.js +31 -5
  196. package/dist/domain/runs/request.d.ts +6 -15
  197. package/dist/domain/runs/run.js +0 -2
  198. package/dist/domain/runs/service.js +0 -2
  199. package/dist/domain/runs/spec-loader.d.ts +4 -6
  200. package/dist/domain/runs/spec-loader.js +3 -5
  201. package/dist/domain/scheduling/builtin-job-migration.js +3 -3
  202. package/dist/domain/scheduling/builtin-jobs.js +0 -13
  203. package/dist/domain/scheduling/job-registry.d.ts +12 -27
  204. package/dist/domain/scheduling/job-registry.js +2 -3
  205. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +18 -6
  206. package/dist/domain/scheduling/jobs/scheduled-task.js +66 -125
  207. package/dist/domain/scheduling/run-guards.d.ts +6 -0
  208. package/dist/domain/scheduling/run-guards.js +18 -0
  209. package/dist/domain/scheduling/runner.d.ts +0 -1
  210. package/dist/domain/scheduling/runner.js +0 -1
  211. package/dist/domain/scheduling/schedule-cli.js +1 -1
  212. package/dist/domain/scheduling/scheduler.d.ts +0 -4
  213. package/dist/domain/scheduling/scheduler.js +2 -6
  214. package/dist/domain/sessions/session-hooks.d.ts +2 -2
  215. package/dist/domain/sessions/session-lifecycle.d.ts +23 -9
  216. package/dist/domain/sessions/session-lifecycle.js +27 -15
  217. package/dist/domain/sessions/session-retention.d.ts +8 -0
  218. package/dist/domain/sessions/session-retention.js +139 -34
  219. package/dist/domain/sessions/team.d.ts +18 -0
  220. package/dist/domain/sessions/team.js +21 -0
  221. package/dist/domain/system/install-cli.js +5 -5
  222. package/dist/domain/system/rebuild-hold.d.ts +1 -1
  223. package/dist/domain/system/server-update-check.js +2 -1
  224. package/dist/domain/ui-service/app-router.d.ts +41 -154
  225. package/dist/domain/ui-service/app-router.js +9 -30
  226. package/dist/domain/ui-service/input-schemas.d.ts +64 -205
  227. package/dist/domain/ui-service/input-schemas.js +26 -71
  228. package/dist/domain/ui-service/mutate/environments.d.ts +23 -0
  229. package/dist/domain/ui-service/mutate/environments.js +51 -0
  230. package/dist/domain/ui-service/mutate/plugin-packages.js +3 -9
  231. package/dist/domain/ui-service/mutate/plugins.js +7 -109
  232. package/dist/domain/ui-service/mutate/schedules.js +1 -2
  233. package/dist/domain/ui-service/plugins-shared.d.ts +0 -3
  234. package/dist/domain/ui-service/plugins-shared.js +0 -14
  235. package/dist/domain/ui-service/query/config.js +10 -13
  236. package/dist/domain/ui-service/query/environments.d.ts +12 -0
  237. package/dist/domain/ui-service/query/environments.js +72 -0
  238. package/dist/domain/ui-service/query/executions.js +1 -1
  239. package/dist/domain/ui-service/query/hooks.d.ts +1 -1
  240. package/dist/domain/ui-service/query/hooks.js +13 -24
  241. package/dist/domain/ui-service/query/memory.js +1 -1
  242. package/dist/domain/ui-service/query/plugins.js +6 -82
  243. package/dist/domain/ui-service/query/schedules.js +0 -1
  244. package/dist/domain/ui-service/query/sessions.js +23 -5
  245. package/dist/domain/ui-service/query/system.js +0 -1
  246. package/dist/domain/ui-service/query-input-schemas.d.ts +5 -26
  247. package/dist/domain/ui-service/query-input-schemas.js +0 -18
  248. package/dist/domain/ui-service/types.d.ts +68 -330
  249. package/dist/domain/ui-service/ui-service.js +7 -23
  250. package/dist/domain/waitpoints/notices.d.ts +1 -1
  251. package/dist/domain/waitpoints/notices.js +1 -1
  252. package/dist/entry/app.js +70 -146
  253. package/dist/entry/cli-help.js +0 -1
  254. package/dist/entry/cli.js +1 -6
  255. package/dist/entry/daemon.d.ts +27 -23
  256. package/dist/entry/daemon.js +61 -49
  257. package/dist/entry/fast-install.d.ts +13 -2
  258. package/dist/entry/fast-install.js +43 -11
  259. package/dist/entry/hook-cli.d.ts +0 -1
  260. package/dist/entry/hook-cli.js +20 -49
  261. package/dist/entry/init.js +8 -11
  262. package/dist/entry/local-ui.d.ts +1 -1
  263. package/dist/entry/platform-connect.d.ts +23 -0
  264. package/dist/entry/platform-connect.js +94 -0
  265. package/dist/entry/production-evidence-export-cli.js +0 -2
  266. package/dist/events/event-logger.js +1 -0
  267. package/dist/events/event-types.d.ts +13 -62
  268. package/dist/hooks/cortex-hook-api.mjs +1 -3
  269. package/dist/hooks/new-session-hook.mjs +2 -3
  270. package/dist/hooks/status-md-guard.mjs +5 -5
  271. package/dist/orchestration/agent-runner.d.ts +3 -0
  272. package/dist/orchestration/agent-runner.js +21 -19
  273. package/dist/orchestration/agent-view-send.d.ts +7 -0
  274. package/dist/orchestration/agent-view-send.js +12 -0
  275. package/dist/orchestration/benchmark-session-webhook.d.ts +19 -0
  276. package/dist/orchestration/benchmark-session-webhook.js +130 -0
  277. package/dist/orchestration/conversation-request.d.ts +39 -1
  278. package/dist/orchestration/conversation-request.js +71 -15
  279. package/dist/orchestration/interactions/answer-question.d.ts +16 -0
  280. package/dist/orchestration/interactions/answer-question.js +38 -0
  281. package/dist/orchestration/interactions/ask-user-question.d.ts +2 -3
  282. package/dist/orchestration/interactions/ask-user-question.js +1 -3
  283. package/dist/orchestration/interactions/ask-user-resume.d.ts +1 -3
  284. package/dist/orchestration/interactions/ask-user-resume.js +2 -14
  285. package/dist/orchestration/interactions/interaction-handlers.js +6 -35
  286. package/dist/orchestration/interactions/plan-response.d.ts +2 -1
  287. package/dist/orchestration/interactions/plan-response.js +2 -2
  288. package/dist/orchestration/orchestrator.d.ts +1 -7
  289. package/dist/orchestration/orchestrator.js +2 -11
  290. package/dist/orchestration/resume-dispatcher.d.ts +0 -22
  291. package/dist/orchestration/resume-dispatcher.js +8 -72
  292. package/dist/orchestration/routing/commands/cancel.d.ts +1 -7
  293. package/dist/orchestration/routing/commands/cancel.js +17 -37
  294. package/dist/orchestration/routing/commands/channel.js +1 -1
  295. package/dist/orchestration/routing/commands/device.js +1 -1
  296. package/dist/orchestration/routing/commands/index.d.ts +0 -7
  297. package/dist/orchestration/routing/commands/index.js +1 -9
  298. package/dist/orchestration/routing/commands/mode.js +7 -7
  299. package/dist/orchestration/routing/commands/nvtop.js +1 -1
  300. package/dist/orchestration/routing/commands/sendfile.js +1 -1
  301. package/dist/orchestration/routing/commands/status.js +8 -14
  302. package/dist/orchestration/routing/hook-bridge-subscribers.d.ts +4 -1
  303. package/dist/orchestration/routing/hook-bridge-subscribers.js +19 -12
  304. package/dist/orchestration/routing/hook-bridge.d.ts +3 -3
  305. package/dist/orchestration/routing/hook-bridge.js +9 -9
  306. package/dist/orchestration/routing/message-router.js +2 -25
  307. package/dist/orchestration/routing/webhook.js +24 -350
  308. package/dist/orchestration/session-events.d.ts +13 -0
  309. package/dist/orchestration/session-events.js +8 -0
  310. package/dist/orchestration/session-gateway.d.ts +4 -2
  311. package/dist/orchestration/session-gateway.js +17 -12
  312. package/dist/orchestration/session-retention-controller.d.ts +5 -2
  313. package/dist/orchestration/session-retention-controller.js +7 -4
  314. package/dist/orchestration/status-helpers.d.ts +1 -4
  315. package/dist/orchestration/status-helpers.js +3 -5
  316. package/dist/orchestration/team-delivery.d.ts +64 -0
  317. package/dist/orchestration/team-delivery.js +224 -0
  318. package/dist/orchestration/team-state.d.ts +48 -0
  319. package/dist/orchestration/team-state.js +146 -0
  320. package/dist/orchestration/team-webhook.d.ts +48 -0
  321. package/dist/orchestration/team-webhook.js +295 -0
  322. package/dist/orchestration/transcript-sink.d.ts +18 -4
  323. package/dist/orchestration/transcript-sink.js +31 -3
  324. package/dist/orchestration/turn/background-hold.d.ts +2 -2
  325. package/dist/orchestration/turn/background-hold.js +1 -1
  326. package/dist/orchestration/turn/hold-render-platform.d.ts +2 -2
  327. package/dist/orchestration/turn/hold-render-platform.js +2 -2
  328. package/dist/orchestration/turn/hold-render-web.d.ts +3 -3
  329. package/dist/orchestration/turn/hold-render-web.js +2 -2
  330. package/dist/orchestration/turn/terminal.d.ts +5 -2
  331. package/dist/orchestration/turn/terminal.js +11 -10
  332. package/dist/orchestration/turn/turn.d.ts +13 -1
  333. package/dist/orchestration/turn/turn.js +58 -15
  334. package/dist/platform/adapters/composite-adapter.d.ts +2 -0
  335. package/dist/platform/adapters/composite-adapter.js +7 -4
  336. package/dist/platform/adapters/feishu.d.ts +6 -0
  337. package/dist/platform/adapters/feishu.js +50 -4
  338. package/dist/platform/index.d.ts +1 -1
  339. package/dist/platform/index.js +1 -1
  340. package/dist/platform/tui/protocol.d.ts +2 -2
  341. package/dist/platform/types.d.ts +3 -3
  342. package/dist/platform/types.js +3 -3
  343. package/dist/store/conversation-history-reader.js +17 -3
  344. package/dist/store/conversation-history-repo.d.ts +18 -4
  345. package/dist/store/conversation-history-repo.js +14 -5
  346. package/dist/store/conversation-ledger-repo.js +1 -16
  347. package/dist/store/execution-repo.d.ts +17 -40
  348. package/dist/store/execution-repo.js +46 -116
  349. package/dist/store/hook-registry.d.ts +4 -16
  350. package/dist/store/hook-registry.js +5 -65
  351. package/dist/store/plugin-sync.js +4 -0
  352. package/dist/store/profile-repo.js +1 -1
  353. package/dist/store/prompt-migration-replacements.d.ts +0 -1
  354. package/dist/store/prompt-migration-replacements.js +0 -49
  355. package/dist/store/retention-candidate-repo.d.ts +2 -0
  356. package/dist/store/retention-candidate-repo.js +5 -0
  357. package/dist/store/schedule-repo.d.ts +3 -15
  358. package/dist/store/schedule-repo.js +18 -4
  359. package/dist/store/session-registry-journal.d.ts +15 -0
  360. package/dist/store/session-registry-journal.js +68 -10
  361. package/dist/store/session-registry-repo.d.ts +13 -0
  362. package/dist/store/session-registry-repo.js +74 -21
  363. package/dist/store/session-totals.d.ts +3 -3
  364. package/dist/store/session-totals.js +3 -3
  365. package/dist/store/team-outbox-repo.d.ts +20 -0
  366. package/dist/store/team-outbox-repo.js +39 -0
  367. package/dist/store/tool-image-files.d.ts +12 -0
  368. package/dist/store/tool-image-files.js +40 -0
  369. package/dist/store/version-migrations.d.ts +31 -8
  370. package/dist/store/version-migrations.js +307 -87
  371. package/dist/store/waitpoint-repo.d.ts +0 -2
  372. package/dist/tui/App.js +1 -1
  373. package/dist/tui/components/Dashboard.js +0 -8
  374. package/dist/tui/components/InputBox.js +1 -7
  375. package/dist/tui/components/StatusLine.js +1 -1
  376. package/dist/tui/hooks/useDashboardData.d.ts +1 -1
  377. package/dist/tui/hooks/useDashboardData.js +0 -4
  378. package/dist/tui/hooks/useNotifications.d.ts +1 -1
  379. package/dist/tui/slash-commands.js +1 -4
  380. package/package.json +4 -5
  381. package/web/dist/assets/index-BU_kY1rV.js +449 -0
  382. package/web/dist/assets/{index-zvUjPRjt.js → index-CDjsmgsy.js} +1 -1
  383. package/web/dist/assets/index-DzPDbcY1.css +1 -0
  384. package/web/dist/index.html +2 -2
  385. package/defaults/config/hooks/02-tasks-yaml-guard.json +0 -11
  386. package/defaults/config/hooks/11-task-status-check.json +0 -14
  387. package/defaults/config/thread-templates/agents/coder-reviewer.json +0 -17
  388. package/defaults/config/thread-templates/agents/coder.json +0 -17
  389. package/defaults/config/thread-templates/agents/direct-review.json +0 -14
  390. package/defaults/config/thread-templates/agents/direct-web.json +0 -14
  391. package/defaults/config/thread-templates/agents/director.json +0 -11
  392. package/defaults/config/thread-templates/agents/doc-reviewer.json +0 -13
  393. package/defaults/config/thread-templates/agents/doc-writer.json +0 -24
  394. package/defaults/config/thread-templates/agents/executor-reviewer.json +0 -13
  395. package/defaults/config/thread-templates/agents/executor.json +0 -24
  396. package/defaults/config/thread-templates/agents/main.json +0 -14
  397. package/defaults/config/thread-templates/agents/manager.json +0 -14
  398. package/defaults/config/thread-templates/agents/scheduler-main.json +0 -13
  399. package/defaults/config/thread-templates/shells/worker-review.json +0 -12
  400. package/defaults/config/thread-templates/templates/coder-review.json +0 -20
  401. package/defaults/config/thread-templates/templates/default.json +0 -10
  402. package/defaults/config/thread-templates/templates/doc-review.json +0 -6
  403. package/defaults/config/thread-templates/templates/execute-review.json +0 -6
  404. package/defaults/config/thread-templates/templates/manager.json +0 -11
  405. package/defaults/config/thread-templates/templates/scheduler.json +0 -10
  406. package/defaults/hooks/task-status-check.mjs +0 -166
  407. package/defaults/hooks/tasks-yaml-guard.mjs +0 -225
  408. package/defaults/plugins/cortex-system/skills/task/SKILL.md +0 -547
  409. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +0 -505
  410. package/defaults/prompts/directives/coder-reviewer.md +0 -7
  411. package/defaults/prompts/directives/coder.md +0 -7
  412. package/defaults/prompts/directives/director.md +0 -7
  413. package/defaults/prompts/directives/doc-reviewer.md +0 -6
  414. package/defaults/prompts/directives/doc-writer.md +0 -7
  415. package/defaults/prompts/directives/executor-reviewer.md +0 -6
  416. package/defaults/prompts/directives/executor.md +0 -7
  417. package/defaults/prompts/directives/manager.md +0 -24
  418. package/defaults/prompts/systemPrompts/coder.md +0 -10
  419. package/defaults/prompts/systemPrompts/worker.md +0 -10
  420. package/defaults/rules/task-system.md +0 -53
  421. package/dist/core/task-node.d.ts +0 -7
  422. package/dist/core/task-node.js +0 -21
  423. package/dist/core/task-parser.d.ts +0 -86
  424. package/dist/core/task-parser.js +0 -436
  425. package/dist/core/types/thread-types.d.ts +0 -506
  426. package/dist/domain/benchmark/production-evidence-topology.d.ts +0 -14
  427. package/dist/domain/benchmark/production-evidence-topology.js +0 -257
  428. package/dist/domain/mcp/tools/manager-qa.d.ts +0 -4
  429. package/dist/domain/mcp/tools/manager-qa.js +0 -63
  430. package/dist/domain/mcp/tools/task-monitor.d.ts +0 -3
  431. package/dist/domain/mcp/tools/task-monitor.js +0 -92
  432. package/dist/domain/mcp/tools/thread-ops.js +0 -73
  433. package/dist/domain/scheduling/jobs/register-thread-session.d.ts +0 -15
  434. package/dist/domain/scheduling/jobs/register-thread-session.js +0 -32
  435. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +0 -30
  436. package/dist/domain/scheduling/jobs/target-dispatch.js +0 -33
  437. package/dist/domain/scheduling/jobs/task-archive.d.ts +0 -2
  438. package/dist/domain/scheduling/jobs/task-archive.js +0 -16
  439. package/dist/domain/scheduling/jobs/task-dispatch.d.ts +0 -12
  440. package/dist/domain/scheduling/jobs/task-dispatch.js +0 -402
  441. package/dist/domain/tasks/acceptance-ledger.d.ts +0 -39
  442. package/dist/domain/tasks/acceptance-ledger.js +0 -133
  443. package/dist/domain/tasks/archiver.d.ts +0 -10
  444. package/dist/domain/tasks/archiver.js +0 -133
  445. package/dist/domain/tasks/claim-recovery.d.ts +0 -9
  446. package/dist/domain/tasks/claim-recovery.js +0 -54
  447. package/dist/domain/tasks/dispatch-utils.d.ts +0 -117
  448. package/dist/domain/tasks/dispatcher.d.ts +0 -49
  449. package/dist/domain/tasks/dispatcher.js +0 -305
  450. package/dist/domain/tasks/lint.d.ts +0 -12
  451. package/dist/domain/tasks/lint.js +0 -130
  452. package/dist/domain/tasks/mutator.d.ts +0 -39
  453. package/dist/domain/tasks/mutator.js +0 -176
  454. package/dist/domain/tasks/production-topology-ledger.d.ts +0 -106
  455. package/dist/domain/tasks/production-topology-ledger.js +0 -161
  456. package/dist/domain/tasks/system/task-cli.d.ts +0 -7
  457. package/dist/domain/tasks/system/task-cli.js +0 -991
  458. package/dist/domain/tasks/system/task-completion.d.ts +0 -44
  459. package/dist/domain/tasks/system/task-completion.js +0 -262
  460. package/dist/domain/tasks/system/task-file-input.d.ts +0 -10
  461. package/dist/domain/tasks/system/task-file-input.js +0 -53
  462. package/dist/domain/tasks/system/task-id-utils.d.ts +0 -24
  463. package/dist/domain/tasks/system/task-id-utils.js +0 -90
  464. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +0 -40
  465. package/dist/domain/tasks/system/task-lifecycle-edit.js +0 -419
  466. package/dist/domain/tasks/system/task-lock.d.ts +0 -44
  467. package/dist/domain/tasks/system/task-lock.js +0 -137
  468. package/dist/domain/tasks/system/task-mutations.d.ts +0 -86
  469. package/dist/domain/tasks/system/task-mutations.js +0 -336
  470. package/dist/domain/tasks/system/task-state.d.ts +0 -140
  471. package/dist/domain/tasks/system/task-state.js +0 -287
  472. package/dist/domain/threads/artifact-io.d.ts +0 -4
  473. package/dist/domain/threads/artifact-io.js +0 -57
  474. package/dist/domain/threads/contract.d.ts +0 -17
  475. package/dist/domain/threads/contract.js +0 -54
  476. package/dist/domain/threads/evidence-context.d.ts +0 -2
  477. package/dist/domain/threads/evidence-context.js +0 -40
  478. package/dist/domain/threads/hook-runner.d.ts +0 -7
  479. package/dist/domain/threads/hook-runner.js +0 -237
  480. package/dist/domain/threads/index.d.ts +0 -7
  481. package/dist/domain/threads/index.js +0 -13
  482. package/dist/domain/threads/pending-user-inputs.d.ts +0 -3
  483. package/dist/domain/threads/pending-user-inputs.js +0 -33
  484. package/dist/domain/threads/prompt-builder.d.ts +0 -55
  485. package/dist/domain/threads/prompt-builder.js +0 -245
  486. package/dist/domain/threads/runner.d.ts +0 -150
  487. package/dist/domain/threads/runner.js +0 -832
  488. package/dist/domain/threads/shell-templates.d.ts +0 -9
  489. package/dist/domain/threads/shell-templates.js +0 -108
  490. package/dist/domain/threads/state-machine.d.ts +0 -96
  491. package/dist/domain/threads/state-machine.js +0 -646
  492. package/dist/domain/threads/template-loader.d.ts +0 -37
  493. package/dist/domain/threads/template-loader.js +0 -487
  494. package/dist/domain/threads/template-validate.d.ts +0 -287
  495. package/dist/domain/threads/template-validate.js +0 -575
  496. package/dist/domain/threads/template-validate.parity.d.ts +0 -1
  497. package/dist/domain/threads/template-validate.parity.js +0 -39
  498. package/dist/domain/threads/template-writer.d.ts +0 -57
  499. package/dist/domain/threads/template-writer.js +0 -126
  500. package/dist/domain/threads/thread-transcript.d.ts +0 -60
  501. package/dist/domain/threads/thread-transcript.js +0 -117
  502. package/dist/domain/threads/tree.d.ts +0 -46
  503. package/dist/domain/threads/tree.js +0 -196
  504. package/dist/domain/threads/utils.d.ts +0 -24
  505. package/dist/domain/threads/utils.js +0 -55
  506. package/dist/domain/ui-service/mutate/tasks.d.ts +0 -23
  507. package/dist/domain/ui-service/mutate/tasks.js +0 -58
  508. package/dist/domain/ui-service/mutate/thread-templates.d.ts +0 -4
  509. package/dist/domain/ui-service/mutate/thread-templates.js +0 -46
  510. package/dist/domain/ui-service/mutate/threads.d.ts +0 -4
  511. package/dist/domain/ui-service/mutate/threads.js +0 -19
  512. package/dist/domain/ui-service/query/task-verification.d.ts +0 -2
  513. package/dist/domain/ui-service/query/task-verification.js +0 -58
  514. package/dist/domain/ui-service/query/tasks.d.ts +0 -3
  515. package/dist/domain/ui-service/query/tasks.js +0 -73
  516. package/dist/domain/ui-service/query/thread-template-detail.d.ts +0 -2
  517. package/dist/domain/ui-service/query/thread-template-detail.js +0 -57
  518. package/dist/domain/ui-service/query/thread-templates.d.ts +0 -15
  519. package/dist/domain/ui-service/query/thread-templates.js +0 -79
  520. package/dist/domain/ui-service/query/threads.d.ts +0 -3
  521. package/dist/domain/ui-service/query/threads.js +0 -180
  522. package/dist/hooks/task-status-check.mjs +0 -166
  523. package/dist/hooks/tasks-yaml-guard.mjs +0 -225
  524. package/dist/orchestration/dispatch-reconciler.d.ts +0 -1
  525. package/dist/orchestration/dispatch-reconciler.js +0 -19
  526. package/dist/orchestration/human-answer-backstop.d.ts +0 -36
  527. package/dist/orchestration/human-answer-backstop.js +0 -69
  528. package/dist/orchestration/manager-qa.d.ts +0 -66
  529. package/dist/orchestration/manager-qa.js +0 -356
  530. package/dist/orchestration/routing/commands/dispatch.d.ts +0 -2
  531. package/dist/orchestration/routing/commands/dispatch.js +0 -48
  532. package/dist/orchestration/routing/commands/task.d.ts +0 -4
  533. package/dist/orchestration/routing/commands/task.js +0 -140
  534. package/dist/orchestration/routing/commands/thread-handlers.d.ts +0 -2
  535. package/dist/orchestration/routing/commands/thread-handlers.js +0 -152
  536. package/dist/orchestration/thread-callback.d.ts +0 -107
  537. package/dist/orchestration/thread-callback.js +0 -555
  538. package/dist/orchestration/thread-delivery.d.ts +0 -40
  539. package/dist/orchestration/thread-delivery.js +0 -76
  540. package/dist/orchestration/thread-executor.d.ts +0 -25
  541. package/dist/orchestration/thread-executor.js +0 -180
  542. package/dist/orchestration/thread-input.d.ts +0 -15
  543. package/dist/orchestration/thread-input.js +0 -50
  544. package/dist/orchestration/thread-notices.d.ts +0 -43
  545. package/dist/orchestration/thread-notices.js +0 -195
  546. package/dist/orchestration/thread-run/index.d.ts +0 -3
  547. package/dist/orchestration/thread-run/index.js +0 -2
  548. package/dist/orchestration/thread-run/render-summary.d.ts +0 -57
  549. package/dist/orchestration/thread-run/render-summary.js +0 -109
  550. package/dist/orchestration/thread-run/render-task.d.ts +0 -94
  551. package/dist/orchestration/thread-run/render-task.js +0 -154
  552. package/dist/orchestration/thread-run/settle.d.ts +0 -11
  553. package/dist/orchestration/thread-run/settle.js +0 -18
  554. package/dist/orchestration/thread-run/thread-run.d.ts +0 -114
  555. package/dist/orchestration/thread-run/thread-run.js +0 -181
  556. package/dist/orchestration/thread-run/thread-surface.d.ts +0 -41
  557. package/dist/orchestration/thread-run/thread-surface.js +0 -23
  558. package/dist/orchestration/thread-run/verdict.d.ts +0 -11
  559. package/dist/orchestration/thread-run/verdict.js +0 -20
  560. package/dist/store/plugin-retirement.d.ts +0 -37
  561. package/dist/store/plugin-retirement.js +0 -144
  562. package/dist/store/task-repo.d.ts +0 -43
  563. package/dist/store/task-repo.js +0 -143
  564. package/dist/store/thread-repo.d.ts +0 -65
  565. package/dist/store/thread-repo.js +0 -294
  566. package/dist/tui/components/DashboardTasksTab.d.ts +0 -12
  567. package/dist/tui/components/DashboardTasksTab.js +0 -196
  568. package/dist/tui/components/DashboardThreadsTab.d.ts +0 -11
  569. package/dist/tui/components/DashboardThreadsTab.js +0 -96
  570. package/web/dist/assets/index-C9sEss8T.css +0 -1
  571. package/web/dist/assets/index-fVf_wSMQ.js +0 -447
  572. /package/defaults/config/{thread-templates/agents → environments}/creative.json +0 -0
  573. /package/dist/core/types/{thread-types.js → benchmark-types.js} +0 -0
  574. /package/dist/domain/{threads/template-resolver.d.ts → agents/environments/prompt-includes.d.ts} +0 -0
@@ -1,832 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { threadStore } from '../../store/thread-repo.js';
3
- import { resolveNextStep, buildReadyStepPrompt, beginStepSession, recordStepResult, evaluateTransitions, formatEndpoint, completeThread, failThread, markThreadRateLimited, abortThread, peekPendingControl, clearPendingControl, tryEnterWaiting, checkContractBudget, isAdHocThread, getSessionKey, getRootThreadId, getTemplate, readArtifact, resolveSystemVars, } from './index.js';
4
- import { getActiveProfile, resolveRateLimitProvider, } from '../agents/index.js';
5
- import { resolveRunConfig } from '../runs/config-resolver.js';
6
- import { isApiRateLimitError, isRetryableError } from '../agents/config.js';
7
- import { activateOutageWindow, isProviderRateLimited, isProviderUsageRateLimited, } from '../costs/rate-limit-throttle.js';
8
- import { removeThreadResume } from '../costs/resume-registry.js';
9
- import { recordThreadResume } from '../runs/observers/resume-recorder.js';
10
- import { Icons } from '../../core/icons.js';
11
- import { engines } from '../runs/engines.js';
12
- import * as executionRegistry from '../executions/registry.js';
13
- import { sessionStore } from '../../store/session-registry-repo.js';
14
- import { formatDurationCompact } from '../../core/utils.js';
15
- import { getSettings } from '../../core/settings.js';
16
- import { runRegistry } from '../../core/run-registry.js';
17
- import { startRun } from '../runs/service.js';
18
- import { fromAgentSlot } from '../runs/spec-loader.js';
19
- import { executeLifecycleHooks } from './hook-runner.js';
20
- import { createToolTrace } from '../../platform/tool-trace.js';
21
- import { conversationHistory } from '../../store/conversation-history-repo.js';
22
- import { createStepTranscriptRecorder } from './thread-transcript.js';
23
- import { ctx as jobCtx } from '../scheduling/job-registry.js';
24
- import { createLogger } from '../../core/log.js';
25
- import { t } from '../../core/i18n.js';
26
- const log = createLogger('thread-runner');
27
- const OUTAGE_BACKOFF_MS = [5, 15, 45].map((minutes) => minutes * 60_000);
28
- const OUTAGE_MAX_RESUMES = OUTAGE_BACKOFF_MS.length;
29
- /** Validate thread, load template/metadata, init the aggregating OutputStream. */
30
- function initThreadContext(threadId, opts) {
31
- const thread = threadStore.get(threadId);
32
- if (!thread)
33
- throw new Error(`Thread not found: ${threadId}`);
34
- const template = thread.templateName ? (getTemplate(thread.templateName) || null) : null;
35
- // The aggregating OutputStream is opened by the caller (it owns the Destination and the
36
- // anchor message); the runner only emits and flushes on it.
37
- return {
38
- thread, template, meta: thread.metadata, stream: opts.stream, lastAgentResult: null, totalNumTurns: 0,
39
- stopReason: null,
40
- };
41
- }
42
- async function executeConfiguredLifecycleHooks(ctx, threadId, phase, configs, opts, previousAgent, logSuffix) {
43
- if (ctx.template?.disableHooks === true)
44
- return;
45
- await executeLifecycleHooks(threadId, phase, configs, opts, previousAgent, logSuffix);
46
- }
47
- /** Resolve next step, post boundary notifications, update the status message.
48
- * Returns null if the loop should break (cancelled, no next step). */
49
- async function resolveAndNotifyStep(threadId, ctx, opts) {
50
- // Check if thread was cancelled externally
51
- const current = threadStore.get(threadId);
52
- if (!current || current.status === 'cancelled')
53
- return null;
54
- // Resolve the next step
55
- const nextStep = resolveNextStep(threadId);
56
- if (!nextStep) {
57
- await completeThread(threadId);
58
- return null;
59
- }
60
- const { agentSlotId, agentConfig, isFirstStep, stage } = nextStep;
61
- const threadRecord = threadStore.get(threadId);
62
- const multiAgent = Object.keys(threadRecord.agents).length > 1;
63
- const label = formatEndpoint(agentSlotId, stage);
64
- const prevStep = threadRecord.steps[threadRecord.steps.length - 1];
65
- const prevLabel = prevStep ? formatEndpoint(prevStep.agentSlotId, prevStep.stage) : null;
66
- // Post step boundary notification for multi-agent threads via OutputStream
67
- if (ctx.stream && multiAgent && !isFirstStep) {
68
- ctx.stream.emitText(`${Icons.arrowRight} ${t('notice.thread.stepStarting', { n: threadRecord.currentStepIndex + 1, label: `*${label}*`, prev: prevLabel ?? '?' })}`);
69
- }
70
- // Report the step boundary. The surface owner decides whether it renders a status line
71
- // (previously: multi-agent AND no caller-supplied progress renderer). Awaiting only when the
72
- // owner actually returned work keeps the pre-refactor ordering byte-for-byte.
73
- const rendered = opts.surface.onStepStarted({
74
- stepNumber: threadRecord.currentStepIndex + 1,
75
- label, prevLabel, multiAgent, isFirstStep,
76
- });
77
- if (rendered) {
78
- try {
79
- await rendered;
80
- }
81
- catch { }
82
- }
83
- return { agentSlotId, agentConfig, isFirstStep, multiAgent, stage };
84
- }
85
- function resolveEffectiveProfileName(configuredProfile, meta, channel) {
86
- return configuredProfile === '__active__'
87
- ? (meta?.profileOverride || getActiveProfile(channel))
88
- : configuredProfile;
89
- }
90
- /**
91
- * The profile for one step. D5: name, backend, provider and mode all come out of one resolution —
92
- * `resolveRunConfig` keeps an unknown name intact and hands back a profile borrowing the channel's
93
- * backend, preserving the "open the execution record, then let the run reject the name" ordering.
94
- */
95
- function resolveStepProfile(profileName, channel) {
96
- const { profile, resolved } = resolveRunConfig({ channel, override: profileName });
97
- return {
98
- profile,
99
- backend: profile.backend,
100
- provider: resolved ? resolveRateLimitProvider(profile) : null,
101
- };
102
- }
103
- function resolveActiveStepProvider(thread, channel) {
104
- const slot = thread.agents[thread.activeAgent];
105
- if (!slot)
106
- return null;
107
- try {
108
- const profileName = resolveEffectiveProfileName(slot.profile, thread.metadata, channel);
109
- const { profile, resolved } = resolveRunConfig({ channel, override: profileName });
110
- return resolved ? resolveRateLimitProvider(profile) : null;
111
- }
112
- catch {
113
- return null;
114
- }
115
- }
116
- /** Build prompt, resolve session config, profile and track/backend ids, and start the transcript
117
- * recorder. The execution record itself is opened later by `startRun` (plan D8).
118
- * Returns a fully-populated StepContext — no placeholder fields. */
119
- async function buildStepConfig(threadId, stepInfo, ctx, opts) {
120
- const { agentSlotId, agentConfig, isFirstStep, multiAgent, stage } = stepInfo;
121
- // Interrupted-step rerun: a pending interruptedBackendSessionId (set at interruption, consumed
122
- // by beginStepSession below) switches the prompt to the continuation reminder.
123
- const interruptedResume = !!threadStore.get(threadId)?.agents[agentSlotId]?.interruptedBackendSessionId;
124
- // Build the prompt after files for the current buffered-input snapshot are ready. ORDER MATTERS:
125
- // prompt construction reads slot.sessionId truthiness as "resuming a persistent session" — it
126
- // must run BEFORE beginStepSession mints the track id, or a fresh slot would skip its directive.
127
- const prompt = await buildReadyStepPrompt(threadId, agentConfig, stage, {
128
- interruptedResume,
129
- });
130
- // Session identity (track/backend decoupling): mint + persist the stable track id on the slot
131
- // (the UI transcript key, visible to threads.get while the step RUNS) and resolve the backend
132
- // resume target. Publishes thread.step.started.
133
- const { trackSessionId, resumeSessionId } = await beginStepSession(threadId, agentSlotId, stage);
134
- // Thread steps use a thread-scoped session key.
135
- const sessionKey = getSessionKey(threadId, agentSlotId);
136
- const profileName = resolveEffectiveProfileName(agentConfig.profile, ctx.meta, opts.channel);
137
- const resolved = resolveStepProfile(profileName, opts.channel);
138
- const profile = resolved.profile;
139
- const profileBackend = resolved.backend;
140
- const rateLimitProvider = resolved.provider;
141
- // The execution record is opened by `startRun` (via executeAndAwaitAgent), which owns the
142
- // registry registration and teardown (plan D8). `execution.id` is filled in once the run starts.
143
- const execution = { id: '' };
144
- const recorder = createStepTranscriptRecorder(conversationHistory, trackSessionId, (ev) => {
145
- jobCtx.bus?.publish({
146
- type: 'session.message', sessionId: trackSessionId, channel: opts.channel,
147
- role: ev.role, text: ev.text ?? '',
148
- ...(ev.toolName !== undefined ? { toolName: ev.toolName } : {}),
149
- ...(ev.toolInput !== undefined ? { toolInput: ev.toolInput } : {}),
150
- ...(ev.toolDevice !== undefined ? { toolDevice: ev.toolDevice } : {}),
151
- ...(ev.noticeLevel !== undefined ? { noticeLevel: ev.noticeLevel } : {}),
152
- ...(ev.subagentId !== undefined ? { subagentId: ev.subagentId } : {}),
153
- ...(ev.subagentSpawns !== undefined ? { subagentSpawns: ev.subagentSpawns } : {}),
154
- ...(ev.subagentType !== undefined ? { subagentType: ev.subagentType } : {}),
155
- ...(ev.subagentDescription !== undefined ? { subagentDescription: ev.subagentDescription } : {}),
156
- ...(ev.subagentModel !== undefined ? { subagentModel: ev.subagentModel } : {}), ts: ev.ts,
157
- });
158
- }, () => jobCtx.bus?.publish({
159
- type: 'session.debug.updated', sessionId: trackSessionId, channel: opts.channel,
160
- }));
161
- // The step prompt opens the turn — recorded now so a reload mid-step shows it.
162
- recorder.recordUser(prompt);
163
- return {
164
- agentSlotId, agentConfig, isFirstStep, multiAgent, stage,
165
- prompt, interruptedResume, sawActivity: false,
166
- resumeSessionId, trackSessionId, sessionKey,
167
- sessionName: await sessionStore.generateSessionName(),
168
- profileName, profileBackend, profile, rateLimitProvider, execution,
169
- stepStartTime: new Date().toISOString(),
170
- recorder,
171
- };
172
- }
173
- /** Resolve onAssistantMessage/onProgress callbacks and mark slot as running.
174
- * Returns the callbacks instead of mutating the StepContext. */
175
- function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
176
- const { agentSlotId, multiAgent, stage } = stepCtx;
177
- const threadRecord = threadStore.get(threadId);
178
- const slot = threadRecord.agents[agentSlotId];
179
- const stream = ctx.stream;
180
- const label = formatEndpoint(agentSlotId, stage);
181
- // Aggregate assistant output into the thread-runner's OutputStream; prefix only for multi-agent.
182
- const slotPrefix = multiAgent ? `*[${label}]*` : null;
183
- const baseAssistantMessage = (text) => { stream.emitText(slotPrefix ? `${slotPrefix} ${text}` : text); };
184
- // Tool trace (env-gated): emit a compact per-tool line to the runner's stream when
185
- // CORTEX_SHOW_TOOL_CALLS is on, while STILL firing any caller-supplied onToolUse
186
- // (interactive plan/ask capture). Both must run — compose, don't choose — so dispatch /
187
- // scheduled / webhook threads stream tool calls like a direct session. The trace fires
188
- // first; the caller (interactive) fires after, preserving the onToolUse-before-ask ordering.
189
- const callerOnToolUse = opts.surface.onToolUse ?? null;
190
- const toolTrace = createToolTrace(stream, { slotPrefix });
191
- const streamAssistantMessage = toolTrace
192
- ? (text) => { toolTrace.flush(); baseAssistantMessage(text); }
193
- : baseAssistantMessage;
194
- const traceToolUse = toolTrace
195
- ? (name, input, toolUseId, subagent) => toolTrace.onToolUse(name, input, subagent, toolUseId)
196
- : null;
197
- const composedToolUse = traceToolUse && callerOnToolUse
198
- ? (name, input, toolUseId, subagent) => {
199
- traceToolUse(name, input, toolUseId, subagent);
200
- callerOnToolUse(name, input);
201
- }
202
- : (traceToolUse ?? callerOnToolUse);
203
- // Transcript recording: mirror the direct path — every assistant message + tool call is
204
- // appended to conversation-history IMMEDIATELY (keyed by the step's track sessionId) and
205
- // published as a session.message delta, so the UI streams the running step and a reload
206
- // shows everything so far. Recording wraps (never replaces) the display callbacks, so
207
- // streaming/tool-trace behaviour is unchanged.
208
- const recorder = stepCtx.recorder;
209
- const onAssistantMessage = (text, _blockId, noticeLevel, _noticeAction, subagent) => {
210
- if (text)
211
- stepCtx.sawActivity = true;
212
- // A subagent's prose never reaches the thread's shared stream: the step's own output is what
213
- // downstream agents read, and interleaving a child's working notes into it would corrupt the
214
- // handoff. Its activity still shows on the trace line (see tool-trace).
215
- if (!subagent)
216
- streamAssistantMessage(text);
217
- if (text && subagent)
218
- recorder.recordAssistant(text, noticeLevel, subagent);
219
- else if (text)
220
- recorder.recordAssistant(text, noticeLevel);
221
- };
222
- const onToolUse = (name, input, toolUseId, subagent) => {
223
- stepCtx.sawActivity = true;
224
- composedToolUse?.(name, input, toolUseId, subagent);
225
- if (subagent)
226
- recorder.recordTool(name, input, toolUseId, subagent);
227
- else
228
- recorder.recordTool(name, input, toolUseId);
229
- };
230
- const onToolResult = (toolUseId, content, isError) => {
231
- recorder.recordToolResult(toolUseId, content, isError);
232
- };
233
- // In-step progress goes out unconditionally; the surface owner decides what (if anything) it
234
- // renders — the scheduler's own progress line, the multi-agent status line, or nothing.
235
- const onProgress = (progress) => {
236
- opts.surface.onStepProgress({
237
- stepNumber: threadRecord.currentStepIndex + 1,
238
- label,
239
- multiAgent,
240
- numTurns: progress?.num_turns ?? null,
241
- durationMs: progress?.duration_ms ?? null,
242
- });
243
- };
244
- // Mark agent slot as running
245
- slot.status = 'running';
246
- threadStore.set(threadRecord);
247
- return { onAssistantMessage, onProgress, onToolUse, onToolResult };
248
- }
249
- /** The background policy a thread step runs under. The pre-refactor path left `awaitBackground`
250
- * undefined, so the engine fell back to its inline background policy (settings-gated, thread-keyed).
251
- * Mapping that decision onto the RunRequest preserves the exact same behaviour:
252
- * `'inline'` while the bg-continuation feature is enabled (thread steps always carry a threadId),
253
- * `'none'` when it is disabled. */
254
- function stepBackgroundPolicy() {
255
- return getSettings().bgContinuation ? 'inline' : 'none';
256
- }
257
- /** Build the run request for one thread step from the fully-populated StepContext. The engine pool
258
- * key stays `thr:<threadId>:<slot>` — a step's engine is opened under it and nothing else shares
259
- * it (the interactive paths key on the channel instead). */
260
- export function buildThreadRunRequest(threadId, stepCtx, ctx, opts) {
261
- const { agentConfig, profile } = stepCtx;
262
- const meta = ctx.meta;
263
- const thread = threadStore.get(threadId);
264
- const mcpComposition = agentConfig.mcpComposition;
265
- const resolvedComposition = mcpComposition === undefined ? 'thread-control' : mcpComposition;
266
- const executionKind = meta?.trigger === 'task-dispatch' ? 'dispatch'
267
- : meta?.trigger === 'scheduled' ? 'scheduled'
268
- : 'local';
269
- const spec = fromAgentSlot(agentConfig, { mcpComposition: resolvedComposition });
270
- return {
271
- runId: randomUUID(),
272
- session: {
273
- sessionId: stepCtx.trackSessionId,
274
- backendSessionId: stepCtx.resumeSessionId,
275
- engineKey: stepCtx.sessionKey,
276
- sessionName: stepCtx.sessionName,
277
- },
278
- profile,
279
- spec,
280
- prompt: {
281
- text: stepCtx.prompt,
282
- // First-step files only (never re-attached on an interrupted-session resume).
283
- attachments: stepCtx.isFirstStep && !stepCtx.interruptedResume
284
- ? (opts.files || []).map((file) => ({
285
- mimeType: file.mimetype, path: file.localPath, name: file.name,
286
- }))
287
- : [],
288
- },
289
- context: {
290
- channel: opts.channel,
291
- project: thread?.projectId ?? 'general',
292
- // One trigger for the execution record AND for cost attribution. The pre-refactor path used
293
- // 'thread-step' for the record and nothing for cost; 'thread-step' is the closest single
294
- // value, and `resolveRunRoute` reads it for the per-attempt gateway path.
295
- trigger: meta?.trigger || 'thread-step',
296
- threadId,
297
- threadDepth: meta?.depth ?? 0,
298
- taskId: meta?.taskId ?? null,
299
- taskProject: meta?.taskProject ?? null,
300
- taskGeneration: meta?.dispatchGeneration ?? null,
301
- scheduleTaskId: meta?.scheduleTaskId ?? null,
302
- executionKind,
303
- isUserInitiated: false,
304
- commissionMode: false,
305
- },
306
- policy: {
307
- background: stepBackgroundPolicy(),
308
- recordCost: true,
309
- // Both levels can switch hooks off and neither can switch the other's decision back on:
310
- // the template speaks for the pipeline, the agent for its own environment.
311
- hooks: ctx.template?.disableHooks !== true && agentConfig.disableHooks !== true,
312
- loadRules: agentConfig.loadRules ?? true,
313
- skills: agentConfig.skills,
314
- settingSources: agentConfig.settingSources,
315
- mcpComposition: resolvedComposition,
316
- // Legacy thread surface selector: true only when the agent declared no explicit composition.
317
- useCoreMcp: mcpComposition === undefined,
318
- mcpToolAllowlist: agentConfig.mcpToolAllowlist,
319
- browserCdpEndpoint: null,
320
- // Claude writes a per-turn transcript file unless told not to; only a frozen subagent
321
- // child opts out. `captureTranscriptLogs` defaults to ON, so this must stay true.
322
- captureTranscripts: true,
323
- },
324
- benchmark: {
325
- evidenceContext: meta?.productionBenchmarkEvidenceContext ?? null,
326
- identityDirective: agentConfig.directive ? resolveSystemVars(agentConfig.directive) : '',
327
- rootThreadId: getRootThreadId(ctx.thread),
328
- parentThreadId: meta?.parentThreadId ?? null,
329
- templateName: ctx.thread.templateName,
330
- agentSlotId: stepCtx.agentSlotId,
331
- stage: stepCtx.stage,
332
- preserveUnreportedAccounting: false,
333
- },
334
- };
335
- }
336
- /** Map the run's event stream onto the step's display/transcript callbacks and the
337
- * caller-supplied plan/ask hooks. Assistant prose arrives as `assistant_text` RunEvents, carrying
338
- * its notice classification with it. */
339
- export function createStepObserver(stepCtx, callbacks, opts) {
340
- return {
341
- onEvent(event) {
342
- switch (event.type) {
343
- case 'assistant_text':
344
- // The step callbacks ignore `noticeAction`; it is passed undefined for byte-compat with
345
- // the pre-refactor call, which never had one on the raw assistant_text path.
346
- callbacks.onAssistantMessage?.(event.text, event.blockId, event.noticeLevel, undefined, event.subagent);
347
- return;
348
- case 'tool_use':
349
- callbacks.onToolUse?.(event.name, event.input, event.toolUseId, event.subagent);
350
- return;
351
- case 'tool_result':
352
- callbacks.onToolResult?.(event.toolUseId, event.content, !event.ok);
353
- return;
354
- case 'turn_progress':
355
- callbacks.onProgress?.({ num_turns: event.numTurns, total_cost_usd: null, duration_ms: null });
356
- return;
357
- case 'plan_written':
358
- opts.surface.onPlanWritten?.({ path: event.path, content: event.content, toolUseId: event.toolUseId });
359
- return;
360
- case 'dialog_request':
361
- if (event.kind === 'ask_user') {
362
- opts.surface.onAskUserQuestion?.({
363
- toolUseId: event.dialogId,
364
- questions: event.payload,
365
- });
366
- }
367
- return;
368
- default:
369
- return;
370
- }
371
- },
372
- };
373
- }
374
- /** Run one thread step through `startRun` and attach the interrupted-step identity to the thrown
375
- * error so the provider-outage/rate-limit pause path can resume the backend session. The execution
376
- * record's registration and teardown are entirely owned by the run (plan D8). */
377
- async function executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts) {
378
- const request = buildThreadRunRequest(threadId, stepCtx, ctx, opts);
379
- const run = startRun(request, [createStepObserver(stepCtx, callbacks, opts)]);
380
- stepCtx.execution = { id: run.executionId };
381
- try {
382
- return await run.result;
383
- }
384
- catch (error) {
385
- if (error && typeof error === 'object') {
386
- error.interruptedStep = {
387
- agentSlotId: stepCtx.agentSlotId,
388
- // Mirrors the old `handle.sessionId`: the run's recorded id
389
- // covers test doubles that expose no process reference (and adapters that never emitted
390
- // session_started before the interruption).
391
- backendSessionId: run.backendSessionId ?? null,
392
- sawActivity: stepCtx.sawActivity,
393
- };
394
- }
395
- throw error;
396
- }
397
- }
398
- /** Record step result, register session and update aggregate counters. The execution record itself
399
- * is finalized by the run (startRun owns teardown, plan D8). */
400
- async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
401
- const { agentSlotId, prompt, sessionName, execution, stepStartTime, stage } = stepCtx;
402
- ctx.lastAgentResult = result;
403
- // Record the step result
404
- const stepEndTime = new Date().toISOString();
405
- const stepDurationS = (new Date(stepEndTime).getTime() - new Date(stepStartTime).getTime()) / 1000;
406
- // Rate-limit interruption (graceful path): the API window is exhausted and the throttle is
407
- // active. Do NOT record the step result — leaving currentStepIndex unadvanced so resume
408
- // re-runs THIS step (matches the thrown path). The run has already torn the execution down as
409
- // failed; here we only pause the thread for auto-resume. Require this result's provider throttle
410
- // to be active so another provider cannot create a resume entry whose reset callback will never
411
- // own it. NOTE: the live recorder has already persisted this step's streamed events — an
412
- // interrupted step is partially recorded (honest history); the re-run opens a fresh prompt turn.
413
- if (result?.rateLimited && isProviderRateLimited(result.rateLimitProvider)) {
414
- await handleRateLimitInterruption(threadId, ctx, opts, result.rateLimitProvider ?? null, {
415
- agentSlotId, backendSessionId: result?.sessionId ?? null, sawActivity: stepCtx.sawActivity,
416
- });
417
- return;
418
- }
419
- // Ensure the incrementally-appended transcript is durable before the step is sealed
420
- // (settle never rejects — failed appends are logged and skipped).
421
- await stepCtx.recorder.settle();
422
- await recordStepResult(threadId, agentSlotId, {
423
- sessionId: stepCtx.trackSessionId,
424
- backendSessionId: result?.sessionId || null,
425
- sessionName,
426
- executionId: execution.id,
427
- input: prompt,
428
- startedAt: stepStartTime,
429
- output: result?.finalOutput || null,
430
- costUsd: result?.total_cost_usd || null,
431
- numTurns: result?.num_turns || null,
432
- durationS: stepDurationS,
433
- stage,
434
- });
435
- ctx.totalNumTurns += result?.num_turns || 0;
436
- // Register session under the TRACK id — the same key the live transcript is recorded under
437
- // (sessions.transcript / session.message), so the thread session renders in the UI.
438
- const currentThread = threadStore.get(threadId);
439
- if (sessionName && currentThread) {
440
- await sessionStore.registerSession(sessionName, {
441
- sessionId: stepCtx.trackSessionId,
442
- channel: opts.channel,
443
- backend: stepCtx.profileBackend,
444
- kind: 'local',
445
- origin: 'thread',
446
- label: `[${threadId}:${agentSlotId}]`,
447
- profileName: stepCtx.profileName,
448
- projectId: currentThread.projectId,
449
- });
450
- }
451
- }
452
- /** Pause the thread for auto-resume after a provider throttle interrupted a step. Records the
453
- * thread in the resume registry (drained when its provider window resets) and
454
- * flips it to the non-terminal 'rate_limited' status. Sets ctx.rateLimited so the loop breaks
455
- * and skips completeThread / onEnd. Shared by the graceful (recordStepOutcome) and thrown
456
- * (runThread catch) paths. When the interrupted attempt streamed real activity, its backend
457
- * session id is persisted on the slot so the rerun resumes it instead of restarting the step. */
458
- async function handleRateLimitInterruption(threadId, ctx, opts, provider, interrupted) {
459
- if (!await markThreadRateLimited(threadId, provider))
460
- return false;
461
- ctx.rateLimited = true;
462
- if (interrupted?.backendSessionId && interrupted.sawActivity) {
463
- await threadStore.mutate(threadId, (record) => {
464
- const slot = record.agents[interrupted.agentSlotId];
465
- if (slot)
466
- slot.interruptedBackendSessionId = interrupted.backendSessionId;
467
- });
468
- }
469
- recordThreadResume({
470
- provider, threadId, channel: opts.channel,
471
- userMessage: threadStore.get(threadId)?.userMessage ?? '',
472
- });
473
- return true;
474
- }
475
- /** Decide whether the loop continues; run onTransition hook when transitioning.
476
- * Returns false to break the loop. */
477
- async function evaluateAndTransition(threadId, stepCtx, ctx, opts) {
478
- // Ad-hoc threads: run one agent per invocation, then stop
479
- if (isAdHocThread(threadId))
480
- return false;
481
- // Evaluate transitions for template-based multi-agent
482
- const transition = evaluateTransitions(threadId);
483
- if (!transition.shouldTransition) {
484
- // Why the loop ends, in the engine's own typed terms. A caller that re-derived it from the
485
- // thread record would be inferring what the engine already decided.
486
- ctx.stopReason = transition.reason === 'transition' ? null : transition.reason;
487
- return false;
488
- }
489
- // transition.nextAgent / nextStage are already set on the thread by evaluateTransitions
490
- const prevAgent = stepCtx.agentSlotId;
491
- const fromLabel = formatEndpoint(prevAgent, stepCtx.stage);
492
- const toLabel = formatEndpoint(transition.nextAgent, transition.nextStage ?? null);
493
- await executeConfiguredLifecycleHooks(ctx, threadId, 'transition', {
494
- template: ctx.template?.hooks?.onTransition,
495
- extra: opts.extraHooks?.onTransition,
496
- }, opts, prevAgent, `(${fromLabel} → ${toLabel})`);
497
- return true;
498
- }
499
- /** Read final artifact, flush VM, build the run result. */
500
- async function finalizeThread(threadId, ctx) {
501
- const finalThread = threadStore.get(threadId);
502
- // Final output comes from the artifact file
503
- const artifactContent = readArtifact(threadId);
504
- const finalOutput = artifactContent || ctx.lastAgentResult?.finalOutput || null;
505
- if (ctx.stream && finalOutput) {
506
- ctx.stream.emitText(finalOutput);
507
- await ctx.stream.flush();
508
- }
509
- return {
510
- thread: finalThread,
511
- finalOutput,
512
- totalCostUsd: finalThread.totalCostUsd,
513
- totalNumTurns: ctx.totalNumTurns,
514
- lastAgentResult: ctx.lastAgentResult,
515
- executionId: finalThread.steps[finalThread.steps.length - 1]?.executionId ?? null,
516
- stopReason: ctx.stopReason,
517
- };
518
- }
519
- /** Terminate a thread by agent abort and, BEFORE onEnd hooks run, hand the owning task to the
520
- * caller's onAbort so it can reach a terminal (blocked) state in time (DR-0015 problem 2).
521
- * No-op on the task side for non-dispatch threads (metadata has no taskId) or when the caller
522
- * did not inject onAbort. Exported for unit testing. */
523
- export async function finalizeAbortedThread(threadId, meta, reason, opts) {
524
- await abortThread(threadId, reason);
525
- const taskId = meta?.taskId ?? null;
526
- if (taskId && opts.onAbort) {
527
- await opts.onAbort({ taskId, project: meta?.taskProject ?? null, reason });
528
- }
529
- }
530
- async function claimOutageResume(threadId, error) {
531
- let claimedCount = null;
532
- let capped = false;
533
- await threadStore.mutate(threadId, (record) => {
534
- if (record.status !== 'running' && record.status !== 'rate_limited')
535
- return;
536
- const current = record.metadata?.outageResumeCount ?? 0;
537
- if (current >= OUTAGE_MAX_RESUMES) {
538
- record.status = 'failed';
539
- record.error = error;
540
- record.endedAt = new Date().toISOString();
541
- capped = true;
542
- return;
543
- }
544
- (record.metadata ??= {}).outageResumeCount = current + 1;
545
- claimedCount = current;
546
- });
547
- if (capped) {
548
- await failThread(threadId, error);
549
- removeThreadResume(threadId);
550
- }
551
- return claimedCount;
552
- }
553
- async function failOutageActivation(threadId, providerError, activationError) {
554
- await threadStore.mutate(threadId, (record) => {
555
- const count = record.metadata?.outageResumeCount ?? 0;
556
- if (count > 0)
557
- record.metadata.outageResumeCount = count - 1;
558
- });
559
- const cause = activationError instanceof Error ? activationError.message : String(activationError);
560
- if (threadStore.get(threadId)?.status === 'running') {
561
- await failThread(threadId, `${providerError.message}; outage activation failed: ${cause}`);
562
- }
563
- providerError.cause = activationError;
564
- throw providerError;
565
- }
566
- async function pauseRetryableProviderError(threadId, ctx, opts, error) {
567
- const thread = threadStore.get(threadId);
568
- const resumableStatus = thread?.status === 'running' || thread?.status === 'rate_limited';
569
- if (!thread || !resumableStatus || !isRetryableError(error))
570
- return false;
571
- const provider = error.rateLimitProvider ?? resolveActiveStepProvider(thread, opts.channel);
572
- const interrupted = error.interruptedStep ?? null;
573
- if (isApiRateLimitError(error.message) && isProviderUsageRateLimited(provider)) {
574
- return handleRateLimitInterruption(threadId, ctx, opts, provider, interrupted);
575
- }
576
- const resumeCount = await claimOutageResume(threadId, error.message);
577
- if (resumeCount === null)
578
- return false;
579
- try {
580
- await activateOutageWindow(provider, OUTAGE_BACKOFF_MS[resumeCount]);
581
- }
582
- catch (activationError) {
583
- await failOutageActivation(threadId, error, activationError);
584
- }
585
- return handleRateLimitInterruption(threadId, ctx, opts, provider, interrupted);
586
- }
587
- async function runThread(threadId, opts) {
588
- const ctx = initThreadContext(threadId, opts);
589
- let enteredWaiting = false;
590
- try {
591
- await executeConfiguredLifecycleHooks(ctx, threadId, 'start', {
592
- template: ctx.template?.hooks?.onStart,
593
- extra: opts.extraHooks?.onStart,
594
- }, opts);
595
- while (true) {
596
- const stepInfo = await resolveAndNotifyStep(threadId, ctx, opts);
597
- if (!stepInfo)
598
- break;
599
- const stepCtx = await buildStepConfig(threadId, stepInfo, ctx, opts);
600
- const callbacks = setupStepCallbacks(threadId, stepCtx, ctx, opts);
601
- const result = await executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts);
602
- await recordStepOutcome(threadId, stepCtx, result, ctx, opts);
603
- // Rate-limit pause (graceful path): recordStepOutcome paused the thread. Break out so the
604
- // thread is NOT completed; resume-dispatcher re-enters it when its provider resets.
605
- if (ctx.rateLimited)
606
- break;
607
- // Out-of-band control plane (DR-0015 problem 1): the agent signals abort / split / wait by
608
- // calling the thread_abort / thread_split / thread_wait MCP tools, which write a typed
609
- // metadata.pendingControl on this thread. Read it here at the step boundary — never scan the
610
- // artifact (prose mentioning "[ABORT]" no longer triggers anything). Higher precedence than
611
- // transitions.
612
- const control = peekPendingControl(threadId);
613
- // Agent-initiated abort. Global check. Loop exits → onEnd hook still fires.
614
- if (control?.action === 'abort') {
615
- await clearPendingControl(threadId);
616
- const reason = control.diagnosis ?? null;
617
- // Abort the thread and block its owning task before end hooks inspect task state.
618
- await finalizeAbortedThread(threadId, ctx.meta, reason, opts);
619
- if (ctx.stream) {
620
- const reasonStr = reason ? `: ${reason}` : '';
621
- const abortLabel = formatEndpoint(stepCtx.agentSlotId, stepCtx.stage);
622
- ctx.stream.emitText(`${Icons.stopped} ${t('notice.thread.abortedBy', { label: `*${abortLabel}*` })}${reasonStr}`);
623
- }
624
- break;
625
- }
626
- // Split proposal (DR-0014): the worker called thread_split with a typed subtask array. Leave
627
- // metadata.pendingControl IN PLACE (do NOT clear) and break — the thread terminates and the
628
- // dispatch path (processSplitOutcome) consumes control.subtasks to decompose keep-parent.
629
- if (control?.action === 'split') {
630
- if (ctx.stream) {
631
- const splitLabel = formatEndpoint(stepCtx.agentSlotId, stepCtx.stage);
632
- const n = Array.isArray(control.subtasks) ? control.subtasks.length : 0;
633
- ctx.stream.emitText(`${Icons.arrowRight} ${t('notice.thread.split', { label: `*${splitLabel}*`, n })}`);
634
- }
635
- break;
636
- }
637
- // Parent suspension (DR-0014): the agent called thread_wait. Checked after abort/split,
638
- // before transitions. Three outcomes:
639
- // - live awaited children remain → thread enters 'waiting' (resumed by thread-callback
640
- // when the last child turns terminal); skip onEnd — it fires once, at true termination.
641
- // - all awaited children already terminal (callback won the race) and their results sit
642
- // in pendingMessages → re-enter the loop immediately so the same agent processes them.
643
- // - signal but nothing to wait on or process → fall through to normal transitions.
644
- if (control?.action === 'wait') {
645
- if (await consumeWaitControl(threadId, control)) {
646
- enteredWaiting = true;
647
- // DR-0014 lock hygiene: release any project lock this execution still holds BEFORE
648
- // suspending. A manager that ran `decompose --auto-lock` (which does not auto-release)
649
- // would otherwise hold the lock across the whole child-wait — starving sibling
650
- // managers — and the terminal auto-release can't recover it (re-entry completes under
651
- // a new executionId that no longer matches the original owner). See registry.ts.
652
- await executionRegistry.releaseExecutionLocksAsync(stepCtx.execution.id);
653
- const n = threadStore.get(threadId)?.metadata?.waitingOn?.length ?? 0;
654
- if (ctx.stream)
655
- ctx.stream.emitText(`${Icons.processing} ${t('notice.thread.suspendedThreads', { n })}`);
656
- break;
657
- }
658
- const rec = threadStore.get(threadId);
659
- if (rec?.metadata?.pendingMessages?.length || rec?.metadata?.pendingUserInputs?.length) {
660
- // Ad-hoc parents bypass transition evaluation, so the contract budget breaker
661
- // must gate the re-entry loop here (template threads get it in checkTemplateLimits).
662
- if (rec && checkContractBudget(rec)) {
663
- if (ctx.stream)
664
- ctx.stream.emitText(`${Icons.warning} ${t('notice.thread.budgetExhausted')}`);
665
- }
666
- else {
667
- continue;
668
- }
669
- }
670
- }
671
- if (!await evaluateAndTransition(threadId, stepCtx, ctx, opts))
672
- break;
673
- }
674
- // End means true termination. A suspended or provider-paused run emits it on re-entry.
675
- if (!enteredWaiting && !ctx.rateLimited) {
676
- const threadForEnd = threadStore.get(threadId);
677
- const lastStep = threadForEnd.steps[threadForEnd.steps.length - 1];
678
- await executeConfiguredLifecycleHooks(ctx, threadId, 'end', {
679
- template: ctx.template?.hooks?.onEnd,
680
- extra: opts.extraHooks?.onEnd,
681
- }, opts, lastStep?.agentSlotId);
682
- }
683
- // Only complete if not already in a terminal state (e.g. cancelled during loop). A
684
- // rate-limit pause leaves status='rate_limited', so this guard also skips it.
685
- const threadBeforeComplete = threadStore.get(threadId);
686
- if (threadBeforeComplete && threadBeforeComplete.status === 'running') {
687
- await completeThread(threadId);
688
- }
689
- }
690
- catch (error) {
691
- // Retryable provider failures pause on a synthetic outage window and return normally;
692
- // permanent errors and the fourth transient failure keep the original fail + rethrow path.
693
- if (!await pauseRetryableProviderError(threadId, ctx, opts, error)) {
694
- const thread = threadStore.get(threadId);
695
- if (thread && thread.status === 'running') {
696
- await failThread(threadId, error.message || 'Unknown error');
697
- }
698
- throw error;
699
- }
700
- }
701
- finally {
702
- // Each step's execution record and live-registry entry are owned by its run (`startRun`),
703
- // which tears them down on every terminal path — success, failure or cancellation. The old
704
- // defensive scan over the live-run registry is therefore gone: a run that outlives the loop is
705
- // killed below with the thread's sessions.
706
- // Cleanup thread-specific sessions. Intentionally also runs on suspension (DR-0014):
707
- // a waiting parent holds no live session — the artifact is its durable memory, and
708
- // persistSession slots keep their sessionId so re-entry resumes via --resume.
709
- engines.closeByPrefix(`thr:${threadId}:`);
710
- }
711
- return finalizeThread(threadId, ctx);
712
- }
713
- // --- Continue an existing thread with new user input ---
714
- async function continueThread(threadId, userMessage, opts) {
715
- const thread = threadStore.get(threadId);
716
- if (!thread)
717
- throw new Error(`Thread not found: ${threadId}`);
718
- if (thread.status !== 'running' && thread.status !== 'waiting' && thread.status !== 'rate_limited') {
719
- throw new Error(`Thread ${threadId} is ${thread.status}, cannot continue`);
720
- }
721
- // Update the thread's user message for the new input
722
- await threadStore.mutate(threadId, (t) => {
723
- t.userMessage = userMessage;
724
- t.status = 'running';
725
- // Interrupted-step rerun sends the continuation reminder instead of {{input}} — deliver the
726
- // new user input through the buffered-replies block so it is not silently dropped.
727
- if (Object.values(t.agents).some((slot) => slot.interruptedBackendSessionId)) {
728
- ((t.metadata ??= {}).pendingMessages ??= []).push(userMessage);
729
- }
730
- if (t.metadata) {
731
- t.metadata.interruptedByRateLimit = false;
732
- t.metadata.rateLimitProvider = null;
733
- }
734
- });
735
- return runThread(threadId, opts);
736
- }
737
- /** Consume one wait intent exactly once, preserving its explicit target selectors. */
738
- export async function consumeWaitControl(threadId, control) {
739
- await clearPendingControl(threadId);
740
- return tryEnterWaiting(threadId, control);
741
- }
742
- // --- Resume a rate-limit-paused thread (auto-resume) ---
743
- /** Re-enter a thread paused by a provider throttle (status==='rate_limited'). Like resumeThread,
744
- * the userMessage is NOT overwritten — the thread re-runs its interrupted step from the original
745
- * prompt/contract. Called when the owning provider window resets. */
746
- async function resumeRateLimitedThread(threadId, opts) {
747
- const thread = threadStore.get(threadId);
748
- if (!thread)
749
- throw new Error(`Thread not found: ${threadId}`);
750
- if (thread.status !== 'rate_limited') {
751
- throw new Error(`Thread ${threadId} is ${thread.status}, cannot resume (expected rate_limited)`);
752
- }
753
- await threadStore.mutate(threadId, (t) => {
754
- t.status = 'running';
755
- if (t.metadata) {
756
- t.metadata.interruptedByRateLimit = false;
757
- t.metadata.rateLimitProvider = null;
758
- }
759
- });
760
- return runThread(threadId, opts);
761
- }
762
- // --- Resume a suspended parent thread (DR-0014) ---
763
- /** Re-enter a parent thread that was suspended via [WAIT_CHILDREN]. Unlike continueThread,
764
- * the userMessage is NOT overwritten — the original contract stays in {{input}}; the child
765
- * results arrive through metadata.pendingMessages (injected by the prompt builder). */
766
- async function resumeThread(threadId, opts) {
767
- const thread = threadStore.get(threadId);
768
- if (!thread)
769
- throw new Error(`Thread not found: ${threadId}`);
770
- if (thread.status !== 'waiting') {
771
- throw new Error(`Thread ${threadId} is ${thread.status}, cannot resume`);
772
- }
773
- await threadStore.mutate(threadId, (t) => {
774
- t.status = 'running';
775
- });
776
- return runThread(threadId, opts);
777
- }
778
- // --- Thread summary for Slack ---
779
- /** The summary's first line (after the status emoji): suspended / paused / complete. */
780
- function summaryHeadline(thread, totalCostUsd, elapsed) {
781
- const steps = thread.steps.length;
782
- const cost = totalCostUsd.toFixed(4);
783
- if (thread.status === 'waiting') {
784
- const n = (thread.metadata?.waitingOn?.length ?? 0) + (thread.metadata?.waitingOnTasks?.length ?? 0);
785
- return t('notice.thread.summaryWaiting', { n, steps, cost });
786
- }
787
- if (thread.status === 'rate_limited')
788
- return t('notice.thread.summaryPaused', { steps, cost });
789
- return t('notice.thread.summaryComplete', { steps, cost, duration: formatDurationCompact(elapsed) });
790
- }
791
- function buildThreadSummary(result) {
792
- const { thread, totalCostUsd, totalNumTurns } = result;
793
- const steps = thread.steps;
794
- const elapsed = thread.endedAt && thread.createdAt
795
- ? (new Date(thread.endedAt).getTime() - new Date(thread.createdAt).getTime()) / 1000
796
- : 0;
797
- const statusEmoji = thread.status === 'completed' ? Icons.ok
798
- : thread.status === 'cancelled' ? Icons.blocked
799
- : thread.status === 'aborted' ? Icons.stopped
800
- : thread.status === 'waiting' ? Icons.processing
801
- : thread.status === 'rate_limited' ? Icons.warning
802
- : Icons.error;
803
- const lines = [`${statusEmoji} ${summaryHeadline(thread, totalCostUsd, elapsed)}`];
804
- if (steps.length > 1) {
805
- for (const step of steps) {
806
- const costStr = step.costUsd != null ? `$${step.costUsd.toFixed(4)}` : '?';
807
- const turnsStr = step.numTurns != null ? t('notice.thread.turns', { n: step.numTurns }) : '?';
808
- const durStr = step.durationS != null ? formatDurationCompact(step.durationS) : '?';
809
- const label = formatEndpoint(step.agentSlotId, step.stage);
810
- lines.push(` ${label}: ${turnsStr} · ${costStr} · ${durStr}`);
811
- }
812
- }
813
- if (thread.abortReason) {
814
- lines.push(t('notice.thread.abortedReason', { reason: thread.abortReason }));
815
- }
816
- else if (thread.status === 'aborted') {
817
- lines.push(t('notice.thread.abortedNoReason'));
818
- }
819
- if (thread.error) {
820
- lines.push(t('notice.thread.errorLine', { error: thread.error }));
821
- }
822
- return lines.join('\n');
823
- }
824
- // Proxy function to support existing callers that import getActiveHandle from runner.ts.
825
- // It delegates to the unified run registry singleton.
826
- function getActiveHandle(channel) {
827
- return runRegistry.getByChannel(channel)[0] ?? null;
828
- }
829
- export { runThread, continueThread, resumeThread, resumeRateLimitedThread, buildThreadSummary, getActiveHandle,
830
- // Internal helpers — exported to support focused unit tests from agent-server/tests/thread-runner.test.ts.
831
- // Not part of the public API; callers outside the test harness should continue to use runThread().
832
- initThreadContext, resolveAndNotifyStep, buildStepConfig, setupStepCallbacks, executeAndAwaitAgent, recordStepOutcome, evaluateAndTransition, finalizeThread, };