@bastani/atomic 0.9.37 → 0.9.38-alpha.10

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 (693) hide show
  1. package/CHANGELOG.md +151 -0
  2. package/README.md +8 -6
  3. package/dist/builtin/intercom/CHANGELOG.md +15 -0
  4. package/dist/builtin/intercom/broker/broker.ts +6 -4
  5. package/dist/builtin/intercom/broker/delivered-message-cache.ts +50 -4
  6. package/dist/builtin/intercom/broker/send-handler.ts +6 -4
  7. package/dist/builtin/intercom/index.bundle.mjs +89 -40
  8. package/dist/builtin/intercom/package.json +2 -2
  9. package/dist/builtin/mcp/package.json +1 -1
  10. package/dist/builtin/subagents/CHANGELOG.md +12 -0
  11. package/dist/builtin/subagents/README.md +9 -4
  12. package/dist/builtin/subagents/package.json +3 -3
  13. package/dist/builtin/subagents/src/extension/index.bundle.mjs +163 -158
  14. package/dist/builtin/web-access/CHANGELOG.md +7 -0
  15. package/dist/builtin/web-access/index.bundle.mjs +53 -15
  16. package/dist/builtin/web-access/package.json +2 -2
  17. package/dist/builtin/workflows/CHANGELOG.md +91 -0
  18. package/dist/builtin/workflows/README.md +5 -10
  19. package/dist/builtin/workflows/builtin/adversarial-verification.js +2 -2
  20. package/dist/builtin/workflows/builtin/{chunk-94f8zfz1.js → chunk-454hz1qt.js} +1 -1
  21. package/dist/builtin/workflows/builtin/{chunk-wf876n16.js → chunk-4bwtzyjq.js} +1 -1
  22. package/dist/builtin/workflows/builtin/{chunk-kb7s3gx2.js → chunk-5eh0brtd.js} +1 -1
  23. package/dist/builtin/workflows/builtin/{chunk-nkj4qhj6.js → chunk-85mx6wcf.js} +7 -7
  24. package/dist/builtin/workflows/builtin/{chunk-rhkg3d8e.js → chunk-8kkv04hz.js} +16 -16
  25. package/dist/builtin/workflows/builtin/chunk-8x61e0s7.js +3148 -0
  26. package/dist/builtin/workflows/builtin/{chunk-r97ndfvt.js → chunk-bjva9j5k.js} +1 -1
  27. package/dist/builtin/workflows/builtin/{chunk-a1ar035d.js → chunk-qdd897wm.js} +1 -1
  28. package/dist/builtin/workflows/builtin/{chunk-gyjck9z8.js → chunk-qjqn389g.js} +1 -1
  29. package/dist/builtin/workflows/builtin/{chunk-632fxeb8.js → chunk-x0vvjyzg.js} +1 -1
  30. package/dist/builtin/workflows/builtin/{chunk-3xffzzbg.js → chunk-y45tkftg.js} +11 -18
  31. package/dist/builtin/workflows/builtin/classify-and-act.js +2 -2
  32. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +2 -2
  33. package/dist/builtin/workflows/builtin/generate-and-filter.js +2 -2
  34. package/dist/builtin/workflows/builtin/goal.js +3 -3
  35. package/dist/builtin/workflows/builtin/index.js +11 -11
  36. package/dist/builtin/workflows/builtin/loop-until-done.js +2 -2
  37. package/dist/builtin/workflows/builtin/open-claude-design.js +2 -2
  38. package/dist/builtin/workflows/builtin/ralph.js +3 -3
  39. package/dist/builtin/workflows/builtin/tournament.js +2 -2
  40. package/dist/builtin/workflows/package.json +2 -2
  41. package/dist/builtin/workflows/src/authoring.d.ts +9 -12
  42. package/dist/builtin/workflows/src/durable/journal/conformance.d.ts +12 -0
  43. package/dist/builtin/workflows/src/durable/journal/internal.d.ts +1 -0
  44. package/dist/builtin/workflows/src/durable/journal/lease-expiry.d.ts +2 -0
  45. package/dist/builtin/workflows/src/durable/journal/legacy-journal-tables.d.ts +42 -0
  46. package/dist/builtin/workflows/src/durable/journal/memory-run-journal.d.ts +35 -0
  47. package/dist/builtin/workflows/src/durable/journal/resolution.d.ts +32 -0
  48. package/dist/builtin/workflows/src/durable/journal/sql-run-journal.d.ts +48 -0
  49. package/dist/builtin/workflows/src/durable/journal/sqlite-run-journal.d.ts +7 -0
  50. package/dist/builtin/workflows/src/durable/journal/types.d.ts +95 -0
  51. package/dist/builtin/workflows/src/durable/journal/values.d.ts +5 -0
  52. package/dist/builtin/workflows/src/extension/index.bundle.mjs +29510 -64819
  53. package/dist/builtin/workflows/src/index.js +10767 -45878
  54. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +8 -14
  55. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +4 -20
  56. package/dist/bun/split-loader.js +0 -13
  57. package/dist/bun/split-loader.js.map +1 -1
  58. package/dist/cli/args.d.ts +3 -0
  59. package/dist/cli/args.d.ts.map +1 -1
  60. package/dist/cli/args.js +35 -5
  61. package/dist/cli/args.js.map +1 -1
  62. package/dist/cli/credential-print.d.ts.map +1 -1
  63. package/dist/cli/credential-print.js +4 -4
  64. package/dist/cli/credential-print.js.map +1 -1
  65. package/dist/cli/session-picker.d.ts +2 -2
  66. package/dist/cli/session-picker.d.ts.map +1 -1
  67. package/dist/cli/session-picker.js +5 -5
  68. package/dist/cli/session-picker.js.map +1 -1
  69. package/dist/core/agent-session-auto-compaction.d.ts +1 -1
  70. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  71. package/dist/core/agent-session-auto-compaction.js +2 -2
  72. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  73. package/dist/core/agent-session-bash.d.ts +2 -3
  74. package/dist/core/agent-session-bash.d.ts.map +1 -1
  75. package/dist/core/agent-session-bash.js +18 -10
  76. package/dist/core/agent-session-bash.js.map +1 -1
  77. package/dist/core/agent-session-boundaries.d.ts +6 -6
  78. package/dist/core/agent-session-boundaries.d.ts.map +1 -1
  79. package/dist/core/agent-session-boundaries.js +22 -22
  80. package/dist/core/agent-session-boundaries.js.map +1 -1
  81. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  82. package/dist/core/agent-session-compaction.js +3 -2
  83. package/dist/core/agent-session-compaction.js.map +1 -1
  84. package/dist/core/agent-session-custom-message-commit.d.ts.map +1 -1
  85. package/dist/core/agent-session-custom-message-commit.js +10 -12
  86. package/dist/core/agent-session-custom-message-commit.js.map +1 -1
  87. package/dist/core/agent-session-events.d.ts.map +1 -1
  88. package/dist/core/agent-session-events.js +26 -14
  89. package/dist/core/agent-session-events.js.map +1 -1
  90. package/dist/core/agent-session-export.js +1 -1
  91. package/dist/core/agent-session-export.js.map +1 -1
  92. package/dist/core/agent-session-extension-bindings.d.ts +3 -3
  93. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  94. package/dist/core/agent-session-extension-bindings.js +98 -64
  95. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  96. package/dist/core/agent-session-message-queue.d.ts +2 -2
  97. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  98. package/dist/core/agent-session-message-queue.js +17 -8
  99. package/dist/core/agent-session-message-queue.js.map +1 -1
  100. package/dist/core/agent-session-methods.d.ts +17 -17
  101. package/dist/core/agent-session-methods.d.ts.map +1 -1
  102. package/dist/core/agent-session-methods.js.map +1 -1
  103. package/dist/core/agent-session-models.d.ts +2 -2
  104. package/dist/core/agent-session-models.d.ts.map +1 -1
  105. package/dist/core/agent-session-models.js +59 -42
  106. package/dist/core/agent-session-models.js.map +1 -1
  107. package/dist/core/agent-session-persistent-custom-messages.d.ts +4 -4
  108. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  109. package/dist/core/agent-session-persistent-custom-messages.js +16 -17
  110. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  111. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  112. package/dist/core/agent-session-prompt.js +6 -8
  113. package/dist/core/agent-session-prompt.js.map +1 -1
  114. package/dist/core/agent-session-retry.d.ts.map +1 -1
  115. package/dist/core/agent-session-retry.js +18 -16
  116. package/dist/core/agent-session-retry.js.map +1 -1
  117. package/dist/core/agent-session-runtime.d.ts +7 -8
  118. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  119. package/dist/core/agent-session-runtime.js +88 -100
  120. package/dist/core/agent-session-runtime.js.map +1 -1
  121. package/dist/core/agent-session-services.d.ts +1 -1
  122. package/dist/core/agent-session-services.d.ts.map +1 -1
  123. package/dist/core/agent-session-services.js +2 -2
  124. package/dist/core/agent-session-services.js.map +1 -1
  125. package/dist/core/agent-session-state.d.ts +4 -6
  126. package/dist/core/agent-session-state.d.ts.map +1 -1
  127. package/dist/core/agent-session-state.js +13 -8
  128. package/dist/core/agent-session-state.js.map +1 -1
  129. package/dist/core/agent-session-summary.js +1 -1
  130. package/dist/core/agent-session-summary.js.map +1 -1
  131. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  132. package/dist/core/agent-session-tool-registry.js +3 -1
  133. package/dist/core/agent-session-tool-registry.js.map +1 -1
  134. package/dist/core/agent-session-tree.d.ts +1 -1
  135. package/dist/core/agent-session-tree.d.ts.map +1 -1
  136. package/dist/core/agent-session-tree.js +8 -7
  137. package/dist/core/agent-session-tree.js.map +1 -1
  138. package/dist/core/agent-session-types.d.ts +2 -0
  139. package/dist/core/agent-session-types.d.ts.map +1 -1
  140. package/dist/core/agent-session-types.js.map +1 -1
  141. package/dist/core/agent-session.js +1 -1
  142. package/dist/core/agent-session.js.map +1 -1
  143. package/dist/core/auth-storage-backends.d.ts +2 -0
  144. package/dist/core/auth-storage-backends.d.ts.map +1 -1
  145. package/dist/core/auth-storage-backends.js +12 -0
  146. package/dist/core/auth-storage-backends.js.map +1 -1
  147. package/dist/core/auth-storage.d.ts +5 -0
  148. package/dist/core/auth-storage.d.ts.map +1 -1
  149. package/dist/core/auth-storage.js +46 -12
  150. package/dist/core/auth-storage.js.map +1 -1
  151. package/dist/core/cache-warmer.js +1 -1
  152. package/dist/core/cache-warmer.js.map +1 -1
  153. package/dist/core/compaction/branch-summarization.d.ts +3 -5
  154. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  155. package/dist/core/compaction/branch-summarization.js +6 -10
  156. package/dist/core/compaction/branch-summarization.js.map +1 -1
  157. package/dist/core/compaction/compaction-runner.d.ts +1 -0
  158. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  159. package/dist/core/compaction/compaction-runner.js +4 -1
  160. package/dist/core/compaction/compaction-runner.js.map +1 -1
  161. package/dist/core/compaction/pi-summary-fallback.d.ts +2 -1
  162. package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -1
  163. package/dist/core/compaction/pi-summary-fallback.js +6 -8
  164. package/dist/core/compaction/pi-summary-fallback.js.map +1 -1
  165. package/dist/core/compaction/utils.d.ts +2 -1
  166. package/dist/core/compaction/utils.d.ts.map +1 -1
  167. package/dist/core/compaction/utils.js +32 -7
  168. package/dist/core/compaction/utils.js.map +1 -1
  169. package/dist/core/export-html/index.js +1 -1
  170. package/dist/core/export-html/index.js.map +1 -1
  171. package/dist/core/export-html/template-js/entries-navigation.js +1 -1
  172. package/dist/core/export-html/template-js/message-tools.js +20 -7
  173. package/dist/core/export-html/template-js/tree-filter-render.js +1 -9
  174. package/dist/core/export-html/template.js +22 -17
  175. package/dist/core/extensions/api-types.d.ts +12 -12
  176. package/dist/core/extensions/api-types.d.ts.map +1 -1
  177. package/dist/core/extensions/api-types.js.map +1 -1
  178. package/dist/core/extensions/context-types.d.ts +4 -2
  179. package/dist/core/extensions/context-types.d.ts.map +1 -1
  180. package/dist/core/extensions/context-types.js.map +1 -1
  181. package/dist/core/extensions/extension-work.d.ts +1 -0
  182. package/dist/core/extensions/extension-work.d.ts.map +1 -1
  183. package/dist/core/extensions/extension-work.js +5 -1
  184. package/dist/core/extensions/extension-work.js.map +1 -1
  185. package/dist/core/extensions/index.d.ts +1 -1
  186. package/dist/core/extensions/index.d.ts.map +1 -1
  187. package/dist/core/extensions/index.js +1 -1
  188. package/dist/core/extensions/index.js.map +1 -1
  189. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  190. package/dist/core/extensions/loader-api.js +40 -42
  191. package/dist/core/extensions/loader-api.js.map +1 -1
  192. package/dist/core/extensions/loader-host-modules.d.ts +1 -1
  193. package/dist/core/extensions/loader-host-modules.d.ts.map +1 -1
  194. package/dist/core/extensions/loader-host-modules.js +6 -2
  195. package/dist/core/extensions/loader-host-modules.js.map +1 -1
  196. package/dist/core/extensions/loader-rollback.d.ts.map +1 -1
  197. package/dist/core/extensions/loader-rollback.js +1 -0
  198. package/dist/core/extensions/loader-rollback.js.map +1 -1
  199. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  200. package/dist/core/extensions/loader-virtual-modules.js +1 -0
  201. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  202. package/dist/core/extensions/runner-context.d.ts +1 -0
  203. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  204. package/dist/core/extensions/runner-context.js +10 -3
  205. package/dist/core/extensions/runner-context.js.map +1 -1
  206. package/dist/core/extensions/runner-handlers.d.ts +1 -1
  207. package/dist/core/extensions/runner-handlers.d.ts.map +1 -1
  208. package/dist/core/extensions/runner-handlers.js.map +1 -1
  209. package/dist/core/extensions/runner.d.ts +5 -2
  210. package/dist/core/extensions/runner.d.ts.map +1 -1
  211. package/dist/core/extensions/runner.js +28 -12
  212. package/dist/core/extensions/runner.js.map +1 -1
  213. package/dist/core/extensions/runtime-types.d.ts +7 -7
  214. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  215. package/dist/core/extensions/runtime-types.js.map +1 -1
  216. package/dist/core/extensions/session-events.d.ts +5 -5
  217. package/dist/core/extensions/session-events.d.ts.map +1 -1
  218. package/dist/core/extensions/session-events.js.map +1 -1
  219. package/dist/core/extensions/workflow-events.d.ts +2 -0
  220. package/dist/core/extensions/workflow-events.d.ts.map +1 -1
  221. package/dist/core/extensions/workflow-events.js.map +1 -1
  222. package/dist/core/extensions/workflow-run-control.d.ts +3 -3
  223. package/dist/core/extensions/workflow-run-control.d.ts.map +1 -1
  224. package/dist/core/extensions/workflow-run-control.js +4 -4
  225. package/dist/core/extensions/workflow-run-control.js.map +1 -1
  226. package/dist/core/fast-model-routing.d.ts.map +1 -1
  227. package/dist/core/fast-model-routing.js +1 -0
  228. package/dist/core/fast-model-routing.js.map +1 -1
  229. package/dist/core/intercom-runtime-group.js +1 -1
  230. package/dist/core/intercom-runtime-group.js.map +1 -1
  231. package/dist/core/model-config.d.ts +774 -9
  232. package/dist/core/model-config.d.ts.map +1 -1
  233. package/dist/core/model-config.js +46 -24
  234. package/dist/core/model-config.js.map +1 -1
  235. package/dist/core/model-fallback-failures.d.ts.map +1 -1
  236. package/dist/core/model-fallback-failures.js +3 -1
  237. package/dist/core/model-fallback-failures.js.map +1 -1
  238. package/dist/core/model-resolver-cli.d.ts +2 -0
  239. package/dist/core/model-resolver-cli.d.ts.map +1 -1
  240. package/dist/core/model-resolver-cli.js +47 -143
  241. package/dist/core/model-resolver-cli.js.map +1 -1
  242. package/dist/core/model-resolver-defaults.js +5 -5
  243. package/dist/core/model-resolver-defaults.js.map +1 -1
  244. package/dist/core/model-resolver-patterns.d.ts +48 -22
  245. package/dist/core/model-resolver-patterns.d.ts.map +1 -1
  246. package/dist/core/model-resolver-patterns.js +154 -105
  247. package/dist/core/model-resolver-patterns.js.map +1 -1
  248. package/dist/core/model-resolver-scope.d.ts +6 -9
  249. package/dist/core/model-resolver-scope.d.ts.map +1 -1
  250. package/dist/core/model-resolver-scope.js +51 -53
  251. package/dist/core/model-resolver-scope.js.map +1 -1
  252. package/dist/core/model-resolver-types.d.ts +0 -6
  253. package/dist/core/model-resolver-types.d.ts.map +1 -1
  254. package/dist/core/model-resolver-types.js.map +1 -1
  255. package/dist/core/model-resolver.d.ts +3 -2
  256. package/dist/core/model-resolver.d.ts.map +1 -1
  257. package/dist/core/model-resolver.js +1 -1
  258. package/dist/core/model-resolver.js.map +1 -1
  259. package/dist/core/model-runtime-streaming.d.ts +9 -2
  260. package/dist/core/model-runtime-streaming.d.ts.map +1 -1
  261. package/dist/core/model-runtime-streaming.js +121 -10
  262. package/dist/core/model-runtime-streaming.js.map +1 -1
  263. package/dist/core/model-runtime.d.ts +6 -0
  264. package/dist/core/model-runtime.d.ts.map +1 -1
  265. package/dist/core/model-runtime.js +103 -2
  266. package/dist/core/model-runtime.js.map +1 -1
  267. package/dist/core/prompt-templates.d.ts.map +1 -1
  268. package/dist/core/prompt-templates.js +6 -2
  269. package/dist/core/prompt-templates.js.map +1 -1
  270. package/dist/core/provider-attribution.js +1 -1
  271. package/dist/core/provider-attribution.js.map +1 -1
  272. package/dist/core/resource-loader-reload.js +1 -1
  273. package/dist/core/resource-loader-reload.js.map +1 -1
  274. package/dist/core/resource-loader-types.d.ts +1 -1
  275. package/dist/core/resource-loader-types.d.ts.map +1 -1
  276. package/dist/core/resource-loader-types.js.map +1 -1
  277. package/dist/core/retry-policy.d.ts +5 -2
  278. package/dist/core/retry-policy.d.ts.map +1 -1
  279. package/dist/core/retry-policy.js +4 -3
  280. package/dist/core/retry-policy.js.map +1 -1
  281. package/dist/core/runtime-credentials.d.ts +1 -0
  282. package/dist/core/runtime-credentials.d.ts.map +1 -1
  283. package/dist/core/runtime-credentials.js +3 -0
  284. package/dist/core/runtime-credentials.js.map +1 -1
  285. package/dist/core/sdk-types.d.ts +4 -0
  286. package/dist/core/sdk-types.d.ts.map +1 -1
  287. package/dist/core/sdk-types.js.map +1 -1
  288. package/dist/core/sdk.d.ts +1 -1
  289. package/dist/core/sdk.d.ts.map +1 -1
  290. package/dist/core/sdk.js +145 -94
  291. package/dist/core/sdk.js.map +1 -1
  292. package/dist/core/session-lifecycle-work.d.ts +3 -0
  293. package/dist/core/session-lifecycle-work.d.ts.map +1 -1
  294. package/dist/core/session-lifecycle-work.js +2 -0
  295. package/dist/core/session-lifecycle-work.js.map +1 -1
  296. package/dist/core/session-manager-archive.d.ts +2 -16
  297. package/dist/core/session-manager-archive.d.ts.map +1 -1
  298. package/dist/core/session-manager-archive.js +8 -109
  299. package/dist/core/session-manager-archive.js.map +1 -1
  300. package/dist/core/session-manager-core.d.ts +53 -51
  301. package/dist/core/session-manager-core.d.ts.map +1 -1
  302. package/dist/core/session-manager-core.js +549 -315
  303. package/dist/core/session-manager-core.js.map +1 -1
  304. package/dist/core/session-manager-entries.d.ts.map +1 -1
  305. package/dist/core/session-manager-entries.js +5 -10
  306. package/dist/core/session-manager-entries.js.map +1 -1
  307. package/dist/core/session-manager-errors.d.ts +10 -0
  308. package/dist/core/session-manager-errors.d.ts.map +1 -0
  309. package/dist/core/session-manager-errors.js +27 -0
  310. package/dist/core/session-manager-errors.js.map +1 -0
  311. package/dist/core/session-manager-list.d.ts +1 -0
  312. package/dist/core/session-manager-list.d.ts.map +1 -1
  313. package/dist/core/session-manager-list.js +23 -25
  314. package/dist/core/session-manager-list.js.map +1 -1
  315. package/dist/core/session-manager-storage.d.ts +3 -12
  316. package/dist/core/session-manager-storage.d.ts.map +1 -1
  317. package/dist/core/session-manager-storage.js +60 -77
  318. package/dist/core/session-manager-storage.js.map +1 -1
  319. package/dist/core/session-manager-types.d.ts +4 -12
  320. package/dist/core/session-manager-types.d.ts.map +1 -1
  321. package/dist/core/session-manager-types.js +2 -1
  322. package/dist/core/session-manager-types.js.map +1 -1
  323. package/dist/core/session-manager-validation.d.ts +3 -0
  324. package/dist/core/session-manager-validation.d.ts.map +1 -1
  325. package/dist/core/session-manager-validation.js +18 -1
  326. package/dist/core/session-manager-validation.js.map +1 -1
  327. package/dist/core/session-manager.d.ts +3 -3
  328. package/dist/core/session-manager.d.ts.map +1 -1
  329. package/dist/core/session-manager.js +3 -3
  330. package/dist/core/session-manager.js.map +1 -1
  331. package/dist/core/session-mutation-queue.d.ts +3 -0
  332. package/dist/core/session-mutation-queue.d.ts.map +1 -0
  333. package/dist/core/session-mutation-queue.js +14 -0
  334. package/dist/core/session-mutation-queue.js.map +1 -0
  335. package/dist/core/session-resume-args.d.ts +4 -0
  336. package/dist/core/session-resume-args.d.ts.map +1 -0
  337. package/dist/core/session-resume-args.js +9 -0
  338. package/dist/core/session-resume-args.js.map +1 -0
  339. package/dist/core/session-storage.d.ts +26 -0
  340. package/dist/core/session-storage.d.ts.map +1 -0
  341. package/dist/core/session-storage.js +171 -0
  342. package/dist/core/session-storage.js.map +1 -0
  343. package/dist/core/session-store-list.d.ts +4 -0
  344. package/dist/core/session-store-list.d.ts.map +1 -0
  345. package/dist/core/session-store-list.js +28 -0
  346. package/dist/core/session-store-list.js.map +1 -0
  347. package/dist/core/settings-manager-basic-accessors.d.ts +1 -1
  348. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  349. package/dist/core/settings-manager-basic-accessors.js +1 -5
  350. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  351. package/dist/core/settings-merge.d.ts.map +1 -1
  352. package/dist/core/settings-merge.js +8 -2
  353. package/dist/core/settings-merge.js.map +1 -1
  354. package/dist/core/settings-schema.d.ts +76 -6
  355. package/dist/core/settings-schema.d.ts.map +1 -1
  356. package/dist/core/settings-schema.js +29 -20
  357. package/dist/core/settings-schema.js.map +1 -1
  358. package/dist/core/storage/database.d.ts +21 -0
  359. package/dist/core/storage/database.d.ts.map +1 -0
  360. package/dist/core/storage/database.js +2 -0
  361. package/dist/core/storage/database.js.map +1 -0
  362. package/dist/core/storage/errors.d.ts +64 -0
  363. package/dist/core/storage/errors.d.ts.map +1 -0
  364. package/dist/core/storage/errors.js +103 -0
  365. package/dist/core/storage/errors.js.map +1 -0
  366. package/dist/core/storage/index.d.ts +10 -0
  367. package/dist/core/storage/index.d.ts.map +1 -0
  368. package/dist/core/storage/index.js +8 -0
  369. package/dist/core/storage/index.js.map +1 -0
  370. package/dist/core/storage/node-sqlite.d.ts +7 -0
  371. package/dist/core/storage/node-sqlite.d.ts.map +1 -0
  372. package/dist/core/storage/node-sqlite.js +202 -0
  373. package/dist/core/storage/node-sqlite.js.map +1 -0
  374. package/dist/core/storage/prefix.d.ts +5 -0
  375. package/dist/core/storage/prefix.d.ts.map +1 -0
  376. package/dist/core/storage/prefix.js +15 -0
  377. package/dist/core/storage/prefix.js.map +1 -0
  378. package/dist/core/storage/provider.d.ts +58 -0
  379. package/dist/core/storage/provider.d.ts.map +1 -0
  380. package/dist/core/storage/provider.js +243 -0
  381. package/dist/core/storage/provider.js.map +1 -0
  382. package/dist/core/storage/run-journal.d.ts +93 -0
  383. package/dist/core/storage/run-journal.d.ts.map +1 -0
  384. package/dist/core/storage/run-journal.js +15 -0
  385. package/dist/core/storage/run-journal.js.map +1 -0
  386. package/dist/core/storage/schema.d.ts +3 -0
  387. package/dist/core/storage/schema.d.ts.map +1 -0
  388. package/dist/core/storage/schema.js +6 -0
  389. package/dist/core/storage/schema.js.map +1 -0
  390. package/dist/core/storage/selection.d.ts +16 -0
  391. package/dist/core/storage/selection.d.ts.map +1 -0
  392. package/dist/core/storage/selection.js +87 -0
  393. package/dist/core/storage/selection.js.map +1 -0
  394. package/dist/core/storage/session/conformance.d.ts +12 -0
  395. package/dist/core/storage/session/conformance.d.ts.map +1 -0
  396. package/dist/core/storage/session/conformance.js +674 -0
  397. package/dist/core/storage/session/conformance.js.map +1 -0
  398. package/dist/core/storage/session/entry-structure.d.ts +4 -0
  399. package/dist/core/storage/session/entry-structure.d.ts.map +1 -0
  400. package/dist/core/storage/session/entry-structure.js +83 -0
  401. package/dist/core/storage/session/entry-structure.js.map +1 -0
  402. package/dist/core/storage/session/errors.d.ts +54 -0
  403. package/dist/core/storage/session/errors.d.ts.map +1 -0
  404. package/dist/core/storage/session/errors.js +95 -0
  405. package/dist/core/storage/session/errors.js.map +1 -0
  406. package/dist/core/storage/session/jsonl-session-store.d.ts +72 -0
  407. package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -0
  408. package/dist/core/storage/session/jsonl-session-store.js +564 -0
  409. package/dist/core/storage/session/jsonl-session-store.js.map +1 -0
  410. package/dist/core/storage/session/legacy-format.d.ts +20 -0
  411. package/dist/core/storage/session/legacy-format.d.ts.map +1 -0
  412. package/dist/core/storage/session/legacy-format.js +89 -0
  413. package/dist/core/storage/session/legacy-format.js.map +1 -0
  414. package/dist/core/storage/session/legacy-session-store.d.ts +63 -0
  415. package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -0
  416. package/dist/core/storage/session/legacy-session-store.js +239 -0
  417. package/dist/core/storage/session/legacy-session-store.js.map +1 -0
  418. package/dist/core/storage/session/legacy-session-summary.d.ts +11 -0
  419. package/dist/core/storage/session/legacy-session-summary.d.ts.map +1 -0
  420. package/dist/core/storage/session/legacy-session-summary.js +103 -0
  421. package/dist/core/storage/session/legacy-session-summary.js.map +1 -0
  422. package/dist/core/storage/session/memory-session-store.d.ts +33 -0
  423. package/dist/core/storage/session/memory-session-store.d.ts.map +1 -0
  424. package/dist/core/storage/session/memory-session-store.js +120 -0
  425. package/dist/core/storage/session/memory-session-store.js.map +1 -0
  426. package/dist/core/storage/session/scratch-directory.d.ts +2 -0
  427. package/dist/core/storage/session/scratch-directory.d.ts.map +1 -0
  428. package/dist/core/storage/session/scratch-directory.js +5 -0
  429. package/dist/core/storage/session/scratch-directory.js.map +1 -0
  430. package/dist/core/storage/session/session-summary.d.ts +24 -0
  431. package/dist/core/storage/session/session-summary.d.ts.map +1 -0
  432. package/dist/core/storage/session/session-summary.js +79 -0
  433. package/dist/core/storage/session/session-summary.js.map +1 -0
  434. package/dist/core/storage/session/sql-session-store.d.ts +49 -0
  435. package/dist/core/storage/session/sql-session-store.d.ts.map +1 -0
  436. package/dist/core/storage/session/sql-session-store.js +246 -0
  437. package/dist/core/storage/session/sql-session-store.js.map +1 -0
  438. package/dist/core/storage/session/types.d.ts +72 -0
  439. package/dist/core/storage/session/types.d.ts.map +1 -0
  440. package/dist/core/storage/session/types.js +2 -0
  441. package/dist/core/storage/session/types.js.map +1 -0
  442. package/dist/core/storage/session/validation.d.ts +7 -0
  443. package/dist/core/storage/session/validation.d.ts.map +1 -0
  444. package/dist/core/storage/session/validation.js +47 -0
  445. package/dist/core/storage/session/validation.js.map +1 -0
  446. package/dist/core/storage/testing.d.ts +15 -0
  447. package/dist/core/storage/testing.d.ts.map +1 -0
  448. package/dist/core/storage/testing.js +309 -0
  449. package/dist/core/storage/testing.js.map +1 -0
  450. package/dist/core/tasks/completion.d.ts.map +1 -1
  451. package/dist/core/tasks/completion.js +2 -4
  452. package/dist/core/tasks/completion.js.map +1 -1
  453. package/dist/core/tools/bash-session-environment.d.ts.map +1 -1
  454. package/dist/core/tools/bash-session-environment.js +0 -2
  455. package/dist/core/tools/bash-session-environment.js.map +1 -1
  456. package/dist/core/tools/malformed-tool-arguments.d.ts +3 -0
  457. package/dist/core/tools/malformed-tool-arguments.d.ts.map +1 -0
  458. package/dist/core/tools/malformed-tool-arguments.js +23 -0
  459. package/dist/core/tools/malformed-tool-arguments.js.map +1 -0
  460. package/dist/core/tools/read-url.d.ts.map +1 -1
  461. package/dist/core/tools/read-url.js +6 -1
  462. package/dist/core/tools/read-url.js.map +1 -1
  463. package/dist/core/tools/render-utils.d.ts +2 -0
  464. package/dist/core/tools/render-utils.d.ts.map +1 -1
  465. package/dist/core/tools/render-utils.js +19 -0
  466. package/dist/core/tools/render-utils.js.map +1 -1
  467. package/dist/core/tools/todos-model.js +3 -3
  468. package/dist/core/tools/todos-model.js.map +1 -1
  469. package/dist/core/tools/todos-mutations.js +2 -2
  470. package/dist/core/tools/todos-mutations.js.map +1 -1
  471. package/dist/core/tools/todos-render.js +1 -1
  472. package/dist/core/tools/todos-render.js.map +1 -1
  473. package/dist/core/tools/todos-storage.js +2 -2
  474. package/dist/core/tools/todos-storage.js.map +1 -1
  475. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  476. package/dist/extensions/codemode/execute.js +14 -1
  477. package/dist/extensions/codemode/execute.js.map +1 -1
  478. package/dist/extensions/codemode/tool.d.ts +1 -1
  479. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  480. package/dist/extensions/codemode/tool.js.map +1 -1
  481. package/dist/extensions/herdr/index.d.ts.map +1 -1
  482. package/dist/extensions/herdr/index.js +6 -8
  483. package/dist/extensions/herdr/index.js.map +1 -1
  484. package/dist/extensions/mcp/index.js +1 -1
  485. package/dist/extensions/mcp/index.js.map +1 -1
  486. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  487. package/dist/extensions/mcp/tools.js +6 -1
  488. package/dist/extensions/mcp/tools.js.map +1 -1
  489. package/dist/index-extensions.d.ts +1 -1
  490. package/dist/index-extensions.d.ts.map +1 -1
  491. package/dist/index-extensions.js +1 -1
  492. package/dist/index-extensions.js.map +1 -1
  493. package/dist/index.d.ts +5 -2
  494. package/dist/index.d.ts.map +1 -1
  495. package/dist/index.js +5 -2
  496. package/dist/index.js.map +1 -1
  497. package/dist/main-session-options.d.ts.map +1 -1
  498. package/dist/main-session-options.js +1 -0
  499. package/dist/main-session-options.js.map +1 -1
  500. package/dist/main-session.d.ts +12 -2
  501. package/dist/main-session.d.ts.map +1 -1
  502. package/dist/main-session.js +151 -53
  503. package/dist/main-session.js.map +1 -1
  504. package/dist/main.d.ts.map +1 -1
  505. package/dist/main.js +97 -42
  506. package/dist/main.js.map +1 -1
  507. package/dist/modes/interactive/components/chat-session-host.d.ts +3 -1
  508. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  509. package/dist/modes/interactive/components/chat-session-host.js +18 -5
  510. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  511. package/dist/modes/interactive/components/extension-input.d.ts +1 -1
  512. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  513. package/dist/modes/interactive/components/extension-input.js +2 -2
  514. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  515. package/dist/modes/interactive/components/host-session-picker.js +1 -1
  516. package/dist/modes/interactive/components/host-session-picker.js.map +1 -1
  517. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  518. package/dist/modes/interactive/components/scoped-models-selector.js +9 -5
  519. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  520. package/dist/modes/interactive/components/session-selector-delete.d.ts +1 -1
  521. package/dist/modes/interactive/components/session-selector-delete.d.ts.map +1 -1
  522. package/dist/modes/interactive/components/session-selector-delete.js.map +1 -1
  523. package/dist/modes/interactive/components/session-selector-list.d.ts +12 -9
  524. package/dist/modes/interactive/components/session-selector-list.d.ts.map +1 -1
  525. package/dist/modes/interactive/components/session-selector-list.js +27 -25
  526. package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
  527. package/dist/modes/interactive/components/session-selector.d.ts +8 -4
  528. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  529. package/dist/modes/interactive/components/session-selector.js +31 -21
  530. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  531. package/dist/modes/interactive/components/tree-selector-component.d.ts +5 -1
  532. package/dist/modes/interactive/components/tree-selector-component.d.ts.map +1 -1
  533. package/dist/modes/interactive/components/tree-selector-component.js +20 -3
  534. package/dist/modes/interactive/components/tree-selector-component.js.map +1 -1
  535. package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
  536. package/dist/modes/interactive/components/tree-selector-content.js +2 -9
  537. package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
  538. package/dist/modes/interactive/interactive-bash-compact.js +1 -1
  539. package/dist/modes/interactive/interactive-bash-compact.js.map +1 -1
  540. package/dist/modes/interactive/interactive-deferred-startup.js +2 -2
  541. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  542. package/dist/modes/interactive/interactive-editor-actions.js +2 -2
  543. package/dist/modes/interactive/interactive-editor-actions.js.map +1 -1
  544. package/dist/modes/interactive/interactive-extension-runtime.js +2 -0
  545. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  546. package/dist/modes/interactive/interactive-input-handling.js +6 -4
  547. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  548. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  549. package/dist/modes/interactive/interactive-mode-base.js +2 -1
  550. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  551. package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
  552. package/dist/modes/interactive/interactive-mode-helpers.js +7 -3
  553. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  554. package/dist/modes/interactive/interactive-mode-surface.d.ts +5 -5
  555. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  556. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  557. package/dist/modes/interactive/interactive-model-routing.js +12 -7
  558. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  559. package/dist/modes/interactive/interactive-queueing.js +8 -5
  560. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  561. package/dist/modes/interactive/interactive-selectors.js +2 -2
  562. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  563. package/dist/modes/interactive/interactive-session-routing.js +38 -14
  564. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  565. package/dist/modes/interactive/interactive-session-runtime.js +6 -0
  566. package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
  567. package/dist/modes/interactive/interactive-slash-commands.js +5 -3
  568. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  569. package/dist/modes/interactive/interactive-tui.d.ts +1 -0
  570. package/dist/modes/interactive/interactive-tui.d.ts.map +1 -1
  571. package/dist/modes/interactive/interactive-tui.js +9 -2
  572. package/dist/modes/interactive/interactive-tui.js.map +1 -1
  573. package/dist/modes/interactive/program-status-reporter.d.ts +4 -0
  574. package/dist/modes/interactive/program-status-reporter.d.ts.map +1 -1
  575. package/dist/modes/interactive/program-status-reporter.js +45 -6
  576. package/dist/modes/interactive/program-status-reporter.js.map +1 -1
  577. package/dist/modes/interactive-engine/create-isolated-runtime.d.ts.map +1 -1
  578. package/dist/modes/interactive-engine/create-isolated-runtime.js +8 -1
  579. package/dist/modes/interactive-engine/create-isolated-runtime.js.map +1 -1
  580. package/dist/modes/interactive-engine/engine-args.d.ts.map +1 -1
  581. package/dist/modes/interactive-engine/engine-args.js +11 -4
  582. package/dist/modes/interactive-engine/engine-args.js.map +1 -1
  583. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts +2 -1
  584. package/dist/modes/interactive-engine/extension-ui-bridge.d.ts.map +1 -1
  585. package/dist/modes/interactive-engine/extension-ui-bridge.js +9 -1
  586. package/dist/modes/interactive-engine/extension-ui-bridge.js.map +1 -1
  587. package/dist/modes/interactive-engine/isolated-runtime.d.ts +1 -1
  588. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  589. package/dist/modes/interactive-engine/isolated-runtime.js +99 -74
  590. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  591. package/dist/modes/interactive-engine/protocol.d.ts +4 -0
  592. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  593. package/dist/modes/interactive-engine/protocol.js +39 -1
  594. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  595. package/dist/modes/rpc/rpc-bash-request-owners.js +1 -1
  596. package/dist/modes/rpc/rpc-bash-request-owners.js.map +1 -1
  597. package/dist/modes/rpc/rpc-client-api.d.ts +1 -1
  598. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  599. package/dist/modes/rpc/rpc-client-api.js +2 -2
  600. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  601. package/dist/modes/rpc/rpc-client-process.d.ts +2 -2
  602. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  603. package/dist/modes/rpc/rpc-client-process.js +20 -7
  604. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  605. package/dist/modes/rpc/rpc-client.d.ts +4 -1
  606. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  607. package/dist/modes/rpc/rpc-client.js +6 -2
  608. package/dist/modes/rpc/rpc-client.js.map +1 -1
  609. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  610. package/dist/modes/rpc/rpc-command-handler.js +12 -9
  611. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  612. package/dist/modes/rpc/rpc-provider-auth.js +2 -2
  613. package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
  614. package/dist/modes/rpc/rpc-session-binding.d.ts.map +1 -1
  615. package/dist/modes/rpc/rpc-session-binding.js +10 -0
  616. package/dist/modes/rpc/rpc-session-binding.js.map +1 -1
  617. package/dist/modes/rpc/rpc-terminal-drain.d.ts.map +1 -1
  618. package/dist/modes/rpc/rpc-terminal-drain.js +11 -2
  619. package/dist/modes/rpc/rpc-terminal-drain.js.map +1 -1
  620. package/dist/modes/rpc/rpc-types.d.ts +6 -2
  621. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  622. package/dist/modes/rpc/rpc-types.js.map +1 -1
  623. package/dist/utils/canonical-path.d.ts +5 -0
  624. package/dist/utils/canonical-path.d.ts.map +1 -0
  625. package/dist/utils/canonical-path.js +26 -0
  626. package/dist/utils/canonical-path.js.map +1 -0
  627. package/dist/utils/paths.d.ts +1 -7
  628. package/dist/utils/paths.d.ts.map +1 -1
  629. package/dist/utils/paths.js +1 -15
  630. package/dist/utils/paths.js.map +1 -1
  631. package/docs/codemode.md +2 -0
  632. package/docs/compaction.md +2 -2
  633. package/docs/custom-provider/oauth.md +2 -2
  634. package/docs/custom-provider/override.md +3 -3
  635. package/docs/custom-provider/registration.md +7 -7
  636. package/docs/custom-provider/streaming.md +1 -1
  637. package/docs/custom-provider.md +5 -5
  638. package/docs/docs.json +6 -0
  639. package/docs/environment-variables.md +10 -2
  640. package/docs/extensions/api-reference.md +40 -19
  641. package/docs/extensions/authoring.md +1 -1
  642. package/docs/extensions/events.md +12 -8
  643. package/docs/extensions/ui.md +10 -0
  644. package/docs/extensions.md +2 -2
  645. package/docs/getting-started/installation.md +2 -4
  646. package/docs/json.md +1 -1
  647. package/docs/llama-cpp.md +95 -0
  648. package/docs/models/reference.md +9 -0
  649. package/docs/models-configuration.md +206 -0
  650. package/docs/models.md +11 -1
  651. package/docs/packages/authoring.md +1 -1
  652. package/docs/prompt-templates.md +2 -0
  653. package/docs/providers.md +13 -5
  654. package/docs/quickstart.md +2 -1
  655. package/docs/reference/cli.md +10 -6
  656. package/docs/rpc/protocol.md +10 -4
  657. package/docs/sdk/reference.md +16 -14
  658. package/docs/sdk/web-server.md +6 -7
  659. package/docs/sdk.md +67 -27
  660. package/docs/session-format.md +35 -34
  661. package/docs/sessions.md +56 -17
  662. package/docs/settings.md +38 -25
  663. package/docs/storage.md +387 -0
  664. package/docs/subagents.md +19 -6
  665. package/docs/tools.md +2 -0
  666. package/docs/usage.md +3 -2
  667. package/docs/workflows/api-reference.md +88 -60
  668. package/docs/workflows/authoring.md +2 -1
  669. package/docs/workflows/operations.md +32 -174
  670. package/docs/workflows/reliable-design.md +17 -17
  671. package/examples/extensions/bookmark.ts +2 -2
  672. package/examples/extensions/handoff.ts +2 -2
  673. package/examples/extensions/minimal-mode.ts +1 -8
  674. package/examples/extensions/plan-mode/index.ts +15 -13
  675. package/examples/extensions/preset.ts +8 -8
  676. package/examples/extensions/session-name.ts +1 -1
  677. package/examples/extensions/snake.ts +3 -1
  678. package/examples/extensions/space-invaders.ts +3 -1
  679. package/examples/extensions/subagent/display.ts +4 -6
  680. package/examples/extensions/tic-tac-toe.ts +80 -80
  681. package/examples/sdk/11-sessions.ts +5 -5
  682. package/examples/sdk/13-session-runtime.ts +7 -7
  683. package/examples/sdk/README.md +1 -1
  684. package/npm-shrinkwrap.json +53 -469
  685. package/package.json +17 -9
  686. package/schemas/models.schema.json +67 -34
  687. package/schemas/settings.schema.json +138 -27
  688. package/dist/builtin/workflows/builtin/chunk-7fvrnzhb.js +0 -8
  689. package/dist/builtin/workflows/builtin/chunk-8c3ae7tt.js +0 -11609
  690. package/dist/core/session-manager-migrations.d.ts +0 -11
  691. package/dist/core/session-manager-migrations.d.ts.map +0 -1
  692. package/dist/core/session-manager-migrations.js +0 -80
  693. package/dist/core/session-manager-migrations.js.map +0 -1
@@ -0,0 +1,3148 @@
1
+ import {
2
+ VERIFICATION_SCALE
3
+ } from "./chunk-n1910xc4.js";
4
+ import {
5
+ DEFAULT_RISE_DELTA,
6
+ DEFAULT_FALL_DELTA,
7
+ classify_trend
8
+ } from "./chunk-z0d03ktm.js";
9
+ import {
10
+ scoring_prompt_reads,
11
+ build_scoring_prompt
12
+ } from "./chunk-2377r57g.js";
13
+
14
+ // dist/builtin/workflows/src/shared/workflow-artifacts.ts
15
+ import { randomUUID as randomUUID2 } from "node:crypto";
16
+ import { mkdir, readdir, rm, stat } from "node:fs/promises";
17
+ import { dirname, join } from "node:path";
18
+ import { getAgentDir, getEnvValue } from "@bastani/atomic";
19
+
20
+ // dist/builtin/workflows/src/shared/run-id.ts
21
+ var RUN_ID_LENGTH = 36;
22
+ var RUN_ID_PREFIX_LENGTH = 8;
23
+ var RUN_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
24
+ var RUN_ID_PREFIX_PATTERN = /^[0-9a-f]{8}$/i;
25
+ function isFullRunId(value) {
26
+ return RUN_ID_PATTERN.test(value);
27
+ }
28
+ function isRunIdPrefix(value) {
29
+ return RUN_ID_PREFIX_PATTERN.test(value);
30
+ }
31
+ function resolveRunIdTarget(target, runIds) {
32
+ const ids = [...new Set(runIds)];
33
+ if (isFullRunId(target)) {
34
+ const exact = ids.find((id) => id === target);
35
+ return exact === undefined ? { kind: "not_found" } : { kind: "exact", runId: exact };
36
+ }
37
+ if (!isRunIdPrefix(target))
38
+ return { kind: "malformed", message: malformedRunIdMessage(target) };
39
+ const normalized = target.toLowerCase();
40
+ const matches = ids.filter((id) => isFullRunId(id) && id.toLowerCase().startsWith(normalized));
41
+ if (matches.length === 0)
42
+ return { kind: "not_found" };
43
+ if (matches.length === 1)
44
+ return { kind: "unique_prefix", runId: matches[0] };
45
+ return { kind: "ambiguous", matches, message: ambiguousRunIdMessage(target, matches) };
46
+ }
47
+ function ambiguousRunIdMessage(target, matches) {
48
+ return `Run id prefix "${target}" is ambiguous; matches: ${matches.join(", ")}. Use the full UUID.`;
49
+ }
50
+ function malformedRunIdMessage(target) {
51
+ return `Run id must be a full ${RUN_ID_LENGTH}-character UUID or a unique ${RUN_ID_PREFIX_LENGTH}-character hexadecimal prefix; got "${target}" (${target.length} chars).`;
52
+ }
53
+
54
+ // dist/builtin/workflows/src/shared/workflow-run-ownership.ts
55
+ function authoritativeWorkflowChildRunId(stage) {
56
+ if (stage === undefined || stage.status === "failed" || stage.status === "skipped") {
57
+ return;
58
+ }
59
+ if (stage.status === "completed") {
60
+ return stage.workflowChild?.runId ?? stage.workflowChildRun?.runId;
61
+ }
62
+ return stage.workflowChildRun?.runId;
63
+ }
64
+ function reciprocalWorkflowRootRunId(runById, runId) {
65
+ const visited = new Set;
66
+ const declaredRoots = [];
67
+ let current = runById.get(runId);
68
+ while (current !== undefined) {
69
+ const currentId = current.id;
70
+ if (visited.has(currentId))
71
+ return;
72
+ visited.add(currentId);
73
+ if (current.rootRunId !== undefined)
74
+ declaredRoots.push(current.rootRunId);
75
+ const parentRunId = current.parentRunId;
76
+ const parentStageId = current.parentStageId;
77
+ if (parentRunId === undefined !== (parentStageId === undefined))
78
+ return;
79
+ if (parentRunId === undefined || parentStageId === undefined) {
80
+ return declaredRoots.every((declared) => declared === currentId) ? currentId : undefined;
81
+ }
82
+ const parent = runById.get(parentRunId);
83
+ const boundary = parent?.stages.find((stage) => stage.id === parentStageId);
84
+ if (parent === undefined || authoritativeWorkflowChildRunId(boundary) !== currentId) {
85
+ return;
86
+ }
87
+ current = parent;
88
+ }
89
+ return;
90
+ }
91
+
92
+ // dist/builtin/workflows/src/durable/prompt-reservations.ts
93
+ function durablePromptScope(backend, workflowId) {
94
+ return backend.promptReservationScope(workflowId);
95
+ }
96
+ function claimDurablePromptToken(backend, workflowId, reservationId) {
97
+ return backend.pendingPromptToken(workflowId, reservationId);
98
+ }
99
+ function reserveDurablePrompt(backend, workflowId, reservationId) {
100
+ return backend.reservePendingPrompt(workflowId, reservationId);
101
+ }
102
+ function releaseDurablePrompt(backend, workflowId, reservationId, token) {
103
+ return backend.releasePendingPrompt(workflowId, reservationId, token);
104
+ }
105
+
106
+ // dist/builtin/workflows/src/durable/scoped-backend.ts
107
+ class ScopedDurableBackend {
108
+ persistent;
109
+ inner;
110
+ scope;
111
+ constructor(inner, scope) {
112
+ this.inner = inner;
113
+ this.scope = scope;
114
+ this.persistent = inner.persistent;
115
+ }
116
+ async archivePendingStageMessage(_workflowId, entry) {
117
+ await this.inner.archivePendingStageMessage?.(this.scope.rootWorkflowId, entry);
118
+ }
119
+ async readSettledPendingStageMessage(workflowId, messageId, logicalRunId = workflowId) {
120
+ return this.inner.readSettledPendingStageMessage?.(this.scope.rootWorkflowId, messageId, logicalRunId);
121
+ }
122
+ getPendingStageMessageDeliveryCount(workflowId, messageId, logicalRunId = workflowId) {
123
+ return this.inner.getPendingStageMessageDeliveryCount?.(this.scope.rootWorkflowId, messageId, logicalRunId) ?? 0;
124
+ }
125
+ async readPendingStageMessageDeliveryCount(workflowId, messageId, logicalRunId = workflowId) {
126
+ return this.inner.readPendingStageMessageDeliveryCount === undefined ? this.getPendingStageMessageDeliveryCount(workflowId, messageId, logicalRunId) : await this.inner.readPendingStageMessageDeliveryCount(this.scope.rootWorkflowId, messageId, logicalRunId);
127
+ }
128
+ async archivePendingStageDeliveryReceipt(_workflowId, messageId, delivery, accounting) {
129
+ await this.inner.archivePendingStageDeliveryReceipt?.(this.scope.rootWorkflowId, messageId, delivery, accounting);
130
+ }
131
+ hasCachedPendingStageDeliveryReceipt(workflowId, messageId, delivery, anySession = false, logicalRunId = workflowId) {
132
+ return this.inner.hasCachedPendingStageDeliveryReceipt?.(this.scope.rootWorkflowId, messageId, delivery, anySession, logicalRunId) ?? false;
133
+ }
134
+ async hasPendingStageDeliveryReceipt(workflowId, messageId, delivery, logicalRunId = workflowId) {
135
+ return await this.inner.hasPendingStageDeliveryReceipt?.(this.scope.rootWorkflowId, messageId, delivery, logicalRunId) ?? false;
136
+ }
137
+ async commitWorkflowRegistration(_handle) {}
138
+ persistPendingStageMessages(workflowId, messages, logicalRunId = workflowId) {
139
+ return this.inner.persistPendingStageMessages(this.scope.rootWorkflowId, messages, logicalRunId);
140
+ }
141
+ async commitCheckpoint(checkpoint, options) {
142
+ await this.inner.commitCheckpoint(this.remap(checkpoint), options);
143
+ }
144
+ async commitAdditiveCheckpointBestEffort(checkpoint) {
145
+ return await this.inner.commitAdditiveCheckpointBestEffort(this.remap(checkpoint));
146
+ }
147
+ workflowOwnership(_workflowId) {
148
+ return this.inner.workflowOwnership(this.scope.rootWorkflowId);
149
+ }
150
+ getToolOutput(_workflowId, argsHash) {
151
+ return this.inner.getToolOutput(this.scope.rootWorkflowId, this.scopeKey(argsHash));
152
+ }
153
+ getToolCheckpoint(_workflowId, argsHash) {
154
+ return this.inner.getToolCheckpoint(this.scope.rootWorkflowId, this.scopeKey(argsHash));
155
+ }
156
+ getUiResponse(_workflowId, promptHash) {
157
+ return this.inner.getUiResponse(this.scope.rootWorkflowId, this.scopeKey(promptHash));
158
+ }
159
+ getStageOutput(_workflowId, replayKey) {
160
+ return this.inner.getStageOutput(this.scope.rootWorkflowId, this.scopeKey(replayKey));
161
+ }
162
+ getStageSession(_workflowId, replayKey) {
163
+ return this.inner.getStageSession(this.scope.rootWorkflowId, this.scopeKey(replayKey));
164
+ }
165
+ listCheckpoints(workflowId) {
166
+ const prefix = `${this.scope.scopePrefix}:`;
167
+ return this.inner.listCheckpoints(this.scope.rootWorkflowId).filter((checkpoint) => checkpointHasPrefix(checkpoint, prefix)).map((checkpoint) => localCheckpoint(checkpoint, workflowId, prefix));
168
+ }
169
+ getWorkflow(_workflowId) {
170
+ return;
171
+ }
172
+ getLoadableWorkflow(_workflowId) {
173
+ return;
174
+ }
175
+ async commitWorkflowStatus(_workflowId, _status, _pendingPrompts, _resumable) {}
176
+ async commitWorkflowStatusTransition(_workflowId, _expectedStatuses, _status, _pendingPrompts, _resumable) {
177
+ return false;
178
+ }
179
+ commitPendingPromptAdjustment(_workflowId, delta) {
180
+ return this.inner.commitPendingPromptAdjustment(this.scope.rootWorkflowId, delta);
181
+ }
182
+ promptReservationScope(_workflowId) {
183
+ return this.effectivePromptScope();
184
+ }
185
+ pendingPromptToken(_workflowId, reservationId) {
186
+ return claimDurablePromptToken(this.inner, this.scope.rootWorkflowId, reservationId);
187
+ }
188
+ reservePendingPrompt(_workflowId, reservationId) {
189
+ return reserveDurablePrompt(this.inner, this.scope.rootWorkflowId, reservationId);
190
+ }
191
+ releasePendingPrompt(_workflowId, reservationId, token) {
192
+ return releaseDurablePrompt(this.inner, this.scope.rootWorkflowId, reservationId, token);
193
+ }
194
+ listResumableWorkflows() {
195
+ return [];
196
+ }
197
+ listCompletedWorkflows() {
198
+ return [];
199
+ }
200
+ async prepareWorkflowCatalog() {
201
+ return { resumable: [], completed: [] };
202
+ }
203
+ toMetadata(_workflowId) {
204
+ return;
205
+ }
206
+ async deleteWorkflow(_workflowId) {}
207
+ async deleteWorkflowIfInactive(_workflowId) {
208
+ return { ok: false, reason: "not_found" };
209
+ }
210
+ isWorkflowLoadable(_workflowId) {
211
+ return false;
212
+ }
213
+ async commitReset() {}
214
+ hydrateWorkflow(_workflowId) {
215
+ return Promise.resolve();
216
+ }
217
+ hydrateResumableWorkflows() {
218
+ return Promise.resolve();
219
+ }
220
+ effectivePromptScope() {
221
+ const parent = durablePromptScope(this.inner, this.scope.rootWorkflowId);
222
+ const scope = parent.scope === "root" ? this.scope.scopePrefix : `${parent.scope}:${this.scope.scopePrefix}`;
223
+ return {
224
+ rootWorkflowId: parent.rootWorkflowId,
225
+ scope
226
+ };
227
+ }
228
+ scopeKey(key) {
229
+ return `${this.scope.scopePrefix}:${key}`;
230
+ }
231
+ remap(checkpoint) {
232
+ const workflowId = this.scope.rootWorkflowId;
233
+ if (checkpoint.kind === "tool") {
234
+ return {
235
+ ...checkpoint,
236
+ workflowId,
237
+ checkpointId: this.scopeKey(checkpoint.checkpointId),
238
+ argsHash: this.scopeKey(checkpoint.argsHash)
239
+ };
240
+ }
241
+ if (checkpoint.kind === "ui") {
242
+ return {
243
+ ...checkpoint,
244
+ workflowId,
245
+ checkpointId: this.scopeKey(checkpoint.checkpointId),
246
+ promptHash: this.scopeKey(checkpoint.promptHash)
247
+ };
248
+ }
249
+ return {
250
+ ...checkpoint,
251
+ workflowId,
252
+ checkpointId: this.scopeKey(checkpoint.checkpointId),
253
+ replayKey: this.scopeKey(checkpoint.replayKey),
254
+ ...remappedBoundaryScope(checkpoint, this.scopeKey(checkpoint.topology?.boundary?.replayScope ?? ""))
255
+ };
256
+ }
257
+ }
258
+ function checkpointHasPrefix(checkpoint, prefix) {
259
+ if (!checkpoint.checkpointId.startsWith(prefix))
260
+ return false;
261
+ if (checkpoint.kind === "tool")
262
+ return checkpoint.argsHash.startsWith(prefix);
263
+ if (checkpoint.kind === "ui")
264
+ return checkpoint.promptHash.startsWith(prefix);
265
+ return checkpoint.replayKey.startsWith(prefix);
266
+ }
267
+ function localCheckpoint(checkpoint, workflowId, prefix) {
268
+ const checkpointId = checkpoint.checkpointId.slice(prefix.length);
269
+ if (checkpoint.kind === "tool") {
270
+ return { ...checkpoint, workflowId, checkpointId, argsHash: checkpoint.argsHash.slice(prefix.length) };
271
+ }
272
+ if (checkpoint.kind === "ui") {
273
+ return { ...checkpoint, workflowId, checkpointId, promptHash: checkpoint.promptHash.slice(prefix.length) };
274
+ }
275
+ const replayKey = checkpoint.replayKey.slice(prefix.length);
276
+ const replayScope = stripOnePrefix(checkpoint.topology?.boundary?.replayScope, prefix);
277
+ return {
278
+ ...checkpoint,
279
+ workflowId,
280
+ checkpointId,
281
+ replayKey,
282
+ ...remappedBoundaryScope(checkpoint, replayScope)
283
+ };
284
+ }
285
+ function remappedBoundaryScope(checkpoint, replayScope) {
286
+ const topology = checkpoint.topology;
287
+ if (topology?.boundary === undefined || replayScope === undefined)
288
+ return {};
289
+ return {
290
+ topology: {
291
+ ...topology,
292
+ boundary: { ...topology.boundary, replayScope }
293
+ }
294
+ };
295
+ }
296
+ function stripOnePrefix(value, prefix) {
297
+ if (value === undefined || !value.startsWith(prefix))
298
+ return value;
299
+ return value.slice(prefix.length);
300
+ }
301
+
302
+ // dist/builtin/workflows/src/durable/run-owner-backend.ts
303
+ var workflowRunBackend = Symbol.for("atomic-workflows/run-journal-backend@1");
304
+ function availableRunDurableBackend(runs, runId) {
305
+ const target = resolveRunIdTarget(runId, runs.map((run) => run.id));
306
+ const id = target.kind === "exact" || target.kind === "unique_prefix" ? target.runId : runId;
307
+ const rootRunId = durableRootRunIdForRun(runs, id);
308
+ return runs.find((run) => run.id === rootRunId)?.[workflowRunBackend];
309
+ }
310
+ function durableRootRunIdForRun(runs, runId) {
311
+ return reciprocalWorkflowRootRunId(new Map(runs.map((run) => [run.id, run])), runId);
312
+ }
313
+ function durableBackendForRun(backend, runs, runId) {
314
+ const rootRunId = durableRootRunIdForRun(runs, runId);
315
+ if (rootRunId === undefined)
316
+ return;
317
+ const runById = new Map(runs.map((run) => [run.id, run]));
318
+ const rootBackend = availableRunDurableBackend(runs, rootRunId) ?? backend;
319
+ if (rootRunId === runId)
320
+ return rootBackend;
321
+ const scopes = [];
322
+ let current = runById.get(runId);
323
+ while (current !== undefined && current.id !== rootRunId) {
324
+ const parent = current.parentRunId === undefined ? undefined : runById.get(current.parentRunId);
325
+ const boundary = parent?.stages.find((stage) => stage.id === current?.parentStageId);
326
+ if (parent === undefined || boundary?.replayKey === undefined)
327
+ return;
328
+ scopes.push(boundary.replayKey);
329
+ current = parent;
330
+ }
331
+ if (current?.id !== rootRunId)
332
+ return;
333
+ let view = rootBackend;
334
+ for (const scopePrefix of scopes.reverse()) {
335
+ view = new ScopedDurableBackend(view, { rootWorkflowId: rootRunId, scopePrefix });
336
+ }
337
+ return view;
338
+ }
339
+
340
+ // dist/builtin/workflows/src/durable/journal/types.ts
341
+ import { StorageSchemaVersionError } from "@bastani/atomic/storage";
342
+ import { StorageUnavailableError } from "@bastani/atomic/storage";
343
+ import { RUN_EVENT_TYPES } from "@bastani/atomic/storage";
344
+ class JournalError extends Error {
345
+ }
346
+
347
+ // dist/builtin/workflows/src/durable/store-backend.ts
348
+ var workflowStoreBackend = Symbol.for("atomic-workflows/store-journal-backend@1");
349
+ var workflowStoreBackendOverride = Symbol.for("atomic-workflows/store-journal-override@1");
350
+ class DurableBackendNotInitializedError extends JournalError {
351
+ constructor() {
352
+ super("Workflow journal has not been initialized");
353
+ this.name = "DurableBackendNotInitializedError";
354
+ }
355
+ }
356
+ function availableStoreDurableBackend(store, runId) {
357
+ return (store !== undefined && runId !== undefined ? availableRunDurableBackend(store.runs(), runId) : undefined) ?? store?.[workflowStoreBackend];
358
+ }
359
+ function requireStoreDurableBackend(store, runId) {
360
+ const backend = availableStoreDurableBackend(store, runId);
361
+ if (backend === undefined)
362
+ throw new DurableBackendNotInitializedError;
363
+ return backend;
364
+ }
365
+
366
+ // dist/builtin/workflows/src/shared/pending-stage-delivery.ts
367
+ var PENDING_STAGE_MESSAGE_LIMIT = 50;
368
+ var PENDING_STAGE_UNDELIVERABLE_NOTIFICATION_PREFIX = "atomic-pending-stage-undeliverable";
369
+
370
+ class PendingStageMessageOrderError extends Error {
371
+ runId;
372
+ messageId;
373
+ constructor(entry) {
374
+ super(`atomic-workflows: pending stage message ${entry.id} in run ${entry.runId} has no admission order`);
375
+ this.name = "PendingStageMessageOrderError";
376
+ this.runId = entry.runId;
377
+ this.messageId = entry.id;
378
+ }
379
+ }
380
+ function pendingStageMessageAdmissionOrder(entry) {
381
+ if (entry.admissionOrder === undefined)
382
+ throw new PendingStageMessageOrderError(entry);
383
+ return entry.admissionOrder;
384
+ }
385
+ function queueStageMessage(messages, input, senderGroup, runGroup, stageIdentity) {
386
+ if (normalizeDeliveryGroup(senderGroup) !== normalizeDeliveryGroup(runGroup)) {
387
+ return { ok: false, reason: "group_mismatch", runId: input.runId, stageKey: input.stageKey };
388
+ }
389
+ const messageId = input.message.id;
390
+ const queued = pendingStageMessagesFor(messages, input.runId, input.stageKey, stageIdentity);
391
+ const existing = messages.find((entry) => entry.runId === input.runId && entry.id === messageId);
392
+ if (existing !== undefined) {
393
+ if (pendingStageMessageSignature(existing, stageIdentity) !== pendingStageMessageSignature(input, stageIdentity)) {
394
+ return {
395
+ ok: false,
396
+ reason: "message_id_conflict",
397
+ runId: input.runId,
398
+ stageKey: input.stageKey,
399
+ messageId
400
+ };
401
+ }
402
+ const queuedPosition = queued.indexOf(existing);
403
+ return {
404
+ ok: true,
405
+ messages,
406
+ entry: existing,
407
+ ...queuedPosition >= 0 ? { position: queuedPosition + 1 } : {},
408
+ deduplicated: true
409
+ };
410
+ }
411
+ if (queued.length >= PENDING_STAGE_MESSAGE_LIMIT) {
412
+ return {
413
+ ok: false,
414
+ reason: "capacity",
415
+ limit: PENDING_STAGE_MESSAGE_LIMIT,
416
+ runId: input.runId,
417
+ stageKey: input.stageKey
418
+ };
419
+ }
420
+ const entry = {
421
+ ...input,
422
+ id: messageId,
423
+ ...stageIdentity !== undefined ? { stageId: stageIdentity.id } : {},
424
+ ...stageIdentity?.replayKey !== undefined ? { stageReplayKey: stageIdentity.replayKey } : {},
425
+ admissionOrder: nextAdmissionOrder(messages, input.runId),
426
+ status: "queued"
427
+ };
428
+ return {
429
+ ok: true,
430
+ messages: [...messages, entry],
431
+ entry,
432
+ position: queued.length + 1,
433
+ deduplicated: false
434
+ };
435
+ }
436
+ function queueStickyStageMessage(messages, input, senderGroup, runGroup) {
437
+ if (normalizeDeliveryGroup(senderGroup) !== normalizeDeliveryGroup(runGroup)) {
438
+ return { ok: false, reason: "group_mismatch", runId: input.runId, stageKey: input.targetPath };
439
+ }
440
+ const messageId = input.message.id;
441
+ const existing = messages.find((entry) => entry.runId === input.runId && entry.id === messageId);
442
+ if (existing !== undefined) {
443
+ if (pendingStageMessageSignature(existing) !== pendingStageMessageSignature(input)) {
444
+ return {
445
+ ok: false,
446
+ reason: "message_id_conflict",
447
+ runId: input.runId,
448
+ stageKey: input.targetPath,
449
+ messageId
450
+ };
451
+ }
452
+ const queuedForTarget = queuedStickyCount(messages, input.runId, input.targetPath);
453
+ return {
454
+ ok: true,
455
+ messages,
456
+ entry: existing,
457
+ ...existing.status === "queued" ? { position: queuedForTarget } : {},
458
+ deduplicated: true
459
+ };
460
+ }
461
+ if (queuedStickyCount(messages, input.runId, input.targetPath) >= PENDING_STAGE_MESSAGE_LIMIT) {
462
+ return {
463
+ ok: false,
464
+ reason: "capacity",
465
+ limit: PENDING_STAGE_MESSAGE_LIMIT,
466
+ runId: input.runId,
467
+ stageKey: input.targetPath
468
+ };
469
+ }
470
+ const entry = {
471
+ ...input,
472
+ id: messageId,
473
+ stageKey: input.targetPath,
474
+ sticky: true,
475
+ deliveries: [],
476
+ deliveryCount: 0,
477
+ admissionOrder: nextAdmissionOrder(messages, input.runId),
478
+ status: "queued"
479
+ };
480
+ return {
481
+ ok: true,
482
+ messages: [...messages, entry],
483
+ entry,
484
+ position: queuedStickyCount(messages, input.runId, input.targetPath) + 1,
485
+ deduplicated: false
486
+ };
487
+ }
488
+ function queuedStickyCount(messages, runId, targetPath) {
489
+ return messages.filter((entry) => entry.runId === runId && entry.sticky === true && entry.targetPath === targetPath && entry.status === "queued").length;
490
+ }
491
+ function recordPendingStageMessageDeliveries(messages, runId, messageId, records, deliveredAt) {
492
+ const index = messages.findIndex((entry) => entry.runId === runId && entry.id === messageId && entry.sticky === true && entry.status === "queued");
493
+ if (index < 0)
494
+ return messages;
495
+ const entry = messages[index];
496
+ const recorded = new Set((entry.deliveries ?? []).map((delivery) => JSON.stringify([delivery.runId, delivery.stageId, delivery.sessionId, delivery.admission])));
497
+ const additions = [];
498
+ for (const record of records) {
499
+ const key = JSON.stringify([record.runId, record.stageId, record.sessionId, record.admission]);
500
+ if (recorded.has(key))
501
+ continue;
502
+ recorded.add(key);
503
+ additions.push({
504
+ runId: record.runId,
505
+ stageId: record.stageId,
506
+ ...record.stageName === undefined ? {} : { stageName: record.stageName },
507
+ ...record.sessionId === undefined ? {} : { sessionId: record.sessionId },
508
+ ...record.admission === undefined ? {} : { admission: record.admission },
509
+ deliveredAt
510
+ });
511
+ }
512
+ if (additions.length === 0)
513
+ return messages;
514
+ const deliveries = [...entry.deliveries ?? [], ...additions];
515
+ const next = {
516
+ ...entry,
517
+ deliveries,
518
+ deliveryCount: (entry.deliveryCount ?? entry.deliveries?.length ?? 0) + additions.length
519
+ };
520
+ const result = [...messages];
521
+ result[index] = next;
522
+ return result;
523
+ }
524
+ function compactStickyStageMessageDeliveries(messages, runs) {
525
+ const finished = new Set(runs.flatMap((run) => run.stages.filter((stage) => stage.status === "completed" || stage.status === "skipped").map((stage) => JSON.stringify([run.id, stage.id]))));
526
+ let changed = false;
527
+ const next = messages.map((entry) => {
528
+ if (entry.sticky !== true || entry.deliveries === undefined)
529
+ return entry;
530
+ const deliveries = entry.deliveries.filter((delivery) => !finished.has(JSON.stringify([delivery.runId, delivery.stageId])));
531
+ if (deliveries.length === entry.deliveries.length)
532
+ return entry;
533
+ changed = true;
534
+ return { ...entry, deliveries, deliveryCount: entry.deliveryCount ?? entry.deliveries.length };
535
+ });
536
+ return changed ? next : messages;
537
+ }
538
+ function settleStickyPendingStageMessageDelivered(messages, runId, messageId, settledAt) {
539
+ const index = messages.findIndex((entry) => entry.runId === runId && entry.id === messageId && entry.sticky === true && entry.status === "queued" && (entry.deliveryCount ?? 0) > 0);
540
+ if (index < 0)
541
+ return messages;
542
+ const next = [...messages];
543
+ next[index] = { ...next[index], status: "delivered", deliveredAt: settledAt };
544
+ return next;
545
+ }
546
+ function pendingStageMessagesFor(messages, runId, stageKey, stageIdentity) {
547
+ return messages.map((entry, index) => ({ entry, index })).filter(({ entry }) => matchesPendingStage(entry, runId, stageKey, stageIdentity) && entry.status === "queued").map(({ entry, index }) => ({ entry, index, order: pendingStageMessageAdmissionOrder(entry) })).sort((left, right) => left.order - right.order || left.index - right.index).map(({ entry }) => entry);
548
+ }
549
+ function markPendingStageMessageDelivered(messages, runId, stageKey, messageId, deliveredAt, stageIdentity) {
550
+ return updateQueuedPendingStageMessage(messages, runId, stageKey, messageId, stageIdentity, (entry) => ({
551
+ ...entry,
552
+ status: "delivered",
553
+ deliveredAt
554
+ }));
555
+ }
556
+ function markPendingStageMessageUndeliverable(messages, runId, stageKey, messageId, reason, stageIdentity) {
557
+ return updateQueuedPendingStageMessage(messages, runId, stageKey, messageId, stageIdentity, (entry) => ({
558
+ ...entry,
559
+ status: "undeliverable",
560
+ undeliverableReason: reason,
561
+ undeliverableNotificationId: pendingStageUndeliverableNotificationId(entry)
562
+ }));
563
+ }
564
+ function markPendingStageMessageUndeliverableNotified(messages, runId, stageKey, messageId, notificationId, notifiedAt) {
565
+ const index = messages.findIndex((entry) => (entry.sticky === true ? entry.runId === runId : matchesPendingStage(entry, runId, stageKey)) && entry.id === messageId && entry.status === "undeliverable" && entry.undeliverableNotificationId === notificationId && entry.undeliverableNotifiedAt === undefined);
566
+ if (index < 0)
567
+ return messages;
568
+ const next = [...messages];
569
+ next[index] = { ...next[index], undeliverableNotifiedAt: notifiedAt };
570
+ return next;
571
+ }
572
+ function pendingStageUndeliverableNotificationId(entry) {
573
+ return [
574
+ PENDING_STAGE_UNDELIVERABLE_NOTIFICATION_PREFIX,
575
+ encodeURIComponent(entry.runId),
576
+ encodeURIComponent(entry.stageKey),
577
+ encodeURIComponent(entry.id)
578
+ ].join(":");
579
+ }
580
+ function updateQueuedPendingStageMessage(messages, runId, stageKey, messageId, stageIdentity, update) {
581
+ const index = messages.findIndex((entry) => queuedEntryMatches(entry, runId, stageKey, messageId, stageIdentity));
582
+ if (index < 0)
583
+ return messages;
584
+ const next = [...messages];
585
+ next[index] = update(next[index]);
586
+ return next;
587
+ }
588
+ function queuedEntryMatches(entry, runId, stageKey, messageId, stageIdentity) {
589
+ if (entry.runId !== runId || entry.id !== messageId || entry.status !== "queued")
590
+ return false;
591
+ return entry.sticky === true || matchesPendingStage(entry, runId, stageKey, stageIdentity);
592
+ }
593
+ function matchesPendingStage(entry, runId, stageKey, stageIdentity) {
594
+ if (entry.sticky === true)
595
+ return false;
596
+ if (entry.runId !== runId)
597
+ return false;
598
+ if (stageIdentity === undefined)
599
+ return entry.stageKey === stageKey;
600
+ return entry.stageId === stageIdentity.id || entry.stageReplayKey !== undefined && entry.stageReplayKey === stageIdentity.replayKey || entry.stageId === undefined && stageIdentity.aliases.includes(entry.stageKey);
601
+ }
602
+ function nextAdmissionOrder(messages, runId) {
603
+ let greatest = 0;
604
+ for (const entry of messages) {
605
+ if (entry.runId !== runId)
606
+ continue;
607
+ greatest = Math.max(greatest, pendingStageMessageAdmissionOrder(entry));
608
+ }
609
+ return greatest + 1;
610
+ }
611
+ function pendingStageMessageSignature(entry, stageIdentity) {
612
+ const storedTarget = "status" in entry ? entry.stageReplayKey ?? entry.stageId : undefined;
613
+ const { timestamp: transportTimestamp, ...logicalMessage } = entry.message;
614
+ return stableJson({
615
+ target: storedTarget ?? stageIdentity?.replayKey ?? stageIdentity?.id ?? entry.stageKey,
616
+ sender: entry.senderReturnAddress ?? entry.from.id,
617
+ message: {
618
+ ...logicalMessage,
619
+ expectsReply: logicalMessage.expectsReply ?? false,
620
+ content: {
621
+ ...logicalMessage.content,
622
+ attachments: logicalMessage.content.attachments ?? []
623
+ }
624
+ }
625
+ });
626
+ }
627
+ function stableJson(value) {
628
+ return JSON.stringify(sortJsonValue(value));
629
+ }
630
+ function sortJsonValue(value) {
631
+ if (Array.isArray(value))
632
+ return value.map(sortJsonValue);
633
+ if (typeof value !== "object" || value === null)
634
+ return value;
635
+ return Object.fromEntries(Object.entries(value).filter(([, nested]) => nested !== undefined).sort(([left], [right]) => left.localeCompare(right)).map(([key, nested]) => [key, sortJsonValue(nested)]));
636
+ }
637
+ function normalizeDeliveryGroup(value) {
638
+ if (typeof value !== "string")
639
+ return "default";
640
+ const trimmed = value.trim();
641
+ return trimmed.length > 0 ? trimmed : "default";
642
+ }
643
+ // dist/builtin/workflows/src/durable/backend-process-owner.ts
644
+ var DURABLE_BACKEND_PROCESS_OWNER_KEY = Symbol.for("atomic-workflows/durable-backend-process-owner@1");
645
+ function emptyOwner() {
646
+ return {
647
+ version: 1,
648
+ injectedBackend: undefined
649
+ };
650
+ }
651
+ function ownerBag() {
652
+ return globalThis;
653
+ }
654
+ function getDurableBackendProcessOwner() {
655
+ const bag = ownerBag();
656
+ const existing = bag[DURABLE_BACKEND_PROCESS_OWNER_KEY];
657
+ if (existing !== undefined && existing.version === 1)
658
+ return existing;
659
+ const created = emptyOwner();
660
+ bag[DURABLE_BACKEND_PROCESS_OWNER_KEY] = created;
661
+ return created;
662
+ }
663
+
664
+ // dist/builtin/workflows/src/shared/session-scoped-singleton.ts
665
+ import { sessionScopedExtensionState } from "@bastani/atomic";
666
+ var SHARED_STATES_KEY = Symbol.for("atomic-workflows/session-scoped-singleton-pre-adoption@1");
667
+ function processBag() {
668
+ return globalThis;
669
+ }
670
+ function recordLocal(key, local) {
671
+ const bag = processBag();
672
+ let states = bag[SHARED_STATES_KEY];
673
+ if (states === undefined || states.version !== 1) {
674
+ states = { version: 1, byKey: new Map };
675
+ bag[SHARED_STATES_KEY] = states;
676
+ }
677
+ const existing = states.byKey.get(key);
678
+ if (existing !== undefined)
679
+ return existing;
680
+ const created = { local, instance: undefined, localClaimed: false };
681
+ states.byKey.set(key, created);
682
+ return created;
683
+ }
684
+ function createSessionScopedSingleton(key, createLocal) {
685
+ const local = createLocal();
686
+ const shared = recordLocal(key, local);
687
+ let instance = local;
688
+ const live = () => shared.instance ?? instance;
689
+ const current = () => live();
690
+ const adoptWithResult = (scope, options) => {
691
+ const current = live();
692
+ let targetCreated = false;
693
+ const target = sessionScopedExtensionState(scope, key, () => {
694
+ targetCreated = true;
695
+ if (shared.localClaimed)
696
+ return (options?.create ?? createLocal)();
697
+ shared.localClaimed = true;
698
+ return shared.local;
699
+ });
700
+ const preservedCurrent = !targetCreated && target !== current && options?.preserveCurrentWhenTargetExists?.(current, target) === true;
701
+ shared.instance = preservedCurrent ? current : target;
702
+ instance = shared.instance;
703
+ return { instance: shared.instance, preservedCurrent };
704
+ };
705
+ const adopt = (scope, options) => adoptWithResult(scope, options).instance;
706
+ const facade = new Proxy(local, {
707
+ get(_target, prop) {
708
+ const value = Reflect.get(live(), prop, live());
709
+ if (typeof value === "function") {
710
+ return value.bind(live());
711
+ }
712
+ return value;
713
+ },
714
+ set(_target, prop, value) {
715
+ return Reflect.set(live(), prop, value, live());
716
+ },
717
+ has(_target, prop) {
718
+ return Reflect.has(live(), prop);
719
+ }
720
+ });
721
+ return { facade, adopt, adoptWithResult, current };
722
+ }
723
+
724
+ // dist/builtin/workflows/src/shared/flat-string.ts
725
+ function flattenTruncatedString(value) {
726
+ return value.split("").join("");
727
+ }
728
+
729
+ // dist/builtin/workflows/src/shared/tool-payload-bounds.ts
730
+ var TOOL_PAYLOAD_MAX_KEYS = 2048;
731
+ var TOOL_PAYLOAD_VALUE_LIMIT = 16384;
732
+ var TOOL_PAYLOAD_TRUNCATION_MARKER = "… [truncated]";
733
+ var TOOL_PAYLOAD_CYCLE_PLACEHOLDER = "<cycle>";
734
+ var TOOL_PAYLOAD_UNREADABLE_PLACEHOLDER = "<unreadable>";
735
+ var TOOL_PAYLOAD_UNSERIALIZABLE_PLACEHOLDER = "<unserializable>";
736
+ var TOOL_PAYLOAD_TRUNCATION_KEY = "…";
737
+ var TOOL_PAYLOAD_MAX_DEPTH = 256;
738
+ function isOmittedJsonValue(value) {
739
+ return value === undefined || typeof value === "function" || typeof value === "symbol";
740
+ }
741
+ function isToolPayloadObject(value) {
742
+ return value !== null && typeof value === "object" && !Array.isArray(value);
743
+ }
744
+ function isToolPayloadArray(value) {
745
+ return Array.isArray(value);
746
+ }
747
+ function isToolPayloadObjectLike(value) {
748
+ return value !== null && typeof value === "object";
749
+ }
750
+ function isToolPayloadCallable(value) {
751
+ return typeof value === "function";
752
+ }
753
+ function readToolPayloadProperty(value, key) {
754
+ try {
755
+ const property = Reflect.get(value, key);
756
+ return { ok: true, value: property };
757
+ } catch {
758
+ return { ok: false };
759
+ }
760
+ }
761
+ function safeProperty(value, key) {
762
+ const result = readToolPayloadProperty(value, key);
763
+ return result.ok ? result.value : TOOL_PAYLOAD_UNREADABLE_PLACEHOLDER;
764
+ }
765
+ function safeOwnKeys(value, consumeKey) {
766
+ let stopped = false;
767
+ function* enumerate() {
768
+ let keys;
769
+ try {
770
+ keys = Reflect.ownKeys(value);
771
+ } catch {
772
+ return;
773
+ }
774
+ for (const key of keys) {
775
+ if (!consumeKey()) {
776
+ stopped = true;
777
+ return;
778
+ }
779
+ if (typeof key !== "string")
780
+ continue;
781
+ let descriptor;
782
+ try {
783
+ descriptor = Object.getOwnPropertyDescriptor(value, key);
784
+ } catch {
785
+ continue;
786
+ }
787
+ if (descriptor?.enumerable === true)
788
+ yield key;
789
+ }
790
+ }
791
+ return { keys: enumerate(), stoppedByLimit: () => stopped };
792
+ }
793
+ function safeArrayLength(value) {
794
+ const result = readToolPayloadProperty(value, "length");
795
+ if (!result.ok || typeof result.value !== "number")
796
+ return 0;
797
+ return Number.isSafeInteger(result.value) && result.value > 0 ? result.value : 0;
798
+ }
799
+ function resolveJsonValue(value) {
800
+ if (!isToolPayloadObjectLike(value))
801
+ return value;
802
+ const toJson = readToolPayloadProperty(value, "toJSON");
803
+ if (!toJson.ok)
804
+ return TOOL_PAYLOAD_UNREADABLE_PLACEHOLDER;
805
+ if (!isToolPayloadCallable(toJson.value))
806
+ return value;
807
+ try {
808
+ return toJson.value.call(value);
809
+ } catch {
810
+ return TOOL_PAYLOAD_UNSERIALIZABLE_PLACEHOLDER;
811
+ }
812
+ }
813
+ var NULL_COST = 4;
814
+ var NUMBER_COST = 8;
815
+ var BOOLEAN_COST = 5;
816
+ var CONTAINER_COST = 2;
817
+ var SEPARATOR_COST = 1;
818
+ function consumeKeyBudget(state) {
819
+ if (state.keysRemaining <= 0)
820
+ return false;
821
+ state.keysRemaining -= 1;
822
+ return true;
823
+ }
824
+ function addTruncationMarker(record) {
825
+ let key = TOOL_PAYLOAD_TRUNCATION_KEY;
826
+ let suffix = 1;
827
+ while (Object.hasOwn(record, key))
828
+ key = `${TOOL_PAYLOAD_TRUNCATION_KEY}${suffix++}`;
829
+ record[key] = TOOL_PAYLOAD_TRUNCATION_MARKER;
830
+ }
831
+ function cloneObjectLike(state, value) {
832
+ if (state.seen.has(value))
833
+ return TOOL_PAYLOAD_CYCLE_PLACEHOLDER;
834
+ if (state.depth >= TOOL_PAYLOAD_MAX_DEPTH)
835
+ return TOOL_PAYLOAD_TRUNCATION_MARKER;
836
+ state.seen.add(value);
837
+ state.depth += 1;
838
+ state.remaining -= CONTAINER_COST;
839
+ try {
840
+ if (isToolPayloadArray(value)) {
841
+ const items = [];
842
+ const length = safeArrayLength(value);
843
+ for (let index = 0;index < length; index++) {
844
+ if (state.remaining <= 0) {
845
+ items.push(TOOL_PAYLOAD_TRUNCATION_MARKER);
846
+ break;
847
+ }
848
+ state.remaining -= SEPARATOR_COST;
849
+ const item = safeProperty(value, index);
850
+ if (isOmittedJsonValue(item)) {
851
+ state.remaining -= NULL_COST;
852
+ items.push(null);
853
+ continue;
854
+ }
855
+ items.push(cloneValue(state, item));
856
+ }
857
+ return items;
858
+ }
859
+ const cloned = {};
860
+ const scan = safeOwnKeys(value, () => state.remaining > 0 && consumeKeyBudget(state));
861
+ for (const key of scan.keys) {
862
+ state.remaining -= key.length + SEPARATOR_COST;
863
+ const child = safeProperty(value, key);
864
+ if (isOmittedJsonValue(child))
865
+ continue;
866
+ cloned[key] = cloneValue(state, child);
867
+ }
868
+ if (scan.stoppedByLimit())
869
+ addTruncationMarker(cloned);
870
+ return cloned;
871
+ } finally {
872
+ state.depth -= 1;
873
+ state.seen.delete(value);
874
+ }
875
+ }
876
+ function cloneValue(state, value) {
877
+ const resolved = resolveJsonValue(value);
878
+ if (resolved === null) {
879
+ state.remaining -= NULL_COST;
880
+ return null;
881
+ }
882
+ switch (typeof resolved) {
883
+ case "string":
884
+ return cloneString(state, resolved);
885
+ case "number":
886
+ state.remaining -= NUMBER_COST;
887
+ return Number.isFinite(resolved) ? resolved : null;
888
+ case "boolean":
889
+ state.remaining -= BOOLEAN_COST;
890
+ return resolved;
891
+ case "object":
892
+ return cloneObjectLike(state, resolved);
893
+ case "bigint":
894
+ state.remaining -= NUMBER_COST;
895
+ return resolved;
896
+ default:
897
+ state.remaining -= TOOL_PAYLOAD_UNSERIALIZABLE_PLACEHOLDER.length;
898
+ return TOOL_PAYLOAD_UNSERIALIZABLE_PLACEHOLDER;
899
+ }
900
+ }
901
+ function boundedToolPayload(value, limit = TOOL_PAYLOAD_VALUE_LIMIT) {
902
+ return cloneValue({ remaining: Math.max(1, limit), depth: 0, keysRemaining: TOOL_PAYLOAD_MAX_KEYS, seen: new Set }, value);
903
+ }
904
+ function boundedToolPayloadRecord(value, limit = TOOL_PAYLOAD_VALUE_LIMIT) {
905
+ const record = {};
906
+ if (!isToolPayloadObject(value) && !isToolPayloadArray(value))
907
+ return record;
908
+ const state = {
909
+ remaining: Math.max(1, limit),
910
+ depth: 0,
911
+ keysRemaining: TOOL_PAYLOAD_MAX_KEYS,
912
+ seen: new Set([value])
913
+ };
914
+ const scan = safeOwnKeys(value, () => state.remaining > 0 && consumeKeyBudget(state));
915
+ for (const key of scan.keys) {
916
+ state.remaining -= key.length + SEPARATOR_COST;
917
+ const child = safeProperty(value, key);
918
+ if (isOmittedJsonValue(child))
919
+ continue;
920
+ record[key] = cloneValue(state, child);
921
+ }
922
+ if (scan.stoppedByLimit())
923
+ addTruncationMarker(record);
924
+ return record;
925
+ }
926
+ function cloneString(state, value) {
927
+ if (state.remaining <= 0)
928
+ return TOOL_PAYLOAD_TRUNCATION_MARKER;
929
+ if (value.length <= state.remaining) {
930
+ state.remaining -= value.length;
931
+ return value;
932
+ }
933
+ const keep = state.remaining;
934
+ state.remaining = 0;
935
+ return `${flattenTruncatedString(value.slice(0, keep))}${TOOL_PAYLOAD_TRUNCATION_MARKER}`;
936
+ }
937
+ function boundedToolText(value, limit = TOOL_PAYLOAD_VALUE_LIMIT) {
938
+ const cap = Math.max(TOOL_PAYLOAD_TRUNCATION_MARKER.length + 1, limit);
939
+ if (value.length <= cap)
940
+ return value;
941
+ const keep = Math.max(0, cap - TOOL_PAYLOAD_TRUNCATION_MARKER.length);
942
+ return `${flattenTruncatedString(value.slice(0, keep))}${TOOL_PAYLOAD_TRUNCATION_MARKER}`;
943
+ }
944
+
945
+ // dist/builtin/workflows/src/shared/graph-store-snapshot.ts
946
+ var COMPACT_RESULT_FIELD_LIMIT = 1024;
947
+ var COMPACT_EXIT_OUTPUT_LIMIT = COMPACT_RESULT_FIELD_LIMIT * 4;
948
+ function compactResultField(value) {
949
+ if (typeof value !== "string")
950
+ return;
951
+ if (value.length <= COMPACT_RESULT_FIELD_LIMIT)
952
+ return value;
953
+ return flattenTruncatedString(value.slice(0, COMPACT_RESULT_FIELD_LIMIT));
954
+ }
955
+ function compactRunResult(result, preserveExitedOutputs = false) {
956
+ if (result === undefined)
957
+ return;
958
+ const status = compactResultField(result.status);
959
+ const summary = compactResultField(result.summary);
960
+ const remainingWork = compactResultField(result.remaining_work);
961
+ const resultText = compactResultField(result.result);
962
+ const budgetDimension = status === "budget_exceeded" && (result.dimension === "duration" || result.dimension === "tokens" || result.dimension === "cost") ? result.dimension : undefined;
963
+ const compact = {
964
+ ...status !== undefined ? { status } : {},
965
+ ...summary !== undefined ? { summary } : {},
966
+ ...remainingWork !== undefined ? { remaining_work: remainingWork } : {},
967
+ ...resultText !== undefined ? { result: resultText } : {},
968
+ ...budgetDimension !== undefined ? { dimension: budgetDimension } : {}
969
+ };
970
+ if (!preserveExitedOutputs)
971
+ return Object.keys(compact).length === 0 ? undefined : compact;
972
+ return compactExitedOutputs(result, compact);
973
+ }
974
+ function compactExitedOutputs(result, compact) {
975
+ try {
976
+ const serialized = JSON.stringify(result);
977
+ if (serialized !== undefined && serialized.length <= COMPACT_EXIT_OUTPUT_LIMIT) {
978
+ const parsed = JSON.parse(serialized);
979
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
980
+ return compactExitedObject(parsed);
981
+ }
982
+ }
983
+ } catch {}
984
+ return Object.keys(compact).length === 0 ? undefined : compact;
985
+ }
986
+ function compactExitedObject(result) {
987
+ const compacted = { ...result };
988
+ for (const key of ["status", "summary", "remaining_work", "result"]) {
989
+ const value = compacted[key];
990
+ if (typeof value === "string")
991
+ compacted[key] = compactResultField(value) ?? "";
992
+ }
993
+ return Object.keys(compacted).length === 0 ? undefined : compacted;
994
+ }
995
+ function clonePrompt(prompt) {
996
+ return {
997
+ ...prompt,
998
+ ...prompt.choices !== undefined ? { choices: [...prompt.choices] } : {}
999
+ };
1000
+ }
1001
+ function cloneInputRequest(request) {
1002
+ return {
1003
+ ...request,
1004
+ questions: request.questions.map((question) => ({
1005
+ ...question,
1006
+ options: question.options.map((option) => ({ ...option }))
1007
+ }))
1008
+ };
1009
+ }
1010
+ function compactToolEvents(events) {
1011
+ const event = events.at(-1);
1012
+ return event === undefined ? [] : [{ name: event.name }];
1013
+ }
1014
+ function compactWorkflowChild(child) {
1015
+ return {
1016
+ ...child,
1017
+ outputs: {},
1018
+ outputCount: child.outputCount ?? Object.keys(child.outputs).length
1019
+ };
1020
+ }
1021
+ function compactStage(stage) {
1022
+ const {
1023
+ toolEvents,
1024
+ workflowChild,
1025
+ workflowChildRun,
1026
+ pendingPrompt,
1027
+ promptFootprint,
1028
+ inputRequest,
1029
+ notices,
1030
+ mcpScope: _mcpScope,
1031
+ attemptedModels: _attemptedModels,
1032
+ modelAttempts: _modelAttempts,
1033
+ result: _result,
1034
+ structured: _structured,
1035
+ ...metadata
1036
+ } = stage;
1037
+ return {
1038
+ ...metadata,
1039
+ parentIds: [...stage.parentIds],
1040
+ toolEvents: compactToolEvents(toolEvents),
1041
+ ...workflowChild !== undefined ? { workflowChild: compactWorkflowChild(workflowChild) } : {},
1042
+ ...workflowChildRun !== undefined ? { workflowChildRun: { ...workflowChildRun } } : {},
1043
+ ...pendingPrompt !== undefined ? { pendingPrompt: clonePrompt(pendingPrompt) } : {},
1044
+ ...promptFootprint !== undefined ? { promptFootprint: clonePrompt(promptFootprint) } : {},
1045
+ ...inputRequest !== undefined ? { inputRequest: cloneInputRequest(inputRequest) } : {},
1046
+ ...notices !== undefined ? { notices: notices.map((notice) => ({ ...notice })) } : {}
1047
+ };
1048
+ }
1049
+ function compactToolNode(node) {
1050
+ return {
1051
+ ...node,
1052
+ parentIds: [...node.parentIds],
1053
+ ...node.args !== undefined ? { args: boundedToolPayloadRecord(node.args) } : {},
1054
+ ...node.result !== undefined ? { result: boundedToolPayload(node.result) } : {},
1055
+ ...node.source !== undefined ? { source: boundedToolText(node.source) } : {}
1056
+ };
1057
+ }
1058
+ function compactRun(run) {
1059
+ const { inputs: _inputs, result: sourceResult, stages, toolNodes, pendingPrompt, ...metadata } = run;
1060
+ const result = compactRunResult(sourceResult, run.exited === true && run.status === "failed");
1061
+ return {
1062
+ ...metadata,
1063
+ inputs: {},
1064
+ stages: stages.map(compactStage),
1065
+ toolNodes: toolNodes.map(compactToolNode),
1066
+ ...pendingPrompt !== undefined ? { pendingPrompt: clonePrompt(pendingPrompt) } : {},
1067
+ ...result !== undefined ? { result } : {}
1068
+ };
1069
+ }
1070
+ function createGraphStoreSnapshot(runs, notices, version) {
1071
+ const snapshot = {
1072
+ runs: runs.map(compactRun),
1073
+ notices: notices.map((notice) => ({ ...notice })),
1074
+ version
1075
+ };
1076
+ deepFreezeGraphValue(snapshot);
1077
+ return snapshot;
1078
+ }
1079
+ function deepFreezeGraphValue(value) {
1080
+ if (value === null || typeof value !== "object" || Object.isFrozen(value))
1081
+ return;
1082
+ Object.freeze(value);
1083
+ if (Array.isArray(value)) {
1084
+ for (const item of value)
1085
+ deepFreezeGraphValue(item);
1086
+ return;
1087
+ }
1088
+ for (const key of Object.keys(value)) {
1089
+ deepFreezeGraphValue(value[key]);
1090
+ }
1091
+ }
1092
+
1093
+ // dist/builtin/workflows/src/shared/workflow-observation-runtime.ts
1094
+ import { randomUUID } from "node:crypto";
1095
+
1096
+ // dist/builtin/workflows/src/shared/workflow-activity.ts
1097
+ function workflowActivityNodeKey(runId, nodeId) {
1098
+ return `${runId}:${nodeId}`;
1099
+ }
1100
+ var endedStatuses = new Set(["completed", "cached", "failed", "cancelled"]);
1101
+
1102
+ // dist/builtin/workflows/src/shared/workflow-observation-runtime.ts
1103
+ class WorkflowObservationRuntime {
1104
+ runs;
1105
+ invalidate;
1106
+ liveRunIds = new Set;
1107
+ executingStageIds = new Set;
1108
+ executingToolNodeIds = new Set;
1109
+ stoppingRunIds = new Set;
1110
+ retryingStageIds = new Set;
1111
+ acknowledgedFailureRunIds = new Set;
1112
+ listeners = new Set;
1113
+ replayStageIds = new Set;
1114
+ previous = new Map;
1115
+ recoveryDepth = 0;
1116
+ constructor(runs, invalidate) {
1117
+ this.runs = runs;
1118
+ this.invalidate = invalidate;
1119
+ }
1120
+ get recovering() {
1121
+ return this.recoveryDepth > 0;
1122
+ }
1123
+ startRun(runId) {
1124
+ this.liveRunIds.add(runId);
1125
+ this.stoppingRunIds.delete(runId);
1126
+ }
1127
+ finishRun(runId) {
1128
+ this.liveRunIds.delete(runId);
1129
+ this.stoppingRunIds.delete(runId);
1130
+ for (const ids of [
1131
+ this.executingStageIds,
1132
+ this.executingToolNodeIds,
1133
+ this.retryingStageIds,
1134
+ this.replayStageIds
1135
+ ]) {
1136
+ for (const id of ids)
1137
+ if (id.startsWith(`${runId}:`))
1138
+ ids.delete(id);
1139
+ }
1140
+ this.invalidate();
1141
+ }
1142
+ emit(event) {
1143
+ for (const listener of this.listeners) {
1144
+ try {
1145
+ listener(event);
1146
+ } catch {}
1147
+ }
1148
+ }
1149
+ rootRunId(run) {
1150
+ if (run.rootRunId !== undefined)
1151
+ return run.rootRunId;
1152
+ if (run.parentRunId === undefined)
1153
+ return run.id;
1154
+ const parent = this.runs().find((candidate) => candidate.id === run.parentRunId);
1155
+ return parent ? this.rootRunId(parent) : run.parentRunId;
1156
+ }
1157
+ lifecycle(target, attribution = "unknown") {
1158
+ if (this.recovering && !this.liveRunIds.has(target.runId))
1159
+ return;
1160
+ const run = this.runs().find((candidate) => candidate.id === target.runId);
1161
+ if (!run)
1162
+ return;
1163
+ const rootRunId = this.rootRunId(run);
1164
+ const now = Date.now();
1165
+ this.emit({
1166
+ kind: "lifecycle",
1167
+ event: {
1168
+ type: "workflow_lifecycle",
1169
+ eventId: randomUUID(),
1170
+ runId: run.id,
1171
+ rootRunId,
1172
+ occurredAt: now,
1173
+ observedAt: now,
1174
+ target: canonicalTarget(target, rootRunId),
1175
+ attribution,
1176
+ delivery: target.kind === "stage" && this.replayStageIds.has(workflowActivityNodeKey(run.id, target.stageId)) ? "replay" : "live"
1177
+ }
1178
+ });
1179
+ }
1180
+ control(runId, action, attribution = "unknown") {
1181
+ const run = this.runs().find((candidate) => candidate.id === runId);
1182
+ if (!run)
1183
+ return;
1184
+ if ((action === "quit" || action === "kill" || action === "pause") && this.liveRunIds.has(runId))
1185
+ this.stoppingRunIds.add(runId);
1186
+ if (action === "resume")
1187
+ this.stoppingRunIds.delete(runId);
1188
+ this.lifecycle({ kind: "run", runId, status: run.status, action }, attribution);
1189
+ this.invalidate();
1190
+ }
1191
+ heartbeat(runId, scheduledAt, intervalMinutes) {
1192
+ const run = this.runs().find((candidate) => candidate.id === runId);
1193
+ if (run)
1194
+ this.emit({
1195
+ kind: "heartbeat",
1196
+ event: { type: "workflow_heartbeat", runId, rootRunId: this.rootRunId(run), scheduledAt, intervalMinutes }
1197
+ });
1198
+ }
1199
+ beginRecovery() {
1200
+ this.recoveryDepth++;
1201
+ if (this.recoveryDepth === 1)
1202
+ this.emit({ kind: "availability" });
1203
+ let ended = false;
1204
+ return () => {
1205
+ if (ended)
1206
+ return;
1207
+ ended = true;
1208
+ this.capture();
1209
+ this.recoveryDepth--;
1210
+ if (!this.recovering)
1211
+ this.emit({ kind: "availability" });
1212
+ };
1213
+ }
1214
+ capture() {
1215
+ const next = new Map;
1216
+ const visit = (key, target, historical = false) => {
1217
+ next.set(key, target);
1218
+ const previous = this.previous.get(key);
1219
+ if (!historical && this.liveRunIds.has(target.runId) && previous?.status !== target.status) {
1220
+ this.lifecycle(previous && previous.kind !== "prompt" && target.kind !== "prompt" ? { ...target, previousStatus: previous.status } : target, this.runs().find((run) => run.id === target.runId)?.origin);
1221
+ }
1222
+ };
1223
+ for (const run of this.runs()) {
1224
+ const existing = this.previous.has(`run:${run.id}`);
1225
+ visit(`run:${run.id}`, { kind: "run", runId: run.id, status: run.status });
1226
+ for (const stage of run.stages) {
1227
+ visit(`stage:${workflowActivityNodeKey(run.id, stage.id)}`, { kind: "stage", runId: run.id, stageId: stage.id, stageName: stage.name, status: stage.status }, !existing);
1228
+ if (stage.pendingPrompt)
1229
+ visit(`prompt:${stage.pendingPrompt.id}`, {
1230
+ kind: "prompt",
1231
+ runId: run.id,
1232
+ stageId: stage.id,
1233
+ promptId: stage.pendingPrompt.id,
1234
+ status: "opened"
1235
+ }, !existing);
1236
+ }
1237
+ for (const tool of run.toolNodes)
1238
+ visit(`tool:${workflowActivityNodeKey(run.id, tool.id)}`, { kind: "tool", runId: run.id, toolNodeId: tool.id, toolName: tool.name, status: tool.status }, !existing);
1239
+ if (run.pendingPrompt)
1240
+ visit(`prompt:${run.pendingPrompt.id}`, { kind: "prompt", runId: run.id, promptId: run.pendingPrompt.id, status: "opened" }, !existing);
1241
+ }
1242
+ this.previous = next;
1243
+ }
1244
+ }
1245
+ var workflowObservationRuntimeKey = Symbol.for("atomic-workflows/store-observation-runtime@1");
1246
+ function canonicalTarget(target, rootRunId) {
1247
+ if (target.runId === rootRunId)
1248
+ return target;
1249
+ switch (target.kind) {
1250
+ case "stage":
1251
+ return { ...target, stageId: workflowActivityNodeKey(target.runId, target.stageId) };
1252
+ case "tool":
1253
+ return { ...target, toolNodeId: workflowActivityNodeKey(target.runId, target.toolNodeId) };
1254
+ case "prompt":
1255
+ return target.stageId === undefined ? target : { ...target, stageId: workflowActivityNodeKey(target.runId, target.stageId) };
1256
+ case "run":
1257
+ return target;
1258
+ }
1259
+ }
1260
+
1261
+ // dist/builtin/workflows/src/shared/store-internal.ts
1262
+ var TERMINAL_STATUSES = new Set([
1263
+ "completed",
1264
+ "failed",
1265
+ "killed",
1266
+ "skipped",
1267
+ "cancelled",
1268
+ "blocked"
1269
+ ]);
1270
+ function isTerminalStageStatus(status) {
1271
+ return status === "completed" || status === "failed" || status === "skipped";
1272
+ }
1273
+ function cannotAwaitInput(status) {
1274
+ return isTerminalStageStatus(status) || status === "paused" || status === "blocked";
1275
+ }
1276
+ function cannotBlock(status) {
1277
+ return isTerminalStageStatus(status) || status === "paused";
1278
+ }
1279
+ function cannotPause(status) {
1280
+ return isTerminalStageStatus(status) || status === "paused" || status === "blocked";
1281
+ }
1282
+ function clearRunFailureMetadata(run) {
1283
+ delete run.error;
1284
+ delete run.failureKind;
1285
+ delete run.failureCode;
1286
+ delete run.failureRecoverability;
1287
+ delete run.failureDisposition;
1288
+ delete run.failureMessage;
1289
+ delete run.failedStageId;
1290
+ delete run.failedToolNodeId;
1291
+ delete run.resumable;
1292
+ delete run.retryAfterMs;
1293
+ delete run.blockedAt;
1294
+ delete run.exited;
1295
+ delete run.exitReason;
1296
+ }
1297
+ function clearStaleBlockedRunMetadata(run, metadata) {
1298
+ if (metadata?.failureKind === undefined)
1299
+ delete run.failureKind;
1300
+ if (metadata?.failureCode === undefined)
1301
+ delete run.failureCode;
1302
+ if (metadata?.failureRecoverability === undefined)
1303
+ delete run.failureRecoverability;
1304
+ if (metadata?.failureDisposition === undefined)
1305
+ delete run.failureDisposition;
1306
+ if (metadata?.failureMessage === undefined)
1307
+ delete run.failureMessage;
1308
+ if (metadata?.failedStageId === undefined)
1309
+ delete run.failedStageId;
1310
+ if (metadata?.failedToolNodeId === undefined)
1311
+ delete run.failedToolNodeId;
1312
+ if (metadata?.resumable === undefined)
1313
+ delete run.resumable;
1314
+ if (metadata?.retryAfterMs === undefined)
1315
+ delete run.retryAfterMs;
1316
+ if (metadata?.exited === undefined)
1317
+ delete run.exited;
1318
+ if (metadata?.exitReason === undefined)
1319
+ delete run.exitReason;
1320
+ }
1321
+ function applyRunEndMetadata(run, metadata) {
1322
+ if (metadata.failureKind !== undefined)
1323
+ run.failureKind = metadata.failureKind;
1324
+ if (metadata.failureCode !== undefined)
1325
+ run.failureCode = metadata.failureCode;
1326
+ if (metadata.failureRecoverability !== undefined)
1327
+ run.failureRecoverability = metadata.failureRecoverability;
1328
+ if (metadata.failureDisposition !== undefined)
1329
+ run.failureDisposition = metadata.failureDisposition;
1330
+ if (metadata.retryAfterMs !== undefined)
1331
+ run.retryAfterMs = metadata.retryAfterMs;
1332
+ if (metadata.failureMessage !== undefined)
1333
+ run.failureMessage = metadata.failureMessage;
1334
+ if (metadata.failedStageId !== undefined)
1335
+ run.failedStageId = metadata.failedStageId;
1336
+ if (metadata.failedToolNodeId !== undefined)
1337
+ run.failedToolNodeId = metadata.failedToolNodeId;
1338
+ if (metadata.resumable !== undefined)
1339
+ run.resumable = metadata.resumable;
1340
+ if (metadata.exited !== undefined)
1341
+ run.exited = metadata.exited;
1342
+ if (metadata.exitReason !== undefined)
1343
+ run.exitReason = metadata.exitReason;
1344
+ }
1345
+ function createStoreState() {
1346
+ return {
1347
+ runs: [],
1348
+ notices: [],
1349
+ listeners: new Set,
1350
+ invalidationListeners: new Set,
1351
+ resolvers: new Map,
1352
+ stagePromptAnswers: new Map,
1353
+ stagePromptDrafts: new Map,
1354
+ version: 0
1355
+ };
1356
+ }
1357
+ function createStoreContext(state = createStoreState()) {
1358
+ let cachedGraphVersion = -1;
1359
+ let cachedGraphSnapshot;
1360
+ const observation = new WorkflowObservationRuntime(() => state.runs, bumpAndNotify);
1361
+ function snapshot() {
1362
+ return JSON.parse(JSON.stringify({ runs: state.runs, notices: state.notices, version: state.version }));
1363
+ }
1364
+ function graphSnapshot() {
1365
+ if (cachedGraphSnapshot === undefined || cachedGraphVersion !== state.version) {
1366
+ cachedGraphSnapshot = createGraphStoreSnapshot(state.runs, state.notices, state.version);
1367
+ cachedGraphVersion = state.version;
1368
+ }
1369
+ return cachedGraphSnapshot;
1370
+ }
1371
+ function notify() {
1372
+ observation.capture();
1373
+ for (const fn of state.invalidationListeners) {
1374
+ try {
1375
+ fn();
1376
+ } catch {}
1377
+ }
1378
+ if (state.listeners.size > 0) {
1379
+ const snap = snapshot();
1380
+ for (const fn of state.listeners) {
1381
+ try {
1382
+ fn(snap);
1383
+ } catch {}
1384
+ }
1385
+ }
1386
+ }
1387
+ function bumpAndNotify() {
1388
+ state.version++;
1389
+ notify();
1390
+ }
1391
+ function findRun(runId) {
1392
+ return state.runs.find((r) => r.id === runId);
1393
+ }
1394
+ function findStage(run, stageId) {
1395
+ return run.stages.find((s) => s.id === stageId);
1396
+ }
1397
+ function rejectPrompt(promptId, reason) {
1398
+ const entry = state.resolvers.get(promptId);
1399
+ if (!entry)
1400
+ return;
1401
+ state.resolvers.delete(promptId);
1402
+ entry.reject(new Error(reason));
1403
+ }
1404
+ function stagePromptAnswerKey(runId, stageId) {
1405
+ return JSON.stringify([runId, stageId]);
1406
+ }
1407
+ function stagePromptDraftKey(runId, stageId, promptId) {
1408
+ return JSON.stringify([runId, stageId, promptId]);
1409
+ }
1410
+ function stageHasActiveTextPrompt(runId, stageId, promptId) {
1411
+ const run = findRun(runId);
1412
+ if (!run || TERMINAL_STATUSES.has(run.status))
1413
+ return;
1414
+ const stage = findStage(run, stageId);
1415
+ if (!stage || isTerminalStageStatus(stage.status))
1416
+ return;
1417
+ const prompt = stage.pendingPrompt;
1418
+ if (!prompt || prompt.id !== promptId)
1419
+ return;
1420
+ if (prompt.kind !== "input" && prompt.kind !== "editor")
1421
+ return;
1422
+ return { prompt };
1423
+ }
1424
+ function rejectStagePrompt(runId, stage, reason) {
1425
+ const prompt = stage.pendingPrompt;
1426
+ if (!prompt)
1427
+ return;
1428
+ observation.lifecycle({ kind: "prompt", runId, stageId: stage.id, promptId: prompt.id, status: "cancelled" });
1429
+ stage.pendingPrompt = undefined;
1430
+ state.stagePromptDrafts.delete(stagePromptDraftKey(runId, stage.id, prompt.id));
1431
+ rejectPrompt(prompt.id, reason);
1432
+ }
1433
+ function rejectAllStagePrompts(runId, run, reason) {
1434
+ for (const stage of run.stages) {
1435
+ rejectStagePrompt(runId, stage, reason);
1436
+ }
1437
+ }
1438
+ return {
1439
+ state,
1440
+ observation,
1441
+ snapshot,
1442
+ graphSnapshot,
1443
+ notify,
1444
+ bumpAndNotify,
1445
+ findRun,
1446
+ findStage,
1447
+ rejectPrompt,
1448
+ rejectStagePrompt,
1449
+ rejectAllStagePrompts,
1450
+ stagePromptAnswerKey,
1451
+ stagePromptDraftKey,
1452
+ stageHasActiveTextPrompt
1453
+ };
1454
+ }
1455
+
1456
+ // dist/builtin/workflows/src/shared/pending-stage-retention.ts
1457
+ var PENDING_STAGE_SETTLED_MESSAGE_LIMIT = 50;
1458
+ async function retainPendingStageMessages(messages, archive) {
1459
+ const settled = messages.filter((entry) => entry.status === "delivered" || entry.status === "undeliverable" && entry.undeliverableNotifiedAt !== undefined);
1460
+ const expired = new Set(settled.slice(0, Math.max(0, settled.length - PENDING_STAGE_SETTLED_MESSAGE_LIMIT)));
1461
+ for (const entry of expired)
1462
+ await archive(entry);
1463
+ return expired.size === 0 ? messages : messages.filter((entry) => !expired.has(entry));
1464
+ }
1465
+
1466
+ // dist/builtin/workflows/src/shared/store-pending-stage-delivery-methods.ts
1467
+ function createPendingStageDeliveryStoreMethods(context) {
1468
+ const transitions = new Map;
1469
+ const serialize = async (runId, transition) => {
1470
+ const previous = transitions.get(runId) ?? Promise.resolve();
1471
+ const result = previous.catch(() => {
1472
+ return;
1473
+ }).then(transition);
1474
+ const settled = result.then(() => {
1475
+ return;
1476
+ }, () => {
1477
+ return;
1478
+ });
1479
+ transitions.set(runId, settled);
1480
+ settled.finally(() => {
1481
+ if (transitions.get(runId) === settled)
1482
+ transitions.delete(runId);
1483
+ });
1484
+ return await result;
1485
+ };
1486
+ return {
1487
+ async queueStageMessage(input, senderGroup, runGroup, backend) {
1488
+ return await serialize(input.runId, async () => {
1489
+ const run = context.findRun(input.runId);
1490
+ if (run === undefined)
1491
+ return;
1492
+ const stageIdentity = resolvePendingStageIdentity(run, input.stageKey);
1493
+ const receipt = await backend.readSettledPendingStageMessage?.(input.runId, input.message.id);
1494
+ const result = queueStageMessage(receipt === undefined ? run.pendingStageMessages ?? [] : [...run.pendingStageMessages ?? [], receipt], input, senderGroup, runGroup, stageIdentity);
1495
+ if (result.ok && !result.deduplicated) {
1496
+ const messages = await persistTransition(backend, input.runId, result.messages, context);
1497
+ run.pendingStageMessages = [...messages];
1498
+ context.bumpAndNotify();
1499
+ }
1500
+ return result.ok ? { ...result, messages: run.pendingStageMessages ?? [] } : result;
1501
+ });
1502
+ },
1503
+ async validateLiveStageMessage(input) {
1504
+ return await serialize(input.runId, async () => {
1505
+ const run = context.findRun(input.runId);
1506
+ if (run === undefined)
1507
+ return;
1508
+ const availableBackend = availableRunDurableBackend(context.state.runs, input.runId) ?? context.backend;
1509
+ const backend = availableBackend === undefined ? undefined : durableBackendForRun(availableBackend, context.state.runs, input.runId);
1510
+ const receipt = await backend?.readSettledPendingStageMessage?.(input.runId, input.message.id);
1511
+ const result = queueStageMessage(receipt === undefined ? run.pendingStageMessages ?? [] : [...run.pendingStageMessages ?? [], receipt], input, undefined, undefined, resolvePendingStageIdentity(run, input.stageKey));
1512
+ if (!result.ok) {
1513
+ return result.reason === "message_id_conflict" ? { outcome: "message_id_conflict", messageId: result.messageId } : { outcome: "forward" };
1514
+ }
1515
+ if (!result.deduplicated)
1516
+ return { outcome: "forward" };
1517
+ if (result.entry.status === "delivered")
1518
+ return { outcome: "delivered" };
1519
+ if (result.entry.status === "undeliverable") {
1520
+ return { outcome: "undeliverable", reason: result.entry.undeliverableReason };
1521
+ }
1522
+ if (result.position === undefined) {
1523
+ throw new Error(`atomic-workflows: queued message ${input.message.id} has no active position`);
1524
+ }
1525
+ return { outcome: "queued", position: result.position };
1526
+ });
1527
+ },
1528
+ pendingStageMessagesFor(runId, stageKey) {
1529
+ const run = context.findRun(runId);
1530
+ return pendingStageMessagesFor(run?.pendingStageMessages ?? [], runId, stageKey, run === undefined ? undefined : resolvePendingStageIdentity(run, stageKey));
1531
+ },
1532
+ async markPendingStageMessageDelivered(runId, stageKey, messageId, deliveredAt, backend) {
1533
+ return await serialize(runId, async () => {
1534
+ const run = context.findRun(runId);
1535
+ if (run === undefined)
1536
+ return false;
1537
+ const current = run.pendingStageMessages ?? [];
1538
+ const next = markPendingStageMessageDelivered(current, runId, stageKey, messageId, deliveredAt, resolvePendingStageIdentity(run, stageKey));
1539
+ if (next === current)
1540
+ return false;
1541
+ const messages = await persistTransition(backend, runId, next, context);
1542
+ run.pendingStageMessages = [...messages];
1543
+ context.bumpAndNotify();
1544
+ return true;
1545
+ });
1546
+ },
1547
+ async markPendingStageMessageUndeliverable(runId, stageKey, messageId, reason, backend) {
1548
+ return await serialize(runId, async () => {
1549
+ const run = context.findRun(runId);
1550
+ if (run === undefined)
1551
+ return false;
1552
+ const current = run.pendingStageMessages ?? [];
1553
+ const next = markPendingStageMessageUndeliverable(current, runId, stageKey, messageId, reason, resolvePendingStageIdentity(run, stageKey));
1554
+ if (next === current)
1555
+ return false;
1556
+ const messages = await persistTransition(backend, runId, next, context);
1557
+ run.pendingStageMessages = [...messages];
1558
+ context.bumpAndNotify();
1559
+ return true;
1560
+ });
1561
+ },
1562
+ async markPendingStageMessageUndeliverableNotified(runId, stageKey, messageId, notificationId, notifiedAt, backend) {
1563
+ return await serialize(runId, async () => {
1564
+ const run = context.findRun(runId);
1565
+ if (run === undefined)
1566
+ return false;
1567
+ const current = run.pendingStageMessages ?? [];
1568
+ const next = markPendingStageMessageUndeliverableNotified(current, runId, stageKey, messageId, notificationId, notifiedAt);
1569
+ if (next === current)
1570
+ return false;
1571
+ const messages = await persistTransition(backend, runId, next, context);
1572
+ run.pendingStageMessages = [...messages];
1573
+ context.bumpAndNotify();
1574
+ return true;
1575
+ });
1576
+ },
1577
+ async queueStickyStageMessage(input, senderGroup, runGroup, backend) {
1578
+ return await serialize(input.runId, async () => {
1579
+ const run = context.findRun(input.runId);
1580
+ if (run === undefined)
1581
+ return;
1582
+ const receipt = await backend.readSettledPendingStageMessage?.(input.runId, input.message.id);
1583
+ const result = queueStickyStageMessage(receipt === undefined ? run.pendingStageMessages ?? [] : [...run.pendingStageMessages ?? [], receipt], input, senderGroup, runGroup);
1584
+ if (result.ok && !result.deduplicated) {
1585
+ const messages = await persistTransition(backend, input.runId, result.messages, context);
1586
+ run.pendingStageMessages = [...messages];
1587
+ context.bumpAndNotify();
1588
+ }
1589
+ return result.ok ? { ...result, messages: run.pendingStageMessages ?? [] } : result;
1590
+ });
1591
+ },
1592
+ async recordPendingStageMessageDeliveries(runId, messageId, records, deliveredAt, backend) {
1593
+ return await serialize(runId, async () => {
1594
+ const run = context.findRun(runId);
1595
+ if (run === undefined)
1596
+ return false;
1597
+ if (records.length === 0)
1598
+ await backend.readPendingStageMessageDeliveryCount?.(runId, messageId, runId);
1599
+ let current = reconcileDeliveryCounts(backend, runId, run.pendingStageMessages ?? []);
1600
+ const unconfirmedRecords = [];
1601
+ for (const record of records) {
1602
+ const contextReceipt = record.admission === "transport" ? { ...record, admission: "context" } : undefined;
1603
+ if (!await backend.hasPendingStageDeliveryReceipt?.(runId, messageId, record) && (contextReceipt === undefined || !current.find((entry) => entry.id === messageId)?.deliveries?.some((delivery) => delivery.runId === record.runId && delivery.stageId === record.stageId && delivery.sessionId === record.sessionId && delivery.admission === "context") && !await backend.hasPendingStageDeliveryReceipt?.(runId, messageId, contextReceipt))) {
1604
+ unconfirmedRecords.push(record);
1605
+ }
1606
+ }
1607
+ current = reconcileDeliveryCounts(backend, runId, current);
1608
+ if (current !== run.pendingStageMessages) {
1609
+ run.pendingStageMessages = [...current];
1610
+ context.bumpAndNotify();
1611
+ }
1612
+ const next = recordPendingStageMessageDeliveries(current, runId, messageId, unconfirmedRecords, deliveredAt);
1613
+ if (next === current)
1614
+ return false;
1615
+ const messages = await persistTransition(backend, runId, next, context);
1616
+ run.pendingStageMessages = [...messages];
1617
+ context.bumpAndNotify();
1618
+ return true;
1619
+ });
1620
+ },
1621
+ async settleStickyPendingStageMessageDelivered(runId, messageId, settledAt, backend) {
1622
+ return await serialize(runId, async () => {
1623
+ const run = context.findRun(runId);
1624
+ if (run === undefined)
1625
+ return false;
1626
+ await backend.readPendingStageMessageDeliveryCount?.(runId, messageId, runId);
1627
+ const current = reconcileDeliveryCounts(backend, runId, run.pendingStageMessages ?? []);
1628
+ const next = settleStickyPendingStageMessageDelivered(current, runId, messageId, settledAt);
1629
+ if (next === current)
1630
+ return false;
1631
+ const messages = await persistTransition(backend, runId, next, context);
1632
+ run.pendingStageMessages = [...messages];
1633
+ context.bumpAndNotify();
1634
+ return true;
1635
+ });
1636
+ }
1637
+ };
1638
+ }
1639
+ function resolvePendingStageIdentity(run, stageKey) {
1640
+ const exactIds = run.stages.filter((stage) => stage.id === stageKey);
1641
+ const candidates = exactIds.length > 0 ? exactIds : run.stages.filter((stage) => stage.name === stageKey);
1642
+ if (candidates.length !== 1)
1643
+ return;
1644
+ const stage = candidates[0];
1645
+ return {
1646
+ id: stage.id,
1647
+ ...stage.replayKey !== undefined ? { replayKey: stage.replayKey } : {},
1648
+ aliases: stage.id === stage.name ? [stage.id] : [stage.id, stage.name]
1649
+ };
1650
+ }
1651
+ async function persistTransition(backend, runId, messages, context) {
1652
+ let retained = reconcileDeliveryCounts(backend, runId, messages);
1653
+ try {
1654
+ if (backend.archivePendingStageDeliveryReceipt !== undefined && backend.hasPendingStageDeliveryReceipt !== undefined) {
1655
+ const compacted = [];
1656
+ for (const entry of retained) {
1657
+ if (entry.sticky !== true || entry.deliveries === undefined) {
1658
+ compacted.push(entry);
1659
+ continue;
1660
+ }
1661
+ const latest = new Map;
1662
+ entry.deliveries.forEach((delivery, index) => {
1663
+ latest.set(JSON.stringify([delivery.runId, delivery.stageId, delivery.admission]), index);
1664
+ });
1665
+ const deliveries = [];
1666
+ let archivedThrough = -1;
1667
+ for (let index = 0;index < entry.deliveries.length; index++) {
1668
+ const delivery = entry.deliveries[index];
1669
+ const stage = context.state.runs.find((run) => run.id === delivery.runId)?.stages.find((stage) => stage.id === delivery.stageId);
1670
+ if (entry.status !== "queued" || stage?.status === "completed" || stage?.status === "skipped" || stage?.status === "failed" || latest.get(JSON.stringify([delivery.runId, delivery.stageId, delivery.admission])) !== index && delivery.sessionId !== undefined) {
1671
+ while (archivedThrough < index) {
1672
+ const prefixIndex = archivedThrough + 1;
1673
+ await backend.archivePendingStageDeliveryReceipt(runId, entry.id, entry.deliveries[prefixIndex], {
1674
+ messageRunId: entry.runId,
1675
+ deliveryCount: (entry.deliveryCount ?? entry.deliveries.length) - entry.deliveries.length + prefixIndex + 1
1676
+ });
1677
+ archivedThrough = prefixIndex;
1678
+ }
1679
+ } else {
1680
+ deliveries.push(delivery);
1681
+ }
1682
+ }
1683
+ compacted.push(deliveries.length === entry.deliveries.length ? entry : { ...entry, deliveries });
1684
+ }
1685
+ retained = compacted;
1686
+ }
1687
+ retained = compactStickyStageMessageDeliveries(retained, context.state.runs);
1688
+ if (backend.archivePendingStageMessage !== undefined && backend.readSettledPendingStageMessage !== undefined) {
1689
+ retained = await retainPendingStageMessages(retained, (entry) => backend.archivePendingStageMessage(runId, entry));
1690
+ }
1691
+ if (!await backend.persistPendingStageMessages(runId, retained)) {
1692
+ throw new Error(`atomic-workflows: durable workflow ${runId} is unavailable for pending-stage persistence`);
1693
+ }
1694
+ return retained;
1695
+ } finally {
1696
+ const run = context.findRun(runId);
1697
+ if (run !== undefined) {
1698
+ const current = run.pendingStageMessages ?? [];
1699
+ const recovered = reconcileDeliveryCounts(backend, runId, current);
1700
+ if (recovered !== current) {
1701
+ run.pendingStageMessages = [...recovered];
1702
+ context.bumpAndNotify();
1703
+ }
1704
+ }
1705
+ }
1706
+ }
1707
+ function reconcileDeliveryCounts(backend, runId, messages) {
1708
+ let changed = false;
1709
+ const recovered = messages.map((entry) => {
1710
+ if (entry.sticky !== true)
1711
+ return entry;
1712
+ const count = backend.getPendingStageMessageDeliveryCount?.(runId, entry.id, entry.runId) ?? 0;
1713
+ if (count <= (entry.deliveryCount ?? entry.deliveries?.length ?? 0))
1714
+ return entry;
1715
+ changed = true;
1716
+ return { ...entry, deliveryCount: count };
1717
+ });
1718
+ return changed ? recovered : messages;
1719
+ }
1720
+
1721
+ // dist/builtin/workflows/src/shared/store-prompt-methods.ts
1722
+ function createPromptStoreMethods(context) {
1723
+ const { state } = context;
1724
+ return {
1725
+ recordPendingPrompt(runId, prompt) {
1726
+ const run = context.findRun(runId);
1727
+ if (!run)
1728
+ return false;
1729
+ if (TERMINAL_STATUSES.has(run.status))
1730
+ return false;
1731
+ if (run.pendingPrompt !== undefined)
1732
+ return false;
1733
+ run.pendingPrompt = { ...prompt };
1734
+ context.bumpAndNotify();
1735
+ return true;
1736
+ },
1737
+ resolvePendingPrompt(runId, promptId, response) {
1738
+ const run = context.findRun(runId);
1739
+ if (!run)
1740
+ return false;
1741
+ const pending = run.pendingPrompt;
1742
+ if (!pending || pending.id !== promptId)
1743
+ return false;
1744
+ context.observation.lifecycle({ kind: "prompt", runId, promptId, status: "answered" });
1745
+ run.pendingPrompt = undefined;
1746
+ context.bumpAndNotify();
1747
+ const entry = state.resolvers.get(promptId);
1748
+ if (entry) {
1749
+ state.resolvers.delete(promptId);
1750
+ entry.resolve(response);
1751
+ }
1752
+ return true;
1753
+ },
1754
+ awaitPendingPrompt(runId, promptId) {
1755
+ return new Promise((resolve, reject) => {
1756
+ const run = context.findRun(runId);
1757
+ if (!run) {
1758
+ reject(new Error(`atomic-workflows: run "${runId}" not found`));
1759
+ return;
1760
+ }
1761
+ const pending = run.pendingPrompt;
1762
+ if (!pending || pending.id !== promptId) {
1763
+ reject(new Error(`atomic-workflows: pending prompt "${promptId}" not registered on run "${runId}"`));
1764
+ return;
1765
+ }
1766
+ state.resolvers.set(promptId, { promptId, resolve, reject });
1767
+ });
1768
+ },
1769
+ recordStagePendingPrompt(runId, stageId, prompt) {
1770
+ const run = context.findRun(runId);
1771
+ if (!run)
1772
+ return false;
1773
+ if (TERMINAL_STATUSES.has(run.status))
1774
+ return false;
1775
+ const stage = context.findStage(run, stageId);
1776
+ if (!stage)
1777
+ return false;
1778
+ if (isTerminalStageStatus(stage.status))
1779
+ return false;
1780
+ if (stage.pendingPrompt !== undefined)
1781
+ return false;
1782
+ stage.pendingPrompt = { ...prompt };
1783
+ stage.promptFootprint = { ...prompt };
1784
+ stage.status = "awaiting_input";
1785
+ stage.awaitingInputSince = prompt.createdAt;
1786
+ context.bumpAndNotify();
1787
+ return true;
1788
+ },
1789
+ resolveStagePendingPrompt(runId, stageId, promptId, response, options = {}) {
1790
+ const run = context.findRun(runId);
1791
+ if (!run)
1792
+ return false;
1793
+ const stage = context.findStage(run, stageId);
1794
+ if (!stage)
1795
+ return false;
1796
+ const pending = stage.pendingPrompt;
1797
+ if (!pending || pending.id !== promptId)
1798
+ return false;
1799
+ state.stagePromptDrafts.delete(context.stagePromptDraftKey(runId, stageId, promptId));
1800
+ if (options.recordAnswer !== false) {
1801
+ state.stagePromptAnswers.set(context.stagePromptAnswerKey(runId, stageId), {
1802
+ runId,
1803
+ stageId,
1804
+ promptId,
1805
+ kind: pending.kind,
1806
+ value: response,
1807
+ answeredAt: Date.now(),
1808
+ ...options.answerSource !== undefined ? { answerSource: options.answerSource } : {}
1809
+ });
1810
+ stage.promptAnswerState = "available";
1811
+ } else {
1812
+ state.stagePromptAnswers.delete(context.stagePromptAnswerKey(runId, stageId));
1813
+ delete stage.promptAnswerState;
1814
+ }
1815
+ context.observation.lifecycle({
1816
+ kind: "prompt",
1817
+ runId,
1818
+ stageId,
1819
+ promptId,
1820
+ status: options.recordAnswer === false ? "cancelled" : "answered"
1821
+ });
1822
+ stage.pendingPrompt = undefined;
1823
+ if (stage.status === "awaiting_input") {
1824
+ stage.status = "running";
1825
+ delete stage.awaitingInputSince;
1826
+ }
1827
+ context.bumpAndNotify();
1828
+ const entry = state.resolvers.get(promptId);
1829
+ if (entry) {
1830
+ state.resolvers.delete(promptId);
1831
+ entry.resolve(response);
1832
+ }
1833
+ return true;
1834
+ },
1835
+ awaitStagePendingPrompt(runId, stageId, promptId) {
1836
+ return new Promise((resolve, reject) => {
1837
+ const run = context.findRun(runId);
1838
+ if (!run) {
1839
+ reject(new Error(`atomic-workflows: run "${runId}" not found`));
1840
+ return;
1841
+ }
1842
+ const stage = context.findStage(run, stageId);
1843
+ if (!stage) {
1844
+ reject(new Error(`atomic-workflows: stage "${stageId}" not found on run "${runId}"`));
1845
+ return;
1846
+ }
1847
+ const pending = stage.pendingPrompt;
1848
+ if (!pending || pending.id !== promptId) {
1849
+ reject(new Error(`atomic-workflows: pending prompt "${promptId}" not registered on stage "${stageId}" in run "${runId}"`));
1850
+ return;
1851
+ }
1852
+ state.resolvers.set(promptId, { promptId, resolve, reject });
1853
+ });
1854
+ },
1855
+ recordStagePromptAnswer(runId, stageId, prompt, response, options = {}) {
1856
+ const run = context.findRun(runId);
1857
+ if (!run)
1858
+ return false;
1859
+ if (TERMINAL_STATUSES.has(run.status))
1860
+ return false;
1861
+ const stage = context.findStage(run, stageId);
1862
+ if (!stage)
1863
+ return false;
1864
+ if (isTerminalStageStatus(stage.status))
1865
+ return false;
1866
+ state.stagePromptAnswers.set(context.stagePromptAnswerKey(runId, stageId), {
1867
+ runId,
1868
+ stageId,
1869
+ promptId: prompt.id,
1870
+ kind: prompt.kind,
1871
+ value: response,
1872
+ answeredAt: Date.now(),
1873
+ ...options.answerSource !== undefined ? { answerSource: options.answerSource } : {}
1874
+ });
1875
+ if (stage.promptFootprint === undefined)
1876
+ stage.promptFootprint = { ...prompt };
1877
+ stage.promptAnswerState = "available";
1878
+ if (stage.status === "awaiting_input") {
1879
+ stage.status = "running";
1880
+ delete stage.awaitingInputSince;
1881
+ }
1882
+ context.bumpAndNotify();
1883
+ return true;
1884
+ },
1885
+ recordStagePromptDraft(runId, stageId, promptId, text) {
1886
+ if (context.stageHasActiveTextPrompt(runId, stageId, promptId) === undefined)
1887
+ return false;
1888
+ state.stagePromptDrafts.set(context.stagePromptDraftKey(runId, stageId, promptId), text);
1889
+ return true;
1890
+ },
1891
+ getStagePromptDraft(runId, stageId, promptId) {
1892
+ if (context.stageHasActiveTextPrompt(runId, stageId, promptId) === undefined)
1893
+ return;
1894
+ return state.stagePromptDrafts.get(context.stagePromptDraftKey(runId, stageId, promptId));
1895
+ },
1896
+ clearStagePromptDraft(runId, stageId, promptId) {
1897
+ return state.stagePromptDrafts.delete(context.stagePromptDraftKey(runId, stageId, promptId));
1898
+ },
1899
+ getStagePromptAnswer(runId, stageId) {
1900
+ return state.stagePromptAnswers.get(context.stagePromptAnswerKey(runId, stageId));
1901
+ },
1902
+ clearStagePromptAnswer(runId, stageId) {
1903
+ const removed = state.stagePromptAnswers.delete(context.stagePromptAnswerKey(runId, stageId));
1904
+ const run = context.findRun(runId);
1905
+ const stage = run ? context.findStage(run, stageId) : undefined;
1906
+ const clearAvailabilityMarker = stage?.promptAnswerState === "available";
1907
+ if (clearAvailabilityMarker) {
1908
+ delete stage.promptAnswerState;
1909
+ }
1910
+ if (removed || clearAvailabilityMarker) {
1911
+ context.bumpAndNotify();
1912
+ }
1913
+ }
1914
+ };
1915
+ }
1916
+
1917
+ // dist/builtin/workflows/src/shared/run-visibility.ts
1918
+ function isTopLevelWorkflowRun(run) {
1919
+ return run.parentRunId === undefined;
1920
+ }
1921
+
1922
+ // dist/builtin/workflows/src/shared/timing.ts
1923
+ function nonNegative(ms) {
1924
+ return Math.max(0, ms);
1925
+ }
1926
+ function nextControlTimestamp(requestedAt, previousAt) {
1927
+ const candidate = requestedAt ?? Date.now();
1928
+ return previousAt === undefined || candidate > previousAt ? candidate : previousAt + 1;
1929
+ }
1930
+ function elapsedFromStart(startedAt, now, pausedDurationMs, pausedAt) {
1931
+ const completedPausedSegment = pausedDurationMs ?? 0;
1932
+ const activePausedSegment = pausedAt === undefined ? 0 : nonNegative(now - pausedAt);
1933
+ return nonNegative(now - startedAt - completedPausedSegment - activePausedSegment);
1934
+ }
1935
+ function accumulatePausedDurationMs(pausedDurationMs, pausedAt, resumedAt) {
1936
+ if (pausedAt === undefined)
1937
+ return pausedDurationMs ?? 0;
1938
+ return (pausedDurationMs ?? 0) + nonNegative(resumedAt - pausedAt);
1939
+ }
1940
+ function elapsedRunMs(run, now = Date.now()) {
1941
+ if (run.durationMs !== undefined)
1942
+ return nonNegative(run.durationMs);
1943
+ const effectiveNow = run.endedAt ?? now;
1944
+ return nonNegative(run.accumulatedDurationMs ?? 0) + elapsedFromStart(run.startedAt, effectiveNow, run.pausedDurationMs, run.pausedAt);
1945
+ }
1946
+
1947
+ // dist/builtin/workflows/src/shared/store-run-methods.ts
1948
+ function createRunStoreMethods(context) {
1949
+ const { state } = context;
1950
+ return {
1951
+ runs() {
1952
+ return state.runs;
1953
+ },
1954
+ notices() {
1955
+ return state.notices;
1956
+ },
1957
+ activeRunId() {
1958
+ for (let i = state.runs.length - 1;i >= 0; i--) {
1959
+ const run = state.runs[i];
1960
+ if (run && isTopLevelWorkflowRun(run) && run.endedAt === undefined) {
1961
+ return run.id;
1962
+ }
1963
+ }
1964
+ for (let i = state.runs.length - 1;i >= 0; i--) {
1965
+ const run = state.runs[i];
1966
+ if (run && run.endedAt === undefined) {
1967
+ return run.id;
1968
+ }
1969
+ }
1970
+ return null;
1971
+ },
1972
+ recordRunStart(run) {
1973
+ const index = state.runs.findIndex((existing) => existing.id === run.id);
1974
+ if (index === -1)
1975
+ state.runs.push(run);
1976
+ else
1977
+ state.runs[index] = run;
1978
+ context.bumpAndNotify();
1979
+ },
1980
+ recordRunSummary(runId, summary, summarizedThrough) {
1981
+ const run = context.findRun(runId);
1982
+ if (!run)
1983
+ return;
1984
+ Object.assign(run, { summary, summarizedThrough });
1985
+ context.bumpAndNotify();
1986
+ },
1987
+ recordRunExecutionState(runId, update) {
1988
+ const run = context.findRun(runId);
1989
+ if (run === undefined || run.endedAt !== undefined)
1990
+ return;
1991
+ if (update.phase !== undefined && update.phase !== run.phase)
1992
+ run.phaseStartedAt = Date.now();
1993
+ Object.assign(run, update);
1994
+ context.bumpAndNotify();
1995
+ },
1996
+ reconcileRunParentStage(runId, expectedParentStageId, parentStageId) {
1997
+ const run = context.findRun(runId);
1998
+ if (run?.parentStageId !== expectedParentStageId || parentStageId === expectedParentStageId)
1999
+ return false;
2000
+ run.parentStageId = parentStageId;
2001
+ context.bumpAndNotify();
2002
+ return true;
2003
+ },
2004
+ recordRunEnd(runId, status, result, error, metadata) {
2005
+ const run = context.findRun(runId);
2006
+ if (!run)
2007
+ return false;
2008
+ if (TERMINAL_STATUSES.has(run.status))
2009
+ return false;
2010
+ run.status = status;
2011
+ run.endedAt = Date.now();
2012
+ if (run.phase !== undefined) {
2013
+ run.phase = "ended";
2014
+ run.phaseStartedAt = run.endedAt;
2015
+ }
2016
+ if (run.pausedAt !== undefined) {
2017
+ run.pausedDurationMs = accumulatePausedDurationMs(run.pausedDurationMs, run.pausedAt, run.endedAt);
2018
+ run.pausedAt = undefined;
2019
+ }
2020
+ run.durationMs = elapsedRunMs(run, run.endedAt);
2021
+ if (result !== undefined && shouldStoreRunResult(status))
2022
+ run.result = result;
2023
+ const wasBlocked = run.blockedAt !== undefined || run.failureDisposition === "active_blocked";
2024
+ delete run.blockedAt;
2025
+ if (status === "completed" || status === "skipped" || status === "cancelled" || status === "blocked") {
2026
+ clearRunFailureMetadata(run);
2027
+ if (status === "blocked" && error !== undefined)
2028
+ run.error = error;
2029
+ if (metadata !== undefined)
2030
+ applyRunEndMetadata(run, metadata);
2031
+ } else {
2032
+ if (wasBlocked && error === undefined)
2033
+ delete run.error;
2034
+ if ((status === "failed" || status === "killed") && error !== undefined) {
2035
+ run.error = error;
2036
+ }
2037
+ if (wasBlocked)
2038
+ clearStaleBlockedRunMetadata(run, metadata);
2039
+ if (metadata !== undefined)
2040
+ applyRunEndMetadata(run, metadata);
2041
+ if (run.failureDisposition === "active_blocked")
2042
+ delete run.failureDisposition;
2043
+ if (status === "killed") {
2044
+ run.failureRecoverability = "non_recoverable";
2045
+ run.failureDisposition = "terminal_killed";
2046
+ run.resumable = false;
2047
+ }
2048
+ }
2049
+ const pending = run.pendingPrompt;
2050
+ if (pending) {
2051
+ context.observation.lifecycle({ kind: "prompt", runId, promptId: pending.id, status: "cancelled" });
2052
+ run.pendingPrompt = undefined;
2053
+ context.rejectPrompt(pending.id, `atomic-workflows: run ${runId} ended before prompt resolved`);
2054
+ }
2055
+ context.rejectAllStagePrompts(runId, run, `atomic-workflows: run ${runId} ended before prompt resolved`);
2056
+ context.bumpAndNotify();
2057
+ return true;
2058
+ },
2059
+ recordRunBlocked(runId, error, metadata) {
2060
+ const run = context.findRun(runId);
2061
+ if (!run)
2062
+ return false;
2063
+ if (TERMINAL_STATUSES.has(run.status))
2064
+ return false;
2065
+ run.status = "running";
2066
+ run.error = error;
2067
+ run.failureKind = metadata.failureKind;
2068
+ run.failureCode = metadata.failureCode;
2069
+ run.failureRecoverability = metadata.failureRecoverability;
2070
+ run.failureDisposition = metadata.failureDisposition;
2071
+ run.failureMessage = metadata.failureMessage;
2072
+ if (metadata.failedStageId === undefined)
2073
+ delete run.failedStageId;
2074
+ else
2075
+ run.failedStageId = metadata.failedStageId;
2076
+ run.resumable = metadata.resumable;
2077
+ run.blockedAt = metadata.blockedAt ?? Date.now();
2078
+ if (metadata.endedAt !== undefined) {
2079
+ run.endedAt = metadata.endedAt;
2080
+ run.durationMs = elapsedRunMs(run, metadata.endedAt);
2081
+ }
2082
+ if (metadata.retryAfterMs !== undefined)
2083
+ run.retryAfterMs = metadata.retryAfterMs;
2084
+ if (metadata.result !== undefined)
2085
+ run.result = metadata.result;
2086
+ if (metadata.budgetState !== undefined)
2087
+ run.budgetState = metadata.budgetState;
2088
+ context.bumpAndNotify();
2089
+ return true;
2090
+ },
2091
+ restoreActiveBlockedRun(source, error, metadata) {
2092
+ const restored = {
2093
+ ...source,
2094
+ status: "running",
2095
+ error,
2096
+ resumable: metadata.resumable,
2097
+ failureRecoverability: metadata.failureRecoverability,
2098
+ failureDisposition: metadata.failureDisposition,
2099
+ blockedAt: metadata.blockedAt ?? Date.now(),
2100
+ stages: source.stages.map((stage) => ({ ...stage })),
2101
+ toolNodes: source.toolNodes.map((node) => ({ ...node }))
2102
+ };
2103
+ delete restored.endedAt;
2104
+ delete restored.durationMs;
2105
+ restored.failureKind = metadata.failureKind;
2106
+ restored.failureCode = metadata.failureCode;
2107
+ restored.failureMessage = metadata.failureMessage;
2108
+ if (metadata.failedStageId === undefined)
2109
+ delete restored.failedStageId;
2110
+ else
2111
+ restored.failedStageId = metadata.failedStageId;
2112
+ if (metadata.retryAfterMs !== undefined)
2113
+ restored.retryAfterMs = metadata.retryAfterMs;
2114
+ if (metadata.result !== undefined)
2115
+ restored.result = metadata.result;
2116
+ if (metadata.budgetState !== undefined)
2117
+ restored.budgetState = metadata.budgetState;
2118
+ const index = state.runs.findIndex((candidate) => candidate.id === source.id);
2119
+ if (index < 0)
2120
+ state.runs.push(restored);
2121
+ else
2122
+ state.runs[index] = restored;
2123
+ context.bumpAndNotify();
2124
+ return true;
2125
+ },
2126
+ removeRun(runId) {
2127
+ const index = state.runs.findIndex((r) => r.id === runId);
2128
+ if (index < 0)
2129
+ return false;
2130
+ const run = state.runs[index];
2131
+ const pending = run.pendingPrompt;
2132
+ if (pending) {
2133
+ context.observation.lifecycle({ kind: "prompt", runId, promptId: pending.id, status: "cancelled" });
2134
+ context.rejectPrompt(pending.id, `atomic-workflows: run ${runId} was removed before prompt resolved`);
2135
+ }
2136
+ context.rejectAllStagePrompts(runId, run, `atomic-workflows: run ${runId} was removed before prompt resolved`);
2137
+ for (const stage of run.stages) {
2138
+ state.stagePromptAnswers.delete(context.stagePromptAnswerKey(runId, stage.id));
2139
+ }
2140
+ state.runs.splice(index, 1);
2141
+ for (let i = state.notices.length - 1;i >= 0; i--) {
2142
+ if (state.notices[i]?.runId === runId)
2143
+ state.notices.splice(i, 1);
2144
+ }
2145
+ context.bumpAndNotify();
2146
+ return true;
2147
+ },
2148
+ recordNotice(notice) {
2149
+ state.notices.push(notice);
2150
+ context.bumpAndNotify();
2151
+ },
2152
+ ackNotice(id) {
2153
+ const notice = state.notices.find((n) => n.id === id);
2154
+ if (!notice || notice.ackedAt !== undefined)
2155
+ return false;
2156
+ notice.ackedAt = Date.now();
2157
+ context.bumpAndNotify();
2158
+ return true;
2159
+ },
2160
+ recordRunPaused(runId, pausedAt, metadata) {
2161
+ const run = context.findRun(runId);
2162
+ if (!run)
2163
+ return false;
2164
+ if (TERMINAL_STATUSES.has(run.status))
2165
+ return false;
2166
+ const wasPaused = run.status === "paused";
2167
+ if (!wasPaused) {
2168
+ run.status = "paused";
2169
+ run.pausedAt = nextControlTimestamp(pausedAt, run.resumedAt);
2170
+ run.resumedAt = undefined;
2171
+ delete run.pauseActor;
2172
+ delete run.resumeActor;
2173
+ delete run.resumeSource;
2174
+ }
2175
+ if (metadata?.resumable !== undefined)
2176
+ run.resumable = metadata.resumable;
2177
+ if (metadata?.exitReason !== undefined)
2178
+ run.exitReason = metadata.exitReason;
2179
+ if (metadata?.exitReason === "quit" && run.quitAt === undefined)
2180
+ run.quitAt = nextControlTimestamp(undefined, run.pausedAt);
2181
+ if (metadata?.actor !== undefined)
2182
+ run.pauseActor = metadata.actor;
2183
+ if (wasPaused && metadata === undefined)
2184
+ return false;
2185
+ context.bumpAndNotify();
2186
+ return true;
2187
+ },
2188
+ recordRunResumed(runId, resumedAt, metadata) {
2189
+ const run = context.findRun(runId);
2190
+ if (!run)
2191
+ return false;
2192
+ if (TERMINAL_STATUSES.has(run.status))
2193
+ return false;
2194
+ const claimsRunControl = metadata?.source === "run_control";
2195
+ if (run.status !== "paused") {
2196
+ if (!claimsRunControl || run.status !== "running" || run.resumedAt === undefined)
2197
+ return false;
2198
+ if (run.resumeSource === "run_control" && run.resumeActor === metadata?.actor)
2199
+ return false;
2200
+ run.resumeSource = "run_control";
2201
+ if (metadata?.actor === undefined)
2202
+ delete run.resumeActor;
2203
+ else
2204
+ run.resumeActor = metadata.actor;
2205
+ context.bumpAndNotify();
2206
+ return false;
2207
+ }
2208
+ const resumedTs = nextControlTimestamp(resumedAt, run.pausedAt);
2209
+ run.status = "running";
2210
+ run.pausedDurationMs = accumulatePausedDurationMs(run.pausedDurationMs, run.pausedAt, resumedTs);
2211
+ run.resumedAt = resumedTs;
2212
+ run.pausedAt = undefined;
2213
+ delete run.quitAt;
2214
+ delete run.exitReason;
2215
+ delete run.pauseActor;
2216
+ if (metadata === undefined) {
2217
+ delete run.resumeActor;
2218
+ delete run.resumeSource;
2219
+ } else {
2220
+ run.resumeSource = metadata.source;
2221
+ if (metadata.actor === undefined)
2222
+ delete run.resumeActor;
2223
+ else
2224
+ run.resumeActor = metadata.actor;
2225
+ }
2226
+ context.bumpAndNotify();
2227
+ return true;
2228
+ },
2229
+ clear() {
2230
+ if (state.runs.length === 0 && state.notices.length === 0 && state.resolvers.size === 0 && state.stagePromptAnswers.size === 0 && state.stagePromptDrafts.size === 0)
2231
+ return;
2232
+ state.runs.length = 0;
2233
+ state.notices.length = 0;
2234
+ for (const entry of state.resolvers.values()) {
2235
+ entry.reject(new Error("atomic-workflows: store cleared"));
2236
+ }
2237
+ state.resolvers.clear();
2238
+ state.stagePromptAnswers.clear();
2239
+ state.stagePromptDrafts.clear();
2240
+ context.bumpAndNotify();
2241
+ },
2242
+ snapshot() {
2243
+ return context.snapshot();
2244
+ },
2245
+ graphSnapshot() {
2246
+ return context.graphSnapshot();
2247
+ },
2248
+ subscribe(fn) {
2249
+ state.listeners.add(fn);
2250
+ return () => {
2251
+ state.listeners.delete(fn);
2252
+ };
2253
+ },
2254
+ subscribeInvalidation(fn) {
2255
+ state.invalidationListeners.add(fn);
2256
+ return () => state.invalidationListeners.delete(fn);
2257
+ }
2258
+ };
2259
+ }
2260
+ function shouldStoreRunResult(status) {
2261
+ return status === "completed" || status === "skipped" || status === "cancelled" || status === "blocked" || status === "failed";
2262
+ }
2263
+
2264
+ // dist/builtin/workflows/src/shared/store-tool-node-methods.ts
2265
+ function nextExecutionOrder(run) {
2266
+ const stageOrders = run.stages.map((stage) => stage.executionOrder ?? 0);
2267
+ const toolOrders = run.toolNodes.map((node) => node.executionOrder ?? 0);
2268
+ return Math.max(0, ...stageOrders, ...toolOrders) + 1;
2269
+ }
2270
+ function createToolNodeStoreMethods(context) {
2271
+ return {
2272
+ recordToolNodeStart(runId, node) {
2273
+ const run = context.findRun(runId);
2274
+ if (run === undefined || TERMINAL_STATUSES.has(run.status))
2275
+ return false;
2276
+ const nodes = run.toolNodes;
2277
+ if (nodes.some((candidate) => candidate.id === node.id))
2278
+ return false;
2279
+ if (node.executionOrder === undefined)
2280
+ node.executionOrder = nextExecutionOrder(run);
2281
+ nodes.push(node);
2282
+ context.bumpAndNotify();
2283
+ return true;
2284
+ },
2285
+ recordToolNodeRunning(runId, nodeId, startedAt) {
2286
+ const node = context.findRun(runId)?.toolNodes.find((candidate) => candidate.id === nodeId);
2287
+ if (node === undefined || node.status !== "pending")
2288
+ return false;
2289
+ node.status = "running";
2290
+ node.startedAt = startedAt;
2291
+ if (context.observation.liveRunIds.has(runId))
2292
+ context.observation.executingToolNodeIds.add(workflowActivityNodeKey(runId, nodeId));
2293
+ context.bumpAndNotify();
2294
+ return true;
2295
+ },
2296
+ recordToolNodeEnd(runId, nodeId, update) {
2297
+ const node = context.findRun(runId)?.toolNodes.find((candidate) => candidate.id === nodeId);
2298
+ if (node === undefined || node.status === "completed" || node.status === "failed" || node.status === "cached" || node.status === "cancelled")
2299
+ return false;
2300
+ context.observation.executingToolNodeIds.delete(workflowActivityNodeKey(runId, nodeId));
2301
+ node.status = update.status;
2302
+ if (update.endedAt !== undefined)
2303
+ node.endedAt = update.endedAt;
2304
+ if (update.durationMs !== undefined)
2305
+ node.durationMs = update.durationMs;
2306
+ if (update.result !== undefined)
2307
+ node.result = boundedToolPayload(update.result);
2308
+ if (update.resultSummary !== undefined)
2309
+ node.resultSummary = update.resultSummary;
2310
+ if (update.error !== undefined)
2311
+ node.error = update.error;
2312
+ context.bumpAndNotify();
2313
+ return true;
2314
+ }
2315
+ };
2316
+ }
2317
+
2318
+ // dist/builtin/workflows/src/shared/store-stage-methods.ts
2319
+ function createStageStoreMethods(context) {
2320
+ return {
2321
+ recordStageStart(runId, stage) {
2322
+ const run = context.findRun(runId);
2323
+ if (!run)
2324
+ return;
2325
+ if (stage.executionOrder === undefined)
2326
+ stage.executionOrder = nextExecutionOrder(run);
2327
+ if (!run.stages.some((s) => s.id === stage.id)) {
2328
+ run.stages.push(stage);
2329
+ }
2330
+ if (stage.status === "running" && context.observation.liveRunIds.has(runId)) {
2331
+ context.observation.executingStageIds.add(workflowActivityNodeKey(runId, stage.id));
2332
+ }
2333
+ context.bumpAndNotify();
2334
+ },
2335
+ recordStageWorkflowChildRun(runId, stageId, ref) {
2336
+ const run = context.findRun(runId);
2337
+ if (!run)
2338
+ return false;
2339
+ const stage = context.findStage(run, stageId);
2340
+ if (!stage)
2341
+ return false;
2342
+ const released = context.observation.executingStageIds.delete(workflowActivityNodeKey(runId, stageId));
2343
+ if (stage.workflowChildRun?.runId === ref.runId && stage.workflowChildRun.alias === ref.alias && stage.workflowChildRun.workflow === ref.workflow) {
2344
+ if (released)
2345
+ context.bumpAndNotify();
2346
+ return false;
2347
+ }
2348
+ stage.workflowChildRun = { ...ref };
2349
+ context.bumpAndNotify();
2350
+ return true;
2351
+ },
2352
+ recordToolStart(runId, stageId, evt) {
2353
+ const run = context.findRun(runId);
2354
+ if (!run)
2355
+ return;
2356
+ const stage = context.findStage(run, stageId);
2357
+ if (!stage)
2358
+ return;
2359
+ const exists = stage.toolEvents.some((e) => e.name === evt.name && e.startedAt === evt.startedAt);
2360
+ if (!exists) {
2361
+ stage.toolEvents.push(evt);
2362
+ }
2363
+ context.bumpAndNotify();
2364
+ },
2365
+ recordToolEnd(runId, stageId, evt) {
2366
+ const run = context.findRun(runId);
2367
+ if (!run)
2368
+ return;
2369
+ const stage = context.findStage(run, stageId);
2370
+ if (!stage)
2371
+ return;
2372
+ const existing = stage.toolEvents.find((e) => e.name === evt.name && e.startedAt === evt.startedAt);
2373
+ if (existing) {
2374
+ existing.endedAt = evt.endedAt;
2375
+ existing.output = evt.output;
2376
+ }
2377
+ context.bumpAndNotify();
2378
+ },
2379
+ recordStageEnd(runId, stage) {
2380
+ const run = context.findRun(runId);
2381
+ if (!run)
2382
+ return;
2383
+ const existing = context.findStage(run, stage.id);
2384
+ if (!existing)
2385
+ return;
2386
+ context.observation.executingStageIds.delete(workflowActivityNodeKey(runId, stage.id));
2387
+ existing.status = stage.status;
2388
+ existing.endedAt = stage.endedAt;
2389
+ if (existing.endedAt !== undefined && existing.pausedAt !== undefined) {
2390
+ existing.pausedDurationMs = accumulatePausedDurationMs(existing.pausedDurationMs, existing.pausedAt, existing.endedAt);
2391
+ existing.pausedAt = undefined;
2392
+ }
2393
+ existing.durationMs = stage.durationMs;
2394
+ existing.result = stage.result;
2395
+ existing.error = stage.error;
2396
+ if (stage.sessionId !== undefined)
2397
+ existing.sessionId = stage.sessionId;
2398
+ if (stage.sessionFile !== undefined)
2399
+ existing.sessionFile = stage.sessionFile;
2400
+ if (stage.modelAttempts !== undefined)
2401
+ existing.modelAttempts = stage.modelAttempts;
2402
+ if (stage.routerSelection !== undefined)
2403
+ existing.routerSelection = Object.freeze({ ...stage.routerSelection });
2404
+ existing.failureKind = stage.failureKind;
2405
+ existing.failureCode = stage.failureCode;
2406
+ existing.failureRecoverability = stage.failureRecoverability;
2407
+ existing.failureDisposition = stage.failureDisposition;
2408
+ existing.retryAfterMs = stage.retryAfterMs;
2409
+ existing.failureMessage = stage.failureMessage;
2410
+ existing.skippedReason = stage.skippedReason;
2411
+ if (stage.replayKey !== undefined)
2412
+ existing.replayKey = stage.replayKey;
2413
+ if (stage.promptAnswerState !== undefined)
2414
+ existing.promptAnswerState = stage.promptAnswerState;
2415
+ if (stage.replayedFromStageId !== undefined)
2416
+ existing.replayedFromStageId = stage.replayedFromStageId;
2417
+ if (stage.replayed !== undefined)
2418
+ existing.replayed = stage.replayed;
2419
+ if (stage.status === "completed") {
2420
+ if (stage.workflowChildRun !== undefined)
2421
+ existing.workflowChildRun = { ...stage.workflowChildRun };
2422
+ if (stage.workflowChild !== undefined)
2423
+ existing.workflowChild = structuredClone(stage.workflowChild);
2424
+ } else {
2425
+ delete existing.workflowChildRun;
2426
+ delete existing.workflowChild;
2427
+ }
2428
+ delete existing.awaitingInputSince;
2429
+ delete existing.inputRequest;
2430
+ context.rejectStagePrompt(runId, existing, `atomic-workflows: stage ${stage.id} ended before prompt resolved`);
2431
+ context.bumpAndNotify();
2432
+ },
2433
+ recordStageSession(runId, stageId, session) {
2434
+ const run = context.findRun(runId);
2435
+ if (!run)
2436
+ return false;
2437
+ const stage = context.findStage(run, stageId);
2438
+ if (!stage || stage.sessionId === session.sessionId)
2439
+ return false;
2440
+ stage.sessionId = session.sessionId;
2441
+ context.bumpAndNotify();
2442
+ return true;
2443
+ },
2444
+ recordStageAttachable(runId, stageId, attachable) {
2445
+ const run = context.findRun(runId);
2446
+ if (!run)
2447
+ return false;
2448
+ const stage = context.findStage(run, stageId);
2449
+ if (!stage)
2450
+ return false;
2451
+ const next = attachable === true ? true : undefined;
2452
+ if (stage.attachable === next)
2453
+ return false;
2454
+ if (next === undefined) {
2455
+ delete stage.attachable;
2456
+ } else {
2457
+ stage.attachable = next;
2458
+ }
2459
+ context.bumpAndNotify();
2460
+ return true;
2461
+ },
2462
+ recordStageAttached(runId, stageId, attached) {
2463
+ const run = context.findRun(runId);
2464
+ if (!run)
2465
+ return false;
2466
+ const stage = context.findStage(run, stageId);
2467
+ if (!stage)
2468
+ return false;
2469
+ const next = attached === true ? true : undefined;
2470
+ if (stage.attached === next)
2471
+ return false;
2472
+ if (next === undefined) {
2473
+ delete stage.attached;
2474
+ } else {
2475
+ stage.attached = next;
2476
+ }
2477
+ context.bumpAndNotify();
2478
+ return true;
2479
+ },
2480
+ recordStageAwaitingInput(runId, stageId, awaiting, ts) {
2481
+ const run = context.findRun(runId);
2482
+ if (!run)
2483
+ return false;
2484
+ if (TERMINAL_STATUSES.has(run.status))
2485
+ return false;
2486
+ const stage = context.findStage(run, stageId);
2487
+ if (!stage)
2488
+ return false;
2489
+ if (cannotAwaitInput(stage.status))
2490
+ return false;
2491
+ if (awaiting) {
2492
+ if (stage.status === "awaiting_input")
2493
+ return false;
2494
+ stage.status = "awaiting_input";
2495
+ stage.awaitingInputSince = ts ?? Date.now();
2496
+ } else {
2497
+ if (stage.pendingPrompt !== undefined)
2498
+ return false;
2499
+ if (stage.status !== "awaiting_input")
2500
+ return false;
2501
+ stage.status = "running";
2502
+ delete stage.awaitingInputSince;
2503
+ }
2504
+ context.bumpAndNotify();
2505
+ return true;
2506
+ },
2507
+ recordStageInputRequest(runId, stageId, request) {
2508
+ const run = context.findRun(runId);
2509
+ if (!run)
2510
+ return false;
2511
+ if (TERMINAL_STATUSES.has(run.status))
2512
+ return false;
2513
+ const stage = context.findStage(run, stageId);
2514
+ if (!stage)
2515
+ return false;
2516
+ if (isTerminalStageStatus(stage.status))
2517
+ return false;
2518
+ if (stage.inputRequest?.id === request.id)
2519
+ return false;
2520
+ stage.inputRequest = { ...request };
2521
+ context.bumpAndNotify();
2522
+ return true;
2523
+ },
2524
+ clearStageInputRequest(runId, stageId) {
2525
+ const run = context.findRun(runId);
2526
+ if (!run)
2527
+ return false;
2528
+ const stage = context.findStage(run, stageId);
2529
+ if (!stage || stage.inputRequest === undefined)
2530
+ return false;
2531
+ delete stage.inputRequest;
2532
+ context.bumpAndNotify();
2533
+ return true;
2534
+ },
2535
+ recordStageBlocked(runId, stageId, blockedBy) {
2536
+ const run = context.findRun(runId);
2537
+ if (!run)
2538
+ return false;
2539
+ if (TERMINAL_STATUSES.has(run.status))
2540
+ return false;
2541
+ const stage = context.findStage(run, stageId);
2542
+ if (!stage)
2543
+ return false;
2544
+ if (cannotBlock(stage.status))
2545
+ return false;
2546
+ if (stage.status === "blocked") {
2547
+ if (stage.blockedByStageId === blockedBy)
2548
+ return false;
2549
+ stage.blockedByStageId = blockedBy;
2550
+ } else {
2551
+ stage.status = "blocked";
2552
+ stage.blockedByStageId = blockedBy;
2553
+ delete stage.awaitingInputSince;
2554
+ }
2555
+ context.bumpAndNotify();
2556
+ return true;
2557
+ },
2558
+ recordStageUnblocked(runId, stageId) {
2559
+ const run = context.findRun(runId);
2560
+ if (!run)
2561
+ return false;
2562
+ const stage = context.findStage(run, stageId);
2563
+ if (stage?.status !== "blocked")
2564
+ return false;
2565
+ stage.status = "pending";
2566
+ delete stage.blockedByStageId;
2567
+ delete stage.awaitingInputSince;
2568
+ context.bumpAndNotify();
2569
+ return true;
2570
+ },
2571
+ recordStageNotice(runId, stageId, notice) {
2572
+ const run = context.findRun(runId);
2573
+ if (!run)
2574
+ return false;
2575
+ const stage = context.findStage(run, stageId);
2576
+ if (!stage)
2577
+ return false;
2578
+ if (!stage.notices)
2579
+ stage.notices = [];
2580
+ stage.notices.push(notice);
2581
+ context.bumpAndNotify();
2582
+ return true;
2583
+ },
2584
+ recordStagePaused(runId, stageId, pausedAt, metadata) {
2585
+ const run = context.findRun(runId);
2586
+ if (!run)
2587
+ return false;
2588
+ if (TERMINAL_STATUSES.has(run.status))
2589
+ return false;
2590
+ const stage = context.findStage(run, stageId);
2591
+ if (!stage)
2592
+ return false;
2593
+ if (cannotPause(stage.status)) {
2594
+ if (stage.status !== "paused" || metadata?.actor === undefined)
2595
+ return false;
2596
+ if (stage.pauseActor === metadata.actor)
2597
+ return false;
2598
+ stage.pauseActor = metadata.actor;
2599
+ context.bumpAndNotify();
2600
+ return false;
2601
+ }
2602
+ context.observation.executingStageIds.delete(workflowActivityNodeKey(runId, stageId));
2603
+ stage.status = "paused";
2604
+ stage.pausedAt = nextControlTimestamp(pausedAt, stage.resumedAt);
2605
+ stage.resumedAt = undefined;
2606
+ delete stage.awaitingInputSince;
2607
+ delete stage.resumeActor;
2608
+ if (metadata?.actor === undefined)
2609
+ delete stage.pauseActor;
2610
+ else
2611
+ stage.pauseActor = metadata.actor;
2612
+ context.bumpAndNotify();
2613
+ return true;
2614
+ },
2615
+ recordStageResumed(runId, stageId, resumedAt, metadata) {
2616
+ const run = context.findRun(runId);
2617
+ if (!run)
2618
+ return false;
2619
+ if (TERMINAL_STATUSES.has(run.status))
2620
+ return false;
2621
+ const stage = context.findStage(run, stageId);
2622
+ if (!stage)
2623
+ return false;
2624
+ if (stage.status !== "paused" && stage.status !== "blocked") {
2625
+ if (stage.status !== "running" || stage.resumedAt === undefined || metadata?.actor === undefined) {
2626
+ return false;
2627
+ }
2628
+ if (stage.resumeActor === metadata.actor)
2629
+ return false;
2630
+ stage.resumeActor = metadata.actor;
2631
+ context.bumpAndNotify();
2632
+ return false;
2633
+ }
2634
+ const resumedTs = nextControlTimestamp(resumedAt, stage.pausedAt);
2635
+ if (context.observation.liveRunIds.has(runId))
2636
+ context.observation.executingStageIds.add(workflowActivityNodeKey(runId, stageId));
2637
+ stage.status = "running";
2638
+ if (stage.startedAt !== undefined) {
2639
+ stage.pausedDurationMs = accumulatePausedDurationMs(stage.pausedDurationMs, stage.pausedAt, resumedTs);
2640
+ }
2641
+ stage.resumedAt = resumedTs;
2642
+ stage.pausedAt = undefined;
2643
+ delete stage.blockedByStageId;
2644
+ delete stage.awaitingInputSince;
2645
+ delete stage.pauseActor;
2646
+ if (metadata?.actor === undefined)
2647
+ delete stage.resumeActor;
2648
+ else
2649
+ stage.resumeActor = metadata.actor;
2650
+ context.bumpAndNotify();
2651
+ return true;
2652
+ }
2653
+ };
2654
+ }
2655
+
2656
+ // dist/builtin/workflows/src/shared/store-factory.ts
2657
+ function createStore() {
2658
+ const context = createStoreContext();
2659
+ context.backend = getDurableBackendProcessOwner().injectedBackend;
2660
+ const created = {
2661
+ [workflowObservationRuntimeKey]: context.observation,
2662
+ [workflowStoreBackendOverride]: context.backend,
2663
+ get [workflowStoreBackend]() {
2664
+ return context.backend;
2665
+ },
2666
+ set [workflowStoreBackend](backend) {
2667
+ context.backend = backend;
2668
+ },
2669
+ ...createRunStoreMethods(context),
2670
+ ...createPendingStageDeliveryStoreMethods(context),
2671
+ ...createStageStoreMethods(context),
2672
+ ...createToolNodeStoreMethods(context),
2673
+ ...createPromptStoreMethods(context)
2674
+ };
2675
+ return created;
2676
+ }
2677
+ var SESSION_KEY = "workflows:store:v1";
2678
+ var singleton = createSessionScopedSingleton(SESSION_KEY, createStore);
2679
+ var store = singleton.facade;
2680
+ // dist/builtin/workflows/src/shared/workflow-artifact-env.ts
2681
+ var WORKFLOW_ARTIFACT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
2682
+ var ENV_WORKFLOW_ARTIFACT_DIR = "ATOMIC_WORKFLOW_ARTIFACT_DIR";
2683
+
2684
+ // dist/builtin/workflows/src/shared/workflow-artifacts.ts
2685
+ var ARTIFACT_PRUNE_RECHECK_MS = 60 * 60 * 1000;
2686
+ var lastArtifactPruneAt = new Map;
2687
+ var pendingArtifactPrunes = new Map;
2688
+ function workflowArtifactRoot() {
2689
+ const override = getEnvValue(ENV_WORKFLOW_ARTIFACT_DIR);
2690
+ if (override !== undefined && override.length > 0)
2691
+ return override;
2692
+ return join(dirname(getAgentDir()), "workflows");
2693
+ }
2694
+ function workflowArtifactRunsRoot() {
2695
+ return join(workflowArtifactRoot(), "runs");
2696
+ }
2697
+ function safeRunId(runId) {
2698
+ const safe = runId.replace(/[^A-Za-z0-9._-]/g, "_");
2699
+ return safe.length > 0 ? safe : "run";
2700
+ }
2701
+ function workflowArtifactRunPath(runId) {
2702
+ return join(workflowArtifactRunsRoot(), safeRunId(runId));
2703
+ }
2704
+ function storeRunState(run) {
2705
+ const hasPendingInput = run.pendingPrompt !== undefined || run.stages.some((stage) => stage.status === "awaiting_input" || stage.status === "paused" || stage.status === "blocked");
2706
+ if (hasPendingInput || run.status === "pending" || run.status === "running" || run.status === "paused" || run.status === "blocked" || run.exitReason === "quit") {
2707
+ return "protected";
2708
+ }
2709
+ return "terminal";
2710
+ }
2711
+ function durableRunState(backend, runId) {
2712
+ const handle = backend.getLoadableWorkflow(runId);
2713
+ if (handle === undefined)
2714
+ return;
2715
+ if (handle.status === "running" || handle.status === "paused" || handle.status === "blocked" || handle.pendingPrompts > 0) {
2716
+ return "protected";
2717
+ }
2718
+ return "terminal";
2719
+ }
2720
+ function createWorkflowArtifactRunStateResolver() {
2721
+ const localRuns = new Map(store.runs().map((run) => [run.id, run]));
2722
+ const findLocalRun = (runId) => localRuns.get(runId) ?? [...localRuns.values()].find((run) => safeRunId(run.id) === runId);
2723
+ const protectedOwners = new Set;
2724
+ for (const run of localRuns.values()) {
2725
+ if (storeRunState(run) !== "protected")
2726
+ continue;
2727
+ let cursor = run;
2728
+ const visited = new Set;
2729
+ while (cursor !== undefined && !visited.has(cursor.id)) {
2730
+ visited.add(cursor.id);
2731
+ protectedOwners.add(safeRunId(cursor.id));
2732
+ const sourceId = cursor.resumedFromRunId;
2733
+ if (sourceId === undefined)
2734
+ break;
2735
+ protectedOwners.add(safeRunId(sourceId));
2736
+ cursor = findLocalRun(sourceId);
2737
+ }
2738
+ }
2739
+ let backend;
2740
+ let backendReady = true;
2741
+ try {
2742
+ backend = requireStoreDurableBackend(store);
2743
+ } catch {
2744
+ backendReady = false;
2745
+ }
2746
+ return (runId) => {
2747
+ if (protectedOwners.has(runId))
2748
+ return "protected";
2749
+ const local = findLocalRun(runId);
2750
+ const localState = local === undefined ? undefined : storeRunState(local);
2751
+ if (!backendReady) {
2752
+ return localState === "protected" ? "protected" : undefined;
2753
+ }
2754
+ let durable;
2755
+ if (backend !== undefined) {
2756
+ try {
2757
+ durable = durableRunState(availableRunDurableBackend(store.runs(), runId) ?? backend, runId);
2758
+ } catch {
2759
+ backendReady = false;
2760
+ return localState === "protected" ? "protected" : undefined;
2761
+ }
2762
+ }
2763
+ if (durable === "protected" || localState === "protected")
2764
+ return "protected";
2765
+ if (durable === "terminal" || localState === "terminal")
2766
+ return "terminal";
2767
+ return "orphan";
2768
+ };
2769
+ }
2770
+ async function deleteTerminalDurableEntry(runId) {
2771
+ let backend;
2772
+ try {
2773
+ backend = requireStoreDurableBackend(store, runId);
2774
+ } catch {
2775
+ return false;
2776
+ }
2777
+ try {
2778
+ const result = await backend.deleteWorkflowIfInactive(runId);
2779
+ return result.ok || result.reason === "not_found";
2780
+ } catch {
2781
+ return false;
2782
+ }
2783
+ }
2784
+ async function pruneWorkflowArtifactRuns(root = workflowArtifactRunsRoot(), now = Date.now(), stateResolver) {
2785
+ try {
2786
+ const entries = await readdir(root, { withFileTypes: true, encoding: "utf8" });
2787
+ for (const entry of entries) {
2788
+ if (!entry.isDirectory())
2789
+ continue;
2790
+ const entryPath = join(root, entry.name);
2791
+ let metadata;
2792
+ try {
2793
+ metadata = await stat(entryPath);
2794
+ } catch (error) {
2795
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
2796
+ continue;
2797
+ throw error;
2798
+ }
2799
+ if (now - metadata.mtimeMs <= WORKFLOW_ARTIFACT_RETENTION_MS)
2800
+ continue;
2801
+ if (stateResolver === undefined)
2802
+ continue;
2803
+ const state = stateResolver(entry.name);
2804
+ if (state !== "terminal" && state !== "orphan")
2805
+ continue;
2806
+ if (state === "terminal" && !await deleteTerminalDurableEntry(entry.name))
2807
+ continue;
2808
+ await rm(entryPath, { recursive: true, force: true });
2809
+ }
2810
+ } catch (error) {
2811
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
2812
+ return;
2813
+ throw error;
2814
+ }
2815
+ }
2816
+ async function pruneArtifactRootIfDue(root, now) {
2817
+ const pending = pendingArtifactPrunes.get(root);
2818
+ if (pending !== undefined) {
2819
+ try {
2820
+ await pending;
2821
+ } catch {}
2822
+ return;
2823
+ }
2824
+ const previous = lastArtifactPruneAt.get(root);
2825
+ if (previous !== undefined && now - previous < ARTIFACT_PRUNE_RECHECK_MS)
2826
+ return;
2827
+ const operation = pruneWorkflowArtifactRuns(root, now, createWorkflowArtifactRunStateResolver());
2828
+ pendingArtifactPrunes.set(root, operation);
2829
+ try {
2830
+ await operation;
2831
+ } catch {} finally {
2832
+ lastArtifactPruneAt.set(root, now);
2833
+ pendingArtifactPrunes.delete(root);
2834
+ }
2835
+ }
2836
+ function workflowArtifactDirectoryPath(runId) {
2837
+ const effectiveRunId = runId ?? randomUUID2();
2838
+ return join(workflowArtifactRunPath(effectiveRunId), `artifact-${randomUUID2()}`);
2839
+ }
2840
+ async function ensureWorkflowArtifactDirectory(directory) {
2841
+ await pruneArtifactRootIfDue(workflowArtifactRunsRoot(), Date.now());
2842
+ await mkdir(directory, { recursive: true });
2843
+ return directory;
2844
+ }
2845
+ async function createWorkflowArtifactDirectory(runId) {
2846
+ return ensureWorkflowArtifactDirectory(workflowArtifactDirectoryPath(runId));
2847
+ }
2848
+
2849
+ // dist/builtin/workflows/builtin/goal-convergence.ts
2850
+ var FRACTION_TREND_RISE_DELTA = DEFAULT_RISE_DELTA / (VERIFICATION_SCALE.max - VERIFICATION_SCALE.min);
2851
+ var FRACTION_TREND_FALL_DELTA = DEFAULT_FALL_DELTA / (VERIFICATION_SCALE.max - VERIFICATION_SCALE.min);
2852
+ function record_convergence(round) {
2853
+ return {
2854
+ unresolvedBlockingCount: round.unresolvedBlockingCount,
2855
+ meanFindingConfidence: round.meanFindingConfidence,
2856
+ fractionProven: round.fractionProven,
2857
+ demotions: round.demotions,
2858
+ usage: round.usage
2859
+ };
2860
+ }
2861
+ function classify_convergence(entries) {
2862
+ return {
2863
+ blocking: classify_trend(entries.map((entry) => entry.unresolvedBlockingCount)),
2864
+ proven: classify_trend(entries.map((entry) => entry.fractionProven), {
2865
+ riseDelta: FRACTION_TREND_RISE_DELTA,
2866
+ fallDelta: FRACTION_TREND_FALL_DELTA
2867
+ })
2868
+ };
2869
+ }
2870
+ function convergence_escalation_evidence(entries) {
2871
+ if (entries.length === 0)
2872
+ return [];
2873
+ const { blocking, proven } = classify_convergence(entries);
2874
+ if (blocking.trend === "regressing" || proven.trend === "rising" && blocking.trend !== "rising")
2875
+ return [];
2876
+ const latest = entries[entries.length - 1]?.meanFindingConfidence;
2877
+ return [
2878
+ `${entries.length} round${entries.length === 1 ? "" : "s"} recorded; no observed convergence: the blocking-count trend is ${blocking.trend}.`,
2879
+ `Blocking-count trend: ${blocking.trend}; raw series: ${JSON.stringify(blocking.evidence.series)}.`,
2880
+ `Fraction-proven trend: ${proven.trend}; raw series: ${JSON.stringify(proven.evidence.series)}.`,
2881
+ latest === null ? "Latest mean finding confidence: no findings were filed." : `Latest mean finding confidence: ${latest}.`,
2882
+ "This is escalation EVIDENCE only; it never approves or terminates anything."
2883
+ ];
2884
+ }
2885
+
2886
+ // dist/builtin/workflows/builtin/review-convergence.ts
2887
+ var FINAL_ACTION_PATTERN = /\b(?:pr|pull[- ]request|merge[- ]request|review request|github pr|create pr)\b/iu;
2888
+ function isFinalActionTraceability(entry) {
2889
+ return FINAL_ACTION_PATTERN.test(`${entry.requirement}
2890
+ ${entry.evidence}`);
2891
+ }
2892
+ function finalActionRemaining(traceability) {
2893
+ return traceability.some((entry) => entry.status !== "proven" && isFinalActionTraceability(entry));
2894
+ }
2895
+ var MAX_BLOCKING_PRIORITY = 2;
2896
+ function findingBlocksClosure(finding) {
2897
+ const alignment = finding.objective_alignment;
2898
+ if (alignment === "beyond_objective" || alignment === "contradicts_objective") {
2899
+ return false;
2900
+ }
2901
+ if (alignment === "required_by_objective")
2902
+ return true;
2903
+ if (alignment !== "consistent_with_objective")
2904
+ return true;
2905
+ const priority = finding.priority;
2906
+ if (priority === undefined || priority === null)
2907
+ return true;
2908
+ return priority <= MAX_BLOCKING_PRIORITY;
2909
+ }
2910
+ function stopReviewLoopContradictions(verdict) {
2911
+ const contradictions = [];
2912
+ if (verdict.overall_correctness !== "patch is correct") {
2913
+ contradictions.push(`overall_correctness is "${verdict.overall_correctness}"`);
2914
+ }
2915
+ if (verdict.goal_oracle_satisfied === false) {
2916
+ contradictions.push("goal_oracle_satisfied is false");
2917
+ }
2918
+ for (const finding of verdict.findings) {
2919
+ if (findingBlocksClosure(finding)) {
2920
+ contradictions.push(`blocking finding "${finding.title}"`);
2921
+ }
2922
+ }
2923
+ return contradictions;
2924
+ }
2925
+ function contradictedStopReviewLoopGap(contradictions) {
2926
+ return `stop_review_loop=true was not counted as approval because the same review reports ${contradictions.join("; ")}`;
2927
+ }
2928
+ function findingConsolidationKey(finding) {
2929
+ const normalizedTitle = finding.title.replace(/^\s*\[P[0-3]\]\s*/iu, "").toLowerCase().replace(/\s+/gu, " ").trim();
2930
+ return `${finding.code_location?.absolute_file_path ?? ""}::${normalizedTitle}`;
2931
+ }
2932
+ function consolidateFindingsBatch(reviews) {
2933
+ const byKey = new Map;
2934
+ for (const review of reviews) {
2935
+ for (const finding of review.findings) {
2936
+ const key = findingConsolidationKey(finding);
2937
+ const existing = byKey.get(key);
2938
+ if (existing === undefined) {
2939
+ byKey.set(key, {
2940
+ finding,
2941
+ reviewers: [review.reviewer],
2942
+ blocking: findingBlocksClosure(finding)
2943
+ });
2944
+ continue;
2945
+ }
2946
+ if (!existing.reviewers.includes(review.reviewer)) {
2947
+ existing.reviewers.push(review.reviewer);
2948
+ }
2949
+ existing.blocking = existing.blocking || findingBlocksClosure(finding);
2950
+ }
2951
+ }
2952
+ return [...byKey.values()].sort((a, b) => Number(b.blocking) - Number(a.blocking));
2953
+ }
2954
+ var PREVIEW_LIMIT = 500;
2955
+ function rawTextPreview(rawText) {
2956
+ const trimmed = rawText.trim();
2957
+ if (trimmed.length === 0)
2958
+ return;
2959
+ return trimmed.slice(0, PREVIEW_LIMIT);
2960
+ }
2961
+ function parseFailureDiagnostics(reviewer, rawText) {
2962
+ const preview = rawTextPreview(rawText);
2963
+ const base = `Structured reviewer decision parse failed for ${reviewer}: no schema-valid JSON decision was returned.`;
2964
+ return preview === undefined ? [base] : [base, `Raw reviewer output preview: ${preview}`];
2965
+ }
2966
+ function errorMessage(error) {
2967
+ return error instanceof Error ? error.message : String(error);
2968
+ }
2969
+ function reviewerFailureText(error) {
2970
+ const messages = [errorMessage(error)];
2971
+ if (error instanceof AggregateError) {
2972
+ for (const nested of error.errors) {
2973
+ messages.push(errorMessage(nested));
2974
+ }
2975
+ }
2976
+ return [...new Set(messages.map((message) => message.trim()).filter(Boolean))].join(`
2977
+ `);
2978
+ }
2979
+ function summarizeReviewConvergence(args) {
2980
+ return {
2981
+ parsed: args.parsed,
2982
+ approved: args.approved,
2983
+ stopReviewLoop: args.stopReviewLoop,
2984
+ nextAction: args.nextAction,
2985
+ finalActionRemaining: args.finalActionRemaining ?? args.nextAction === "pull-request",
2986
+ diagnostics: args.diagnostics
2987
+ };
2988
+ }
2989
+
2990
+ // dist/builtin/workflows/builtin/goal-reverify.ts
2991
+ import { Type } from "typebox";
2992
+ var DEFAULT_REVERIFY_THRESHOLD = 0.7;
2993
+ var STANDARD_CONFIRM_THRESHOLD = 10;
2994
+ var REQUIRED_CONFIRM_THRESHOLD = 6;
2995
+ var DEFAULT_REPEATS = 3;
2996
+ var REVERIFY_QUESTION = "Assess this specific finding against the code it cites: is it a real, objective-relevant, currently-unresolved blocker?";
2997
+ var reverifySchema = Type.Object({
2998
+ score: VERIFICATION_SCALE.schema,
2999
+ evidence: Type.Array(Type.String())
3000
+ }, { additionalProperties: false });
3001
+ function isRecord(value) {
3002
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3003
+ }
3004
+ function isStringArray(value) {
3005
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
3006
+ }
3007
+ function parseReport(result) {
3008
+ if (!isRecord(result.structured))
3009
+ return;
3010
+ const score = result.structured.score;
3011
+ if (typeof score !== "number" || !Number.isInteger(score) || score < VERIFICATION_SCALE.min || score > VERIFICATION_SCALE.max) {
3012
+ return;
3013
+ }
3014
+ const evidence = result.structured.evidence;
3015
+ return {
3016
+ score,
3017
+ evidence: isStringArray(evidence) ? evidence : []
3018
+ };
3019
+ }
3020
+ function requiredByObjective(finding) {
3021
+ return finding.finding.objective_alignment === "required_by_objective";
3022
+ }
3023
+ function is_reverifiable(finding, threshold = DEFAULT_REVERIFY_THRESHOLD) {
3024
+ const confidence = finding.finding.confidence_score;
3025
+ return finding.blocking && finding.reviewers.length === 1 && typeof confidence === "number" && Number.isFinite(confidence) && confidence < threshold && finding.finding.objective_alignment !== "beyond_objective" && finding.finding.objective_alignment !== "contradicts_objective";
3026
+ }
3027
+ function readPaths(finding, candidateRefs) {
3028
+ const codePath = finding.finding.code_location?.absolute_file_path;
3029
+ return [
3030
+ ...codePath === undefined ? [] : [codePath],
3031
+ ...candidateRefs
3032
+ ];
3033
+ }
3034
+ function promptFor(finding, context) {
3035
+ const codePath = finding.finding.code_location?.absolute_file_path;
3036
+ const candidate = {
3037
+ ...codePath === undefined ? {} : { path: codePath },
3038
+ body: [
3039
+ `Title: ${finding.finding.title}`,
3040
+ `Body: ${finding.finding.body ?? ""}`,
3041
+ `Code location: ${codePath ?? "not supplied"}`
3042
+ ].join(`
3043
+ `)
3044
+ };
3045
+ const head = {
3046
+ task: `${REVERIFY_QUESTION}
3047
+
3048
+ Objective:
3049
+ ${context.objective}`,
3050
+ groundTruthNote: `The objective is the contract. Verify the finding against observed code, not reviewer narration.`,
3051
+ candidates: [candidate],
3052
+ outputFormat: "Call structured_output with score (an integer from 1 to 20) and evidence (an array of observed, concise reasons)."
3053
+ };
3054
+ const prompt = build_scoring_prompt(head, {
3055
+ id: "finding_reverification",
3056
+ name: "Finding re-verification",
3057
+ description: REVERIFY_QUESTION
3058
+ });
3059
+ return {
3060
+ prompt,
3061
+ reads: [
3062
+ ...readPaths(finding, context.candidateRefs),
3063
+ ...scoring_prompt_reads(head)
3064
+ ]
3065
+ };
3066
+ }
3067
+ async function runRepeat(ctx, finding, context, stageName) {
3068
+ try {
3069
+ const rendered = promptFor(finding, context);
3070
+ const options = {
3071
+ prompt: rendered.prompt,
3072
+ context: "fresh",
3073
+ reads: rendered.reads,
3074
+ schema: reverifySchema
3075
+ };
3076
+ return parseReport(await ctx.task(stageName, options));
3077
+ } catch {
3078
+ return;
3079
+ }
3080
+ }
3081
+ async function reverify_finding(ctx, input) {
3082
+ if (!is_reverifiable(input.finding, input.threshold)) {
3083
+ throw new Error("Cannot re-verify an ineligible finding.");
3084
+ }
3085
+ const repeatCount = Number.isFinite(input.repeats) && input.repeats !== undefined ? Math.max(0, Math.floor(input.repeats)) : DEFAULT_REPEATS;
3086
+ const perRepeat = [];
3087
+ const evidence = [];
3088
+ const validScores = [];
3089
+ for (let repeat = 1;repeat <= repeatCount; repeat += 1) {
3090
+ let report = await runRepeat(ctx, input.finding, input.context, `reverify-${repeat}`);
3091
+ if (report === undefined) {
3092
+ report = await runRepeat(ctx, input.finding, input.context, `reverify-${repeat}-reask`);
3093
+ }
3094
+ if (report === undefined) {
3095
+ perRepeat.push(null);
3096
+ evidence.push(`Re-verification repeat ${repeat} was invalid after one re-ask; doubt defaults to confirmed.`);
3097
+ continue;
3098
+ }
3099
+ perRepeat.push(report.score);
3100
+ validScores.push(report.score);
3101
+ if (report.evidence.length === 0) {
3102
+ evidence.push(`Re-verification repeat ${repeat} scored ${report.score}/20.`);
3103
+ } else {
3104
+ evidence.push(...report.evidence);
3105
+ }
3106
+ }
3107
+ const meanScore = validScores.length === 0 ? 0 : validScores.reduce((total, score) => total + score, 0) / validScores.length;
3108
+ const validCount = validScores.length;
3109
+ const requiredQuorum = Math.ceil(repeatCount / 2);
3110
+ const demoted = requiredByObjective(input.finding) ? repeatCount > 0 && validCount === repeatCount && meanScore < REQUIRED_CONFIRM_THRESHOLD : validCount > 0 && validCount >= requiredQuorum && meanScore < STANDARD_CONFIRM_THRESHOLD;
3111
+ return {
3112
+ verdict: demoted ? "demoted" : "confirmed",
3113
+ meanScore,
3114
+ perRepeat,
3115
+ evidence
3116
+ };
3117
+ }
3118
+ function auditKey(finding) {
3119
+ return JSON.stringify([
3120
+ finding.finding.code_location?.absolute_file_path ?? "",
3121
+ finding.finding.title,
3122
+ finding.reviewers
3123
+ ]);
3124
+ }
3125
+ function apply_reverify_results(batch, audits) {
3126
+ const demoted = new Set(audits.filter((audit) => audit.verdict === "demoted").map((audit) => auditKey(audit.finding)));
3127
+ return {
3128
+ batch: batch.map((entry) => demoted.has(auditKey(entry)) ? { ...entry, blocking: false } : entry),
3129
+ audits
3130
+ };
3131
+ }
3132
+ async function reverify_consolidated_batch(ctx, input) {
3133
+ const audits = [];
3134
+ for (const entry of input.batch) {
3135
+ if (!is_reverifiable(entry, input.threshold))
3136
+ continue;
3137
+ const result = await reverify_finding(ctx, {
3138
+ finding: entry,
3139
+ context: input.context,
3140
+ repeats: input.repeats,
3141
+ threshold: input.threshold
3142
+ });
3143
+ audits.push({ finding: entry, ...result });
3144
+ }
3145
+ return apply_reverify_results(input.batch, audits);
3146
+ }
3147
+
3148
+ export { workflowArtifactDirectoryPath, ensureWorkflowArtifactDirectory, createWorkflowArtifactDirectory, record_convergence, convergence_escalation_evidence, finalActionRemaining, stopReviewLoopContradictions, contradictedStopReviewLoopGap, consolidateFindingsBatch, parseFailureDiagnostics, reviewerFailureText, summarizeReviewConvergence, reverify_consolidated_batch };