@bastani/atomic 0.9.19-alpha.1 → 0.9.19-alpha.3

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 (720) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +23 -0
  3. package/dist/builtin/intercom/README.md +21 -11
  4. package/dist/builtin/intercom/broker/broker.ts +81 -9
  5. package/dist/builtin/intercom/broker/client.ts +22 -0
  6. package/dist/builtin/intercom/broker/framing.ts +5 -2
  7. package/dist/builtin/intercom/broker/group-membership.ts +4 -2
  8. package/dist/builtin/intercom/broker/presence-handler.ts +14 -0
  9. package/dist/builtin/intercom/broker/send-handler.ts +43 -5
  10. package/dist/builtin/intercom/broker/terminal-questions.ts +29 -0
  11. package/dist/builtin/intercom/index.bundle.mjs +978 -742
  12. package/dist/builtin/intercom/package.json +2 -2
  13. package/dist/builtin/intercom/recipient-purpose.ts +9 -0
  14. package/dist/builtin/intercom/recoverable-disconnect.ts +2 -3
  15. package/dist/builtin/intercom/retry-policy.ts +4 -2
  16. package/dist/builtin/intercom/skills/intercom/SKILL.md +5 -4
  17. package/dist/builtin/intercom/types.ts +18 -3
  18. package/dist/builtin/mcp/CHANGELOG.md +6 -0
  19. package/dist/builtin/mcp/README.md +2 -0
  20. package/dist/builtin/mcp/index.bundle.mjs +2201 -12000
  21. package/dist/builtin/mcp/package.json +2 -2
  22. package/dist/builtin/subagents/CHANGELOG.md +33 -0
  23. package/dist/builtin/subagents/README.md +35 -14
  24. package/dist/builtin/subagents/agents/code-simplifier.md +1 -1
  25. package/dist/builtin/subagents/agents/codebase-analyzer.md +1 -1
  26. package/dist/builtin/subagents/agents/codebase-locator.md +2 -2
  27. package/dist/builtin/subagents/agents/codebase-online-researcher.md +1 -1
  28. package/dist/builtin/subagents/agents/codebase-pattern-finder.md +2 -2
  29. package/dist/builtin/subagents/agents/codebase-research-analyzer.md +1 -1
  30. package/dist/builtin/subagents/agents/codebase-research-locator.md +2 -2
  31. package/dist/builtin/subagents/agents/debugger.md +1 -1
  32. package/dist/builtin/subagents/agents/worker.md +1 -1
  33. package/dist/builtin/subagents/package.json +2 -2
  34. package/dist/builtin/subagents/skills/herdr/LICENSE +201 -0
  35. package/dist/builtin/subagents/skills/herdr/SKILL.md +202 -0
  36. package/dist/builtin/subagents/skills/subagent/SKILL.md +14 -10
  37. package/dist/builtin/subagents/skills/tmux/SKILL.md +1 -1
  38. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1286 -611
  39. package/dist/builtin/web-access/index.bundle.mjs +26280 -26274
  40. package/dist/builtin/web-access/package.json +2 -2
  41. package/dist/builtin/workflows/CHANGELOG.md +51 -0
  42. package/dist/builtin/workflows/README.md +1 -1
  43. package/dist/builtin/workflows/builtin/adversarial-verification.js +5 -7
  44. package/dist/builtin/workflows/builtin/{chunk-reqr3sr3.js → chunk-1kx4aggw.js} +22 -22
  45. package/dist/builtin/workflows/builtin/{chunk-42s7sw0b.js → chunk-62v3gg9f.js} +9 -9
  46. package/dist/builtin/workflows/builtin/{chunk-wgccch41.js → chunk-6w6cvk6b.js} +16 -16
  47. package/dist/builtin/workflows/builtin/{chunk-zbekjqew.js → chunk-a2kdsqn8.js} +4 -4
  48. package/dist/builtin/workflows/builtin/{chunk-ze5x3d1r.js → chunk-fg9esgkj.js} +7 -7
  49. package/dist/builtin/workflows/builtin/{chunk-n8h4yyew.js → chunk-g0csgs7w.js} +11 -11
  50. package/dist/builtin/workflows/builtin/{chunk-79fjkcvh.js → chunk-hbnwv56f.js} +17 -17
  51. package/dist/builtin/workflows/builtin/{chunk-ed4jfn5t.js → chunk-mygmtz6e.js} +43 -43
  52. package/dist/builtin/workflows/builtin/{chunk-7430zyas.js → chunk-p8jjwfg6.js} +1 -1
  53. package/dist/builtin/workflows/builtin/{chunk-hqpe2cyx.js → chunk-r9qq7xfj.js} +49 -49
  54. package/dist/builtin/workflows/builtin/{chunk-k3w87x8y.js → chunk-t6x2d78s.js} +10 -10
  55. package/dist/builtin/workflows/builtin/{chunk-6fqs7c01.js → chunk-z0d03ktm.js} +1 -1
  56. package/dist/builtin/workflows/builtin/{chunk-b0v2xab1.js → chunk-zggjyg5z.js} +221 -23
  57. package/dist/builtin/workflows/builtin/classify-and-act.js +5 -6
  58. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -4
  59. package/dist/builtin/workflows/builtin/generate-and-filter.js +5 -6
  60. package/dist/builtin/workflows/builtin/goal.js +7 -8
  61. package/dist/builtin/workflows/builtin/index.js +20 -22
  62. package/dist/builtin/workflows/builtin/loop-until-done.js +5 -6
  63. package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
  64. package/dist/builtin/workflows/builtin/ralph.js +7 -8
  65. package/dist/builtin/workflows/builtin/steering-context.js +3 -3
  66. package/dist/builtin/workflows/builtin/tournament.js +5 -7
  67. package/dist/builtin/workflows/package.json +2 -2
  68. package/dist/builtin/workflows/src/extension/index.bundle.mjs +26708 -25862
  69. package/dist/builtin/workflows/src/index.js +921 -477
  70. package/dist/cli/config-selector.js.map +1 -1
  71. package/dist/cli/startup-ui.d.ts +1 -1
  72. package/dist/cli/startup-ui.js.map +1 -1
  73. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  74. package/dist/core/agent-session-auto-compaction.js +5 -4
  75. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  76. package/dist/core/agent-session-bash.d.ts +1 -1
  77. package/dist/core/agent-session-bash.d.ts.map +1 -1
  78. package/dist/core/agent-session-bash.js +5 -1
  79. package/dist/core/agent-session-bash.js.map +1 -1
  80. package/dist/core/agent-session-compaction.d.ts +1 -1
  81. package/dist/core/agent-session-compaction.js.map +1 -1
  82. package/dist/core/agent-session-custom-message-commit.d.ts +1 -1
  83. package/dist/core/agent-session-custom-message-commit.js.map +1 -1
  84. package/dist/core/agent-session-delivery-forwarding.d.ts +1 -1
  85. package/dist/core/agent-session-delivery-forwarding.js.map +1 -1
  86. package/dist/core/agent-session-events.d.ts.map +1 -1
  87. package/dist/core/agent-session-events.js +5 -0
  88. package/dist/core/agent-session-events.js.map +1 -1
  89. package/dist/core/agent-session-export.d.ts +1 -1
  90. package/dist/core/agent-session-export.js.map +1 -1
  91. package/dist/core/agent-session-extension-bindings.d.ts +8 -1
  92. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  93. package/dist/core/agent-session-extension-bindings.js +45 -3
  94. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  95. package/dist/core/agent-session-message-queue.d.ts +1 -1
  96. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  97. package/dist/core/agent-session-message-queue.js +2 -2
  98. package/dist/core/agent-session-message-queue.js.map +1 -1
  99. package/dist/core/agent-session-methods.d.ts +17 -7
  100. package/dist/core/agent-session-methods.d.ts.map +1 -1
  101. package/dist/core/agent-session-methods.js.map +1 -1
  102. package/dist/core/agent-session-prompt.d.ts +2 -2
  103. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  104. package/dist/core/agent-session-prompt.js +22 -18
  105. package/dist/core/agent-session-prompt.js.map +1 -1
  106. package/dist/core/agent-session-runtime-auth.d.ts +1 -1
  107. package/dist/core/agent-session-runtime-auth.js.map +1 -1
  108. package/dist/core/agent-session-runtime.d.ts +13 -4
  109. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  110. package/dist/core/agent-session-runtime.js +27 -4
  111. package/dist/core/agent-session-runtime.js.map +1 -1
  112. package/dist/core/agent-session-services.d.ts +5 -1
  113. package/dist/core/agent-session-services.d.ts.map +1 -1
  114. package/dist/core/agent-session-services.js +44 -34
  115. package/dist/core/agent-session-services.js.map +1 -1
  116. package/dist/core/agent-session-state.d.ts +1 -1
  117. package/dist/core/agent-session-state.js.map +1 -1
  118. package/dist/core/agent-session-tasks.d.ts +14 -0
  119. package/dist/core/agent-session-tasks.d.ts.map +1 -0
  120. package/dist/core/agent-session-tasks.js +120 -0
  121. package/dist/core/agent-session-tasks.js.map +1 -0
  122. package/dist/core/agent-session-tool-registry.d.ts +1 -0
  123. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  124. package/dist/core/agent-session-tool-registry.js +30 -5
  125. package/dist/core/agent-session-tool-registry.js.map +1 -1
  126. package/dist/core/agent-session-tree.d.ts.map +1 -1
  127. package/dist/core/agent-session-tree.js +3 -0
  128. package/dist/core/agent-session-tree.js.map +1 -1
  129. package/dist/core/agent-session-types.d.ts +2 -2
  130. package/dist/core/agent-session-types.js.map +1 -1
  131. package/dist/core/agent-session.d.ts +4 -1
  132. package/dist/core/agent-session.d.ts.map +1 -1
  133. package/dist/core/agent-session.js +7 -1
  134. package/dist/core/agent-session.js.map +1 -1
  135. package/dist/core/bash-executor.d.ts +1 -1
  136. package/dist/core/bash-executor.js.map +1 -1
  137. package/dist/core/export-html/index.js.map +1 -1
  138. package/dist/core/export-html/tool-renderer.d.ts +1 -1
  139. package/dist/core/export-html/tool-renderer.js.map +1 -1
  140. package/dist/core/extension-session-state.js.map +1 -1
  141. package/dist/core/extensions/agent-events.d.ts +4 -4
  142. package/dist/core/extensions/agent-events.d.ts.map +1 -1
  143. package/dist/core/extensions/agent-events.js.map +1 -1
  144. package/dist/core/extensions/api-types.d.ts +8 -2
  145. package/dist/core/extensions/api-types.d.ts.map +1 -1
  146. package/dist/core/extensions/api-types.js.map +1 -1
  147. package/dist/core/extensions/context-types.d.ts +9 -0
  148. package/dist/core/extensions/context-types.d.ts.map +1 -1
  149. package/dist/core/extensions/context-types.js.map +1 -1
  150. package/dist/core/extensions/event-results.d.ts +1 -1
  151. package/dist/core/extensions/event-results.js.map +1 -1
  152. package/dist/core/extensions/event-types.d.ts +2 -1
  153. package/dist/core/extensions/event-types.d.ts.map +1 -1
  154. package/dist/core/extensions/event-types.js.map +1 -1
  155. package/dist/core/extensions/index.d.ts +2 -1
  156. package/dist/core/extensions/index.d.ts.map +1 -1
  157. package/dist/core/extensions/index.js.map +1 -1
  158. package/dist/core/extensions/loader-api.d.ts +1 -1
  159. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  160. package/dist/core/extensions/loader-api.js +10 -0
  161. package/dist/core/extensions/loader-api.js.map +1 -1
  162. package/dist/core/extensions/loader-core.d.ts +1 -1
  163. package/dist/core/extensions/loader-core.js.map +1 -1
  164. package/dist/core/extensions/loader-discovery.d.ts +1 -1
  165. package/dist/core/extensions/loader-discovery.js.map +1 -1
  166. package/dist/core/extensions/loader-host-modules.d.ts +1 -1
  167. package/dist/core/extensions/loader-host-modules.d.ts.map +1 -1
  168. package/dist/core/extensions/loader-host-modules.js +2 -1
  169. package/dist/core/extensions/loader-host-modules.js.map +1 -1
  170. package/dist/core/extensions/loader-runtime.d.ts.map +1 -1
  171. package/dist/core/extensions/loader-runtime.js +3 -0
  172. package/dist/core/extensions/loader-runtime.js.map +1 -1
  173. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  174. package/dist/core/extensions/loader-virtual-modules.js +4 -1
  175. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  176. package/dist/core/extensions/loader.d.ts +1 -1
  177. package/dist/core/extensions/loader.js.map +1 -1
  178. package/dist/core/extensions/message-types.d.ts +1 -1
  179. package/dist/core/extensions/message-types.js.map +1 -1
  180. package/dist/core/extensions/runner-context.d.ts +11 -1
  181. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  182. package/dist/core/extensions/runner-context.js +41 -2
  183. package/dist/core/extensions/runner-context.js.map +1 -1
  184. package/dist/core/extensions/runner-events.d.ts +1 -1
  185. package/dist/core/extensions/runner-events.d.ts.map +1 -1
  186. package/dist/core/extensions/runner-events.js +17 -2
  187. package/dist/core/extensions/runner-events.js.map +1 -1
  188. package/dist/core/extensions/runner-ui.js.map +1 -1
  189. package/dist/core/extensions/runner.d.ts +17 -2
  190. package/dist/core/extensions/runner.d.ts.map +1 -1
  191. package/dist/core/extensions/runner.js +68 -18
  192. package/dist/core/extensions/runner.js.map +1 -1
  193. package/dist/core/extensions/runtime-types.d.ts +4 -1
  194. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  195. package/dist/core/extensions/runtime-types.js.map +1 -1
  196. package/dist/core/extensions/tool-types.d.ts +1 -1
  197. package/dist/core/extensions/tool-types.js.map +1 -1
  198. package/dist/core/extensions/types.d.ts +1 -0
  199. package/dist/core/extensions/types.d.ts.map +1 -1
  200. package/dist/core/extensions/types.js.map +1 -1
  201. package/dist/core/extensions/ui-types.d.ts +5 -1
  202. package/dist/core/extensions/ui-types.d.ts.map +1 -1
  203. package/dist/core/extensions/ui-types.js.map +1 -1
  204. package/dist/core/extensions/workflow-activity-hub.d.ts +25 -0
  205. package/dist/core/extensions/workflow-activity-hub.d.ts.map +1 -0
  206. package/dist/core/extensions/workflow-activity-hub.js +183 -0
  207. package/dist/core/extensions/workflow-activity-hub.js.map +1 -0
  208. package/dist/core/extensions/workflow-events.d.ts +118 -0
  209. package/dist/core/extensions/workflow-events.d.ts.map +1 -0
  210. package/dist/core/extensions/workflow-events.js +2 -0
  211. package/dist/core/extensions/workflow-events.js.map +1 -0
  212. package/dist/core/footer-data-provider.d.ts +8 -4
  213. package/dist/core/footer-data-provider.d.ts.map +1 -1
  214. package/dist/core/footer-data-provider.js +97 -11
  215. package/dist/core/footer-data-provider.js.map +1 -1
  216. package/dist/core/index.d.ts +3 -3
  217. package/dist/core/index.js.map +1 -1
  218. package/dist/core/keybindings.d.ts +27 -2
  219. package/dist/core/keybindings.d.ts.map +1 -1
  220. package/dist/core/keybindings.js +7 -2
  221. package/dist/core/keybindings.js.map +1 -1
  222. package/dist/core/mandatory-runtime-tools.d.ts +1 -1
  223. package/dist/core/mandatory-runtime-tools.js.map +1 -1
  224. package/dist/core/model-fallback-failures.js +2 -2
  225. package/dist/core/model-fallback-failures.js.map +1 -1
  226. package/dist/core/model-registry.d.ts +5 -1
  227. package/dist/core/model-registry.d.ts.map +1 -1
  228. package/dist/core/model-registry.js +8 -0
  229. package/dist/core/model-registry.js.map +1 -1
  230. package/dist/core/model-resolver-defaults.js +1 -1
  231. package/dist/core/model-resolver-defaults.js.map +1 -1
  232. package/dist/core/resource-loader-assets.js.map +1 -1
  233. package/dist/core/resource-loader-core.d.ts +1 -1
  234. package/dist/core/resource-loader-core.js.map +1 -1
  235. package/dist/core/resource-loader-internals.d.ts +2 -2
  236. package/dist/core/resource-loader-internals.js.map +1 -1
  237. package/dist/core/resource-loader-reload.d.ts +2 -0
  238. package/dist/core/resource-loader-reload.d.ts.map +1 -1
  239. package/dist/core/resource-loader-reload.js +231 -191
  240. package/dist/core/resource-loader-reload.js.map +1 -1
  241. package/dist/core/resource-loader-types.d.ts +4 -2
  242. package/dist/core/resource-loader-types.d.ts.map +1 -1
  243. package/dist/core/resource-loader-types.js.map +1 -1
  244. package/dist/core/retry-policy.d.ts +1 -0
  245. package/dist/core/retry-policy.d.ts.map +1 -1
  246. package/dist/core/retry-policy.js +2 -1
  247. package/dist/core/retry-policy.js.map +1 -1
  248. package/dist/core/sdk-exports.d.ts +2 -2
  249. package/dist/core/sdk-exports.js.map +1 -1
  250. package/dist/core/sdk-types.d.ts +2 -2
  251. package/dist/core/sdk-types.js.map +1 -1
  252. package/dist/core/sdk.js.map +1 -1
  253. package/dist/core/settings-manager-basic-accessors.d.ts +1 -0
  254. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  255. package/dist/core/settings-manager-basic-accessors.js +2 -0
  256. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  257. package/dist/core/settings-manager-core.d.ts.map +1 -1
  258. package/dist/core/settings-manager-core.js +10 -4
  259. package/dist/core/settings-manager-core.js.map +1 -1
  260. package/dist/core/settings-storage.d.ts +1 -0
  261. package/dist/core/settings-storage.d.ts.map +1 -1
  262. package/dist/core/settings-storage.js +18 -0
  263. package/dist/core/settings-storage.js.map +1 -1
  264. package/dist/core/settings-types.d.ts +12 -0
  265. package/dist/core/settings-types.d.ts.map +1 -1
  266. package/dist/core/settings-types.js.map +1 -1
  267. package/dist/core/slash-commands.d.ts.map +1 -1
  268. package/dist/core/slash-commands.js +2 -0
  269. package/dist/core/slash-commands.js.map +1 -1
  270. package/dist/core/system-prompt.d.ts.map +1 -1
  271. package/dist/core/system-prompt.js +5 -6
  272. package/dist/core/system-prompt.js.map +1 -1
  273. package/dist/core/tasks/agent-adapter.d.ts +41 -0
  274. package/dist/core/tasks/agent-adapter.d.ts.map +1 -0
  275. package/dist/core/tasks/agent-adapter.js +105 -0
  276. package/dist/core/tasks/agent-adapter.js.map +1 -0
  277. package/dist/core/tasks/command-output.d.ts +15 -0
  278. package/dist/core/tasks/command-output.d.ts.map +1 -0
  279. package/dist/core/tasks/command-output.js +29 -0
  280. package/dist/core/tasks/command-output.js.map +1 -0
  281. package/dist/core/tasks/completion-ordering.d.ts +11 -0
  282. package/dist/core/tasks/completion-ordering.d.ts.map +1 -0
  283. package/dist/core/tasks/completion-ordering.js +19 -0
  284. package/dist/core/tasks/completion-ordering.js.map +1 -0
  285. package/dist/core/tasks/completion.d.ts +36 -0
  286. package/dist/core/tasks/completion.d.ts.map +1 -0
  287. package/dist/core/tasks/completion.js +115 -0
  288. package/dist/core/tasks/completion.js.map +1 -0
  289. package/dist/core/tasks/contracts.d.ts +404 -0
  290. package/dist/core/tasks/contracts.d.ts.map +1 -0
  291. package/dist/core/tasks/contracts.js +2 -0
  292. package/dist/core/tasks/contracts.js.map +1 -0
  293. package/dist/core/tasks/execution-scope.d.ts +10 -0
  294. package/dist/core/tasks/execution-scope.d.ts.map +1 -0
  295. package/dist/core/tasks/execution-scope.js +27 -0
  296. package/dist/core/tasks/execution-scope.js.map +1 -0
  297. package/dist/core/tasks/owner-store.d.ts +53 -0
  298. package/dist/core/tasks/owner-store.d.ts.map +1 -0
  299. package/dist/core/tasks/owner-store.js +155 -0
  300. package/dist/core/tasks/owner-store.js.map +1 -0
  301. package/dist/core/tasks/pause.d.ts +4 -0
  302. package/dist/core/tasks/pause.d.ts.map +1 -0
  303. package/dist/core/tasks/pause.js +49 -0
  304. package/dist/core/tasks/pause.js.map +1 -0
  305. package/dist/core/tasks/supervisor.d.ts +123 -0
  306. package/dist/core/tasks/supervisor.d.ts.map +1 -0
  307. package/dist/core/tasks/supervisor.js +942 -0
  308. package/dist/core/tasks/supervisor.js.map +1 -0
  309. package/dist/core/tasks/transcript.d.ts +23 -0
  310. package/dist/core/tasks/transcript.d.ts.map +1 -0
  311. package/dist/core/tasks/transcript.js +74 -0
  312. package/dist/core/tasks/transcript.js.map +1 -0
  313. package/dist/core/tools/ask-user-question/ask-user-question.d.ts +2 -2
  314. package/dist/core/tools/ask-user-question/ask-user-question.d.ts.map +1 -1
  315. package/dist/core/tools/ask-user-question/ask-user-question.js +8 -4
  316. package/dist/core/tools/ask-user-question/ask-user-question.js.map +1 -1
  317. package/dist/core/tools/ask-user-question/state/build-questionnaire.d.ts +1 -1
  318. package/dist/core/tools/ask-user-question/state/build-questionnaire.js.map +1 -1
  319. package/dist/core/tools/ask-user-question/state/questionnaire-session.d.ts +1 -1
  320. package/dist/core/tools/ask-user-question/state/questionnaire-session.js.map +1 -1
  321. package/dist/core/tools/ask-user-question/view/components/multi-select-view.d.ts +1 -1
  322. package/dist/core/tools/ask-user-question/view/components/multi-select-view.js.map +1 -1
  323. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.d.ts +1 -1
  324. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.js.map +1 -1
  325. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.d.ts +1 -1
  326. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js.map +1 -1
  327. package/dist/core/tools/ask-user-question/view/components/submit-picker.d.ts +1 -1
  328. package/dist/core/tools/ask-user-question/view/components/submit-picker.js.map +1 -1
  329. package/dist/core/tools/ask-user-question/view/components/tab-bar.d.ts +1 -1
  330. package/dist/core/tools/ask-user-question/view/components/tab-bar.js.map +1 -1
  331. package/dist/core/tools/ask-user-question/view/dialog-builder.d.ts +1 -1
  332. package/dist/core/tools/ask-user-question/view/dialog-builder.js.map +1 -1
  333. package/dist/core/tools/ask-user-question/view/tab-content-strategy.d.ts +1 -1
  334. package/dist/core/tools/ask-user-question/view/tab-content-strategy.js.map +1 -1
  335. package/dist/core/tools/bash-pty-native.d.ts +18 -3
  336. package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
  337. package/dist/core/tools/bash-pty-native.js +116 -1
  338. package/dist/core/tools/bash-pty-native.js.map +1 -1
  339. package/dist/core/tools/bash.d.ts +13 -4
  340. package/dist/core/tools/bash.d.ts.map +1 -1
  341. package/dist/core/tools/bash.js +53 -9
  342. package/dist/core/tools/bash.js.map +1 -1
  343. package/dist/core/tools/edit.d.ts.map +1 -1
  344. package/dist/core/tools/edit.js +1 -2
  345. package/dist/core/tools/edit.js.map +1 -1
  346. package/dist/core/tools/find.js.map +1 -1
  347. package/dist/core/tools/grep.js.map +1 -1
  348. package/dist/core/tools/index.d.ts +2 -2
  349. package/dist/core/tools/index.js.map +1 -1
  350. package/dist/core/tools/ls.js.map +1 -1
  351. package/dist/core/tools/powershell.d.ts +20 -10
  352. package/dist/core/tools/powershell.d.ts.map +1 -1
  353. package/dist/core/tools/powershell.js +33 -7
  354. package/dist/core/tools/powershell.js.map +1 -1
  355. package/dist/core/tools/read.d.ts.map +1 -1
  356. package/dist/core/tools/read.js +1 -2
  357. package/dist/core/tools/read.js.map +1 -1
  358. package/dist/core/tools/render-utils.d.ts +1 -1
  359. package/dist/core/tools/render-utils.js.map +1 -1
  360. package/dist/core/tools/resource-selectors.d.ts +1 -1
  361. package/dist/core/tools/resource-selectors.d.ts.map +1 -1
  362. package/dist/core/tools/resource-selectors.js +21 -10
  363. package/dist/core/tools/resource-selectors.js.map +1 -1
  364. package/dist/core/tools/search.js.map +1 -1
  365. package/dist/core/tools/todos-render.d.ts +1 -1
  366. package/dist/core/tools/todos-render.js.map +1 -1
  367. package/dist/core/tools/write.d.ts.map +1 -1
  368. package/dist/core/tools/write.js +1 -2
  369. package/dist/core/tools/write.js.map +1 -1
  370. package/dist/core/workflow-stage-admission.d.ts +10 -0
  371. package/dist/core/workflow-stage-admission.d.ts.map +1 -1
  372. package/dist/core/workflow-stage-admission.js +24 -0
  373. package/dist/core/workflow-stage-admission.js.map +1 -1
  374. package/dist/extensions/herdr/activity.d.ts +15 -0
  375. package/dist/extensions/herdr/activity.d.ts.map +1 -0
  376. package/dist/extensions/herdr/activity.js +24 -0
  377. package/dist/extensions/herdr/activity.js.map +1 -0
  378. package/dist/extensions/herdr/environment.d.ts +7 -0
  379. package/dist/extensions/herdr/environment.d.ts.map +1 -0
  380. package/dist/extensions/herdr/environment.js +6 -0
  381. package/dist/extensions/herdr/environment.js.map +1 -0
  382. package/dist/extensions/herdr/index.d.ts +9 -0
  383. package/dist/extensions/herdr/index.d.ts.map +1 -0
  384. package/dist/extensions/herdr/index.js +225 -0
  385. package/dist/extensions/herdr/index.js.map +1 -0
  386. package/dist/extensions/herdr/pane-owner.d.ts +30 -0
  387. package/dist/extensions/herdr/pane-owner.d.ts.map +1 -0
  388. package/dist/extensions/herdr/pane-owner.js +111 -0
  389. package/dist/extensions/herdr/pane-owner.js.map +1 -0
  390. package/dist/extensions/herdr/transport.d.ts +8 -0
  391. package/dist/extensions/herdr/transport.d.ts.map +1 -0
  392. package/dist/extensions/herdr/transport.js +28 -0
  393. package/dist/extensions/herdr/transport.js.map +1 -0
  394. package/dist/extensions/index.d.ts.map +1 -1
  395. package/dist/extensions/index.js +2 -0
  396. package/dist/extensions/index.js.map +1 -1
  397. package/dist/extensions/llama/huggingface-ui.d.ts +1 -1
  398. package/dist/extensions/llama/huggingface-ui.js.map +1 -1
  399. package/dist/extensions/llama/ui.js.map +1 -1
  400. package/dist/index-extensions.d.ts +3 -2
  401. package/dist/index-extensions.d.ts.map +1 -1
  402. package/dist/index-extensions.js.map +1 -1
  403. package/dist/index.d.ts +11 -3
  404. package/dist/index.d.ts.map +1 -1
  405. package/dist/index.js +8 -0
  406. package/dist/index.js.map +1 -1
  407. package/dist/main-session.js.map +1 -1
  408. package/dist/main.d.ts.map +1 -1
  409. package/dist/main.js +149 -69
  410. package/dist/main.js.map +1 -1
  411. package/dist/modes/interactive/components/armin.js.map +1 -1
  412. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  413. package/dist/modes/interactive/components/atomic-banner.d.ts +1 -1
  414. package/dist/modes/interactive/components/atomic-banner.js.map +1 -1
  415. package/dist/modes/interactive/components/atomic-working-status.js.map +1 -1
  416. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  417. package/dist/modes/interactive/components/bordered-loader.d.ts +1 -1
  418. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  419. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  420. package/dist/modes/interactive/components/chat-message-renderer.d.ts +12 -0
  421. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  422. package/dist/modes/interactive/components/chat-message-renderer.js +44 -0
  423. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  424. package/dist/modes/interactive/components/chat-session-host-actions.d.ts +1 -1
  425. package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
  426. package/dist/modes/interactive/components/chat-session-host-actions.js +43 -8
  427. package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
  428. package/dist/modes/interactive/components/chat-session-host-editor.d.ts +1 -1
  429. package/dist/modes/interactive/components/chat-session-host-editor.js.map +1 -1
  430. package/dist/modes/interactive/components/chat-session-host-events.d.ts +2 -2
  431. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  432. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts +2 -2
  433. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
  434. package/dist/modes/interactive/components/chat-session-host-rendering.js +12 -3
  435. package/dist/modes/interactive/components/chat-session-host-rendering.js.map +1 -1
  436. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts +4 -5
  437. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts.map +1 -1
  438. package/dist/modes/interactive/components/chat-session-host-runtime.js +8 -6
  439. package/dist/modes/interactive/components/chat-session-host-runtime.js.map +1 -1
  440. package/dist/modes/interactive/components/chat-session-host-state.d.ts +7 -2
  441. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  442. package/dist/modes/interactive/components/chat-session-host-state.js +1 -0
  443. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  444. package/dist/modes/interactive/components/chat-session-host-terminal-cleanup.d.ts +1 -1
  445. package/dist/modes/interactive/components/chat-session-host-terminal-cleanup.js.map +1 -1
  446. package/dist/modes/interactive/components/chat-session-host-types.d.ts +8 -3
  447. package/dist/modes/interactive/components/chat-session-host-types.d.ts.map +1 -1
  448. package/dist/modes/interactive/components/chat-session-host-types.js.map +1 -1
  449. package/dist/modes/interactive/components/chat-session-host-utils.d.ts +1 -1
  450. package/dist/modes/interactive/components/chat-session-host-utils.d.ts.map +1 -1
  451. package/dist/modes/interactive/components/chat-session-host-utils.js +2 -0
  452. package/dist/modes/interactive/components/chat-session-host-utils.js.map +1 -1
  453. package/dist/modes/interactive/components/chat-session-host.d.ts +17 -2
  454. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  455. package/dist/modes/interactive/components/chat-session-host.js +100 -3
  456. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  457. package/dist/modes/interactive/components/chat-transcript.d.ts +1 -0
  458. package/dist/modes/interactive/components/chat-transcript.d.ts.map +1 -1
  459. package/dist/modes/interactive/components/chat-transcript.js +1 -1
  460. package/dist/modes/interactive/components/chat-transcript.js.map +1 -1
  461. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  462. package/dist/modes/interactive/components/config-selector-list.js.map +1 -1
  463. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  464. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  465. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  466. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  467. package/dist/modes/interactive/components/custom-message.js +12 -0
  468. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  469. package/dist/modes/interactive/components/daxnuts.js.map +1 -1
  470. package/dist/modes/interactive/components/diff.js.map +1 -1
  471. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  472. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -1
  473. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  474. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  475. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  476. package/dist/modes/interactive/components/first-time-setup.d.ts +1 -1
  477. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  478. package/dist/modes/interactive/components/footer.d.ts +7 -6
  479. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  480. package/dist/modes/interactive/components/footer.js +27 -9
  481. package/dist/modes/interactive/components/footer.js.map +1 -1
  482. package/dist/modes/interactive/components/host-input-form-mount.js.map +1 -1
  483. package/dist/modes/interactive/components/host-input-form.d.ts +1 -1
  484. package/dist/modes/interactive/components/host-input-form.js.map +1 -1
  485. package/dist/modes/interactive/components/index.d.ts +2 -2
  486. package/dist/modes/interactive/components/index.js.map +1 -1
  487. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  488. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  489. package/dist/modes/interactive/components/mermaid.d.ts +1 -1
  490. package/dist/modes/interactive/components/mermaid.js.map +1 -1
  491. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  492. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  493. package/dist/modes/interactive/components/reserved-bottom-overlay.js.map +1 -1
  494. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  495. package/dist/modes/interactive/components/session-selector-header.js.map +1 -1
  496. package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
  497. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  498. package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
  499. package/dist/modes/interactive/components/settings-selector-submenus.d.ts +1 -1
  500. package/dist/modes/interactive/components/settings-selector-submenus.js.map +1 -1
  501. package/dist/modes/interactive/components/settings-selector-types.d.ts +1 -1
  502. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  503. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  504. package/dist/modes/interactive/components/show-images-selector.js.map +1 -1
  505. package/dist/modes/interactive/components/skill-invocation-message.d.ts +1 -1
  506. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  507. package/dist/modes/interactive/components/task-completion-message.d.ts +13 -0
  508. package/dist/modes/interactive/components/task-completion-message.d.ts.map +1 -0
  509. package/dist/modes/interactive/components/task-completion-message.js +65 -0
  510. package/dist/modes/interactive/components/task-completion-message.js.map +1 -0
  511. package/dist/modes/interactive/components/task-detail.d.ts +27 -0
  512. package/dist/modes/interactive/components/task-detail.d.ts.map +1 -0
  513. package/dist/modes/interactive/components/task-detail.js +107 -0
  514. package/dist/modes/interactive/components/task-detail.js.map +1 -0
  515. package/dist/modes/interactive/components/task-inspector.d.ts +50 -0
  516. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -0
  517. package/dist/modes/interactive/components/task-inspector.js +599 -0
  518. package/dist/modes/interactive/components/task-inspector.js.map +1 -0
  519. package/dist/modes/interactive/components/task-list.d.ts +18 -0
  520. package/dist/modes/interactive/components/task-list.d.ts.map +1 -0
  521. package/dist/modes/interactive/components/task-list.js +59 -0
  522. package/dist/modes/interactive/components/task-list.js.map +1 -0
  523. package/dist/modes/interactive/components/task-live-transcript.d.ts +17 -0
  524. package/dist/modes/interactive/components/task-live-transcript.d.ts.map +1 -0
  525. package/dist/modes/interactive/components/task-live-transcript.js +33 -0
  526. package/dist/modes/interactive/components/task-live-transcript.js.map +1 -0
  527. package/dist/modes/interactive/components/task-navigation.d.ts +38 -0
  528. package/dist/modes/interactive/components/task-navigation.d.ts.map +1 -0
  529. package/dist/modes/interactive/components/task-navigation.js +93 -0
  530. package/dist/modes/interactive/components/task-navigation.js.map +1 -0
  531. package/dist/modes/interactive/components/task-row.d.ts +34 -0
  532. package/dist/modes/interactive/components/task-row.d.ts.map +1 -0
  533. package/dist/modes/interactive/components/task-row.js +158 -0
  534. package/dist/modes/interactive/components/task-row.js.map +1 -0
  535. package/dist/modes/interactive/components/theme-selector.js.map +1 -1
  536. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  537. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  538. package/dist/modes/interactive/components/transcript-follow-indicator.js.map +1 -1
  539. package/dist/modes/interactive/components/tree-selector-component.js.map +1 -1
  540. package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
  541. package/dist/modes/interactive/components/tree-selector-help.js.map +1 -1
  542. package/dist/modes/interactive/components/tree-selector-label-input.js.map +1 -1
  543. package/dist/modes/interactive/components/tree-selector-list.js.map +1 -1
  544. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  545. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  546. package/dist/modes/interactive/components/user-message.js.map +1 -1
  547. package/dist/modes/interactive/components/working-status.js.map +1 -1
  548. package/dist/modes/interactive/interactive-agent-events.js +8 -2
  549. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  550. package/dist/modes/interactive/interactive-auth-login.js +3 -1
  551. package/dist/modes/interactive/interactive-auth-login.js.map +1 -1
  552. package/dist/modes/interactive/interactive-autocomplete.js +9 -30
  553. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  554. package/dist/modes/interactive/interactive-deferred-startup.js +2 -1
  555. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  556. package/dist/modes/interactive/interactive-extension-context.js +14 -4
  557. package/dist/modes/interactive/interactive-extension-context.js.map +1 -1
  558. package/dist/modes/interactive/interactive-extension-custom-ui.js +52 -4
  559. package/dist/modes/interactive/interactive-extension-custom-ui.js.map +1 -1
  560. package/dist/modes/interactive/interactive-extension-runtime.js +1 -0
  561. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  562. package/dist/modes/interactive/interactive-extension-widgets.js +9 -1
  563. package/dist/modes/interactive/interactive-extension-widgets.js.map +1 -1
  564. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  565. package/dist/modes/interactive/interactive-input-handling.js +19 -0
  566. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  567. package/dist/modes/interactive/interactive-mode-base.d.ts +6 -1
  568. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  569. package/dist/modes/interactive/interactive-mode-base.js +4 -1
  570. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  571. package/dist/modes/interactive/interactive-mode-deps.d.ts +6 -6
  572. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  573. package/dist/modes/interactive/interactive-mode-surface.d.ts +2 -1
  574. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  575. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  576. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  577. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  578. package/dist/modes/interactive/interactive-mode.js +3 -0
  579. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  580. package/dist/modes/interactive/interactive-process-lifecycle.js +4 -1
  581. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  582. package/dist/modes/interactive/interactive-render-chat.js +2 -0
  583. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  584. package/dist/modes/interactive/interactive-session-routing.js +33 -23
  585. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  586. package/dist/modes/interactive/interactive-session-runtime.js +1 -0
  587. package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
  588. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  589. package/dist/modes/interactive/interactive-summarization-retry-events.js +2 -2
  590. package/dist/modes/interactive/interactive-summarization-retry-events.js.map +1 -1
  591. package/dist/modes/interactive/interactive-task-projection.d.ts +13 -0
  592. package/dist/modes/interactive/interactive-task-projection.d.ts.map +1 -0
  593. package/dist/modes/interactive/interactive-task-projection.js +72 -0
  594. package/dist/modes/interactive/interactive-task-projection.js.map +1 -0
  595. package/dist/modes/interactive/interactive-tui.js.map +1 -1
  596. package/dist/modes/interactive/interactive-windows-subshell.d.ts +17 -0
  597. package/dist/modes/interactive/interactive-windows-subshell.d.ts.map +1 -0
  598. package/dist/modes/interactive/interactive-windows-subshell.js +92 -0
  599. package/dist/modes/interactive/interactive-windows-subshell.js.map +1 -0
  600. package/dist/modes/interactive/skill-command-autocomplete.d.ts +12 -0
  601. package/dist/modes/interactive/skill-command-autocomplete.d.ts.map +1 -0
  602. package/dist/modes/interactive/skill-command-autocomplete.js +69 -0
  603. package/dist/modes/interactive/skill-command-autocomplete.js.map +1 -0
  604. package/dist/modes/interactive/theme/theme-class.d.ts.map +1 -1
  605. package/dist/modes/interactive/theme/theme-class.js +4 -1
  606. package/dist/modes/interactive/theme/theme-class.js.map +1 -1
  607. package/dist/modes/interactive/theme/theme-controller.d.ts +1 -1
  608. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  609. package/dist/modes/interactive-engine/create-isolated-runtime.d.ts +1 -1
  610. package/dist/modes/interactive-engine/create-isolated-runtime.js.map +1 -1
  611. package/dist/modes/interactive-engine/engine-custom-ui.d.ts +5 -9
  612. package/dist/modes/interactive-engine/engine-custom-ui.d.ts.map +1 -1
  613. package/dist/modes/interactive-engine/engine-custom-ui.js +14 -5
  614. package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
  615. package/dist/modes/interactive-engine/engine-dialog-host.d.ts +2 -2
  616. package/dist/modes/interactive-engine/engine-dialog-host.js.map +1 -1
  617. package/dist/modes/interactive-engine/engine-project-trust.d.ts +10 -0
  618. package/dist/modes/interactive-engine/engine-project-trust.d.ts.map +1 -0
  619. package/dist/modes/interactive-engine/engine-project-trust.js +28 -0
  620. package/dist/modes/interactive-engine/engine-project-trust.js.map +1 -0
  621. package/dist/modes/interactive-engine/engine-render-service.d.ts +1 -1
  622. package/dist/modes/interactive-engine/engine-render-service.js.map +1 -1
  623. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts +3 -1
  624. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts.map +1 -1
  625. package/dist/modes/interactive-engine/extension-ui-bridge.js +6 -0
  626. package/dist/modes/interactive-engine/extension-ui-bridge.js.map +1 -1
  627. package/dist/modes/interactive-engine/input-form-host.d.ts +2 -2
  628. package/dist/modes/interactive-engine/input-form-host.js.map +1 -1
  629. package/dist/modes/interactive-engine/isolated-auth.d.ts +1 -1
  630. package/dist/modes/interactive-engine/isolated-auth.js.map +1 -1
  631. package/dist/modes/interactive-engine/isolated-runtime.d.ts +5 -2
  632. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  633. package/dist/modes/interactive-engine/isolated-runtime.js +40 -3
  634. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  635. package/dist/modes/interactive-engine/protocol.d.ts +9 -0
  636. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  637. package/dist/modes/interactive-engine/protocol.js +8 -0
  638. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  639. package/dist/modes/interactive-engine/remote-component.d.ts +2 -2
  640. package/dist/modes/interactive-engine/remote-component.d.ts.map +1 -1
  641. package/dist/modes/interactive-engine/remote-component.js +3 -2
  642. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  643. package/dist/modes/interactive-engine/remote-model-catalog.d.ts +1 -1
  644. package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -1
  645. package/dist/modes/interactive-engine/remote-renderer.d.ts +1 -1
  646. package/dist/modes/interactive-engine/remote-renderer.js.map +1 -1
  647. package/dist/modes/interactive-engine/session-picker-host.d.ts +2 -2
  648. package/dist/modes/interactive-engine/session-picker-host.js.map +1 -1
  649. package/dist/modes/json-event.d.ts +1 -1
  650. package/dist/modes/json-event.js.map +1 -1
  651. package/dist/modes/print-mode.js.map +1 -1
  652. package/dist/modes/rpc/rpc-bash-request-owners.d.ts +2 -2
  653. package/dist/modes/rpc/rpc-bash-request-owners.js.map +1 -1
  654. package/dist/modes/rpc/rpc-client-api.d.ts +2 -2
  655. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  656. package/dist/modes/rpc/rpc-client-api.js +2 -2
  657. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  658. package/dist/modes/rpc/rpc-client-waits.d.ts +1 -1
  659. package/dist/modes/rpc/rpc-client-waits.js.map +1 -1
  660. package/dist/modes/rpc/rpc-client.d.ts +3 -1
  661. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  662. package/dist/modes/rpc/rpc-client.js +20 -0
  663. package/dist/modes/rpc/rpc-client.js.map +1 -1
  664. package/dist/modes/rpc/rpc-command-handler.d.ts +4 -2
  665. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  666. package/dist/modes/rpc/rpc-command-handler.js +12 -4
  667. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  668. package/dist/modes/rpc/rpc-extension-ui.d.ts +1 -1
  669. package/dist/modes/rpc/rpc-extension-ui.js.map +1 -1
  670. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  671. package/dist/modes/rpc/rpc-mode.js +11 -2
  672. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  673. package/dist/modes/rpc/rpc-provider-auth.d.ts +1 -1
  674. package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
  675. package/dist/modes/rpc/rpc-session-binding.d.ts +4 -1
  676. package/dist/modes/rpc/rpc-session-binding.d.ts.map +1 -1
  677. package/dist/modes/rpc/rpc-session-binding.js +35 -1
  678. package/dist/modes/rpc/rpc-session-binding.js.map +1 -1
  679. package/dist/modes/rpc/rpc-types.d.ts +13 -1
  680. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  681. package/dist/modes/rpc/rpc-types.js.map +1 -1
  682. package/dist/modes/rpc/task-ui-bridge.d.ts +9 -0
  683. package/dist/modes/rpc/task-ui-bridge.d.ts.map +1 -0
  684. package/dist/modes/rpc/task-ui-bridge.js +146 -0
  685. package/dist/modes/rpc/task-ui-bridge.js.map +1 -0
  686. package/dist/self-update-plan.js.map +1 -1
  687. package/docs/background-tasks.md +205 -0
  688. package/docs/compaction.md +2 -0
  689. package/docs/development.md +23 -72
  690. package/docs/docs.json +2 -0
  691. package/docs/environment-variables.md +1 -1
  692. package/docs/extensions.md +112 -6
  693. package/docs/herdr.md +53 -0
  694. package/docs/intercom.md +42 -35
  695. package/docs/keybindings.md +19 -2
  696. package/docs/models/evals.md +224 -147
  697. package/docs/models/model-selection.md +28 -19
  698. package/docs/models/pareto-efficiency.md +2 -2
  699. package/docs/providers.md +48 -46
  700. package/docs/quickstart.md +1 -1
  701. package/docs/sdk.md +244 -0
  702. package/docs/settings.md +19 -3
  703. package/docs/skills.md +23 -1
  704. package/docs/subagents.md +74 -10
  705. package/docs/themes.md +4 -0
  706. package/docs/tools.md +29 -0
  707. package/docs/tui.md +29 -2
  708. package/docs/usage.md +4 -0
  709. package/docs/windows.md +4 -4
  710. package/docs/workflows/api-reference.md +14 -5
  711. package/docs/workflows/operations.md +49 -3
  712. package/docs/workflows/reliable-design.md +35 -4
  713. package/docs/workflows/verification.md +21 -4
  714. package/docs/workflows.md +3 -1
  715. package/npm-shrinkwrap.json +797 -677
  716. package/package.json +10 -10
  717. /package/dist/builtin/workflows/builtin/{chunk-cg9tmks0.js → chunk-n1910xc4.js} +0 -0
  718. /package/dist/builtin/workflows/builtin/{chunk-wpckd35c.js → chunk-rc5ec5xx.js} +0 -0
  719. /package/dist/builtin/workflows/builtin/{chunk-7at6dnkr.js → chunk-tgt0s5e5.js} +0 -0
  720. /package/dist/builtin/workflows/builtin/{chunk-bfkmzv9h.js → chunk-xtxcq5tj.js} +0 -0
@@ -302,7 +302,7 @@ function createSessionScopedSingleton(key, createLocal) {
302
302
  const live = () => shared.instance ?? instance;
303
303
  const current = () => live();
304
304
  const adoptWithResult = (scope, options) => {
305
- const current2 = live();
305
+ const current = live();
306
306
  let targetCreated = false;
307
307
  const target = sessionScopedExtensionState(scope, key, () => {
308
308
  targetCreated = true;
@@ -311,8 +311,8 @@ function createSessionScopedSingleton(key, createLocal) {
311
311
  shared.localClaimed = true;
312
312
  return shared.local;
313
313
  });
314
- const preservedCurrent = !targetCreated && target !== current2 && options?.preserveCurrentWhenTargetExists?.(current2, target) === true;
315
- shared.instance = preservedCurrent ? current2 : target;
314
+ const preservedCurrent = !targetCreated && target !== current && options?.preserveCurrentWhenTargetExists?.(current, target) === true;
315
+ shared.instance = preservedCurrent ? current : target;
316
316
  instance = shared.instance;
317
317
  return { instance: shared.instance, preservedCurrent };
318
318
  };
@@ -569,17 +569,17 @@ function cloneWorkflowExitSnapshotValue(value, seen, stack = new Set) {
569
569
  return stack.has(objectValue) ? makeWorkflowExitSnapshotInvalidValue("circular object") : previousClone;
570
570
  }
571
571
  if (Array.isArray(value)) {
572
- const clone2 = [];
573
- seen.set(objectValue, clone2);
572
+ const clone = [];
573
+ seen.set(objectValue, clone);
574
574
  stack.add(objectValue);
575
575
  try {
576
576
  for (let index = 0;index < value.length; index += 1) {
577
- clone2[index] = cloneWorkflowExitSnapshotValue(value[index], seen, stack);
577
+ clone[index] = cloneWorkflowExitSnapshotValue(value[index], seen, stack);
578
578
  }
579
579
  } finally {
580
580
  stack.delete(objectValue);
581
581
  }
582
- return clone2;
582
+ return clone;
583
583
  }
584
584
  if (!isPlainWorkflowExitSnapshotObject(objectValue)) {
585
585
  return makeWorkflowExitSnapshotInvalidValue(workflowSerializableTypeName(value));
@@ -952,7 +952,7 @@ function buildStagePromptAdapter(id, kind, args, createdAt) {
952
952
  }
953
953
 
954
954
  // dist/builtin/workflows/src/shared/stage-ui-broker.ts
955
- import { randomUUID } from "node:crypto";
955
+ import { randomUUID as randomUUID2 } from "node:crypto";
956
956
 
957
957
  // dist/builtin/workflows/src/shared/pending-stage-delivery.ts
958
958
  var PENDING_STAGE_MESSAGE_LIMIT = 50;
@@ -963,7 +963,7 @@ function queueStageMessage(messages, input, senderGroup, runGroup, stageIdentity
963
963
  }
964
964
  const messageId = input.message.id;
965
965
  const queued = pendingStageMessagesFor(messages, input.runId, input.stageKey, stageIdentity);
966
- const existing = messages.find((entry2) => entry2.runId === input.runId && entry2.id === messageId);
966
+ const existing = messages.find((entry) => entry.runId === input.runId && entry.id === messageId);
967
967
  if (existing !== undefined) {
968
968
  if (pendingStageMessageSignature(existing, stageIdentity) !== pendingStageMessageSignature(input, stageIdentity)) {
969
969
  return {
@@ -1013,7 +1013,7 @@ function queueStickyStageMessage(messages, input, senderGroup, runGroup) {
1013
1013
  return { ok: false, reason: "group_mismatch", runId: input.runId, stageKey: input.targetPath };
1014
1014
  }
1015
1015
  const messageId = input.message.id;
1016
- const existing = messages.find((entry2) => entry2.runId === input.runId && entry2.id === messageId);
1016
+ const existing = messages.find((entry) => entry.runId === input.runId && entry.id === messageId);
1017
1017
  if (existing !== undefined) {
1018
1018
  if (pendingStageMessageSignature(existing) !== pendingStageMessageSignature(input)) {
1019
1019
  return {
@@ -1064,7 +1064,7 @@ function queuedStickyCount(messages, runId, targetPath) {
1064
1064
  return messages.filter((entry) => entry.runId === runId && entry.sticky === true && entry.targetPath === targetPath && entry.status === "queued").length;
1065
1065
  }
1066
1066
  function recordPendingStageMessageDeliveries(messages, runId, messageId, records, deliveredAt) {
1067
- const index = messages.findIndex((entry2) => entry2.runId === runId && entry2.id === messageId && entry2.sticky === true && entry2.status === "queued");
1067
+ const index = messages.findIndex((entry) => entry.runId === runId && entry.id === messageId && entry.sticky === true && entry.status === "queued");
1068
1068
  if (index < 0)
1069
1069
  return messages;
1070
1070
  const entry = messages[index];
@@ -1507,6 +1507,7 @@ function compactStage(stage) {
1507
1507
  attemptedModels: _attemptedModels,
1508
1508
  modelAttempts: _modelAttempts,
1509
1509
  result: _result,
1510
+ structured: _structured,
1510
1511
  ...metadata
1511
1512
  } = stage;
1512
1513
  return {
@@ -1565,6 +1566,173 @@ function deepFreezeGraphValue(value) {
1565
1566
  }
1566
1567
  }
1567
1568
 
1569
+ // dist/builtin/workflows/src/shared/workflow-observation-runtime.ts
1570
+ import { randomUUID } from "node:crypto";
1571
+
1572
+ // dist/builtin/workflows/src/shared/workflow-activity.ts
1573
+ function workflowActivityNodeKey(runId, nodeId) {
1574
+ return `${runId}:${nodeId}`;
1575
+ }
1576
+
1577
+ // dist/builtin/workflows/src/shared/workflow-observation-runtime.ts
1578
+ class WorkflowObservationRuntime {
1579
+ runs;
1580
+ invalidate;
1581
+ liveRunIds = new Set;
1582
+ executingStageIds = new Set;
1583
+ executingToolNodeIds = new Set;
1584
+ stoppingRunIds = new Set;
1585
+ retryingStageIds = new Set;
1586
+ acknowledgedFailureRunIds = new Set;
1587
+ listeners = new Set;
1588
+ replayStageIds = new Set;
1589
+ previous = new Map;
1590
+ recoveryDepth = 0;
1591
+ constructor(runs, invalidate) {
1592
+ this.runs = runs;
1593
+ this.invalidate = invalidate;
1594
+ }
1595
+ get recovering() {
1596
+ return this.recoveryDepth > 0;
1597
+ }
1598
+ startRun(runId) {
1599
+ this.liveRunIds.add(runId);
1600
+ this.stoppingRunIds.delete(runId);
1601
+ }
1602
+ finishRun(runId) {
1603
+ this.liveRunIds.delete(runId);
1604
+ this.stoppingRunIds.delete(runId);
1605
+ for (const ids of [
1606
+ this.executingStageIds,
1607
+ this.executingToolNodeIds,
1608
+ this.retryingStageIds,
1609
+ this.replayStageIds
1610
+ ]) {
1611
+ for (const id of ids)
1612
+ if (id.startsWith(`${runId}:`))
1613
+ ids.delete(id);
1614
+ }
1615
+ this.invalidate();
1616
+ }
1617
+ emit(event) {
1618
+ for (const listener of this.listeners) {
1619
+ try {
1620
+ listener(event);
1621
+ } catch {}
1622
+ }
1623
+ }
1624
+ rootRunId(run) {
1625
+ if (run.rootRunId !== undefined)
1626
+ return run.rootRunId;
1627
+ if (run.parentRunId === undefined)
1628
+ return run.id;
1629
+ const parent = this.runs().find((candidate) => candidate.id === run.parentRunId);
1630
+ return parent ? this.rootRunId(parent) : run.parentRunId;
1631
+ }
1632
+ lifecycle(target, attribution = "unknown") {
1633
+ if (this.recovering && !this.liveRunIds.has(target.runId))
1634
+ return;
1635
+ const run = this.runs().find((candidate) => candidate.id === target.runId);
1636
+ if (!run)
1637
+ return;
1638
+ const rootRunId = this.rootRunId(run);
1639
+ const now = Date.now();
1640
+ this.emit({
1641
+ kind: "lifecycle",
1642
+ event: {
1643
+ type: "workflow_lifecycle",
1644
+ eventId: randomUUID(),
1645
+ runId: run.id,
1646
+ rootRunId,
1647
+ occurredAt: now,
1648
+ observedAt: now,
1649
+ target: canonicalTarget(target, rootRunId),
1650
+ attribution,
1651
+ delivery: target.kind === "stage" && this.replayStageIds.has(workflowActivityNodeKey(run.id, target.stageId)) ? "replay" : "live"
1652
+ }
1653
+ });
1654
+ }
1655
+ control(runId, action, attribution = "unknown") {
1656
+ const run = this.runs().find((candidate) => candidate.id === runId);
1657
+ if (!run)
1658
+ return;
1659
+ if ((action === "quit" || action === "kill" || action === "interrupt") && this.liveRunIds.has(runId))
1660
+ this.stoppingRunIds.add(runId);
1661
+ if (action === "resume")
1662
+ this.stoppingRunIds.delete(runId);
1663
+ this.lifecycle({ kind: "run", runId, status: run.status, action }, attribution);
1664
+ this.invalidate();
1665
+ }
1666
+ heartbeat(runId, scheduledAt, intervalMinutes) {
1667
+ const run = this.runs().find((candidate) => candidate.id === runId);
1668
+ if (run)
1669
+ this.emit({
1670
+ kind: "heartbeat",
1671
+ event: { type: "workflow_heartbeat", runId, rootRunId: this.rootRunId(run), scheduledAt, intervalMinutes }
1672
+ });
1673
+ }
1674
+ beginRecovery() {
1675
+ this.recoveryDepth++;
1676
+ if (this.recoveryDepth === 1)
1677
+ this.emit({ kind: "availability" });
1678
+ let ended = false;
1679
+ return () => {
1680
+ if (ended)
1681
+ return;
1682
+ ended = true;
1683
+ this.capture();
1684
+ this.recoveryDepth--;
1685
+ if (!this.recovering)
1686
+ this.emit({ kind: "availability" });
1687
+ };
1688
+ }
1689
+ capture() {
1690
+ const next = new Map;
1691
+ const visit = (key, target, historical = false) => {
1692
+ next.set(key, target);
1693
+ const previous = this.previous.get(key);
1694
+ if (!historical && this.liveRunIds.has(target.runId) && previous?.status !== target.status) {
1695
+ this.lifecycle(previous && previous.kind !== "prompt" && target.kind !== "prompt" ? { ...target, previousStatus: previous.status } : target, this.runs().find((run) => run.id === target.runId)?.origin);
1696
+ }
1697
+ };
1698
+ for (const run of this.runs()) {
1699
+ const existing = this.previous.has(`run:${run.id}`);
1700
+ visit(`run:${run.id}`, { kind: "run", runId: run.id, status: run.status });
1701
+ for (const stage of run.stages) {
1702
+ visit(`stage:${workflowActivityNodeKey(run.id, stage.id)}`, { kind: "stage", runId: run.id, stageId: stage.id, stageName: stage.name, status: stage.status }, !existing);
1703
+ if (stage.pendingPrompt)
1704
+ visit(`prompt:${stage.pendingPrompt.id}`, {
1705
+ kind: "prompt",
1706
+ runId: run.id,
1707
+ stageId: stage.id,
1708
+ promptId: stage.pendingPrompt.id,
1709
+ status: "opened"
1710
+ }, !existing);
1711
+ }
1712
+ for (const tool of run.toolNodes ?? [])
1713
+ visit(`tool:${workflowActivityNodeKey(run.id, tool.id)}`, { kind: "tool", runId: run.id, toolNodeId: tool.id, toolName: tool.name, status: tool.status }, !existing);
1714
+ if (run.pendingPrompt)
1715
+ visit(`prompt:${run.pendingPrompt.id}`, { kind: "prompt", runId: run.id, promptId: run.pendingPrompt.id, status: "opened" }, !existing);
1716
+ }
1717
+ this.previous = next;
1718
+ }
1719
+ }
1720
+ var workflowObservationRuntimeKey = Symbol.for("atomic-workflows/store-observation-runtime@1");
1721
+ function canonicalTarget(target, rootRunId) {
1722
+ if (target.runId === rootRunId)
1723
+ return target;
1724
+ switch (target.kind) {
1725
+ case "stage":
1726
+ return { ...target, stageId: workflowActivityNodeKey(target.runId, target.stageId) };
1727
+ case "tool":
1728
+ return { ...target, toolNodeId: workflowActivityNodeKey(target.runId, target.toolNodeId) };
1729
+ case "prompt":
1730
+ return target.stageId === undefined ? target : { ...target, stageId: workflowActivityNodeKey(target.runId, target.stageId) };
1731
+ case "run":
1732
+ return target;
1733
+ }
1734
+ }
1735
+
1568
1736
  // dist/builtin/workflows/src/shared/store-internal.ts
1569
1737
  var TERMINAL_STATUSES = new Set([
1570
1738
  "completed",
@@ -1667,6 +1835,7 @@ function createStoreState() {
1667
1835
  function createStoreContext(state = createStoreState()) {
1668
1836
  let cachedGraphVersion = -1;
1669
1837
  let cachedGraphSnapshot;
1838
+ const observation = new WorkflowObservationRuntime(() => state.runs, bumpAndNotify);
1670
1839
  function snapshot() {
1671
1840
  return JSON.parse(JSON.stringify({ runs: state.runs, notices: state.notices, version: state.version }));
1672
1841
  }
@@ -1678,6 +1847,7 @@ function createStoreContext(state = createStoreState()) {
1678
1847
  return cachedGraphSnapshot;
1679
1848
  }
1680
1849
  function notify() {
1850
+ observation.capture();
1681
1851
  for (const fn of state.invalidationListeners) {
1682
1852
  try {
1683
1853
  fn();
@@ -1733,6 +1903,7 @@ function createStoreContext(state = createStoreState()) {
1733
1903
  const prompt = stage.pendingPrompt;
1734
1904
  if (!prompt)
1735
1905
  return;
1906
+ observation.lifecycle({ kind: "prompt", runId, stageId: stage.id, promptId: prompt.id, status: "cancelled" });
1736
1907
  stage.pendingPrompt = undefined;
1737
1908
  state.stagePromptDrafts.delete(stagePromptDraftKey(runId, stage.id, prompt.id));
1738
1909
  rejectPrompt(prompt.id, reason);
@@ -1744,6 +1915,7 @@ function createStoreContext(state = createStoreState()) {
1744
1915
  }
1745
1916
  return {
1746
1917
  state,
1918
+ observation,
1747
1919
  snapshot,
1748
1920
  graphSnapshot,
1749
1921
  notify,
@@ -1913,8 +2085,8 @@ function createPendingStageDeliveryStoreMethods(context) {
1913
2085
  };
1914
2086
  }
1915
2087
  function resolvePendingStageIdentity(run, stageKey) {
1916
- const exactIds = run.stages.filter((stage2) => stage2.id === stageKey);
1917
- const candidates = exactIds.length > 0 ? exactIds : run.stages.filter((stage2) => stage2.name === stageKey);
2088
+ const exactIds = run.stages.filter((stage) => stage.id === stageKey);
2089
+ const candidates = exactIds.length > 0 ? exactIds : run.stages.filter((stage) => stage.name === stageKey);
1918
2090
  if (candidates.length !== 1)
1919
2091
  return;
1920
2092
  const stage = candidates[0];
@@ -1953,6 +2125,7 @@ function createPromptStoreMethods(context) {
1953
2125
  const pending = run.pendingPrompt;
1954
2126
  if (!pending || pending.id !== promptId)
1955
2127
  return false;
2128
+ context.observation.lifecycle({ kind: "prompt", runId, promptId, status: "answered" });
1956
2129
  run.pendingPrompt = undefined;
1957
2130
  context.bumpAndNotify();
1958
2131
  const entry = state.resolvers.get(promptId);
@@ -2023,6 +2196,13 @@ function createPromptStoreMethods(context) {
2023
2196
  state.stagePromptAnswers.delete(context.stagePromptAnswerKey(runId, stageId));
2024
2197
  delete stage.promptAnswerState;
2025
2198
  }
2199
+ context.observation.lifecycle({
2200
+ kind: "prompt",
2201
+ runId,
2202
+ stageId,
2203
+ promptId,
2204
+ status: options.recordAnswer === false ? "cancelled" : "answered"
2205
+ });
2026
2206
  stage.pendingPrompt = undefined;
2027
2207
  if (stage.status === "awaiting_input") {
2028
2208
  stage.status = "running";
@@ -2239,6 +2419,7 @@ function createRunStoreMethods(context) {
2239
2419
  }
2240
2420
  const pending = run.pendingPrompt;
2241
2421
  if (pending) {
2422
+ context.observation.lifecycle({ kind: "prompt", runId, promptId: pending.id, status: "cancelled" });
2242
2423
  run.pendingPrompt = undefined;
2243
2424
  context.rejectPrompt(pending.id, `atomic-workflows: run ${runId} ended before prompt resolved`);
2244
2425
  }
@@ -2320,6 +2501,7 @@ function createRunStoreMethods(context) {
2320
2501
  const run = state.runs[index];
2321
2502
  const pending = run.pendingPrompt;
2322
2503
  if (pending) {
2504
+ context.observation.lifecycle({ kind: "prompt", runId, promptId: pending.id, status: "cancelled" });
2323
2505
  context.rejectPrompt(pending.id, `atomic-workflows: run ${runId} was removed before prompt resolved`);
2324
2506
  }
2325
2507
  context.rejectAllStagePrompts(runId, run, `atomic-workflows: run ${runId} was removed before prompt resolved`);
@@ -2480,6 +2662,8 @@ function createToolNodeStoreMethods(context) {
2480
2662
  return false;
2481
2663
  node.status = "running";
2482
2664
  node.startedAt = startedAt;
2665
+ if (context.observation.liveRunIds.has(runId))
2666
+ context.observation.executingToolNodeIds.add(workflowActivityNodeKey(runId, nodeId));
2483
2667
  context.bumpAndNotify();
2484
2668
  return true;
2485
2669
  },
@@ -2487,6 +2671,7 @@ function createToolNodeStoreMethods(context) {
2487
2671
  const node = context.findRun(runId)?.toolNodes?.find((candidate) => candidate.id === nodeId);
2488
2672
  if (node === undefined || node.status === "completed" || node.status === "failed" || node.status === "cached" || node.status === "cancelled")
2489
2673
  return false;
2674
+ context.observation.executingToolNodeIds.delete(workflowActivityNodeKey(runId, nodeId));
2490
2675
  node.status = update.status;
2491
2676
  if (update.endedAt !== undefined)
2492
2677
  node.endedAt = update.endedAt;
@@ -2516,6 +2701,9 @@ function createStageStoreMethods(context) {
2516
2701
  if (!run.stages.some((s) => s.id === stage.id)) {
2517
2702
  run.stages.push(stage);
2518
2703
  }
2704
+ if (stage.status === "running" && context.observation.liveRunIds.has(runId)) {
2705
+ context.observation.executingStageIds.add(workflowActivityNodeKey(runId, stage.id));
2706
+ }
2519
2707
  context.bumpAndNotify();
2520
2708
  },
2521
2709
  recordStageWorkflowChildRun(runId, stageId, ref) {
@@ -2525,8 +2713,12 @@ function createStageStoreMethods(context) {
2525
2713
  const stage = context.findStage(run, stageId);
2526
2714
  if (!stage)
2527
2715
  return false;
2528
- if (stage.workflowChildRun?.runId === ref.runId && stage.workflowChildRun.alias === ref.alias && stage.workflowChildRun.workflow === ref.workflow)
2716
+ const released = context.observation.executingStageIds.delete(workflowActivityNodeKey(runId, stageId));
2717
+ if (stage.workflowChildRun?.runId === ref.runId && stage.workflowChildRun.alias === ref.alias && stage.workflowChildRun.workflow === ref.workflow) {
2718
+ if (released)
2719
+ context.bumpAndNotify();
2529
2720
  return false;
2721
+ }
2530
2722
  stage.workflowChildRun = { ...ref };
2531
2723
  context.bumpAndNotify();
2532
2724
  return true;
@@ -2565,6 +2757,7 @@ function createStageStoreMethods(context) {
2565
2757
  const existing = context.findStage(run, stage.id);
2566
2758
  if (!existing)
2567
2759
  return;
2760
+ context.observation.executingStageIds.delete(workflowActivityNodeKey(runId, stage.id));
2568
2761
  existing.status = stage.status;
2569
2762
  existing.endedAt = stage.endedAt;
2570
2763
  if (existing.endedAt !== undefined && existing.pausedAt !== undefined) {
@@ -2788,6 +2981,7 @@ function createStageStoreMethods(context) {
2788
2981
  context.bumpAndNotify();
2789
2982
  return false;
2790
2983
  }
2984
+ context.observation.executingStageIds.delete(workflowActivityNodeKey(runId, stageId));
2791
2985
  stage.status = "paused";
2792
2986
  stage.pausedAt = nextControlTimestamp(pausedAt, stage.resumedAt);
2793
2987
  stage.resumedAt = undefined;
@@ -2820,6 +3014,8 @@ function createStageStoreMethods(context) {
2820
3014
  return false;
2821
3015
  }
2822
3016
  const resumedTs = nextControlTimestamp(resumedAt, stage.pausedAt);
3017
+ if (context.observation.liveRunIds.has(runId))
3018
+ context.observation.executingStageIds.add(workflowActivityNodeKey(runId, stageId));
2823
3019
  stage.status = "running";
2824
3020
  if (stage.startedAt !== undefined) {
2825
3021
  stage.pausedDurationMs = accumulatePausedDurationMs(stage.pausedDurationMs, stage.pausedAt, resumedTs);
@@ -2842,13 +3038,18 @@ function createStageStoreMethods(context) {
2842
3038
  // dist/builtin/workflows/src/shared/store-factory.ts
2843
3039
  function createStore() {
2844
3040
  const context = createStoreContext();
2845
- return {
3041
+ const created = {
3042
+ [workflowObservationRuntimeKey]: context.observation,
2846
3043
  ...createRunStoreMethods(context),
2847
3044
  ...createPendingStageDeliveryStoreMethods(context),
2848
3045
  ...createStageStoreMethods(context),
2849
3046
  ...createToolNodeStoreMethods(context),
2850
3047
  ...createPromptStoreMethods(context)
2851
3048
  };
3049
+ return created;
3050
+ }
3051
+ function workflowObservationRuntime(activeStore) {
3052
+ return activeStore[workflowObservationRuntimeKey];
2852
3053
  }
2853
3054
  var SESSION_KEY2 = "workflows:store:v1";
2854
3055
  var singleton2 = createSessionScopedSingleton(SESSION_KEY2, createStore);
@@ -2858,7 +3059,7 @@ function key(runId, stageId) {
2858
3059
  return `${runId}\x00${stageId}`;
2859
3060
  }
2860
3061
  function nextRequestId() {
2861
- return `stage-ui-${randomUUID()}`;
3062
+ return `stage-ui-${randomUUID2()}`;
2862
3063
  }
2863
3064
 
2864
3065
  class StageUiBroker {
@@ -3265,8 +3466,8 @@ function normalizeUIContext(adapter) {
3265
3466
  };
3266
3467
  }
3267
3468
  function stringField(value, keys) {
3268
- for (const key2 of keys) {
3269
- const candidate = value[key2];
3469
+ for (const key of keys) {
3470
+ const candidate = value[key];
3270
3471
  if (typeof candidate === "string" && candidate.length > 0)
3271
3472
  return candidate;
3272
3473
  }
@@ -3463,17 +3664,17 @@ function schemaIsRequired(schema) {
3463
3664
  import { Value as Value2 } from "typebox/value";
3464
3665
  function validateInputs(schema, inputs) {
3465
3666
  const errors = [];
3466
- for (const key2 of Object.keys(inputs)) {
3467
- if (!(key2 in schema)) {
3468
- errors.push({ key: key2, reason: "unknown input key (not declared by this workflow)" });
3667
+ for (const key of Object.keys(inputs)) {
3668
+ if (!(key in schema)) {
3669
+ errors.push({ key, reason: "unknown input key (not declared by this workflow)" });
3469
3670
  }
3470
3671
  }
3471
- for (const [key2, def] of Object.entries(schema)) {
3472
- const value = inputs[key2];
3672
+ for (const [key, def] of Object.entries(schema)) {
3673
+ const value = inputs[key];
3473
3674
  let hasTypeError = false;
3474
3675
  if (value === undefined) {
3475
3676
  if (schemaIsRequired(def)) {
3476
- errors.push({ key: key2, reason: "required input is missing" });
3677
+ errors.push({ key, reason: "required input is missing" });
3477
3678
  }
3478
3679
  continue;
3479
3680
  }
@@ -3481,25 +3682,25 @@ function validateInputs(schema, inputs) {
3481
3682
  switch (kind) {
3482
3683
  case "text":
3483
3684
  if (typeof value !== "string") {
3484
- errors.push({ key: key2, reason: `expected string, got ${workflowSerializableTypeName(value)}` });
3685
+ errors.push({ key, reason: `expected string, got ${workflowSerializableTypeName(value)}` });
3485
3686
  hasTypeError = true;
3486
3687
  }
3487
3688
  break;
3488
3689
  case "number":
3489
3690
  if (typeof value !== "number" || !Number.isFinite(value)) {
3490
- errors.push({ key: key2, reason: `expected finite number, got ${workflowSerializableTypeName(value)}` });
3691
+ errors.push({ key, reason: `expected finite number, got ${workflowSerializableTypeName(value)}` });
3491
3692
  hasTypeError = true;
3492
3693
  }
3493
3694
  break;
3494
3695
  case "integer":
3495
3696
  if (typeof value !== "number" || !Number.isInteger(value)) {
3496
- errors.push({ key: key2, reason: `expected integer, got ${workflowSerializableTypeName(value)}` });
3697
+ errors.push({ key, reason: `expected integer, got ${workflowSerializableTypeName(value)}` });
3497
3698
  hasTypeError = true;
3498
3699
  }
3499
3700
  break;
3500
3701
  case "boolean":
3501
3702
  if (typeof value !== "boolean") {
3502
- errors.push({ key: key2, reason: `expected boolean, got ${workflowSerializableTypeName(value)}` });
3703
+ errors.push({ key, reason: `expected boolean, got ${workflowSerializableTypeName(value)}` });
3503
3704
  hasTypeError = true;
3504
3705
  }
3505
3706
  break;
@@ -3507,24 +3708,24 @@ function validateInputs(schema, inputs) {
3507
3708
  const choices = schemaChoices(def) ?? [];
3508
3709
  const allowed = choices.join(", ");
3509
3710
  if (typeof value !== "string") {
3510
- errors.push({ key: key2, reason: `expected one of [${allowed}], got ${workflowSerializableTypeName(value)}` });
3711
+ errors.push({ key, reason: `expected one of [${allowed}], got ${workflowSerializableTypeName(value)}` });
3511
3712
  hasTypeError = true;
3512
3713
  } else if (!choices.includes(value)) {
3513
- errors.push({ key: key2, reason: `must be one of [${allowed}]` });
3714
+ errors.push({ key, reason: `must be one of [${allowed}]` });
3514
3715
  }
3515
3716
  break;
3516
3717
  }
3517
3718
  default:
3518
3719
  if (!Value2.Check(def, value)) {
3519
3720
  const first = [...Value2.Errors(def, value)][0];
3520
- errors.push({ key: key2, reason: first === undefined ? `does not match ${kind} schema` : first.message });
3721
+ errors.push({ key, reason: first === undefined ? `does not match ${kind} schema` : first.message });
3521
3722
  hasTypeError = true;
3522
3723
  }
3523
3724
  break;
3524
3725
  }
3525
- const serializableError = hasTypeError ? undefined : workflowSerializableValidationError(value, `input "${key2}"`);
3726
+ const serializableError = hasTypeError ? undefined : workflowSerializableValidationError(value, `input "${key}"`);
3526
3727
  if (serializableError !== undefined) {
3527
- errors.push({ key: key2, reason: serializableError.replace(/^input "[^"]+" /, "") });
3728
+ errors.push({ key, reason: serializableError.replace(/^input "[^"]+" /, "") });
3528
3729
  }
3529
3730
  }
3530
3731
  return errors;
@@ -3533,18 +3734,19 @@ function validateInputs(schema, inputs) {
3533
3734
  // dist/builtin/workflows/src/runs/foreground/executor-inputs.ts
3534
3735
  function resolveInputs(schema, provided) {
3535
3736
  const resolved = {};
3536
- for (const [key2, value] of Object.entries(provided)) {
3737
+ for (const [key, value] of Object.entries(provided)) {
3537
3738
  if (value !== undefined)
3538
- resolved[key2] = value;
3739
+ resolved[key] = value;
3539
3740
  }
3540
- const withDefaults = Value3.Default(Type2.Object(schema, { additionalProperties: true }), resolved);
3541
- for (const [key2, value] of Object.entries(withDefaults)) {
3741
+ const ownedInputs = Value3.Clone(resolved);
3742
+ const withDefaults = Value3.Default(Type2.Object(schema, { additionalProperties: true }), ownedInputs);
3743
+ for (const [key, value] of Object.entries(withDefaults)) {
3542
3744
  if (value !== undefined)
3543
- resolved[key2] = value;
3745
+ resolved[key] = value;
3544
3746
  }
3545
- for (const [key2, schemaDef] of Object.entries(schema)) {
3546
- if (schemaIsRequired(schemaDef) && resolved[key2] === undefined) {
3547
- throw new TypeError(`atomic-workflows: required input "${key2}" not provided`);
3747
+ for (const [key, schemaDef] of Object.entries(schema)) {
3748
+ if (schemaIsRequired(schemaDef) && resolved[key] === undefined) {
3749
+ throw new TypeError(`atomic-workflows: required input "${key}" not provided`);
3548
3750
  }
3549
3751
  }
3550
3752
  return resolved;
@@ -3590,12 +3792,12 @@ ${formatValidationErrors(errors)}`);
3590
3792
  function asRecord(value) {
3591
3793
  return value !== null && typeof value === "object" ? value : undefined;
3592
3794
  }
3593
- function field(value, key2) {
3594
- return asRecord(value)?.[key2];
3795
+ function field(value, key) {
3796
+ return asRecord(value)?.[key];
3595
3797
  }
3596
- function safeField(value, key2) {
3798
+ function safeField(value, key) {
3597
3799
  try {
3598
- return field(value, key2);
3800
+ return field(value, key);
3599
3801
  } catch {
3600
3802
  return;
3601
3803
  }
@@ -3625,8 +3827,8 @@ function findProcessFailureError(value, seen, depth) {
3625
3827
  return value;
3626
3828
  if (nonEmptyProcessOutput(safeField(value, "stderr")))
3627
3829
  return value;
3628
- for (const key2 of ["cause", "error", "response", "body"]) {
3629
- const selected = findProcessFailureError(safeField(value, key2), seen, depth + 1);
3830
+ for (const key of ["cause", "error", "response", "body"]) {
3831
+ const selected = findProcessFailureError(safeField(value, key), seen, depth + 1);
3630
3832
  if (selected !== undefined)
3631
3833
  return selected;
3632
3834
  }
@@ -3654,8 +3856,8 @@ function selectProcessFailureError(error) {
3654
3856
  function hasProcessFailureEvidence(error) {
3655
3857
  return findProcessFailureError(error, new Set, 0) !== undefined;
3656
3858
  }
3657
- function stringField2(value, key2) {
3658
- const raw = field(value, key2);
3859
+ function stringField2(value, key) {
3860
+ const raw = field(value, key);
3659
3861
  return typeof raw === "string" && raw.length > 0 ? raw : undefined;
3660
3862
  }
3661
3863
  function errorMessage(error) {
@@ -3837,15 +4039,15 @@ function redactSensitiveText(value) {
3837
4039
  var TOOL_FAILURE_TEXT_LIMIT_BYTES = 16384;
3838
4040
  var TRUNCATION_PREFIX = `[workflow tool output truncated; showing final bytes]
3839
4041
  `;
3840
- function safeField2(error, key2) {
4042
+ function safeField2(error, key) {
3841
4043
  try {
3842
- return field(error, key2);
4044
+ return field(error, key);
3843
4045
  } catch {
3844
4046
  return;
3845
4047
  }
3846
4048
  }
3847
- function exposedText(error, key2) {
3848
- const value = safeField2(error, key2);
4049
+ function exposedText(error, key) {
4050
+ const value = safeField2(error, key);
3849
4051
  if (typeof value === "string")
3850
4052
  return value;
3851
4053
  try {
@@ -3954,7 +4156,7 @@ function canonicalJsonString(value) {
3954
4156
  return `[${value.map(canonicalJsonString).join(",")}]`;
3955
4157
  const object = value;
3956
4158
  const keys = Object.keys(object).sort();
3957
- return `{${keys.map((key2) => `${JSON.stringify(key2)}:${canonicalJsonString(object[key2])}`).join(",")}}`;
4159
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJsonString(object[key])}`).join(",")}}`;
3958
4160
  }
3959
4161
  // dist/builtin/workflows/src/durable/backend.ts
3960
4162
  function pendingStageMessagesForDurableRun(backend, logicalRunId, rootWorkflowId = logicalRunId) {
@@ -3993,13 +4195,13 @@ function cloneWorkflowChildReplaySnapshot(snapshot) {
3993
4195
  }
3994
4196
  function workflowChildReplaySnapshot(alias, childResult) {
3995
4197
  const outputs = {};
3996
- for (const [key2, value] of Object.entries(childResult.outputs)) {
4198
+ for (const [key, value] of Object.entries(childResult.outputs)) {
3997
4199
  if (value === undefined)
3998
4200
  continue;
3999
4201
  try {
4000
- outputs[key2] = cloneWorkflowChildValue(value);
4202
+ outputs[key] = cloneWorkflowChildValue(value);
4001
4203
  } catch (err) {
4002
- throw new Error(`atomic-workflows: child workflow "${alias}" (${childResult.workflow}) exposed output "${key2}" is not serializable for continuation replay: ${workflowChildSerializationMessage(err)}`, { cause: err });
4204
+ throw new Error(`atomic-workflows: child workflow "${alias}" (${childResult.workflow}) exposed output "${key}" is not serializable for continuation replay: ${workflowChildSerializationMessage(err)}`, { cause: err });
4003
4205
  }
4004
4206
  }
4005
4207
  const exitReason = childResult.exited === true ? childResult.exitReason : undefined;
@@ -4148,10 +4350,10 @@ function durableStageGroupKey(stage, stages = [stage]) {
4148
4350
  function groupByDurableStageKey(stages) {
4149
4351
  const groups = new Map;
4150
4352
  for (const stage of stages) {
4151
- const key2 = durableStageGroupKey(stage, stages);
4152
- const group = groups.get(key2) ?? [];
4353
+ const key = durableStageGroupKey(stage, stages);
4354
+ const group = groups.get(key) ?? [];
4153
4355
  group.push(stage);
4154
- groups.set(key2, group);
4356
+ groups.set(key, group);
4155
4357
  }
4156
4358
  return groups;
4157
4359
  }
@@ -4193,13 +4395,13 @@ function hasCycle(topologies) {
4193
4395
  function parseWorkflowChildResult(value) {
4194
4396
  if (!isOrdinaryObject(value))
4195
4397
  return;
4196
- const workflow2 = value.workflow;
4398
+ const workflow = value.workflow;
4197
4399
  const runId = value.runId;
4198
4400
  const status = value.status;
4199
4401
  const exited = value.exited;
4200
4402
  const outputs = value.outputs;
4201
4403
  const exitReason = value.exitReason;
4202
- if (typeof workflow2 !== "string" || typeof runId !== "string" || !isOrdinaryObject(outputs))
4404
+ if (typeof workflow !== "string" || typeof runId !== "string" || !isOrdinaryObject(outputs))
4203
4405
  return;
4204
4406
  if (exited === false) {
4205
4407
  if (status !== "completed" || exitReason !== undefined)
@@ -4637,7 +4839,7 @@ function durableStageCheckpointMetadata(stage, run, sourceOrder) {
4637
4839
  }
4638
4840
 
4639
4841
  // dist/builtin/workflows/src/durable/tool-primitive.ts
4640
- import { runCallback } from "@bastani/atomic";
4842
+ import { collectAgentTasks, runCallback } from "@bastani/atomic";
4641
4843
 
4642
4844
  // dist/builtin/workflows/src/engine/workflow-tool-abort.ts
4643
4845
  class WorkflowToolAbortError extends Error {
@@ -4767,6 +4969,58 @@ function captureCallbackSource(fn) {
4767
4969
  return;
4768
4970
  }
4769
4971
  }
4972
+ async function awaitTerminalTask(task) {
4973
+ for (;; ) {
4974
+ const observed = await task.host.waitForTask(task.taskId);
4975
+ if (!observed.ok)
4976
+ throw new Error(`${observed.error.code}: ${observed.error.message}`);
4977
+ if (observed.value.kind === "settled")
4978
+ return observed.value.result;
4979
+ }
4980
+ }
4981
+ function replaceTaskObservations(value, terminal) {
4982
+ if (!value || typeof value !== "object")
4983
+ return value;
4984
+ if (Array.isArray(value)) {
4985
+ const next = value.map((item) => replaceTaskObservations(item, terminal));
4986
+ return next.some((item, index) => item !== value[index]) ? next : value;
4987
+ }
4988
+ const object = value;
4989
+ if (object.kind === "yielded" && typeof object.taskId === "string") {
4990
+ const result = terminal.get(object.taskId);
4991
+ if (result)
4992
+ return { kind: "settled", taskId: object.taskId, result };
4993
+ }
4994
+ let changed = false;
4995
+ const next = {};
4996
+ for (const [key, item] of Object.entries(object)) {
4997
+ next[key] = replaceTaskObservations(item, terminal);
4998
+ changed ||= next[key] !== item;
4999
+ }
5000
+ if (changed && next.details !== object.details && next.details && typeof next.details === "object" && !Array.isArray(next.details) && Array.isArray(object.content)) {
5001
+ const details = next.details;
5002
+ const original = object.details;
5003
+ if (details.taskResponse !== undefined && details.taskResponse !== original.taskResponse) {
5004
+ const before = JSON.stringify(original.taskResponse);
5005
+ next.content = object.content.map((part) => {
5006
+ if (!part || typeof part !== "object" || Array.isArray(part))
5007
+ return part;
5008
+ const content = part;
5009
+ return content.type === "text" && content.text === before ? { ...content, text: JSON.stringify(details.taskResponse) } : part;
5010
+ });
5011
+ }
5012
+ }
5013
+ return changed ? next : value;
5014
+ }
5015
+ function invokeTaskCallback(fn, signal) {
5016
+ return collectAgentTasks(signal, () => fn({ signal }), async (value, tasks) => {
5017
+ if (tasks.length === 0)
5018
+ return value;
5019
+ const terminal = new Map;
5020
+ await Promise.all(tasks.map(async (task) => terminal.set(task.taskId, await awaitTerminalTask(task))));
5021
+ return replaceTaskObservations(value, terminal);
5022
+ });
5023
+ }
4770
5024
  function createToolPrimitive(input) {
4771
5025
  const ordinals = new Map;
4772
5026
  return (name, args, fn, options) => {
@@ -4883,11 +5137,11 @@ async function executeToolInvocation(input, ordinals, name, args, fn, options, c
4883
5137
  control.noteCancelled();
4884
5138
  else
4885
5139
  input.onFailureObserved?.(error, node.id);
4886
- const endedAt2 = Date.now();
5140
+ const endedAt = Date.now();
4887
5141
  input.onNodeEnd?.(node.id, {
4888
5142
  status: cancelled ? "cancelled" : "failed",
4889
- endedAt: endedAt2,
4890
- ...node.startedAt !== undefined ? { durationMs: Math.max(0, endedAt2 - node.startedAt) } : {},
5143
+ endedAt,
5144
+ ...node.startedAt !== undefined ? { durationMs: Math.max(0, endedAt - node.startedAt) } : {},
4891
5145
  error: error instanceof Error ? error.message : String(error)
4892
5146
  });
4893
5147
  input.onNodeSettle?.(node.id);
@@ -4942,7 +5196,7 @@ async function executeTimedToolAttempt(toolName, runId, fn, baseSignal, timeoutM
4942
5196
  const timeoutController = new AbortController;
4943
5197
  const attemptSignal = AbortSignal.any([baseSignal, timeoutController.signal]);
4944
5198
  return runCallback({ kind: "workflow.ctx_tool", name: toolName, runId }, async () => {
4945
- const callbackResult = Promise.resolve().then(() => fn({ signal: attemptSignal })).then((value) => ({ kind: "value", value }), (error) => ({ kind: "error", error }));
5199
+ const callbackResult = Promise.resolve().then(() => invokeTaskCallback(fn, attemptSignal)).then((value) => ({ kind: "value", value }), (error) => ({ kind: "error", error }));
4946
5200
  let cancelDeadline;
4947
5201
  let onAbort;
4948
5202
  let timeoutError;
@@ -4997,7 +5251,7 @@ async function executeLiveToolInvocation(live) {
4997
5251
  try {
4998
5252
  const result = await executeWithRetries(() => {
4999
5253
  attempts += 1;
5000
- const callback = options?.timeoutMs === undefined ? runCallback({ kind: "workflow.ctx_tool", name, runId: input.workflowId }, () => fn({ signal: toolSignal })) : executeTimedToolAttempt(name, input.workflowId, fn, toolSignal, options.timeoutMs);
5254
+ const callback = options?.timeoutMs === undefined ? runCallback({ kind: "workflow.ctx_tool", name, runId: input.workflowId }, () => invokeTaskCallback(fn, toolSignal)) : executeTimedToolAttempt(name, input.workflowId, fn, toolSignal, options.timeoutMs);
5001
5255
  return callback.catch((error) => {
5002
5256
  callbackError = error;
5003
5257
  throw error;
@@ -5060,12 +5314,12 @@ async function executeLiveToolInvocation(live) {
5060
5314
  const callbackFailure = callbackError ?? error;
5061
5315
  if (returnFailure && !callbackCompleted && isExplicitCallbackCancellation(callbackFailure)) {
5062
5316
  input.onFailureObserved?.(callbackFailure, node.id);
5063
- const failure3 = await recordThrowingToolFailure(input, node, { name, args, ...source !== undefined ? { source } : {}, argsHash, ordinal, startedAt }, callbackFailure, attempts);
5317
+ const failure = await recordThrowingToolFailure(input, node, { name, args, ...source !== undefined ? { source } : {}, argsHash, ordinal, startedAt }, callbackFailure, attempts);
5064
5318
  input.onNodeEnd?.(node.id, {
5065
5319
  status: "failed",
5066
- endedAt: failure3.failedAt,
5067
- durationMs: Math.max(0, failure3.failedAt - startedAt),
5068
- error: failure3.message
5320
+ endedAt: failure.failedAt,
5321
+ durationMs: Math.max(0, failure.failedAt - startedAt),
5322
+ error: failure.message
5069
5323
  });
5070
5324
  input.onNodeSettle?.(node.id);
5071
5325
  throw callbackFailure;
@@ -5123,12 +5377,12 @@ async function executeLiveToolInvocation(live) {
5123
5377
  }
5124
5378
  const reportedFailure = timeoutFailure ? callbackError : error;
5125
5379
  input.onFailureObserved?.(reportedFailure, node.id);
5126
- const failure2 = await recordThrowingToolFailure(input, node, { name, args, ...source !== undefined ? { source } : {}, argsHash, ordinal, startedAt }, reportedFailure, attempts);
5380
+ const failure = await recordThrowingToolFailure(input, node, { name, args, ...source !== undefined ? { source } : {}, argsHash, ordinal, startedAt }, reportedFailure, attempts);
5127
5381
  input.onNodeEnd?.(node.id, {
5128
5382
  status: "failed",
5129
- endedAt: failure2.failedAt,
5130
- durationMs: Math.max(0, failure2.failedAt - startedAt),
5131
- error: failure2.message
5383
+ endedAt: failure.failedAt,
5384
+ durationMs: Math.max(0, failure.failedAt - startedAt),
5385
+ error: failure.message
5132
5386
  });
5133
5387
  input.onNodeSettle?.(node.id);
5134
5388
  throw reportedFailure;
@@ -5184,9 +5438,9 @@ var CALLBACK_CANCELLATION_CODES = new Set([
5184
5438
  "err_cancelled"
5185
5439
  ]);
5186
5440
  var CALLBACK_CANCELLATION_STOP_REASONS = new Set(["aborted", "canceled", "cancelled"]);
5187
- function safeCancellationField(error, key2) {
5441
+ function safeCancellationField(error, key) {
5188
5442
  try {
5189
- return field(error, key2);
5443
+ return field(error, key);
5190
5444
  } catch {
5191
5445
  return;
5192
5446
  }
@@ -5213,16 +5467,16 @@ function isExplicitCallbackCancellation(error) {
5213
5467
  return true;
5214
5468
  if (!hasProcessFailure && hasCancellationMarker(CALLBACK_CANCELLATION_CODES, safeCancellationField(current.value, "code")))
5215
5469
  return true;
5216
- for (const key2 of ["cause", "error", "response", "body"]) {
5217
- pending.push({ value: safeCancellationField(current.value, key2), depth: current.depth + 1 });
5470
+ for (const key of ["cause", "error", "response", "body"]) {
5471
+ pending.push({ value: safeCancellationField(current.value, key), depth: current.depth + 1 });
5218
5472
  }
5219
- for (const key2 of ["diagnostics", "errors"]) {
5220
- const entries = safeCancellationField(current.value, key2);
5473
+ for (const key of ["diagnostics", "errors"]) {
5474
+ const entries = safeCancellationField(current.value, key);
5221
5475
  if (!Array.isArray(entries))
5222
5476
  continue;
5223
5477
  for (const entry of entries) {
5224
5478
  pending.push({
5225
- value: key2 === "diagnostics" ? safeCancellationField(entry, "error") ?? entry : entry,
5479
+ value: key === "diagnostics" ? safeCancellationField(entry, "error") ?? entry : entry,
5226
5480
  depth: current.depth + 1
5227
5481
  });
5228
5482
  }
@@ -5702,11 +5956,11 @@ function preferredHydrationTopology(replayValueCheckpoint, checkpoints) {
5702
5956
  }
5703
5957
  return replayValueCheckpoint.topology === undefined ? metadataValue(checkpoints, "topology") : {};
5704
5958
  }
5705
- function metadataValue(checkpoints, key2) {
5959
+ function metadataValue(checkpoints, key) {
5706
5960
  for (let index = checkpoints.length - 1;index >= 0; index -= 1) {
5707
- const value = checkpoints[index]?.[key2];
5961
+ const value = checkpoints[index]?.[key];
5708
5962
  if (value !== undefined)
5709
- return { [key2]: value };
5963
+ return { [key]: value };
5710
5964
  }
5711
5965
  return {};
5712
5966
  }
@@ -5741,7 +5995,7 @@ function stageMetadataCheckpointId(replayKey, stage) {
5741
5995
  result: stage.result ?? ""
5742
5996
  })}`;
5743
5997
  }
5744
- function recordCachedStageIntoStore(store2, runId, name, replayKey, output, completedStageReplayKeys, parentIds, checkpoint) {
5998
+ function recordCachedStageIntoStore(store, runId, name, replayKey, output, completedStageReplayKeys, parentIds, checkpoint) {
5745
5999
  const now = Date.now();
5746
6000
  const sourceStageId = checkpoint?.topology?.run?.runId === runId ? checkpoint.topology.stageId : undefined;
5747
6001
  const stageId = sourceStageId ?? cachedStageId(runId, replayKey);
@@ -5777,16 +6031,16 @@ function recordCachedStageIntoStore(store2, runId, name, replayKey, output, comp
5777
6031
  ...checkpoint?.artifacts !== undefined ? { artifacts: checkpoint.artifacts } : {},
5778
6032
  ...checkpoint?.warnings !== undefined ? { warnings: checkpoint.warnings } : {}
5779
6033
  };
5780
- store2.recordStageStart(runId, snapshot);
5781
- store2.recordStageEnd(runId, snapshot);
6034
+ store.recordStageStart(runId, snapshot);
6035
+ store.recordStageEnd(runId, snapshot);
5782
6036
  completedStageReplayKeys.set(stageId, replayKey);
5783
6037
  }
5784
- function recordCachedStageWithTracker(store2, tracker, runId, name, replayKey, checkpoint, completedStageReplayKeys, stageFailFastScope, sourceToReplayedNodeIds) {
6038
+ function recordCachedStageWithTracker(store, tracker, runId, name, replayKey, checkpoint, completedStageReplayKeys, stageFailFastScope, sourceToReplayedNodeIds) {
5785
6039
  const sourceStageId = checkpoint.topology?.run?.runId === runId ? checkpoint.topology.stageId : undefined;
5786
6040
  const stageId = sourceStageId ?? cachedStageId(runId, replayKey);
5787
6041
  let parentIds = tracker.onSpawn(stageId, name);
5788
6042
  const sourceParents = sourceStageId === undefined ? undefined : checkpoint.topology?.parentIds;
5789
- const run = store2.runs().find((candidate) => candidate.id === runId);
6043
+ const run = store.runs().find((candidate) => candidate.id === runId);
5790
6044
  const restored = sourceParents?.map((sourceId) => sourceToReplayedNodeIds?.get(sourceId) ?? run?.stages.find((stage) => stage.id === sourceId || stage.replayedFromStageId === sourceId)?.id);
5791
6045
  if (restored?.every((id) => id !== undefined)) {
5792
6046
  parentIds = restored;
@@ -5797,7 +6051,7 @@ function recordCachedStageWithTracker(store2, tracker, runId, name, replayKey, c
5797
6051
  }
5798
6052
  if (checkpoint.topology?.run?.runId === runId)
5799
6053
  sourceToReplayedNodeIds?.set(checkpoint.topology.stageId, stageId);
5800
- recordCachedStageIntoStore(store2, runId, name, replayKey, checkpoint.output, completedStageReplayKeys, parentIds, checkpoint);
6054
+ recordCachedStageIntoStore(store, runId, name, replayKey, checkpoint.output, completedStageReplayKeys, parentIds, checkpoint);
5801
6055
  tracker.onSettle(stageId);
5802
6056
  }
5803
6057
  function isWorkflowTaskResult(value) {
@@ -6545,9 +6799,9 @@ function isMemoizedBackendUsable(backend) {
6545
6799
  return !backend.persistent || dbosLifecycleState() === "ready";
6546
6800
  }
6547
6801
  function getDurableBackend() {
6548
- const owner2 = getDurableBackendProcessOwner();
6549
- const memoized = owner2.initializedBackend !== undefined && isMemoizedBackendUsable(owner2.initializedBackend) ? owner2.initializedBackend : undefined;
6550
- const backend = owner2.injectedBackend ?? memoized ?? getReadyDbosBackendSync();
6802
+ const owner = getDurableBackendProcessOwner();
6803
+ const memoized = owner.initializedBackend !== undefined && isMemoizedBackendUsable(owner.initializedBackend) ? owner.initializedBackend : undefined;
6804
+ const backend = owner.injectedBackend ?? memoized ?? getReadyDbosBackendSync();
6551
6805
  if (backend === undefined)
6552
6806
  throw new DbosNotReadyError;
6553
6807
  return backend;
@@ -6580,7 +6834,7 @@ function restoreBudgetState(value) {
6580
6834
  if (restored !== undefined)
6581
6835
  warnings[dimension] = restored;
6582
6836
  }
6583
- const requiredNumbers = (candidate, fields) => isRecord(candidate) && fields.every((field2) => numericDuration(candidate[field2]) !== undefined);
6837
+ const requiredNumbers = (candidate, fields) => isRecord(candidate) && fields.every((field) => numericDuration(candidate[field]) !== undefined);
6584
6838
  const accountingValue = value.accounting;
6585
6839
  const accounting = isRecord(accountingValue) && requiredNumbers(accountingValue, ["tokens", "cost"]) && requiredNumbers(accountingValue.baseline, ["input", "output", "cacheRead", "cacheWrite", "cost"]) && requiredNumbers(accountingValue.perCounter, ["input", "output", "cacheRead", "cacheWrite"]) ? accountingValue : undefined;
6586
6840
  const state = {
@@ -6812,8 +7066,8 @@ class ScopedDurableBackend {
6812
7066
  scope
6813
7067
  };
6814
7068
  }
6815
- scopeKey(key2) {
6816
- return `${this.scope.scopePrefix}:${key2}`;
7069
+ scopeKey(key) {
7070
+ return `${this.scope.scopePrefix}:${key}`;
6817
7071
  }
6818
7072
  remap(checkpoint) {
6819
7073
  const workflowId = this.scope.rootWorkflowId;
@@ -7318,31 +7572,31 @@ function createGitWorktreeSetupCache() {
7318
7572
  get(options) {
7319
7573
  if (disposed)
7320
7574
  throw new Error("Git worktree setup cache is already disposed");
7321
- const key2 = gitWorktreeSetupCacheKey(options);
7322
- const cached = results.get(key2);
7575
+ const key = gitWorktreeSetupCacheKey(options);
7576
+ const cached = results.get(key);
7323
7577
  if (cached !== undefined) {
7324
7578
  assertCachedGitWorktreeIdentity(cached, options);
7325
7579
  return cached.result;
7326
7580
  }
7327
7581
  const result = setupGitWorktree(options);
7328
- results.set(key2, { result, identity: captureGitWorktreeIdentity(result) });
7582
+ results.set(key, { result, identity: captureGitWorktreeIdentity(result) });
7329
7583
  return result;
7330
7584
  },
7331
7585
  dispose() {
7332
7586
  if (disposed)
7333
7587
  return;
7334
7588
  disposed = true;
7335
- let firstError2;
7589
+ let firstError;
7336
7590
  for (const cached of results.values()) {
7337
7591
  try {
7338
7592
  cached.identity.generation.dispose();
7339
7593
  } catch (error) {
7340
- firstError2 ??= error instanceof Error ? error : new Error(String(error));
7594
+ firstError ??= error instanceof Error ? error : new Error(String(error));
7341
7595
  }
7342
7596
  }
7343
7597
  results.clear();
7344
- if (firstError2 !== undefined)
7345
- throw firstError2;
7598
+ if (firstError !== undefined)
7599
+ throw firstError;
7346
7600
  }
7347
7601
  };
7348
7602
  }
@@ -7642,24 +7896,24 @@ function safePatchAgentName(agent) {
7642
7896
  }
7643
7897
  function removeSyntheticPath(worktree, syntheticPath) {
7644
7898
  const resolved = path4.resolve(worktree.path, syntheticPath);
7645
- const relative3 = path4.relative(worktree.path, resolved);
7646
- if (!relative3 || relative3 === "." || relative3 === ".." || relative3.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative3)) {
7899
+ const relative = path4.relative(worktree.path, resolved);
7900
+ if (!relative || relative === "." || relative === ".." || relative.startsWith(`..${path4.sep}`) || path4.isAbsolute(relative)) {
7647
7901
  return;
7648
7902
  }
7649
- let stat2;
7903
+ let stat;
7650
7904
  try {
7651
- stat2 = fs4.lstatSync(resolved);
7905
+ stat = fs4.lstatSync(resolved);
7652
7906
  } catch (error) {
7653
7907
  const code = error && typeof error === "object" && "code" in error ? error.code : undefined;
7654
7908
  if (code === "ENOENT")
7655
7909
  return;
7656
7910
  throw error;
7657
7911
  }
7658
- if (stat2.isSymbolicLink()) {
7912
+ if (stat.isSymbolicLink()) {
7659
7913
  fs4.unlinkSync(resolved);
7660
7914
  return;
7661
7915
  }
7662
- if (stat2.isDirectory()) {
7916
+ if (stat.isDirectory()) {
7663
7917
  fs4.rmSync(resolved, { recursive: true, force: true });
7664
7918
  return;
7665
7919
  }
@@ -8023,14 +8277,14 @@ function normalizeSyntheticPath(worktreePath, rawPath) {
8023
8277
  if (path6.isAbsolute(trimmed))
8024
8278
  throw new Error(`synthetic path must be relative: ${rawPath}`);
8025
8279
  const resolved = path6.resolve(worktreePath, trimmed);
8026
- const relative4 = path6.relative(worktreePath, resolved);
8027
- if (!relative4 || relative4 === ".") {
8280
+ const relative = path6.relative(worktreePath, resolved);
8281
+ if (!relative || relative === ".") {
8028
8282
  throw new Error(`synthetic path cannot target the worktree root: ${rawPath}`);
8029
8283
  }
8030
- if (relative4 === ".." || relative4.startsWith(`..${path6.sep}`) || path6.isAbsolute(relative4)) {
8284
+ if (relative === ".." || relative.startsWith(`..${path6.sep}`) || path6.isAbsolute(relative)) {
8031
8285
  throw new Error(`synthetic path escapes the worktree root: ${rawPath}`);
8032
8286
  }
8033
- return path6.normalize(relative4);
8287
+ return path6.normalize(relative);
8034
8288
  }
8035
8289
  function hasTrackedEntries(worktreePath, relativePath) {
8036
8290
  const result = runGit(worktreePath, ["ls-files", "--", relativePath]);
@@ -8173,15 +8427,15 @@ function cleanupWorktrees(setup) {
8173
8427
  import { lstatSync as lstatSync4, realpathSync as realpathSync4 } from "node:fs";
8174
8428
  import { dirname as dirname6, isAbsolute as isAbsolute5, relative as relative4, resolve as resolve6, sep as sep5 } from "node:path";
8175
8429
  function relativePathWithin(root, candidate) {
8176
- const path7 = relative4(root, candidate);
8177
- return path7 === ".." || path7.startsWith(`..${sep5}`) || isAbsolute5(path7) ? undefined : path7;
8430
+ const path = relative4(root, candidate);
8431
+ return path === ".." || path.startsWith(`..${sep5}`) || isAbsolute5(path) ? undefined : path;
8178
8432
  }
8179
- function existingRealPath(path7, description) {
8433
+ function existingRealPath(path, description) {
8180
8434
  try {
8181
- return realpathSync4.native(path7);
8435
+ return realpathSync4.native(path);
8182
8436
  } catch (error) {
8183
8437
  const message = error instanceof Error ? error.message : String(error);
8184
- throw new Error(`atomic-workflows: cannot resolve ${description} ${path7}: ${message}`);
8438
+ throw new Error(`atomic-workflows: cannot resolve ${description} ${path}: ${message}`);
8185
8439
  }
8186
8440
  }
8187
8441
  function resolveWorktreeStageCwd(cwd, setup) {
@@ -8399,7 +8653,7 @@ function truncateTaskOutput(text, maxOutput) {
8399
8653
  [workflow output truncated; limits: ${limits.bytes} bytes, ${limits.lines} lines]`;
8400
8654
  }
8401
8655
  function withoutUndefinedProperties(value) {
8402
- return Object.fromEntries(Object.entries(value).filter(([, field2]) => field2 !== undefined));
8656
+ return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== undefined));
8403
8657
  }
8404
8658
  function sharedTaskDefaultsFromOptions(options) {
8405
8659
  const {
@@ -8505,7 +8759,7 @@ async function mapParallelSteps(steps, concurrency, failFast, mapper, onFirstFai
8505
8759
  if (selectedFailure !== undefined)
8506
8760
  throw selectedFailure;
8507
8761
  }
8508
- throw new AggregateError(failures.map((failure2) => failure2.error), `atomic-workflows: ${failures.length} parallel ${failures.length === 1 ? "step" : "steps"} failed`);
8762
+ throw new AggregateError(failures.map((failure) => failure.error), `atomic-workflows: ${failures.length} parallel ${failures.length === 1 ? "step" : "steps"} failed`);
8509
8763
  }
8510
8764
  return results;
8511
8765
  }
@@ -8778,32 +9032,32 @@ function reconcileTerminalRunResult(runId, runSnapshot, activeStore, fallback, o
8778
9032
  onRunEnd?.(runId, result.status, result.result, result.error, result.exitReason);
8779
9033
  return result;
8780
9034
  }
8781
- function applyFailureToStage(stage, failure2) {
9035
+ function applyFailureToStage(stage, failure) {
8782
9036
  stage.status = "failed";
8783
- stage.error = failure2.userMessage;
8784
- stage.failureKind = failure2.kind;
8785
- stage.failureCode = failure2.code;
8786
- stage.failureRecoverability = failure2.recoverability;
8787
- stage.failureDisposition = failure2.disposition;
8788
- stage.retryAfterMs = failure2.retryAfterMs;
8789
- stage.failureMessage = failure2.message;
8790
- }
8791
- function runFailureMetadata(failure2, stages) {
9037
+ stage.error = failure.userMessage;
9038
+ stage.failureKind = failure.kind;
9039
+ stage.failureCode = failure.code;
9040
+ stage.failureRecoverability = failure.recoverability;
9041
+ stage.failureDisposition = failure.disposition;
9042
+ stage.retryAfterMs = failure.retryAfterMs;
9043
+ stage.failureMessage = failure.message;
9044
+ }
9045
+ function runFailureMetadata(failure, stages) {
8792
9046
  const failedStage = stages.find((stage) => stage.status === "failed");
8793
- const failureKind = failedStage?.failureKind ?? failure2.kind;
8794
- const failureCode = failedStage?.failureCode ?? failure2.code;
8795
- const failureRecoverability = failedStage?.failureRecoverability ?? failure2.recoverability;
8796
- const failureDisposition = failedStage?.failureDisposition ?? failure2.disposition;
8797
- const retryAfterMs = failedStage?.retryAfterMs ?? failure2.retryAfterMs;
9047
+ const failureKind = failedStage?.failureKind ?? failure.kind;
9048
+ const failureCode = failedStage?.failureCode ?? failure.code;
9049
+ const failureRecoverability = failedStage?.failureRecoverability ?? failure.recoverability;
9050
+ const failureDisposition = failedStage?.failureDisposition ?? failure.disposition;
9051
+ const retryAfterMs = failedStage?.retryAfterMs ?? failure.retryAfterMs;
8798
9052
  return {
8799
- errorMessage: failedStage?.error ?? failure2.userMessage,
9053
+ errorMessage: failedStage?.error ?? failure.userMessage,
8800
9054
  failureKind,
8801
9055
  ...failureCode !== undefined ? { failureCode } : {},
8802
9056
  failureRecoverability,
8803
9057
  failureDisposition,
8804
- failureMessage: failedStage?.failureMessage ?? failure2.message,
9058
+ failureMessage: failedStage?.failureMessage ?? failure.message,
8805
9059
  ...failedStage !== undefined ? { failedStageId: failedStage.id } : {},
8806
- resumable: failure2.resumable,
9060
+ resumable: failure.resumable,
8807
9061
  ...retryAfterMs !== undefined ? { retryAfterMs } : {}
8808
9062
  };
8809
9063
  }
@@ -8832,17 +9086,17 @@ function runFailureMetadataFromStage(fallbackFailure, stage) {
8832
9086
  ...retryAfterMs !== undefined ? { retryAfterMs } : {}
8833
9087
  };
8834
9088
  }
8835
- function runFailureMetadataFromFailure(failure2, failedStage) {
9089
+ function runFailureMetadataFromFailure(failure, failedStage) {
8836
9090
  return {
8837
- errorMessage: failedStage?.error ?? failure2.userMessage,
8838
- failureKind: failure2.kind,
8839
- ...failure2.code !== undefined ? { failureCode: failure2.code } : {},
8840
- failureRecoverability: failure2.recoverability,
8841
- failureDisposition: failure2.disposition,
8842
- failureMessage: failedStage?.failureMessage ?? failure2.message,
9091
+ errorMessage: failedStage?.error ?? failure.userMessage,
9092
+ failureKind: failure.kind,
9093
+ ...failure.code !== undefined ? { failureCode: failure.code } : {},
9094
+ failureRecoverability: failure.recoverability,
9095
+ failureDisposition: failure.disposition,
9096
+ failureMessage: failedStage?.failureMessage ?? failure.message,
8843
9097
  ...failedStage !== undefined ? { failedStageId: failedStage.id } : {},
8844
- resumable: failure2.resumable,
8845
- ...failure2.retryAfterMs !== undefined ? { retryAfterMs: failure2.retryAfterMs } : {}
9098
+ resumable: failure.resumable,
9099
+ ...failure.retryAfterMs !== undefined ? { retryAfterMs: failure.retryAfterMs } : {}
8846
9100
  };
8847
9101
  }
8848
9102
  function aggregateInnerFailures(error, classifyFailure) {
@@ -8856,20 +9110,20 @@ function stageFailureCandidate(stage) {
8856
9110
  recoverability: stage.failureRecoverability ?? "unknown"
8857
9111
  };
8858
9112
  }
8859
- function aggregateFailureCandidate(failure2) {
9113
+ function aggregateFailureCandidate(failure) {
8860
9114
  return {
8861
9115
  source: "aggregate",
8862
- failure: failure2,
8863
- disposition: failure2.disposition,
8864
- recoverability: failure2.recoverability
9116
+ failure,
9117
+ disposition: failure.disposition,
9118
+ recoverability: failure.recoverability
8865
9119
  };
8866
9120
  }
8867
- function outerFailureCandidate(failure2) {
9121
+ function outerFailureCandidate(failure) {
8868
9122
  return {
8869
9123
  source: "outer",
8870
- failure: failure2,
8871
- disposition: failure2.disposition,
8872
- recoverability: failure2.recoverability
9124
+ failure,
9125
+ disposition: failure.disposition,
9126
+ recoverability: failure.recoverability
8873
9127
  };
8874
9128
  }
8875
9129
  function isRecoverableActiveBlockedCandidate(candidate) {
@@ -8956,24 +9210,24 @@ function stageReplayFields(stage) {
8956
9210
  };
8957
9211
  }
8958
9212
  function finalizeKilled(runId, runSnapshot, activeStore, persistence, onRunEnd) {
8959
- const errorMessage2 = "workflow killed";
9213
+ const errorMessage = "workflow killed";
8960
9214
  const metadata = {
8961
9215
  failureKind: "cancelled",
8962
9216
  failureCode: "cancelled",
8963
9217
  failureRecoverability: "non_recoverable",
8964
9218
  failureDisposition: "terminal_killed",
8965
- failureMessage: errorMessage2,
9219
+ failureMessage: errorMessage,
8966
9220
  resumable: false
8967
9221
  };
8968
- const recorded = activeStore.recordRunEnd(runId, "killed", undefined, errorMessage2, metadata);
9222
+ const recorded = activeStore.recordRunEnd(runId, "killed", undefined, errorMessage, metadata);
8969
9223
  appendRunEndWhenRecorded(persistence, recorded, {
8970
9224
  runId,
8971
9225
  status: "killed",
8972
- error: errorMessage2,
9226
+ error: errorMessage,
8973
9227
  ...metadata,
8974
9228
  ts: Date.now()
8975
9229
  });
8976
- return reconcileTerminalRunResult(runId, runSnapshot, activeStore, { status: "killed", error: errorMessage2 }, onRunEnd);
9230
+ return reconcileTerminalRunResult(runId, runSnapshot, activeStore, { status: "killed", error: errorMessage }, onRunEnd);
8977
9231
  }
8978
9232
  function finalizeKilledByFailure(runId, runSnapshot, activeStore, persistence, onRunEnd, metadata) {
8979
9233
  const recorded = activeStore.recordRunEnd(runId, "killed", undefined, metadata.errorMessage, metadata);
@@ -9040,32 +9294,32 @@ function recordActiveBlockedFailure(runId, runSnapshot, activeStore, persistence
9040
9294
 
9041
9295
  // dist/builtin/workflows/src/runs/foreground/executor-outputs.ts
9042
9296
  import { Value as Value5 } from "typebox/value";
9043
- function hasOwnWorkflowOutput(record, key2) {
9044
- return Object.hasOwn(record, key2);
9297
+ function hasOwnWorkflowOutput(record, key) {
9298
+ return Object.hasOwn(record, key);
9045
9299
  }
9046
9300
  function assertWorkflowOutputsExplicit(scope, sourceOutput, declarations, missingOutputSuffix = "") {
9047
- for (const key2 of Object.keys(sourceOutput)) {
9048
- if (!hasOwnWorkflowOutput(declarations, key2)) {
9049
- throw new Error(`atomic-workflows: ${scope} returned undeclared output "${key2}"; declare it in outputs: { "${key2}": Type.... } or remove it from the .run() return`);
9301
+ for (const key of Object.keys(sourceOutput)) {
9302
+ if (!hasOwnWorkflowOutput(declarations, key)) {
9303
+ throw new Error(`atomic-workflows: ${scope} returned undeclared output "${key}"; declare it in outputs: { "${key}": Type.... } or remove it from the .run() return`);
9050
9304
  }
9051
9305
  }
9052
- for (const [key2, schema] of Object.entries(declarations)) {
9053
- if (!(key2 in sourceOutput)) {
9306
+ for (const [key, schema] of Object.entries(declarations)) {
9307
+ if (!(key in sourceOutput)) {
9054
9308
  if (schemaIsRequired(schema)) {
9055
- throw new Error(`atomic-workflows: ${scope} missing output "${key2}"${missingOutputSuffix}`);
9309
+ throw new Error(`atomic-workflows: ${scope} missing output "${key}"${missingOutputSuffix}`);
9056
9310
  }
9057
9311
  continue;
9058
9312
  }
9059
- const value = sourceOutput[key2];
9313
+ const value = sourceOutput[key];
9060
9314
  const kind = schemaFieldKind(schema);
9061
9315
  if (!Value5.Check(schema, value)) {
9062
9316
  const choices = schemaChoices(schema);
9063
9317
  if (kind === "select" && choices !== undefined && typeof value === "string") {
9064
- throw new Error(`atomic-workflows: ${scope} output "${key2}" must be one of [${choices.join(", ")}], got ${JSON.stringify(value)}`);
9318
+ throw new Error(`atomic-workflows: ${scope} output "${key}" must be one of [${choices.join(", ")}], got ${JSON.stringify(value)}`);
9065
9319
  }
9066
- throw new Error(`atomic-workflows: ${scope} output "${key2}" expected ${kind}, got ${workflowSerializableTypeName(value)}`);
9320
+ throw new Error(`atomic-workflows: ${scope} output "${key}" expected ${kind}, got ${workflowSerializableTypeName(value)}`);
9067
9321
  }
9068
- const serializableError = workflowSerializableValidationError(value, `${scope} output "${key2}"`);
9322
+ const serializableError = workflowSerializableValidationError(value, `${scope} output "${key}"`);
9069
9323
  if (serializableError !== undefined)
9070
9324
  throw new Error(`atomic-workflows: ${serializableError}`);
9071
9325
  }
@@ -9098,27 +9352,27 @@ function assertWorkflowExitOutputs(workflowName, result, declaredOutputs) {
9098
9352
  const declarations = declaredOutputs ?? {};
9099
9353
  const sourceOutput = result ?? {};
9100
9354
  const scope = `workflow "${workflowName}" ctx.exit()`;
9101
- for (const key2 of Object.keys(sourceOutput)) {
9102
- if (!hasOwnWorkflowOutput(declarations, key2)) {
9103
- throw new Error(`atomic-workflows: ${scope} provided undeclared output "${key2}"; declare it in outputs: { "${key2}": Type.... } or remove it from ctx.exit({ outputs })`);
9355
+ for (const key of Object.keys(sourceOutput)) {
9356
+ if (!hasOwnWorkflowOutput(declarations, key)) {
9357
+ throw new Error(`atomic-workflows: ${scope} provided undeclared output "${key}"; declare it in outputs: { "${key}": Type.... } or remove it from ctx.exit({ outputs })`);
9104
9358
  }
9105
9359
  }
9106
- for (const [key2, schema] of Object.entries(declarations)) {
9107
- if (!(key2 in sourceOutput))
9360
+ for (const [key, schema] of Object.entries(declarations)) {
9361
+ if (!(key in sourceOutput))
9108
9362
  continue;
9109
- const value = sourceOutput[key2];
9110
- const invalidSnapshotValue = workflowExitSnapshotInvalidValueMessage(`${scope} output "${key2}"`, value);
9363
+ const value = sourceOutput[key];
9364
+ const invalidSnapshotValue = workflowExitSnapshotInvalidValueMessage(`${scope} output "${key}"`, value);
9111
9365
  if (invalidSnapshotValue !== undefined)
9112
9366
  throw new Error(`atomic-workflows: ${invalidSnapshotValue}`);
9113
9367
  const kind = schemaFieldKind(schema);
9114
9368
  if (!Value5.Check(schema, value)) {
9115
9369
  const choices = schemaChoices(schema);
9116
9370
  if (kind === "select" && choices !== undefined && typeof value === "string") {
9117
- throw new Error(`atomic-workflows: ${scope} output "${key2}" must be one of [${choices.join(", ")}], got ${JSON.stringify(value)}`);
9371
+ throw new Error(`atomic-workflows: ${scope} output "${key}" must be one of [${choices.join(", ")}], got ${JSON.stringify(value)}`);
9118
9372
  }
9119
- throw new Error(`atomic-workflows: ${scope} output "${key2}" expected ${kind}, got ${workflowSerializableTypeName(value)}`);
9373
+ throw new Error(`atomic-workflows: ${scope} output "${key}" expected ${kind}, got ${workflowSerializableTypeName(value)}`);
9120
9374
  }
9121
- const serializableError = workflowSerializableValidationError(value, `${scope} output "${key2}"`);
9375
+ const serializableError = workflowSerializableValidationError(value, `${scope} output "${key}"`);
9122
9376
  if (serializableError !== undefined)
9123
9377
  throw new Error(`atomic-workflows: ${serializableError}`);
9124
9378
  }
@@ -9127,10 +9381,10 @@ function selectWorkflowOutputs(child, rawOutput) {
9127
9381
  const declarations = child.outputs ?? {};
9128
9382
  const sourceOutput = rawOutput ?? {};
9129
9383
  const selected = {};
9130
- for (const key2 of Object.keys(declarations)) {
9131
- const value = sourceOutput[key2];
9384
+ for (const key of Object.keys(declarations)) {
9385
+ const value = sourceOutput[key];
9132
9386
  if (value !== undefined)
9133
- selected[key2] = value;
9387
+ selected[key] = value;
9134
9388
  }
9135
9389
  return selected;
9136
9390
  }
@@ -9545,8 +9799,8 @@ function buildPromptNodeUiAdapter(input) {
9545
9799
  try {
9546
9800
  if (mergedSignal.signal.aborted)
9547
9801
  throw hilAbortError(mergedSignal.signal);
9548
- const accepted3 = input.activeStore.recordStageAwaitingInput(input.runId, stageId, true, prompt.createdAt);
9549
- if (!accepted3) {
9802
+ const accepted = input.activeStore.recordStageAwaitingInput(input.runId, stageId, true, prompt.createdAt);
9803
+ if (!accepted) {
9550
9804
  const error = new Error("atomic-workflows: ctx.ui.custom prompt node is unavailable");
9551
9805
  stageSnapshot.skippedReason = "prompt-unavailable";
9552
9806
  await finalizePromptStage("skipped");
@@ -9576,15 +9830,15 @@ function buildPromptNodeUiAdapter(input) {
9576
9830
  mergedSignal.dispose();
9577
9831
  }
9578
9832
  }
9579
- const accepted2 = input.activeStore.recordStagePendingPrompt(input.runId, stageId, prompt);
9580
- if (!accepted2) {
9833
+ const accepted = input.activeStore.recordStagePendingPrompt(input.runId, stageId, prompt);
9834
+ if (!accepted) {
9581
9835
  stageSnapshot.skippedReason = "prompt-unavailable";
9582
9836
  await finalizePromptStage("skipped");
9583
9837
  return fallbackForPromptDescriptor(descriptor);
9584
9838
  }
9585
9839
  const waiter = input.activeStore.awaitStagePendingPrompt(input.runId, stageId, prompt.id);
9586
9840
  try {
9587
- const response = await new Promise((resolve9, reject) => {
9841
+ const response = await new Promise((resolve, reject) => {
9588
9842
  const onAbort = () => {
9589
9843
  input.activeStore.resolveStagePendingPrompt(input.runId, stageId, prompt.id, fallbackForPromptDescriptor(descriptor), { recordAnswer: false });
9590
9844
  reject(hilAbortError(input.signal));
@@ -9596,7 +9850,7 @@ function buildPromptNodeUiAdapter(input) {
9596
9850
  input.signal.addEventListener("abort", onAbort, { once: true });
9597
9851
  waiter.then((value) => {
9598
9852
  input.signal.removeEventListener("abort", onAbort);
9599
- resolve9(value);
9853
+ resolve(value);
9600
9854
  }, (err) => {
9601
9855
  input.signal.removeEventListener("abort", onAbort);
9602
9856
  reject(err);
@@ -9657,8 +9911,8 @@ function buildPromptNodeUiAdapter(input) {
9657
9911
  // dist/builtin/workflows/src/runs/foreground/executor-run-finalizers.ts
9658
9912
  function createRunFinalizers(input) {
9659
9913
  const finalizeWorkflowExitValidationFailure = (err, exitReason) => {
9660
- const failure2 = input.classifyExecutorFailure(err);
9661
- const classifiedMetadata = runFailureMetadata(failure2, input.runSnapshot.stages);
9914
+ const failure = input.classifyExecutorFailure(err);
9915
+ const classifiedMetadata = runFailureMetadata(failure, input.runSnapshot.stages);
9662
9916
  const metadata = {
9663
9917
  ...classifiedMetadata,
9664
9918
  resumable: false,
@@ -9723,8 +9977,8 @@ function createRunFinalizers(input) {
9723
9977
  ...signal.reason !== undefined ? { exitReason: signal.reason } : {}
9724
9978
  }, input.opts.onRunEnd);
9725
9979
  };
9726
- const finalizeParentWorkflowExitCancellation = async (abortReason3) => {
9727
- const parentReason = abortReason3.workflowExitReason;
9980
+ const finalizeParentWorkflowExitCancellation = async (abortReason) => {
9981
+ const parentReason = abortReason.workflowExitReason;
9728
9982
  await input.drainWorkflowExitCleanups(parentReason);
9729
9983
  const exitReason = parentWorkflowExitRunReason(parentReason);
9730
9984
  const metadata = { resumable: false, exited: true, exitReason };
@@ -10186,8 +10440,8 @@ class ConcurrencyLimiter {
10186
10440
  this._running++;
10187
10441
  return Promise.resolve();
10188
10442
  }
10189
- return new Promise((resolve9) => {
10190
- this._queue.push(resolve9);
10443
+ return new Promise((resolve) => {
10444
+ this._queue.push(resolve);
10191
10445
  });
10192
10446
  }
10193
10447
  release() {
@@ -10208,7 +10462,7 @@ class ConcurrencyLimiter {
10208
10462
  }
10209
10463
  }
10210
10464
  function createRunLimiter(defaultConcurrency) {
10211
- return new ConcurrencyLimiter(defaultConcurrency ?? 4);
10465
+ return new ConcurrencyLimiter(defaultConcurrency ?? 3);
10212
10466
  }
10213
10467
 
10214
10468
  // dist/builtin/workflows/src/shared/abort.ts
@@ -10273,11 +10527,11 @@ function createWorkflowExitManager(input) {
10273
10527
  const trackWorkflowExitCleanup = (operation) => {
10274
10528
  if (operation === undefined)
10275
10529
  return;
10276
- let tracked2;
10277
- tracked2 = Promise.resolve(operation).catch(() => {}).finally(() => {
10278
- workflowExitCleanupPromises.delete(tracked2);
10530
+ let tracked;
10531
+ tracked = Promise.resolve(operation).catch(() => {}).finally(() => {
10532
+ workflowExitCleanupPromises.delete(tracked);
10279
10533
  });
10280
- workflowExitCleanupPromises.add(tracked2);
10534
+ workflowExitCleanupPromises.add(tracked);
10281
10535
  };
10282
10536
  const invokeWorkflowExitCleanup = (cleanup, reason) => {
10283
10537
  try {
@@ -10403,10 +10657,10 @@ function createWorkflowExitManager(input) {
10403
10657
  };
10404
10658
  }
10405
10659
  // dist/builtin/workflows/src/engine/primitives/parallel.ts
10406
- import { randomUUID as randomUUID3 } from "node:crypto";
10660
+ import { randomUUID as randomUUID4 } from "node:crypto";
10407
10661
 
10408
10662
  // dist/builtin/workflows/src/shared/intercom-group.ts
10409
- import { randomUUID as randomUUID2 } from "node:crypto";
10663
+ import { randomUUID as randomUUID3 } from "node:crypto";
10410
10664
  var DEFAULT_INTERCOM_GROUP = "default";
10411
10665
  function workflowInvocationIntercomGroup(rootRunId) {
10412
10666
  return `workflow:${rootRunId}`;
@@ -10429,22 +10683,22 @@ function resolveStageGroup(stageOptions, workflowGroup) {
10429
10683
  const group = stageOptions.group;
10430
10684
  if (group === undefined)
10431
10685
  return workflowGroup;
10432
- const authored = group === true ? randomUUID2() : group.trim();
10686
+ const authored = group === true ? randomUUID3() : group.trim();
10433
10687
  if (authored.length === 0)
10434
10688
  return;
10435
10689
  if (workflowGroup === undefined || authored === DEFAULT_INTERCOM_GROUP)
10436
10690
  return authored;
10437
- const owner2 = normalizeGroup(workflowGroup);
10438
- if (authored === owner2 || authored.startsWith(`${owner2}/`))
10691
+ const owner = normalizeGroup(workflowGroup);
10692
+ if (authored === owner || authored.startsWith(`${owner}/`))
10439
10693
  return authored;
10440
- return `${owner2}/${authored}`;
10694
+ return `${owner}/${authored}`;
10441
10695
  }
10442
10696
  function workflowInvocationOwnsGroup(workflowGroup, candidate) {
10443
10697
  if (workflowGroup === undefined || candidate === undefined)
10444
10698
  return false;
10445
- const owner2 = normalizeGroup(workflowGroup);
10699
+ const owner = normalizeGroup(workflowGroup);
10446
10700
  const group = normalizeGroup(candidate);
10447
- return group === owner2 || group.startsWith(`${owner2}/`);
10701
+ return group === owner || group.startsWith(`${owner}/`);
10448
10702
  }
10449
10703
  function stageHasIntercomAccess(_stageOptions) {
10450
10704
  return true;
@@ -10487,7 +10741,7 @@ function fold_usage(results) {
10487
10741
 
10488
10742
  // dist/builtin/workflows/src/shared/budget-meter.ts
10489
10743
  var usageFields = ["input", "output", "cacheRead", "cacheWrite", "cost"];
10490
- var addUsage = (left, right) => Object.fromEntries(usageFields.map((field2) => [field2, left[field2] + right[field2]]));
10744
+ var addUsage = (left, right) => Object.fromEntries(usageFields.map((field) => [field, left[field] + right[field]]));
10491
10745
  function foldTreeUsage(tree) {
10492
10746
  const run = "run" in tree ? tree.run : tree;
10493
10747
  const folded = fold_usage(run.stages.filter((stage) => stage.replayed !== true).map((stage) => ({ stageName: stage.name, text: stage.result ?? "", modelAttempts: stage.modelAttempts })));
@@ -10499,7 +10753,7 @@ function meter_run(tree, now) {
10499
10753
  durationMs: elapsedRunMs("run" in tree ? tree.run : tree, now),
10500
10754
  tokens: usage.input + usage.output,
10501
10755
  cost: usage.cost,
10502
- perCounter: Object.fromEntries(usageFields.filter((field2) => field2 !== "cost").map((field2) => [field2, usage[field2]]))
10756
+ perCounter: Object.fromEntries(usageFields.filter((field) => field !== "cost").map((field) => [field, usage[field]]))
10503
10757
  };
10504
10758
  }
10505
10759
 
@@ -10518,7 +10772,7 @@ class WorkflowBudgetExceededError extends Error {
10518
10772
  var withFrontier = (report, frontierStage, summary, usage) => Object.assign({ ...report, frontierStage: frontierStage ?? "workflow frontier" }, summary === undefined ? {} : { wrapUpSummary: summary }, usage === undefined ? {} : { wrapUpUsage: usage });
10519
10773
  var usageFields2 = ["input", "output", "cacheRead", "cacheWrite", "cost"];
10520
10774
  var counterFields = ["input", "output", "cacheRead", "cacheWrite"];
10521
- var mapFields = (fields, fn = () => 0) => Object.fromEntries(fields.map((field2) => [field2, fn(field2)]));
10775
+ var mapFields = (fields, fn = () => 0) => Object.fromEntries(fields.map((field) => [field, fn(field)]));
10522
10776
  function createRunBudgetController(input) {
10523
10777
  const { run, budget } = input;
10524
10778
  const ownEnabled = budget.maxDurationMs > 0 || budget.maxTokens > 0 || budget.maxCost > 0;
@@ -10529,7 +10783,7 @@ function createRunBudgetController(input) {
10529
10783
  const previousAccounting = state?.accounting;
10530
10784
  const initial = previousAccounting && usageEnabled ? meter_run(input.usageTree?.() ?? { run }, Date.now()) : undefined;
10531
10785
  const initialAccounting = initial === undefined ? undefined : { ...initial.perCounter, cost: initial.cost };
10532
- let baseline = mapFields(usageFields2, (field2) => initialAccounting?.[field2] ?? 0);
10786
+ let baseline = mapFields(usageFields2, (field) => initialAccounting?.[field] ?? 0);
10533
10787
  let charged = {
10534
10788
  baseline,
10535
10789
  tokens: previousAccounting?.tokens ?? 0,
@@ -10547,13 +10801,13 @@ function createRunBudgetController(input) {
10547
10801
  };
10548
10802
  const accountUsage = (meters) => {
10549
10803
  const current = { ...meters.perCounter, cost: meters.cost };
10550
- const delta = mapFields(usageFields2, (field2) => Math.max(0, current[field2] - baseline[field2]));
10551
- baseline = mapFields(usageFields2, (field2) => Math.max(baseline[field2], current[field2]));
10804
+ const delta = mapFields(usageFields2, (field) => Math.max(0, current[field] - baseline[field]));
10805
+ baseline = mapFields(usageFields2, (field) => Math.max(baseline[field], current[field]));
10552
10806
  charged = {
10553
10807
  baseline,
10554
10808
  tokens: charged.tokens + delta.input + delta.output,
10555
10809
  cost: charged.cost + delta.cost,
10556
- perCounter: mapFields(counterFields, (field2) => charged.perCounter[field2] + delta[field2])
10810
+ perCounter: mapFields(counterFields, (field) => charged.perCounter[field] + delta[field])
10557
10811
  };
10558
10812
  updateState({ accounting: charged });
10559
10813
  return Object.assign(meters, { tokens: charged.tokens, cost: charged.cost, perCounter: charged.perCounter });
@@ -10630,21 +10884,21 @@ function createRunBudgetController(input) {
10630
10884
  return { check: ownCheckpoint(frontierStage) };
10631
10885
  };
10632
10886
  const checkpoint = (frontierStage) => boundaryCheckpoint(frontierStage).check;
10633
- const finishBoundary = (owner2, frontierStage) => {
10634
- throw owner2?.finishWrapUp(frontierStage, undefined, undefined, false) ?? finishWrapUp(frontierStage, undefined, undefined, false);
10887
+ const finishBoundary = (owner, frontierStage) => {
10888
+ throw owner?.finishWrapUp(frontierStage, undefined, undefined, false) ?? finishWrapUp(frontierStage, undefined, undefined, false);
10635
10889
  };
10636
- const deliverBoundary = (owner2, frontierStage) => {
10637
- owner2?.deliverWrapUp(frontierStage) ?? deliverWrapUp(frontierStage);
10890
+ const deliverBoundary = (owner, frontierStage) => {
10891
+ owner?.deliverWrapUp(frontierStage) ?? deliverWrapUp(frontierStage);
10638
10892
  };
10639
10893
  const stopAtBoundary = (frontierStage) => {
10640
10894
  const resolvedFrontierStage = frontierStage ?? handlers.at(-1)?.frontierStage;
10641
- const { check, owner: owner2 } = boundaryCheckpoint(resolvedFrontierStage);
10895
+ const { check, owner } = boundaryCheckpoint(resolvedFrontierStage);
10642
10896
  if (check.kind === "wrap_up") {
10643
- deliverBoundary(owner2, resolvedFrontierStage ?? "workflow frontier");
10644
- finishBoundary(owner2, resolvedFrontierStage);
10897
+ deliverBoundary(owner, resolvedFrontierStage ?? "workflow frontier");
10898
+ finishBoundary(owner, resolvedFrontierStage);
10645
10899
  }
10646
10900
  if (check.kind === "exhausted")
10647
- finishBoundary(owner2, resolvedFrontierStage);
10901
+ finishBoundary(owner, resolvedFrontierStage);
10648
10902
  };
10649
10903
  const rethrowIfSystemOwnedStop = (frontierStage) => {
10650
10904
  root?.rethrowIfSystemOwnedStop(frontierStage);
@@ -10738,11 +10992,11 @@ function createRunBudgetController(input) {
10738
10992
  function createParallelPrimitive(input) {
10739
10993
  return async (steps, options = {}) => {
10740
10994
  input.runtime.exit.throwIfWorkflowExitSelected();
10741
- const normalizeGroup2 = (value) => value.group === undefined ? value : { ...value, group: normalizeAutoGroupSentinel(value.group) };
10742
- const normalizedOptions = normalizeGroup2(options);
10743
- const normalizedSteps = steps.map(normalizeGroup2);
10995
+ const normalizeGroup = (value) => value.group === undefined ? value : { ...value, group: normalizeAutoGroupSentinel(value.group) };
10996
+ const normalizedOptions = normalizeGroup(options);
10997
+ const normalizedSteps = steps.map(normalizeGroup);
10744
10998
  const needsAutoGroup = normalizedOptions.group === true || normalizedSteps.some((step) => step.group === true);
10745
- const autoGroup = needsAutoGroup ? randomUUID3() : undefined;
10999
+ const autoGroup = needsAutoGroup ? randomUUID4() : undefined;
10746
11000
  const resolveAutoGroup = (value) => value.group === true && autoGroup ? { ...value, group: autoGroup } : value;
10747
11001
  const resolvedOptions = resolveAutoGroup(normalizedOptions);
10748
11002
  const resolvedSteps = normalizedSteps.map(resolveAutoGroup);
@@ -10783,9 +11037,9 @@ function createParallelPrimitive(input) {
10783
11037
  beforeMap: input.runtime.exit.throwIfWorkflowExitSelected,
10784
11038
  isControlSignal: (error) => findWorkflowExitSignal(error, input.runtime.exit.exitScope) !== undefined,
10785
11039
  selectSettledFailure: (failures) => {
10786
- if (!everyStepCompleted() || !failures.every((failure2) => failure2.error instanceof WorkflowBudgetExceededError))
11040
+ if (!everyStepCompleted() || !failures.every((failure) => failure.error instanceof WorkflowBudgetExceededError))
10787
11041
  return;
10788
- return failures.reduce((selected, failure2) => failure2.index < selected.index ? failure2 : selected).error;
11042
+ return failures.reduce((selected, failure) => failure.index < selected.index ? failure : selected).error;
10789
11043
  }
10790
11044
  });
10791
11045
  };
@@ -11328,8 +11582,8 @@ function structuredRecoverableFailureFromSnapshot(snapshot, failedStageId) {
11328
11582
  function isRecoverableProviderFailureKind(kind) {
11329
11583
  return kind === "auth" || kind === "rate_limit" || kind === "provider";
11330
11584
  }
11331
- function stringResultField(result, key2) {
11332
- const value = result?.[key2];
11585
+ function stringResultField(result, key) {
11586
+ const value = result?.[key];
11333
11587
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
11334
11588
  }
11335
11589
 
@@ -11347,7 +11601,7 @@ async function finalizeDurableTerminalStatus(input) {
11347
11601
  if (durableStatus === "failed" || durableStatus === "blocked") {
11348
11602
  recordRunTimingCheckpoint(input.durableBackend, input.runSnapshot);
11349
11603
  }
11350
- const failure2 = durableStatus === "failed" ? {
11604
+ const failure = durableStatus === "failed" ? {
11351
11605
  ...input.runSnapshot.error !== undefined ? { error: input.runSnapshot.error } : {},
11352
11606
  ...input.runSnapshot.exited === true ? {
11353
11607
  exited: true,
@@ -11359,7 +11613,7 @@ async function finalizeDurableTerminalStatus(input) {
11359
11613
  ...input.runSnapshot.failureDisposition !== undefined ? { failureDisposition: input.runSnapshot.failureDisposition } : {},
11360
11614
  ...input.runSnapshot.failedToolNodeId !== undefined ? { failedToolNodeId: input.runSnapshot.failedToolNodeId } : {}
11361
11615
  } : undefined;
11362
- input.durableBackend.setWorkflowStatus(input.runId, durableStatus, undefined, input.runSnapshot.resumable, failure2);
11616
+ input.durableBackend.setWorkflowStatus(input.runId, durableStatus, undefined, input.runSnapshot.resumable, failure);
11363
11617
  }
11364
11618
  await input.durableBackend.flush(input.runId);
11365
11619
  }
@@ -11616,17 +11870,17 @@ function childRunIdFromDraft(draft) {
11616
11870
  }
11617
11871
  function boundaryOwner(grouped, childRunId) {
11618
11872
  for (const drafts of grouped.values()) {
11619
- const owner2 = drafts.find((draft) => childRunIdFromDraft(draft) === childRunId);
11620
- if (owner2 !== undefined)
11621
- return owner2;
11873
+ const owner = drafts.find((draft) => childRunIdFromDraft(draft) === childRunId);
11874
+ if (owner !== undefined)
11875
+ return owner;
11622
11876
  }
11623
11877
  return;
11624
11878
  }
11625
- function childRunStatus(owner2) {
11626
- const child = workflowChildFromDraft(owner2);
11879
+ function childRunStatus(owner) {
11880
+ const child = workflowChildFromDraft(owner);
11627
11881
  if (child !== undefined)
11628
11882
  return child.status;
11629
- const status = owner2.topology?.boundary?.status;
11883
+ const status = owner.topology?.boundary?.status;
11630
11884
  return status === "failed" || status === "skipped" || status === "completed" ? status : "running";
11631
11885
  }
11632
11886
  function mergeStageGroup(records, allStages, allCheckpoints) {
@@ -11676,12 +11930,12 @@ function mergeStageDraft(existing, checkpoint, sequence) {
11676
11930
  ...checkpoint.topology !== undefined ? { topology: checkpoint.topology } : existing?.topology !== undefined ? { topology: existing.topology } : {}
11677
11931
  };
11678
11932
  }
11679
- function valueOrExisting(key2, checkpoint, existing) {
11680
- const checkpointValue = checkpoint[key2];
11933
+ function valueOrExisting(key, checkpoint, existing) {
11934
+ const checkpointValue = checkpoint[key];
11681
11935
  if (checkpointValue !== undefined)
11682
- return { [key2]: checkpointValue };
11683
- const existingValue = existing?.[key2];
11684
- return existingValue === undefined ? {} : { [key2]: existingValue };
11936
+ return { [key]: checkpointValue };
11937
+ const existingValue = existing?.[key];
11938
+ return existingValue === undefined ? {} : { [key]: existingValue };
11685
11939
  }
11686
11940
  function workflowChildFromDraft(draft) {
11687
11941
  const strict = parseWorkflowChildResult(draft.output);
@@ -11757,7 +12011,7 @@ function durableNestedRunSnapshots(backend, rootWorkflowId) {
11757
12011
  const handle = backend.getWorkflow(rootWorkflowId);
11758
12012
  if (handle === undefined)
11759
12013
  return [];
11760
- return runSnapshotsFromCheckpoints(backend.listCheckpoints(rootWorkflowId), rootWorkflowId, handle.name, handle.updatedAt, LEGACY_ACTIVE_RECONSTRUCTION).filter((run2) => run2.id !== rootWorkflowId);
12014
+ return runSnapshotsFromCheckpoints(backend.listCheckpoints(rootWorkflowId), rootWorkflowId, handle.name, handle.updatedAt, LEGACY_ACTIVE_RECONSTRUCTION).filter((run) => run.id !== rootWorkflowId);
11761
12015
  }
11762
12016
  function checkpointDrafts(checkpoints) {
11763
12017
  const stageByReplayKey = new Map;
@@ -11766,8 +12020,8 @@ function checkpointDrafts(checkpoints) {
11766
12020
  checkpoints.forEach((checkpoint, index) => {
11767
12021
  const sequence = index + 1;
11768
12022
  if (checkpoint.kind === "stage") {
11769
- const existing2 = stageByReplayKey.get(checkpoint.replayKey);
11770
- stageByReplayKey.set(checkpoint.replayKey, mergeStageDraft(existing2, checkpoint, sequence));
12023
+ const existing = stageByReplayKey.get(checkpoint.replayKey);
12024
+ stageByReplayKey.set(checkpoint.replayKey, mergeStageDraft(existing, checkpoint, sequence));
11771
12025
  return;
11772
12026
  }
11773
12027
  if (checkpoint.kind !== "tool" || isReservedRunCheckpointHash(checkpoint.argsHash))
@@ -11968,29 +12222,29 @@ function runSnapshotsFromCheckpoints(checkpoints, rootRunId, rootRunName, fallba
11968
12222
  }
11969
12223
  const stages = runDrafts.map((draft) => stageSnapshotFromDraft(draft, ids.get(draft.topology.stageId), draft.topology.parentIds.map((parentId) => ids.get(parentId))));
11970
12224
  const toolNodes = completedToolNodes(toolCheckpoints, runId, rootRunId, ids, drafts.firstToolSequenceByHash);
11971
- const run2 = runTopologyFor(runDrafts, ownedTools);
12225
+ const run = runTopologyFor(runDrafts, ownedTools);
11972
12226
  const startedAt = Math.min(...stages.map((stage) => stage.startedAt ?? fallbackCompletedAt), ...toolNodes.map((tool) => tool.startedAt ?? tool.endedAt ?? fallbackCompletedAt));
11973
12227
  const endedAt = Math.max(...stages.map((stage) => stage.endedAt ?? fallbackCompletedAt), ...toolNodes.map((tool) => tool.endedAt ?? fallbackCompletedAt));
11974
- const owner2 = runId === rootRunId ? undefined : boundaryOwner(grouped, runId);
11975
- const status = owner2 === undefined ? "completed" : childRunStatus(owner2);
12228
+ const owner = runId === rootRunId ? undefined : boundaryOwner(grouped, runId);
12229
+ const status = owner === undefined ? "completed" : childRunStatus(owner);
11976
12230
  const terminal = status !== "running" && status !== "pending" && status !== "paused" && status !== "blocked";
11977
- const parentRunId = run2?.parentRunId ?? rootRunId;
12231
+ const parentRunId = run?.parentRunId ?? rootRunId;
11978
12232
  const boundarySourceId = grouped.get(parentRunId)?.find((draft) => childRunIdFromDraft(draft) === runId)?.topology?.stageId;
11979
- const declaredParentStageId = run2?.parentStageId === undefined ? undefined : idMaps.get(parentRunId)?.get(run2.parentStageId);
12233
+ const declaredParentStageId = run?.parentStageId === undefined ? undefined : idMaps.get(parentRunId)?.get(run.parentStageId);
11980
12234
  const parentStageId = declaredParentStageId ?? (boundarySourceId === undefined ? undefined : idMaps.get(parentRunId)?.get(boundarySourceId));
11981
- const ownerChild = owner2 === undefined ? undefined : workflowChildFromDraft(owner2);
12235
+ const ownerChild = owner === undefined ? undefined : workflowChildFromDraft(owner);
11982
12236
  runs.push({
11983
12237
  id: runId,
11984
- name: run2?.runName ?? rootRunName,
12238
+ name: run?.runName ?? rootRunName,
11985
12239
  inputs: {},
11986
12240
  status,
11987
12241
  stages,
11988
12242
  toolNodes,
11989
12243
  startedAt,
11990
12244
  ...terminal ? { endedAt, durationMs: Math.max(0, endedAt - startedAt) } : {},
11991
- ...run2?.parentRunId !== undefined ? { parentRunId: run2.parentRunId } : {},
12245
+ ...run?.parentRunId !== undefined ? { parentRunId: run.parentRunId } : {},
11992
12246
  ...parentStageId !== undefined ? { parentStageId } : {},
11993
- ...run2?.rootRunId !== undefined ? { rootRunId: run2.rootRunId } : {},
12247
+ ...run?.rootRunId !== undefined ? { rootRunId: run.rootRunId } : {},
11994
12248
  ...ownerChild?.exited === true ? {
11995
12249
  result: ownerChild.outputs,
11996
12250
  exited: true,
@@ -12000,13 +12254,13 @@ function runSnapshotsFromCheckpoints(checkpoints, rootRunId, rootRunName, fallba
12000
12254
  });
12001
12255
  emittedRunIds.add(runId);
12002
12256
  }
12003
- for (const { parentRunId, owner: owner2, child } of syntheticChildren) {
12257
+ for (const { parentRunId, owner, child } of syntheticChildren) {
12004
12258
  if (!emittedRunIds.has(parentRunId)) {
12005
12259
  if (policy.failClosed)
12006
12260
  return [];
12007
12261
  continue;
12008
12262
  }
12009
- const topology = owner2.topology;
12263
+ const topology = owner.topology;
12010
12264
  const boundary = topology.boundary;
12011
12265
  const parentStageId = idMaps.get(parentRunId)?.get(topology.stageId);
12012
12266
  if (parentStageId === undefined) {
@@ -12014,8 +12268,8 @@ function runSnapshotsFromCheckpoints(checkpoints, rootRunId, rootRunName, fallba
12014
12268
  return [];
12015
12269
  continue;
12016
12270
  }
12017
- const startedAt = owner2.startedAt ?? owner2.firstCompletedAt;
12018
- const endedAt = owner2.endedAt ?? owner2.firstCompletedAt;
12271
+ const startedAt = owner.startedAt ?? owner.firstCompletedAt;
12272
+ const endedAt = owner.endedAt ?? owner.firstCompletedAt;
12019
12273
  runs.push({
12020
12274
  id: child.runId,
12021
12275
  name: boundary.child.runName,
@@ -12123,7 +12377,7 @@ function syntheticCheckpointStage(checkpointCount, completedAt) {
12123
12377
  // dist/builtin/workflows/src/durable/completed-subtree.ts
12124
12378
  function durableCompletedNestedRunSubtree(backend, rootWorkflowId, childRunId) {
12125
12379
  const nested = durableNestedRunSnapshots(backend, rootWorkflowId);
12126
- if (!nested.some((run2) => run2.id === childRunId))
12380
+ if (!nested.some((run) => run.id === childRunId))
12127
12381
  return;
12128
12382
  const intentionalExitStatuses = new Map;
12129
12383
  for (const checkpoint of backend.listCheckpoints(rootWorkflowId)) {
@@ -12137,22 +12391,22 @@ function durableCompletedNestedRunSubtree(backend, rootWorkflowId, childRunId) {
12137
12391
  let priorSize = -1;
12138
12392
  while (priorSize !== included.size) {
12139
12393
  priorSize = included.size;
12140
- for (const run2 of nested) {
12141
- if (run2.parentRunId !== undefined && included.has(run2.parentRunId))
12142
- included.add(run2.id);
12394
+ for (const run of nested) {
12395
+ if (run.parentRunId !== undefined && included.has(run.parentRunId))
12396
+ included.add(run.id);
12143
12397
  }
12144
12398
  }
12145
- const subtree = nested.filter((run2) => included.has(run2.id));
12146
- const complete = subtree.length === included.size && subtree.every((run2) => isCompleteCachedRun(run2, intentionalExitStatuses));
12399
+ const subtree = nested.filter((run) => included.has(run.id));
12400
+ const complete = subtree.length === included.size && subtree.every((run) => isCompleteCachedRun(run, intentionalExitStatuses));
12147
12401
  return complete ? subtree : undefined;
12148
12402
  }
12149
- function isCompleteCachedRun(run2, intentionalExitStatuses) {
12150
- if (run2.endedAt === undefined || !run2.stages.every((stage) => isTerminalStage2(stage.status) && stage.endedAt !== undefined)) {
12403
+ function isCompleteCachedRun(run, intentionalExitStatuses) {
12404
+ if (run.endedAt === undefined || !run.stages.every((stage) => isTerminalStage2(stage.status) && stage.endedAt !== undefined)) {
12151
12405
  return false;
12152
12406
  }
12153
- if (run2.status === "completed" || run2.exited === true)
12407
+ if (run.status === "completed" || run.exited === true)
12154
12408
  return true;
12155
- return intentionalExitStatuses.get(run2.id) === run2.status;
12409
+ return intentionalExitStatuses.get(run.id) === run.status;
12156
12410
  }
12157
12411
  function isTerminalStage2(status) {
12158
12412
  return status === "completed" || status === "failed" || status === "skipped";
@@ -12197,13 +12451,13 @@ function reciprocalWorkflowRootRunId(runById, runId) {
12197
12451
  }
12198
12452
 
12199
12453
  // dist/builtin/workflows/src/engine/run-durable-topology.ts
12200
- function durableRunTopology(run2) {
12454
+ function durableRunTopology(run) {
12201
12455
  return {
12202
- runId: run2.id,
12203
- runName: run2.name,
12204
- ...run2.parentRunId !== undefined ? { parentRunId: run2.parentRunId } : {},
12205
- ...run2.parentStageId !== undefined ? { parentStageId: run2.parentStageId } : {},
12206
- ...run2.rootRunId !== undefined ? { rootRunId: run2.rootRunId } : {}
12456
+ runId: run.id,
12457
+ runName: run.name,
12458
+ ...run.parentRunId !== undefined ? { parentRunId: run.parentRunId } : {},
12459
+ ...run.parentStageId !== undefined ? { parentStageId: run.parentStageId } : {},
12460
+ ...run.rootRunId !== undefined ? { rootRunId: run.rootRunId } : {}
12207
12461
  };
12208
12462
  }
12209
12463
  function createDurableStageDeps(input) {
@@ -12278,7 +12532,7 @@ function createDurableCachedStageRecorder(input) {
12278
12532
  return {
12279
12533
  record(name, replayKey, checkpoint, scope) {
12280
12534
  const cachedChildRunId = workflowChildRunId(checkpoint);
12281
- const runById = new Map(input.store.runs().map((run2) => [run2.id, run2]));
12535
+ const runById = new Map(input.store.runs().map((run) => [run.id, run]));
12282
12536
  if (!runById.has(input.run.id))
12283
12537
  runById.set(input.run.id, input.run);
12284
12538
  const durableRootId = reciprocalWorkflowRootRunId(runById, input.run.id);
@@ -12294,7 +12548,7 @@ function createDurableCachedStageRecorder(input) {
12294
12548
  replaySourceOrders.set(replayedStage.id, sourceOrder);
12295
12549
  input.run.stages.sort((left, right) => (replaySourceOrders.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (replaySourceOrders.get(right.id) ?? Number.MAX_SAFE_INTEGER));
12296
12550
  }
12297
- const stage = input.store.runs().find((run2) => run2.id === input.run.id)?.stages.find((candidate) => candidate.replayKey === replayKey);
12551
+ const stage = input.store.runs().find((run) => run.id === input.run.id)?.stages.find((candidate) => candidate.replayKey === replayKey);
12298
12552
  if (stage !== undefined) {
12299
12553
  input.backend.recordCheckpoint({
12300
12554
  kind: "stage",
@@ -12332,10 +12586,10 @@ function createDurableCachedStageRecorder(input) {
12332
12586
  };
12333
12587
  }
12334
12588
  function reconcileCachedDirectChildParentStage(input) {
12335
- const existingRun = input.store.runs().find((run2) => run2.id === input.checkpointChildRunId);
12589
+ const existingRun = input.store.runs().find((run) => run.id === input.checkpointChildRunId);
12336
12590
  if (existingRun === undefined)
12337
12591
  return false;
12338
- const runById = new Map(input.store.runs().map((run2) => [run2.id, run2]));
12592
+ const runById = new Map(input.store.runs().map((run) => [run.id, run]));
12339
12593
  const storedParentRun = runById.get(input.parentRun.id);
12340
12594
  if (storedParentRun !== undefined && (storedParentRun.parentRunId !== input.parentRun.parentRunId || storedParentRun.parentStageId !== input.parentRun.parentStageId))
12341
12595
  return false;
@@ -12376,11 +12630,11 @@ function deferStageUntilRunRelease(input) {
12376
12630
  };
12377
12631
  return {
12378
12632
  name: input.name,
12379
- prompt: (...args) => invoke((stage2) => stage2.prompt(...args)),
12380
- complete: (...args) => invoke((stage2) => stage2.complete(...args)),
12381
- sendUserMessage: (...args) => invoke((stage2) => stage2.sendUserMessage(...args)),
12382
- steer: (...args) => invoke((stage2) => stage2.steer(...args)),
12383
- followUp: (...args) => invoke((stage2) => stage2.followUp(...args)),
12633
+ prompt: (...args) => invoke((stage) => stage.prompt(...args)),
12634
+ complete: (...args) => invoke((stage) => stage.complete(...args)),
12635
+ sendUserMessage: (...args) => invoke((stage) => stage.sendUserMessage(...args)),
12636
+ steer: (...args) => invoke((stage) => stage.steer(...args)),
12637
+ followUp: (...args) => invoke((stage) => stage.followUp(...args)),
12384
12638
  subscribe: (...args) => current().subscribe(...args),
12385
12639
  get sessionFile() {
12386
12640
  return current().sessionFile;
@@ -12388,9 +12642,9 @@ function deferStageUntilRunRelease(input) {
12388
12642
  get sessionId() {
12389
12643
  return current().sessionId;
12390
12644
  },
12391
- setModel: (...args) => invoke((stage2) => stage2.setModel(...args)),
12645
+ setModel: (...args) => invoke((stage) => stage.setModel(...args)),
12392
12646
  setThinkingLevel: (...args) => current().setThinkingLevel(...args),
12393
- cycleModel: () => invoke((stage2) => stage2.cycleModel()),
12647
+ cycleModel: () => invoke((stage) => stage.cycleModel()),
12394
12648
  cycleThinkingLevel: () => current().cycleThinkingLevel(),
12395
12649
  get agent() {
12396
12650
  return current().agent;
@@ -12407,10 +12661,10 @@ function deferStageUntilRunRelease(input) {
12407
12661
  get isStreaming() {
12408
12662
  return current().isStreaming;
12409
12663
  },
12410
- navigateTree: (...args) => invoke((stage2) => stage2.navigateTree(...args)),
12411
- compact: () => invoke((stage2) => stage2.compact()),
12664
+ navigateTree: (...args) => invoke((stage) => stage.navigateTree(...args)),
12665
+ compact: () => invoke((stage) => stage.compact()),
12412
12666
  abortCompaction: () => current().abortCompaction(),
12413
- abort: () => invoke((stage2) => stage2.abort())
12667
+ abort: () => invoke((stage) => stage.abort())
12414
12668
  };
12415
12669
  }
12416
12670
 
@@ -12494,9 +12748,9 @@ function createRunTerminalEventArbiter(runId) {
12494
12748
 
12495
12749
  // dist/builtin/workflows/src/engine/run-terminal-failure.ts
12496
12750
  function finalizeTerminalFailure(input) {
12497
- const { runId, runSnapshot, store: store2, persistence, metadata, onRunEnd } = input;
12751
+ const { runId, runSnapshot, store, persistence, metadata, onRunEnd } = input;
12498
12752
  const failedToolNode = metadata.failedToolNodeId === undefined ? undefined : runSnapshot.toolNodes?.find((node) => node.id === metadata.failedToolNodeId);
12499
- const recorded = store2.recordRunEnd(runId, "failed", undefined, metadata.errorMessage, metadata);
12753
+ const recorded = store.recordRunEnd(runId, "failed", undefined, metadata.errorMessage, metadata);
12500
12754
  appendRunEndWhenRecorded(persistence, recorded, {
12501
12755
  runId,
12502
12756
  status: "failed",
@@ -12515,7 +12769,7 @@ function finalizeTerminalFailure(input) {
12515
12769
  ...runSnapshot.durationMs !== undefined ? { durationMs: runSnapshot.durationMs } : {},
12516
12770
  ts: Date.now()
12517
12771
  });
12518
- return reconcileTerminalRunResult(runId, runSnapshot, store2, { status: "failed", error: metadata.errorMessage }, onRunEnd);
12772
+ return reconcileTerminalRunResult(runId, runSnapshot, store, { status: "failed", error: metadata.errorMessage }, onRunEnd);
12519
12773
  }
12520
12774
 
12521
12775
  // dist/builtin/workflows/src/engine/run-tool-admission-boundary.ts
@@ -12653,7 +12907,7 @@ function createAdmittedToolExecutionTracker(options = {}) {
12653
12907
  const admissions = [];
12654
12908
  const failures = [];
12655
12909
  const cancellations = [];
12656
- let nextAdmissionOrder2 = 0;
12910
+ let nextAdmissionOrder = 0;
12657
12911
  let state = "OPEN";
12658
12912
  let closing;
12659
12913
  const abandonment = Promise.withResolvers();
@@ -12662,17 +12916,17 @@ function createAdmittedToolExecutionTracker(options = {}) {
12662
12916
  const recordFailure = (admission, error, nodeId) => {
12663
12917
  if (admission.failure !== undefined)
12664
12918
  return;
12665
- const failure2 = { admissionOrder: admission.admissionOrder, error, ...nodeId === undefined ? {} : { nodeId } };
12666
- admission.failure = failure2;
12667
- failures.push(failure2);
12668
- options.onFailureObserved?.(failure2);
12919
+ const failure = { admissionOrder: admission.admissionOrder, error, ...nodeId === undefined ? {} : { nodeId } };
12920
+ admission.failure = failure;
12921
+ failures.push(failure);
12922
+ options.onFailureObserved?.(failure);
12669
12923
  };
12670
12924
  const reportDrainFailure = () => {
12671
- const failure2 = failures[0];
12672
- if (state !== "DRAINING" || failure2 === undefined || drainFailureReported)
12925
+ const failure = failures[0];
12926
+ if (state !== "DRAINING" || failure === undefined || drainFailureReported)
12673
12927
  return;
12674
12928
  drainFailureReported = true;
12675
- options.onFailureDuringDrain?.(failure2);
12929
+ options.onFailureDuringDrain?.(failure);
12676
12930
  };
12677
12931
  const drainRecordedFailures = () => Promise.all(admissions.flatMap((admission) => admission.failure !== undefined && admission.observed !== undefined ? [admission.observed] : []));
12678
12932
  const closeAtFixedPoint = async () => {
@@ -12704,7 +12958,7 @@ function createAdmittedToolExecutionTracker(options = {}) {
12704
12958
  return { accepted: false, error, bindNode() {}, noteCancelled() {} };
12705
12959
  }
12706
12960
  const admission = {
12707
- admissionOrder: ++nextAdmissionOrder2,
12961
+ admissionOrder: ++nextAdmissionOrder,
12708
12962
  nodeId: undefined,
12709
12963
  failure: undefined,
12710
12964
  cancelled: false,
@@ -12764,7 +13018,7 @@ function createAdmittedToolExecutionTracker(options = {}) {
12764
13018
  return failures[0];
12765
13019
  },
12766
13020
  uniqueFailureFor(error) {
12767
- const matching = [...failures, ...cancellations].filter((failure2) => Object.is(failure2.error, error));
13021
+ const matching = [...failures, ...cancellations].filter((failure) => Object.is(failure.error, error));
12768
13022
  return matching.length === 1 ? matching[0] : undefined;
12769
13023
  }
12770
13024
  };
@@ -12772,8 +13026,8 @@ function createAdmittedToolExecutionTracker(options = {}) {
12772
13026
 
12773
13027
  // dist/builtin/workflows/src/engine/run-tool-node-lifecycle.ts
12774
13028
  function createToolNodeLifecycle(input) {
12775
- const { store: store2, tracker, run: run2, sourceToContinuationNodeIds } = input;
12776
- const ownsCurrentRun = () => store2.runs().some((candidate) => candidate === run2);
13029
+ const { store, tracker, run, sourceToContinuationNodeIds } = input;
13030
+ const ownsCurrentRun = () => store.runs().some((candidate) => candidate === run);
12777
13031
  const replayedToolNodeIds = new Set;
12778
13032
  let pendingFrontier = input.resumeToolNode;
12779
13033
  return {
@@ -12791,11 +13045,11 @@ function createToolNodeLifecycle(input) {
12791
13045
  const sourceParents = frontier?.parentIds ?? (node.replayed === true && node.topologyState !== "unavailable" ? node.parentIds : undefined);
12792
13046
  const restored = sourceParents?.map((sourceId) => sourceToContinuationNodeIds.get(sourceId));
12793
13047
  const translated = restored?.every((id) => id !== undefined) ? restored : undefined;
12794
- if (run2.resumedFromRunId !== undefined && sourceParents !== undefined && translated === undefined) {
12795
- throw new Error(`${REPLAY_TOPOLOGY_MISMATCH_MESSAGE} for tool "${node.name}" (node "${node.id}") in source run ${run2.resumedFromRunId}`);
13048
+ if (run.resumedFromRunId !== undefined && sourceParents !== undefined && translated === undefined) {
13049
+ throw new Error(`${REPLAY_TOPOLOGY_MISMATCH_MESSAGE} for tool "${node.name}" (node "${node.id}") in source run ${run.resumedFromRunId}`);
12796
13050
  }
12797
- if (translated !== undefined && run2.resumedFromRunId !== undefined && !compatibleReplayedToolParents(tracker, translated, inferredParents, (parentId) => isReplayedContinuationNode(store2, run2, replayedToolNodeIds, parentId))) {
12798
- throw new Error(`${REPLAY_TOPOLOGY_MISMATCH_MESSAGE} for tool "${node.name}" (node "${node.id}") in source run ${run2.resumedFromRunId}`);
13051
+ if (translated !== undefined && run.resumedFromRunId !== undefined && !compatibleReplayedToolParents(tracker, translated, inferredParents, (parentId) => isReplayedContinuationNode(store, run, replayedToolNodeIds, parentId))) {
13052
+ throw new Error(`${REPLAY_TOPOLOGY_MISMATCH_MESSAGE} for tool "${node.name}" (node "${node.id}") in source run ${run.resumedFromRunId}`);
12799
13053
  }
12800
13054
  const parentIds = translated ?? inferredParents;
12801
13055
  tracker.replaceParents(node.id, parentIds);
@@ -12804,28 +13058,28 @@ function createToolNodeLifecycle(input) {
12804
13058
  if (node.replayed === true)
12805
13059
  replayedToolNodeIds.add(node.id);
12806
13060
  if (ownsCurrentRun())
12807
- store2.recordToolNodeStart(run2.id, node);
13061
+ store.recordToolNodeStart(run.id, node);
12808
13062
  if (frontier !== undefined)
12809
13063
  pendingFrontier = undefined;
12810
13064
  },
12811
13065
  onNodeRunning: (nodeId, startedAt) => {
12812
13066
  if (ownsCurrentRun())
12813
- store2.recordToolNodeRunning(run2.id, nodeId, startedAt);
13067
+ store.recordToolNodeRunning(run.id, nodeId, startedAt);
12814
13068
  },
12815
13069
  onNodeEnd: (nodeId, update) => {
12816
13070
  if (ownsCurrentRun())
12817
- store2.recordToolNodeEnd(run2.id, nodeId, update);
13071
+ store.recordToolNodeEnd(run.id, nodeId, update);
12818
13072
  },
12819
13073
  onNodeSettle: (nodeId) => {
12820
13074
  tracker.onSettle(nodeId);
12821
13075
  },
12822
- runTopology: durableRunTopology(run2)
13076
+ runTopology: durableRunTopology(run)
12823
13077
  };
12824
13078
  }
12825
- function isReplayedContinuationNode(store2, run2, replayedToolNodeIds, nodeId) {
13079
+ function isReplayedContinuationNode(store, run, replayedToolNodeIds, nodeId) {
12826
13080
  if (replayedToolNodeIds.has(nodeId))
12827
13081
  return true;
12828
- const live = store2.runs().find((candidate) => candidate === run2);
13082
+ const live = store.runs().find((candidate) => candidate === run);
12829
13083
  return live?.stages.some((stage) => stage.id === nodeId && stage.replayed === true) === true;
12830
13084
  }
12831
13085
  function compatibleReplayedToolParents(tracker, translated, inferredParents, isReplayedNode) {
@@ -12842,9 +13096,9 @@ function createTrackedToolPrimitive(input) {
12842
13096
  onFailureObserved: ({ error, nodeId }) => {
12843
13097
  input.terminalEvents.selectFailure(error, nodeId);
12844
13098
  },
12845
- onFailureDuringDrain: (failure2) => {
13099
+ onFailureDuringDrain: (failure) => {
12846
13100
  if (input.terminalEvents.winner()?.kind === "failure")
12847
- input.controller.abort(failure2.error);
13101
+ input.controller.abort(failure.error);
12848
13102
  }
12849
13103
  });
12850
13104
  const lifecycle = createToolNodeLifecycle(input);
@@ -13223,7 +13477,7 @@ function createTrackedStageCaller(input) {
13223
13477
  if (suppressQueuedContinuation)
13224
13478
  runtime.state.suppressQueuedUserMessageContinuation = true;
13225
13479
  try {
13226
- result = await runtime.raceStageSessionHeartbeat(raceAbort(runtime.innerCtx.prompt(RESUME_CONTINUATION_PROMPT), runtime.signal));
13480
+ result = await runtime.raceStageSessionHeartbeat(raceAbort(runtime.innerCtx.__continuePrompt(RESUME_CONTINUATION_PROMPT), runtime.signal));
13227
13481
  } finally {
13228
13482
  if (suppressQueuedContinuation)
13229
13483
  runtime.state.suppressQueuedUserMessageContinuation = false;
@@ -13328,9 +13582,9 @@ function createTrackedStageCaller(input) {
13328
13582
  let resolveNextTurnEnd = null;
13329
13583
  const unsubscribeTurnWatcher = runtime.innerCtx.subscribe((event) => {
13330
13584
  if (event.type === "agent_end" && resolveNextTurnEnd) {
13331
- const resolve9 = resolveNextTurnEnd;
13585
+ const resolve = resolveNextTurnEnd;
13332
13586
  resolveNextTurnEnd = null;
13333
- resolve9();
13587
+ resolve();
13334
13588
  }
13335
13589
  });
13336
13590
  try {
@@ -13343,15 +13597,15 @@ function createTrackedStageCaller(input) {
13343
13597
  runtime.state.askUserQuestionObservedThisTurn = false;
13344
13598
  runtime.state.chatAnswerObservedThisTurn = false;
13345
13599
  if (decision.message !== undefined) {
13346
- result = await runtime.raceStageSessionHeartbeat(raceAbort(runtime.innerCtx.prompt(decision.message), runtime.signal));
13600
+ result = await runtime.raceStageSessionHeartbeat(raceAbort(runtime.innerCtx.__continuePrompt(decision.message), runtime.signal));
13347
13601
  if (runtime.budget.enabled && typeof result === "string")
13348
13602
  stageResultBeforeBudget = result;
13349
13603
  } else {
13350
13604
  runtime.state.waitingForStageChatTurn = true;
13351
13605
  try {
13352
- await runtime.raceStageSessionHeartbeat(raceAbort(new Promise((resolve9) => {
13353
- resolveNextTurnEnd = resolve9;
13354
- runtime.state.wakeWaitingForStageChatTurn = resolve9;
13606
+ await runtime.raceStageSessionHeartbeat(raceAbort(new Promise((resolve) => {
13607
+ resolveNextTurnEnd = resolve;
13608
+ runtime.state.wakeWaitingForStageChatTurn = resolve;
13355
13609
  }), runtime.signal));
13356
13610
  } finally {
13357
13611
  runtime.state.wakeWaitingForStageChatTurn = undefined;
@@ -13391,7 +13645,9 @@ function createTrackedStageCaller(input) {
13391
13645
  await runtime.budget.deliverWrapUp(runtime.name);
13392
13646
  if (afterBudget.kind === "exhausted" && runtime.budget.enabled)
13393
13647
  await runtime.budget.stopAtBoundaryAsync(runtime.name);
13394
- await runtime.innerCtx.__closeGeneration();
13648
+ const finalizedArtifact = await runtime.innerCtx.__closeGeneration();
13649
+ if (typeof result === "string" && finalizedArtifact !== undefined)
13650
+ result = finalizedArtifact;
13395
13651
  await runtime.captureStageSessionMeta({ awaitDurable: true });
13396
13652
  if (trackStageLifecycle && runtime.stageFailFastScope?.failed === true && runtime.stageFailFastScope.activeStages.has(runtime.stageId)) {
13397
13653
  runtime.markSkippedForParallelFailFast();
@@ -13420,7 +13676,7 @@ function createTrackedStageCaller(input) {
13420
13676
  const budgetError = err instanceof WorkflowBudgetExceededError ? err : undefined;
13421
13677
  if (budgetError !== undefined && trackStageLifecycle && !runtime.state.skippedForParallelFailFast) {
13422
13678
  let selectedBudgetError = budgetError;
13423
- if (runtime.activeStore.runs().find((run2) => run2.id === runtime.runId)?.budgetState?.wrapUpCompleted !== true) {
13679
+ if (runtime.activeStore.runs().find((run) => run.id === runtime.runId)?.budgetState?.wrapUpCompleted !== true) {
13424
13680
  try {
13425
13681
  await runtime.budget.deliverWrapUp(runtime.name);
13426
13682
  } catch (wrapUpError) {
@@ -13448,8 +13704,8 @@ function createTrackedStageCaller(input) {
13448
13704
  };
13449
13705
  }
13450
13706
  } else if (trackStageLifecycle && !runtime.signal.aborted && !runtime.state.skippedForParallelFailFast) {
13451
- const failure2 = runtime.classifyExecutorFailure(err);
13452
- applyTerminalStageState = () => applyFailureToStage(runtime.stageSnapshot, failure2);
13707
+ const failure = runtime.classifyExecutorFailure(err);
13708
+ applyTerminalStageState = () => applyFailureToStage(runtime.stageSnapshot, failure);
13453
13709
  }
13454
13710
  throw err;
13455
13711
  } finally {
@@ -13475,8 +13731,8 @@ function createTrackedStageCaller(input) {
13475
13731
  finalizationError ??= durableCheckpointError;
13476
13732
  if (trackStageLifecycle) {
13477
13733
  if (durableCheckpointError !== undefined && terminalStateIsSuccess) {
13478
- const failure2 = runtime.classifyExecutorFailure(durableCheckpointError.error);
13479
- applyTerminalStageState = () => applyFailureToStage(runtime.stageSnapshot, failure2);
13734
+ const failure = runtime.classifyExecutorFailure(durableCheckpointError.error);
13735
+ applyTerminalStageState = () => applyFailureToStage(runtime.stageSnapshot, failure);
13480
13736
  }
13481
13737
  if (!runtime.state.stageFinalized)
13482
13738
  applyTerminalStageState?.();
@@ -13734,8 +13990,8 @@ class StageToolExecutionBuffer {
13734
13990
  // dist/builtin/workflows/src/runs/foreground/executor-stage-control.ts
13735
13991
  function createStageControlHandle(runtime) {
13736
13992
  const messagePreparation = () => {
13737
- const meta2 = runtime.innerCtx.__sessionMeta();
13738
- if (meta2.sessionId !== undefined || meta2.sessionFile !== undefined) {
13993
+ const meta = runtime.innerCtx.__sessionMeta();
13994
+ if (meta.sessionId !== undefined || meta.sessionFile !== undefined) {
13739
13995
  return { beforePreparation: runtime.throwIfStageMutationBlocked };
13740
13996
  }
13741
13997
  if (runtime.stageSnapshot.sessionFile !== undefined) {
@@ -13865,8 +14121,8 @@ function createStageControlHandle(runtime) {
13865
14121
  if (changed) {
13866
14122
  runtime.scheduler.ensureReleaseBarrier(runtime.stageId);
13867
14123
  await runtime.scheduler.cascadePauseFrom(runtime.stageId);
13868
- const run2 = runtime.activeStore.runs().find((candidate) => candidate.id === runtime.runId);
13869
- const stillActive = run2?.stages.some((stage) => stage.status === "running" && stage.id !== runtime.stageId) ?? false;
14124
+ const run = runtime.activeStore.runs().find((candidate) => candidate.id === runtime.runId);
14125
+ const stillActive = run?.stages.some((stage) => stage.status === "running" && stage.id !== runtime.stageId) ?? false;
13870
14126
  if (!stillActive)
13871
14127
  runtime.activeStore.recordRunPaused(runtime.runId);
13872
14128
  }
@@ -13933,6 +14189,7 @@ function createStageControlHandle(runtime) {
13933
14189
  // dist/builtin/workflows/src/runs/foreground/executor-stage-replay.ts
13934
14190
  function createReplayStageContext(input) {
13935
14191
  const { runId, name, stageId, stageSnapshot, replaySource } = input;
14192
+ workflowObservationRuntime(input.activeStore).replayStageIds.add(workflowActivityNodeKey(runId, stageId));
13936
14193
  let replayFinalized = false;
13937
14194
  let unregisterWorkflowExitCleanup = () => {};
13938
14195
  let stageStartEntryAppended = false;
@@ -14002,6 +14259,7 @@ function createReplayStageContext(input) {
14002
14259
  return {
14003
14260
  name,
14004
14261
  prompt: replayText,
14262
+ __continuePrompt: replayText,
14005
14263
  complete: replayText,
14006
14264
  sendUserMessage: async () => rejectReplayMutation("send a user message"),
14007
14265
  __sendUserMessage: async () => rejectReplayMutation("send a user message"),
@@ -14064,13 +14322,13 @@ function createReplayStageContext(input) {
14064
14322
 
14065
14323
  // dist/builtin/workflows/src/durable/run-owner-backend.ts
14066
14324
  function durableRootRunIdForRun(runs, runId) {
14067
- return reciprocalWorkflowRootRunId(new Map(runs.map((run2) => [run2.id, run2])), runId);
14325
+ return reciprocalWorkflowRootRunId(new Map(runs.map((run) => [run.id, run])), runId);
14068
14326
  }
14069
14327
  function durableBackendForRun(backend, runs, runId) {
14070
14328
  const rootRunId = durableRootRunIdForRun(runs, runId);
14071
14329
  if (rootRunId === undefined)
14072
14330
  return;
14073
- const runById = new Map(runs.map((run2) => [run2.id, run2]));
14331
+ const runById = new Map(runs.map((run) => [run.id, run]));
14074
14332
  if (rootRunId === runId)
14075
14333
  return backend;
14076
14334
  const scopes = [];
@@ -14093,17 +14351,17 @@ function durableBackendForRun(backend, runs, runId) {
14093
14351
  }
14094
14352
 
14095
14353
  // dist/builtin/workflows/src/shared/pending-stage-route-capability.ts
14096
- import { randomUUID as randomUUID4 } from "node:crypto";
14354
+ import { randomUUID as randomUUID5 } from "node:crypto";
14097
14355
  var routeCapabilities = new WeakMap;
14098
- function workflowPendingStageRouteCapability(store2, runId) {
14099
- let capabilities = routeCapabilities.get(store2);
14356
+ function workflowPendingStageRouteCapability(store, runId) {
14357
+ let capabilities = routeCapabilities.get(store);
14100
14358
  if (capabilities === undefined) {
14101
14359
  capabilities = new Map;
14102
- routeCapabilities.set(store2, capabilities);
14360
+ routeCapabilities.set(store, capabilities);
14103
14361
  }
14104
14362
  let capability = capabilities.get(runId);
14105
14363
  if (capability === undefined) {
14106
- capability = randomUUID4();
14364
+ capability = randomUUID5();
14107
14365
  capabilities.set(runId, capability);
14108
14366
  }
14109
14367
  return capability;
@@ -14187,7 +14445,7 @@ function parseWorkflowStageTarget(target) {
14187
14445
 
14188
14446
  // dist/builtin/workflows/src/shared/pending-stage-status.ts
14189
14447
  function workflowBoundaryHops(runs, runId) {
14190
- const runById = new Map(runs.map((run2) => [run2.id, run2]));
14448
+ const runById = new Map(runs.map((run) => [run.id, run]));
14191
14449
  const hops = [];
14192
14450
  let current = runById.get(runId);
14193
14451
  while (current !== undefined && current.parentRunId !== undefined) {
@@ -14246,8 +14504,8 @@ function createWorkflowPendingStageDelivery(activeStore, runId, stageId, stageNa
14246
14504
  let drainPromise;
14247
14505
  const pendingReady = () => {
14248
14506
  if (readyPromise === undefined) {
14249
- readyPromise = new Promise((resolve9, reject) => {
14250
- resolveReady = resolve9;
14507
+ readyPromise = new Promise((resolve, reject) => {
14508
+ resolveReady = resolve;
14251
14509
  rejectReady = reject;
14252
14510
  });
14253
14511
  }
@@ -14303,7 +14561,7 @@ async function deliverPendingStageMessages(activeStore, runId, stageId, stageNam
14303
14561
  ].map((entry) => entry.id));
14304
14562
  const runs = activeStore.runs();
14305
14563
  const entries = [
14306
- ...(runs.find((run2) => run2.id === runId)?.pendingStageMessages ?? []).map((entry, index) => ({ entry, index })).filter(({ entry }) => candidateIds.has(entry.id) && entry.sticky !== true),
14564
+ ...(runs.find((run) => run.id === runId)?.pendingStageMessages ?? []).map((entry, index) => ({ entry, index })).filter(({ entry }) => candidateIds.has(entry.id) && entry.sticky !== true),
14307
14565
  ...stickyEntries.map((entry) => ({ entry, index: Number.MAX_SAFE_INTEGER }))
14308
14566
  ].sort((left, right) => (left.entry.admissionOrder ?? left.index + 1) - (right.entry.admissionOrder ?? right.index + 1) || left.index - right.index).map(({ entry }) => entry);
14309
14567
  const rootBackend = getDurableBackend();
@@ -14347,7 +14605,7 @@ function stickyPendingStageEntriesForStage(activeStore, runId, stageId, stageNam
14347
14605
  const rootRunId = durableRootRunIdForRun(runs, runId);
14348
14606
  if (rootRunId === undefined)
14349
14607
  return [];
14350
- const rootRun = runs.find((run2) => run2.id === rootRunId);
14608
+ const rootRun = runs.find((run) => run.id === rootRunId);
14351
14609
  if (rootRun === undefined)
14352
14610
  return [];
14353
14611
  const hops = workflowBoundaryHops(runs, runId);
@@ -14365,20 +14623,20 @@ function stickyPendingStageEntriesForStage(activeStore, runId, stageId, stageNam
14365
14623
  return stageMatchesPathPattern(parsed.segments, hops, [stageId, stageName]);
14366
14624
  });
14367
14625
  }
14368
- function claimPendingDelivery(store2, runId, stageKey, messageId) {
14369
- let claims = pendingDeliveryClaims.get(store2);
14626
+ function claimPendingDelivery(store, runId, stageKey, messageId) {
14627
+ let claims = pendingDeliveryClaims.get(store);
14370
14628
  if (claims === undefined) {
14371
14629
  claims = new Set;
14372
- pendingDeliveryClaims.set(store2, claims);
14630
+ pendingDeliveryClaims.set(store, claims);
14373
14631
  }
14374
- const key2 = JSON.stringify([runId, stageKey, messageId]);
14375
- if (claims.has(key2))
14632
+ const key = JSON.stringify([runId, stageKey, messageId]);
14633
+ if (claims.has(key))
14376
14634
  return;
14377
- claims.add(key2);
14635
+ claims.add(key);
14378
14636
  return () => {
14379
- claims?.delete(key2);
14637
+ claims?.delete(key);
14380
14638
  if (claims?.size === 0)
14381
- pendingDeliveryClaims.delete(store2);
14639
+ pendingDeliveryClaims.delete(store);
14382
14640
  };
14383
14641
  }
14384
14642
  function toPendingStageSender(entry) {
@@ -14442,8 +14700,8 @@ class WorkflowModelValidationError extends Error {
14442
14700
  }
14443
14701
  function formatModelValidationError(failures) {
14444
14702
  const lines = ["workflows: model validation failed before starting workflow.", "Unavailable or ambiguous models:"];
14445
- for (const failure2 of failures) {
14446
- lines.push(`- ${failure2.input} (${failure2.reason})`);
14703
+ for (const failure of failures) {
14704
+ lines.push(`- ${failure.input} (${failure.reason})`);
14447
14705
  }
14448
14706
  return lines.join(`
14449
14707
  `);
@@ -14551,10 +14809,10 @@ function buildModelCandidates(input) {
14551
14809
  failures.push(resolved);
14552
14810
  continue;
14553
14811
  }
14554
- const key2 = candidateKey(resolved);
14555
- if (seen.has(key2))
14812
+ const key = candidateKey(resolved);
14813
+ if (seen.has(key))
14556
14814
  continue;
14557
- seen.add(key2);
14815
+ seen.add(key);
14558
14816
  candidates.push(resolved);
14559
14817
  }
14560
14818
  if (failures.length > 0)
@@ -14647,6 +14905,89 @@ class StageDeliveryActivity {
14647
14905
  }
14648
14906
  }
14649
14907
 
14908
+ // dist/builtin/workflows/src/runs/foreground/stage-runner-artifact-capture.ts
14909
+ class StageArtifactCapture {
14910
+ session;
14911
+ seen = new WeakSet;
14912
+ accepted = [];
14913
+ provisional;
14914
+ receivesMessageEvents = false;
14915
+ closed = false;
14916
+ reset() {
14917
+ this.session = undefined;
14918
+ this.seen = new WeakSet;
14919
+ this.accepted = [];
14920
+ this.provisional = undefined;
14921
+ this.receivesMessageEvents = false;
14922
+ this.closed = false;
14923
+ }
14924
+ beginAttempt(session) {
14925
+ if (this.closed)
14926
+ return;
14927
+ if (this.session === session)
14928
+ this.scan();
14929
+ else {
14930
+ this.session = session;
14931
+ this.receivesMessageEvents = false;
14932
+ this.rememberContext();
14933
+ }
14934
+ this.provisional = [];
14935
+ }
14936
+ settleAttempt(success) {
14937
+ if (this.closed)
14938
+ return;
14939
+ this.scan();
14940
+ if (success)
14941
+ this.accepted.push(...this.provisional ?? []);
14942
+ this.provisional = undefined;
14943
+ }
14944
+ close() {
14945
+ this.scan();
14946
+ this.closed = true;
14947
+ this.session = undefined;
14948
+ this.seen = new WeakSet;
14949
+ this.provisional = undefined;
14950
+ }
14951
+ onEvent(session, event) {
14952
+ if (session !== this.session)
14953
+ return;
14954
+ if (event.type === "message_end") {
14955
+ this.receivesMessageEvents = true;
14956
+ this.capture(event.message);
14957
+ }
14958
+ if (event.type === "compaction_end")
14959
+ this.rememberContext();
14960
+ }
14961
+ messages() {
14962
+ this.scan();
14963
+ return this.accepted;
14964
+ }
14965
+ rememberContext(session = this.session) {
14966
+ if (session !== this.session)
14967
+ return;
14968
+ for (const message of this.session?.messages ?? [])
14969
+ this.seen.add(message);
14970
+ }
14971
+ scan() {
14972
+ if (this.receivesMessageEvents)
14973
+ return;
14974
+ for (const message of this.session?.messages ?? [])
14975
+ this.capture(message);
14976
+ }
14977
+ capture(message) {
14978
+ if (this.seen.has(message))
14979
+ return;
14980
+ this.seen.add(message);
14981
+ if (message.role !== "assistant")
14982
+ return;
14983
+ if (message.stopReason !== "stop" && message.stopReason !== "length")
14984
+ return;
14985
+ if (message.content.some((block) => block.type === "toolCall"))
14986
+ return;
14987
+ (this.provisional ?? this.accepted).push(structuredClone(message));
14988
+ }
14989
+ }
14990
+
14650
14991
  // dist/builtin/workflows/src/runs/foreground/stage-runner-candidate.ts
14651
14992
  function effectiveCandidateReasoning(candidate, fallback) {
14652
14993
  return candidate.reasoningLevel ?? fallback;
@@ -14852,6 +15193,23 @@ function extractMessageText(message) {
14852
15193
  }
14853
15194
  return "";
14854
15195
  }
15196
+ function assistantArtifactTextForGeneration(messages) {
15197
+ const answers = messages.flatMap((message) => {
15198
+ if (message.role !== "assistant")
15199
+ return [];
15200
+ if (message.stopReason !== "stop" && message.stopReason !== "length")
15201
+ return [];
15202
+ if (message.content.some((block) => block.type === "toolCall"))
15203
+ return [];
15204
+ const text = extractMessageText(message);
15205
+ return text.length > 0 ? [text] : [];
15206
+ });
15207
+ return answers.map((text, index) => index === 0 ? text : `
15208
+
15209
+ ## Supplement ${index}
15210
+
15211
+ ${text}`).join("");
15212
+ }
14855
15213
  function lastAssistantTextFromMessages(messages) {
14856
15214
  for (let index = messages.length - 1;index >= 0; index -= 1) {
14857
15215
  const message = messages[index];
@@ -14872,7 +15230,7 @@ function structuredOutputTurnDetail(messages, startIndex) {
14872
15230
  }
14873
15231
  return "The model produced no assistant message after the prompt";
14874
15232
  }
14875
- function assistantArtifactTextForToolCall(messages, toolCallId2) {
15233
+ function assistantArtifactTextForToolCall(messages, toolCallId) {
14876
15234
  for (let index = messages.length - 1;index >= 0; index -= 1) {
14877
15235
  const message = messages[index];
14878
15236
  if (message?.role !== "assistant")
@@ -14880,7 +15238,7 @@ function assistantArtifactTextForToolCall(messages, toolCallId2) {
14880
15238
  const { content } = message;
14881
15239
  if (!Array.isArray(content))
14882
15240
  continue;
14883
- if (!content.some((block) => block.type === "toolCall" && block.id === toolCallId2))
15241
+ if (!content.some((block) => block.type === "toolCall" && block.id === toolCallId))
14884
15242
  continue;
14885
15243
  const text = extractMessageText(message);
14886
15244
  if (text.trim().length > 0)
@@ -14955,8 +15313,8 @@ function terminatingToolResultText(messages, terminatingToolCallIds) {
14955
15313
  if (!message)
14956
15314
  continue;
14957
15315
  if (message.role === "toolResult") {
14958
- const toolCallId2 = message.toolCallId;
14959
- if (typeof toolCallId2 !== "string" || !terminatingToolCallIds.has(toolCallId2)) {
15316
+ const toolCallId = message.toolCallId;
15317
+ if (typeof toolCallId !== "string" || !terminatingToolCallIds.has(toolCallId)) {
14960
15318
  return;
14961
15319
  }
14962
15320
  const text = extractMessageText(message).trim();
@@ -14989,27 +15347,27 @@ function assistantMessage(text) {
14989
15347
 
14990
15348
  // dist/builtin/workflows/src/runs/foreground/stage-runner-options.ts
14991
15349
  import { SessionManager } from "@bastani/atomic";
14992
- function workflowSessionOptions(meta2) {
15350
+ function workflowSessionOptions(meta) {
14993
15351
  return {
14994
15352
  internal: true,
14995
- workflow: { runId: meta2.runId, stageId: meta2.stageId, stageName: meta2.stageName }
15353
+ workflow: { runId: meta.runId, stageId: meta.stageId, stageName: meta.stageName }
14996
15354
  };
14997
15355
  }
14998
- function workflowOrchestrationContext(meta2, stageOptions, pendingStageDelivery) {
15356
+ function workflowOrchestrationContext(meta, stageOptions, pendingStageDelivery) {
14999
15357
  const base = {
15000
15358
  kind: "workflow-stage",
15001
- workflowRunId: meta2.runId,
15002
- workflowStageId: meta2.stageId,
15003
- workflowStageName: meta2.stageName,
15359
+ workflowRunId: meta.runId,
15360
+ workflowStageId: meta.stageId,
15361
+ workflowStageName: meta.stageName,
15004
15362
  constraints: { disableWorkflowTool: true }
15005
15363
  };
15006
- const intercomGroup = stageHasIntercomAccess(stageOptions) ? resolveStageGroup(stageOptions, meta2.workflowIntercomGroup) : undefined;
15364
+ const intercomGroup = stageHasIntercomAccess(stageOptions) ? resolveStageGroup(stageOptions, meta.workflowIntercomGroup) : undefined;
15007
15365
  const context = intercomGroup ? { ...base, intercomGroup } : base;
15008
15366
  return pendingStageDelivery === undefined ? context : { ...context, pendingStageDelivery };
15009
15367
  }
15010
- function stripWorkflowOnlyOptions(options, defaultSessionDir, meta2, pendingStageDelivery) {
15011
- const classification = workflowSessionOptions(meta2);
15012
- const orchestrationContext = workflowOrchestrationContext(meta2, options, pendingStageDelivery);
15368
+ function stripWorkflowOnlyOptions(options, defaultSessionDir, meta, pendingStageDelivery) {
15369
+ const classification = workflowSessionOptions(meta);
15370
+ const orchestrationContext = workflowOrchestrationContext(meta, options, pendingStageDelivery);
15013
15371
  if (!options) {
15014
15372
  return defaultSessionDir === undefined ? { orchestrationContext } : {
15015
15373
  orchestrationContext,
@@ -15090,7 +15448,8 @@ class StageSessionPause {
15090
15448
  abortBoundary: Promise.withResolvers(),
15091
15449
  runnerOwnedDeliveries: new Set,
15092
15450
  confirmed: false,
15093
- ...nativeQueuePause === undefined ? {} : { nativeQueuePause }
15451
+ ...nativeQueuePause === undefined ? {} : { nativeQueuePause },
15452
+ ...session?.pauseTasks && session.resumeTasks ? { taskControl: session } : {}
15094
15453
  };
15095
15454
  request.deferred.promise.catch(() => {});
15096
15455
  request.abortBoundary.promise.catch(() => {});
@@ -15098,7 +15457,11 @@ class StageSessionPause {
15098
15457
  let failed = false;
15099
15458
  try {
15100
15459
  request.nativeQueuePause?.pauseQueuedMessages();
15101
- await session?.abort();
15460
+ const tasks = request.taskControl?.pauseTasks?.();
15461
+ const settled = await Promise.allSettled([tasks, (async () => session?.abort())()]);
15462
+ for (const result of settled)
15463
+ if (result.status === "rejected")
15464
+ throw result.reason;
15102
15465
  request.abortBoundary.resolve();
15103
15466
  await request.abortBoundary.promise;
15104
15467
  request.confirmed = true;
@@ -15106,6 +15469,7 @@ class StageSessionPause {
15106
15469
  failed = true;
15107
15470
  request.abortBoundary.reject(error);
15108
15471
  request.deferred.reject(error);
15472
+ request.taskControl?.resumeTasks?.();
15109
15473
  await this.rollbackNativePause(request.nativeQueuePause);
15110
15474
  throw error;
15111
15475
  } finally {
@@ -15173,6 +15537,7 @@ class StageSessionPause {
15173
15537
  if (releaseAdmitted)
15174
15538
  return;
15175
15539
  beforeRelease?.();
15540
+ request.taskControl?.resumeTasks?.();
15176
15541
  releaseAdmitted = true;
15177
15542
  };
15178
15543
  let releasedQueuedMessages;
@@ -15269,6 +15634,9 @@ async function rejectDisposedCreatedSession(result, stageName) {
15269
15634
  class StageSessionReplacement {
15270
15635
  previous;
15271
15636
  cleanups = new Set;
15637
+ get retiringSession() {
15638
+ return this.previous;
15639
+ }
15272
15640
  retire(session) {
15273
15641
  this.previous = session;
15274
15642
  }
@@ -15348,30 +15716,31 @@ async function sendStageUserMessage(activeSession, content, options, beforeDeliv
15348
15716
  if (activeSession.sendUserMessage !== undefined) {
15349
15717
  beforeDelivery?.();
15350
15718
  let reportedAction;
15351
- const ownership2 = streaming ? undefined : admission === undefined ? createLocalPromptOwnershipObserver(activeSession, promptStarted) : coordinatedPromptOwnershipObserver(admission.startTurn(activeSession, promptStarted ?? (() => {})));
15352
- ownership2?.arm();
15353
- const deliveryId2 = streaming ? undefined : activity?.start();
15719
+ const ownership = streaming ? undefined : admission === undefined ? createLocalPromptOwnershipObserver(activeSession, promptStarted) : coordinatedPromptOwnershipObserver(admission.startTurn(activeSession, promptStarted ?? (() => {})));
15720
+ ownership?.arm();
15721
+ const deliveryId = streaming ? undefined : activity?.start();
15354
15722
  try {
15355
15723
  const delivery = activeSession.sendUserMessage(content, {
15356
15724
  ...deliverAs === undefined ? {} : { deliverAs },
15725
+ ...options?.expandPromptTemplates === undefined ? {} : { expandPromptTemplates: options.expandPromptTemplates },
15357
15726
  __workflowDelivery: {
15358
- promptStarted: ownership2?.observe ?? promptStarted,
15359
- delivered(action2) {
15360
- reportedAction = action2;
15727
+ promptStarted: ownership?.observe ?? promptStarted,
15728
+ delivered(action) {
15729
+ reportedAction = action;
15361
15730
  }
15362
15731
  }
15363
15732
  });
15364
- ownership2?.observeStreaming();
15733
+ ownership?.observeStreaming();
15365
15734
  await delivery;
15366
15735
  const action = reportedAction ?? (streaming ? deliverAs ?? "followUp" : "prompt");
15367
- ownership2?.settle(action);
15736
+ ownership?.settle(action);
15368
15737
  return action;
15369
15738
  } catch (error) {
15370
- ownership2?.settle();
15739
+ ownership?.settle();
15371
15740
  throw error;
15372
15741
  } finally {
15373
- ownership2?.dispose();
15374
- activity?.settle(deliveryId2);
15742
+ ownership?.dispose();
15743
+ activity?.settle(deliveryId);
15375
15744
  }
15376
15745
  }
15377
15746
  if (typeof content !== "string")
@@ -15652,7 +16021,7 @@ class StageSessionController {
15652
16021
  pendingThinkingLevel;
15653
16022
  pendingListeners = new Set;
15654
16023
  listenerUnsubscribes = new Map;
15655
- pauseControl = new StageSessionPause(() => this.session);
16024
+ pauseControl = new StageSessionPause(() => this.session ?? this.replacement.retiringSession);
15656
16025
  hasExplicitModelFallbackConfig;
15657
16026
  candidatesPromise;
15658
16027
  activeCandidateIndex;
@@ -15671,9 +16040,25 @@ class StageSessionController {
15671
16040
  pendingCreationResumeMessage;
15672
16041
  messageAdmission = new StageMessageAdmission;
15673
16042
  deliveryActivity = new StageDeliveryActivity;
15674
- constructor(opts, meta2, effectiveStageOptions, structuredOutputCapture) {
16043
+ artifactCapture = new StageArtifactCapture;
16044
+ beginOutputGeneration() {
16045
+ this.artifactCapture.reset();
16046
+ }
16047
+ outputGenerationMessages() {
16048
+ return this.artifactCapture.messages();
16049
+ }
16050
+ async navigateTree(...args) {
16051
+ const session = await this.ensureSession();
16052
+ this.artifactCapture.messages();
16053
+ try {
16054
+ return await session.navigateTree(...args);
16055
+ } finally {
16056
+ this.artifactCapture.rememberContext(session);
16057
+ }
16058
+ }
16059
+ constructor(opts, meta, effectiveStageOptions, structuredOutputCapture) {
15675
16060
  this.opts = opts;
15676
- this.meta = meta2;
16061
+ this.meta = meta;
15677
16062
  this.effectiveStageOptions = effectiveStageOptions;
15678
16063
  this.structuredOutputCapture = structuredOutputCapture;
15679
16064
  this.hasExplicitModelFallbackConfig = effectiveStageOptions?.model !== undefined || (effectiveStageOptions?.fallbackModels?.length ?? 0) > 0;
@@ -15796,10 +16181,10 @@ class StageSessionController {
15796
16181
  const sessionFile = preparation?.sessionFile;
15797
16182
  const deliver = async (activity) => {
15798
16183
  const activeSession = sessionFile === undefined ? await this.ensureSession("prompt") : await this.ensureSessionFromFile(sessionFile, "prompt");
15799
- const pausedDelivery2 = this.pauseControl.deferRunnerOwnedDelivery(() => sendStageUserMessage(activeSession, content, options, beforeDelivery, release, this.messageAdmission, activity));
15800
- if (pausedDelivery2 !== undefined) {
16184
+ const pausedDelivery = this.pauseControl.deferRunnerOwnedDelivery(() => sendStageUserMessage(activeSession, content, options, beforeDelivery, release, this.messageAdmission, activity));
16185
+ if (pausedDelivery !== undefined) {
15801
16186
  release();
15802
- return pausedDelivery2;
16187
+ return pausedDelivery;
15803
16188
  }
15804
16189
  return sendStageUserMessage(activeSession, content, options, beforeDelivery, release, this.messageAdmission, activity);
15805
16190
  };
@@ -15821,18 +16206,19 @@ class StageSessionController {
15821
16206
  const pending = this.activeCreation ?? this.sessionPromise;
15822
16207
  const session = pending ? await pending : this.session;
15823
16208
  await session?.closeWorkflowStageGeneration?.();
16209
+ this.artifactCapture.close();
15824
16210
  }
15825
16211
  async promptWithFallback(text, sdkOptions, consumer = "prompt") {
15826
16212
  if (!this.hasExplicitModelFallbackConfig) {
15827
16213
  try {
15828
16214
  const activeSession = await this.ensureSession(consumer);
15829
- const resumedText2 = this.pendingCreationResumeMessage;
16215
+ const resumedText = this.pendingCreationResumeMessage;
15830
16216
  this.pendingCreationResumeMessage = undefined;
15831
16217
  const value = activeSession.model ?? "default";
15832
16218
  const candidate = { id: workflowModelId(value) ?? "default", value };
15833
16219
  this.beginAttemptUsage(activeSession);
15834
16220
  try {
15835
- await this.promptWithThrownErrorRetry(activeSession, resumedText2 ?? text, sdkOptions);
16221
+ await this.promptWithThrownErrorRetry(activeSession, resumedText ?? text, sdkOptions);
15836
16222
  } catch (error) {
15837
16223
  await this.handleCandidateFailure(error, candidate, [candidate], 0);
15838
16224
  throw error;
@@ -15849,10 +16235,12 @@ class StageSessionController {
15849
16235
  if (candidates.length === 0) {
15850
16236
  try {
15851
16237
  const activeSession = await this.ensureSession(consumer);
15852
- const resumedText2 = this.pendingCreationResumeMessage;
16238
+ const resumedText = this.pendingCreationResumeMessage;
15853
16239
  this.pendingCreationResumeMessage = undefined;
15854
- await this.promptWithThrownErrorRetry(activeSession, resumedText2 ?? text, sdkOptions);
16240
+ await this.promptWithThrownErrorRetry(activeSession, resumedText ?? text, sdkOptions);
16241
+ this.artifactCapture.settleAttempt(true);
15855
16242
  } catch (error) {
16243
+ this.artifactCapture.settleAttempt(false);
15856
16244
  if (error instanceof StageSessionCreationCancelled)
15857
16245
  return;
15858
16246
  throw error;
@@ -15900,10 +16288,10 @@ class StageSessionController {
15900
16288
  this.recordSuccessfulAttempt(candidate);
15901
16289
  return;
15902
16290
  } catch (err) {
15903
- const failure2 = await this.handleCandidateFailure(err, candidate, candidates, index);
15904
- if (failure2 === "handled")
16291
+ const failure = await this.handleCandidateFailure(err, candidate, candidates, index);
16292
+ if (failure === "handled")
15905
16293
  return;
15906
- if (failure2 === "throw")
16294
+ if (failure === "throw")
15907
16295
  throw err;
15908
16296
  index += 1;
15909
16297
  }
@@ -15997,14 +16385,14 @@ class StageSessionController {
15997
16385
  const { signal } = this.opts;
15998
16386
  if (!signal)
15999
16387
  return;
16000
- const abortReason3 = () => {
16388
+ const abortReason = () => {
16001
16389
  const reason = signal.reason;
16002
16390
  if (reason instanceof Error || reason instanceof DOMException || typeof reason === "string")
16003
16391
  return reason;
16004
16392
  return new DOMException("workflow killed", "AbortError");
16005
16393
  };
16006
16394
  const onAbort = () => {
16007
- const reason = abortReason3();
16395
+ const reason = abortReason();
16008
16396
  this.markAbort(reason);
16009
16397
  this.session?.abort().catch(() => {});
16010
16398
  this.pauseControl.reject(reason);
@@ -16144,6 +16532,7 @@ class StageSessionController {
16144
16532
  let retainedPrompt;
16145
16533
  let terminalScanStartIndex;
16146
16534
  while (true) {
16535
+ this.artifactCapture.beginAttempt(activeSession);
16147
16536
  const messagesBeforeAttempt = [...activeSession.messages];
16148
16537
  try {
16149
16538
  if (retryAdmittedPrompt) {
@@ -16186,6 +16575,7 @@ class StageSessionController {
16186
16575
  const willRetry = decision !== undefined && !this.disposed && this.opts.signal?.aborted !== true && !this.capturedStructuredOutputForAttempt();
16187
16576
  const willContinue = continuationSession !== undefined && admittedMessages;
16188
16577
  if (retryableFailure && willRetry) {
16578
+ this.artifactCapture.settleAttempt(false);
16189
16579
  retainedPrompt = this.restoreSessionMessages(activeSession, messagesBeforeAttempt, nextText, willContinue) ?? retainedPrompt;
16190
16580
  }
16191
16581
  if (!willRetry)
@@ -16352,9 +16742,9 @@ class StageSessionController {
16352
16742
  while (true) {
16353
16743
  try {
16354
16744
  if (pendingFailure !== undefined) {
16355
- const failure2 = pendingFailure;
16745
+ const failure = pendingFailure;
16356
16746
  pendingFailure = undefined;
16357
- throw failure2.error;
16747
+ throw failure.error;
16358
16748
  }
16359
16749
  return await this.createSessionObservingPause(candidate, consumer);
16360
16750
  } catch (error) {
@@ -16471,6 +16861,7 @@ class StageSessionController {
16471
16861
  }
16472
16862
  this.unsubscribeTerminateWatcher?.();
16473
16863
  this.unsubscribeTerminateWatcher = result.session.subscribe((event) => {
16864
+ this.artifactCapture.onEvent(result.session, event);
16474
16865
  const terminatingId = terminatingToolCallId(event);
16475
16866
  if (terminatingId !== undefined)
16476
16867
  this.terminatingToolCallIds.add(terminatingId);
@@ -16554,6 +16945,7 @@ class StageSessionController {
16554
16945
  const { terminalScanStartIndex } = await this.promptWithThrownErrorRetry(resumedSession, text, sdkOptions);
16555
16946
  const terminalFailure = latestTerminalAssistantFailureSince(resumedSession.messages, terminalScanStartIndex);
16556
16947
  if (terminalFailure === undefined || this.capturedStructuredOutputForAttempt()) {
16948
+ this.artifactCapture.settleAttempt(true);
16557
16949
  const usage = this.takeAttemptUsage(resumedSession);
16558
16950
  this.modelAttempts.push({
16559
16951
  model: resumedLabel,
@@ -16568,17 +16960,19 @@ class StageSessionController {
16568
16960
  throw new WorkflowPromptModelFailure(terminalFailure);
16569
16961
  } catch (err) {
16570
16962
  if (this.capturedStructuredOutputForAttempt() && isRetryableModelFailure(err)) {
16571
- const usage2 = this.takeAttemptUsage(resumedSession);
16963
+ this.artifactCapture.settleAttempt(true);
16964
+ const usage = this.takeAttemptUsage(resumedSession);
16572
16965
  this.modelAttempts.push({
16573
16966
  model: resumedLabel,
16574
16967
  success: true,
16575
- ...usage2 === undefined ? {} : { usage: usage2 }
16968
+ ...usage === undefined ? {} : { usage }
16576
16969
  });
16577
16970
  this.pendingFallbackWarnings.length = 0;
16578
16971
  this.resumeCurrentSession = true;
16579
16972
  this.notifySuccessfulModelFallbackMeta();
16580
16973
  return true;
16581
16974
  }
16975
+ this.artifactCapture.settleAttempt(false);
16582
16976
  const message = errorMessage2(err);
16583
16977
  const usage = this.takeAttemptUsage(resumedSession);
16584
16978
  this.modelAttempts.push({
@@ -16613,6 +17007,7 @@ class StageSessionController {
16613
17007
  this.recordSuccessfulAttempt(candidate);
16614
17008
  return "handled";
16615
17009
  }
17010
+ this.artifactCapture.settleAttempt(false);
16616
17011
  const usage = this.takeAttemptUsage(this.session);
16617
17012
  this.modelAttempts.push({
16618
17013
  model: candidate.id,
@@ -16636,6 +17031,7 @@ class StageSessionController {
16636
17031
  return this.structuredOutputCapture?.called === true && this.opts.signal?.aborted !== true;
16637
17032
  }
16638
17033
  recordSuccessfulAttempt(candidate) {
17034
+ this.artifactCapture.settleAttempt(true);
16639
17035
  const usage = this.takeAttemptUsage(this.session);
16640
17036
  this.modelAttempts.push({
16641
17037
  model: candidate.id,
@@ -16843,7 +17239,7 @@ function stageOutputInstruction(outputOptions, hasStructuredOutput = false) {
16843
17239
  }
16844
17240
  return `
16845
17241
 
16846
- [This stage's final message is saved verbatim as its artifact and is what later stages read. Return the complete result in that message rather than a pointer to it. Files you write yourself are not the artifact.]`;
17242
+ [This stage's completed answers are saved as its artifact and are what later stages read. Return the complete result as ordinary assistant text rather than a pointer to it. Follow-up answers within this stage are appended as numbered supplements, not replacements; state corrections explicitly. Tool-call progress is transcript-only. Files you write yourself are not the artifact.]`;
16847
17243
  }
16848
17244
  async function finalizePromptOutput(fullOutput, outputOptions, runtimeCwd, runId, messages) {
16849
17245
  const outputPath = resolveOutputPath(outputOptions.output, runtimeCwd, outputOptions.cwd);
@@ -16889,7 +17285,7 @@ function createStageContext2(opts) {
16889
17285
  const structuredOutputCapture = stageOptions?.schema ? createStructuredOutputCapture() : undefined;
16890
17286
  const structuredOutputExecutionCapture = stageOptions?.schema ? {} : undefined;
16891
17287
  const effectiveStageOptions = stageOptionsWithStructuredOutput(stageOptions, structuredOutputCapture, structuredOutputExecutionCapture);
16892
- const meta2 = {
17288
+ const meta = {
16893
17289
  runId,
16894
17290
  stageId,
16895
17291
  stageName,
@@ -16898,21 +17294,40 @@ function createStageContext2(opts) {
16898
17294
  stageOptions: effectiveStageOptions,
16899
17295
  executionMode
16900
17296
  };
16901
- const controller = new StageSessionController(opts, meta2, effectiveStageOptions, structuredOutputCapture);
17297
+ const controller = new StageSessionController(opts, meta, effectiveStageOptions, structuredOutputCapture);
16902
17298
  let lastAssistantText;
16903
17299
  let lastFinalizedOutput;
16904
17300
  let lastFinalizedMessageCount;
16905
17301
  let structuredArtifactFinalized = false;
16906
17302
  let adapterMessages = [];
17303
+ let artifactOptions;
17304
+ let artifactClosed = false;
17305
+ let artifactText;
17306
+ let continuing = false;
17307
+ async function exportArtifact() {
17308
+ const text = assistantArtifactTextForGeneration(controller.outputGenerationMessages());
17309
+ if (text !== artifactText || lastFinalizedOutput === undefined) {
17310
+ lastFinalizedOutput = await finalizePromptOutput(text, artifactOptions, runtimeCwd(), runId, controller.currentSession?.messages);
17311
+ artifactText = text;
17312
+ lastAssistantText = lastFinalizedOutput;
17313
+ }
17314
+ return lastFinalizedOutput;
17315
+ }
16907
17316
  function runtimeCwd() {
16908
17317
  return typeof effectiveStageOptions?.cwd === "string" ? effectiveStageOptions.cwd : process.cwd();
16909
17318
  }
16910
17319
  function finalizedOutputIsCurrent() {
16911
- return lastFinalizedOutput !== undefined && (structuredArtifactFinalized || lastFinalizedMessageCount === undefined || controller.currentSession?.messages.length === lastFinalizedMessageCount);
17320
+ if (lastFinalizedOutput === undefined)
17321
+ return false;
17322
+ if (artifactOptions !== undefined || structuredArtifactFinalized)
17323
+ return true;
17324
+ return lastFinalizedMessageCount === undefined || controller.currentSession?.messages.length === lastFinalizedMessageCount;
16912
17325
  }
16913
17326
  return {
16914
17327
  name: stageName,
16915
17328
  async prompt(text, options) {
17329
+ if (continuing && artifactOptions)
17330
+ options = { ...options, ...artifactOptions };
16916
17331
  const { sdkOptions, outputOptions } = splitPromptOptions(options);
16917
17332
  validatePromptOutputOptions(outputOptions);
16918
17333
  const hasOutputArtifact = typeof outputOptions.output === "string" && outputOptions.output.length > 0;
@@ -16920,15 +17335,23 @@ function createStageContext2(opts) {
16920
17335
  if (structuredOutputCapture?.called) {
16921
17336
  throw new Error("atomic-workflows: stage schema supports one prompt() call per stage context because structured_output may be called exactly once. Create a new ctx.stage(...) for each additional schema-backed prompt.");
16922
17337
  }
17338
+ if (!continuing) {
17339
+ controller.beginOutputGeneration();
17340
+ artifactOptions = undefined;
17341
+ artifactClosed = false;
17342
+ artifactText = undefined;
17343
+ }
17344
+ if (hasOutputArtifact && !structuredOutputCapture && !adapters.prompt)
17345
+ artifactOptions = outputOptions;
16923
17346
  if (adapters.prompt) {
16924
17347
  if (structuredOutputCapture) {
16925
17348
  throw new Error("atomic-workflows: stage schema requires an AgentSessionAdapter so the structured_output tool can be registered.");
16926
17349
  }
16927
- const rawText2 = await runCallback2({ kind: "workflow.stage_adapter", name: `prompt:${stageName}`, runId, stageId }, () => adapters.prompt.prompt(promptText, meta2));
16928
- if (typeof rawText2 !== "string")
16929
- return rawText2;
16930
- adapterMessages = assistantMessage(rawText2);
16931
- lastAssistantText = await finalizePromptOutput(rawText2, outputOptions, runtimeCwd(), runId, adapterMessages);
17350
+ const rawText = await runCallback2({ kind: "workflow.stage_adapter", name: `prompt:${stageName}`, runId, stageId }, () => adapters.prompt.prompt(promptText, meta));
17351
+ if (typeof rawText !== "string")
17352
+ return rawText;
17353
+ adapterMessages = assistantMessage(rawText);
17354
+ lastAssistantText = await finalizePromptOutput(rawText, outputOptions, runtimeCwd(), runId, adapterMessages);
16932
17355
  lastFinalizedOutput = lastAssistantText;
16933
17356
  lastFinalizedMessageCount = controller.currentSession?.messages.length;
16934
17357
  return lastAssistantText;
@@ -16970,17 +17393,28 @@ function createStageContext2(opts) {
16970
17393
  return executionSnapshot.value;
16971
17394
  }
16972
17395
  await controller.promptWithFallback(promptText, sdkOptions);
17396
+ if (artifactOptions)
17397
+ return await exportArtifact();
16973
17398
  const rawText = controller.lastAssistantText(lastAssistantText) ?? "";
16974
17399
  lastAssistantText = await finalizePromptOutput(rawText, outputOptions, runtimeCwd(), runId, controller.currentSession?.messages);
16975
17400
  lastFinalizedOutput = lastAssistantText;
16976
17401
  lastFinalizedMessageCount = controller.currentSession?.messages.length;
16977
17402
  return lastAssistantText;
16978
17403
  },
17404
+ async __continuePrompt(text) {
17405
+ continuing = true;
17406
+ try {
17407
+ return await this.prompt(text);
17408
+ } finally {
17409
+ continuing = false;
17410
+ }
17411
+ },
16979
17412
  async complete(text, completeOpts) {
17413
+ artifactOptions = undefined;
16980
17414
  if (adapters.complete) {
16981
17415
  lastFinalizedOutput = undefined;
16982
17416
  lastFinalizedMessageCount = undefined;
16983
- lastAssistantText = await runCallback2({ kind: "workflow.stage_adapter", name: `complete:${stageName}`, runId, stageId }, () => adapters.complete.complete(text, completeOpts, meta2));
17417
+ lastAssistantText = await runCallback2({ kind: "workflow.stage_adapter", name: `complete:${stageName}`, runId, stageId }, () => adapters.complete.complete(text, completeOpts, meta));
16984
17418
  adapterMessages = assistantMessage(lastAssistantText);
16985
17419
  return lastAssistantText;
16986
17420
  }
@@ -17045,7 +17479,7 @@ function createStageContext2(opts) {
17045
17479
  return controller.currentSession?.isStreaming ?? false;
17046
17480
  },
17047
17481
  async navigateTree(targetId, options) {
17048
- return (await controller.ensureSession()).navigateTree(targetId, options);
17482
+ return controller.navigateTree(targetId, options);
17049
17483
  },
17050
17484
  async compact() {
17051
17485
  return (await controller.ensureSession()).compact();
@@ -17076,6 +17510,11 @@ function createStageContext2(opts) {
17076
17510
  },
17077
17511
  async __closeGeneration() {
17078
17512
  await controller.closeGeneration();
17513
+ if (artifactOptions && !artifactClosed) {
17514
+ await exportArtifact();
17515
+ artifactClosed = true;
17516
+ }
17517
+ return artifactOptions ? lastFinalizedOutput : undefined;
17079
17518
  },
17080
17519
  __sessionMeta() {
17081
17520
  return controller.sessionMeta();
@@ -17110,7 +17549,7 @@ function createStageSessionHeartbeat(checkpoint, intervalMs = STAGE_SESSION_HEAR
17110
17549
  let timer;
17111
17550
  let generation = 0;
17112
17551
  let nextDeadline = 0;
17113
- let failure2;
17552
+ let failure;
17114
17553
  let inFlight;
17115
17554
  let rejectFailure;
17116
17555
  const failureSignal = new Promise((_resolve, reject) => {
@@ -17127,14 +17566,14 @@ function createStageSessionHeartbeat(checkpoint, intervalMs = STAGE_SESSION_HEAR
17127
17566
  timer = undefined;
17128
17567
  };
17129
17568
  const fail = (error) => {
17130
- if (failure2 !== undefined)
17569
+ if (failure !== undefined)
17131
17570
  return;
17132
- failure2 = error;
17571
+ failure = error;
17133
17572
  stopScheduling();
17134
17573
  rejectFailure(error);
17135
17574
  };
17136
17575
  const schedule = (scheduledGeneration) => {
17137
- if (!active || failure2 !== undefined || scheduledGeneration !== generation)
17576
+ if (!active || failure !== undefined || scheduledGeneration !== generation)
17138
17577
  return;
17139
17578
  const delayMs = Math.max(0, nextDeadline - Date.now());
17140
17579
  timer = setTimeout(() => {
@@ -17155,12 +17594,12 @@ function createStageSessionHeartbeat(checkpoint, intervalMs = STAGE_SESSION_HEAR
17155
17594
  const drain = async () => {
17156
17595
  stopScheduling();
17157
17596
  await inFlight;
17158
- if (failure2 !== undefined)
17159
- throw failure2;
17597
+ if (failure !== undefined)
17598
+ throw failure;
17160
17599
  };
17161
17600
  return {
17162
17601
  start() {
17163
- if (active || failure2 !== undefined)
17602
+ if (active || failure !== undefined)
17164
17603
  return;
17165
17604
  active = true;
17166
17605
  generation += 1;
@@ -17171,8 +17610,8 @@ function createStageSessionHeartbeat(checkpoint, intervalMs = STAGE_SESSION_HEAR
17171
17610
  drain,
17172
17611
  fail,
17173
17612
  race(work) {
17174
- if (failure2 !== undefined)
17175
- return Promise.reject(failure2);
17613
+ if (failure !== undefined)
17614
+ return Promise.reject(failure);
17176
17615
  return Promise.race([work, failureSignal]);
17177
17616
  }
17178
17617
  };
@@ -17253,16 +17692,16 @@ function createWorkflowStageFactory(input) {
17253
17692
  throwIfWorkflowExitSelected: input.exit.throwIfWorkflowExitSelected
17254
17693
  });
17255
17694
  }
17256
- const applyModelFallbackMeta = (meta2) => {
17257
- if (meta2.model !== undefined)
17258
- stageSnapshot.model = meta2.model;
17259
- if (meta2.attemptedModels !== undefined)
17260
- stageSnapshot.attemptedModels = meta2.attemptedModels;
17261
- if (meta2.modelAttempts !== undefined)
17262
- stageSnapshot.modelAttempts = meta2.modelAttempts;
17263
- if (meta2.warnings !== undefined) {
17264
- if (meta2.warnings.length > 0)
17265
- stageSnapshot.warnings = meta2.warnings;
17695
+ const applyModelFallbackMeta = (meta) => {
17696
+ if (meta.model !== undefined)
17697
+ stageSnapshot.model = meta.model;
17698
+ if (meta.attemptedModels !== undefined)
17699
+ stageSnapshot.attemptedModels = meta.attemptedModels;
17700
+ if (meta.modelAttempts !== undefined)
17701
+ stageSnapshot.modelAttempts = meta.modelAttempts;
17702
+ if (meta.warnings !== undefined) {
17703
+ if (meta.warnings.length > 0)
17704
+ stageSnapshot.warnings = meta.warnings;
17266
17705
  else
17267
17706
  delete stageSnapshot.warnings;
17268
17707
  }
@@ -17290,8 +17729,8 @@ function createWorkflowStageFactory(input) {
17290
17729
  models: input.opts.models,
17291
17730
  executionMode: input.opts.executionMode,
17292
17731
  defaultSessionDir: input.opts.defaultSessionDir,
17293
- onModelFallbackMetaChange(meta2) {
17294
- applyModelFallbackMeta(meta2);
17732
+ onModelFallbackMetaChange(meta) {
17733
+ applyModelFallbackMeta(meta);
17295
17734
  if (stageSnapshot.status === "running")
17296
17735
  input.activeStore.recordStageStart(input.runId, stageSnapshot);
17297
17736
  },
@@ -17363,13 +17802,13 @@ function createWorkflowStageFactory(input) {
17363
17802
  await innerCtx.__dispose();
17364
17803
  };
17365
17804
  const captureStageSessionMeta = async (checkpointOptions) => {
17366
- const meta2 = innerCtx.__sessionMeta();
17367
- if (meta2.sessionId !== undefined)
17368
- stageSnapshot.sessionId = meta2.sessionId;
17369
- if (meta2.sessionFile !== undefined)
17370
- stageSnapshot.sessionFile = meta2.sessionFile;
17371
- if (meta2.sessionId !== undefined || meta2.sessionFile !== undefined)
17372
- input.activeStore.recordStageSession(input.runId, stageId, meta2);
17805
+ const meta = innerCtx.__sessionMeta();
17806
+ if (meta.sessionId !== undefined)
17807
+ stageSnapshot.sessionId = meta.sessionId;
17808
+ if (meta.sessionFile !== undefined)
17809
+ stageSnapshot.sessionFile = meta.sessionFile;
17810
+ if (meta.sessionId !== undefined || meta.sessionFile !== undefined)
17811
+ input.activeStore.recordStageSession(input.runId, stageId, meta);
17373
17812
  const pending = input.opts.onStageSession?.(input.runId, stageSnapshot, checkpointOptions);
17374
17813
  if (checkpointOptions?.forceDurable === true || checkpointOptions?.awaitDurable === true) {
17375
17814
  await pending;
@@ -17709,7 +18148,7 @@ class EngineRuntime {
17709
18148
  // dist/builtin/workflows/src/engine/workflow-activity.ts
17710
18149
  import { runCallback as runCallback4 } from "@bastani/atomic";
17711
18150
  function nextEventLoopTurn() {
17712
- return new Promise((resolve10) => setTimeout(resolve10, 0));
18151
+ return new Promise((resolve) => setTimeout(resolve, 0));
17713
18152
  }
17714
18153
  function runWorkflowDefinitionCallback(name, runId, callback) {
17715
18154
  return runCallback4({ kind: "workflow.run", name, runId }, callback);
@@ -17737,7 +18176,7 @@ async function run(def, inputs, opts = {}) {
17737
18176
  }
17738
18177
  const resolvedInputs = resolveAndValidateInputs(def.inputs, inputs, `workflow "${def.name}"`);
17739
18178
  const runId = opts.runId ?? crypto.randomUUID();
17740
- const declaresBudget = (budget2) => (budget2?.maxDurationMs ?? 0) > 0 || (budget2?.maxTokens ?? 0) > 0 || (budget2?.maxCost ?? 0) > 0;
18179
+ const declaresBudget = (budget) => (budget?.maxDurationMs ?? 0) > 0 || (budget?.maxTokens ?? 0) > 0 || (budget?.maxCost ?? 0) > 0;
17741
18180
  const hasBudgetDeclaration = declaresBudget(opts.budget) || declaresBudget(def.budget) || declaresBudget(opts.config?.budget);
17742
18181
  const priorRun = hasBudgetDeclaration && opts.rootBudget === undefined && opts.continuation === undefined && opts.runId !== undefined ? activeStore.runs().find((candidate) => candidate.id === runId) : undefined;
17743
18182
  const continuedBudget = opts.continuation?.source.budget ?? priorRun?.budget;
@@ -17750,14 +18189,17 @@ async function run(def, inputs, opts = {}) {
17750
18189
  terminalEvents.selectCancellation(ownController.signal.reason);
17751
18190
  }, { once: true });
17752
18191
  const callerSignal = opts.signal;
17753
- const onCallerAbort = () => ownController.abort(callerSignal?.reason);
18192
+ const onCallerAbort = () => {
18193
+ workflowObservationRuntime(activeStore).control(runId, "kill");
18194
+ ownController.abort(callerSignal?.reason);
18195
+ };
17754
18196
  const exit = createWorkflowExitManager({ runId, exitScope, controller: ownController });
17755
18197
  const backendView = opts.durableBackend ?? getDurableBackend();
17756
18198
  const rootBackend = opts.durableRootBackend ?? backendView;
17757
18199
  const durableBackend = opts.durableScope !== undefined ? new ScopedDurableBackend(backendView, opts.durableScope) : backendView;
17758
18200
  const inheritedElapsedMs = opts.parentRun === undefined ? inheritedRunElapsedMs({ backend: durableBackend, runId, continuationSource: opts.continuation?.source }) : undefined;
17759
18201
  const continuationOrigin = opts.continuation !== undefined ? opts.continuation.source.origin : opts.origin;
17760
- const snapshotField = (field2) => resolvedBudget[field2] > 0 || opts.budget?.[field2] !== undefined || def.budget?.[field2] !== undefined ? resolvedBudget[field2] : undefined;
18202
+ const snapshotField = (field) => resolvedBudget[field] > 0 || opts.budget?.[field] !== undefined || def.budget?.[field] !== undefined ? resolvedBudget[field] : undefined;
17761
18203
  const budgetSnapshot = resolvedBudget.maxDurationMs > 0 || resolvedBudget.maxTokens > 0 || resolvedBudget.maxCost > 0 ? {
17762
18204
  maxDurationMs: resolvedBudget.maxDurationMs,
17763
18205
  ...snapshotField("maxTokens") !== undefined ? { maxTokens: snapshotField("maxTokens") } : {},
@@ -17766,7 +18208,7 @@ async function run(def, inputs, opts = {}) {
17766
18208
  } : undefined;
17767
18209
  const durableAccounting = hasBudgetDeclaration && opts.parentRun === undefined && opts.continuation === undefined && priorRun === undefined ? priorRunAccounting(durableBackend, runId) : undefined;
17768
18210
  const continuedBudgetState = opts.continuation?.source.budgetState ?? priorRun?.budgetState ?? (durableAccounting === undefined ? undefined : { accounting: durableAccounting });
17769
- const sameBudget = budgetSnapshot !== undefined && continuedBudget?.warnAtPercent === budgetSnapshot.warnAtPercent && ["maxDurationMs", "maxTokens", "maxCost"].every((field2) => (continuedBudget?.[field2] ?? 0) === (budgetSnapshot[field2] ?? 0));
18211
+ const sameBudget = budgetSnapshot !== undefined && continuedBudget?.warnAtPercent === budgetSnapshot.warnAtPercent && ["maxDurationMs", "maxTokens", "maxCost"].every((field) => (continuedBudget?.[field] ?? 0) === (budgetSnapshot[field] ?? 0));
17770
18212
  const continuationBudgetState = continuedBudgetState === undefined || !sameBudget && continuedBudgetState.accounting === undefined ? undefined : sameBudget ? continuedBudgetState : { accounting: continuedBudgetState.accounting };
17771
18213
  const continuationSourceRunId = opts.continuation?.source.id;
17772
18214
  const persistedPossibleStages = coercePossibleStages(opts.possibleStages) ?? (continuationSourceRunId !== undefined ? coercePossibleStages(rootBackend.getWorkflow(continuationSourceRunId)?.possibleStages) : undefined);
@@ -17808,9 +18250,9 @@ async function run(def, inputs, opts = {}) {
17808
18250
  children.push(snapshot);
17809
18251
  childrenByParent.set(snapshot.parentRunId, children);
17810
18252
  }
17811
- const build = (run2) => {
17812
- const children = (childrenByParent.get(run2.id) ?? []).map(build);
17813
- return children.length === 0 ? { run: run2 } : { run: run2, children };
18253
+ const build = (run) => {
18254
+ const children = (childrenByParent.get(run.id) ?? []).map(build);
18255
+ return children.length === 0 ? { run } : { run, children };
17814
18256
  };
17815
18257
  return build(snapshots.find((snapshot) => snapshot.id === runSnapshot.id) ?? runSnapshot);
17816
18258
  };
@@ -18005,7 +18447,7 @@ async function run(def, inputs, opts = {}) {
18005
18447
  };
18006
18448
  const taskRunners = createWorkflowTaskRunners({ runtime });
18007
18449
  let pendingChildDurableInvocation;
18008
- const workflow2 = createChildWorkflowRunner({
18450
+ const workflow = createChildWorkflowRunner({
18009
18451
  runtime,
18010
18452
  resolveWorkflowCwd,
18011
18453
  nextWorkflowBoundaryReplayKey,
@@ -18138,7 +18580,7 @@ async function run(def, inputs, opts = {}) {
18138
18580
  },
18139
18581
  recordCachedStage,
18140
18582
  runTopology: durableRunTopology(runSnapshot),
18141
- workflow: workflow2
18583
+ workflow
18142
18584
  });
18143
18585
  const pendingChildWorkflows = new Set;
18144
18586
  const durableStage = createDurableStagePrimitive({
@@ -18251,11 +18693,12 @@ async function run(def, inputs, opts = {}) {
18251
18693
  });
18252
18694
  terminalEvents.register();
18253
18695
  try {
18696
+ workflowObservationRuntime(activeStore).startRun(runId);
18697
+ activeStore.recordRunStart(runSnapshot);
18254
18698
  if (callerSignal?.aborted)
18255
18699
  onCallerAbort();
18256
18700
  else
18257
18701
  callerSignal?.addEventListener("abort", onCallerAbort, { once: true });
18258
- activeStore.recordRunStart(runSnapshot);
18259
18702
  if (ownsCancellationRegistration)
18260
18703
  opts.cancellation?.register(runId, ownController);
18261
18704
  opts.onRunStart?.(runSnapshot);
@@ -18406,15 +18849,15 @@ async function run(def, inputs, opts = {}) {
18406
18849
  return await finalizers.finalizeParentWorkflowExitCancellation(parentExit);
18407
18850
  return finalizeKilled(runId, runSnapshot, activeStore, opts.persistence, opts.onRunEnd);
18408
18851
  }
18409
- const failure2 = classifyExecutorFailure(err);
18410
- const selectedMetadata2 = normalizeFailureWinnerMetadata(normalizeStageLessFailureMetadata(selectRunFailureDisposition({
18411
- outerFailure: failure2,
18852
+ const failure = classifyExecutorFailure(err);
18853
+ const selectedMetadata = normalizeFailureWinnerMetadata(normalizeStageLessFailureMetadata(selectRunFailureDisposition({
18854
+ outerFailure: failure,
18412
18855
  thrownError: err,
18413
18856
  stages: runSnapshot.stages,
18414
18857
  classifyFailure: classifyExecutorFailure
18415
18858
  }), runSnapshot.stages.length));
18416
- const failedToolNodeId = selectedMetadata2.failedStageId === undefined && selectedMetadata2.failureDisposition !== "terminal_killed" ? catchTerminalEvent?.kind === "failure" && Object.is(catchTerminalEvent.error, err) ? catchTerminalEvent.nodeId ?? observedAdmittedToolFailure?.nodeId : observedAdmittedToolFailure?.nodeId : undefined;
18417
- const metadata = failedToolNodeId === undefined ? selectedMetadata2 : { ...selectedMetadata2, failedToolNodeId };
18859
+ const failedToolNodeId = selectedMetadata.failedStageId === undefined && selectedMetadata.failureDisposition !== "terminal_killed" ? catchTerminalEvent?.kind === "failure" && Object.is(catchTerminalEvent.error, err) ? catchTerminalEvent.nodeId ?? observedAdmittedToolFailure?.nodeId : observedAdmittedToolFailure?.nodeId : undefined;
18860
+ const metadata = failedToolNodeId === undefined ? selectedMetadata : { ...selectedMetadata, failedToolNodeId };
18418
18861
  if (metadata.failureDisposition === "terminal_killed") {
18419
18862
  for (const failedStageId of metadata.failedStageIds)
18420
18863
  scheduler.blockKnownNonTerminalDescendants(failedStageId);
@@ -18443,6 +18886,7 @@ async function run(def, inputs, opts = {}) {
18443
18886
  });
18444
18887
  } finally {
18445
18888
  callerSignal?.removeEventListener("abort", onCallerAbort);
18889
+ workflowObservationRuntime(activeStore).finishRun(runId);
18446
18890
  runtimeSettled.resolve();
18447
18891
  unregisterRunControl();
18448
18892
  try {
@@ -18482,45 +18926,45 @@ var NON_INTERACTIVE_WORKFLOW_POLICY = Object.freeze({
18482
18926
  allowInputPicker: false
18483
18927
  });
18484
18928
  // dist/builtin/workflows/src/workflows/registry.ts
18485
- function makeRegistry(store2) {
18929
+ function makeRegistry(store) {
18486
18930
  return {
18487
18931
  register(definition) {
18488
- const next = new Map(store2);
18932
+ const next = new Map(store);
18489
18933
  next.set(definition.normalizedName, definition);
18490
18934
  return makeRegistry(next);
18491
18935
  },
18492
18936
  merge(other) {
18493
- const next = new Map(store2);
18937
+ const next = new Map(store);
18494
18938
  for (const def of other.all()) {
18495
18939
  next.set(def.normalizedName, def);
18496
18940
  }
18497
18941
  return makeRegistry(next);
18498
18942
  },
18499
18943
  get(name) {
18500
- return store2.get(normalizeWorkflowName(name));
18944
+ return store.get(normalizeWorkflowName(name));
18501
18945
  },
18502
18946
  has(name) {
18503
- return store2.has(normalizeWorkflowName(name));
18947
+ return store.has(normalizeWorkflowName(name));
18504
18948
  },
18505
18949
  remove(name) {
18506
- const key2 = normalizeWorkflowName(name);
18507
- if (!store2.has(key2))
18950
+ const key = normalizeWorkflowName(name);
18951
+ if (!store.has(key))
18508
18952
  return this;
18509
- const next = new Map(store2);
18510
- next.delete(key2);
18953
+ const next = new Map(store);
18954
+ next.delete(key);
18511
18955
  return makeRegistry(next);
18512
18956
  },
18513
18957
  names() {
18514
- return [...store2.keys()];
18958
+ return [...store.keys()];
18515
18959
  },
18516
18960
  all() {
18517
- return [...store2.values()];
18961
+ return [...store.values()];
18518
18962
  }
18519
18963
  };
18520
18964
  }
18521
18965
  function createRegistry(initial = []) {
18522
- const store2 = new Map(initial.map((d) => [d.normalizedName, d]));
18523
- return makeRegistry(store2);
18966
+ const store = new Map(initial.map((d) => [d.normalizedName, d]));
18967
+ return makeRegistry(store);
18524
18968
  }
18525
18969
 
18526
18970
  // dist/builtin/workflows/src/sdk-surface.ts