@bastani/atomic 0.9.38-alpha.6 → 0.9.38-alpha.8

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 (256) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/builtin/intercom/package.json +2 -2
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/CHANGELOG.md +12 -0
  5. package/dist/builtin/subagents/README.md +9 -4
  6. package/dist/builtin/subagents/package.json +3 -3
  7. package/dist/builtin/subagents/src/extension/index.bundle.mjs +143 -134
  8. package/dist/builtin/web-access/package.json +2 -2
  9. package/dist/builtin/workflows/CHANGELOG.md +25 -0
  10. package/dist/builtin/workflows/builtin/{chunk-q7dx7kh7.js → chunk-85mx6wcf.js} +6 -6
  11. package/dist/builtin/workflows/builtin/{chunk-neszcj53.js → chunk-8kkv04hz.js} +15 -15
  12. package/dist/builtin/workflows/builtin/{chunk-g1a4hw0s.js → chunk-8x61e0s7.js} +13 -25
  13. package/dist/builtin/workflows/builtin/{chunk-2qgfyvzs.js → chunk-y45tkftg.js} +7 -7
  14. package/dist/builtin/workflows/builtin/goal.js +2 -2
  15. package/dist/builtin/workflows/builtin/index.js +4 -4
  16. package/dist/builtin/workflows/builtin/open-claude-design.js +1 -1
  17. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  18. package/dist/builtin/workflows/package.json +2 -2
  19. package/dist/builtin/workflows/src/durable/journal/internal.d.ts +0 -19
  20. package/dist/builtin/workflows/src/durable/journal/legacy-journal-tables.d.ts +42 -0
  21. package/dist/builtin/workflows/src/durable/journal/memory-run-journal.d.ts +3 -11
  22. package/dist/builtin/workflows/src/durable/journal/resolution.d.ts +15 -9
  23. package/dist/builtin/workflows/src/durable/journal/sql-run-journal.d.ts +3 -0
  24. package/dist/builtin/workflows/src/durable/journal/types.d.ts +3 -93
  25. package/dist/builtin/workflows/src/extension/index.bundle.mjs +1137 -748
  26. package/dist/builtin/workflows/src/index.js +709 -403
  27. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +1 -1
  28. package/dist/cli/args.d.ts +2 -0
  29. package/dist/cli/args.d.ts.map +1 -1
  30. package/dist/cli/args.js +29 -3
  31. package/dist/cli/args.js.map +1 -1
  32. package/dist/cli/session-picker.d.ts +1 -1
  33. package/dist/cli/session-picker.d.ts.map +1 -1
  34. package/dist/cli/session-picker.js +2 -2
  35. package/dist/cli/session-picker.js.map +1 -1
  36. package/dist/core/agent-session-events.d.ts.map +1 -1
  37. package/dist/core/agent-session-events.js +6 -1
  38. package/dist/core/agent-session-events.js.map +1 -1
  39. package/dist/core/agent-session-runtime.d.ts +4 -0
  40. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  41. package/dist/core/agent-session-runtime.js +44 -4
  42. package/dist/core/agent-session-runtime.js.map +1 -1
  43. package/dist/core/agent-session-services.d.ts +1 -1
  44. package/dist/core/agent-session-services.d.ts.map +1 -1
  45. package/dist/core/agent-session-services.js +2 -2
  46. package/dist/core/agent-session-services.js.map +1 -1
  47. package/dist/core/compaction/branch-summarization.d.ts +1 -4
  48. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  49. package/dist/core/compaction/branch-summarization.js +0 -4
  50. package/dist/core/compaction/branch-summarization.js.map +1 -1
  51. package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -1
  52. package/dist/core/compaction/pi-summary-fallback.js +1 -3
  53. package/dist/core/compaction/pi-summary-fallback.js.map +1 -1
  54. package/dist/core/extensions/loader-api.js +1 -1
  55. package/dist/core/extensions/loader-api.js.map +1 -1
  56. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  57. package/dist/core/extensions/runner-context.js +7 -1
  58. package/dist/core/extensions/runner-context.js.map +1 -1
  59. package/dist/core/fast-model-routing.js +1 -1
  60. package/dist/core/fast-model-routing.js.map +1 -1
  61. package/dist/core/model-config.d.ts +765 -0
  62. package/dist/core/model-config.d.ts.map +1 -1
  63. package/dist/core/model-config.js +46 -24
  64. package/dist/core/model-config.js.map +1 -1
  65. package/dist/core/model-resolver-defaults.js +1 -1
  66. package/dist/core/model-resolver-defaults.js.map +1 -1
  67. package/dist/core/resource-loader-reload.js +1 -1
  68. package/dist/core/resource-loader-reload.js.map +1 -1
  69. package/dist/core/resource-loader-types.d.ts +1 -1
  70. package/dist/core/resource-loader-types.d.ts.map +1 -1
  71. package/dist/core/resource-loader-types.js.map +1 -1
  72. package/dist/core/sdk-types.d.ts +4 -0
  73. package/dist/core/sdk-types.d.ts.map +1 -1
  74. package/dist/core/sdk-types.js.map +1 -1
  75. package/dist/core/sdk.d.ts +1 -1
  76. package/dist/core/sdk.d.ts.map +1 -1
  77. package/dist/core/sdk.js +48 -19
  78. package/dist/core/sdk.js.map +1 -1
  79. package/dist/core/session-lifecycle-work.d.ts +3 -0
  80. package/dist/core/session-lifecycle-work.d.ts.map +1 -1
  81. package/dist/core/session-lifecycle-work.js +2 -0
  82. package/dist/core/session-lifecycle-work.js.map +1 -1
  83. package/dist/core/session-manager-core.d.ts +7 -4
  84. package/dist/core/session-manager-core.d.ts.map +1 -1
  85. package/dist/core/session-manager-core.js +149 -41
  86. package/dist/core/session-manager-core.js.map +1 -1
  87. package/dist/core/session-manager-list.d.ts.map +1 -1
  88. package/dist/core/session-manager-list.js +7 -7
  89. package/dist/core/session-manager-list.js.map +1 -1
  90. package/dist/core/session-manager-storage.d.ts +2 -1
  91. package/dist/core/session-manager-storage.d.ts.map +1 -1
  92. package/dist/core/session-manager-storage.js +24 -9
  93. package/dist/core/session-manager-storage.js.map +1 -1
  94. package/dist/core/session-manager-types.d.ts +1 -1
  95. package/dist/core/session-manager-types.d.ts.map +1 -1
  96. package/dist/core/session-manager-types.js.map +1 -1
  97. package/dist/core/session-manager.d.ts +1 -1
  98. package/dist/core/session-manager.d.ts.map +1 -1
  99. package/dist/core/session-manager.js +1 -1
  100. package/dist/core/session-manager.js.map +1 -1
  101. package/dist/core/session-resume-args.d.ts +4 -0
  102. package/dist/core/session-resume-args.d.ts.map +1 -0
  103. package/dist/core/session-resume-args.js +9 -0
  104. package/dist/core/session-resume-args.js.map +1 -0
  105. package/dist/core/session-storage.d.ts +26 -0
  106. package/dist/core/session-storage.d.ts.map +1 -0
  107. package/dist/core/session-storage.js +171 -0
  108. package/dist/core/session-storage.js.map +1 -0
  109. package/dist/core/session-store-list.d.ts +4 -0
  110. package/dist/core/session-store-list.d.ts.map +1 -0
  111. package/dist/core/session-store-list.js +28 -0
  112. package/dist/core/session-store-list.js.map +1 -0
  113. package/dist/core/settings-manager-basic-accessors.d.ts +0 -1
  114. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  115. package/dist/core/settings-manager-basic-accessors.js +0 -5
  116. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  117. package/dist/core/settings-merge.d.ts.map +1 -1
  118. package/dist/core/settings-merge.js +5 -0
  119. package/dist/core/settings-merge.js.map +1 -1
  120. package/dist/core/settings-schema.d.ts +74 -3
  121. package/dist/core/settings-schema.d.ts.map +1 -1
  122. package/dist/core/settings-schema.js +28 -14
  123. package/dist/core/settings-schema.js.map +1 -1
  124. package/dist/core/storage/errors.d.ts +1 -0
  125. package/dist/core/storage/errors.d.ts.map +1 -1
  126. package/dist/core/storage/errors.js.map +1 -1
  127. package/dist/core/storage/index.d.ts +4 -0
  128. package/dist/core/storage/index.d.ts.map +1 -1
  129. package/dist/core/storage/index.js +3 -0
  130. package/dist/core/storage/index.js.map +1 -1
  131. package/dist/core/storage/provider.d.ts +58 -0
  132. package/dist/core/storage/provider.d.ts.map +1 -0
  133. package/dist/core/storage/provider.js +243 -0
  134. package/dist/core/storage/provider.js.map +1 -0
  135. package/dist/core/storage/run-journal.d.ts +93 -0
  136. package/dist/core/storage/run-journal.d.ts.map +1 -0
  137. package/dist/core/storage/run-journal.js +15 -0
  138. package/dist/core/storage/run-journal.js.map +1 -0
  139. package/dist/core/storage/selection.d.ts +16 -0
  140. package/dist/core/storage/selection.d.ts.map +1 -0
  141. package/dist/core/storage/selection.js +87 -0
  142. package/dist/core/storage/selection.js.map +1 -0
  143. package/dist/core/storage/session/jsonl-session-store.d.ts +9 -1
  144. package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
  145. package/dist/core/storage/session/jsonl-session-store.js +82 -44
  146. package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
  147. package/dist/core/storage/session/legacy-format.d.ts +20 -0
  148. package/dist/core/storage/session/legacy-format.d.ts.map +1 -0
  149. package/dist/core/storage/session/legacy-format.js +89 -0
  150. package/dist/core/storage/session/legacy-format.js.map +1 -0
  151. package/dist/core/storage/session/legacy-session-store.d.ts +60 -0
  152. package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -0
  153. package/dist/core/storage/session/legacy-session-store.js +225 -0
  154. package/dist/core/storage/session/legacy-session-store.js.map +1 -0
  155. package/dist/core/storage/session/memory-session-store.d.ts +3 -1
  156. package/dist/core/storage/session/memory-session-store.d.ts.map +1 -1
  157. package/dist/core/storage/session/memory-session-store.js +9 -2
  158. package/dist/core/storage/session/memory-session-store.js.map +1 -1
  159. package/dist/core/storage/session/sql-session-store.d.ts +4 -1
  160. package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
  161. package/dist/core/storage/session/sql-session-store.js +25 -6
  162. package/dist/core/storage/session/sql-session-store.js.map +1 -1
  163. package/dist/core/storage/session/types.d.ts +4 -0
  164. package/dist/core/storage/session/types.d.ts.map +1 -1
  165. package/dist/core/storage/session/types.js.map +1 -1
  166. package/dist/core/tools/read-url.d.ts.map +1 -1
  167. package/dist/core/tools/read-url.js +6 -1
  168. package/dist/core/tools/read-url.js.map +1 -1
  169. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  170. package/dist/extensions/codemode/execute.js +13 -0
  171. package/dist/extensions/codemode/execute.js.map +1 -1
  172. package/dist/extensions/herdr/index.d.ts.map +1 -1
  173. package/dist/extensions/herdr/index.js +5 -3
  174. package/dist/extensions/herdr/index.js.map +1 -1
  175. package/dist/index.d.ts +3 -1
  176. package/dist/index.d.ts.map +1 -1
  177. package/dist/index.js +3 -1
  178. package/dist/index.js.map +1 -1
  179. package/dist/main-session.d.ts +5 -1
  180. package/dist/main-session.d.ts.map +1 -1
  181. package/dist/main-session.js +106 -45
  182. package/dist/main-session.js.map +1 -1
  183. package/dist/main.d.ts.map +1 -1
  184. package/dist/main.js +49 -15
  185. package/dist/main.js.map +1 -1
  186. package/dist/modes/interactive/components/chat-session-host.d.ts +3 -1
  187. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  188. package/dist/modes/interactive/components/chat-session-host.js +15 -7
  189. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  190. package/dist/modes/interactive/components/session-selector-delete.d.ts +1 -1
  191. package/dist/modes/interactive/components/session-selector-delete.d.ts.map +1 -1
  192. package/dist/modes/interactive/components/session-selector-delete.js.map +1 -1
  193. package/dist/modes/interactive/components/session-selector-list.d.ts +4 -4
  194. package/dist/modes/interactive/components/session-selector-list.d.ts.map +1 -1
  195. package/dist/modes/interactive/components/session-selector-list.js +13 -12
  196. package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
  197. package/dist/modes/interactive/components/session-selector.d.ts +1 -0
  198. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  199. package/dist/modes/interactive/components/session-selector.js +16 -5
  200. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  201. package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
  202. package/dist/modes/interactive/interactive-mode-helpers.js +6 -2
  203. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  204. package/dist/modes/interactive/interactive-session-routing.js +19 -7
  205. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  206. package/dist/modes/interactive/interactive-slash-commands.js +3 -1
  207. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  208. package/dist/modes/interactive-engine/create-isolated-runtime.d.ts.map +1 -1
  209. package/dist/modes/interactive-engine/create-isolated-runtime.js +8 -1
  210. package/dist/modes/interactive-engine/create-isolated-runtime.js.map +1 -1
  211. package/dist/modes/interactive-engine/engine-args.d.ts.map +1 -1
  212. package/dist/modes/interactive-engine/engine-args.js +5 -1
  213. package/dist/modes/interactive-engine/engine-args.js.map +1 -1
  214. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  215. package/dist/modes/interactive-engine/isolated-runtime.js +21 -15
  216. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  217. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  218. package/dist/modes/rpc/rpc-client-process.js +3 -1
  219. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  220. package/dist/modes/rpc/rpc-command-handler.js +1 -1
  221. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  222. package/dist/modes/rpc/rpc-terminal-drain.d.ts.map +1 -1
  223. package/dist/modes/rpc/rpc-terminal-drain.js +11 -2
  224. package/dist/modes/rpc/rpc-terminal-drain.js.map +1 -1
  225. package/dist/utils/canonical-path.d.ts +5 -0
  226. package/dist/utils/canonical-path.d.ts.map +1 -0
  227. package/dist/utils/canonical-path.js +26 -0
  228. package/dist/utils/canonical-path.js.map +1 -0
  229. package/dist/utils/paths.d.ts +1 -7
  230. package/dist/utils/paths.d.ts.map +1 -1
  231. package/dist/utils/paths.js +1 -15
  232. package/dist/utils/paths.js.map +1 -1
  233. package/docs/codemode.md +2 -0
  234. package/docs/compaction.md +2 -2
  235. package/docs/docs.json +1 -0
  236. package/docs/environment-variables.md +6 -2
  237. package/docs/getting-started/installation.md +1 -1
  238. package/docs/models/reference.md +2 -0
  239. package/docs/models-configuration.md +206 -0
  240. package/docs/models.md +11 -1
  241. package/docs/providers.md +2 -2
  242. package/docs/reference/cli.md +4 -0
  243. package/docs/sdk/web-server.md +3 -3
  244. package/docs/sdk.md +40 -3
  245. package/docs/session-format.md +30 -25
  246. package/docs/sessions.md +43 -17
  247. package/docs/settings.md +31 -9
  248. package/docs/storage.md +85 -2
  249. package/docs/subagents.md +19 -6
  250. package/docs/workflows/api-reference.md +23 -15
  251. package/docs/workflows/operations.md +3 -3
  252. package/docs/workflows/reliable-design.md +16 -16
  253. package/npm-shrinkwrap.json +53 -53
  254. package/package.json +7 -6
  255. package/schemas/models.schema.json +62 -29
  256. package/schemas/settings.schema.json +136 -31
@@ -41097,6 +41097,19 @@ function createSessionScopedSingleton(key, createLocal) {
41097
41097
  function createStageControlRegistry() {
41098
41098
  const _byRun = new Map;
41099
41099
  const pendingDisposals = new Set;
41100
+ const sessionStores = new Map;
41101
+ let generation = 0;
41102
+ function rememberSessionStore(handle) {
41103
+ const store = handle.sessionStore;
41104
+ if (store === undefined)
41105
+ return;
41106
+ let stores = sessionStores.get(handle.runId);
41107
+ if (stores === undefined) {
41108
+ stores = new Map;
41109
+ sessionStores.set(handle.runId, stores);
41110
+ }
41111
+ stores.set(handle.stageId, store);
41112
+ }
41100
41113
  function ensureRun(runId) {
41101
41114
  let runMap = _byRun.get(runId);
41102
41115
  if (!runMap) {
@@ -41184,7 +41197,11 @@ function createStageControlRegistry() {
41184
41197
  };
41185
41198
  }
41186
41199
  return {
41200
+ get generation() {
41201
+ return generation;
41202
+ },
41187
41203
  register(handle) {
41204
+ rememberSessionStore(handle);
41188
41205
  const runMap = ensureRun(handle.runId);
41189
41206
  const displaced = runMap.get(handle.stageId);
41190
41207
  runMap.set(handle.stageId, {
@@ -41201,6 +41218,7 @@ function createStageControlRegistry() {
41201
41218
  if (!existing)
41202
41219
  return;
41203
41220
  if (existing.get(handle.stageId)?.handle === handle) {
41221
+ rememberSessionStore(handle);
41204
41222
  existing.delete(handle.stageId);
41205
41223
  }
41206
41224
  if (existing.size === 0)
@@ -41286,6 +41304,7 @@ function createStageControlRegistry() {
41286
41304
  return false;
41287
41305
  if (handle !== undefined && entry.handle !== handle)
41288
41306
  return false;
41307
+ rememberSessionStore(entry.handle);
41289
41308
  if (!entry.controlsDependencies)
41290
41309
  return false;
41291
41310
  entry.controlsDependencies = false;
@@ -41303,6 +41322,9 @@ function createStageControlRegistry() {
41303
41322
  get(runId, stageId) {
41304
41323
  return _byRun.get(runId)?.get(stageId)?.handle;
41305
41324
  },
41325
+ getSessionStore(runId, stageId) {
41326
+ return _byRun.get(runId)?.get(stageId)?.handle.sessionStore ?? sessionStores.get(runId)?.get(stageId);
41327
+ },
41306
41328
  forRun(runId) {
41307
41329
  const runMap = _byRun.get(runId);
41308
41330
  if (!runMap)
@@ -41315,17 +41337,28 @@ function createStageControlRegistry() {
41315
41337
  run(runId) {
41316
41338
  return makeRunHandle(runId);
41317
41339
  },
41318
- async clear() {
41319
- const entries = [..._byRun.values()].flatMap((runMap) => [...runMap.values()]);
41320
- _byRun.clear();
41340
+ async clear(runId) {
41341
+ if (runId === undefined)
41342
+ generation += 1;
41343
+ const entries = runId === undefined ? [..._byRun.values()].flatMap((runMap) => [...runMap.values()]) : [..._byRun.get(runId)?.values() ?? []];
41344
+ if (runId === undefined) {
41345
+ _byRun.clear();
41346
+ sessionStores.clear();
41347
+ } else {
41348
+ _byRun.get(runId)?.clear();
41349
+ _byRun.delete(runId);
41350
+ sessionStores.delete(runId);
41351
+ }
41321
41352
  await disposeEntries(entries);
41322
41353
  },
41323
41354
  async clearDetached() {
41324
41355
  const entries = [];
41356
+ generation += 1;
41325
41357
  for (const [runId, runMap] of [..._byRun]) {
41326
41358
  for (const [stageId, entry] of [...runMap]) {
41327
41359
  if (entry.controlsDependencies)
41328
41360
  continue;
41361
+ rememberSessionStore(entry.handle);
41329
41362
  runMap.delete(stageId);
41330
41363
  entries.push(entry);
41331
41364
  }
@@ -45031,6 +45064,7 @@ function getDurableBackendProcessOwner() {
45031
45064
  // dist/builtin/workflows/src/durable/journal/types.ts
45032
45065
  import { StorageSchemaVersionError } from "@bastani/atomic/storage";
45033
45066
  import { StorageUnavailableError } from "@bastani/atomic/storage";
45067
+ import { RUN_EVENT_TYPES } from "@bastani/atomic/storage";
45034
45068
  var JOURNAL_SCHEMA_VERSION = 1;
45035
45069
  var JOURNAL_PAYLOAD_ENCODING = "json-text";
45036
45070
  var JOURNAL_TABLES = { meta: "meta", runs: "runs", events: "events", leases: "leases" };
@@ -45052,20 +45086,6 @@ var JOURNAL_COLUMNS = {
45052
45086
  renewedAt: "renewed_at"
45053
45087
  };
45054
45088
  var JOURNAL_LEASE = { initialEpoch: 1, epochIncrement: 1, unheld: null, absentEpoch: 0 };
45055
- var RUN_EVENT_TYPES = {
45056
- runStarted: "RunStarted",
45057
- runFinished: "RunFinished",
45058
- statusChanged: "StatusChanged",
45059
- checkpointRecorded: "CheckpointRecorded",
45060
- promptAsked: "PromptAsked",
45061
- promptReleased: "PromptReleased",
45062
- controlRequested: "ControlRequested",
45063
- messageQueued: "MessageQueued",
45064
- messageDelivered: "MessageDelivered",
45065
- messageSettled: "MessageSettled",
45066
- timerScheduled: "TimerScheduled",
45067
- summaryRecorded: "SummaryRecorded"
45068
- };
45069
45089
 
45070
45090
  class JournalError extends Error {
45071
45091
  }
@@ -45077,19 +45097,6 @@ class JournalClosedError extends JournalError {
45077
45097
  }
45078
45098
  }
45079
45099
 
45080
- class JournalConfigurationError extends JournalError {
45081
- source;
45082
- setting;
45083
- reason;
45084
- constructor(source, setting, reason) {
45085
- super(`Invalid journal configuration at ${source}.${setting}: ${reason}`);
45086
- this.name = "JournalConfigurationError";
45087
- this.source = source;
45088
- this.setting = setting;
45089
- this.reason = reason;
45090
- }
45091
- }
45092
-
45093
45100
  class JournalInvalidTextError extends JournalError {
45094
45101
  field;
45095
45102
  reason;
@@ -45251,18 +45258,15 @@ class ScopedDurableBackend {
45251
45258
  async hasPendingStageDeliveryReceipt(workflowId, messageId, delivery, logicalRunId = workflowId) {
45252
45259
  return await this.inner.hasPendingStageDeliveryReceipt?.(this.scope.rootWorkflowId, messageId, delivery, logicalRunId) ?? false;
45253
45260
  }
45254
- registerWorkflow(_handle) {}
45261
+ async commitWorkflowRegistration(_handle) {}
45255
45262
  persistPendingStageMessages(workflowId, messages, logicalRunId = workflowId) {
45256
45263
  return this.inner.persistPendingStageMessages(this.scope.rootWorkflowId, messages, logicalRunId);
45257
45264
  }
45258
- recordCheckpoint(checkpoint) {
45259
- return this.inner.recordCheckpoint(this.remap(checkpoint));
45260
- }
45261
- async recordCheckpointAsync(checkpoint, options) {
45262
- await this.inner.recordCheckpointAsync(this.remap(checkpoint), options);
45265
+ async commitCheckpoint(checkpoint, options) {
45266
+ await this.inner.commitCheckpoint(this.remap(checkpoint), options);
45263
45267
  }
45264
- async recordAdditiveCheckpointBestEffort(checkpoint) {
45265
- return await this.inner.recordAdditiveCheckpointBestEffort(this.remap(checkpoint));
45268
+ async commitAdditiveCheckpointBestEffort(checkpoint) {
45269
+ return await this.inner.commitAdditiveCheckpointBestEffort(this.remap(checkpoint));
45266
45270
  }
45267
45271
  workflowOwnership(_workflowId) {
45268
45272
  return this.inner.workflowOwnership(this.scope.rootWorkflowId);
@@ -45292,12 +45296,12 @@ class ScopedDurableBackend {
45292
45296
  getLoadableWorkflow(_workflowId) {
45293
45297
  return;
45294
45298
  }
45295
- setWorkflowStatus(_workflowId, _status, _pendingPrompts, _resumable) {}
45296
- async transitionWorkflowStatus(_workflowId, _expectedStatuses, _status, _pendingPrompts, _resumable) {
45299
+ async commitWorkflowStatus(_workflowId, _status, _pendingPrompts, _resumable) {}
45300
+ async commitWorkflowStatusTransition(_workflowId, _expectedStatuses, _status, _pendingPrompts, _resumable) {
45297
45301
  return false;
45298
45302
  }
45299
- adjustPendingPrompts(_workflowId, delta) {
45300
- return this.inner.adjustPendingPrompts(this.scope.rootWorkflowId, delta);
45303
+ commitPendingPromptAdjustment(_workflowId, delta) {
45304
+ return this.inner.commitPendingPromptAdjustment(this.scope.rootWorkflowId, delta);
45301
45305
  }
45302
45306
  promptReservationScope(_workflowId) {
45303
45307
  return this.effectivePromptScope();
@@ -45330,7 +45334,7 @@ class ScopedDurableBackend {
45330
45334
  isWorkflowLoadable(_workflowId) {
45331
45335
  return false;
45332
45336
  }
45333
- reset() {}
45337
+ async commitReset() {}
45334
45338
  hydrateWorkflow(_workflowId) {
45335
45339
  return Promise.resolve();
45336
45340
  }
@@ -46724,19 +46728,9 @@ function createStageStoreMethods(context) {
46724
46728
  if (!run)
46725
46729
  return false;
46726
46730
  const stage = context.findStage(run, stageId);
46727
- if (!stage)
46728
- return false;
46729
- let changed = false;
46730
- if (session.sessionId !== undefined && stage.sessionId !== session.sessionId) {
46731
- stage.sessionId = session.sessionId;
46732
- changed = true;
46733
- }
46734
- if (session.sessionFile !== undefined && stage.sessionFile !== session.sessionFile) {
46735
- stage.sessionFile = session.sessionFile;
46736
- changed = true;
46737
- }
46738
- if (!changed)
46731
+ if (!stage || stage.sessionId === session.sessionId)
46739
46732
  return false;
46733
+ stage.sessionId = session.sessionId;
46740
46734
  context.bumpAndNotify();
46741
46735
  return true;
46742
46736
  },
@@ -48077,6 +48071,7 @@ function isReadOnlyArchiveStatus(status) {
48077
48071
  // dist/builtin/workflows/src/tui/stage-chat-view-state.ts
48078
48072
  function initializeStageChatView(ctx, opts) {
48079
48073
  ctx.store = opts.store;
48074
+ ctx.sessionStore = opts.sessionStore;
48080
48075
  ctx.theme = opts.graphTheme;
48081
48076
  ctx.runId = opts.runId;
48082
48077
  ctx.stageId = opts.stageId;
@@ -48136,7 +48131,7 @@ function initializeStageChatView(ctx, opts) {
48136
48131
  const initialStage = initialRun?.stages.find((s) => s.id === ctx.stageId);
48137
48132
  ctx.lastObservedRunStatus = initialRun?.status;
48138
48133
  ctx.lastObservedStageStatus = initialStage?.status;
48139
- snapshotMessagesFromSessionFile(ctx, initialStage);
48134
+ snapshotMessagesFromSession(ctx, initialStage);
48140
48135
  absorbStageNotices(ctx, initialStage);
48141
48136
  syncPromptState(ctx, initialStage?.pendingPrompt);
48142
48137
  const initialChatIsTerminal = isTerminalStageChatState(initialRun?.status) || isTerminalStageChatState(initialStage?.status);
@@ -48332,11 +48327,22 @@ function snapshotMessagesFromHandle(ctx) {
48332
48327
  ctx.chatHost.appendMessages(handle.messages);
48333
48328
  ctx.chatHost.hydrateStreamingAssistantMessage(handle.agentSession?.agent?.state.streamingMessage);
48334
48329
  }
48335
- function snapshotMessagesFromSessionFile(ctx, stage) {
48330
+ function snapshotMessagesFromSession(ctx, stage) {
48336
48331
  const handle = liveHandle(ctx);
48337
- if (!ctx.chatHost.loadSessionFile(handle?.sessionFile ?? stage?.sessionFile) && !handle) {
48338
- ctx.postMortemUnavailableReason ??= "invalid_session";
48332
+ const sessionId = handle?.sessionId ?? stage?.sessionId;
48333
+ if (sessionId === undefined)
48334
+ return;
48335
+ const sessionStore = handle?.sessionStore ?? handle?.agentSession?.sessionManager.getSessionStore() ?? ctx.sessionStore;
48336
+ if (sessionStore === undefined) {
48337
+ if (!handle)
48338
+ ctx.postMortemUnavailableReason ??= "invalid_session";
48339
+ return;
48339
48340
  }
48341
+ ctx.chatHost.loadSession(sessionStore, sessionId).then((loaded) => {
48342
+ if (!loaded && !liveHandle(ctx))
48343
+ ctx.postMortemUnavailableReason ??= "invalid_session";
48344
+ ctx.requestRender?.();
48345
+ });
48340
48346
  }
48341
48347
  function absorbStageNotices(ctx, stage) {
48342
48348
  const notices = stage?.notices;
@@ -48504,7 +48510,7 @@ function isReadOnlyArchive(ctx, stage = currentStage(ctx)) {
48504
48510
  return false;
48505
48511
  if (!stage)
48506
48512
  return true;
48507
- return isReadOnlyArchiveStatus(stage.status) || Boolean(stage.sessionFile);
48513
+ return isReadOnlyArchiveStatus(stage.status) || stage.sessionId !== undefined;
48508
48514
  }
48509
48515
  async function handleSlashCommand(ctx, text) {
48510
48516
  const [command, ...rest] = text.trim().split(/\s+/);
@@ -48566,6 +48572,8 @@ function promptPageSize(ctx) {
48566
48572
  // dist/builtin/workflows/src/tui/stage-chat-view-archive-history.ts
48567
48573
  function postMortemUnavailableMessage(reason) {
48568
48574
  switch (reason) {
48575
+ case "closed":
48576
+ return "Post-mortem chat is unavailable because its owning session has closed.";
48569
48577
  case "no_adapter":
48570
48578
  return "Post-mortem chat is unavailable because no agent session adapter is configured.";
48571
48579
  case "not_terminal":
@@ -48573,7 +48581,7 @@ function postMortemUnavailableMessage(reason) {
48573
48581
  case "no_session":
48574
48582
  return "No retained agent session is available for this stage.";
48575
48583
  case "invalid_session":
48576
- return "The retained session is missing, unreadable, or invalid. Check that the session file still exists and is readable.";
48584
+ return "The retained session is missing, unreadable, or invalid in the selected session store.";
48577
48585
  case undefined:
48578
48586
  return;
48579
48587
  }
@@ -48586,7 +48594,7 @@ function renderReadOnlyArchiveBody(ctx, width, budget, stage, indicatorLines = [
48586
48594
  const unavailableMessage = postMortemUnavailableMessage(ctx.postMortemUnavailableReason);
48587
48595
  const callout = [];
48588
48596
  callout.push(blankLine(width));
48589
- callout.push(...bannerLines(ctx, width, unavailableMessage === undefined ? "info" : "warning", unavailableMessage === undefined ? "◌" : "!", unavailableMessage === undefined ? "READ-ONLY SESSION" : "SESSION UNAVAILABLE", unavailableMessage === undefined ? stage?.sessionFile ? "archived transcript" : "no live chat session" : "post-mortem chat cannot be reopened"));
48597
+ callout.push(...bannerLines(ctx, width, unavailableMessage === undefined ? "info" : "warning", unavailableMessage === undefined ? "◌" : "!", unavailableMessage === undefined ? "READ-ONLY SESSION" : "SESSION UNAVAILABLE", unavailableMessage === undefined ? stage?.sessionId !== undefined ? "archived transcript" : "no live chat session" : "post-mortem chat cannot be reopened"));
48590
48598
  callout.push(...new Text3(paint2(unavailableMessage ?? "This node is no longer attached to a live chat session.", t.textMuted), 2, 0).render(width));
48591
48599
  const transcriptBudget = Math.max(0, budget - callout.length);
48592
48600
  const reservedIndicatorRows = indicatorLines.length > 0 && transcriptBudget > indicatorLines.length ? indicatorLines.length : 0;
@@ -49275,6 +49283,9 @@ function resolveAttachedStageHandle(registry, resolvePostMortemHandle, runId, st
49275
49283
  if (liveHandle !== undefined)
49276
49284
  return { handle: liveHandle };
49277
49285
  const postMortem = resolvePostMortemHandle?.(runId, stageId);
49286
+ return postMortem instanceof Promise ? postMortem.then(attachedResolution, () => ({ postMortemUnavailableReason: "invalid_session" })) : attachedResolution(postMortem);
49287
+ }
49288
+ function attachedResolution(postMortem) {
49278
49289
  if (postMortem?.ok === true)
49279
49290
  return { handle: postMortem.handle };
49280
49291
  return postMortem?.ok === false ? { postMortemUnavailableReason: postMortem.reason } : {};
@@ -49285,6 +49296,7 @@ var ENTER_TRANSITION_QUARANTINE_MS = 200;
49285
49296
 
49286
49297
  class WorkflowAttachPane {
49287
49298
  store;
49299
+ sessionStore;
49288
49300
  theme;
49289
49301
  runId;
49290
49302
  registry;
@@ -49305,6 +49317,7 @@ class WorkflowAttachPane {
49305
49317
  now;
49306
49318
  mode = "graph";
49307
49319
  visible = true;
49320
+ attachmentGeneration = 0;
49308
49321
  graphView;
49309
49322
  chatView = null;
49310
49323
  unsubscribeStore = null;
@@ -49317,6 +49330,7 @@ class WorkflowAttachPane {
49317
49330
  lastStageAwaitingInputKey = null;
49318
49331
  constructor(opts) {
49319
49332
  this.store = opts.store;
49333
+ this.sessionStore = opts.sessionStore;
49320
49334
  this.theme = opts.graphTheme;
49321
49335
  this.runId = opts.runId;
49322
49336
  this.registry = opts.stageControlRegistry;
@@ -49391,7 +49405,8 @@ class WorkflowAttachPane {
49391
49405
  const run = snap.runs.find((r) => r.id === runId);
49392
49406
  return run?.name ?? "workflow";
49393
49407
  }
49394
- _attachToStage(runId, stageId, options = { suppressInitialPromptSubmit: true }) {
49408
+ async _attachToStage(runId, stageId, options = { suppressInitialPromptSubmit: true }) {
49409
+ const generation = ++this.attachmentGeneration;
49395
49410
  this.graphEnterQuarantineUntil = 0;
49396
49411
  const snapshot = readGraphStoreSnapshot(this.store);
49397
49412
  const graphRunId = this._resolveRunId();
@@ -49400,11 +49415,15 @@ class WorkflowAttachPane {
49400
49415
  this.stagePromptEnterQuarantineUntil = options.suppressInitialPromptSubmit === true && this.lastStageAwaitingInputKey !== null ? this.now() + ENTER_TRANSITION_QUARANTINE_MS : 0;
49401
49416
  this.attachedRunId = runId;
49402
49417
  this.lastAttachedStageId = stageId;
49403
- const { handle, postMortemUnavailableReason } = resolveAttachedStageHandle(this.registry, this.resolvePostMortemHandle, runId, stageId);
49418
+ const resolution = resolveAttachedStageHandle(this.registry, this.resolvePostMortemHandle, runId, stageId);
49419
+ const { handle, postMortemUnavailableReason } = resolution instanceof Promise ? await resolution : resolution;
49420
+ if (generation !== this.attachmentGeneration || !this.visible)
49421
+ return;
49404
49422
  this.chatView?.dispose();
49405
49423
  let chatView;
49406
49424
  chatView = new StageChatView({
49407
49425
  store: this.store,
49426
+ sessionStore: this.sessionStore,
49408
49427
  graphTheme: this.theme,
49409
49428
  runId,
49410
49429
  stageId,
@@ -49430,8 +49449,10 @@ class WorkflowAttachPane {
49430
49449
  this.chatView = chatView;
49431
49450
  this.mode = "stage-chat";
49432
49451
  this.store.recordStageAttached(runId, stageId, this.visible);
49452
+ this.hostRequestRender?.();
49433
49453
  }
49434
49454
  _detachFromStage(reason = "user", metadata = {}) {
49455
+ this.attachmentGeneration += 1;
49435
49456
  this.composerDrafts.capture(this.attachedRunId, this.lastAttachedStageId, this.chatView?._inputBuffer);
49436
49457
  if (this.chatView && this.attachedRunId && this.lastAttachedStageId) {
49437
49458
  this.store.recordStageAttached(this.attachedRunId, this.lastAttachedStageId, false);
@@ -49448,6 +49469,7 @@ class WorkflowAttachPane {
49448
49469
  this.graphEnterQuarantineUntil = reason === "prompt-resolved" && metadata.suppressNextGraphSubmit === true ? this.now() + ENTER_TRANSITION_QUARANTINE_MS : 0;
49449
49470
  }
49450
49471
  retarget(runId, stageId, stageRunId) {
49472
+ this.attachmentGeneration += 1;
49451
49473
  if (this.chatView && this.attachedRunId && this.lastAttachedStageId) {
49452
49474
  this.store.recordStageAttached(this.attachedRunId, this.lastAttachedStageId, false);
49453
49475
  }
@@ -49521,6 +49543,8 @@ class WorkflowAttachPane {
49521
49543
  }
49522
49544
  setVisible(visible) {
49523
49545
  this.visible = visible;
49546
+ if (!visible)
49547
+ this.attachmentGeneration += 1;
49524
49548
  if (this.mode === "stage-chat" && this.attachedRunId && this.lastAttachedStageId) {
49525
49549
  this.store.recordStageAttached(this.attachedRunId, this.lastAttachedStageId, visible);
49526
49550
  }
@@ -49667,6 +49691,7 @@ class WorkflowAttachPane {
49667
49691
  this.graphView.invalidate();
49668
49692
  }
49669
49693
  dispose() {
49694
+ this.attachmentGeneration += 1;
49670
49695
  this.unsubscribeStore?.();
49671
49696
  this.unsubscribeStore = null;
49672
49697
  if (this.chatView && this.attachedRunId && this.lastAttachedStageId) {
@@ -49843,8 +49868,8 @@ function buildGraphOverlayAdapter(pi, store, buildOpts = {}) {
49843
49868
  const ui = surface?.ui ?? pi.ui;
49844
49869
  observeHostCustomUi(ui);
49845
49870
  if (mounted && currentHandle?.isHidden()) {
49846
- currentView?.retarget(runId, stageId, stageRunId);
49847
49871
  currentView?.setVisible(true);
49872
+ currentView?.retarget(runId, stageId, stageRunId);
49848
49873
  updateTerminalAutowrap(true);
49849
49874
  currentHandle.setHidden(false);
49850
49875
  currentHandle.focus();
@@ -49889,6 +49914,7 @@ function buildGraphOverlayAdapter(pi, store, buildOpts = {}) {
49889
49914
  graphTheme: deriveGraphThemeFromPiTheme(theme),
49890
49915
  runId,
49891
49916
  stageControlRegistry: registry,
49917
+ sessionStore: buildOpts.resolveSessionStore?.(),
49892
49918
  resolvePostMortemHandle,
49893
49919
  stageUiBroker,
49894
49920
  onClose: finish,
@@ -51232,11 +51258,15 @@ var POST_MORTEM_ATTACH_TIMEOUT_MS = 1e4;
51232
51258
  function registerCompletedStageIntercomAskRouter(pi, resolveHandle) {
51233
51259
  const queues = new Map;
51234
51260
  let disposed = false;
51261
+ const assertActive = () => {
51262
+ if (disposed)
51263
+ throw new Error("Intercom ask target is unavailable: its owning session has closed.");
51264
+ };
51235
51265
  const subscription = pi.events?.on?.(LATE_STAGE_MESSAGE_EVENT, (payload) => {
51236
51266
  if (disposed || !isCompletedStageAskEvent(payload) || payload.handled === true)
51237
51267
  return;
51238
51268
  payload.handled = true;
51239
- payload.completion = enqueueTargetTurn(queues, `${payload.workflowRunId}:${payload.workflowStageId}`, () => deliverAsPostMortemTurn(payload, resolveHandle));
51269
+ payload.completion = enqueueTargetTurn(queues, `${payload.workflowRunId}:${payload.workflowStageId}`, () => deliverAsPostMortemTurn(payload, resolveHandle, assertActive));
51240
51270
  });
51241
51271
  const dispose = () => {
51242
51272
  disposed = true;
@@ -51263,8 +51293,10 @@ function enqueueTargetTurn(queues, key, deliver) {
51263
51293
  }).catch(() => {});
51264
51294
  return current;
51265
51295
  }
51266
- async function deliverAsPostMortemTurn(event, resolveHandle) {
51267
- const resolution = resolveHandle(event.workflowRunId, event.workflowStageId);
51296
+ async function deliverAsPostMortemTurn(event, resolveHandle, assertActive) {
51297
+ assertActive();
51298
+ const resolution = await resolveHandle(event.workflowRunId, event.workflowStageId);
51299
+ assertActive();
51268
51300
  if (resolution === undefined) {
51269
51301
  throw new Error(`Intercom ask target is unavailable: completed workflow stage ${event.workflowRunId}/${event.workflowStageId} was deleted or is no longer retained.`);
51270
51302
  }
@@ -51277,6 +51309,7 @@ async function deliverAsPostMortemTurn(event, resolveHandle) {
51277
51309
  }
51278
51310
  await attachWithTimeout(handle);
51279
51311
  for (const message of event.messages) {
51312
+ assertActive();
51280
51313
  if (handle.isStreaming)
51281
51314
  await handle.followUp(message.content);
51282
51315
  else
@@ -51298,6 +51331,8 @@ async function attachWithTimeout(handle) {
51298
51331
  function unavailableReason(runId, stageId, reason) {
51299
51332
  const target = `${runId}/${stageId}`;
51300
51333
  switch (reason) {
51334
+ case "closed":
51335
+ return `Intercom ask target is unavailable: the owning session for workflow stage ${target} has closed.`;
51301
51336
  case "not_terminal":
51302
51337
  return `Intercom ask target is not resumable: workflow stage ${target} is not a completed stage with a retained conversation.`;
51303
51338
  case "no_session":
@@ -51316,7 +51351,7 @@ import { registerExtensionContextRetirementEffect, sessionScopedExtensionState a
51316
51351
  var releasedRuns = new WeakMap;
51317
51352
  async function releasePausedRunsOwnedBy(backend, modelOwner) {
51318
51353
  const settled = await Promise.allSettled(backend.listResumableWorkflows().filter((entry) => entry.status === "paused" && entry.modelOwner === modelOwner).map(async (entry) => {
51319
- const released = await backend.transitionWorkflowStatus(entry.workflowId, ["paused"], "paused", undefined, undefined, undefined, undefined, modelOwner);
51354
+ const released = await backend.commitWorkflowStatusTransition(entry.workflowId, ["paused"], "paused", undefined, undefined, undefined, undefined, modelOwner);
51320
51355
  return released ? entry.workflowId : undefined;
51321
51356
  }));
51322
51357
  const failures = settled.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
@@ -51337,7 +51372,7 @@ async function reclaimReleasedRunsOwnedBy(backend, modelOwner) {
51337
51372
  const handle = backend.getWorkflow(entry.workflowId);
51338
51373
  return handle?.releasedModelOwner === modelOwner ? [handle] : [];
51339
51374
  }).map(async (handle) => {
51340
- const reclaimed = await backend.transitionWorkflowStatus(handle.workflowId, ["paused"], "paused", undefined, undefined, handle.updatedAt);
51375
+ const reclaimed = await backend.commitWorkflowStatusTransition(handle.workflowId, ["paused"], "paused", undefined, undefined, handle.updatedAt);
51341
51376
  if (reclaimed)
51342
51377
  releasedRuns.get(backend)?.delete(handle.workflowId);
51343
51378
  }));
@@ -52407,7 +52442,7 @@ async function recordRunTimingCheckpointAsync(backend, run, options) {
52407
52442
  return false;
52408
52443
  for (const checkpoint of checkpoints)
52409
52444
  if (checkpoint !== undefined)
52410
- await backend.recordCheckpointAsync(checkpoint);
52445
+ await backend.commitCheckpoint(checkpoint);
52411
52446
  return true;
52412
52447
  }
52413
52448
  function runTimingCheckpoint(backend, run, options) {
@@ -52461,12 +52496,42 @@ function inheritedRunElapsedMs(input) {
52461
52496
  // dist/builtin/workflows/src/shared/resume-continuation.ts
52462
52497
  var RESUME_CONTINUATION_PROMPT = "Continue where you left off. If you believe you are finished with your original task (or a redefined task if the user told you), stop.";
52463
52498
 
52499
+ // dist/builtin/workflows/src/durable/backend.ts
52500
+ import { closeSync, openSync, readSync } from "node:fs";
52501
+
52464
52502
  // dist/builtin/workflows/src/durable/types.ts
52465
52503
  var DURABLE_TOOL_TOPOLOGY_VERSION = 1;
52466
52504
  var DURABLE_STAGE_TOPOLOGY_VERSION = 1;
52467
52505
  var DURABLE_BOUNDARY_TOPOLOGY_VERSION = 1;
52468
52506
 
52469
52507
  // dist/builtin/workflows/src/durable/backend.ts
52508
+ var SESSION_HEADER_READ_LIMIT_BYTES = 64 * 1024;
52509
+ function readSessionHeaderId(sessionFile) {
52510
+ let fd;
52511
+ try {
52512
+ fd = openSync(sessionFile, "r");
52513
+ } catch {
52514
+ return;
52515
+ }
52516
+ try {
52517
+ const buffer = Buffer.alloc(SESSION_HEADER_READ_LIMIT_BYTES);
52518
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, 0);
52519
+ const firstLine = buffer.subarray(0, bytesRead).toString("utf8").replace(/^\uFEFF/, "").split(`
52520
+ `)[0];
52521
+ const header = JSON.parse(firstLine ?? "");
52522
+ return header.type === "session" && typeof header.id === "string" ? header.id : undefined;
52523
+ } catch {
52524
+ return;
52525
+ } finally {
52526
+ closeSync(fd);
52527
+ }
52528
+ }
52529
+ function migrateStageSessionCheckpoint(checkpoint) {
52530
+ if (checkpoint.sessionId !== undefined || checkpoint.sessionFile === undefined)
52531
+ return checkpoint;
52532
+ const sessionId = readSessionHeaderId(checkpoint.sessionFile);
52533
+ return sessionId === undefined ? checkpoint : { ...checkpoint, sessionId };
52534
+ }
52470
52535
  function replacePendingStageMessagesForRun(existing, logicalRunId, messages) {
52471
52536
  if (messages.some((entry) => entry.runId !== logicalRunId)) {
52472
52537
  throw new Error(`atomic-workflows: pending-stage persistence mixed logical run ${logicalRunId}`);
@@ -52601,7 +52666,8 @@ class JournalProjection {
52601
52666
  return this.stickyReceipts.get(workflowId)?.has(name) ?? false;
52602
52667
  });
52603
52668
  }
52604
- recordCheckpoint(checkpoint) {
52669
+ recordCheckpoint(recorded) {
52670
+ const checkpoint = recorded.kind === "stage" ? migrateStageSessionCheckpoint(recorded) : recorded;
52605
52671
  const currentCheckpoint = checkpoint.kind === "stage" && checkpoint.topology === undefined ? {
52606
52672
  ...checkpoint,
52607
52673
  topology: {
@@ -52627,7 +52693,7 @@ class JournalProjection {
52627
52693
  } else {
52628
52694
  if ("output" in currentCheckpoint)
52629
52695
  rec.stageOutputByReplayKey.set(currentCheckpoint.replayKey, currentCheckpoint);
52630
- if (currentCheckpoint.sessionId !== undefined || currentCheckpoint.sessionFile !== undefined) {
52696
+ if (currentCheckpoint.sessionId !== undefined) {
52631
52697
  const existing = rec.stageSessionByReplayKey.get(currentCheckpoint.replayKey);
52632
52698
  if (existing === undefined || currentCheckpoint.completedAt >= existing.completedAt) {
52633
52699
  rec.stageSessionByReplayKey.set(currentCheckpoint.replayKey, currentCheckpoint);
@@ -52655,7 +52721,7 @@ class JournalProjection {
52655
52721
  }
52656
52722
  getStageSession(workflowId, replayKey) {
52657
52723
  const checkpoint = this.workflows.get(workflowId)?.stageSessionByReplayKey.get(replayKey);
52658
- if (checkpoint?.sessionId === undefined && checkpoint?.sessionFile === undefined)
52724
+ if (checkpoint?.sessionId === undefined)
52659
52725
  return;
52660
52726
  return {
52661
52727
  ...checkpoint.sessionId !== undefined ? { sessionId: checkpoint.sessionId } : {},
@@ -53005,9 +53071,10 @@ function replayedWorkflowToolOutcome(outcome) {
53005
53071
 
53006
53072
  // dist/builtin/workflows/src/durable/tool-failure-checkpoint.ts
53007
53073
  async function recordThrowingToolFailure(input, node, identity, error, attempts, cancelled = false) {
53074
+ await input.beforeCheckpoint?.();
53008
53075
  const message = workflowToolFailure(error, attempts, false).error.message;
53009
53076
  const failedAt = Date.now();
53010
- await input.backend.recordAdditiveCheckpointBestEffort({
53077
+ await input.backend.commitAdditiveCheckpointBestEffort({
53011
53078
  kind: "tool",
53012
53079
  workflowId: input.workflowId,
53013
53080
  checkpointId: `tool-failure:${identity.argsHash}:${input.nextCheckpointId()}`,
@@ -53335,6 +53402,21 @@ async function executeLiveToolInvocation(live) {
53335
53402
  const startedAt = Date.now();
53336
53403
  let attempts = 0;
53337
53404
  let callbackCompleted = false;
53405
+ const cancelInvocation = async (cancellation) => {
53406
+ control.noteCancelled();
53407
+ if (returnFailure || isWorkflowToolAbortError(cancellation) && cancellation.scope === "node" || input.runFailing?.() === true) {
53408
+ await recordCancelledToolInspection(live, startedAt, cancellation, attempts);
53409
+ }
53410
+ const endedAt = Date.now();
53411
+ input.onNodeEnd?.(node.id, {
53412
+ status: "cancelled",
53413
+ endedAt,
53414
+ durationMs: Math.max(0, endedAt - startedAt),
53415
+ error: cancellation.message
53416
+ });
53417
+ input.onNodeSettle?.(node.id);
53418
+ throw cancellation;
53419
+ };
53338
53420
  input.onNodeRunning?.(node.id, startedAt);
53339
53421
  try {
53340
53422
  const result = await executeWithRetries(() => {
@@ -53371,6 +53453,8 @@ async function executeLiveToolInvocation(live) {
53371
53453
  ...input.runTopology !== undefined ? { run: { ...input.runTopology } } : {}
53372
53454
  }
53373
53455
  };
53456
+ await input.beforeCheckpoint?.();
53457
+ throwIfInvocationCancelled(input, toolSignal);
53374
53458
  await recordCheckpointDurably(input.backend, checkpoint);
53375
53459
  input.onNodeEnd?.(node.id, {
53376
53460
  status: "completed",
@@ -53384,21 +53468,8 @@ async function executeLiveToolInvocation(live) {
53384
53468
  } catch (error) {
53385
53469
  const timeoutFailure = error instanceof WorkflowToolTimeoutError;
53386
53470
  const cancellation = timeoutFailure ? undefined : invocationCancellation(input, toolSignal);
53387
- if (cancellation !== undefined) {
53388
- control.noteCancelled();
53389
- if (returnFailure || isWorkflowToolAbortError(cancellation) && cancellation.scope === "node" || input.runFailing?.() === true) {
53390
- await recordCancelledToolInspection(live, startedAt, cancellation, attempts);
53391
- }
53392
- const endedAt = Date.now();
53393
- input.onNodeEnd?.(node.id, {
53394
- status: "cancelled",
53395
- endedAt,
53396
- durationMs: Math.max(0, endedAt - startedAt),
53397
- error: cancellation.message
53398
- });
53399
- input.onNodeSettle?.(node.id);
53400
- throw cancellation;
53401
- }
53471
+ if (cancellation !== undefined)
53472
+ return await cancelInvocation(cancellation);
53402
53473
  const callbackFailure = callbackError ?? error;
53403
53474
  if (returnFailure && !callbackCompleted && isExplicitCallbackCancellation(callbackFailure)) {
53404
53475
  input.onFailureObserved?.(callbackFailure, node.id);
@@ -53438,8 +53509,14 @@ async function executeLiveToolInvocation(live) {
53438
53509
  }
53439
53510
  };
53440
53511
  try {
53512
+ await input.beforeCheckpoint?.();
53513
+ if (!timeoutFailure)
53514
+ throwIfInvocationCancelled(input, toolSignal);
53441
53515
  await recordCheckpointDurably(input.backend, checkpoint);
53442
53516
  } catch (persistenceError) {
53517
+ const cancellation = timeoutFailure ? undefined : invocationCancellation(input, toolSignal);
53518
+ if (cancellation !== undefined)
53519
+ return await cancelInvocation(cancellation);
53443
53520
  input.onFailureObserved?.(persistenceError, node.id);
53444
53521
  const endedAt = Date.now();
53445
53522
  input.onNodeEnd?.(node.id, {
@@ -53590,7 +53667,7 @@ async function recordReplayedToolTopology(input, node, cached, argsHash, endedAt
53590
53667
  const unchanged = JSON.stringify(cached.topology.parentIds) === JSON.stringify(topology.parentIds) && JSON.stringify(cached.topology.run) === JSON.stringify(topology.run) && cached.topology.endedAt === topology.endedAt;
53591
53668
  if (unchanged)
53592
53669
  return;
53593
- await input.backend.recordAdditiveCheckpointBestEffort({
53670
+ await input.backend.commitAdditiveCheckpointBestEffort({
53594
53671
  kind: "tool",
53595
53672
  workflowId: input.workflowId,
53596
53673
  checkpointId: `tool-replay-meta:${durableHash({ argsHash, topology })}`,
@@ -53612,7 +53689,7 @@ function summarizeToolResult(value2) {
53612
53689
  return serialized.length <= 240 ? serialized : `${flattenTruncatedString(serialized.slice(0, 237))}...`;
53613
53690
  }
53614
53691
  async function recordCheckpointDurably(backend, checkpoint, signal) {
53615
- await backend.recordCheckpointAsync(checkpoint, signal === undefined ? undefined : { signal });
53692
+ await backend.commitCheckpoint(checkpoint, signal === undefined ? undefined : { signal });
53616
53693
  }
53617
53694
  async function executeWithRetries(fn, options, throwIfCancelled, signal) {
53618
53695
  throwIfCancelled();
@@ -53705,6 +53782,7 @@ async function recordStageCheckpoint(deps, stage, options) {
53705
53782
  completedAt: stage.endedAt ?? Date.now(),
53706
53783
  ...metadata
53707
53784
  };
53785
+ await deps.beforeCheckpoint?.();
53708
53786
  await recordCheckpointDurably(deps.backend, checkpoint);
53709
53787
  return true;
53710
53788
  }
@@ -53714,12 +53792,12 @@ function stageSessionDurationBucket(durationMs) {
53714
53792
  }
53715
53793
  async function recordStageSessionCheckpoint(deps, stage, options) {
53716
53794
  const replayKey = deps.replayKeyForCompletedStage?.(stage) ?? stage.replayKey ?? deps.nextReplayKey(stage.name);
53717
- if (stage.sessionFile === undefined)
53795
+ if (stage.sessionId === undefined)
53718
53796
  return false;
53719
53797
  const checkpointNow = deps.now?.() ?? Date.now();
53720
53798
  const durationMs = elapsedStageMs(stage, checkpointNow) ?? 0;
53721
53799
  const current = deps.backend.getStageSession(deps.workflowId, replayKey);
53722
- if (options?.force !== true && current !== undefined && current.sessionId === stage.sessionId && current.sessionFile === stage.sessionFile && current.startedAt === stage.startedAt && stageSessionDurationBucket(current.durationMs) === stageSessionDurationBucket(durationMs))
53800
+ if (options?.force !== true && current !== undefined && current.sessionId === stage.sessionId && current.startedAt === stage.startedAt && stageSessionDurationBucket(current.durationMs) === stageSessionDurationBucket(durationMs))
53723
53801
  return false;
53724
53802
  const checkpoint = {
53725
53803
  kind: "stage",
@@ -53734,6 +53812,7 @@ async function recordStageSessionCheckpoint(deps, stage, options) {
53734
53812
  durationMs,
53735
53813
  completedAt: checkpointNow
53736
53814
  };
53815
+ await deps.beforeCheckpoint?.();
53737
53816
  await recordCheckpointDurably(deps.backend, checkpoint);
53738
53817
  return true;
53739
53818
  }
@@ -53760,10 +53839,10 @@ function createDurableStagePrimitive(input) {
53760
53839
  const cached = stageCheckpointWithOutput(input.backend, input.workflowId, replayKey);
53761
53840
  if (cached !== undefined) {
53762
53841
  const recorded = input.recordCachedStage?.(name, replayKey, cached);
53763
- return createCachedStageContext(name, cached.output, cached.result, recorded);
53842
+ return withStageWriteBarrier(createCachedStageContext(name, cached.output, cached.result, recorded), input.beforeCall);
53764
53843
  }
53765
53844
  const session = input.backend.getStageSession(input.workflowId, replayKey);
53766
- const isMidSessionResume = session?.sessionFile !== undefined;
53845
+ const isMidSessionResume = session?.sessionId !== undefined;
53767
53846
  const topology = activeStageTopology(input.backend, input.workflowId, replayKey);
53768
53847
  const durableStageId = topology?.stageId ?? pendingStageIdForReplay(input.backend, input.workflowId, replayKey, name);
53769
53848
  const durableIntercomGroup = topology?.intercomGroup ?? input.durableIntercomGroup?.(replayKey, durableStageId);
@@ -53774,12 +53853,13 @@ function createDurableStagePrimitive(input) {
53774
53853
  ...topology !== undefined ? { durableParentIds: [...topology.parentIds] } : {},
53775
53854
  ...durableIntercomGroup !== undefined ? { durableIntercomGroup } : {},
53776
53855
  ...isMidSessionResume ? {
53777
- resumeFromSessionFile: session.sessionFile,
53856
+ resumeFromSessionId: session.sessionId,
53857
+ ...session.sessionFile !== undefined ? { resumeFromLegacySessionFile: session.sessionFile } : {},
53778
53858
  routerSelection: session.routerSelection,
53779
53859
  durableAccumulatedDurationMs: session.durationMs ?? 0
53780
53860
  } : {}
53781
53861
  };
53782
- const live = withMidSessionResumePrompt(input.stage(name, liveOptions, replayKey), isMidSessionResume);
53862
+ const live = withStageWriteBarrier(withMidSessionResumePrompt(input.stage(name, liveOptions, replayKey), isMidSessionResume), input.beforeCall);
53783
53863
  if (options?.schema === undefined)
53784
53864
  return live;
53785
53865
  return wrapSchemaStageForDurability({
@@ -53787,10 +53867,31 @@ function createDurableStagePrimitive(input) {
53787
53867
  workflowId: input.workflowId,
53788
53868
  backend: input.backend,
53789
53869
  replayKey,
53870
+ beforeCheckpoint: input.beforeCheckpoint,
53790
53871
  name
53791
53872
  });
53792
53873
  };
53793
53874
  }
53875
+ function withStageWriteBarrier(stage, beforeCall) {
53876
+ if (beforeCall === undefined)
53877
+ return stage;
53878
+ const wrapped = Object.create(stage);
53879
+ Object.defineProperties(wrapped, {
53880
+ prompt: {
53881
+ value: async (...args) => {
53882
+ await beforeCall();
53883
+ return stage.prompt(...args);
53884
+ }
53885
+ },
53886
+ complete: {
53887
+ value: async (...args) => {
53888
+ await beforeCall();
53889
+ return stage.complete(...args);
53890
+ }
53891
+ }
53892
+ });
53893
+ return wrapped;
53894
+ }
53794
53895
  var TASK_RESULT_CHECKPOINT_CONTROL_PREFIX = "task-checkpoint:";
53795
53896
  function createDurableTaskPrimitive(input) {
53796
53897
  return async (name, options, stageFailFastScope) => {
@@ -53811,8 +53912,9 @@ function createDurableTaskPrimitive(input) {
53811
53912
  durableParentIds: [...topology.parentIds]
53812
53913
  } : {},
53813
53914
  ...durableIntercomGroup !== undefined ? { durableIntercomGroup } : {},
53814
- ...session?.sessionFile !== undefined ? {
53815
- resumeFromSessionFile: session.sessionFile,
53915
+ ...session?.sessionId !== undefined ? {
53916
+ resumeFromSessionId: session.sessionId,
53917
+ ...session.sessionFile !== undefined ? { resumeFromLegacySessionFile: session.sessionFile } : {},
53816
53918
  routerSelection: session.routerSelection,
53817
53919
  durableAccumulatedDurationMs: session.durationMs ?? 0
53818
53920
  } : {}
@@ -53829,6 +53931,9 @@ function createDurableTaskPrimitive(input) {
53829
53931
  });
53830
53932
  const signal = mergeAbortSignals(input.signal, tailController.signal);
53831
53933
  try {
53934
+ await input.beforeCheckpoint?.();
53935
+ if (signal?.aborted)
53936
+ throw abortReasonError(signal);
53832
53937
  await awaitAbortable(signal, recordCheckpointDurably(input.backend, {
53833
53938
  kind: "stage",
53834
53939
  workflowId: input.workflowId,
@@ -53960,6 +54065,7 @@ function wrapSchemaStageForDurability(input) {
53960
54065
  value: async (text, options) => {
53961
54066
  const result = await stage.prompt(text, options);
53962
54067
  if (typeof result !== "string" || result.length === 0) {
54068
+ await input.beforeCheckpoint?.();
53963
54069
  await recordCheckpointDurably(input.backend, {
53964
54070
  kind: "stage",
53965
54071
  workflowId: input.workflowId,
@@ -54104,7 +54210,6 @@ function stableCheckpointId(kind, replayKey) {
54104
54210
  function stageSessionCheckpointId(replayKey, stage, durationMs) {
54105
54211
  return `${stableCheckpointId("stage-session", replayKey)}:${durableHash({
54106
54212
  sessionId: stage.sessionId ?? "",
54107
- sessionFile: stage.sessionFile ?? "",
54108
54213
  startedAt: stage.startedAt ?? 0,
54109
54214
  durationMs
54110
54215
  })}`;
@@ -54199,7 +54304,7 @@ function getLoadableDurableWorkflow(backend, workflowId) {
54199
54304
  return backend.getLoadableWorkflow(workflowId);
54200
54305
  }
54201
54306
  async function transitionDurableWorkflowStatus(backend, workflowId, expectedStatuses, status, pendingPrompts, resumable) {
54202
- return await backend.transitionWorkflowStatus(workflowId, expectedStatuses, status, pendingPrompts, resumable);
54307
+ return await backend.commitWorkflowStatusTransition(workflowId, expectedStatuses, status, pendingPrompts, resumable);
54203
54308
  }
54204
54309
  // dist/builtin/workflows/src/runs/background/workflow-lifecycle-aggregate.ts
54205
54310
  function expandedControlRunIds(store, runId) {
@@ -56804,25 +56909,10 @@ function formatStartupDiagnostics(configResult, discoveryResult) {
56804
56909
  }
56805
56910
 
56806
56911
  // dist/builtin/workflows/src/shared/session-transcript.ts
56807
- import { readFileSync, statSync } from "node:fs";
56808
- function isReopenableSessionTranscript(path) {
56912
+ async function isReopenableSession(store, sessionId) {
56809
56913
  try {
56810
- const stats = statSync(path);
56811
- if (!stats.isFile() || stats.size === 0)
56812
- return false;
56813
- const lines = readFileSync(path, "utf8").split(`
56814
- `).filter((line) => line.trim().length > 0);
56815
- if (lines.length < 2)
56816
- return false;
56817
- const entries = [];
56818
- for (const line of lines) {
56819
- const parsed = JSON.parse(line);
56820
- if (typeof parsed !== "object" || parsed === null)
56821
- return false;
56822
- entries.push(parsed);
56823
- }
56824
- const header = entries[0];
56825
- return header?.type === "session" && typeof header.id === "string" && entries.some(isUsableContextMessage);
56914
+ const snapshot = await store.load(sessionId);
56915
+ return snapshot.header.id === sessionId && snapshot.entries.some(isUsableContextMessage);
56826
56916
  } catch {
56827
56917
  return false;
56828
56918
  }
@@ -56842,6 +56932,60 @@ function hasUsableContentBlock(block) {
56842
56932
  return [contentBlock.text, contentBlock.thinking, contentBlock.data, contentBlock.name].some((value2) => typeof value2 === "string" && value2.trim().length > 0);
56843
56933
  }
56844
56934
 
56935
+ // dist/builtin/workflows/src/shared/stage-session-store.ts
56936
+ import { randomUUID as randomUUID3 } from "node:crypto";
56937
+ import { dirname, resolve as resolve2 } from "node:path";
56938
+ import {
56939
+ JsonlSessionStore,
56940
+ resolveSessionStore,
56941
+ SessionManager
56942
+ } from "@bastani/atomic";
56943
+ async function stageSessionStore(options, defaultSessionDir) {
56944
+ if (options.sessionStore !== undefined)
56945
+ return options.sessionStore;
56946
+ if (options.sessionManager !== undefined)
56947
+ return options.sessionManager.getSessionStore();
56948
+ const directory = options.sessionDir ?? defaultSessionDir;
56949
+ if (directory !== undefined)
56950
+ return JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false });
56951
+ return resolveSessionStore(options.cwd ?? process.cwd(), {
56952
+ agentDir: options.agentDir,
56953
+ settings: options.settingsManager?.getSettings()
56954
+ });
56955
+ }
56956
+ async function forkStageSession(store, sessionId, cwd, options, destination = store) {
56957
+ const source = await store.load(sessionId);
56958
+ const id = randomUUID3();
56959
+ await destination.create({
56960
+ id,
56961
+ version: 4,
56962
+ createdAt: new Date().toISOString(),
56963
+ cwd,
56964
+ parentSessionId: sessionId,
56965
+ ...options.internal === true ? { internal: true } : {},
56966
+ ...options.workflow === undefined ? {} : { workflow: options.workflow }
56967
+ }, source.entries);
56968
+ return SessionManager.open(destination, id, cwd);
56969
+ }
56970
+ async function migrateLegacyStageSession(store, sessionId, sessionFile) {
56971
+ if (sessionFile === undefined || await store.readHeader(sessionId) !== undefined)
56972
+ return;
56973
+ const location = resolve2(sessionFile);
56974
+ const legacy = await JsonlSessionStore.open(dirname(location), { exactDirectory: true, scanExisting: false });
56975
+ try {
56976
+ for await (const file of legacy.scanFiles()) {
56977
+ if (resolve2(file.location) !== location || file.header.id !== sessionId)
56978
+ continue;
56979
+ const snapshot = await file.read();
56980
+ if (await store.readHeader(sessionId) === undefined)
56981
+ await store.create(snapshot.header, snapshot.entries);
56982
+ return;
56983
+ }
56984
+ } finally {
56985
+ await legacy.close();
56986
+ }
56987
+ }
56988
+
56845
56989
  // dist/builtin/workflows/src/durable/stage-topology-validation.ts
56846
56990
  function immutableStageGroupError(stages) {
56847
56991
  const occurrenceError = promptOccurrenceIdentityError(stages);
@@ -57337,12 +57481,12 @@ function raceAbort(operation, signal) {
57337
57481
  }
57338
57482
 
57339
57483
  // dist/builtin/workflows/src/durable/factory.ts
57340
- import { resolve as resolve2 } from "node:path";
57341
- import { SettingsManager } from "@bastani/atomic";
57484
+ import { getAgentDir as getAgentDir3, SettingsManager } from "@bastani/atomic";
57485
+ import { storageSelectionKey } from "@bastani/atomic/storage";
57342
57486
 
57343
57487
  // dist/builtin/workflows/src/durable/journal/journal-backend.ts
57344
57488
  import { AsyncLocalStorage } from "node:async_hooks";
57345
- import { randomUUID as randomUUID3 } from "node:crypto";
57489
+ import { randomUUID as randomUUID4 } from "node:crypto";
57346
57490
  import { StorageError } from "@bastani/atomic/storage";
57347
57491
 
57348
57492
  // dist/builtin/workflows/src/runs/foreground/stage-session-heartbeat.ts
@@ -57482,7 +57626,7 @@ function prepareDurableChildInvocation(input) {
57482
57626
  return;
57483
57627
  }
57484
57628
  topology = makeTopology(input, boundaryId, childRunId, parentIds, sourceOrder, "start", "running");
57485
- await input.backend.recordCheckpointAsync({
57629
+ await input.backend.commitCheckpoint({
57486
57630
  kind: "stage",
57487
57631
  workflowId: input.workflowId,
57488
57632
  checkpointId: `boundary-start:${input.replayKey}`,
@@ -57509,7 +57653,7 @@ function prepareDurableChildInvocation(input) {
57509
57653
  const terminalTopology = makeTopology(input, boundaryId, childRunId, topology.parentIds, topology.sourceOrder, "terminal", status);
57510
57654
  const priorTerminalAt = stages.filter((stage) => stage.replayKey === input.replayKey && stage.topology?.boundary?.event === "terminal").reduce((latest, stage) => Math.max(latest, stage.completedAt), 0);
57511
57655
  const now = Math.max(Date.now(), priorTerminalAt + 1);
57512
- await input.backend.recordCheckpointAsync({
57656
+ await input.backend.commitCheckpoint({
57513
57657
  kind: "stage",
57514
57658
  workflowId: input.workflowId,
57515
57659
  checkpointId: `boundary-terminal:${input.replayKey}:${status}`,
@@ -57692,6 +57836,25 @@ function validatedInvocationRecords(input) {
57692
57836
  return { stages, start };
57693
57837
  }
57694
57838
 
57839
+ // dist/builtin/workflows/src/durable/execution-context-boundary.ts
57840
+ var executionStorages = new Set;
57841
+ function registerExecutionStorages(...storages) {
57842
+ for (const storage of storages)
57843
+ executionStorages.add(storage);
57844
+ return () => {
57845
+ for (const storage of storages)
57846
+ executionStorages.delete(storage);
57847
+ };
57848
+ }
57849
+ function outsideWorkflowExecutions(callback) {
57850
+ let run = callback;
57851
+ for (const storage of executionStorages) {
57852
+ const inner = run;
57853
+ run = () => storage.exit(inner);
57854
+ }
57855
+ return run();
57856
+ }
57857
+
57695
57858
  // dist/builtin/workflows/src/durable/prompt-reservation-state.ts
57696
57859
  function promptReservationToken(entry) {
57697
57860
  return entry;
@@ -57818,13 +57981,6 @@ class PromptReservationState {
57818
57981
 
57819
57982
  // dist/builtin/workflows/src/durable/journal/internal.ts
57820
57983
  var JOURNAL_READ_PAGE_SIZE = 256;
57821
- var synchronousJournals = new WeakMap;
57822
- function registerSynchronousJournal(journal, synchronous) {
57823
- synchronousJournals.set(journal, synchronous);
57824
- }
57825
- function synchronousJournal(journal) {
57826
- return synchronousJournals.get(journal);
57827
- }
57828
57984
 
57829
57985
  // dist/builtin/workflows/src/durable/journal/values.ts
57830
57986
  function validateText(field, value2) {
@@ -57860,33 +58016,22 @@ class MemoryRunJournal {
57860
58016
  runs = new Map;
57861
58017
  leases = new Map;
57862
58018
  closed = false;
57863
- constructor() {
57864
- registerSynchronousJournal(this, {
57865
- createRunSync: this.createRunSync.bind(this),
57866
- listRunsSync: this.listRunsSync.bind(this),
57867
- takeoverExpiredSync: this.takeoverExpiredSync.bind(this),
57868
- leaseStateSync: this.leaseStateSync.bind(this),
57869
- renewSync: this.renewSync.bind(this),
57870
- releaseSync: this.releaseSync.bind(this),
57871
- appendSync: this.appendSync.bind(this),
57872
- readEntries: this.readEntries.bind(this),
57873
- deleteRunSync: this.deleteRunSync.bind(this)
57874
- });
58019
+ storage;
58020
+ constructor(storage) {
58021
+ this.storage = storage === undefined ? undefined : { ...storage };
57875
58022
  }
57876
58023
  ensureOpen() {
57877
58024
  if (this.closed)
57878
58025
  throw new StorageUnavailableError({ adapter: "memory", location: ":memory:" }, new JournalClosedError);
57879
58026
  }
57880
58027
  async createRun(header) {
57881
- return this.createRunSync(header);
57882
- }
57883
- createRunSync(header) {
57884
58028
  this.ensureOpen();
57885
58029
  validateText("runId", header.runId);
57886
58030
  validateText("name", header.name);
57887
58031
  validateText("cwd", header.cwd);
57888
58032
  validateText("status", header.status);
57889
- const stored = storageBoundary(":memory:", () => JSON.parse(serializeJson(header)));
58033
+ const record = this.storage === undefined ? header : { ...header, storage: this.storage };
58034
+ const stored = storageBoundary(":memory:", () => JSON.parse(serializeJson(record)));
57890
58035
  if (this.runs.has(header.runId))
57891
58036
  return "exists";
57892
58037
  this.runs.set(header.runId, { header: stored, entries: [] });
@@ -57899,9 +58044,6 @@ class MemoryRunJournal {
57899
58044
  return run ? JSON.parse(serializeJson(run.header)) : undefined;
57900
58045
  }
57901
58046
  async listRuns(filter) {
57902
- return this.listRunsSync(filter);
57903
- }
57904
- listRunsSync(filter) {
57905
58047
  this.ensureOpen();
57906
58048
  if (filter?.cwd !== undefined)
57907
58049
  validateText("cwd", filter.cwd);
@@ -57921,9 +58063,6 @@ class MemoryRunJournal {
57921
58063
  return { status: "acquired", lease: { runId, holderId, epoch } };
57922
58064
  }
57923
58065
  async acquire(runId, holderId) {
57924
- return this.acquireSync(runId, holderId);
57925
- }
57926
- acquireSync(runId, holderId) {
57927
58066
  this.ensureOpen();
57928
58067
  validateText("runId", runId);
57929
58068
  validateText("holderId", holderId);
@@ -57951,24 +58090,18 @@ class MemoryRunJournal {
57951
58090
  return this.grant(runId, holderId);
57952
58091
  }
57953
58092
  async takeoverExpired(runId, holderId, staleAfterMs) {
57954
- return this.takeoverExpiredSync(runId, holderId, staleAfterMs);
57955
- }
57956
- takeoverExpiredSync(runId, holderId, staleAfterMs) {
57957
58093
  this.ensureOpen();
57958
58094
  validateText("runId", runId);
57959
58095
  validateText("holderId", holderId);
57960
58096
  this.requireRun(runId);
57961
- const current = this.leaseStateSync(runId);
58097
+ const current = this.leases.get(runId);
57962
58098
  if (current?.holderId === holderId)
57963
- return this.acquireSync(runId, holderId);
57964
- if (current !== undefined && !isWorkflowLeaseExpired(0, staleAfterMs, current.ageMs))
58099
+ return { status: "acquired", lease: { runId, holderId, epoch: current.epoch } };
58100
+ if (current?.holderId !== undefined && current.holderId !== null && !isWorkflowLeaseExpired(0, staleAfterMs, Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Date.now() - current.renewedAt))))
57965
58101
  return { status: "held", holderId: current.holderId, epoch: current.epoch };
57966
58102
  return this.grant(runId, holderId);
57967
58103
  }
57968
58104
  async leaseState(runId) {
57969
- return this.leaseStateSync(runId);
57970
- }
57971
- leaseStateSync(runId) {
57972
58105
  this.ensureOpen();
57973
58106
  validateText("runId", runId);
57974
58107
  const current = this.leases.get(runId);
@@ -57987,9 +58120,6 @@ class MemoryRunJournal {
57987
58120
  throw new StaleLeaseError(lease.runId, lease.epoch, current?.epoch ?? JOURNAL_LEASE.absentEpoch);
57988
58121
  }
57989
58122
  async renew(lease) {
57990
- this.renewSync(lease);
57991
- }
57992
- renewSync(lease) {
57993
58123
  this.ensureOpen();
57994
58124
  validateText("runId", lease.runId);
57995
58125
  validateText("holderId", lease.holderId);
@@ -57997,9 +58127,6 @@ class MemoryRunJournal {
57997
58127
  this.leases.set(lease.runId, { holderId: lease.holderId, epoch: lease.epoch, renewedAt: Date.now() });
57998
58128
  }
57999
58129
  async release(lease) {
58000
- this.releaseSync(lease);
58001
- }
58002
- releaseSync(lease) {
58003
58130
  this.ensureOpen();
58004
58131
  validateText("runId", lease.runId);
58005
58132
  validateText("holderId", lease.holderId);
@@ -58007,9 +58134,6 @@ class MemoryRunJournal {
58007
58134
  this.leases.set(lease.runId, { holderId: JOURNAL_LEASE.unheld, epoch: lease.epoch, renewedAt: Date.now() });
58008
58135
  }
58009
58136
  async append(lease, event, options) {
58010
- return this.appendSync(lease, event, options);
58011
- }
58012
- appendSync(lease, event, options) {
58013
58137
  this.ensureOpen();
58014
58138
  validateText("runId", lease.runId);
58015
58139
  validateText("holderId", lease.holderId);
@@ -58071,11 +58195,6 @@ class MemoryRunJournal {
58071
58195
  const start = Math.max(0, Math.ceil(fromSeq) - 1);
58072
58196
  return fromSeq <= entries.length ? entries.slice(start, start + JOURNAL_READ_PAGE_SIZE).map((entry) => this.copyEntry(entry)) : [];
58073
58197
  }
58074
- readEntries(runId, fromSeq = 1) {
58075
- this.ensureOpen();
58076
- validateText("runId", runId);
58077
- return (this.runs.get(runId)?.entries ?? []).filter((entry) => entry.seq >= fromSeq).map((entry) => this.copyEntry(entry));
58078
- }
58079
58198
  async readKey(runId, key) {
58080
58199
  this.ensureOpen();
58081
58200
  validateText("runId", runId);
@@ -58084,9 +58203,6 @@ class MemoryRunJournal {
58084
58203
  return entry ? this.copyEntry(entry) : undefined;
58085
58204
  }
58086
58205
  async deleteRun(runId) {
58087
- this.deleteRunSync(runId);
58088
- }
58089
- deleteRunSync(runId) {
58090
58206
  this.ensureOpen();
58091
58207
  validateText("runId", runId);
58092
58208
  const current = this.leases.get(runId);
@@ -58102,7 +58218,7 @@ class MemoryRunJournal {
58102
58218
  const actual = this.runs.get(lease.runId)?.entries.at(-1)?.seq ?? 0;
58103
58219
  if (expectSeq !== undefined && expectSeq !== actual)
58104
58220
  throw new JournalCasConflictError(lease.runId, expectSeq, actual);
58105
- this.deleteRunSync(lease.runId);
58221
+ await this.deleteRun(lease.runId);
58106
58222
  }
58107
58223
  async close() {
58108
58224
  this.closed = true;
@@ -58110,18 +58226,12 @@ class MemoryRunJournal {
58110
58226
  }
58111
58227
 
58112
58228
  // dist/builtin/workflows/src/durable/journal/journal-backend.ts
58113
- var PROCESS_HOLDER_ID = randomUUID3();
58114
- var DEFER_REBUILD = Symbol("defer-rebuild");
58115
- function isPromise(value2) {
58116
- return typeof value2?.then === "function";
58117
- }
58118
- function* invoke(action, synchronous = false) {
58229
+ var PROCESS_HOLDER_ID = randomUUID4();
58230
+ function* invoke(action) {
58119
58231
  try {
58120
58232
  const result = action();
58121
- if (synchronous)
58122
- return result;
58123
58233
  let value2;
58124
- yield Promise.resolve(result).then((resolved) => {
58234
+ yield result.then((resolved) => {
58125
58235
  value2 = resolved;
58126
58236
  });
58127
58237
  return value2;
@@ -58131,10 +58241,17 @@ function* invoke(action, synchronous = false) {
58131
58241
  throw new StorageUnavailableError({ adapter: "custom", location: "custom journal" }, error instanceof Error ? error : new Error(String(error)));
58132
58242
  }
58133
58243
  }
58134
- function execute(operation, step = operation.next()) {
58135
- if (step.done)
58136
- return step.value;
58137
- return step.value.then(() => execute(operation), (error) => execute(operation, operation.throw(error)));
58244
+ async function execute(operation) {
58245
+ let step = operation.next();
58246
+ while (!step.done) {
58247
+ try {
58248
+ await step.value;
58249
+ step = operation.next();
58250
+ } catch (error) {
58251
+ step = operation.throw(error);
58252
+ }
58253
+ }
58254
+ return step.value;
58138
58255
  }
58139
58256
 
58140
58257
  class JournalOwnershipError extends WorkflowInstanceOwnershipError {
@@ -58194,31 +58311,31 @@ class JournalDurableBackend {
58194
58311
  ownsJournal;
58195
58312
  persistent;
58196
58313
  projection = createJournalProjection();
58197
- synchronous;
58198
58314
  sequences = new Map;
58199
58315
  leases = new Map;
58200
58316
  executions = new Map;
58201
58317
  executionContext = new AsyncLocalStorage;
58202
58318
  pending = new Map;
58319
+ catalogQueue = Symbol("catalog");
58203
58320
  lost = new Map;
58204
58321
  prompts = new Map;
58205
58322
  timer;
58206
- closed = false;
58323
+ state = "open";
58324
+ closing;
58325
+ renewing;
58326
+ mutationContext = new AsyncLocalStorage;
58207
58327
  processExitCleanup;
58208
- constructor(journal, holderId = `${PROCESS_HOLDER_ID}:${randomUUID3()}`, rebuild, ownsJournal = true) {
58328
+ unregisterExecutionStorages = registerExecutionStorages(this.executionContext, this.mutationContext);
58329
+ constructor(journal, holderId = `${PROCESS_HOLDER_ID}:${randomUUID4()}`, ownsJournal = true) {
58209
58330
  this.journal = journal;
58210
58331
  this.holderId = holderId;
58211
58332
  this.ownsJournal = ownsJournal;
58212
- this.synchronous = synchronousJournal(journal);
58213
58333
  this.persistent = !(journal instanceof MemoryRunJournal);
58214
- if (rebuild !== DEFER_REBUILD && this.synchronous !== undefined)
58215
- for (const run of this.synchronous.listRunsSync())
58216
- execute(this.refresh(run.runId));
58217
58334
  }
58218
58335
  static async open(journal, options = {}) {
58219
58336
  let backend;
58220
58337
  try {
58221
- backend = new JournalDurableBackend(journal, undefined, DEFER_REBUILD, options.ownsJournal ?? true);
58338
+ backend = new JournalDurableBackend(journal, undefined, options.ownsJournal ?? true);
58222
58339
  for (const run of await journal.listRuns())
58223
58340
  for await (const entry of journal.read(run.runId))
58224
58341
  backend.fold(entry);
@@ -58234,21 +58351,31 @@ class JournalDurableBackend {
58234
58351
  throw new StorageUnavailableError({ adapter: "custom", location: "custom journal" }, error instanceof Error ? error : new Error(String(error)));
58235
58352
  }
58236
58353
  }
58237
- serialize(runId, action) {
58238
- const prior = this.pending.get(runId);
58239
- if (prior !== undefined)
58240
- return prior.then(() => this.serialize(runId, action));
58241
- const result = execute(action());
58242
- if (!isPromise(result))
58243
- return result;
58354
+ serialize(runId, action, requiresActiveExecution = true) {
58355
+ try {
58356
+ this.ensureOpen();
58357
+ if (requiresActiveExecution)
58358
+ this.assertExecutionActive(runId);
58359
+ } catch (error) {
58360
+ return Promise.reject(error);
58361
+ }
58362
+ const admitted = new Set([...this.executionContext.getStore()?.values() ?? []].filter((execution) => !execution.retired));
58363
+ return this.enqueue(runId, action, admitted);
58364
+ }
58365
+ enqueue(runId, action, admitted = this.mutationContext.getStore() ?? new Set) {
58366
+ const prior = this.pending.get(runId) ?? Promise.resolve();
58367
+ const result = prior.then(() => this.mutationContext.run(admitted, () => execute(action())));
58244
58368
  const settled = result.then(() => {}, () => {});
58245
58369
  this.pending.set(runId, settled);
58246
- return result.finally(() => {
58370
+ settled.then(() => {
58247
58371
  if (this.pending.get(runId) === settled)
58248
58372
  this.pending.delete(runId);
58249
58373
  });
58374
+ return result;
58250
58375
  }
58251
58376
  fold(entry) {
58377
+ if (entry.seq <= (this.sequences.get(entry.runId) ?? 0))
58378
+ return;
58252
58379
  const event = entry.event;
58253
58380
  if (event.type === RUN_EVENT_TYPES.checkpointRecorded) {
58254
58381
  const checkpoint = event.payload;
@@ -58283,8 +58410,6 @@ class JournalDurableBackend {
58283
58410
  this.sequences.set(entry.runId, entry.seq);
58284
58411
  }
58285
58412
  *entries(runId, fromSeq) {
58286
- if (this.synchronous !== undefined)
58287
- return this.synchronous.readEntries(runId, fromSeq);
58288
58413
  return yield* invoke(async () => {
58289
58414
  const entries = [];
58290
58415
  for await (const entry of this.journal.read(runId, fromSeq))
@@ -58308,7 +58433,7 @@ class JournalDurableBackend {
58308
58433
  }
58309
58434
  *current(runId) {
58310
58435
  this.ensureOpen();
58311
- this.assertExecutionActive(runId);
58436
+ this.assertExecutionActive(runId, true);
58312
58437
  yield* this.refresh(runId);
58313
58438
  if (this.projection.getWorkflow(runId) === undefined)
58314
58439
  return;
@@ -58324,24 +58449,24 @@ class JournalDurableBackend {
58324
58449
  return this.projection.getWorkflow(runId);
58325
58450
  }
58326
58451
  ensureOpen() {
58327
- if (this.closed)
58452
+ if (this.state === "closed" || this.state === "closing" && !this.mutationContext.getStore())
58328
58453
  throw new JournalBackendClosedError;
58329
58454
  }
58330
- assertExecutionActive(runId) {
58331
- for (const execution of this.executionContext.getStore()?.values() ?? [])
58332
- if (execution.retired)
58333
- throw new JournalExecutionRetiredError(runId);
58455
+ assertExecutionActive(runId, admitted = false) {
58456
+ for (const [executionRunId, execution] of this.executionContext.getStore() ?? [])
58457
+ if (execution.retired && !(admitted && this.mutationContext.getStore()?.has(execution)))
58458
+ throw new JournalExecutionRetiredError(typeof runId === "string" ? runId : executionRunId);
58334
58459
  }
58335
58460
  *ownership(runId) {
58336
58461
  this.ensureOpen();
58337
- this.assertExecutionActive(runId);
58462
+ this.assertExecutionActive(runId, true);
58338
58463
  const lost = this.lost.get(runId);
58339
58464
  if (lost)
58340
58465
  throw lost;
58341
58466
  const existing = this.leases.get(runId);
58342
58467
  if (existing)
58343
58468
  return existing;
58344
- const result = yield* invoke(() => this.synchronous !== undefined ? this.synchronous.takeoverExpiredSync(runId, this.holderId, FOREIGN_LIVE_WORKFLOW_WINDOW_MS) : this.journal.takeoverExpired(runId, this.holderId, FOREIGN_LIVE_WORKFLOW_WINDOW_MS), this.synchronous !== undefined);
58469
+ const result = yield* invoke(() => this.journal.takeoverExpired(runId, this.holderId, FOREIGN_LIVE_WORKFLOW_WINDOW_MS));
58345
58470
  if (result.status === "held")
58346
58471
  throw new JournalOwnershipError(runId, result.holderId);
58347
58472
  this.leases.set(runId, result.lease);
@@ -58351,7 +58476,7 @@ class JournalDurableBackend {
58351
58476
  }, STAGE_SESSION_HEARTBEAT_INTERVAL_MS);
58352
58477
  this.timer.unref();
58353
58478
  }
58354
- const execution = this.executions.get(runId);
58479
+ const execution = this.executionContext.getStore()?.get(runId) ?? this.executions.get(runId);
58355
58480
  if (execution !== undefined)
58356
58481
  execution.lease = result.lease;
58357
58482
  yield* this.rebuild(runId);
@@ -58363,7 +58488,7 @@ class JournalDurableBackend {
58363
58488
  let failure = new JournalOwnershipError(runId, null, error);
58364
58489
  this.lost.set(runId, failure);
58365
58490
  try {
58366
- const current = yield* invoke(() => this.synchronous !== undefined ? this.synchronous.leaseStateSync(runId) : this.journal.leaseState(runId), this.synchronous !== undefined);
58491
+ const current = yield* invoke(() => this.journal.leaseState(runId));
58367
58492
  failure = new JournalOwnershipError(runId, current?.holderId ?? null, error);
58368
58493
  this.lost.set(runId, failure);
58369
58494
  } catch {}
@@ -58372,8 +58497,8 @@ class JournalDurableBackend {
58372
58497
  *append(runId, event, options) {
58373
58498
  const lease = yield* this.ownership(runId);
58374
58499
  try {
58375
- yield* invoke(() => this.synchronous !== undefined ? this.synchronous.appendSync(lease, event, options) : this.journal.append(lease, event, options), this.synchronous !== undefined);
58376
- yield* this.refresh(runId);
58500
+ const outcome = yield* invoke(() => this.journal.append(lease, event, options));
58501
+ this.fold(outcome.entry);
58377
58502
  } catch (error) {
58378
58503
  if (error instanceof Error)
58379
58504
  throw yield* this.mapOwnership(error, runId);
@@ -58390,11 +58515,11 @@ class JournalDurableBackend {
58390
58515
  draft.registerWorkflow(handle, true);
58391
58516
  return draft;
58392
58517
  }
58393
- registerWorkflow(input) {
58518
+ commitWorkflowRegistration(input) {
58394
58519
  return this.serialize(input.workflowId, () => this.register(input));
58395
58520
  }
58396
58521
  *register(input) {
58397
- this.assertExecutionActive(input.workflowId);
58522
+ this.assertExecutionActive(input.workflowId, true);
58398
58523
  this.ensureOpen();
58399
58524
  const header = {
58400
58525
  runId: input.workflowId,
@@ -58404,7 +58529,7 @@ class JournalDurableBackend {
58404
58529
  status: input.status,
58405
58530
  inputs: input.inputs
58406
58531
  };
58407
- yield* invoke(() => this.synchronous?.createRunSync(header) ?? this.journal.createRun(header), this.synchronous !== undefined);
58532
+ yield* invoke(() => this.journal.createRun(header));
58408
58533
  yield* this.ownership(input.workflowId);
58409
58534
  yield* this.refresh(input.workflowId);
58410
58535
  const draft = yield* this.draft(input.workflowId);
@@ -58415,7 +58540,9 @@ class JournalDurableBackend {
58415
58540
  if (checkpoint.kind === "stage" && checkpoint.topology?.boundary !== undefined && typeof checkpoint.topology.boundary.invocationFingerprint !== "string")
58416
58541
  throw new DurableNestedTopologyError(`missing invocation fingerprint at ${checkpoint.checkpointId}`);
58417
58542
  }
58418
- recordCheckpoint(checkpoint) {
58543
+ commitCheckpoint(checkpoint, options) {
58544
+ if (options?.signal?.aborted)
58545
+ return Promise.reject(new JournalOperationAbortedError(checkpoint.workflowId, options.signal.reason instanceof Error ? options.signal.reason : undefined));
58419
58546
  return this.serialize(checkpoint.workflowId, () => this.checkpoint(checkpoint));
58420
58547
  }
58421
58548
  *checkpoint(checkpoint) {
@@ -58426,14 +58553,9 @@ class JournalDurableBackend {
58426
58553
  key: JSON.stringify([RUN_EVENT_TYPES.checkpointRecorded, checkpoint.kind, checkpoint.checkpointId])
58427
58554
  });
58428
58555
  }
58429
- async recordCheckpointAsync(checkpoint, options) {
58430
- if (options?.signal?.aborted)
58431
- throw new JournalOperationAbortedError(checkpoint.workflowId, options.signal.reason instanceof Error ? options.signal.reason : undefined);
58432
- await this.recordCheckpoint(checkpoint);
58433
- }
58434
- async recordAdditiveCheckpointBestEffort(checkpoint) {
58556
+ async commitAdditiveCheckpointBestEffort(checkpoint) {
58435
58557
  try {
58436
- await this.recordCheckpointAsync(checkpoint);
58558
+ await this.commitCheckpoint(checkpoint);
58437
58559
  return true;
58438
58560
  } catch (error) {
58439
58561
  if (!(error instanceof StorageUnavailableError))
@@ -58442,13 +58564,7 @@ class JournalDurableBackend {
58442
58564
  }
58443
58565
  }
58444
58566
  workflowOwnership(runId) {
58445
- if (this.synchronous !== undefined) {
58446
- const lease = this.synchronous.leaseStateSync(runId);
58447
- if (lease === undefined || isWorkflowLeaseExpired(0, FOREIGN_LIVE_WORKFLOW_WINDOW_MS, lease.ageMs))
58448
- return "available";
58449
- return lease.holderId === this.holderId ? "local" : "foreign";
58450
- }
58451
- return this.serialize(runId, () => this.probeOwnership(runId));
58567
+ return this.serialize(runId, () => this.probeOwnership(runId), false);
58452
58568
  }
58453
58569
  *probeOwnership(runId) {
58454
58570
  this.ensureOpen();
@@ -58457,7 +58573,7 @@ class JournalDurableBackend {
58457
58573
  return "available";
58458
58574
  return lease.holderId === this.holderId ? "local" : "foreign";
58459
58575
  }
58460
- setWorkflowStatus(runId, status, pendingPrompts, resumable, failure) {
58576
+ commitWorkflowStatus(runId, status, pendingPrompts, resumable, failure) {
58461
58577
  return this.serialize(runId, () => this.setStatus(runId, status, pendingPrompts, resumable, failure));
58462
58578
  }
58463
58579
  *setStatus(runId, status, pendingPrompts, resumable, failure) {
@@ -58467,7 +58583,7 @@ class JournalDurableBackend {
58467
58583
  if (handle)
58468
58584
  yield* this.snapshot(handle);
58469
58585
  }
58470
- async transitionWorkflowStatus(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
58586
+ async commitWorkflowStatusTransition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
58471
58587
  return await this.serialize(runId, () => this.transition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner));
58472
58588
  }
58473
58589
  *transition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
@@ -58517,7 +58633,7 @@ class JournalDurableBackend {
58517
58633
  });
58518
58634
  return result;
58519
58635
  }
58520
- adjustPendingPrompts(runId, delta) {
58636
+ commitPendingPromptAdjustment(runId, delta) {
58521
58637
  return this.serialize(runId, () => this.promptChange(runId, delta >= 0 ? RUN_EVENT_TYPES.promptAsked : RUN_EVENT_TYPES.promptReleased, (state) => state.adjust(delta)));
58522
58638
  }
58523
58639
  promptReservationScope(runId) {
@@ -58623,12 +58739,14 @@ class JournalDurableBackend {
58623
58739
  return this.getPendingStageMessageDeliveryCount(runId, messageId, logicalRunId);
58624
58740
  }
58625
58741
  async hydrateWorkflow(runId) {
58626
- await this.serialize(runId, () => this.rebuild(runId));
58742
+ await this.serialize(runId, () => this.rebuild(runId), false);
58627
58743
  }
58628
- async hydrateResumableWorkflows() {
58629
- const runs = await execute(invoke(() => this.journal.listRuns()));
58630
- for (const runId of new Set([...this.sequences.keys(), ...runs.map((run) => run.runId)]))
58631
- await this.hydrateWorkflow(runId);
58744
+ hydrateResumableWorkflows() {
58745
+ return this.serialize(this.catalogQueue, () => invoke(async () => {
58746
+ const runs = await this.journal.listRuns();
58747
+ for (const runId of new Set([...this.sequences.keys(), ...runs.map((run) => run.runId)]))
58748
+ await this.hydrateWorkflow(runId);
58749
+ }));
58632
58750
  }
58633
58751
  async prepareWorkflowCatalog() {
58634
58752
  await this.hydrateResumableWorkflows();
@@ -58637,13 +58755,7 @@ class JournalDurableBackend {
58637
58755
  *deleteOwned(runId, expectSeq) {
58638
58756
  try {
58639
58757
  const lease = yield* this.ownership(runId);
58640
- if (expectSeq !== undefined) {
58641
- const entries = yield* this.entries(runId);
58642
- const actualSeq = entries.at(-1)?.seq ?? 0;
58643
- if (actualSeq !== expectSeq)
58644
- throw new JournalCasConflictError(runId, expectSeq, actualSeq);
58645
- }
58646
- yield* invoke(() => this.journal.deleteOwnedRun(lease));
58758
+ yield* invoke(() => this.journal.deleteOwnedRun(lease, expectSeq));
58647
58759
  } catch (error) {
58648
58760
  if (!(error instanceof RunNotFoundError)) {
58649
58761
  if (error instanceof Error)
@@ -58684,27 +58796,33 @@ class JournalDurableBackend {
58684
58796
  }
58685
58797
  }
58686
58798
  }
58687
- reset() {
58688
- return execute(this.resetJournal());
58799
+ commitReset() {
58800
+ return this.serialize(this.catalogQueue, () => this.resetJournal());
58689
58801
  }
58690
58802
  *resetJournal() {
58691
- const runs = yield* invoke(() => this.synchronous?.listRunsSync() ?? this.journal.listRuns(), this.synchronous !== undefined);
58803
+ const runIds = new Set(this.sequences.keys());
58804
+ const runs = yield* invoke(() => this.journal.listRuns());
58692
58805
  for (const run of runs)
58693
- yield* invoke(() => {
58694
- if (this.synchronous !== undefined)
58695
- return this.synchronous.deleteRunSync(run.runId);
58696
- return this.journal.deleteRun(run.runId);
58697
- }, this.synchronous !== undefined);
58698
- this.projection.reset();
58699
- this.sequences.clear();
58700
- this.leases.clear();
58701
- this.lost.clear();
58702
- this.prompts.clear();
58703
- }
58704
- async renewLeases() {
58806
+ runIds.add(run.runId);
58807
+ for (const runId of runIds)
58808
+ yield this.enqueue(runId, () => this.deleteOwned(runId));
58809
+ }
58810
+ renewLeases() {
58811
+ if (this.renewing !== undefined)
58812
+ return this.renewing;
58813
+ if (this.state !== "open")
58814
+ return Promise.resolve();
58815
+ this.renewing = this.renewOwnedLeases().finally(() => {
58816
+ this.renewing = undefined;
58817
+ });
58818
+ return this.renewing;
58819
+ }
58820
+ async renewOwnedLeases() {
58705
58821
  for (const [runId, lease] of this.leases) {
58822
+ if (this.state !== "open")
58823
+ return;
58706
58824
  try {
58707
- await this.serialize(runId, () => this.renewLease(runId, lease));
58825
+ await this.serialize(runId, () => this.renewLease(runId, lease), false);
58708
58826
  } catch (error) {
58709
58827
  if (error instanceof Error)
58710
58828
  this.lost.set(runId, error);
@@ -58716,11 +58834,7 @@ class JournalDurableBackend {
58716
58834
  if (this.leases.get(runId) !== lease || this.lost.has(runId))
58717
58835
  return;
58718
58836
  try {
58719
- yield* invoke(() => {
58720
- if (this.synchronous !== undefined)
58721
- return this.synchronous.renewSync(lease);
58722
- return this.journal.renew(lease);
58723
- }, this.synchronous !== undefined);
58837
+ yield* invoke(() => this.journal.renew(lease));
58724
58838
  } catch (error) {
58725
58839
  if (this.leases.get(runId) === lease) {
58726
58840
  if (error instanceof Error)
@@ -58773,23 +58887,20 @@ class JournalDurableBackend {
58773
58887
  execution.retired = true;
58774
58888
  if (this.executions.get(runId) === execution)
58775
58889
  this.executions.delete(runId);
58776
- if (execution.lease !== undefined && this.leases.get(runId) === execution.lease)
58777
- return this.serialize(runId, () => this.release(runId));
58890
+ if (this.state !== "open")
58891
+ return this.closing;
58892
+ return this.serialize(runId, () => this.release(runId, execution), false);
58778
58893
  }
58779
58894
  releaseWorkflow(runId) {
58780
58895
  this.assertExecutionActive(runId);
58781
58896
  return this.serialize(runId, () => this.release(runId));
58782
58897
  }
58783
- *release(runId) {
58898
+ *release(runId, execution) {
58784
58899
  const lease = this.leases.get(runId);
58785
- if (lease === undefined)
58900
+ if (lease === undefined || execution !== undefined && execution.lease !== lease)
58786
58901
  return;
58787
58902
  try {
58788
- yield* invoke(() => {
58789
- if (this.synchronous !== undefined)
58790
- return this.synchronous.releaseSync(lease);
58791
- return this.journal.release(lease);
58792
- }, this.synchronous !== undefined);
58903
+ yield* invoke(() => this.journal.release(lease));
58793
58904
  } catch (error) {
58794
58905
  if (!(error instanceof StaleLeaseError))
58795
58906
  throw error;
@@ -58800,31 +58911,38 @@ class JournalDurableBackend {
58800
58911
  dropLease(runId) {
58801
58912
  this.leases.delete(runId);
58802
58913
  if (this.leases.size === 0) {
58803
- clearInterval(this.timer);
58914
+ if (this.timer !== undefined)
58915
+ clearInterval(this.timer);
58804
58916
  this.timer = undefined;
58805
58917
  }
58806
58918
  }
58807
- *releaseAll() {
58808
- for (const runId of this.leases.keys())
58809
- yield* this.release(runId);
58810
- }
58811
- async close() {
58919
+ close() {
58920
+ if (this.closing !== undefined)
58921
+ return this.closing;
58922
+ this.state = "closing";
58812
58923
  if (this.processExitCleanup !== undefined) {
58813
58924
  process.off("exit", this.processExitCleanup);
58814
58925
  this.processExitCleanup = undefined;
58815
58926
  }
58816
- if (this.closed)
58817
- return;
58818
58927
  if (this.timer !== undefined)
58819
58928
  clearInterval(this.timer);
58820
- if (this.pending.size > 0)
58821
- await Promise.all(this.pending.values());
58929
+ this.timer = undefined;
58930
+ this.closing = this.drainAndClose();
58931
+ return this.closing;
58932
+ }
58933
+ async drainAndClose() {
58822
58934
  try {
58823
- const released = execute(this.releaseAll());
58824
- if (isPromise(released))
58825
- await released;
58935
+ await this.renewing;
58936
+ while (this.pending.size > 0)
58937
+ await Promise.all(this.pending.values());
58938
+ for (const runId of this.leases.keys())
58939
+ await execute(this.release(runId));
58826
58940
  } finally {
58827
- this.closed = true;
58941
+ if (this.timer !== undefined)
58942
+ clearInterval(this.timer);
58943
+ this.timer = undefined;
58944
+ this.state = "closed";
58945
+ this.unregisterExecutionStorages();
58828
58946
  if (this.ownsJournal)
58829
58947
  await execute(invoke(() => this.journal.close()));
58830
58948
  }
@@ -58832,20 +58950,100 @@ class JournalDurableBackend {
58832
58950
  }
58833
58951
 
58834
58952
  // dist/builtin/workflows/src/durable/journal/resolution.ts
58835
- import { dirname as dirname2, isAbsolute as isAbsolute2, join as join3 } from "node:path";
58836
- import { getAgentDir as getAgentDir3 } from "@bastani/atomic";
58837
-
58838
- // dist/builtin/workflows/src/durable/journal/sqlite-run-journal.ts
58839
- import { dirname, join as join2 } from "node:path";
58840
- import { getAgentDir as getAgentDir2, openNodeSqliteDatabase, validateStoragePrefix, wrapNodeSqliteDatabase } from "@bastani/atomic";
58953
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join2 } from "node:path";
58954
+ import { getAgentDir as getAgentDir2 } from "@bastani/atomic";
58955
+ import {
58956
+ StorageConfigError,
58957
+ StorageProvider,
58958
+ selectStorage
58959
+ } from "@bastani/atomic/storage";
58841
58960
 
58842
58961
  // dist/builtin/workflows/src/durable/journal/sql-run-journal.ts
58843
58962
  import {
58844
58963
  assertStorageSchemaVersion,
58845
- renderStorageIdentifiers,
58964
+ renderStorageIdentifiers as renderStorageIdentifiers2,
58846
58965
  StorageSchemaVersionError as StorageSchemaVersionError2,
58847
58966
  StorageUnavailableError as StorageUnavailableError2
58848
58967
  } from "@bastani/atomic/storage";
58968
+
58969
+ // dist/builtin/workflows/src/durable/journal/legacy-journal-tables.ts
58970
+ import {
58971
+ renderStorageIdentifiers
58972
+ } from "@bastani/atomic/storage";
58973
+ var CURRENT = renderStorageIdentifiers("journal", {
58974
+ ...JOURNAL_TABLES,
58975
+ legacyDeleted: "legacy_deleted",
58976
+ migrations: "migrations"
58977
+ });
58978
+ var COPIED_ALL_MARKER = "unprefixed-journal-tables";
58979
+ var LEGACY_COLUMNS = {
58980
+ meta: [JOURNAL_COLUMNS.schemaVersion],
58981
+ runs: [JOURNAL_COLUMNS.runId, JOURNAL_COLUMNS.name, JOURNAL_COLUMNS.cwd, JOURNAL_COLUMNS.createdAt, JOURNAL_COLUMNS.status, JOURNAL_COLUMNS.headerJson],
58982
+ events: [JOURNAL_COLUMNS.runId, JOURNAL_COLUMNS.seq, JOURNAL_COLUMNS.epoch, JOURNAL_COLUMNS.key, JOURNAL_COLUMNS.type, JOURNAL_COLUMNS.payload, JOURNAL_COLUMNS.at],
58983
+ leases: [JOURNAL_COLUMNS.runId, JOURNAL_COLUMNS.holderId, JOURNAL_COLUMNS.epoch, JOURNAL_COLUMNS.renewedAt]
58984
+ };
58985
+ var PENDING_LEGACY_RUNS = `SELECT ${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.headerJson}, ${JOURNAL_COLUMNS.status} FROM ${JOURNAL_TABLES.runs}
58986
+ WHERE ${JOURNAL_COLUMNS.runId} NOT IN (SELECT ${JOURNAL_COLUMNS.runId} FROM ${CURRENT.runs})
58987
+ AND ${JOURNAL_COLUMNS.runId} NOT IN (SELECT ${JOURNAL_COLUMNS.runId} FROM ${CURRENT.legacyDeleted})`;
58988
+ async function hasLegacyTable(tx, table) {
58989
+ const columns = await tx.all("SELECT name FROM pragma_table_info(?)", JOURNAL_TABLES[table]);
58990
+ const names = new Set(columns.map((column) => column.name));
58991
+ return columns.length === LEGACY_COLUMNS[table].length && LEGACY_COLUMNS[table].every((name) => names.has(name));
58992
+ }
58993
+
58994
+ class LegacyJournalRuns {
58995
+ static async open(database) {
58996
+ try {
58997
+ return await database.transaction(async (tx) => {
58998
+ for (const table of ["meta", "runs", "events"]) {
58999
+ if (!await hasLegacyTable(tx, table))
59000
+ return;
59001
+ }
59002
+ const versions = await tx.all(`SELECT ${JOURNAL_COLUMNS.schemaVersion} FROM ${JOURNAL_TABLES.meta}`);
59003
+ if (versions.length !== 1 || Number(versions[0][JOURNAL_COLUMNS.schemaVersion]) !== JOURNAL_SCHEMA_VERSION)
59004
+ return;
59005
+ const copiedAll = await tx.get(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`, CURRENT.migrations) !== undefined && await tx.get(`SELECT name FROM ${CURRENT.migrations} WHERE name = ?`, COPIED_ALL_MARKER) !== undefined;
59006
+ if (copiedAll)
59007
+ return;
59008
+ await tx.exec(`CREATE TABLE IF NOT EXISTS ${CURRENT.legacyDeleted}(${JOURNAL_COLUMNS.runId} TEXT PRIMARY KEY, deleted_at INTEGER NOT NULL)`);
59009
+ return new LegacyJournalRuns;
59010
+ });
59011
+ } catch {
59012
+ return;
59013
+ }
59014
+ }
59015
+ async pending(executor, filter) {
59016
+ return executor.all(`${PENDING_LEGACY_RUNS}${filter?.cwd === undefined ? "" : ` AND ${JOURNAL_COLUMNS.cwd} = ?`}`, ...filter?.cwd === undefined ? [] : [filter.cwd]);
59017
+ }
59018
+ async find(executor, runId) {
59019
+ return executor.get(`${PENDING_LEGACY_RUNS} AND ${JOURNAL_COLUMNS.runId} = ?`, runId);
59020
+ }
59021
+ async events(executor, runId, fromSeq, limit) {
59022
+ return executor.all(`SELECT ${LEGACY_COLUMNS.events.join(", ")} FROM ${JOURNAL_TABLES.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.seq} >= ? ORDER BY ${JOURNAL_COLUMNS.seq} LIMIT ?`, runId, fromSeq, limit);
59023
+ }
59024
+ async eventByKey(executor, runId, key) {
59025
+ return executor.get(`SELECT ${LEGACY_COLUMNS.events.join(", ")} FROM ${JOURNAL_TABLES.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.key} = ?`, runId, key);
59026
+ }
59027
+ async convert(tx, runId) {
59028
+ if (await this.find(tx, runId) === undefined)
59029
+ return false;
59030
+ const eventColumns = LEGACY_COLUMNS.events.join(", ");
59031
+ await tx.run(`INSERT OR IGNORE INTO ${CURRENT.events}(${eventColumns}) SELECT ${eventColumns} FROM ${JOURNAL_TABLES.events} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
59032
+ if (await hasLegacyTable(tx, "leases")) {
59033
+ await tx.run(`INSERT OR IGNORE INTO ${CURRENT.leases}(${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.holderId}, ${JOURNAL_COLUMNS.epoch}, ${JOURNAL_COLUMNS.renewedAt}) SELECT ${JOURNAL_COLUMNS.runId}, NULL, ${JOURNAL_COLUMNS.epoch}, ${JOURNAL_COLUMNS.renewedAt} FROM ${JOURNAL_TABLES.leases} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
59034
+ }
59035
+ const runColumns = LEGACY_COLUMNS.runs.join(", ");
59036
+ await tx.run(`INSERT INTO ${CURRENT.runs}(${runColumns}) SELECT ${runColumns} FROM ${JOURNAL_TABLES.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
59037
+ return true;
59038
+ }
59039
+ async markDeleted(tx, runId) {
59040
+ if (await tx.get(`SELECT ${JOURNAL_COLUMNS.runId} FROM ${JOURNAL_TABLES.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId) === undefined)
59041
+ return;
59042
+ await tx.run(`INSERT OR IGNORE INTO ${CURRENT.legacyDeleted} VALUES (?, ?)`, runId, Date.now());
59043
+ }
59044
+ }
59045
+
59046
+ // dist/builtin/workflows/src/durable/journal/sql-run-journal.ts
58849
59047
  var STORE_NOW = "CAST(unixepoch('subsec') * 1000 AS INTEGER)";
58850
59048
  function entryFromRow(row) {
58851
59049
  const key = row[JOURNAL_COLUMNS.key];
@@ -58865,12 +59063,14 @@ class SqlRunJournal {
58865
59063
  closePromise;
58866
59064
  database;
58867
59065
  tables;
58868
- constructor(database, tables) {
59066
+ legacy;
59067
+ constructor(database, tables, legacy) {
58869
59068
  this.database = database;
58870
59069
  this.tables = tables;
59070
+ this.legacy = legacy;
58871
59071
  }
58872
59072
  static async open(database, options = {}) {
58873
- const t = renderStorageIdentifiers("journal", JOURNAL_TABLES, options.prefix);
59073
+ const t = renderStorageIdentifiers2("journal", JOURNAL_TABLES, options.prefix);
58874
59074
  await database.transaction(async (tx) => {
58875
59075
  await tx.exec(`CREATE TABLE IF NOT EXISTS ${t.meta}(${JOURNAL_COLUMNS.schemaVersion} INTEGER NOT NULL)`);
58876
59076
  const versions = await tx.all(`SELECT ${JOURNAL_COLUMNS.schemaVersion} FROM ${t.meta}`);
@@ -58904,7 +59104,8 @@ class SqlRunJournal {
58904
59104
  );
58905
59105
  `);
58906
59106
  });
58907
- return new SqlRunJournal(database, t);
59107
+ const legacy = options.prefix ? undefined : await LegacyJournalRuns.open(database);
59108
+ return new SqlRunJournal(database, t, legacy);
58908
59109
  }
58909
59110
  get descriptor() {
58910
59111
  return { ...this.database.descriptor };
@@ -58940,6 +59141,8 @@ class SqlRunJournal {
58940
59141
  throw json;
58941
59142
  const { runs } = this.tables;
58942
59143
  return this.operation(async () => {
59144
+ if (await this.legacy?.find(this.database, header.runId))
59145
+ return "exists";
58943
59146
  const result = await this.database.run(`INSERT INTO ${runs} VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(${JOURNAL_COLUMNS.runId}) DO NOTHING`, header.runId, header.name, header.cwd, header.createdAt, header.status, json);
58944
59147
  return result.changes === 1 ? "created" : "exists";
58945
59148
  });
@@ -58949,7 +59152,8 @@ class SqlRunJournal {
58949
59152
  validateText("runId", runId);
58950
59153
  return this.operation(async () => {
58951
59154
  const row = await this.database.get(`SELECT ${JOURNAL_COLUMNS.headerJson}, ${JOURNAL_COLUMNS.status} FROM ${this.tables.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
58952
- return row ? { ...JSON.parse(row[JOURNAL_COLUMNS.headerJson]), status: row[JOURNAL_COLUMNS.status] } : undefined;
59155
+ const found = row ?? await this.legacy?.find(this.database, runId);
59156
+ return found ? { ...JSON.parse(found[JOURNAL_COLUMNS.headerJson]), status: found[JOURNAL_COLUMNS.status] } : undefined;
58953
59157
  });
58954
59158
  }
58955
59159
  async listRuns(filter) {
@@ -58958,13 +59162,23 @@ class SqlRunJournal {
58958
59162
  validateText("cwd", filter.cwd);
58959
59163
  return this.operation(async () => {
58960
59164
  const rows = await this.database.all(`SELECT ${JOURNAL_COLUMNS.headerJson}, ${JOURNAL_COLUMNS.status} FROM ${this.tables.runs} ${filter?.cwd === undefined ? "" : `WHERE ${JOURNAL_COLUMNS.cwd} = ?`} ORDER BY ${JOURNAL_COLUMNS.runId}`, ...filter?.cwd === undefined ? [] : [filter.cwd]);
58961
- return rows.map((row) => ({ ...JSON.parse(row[JOURNAL_COLUMNS.headerJson]), status: row[JOURNAL_COLUMNS.status] }));
59165
+ const legacy = await this.legacy?.pending(this.database, filter) ?? [];
59166
+ return [...rows, ...legacy].map((row) => ({ ...JSON.parse(row[JOURNAL_COLUMNS.headerJson]), status: row[JOURNAL_COLUMNS.status] })).sort((left, right) => left.runId < right.runId ? -1 : left.runId > right.runId ? 1 : 0);
58962
59167
  });
58963
59168
  }
58964
59169
  async requireRun(tx, runId) {
58965
- if (!await tx.get(`SELECT ${JOURNAL_COLUMNS.runId} FROM ${this.tables.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId))
59170
+ if (await tx.get(`SELECT ${JOURNAL_COLUMNS.runId} FROM ${this.tables.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId))
59171
+ return;
59172
+ if (!await this.legacy?.convert(tx, runId))
58966
59173
  throw new RunNotFoundError(runId);
58967
59174
  }
59175
+ async isUnconvertedLegacyRun(runId) {
59176
+ if (this.legacy === undefined)
59177
+ return false;
59178
+ if (await this.database.get(`SELECT ${JOURNAL_COLUMNS.runId} FROM ${this.tables.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId))
59179
+ return false;
59180
+ return await this.legacy.find(this.database, runId) !== undefined;
59181
+ }
58968
59182
  async leaseRow(tx, runId) {
58969
59183
  const row = await tx.get(`SELECT * FROM ${this.tables.leases} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
58970
59184
  return row ? { ...row, [JOURNAL_COLUMNS.epoch]: journalCounter(runId, "epoch", row[JOURNAL_COLUMNS.epoch]) } : undefined;
@@ -59104,9 +59318,11 @@ class SqlRunJournal {
59104
59318
  this.assertOpen();
59105
59319
  validateText("runId", runId);
59106
59320
  let nextSeq = fromSeq;
59321
+ const legacy = this.legacy;
59322
+ const readsLegacy = legacy !== undefined && await this.operation(() => this.isUnconvertedLegacyRun(runId));
59107
59323
  for (;; ) {
59108
59324
  const page = await this.operation(async () => {
59109
- const rows = await this.database.all(`SELECT * FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.seq} >= ? ORDER BY ${JOURNAL_COLUMNS.seq} LIMIT ?`, runId, nextSeq, JOURNAL_READ_PAGE_SIZE);
59325
+ const rows = readsLegacy ? await legacy.events(this.database, runId, nextSeq, JOURNAL_READ_PAGE_SIZE) : await this.database.all(`SELECT * FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.seq} >= ? ORDER BY ${JOURNAL_COLUMNS.seq} LIMIT ?`, runId, nextSeq, JOURNAL_READ_PAGE_SIZE);
59110
59326
  return rows.map(entryFromRow);
59111
59327
  });
59112
59328
  for (const entry of page) {
@@ -59125,7 +59341,7 @@ class SqlRunJournal {
59125
59341
  validateText("runId", runId);
59126
59342
  validateText("key", key);
59127
59343
  return this.operation(async () => {
59128
- const row = await this.database.get(`SELECT * FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.key} = ?`, runId, key);
59344
+ const row = this.legacy !== undefined && await this.isUnconvertedLegacyRun(runId) ? await this.legacy.eventByKey(this.database, runId, key) : await this.database.get(`SELECT * FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.key} = ?`, runId, key);
59129
59345
  return row ? entryFromRow(row) : undefined;
59130
59346
  });
59131
59347
  }
@@ -59150,6 +59366,7 @@ class SqlRunJournal {
59150
59366
  }));
59151
59367
  }
59152
59368
  async deleteRunData(tx, runId) {
59369
+ await this.legacy?.markDeleted(tx, runId);
59153
59370
  await this.leaseRow(tx, runId);
59154
59371
  await tx.run(`UPDATE ${this.tables.leases} SET ${JOURNAL_COLUMNS.holderId} = ? WHERE ${JOURNAL_COLUMNS.runId} = ?`, JOURNAL_LEASE.unheld, runId);
59155
59372
  await tx.run(`DELETE FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
@@ -59164,78 +59381,97 @@ class SqlRunJournal {
59164
59381
  }
59165
59382
  }
59166
59383
 
59167
- // dist/builtin/workflows/src/durable/journal/sqlite-run-journal.ts
59168
- function workflowJournalPath() {
59169
- const override = process.env.ATOMIC_WORKFLOW_JOURNAL_PATH;
59170
- return override !== undefined && override.length > 0 ? override : join2(dirname(getAgentDir2()), "workflows", "journal.sqlite");
59171
- }
59172
- async function openSqlRunJournal(source = workflowJournalPath(), options = {}) {
59173
- validateStoragePrefix(options.prefix);
59174
- const database = typeof source === "string" ? await openNodeSqliteDatabase(source) : wrapNodeSqliteDatabase(source);
59175
- try {
59176
- const journal = await SqlRunJournal.open(database, options);
59177
- const close = journal.close.bind(journal);
59178
- let closing;
59179
- journal.close = () => {
59180
- closing ??= close().then(() => database.close());
59181
- return closing;
59182
- };
59183
- return journal;
59184
- } catch (error) {
59185
- await database.close();
59186
- throw error;
59187
- }
59188
- }
59189
-
59190
59384
  // dist/builtin/workflows/src/durable/journal/resolution.ts
59385
+ var provider = new StorageProvider({
59386
+ memory: (descriptor) => new MemoryRunJournal(descriptor),
59387
+ sql: SqlRunJournal.open
59388
+ });
59389
+ var settingsSelections = new WeakSet;
59191
59390
  function selectRunJournal(options = {}) {
59192
- if (options.journal !== undefined)
59193
- return options.journal;
59391
+ const agentDir = getAgentDir2();
59392
+ const defaultPath = join2(dirname2(agentDir), "workflows", "journal.sqlite");
59393
+ if (options.journal !== undefined) {
59394
+ if (options.journal !== null && typeof options.journal === "object" && "createRun" in options.journal) {
59395
+ const journal = options.journal;
59396
+ if ([
59397
+ journal.createRun,
59398
+ journal.getRun,
59399
+ journal.listRuns,
59400
+ journal.acquire,
59401
+ journal.takeover,
59402
+ journal.takeoverExpired,
59403
+ journal.leaseState,
59404
+ journal.renew,
59405
+ journal.release,
59406
+ journal.append,
59407
+ journal.read,
59408
+ journal.readKey,
59409
+ journal.deleteOwnedRun,
59410
+ journal.deleteRun,
59411
+ journal.close
59412
+ ].some((hook) => typeof hook !== "function")) {
59413
+ throw new StorageConfigError("sdk", "journal", "invalid-journal");
59414
+ }
59415
+ return journal;
59416
+ }
59417
+ return selectStorage(options.journal, "sdk", "journal", defaultPath);
59418
+ }
59194
59419
  const environment = process.env.ATOMIC_WORKFLOW_JOURNAL_PATH;
59195
59420
  if (environment !== undefined && environment.length > 0)
59196
- return { path: environment };
59421
+ return { kind: "sqlite", path: environment };
59197
59422
  const workflows = options.settings?.workflows;
59198
- const settings = Array.isArray(workflows) ? undefined : workflows?.journal;
59199
- const path = settings?.path;
59200
- if (path !== undefined && path.length > 0) {
59201
- if (settings?.memory === true)
59202
- throw new JournalConfigurationError("settings", "workflows.journal", "path-and-memory");
59203
- return { path: isAbsolute2(path) ? path : join3(dirname2(getAgentDir3()), path) };
59204
- }
59205
- if (settings?.memory === true)
59206
- return { memory: true };
59207
- return { path: workflowJournalPath() };
59423
+ const journal = Array.isArray(workflows) ? undefined : workflows?.journal;
59424
+ const value2 = journal !== undefined ? journal : options.settings?.storage;
59425
+ if (value2 === undefined)
59426
+ return { kind: "sqlite", path: defaultPath };
59427
+ const selection = selectStorage(value2, "settings", journal !== undefined ? "workflows.journal" : "storage", journal !== undefined ? defaultPath : join2(dirname2(agentDir), "storage.sqlite"));
59428
+ const resolved = selection.kind === "sqlite" && !isAbsolute2(selection.path) ? { ...selection, path: join2(dirname2(agentDir), selection.path) } : selection;
59429
+ settingsSelections.add(resolved);
59430
+ return resolved;
59208
59431
  }
59209
59432
  async function resolveRunJournal(options = {}) {
59210
- const selected = selectRunJournal(options);
59211
- if ("createRun" in selected)
59212
- return selected;
59213
- if ("path" in selected)
59214
- return await openSqlRunJournal(selected.path);
59215
- if ("database" in selected)
59216
- return await openSqlRunJournal(selected.database);
59217
- return new MemoryRunJournal;
59433
+ return openSelectedRunJournal(selectRunJournal(options));
59434
+ }
59435
+ async function openSelectedRunJournal(selection) {
59436
+ if ("createRun" in selection)
59437
+ return selection;
59438
+ return withRunJournalConfigSource(selection, () => provider.openRunJournal(selection, { agentDir: getAgentDir2(), domain: "journal" }));
59439
+ }
59440
+ async function withRunJournalConfigSource(selection, open) {
59441
+ if ("createRun" in selection)
59442
+ return open();
59443
+ try {
59444
+ return await open();
59445
+ } catch (error) {
59446
+ if (error instanceof StorageConfigError) {
59447
+ const source = settingsSelections.has(selection) ? "settings" : "sdk";
59448
+ if (error.source !== source)
59449
+ throw new StorageConfigError(source, error.field, error.reason);
59450
+ }
59451
+ throw error;
59452
+ }
59218
59453
  }
59219
59454
 
59220
59455
  // dist/builtin/workflows/src/durable/factory.ts
59221
- var DEFAULT_MEMORY_JOURNAL = "memory";
59222
59456
  async function initializeDurableBackend(options = {}) {
59223
59457
  const owner = getDurableBackendProcessOwner();
59224
59458
  const choice = options.journal;
59225
59459
  const selection = selectRunJournal({
59226
59460
  journal: choice,
59227
- settings: choice === undefined ? options.settings ?? SettingsManager.create(options.cwd ?? process.cwd()).getSettings() : undefined
59461
+ settings: choice === undefined ? options.settings ?? SettingsManager.create(options.cwd ?? process.cwd(), getAgentDir3(), {
59462
+ projectTrusted: options.projectTrusted
59463
+ }).getSettings() : undefined
59228
59464
  });
59229
- const key = "createRun" in selection ? selection : ("path" in selection) ? resolve2(selection.path) : ("database" in selection) ? selection.database : choice === undefined ? DEFAULT_MEMORY_JOURNAL : choice;
59465
+ const key = "createRun" in selection ? selection : selection.kind === "memory" && choice !== undefined ? choice : storageSelectionKey(selection, getAgentDir3());
59230
59466
  const ownsJournal = choice === undefined || !("createRun" in choice);
59231
59467
  owner.selectedBackends ??= new Map;
59232
59468
  const selected = owner.selectedBackends;
59233
59469
  const existing = selected.get(key);
59234
- let backend;
59470
+ let ready;
59235
59471
  if (existing !== undefined) {
59236
- backend = await existing.ready;
59472
+ ready = existing.ready;
59237
59473
  } else {
59238
- const ready = resolveRunJournal({ journal: selection }).then((journal) => JournalDurableBackend.open(journal, { ownsJournal })).then((opened) => {
59474
+ ready = openSelectedRunJournal(selection).then((journal) => JournalDurableBackend.open(journal, { ownsJournal })).then((opened) => {
59239
59475
  if (ownsJournal)
59240
59476
  opened.closeOnProcessExit();
59241
59477
  entry.close = () => opened.close();
@@ -59246,9 +59482,8 @@ async function initializeDurableBackend(options = {}) {
59246
59482
  });
59247
59483
  const entry = { ready };
59248
59484
  selected.set(key, entry);
59249
- backend = await ready;
59250
59485
  }
59251
- return backend;
59486
+ return withRunJournalConfigSource(selection, () => ready);
59252
59487
  }
59253
59488
 
59254
59489
  // dist/builtin/workflows/src/shared/workflow-request-timeout.ts
@@ -60596,14 +60831,14 @@ function createDurableChildWorkflowPrimitive(input) {
60596
60831
  }
60597
60832
 
60598
60833
  // dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts
60599
- import { isAbsolute as isAbsolute9, join as join11, resolve as resolve10 } from "node:path";
60834
+ import { isAbsolute as isAbsolute9, join as join10, resolve as resolve10 } from "node:path";
60600
60835
  import { CONFIG_DIR_NAME as CONFIG_DIR_NAME2 } from "@bastani/atomic";
60601
60836
 
60602
60837
  // dist/builtin/workflows/src/shared/workflow-artifacts.ts
60603
- import { randomUUID as randomUUID4 } from "node:crypto";
60838
+ import { randomUUID as randomUUID5 } from "node:crypto";
60604
60839
  import { existsSync } from "node:fs";
60605
60840
  import { mkdir, readdir, rm, stat } from "node:fs/promises";
60606
- import { dirname as dirname3, join as join4 } from "node:path";
60841
+ import { dirname as dirname3, join as join3 } from "node:path";
60607
60842
  import { getAgentDir as getAgentDir4, getEnvValue as getEnvValue2 } from "@bastani/atomic";
60608
60843
 
60609
60844
  // dist/builtin/workflows/src/shared/workflow-artifact-env.ts
@@ -60618,17 +60853,17 @@ function workflowArtifactRoot() {
60618
60853
  const override = getEnvValue2(ENV_WORKFLOW_ARTIFACT_DIR);
60619
60854
  if (override !== undefined && override.length > 0)
60620
60855
  return override;
60621
- return join4(dirname3(getAgentDir4()), "workflows");
60856
+ return join3(dirname3(getAgentDir4()), "workflows");
60622
60857
  }
60623
60858
  function workflowArtifactRunsRoot() {
60624
- return join4(workflowArtifactRoot(), "runs");
60859
+ return join3(workflowArtifactRoot(), "runs");
60625
60860
  }
60626
60861
  function safeRunId(runId) {
60627
60862
  const safe = runId.replace(/[^A-Za-z0-9._-]/g, "_");
60628
60863
  return safe.length > 0 ? safe : "run";
60629
60864
  }
60630
60865
  function workflowArtifactRunPath(runId) {
60631
- return join4(workflowArtifactRunsRoot(), safeRunId(runId));
60866
+ return join3(workflowArtifactRunsRoot(), safeRunId(runId));
60632
60867
  }
60633
60868
  function normalizeSerializedPath(value2) {
60634
60869
  return value2.replaceAll("\\", "/").replace(/\/{2,}/g, "/");
@@ -60764,7 +60999,7 @@ async function pruneWorkflowArtifactRuns(root = workflowArtifactRunsRoot(), now
60764
60999
  for (const entry of entries) {
60765
61000
  if (!entry.isDirectory())
60766
61001
  continue;
60767
- const entryPath = join4(root, entry.name);
61002
+ const entryPath = join3(root, entry.name);
60768
61003
  let metadata;
60769
61004
  try {
60770
61005
  metadata = await stat(entryPath);
@@ -60818,8 +61053,8 @@ async function ensureWorkflowArtifactRunDirectory(runId) {
60818
61053
  return directory;
60819
61054
  }
60820
61055
  function workflowArtifactDirectoryPath(runId) {
60821
- const effectiveRunId = runId ?? randomUUID4();
60822
- return join4(workflowArtifactRunPath(effectiveRunId), `artifact-${randomUUID4()}`);
61056
+ const effectiveRunId = runId ?? randomUUID5();
61057
+ return join3(workflowArtifactRunPath(effectiveRunId), `artifact-${randomUUID5()}`);
60823
61058
  }
60824
61059
  async function ensureWorkflowArtifactDirectory(directory) {
60825
61060
  await pruneArtifactRootIfDue(workflowArtifactRunsRoot(), Date.now());
@@ -62345,7 +62580,7 @@ function resolvedTaskCwd(cwd, workflowInvocationCwd) {
62345
62580
  return isAbsolute9(cwd) ? cwd : resolve10(workflowInvocationCwd, cwd);
62346
62581
  }
62347
62582
  function taskWorktreeOutputsRoot(runId) {
62348
- return join11(workflowArtifactRunPath(runId), "task-outputs");
62583
+ return join10(workflowArtifactRunPath(runId), "task-outputs");
62349
62584
  }
62350
62585
  function prepareTaskWorktrees(tasks, options, runId, scope, workflowInvocationCwd = process.cwd(), symlinkDirectories) {
62351
62586
  if (options.worktree !== true && !tasks.some((task) => task.worktree === true)) {
@@ -62370,9 +62605,9 @@ function prepareTaskWorktrees(tasks, options, runId, scope, workflowInvocationCw
62370
62605
  tasks: tasks.map((task, index) => ({ ...task, cwd: setup.worktrees[index].agentCwd })),
62371
62606
  setup,
62372
62607
  agents,
62373
- diffsDir: join11(setup.cwd, CONFIG_DIR_NAME2, "workflows", "worktree-diffs", runId, scope),
62608
+ diffsDir: join10(setup.cwd, CONFIG_DIR_NAME2, "workflows", "worktree-diffs", runId, scope),
62374
62609
  outputIsolations: tasks.map((_, index) => ({
62375
- baseDir: join11(trustedRoot, runId, scope, String(index)),
62610
+ baseDir: join10(trustedRoot, runId, scope, String(index)),
62376
62611
  trustedRoot
62377
62612
  }))
62378
62613
  };
@@ -63655,8 +63890,8 @@ function createRunLimiter(defaultConcurrency) {
63655
63890
  }
63656
63891
 
63657
63892
  // dist/builtin/workflows/src/shared/possible-stages.ts
63658
- import { existsSync as existsSync5, readFileSync as readFileSync3 } from "node:fs";
63659
- import { dirname as dirname9, join as join12, resolve as resolve11 } from "node:path";
63893
+ import { existsSync as existsSync5, readFileSync as readFileSync2 } from "node:fs";
63894
+ import { dirname as dirname9, join as join11, resolve as resolve11 } from "node:path";
63660
63895
  import { fileURLToPath as fileURLToPath3 } from "node:url";
63661
63896
  var DEFAULT_MAX_DEPTH = 4;
63662
63897
  var BUILTIN_BARREL_SPECIFIERS = new Set(["@bastani/atomic/workflows/builtin"]);
@@ -63676,7 +63911,7 @@ function resolveBuiltinDefinitionSource(name) {
63676
63911
  const builtinDir = fileURLToPath3(new URL("../../builtin/", import.meta.url));
63677
63912
  for (const stem of [name, kebabCase(name)]) {
63678
63913
  for (const extension of [".ts", ".js"]) {
63679
- const candidate = join12(builtinDir, `${stem}${extension}`);
63914
+ const candidate = join11(builtinDir, `${stem}${extension}`);
63680
63915
  if (isFileSync(candidate))
63681
63916
  return candidate;
63682
63917
  }
@@ -63915,7 +64150,7 @@ function templateToPattern(raw) {
63915
64150
  function buildFileUnit(path, warnings) {
63916
64151
  let source;
63917
64152
  try {
63918
- source = readFileSync3(path, "utf-8");
64153
+ source = readFileSync2(path, "utf-8");
63919
64154
  } catch (error) {
63920
64155
  warnings.push(`possible-stages: failed to read ${path}: ${errorMessage2(error)}`);
63921
64156
  return;
@@ -65119,16 +65354,16 @@ function resolveRelativeSpecifier(specifier, importingFile) {
65119
65354
  return;
65120
65355
  const candidates = [];
65121
65356
  if (specifier.endsWith(".js")) {
65122
- candidates.push(join12(dirname9(importingFile), `${specifier.slice(0, -3)}.ts`));
65357
+ candidates.push(join11(dirname9(importingFile), `${specifier.slice(0, -3)}.ts`));
65123
65358
  }
65124
- candidates.push(join12(dirname9(importingFile), specifier), join12(dirname9(importingFile), `${specifier}.ts`), join12(dirname9(importingFile), `${specifier}.js`), join12(dirname9(importingFile), specifier, "index.ts"), join12(dirname9(importingFile), specifier, "index.js"));
65359
+ candidates.push(join11(dirname9(importingFile), specifier), join11(dirname9(importingFile), `${specifier}.ts`), join11(dirname9(importingFile), `${specifier}.js`), join11(dirname9(importingFile), specifier, "index.ts"), join11(dirname9(importingFile), specifier, "index.js"));
65125
65360
  return candidates.find((candidate) => isFileSync(candidate));
65126
65361
  }
65127
65362
  function isFileSync(path) {
65128
65363
  if (!existsSync5(path))
65129
65364
  return false;
65130
65365
  try {
65131
- readFileSync3(path, { flag: "r" });
65366
+ readFileSync2(path, { flag: "r" });
65132
65367
  return true;
65133
65368
  } catch {
65134
65369
  return false;
@@ -65386,10 +65621,10 @@ function createWorkflowExitManager(input) {
65386
65621
  };
65387
65622
  }
65388
65623
  // dist/builtin/workflows/src/engine/primitives/parallel.ts
65389
- import { randomUUID as randomUUID6 } from "node:crypto";
65624
+ import { randomUUID as randomUUID7 } from "node:crypto";
65390
65625
 
65391
65626
  // dist/builtin/workflows/src/shared/intercom-group.ts
65392
- import { randomUUID as randomUUID5 } from "node:crypto";
65627
+ import { randomUUID as randomUUID6 } from "node:crypto";
65393
65628
  var DEFAULT_INTERCOM_GROUP = "default";
65394
65629
  function workflowInvocationIntercomGroup(rootRunId) {
65395
65630
  return `workflow:${rootRunId}`;
@@ -65412,7 +65647,7 @@ function resolveStageGroup(stageOptions, workflowGroup) {
65412
65647
  const group = stageOptions.group;
65413
65648
  if (group === undefined)
65414
65649
  return workflowGroup;
65415
- const authored = group === true ? randomUUID5() : group.trim();
65650
+ const authored = group === true ? randomUUID6() : group.trim();
65416
65651
  if (authored.length === 0)
65417
65652
  return;
65418
65653
  if (workflowGroup === undefined || authored === DEFAULT_INTERCOM_GROUP)
@@ -65724,7 +65959,7 @@ function createParallelPrimitive(input) {
65724
65959
  const normalizedOptions = normalizeGroup(options);
65725
65960
  const normalizedSteps = steps.map(normalizeGroup);
65726
65961
  const needsAutoGroup = normalizedOptions.group === true || normalizedSteps.some((step) => step.group === true);
65727
- const autoGroup = needsAutoGroup ? randomUUID6() : undefined;
65962
+ const autoGroup = needsAutoGroup ? randomUUID7() : undefined;
65728
65963
  const resolveAutoGroup = (value2) => value2.group === true && autoGroup ? { ...value2, group: autoGroup } : value2;
65729
65964
  const resolvedOptions = resolveAutoGroup(normalizedOptions);
65730
65965
  const resolvedSteps = normalizedSteps.map(resolveAutoGroup);
@@ -65792,7 +66027,7 @@ function createTaskPrimitive(runtime) {
65792
66027
  }
65793
66028
  });
65794
66029
  const stage = stageHandle.context;
65795
- const promptText = resolvedTaskOptions.resumeFromSessionFile !== undefined ? RESUME_CONTINUATION_PROMPT : applyTaskContext(`${taskReadInstruction(resolvedTaskOptions)}${taskPrompt(resolvedTaskOptions)}`, taskPrevious(resolvedTaskOptions));
66030
+ const promptText = resolvedTaskOptions.resumeFromSessionId !== undefined ? RESUME_CONTINUATION_PROMPT : applyTaskContext(`${taskReadInstruction(resolvedTaskOptions)}${taskPrompt(resolvedTaskOptions)}`, taskPrevious(resolvedTaskOptions));
65796
66031
  const rawOutput = await stage.prompt(promptText, taskPromptOptions(resolvedTaskOptions));
65797
66032
  const structured = typeof rawOutput === "string" ? undefined : rawOutput;
65798
66033
  const text = truncateTaskOutput(structuredTaskOutputText(rawOutput), resolvedTaskOptions.maxOutput);
@@ -65882,6 +66117,7 @@ function wrapUiWithDurable(base, deps) {
65882
66117
  response,
65883
66118
  completedAt: Date.now()
65884
66119
  };
66120
+ await deps.beforeCheckpoint?.();
65885
66121
  await recordCheckpointDurably(deps.backend, checkpoint);
65886
66122
  };
65887
66123
  const cached = (identity) => deps.backend.getUiResponse(deps.workflowId, identity.hash);
@@ -66203,7 +66439,7 @@ async function finalizeDurableTerminalStatus(input) {
66203
66439
  ...input.runSnapshot.failureDisposition !== undefined ? { failureDisposition: input.runSnapshot.failureDisposition } : {},
66204
66440
  ...input.runSnapshot.failedToolNodeId !== undefined ? { failedToolNodeId: input.runSnapshot.failedToolNodeId } : {}
66205
66441
  } : undefined;
66206
- await input.durableBackend.setWorkflowStatus(input.runId, durableStatus, undefined, input.runSnapshot.resumable, failure);
66442
+ await input.durableBackend.commitWorkflowStatus(input.runId, durableStatus, undefined, input.runSnapshot.resumable, failure);
66207
66443
  }
66208
66444
  }
66209
66445
  function toDurableStatus(status) {
@@ -66308,7 +66544,7 @@ async function recordWorkflowHeartbeatAnchor(backend, record) {
66308
66544
  output: { anchorAt: record.anchorAt, intervalMinutes: record.intervalMinutes },
66309
66545
  completedAt: record.now
66310
66546
  };
66311
- const stored = await backend.recordAdditiveCheckpointBestEffort(checkpoint);
66547
+ const stored = await backend.commitAdditiveCheckpointBestEffort(checkpoint);
66312
66548
  if (!stored)
66313
66549
  return false;
66314
66550
  return readWorkflowHeartbeatAnchor(backend, record.runId) !== undefined;
@@ -66392,6 +66628,7 @@ function createDurableStageDeps(input) {
66392
66628
  backend: input.backend,
66393
66629
  nextCheckpointId: input.nextCheckpointId,
66394
66630
  nextReplayKey: input.nextReplayKey,
66631
+ beforeCheckpoint: input.beforeCheckpoint,
66395
66632
  replayKeyForCompletedStage: (stage) => input.completedReplayKeys.get(stage.id),
66396
66633
  runTopology: durableRunTopology(input.run),
66397
66634
  sourceOrderForStage: (stage) => {
@@ -66442,7 +66679,8 @@ function createDurableStageTopologyResolver(backend, workflowId) {
66442
66679
  async function recordDurableActiveStage(deps, stage) {
66443
66680
  if (stage.replayKey === undefined || stage.status === "completed" || stage.status === "failed" || stage.status === "skipped")
66444
66681
  return false;
66445
- await deps.backend.recordCheckpointAsync({
66682
+ await deps.beforeCheckpoint?.();
66683
+ await deps.backend.commitCheckpoint({
66446
66684
  kind: "stage",
66447
66685
  workflowId: deps.workflowId,
66448
66686
  checkpointId: `stage-active-meta:${durableHash({ replayKey: stage.replayKey, stageId: stage.id })}`,
@@ -66475,7 +66713,7 @@ function createDurableCachedStageRecorder(input) {
66475
66713
  input.run.stages.sort((left, right) => (replaySourceOrders.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (replaySourceOrders.get(right.id) ?? Number.MAX_SAFE_INTEGER));
66476
66714
  }
66477
66715
  const stage = input.store.runs().find((run) => run.id === input.run.id)?.stages.find((candidate) => candidate.replayKey === replayKey);
66478
- const persistence = stage === undefined ? undefined : input.backend.recordCheckpoint({
66716
+ const persistence = stage === undefined ? undefined : input.backend.commitCheckpoint({
66479
66717
  kind: "stage",
66480
66718
  workflowId: input.run.id,
66481
66719
  checkpointId: `stage-replay-meta:${durableHash({ replayKey, stageId: stage.id, parentIds: stage.parentIds })}`,
@@ -66767,6 +67005,9 @@ function createAdmittedToolExecutionTracker(options = {}) {
66767
67005
  await drainRecordedFailures();
66768
67006
  };
66769
67007
  return {
67008
+ get closed() {
67009
+ return state === "CLOSED" || options.signal?.aborted === true;
67010
+ },
66770
67011
  track(execution) {
66771
67012
  if (state === "CLOSED" || options.signal?.aborted) {
66772
67013
  const error = new Error("atomic-workflows: ctx.tool admission is closed for this run");
@@ -66942,6 +67183,13 @@ function createTrackedToolPrimitive(input) {
66942
67183
  });
66943
67184
  const lifecycle = createToolNodeLifecycle(input);
66944
67185
  const budgetBoundary = input.budget.enabled ? () => input.budget.stopAtBoundaryAsync(input.run.stages.at(-1)?.name) : undefined;
67186
+ const assertToolAdmissionOpen = () => {
67187
+ const quit = input.toolAdmission.quitReason;
67188
+ if (quit !== undefined) {
67189
+ observedQuit ??= quit;
67190
+ throw quit;
67191
+ }
67192
+ };
66945
67193
  const tool = createToolPrimitive({
66946
67194
  workflowId: input.workflowId,
66947
67195
  ...input.checkpointSourceWorkflowId === undefined ? {} : { checkpointSourceWorkflowId: input.checkpointSourceWorkflowId },
@@ -66975,7 +67223,16 @@ function createTrackedToolPrimitive(input) {
66975
67223
  observedQuit ??= admission.error;
66976
67224
  return admission;
66977
67225
  },
66978
- ...budgetBoundary !== undefined ? { beforeToolCall: budgetBoundary, afterToolCall: budgetBoundary } : {},
67226
+ beforeToolCall: () => {
67227
+ const afterDrain = () => {
67228
+ const budget = budgetBoundary?.();
67229
+ return budget === undefined ? assertToolAdmissionOpen() : budget.then(assertToolAdmissionOpen);
67230
+ };
67231
+ const pending = input.beforeToolCall?.();
67232
+ return pending === undefined ? afterDrain() : pending.then(afterDrain);
67233
+ },
67234
+ beforeCheckpoint: input.beforeCheckpoint,
67235
+ ...budgetBoundary !== undefined ? { afterToolCall: budgetBoundary } : {},
66979
67236
  ...lifecycle
66980
67237
  });
66981
67238
  const abandonInFlightAsCancelled = (reason) => {
@@ -67863,12 +68120,12 @@ class StageToolExecutionBuffer {
67863
68120
  function createStageControlHandle(runtime) {
67864
68121
  const messagePreparation = () => {
67865
68122
  const meta = runtime.innerCtx.__sessionMeta();
67866
- if (meta.sessionId !== undefined || meta.sessionFile !== undefined) {
68123
+ if (meta.sessionId !== undefined) {
67867
68124
  return { beforePreparation: runtime.throwIfStageMutationBlocked };
67868
68125
  }
67869
- if (runtime.stageSnapshot.sessionFile !== undefined) {
68126
+ if (runtime.stageSnapshot.sessionId !== undefined) {
67870
68127
  return {
67871
- sessionFile: runtime.stageSnapshot.sessionFile,
68128
+ sessionId: runtime.stageSnapshot.sessionId,
67872
68129
  beforePreparation: runtime.throwIfStageMutationBlocked
67873
68130
  };
67874
68131
  }
@@ -67878,10 +68135,10 @@ function createStageControlHandle(runtime) {
67878
68135
  return { beforePreparation: runtime.throwIfStageMutationBlocked };
67879
68136
  };
67880
68137
  const ensureMessagingSession = async () => {
67881
- const sessionFile = messagePreparation().sessionFile;
67882
- if (sessionFile === undefined)
68138
+ const sessionId = messagePreparation().sessionId;
68139
+ if (sessionId === undefined)
67883
68140
  return;
67884
- await runtime.innerCtx.__ensureSessionFromFile(sessionFile);
68141
+ await runtime.innerCtx.__ensureSessionFromId(sessionId);
67885
68142
  await runtime.captureStageSessionMeta({ awaitDurable: true });
67886
68143
  };
67887
68144
  const toolExecutions = new StageToolExecutionBuffer;
@@ -67897,6 +68154,9 @@ function createStageControlHandle(runtime) {
67897
68154
  get status() {
67898
68155
  return runtime.stageSnapshot.status;
67899
68156
  },
68157
+ get sessionStore() {
68158
+ return runtime.innerCtx.__agentSession()?.sessionManager.getSessionStore();
68159
+ },
67900
68160
  get sessionId() {
67901
68161
  return runtime.innerCtx.__sessionMeta().sessionId ?? runtime.stageSnapshot.sessionId;
67902
68162
  },
@@ -68185,7 +68445,7 @@ function createReplayStageContext(input) {
68185
68445
  __getLastAssistantText: () => replayResult,
68186
68446
  getLastAssistantText: () => replayResult,
68187
68447
  __ensureSession: async () => {},
68188
- __ensureSessionFromFile: async () => {},
68448
+ __ensureSessionFromId: async () => {},
68189
68449
  __sealGeneration: () => {},
68190
68450
  __closeGeneration: async () => {},
68191
68451
  __sessionMeta: () => ({ sessionId: replaySource.sessionId, sessionFile: replaySource.sessionFile }),
@@ -68208,7 +68468,7 @@ function createReplayStageContext(input) {
68208
68468
  }
68209
68469
 
68210
68470
  // dist/builtin/workflows/src/shared/pending-stage-route-capability.ts
68211
- import { randomUUID as randomUUID7 } from "node:crypto";
68471
+ import { randomUUID as randomUUID8 } from "node:crypto";
68212
68472
  var routeCapabilitiesKey = Symbol.for("atomic-workflows/pending-stage-route-capabilities@1");
68213
68473
  var processState = globalThis;
68214
68474
  var routeCapabilities = processState[routeCapabilitiesKey] ?? new WeakMap;
@@ -68221,7 +68481,7 @@ function workflowPendingStageRouteCapability(store, runId) {
68221
68481
  }
68222
68482
  let capability = capabilities.get(runId);
68223
68483
  if (capability === undefined) {
68224
- capability = randomUUID7();
68484
+ capability = randomUUID8();
68225
68485
  capabilities.set(runId, capability);
68226
68486
  }
68227
68487
  return capability;
@@ -69192,7 +69452,7 @@ function assistantMessage(text) {
69192
69452
  }
69193
69453
 
69194
69454
  // dist/builtin/workflows/src/runs/foreground/stage-runner-options.ts
69195
- import { SessionManager } from "@bastani/atomic";
69455
+ import { SessionManager as SessionManager2 } from "@bastani/atomic";
69196
69456
  function workflowSessionOptions(meta) {
69197
69457
  return {
69198
69458
  internal: true,
@@ -69217,7 +69477,7 @@ async function stripWorkflowOnlyOptions(options, defaultSessionDir, meta, pendin
69217
69477
  if (!options) {
69218
69478
  return defaultSessionDir === undefined ? { orchestrationContext } : {
69219
69479
  orchestrationContext,
69220
- sessionManager: await SessionManager.create(process.cwd(), defaultSessionDir, classification)
69480
+ sessionManager: await SessionManager2.create(process.cwd(), defaultSessionDir, classification)
69221
69481
  };
69222
69482
  }
69223
69483
  const {
@@ -69229,8 +69489,10 @@ async function stripWorkflowOnlyOptions(options, defaultSessionDir, meta, pendin
69229
69489
  inheritedModelConstraints: _inheritedModelConstraints,
69230
69490
  routerSelection: _routerSelection,
69231
69491
  context,
69232
- forkFromSessionFile,
69233
- resumeFromSessionFile,
69492
+ forkFromSessionId,
69493
+ resumeFromSessionId,
69494
+ resumeFromLegacySessionFile,
69495
+ sessionStore,
69234
69496
  durableReplayKey: _durableReplayKey,
69235
69497
  durableAccumulatedDurationMs: _durableAccumulatedDurationMs,
69236
69498
  durableStageId: _durableStageId,
@@ -69242,15 +69504,18 @@ async function stripWorkflowOnlyOptions(options, defaultSessionDir, meta, pendin
69242
69504
  group: _group,
69243
69505
  ...sessionOptions
69244
69506
  } = options;
69245
- if (sessionOptions.sessionManager === undefined) {
69246
- const cwd = sessionOptions.cwd ?? process.cwd();
69247
- const effectiveSessionDir = sessionDir ?? defaultSessionDir;
69248
- if (resumeFromSessionFile !== undefined) {
69249
- sessionOptions.sessionManager = await SessionManager.open(resumeFromSessionFile, effectiveSessionDir, cwd);
69250
- } else if (context === "fork" && forkFromSessionFile !== undefined) {
69251
- sessionOptions.sessionManager = await SessionManager.forkFrom(forkFromSessionFile, cwd, effectiveSessionDir, classification);
69252
- } else if (effectiveSessionDir !== undefined) {
69253
- sessionOptions.sessionManager = await SessionManager.create(cwd, effectiveSessionDir, classification);
69507
+ const cwd = sessionOptions.cwd ?? process.cwd();
69508
+ if (resumeFromSessionId !== undefined) {
69509
+ const store = await stageSessionStore(options, defaultSessionDir);
69510
+ await migrateLegacyStageSession(store, resumeFromSessionId, resumeFromLegacySessionFile);
69511
+ sessionOptions.sessionManager = await SessionManager2.open(store, resumeFromSessionId, cwd);
69512
+ } else if (context === "fork" && forkFromSessionId !== undefined) {
69513
+ sessionOptions.sessionManager = await forkStageSession(await stageSessionStore(options, defaultSessionDir), forkFromSessionId, cwd, classification);
69514
+ } else if (sessionOptions.sessionManager === undefined) {
69515
+ if (sessionStore !== undefined) {
69516
+ sessionOptions.sessionManager = await SessionManager2.create(sessionStore, cwd, classification);
69517
+ } else if ((sessionDir ?? defaultSessionDir) !== undefined) {
69518
+ sessionOptions.sessionManager = await SessionManager2.create(cwd, sessionDir ?? defaultSessionDir, classification);
69254
69519
  }
69255
69520
  }
69256
69521
  return {
@@ -69660,7 +69925,6 @@ async function sendStageUserMessage(activeSession, content, options, beforeDeliv
69660
69925
  }
69661
69926
 
69662
69927
  // dist/builtin/workflows/src/runs/foreground/stage-runner-session-options.ts
69663
- import { SessionManager as SessionManager2 } from "@bastani/atomic";
69664
69928
  var adapterDefaultCwds = new WeakMap;
69665
69929
  function setAgentSessionAdapterDefaultCwd(adapter, cwd) {
69666
69930
  adapterDefaultCwds.set(adapter, cwd);
@@ -69683,11 +69947,10 @@ async function buildStageSessionOptions(input) {
69683
69947
  }
69684
69948
  if (input.restoreSavedModel === true)
69685
69949
  delete options.model;
69686
- if (input.reattachSessionFile !== undefined && options.sessionManager === undefined) {
69687
- const cwd = options.cwd ?? process.cwd();
69688
- options.sessionManager = await SessionManager2.open(input.reattachSessionFile, options.sessionDir, cwd);
69950
+ if (input.reattachSessionId !== undefined) {
69951
+ options.resumeFromSessionId = input.reattachSessionId;
69689
69952
  options.context = undefined;
69690
- options.forkFromSessionFile = undefined;
69953
+ options.forkFromSessionId = undefined;
69691
69954
  }
69692
69955
  if (input.sharedModelRuntime !== undefined && options.modelRuntime === undefined) {
69693
69956
  options.modelRuntime = input.sharedModelRuntime;
@@ -69938,7 +70201,7 @@ class StageSessionController {
69938
70201
  sessionPromise;
69939
70202
  sessionShutdownPromise;
69940
70203
  bindingCleanupFailure;
69941
- reattachSessionFile;
70204
+ reattachSessionId;
69942
70205
  lastPromptStartIndex;
69943
70206
  attemptUsageStartIndex;
69944
70207
  discardedAttemptUsage = {
@@ -70194,9 +70457,9 @@ class StageSessionController {
70194
70457
  const ready = waitForStageStartup(this.sessionPromise, this.startupWait.signal);
70195
70458
  return this.modelRoute ? this.checkedSession(await ready) : ready;
70196
70459
  }
70197
- async ensureSessionFromFile(sessionFile, consumer = "prompt") {
70460
+ async ensureSessionFromId(sessionId, consumer = "prompt") {
70198
70461
  if (!this.sessionShutdownPromise && !this.sessionPromise && !this.session)
70199
- this.reattachSessionFile = sessionFile;
70462
+ this.reattachSessionId = sessionId;
70200
70463
  const session = await this.ensureSession(consumer);
70201
70464
  await session.closeWorkflowStageGeneration?.();
70202
70465
  return session;
@@ -70209,12 +70472,12 @@ class StageSessionController {
70209
70472
  return pausedDelivery;
70210
70473
  }
70211
70474
  preparation?.beforePreparation?.();
70212
- const sessionFile = preparation?.sessionFile;
70475
+ const sessionId = preparation?.sessionId;
70213
70476
  const deliver = async (activity) => {
70214
70477
  if (this.effectiveStageOptions?.model === "auto")
70215
70478
  await this.preparePrompt(typeof content === "string" ? content : content.filter((part) => part.type === "text").map((part) => part.text).join(`
70216
70479
  `));
70217
- const activeSession = sessionFile === undefined ? await this.ensureSession("prompt") : await this.ensureSessionFromFile(sessionFile, "prompt");
70480
+ const activeSession = sessionId === undefined ? await this.ensureSession("prompt") : await this.ensureSessionFromId(sessionId, "prompt");
70218
70481
  const pausedDelivery = this.pauseControl.deferRunnerOwnedDelivery(() => sendStageUserMessage(activeSession, content, options, beforeDelivery, release, this.messageAdmission, activity));
70219
70482
  if (pausedDelivery !== undefined) {
70220
70483
  release();
@@ -70222,7 +70485,7 @@ class StageSessionController {
70222
70485
  }
70223
70486
  return sendStageUserMessage(activeSession, content, options, beforeDelivery, release, this.messageAdmission, activity);
70224
70487
  };
70225
- if (this.session === undefined || sessionFile !== undefined)
70488
+ if (this.session === undefined || sessionId !== undefined)
70226
70489
  return this.deliveryActivity.runWithLease(() => deliver());
70227
70490
  return deliver(this.deliveryActivity);
70228
70491
  });
@@ -70762,7 +71025,7 @@ class StageSessionController {
70762
71025
  if (first === undefined) {
70763
71026
  return this.createSessionObservingPause(undefined, consumer).catch((error) => this.createInitialSessionWithRetry(undefined, consumer, { error }));
70764
71027
  }
70765
- if (this.reattachSessionFile !== undefined) {
71028
+ if (this.reattachSessionId !== undefined) {
70766
71029
  const resumed = await this.createSession(undefined, consumer, { restoreSavedModel: true });
70767
71030
  const restoredId = workflowModelId(resumed.model);
70768
71031
  const exactRestoredIndex = restoredId === undefined ? -1 : candidates.findIndex((entry) => entry.id === restoredId && entry.reasoningLevel === resumed.thinkingLevel);
@@ -70985,7 +71248,7 @@ class StageSessionController {
70985
71248
  ownsFallbackChain: this.hasExplicitModelFallbackConfig,
70986
71249
  scopedModels,
70987
71250
  restoreSavedModel: resumeOptions?.restoreSavedModel,
70988
- reattachSessionFile: this.reattachSessionFile,
71251
+ reattachSessionId: this.reattachSessionId,
70989
71252
  sharedModelRuntime: this.sharedModelRuntime,
70990
71253
  defaultCwd: this.opts.defaultCwd
70991
71254
  });
@@ -71334,7 +71597,7 @@ class StageSessionController {
71334
71597
  // dist/builtin/workflows/src/runs/foreground/stage-runner-output.ts
71335
71598
  import { createHash as createHash3 } from "node:crypto";
71336
71599
  import { mkdir as mkdir2, writeFile } from "node:fs/promises";
71337
- import { basename as basename4, dirname as dirname10, isAbsolute as isAbsolute10, join as join13, resolve as resolve12 } from "node:path";
71600
+ import { basename as basename4, dirname as dirname10, isAbsolute as isAbsolute10, join as join12, resolve as resolve12 } from "node:path";
71338
71601
  var DEFAULT_MAX_OUTPUT_BYTES = 200 * 1024;
71339
71602
  var DEFAULT_MAX_OUTPUT_LINES = 5000;
71340
71603
  function normalizeMaxOutput2(maxOutput) {
@@ -71399,7 +71662,7 @@ function formatByteSize(bytes) {
71399
71662
  }
71400
71663
  function transcriptPath(runId, outputPath) {
71401
71664
  const digest = createHash3("sha256").update(outputPath).digest("hex").slice(0, 16);
71402
- return join13(workflowArtifactRunPath(runId), "transcripts", `${digest}-${basename4(outputPath)}.transcript.md`);
71665
+ return join12(workflowArtifactRunPath(runId), "transcripts", `${digest}-${basename4(outputPath)}.transcript.md`);
71403
71666
  }
71404
71667
  function appendContent(lines, content) {
71405
71668
  if (typeof content === "string") {
@@ -71554,7 +71817,7 @@ function createStageContext2(opts) {
71554
71817
  const stageCwd = stageOptions?.cwd ?? stageOptions?.sessionManager?.getCwd() ?? agentSessionAdapterDefaultCwd(adapters.agentSession) ?? opts.defaultCwd ?? process.cwd();
71555
71818
  const structuredOutputCapture = stageOptions?.schema ? createStructuredOutputCapture() : undefined;
71556
71819
  const structuredOutputExecutionCapture = stageOptions?.schema ? {} : undefined;
71557
- const effectiveStageOptions = stageOptionsWithStructuredOutput(stageOptions, structuredOutputCapture, structuredOutputExecutionCapture);
71820
+ const effectiveStageOptions = stageOptionsWithStructuredOutput(adapters.sessionStore === undefined || stageOptions?.sessionStore !== undefined || stageOptions?.sessionDir !== undefined || stageOptions?.sessionManager !== undefined ? stageOptions : { ...stageOptions, sessionStore: adapters.sessionStore }, structuredOutputCapture, structuredOutputExecutionCapture);
71558
71821
  const meta = {
71559
71822
  runId,
71560
71823
  stageId,
@@ -71793,8 +72056,8 @@ ${nextPrompt}`;
71793
72056
  return;
71794
72057
  await controller.ensureSession();
71795
72058
  },
71796
- async __ensureSessionFromFile(sessionFile) {
71797
- await controller.ensureSessionFromFile(sessionFile);
72059
+ async __ensureSessionFromId(sessionId) {
72060
+ await controller.ensureSessionFromId(sessionId);
71798
72061
  },
71799
72062
  __sealGeneration() {
71800
72063
  controller.sealGeneration();
@@ -71863,11 +72126,11 @@ function createWorkflowStageFactory(input) {
71863
72126
  input.assertLiveWorkAllowed?.();
71864
72127
  options = stageOptionsWithGitWorktree(prepareLiveOptions?.() ?? options, input.workflowInvocationCwd, input.gitWorktreeSetupCache);
71865
72128
  }
71866
- const replayStageOptions = executeReplaySource?.sessionFile === undefined ? options : {
72129
+ const replayStageOptions = executeReplaySource?.sessionId === undefined ? options : {
71867
72130
  ...options ?? {},
71868
72131
  routerSelection: executeReplaySource.routerSelection,
71869
72132
  context: options?.context ?? "fork",
71870
- forkFromSessionFile: options?.forkFromSessionFile ?? executeReplaySource.sessionFile
72133
+ forkFromSessionId: options?.forkFromSessionId ?? executeReplaySource.sessionId
71871
72134
  };
71872
72135
  const intercomGroup = options?.durableIntercomGroup ?? resolveStageGroup(replayStageOptions, input.workflowIntercomGroup);
71873
72136
  const stageOptionsForContext = replayStageOptions?.group === undefined || intercomGroup === undefined ? replayStageOptions : { ...replayStageOptions, group: intercomGroup };
@@ -72042,8 +72305,8 @@ function createWorkflowStageFactory(input) {
72042
72305
  stageSnapshot.sessionId = meta.sessionId;
72043
72306
  if (meta.sessionFile !== undefined)
72044
72307
  stageSnapshot.sessionFile = meta.sessionFile;
72045
- if (meta.sessionId !== undefined || meta.sessionFile !== undefined)
72046
- input.activeStore.recordStageSession(input.runId, stageId, meta);
72308
+ if (meta.sessionId !== undefined)
72309
+ input.activeStore.recordStageSession(input.runId, stageId, { sessionId: meta.sessionId });
72047
72310
  const pending = input.opts.onStageSession?.(input.runId, stageSnapshot, checkpointOptions);
72048
72311
  if (checkpointOptions?.forceDurable === true || checkpointOptions?.awaitDurable === true) {
72049
72312
  await pending;
@@ -72575,11 +72838,45 @@ async function executeRun(def, resolvedInputs, opts) {
72575
72838
  return waitForRunRelease().then(() => whenRunning(call));
72576
72839
  if (ownController.signal.aborted)
72577
72840
  return Promise.reject(ownController.signal.reason);
72578
- return call();
72841
+ const persistence = drainCachedStagePersistence();
72842
+ return persistence === undefined ? call() : persistence.then(() => whenRunning(call));
72579
72843
  };
72580
72844
  ownController.signal.addEventListener("abort", () => scheduler.rejectReleaseBarriers(ownController.signal.reason ?? new Error("atomic-workflows: run aborted")), { once: true });
72581
72845
  const cachedStagePersistence = [];
72582
72846
  let cachedStageFailure;
72847
+ let cachedStageDrain;
72848
+ const drainCachedStagePersistence = () => {
72849
+ if (cachedStageDrain !== undefined)
72850
+ return cachedStageDrain;
72851
+ if (cachedStagePersistence.length === 0) {
72852
+ if (cachedStageFailure !== undefined)
72853
+ throw cachedStageFailure;
72854
+ return;
72855
+ }
72856
+ cachedStageDrain = (async () => {
72857
+ try {
72858
+ while (cachedStagePersistence.length > 0)
72859
+ await Promise.all(cachedStagePersistence.splice(0));
72860
+ if (cachedStageFailure !== undefined)
72861
+ throw cachedStageFailure;
72862
+ } finally {
72863
+ cachedStageDrain = undefined;
72864
+ }
72865
+ })();
72866
+ return cachedStageDrain;
72867
+ };
72868
+ const drainBeforeCheckpoint = () => {
72869
+ const persistence = drainCachedStagePersistence();
72870
+ return persistence?.then(() => ownController.signal.throwIfAborted());
72871
+ };
72872
+ const beforeLiveCall = () => {
72873
+ ownController.signal.throwIfAborted();
72874
+ const persistence = drainCachedStagePersistence();
72875
+ if (persistence !== undefined)
72876
+ return persistence.then(beforeLiveCall);
72877
+ if (scheduler.isRunPaused())
72878
+ return waitForRunRelease().then(beforeLiveCall);
72879
+ };
72583
72880
  const finalizers = createRunFinalizers({
72584
72881
  def,
72585
72882
  runId,
@@ -72588,8 +72885,14 @@ async function executeRun(def, resolvedInputs, opts) {
72588
72885
  opts,
72589
72886
  classifyExecutorFailure,
72590
72887
  drainWorkflowExitCleanups: async (reason) => {
72591
- await Promise.all(cachedStagePersistence);
72592
- await exit.drainWorkflowExitCleanups(reason);
72888
+ try {
72889
+ await drainCachedStagePersistence();
72890
+ } catch (error) {
72891
+ if (error !== cachedStageFailure)
72892
+ throw error;
72893
+ } finally {
72894
+ await exit.drainWorkflowExitCleanups(reason);
72895
+ }
72593
72896
  },
72594
72897
  assertSuccessfulCompletion: () => {
72595
72898
  if (cachedStageFailure !== undefined)
@@ -72605,7 +72908,8 @@ async function executeRun(def, resolvedInputs, opts) {
72605
72908
  run: runSnapshot,
72606
72909
  nextCheckpointId: checkpointIdGenerator,
72607
72910
  nextReplayKey: stageReplayKeyGenerator,
72608
- completedReplayKeys: completedStageReplayKeys
72911
+ completedReplayKeys: completedStageReplayKeys,
72912
+ beforeCheckpoint: drainBeforeCheckpoint
72609
72913
  });
72610
72914
  const durableOnStageEnd = createDurableStageEndRecorder({
72611
72915
  rootRunId: runId,
@@ -72754,7 +73058,9 @@ async function executeRun(def, resolvedInputs, opts) {
72754
73058
  retryToolNodes: opts.continuation?.retryToolNodes,
72755
73059
  toolControls,
72756
73060
  toolAdmission,
72757
- budget
73061
+ budget,
73062
+ beforeToolCall: drainCachedStagePersistence,
73063
+ beforeCheckpoint: drainBeforeCheckpoint
72758
73064
  });
72759
73065
  let selectedAdmittedToolFailure;
72760
73066
  const suspendForGracefulQuit = (reason) => {
@@ -72795,9 +73101,11 @@ async function executeRun(def, resolvedInputs, opts) {
72795
73101
  workflowId: runId,
72796
73102
  backend: durableBackend,
72797
73103
  nextCheckpointId: checkpointIdGenerator,
73104
+ beforeCheckpoint: drainBeforeCheckpoint,
72798
73105
  beforeCall: () => {
72799
73106
  ownController.signal.throwIfAborted();
72800
- return scheduler.isRunPaused() ? waitForRunRelease() : undefined;
73107
+ const persistence = drainCachedStagePersistence();
73108
+ return persistence ?? (scheduler.isRunPaused() ? waitForRunRelease() : undefined);
72801
73109
  },
72802
73110
  ...opts.usePromptNodesForUi === true ? {
72803
73111
  onReplay: async (request) => getPromptNodeUi().replayDurable(request)
@@ -72834,6 +73142,7 @@ async function executeRun(def, resolvedInputs, opts) {
72834
73142
  durableIntercomGroup,
72835
73143
  task: taskRunners.task,
72836
73144
  recordCachedTask: recordCachedStage,
73145
+ beforeCheckpoint: drainBeforeCheckpoint,
72837
73146
  signal: ownController.signal,
72838
73147
  registerTailControl: (registration) => {
72839
73148
  registration.controller.signal.addEventListener("abort", () => {
@@ -72870,6 +73179,8 @@ async function executeRun(def, resolvedInputs, opts) {
72870
73179
  backend: durableBackend,
72871
73180
  nextReplayKey: (stageName) => stageReplayKeyGenerator(stageName),
72872
73181
  durableIntercomGroup,
73182
+ beforeCall: beforeLiveCall,
73183
+ beforeCheckpoint: drainBeforeCheckpoint,
72873
73184
  recordCachedStage,
72874
73185
  stage: (name, options, replayKey) => {
72875
73186
  const stage = runtime.stage(name, options);
@@ -72930,7 +73241,7 @@ async function executeRun(def, resolvedInputs, opts) {
72930
73241
  return pending;
72931
73242
  }),
72932
73243
  tool: (...args) => {
72933
- if (!scheduler.isRunPaused())
73244
+ if (admittedTools.closed)
72934
73245
  return tool(...args);
72935
73246
  const pending = whenRunning(() => tool(...args));
72936
73247
  pending.catch(() => {});
@@ -73058,13 +73369,13 @@ async function executeRun(def, resolvedInputs, opts) {
73058
73369
  ownController.signal.throwIfAborted();
73059
73370
  if (opts.parentRun === undefined) {
73060
73371
  if (durableRootRegistration !== undefined) {
73061
- await durableBackend.registerWorkflow({
73372
+ await durableBackend.commitWorkflowRegistration({
73062
73373
  ...durableRootRegistration,
73063
73374
  modelOwner: runSnapshot.modelOwner,
73064
73375
  ...workflowInvocationMetadata(inputRuntimeDefaults, workflowInvocationCwd, gitWorktreeSetupCache, runSnapshot.origin)
73065
73376
  });
73066
73377
  } else {
73067
- await durableBackend.setWorkflowStatus(runId, "running");
73378
+ await durableBackend.commitWorkflowStatus(runId, "running");
73068
73379
  }
73069
73380
  }
73070
73381
  durableRootAdmitted = true;
@@ -73086,9 +73397,7 @@ async function executeRun(def, resolvedInputs, opts) {
73086
73397
  await waitForRunRelease();
73087
73398
  ownController.signal.throwIfAborted();
73088
73399
  const rawResult = await raceAbort(runWorkflowDefinitionCallback(def.name, runId, () => def.run(ctx)), ownController.signal);
73089
- await Promise.all(cachedStagePersistence);
73090
- if (cachedStageFailure !== undefined)
73091
- throw cachedStageFailure;
73400
+ await drainCachedStagePersistence();
73092
73401
  while (scheduler.isRunPaused())
73093
73402
  await waitForRunRelease();
73094
73403
  await admittedTools.closeAndDrain();
@@ -73128,7 +73437,7 @@ async function executeRun(def, resolvedInputs, opts) {
73128
73437
  const recorded = activeStore.recordRunEnd(runId, returned.status, result, returned.error, returned.metadata);
73129
73438
  if (opts.parentRun === undefined)
73130
73439
  await recordRunTimingCheckpointAsync(durableBackend, runSnapshot);
73131
- await durableBackend.setWorkflowStatus(runId, returned.status, undefined, returned.metadata?.resumable);
73440
+ await durableBackend.commitWorkflowStatus(runId, returned.status, undefined, returned.metadata?.resumable);
73132
73441
  await appendRunEndWhenRecorded(opts.persistence, recorded, {
73133
73442
  runId,
73134
73443
  status: returned.status,
@@ -73258,6 +73567,9 @@ async function executeRun(def, resolvedInputs, opts) {
73258
73567
  unregisterToolAdmission();
73259
73568
  } finally {
73260
73569
  terminalEvents.dispose();
73570
+ if (opts.stageControlRegistry === undefined && opts.executionMode !== "interactive" && isTerminalRunStatus(runSnapshot.status) && runSnapshot.resumable !== true) {
73571
+ await stageRegistry.clear(runId);
73572
+ }
73261
73573
  }
73262
73574
  }
73263
73575
  }
@@ -73424,127 +73736,141 @@ function workflowStartupFailureMessage(admission, snapshotError, fallback) {
73424
73736
  }
73425
73737
 
73426
73738
  // dist/builtin/workflows/src/durable/fork-workflow.ts
73427
- import { randomUUID as randomUUID8 } from "node:crypto";
73428
- import { SessionManager as SessionManager3 } from "@bastani/atomic";
73429
- async function forkDurableWorkflow(backend, source, cwd, modelOwner) {
73739
+ import { randomUUID as randomUUID9 } from "node:crypto";
73740
+ async function forkDurableWorkflow(backend, source, cwd, modelOwner, sessionStore) {
73430
73741
  source = structuredClone(source);
73431
- const workflowId = randomUUID8();
73432
- const ids = new Map([[source.workflowId, workflowId]]);
73433
- const mapId = (id) => {
73434
- let mapped = ids.get(id);
73435
- if (mapped === undefined) {
73436
- mapped = randomUUID8();
73437
- ids.set(id, mapped);
73438
- }
73439
- return mapped;
73440
- };
73441
- const mapTarget = (target) => {
73442
- const parsed = parseWorkflowStageTarget(target);
73443
- if (parsed === undefined || parsed.rootRunId !== source.workflowId)
73444
- return target;
73445
- return formatWorkflowStageTarget(workflowId, ...parsed.segments.map((segment) => ids.get(segment) ?? segment));
73446
- };
73447
- const mapRun = (run) => ({
73448
- ...run,
73449
- runId: mapId(run.runId),
73450
- ...run.parentRunId === undefined ? {} : { parentRunId: mapId(run.parentRunId) },
73451
- ...run.rootRunId === undefined ? {} : { rootRunId: workflowId }
73452
- });
73453
- const sessions = new Map;
73454
- const checkpoints = [];
73455
- for (const checkpoint of backend.listCheckpoints(source.workflowId)) {
73456
- const copy = structuredClone(checkpoint);
73457
- if (copy.kind === "ui") {
73458
- checkpoints.push({ ...copy, workflowId });
73459
- continue;
73460
- }
73461
- const topology = copy.topology;
73462
- if (copy.kind === "tool") {
73742
+ const sourceStore = await stageSessionStore({ cwd: source.workflowCwd ?? source.invocationCwd ?? cwd });
73743
+ let destinationStore;
73744
+ try {
73745
+ destinationStore = sessionStore ?? await stageSessionStore({ cwd });
73746
+ const workflowId = randomUUID9();
73747
+ const ids = new Map([[source.workflowId, workflowId]]);
73748
+ const mapId = (id) => {
73749
+ let mapped = ids.get(id);
73750
+ if (mapped === undefined) {
73751
+ mapped = randomUUID9();
73752
+ ids.set(id, mapped);
73753
+ }
73754
+ return mapped;
73755
+ };
73756
+ const mapTarget = (target) => {
73757
+ const parsed = parseWorkflowStageTarget(target);
73758
+ if (parsed === undefined || parsed.rootRunId !== source.workflowId)
73759
+ return target;
73760
+ return formatWorkflowStageTarget(workflowId, ...parsed.segments.map((segment) => ids.get(segment) ?? segment));
73761
+ };
73762
+ const mapRun = (run) => ({
73763
+ ...run,
73764
+ runId: mapId(run.runId),
73765
+ ...run.parentRunId === undefined ? {} : { parentRunId: mapId(run.parentRunId) },
73766
+ ...run.rootRunId === undefined ? {} : { rootRunId: workflowId }
73767
+ });
73768
+ const sessions = new Map;
73769
+ const checkpoints = [];
73770
+ for (const checkpoint of backend.listCheckpoints(source.workflowId)) {
73771
+ const copy = structuredClone(checkpoint);
73772
+ if (copy.kind === "ui") {
73773
+ checkpoints.push({ ...copy, workflowId });
73774
+ continue;
73775
+ }
73776
+ const topology = copy.topology;
73777
+ if (copy.kind === "tool") {
73778
+ checkpoints.push({
73779
+ ...copy,
73780
+ workflowId,
73781
+ ...topology === undefined ? {} : {
73782
+ topology: {
73783
+ ...copy.topology,
73784
+ ...copy.topology?.run === undefined ? {} : { run: mapRun(copy.topology.run) }
73785
+ }
73786
+ }
73787
+ });
73788
+ continue;
73789
+ }
73790
+ const stageTopology = copy.topology;
73791
+ const boundary = stageTopology?.boundary;
73792
+ const taskOutput = isToolPayloadObject(copy.output) && typeof copy.output.text === "string" ? copy.output : undefined;
73793
+ const sessionId = copy.sessionId ?? (typeof taskOutput?.sessionId === "string" ? taskOutput.sessionId : undefined);
73794
+ let session = sessionId === undefined ? undefined : sessions.get(sessionId);
73795
+ if (session === undefined && sessionId !== undefined) {
73796
+ session = await forkStageSession(sourceStore, sessionId, cwd, {
73797
+ internal: true,
73798
+ workflow: {
73799
+ runId: workflowId,
73800
+ stageId: stageTopology?.stageId ?? copy.checkpointId,
73801
+ stageName: copy.name
73802
+ }
73803
+ }, destinationStore);
73804
+ sessions.set(sessionId, session);
73805
+ }
73806
+ const childOutput = boundary === undefined ? undefined : parseWorkflowChildResult(copy.output);
73463
73807
  checkpoints.push({
73464
73808
  ...copy,
73465
73809
  workflowId,
73466
- ...topology === undefined ? {} : {
73810
+ ...childOutput === undefined ? {} : { output: { ...childOutput, runId: mapId(childOutput.runId) } },
73811
+ ...taskOutput === undefined ? {} : {
73812
+ output: {
73813
+ ...taskOutput,
73814
+ sessionId: session?.getSessionId(),
73815
+ sessionFile: session?.getSessionFile()
73816
+ }
73817
+ },
73818
+ sessionId: session?.getSessionId(),
73819
+ sessionFile: session?.getSessionFile(),
73820
+ ...stageTopology === undefined ? {} : {
73467
73821
  topology: {
73468
- ...copy.topology,
73469
- ...copy.topology?.run === undefined ? {} : { run: mapRun(copy.topology.run) }
73822
+ ...stageTopology,
73823
+ intercomGroup: undefined,
73824
+ ...stageTopology.run === undefined ? {} : { run: mapRun(stageTopology.run) },
73825
+ ...boundary === undefined ? {} : {
73826
+ boundary: {
73827
+ ...boundary,
73828
+ child: {
73829
+ ...boundary.child,
73830
+ runId: mapId(boundary.child.runId),
73831
+ parentRunId: mapId(boundary.child.parentRunId),
73832
+ rootRunId: workflowId
73833
+ }
73834
+ }
73835
+ }
73470
73836
  }
73471
73837
  }
73472
73838
  });
73473
- continue;
73474
- }
73475
- const stageTopology = copy.topology;
73476
- const boundary = stageTopology?.boundary;
73477
- const taskOutput = isToolPayloadObject(copy.output) && typeof copy.output.text === "string" ? copy.output : undefined;
73478
- const sessionFile = copy.sessionFile ?? (typeof taskOutput?.sessionFile === "string" ? taskOutput.sessionFile : undefined);
73479
- let session = sessionFile === undefined ? undefined : sessions.get(sessionFile);
73480
- if (session === undefined && sessionFile !== undefined) {
73481
- session = await SessionManager3.forkFrom(sessionFile, cwd, undefined, {
73482
- internal: true,
73483
- workflow: { runId: workflowId, stageId: stageTopology?.stageId ?? copy.checkpointId, stageName: copy.name }
73484
- });
73485
- sessions.set(sessionFile, session);
73486
73839
  }
73487
- const childOutput = boundary === undefined ? undefined : parseWorkflowChildResult(copy.output);
73488
- checkpoints.push({
73489
- ...copy,
73840
+ const fork = {
73841
+ ...source,
73490
73842
  workflowId,
73491
- ...childOutput === undefined ? {} : { output: { ...childOutput, runId: mapId(childOutput.runId) } },
73492
- ...taskOutput === undefined ? {} : {
73493
- output: { ...taskOutput, sessionId: session?.getSessionId(), sessionFile: session?.getSessionFile() }
73494
- },
73495
- sessionId: session?.getSessionId(),
73496
- sessionFile: session?.getSessionFile(),
73497
- ...stageTopology === undefined ? {} : {
73498
- topology: {
73499
- ...stageTopology,
73500
- intercomGroup: undefined,
73501
- ...stageTopology.run === undefined ? {} : { run: mapRun(stageTopology.run) },
73502
- ...boundary === undefined ? {} : {
73503
- boundary: {
73504
- ...boundary,
73505
- child: {
73506
- ...boundary.child,
73507
- runId: mapId(boundary.child.runId),
73508
- parentRunId: mapId(boundary.child.parentRunId),
73509
- rootRunId: workflowId
73510
- }
73511
- }
73512
- }
73513
- }
73514
- }
73843
+ rootWorkflowId: undefined,
73844
+ invocationCwd: cwd,
73845
+ workflowCwd: undefined,
73846
+ repositoryRoot: undefined,
73847
+ gitWorktreeRoot: undefined,
73848
+ sessionFile: undefined,
73849
+ modelOwner,
73850
+ releasedModelOwner: undefined,
73851
+ ownerExecutorId: undefined,
73852
+ createdAt: Date.now(),
73853
+ updatedAt: Date.now(),
73854
+ completedCheckpoints: 0,
73855
+ pendingStageMessages: source.pendingStageMessages?.map((message) => ({
73856
+ ...message,
73857
+ runId: mapId(message.runId),
73858
+ stageKey: mapTarget(message.stageKey),
73859
+ ...message.targetPath === undefined ? {} : { targetPath: mapTarget(message.targetPath) }
73860
+ }))
73861
+ };
73862
+ await backend.commitWorkflowRegistration({ ...fork, status: "running", resumable: false });
73863
+ for (const checkpoint of checkpoints)
73864
+ await backend.commitCheckpoint(checkpoint);
73865
+ await backend.commitWorkflowRegistration({
73866
+ ...fork,
73867
+ resumable: source.resumable ?? true,
73868
+ completedCheckpoints: backend.getWorkflow(workflowId).completedCheckpoints
73515
73869
  });
73870
+ return workflowId;
73871
+ } finally {
73872
+ await Promise.all([sourceStore.close(), sessionStore === undefined ? destinationStore?.close() : undefined]);
73516
73873
  }
73517
- const fork = {
73518
- ...source,
73519
- workflowId,
73520
- rootWorkflowId: undefined,
73521
- invocationCwd: cwd,
73522
- workflowCwd: undefined,
73523
- repositoryRoot: undefined,
73524
- gitWorktreeRoot: undefined,
73525
- sessionFile: undefined,
73526
- modelOwner,
73527
- releasedModelOwner: undefined,
73528
- ownerExecutorId: undefined,
73529
- createdAt: Date.now(),
73530
- updatedAt: Date.now(),
73531
- completedCheckpoints: 0,
73532
- pendingStageMessages: source.pendingStageMessages?.map((message) => ({
73533
- ...message,
73534
- runId: mapId(message.runId),
73535
- stageKey: mapTarget(message.stageKey),
73536
- ...message.targetPath === undefined ? {} : { targetPath: mapTarget(message.targetPath) }
73537
- }))
73538
- };
73539
- await backend.registerWorkflow({ ...fork, status: "running", resumable: false });
73540
- for (const checkpoint of checkpoints)
73541
- await backend.recordCheckpointAsync(checkpoint);
73542
- await backend.registerWorkflow({
73543
- ...fork,
73544
- resumable: source.resumable ?? true,
73545
- completedCheckpoints: backend.getWorkflow(workflowId).completedCheckpoints
73546
- });
73547
- return workflowId;
73548
73874
  }
73549
73875
 
73550
73876
  // dist/builtin/workflows/src/durable/tool-resume-frontier.ts
@@ -73780,7 +74106,7 @@ async function resumeDurableWorkflowClaimed(workflowId, deps, catalog) {
73780
74106
  }
73781
74107
  if (crossProject) {
73782
74108
  deps.signal?.throwIfAborted();
73783
- const forkId = await forkDurableWorkflow(backend, handle, currentCwd, deps.forkModelOwner ?? requestedOwner);
74109
+ const forkId = await forkDurableWorkflow(backend, handle, currentCwd, deps.forkModelOwner ?? requestedOwner, deps.baseRunOpts.adapters?.sessionStore);
73784
74110
  const fork = backend.getWorkflow(forkId);
73785
74111
  const result = await resumeDurableWorkflow(forkId, {
73786
74112
  ...deps,
@@ -73824,12 +74150,12 @@ async function resumeDurableWorkflowClaimed(workflowId, deps, catalog) {
73824
74150
  const current = backend.getWorkflow(resolved.workflowId);
73825
74151
  if (adoptedClaimUpdatedAt === undefined || current?.modelOwner !== requestedOwner)
73826
74152
  return false;
73827
- const restored = await backend.transitionWorkflowStatus(resolved.workflowId, ["running"], handle.status, handle.pendingPrompts, handle.resumable, adoptedClaimUpdatedAt);
74153
+ const restored = await backend.commitWorkflowStatusTransition(resolved.workflowId, ["running"], handle.status, handle.pendingPrompts, handle.resumable, adoptedClaimUpdatedAt);
73828
74154
  if (restored)
73829
74155
  onRestored?.();
73830
74156
  return restored;
73831
74157
  }
73832
- await backend.setWorkflowStatus(resolved.workflowId, handle.status, handle.pendingPrompts, handle.resumable, sourceFailure);
74158
+ await backend.commitWorkflowStatus(resolved.workflowId, handle.status, handle.pendingPrompts, handle.resumable, sourceFailure);
73833
74159
  onRestored?.();
73834
74160
  return true;
73835
74161
  };
@@ -73844,7 +74170,7 @@ async function resumeDurableWorkflowClaimed(workflowId, deps, catalog) {
73844
74170
  }
73845
74171
  unsettled.add(resolved.workflowId);
73846
74172
  try {
73847
- claimed = await backend.transitionWorkflowStatus(resolved.workflowId, [handle.status], "running", undefined, undefined, resolved.updatedAt, adopting ? requestedOwner : undefined);
74173
+ claimed = await backend.commitWorkflowStatusTransition(resolved.workflowId, [handle.status], "running", undefined, undefined, resolved.updatedAt, adopting ? requestedOwner : undefined);
73848
74174
  if (claimed && adopting)
73849
74175
  adoptedClaimUpdatedAt = backend.getWorkflow(resolved.workflowId)?.updatedAt;
73850
74176
  if (claimed && !adopting && deps.signal?.aborted)
@@ -73889,7 +74215,7 @@ async function resumeDurableWorkflowClaimed(workflowId, deps, catalog) {
73889
74215
  if (toolContinuation !== undefined && (message.includes("insufficient_state: replay topology mismatch") || message.includes("insufficient_state: replay topology ambiguous"))) {
73890
74216
  const current = deps.baseRunOpts.store?.runs().find((run) => run.id === resolved.workflowId);
73891
74217
  if (current?.status === "failed" && current.error === message) {
73892
- await backend.setWorkflowStatus(resolved.workflowId, handle.status, handle.pendingPrompts, handle.resumable, sourceFailure);
74218
+ await backend.commitWorkflowStatus(resolved.workflowId, handle.status, handle.pendingPrompts, handle.resumable, sourceFailure);
73893
74219
  if (deps.baseRunOpts.store?.runs().find((run) => run.id === resolved.workflowId) === current && current.status === "failed" && current.error === message) {
73894
74220
  deps.baseRunOpts.store.recordRunStart({ ...toolContinuation.source, error: message });
73895
74221
  }
@@ -74001,15 +74327,17 @@ function isReservedRunCheckpointHash(argsHash) {
74001
74327
  function listCompletedFromBackend(backend) {
74002
74328
  return backend.listCompletedWorkflows();
74003
74329
  }
74004
- function listOpenableCompletedWorkflows(backend) {
74005
- return listCompletedFromBackend(backend).filter((entry) => completedWorkflowSnapshot(backend, entry) !== undefined).sort((a, b) => b.updatedAt - a.updatedAt);
74330
+ async function listOpenableCompletedWorkflows(backend, sessionStore) {
74331
+ const entries = listCompletedFromBackend(backend);
74332
+ const snapshots = await Promise.all(entries.map((entry) => completedWorkflowSnapshot(backend, entry, sessionStore)));
74333
+ return entries.filter((_entry, index) => snapshots[index] !== undefined).sort((a, b) => b.updatedAt - a.updatedAt);
74006
74334
  }
74007
- function resolveCompletedWorkflow(workflowId, backend, openableCatalog = listOpenableCompletedWorkflows(backend)) {
74008
- const resolved = resolveDurableEntry(workflowId, openableCatalog);
74335
+ async function resolveCompletedWorkflow(workflowId, backend, openableCatalog, sessionStore) {
74336
+ const resolved = resolveDurableEntry(workflowId, openableCatalog ?? await listOpenableCompletedWorkflows(backend, sessionStore));
74009
74337
  if (resolved !== undefined) {
74010
74338
  if ("kind" in resolved)
74011
74339
  return { kind: "malformed", message: resolved.message };
74012
- const snapshot = completedWorkflowSnapshot(backend, resolved);
74340
+ const snapshot = await completedWorkflowSnapshot(backend, resolved, sessionStore);
74013
74341
  if (snapshot === undefined) {
74014
74342
  return { kind: "stale", entry: resolved };
74015
74343
  }
@@ -74022,40 +74350,49 @@ function resolveCompletedWorkflow(workflowId, backend, openableCatalog = listOpe
74022
74350
  return { kind: "malformed", message: authoritative.message };
74023
74351
  return { kind: "stale", entry: authoritative };
74024
74352
  }
74025
- function completedWorkflowSnapshot(backend, entry) {
74026
- const runs = completedWorkflowRunSnapshots(backend, entry);
74353
+ async function completedWorkflowSnapshot(backend, entry, sessionStore) {
74354
+ const runs = await completedWorkflowRunSnapshots(backend, entry, sessionStore);
74027
74355
  return runs.find((run) => run.id === entry.workflowId);
74028
74356
  }
74029
- function completedWorkflowRunSnapshots(backend, entry) {
74357
+ async function completedWorkflowRunSnapshots(backend, entry, sessionStore) {
74030
74358
  const handle = backend.getWorkflow(entry.workflowId);
74031
74359
  if (handle === undefined || handle.status !== "completed" && handle.status !== "failed")
74032
74360
  return [];
74033
74361
  const checkpoints = backend.listCheckpoints(entry.workflowId);
74034
74362
  if (checkpoints.length === 0)
74035
74363
  return [];
74036
- const runs = runSnapshotsFromCheckpoints(checkpoints, handle.workflowId, handle.name, handle.updatedAt, COMPLETED_RECONSTRUCTION).map((run) => ({ ...run, stages: run.stages.map(validatedStageTranscript) }));
74037
- const rootIndex = runs.findIndex((run) => run.id === handle.workflowId);
74038
- if (rootIndex < 0)
74039
- return [];
74040
- const rootDuration = priorRunElapsedMs(backend, handle.workflowId) ?? Math.max(0, handle.updatedAt - handle.createdAt);
74041
- const root = {
74042
- ...runs[rootIndex],
74043
- inputs: { ...handle.inputs },
74044
- status: handle.status,
74045
- startedAt: handle.createdAt,
74046
- endedAt: handle.updatedAt,
74047
- durationMs: rootDuration,
74048
- ...handle.error !== undefined ? { error: handle.error } : {},
74049
- ...handle.exited !== undefined ? { exited: handle.exited } : {},
74050
- ...handle.exitReason !== undefined ? { exitReason: handle.exitReason } : {},
74051
- ...handle.failureKind !== undefined ? { failureKind: handle.failureKind } : {},
74052
- ...handle.failureCode !== undefined ? { failureCode: handle.failureCode } : {},
74053
- ...handle.failureRecoverability !== undefined ? { failureRecoverability: handle.failureRecoverability } : {},
74054
- ...handle.failureDisposition !== undefined ? { failureDisposition: handle.failureDisposition } : {},
74055
- ...handle.failedToolNodeId !== undefined ? { failedToolNodeId: handle.failedToolNodeId } : {},
74056
- resumable: handle.resumable ?? false
74057
- };
74058
- return [root, ...runs.filter((_, index) => index !== rootIndex)];
74364
+ const selectedStore = sessionStore ?? await stageSessionStore({ cwd: handle.workflowCwd ?? handle.invocationCwd });
74365
+ try {
74366
+ const runs = await Promise.all(runSnapshotsFromCheckpoints(checkpoints, handle.workflowId, handle.name, handle.updatedAt, COMPLETED_RECONSTRUCTION).map(async (run) => ({
74367
+ ...run,
74368
+ stages: await Promise.all(run.stages.map((stage) => validatedStageTranscript(stage, selectedStore)))
74369
+ })));
74370
+ const rootIndex = runs.findIndex((run) => run.id === handle.workflowId);
74371
+ if (rootIndex < 0)
74372
+ return [];
74373
+ const rootDuration = priorRunElapsedMs(backend, handle.workflowId) ?? Math.max(0, handle.updatedAt - handle.createdAt);
74374
+ const root = {
74375
+ ...runs[rootIndex],
74376
+ inputs: { ...handle.inputs },
74377
+ status: handle.status,
74378
+ startedAt: handle.createdAt,
74379
+ endedAt: handle.updatedAt,
74380
+ durationMs: rootDuration,
74381
+ ...handle.error !== undefined ? { error: handle.error } : {},
74382
+ ...handle.exited !== undefined ? { exited: handle.exited } : {},
74383
+ ...handle.exitReason !== undefined ? { exitReason: handle.exitReason } : {},
74384
+ ...handle.failureKind !== undefined ? { failureKind: handle.failureKind } : {},
74385
+ ...handle.failureCode !== undefined ? { failureCode: handle.failureCode } : {},
74386
+ ...handle.failureRecoverability !== undefined ? { failureRecoverability: handle.failureRecoverability } : {},
74387
+ ...handle.failureDisposition !== undefined ? { failureDisposition: handle.failureDisposition } : {},
74388
+ ...handle.failedToolNodeId !== undefined ? { failedToolNodeId: handle.failedToolNodeId } : {},
74389
+ resumable: handle.resumable ?? false
74390
+ };
74391
+ return [root, ...runs.filter((_, index) => index !== rootIndex)];
74392
+ } finally {
74393
+ if (sessionStore === undefined)
74394
+ await selectedStore.close();
74395
+ }
74059
74396
  }
74060
74397
  function durableWorkflowRunSnapshots(backend, handle) {
74061
74398
  const checkpoints = backend.listCheckpoints(handle.workflowId);
@@ -74100,11 +74437,11 @@ function durableNestedRunSnapshots(backend, rootWorkflowId) {
74100
74437
  return [];
74101
74438
  return runSnapshotsFromCheckpoints(backend.listCheckpoints(rootWorkflowId), rootWorkflowId, handle.name, handle.updatedAt, ACTIVE_INSPECTION_RECONSTRUCTION).filter((run) => run.id !== rootWorkflowId);
74102
74439
  }
74103
- function validatedStageTranscript(stage) {
74104
- if (stage.sessionFile === undefined || isReopenableSessionTranscript(stage.sessionFile))
74440
+ async function validatedStageTranscript(stage, store) {
74441
+ if (stage.sessionId !== undefined && await isReopenableSession(store, stage.sessionId))
74105
74442
  return stage;
74106
- const { sessionFile, ...withoutSessionFile } = stage;
74107
- return withoutSessionFile;
74443
+ const { sessionId: _sessionId, sessionFile: _sessionFile, ...withoutSession } = stage;
74444
+ return withoutSession;
74108
74445
  }
74109
74446
  function checkpointDrafts(checkpoints) {
74110
74447
  const stageByReplayKey = new Map;
@@ -74410,7 +74747,8 @@ function emptyGraphRun(runId, runName, completedAt) {
74410
74747
 
74411
74748
  // dist/builtin/workflows/src/runs/foreground/postmortem-stage-chat.ts
74412
74749
  var TERMINAL_POSTMORTEM_STATUSES = new Set(["completed"]);
74413
- function ensurePostMortemStageHandle(runId, stage, deps) {
74750
+ async function ensurePostMortemStageHandle(runId, stage, deps) {
74751
+ const generation = deps.registry.generation;
74414
74752
  if (!TERMINAL_POSTMORTEM_STATUSES.has(stage.status))
74415
74753
  return { ok: false, reason: "not_terminal" };
74416
74754
  const existing = deps.registry.claim(runId, stage.id);
@@ -74419,23 +74757,30 @@ function ensurePostMortemStageHandle(runId, stage, deps) {
74419
74757
  }
74420
74758
  if (deps.adapters?.agentSession === undefined)
74421
74759
  return { ok: false, reason: "no_adapter" };
74422
- const sessionFile = stage.sessionFile;
74423
- if (typeof sessionFile !== "string" || sessionFile.length === 0)
74760
+ const sessionId = stage.sessionId;
74761
+ if (sessionId === undefined)
74424
74762
  return { ok: false, reason: "no_session" };
74425
- if (!isReopenableSessionTranscript(sessionFile))
74763
+ const sessionStore = await stageSessionStore({
74764
+ sessionStore: deps.registry.getSessionStore(runId, stage.id) ?? deps.sessionStore ?? deps.adapters.sessionStore,
74765
+ cwd: deps.cwd
74766
+ }, deps.defaultSessionDir);
74767
+ if (!await isReopenableSession(sessionStore, sessionId))
74426
74768
  return { ok: false, reason: "invalid_session" };
74769
+ if (deps.registry.generation !== generation)
74770
+ return { ok: false, reason: "closed" };
74427
74771
  const adapters = deps.adapters;
74428
- const handle = deps.registry.getOrCreateDetached(runId, stage.id, () => createPostMortemStageHandle(runId, stage, sessionFile, adapters, deps.cwd, deps.defaultSessionDir));
74772
+ const handle = deps.registry.getOrCreateDetached(runId, stage.id, () => createPostMortemStageHandle(runId, stage, sessionId, adapters, deps.cwd, deps.defaultSessionDir, sessionStore));
74429
74773
  return { ok: true, handle };
74430
74774
  }
74431
- function createPostMortemStageHandle(runId, stage, sessionFile, adapters, cwd, defaultSessionDir) {
74775
+ function createPostMortemStageHandle(runId, stage, sessionId, adapters, cwd, defaultSessionDir, sessionStore) {
74432
74776
  const context = createStageContext2({
74433
74777
  runId,
74434
74778
  stageId: stage.id,
74435
74779
  stageName: stage.name,
74436
74780
  adapters,
74437
74781
  stageOptions: {
74438
- resumeFromSessionFile: sessionFile,
74782
+ resumeFromSessionId: sessionId,
74783
+ sessionStore,
74439
74784
  ...cwd !== undefined ? { cwd } : {}
74440
74785
  },
74441
74786
  ...defaultSessionDir !== undefined ? { defaultSessionDir } : {}
@@ -74446,14 +74791,14 @@ function createPostMortemStageHandle(runId, stage, sessionFile, adapters, cwd, d
74446
74791
  throw new Error(`Post-mortem stage chat "${stage.name}" is closed.`);
74447
74792
  };
74448
74793
  const messagePreparation = () => ({
74449
- ...context.__sessionMeta().sessionFile === undefined ? { sessionFile } : {},
74794
+ ...context.__sessionMeta().sessionId === undefined ? { sessionId } : {},
74450
74795
  beforePreparation: throwIfClosed
74451
74796
  });
74452
74797
  const ensureAttached = async () => {
74453
74798
  throwIfClosed();
74454
- const sessionFileToRestore = messagePreparation().sessionFile;
74455
- if (sessionFileToRestore !== undefined) {
74456
- await context.__ensureSessionFromFile(sessionFileToRestore);
74799
+ const sessionIdToRestore = messagePreparation().sessionId;
74800
+ if (sessionIdToRestore !== undefined) {
74801
+ await context.__ensureSessionFromId(sessionIdToRestore);
74457
74802
  }
74458
74803
  };
74459
74804
  const queuedUserMessages = new StageQueuedUserMessageBuffer;
@@ -74463,11 +74808,12 @@ function createPostMortemStageHandle(runId, stage, sessionFile, adapters, cwd, d
74463
74808
  stageId: stage.id,
74464
74809
  stageName: stage.name,
74465
74810
  status: "completed",
74811
+ sessionStore,
74466
74812
  get sessionId() {
74467
- return context.__sessionMeta().sessionId ?? stage.sessionId;
74813
+ return context.__sessionMeta().sessionId ?? sessionId;
74468
74814
  },
74469
74815
  get sessionFile() {
74470
- return context.__sessionMeta().sessionFile ?? sessionFile;
74816
+ return context.__sessionMeta().sessionFile ?? stage.sessionFile;
74471
74817
  },
74472
74818
  get isStreaming() {
74473
74819
  return context.isStreaming;
@@ -74533,8 +74879,9 @@ function createPostMortemStageHandle(runId, stage, sessionFile, adapters, cwd, d
74533
74879
 
74534
74880
  // dist/builtin/workflows/src/durable/completed-inspection.ts
74535
74881
  var completedChatRegistrations = new WeakMap;
74536
- function openCompletedDurableWorkflow(workflowId, deps, catalog = listOpenableCompletedWorkflows(deps.durableBackend)) {
74537
- const resolved = resolveCompletedWorkflow(workflowId, deps.durableBackend, catalog);
74882
+ async function openCompletedDurableWorkflow(workflowId, deps, catalog) {
74883
+ const selectedStore = await stageSessionStore({ sessionStore: deps.sessionStore ?? deps.adapters?.sessionStore, cwd: deps.cwd }, deps.defaultSessionDir);
74884
+ const resolved = await resolveCompletedWorkflow(workflowId, deps.durableBackend, catalog, selectedStore);
74538
74885
  if (resolved.kind === "not_found") {
74539
74886
  return failure2("not_found", `No completed durable workflow found for id: ${workflowId}`);
74540
74887
  }
@@ -74548,7 +74895,7 @@ function openCompletedDurableWorkflow(workflowId, deps, catalog = listOpenableCo
74548
74895
  if (existing !== undefined && existing.status !== "completed") {
74549
74896
  return failure2("active", `Workflow ${resolved.snapshot.id} is already active in this session; attach with /workflow connect ${resolved.snapshot.id} instead.`);
74550
74897
  }
74551
- const snapshots = completedWorkflowRunSnapshots(deps.durableBackend, resolved.entry);
74898
+ const snapshots = await completedWorkflowRunSnapshots(deps.durableBackend, resolved.entry, selectedStore);
74552
74899
  const snapshot = snapshots.find((run) => run.id === resolved.snapshot.id) ?? resolved.snapshot;
74553
74900
  deps.beforeRestore?.(snapshots);
74554
74901
  for (const restored of snapshots) {
@@ -74556,9 +74903,9 @@ function openCompletedDurableWorkflow(workflowId, deps, catalog = listOpenableCo
74556
74903
  if (previous !== undefined)
74557
74904
  deps.store.removeRun(previous.id);
74558
74905
  deps.store.recordRunStart(restored);
74559
- registerCompletedChatHandles(restored, deps);
74906
+ registerCompletedChatHandles(restored, deps, selectedStore);
74560
74907
  }
74561
- const hasReopenableStage = snapshots.some((run) => run.stages.some((stage) => stage.sessionFile !== undefined));
74908
+ const hasReopenableStage = snapshots.some((run) => run.stages.some((stage) => stage.sessionId !== undefined));
74562
74909
  return {
74563
74910
  ok: true,
74564
74911
  runId: snapshot.id,
@@ -74570,32 +74917,32 @@ function openCompletedDurableWorkflow(workflowId, deps, catalog = listOpenableCo
74570
74917
  function failure2(reason, message) {
74571
74918
  return { ok: false, reason, message };
74572
74919
  }
74573
- function registerCompletedChatHandles(snapshot, deps) {
74920
+ function registerCompletedChatHandles(snapshot, deps, sessionStore) {
74574
74921
  if (deps.adapters?.agentSession === undefined)
74575
74922
  return;
74576
74923
  const registry = deps.stageControlRegistry ?? stageControlRegistry;
74577
74924
  const registrations = completedChatRegistrations.get(registry) ?? new Map;
74578
74925
  completedChatRegistrations.set(registry, registrations);
74579
- const desiredKeys = new Set(snapshot.stages.filter((stage) => stage.sessionFile !== undefined).map((stage) => completedChatKey(snapshot.id, stage.id)));
74926
+ const desiredKeys = new Set(snapshot.stages.filter((stage) => stage.sessionId !== undefined).map((stage) => completedChatKey(snapshot.id, stage.id)));
74580
74927
  for (const [key, registration] of registrations) {
74581
74928
  if (!key.startsWith(`${snapshot.id}:`) || desiredKeys.has(key))
74582
74929
  continue;
74583
74930
  removeCompletedChatRegistration(registrations, key, registration);
74584
74931
  }
74585
74932
  for (const stage of snapshot.stages) {
74586
- if (stage.sessionFile === undefined)
74933
+ if (stage.sessionId === undefined)
74587
74934
  continue;
74588
74935
  const key = completedChatKey(snapshot.id, stage.id);
74589
74936
  const registration = registrations.get(key);
74590
74937
  const existing = registry.claim(snapshot.id, stage.id);
74591
- if (existing?.sessionFile === stage.sessionFile && !existing.isDisposed)
74938
+ if (existing?.sessionId === stage.sessionId && existing.sessionStore === sessionStore && !existing.isDisposed)
74592
74939
  continue;
74593
74940
  if (registration !== undefined) {
74594
74941
  removeCompletedChatRegistration(registrations, key, registration);
74595
74942
  } else if (existing !== undefined) {
74596
74943
  disposeCompletedChatHandle(existing);
74597
74944
  }
74598
- const handle = createPostMortemStageHandle(snapshot.id, stage, stage.sessionFile, deps.adapters, deps.cwd, deps.defaultSessionDir);
74945
+ const handle = createPostMortemStageHandle(snapshot.id, stage, stage.sessionId, deps.adapters, deps.cwd, deps.defaultSessionDir, sessionStore);
74599
74946
  const unregister = registry.register(handle);
74600
74947
  registrations.set(key, { handle, unregister });
74601
74948
  registry.detachControl(snapshot.id, stage.id, handle);
@@ -74995,7 +75342,7 @@ async function prepareWorkflowResumeCatalog(runtime, suppressedLiveIds, target)
74995
75342
  const fallbackBackend = shared === undefined ? runtime.durableBackend() : undefined;
74996
75343
  const isDisplayLoadable = (entry) => fallbackBackend === undefined || fallbackBackend.isWorkflowLoadable(entry.workflowId);
74997
75344
  const resumable = filterSelectorDurableEntries(runtime, prepared).filter((entry) => !suppressedLiveIds.has(entry.workflowId) && isDisplayLoadable(entry));
74998
- const completed = shared?.completed ?? (runtime.prepareCompletedDurable !== undefined ? await runtime.prepareCompletedDurable() : listOpenableCompletedWorkflows(fallbackBackend ?? runtime.durableBackend()));
75345
+ const completed = shared?.completed ?? (runtime.prepareCompletedDurable !== undefined ? await runtime.prepareCompletedDurable() : await listOpenableCompletedWorkflows(fallbackBackend ?? runtime.durableBackend()));
74999
75346
  return {
75000
75347
  resumable,
75001
75348
  completed: completed.filter((entry) => isDisplayLoadable(entry))
@@ -75033,7 +75380,7 @@ async function handleDurableResume(target, ctx, reporter, deps, preparedCatalog)
75033
75380
  if (resolved.kind === "durable") {
75034
75381
  return await resumeDurableTarget(resolved.workflowId, ctx, reporter, deps, runtime);
75035
75382
  }
75036
- const completedAttempt = openCompleted(runtime, target, catalog.completed, deps.beforeRestoreCompleted, owner.store);
75383
+ const completedAttempt = await openCompleted(runtime, target, catalog.completed, deps.beforeRestoreCompleted, owner.store);
75037
75384
  if (!completedAttempt.ok && completedAttempt.reason !== "not_found") {
75038
75385
  fail(completedAttempt.message);
75039
75386
  return true;
@@ -75148,8 +75495,8 @@ async function resumeDurableTarget(workflowId, ctx, reporter, deps, runtime) {
75148
75495
  }
75149
75496
  return true;
75150
75497
  }
75151
- function openCompletedTarget(workflowId, catalog, ctx, reporter, deps, runtime) {
75152
- const result = openCompleted(runtime, workflowId, catalog, deps.beforeRestoreCompleted, deps.owner?.store);
75498
+ async function openCompletedTarget(workflowId, catalog, ctx, reporter, deps, runtime) {
75499
+ const result = await openCompleted(runtime, workflowId, catalog, deps.beforeRestoreCompleted, deps.owner?.store);
75153
75500
  if (!result.ok)
75154
75501
  reporter.error(result.message);
75155
75502
  else {
@@ -75484,7 +75831,7 @@ import { registerExtensionContextRetirementEffect as registerExtensionContextRet
75484
75831
 
75485
75832
  // dist/builtin/workflows/src/extension/discovery.ts
75486
75833
  import { join as join30 } from "node:path";
75487
- import { CONFIG_DIR_NAME as CONFIG_DIR_NAME3, getAgentDir as getAgentDir5 } from "@bastani/atomic";
75834
+ import { CONFIG_DIR_NAME as CONFIG_DIR_NAME3, getAgentDir as getAgentDir6 } from "@bastani/atomic";
75488
75835
 
75489
75836
  // dist/builtin/workflows/builtin/index.ts
75490
75837
  var exports_builtin = {};
@@ -75739,7 +76086,7 @@ function withBuiltinContext(ctx) {
75739
76086
 
75740
76087
  // dist/builtin/workflows/builtin/adversarial-verification-runner.ts
75741
76088
  import { readFile, writeFile as writeFile2 } from "node:fs/promises";
75742
- import { join as join15 } from "node:path";
76089
+ import { join as join14 } from "node:path";
75743
76090
  import { Type as Type4 } from "typebox";
75744
76091
 
75745
76092
  // dist/builtin/workflows/builtin/adversarial-verification-prompts.ts
@@ -76149,12 +76496,12 @@ async function warm_first_fan_out(ctx, steps, prefixKeyOf, options = {}) {
76149
76496
  }
76150
76497
 
76151
76498
  // dist/builtin/workflows/builtin/pattern-artifact-root.ts
76152
- import { randomUUID as randomUUID9 } from "node:crypto";
76499
+ import { randomUUID as randomUUID10 } from "node:crypto";
76153
76500
  import { mkdir as mkdir3 } from "node:fs/promises";
76154
- import { join as join14 } from "node:path";
76501
+ import { join as join13 } from "node:path";
76155
76502
  async function stableArtifactRoot(ctx, workflowName) {
76156
76503
  const cwd = ctx.cwd ?? process.cwd();
76157
- const artifactDir = await ctx.tool("artifact-root", { workflow: workflowName }, async () => join14(cwd, ".atomic", "workflows", "runs", `${workflowName}-${randomUUID9()}`));
76504
+ const artifactDir = await ctx.tool("artifact-root", { workflow: workflowName }, async () => join13(cwd, ".atomic", "workflows", "runs", `${workflowName}-${randomUUID10()}`));
76158
76505
  await mkdir3(artifactDir, { recursive: true });
76159
76506
  return artifactDir;
76160
76507
  }
@@ -76272,8 +76619,8 @@ async function writeInvalid(path, stage) {
76272
76619
  }
76273
76620
  async function runAdversarialVerification(ctx) {
76274
76621
  const root = await stableArtifactRoot(ctx, "adversarial-verification");
76275
- const criteriaPath = join15(root, "criteria.md");
76276
- const candidatePath = join15(root, "candidate.md");
76622
+ const criteriaPath = join14(root, "criteria.md");
76623
+ const candidatePath = join14(root, "candidate.md");
76277
76624
  const resolvedCriteria = resolveCriteria(ctx.inputs.criteria);
76278
76625
  await writeFile2(criteriaPath, renderCriteriaMarkdown(resolvedCriteria));
76279
76626
  await ctx.task("worker", { prompt: renderWorkerPrompt(ctx.inputs.task), context: "fresh", output: candidatePath, outputMode: "file-only" });
@@ -76305,7 +76652,7 @@ async function runAdversarialVerification(ctx) {
76305
76652
  criterion,
76306
76653
  verifierIndex: index + 1,
76307
76654
  name,
76308
- artifactPath: join15(root, `verification-${round}-${criterion.id}-${index + 1}.json`)
76655
+ artifactPath: join14(root, `verification-${round}-${criterion.id}-${index + 1}.json`)
76309
76656
  });
76310
76657
  }
76311
76658
  }
@@ -76358,8 +76705,8 @@ async function runAdversarialVerification(ctx) {
76358
76705
  const decision = decide_verification(roundResult, { acceptMean, quorumFraction: QUORUM_FRACTION });
76359
76706
  finalDecision = decision;
76360
76707
  finalMean = meanScore(scoreReports);
76361
- scoreTablePath = join15(root, `verification-summary-${round}.json`);
76362
- reviewReportPath = join15(root, `review-${round}.json`);
76708
+ scoreTablePath = join14(root, `verification-summary-${round}.json`);
76709
+ reviewReportPath = join14(root, `review-${round}.json`);
76363
76710
  const summary = {
76364
76711
  scores: scoreReports,
76365
76712
  mean: finalMean,
@@ -76456,7 +76803,7 @@ import { Type as Type7 } from "typebox";
76456
76803
 
76457
76804
  // dist/builtin/workflows/builtin/classify-and-act-runner.ts
76458
76805
  import { writeFile as writeFile3 } from "node:fs/promises";
76459
- import { join as join16 } from "node:path";
76806
+ import { join as join15 } from "node:path";
76460
76807
  import { Type as Type6 } from "typebox";
76461
76808
 
76462
76809
  // dist/builtin/workflows/builtin/classify-and-act-prompts.ts
@@ -76559,7 +76906,7 @@ async function runClassifyAndAct(ctx) {
76559
76906
  const needsFallback = exactCategory === undefined || confidence < ctx.inputs.confidence_threshold;
76560
76907
  const fallback = needsFallback ? await resolveFallbackCategory(ctx, exactCategory) : undefined;
76561
76908
  const category = fallback?.category ?? exactCategory;
76562
- const classificationPath = join16(artifactDir, "classification.json");
76909
+ const classificationPath = join15(artifactDir, "classification.json");
76563
76910
  await writeFile3(classificationPath, JSON.stringify({
76564
76911
  proposed_category: proposedCategory,
76565
76912
  selected_category: category,
@@ -76569,7 +76916,7 @@ async function runClassifyAndAct(ctx) {
76569
76916
  fallback_used: needsFallback,
76570
76917
  fallback_mode: fallback?.fallbackMode ?? "none"
76571
76918
  }, null, 2));
76572
- const actionPath = join16(artifactDir, `action-${safeName(category)}.md`);
76919
+ const actionPath = join15(artifactDir, `action-${safeName(category)}.md`);
76573
76920
  const action = await ctx.task(`action-${safeName(category)}`, {
76574
76921
  tools: actionTools(category),
76575
76922
  prompt: actionPrompt({ prompt: ctx.inputs.prompt, category, classificationPath }),
@@ -76619,7 +76966,7 @@ import { Type as Type9 } from "typebox";
76619
76966
 
76620
76967
  // dist/builtin/workflows/builtin/fan-out-and-synthesize-runner.ts
76621
76968
  import { writeFile as writeFile4 } from "node:fs/promises";
76622
- import { join as join17 } from "node:path";
76969
+ import { join as join16 } from "node:path";
76623
76970
  import { Type as Type8 } from "typebox";
76624
76971
 
76625
76972
  // dist/builtin/workflows/builtin/fan-out-and-synthesize-prompts.ts
@@ -76735,9 +77082,9 @@ async function runFanOutAndSynthesize(ctx) {
76735
77082
  context: "fresh"
76736
77083
  });
76737
77084
  const partitions = parsedPartitions(plan.structured, ctx.inputs.max_branches, ctx.inputs.prompt);
76738
- const partitionPath = join17(artifactDir, "partition-plan.json");
77085
+ const partitionPath = join16(artifactDir, "partition-plan.json");
76739
77086
  await writeFile4(partitionPath, JSON.stringify({ task: ctx.inputs.prompt, partitions }, null, 2));
76740
- const branchPaths = partitions.map((partition, index) => join17(artifactDir, `branch-${safeName2(partition.label, index)}.md`));
77087
+ const branchPaths = partitions.map((partition, index) => join16(artifactDir, `branch-${safeName2(partition.label, index)}.md`));
76741
77088
  const steps = partitions.map((partition, index) => ({
76742
77089
  name: `branch-${safeName2(partition.label, index)}`,
76743
77090
  prompt: branchPrompt({ prompt: ctx.inputs.prompt, ...partition }),
@@ -76747,13 +77094,13 @@ async function runFanOutAndSynthesize(ctx) {
76747
77094
  outputMode: "file-only"
76748
77095
  }));
76749
77096
  await ctx.parallel(steps, { concurrency: Math.min(ctx.inputs.max_concurrency, partitions.length), failFast: false });
76750
- const manifestPath = join17(artifactDir, "manifest.json");
77097
+ const manifestPath = join16(artifactDir, "manifest.json");
76751
77098
  await writeFile4(manifestPath, JSON.stringify({
76752
77099
  task: ctx.inputs.prompt,
76753
77100
  partition_plan: partitionPath,
76754
77101
  branches: partitions.map((partition, index) => ({ ...partition, artifact_path: branchPaths[index] }))
76755
77102
  }, null, 2));
76756
- const synthesisPath = join17(artifactDir, "synthesis.md");
77103
+ const synthesisPath = join16(artifactDir, "synthesis.md");
76757
77104
  const synthesis = await ctx.task("synthesize", {
76758
77105
  prompt: synthesisPrompt(ctx.inputs.prompt, manifestPath),
76759
77106
  context: "fresh",
@@ -76806,7 +77153,7 @@ import { Type as Type11 } from "typebox";
76806
77153
 
76807
77154
  // dist/builtin/workflows/builtin/generate-and-filter-runner.ts
76808
77155
  import { readFile as readFile2, writeFile as writeFile5 } from "node:fs/promises";
76809
- import { join as join18 } from "node:path";
77156
+ import { join as join17 } from "node:path";
76810
77157
  import { Type as Type10 } from "typebox";
76811
77158
 
76812
77159
  // dist/builtin/workflows/builtin/generate-and-filter-prompts.ts
@@ -76927,7 +77274,7 @@ function judgeDecision(value2) {
76927
77274
  }
76928
77275
  async function runGenerateAndFilter(ctx) {
76929
77276
  const root = await stableArtifactRoot(ctx, "generate-and-filter");
76930
- const candidatePaths = Array.from({ length: ctx.inputs.num_candidates }, (_, index) => join18(root, `candidate-${index + 1}.md`));
77277
+ const candidatePaths = Array.from({ length: ctx.inputs.num_candidates }, (_, index) => join17(root, `candidate-${index + 1}.md`));
76931
77278
  const shortlistLimit = Math.min(ctx.inputs.shortlist_size, ctx.inputs.num_candidates);
76932
77279
  await ctx.parallel(candidatePaths.map((path, index) => ({
76933
77280
  name: `generate-${index + 1}`,
@@ -76936,9 +77283,9 @@ async function runGenerateAndFilter(ctx) {
76936
77283
  output: path,
76937
77284
  outputMode: "file-only"
76938
77285
  })), { concurrency: ctx.inputs.max_concurrency, failFast: false });
76939
- const manifestPath = join18(root, "manifest.json");
77286
+ const manifestPath = join17(root, "manifest.json");
76940
77287
  await writeFile5(manifestPath, JSON.stringify({ task: ctx.inputs.prompt, candidate_artifact_paths: candidatePaths }, null, 2));
76941
- const filterPath = join18(root, "filter.json");
77288
+ const filterPath = join17(root, "filter.json");
76942
77289
  const filtered = await ctx.task("dedupe-and-filter", {
76943
77290
  prompt: renderFilterPrompt(ctx.inputs.prompt, candidatePaths, shortlistLimit),
76944
77291
  context: "fresh",
@@ -76955,7 +77302,7 @@ async function runGenerateAndFilter(ctx) {
76955
77302
  let judgePath = null;
76956
77303
  let decisionPath = filterPath;
76957
77304
  if (ctx.inputs.use_judge) {
76958
- judgePath = join18(root, "judge.json");
77305
+ judgePath = join17(root, "judge.json");
76959
77306
  const judgeCandidates = await Promise.all(shortlist.map(async (path) => ({ path, body: await readFile2(path, "utf8") })));
76960
77307
  const judgePrompt = renderJudgePrompt(ctx.inputs.prompt, filterPath, shortlistLimit, judgeCandidates);
76961
77308
  const judged = await ctx.task("judge", {
@@ -76971,7 +77318,7 @@ async function runGenerateAndFilter(ctx) {
76971
77318
  shortlist = judgedShortlist.length > 0 ? judgedShortlist : shortlist;
76972
77319
  decisionPath = judgePath;
76973
77320
  }
76974
- const finalPath = join18(root, "shortlist.md");
77321
+ const finalPath = join17(root, "shortlist.md");
76975
77322
  const finalShortlist = await ctx.task("final-shortlist", {
76976
77323
  prompt: renderFinalShortlistPrompt(ctx.inputs.prompt, decisionPath),
76977
77324
  context: "fresh",
@@ -77010,7 +77357,7 @@ var generate_and_filter_default = workflow({
77010
77357
  import { Type as Type15 } from "typebox";
77011
77358
 
77012
77359
  // dist/builtin/workflows/builtin/goal-runner.ts
77013
- import { join as join21 } from "node:path";
77360
+ import { join as join20 } from "node:path";
77014
77361
 
77015
77362
  // dist/builtin/workflows/builtin/progress-scoring.ts
77016
77363
  import { Type as Type12 } from "typebox";
@@ -77279,7 +77626,7 @@ var LEDGER_FILENAME = "goal-ledger.json";
77279
77626
 
77280
77627
  // dist/builtin/workflows/builtin/goal-artifacts.ts
77281
77628
  import { writeFile as writeFile6 } from "node:fs/promises";
77282
- import { join as join19 } from "node:path";
77629
+ import { join as join18 } from "node:path";
77283
77630
 
77284
77631
  // dist/builtin/workflows/builtin/review-convergence.ts
77285
77632
  var FINAL_ACTION_PATTERN = /\b(?:pr|pull[- ]request|merge[- ]request|review request|github pr|create pr)\b/iu;
@@ -77396,7 +77743,7 @@ function withoutTurn(value2) {
77396
77743
  return copy;
77397
77744
  }
77398
77745
  async function writeReviewArtifact(artifactDir, reviewer, decision, rawText, convergenceDecision) {
77399
- const artifactPath = join19(artifactDir, `review-${artifactSafeName(reviewer)}.json`);
77746
+ const artifactPath = join18(artifactDir, `review-${artifactSafeName(reviewer)}.json`);
77400
77747
  await writeFile6(artifactPath, `${JSON.stringify({ reviewer, decision, convergence_decision: convergenceDecision, raw_text: rawText }, null, 2)}
77401
77748
  `, { encoding: "utf8" });
77402
77749
  return artifactPath;
@@ -77405,7 +77752,7 @@ async function writeReviewRoundArtifact(artifactDir, reviews, consolidatedFindin
77405
77752
  reviewer: review.reviewer,
77406
77753
  findings: review.findings
77407
77754
  }))), reverification = []) {
77408
- const artifactPath = join19(artifactDir, "review-round-latest.json");
77755
+ const artifactPath = join18(artifactDir, "review-round-latest.json");
77409
77756
  const visibleReviews = reviews.map(withoutTurn);
77410
77757
  await writeFile6(artifactPath, `${JSON.stringify({ reviews: visibleReviews, consolidated_findings: consolidatedFindings, reverification }, null, 2)}
77411
77758
  `, { encoding: "utf8" });
@@ -77413,9 +77760,9 @@ async function writeReviewRoundArtifact(artifactDir, reviews, consolidatedFindin
77413
77760
  }
77414
77761
 
77415
77762
  // dist/builtin/workflows/builtin/goal-ledger.ts
77416
- import { randomUUID as randomUUID10 } from "node:crypto";
77763
+ import { randomUUID as randomUUID11 } from "node:crypto";
77417
77764
  import { readFile as readFile3, rename, rm as rm2, writeFile as writeFile7 } from "node:fs/promises";
77418
- import { dirname as dirname11, join as join20 } from "node:path";
77765
+ import { dirname as dirname11, join as join19 } from "node:path";
77419
77766
  import { isDeepStrictEqual } from "node:util";
77420
77767
 
77421
77768
  // dist/builtin/workflows/builtin/goal-reducer.ts
@@ -77653,7 +78000,7 @@ function modelVisibleLedger(ledger) {
77653
78000
  };
77654
78001
  }
77655
78002
  function goalLedgerStatePath(ledgerPath) {
77656
- return join20(dirname11(ledgerPath), LEDGER_STATE_FILENAME);
78003
+ return join19(dirname11(ledgerPath), LEDGER_STATE_FILENAME);
77657
78004
  }
77658
78005
  function appendLifecycleEvent(ledger, event, summary, turn = ledger.turns) {
77659
78006
  ledger.lifecycle.push({
@@ -77729,14 +78076,14 @@ function recoverLegacyExecutionInterruption(ledger) {
77729
78076
  return true;
77730
78077
  }
77731
78078
  async function createGoalLedger(objective, acceptanceCriteria, artifactDir) {
77732
- const ledgerPath = join20(artifactDir, LEDGER_FILENAME);
78079
+ const ledgerPath = join19(artifactDir, LEDGER_FILENAME);
77733
78080
  const existing = await readExistingGoalLedger(ledgerPath);
77734
78081
  if (existing !== undefined) {
77735
78082
  if (recoverLegacyExecutionInterruption(existing))
77736
78083
  await writeGoalLedger(ledgerPath, existing);
77737
78084
  return { ledger: existing, ledgerPath, artifactDir };
77738
78085
  }
77739
- const goalId = randomUUID10();
78086
+ const goalId = randomUUID11();
77740
78087
  const now = new Date().toISOString();
77741
78088
  const ledger = {
77742
78089
  goal_id: goalId,
@@ -77765,7 +78112,7 @@ async function writeGoalLedger(ledgerPath, ledger) {
77765
78112
  const stateContents = `${JSON.stringify(ledger, null, 2)}
77766
78113
  `;
77767
78114
  const statePath = goalLedgerStatePath(ledgerPath);
77768
- const pendingStatePath = `${statePath}.${randomUUID10()}.tmp`;
78115
+ const pendingStatePath = `${statePath}.${randomUUID11()}.tmp`;
77769
78116
  await writeFile7(pendingStatePath, stateContents, { encoding: "utf8" });
77770
78117
  try {
77771
78118
  await rename(pendingStatePath, statePath);
@@ -78228,8 +78575,8 @@ function positiveInteger(value2, fallback) {
78228
78575
  const floored = Math.floor(value2);
78229
78576
  return floored >= 1 ? floored : fallback;
78230
78577
  }
78231
- function forkContinuationOptions(sessionFile) {
78232
- return sessionFile === undefined || sessionFile.length === 0 ? {} : { context: "fork", forkFromSessionFile: sessionFile };
78578
+ function forkContinuationOptions(sessionId) {
78579
+ return sessionId === undefined ? {} : { context: "fork", forkFromSessionId: sessionId };
78233
78580
  }
78234
78581
  function normalizeBranchInput(value2, fallback) {
78235
78582
  const trimmed = value2?.trim();
@@ -78261,7 +78608,7 @@ async function runGoalWorkflow(ctx, options) {
78261
78608
  let latestReviews = [];
78262
78609
  let latestReviewArtifactPaths = [];
78263
78610
  let latestReviewReportPath;
78264
- let previousOrchestratorSessionFile;
78611
+ let previousOrchestratorSessionId;
78265
78612
  const recordedTurns = new Set(ledger.decisions.map((decision) => decision.turn));
78266
78613
  const lastRecordedTurn = Math.max(0, ...recordedTurns);
78267
78614
  for (let turn = 1;turn <= maxTurns && (ledger.status === "active" || turn <= lastRecordedTurn); turn += 1) {
@@ -78271,9 +78618,9 @@ async function runGoalWorkflow(ctx, options) {
78271
78618
  appendLifecycleEvent(ledger, "work_turn_started", "Orchestrator started.", turn);
78272
78619
  await writeGoalLedger(ledgerPath, ledger);
78273
78620
  }
78274
- const orchestratorReceiptPath = join21(artifactDir, "orchestrator-receipt.md");
78275
- const orchestratorForkOptions = forkContinuationOptions(previousOrchestratorSessionFile);
78276
- const orchestratorPrompt = orchestratorForkOptions.forkFromSessionFile === undefined ? renderGoalOrchestratorPrompt({
78621
+ const orchestratorReceiptPath = join20(artifactDir, "orchestrator-receipt.md");
78622
+ const orchestratorForkOptions = forkContinuationOptions(previousOrchestratorSessionId);
78623
+ const orchestratorPrompt = orchestratorForkOptions.forkFromSessionId === undefined ? renderGoalOrchestratorPrompt({
78277
78624
  ledger,
78278
78625
  ledgerPath,
78279
78626
  blockerThreshold,
@@ -78288,7 +78635,7 @@ async function runGoalWorkflow(ctx, options) {
78288
78635
  ...orchestratorModelConfig,
78289
78636
  ...orchestratorForkOptions
78290
78637
  });
78291
- previousOrchestratorSessionFile = orchestrator.sessionFile;
78638
+ previousOrchestratorSessionId = orchestrator.sessionId;
78292
78639
  if (!replayingRecordedTurn) {
78293
78640
  ledger.turns = turn;
78294
78641
  const receiptAlreadyRecorded = ledger.receipts.some((receipt) => receipt.turn === turn && receipt.artifact_path === orchestratorReceiptPath);
@@ -78342,7 +78689,7 @@ async function runGoalWorkflow(ctx, options) {
78342
78689
  const reviewerName = result.name ?? result.stageName;
78343
78690
  const normalizedReviewerName = reviewerName.replace(/-\d+$/u, "");
78344
78691
  const parsed = reviewerContractError === undefined ? parsedReviewDecisionFromResult(result, reviewerName) : { decision: reviewerErrorDecision(reviewerContractError.message), parsed: false, diagnostics: [reviewerContractError.message] };
78345
- const reviewArtifactPath = join21(artifactDir, `review-${artifactSafeName(normalizedReviewerName)}.json`);
78692
+ const reviewArtifactPath = join20(artifactDir, `review-${artifactSafeName(normalizedReviewerName)}.json`);
78346
78693
  const record = reviewDecisionToRecord({
78347
78694
  turn,
78348
78695
  reviewer: normalizedReviewerName,
@@ -78570,7 +78917,7 @@ import { Type as Type17 } from "typebox";
78570
78917
  import { spawnSync as spawnSync3 } from "node:child_process";
78571
78918
  import { mkdirSync as mkdirSync5 } from "node:fs";
78572
78919
  import { tmpdir, userInfo } from "node:os";
78573
- import { join as join22 } from "node:path";
78920
+ import { join as join21 } from "node:path";
78574
78921
  import { Type as Type16 } from "typebox";
78575
78922
  import { createChildProcessEnvironment as createChildProcessEnvironment3 } from "@bastani/atomic";
78576
78923
  var OUTPUT_TYPES = [
@@ -78627,32 +78974,32 @@ function tmpArtifactBase() {
78627
78974
  try {
78628
78975
  user = userInfo().username.replace(/[^A-Za-z0-9._-]/g, "_") || "default";
78629
78976
  } catch {}
78630
- return join22(tmpdir(), `open-claude-design-${user}`);
78977
+ return join21(tmpdir(), `open-claude-design-${user}`);
78631
78978
  }
78632
78979
  function prepareArtifactDir(cwd = process.cwd()) {
78633
78980
  const runId = `${new Date().toISOString().replace(/[:.]/g, "-")}-${Math.random().toString(36).slice(2, 8)}`;
78634
78981
  const tmpCandidates = [
78635
- join22(tmpArtifactBase(), runId),
78636
- join22(tmpdir(), "open-claude-design", runId)
78982
+ join21(tmpArtifactBase(), runId),
78983
+ join21(tmpdir(), "open-claude-design", runId)
78637
78984
  ];
78638
- const candidates = process.env.NODE_ENV === "test" ? tmpCandidates : [join22(cwd, "specs", "design", runId), ...tmpCandidates];
78985
+ const candidates = process.env.NODE_ENV === "test" ? tmpCandidates : [join21(cwd, "specs", "design", runId), ...tmpCandidates];
78639
78986
  for (const candidate of candidates) {
78640
78987
  try {
78641
78988
  mkdirSync5(candidate, { recursive: true });
78642
78989
  return {
78643
78990
  runId,
78644
78991
  artifactDir: candidate,
78645
- previewPath: join22(candidate, "preview.html"),
78646
- specPath: join22(candidate, "spec.html")
78992
+ previewPath: join21(candidate, "preview.html"),
78993
+ specPath: join21(candidate, "spec.html")
78647
78994
  };
78648
78995
  } catch {}
78649
78996
  }
78650
- const fallback = join22(tmpArtifactBase(), runId);
78997
+ const fallback = join21(tmpArtifactBase(), runId);
78651
78998
  return {
78652
78999
  runId,
78653
79000
  artifactDir: fallback,
78654
- previewPath: join22(fallback, "preview.html"),
78655
- specPath: join22(fallback, "spec.html")
79001
+ previewPath: join21(fallback, "preview.html"),
79002
+ specPath: join21(fallback, "spec.html")
78656
79003
  };
78657
79004
  }
78658
79005
  var HTML_PREVIEW_RULES = [
@@ -78970,7 +79317,7 @@ function buildLiveSessionStartPrompt(input) {
78970
79317
 
78971
79318
  // dist/builtin/workflows/builtin/open-claude-design-setup.ts
78972
79319
  import { mkdirSync as mkdirSync6, writeFileSync as writeFileSync3 } from "node:fs";
78973
- import { join as join23 } from "node:path";
79320
+ import { join as join22 } from "node:path";
78974
79321
  var GROUNDED_REPORTING5 = "Before reporting progress, audit each claim against a tool result from this session. Report only work you can point to evidence for; say so explicitly when something is unverified.";
78975
79322
  function renderDiscoveryContext(discovery) {
78976
79323
  return [
@@ -79046,10 +79393,10 @@ var NO_REFERENCES_BRIEF = "Reference discovery was skipped. Generate from the pr
79046
79393
  var DESIGN_CONTEXT_FILENAME = "design-context.md";
79047
79394
  var REFERENCES_BRIEF_FILENAME = "references.md";
79048
79395
  function designContextPath(artifactDir) {
79049
- return join23(artifactDir, DESIGN_CONTEXT_FILENAME);
79396
+ return join22(artifactDir, DESIGN_CONTEXT_FILENAME);
79050
79397
  }
79051
79398
  function referencesBriefPath(artifactDir) {
79052
- return join23(artifactDir, REFERENCES_BRIEF_FILENAME);
79399
+ return join22(artifactDir, REFERENCES_BRIEF_FILENAME);
79053
79400
  }
79054
79401
  function buildReferenceDiscoveryPrompt(args) {
79055
79402
  const siteList = REFERENCE_DESIGN_SITES.map((site, index) => `${index + 1}. ${site.name} — ${site.url}`).join(`
@@ -79075,8 +79422,8 @@ function buildReferenceDiscoveryPrompt(args) {
79075
79422
  [
79076
79423
  "Use the agent-browser skill to open each gallery; if `agent-browser` reports a missing browser executable, follow the bootstrap rules and retry once.",
79077
79424
  "From each gallery, choose 1-3 fitting designs and CLICK INTO each actual live or project-detail page; do not capture only the grid or thumbnail.",
79078
- `Capture motion across the entire page: start \`agent-browser record start ${join23(args.artifactDir, "ref-<site>-<n>.webm")}\`, scroll smoothly in small increments with waits (using repeated \`agent-browser scroll down 600\` or \`agent-browser mouse wheel 600\`) so animations fire and lazy content loads, then run \`agent-browser record stop\`.`,
79079
- `Also run \`agent-browser screenshot ${join23(args.artifactDir, "ref-<site>-<n>.png")} --full\`; this still is the minimum when video is unavailable.`,
79425
+ `Capture motion across the entire page: start \`agent-browser record start ${join22(args.artifactDir, "ref-<site>-<n>.webm")}\`, scroll smoothly in small increments with waits (using repeated \`agent-browser scroll down 600\` or \`agent-browser mouse wheel 600\`) so animations fire and lazy content loads, then run \`agent-browser record stop\`.`,
79426
+ `Also run \`agent-browser screenshot ${join22(args.artifactDir, "ref-<site>-<n>.png")} --full\`; this still is the minimum when video is unavailable.`,
79080
79427
  "Record the actual destination URL, title, and author. For each reference, cite observed layout, typography, color, spacing, and motion traits rather than inferred traits.",
79081
79428
  "Assess fit against DESIGN.md, PRODUCT.md, and the ds-* discovery evidence in the design-context file; prefer on-brand references and flag departures.",
79082
79429
  "Use ask_user_question to ask which reference direction they prefer, offering 2-4 strongest options plus `None of these fit`. If none fit, ask them to provide a reference image, screenshot, URL, or local file path and record the answer.",
@@ -79142,8 +79489,8 @@ function isUiUnavailableRejection(error) {
79142
79489
 
79143
79490
  // dist/builtin/workflows/builtin/open-claude-design-phases.ts
79144
79491
  var GROUNDED_REPORTING6 = "Before reporting progress, audit each claim against a tool result from this session. Report only work you can point to evidence for; say so explicitly when something is unverified.";
79145
- function forkContinuationOptions2(sessionFile) {
79146
- return sessionFile === undefined || sessionFile.length === 0 ? {} : { context: "fork", forkFromSessionFile: sessionFile };
79492
+ function forkContinuationOptions2(sessionId) {
79493
+ return sessionId === undefined ? {} : { context: "fork", forkFromSessionId: sessionId };
79147
79494
  }
79148
79495
  async function refineOpenClaudeDesign(options) {
79149
79496
  const { designContext, prompt, outputType, previewPath, previewFileUrl, browserBootstrapRules, designContextFile, referencesFile, designModelConfig, workflowCwd } = options;
@@ -79181,12 +79528,12 @@ async function refineOpenClaudeDesign(options) {
79181
79528
  }
79182
79529
  async function runLiveReviewSession(options) {
79183
79530
  const { designContext, round, reviewStageName, previewPath, previewFileUrl, browserBootstrapRules, designModelConfig, workflowCwd } = options;
79184
- let sessionFile;
79531
+ let sessionId;
79185
79532
  const start = await designContext.task(`${reviewStageName}-start`, {
79186
79533
  prompt: buildLiveSessionStartPrompt({ previewPath, previewFileUrl, browserBootstrapRules, round }),
79187
79534
  ...designModelConfig
79188
79535
  });
79189
- sessionFile = start.sessionFile;
79536
+ sessionId = start.sessionId;
79190
79537
  for (let index = 1;; index += 1) {
79191
79538
  const event = await designContext.tool(`live-poll-${round}-${index}`, { round, index }, async ({ signal }) => pollLiveEvent({ workflowCwd, signal }));
79192
79539
  if (event.type === "exit")
@@ -79199,9 +79546,9 @@ async function runLiveReviewSession(options) {
79199
79546
  const response = await designContext.task(`live-${event.type}-${round}-${index}`, {
79200
79547
  prompt: buildLiveEventPrompt({ event, previewPath }),
79201
79548
  ...designModelConfig,
79202
- ...forkContinuationOptions2(sessionFile)
79549
+ ...forkContinuationOptions2(sessionId)
79203
79550
  });
79204
- sessionFile = response.sessionFile ?? sessionFile;
79551
+ sessionId = response.sessionId ?? sessionId;
79205
79552
  const status = replyTokenFor(event);
79206
79553
  await designContext.tool(`live-reply-${round}-${index}`, { round, index, eventId: event.id, status }, async ({ signal }) => replyLiveEvent({ workflowCwd, event, status, signal }));
79207
79554
  }
@@ -79619,7 +79966,7 @@ import { Type as Type19 } from "typebox";
79619
79966
 
79620
79967
  // dist/builtin/workflows/builtin/loop-until-done-runner.ts
79621
79968
  import { mkdir as mkdir4, writeFile as writeFile8 } from "node:fs/promises";
79622
- import { join as join24 } from "node:path";
79969
+ import { join as join23 } from "node:path";
79623
79970
  import { Type as Type18 } from "typebox";
79624
79971
 
79625
79972
  // dist/builtin/workflows/builtin/loop-until-done-prompts.ts
@@ -79789,18 +80136,18 @@ async function writeLedger(path, task, maxIterations, status, entries) {
79789
80136
  }
79790
80137
  async function runLoopUntilDone(ctx) {
79791
80138
  const artifactDir = await stableArtifactRoot(ctx, "loop-until-done");
79792
- const iterationsDir = join24(artifactDir, "iterations");
79793
- const evaluationsDir = join24(artifactDir, "evaluations");
80139
+ const iterationsDir = join23(artifactDir, "iterations");
80140
+ const evaluationsDir = join23(artifactDir, "evaluations");
79794
80141
  await mkdir4(iterationsDir, { recursive: true });
79795
80142
  await mkdir4(evaluationsDir, { recursive: true });
79796
- const ledgerPath = join24(artifactDir, "progress-ledger.json");
80143
+ const ledgerPath = join23(artifactDir, "progress-ledger.json");
79797
80144
  const entries = [];
79798
80145
  const iterationArtifactPaths = [];
79799
80146
  const evaluationArtifactPaths = [];
79800
80147
  await writeLedger(ledgerPath, ctx.inputs.prompt, ctx.inputs.max_iterations, "active", entries);
79801
80148
  for (let iteration = 1;iteration <= ctx.inputs.max_iterations; iteration += 1) {
79802
- const iterationPath = join24(iterationsDir, `iteration-${iteration}.md`);
79803
- const evaluationPath = join24(evaluationsDir, `evaluation-${iteration}.json`);
80149
+ const iterationPath = join23(iterationsDir, `iteration-${iteration}.md`);
80150
+ const evaluationPath = join23(evaluationsDir, `evaluation-${iteration}.json`);
79804
80151
  iterationArtifactPaths.push(iterationPath);
79805
80152
  evaluationArtifactPaths.push(evaluationPath);
79806
80153
  await ctx.task(`iteration-${iteration}`, {
@@ -79849,7 +80196,7 @@ async function runLoopUntilDone(ctx) {
79849
80196
  await writeLedger(ledgerPath, ctx.inputs.prompt, ctx.inputs.max_iterations, decision.done ? "complete" : "active", entries);
79850
80197
  if (decision.done) {
79851
80198
  const report = progressReport(entries);
79852
- const resultPath = join24(artifactDir, "result.md");
80199
+ const resultPath = join23(artifactDir, "result.md");
79853
80200
  const final = await ctx.task("completion-summary", {
79854
80201
  prompt: renderCompletionPrompt({ task: ctx.inputs.prompt, ledgerPath, iterationPath }),
79855
80202
  context: "fresh",
@@ -79948,7 +80295,7 @@ import { Type as Type21 } from "typebox";
79948
80295
 
79949
80296
  // dist/builtin/workflows/builtin/ralph-core.ts
79950
80297
  import { mkdir as mkdir5, writeFile as writeFile9 } from "node:fs/promises";
79951
- import { dirname as dirname12, join as join25 } from "node:path";
80298
+ import { dirname as dirname12, join as join24 } from "node:path";
79952
80299
  import { Type as Type20 } from "typebox";
79953
80300
  // dist/builtin/workflows/builtin/ralph-review-gate.ts
79954
80301
  function reviewDecisionApproved(decision) {
@@ -80055,11 +80402,11 @@ function slugifyResearchTopic(prompt) {
80055
80402
  }
80056
80403
  function defaultResearchPath(prompt, now = new Date) {
80057
80404
  const date = now.toISOString().slice(0, 10);
80058
- return join25(DEFAULT_RESEARCH_DIR, `${date}-${slugifyResearchTopic(prompt)}.md`);
80405
+ return join24(DEFAULT_RESEARCH_DIR, `${date}-${slugifyResearchTopic(prompt)}.md`);
80059
80406
  }
80060
80407
  async function createImplementationNotesFile(prompt, runId) {
80061
80408
  const notesDir = await createWorkflowArtifactDirectory(runId);
80062
- const notesPath = join25(notesDir, IMPLEMENTATION_NOTES_FILENAME);
80409
+ const notesPath = join24(notesDir, IMPLEMENTATION_NOTES_FILENAME);
80063
80410
  const initialNotes = [
80064
80411
  "# Implementation Notes",
80065
80412
  "",
@@ -80080,7 +80427,7 @@ async function createImplementationNotesFile(prompt, runId) {
80080
80427
  }
80081
80428
  async function createQaEvidenceVideoPath(runId) {
80082
80429
  const qaDir = await createWorkflowArtifactDirectory(runId);
80083
- return join25(qaDir, QA_E2E_VIDEO_FILENAME);
80430
+ return join24(qaDir, QA_E2E_VIDEO_FILENAME);
80084
80431
  }
80085
80432
  function renderQaE2eVideoGuidance(qaVideoPath) {
80086
80433
  return [
@@ -80156,8 +80503,8 @@ async function writeJsonArtifact(path, content) {
80156
80503
  function compactReviewReport(path) {
80157
80504
  return path === undefined ? "No reviewer artifact was produced." : `Latest review round artifact: ${path}`;
80158
80505
  }
80159
- function forkContinuationOptions3(sessionFile) {
80160
- return sessionFile === undefined || sessionFile.length === 0 ? {} : { context: "fork", forkFromSessionFile: sessionFile };
80506
+ function forkContinuationOptions3(sessionId) {
80507
+ return sessionId === undefined ? {} : { context: "fork", forkFromSessionId: sessionId };
80161
80508
  }
80162
80509
  function renderResearchPromptRefinementPrompt(args) {
80163
80510
  return taggedPrompt4([
@@ -80216,7 +80563,7 @@ function renderResearchPrompt(args) {
80216
80563
 
80217
80564
  // dist/builtin/workflows/builtin/ralph-runner.ts
80218
80565
  import { existsSync as existsSync6 } from "node:fs";
80219
- import { join as join26, resolve as resolve13 } from "node:path";
80566
+ import { join as join25, resolve as resolve13 } from "node:path";
80220
80567
 
80221
80568
  // dist/builtin/workflows/builtin/ralph-reviewer-prompt.ts
80222
80569
  function renderRalphReviewerPrompt(args) {
@@ -80429,15 +80776,15 @@ async function runRalphWorkflow(ctx, options) {
80429
80776
  const artifactDir = await createWorkflowArtifactDirectory(runId);
80430
80777
  let approved = false;
80431
80778
  let iterationsCompleted = 0;
80432
- let previousResearchPromptRefinementSessionFile;
80779
+ let previousResearchPromptRefinementSessionId;
80433
80780
  const convergenceEntries = [];
80434
- let previousResearchSessionFile;
80435
- let previousOrchestratorSessionFile;
80781
+ let previousResearchSessionId;
80782
+ let previousOrchestratorSessionId;
80436
80783
  for (let iteration = 1;iteration <= maxLoops; iteration += 1) {
80437
80784
  iterationsCompleted = iteration;
80438
- const researchPromptRefinementForkOptions = forkContinuationOptions3(previousResearchPromptRefinementSessionFile);
80785
+ const researchPromptRefinementForkOptions = forkContinuationOptions3(previousResearchPromptRefinementSessionId);
80439
80786
  const researchPromptRefinement = await ctx.task(`research-prompt-refinement-${iteration}`, {
80440
- prompt: researchPromptRefinementForkOptions.forkFromSessionFile === undefined ? renderResearchPromptRefinementPrompt({
80787
+ prompt: researchPromptRefinementForkOptions.forkFromSessionId === undefined ? renderResearchPromptRefinementPrompt({
80441
80788
  request: workflowPrompt,
80442
80789
  acceptanceCriteria,
80443
80790
  workflowCwdContext,
@@ -80447,11 +80794,11 @@ async function runRalphWorkflow(ctx, options) {
80447
80794
  ...promptEngineerModelConfig,
80448
80795
  ...researchPromptRefinementForkOptions
80449
80796
  });
80450
- previousResearchPromptRefinementSessionFile = researchPromptRefinement.sessionFile;
80797
+ previousResearchPromptRefinementSessionId = researchPromptRefinement.sessionId;
80451
80798
  finalPlan = researchPromptRefinement.text;
80452
- const researchForkOptions = forkContinuationOptions3(previousResearchSessionFile);
80799
+ const researchForkOptions = forkContinuationOptions3(previousResearchSessionId);
80453
80800
  const research = await ctx.task(`research-${iteration}`, {
80454
- prompt: researchForkOptions.forkFromSessionFile === undefined ? renderResearchPrompt({
80801
+ prompt: researchForkOptions.forkFromSessionId === undefined ? renderResearchPrompt({
80455
80802
  transformedResearchQuestion: researchPromptRefinement.text,
80456
80803
  prompt: workflowPrompt,
80457
80804
  acceptanceCriteria,
@@ -80467,14 +80814,14 @@ async function runRalphWorkflow(ctx, options) {
80467
80814
  ...researchModelConfig,
80468
80815
  ...researchForkOptions
80469
80816
  });
80470
- previousResearchSessionFile = research.sessionFile;
80817
+ previousResearchSessionId = research.sessionId;
80471
80818
  finalResearch = research.text || `Research artifact: ${workflowResearchPath}`;
80472
80819
  const researchPath = workflowResearchPath;
80473
80820
  finalResearchPath = researchPath;
80474
80821
  finalPlanPath = researchPath;
80475
- const orchestratorReportPath = join26(artifactDir, "orchestrator-report.md");
80476
- const orchestratorForkOptions = forkContinuationOptions3(previousOrchestratorSessionFile);
80477
- const orchestratorPrompt = orchestratorForkOptions.forkFromSessionFile === undefined ? taggedPrompt4([
80822
+ const orchestratorReportPath = join25(artifactDir, "orchestrator-report.md");
80823
+ const orchestratorForkOptions = forkContinuationOptions3(previousOrchestratorSessionId);
80824
+ const orchestratorPrompt = orchestratorForkOptions.forkFromSessionId === undefined ? taggedPrompt4([
80478
80825
  ["acceptance_criteria", keepContext(acceptanceCriteria)],
80479
80826
  ["literal_contract", LITERAL_OBJECTIVE_CONTRACT],
80480
80827
  ["acceptance_matrix", ACCEPTANCE_MATRIX_CONTRACT],
@@ -80553,7 +80900,7 @@ Read it before implementation or delegation because it is the primary current im
80553
80900
  ...orchestratorModelConfig2,
80554
80901
  ...orchestratorForkOptions
80555
80902
  });
80556
- previousOrchestratorSessionFile = orchestrator.sessionFile;
80903
+ previousOrchestratorSessionId = orchestrator.sessionId;
80557
80904
  finalResult = orchestrator.text || `Orchestrator report artifact: ${orchestratorReportPath}`;
80558
80905
  const reviewPrompt = renderRalphReviewerPrompt({
80559
80906
  workflowPrompt,
@@ -80608,7 +80955,7 @@ Read it before implementation or delegation because it is the primary current im
80608
80955
  diagnostics: parsed.diagnostics,
80609
80956
  allowFinalActionRemaining: createPr
80610
80957
  });
80611
- const artifactPath = join26(artifactDir, `review-${artifactSafeName2(reviewer)}.json`);
80958
+ const artifactPath = join25(artifactDir, `review-${artifactSafeName2(reviewer)}.json`);
80612
80959
  await writeJsonArtifact(artifactPath, {
80613
80960
  reviewer,
80614
80961
  decision: parsed.decision,
@@ -80664,7 +81011,7 @@ Read it before implementation or delegation because it is the primary current im
80664
81011
  usage: fold_usage([orchestrator, ...reviews, ...reverifyResults])
80665
81012
  }));
80666
81013
  }
80667
- latestReviewReportPath = await writeJsonArtifact(join26(artifactDir, "review-round-latest.json"), {
81014
+ latestReviewReportPath = await writeJsonArtifact(join25(artifactDir, "review-round-latest.json"), {
80668
81015
  convergence_decision: roundConvergenceDecision,
80669
81016
  convergence: convergenceEntries,
80670
81017
  consolidated_findings: reverified.batch,
@@ -80845,7 +81192,7 @@ import { Type as Type23 } from "typebox";
80845
81192
 
80846
81193
  // dist/builtin/workflows/builtin/tournament-runner.ts
80847
81194
  import { mkdir as mkdir6, readFile as readFile4, writeFile as writeFile10 } from "node:fs/promises";
80848
- import { join as join27, isAbsolute as isAbsolute11, relative as relative5, resolve as resolve14 } from "node:path";
81195
+ import { join as join26, isAbsolute as isAbsolute11, relative as relative5, resolve as resolve14 } from "node:path";
80849
81196
  import { Type as Type22 } from "typebox";
80850
81197
 
80851
81198
  // dist/builtin/workflows/builtin/selection-math.ts
@@ -81112,16 +81459,16 @@ function combineUsage(totals) {
81112
81459
  }
81113
81460
  async function runTournament(ctx) {
81114
81461
  const artifactDir = await stableArtifactRoot(ctx, "tournament");
81115
- const attemptsDir = join27(artifactDir, "attempts");
81462
+ const attemptsDir = join26(artifactDir, "attempts");
81116
81463
  const numAttempts = ctx.inputs.num_attempts ?? 4;
81117
81464
  const maxConcurrency = ctx.inputs.max_concurrency ?? 4;
81118
81465
  const nEvaluations = ctx.inputs.n_evaluations ?? 2;
81119
81466
  const pivotCount = ctx.inputs.pivots ?? 1;
81120
81467
  const seed = ctx.inputs.seed ?? 0;
81121
- const judgesDir = join27(artifactDir, "judges");
81468
+ const judgesDir = join26(artifactDir, "judges");
81122
81469
  await mkdir6(attemptsDir, { recursive: true });
81123
81470
  await mkdir6(judgesDir, { recursive: true });
81124
- const attemptArtifactPaths = Array.from({ length: numAttempts }, (_, index) => join27(attemptsDir, `attempt-${index + 1}.md`));
81471
+ const attemptArtifactPaths = Array.from({ length: numAttempts }, (_, index) => join26(attemptsDir, `attempt-${index + 1}.md`));
81125
81472
  const models = ctx.inputs.models;
81126
81473
  const attemptResults = await ctx.parallel(attemptArtifactPaths.map((path, index) => ({
81127
81474
  name: `attempt-${index + 1}`,
@@ -81286,7 +81633,7 @@ The previous report was invalid. Return the required JSON schema exactly once.`,
81286
81633
  const outputRanking = ranking.map(({ label, meanPreference }) => ({ label, meanPreference }));
81287
81634
  const budgetPivots = Math.min(pivotCount, entrants.length);
81288
81635
  const comparisonBudget = (entrants.length + budgetPivots * (entrants.length - budgetPivots) + budgetPivots * (budgetPivots - 1) / 2) * criteria.length * nEvaluations;
81289
- const comparisonPath = join27(artifactDir, "comparisons.json");
81636
+ const comparisonPath = join26(artifactDir, "comparisons.json");
81290
81637
  const assignment = modelAssignment(entrants, models);
81291
81638
  const phaseUsage = {
81292
81639
  attempts: fold_usage(attemptResults),
@@ -81322,7 +81669,7 @@ The previous report was invalid. Return the required JSON schema exactly once.`,
81322
81669
  await writeLedger(fold_usage([]));
81323
81670
  const winner = ranking[0];
81324
81671
  const winnerEntrant = entrants[winner.index];
81325
- const resultPath = join27(artifactDir, "winner.md");
81672
+ const resultPath = join26(artifactDir, "winner.md");
81326
81673
  const reducer = await ctx.task("comparisons-reducer", {
81327
81674
  prompt: renderComparisonsReducerPrompt({
81328
81675
  task: ctx.inputs.prompt,
@@ -81500,7 +81847,6 @@ __export(exports_sdk_surface, {
81500
81847
  JOURNAL_TABLES: () => JOURNAL_TABLES,
81501
81848
  JournalCasConflictError: () => JournalCasConflictError,
81502
81849
  JournalClosedError: () => JournalClosedError,
81503
- JournalConfigurationError: () => JournalConfigurationError,
81504
81850
  JournalCounterRangeError: () => JournalCounterRangeError,
81505
81851
  JournalError: () => JournalError,
81506
81852
  JournalInvalidTextError: () => JournalInvalidTextError,
@@ -82026,6 +82372,30 @@ function registerRunJournalConformance(runner, name, open, observeRead) {
82026
82372
  });
82027
82373
  });
82028
82374
  }
82375
+ // dist/builtin/workflows/src/durable/journal/sqlite-run-journal.ts
82376
+ import { dirname as dirname13, join as join27 } from "node:path";
82377
+ import { getAgentDir as getAgentDir5, openNodeSqliteDatabase, validateStoragePrefix, wrapNodeSqliteDatabase } from "@bastani/atomic";
82378
+ function workflowJournalPath() {
82379
+ const override = process.env.ATOMIC_WORKFLOW_JOURNAL_PATH;
82380
+ return override !== undefined && override.length > 0 ? override : join27(dirname13(getAgentDir5()), "workflows", "journal.sqlite");
82381
+ }
82382
+ async function openSqlRunJournal(source = workflowJournalPath(), options = {}) {
82383
+ validateStoragePrefix(options.prefix);
82384
+ const database = typeof source === "string" ? await openNodeSqliteDatabase(source) : wrapNodeSqliteDatabase(source);
82385
+ try {
82386
+ const journal = await SqlRunJournal.open(database, options);
82387
+ const close = journal.close.bind(journal);
82388
+ let closing;
82389
+ journal.close = () => {
82390
+ closing ??= close().then(() => database.close());
82391
+ return closing;
82392
+ };
82393
+ return journal;
82394
+ } catch (error) {
82395
+ await database.close();
82396
+ throw error;
82397
+ }
82398
+ }
82029
82399
  // dist/builtin/workflows/src/extension/wiring.ts
82030
82400
  import { join as join28 } from "node:path";
82031
82401
  import {
@@ -82409,7 +82779,7 @@ function makeWorkflowStageOrchestrationContext(meta, pi) {
82409
82779
  const sendMessage = pi.sendMessage;
82410
82780
  if (!sendMessage)
82411
82781
  throw new Error("atomic-workflows: main-chat late-message route is unavailable");
82412
- return routeThroughStaleContextGuard(() => sendMessage(message, options));
82782
+ return routeThroughStaleContextGuard(() => outsideWorkflowExecutions(() => sendMessage(message, options)));
82413
82783
  },
82414
82784
  routeMessages(messages, options) {
82415
82785
  const intercomRoute = emitLateIntercomRoute(pi, meta, messages, options, true);
@@ -82417,15 +82787,15 @@ function makeWorkflowStageOrchestrationContext(meta, pi) {
82417
82787
  return intercomRoute;
82418
82788
  const sendMessages = pi.sendMessages;
82419
82789
  if (sendMessages)
82420
- return routeThroughStaleContextGuard(() => sendMessages(messages, options));
82790
+ return routeThroughStaleContextGuard(() => outsideWorkflowExecutions(() => sendMessages(messages, options)));
82421
82791
  const sendMessage = pi.sendMessage;
82422
82792
  if (!sendMessage)
82423
82793
  throw new Error("atomic-workflows: main-chat late-message route is unavailable");
82424
- return (async () => {
82794
+ return outsideWorkflowExecutions(async () => {
82425
82795
  for (const [index, message] of messages.entries()) {
82426
82796
  await sendMessage(message, index === 0 ? options : { deliverAs: "followUp" });
82427
82797
  }
82428
- })();
82798
+ });
82429
82799
  }
82430
82800
  }
82431
82801
  };
@@ -82892,7 +83262,7 @@ function workflowAgentDirs2(options) {
82892
83262
  const homeDir = options.homeDir;
82893
83263
  return [join30(homeDir, CONFIG_DIR_NAME3, "agent")];
82894
83264
  }
82895
- return [getAgentDir5()];
83265
+ return [getAgentDir6()];
82896
83266
  }
82897
83267
  function validateConfig2(config) {
82898
83268
  if (config === null || typeof config !== "object") {
@@ -83239,7 +83609,7 @@ async function discardUnadmittedRun(runId, activeStore) {
83239
83609
  activeStore.removeRun(runId);
83240
83610
  const handle = backend.getWorkflow(runId);
83241
83611
  if (handle?.status === "running") {
83242
- await backend.setWorkflowStatus(runId, "failed", handle.pendingPrompts, false);
83612
+ await backend.commitWorkflowStatus(runId, "failed", handle.pendingPrompts, false);
83243
83613
  }
83244
83614
  const deleted = await backend.deleteWorkflowIfInactive(runId);
83245
83615
  if (!deleted.ok && deleted.reason !== "not_found") {
@@ -83612,23 +83982,24 @@ function createDurableResumeRuntime(deps) {
83612
83982
  try {
83613
83983
  await backend.hydrateResumableWorkflows();
83614
83984
  await hydrateStoredWorkflowCandidates(backend);
83615
- return listOpenableCompletedWorkflows(backend);
83985
+ return await listOpenableCompletedWorkflows(backend, deps.adapters?.sessionStore);
83616
83986
  } finally {
83617
83987
  purgeSuppressedWorkflowRuns(backend, deps.store, deps.toolControlRegistry);
83618
83988
  }
83619
83989
  });
83620
83990
  },
83621
- openCompletedDurableWorkflow(workflowId, catalog) {
83991
+ async openCompletedDurableWorkflow(workflowId, catalog) {
83622
83992
  const finish = workflowObservationRuntime(deps.store).beginRecovery();
83623
83993
  try {
83624
83994
  const backend = selectedBackend(workflowId);
83625
83995
  const entry = resolveCatalogEntry(workflowId, catalog ?? []);
83626
83996
  const handle = backend.getWorkflow(entry?.workflowId ?? workflowId);
83627
- return openCompletedDurableWorkflow(workflowId, {
83997
+ return await openCompletedDurableWorkflow(workflowId, {
83628
83998
  durableBackend: backend,
83629
83999
  store: deps.store,
83630
84000
  stageControlRegistry: deps.stageControlRegistry,
83631
84001
  adapters: deps.adapters,
84002
+ sessionStore: deps.adapters?.sessionStore,
83632
84003
  cwd: handle?.workflowCwd ?? handle?.invocationCwd ?? deps.runtimeCwd,
83633
84004
  defaultSessionDir: deps.resolveDefaultStageSessionDir?.(),
83634
84005
  beforeRestore: deps.beforeRestoreCompleted
@@ -83669,7 +84040,11 @@ function createExtensionRuntime(opts = {}) {
83669
84040
  const presetBackend = opts.journal === undefined ? availableStoreDurableBackendOverride(activeStore) : undefined;
83670
84041
  const backendRef = { current: presetBackend };
83671
84042
  let ready;
83672
- const ensureReady = () => ready ??= (presetBackend === undefined ? initializeDurableBackend({ cwd: runtimeCwd, journal: opts.journal }) : Promise.resolve(presetBackend)).then((backend) => {
84043
+ const ensureReady = () => ready ??= (presetBackend === undefined ? initializeDurableBackend({
84044
+ cwd: runtimeCwd,
84045
+ journal: opts.journal,
84046
+ projectTrusted: opts.isProjectTrusted?.()
84047
+ }) : Promise.resolve(presetBackend)).then((backend) => {
83673
84048
  backendRef.current = backend;
83674
84049
  bindStoreDurableBackend(activeStore, backend);
83675
84050
  return backend;
@@ -83871,7 +84246,7 @@ function createExtensionRuntime(opts = {}) {
83871
84246
 
83872
84247
  // dist/builtin/workflows/src/extension/status-writer.ts
83873
84248
  import { mkdir as mkdir7, rename as rename2, writeFile as writeFile11 } from "node:fs/promises";
83874
- import { dirname as dirname13, join as join31 } from "node:path";
84249
+ import { dirname as dirname14, join as join31 } from "node:path";
83875
84250
  import { CONFIG_DIR_NAME as CONFIG_DIR_NAME4 } from "@bastani/atomic";
83876
84251
  var DEFAULT_STATUS_SUBPATH = join31(CONFIG_DIR_NAME4, "workflows", "status.json");
83877
84252
  function resolveStatusFilePath(config, opts = {}) {
@@ -83881,7 +84256,7 @@ function resolveStatusFilePath(config, opts = {}) {
83881
84256
  return join31(root, DEFAULT_STATUS_SUBPATH);
83882
84257
  }
83883
84258
  async function atomicWriteJson(path, content) {
83884
- const dir = dirname13(path);
84259
+ const dir = dirname14(path);
83885
84260
  await mkdir7(dir, { recursive: true });
83886
84261
  const tmpPath = `${path}.tmp`;
83887
84262
  await writeFile11(tmpPath, content, "utf8");
@@ -84861,12 +85236,21 @@ function durableWorkflowHeartbeatAnchorStore(store) {
84861
85236
  function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
84862
85237
  const { resolveHostCwd, resolveLiveModelContext } = options;
84863
85238
  const { store, stageUiBroker, cancellationRegistry, jobs, stageControlRegistry, toolControlRegistry } = options.runState ?? currentWorkflowSessionRunState();
84864
- const scopedRunOptions = { store, jobs, stageControlRegistry, toolControlRegistry, stageUiBroker };
85239
+ let projectTrusted;
85240
+ const scopedRunOptions = {
85241
+ store,
85242
+ jobs,
85243
+ stageControlRegistry,
85244
+ toolControlRegistry,
85245
+ stageUiBroker,
85246
+ isProjectTrusted: () => projectTrusted ?? pi.getResourceLoaderInheritanceSnapshot?.()?.projectTrusted ?? true
85247
+ };
84865
85248
  let contextCwd;
84866
85249
  const resolveCwd = () => resolveHostCwd?.() ?? contextCwd ?? pi.sessionManager?.getCwd?.() ?? process.cwd();
84867
85250
  let detachHumanInput;
84868
85251
  pi.on?.("session_start", (_event, ctx) => {
84869
85252
  contextCwd = ctx?.cwd ?? ctx?.sessionManager?.getCwd?.();
85253
+ projectTrusted = ctx?.isProjectTrusted?.();
84870
85254
  detachHumanInput?.();
84871
85255
  detachHumanInput = ctx === undefined ? undefined : bindWorkflowHumanInput(store, ctx, stageUiBroker);
84872
85256
  if (ctx)
@@ -84922,7 +85306,7 @@ function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
84922
85306
  registerLifecycleNoticeRenderer({ rendererHost: pi, registerMessageRenderer });
84923
85307
  registerHilAnswerNoticeRenderer({ rendererHost: pi, registerMessageRenderer });
84924
85308
  registerWorkflowHeartbeatRenderer({ rendererHost: pi, registerMessageRenderer });
84925
- const sendWorkflowNotificationMessage = typeof pi.sendMessage === "function" ? (message, options) => pi.sendMessage(message, options) : undefined;
85309
+ const sendWorkflowNotificationMessage = typeof pi.sendMessage === "function" ? (message, options) => outsideWorkflowExecutions(() => pi.sendMessage(message, options)) : undefined;
84926
85310
  const reinstallLifecycleNotifications = () => {
84927
85311
  lifecycleNotificationsUnsubscribe?.();
84928
85312
  lifecycleNotificationsUnsubscribe = null;
@@ -85035,7 +85419,7 @@ function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
85035
85419
  prepareCompletedDurable() {
85036
85420
  return runtimeRef.current.prepareCompletedDurable?.() ?? Promise.resolve([]);
85037
85421
  },
85038
- openCompletedDurableWorkflow(workflowId, catalog) {
85422
+ async openCompletedDurableWorkflow(workflowId, catalog) {
85039
85423
  const open = runtimeRef.current.openCompletedDurableWorkflow;
85040
85424
  if (open === undefined) {
85041
85425
  return {
@@ -85048,8 +85432,9 @@ function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
85048
85432
  }
85049
85433
  };
85050
85434
  function runtimeForContext(ctx) {
85435
+ const contextTrusted = ctx?.isProjectTrusted?.();
85051
85436
  const models = workflowModelCatalogFromContext(ctx, resolveLiveModelContext);
85052
- if (models === undefined && !ctx?.generateWorkflowSummary)
85437
+ if (models === undefined && !ctx?.generateWorkflowSummary && contextTrusted === undefined)
85053
85438
  return runtimeProxy;
85054
85439
  return createExtensionRuntime({
85055
85440
  registry: runtimeRef.current.registry,
@@ -85058,6 +85443,7 @@ function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
85058
85443
  adapters,
85059
85444
  cancellation: cancellationRegistry,
85060
85445
  ...scopedRunOptions,
85446
+ isProjectTrusted: () => contextTrusted ?? scopedRunOptions.isProjectTrusted(),
85061
85447
  persistence: persistenceRef.current,
85062
85448
  mcp: mcpPort,
85063
85449
  config: runtimeConfigRef.current,
@@ -85306,6 +85692,7 @@ function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
85306
85692
  reinstallWorkflowHeartbeatScheduler();
85307
85693
  },
85308
85694
  updateHostStageSessionDir(sessionManager) {
85695
+ adapters.sessionStore = sessionManager?.getSessionStore?.();
85309
85696
  try {
85310
85697
  hostStageSessionDir.current = sessionManager?.usesDefaultSessionDir?.() === false ? sessionManager.getSessionDir?.() : undefined;
85311
85698
  } catch {
@@ -86036,12 +86423,13 @@ function postMortemDepsForRun(runId, deps) {
86036
86423
  return {
86037
86424
  registry: deps.stageControlRegistry ?? stageControlRegistry,
86038
86425
  adapters: deps.adapters,
86426
+ sessionStore: deps.adapters.sessionStore,
86039
86427
  cwd: resolveStageCwd(runId, deps.store ?? store),
86040
86428
  defaultSessionDir: deps.resolveDefaultStageSessionDir()
86041
86429
  };
86042
86430
  }
86043
86431
  function createPostMortemHandleResolver(deps) {
86044
- return (runId, stageId) => {
86432
+ return async (runId, stageId) => {
86045
86433
  const run = readGraphStoreSnapshot(deps.store ?? store).runs.find((candidate) => candidate.id === runId);
86046
86434
  const stage = run?.stages.find((candidate) => candidate.id === stageId);
86047
86435
  if (stage === undefined)
@@ -90155,9 +90543,10 @@ function registerWorkflowMessageRenderers(pi) {
90155
90543
  registerInlineFormRenderer(pi, deriveGraphTheme({}));
90156
90544
  registerChatSurfaceRenderer(pi, deriveGraphTheme({}));
90157
90545
  }
90158
- function buildWorkflowOverlay(pi, owner, resolvePostMortemHandle) {
90546
+ function buildWorkflowOverlay(pi, owner, resolvePostMortemHandle, resolveSessionStore) {
90159
90547
  return buildGraphOverlayAdapter(pi, owner.store, {
90160
90548
  resolvePostMortemHandle,
90549
+ resolveSessionStore,
90161
90550
  stageControlRegistry: owner.stageControlRegistry,
90162
90551
  stageUiBroker: owner.stageUiBroker
90163
90552
  });
@@ -90236,7 +90625,7 @@ function factory(pi) {
90236
90625
  registerExtensionContextRetirementEffect3(ctx, disposeCompletedRoutes);
90237
90626
  registerExtensionContextRetirementEffect3(ctx, disposePendingRoutes);
90238
90627
  });
90239
- const overlay = buildWorkflowOverlay(pi, owner, postMortemHandleResolver);
90628
+ const overlay = buildWorkflowOverlay(pi, owner, postMortemHandleResolver, () => adapters.sessionStore);
90240
90629
  const workflowCommands = new Map;
90241
90630
  const storeWidgetRef = { current: null };
90242
90631
  const intercomControlRef = { current: null };