@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
@@ -218,6 +218,7 @@ import assert from "node:assert/strict";
218
218
  // dist/builtin/workflows/src/durable/journal/types.ts
219
219
  import { StorageSchemaVersionError } from "@bastani/atomic/storage";
220
220
  import { StorageUnavailableError } from "@bastani/atomic/storage";
221
+ import { RUN_EVENT_TYPES } from "@bastani/atomic/storage";
221
222
  var JOURNAL_SCHEMA_VERSION = 1;
222
223
  var JOURNAL_PAYLOAD_ENCODING = "json-text";
223
224
  var JOURNAL_TABLES = { meta: "meta", runs: "runs", events: "events", leases: "leases" };
@@ -239,20 +240,6 @@ var JOURNAL_COLUMNS = {
239
240
  renewedAt: "renewed_at"
240
241
  };
241
242
  var JOURNAL_LEASE = { initialEpoch: 1, epochIncrement: 1, unheld: null, absentEpoch: 0 };
242
- var RUN_EVENT_TYPES = {
243
- runStarted: "RunStarted",
244
- runFinished: "RunFinished",
245
- statusChanged: "StatusChanged",
246
- checkpointRecorded: "CheckpointRecorded",
247
- promptAsked: "PromptAsked",
248
- promptReleased: "PromptReleased",
249
- controlRequested: "ControlRequested",
250
- messageQueued: "MessageQueued",
251
- messageDelivered: "MessageDelivered",
252
- messageSettled: "MessageSettled",
253
- timerScheduled: "TimerScheduled",
254
- summaryRecorded: "SummaryRecorded"
255
- };
256
243
 
257
244
  class JournalError extends Error {
258
245
  }
@@ -264,19 +251,6 @@ class JournalClosedError extends JournalError {
264
251
  }
265
252
  }
266
253
 
267
- class JournalConfigurationError extends JournalError {
268
- source;
269
- setting;
270
- reason;
271
- constructor(source, setting, reason) {
272
- super(`Invalid journal configuration at ${source}.${setting}: ${reason}`);
273
- this.name = "JournalConfigurationError";
274
- this.source = source;
275
- this.setting = setting;
276
- this.reason = reason;
277
- }
278
- }
279
-
280
254
  class JournalInvalidTextError extends JournalError {
281
255
  field;
282
256
  reason;
@@ -849,13 +823,6 @@ function registerRunJournalConformance(runner, name, open, observeRead) {
849
823
  }
850
824
  // dist/builtin/workflows/src/durable/journal/internal.ts
851
825
  var JOURNAL_READ_PAGE_SIZE = 256;
852
- var synchronousJournals = new WeakMap;
853
- function registerSynchronousJournal(journal, synchronous) {
854
- synchronousJournals.set(journal, synchronous);
855
- }
856
- function synchronousJournal(journal) {
857
- return synchronousJournals.get(journal);
858
- }
859
826
 
860
827
  // dist/builtin/workflows/src/durable/journal/lease-expiry.ts
861
828
  function isWorkflowLeaseExpired(renewedAt, staleAfterMs, now = Date.now()) {
@@ -896,33 +863,22 @@ class MemoryRunJournal {
896
863
  runs = new Map;
897
864
  leases = new Map;
898
865
  closed = false;
899
- constructor() {
900
- registerSynchronousJournal(this, {
901
- createRunSync: this.createRunSync.bind(this),
902
- listRunsSync: this.listRunsSync.bind(this),
903
- takeoverExpiredSync: this.takeoverExpiredSync.bind(this),
904
- leaseStateSync: this.leaseStateSync.bind(this),
905
- renewSync: this.renewSync.bind(this),
906
- releaseSync: this.releaseSync.bind(this),
907
- appendSync: this.appendSync.bind(this),
908
- readEntries: this.readEntries.bind(this),
909
- deleteRunSync: this.deleteRunSync.bind(this)
910
- });
866
+ storage;
867
+ constructor(storage) {
868
+ this.storage = storage === undefined ? undefined : { ...storage };
911
869
  }
912
870
  ensureOpen() {
913
871
  if (this.closed)
914
872
  throw new StorageUnavailableError({ adapter: "memory", location: ":memory:" }, new JournalClosedError);
915
873
  }
916
874
  async createRun(header) {
917
- return this.createRunSync(header);
918
- }
919
- createRunSync(header) {
920
875
  this.ensureOpen();
921
876
  validateText("runId", header.runId);
922
877
  validateText("name", header.name);
923
878
  validateText("cwd", header.cwd);
924
879
  validateText("status", header.status);
925
- const stored = storageBoundary(":memory:", () => JSON.parse(serializeJson(header)));
880
+ const record = this.storage === undefined ? header : { ...header, storage: this.storage };
881
+ const stored = storageBoundary(":memory:", () => JSON.parse(serializeJson(record)));
926
882
  if (this.runs.has(header.runId))
927
883
  return "exists";
928
884
  this.runs.set(header.runId, { header: stored, entries: [] });
@@ -935,9 +891,6 @@ class MemoryRunJournal {
935
891
  return run ? JSON.parse(serializeJson(run.header)) : undefined;
936
892
  }
937
893
  async listRuns(filter) {
938
- return this.listRunsSync(filter);
939
- }
940
- listRunsSync(filter) {
941
894
  this.ensureOpen();
942
895
  if (filter?.cwd !== undefined)
943
896
  validateText("cwd", filter.cwd);
@@ -957,9 +910,6 @@ class MemoryRunJournal {
957
910
  return { status: "acquired", lease: { runId, holderId, epoch } };
958
911
  }
959
912
  async acquire(runId, holderId) {
960
- return this.acquireSync(runId, holderId);
961
- }
962
- acquireSync(runId, holderId) {
963
913
  this.ensureOpen();
964
914
  validateText("runId", runId);
965
915
  validateText("holderId", holderId);
@@ -987,24 +937,18 @@ class MemoryRunJournal {
987
937
  return this.grant(runId, holderId);
988
938
  }
989
939
  async takeoverExpired(runId, holderId, staleAfterMs) {
990
- return this.takeoverExpiredSync(runId, holderId, staleAfterMs);
991
- }
992
- takeoverExpiredSync(runId, holderId, staleAfterMs) {
993
940
  this.ensureOpen();
994
941
  validateText("runId", runId);
995
942
  validateText("holderId", holderId);
996
943
  this.requireRun(runId);
997
- const current = this.leaseStateSync(runId);
944
+ const current = this.leases.get(runId);
998
945
  if (current?.holderId === holderId)
999
- return this.acquireSync(runId, holderId);
1000
- if (current !== undefined && !isWorkflowLeaseExpired(0, staleAfterMs, current.ageMs))
946
+ return { status: "acquired", lease: { runId, holderId, epoch: current.epoch } };
947
+ if (current?.holderId !== undefined && current.holderId !== null && !isWorkflowLeaseExpired(0, staleAfterMs, Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Date.now() - current.renewedAt))))
1001
948
  return { status: "held", holderId: current.holderId, epoch: current.epoch };
1002
949
  return this.grant(runId, holderId);
1003
950
  }
1004
951
  async leaseState(runId) {
1005
- return this.leaseStateSync(runId);
1006
- }
1007
- leaseStateSync(runId) {
1008
952
  this.ensureOpen();
1009
953
  validateText("runId", runId);
1010
954
  const current = this.leases.get(runId);
@@ -1023,9 +967,6 @@ class MemoryRunJournal {
1023
967
  throw new StaleLeaseError(lease.runId, lease.epoch, current?.epoch ?? JOURNAL_LEASE.absentEpoch);
1024
968
  }
1025
969
  async renew(lease) {
1026
- this.renewSync(lease);
1027
- }
1028
- renewSync(lease) {
1029
970
  this.ensureOpen();
1030
971
  validateText("runId", lease.runId);
1031
972
  validateText("holderId", lease.holderId);
@@ -1033,9 +974,6 @@ class MemoryRunJournal {
1033
974
  this.leases.set(lease.runId, { holderId: lease.holderId, epoch: lease.epoch, renewedAt: Date.now() });
1034
975
  }
1035
976
  async release(lease) {
1036
- this.releaseSync(lease);
1037
- }
1038
- releaseSync(lease) {
1039
977
  this.ensureOpen();
1040
978
  validateText("runId", lease.runId);
1041
979
  validateText("holderId", lease.holderId);
@@ -1043,9 +981,6 @@ class MemoryRunJournal {
1043
981
  this.leases.set(lease.runId, { holderId: JOURNAL_LEASE.unheld, epoch: lease.epoch, renewedAt: Date.now() });
1044
982
  }
1045
983
  async append(lease, event, options) {
1046
- return this.appendSync(lease, event, options);
1047
- }
1048
- appendSync(lease, event, options) {
1049
984
  this.ensureOpen();
1050
985
  validateText("runId", lease.runId);
1051
986
  validateText("holderId", lease.holderId);
@@ -1107,11 +1042,6 @@ class MemoryRunJournal {
1107
1042
  const start = Math.max(0, Math.ceil(fromSeq) - 1);
1108
1043
  return fromSeq <= entries.length ? entries.slice(start, start + JOURNAL_READ_PAGE_SIZE).map((entry) => this.copyEntry(entry)) : [];
1109
1044
  }
1110
- readEntries(runId, fromSeq = 1) {
1111
- this.ensureOpen();
1112
- validateText("runId", runId);
1113
- return (this.runs.get(runId)?.entries ?? []).filter((entry) => entry.seq >= fromSeq).map((entry) => this.copyEntry(entry));
1114
- }
1115
1045
  async readKey(runId, key) {
1116
1046
  this.ensureOpen();
1117
1047
  validateText("runId", runId);
@@ -1120,9 +1050,6 @@ class MemoryRunJournal {
1120
1050
  return entry ? this.copyEntry(entry) : undefined;
1121
1051
  }
1122
1052
  async deleteRun(runId) {
1123
- this.deleteRunSync(runId);
1124
- }
1125
- deleteRunSync(runId) {
1126
1053
  this.ensureOpen();
1127
1054
  validateText("runId", runId);
1128
1055
  const current = this.leases.get(runId);
@@ -1138,27 +1065,107 @@ class MemoryRunJournal {
1138
1065
  const actual = this.runs.get(lease.runId)?.entries.at(-1)?.seq ?? 0;
1139
1066
  if (expectSeq !== undefined && expectSeq !== actual)
1140
1067
  throw new JournalCasConflictError(lease.runId, expectSeq, actual);
1141
- this.deleteRunSync(lease.runId);
1068
+ await this.deleteRun(lease.runId);
1142
1069
  }
1143
1070
  async close() {
1144
1071
  this.closed = true;
1145
1072
  }
1146
1073
  }
1147
1074
  // dist/builtin/workflows/src/durable/journal/resolution.ts
1148
- import { dirname as dirname2, isAbsolute, join as join2 } from "node:path";
1149
- import { getAgentDir as getAgentDir2 } from "@bastani/atomic";
1150
-
1151
- // dist/builtin/workflows/src/durable/journal/sqlite-run-journal.ts
1152
- import { dirname, join } from "node:path";
1153
- import { getAgentDir, openNodeSqliteDatabase, validateStoragePrefix, wrapNodeSqliteDatabase } from "@bastani/atomic";
1075
+ import { dirname, isAbsolute, join } from "node:path";
1076
+ import { getAgentDir } from "@bastani/atomic";
1077
+ import {
1078
+ StorageConfigError,
1079
+ StorageProvider,
1080
+ selectStorage
1081
+ } from "@bastani/atomic/storage";
1154
1082
 
1155
1083
  // dist/builtin/workflows/src/durable/journal/sql-run-journal.ts
1156
1084
  import {
1157
1085
  assertStorageSchemaVersion,
1158
- renderStorageIdentifiers,
1086
+ renderStorageIdentifiers as renderStorageIdentifiers2,
1159
1087
  StorageSchemaVersionError as StorageSchemaVersionError2,
1160
1088
  StorageUnavailableError as StorageUnavailableError2
1161
1089
  } from "@bastani/atomic/storage";
1090
+
1091
+ // dist/builtin/workflows/src/durable/journal/legacy-journal-tables.ts
1092
+ import {
1093
+ renderStorageIdentifiers
1094
+ } from "@bastani/atomic/storage";
1095
+ var CURRENT = renderStorageIdentifiers("journal", {
1096
+ ...JOURNAL_TABLES,
1097
+ legacyDeleted: "legacy_deleted",
1098
+ migrations: "migrations"
1099
+ });
1100
+ var COPIED_ALL_MARKER = "unprefixed-journal-tables";
1101
+ var LEGACY_COLUMNS = {
1102
+ meta: [JOURNAL_COLUMNS.schemaVersion],
1103
+ runs: [JOURNAL_COLUMNS.runId, JOURNAL_COLUMNS.name, JOURNAL_COLUMNS.cwd, JOURNAL_COLUMNS.createdAt, JOURNAL_COLUMNS.status, JOURNAL_COLUMNS.headerJson],
1104
+ events: [JOURNAL_COLUMNS.runId, JOURNAL_COLUMNS.seq, JOURNAL_COLUMNS.epoch, JOURNAL_COLUMNS.key, JOURNAL_COLUMNS.type, JOURNAL_COLUMNS.payload, JOURNAL_COLUMNS.at],
1105
+ leases: [JOURNAL_COLUMNS.runId, JOURNAL_COLUMNS.holderId, JOURNAL_COLUMNS.epoch, JOURNAL_COLUMNS.renewedAt]
1106
+ };
1107
+ var PENDING_LEGACY_RUNS = `SELECT ${JOURNAL_COLUMNS.runId}, ${JOURNAL_COLUMNS.headerJson}, ${JOURNAL_COLUMNS.status} FROM ${JOURNAL_TABLES.runs}
1108
+ WHERE ${JOURNAL_COLUMNS.runId} NOT IN (SELECT ${JOURNAL_COLUMNS.runId} FROM ${CURRENT.runs})
1109
+ AND ${JOURNAL_COLUMNS.runId} NOT IN (SELECT ${JOURNAL_COLUMNS.runId} FROM ${CURRENT.legacyDeleted})`;
1110
+ async function hasLegacyTable(tx, table) {
1111
+ const columns = await tx.all("SELECT name FROM pragma_table_info(?)", JOURNAL_TABLES[table]);
1112
+ const names = new Set(columns.map((column) => column.name));
1113
+ return columns.length === LEGACY_COLUMNS[table].length && LEGACY_COLUMNS[table].every((name) => names.has(name));
1114
+ }
1115
+
1116
+ class LegacyJournalRuns {
1117
+ static async open(database) {
1118
+ try {
1119
+ return await database.transaction(async (tx) => {
1120
+ for (const table of ["meta", "runs", "events"]) {
1121
+ if (!await hasLegacyTable(tx, table))
1122
+ return;
1123
+ }
1124
+ const versions = await tx.all(`SELECT ${JOURNAL_COLUMNS.schemaVersion} FROM ${JOURNAL_TABLES.meta}`);
1125
+ if (versions.length !== 1 || Number(versions[0][JOURNAL_COLUMNS.schemaVersion]) !== JOURNAL_SCHEMA_VERSION)
1126
+ return;
1127
+ 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;
1128
+ if (copiedAll)
1129
+ return;
1130
+ await tx.exec(`CREATE TABLE IF NOT EXISTS ${CURRENT.legacyDeleted}(${JOURNAL_COLUMNS.runId} TEXT PRIMARY KEY, deleted_at INTEGER NOT NULL)`);
1131
+ return new LegacyJournalRuns;
1132
+ });
1133
+ } catch {
1134
+ return;
1135
+ }
1136
+ }
1137
+ async pending(executor, filter) {
1138
+ return executor.all(`${PENDING_LEGACY_RUNS}${filter?.cwd === undefined ? "" : ` AND ${JOURNAL_COLUMNS.cwd} = ?`}`, ...filter?.cwd === undefined ? [] : [filter.cwd]);
1139
+ }
1140
+ async find(executor, runId) {
1141
+ return executor.get(`${PENDING_LEGACY_RUNS} AND ${JOURNAL_COLUMNS.runId} = ?`, runId);
1142
+ }
1143
+ async events(executor, runId, fromSeq, limit) {
1144
+ 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);
1145
+ }
1146
+ async eventByKey(executor, runId, key) {
1147
+ return executor.get(`SELECT ${LEGACY_COLUMNS.events.join(", ")} FROM ${JOURNAL_TABLES.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.key} = ?`, runId, key);
1148
+ }
1149
+ async convert(tx, runId) {
1150
+ if (await this.find(tx, runId) === undefined)
1151
+ return false;
1152
+ const eventColumns = LEGACY_COLUMNS.events.join(", ");
1153
+ await tx.run(`INSERT OR IGNORE INTO ${CURRENT.events}(${eventColumns}) SELECT ${eventColumns} FROM ${JOURNAL_TABLES.events} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
1154
+ if (await hasLegacyTable(tx, "leases")) {
1155
+ 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);
1156
+ }
1157
+ const runColumns = LEGACY_COLUMNS.runs.join(", ");
1158
+ await tx.run(`INSERT INTO ${CURRENT.runs}(${runColumns}) SELECT ${runColumns} FROM ${JOURNAL_TABLES.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
1159
+ return true;
1160
+ }
1161
+ async markDeleted(tx, runId) {
1162
+ if (await tx.get(`SELECT ${JOURNAL_COLUMNS.runId} FROM ${JOURNAL_TABLES.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId) === undefined)
1163
+ return;
1164
+ await tx.run(`INSERT OR IGNORE INTO ${CURRENT.legacyDeleted} VALUES (?, ?)`, runId, Date.now());
1165
+ }
1166
+ }
1167
+
1168
+ // dist/builtin/workflows/src/durable/journal/sql-run-journal.ts
1162
1169
  var STORE_NOW = "CAST(unixepoch('subsec') * 1000 AS INTEGER)";
1163
1170
  function entryFromRow(row) {
1164
1171
  const key = row[JOURNAL_COLUMNS.key];
@@ -1178,12 +1185,14 @@ class SqlRunJournal {
1178
1185
  closePromise;
1179
1186
  database;
1180
1187
  tables;
1181
- constructor(database, tables) {
1188
+ legacy;
1189
+ constructor(database, tables, legacy) {
1182
1190
  this.database = database;
1183
1191
  this.tables = tables;
1192
+ this.legacy = legacy;
1184
1193
  }
1185
1194
  static async open(database, options = {}) {
1186
- const t = renderStorageIdentifiers("journal", JOURNAL_TABLES, options.prefix);
1195
+ const t = renderStorageIdentifiers2("journal", JOURNAL_TABLES, options.prefix);
1187
1196
  await database.transaction(async (tx) => {
1188
1197
  await tx.exec(`CREATE TABLE IF NOT EXISTS ${t.meta}(${JOURNAL_COLUMNS.schemaVersion} INTEGER NOT NULL)`);
1189
1198
  const versions = await tx.all(`SELECT ${JOURNAL_COLUMNS.schemaVersion} FROM ${t.meta}`);
@@ -1217,7 +1226,8 @@ class SqlRunJournal {
1217
1226
  );
1218
1227
  `);
1219
1228
  });
1220
- return new SqlRunJournal(database, t);
1229
+ const legacy = options.prefix ? undefined : await LegacyJournalRuns.open(database);
1230
+ return new SqlRunJournal(database, t, legacy);
1221
1231
  }
1222
1232
  get descriptor() {
1223
1233
  return { ...this.database.descriptor };
@@ -1253,6 +1263,8 @@ class SqlRunJournal {
1253
1263
  throw json;
1254
1264
  const { runs } = this.tables;
1255
1265
  return this.operation(async () => {
1266
+ if (await this.legacy?.find(this.database, header.runId))
1267
+ return "exists";
1256
1268
  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);
1257
1269
  return result.changes === 1 ? "created" : "exists";
1258
1270
  });
@@ -1262,7 +1274,8 @@ class SqlRunJournal {
1262
1274
  validateText("runId", runId);
1263
1275
  return this.operation(async () => {
1264
1276
  const row = await this.database.get(`SELECT ${JOURNAL_COLUMNS.headerJson}, ${JOURNAL_COLUMNS.status} FROM ${this.tables.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
1265
- return row ? { ...JSON.parse(row[JOURNAL_COLUMNS.headerJson]), status: row[JOURNAL_COLUMNS.status] } : undefined;
1277
+ const found = row ?? await this.legacy?.find(this.database, runId);
1278
+ return found ? { ...JSON.parse(found[JOURNAL_COLUMNS.headerJson]), status: found[JOURNAL_COLUMNS.status] } : undefined;
1266
1279
  });
1267
1280
  }
1268
1281
  async listRuns(filter) {
@@ -1271,13 +1284,23 @@ class SqlRunJournal {
1271
1284
  validateText("cwd", filter.cwd);
1272
1285
  return this.operation(async () => {
1273
1286
  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]);
1274
- return rows.map((row) => ({ ...JSON.parse(row[JOURNAL_COLUMNS.headerJson]), status: row[JOURNAL_COLUMNS.status] }));
1287
+ const legacy = await this.legacy?.pending(this.database, filter) ?? [];
1288
+ 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);
1275
1289
  });
1276
1290
  }
1277
1291
  async requireRun(tx, runId) {
1278
- if (!await tx.get(`SELECT ${JOURNAL_COLUMNS.runId} FROM ${this.tables.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId))
1292
+ if (await tx.get(`SELECT ${JOURNAL_COLUMNS.runId} FROM ${this.tables.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId))
1293
+ return;
1294
+ if (!await this.legacy?.convert(tx, runId))
1279
1295
  throw new RunNotFoundError(runId);
1280
1296
  }
1297
+ async isUnconvertedLegacyRun(runId) {
1298
+ if (this.legacy === undefined)
1299
+ return false;
1300
+ if (await this.database.get(`SELECT ${JOURNAL_COLUMNS.runId} FROM ${this.tables.runs} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId))
1301
+ return false;
1302
+ return await this.legacy.find(this.database, runId) !== undefined;
1303
+ }
1281
1304
  async leaseRow(tx, runId) {
1282
1305
  const row = await tx.get(`SELECT * FROM ${this.tables.leases} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
1283
1306
  return row ? { ...row, [JOURNAL_COLUMNS.epoch]: journalCounter(runId, "epoch", row[JOURNAL_COLUMNS.epoch]) } : undefined;
@@ -1417,9 +1440,11 @@ class SqlRunJournal {
1417
1440
  this.assertOpen();
1418
1441
  validateText("runId", runId);
1419
1442
  let nextSeq = fromSeq;
1443
+ const legacy = this.legacy;
1444
+ const readsLegacy = legacy !== undefined && await this.operation(() => this.isUnconvertedLegacyRun(runId));
1420
1445
  for (;; ) {
1421
1446
  const page = await this.operation(async () => {
1422
- 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);
1447
+ 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);
1423
1448
  return rows.map(entryFromRow);
1424
1449
  });
1425
1450
  for (const entry of page) {
@@ -1438,7 +1463,7 @@ class SqlRunJournal {
1438
1463
  validateText("runId", runId);
1439
1464
  validateText("key", key);
1440
1465
  return this.operation(async () => {
1441
- const row = await this.database.get(`SELECT * FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ? AND ${JOURNAL_COLUMNS.key} = ?`, runId, key);
1466
+ 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);
1442
1467
  return row ? entryFromRow(row) : undefined;
1443
1468
  });
1444
1469
  }
@@ -1463,6 +1488,7 @@ class SqlRunJournal {
1463
1488
  }));
1464
1489
  }
1465
1490
  async deleteRunData(tx, runId) {
1491
+ await this.legacy?.markDeleted(tx, runId);
1466
1492
  await this.leaseRow(tx, runId);
1467
1493
  await tx.run(`UPDATE ${this.tables.leases} SET ${JOURNAL_COLUMNS.holderId} = ? WHERE ${JOURNAL_COLUMNS.runId} = ?`, JOURNAL_LEASE.unheld, runId);
1468
1494
  await tx.run(`DELETE FROM ${this.tables.events} WHERE ${JOURNAL_COLUMNS.runId} = ?`, runId);
@@ -1477,10 +1503,82 @@ class SqlRunJournal {
1477
1503
  }
1478
1504
  }
1479
1505
 
1506
+ // dist/builtin/workflows/src/durable/journal/resolution.ts
1507
+ var provider = new StorageProvider({
1508
+ memory: (descriptor) => new MemoryRunJournal(descriptor),
1509
+ sql: SqlRunJournal.open
1510
+ });
1511
+ var settingsSelections = new WeakSet;
1512
+ function selectRunJournal(options = {}) {
1513
+ const agentDir = getAgentDir();
1514
+ const defaultPath = join(dirname(agentDir), "workflows", "journal.sqlite");
1515
+ if (options.journal !== undefined) {
1516
+ if (options.journal !== null && typeof options.journal === "object" && "createRun" in options.journal) {
1517
+ const journal = options.journal;
1518
+ if ([
1519
+ journal.createRun,
1520
+ journal.getRun,
1521
+ journal.listRuns,
1522
+ journal.acquire,
1523
+ journal.takeover,
1524
+ journal.takeoverExpired,
1525
+ journal.leaseState,
1526
+ journal.renew,
1527
+ journal.release,
1528
+ journal.append,
1529
+ journal.read,
1530
+ journal.readKey,
1531
+ journal.deleteOwnedRun,
1532
+ journal.deleteRun,
1533
+ journal.close
1534
+ ].some((hook) => typeof hook !== "function")) {
1535
+ throw new StorageConfigError("sdk", "journal", "invalid-journal");
1536
+ }
1537
+ return journal;
1538
+ }
1539
+ return selectStorage(options.journal, "sdk", "journal", defaultPath);
1540
+ }
1541
+ const environment = process.env.ATOMIC_WORKFLOW_JOURNAL_PATH;
1542
+ if (environment !== undefined && environment.length > 0)
1543
+ return { kind: "sqlite", path: environment };
1544
+ const workflows = options.settings?.workflows;
1545
+ const journal = Array.isArray(workflows) ? undefined : workflows?.journal;
1546
+ const value = journal !== undefined ? journal : options.settings?.storage;
1547
+ if (value === undefined)
1548
+ return { kind: "sqlite", path: defaultPath };
1549
+ const selection = selectStorage(value, "settings", journal !== undefined ? "workflows.journal" : "storage", journal !== undefined ? defaultPath : join(dirname(agentDir), "storage.sqlite"));
1550
+ const resolved = selection.kind === "sqlite" && !isAbsolute(selection.path) ? { ...selection, path: join(dirname(agentDir), selection.path) } : selection;
1551
+ settingsSelections.add(resolved);
1552
+ return resolved;
1553
+ }
1554
+ async function resolveRunJournal(options = {}) {
1555
+ return openSelectedRunJournal(selectRunJournal(options));
1556
+ }
1557
+ async function openSelectedRunJournal(selection) {
1558
+ if ("createRun" in selection)
1559
+ return selection;
1560
+ return withRunJournalConfigSource(selection, () => provider.openRunJournal(selection, { agentDir: getAgentDir(), domain: "journal" }));
1561
+ }
1562
+ async function withRunJournalConfigSource(selection, open) {
1563
+ if ("createRun" in selection)
1564
+ return open();
1565
+ try {
1566
+ return await open();
1567
+ } catch (error) {
1568
+ if (error instanceof StorageConfigError) {
1569
+ const source = settingsSelections.has(selection) ? "settings" : "sdk";
1570
+ if (error.source !== source)
1571
+ throw new StorageConfigError(source, error.field, error.reason);
1572
+ }
1573
+ throw error;
1574
+ }
1575
+ }
1480
1576
  // dist/builtin/workflows/src/durable/journal/sqlite-run-journal.ts
1577
+ import { dirname as dirname2, join as join2 } from "node:path";
1578
+ import { getAgentDir as getAgentDir2, openNodeSqliteDatabase, validateStoragePrefix, wrapNodeSqliteDatabase } from "@bastani/atomic";
1481
1579
  function workflowJournalPath() {
1482
1580
  const override = process.env.ATOMIC_WORKFLOW_JOURNAL_PATH;
1483
- return override !== undefined && override.length > 0 ? override : join(dirname(getAgentDir()), "workflows", "journal.sqlite");
1581
+ return override !== undefined && override.length > 0 ? override : join2(dirname2(getAgentDir2()), "workflows", "journal.sqlite");
1484
1582
  }
1485
1583
  async function openSqlRunJournal(source = workflowJournalPath(), options = {}) {
1486
1584
  validateStoragePrefix(options.prefix);
@@ -1499,36 +1597,6 @@ async function openSqlRunJournal(source = workflowJournalPath(), options = {}) {
1499
1597
  throw error;
1500
1598
  }
1501
1599
  }
1502
-
1503
- // dist/builtin/workflows/src/durable/journal/resolution.ts
1504
- function selectRunJournal(options = {}) {
1505
- if (options.journal !== undefined)
1506
- return options.journal;
1507
- const environment = process.env.ATOMIC_WORKFLOW_JOURNAL_PATH;
1508
- if (environment !== undefined && environment.length > 0)
1509
- return { path: environment };
1510
- const workflows = options.settings?.workflows;
1511
- const settings = Array.isArray(workflows) ? undefined : workflows?.journal;
1512
- const path = settings?.path;
1513
- if (path !== undefined && path.length > 0) {
1514
- if (settings?.memory === true)
1515
- throw new JournalConfigurationError("settings", "workflows.journal", "path-and-memory");
1516
- return { path: isAbsolute(path) ? path : join2(dirname2(getAgentDir2()), path) };
1517
- }
1518
- if (settings?.memory === true)
1519
- return { memory: true };
1520
- return { path: workflowJournalPath() };
1521
- }
1522
- async function resolveRunJournal(options = {}) {
1523
- const selected = selectRunJournal(options);
1524
- if ("createRun" in selected)
1525
- return selected;
1526
- if ("path" in selected)
1527
- return await openSqlRunJournal(selected.path);
1528
- if ("database" in selected)
1529
- return await openSqlRunJournal(selected.database);
1530
- return new MemoryRunJournal;
1531
- }
1532
1600
  // dist/builtin/workflows/src/engine/graph-inference.ts
1533
1601
  class GraphFrontierTracker {
1534
1602
  frontier = new Set;
@@ -1600,6 +1668,25 @@ import {
1600
1668
  resolveRestoredModelReference
1601
1669
  } from "@bastani/atomic";
1602
1670
 
1671
+ // dist/builtin/workflows/src/durable/execution-context-boundary.ts
1672
+ var executionStorages = new Set;
1673
+ function registerExecutionStorages(...storages) {
1674
+ for (const storage of storages)
1675
+ executionStorages.add(storage);
1676
+ return () => {
1677
+ for (const storage of storages)
1678
+ executionStorages.delete(storage);
1679
+ };
1680
+ }
1681
+ function outsideWorkflowExecutions(callback) {
1682
+ let run = callback;
1683
+ for (const storage of executionStorages) {
1684
+ const inner = run;
1685
+ run = () => storage.exit(inner);
1686
+ }
1687
+ return run();
1688
+ }
1689
+
1603
1690
  // dist/builtin/workflows/src/runs/foreground/stage-runner-session.ts
1604
1691
  function stageSessionExtensionRunner(current) {
1605
1692
  const runner = current.extensionRunner;
@@ -1683,7 +1770,6 @@ async function rejectDisposedCreatedSession(result, stageName) {
1683
1770
  }
1684
1771
 
1685
1772
  // dist/builtin/workflows/src/runs/foreground/stage-runner-session-options.ts
1686
- import { SessionManager } from "@bastani/atomic";
1687
1773
  var adapterDefaultCwds = new WeakMap;
1688
1774
  function setAgentSessionAdapterDefaultCwd(adapter, cwd) {
1689
1775
  adapterDefaultCwds.set(adapter, cwd);
@@ -1706,11 +1792,10 @@ async function buildStageSessionOptions(input) {
1706
1792
  }
1707
1793
  if (input.restoreSavedModel === true)
1708
1794
  delete options.model;
1709
- if (input.reattachSessionFile !== undefined && options.sessionManager === undefined) {
1710
- const cwd = options.cwd ?? process.cwd();
1711
- options.sessionManager = await SessionManager.open(input.reattachSessionFile, options.sessionDir, cwd);
1795
+ if (input.reattachSessionId !== undefined) {
1796
+ options.resumeFromSessionId = input.reattachSessionId;
1712
1797
  options.context = undefined;
1713
- options.forkFromSessionFile = undefined;
1798
+ options.forkFromSessionId = undefined;
1714
1799
  }
1715
1800
  if (input.sharedModelRuntime !== undefined && options.modelRuntime === undefined) {
1716
1801
  options.modelRuntime = input.sharedModelRuntime;
@@ -1967,18 +2052,15 @@ class ScopedDurableBackend {
1967
2052
  async hasPendingStageDeliveryReceipt(workflowId, messageId, delivery, logicalRunId = workflowId) {
1968
2053
  return await this.inner.hasPendingStageDeliveryReceipt?.(this.scope.rootWorkflowId, messageId, delivery, logicalRunId) ?? false;
1969
2054
  }
1970
- registerWorkflow(_handle) {}
2055
+ async commitWorkflowRegistration(_handle) {}
1971
2056
  persistPendingStageMessages(workflowId, messages, logicalRunId = workflowId) {
1972
2057
  return this.inner.persistPendingStageMessages(this.scope.rootWorkflowId, messages, logicalRunId);
1973
2058
  }
1974
- recordCheckpoint(checkpoint) {
1975
- return this.inner.recordCheckpoint(this.remap(checkpoint));
1976
- }
1977
- async recordCheckpointAsync(checkpoint, options) {
1978
- await this.inner.recordCheckpointAsync(this.remap(checkpoint), options);
2059
+ async commitCheckpoint(checkpoint, options) {
2060
+ await this.inner.commitCheckpoint(this.remap(checkpoint), options);
1979
2061
  }
1980
- async recordAdditiveCheckpointBestEffort(checkpoint) {
1981
- return await this.inner.recordAdditiveCheckpointBestEffort(this.remap(checkpoint));
2062
+ async commitAdditiveCheckpointBestEffort(checkpoint) {
2063
+ return await this.inner.commitAdditiveCheckpointBestEffort(this.remap(checkpoint));
1982
2064
  }
1983
2065
  workflowOwnership(_workflowId) {
1984
2066
  return this.inner.workflowOwnership(this.scope.rootWorkflowId);
@@ -2008,12 +2090,12 @@ class ScopedDurableBackend {
2008
2090
  getLoadableWorkflow(_workflowId) {
2009
2091
  return;
2010
2092
  }
2011
- setWorkflowStatus(_workflowId, _status, _pendingPrompts, _resumable) {}
2012
- async transitionWorkflowStatus(_workflowId, _expectedStatuses, _status, _pendingPrompts, _resumable) {
2093
+ async commitWorkflowStatus(_workflowId, _status, _pendingPrompts, _resumable) {}
2094
+ async commitWorkflowStatusTransition(_workflowId, _expectedStatuses, _status, _pendingPrompts, _resumable) {
2013
2095
  return false;
2014
2096
  }
2015
- adjustPendingPrompts(_workflowId, delta) {
2016
- return this.inner.adjustPendingPrompts(this.scope.rootWorkflowId, delta);
2097
+ commitPendingPromptAdjustment(_workflowId, delta) {
2098
+ return this.inner.commitPendingPromptAdjustment(this.scope.rootWorkflowId, delta);
2017
2099
  }
2018
2100
  promptReservationScope(_workflowId) {
2019
2101
  return this.effectivePromptScope();
@@ -2046,7 +2128,7 @@ class ScopedDurableBackend {
2046
2128
  isWorkflowLoadable(_workflowId) {
2047
2129
  return false;
2048
2130
  }
2049
- reset() {}
2131
+ async commitReset() {}
2050
2132
  hydrateWorkflow(_workflowId) {
2051
2133
  return Promise.resolve();
2052
2134
  }
@@ -4217,19 +4299,9 @@ function createStageStoreMethods(context) {
4217
4299
  if (!run)
4218
4300
  return false;
4219
4301
  const stage = context.findStage(run, stageId);
4220
- if (!stage)
4221
- return false;
4222
- let changed = false;
4223
- if (session.sessionId !== undefined && stage.sessionId !== session.sessionId) {
4224
- stage.sessionId = session.sessionId;
4225
- changed = true;
4226
- }
4227
- if (session.sessionFile !== undefined && stage.sessionFile !== session.sessionFile) {
4228
- stage.sessionFile = session.sessionFile;
4229
- changed = true;
4230
- }
4231
- if (!changed)
4302
+ if (!stage || stage.sessionId === session.sessionId)
4232
4303
  return false;
4304
+ stage.sessionId = session.sessionId;
4233
4305
  context.bumpAndNotify();
4234
4306
  return true;
4235
4307
  },
@@ -4950,7 +5022,7 @@ function makeWorkflowStageOrchestrationContext(meta, pi) {
4950
5022
  const sendMessage = pi.sendMessage;
4951
5023
  if (!sendMessage)
4952
5024
  throw new Error("atomic-workflows: main-chat late-message route is unavailable");
4953
- return routeThroughStaleContextGuard(() => sendMessage(message, options));
5025
+ return routeThroughStaleContextGuard(() => outsideWorkflowExecutions(() => sendMessage(message, options)));
4954
5026
  },
4955
5027
  routeMessages(messages, options) {
4956
5028
  const intercomRoute = emitLateIntercomRoute(pi, meta, messages, options, true);
@@ -4958,15 +5030,15 @@ function makeWorkflowStageOrchestrationContext(meta, pi) {
4958
5030
  return intercomRoute;
4959
5031
  const sendMessages = pi.sendMessages;
4960
5032
  if (sendMessages)
4961
- return routeThroughStaleContextGuard(() => sendMessages(messages, options));
5033
+ return routeThroughStaleContextGuard(() => outsideWorkflowExecutions(() => sendMessages(messages, options)));
4962
5034
  const sendMessage = pi.sendMessage;
4963
5035
  if (!sendMessage)
4964
5036
  throw new Error("atomic-workflows: main-chat late-message route is unavailable");
4965
- return (async () => {
5037
+ return outsideWorkflowExecutions(async () => {
4966
5038
  for (const [index, message] of messages.entries()) {
4967
5039
  await sendMessage(message, index === 0 ? options : { deliverAs: "followUp" });
4968
5040
  }
4969
- })();
5041
+ });
4970
5042
  }
4971
5043
  }
4972
5044
  };
@@ -6375,6 +6447,9 @@ ${formatValidationErrors(errors)}`);
6375
6447
  }
6376
6448
  return resolved;
6377
6449
  }
6450
+ // dist/builtin/workflows/src/durable/backend.ts
6451
+ import { closeSync, openSync, readSync } from "node:fs";
6452
+
6378
6453
  // dist/builtin/workflows/src/durable/resume-eligibility.ts
6379
6454
  function isDurableWorkflowResumable(candidate) {
6380
6455
  const isRoot = candidate.rootWorkflowId === undefined || candidate.rootWorkflowId === candidate.workflowId;
@@ -6410,6 +6485,33 @@ function canonicalJsonString(value) {
6410
6485
  }
6411
6486
 
6412
6487
  // dist/builtin/workflows/src/durable/backend.ts
6488
+ var SESSION_HEADER_READ_LIMIT_BYTES = 64 * 1024;
6489
+ function readSessionHeaderId(sessionFile) {
6490
+ let fd;
6491
+ try {
6492
+ fd = openSync(sessionFile, "r");
6493
+ } catch {
6494
+ return;
6495
+ }
6496
+ try {
6497
+ const buffer = Buffer.alloc(SESSION_HEADER_READ_LIMIT_BYTES);
6498
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, 0);
6499
+ const firstLine = buffer.subarray(0, bytesRead).toString("utf8").replace(/^\uFEFF/, "").split(`
6500
+ `)[0];
6501
+ const header = JSON.parse(firstLine ?? "");
6502
+ return header.type === "session" && typeof header.id === "string" ? header.id : undefined;
6503
+ } catch {
6504
+ return;
6505
+ } finally {
6506
+ closeSync(fd);
6507
+ }
6508
+ }
6509
+ function migrateStageSessionCheckpoint(checkpoint) {
6510
+ if (checkpoint.sessionId !== undefined || checkpoint.sessionFile === undefined)
6511
+ return checkpoint;
6512
+ const sessionId = readSessionHeaderId(checkpoint.sessionFile);
6513
+ return sessionId === undefined ? checkpoint : { ...checkpoint, sessionId };
6514
+ }
6413
6515
  function replacePendingStageMessagesForRun(existing, logicalRunId, messages) {
6414
6516
  if (messages.some((entry) => entry.runId !== logicalRunId)) {
6415
6517
  throw new Error(`atomic-workflows: pending-stage persistence mixed logical run ${logicalRunId}`);
@@ -6544,7 +6646,8 @@ class JournalProjection {
6544
6646
  return this.stickyReceipts.get(workflowId)?.has(name) ?? false;
6545
6647
  });
6546
6648
  }
6547
- recordCheckpoint(checkpoint) {
6649
+ recordCheckpoint(recorded) {
6650
+ const checkpoint = recorded.kind === "stage" ? migrateStageSessionCheckpoint(recorded) : recorded;
6548
6651
  const currentCheckpoint = checkpoint.kind === "stage" && checkpoint.topology === undefined ? {
6549
6652
  ...checkpoint,
6550
6653
  topology: {
@@ -6570,7 +6673,7 @@ class JournalProjection {
6570
6673
  } else {
6571
6674
  if ("output" in currentCheckpoint)
6572
6675
  rec.stageOutputByReplayKey.set(currentCheckpoint.replayKey, currentCheckpoint);
6573
- if (currentCheckpoint.sessionId !== undefined || currentCheckpoint.sessionFile !== undefined) {
6676
+ if (currentCheckpoint.sessionId !== undefined) {
6574
6677
  const existing = rec.stageSessionByReplayKey.get(currentCheckpoint.replayKey);
6575
6678
  if (existing === undefined || currentCheckpoint.completedAt >= existing.completedAt) {
6576
6679
  rec.stageSessionByReplayKey.set(currentCheckpoint.replayKey, currentCheckpoint);
@@ -6598,7 +6701,7 @@ class JournalProjection {
6598
6701
  }
6599
6702
  getStageSession(workflowId, replayKey) {
6600
6703
  const checkpoint = this.workflows.get(workflowId)?.stageSessionByReplayKey.get(replayKey);
6601
- if (checkpoint?.sessionId === undefined && checkpoint?.sessionFile === undefined)
6704
+ if (checkpoint?.sessionId === undefined)
6602
6705
  return;
6603
6706
  return {
6604
6707
  ...checkpoint.sessionId !== undefined ? { sessionId: checkpoint.sessionId } : {},
@@ -7129,7 +7232,7 @@ function prepareDurableChildInvocation(input) {
7129
7232
  return;
7130
7233
  }
7131
7234
  topology = makeTopology(input, boundaryId, childRunId, parentIds, sourceOrder, "start", "running");
7132
- await input.backend.recordCheckpointAsync({
7235
+ await input.backend.commitCheckpoint({
7133
7236
  kind: "stage",
7134
7237
  workflowId: input.workflowId,
7135
7238
  checkpointId: `boundary-start:${input.replayKey}`,
@@ -7156,7 +7259,7 @@ function prepareDurableChildInvocation(input) {
7156
7259
  const terminalTopology = makeTopology(input, boundaryId, childRunId, topology.parentIds, topology.sourceOrder, "terminal", status);
7157
7260
  const priorTerminalAt = stages.filter((stage) => stage.replayKey === input.replayKey && stage.topology?.boundary?.event === "terminal").reduce((latest, stage) => Math.max(latest, stage.completedAt), 0);
7158
7261
  const now = Math.max(Date.now(), priorTerminalAt + 1);
7159
- await input.backend.recordCheckpointAsync({
7262
+ await input.backend.commitCheckpoint({
7160
7263
  kind: "stage",
7161
7264
  workflowId: input.workflowId,
7162
7265
  checkpointId: `boundary-terminal:${input.replayKey}:${status}`,
@@ -7829,9 +7932,10 @@ function replayedWorkflowToolOutcome(outcome) {
7829
7932
 
7830
7933
  // dist/builtin/workflows/src/durable/tool-failure-checkpoint.ts
7831
7934
  async function recordThrowingToolFailure(input, node, identity, error, attempts, cancelled = false) {
7935
+ await input.beforeCheckpoint?.();
7832
7936
  const message = workflowToolFailure(error, attempts, false).error.message;
7833
7937
  const failedAt = Date.now();
7834
- await input.backend.recordAdditiveCheckpointBestEffort({
7938
+ await input.backend.commitAdditiveCheckpointBestEffort({
7835
7939
  kind: "tool",
7836
7940
  workflowId: input.workflowId,
7837
7941
  checkpointId: `tool-failure:${identity.argsHash}:${input.nextCheckpointId()}`,
@@ -8159,6 +8263,21 @@ async function executeLiveToolInvocation(live) {
8159
8263
  const startedAt = Date.now();
8160
8264
  let attempts = 0;
8161
8265
  let callbackCompleted = false;
8266
+ const cancelInvocation = async (cancellation) => {
8267
+ control.noteCancelled();
8268
+ if (returnFailure || isWorkflowToolAbortError(cancellation) && cancellation.scope === "node" || input.runFailing?.() === true) {
8269
+ await recordCancelledToolInspection(live, startedAt, cancellation, attempts);
8270
+ }
8271
+ const endedAt = Date.now();
8272
+ input.onNodeEnd?.(node.id, {
8273
+ status: "cancelled",
8274
+ endedAt,
8275
+ durationMs: Math.max(0, endedAt - startedAt),
8276
+ error: cancellation.message
8277
+ });
8278
+ input.onNodeSettle?.(node.id);
8279
+ throw cancellation;
8280
+ };
8162
8281
  input.onNodeRunning?.(node.id, startedAt);
8163
8282
  try {
8164
8283
  const result = await executeWithRetries(() => {
@@ -8195,6 +8314,8 @@ async function executeLiveToolInvocation(live) {
8195
8314
  ...input.runTopology !== undefined ? { run: { ...input.runTopology } } : {}
8196
8315
  }
8197
8316
  };
8317
+ await input.beforeCheckpoint?.();
8318
+ throwIfInvocationCancelled(input, toolSignal);
8198
8319
  await recordCheckpointDurably(input.backend, checkpoint);
8199
8320
  input.onNodeEnd?.(node.id, {
8200
8321
  status: "completed",
@@ -8208,21 +8329,8 @@ async function executeLiveToolInvocation(live) {
8208
8329
  } catch (error) {
8209
8330
  const timeoutFailure = error instanceof WorkflowToolTimeoutError;
8210
8331
  const cancellation = timeoutFailure ? undefined : invocationCancellation(input, toolSignal);
8211
- if (cancellation !== undefined) {
8212
- control.noteCancelled();
8213
- if (returnFailure || isWorkflowToolAbortError(cancellation) && cancellation.scope === "node" || input.runFailing?.() === true) {
8214
- await recordCancelledToolInspection(live, startedAt, cancellation, attempts);
8215
- }
8216
- const endedAt = Date.now();
8217
- input.onNodeEnd?.(node.id, {
8218
- status: "cancelled",
8219
- endedAt,
8220
- durationMs: Math.max(0, endedAt - startedAt),
8221
- error: cancellation.message
8222
- });
8223
- input.onNodeSettle?.(node.id);
8224
- throw cancellation;
8225
- }
8332
+ if (cancellation !== undefined)
8333
+ return await cancelInvocation(cancellation);
8226
8334
  const callbackFailure = callbackError ?? error;
8227
8335
  if (returnFailure && !callbackCompleted && isExplicitCallbackCancellation(callbackFailure)) {
8228
8336
  input.onFailureObserved?.(callbackFailure, node.id);
@@ -8262,8 +8370,14 @@ async function executeLiveToolInvocation(live) {
8262
8370
  }
8263
8371
  };
8264
8372
  try {
8373
+ await input.beforeCheckpoint?.();
8374
+ if (!timeoutFailure)
8375
+ throwIfInvocationCancelled(input, toolSignal);
8265
8376
  await recordCheckpointDurably(input.backend, checkpoint);
8266
8377
  } catch (persistenceError) {
8378
+ const cancellation = timeoutFailure ? undefined : invocationCancellation(input, toolSignal);
8379
+ if (cancellation !== undefined)
8380
+ return await cancelInvocation(cancellation);
8267
8381
  input.onFailureObserved?.(persistenceError, node.id);
8268
8382
  const endedAt = Date.now();
8269
8383
  input.onNodeEnd?.(node.id, {
@@ -8414,7 +8528,7 @@ async function recordReplayedToolTopology(input, node, cached, argsHash, endedAt
8414
8528
  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;
8415
8529
  if (unchanged)
8416
8530
  return;
8417
- await input.backend.recordAdditiveCheckpointBestEffort({
8531
+ await input.backend.commitAdditiveCheckpointBestEffort({
8418
8532
  kind: "tool",
8419
8533
  workflowId: input.workflowId,
8420
8534
  checkpointId: `tool-replay-meta:${durableHash({ argsHash, topology })}`,
@@ -8436,7 +8550,7 @@ function summarizeToolResult(value) {
8436
8550
  return serialized.length <= 240 ? serialized : `${flattenTruncatedString(serialized.slice(0, 237))}...`;
8437
8551
  }
8438
8552
  async function recordCheckpointDurably(backend, checkpoint, signal) {
8439
- await backend.recordCheckpointAsync(checkpoint, signal === undefined ? undefined : { signal });
8553
+ await backend.commitCheckpoint(checkpoint, signal === undefined ? undefined : { signal });
8440
8554
  }
8441
8555
  async function executeWithRetries(fn, options, throwIfCancelled, signal) {
8442
8556
  throwIfCancelled();
@@ -8495,6 +8609,7 @@ async function recordStageCheckpoint(deps, stage, options) {
8495
8609
  completedAt: stage.endedAt ?? Date.now(),
8496
8610
  ...metadata
8497
8611
  };
8612
+ await deps.beforeCheckpoint?.();
8498
8613
  await recordCheckpointDurably(deps.backend, checkpoint);
8499
8614
  return true;
8500
8615
  }
@@ -8504,12 +8619,12 @@ function stageSessionDurationBucket(durationMs) {
8504
8619
  }
8505
8620
  async function recordStageSessionCheckpoint(deps, stage, options) {
8506
8621
  const replayKey = deps.replayKeyForCompletedStage?.(stage) ?? stage.replayKey ?? deps.nextReplayKey(stage.name);
8507
- if (stage.sessionFile === undefined)
8622
+ if (stage.sessionId === undefined)
8508
8623
  return false;
8509
8624
  const checkpointNow = deps.now?.() ?? Date.now();
8510
8625
  const durationMs = elapsedStageMs(stage, checkpointNow) ?? 0;
8511
8626
  const current = deps.backend.getStageSession(deps.workflowId, replayKey);
8512
- if (options?.force !== true && current !== undefined && current.sessionId === stage.sessionId && current.sessionFile === stage.sessionFile && current.startedAt === stage.startedAt && stageSessionDurationBucket(current.durationMs) === stageSessionDurationBucket(durationMs))
8627
+ if (options?.force !== true && current !== undefined && current.sessionId === stage.sessionId && current.startedAt === stage.startedAt && stageSessionDurationBucket(current.durationMs) === stageSessionDurationBucket(durationMs))
8513
8628
  return false;
8514
8629
  const checkpoint = {
8515
8630
  kind: "stage",
@@ -8524,6 +8639,7 @@ async function recordStageSessionCheckpoint(deps, stage, options) {
8524
8639
  durationMs,
8525
8640
  completedAt: checkpointNow
8526
8641
  };
8642
+ await deps.beforeCheckpoint?.();
8527
8643
  await recordCheckpointDurably(deps.backend, checkpoint);
8528
8644
  return true;
8529
8645
  }
@@ -8550,10 +8666,10 @@ function createDurableStagePrimitive(input) {
8550
8666
  const cached = stageCheckpointWithOutput(input.backend, input.workflowId, replayKey);
8551
8667
  if (cached !== undefined) {
8552
8668
  const recorded = input.recordCachedStage?.(name, replayKey, cached);
8553
- return createCachedStageContext(name, cached.output, cached.result, recorded);
8669
+ return withStageWriteBarrier(createCachedStageContext(name, cached.output, cached.result, recorded), input.beforeCall);
8554
8670
  }
8555
8671
  const session = input.backend.getStageSession(input.workflowId, replayKey);
8556
- const isMidSessionResume = session?.sessionFile !== undefined;
8672
+ const isMidSessionResume = session?.sessionId !== undefined;
8557
8673
  const topology = activeStageTopology(input.backend, input.workflowId, replayKey);
8558
8674
  const durableStageId = topology?.stageId ?? pendingStageIdForReplay(input.backend, input.workflowId, replayKey, name);
8559
8675
  const durableIntercomGroup = topology?.intercomGroup ?? input.durableIntercomGroup?.(replayKey, durableStageId);
@@ -8564,12 +8680,13 @@ function createDurableStagePrimitive(input) {
8564
8680
  ...topology !== undefined ? { durableParentIds: [...topology.parentIds] } : {},
8565
8681
  ...durableIntercomGroup !== undefined ? { durableIntercomGroup } : {},
8566
8682
  ...isMidSessionResume ? {
8567
- resumeFromSessionFile: session.sessionFile,
8683
+ resumeFromSessionId: session.sessionId,
8684
+ ...session.sessionFile !== undefined ? { resumeFromLegacySessionFile: session.sessionFile } : {},
8568
8685
  routerSelection: session.routerSelection,
8569
8686
  durableAccumulatedDurationMs: session.durationMs ?? 0
8570
8687
  } : {}
8571
8688
  };
8572
- const live = withMidSessionResumePrompt(input.stage(name, liveOptions, replayKey), isMidSessionResume);
8689
+ const live = withStageWriteBarrier(withMidSessionResumePrompt(input.stage(name, liveOptions, replayKey), isMidSessionResume), input.beforeCall);
8573
8690
  if (options?.schema === undefined)
8574
8691
  return live;
8575
8692
  return wrapSchemaStageForDurability({
@@ -8577,10 +8694,31 @@ function createDurableStagePrimitive(input) {
8577
8694
  workflowId: input.workflowId,
8578
8695
  backend: input.backend,
8579
8696
  replayKey,
8697
+ beforeCheckpoint: input.beforeCheckpoint,
8580
8698
  name
8581
8699
  });
8582
8700
  };
8583
8701
  }
8702
+ function withStageWriteBarrier(stage, beforeCall) {
8703
+ if (beforeCall === undefined)
8704
+ return stage;
8705
+ const wrapped = Object.create(stage);
8706
+ Object.defineProperties(wrapped, {
8707
+ prompt: {
8708
+ value: async (...args) => {
8709
+ await beforeCall();
8710
+ return stage.prompt(...args);
8711
+ }
8712
+ },
8713
+ complete: {
8714
+ value: async (...args) => {
8715
+ await beforeCall();
8716
+ return stage.complete(...args);
8717
+ }
8718
+ }
8719
+ });
8720
+ return wrapped;
8721
+ }
8584
8722
  var TASK_RESULT_CHECKPOINT_CONTROL_PREFIX = "task-checkpoint:";
8585
8723
  function createDurableTaskPrimitive(input) {
8586
8724
  return async (name, options, stageFailFastScope) => {
@@ -8601,8 +8739,9 @@ function createDurableTaskPrimitive(input) {
8601
8739
  durableParentIds: [...topology.parentIds]
8602
8740
  } : {},
8603
8741
  ...durableIntercomGroup !== undefined ? { durableIntercomGroup } : {},
8604
- ...session?.sessionFile !== undefined ? {
8605
- resumeFromSessionFile: session.sessionFile,
8742
+ ...session?.sessionId !== undefined ? {
8743
+ resumeFromSessionId: session.sessionId,
8744
+ ...session.sessionFile !== undefined ? { resumeFromLegacySessionFile: session.sessionFile } : {},
8606
8745
  routerSelection: session.routerSelection,
8607
8746
  durableAccumulatedDurationMs: session.durationMs ?? 0
8608
8747
  } : {}
@@ -8619,6 +8758,9 @@ function createDurableTaskPrimitive(input) {
8619
8758
  });
8620
8759
  const signal = mergeAbortSignals(input.signal, tailController.signal);
8621
8760
  try {
8761
+ await input.beforeCheckpoint?.();
8762
+ if (signal?.aborted)
8763
+ throw abortReasonError(signal);
8622
8764
  await awaitAbortable(signal, recordCheckpointDurably(input.backend, {
8623
8765
  kind: "stage",
8624
8766
  workflowId: input.workflowId,
@@ -8750,6 +8892,7 @@ function wrapSchemaStageForDurability(input) {
8750
8892
  value: async (text, options) => {
8751
8893
  const result = await stage.prompt(text, options);
8752
8894
  if (typeof result !== "string" || result.length === 0) {
8895
+ await input.beforeCheckpoint?.();
8753
8896
  await recordCheckpointDurably(input.backend, {
8754
8897
  kind: "stage",
8755
8898
  workflowId: input.workflowId,
@@ -8894,7 +9037,6 @@ function stableCheckpointId(kind, replayKey) {
8894
9037
  function stageSessionCheckpointId(replayKey, stage, durationMs) {
8895
9038
  return `${stableCheckpointId("stage-session", replayKey)}:${durableHash({
8896
9039
  sessionId: stage.sessionId ?? "",
8897
- sessionFile: stage.sessionFile ?? "",
8898
9040
  startedAt: stage.startedAt ?? 0,
8899
9041
  durationMs
8900
9042
  })}`;
@@ -9024,8 +9166,8 @@ function createDurableChildWorkflowPrimitive(input) {
9024
9166
  }
9025
9167
 
9026
9168
  // dist/builtin/workflows/src/durable/factory.ts
9027
- import { resolve } from "node:path";
9028
- import { SettingsManager } from "@bastani/atomic";
9169
+ import { getAgentDir as getAgentDir3, SettingsManager } from "@bastani/atomic";
9170
+ import { storageSelectionKey } from "@bastani/atomic/storage";
9029
9171
 
9030
9172
  // dist/builtin/workflows/src/durable/journal/journal-backend.ts
9031
9173
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
@@ -9241,17 +9383,11 @@ class PromptReservationState {
9241
9383
 
9242
9384
  // dist/builtin/workflows/src/durable/journal/journal-backend.ts
9243
9385
  var PROCESS_HOLDER_ID = randomUUID4();
9244
- var DEFER_REBUILD = Symbol("defer-rebuild");
9245
- function isPromise(value) {
9246
- return typeof value?.then === "function";
9247
- }
9248
- function* invoke(action, synchronous = false) {
9386
+ function* invoke(action) {
9249
9387
  try {
9250
9388
  const result = action();
9251
- if (synchronous)
9252
- return result;
9253
9389
  let value;
9254
- yield Promise.resolve(result).then((resolved) => {
9390
+ yield result.then((resolved) => {
9255
9391
  value = resolved;
9256
9392
  });
9257
9393
  return value;
@@ -9261,10 +9397,17 @@ function* invoke(action, synchronous = false) {
9261
9397
  throw new StorageUnavailableError({ adapter: "custom", location: "custom journal" }, error instanceof Error ? error : new Error(String(error)));
9262
9398
  }
9263
9399
  }
9264
- function execute(operation, step = operation.next()) {
9265
- if (step.done)
9266
- return step.value;
9267
- return step.value.then(() => execute(operation), (error) => execute(operation, operation.throw(error)));
9400
+ async function execute(operation) {
9401
+ let step = operation.next();
9402
+ while (!step.done) {
9403
+ try {
9404
+ await step.value;
9405
+ step = operation.next();
9406
+ } catch (error) {
9407
+ step = operation.throw(error);
9408
+ }
9409
+ }
9410
+ return step.value;
9268
9411
  }
9269
9412
 
9270
9413
  class JournalOwnershipError extends WorkflowInstanceOwnershipError {
@@ -9324,31 +9467,31 @@ class JournalDurableBackend {
9324
9467
  ownsJournal;
9325
9468
  persistent;
9326
9469
  projection = createJournalProjection();
9327
- synchronous;
9328
9470
  sequences = new Map;
9329
9471
  leases = new Map;
9330
9472
  executions = new Map;
9331
9473
  executionContext = new AsyncLocalStorage2;
9332
9474
  pending = new Map;
9475
+ catalogQueue = Symbol("catalog");
9333
9476
  lost = new Map;
9334
9477
  prompts = new Map;
9335
9478
  timer;
9336
- closed = false;
9479
+ state = "open";
9480
+ closing;
9481
+ renewing;
9482
+ mutationContext = new AsyncLocalStorage2;
9337
9483
  processExitCleanup;
9338
- constructor(journal, holderId = `${PROCESS_HOLDER_ID}:${randomUUID4()}`, rebuild, ownsJournal = true) {
9484
+ unregisterExecutionStorages = registerExecutionStorages(this.executionContext, this.mutationContext);
9485
+ constructor(journal, holderId = `${PROCESS_HOLDER_ID}:${randomUUID4()}`, ownsJournal = true) {
9339
9486
  this.journal = journal;
9340
9487
  this.holderId = holderId;
9341
9488
  this.ownsJournal = ownsJournal;
9342
- this.synchronous = synchronousJournal(journal);
9343
9489
  this.persistent = !(journal instanceof MemoryRunJournal);
9344
- if (rebuild !== DEFER_REBUILD && this.synchronous !== undefined)
9345
- for (const run of this.synchronous.listRunsSync())
9346
- execute(this.refresh(run.runId));
9347
9490
  }
9348
9491
  static async open(journal, options = {}) {
9349
9492
  let backend;
9350
9493
  try {
9351
- backend = new JournalDurableBackend(journal, undefined, DEFER_REBUILD, options.ownsJournal ?? true);
9494
+ backend = new JournalDurableBackend(journal, undefined, options.ownsJournal ?? true);
9352
9495
  for (const run of await journal.listRuns())
9353
9496
  for await (const entry of journal.read(run.runId))
9354
9497
  backend.fold(entry);
@@ -9364,21 +9507,31 @@ class JournalDurableBackend {
9364
9507
  throw new StorageUnavailableError({ adapter: "custom", location: "custom journal" }, error instanceof Error ? error : new Error(String(error)));
9365
9508
  }
9366
9509
  }
9367
- serialize(runId, action) {
9368
- const prior = this.pending.get(runId);
9369
- if (prior !== undefined)
9370
- return prior.then(() => this.serialize(runId, action));
9371
- const result = execute(action());
9372
- if (!isPromise(result))
9373
- return result;
9510
+ serialize(runId, action, requiresActiveExecution = true) {
9511
+ try {
9512
+ this.ensureOpen();
9513
+ if (requiresActiveExecution)
9514
+ this.assertExecutionActive(runId);
9515
+ } catch (error) {
9516
+ return Promise.reject(error);
9517
+ }
9518
+ const admitted = new Set([...this.executionContext.getStore()?.values() ?? []].filter((execution) => !execution.retired));
9519
+ return this.enqueue(runId, action, admitted);
9520
+ }
9521
+ enqueue(runId, action, admitted = this.mutationContext.getStore() ?? new Set) {
9522
+ const prior = this.pending.get(runId) ?? Promise.resolve();
9523
+ const result = prior.then(() => this.mutationContext.run(admitted, () => execute(action())));
9374
9524
  const settled = result.then(() => {}, () => {});
9375
9525
  this.pending.set(runId, settled);
9376
- return result.finally(() => {
9526
+ settled.then(() => {
9377
9527
  if (this.pending.get(runId) === settled)
9378
9528
  this.pending.delete(runId);
9379
9529
  });
9530
+ return result;
9380
9531
  }
9381
9532
  fold(entry) {
9533
+ if (entry.seq <= (this.sequences.get(entry.runId) ?? 0))
9534
+ return;
9382
9535
  const event = entry.event;
9383
9536
  if (event.type === RUN_EVENT_TYPES.checkpointRecorded) {
9384
9537
  const checkpoint = event.payload;
@@ -9413,8 +9566,6 @@ class JournalDurableBackend {
9413
9566
  this.sequences.set(entry.runId, entry.seq);
9414
9567
  }
9415
9568
  *entries(runId, fromSeq) {
9416
- if (this.synchronous !== undefined)
9417
- return this.synchronous.readEntries(runId, fromSeq);
9418
9569
  return yield* invoke(async () => {
9419
9570
  const entries = [];
9420
9571
  for await (const entry of this.journal.read(runId, fromSeq))
@@ -9438,7 +9589,7 @@ class JournalDurableBackend {
9438
9589
  }
9439
9590
  *current(runId) {
9440
9591
  this.ensureOpen();
9441
- this.assertExecutionActive(runId);
9592
+ this.assertExecutionActive(runId, true);
9442
9593
  yield* this.refresh(runId);
9443
9594
  if (this.projection.getWorkflow(runId) === undefined)
9444
9595
  return;
@@ -9454,24 +9605,24 @@ class JournalDurableBackend {
9454
9605
  return this.projection.getWorkflow(runId);
9455
9606
  }
9456
9607
  ensureOpen() {
9457
- if (this.closed)
9608
+ if (this.state === "closed" || this.state === "closing" && !this.mutationContext.getStore())
9458
9609
  throw new JournalBackendClosedError;
9459
9610
  }
9460
- assertExecutionActive(runId) {
9461
- for (const execution of this.executionContext.getStore()?.values() ?? [])
9462
- if (execution.retired)
9463
- throw new JournalExecutionRetiredError(runId);
9611
+ assertExecutionActive(runId, admitted = false) {
9612
+ for (const [executionRunId, execution] of this.executionContext.getStore() ?? [])
9613
+ if (execution.retired && !(admitted && this.mutationContext.getStore()?.has(execution)))
9614
+ throw new JournalExecutionRetiredError(typeof runId === "string" ? runId : executionRunId);
9464
9615
  }
9465
9616
  *ownership(runId) {
9466
9617
  this.ensureOpen();
9467
- this.assertExecutionActive(runId);
9618
+ this.assertExecutionActive(runId, true);
9468
9619
  const lost = this.lost.get(runId);
9469
9620
  if (lost)
9470
9621
  throw lost;
9471
9622
  const existing = this.leases.get(runId);
9472
9623
  if (existing)
9473
9624
  return existing;
9474
- 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);
9625
+ const result = yield* invoke(() => this.journal.takeoverExpired(runId, this.holderId, FOREIGN_LIVE_WORKFLOW_WINDOW_MS));
9475
9626
  if (result.status === "held")
9476
9627
  throw new JournalOwnershipError(runId, result.holderId);
9477
9628
  this.leases.set(runId, result.lease);
@@ -9481,7 +9632,7 @@ class JournalDurableBackend {
9481
9632
  }, STAGE_SESSION_HEARTBEAT_INTERVAL_MS);
9482
9633
  this.timer.unref();
9483
9634
  }
9484
- const execution = this.executions.get(runId);
9635
+ const execution = this.executionContext.getStore()?.get(runId) ?? this.executions.get(runId);
9485
9636
  if (execution !== undefined)
9486
9637
  execution.lease = result.lease;
9487
9638
  yield* this.rebuild(runId);
@@ -9493,7 +9644,7 @@ class JournalDurableBackend {
9493
9644
  let failure = new JournalOwnershipError(runId, null, error);
9494
9645
  this.lost.set(runId, failure);
9495
9646
  try {
9496
- const current = yield* invoke(() => this.synchronous !== undefined ? this.synchronous.leaseStateSync(runId) : this.journal.leaseState(runId), this.synchronous !== undefined);
9647
+ const current = yield* invoke(() => this.journal.leaseState(runId));
9497
9648
  failure = new JournalOwnershipError(runId, current?.holderId ?? null, error);
9498
9649
  this.lost.set(runId, failure);
9499
9650
  } catch {}
@@ -9502,8 +9653,8 @@ class JournalDurableBackend {
9502
9653
  *append(runId, event, options) {
9503
9654
  const lease = yield* this.ownership(runId);
9504
9655
  try {
9505
- yield* invoke(() => this.synchronous !== undefined ? this.synchronous.appendSync(lease, event, options) : this.journal.append(lease, event, options), this.synchronous !== undefined);
9506
- yield* this.refresh(runId);
9656
+ const outcome = yield* invoke(() => this.journal.append(lease, event, options));
9657
+ this.fold(outcome.entry);
9507
9658
  } catch (error) {
9508
9659
  if (error instanceof Error)
9509
9660
  throw yield* this.mapOwnership(error, runId);
@@ -9520,11 +9671,11 @@ class JournalDurableBackend {
9520
9671
  draft.registerWorkflow(handle, true);
9521
9672
  return draft;
9522
9673
  }
9523
- registerWorkflow(input) {
9674
+ commitWorkflowRegistration(input) {
9524
9675
  return this.serialize(input.workflowId, () => this.register(input));
9525
9676
  }
9526
9677
  *register(input) {
9527
- this.assertExecutionActive(input.workflowId);
9678
+ this.assertExecutionActive(input.workflowId, true);
9528
9679
  this.ensureOpen();
9529
9680
  const header = {
9530
9681
  runId: input.workflowId,
@@ -9534,7 +9685,7 @@ class JournalDurableBackend {
9534
9685
  status: input.status,
9535
9686
  inputs: input.inputs
9536
9687
  };
9537
- yield* invoke(() => this.synchronous?.createRunSync(header) ?? this.journal.createRun(header), this.synchronous !== undefined);
9688
+ yield* invoke(() => this.journal.createRun(header));
9538
9689
  yield* this.ownership(input.workflowId);
9539
9690
  yield* this.refresh(input.workflowId);
9540
9691
  const draft = yield* this.draft(input.workflowId);
@@ -9545,7 +9696,9 @@ class JournalDurableBackend {
9545
9696
  if (checkpoint.kind === "stage" && checkpoint.topology?.boundary !== undefined && typeof checkpoint.topology.boundary.invocationFingerprint !== "string")
9546
9697
  throw new DurableNestedTopologyError(`missing invocation fingerprint at ${checkpoint.checkpointId}`);
9547
9698
  }
9548
- recordCheckpoint(checkpoint) {
9699
+ commitCheckpoint(checkpoint, options) {
9700
+ if (options?.signal?.aborted)
9701
+ return Promise.reject(new JournalOperationAbortedError(checkpoint.workflowId, options.signal.reason instanceof Error ? options.signal.reason : undefined));
9549
9702
  return this.serialize(checkpoint.workflowId, () => this.checkpoint(checkpoint));
9550
9703
  }
9551
9704
  *checkpoint(checkpoint) {
@@ -9556,14 +9709,9 @@ class JournalDurableBackend {
9556
9709
  key: JSON.stringify([RUN_EVENT_TYPES.checkpointRecorded, checkpoint.kind, checkpoint.checkpointId])
9557
9710
  });
9558
9711
  }
9559
- async recordCheckpointAsync(checkpoint, options) {
9560
- if (options?.signal?.aborted)
9561
- throw new JournalOperationAbortedError(checkpoint.workflowId, options.signal.reason instanceof Error ? options.signal.reason : undefined);
9562
- await this.recordCheckpoint(checkpoint);
9563
- }
9564
- async recordAdditiveCheckpointBestEffort(checkpoint) {
9712
+ async commitAdditiveCheckpointBestEffort(checkpoint) {
9565
9713
  try {
9566
- await this.recordCheckpointAsync(checkpoint);
9714
+ await this.commitCheckpoint(checkpoint);
9567
9715
  return true;
9568
9716
  } catch (error) {
9569
9717
  if (!(error instanceof StorageUnavailableError))
@@ -9572,13 +9720,7 @@ class JournalDurableBackend {
9572
9720
  }
9573
9721
  }
9574
9722
  workflowOwnership(runId) {
9575
- if (this.synchronous !== undefined) {
9576
- const lease = this.synchronous.leaseStateSync(runId);
9577
- if (lease === undefined || isWorkflowLeaseExpired(0, FOREIGN_LIVE_WORKFLOW_WINDOW_MS, lease.ageMs))
9578
- return "available";
9579
- return lease.holderId === this.holderId ? "local" : "foreign";
9580
- }
9581
- return this.serialize(runId, () => this.probeOwnership(runId));
9723
+ return this.serialize(runId, () => this.probeOwnership(runId), false);
9582
9724
  }
9583
9725
  *probeOwnership(runId) {
9584
9726
  this.ensureOpen();
@@ -9587,7 +9729,7 @@ class JournalDurableBackend {
9587
9729
  return "available";
9588
9730
  return lease.holderId === this.holderId ? "local" : "foreign";
9589
9731
  }
9590
- setWorkflowStatus(runId, status, pendingPrompts, resumable, failure) {
9732
+ commitWorkflowStatus(runId, status, pendingPrompts, resumable, failure) {
9591
9733
  return this.serialize(runId, () => this.setStatus(runId, status, pendingPrompts, resumable, failure));
9592
9734
  }
9593
9735
  *setStatus(runId, status, pendingPrompts, resumable, failure) {
@@ -9597,7 +9739,7 @@ class JournalDurableBackend {
9597
9739
  if (handle)
9598
9740
  yield* this.snapshot(handle);
9599
9741
  }
9600
- async transitionWorkflowStatus(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
9742
+ async commitWorkflowStatusTransition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
9601
9743
  return await this.serialize(runId, () => this.transition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner));
9602
9744
  }
9603
9745
  *transition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
@@ -9647,7 +9789,7 @@ class JournalDurableBackend {
9647
9789
  });
9648
9790
  return result;
9649
9791
  }
9650
- adjustPendingPrompts(runId, delta) {
9792
+ commitPendingPromptAdjustment(runId, delta) {
9651
9793
  return this.serialize(runId, () => this.promptChange(runId, delta >= 0 ? RUN_EVENT_TYPES.promptAsked : RUN_EVENT_TYPES.promptReleased, (state) => state.adjust(delta)));
9652
9794
  }
9653
9795
  promptReservationScope(runId) {
@@ -9753,12 +9895,14 @@ class JournalDurableBackend {
9753
9895
  return this.getPendingStageMessageDeliveryCount(runId, messageId, logicalRunId);
9754
9896
  }
9755
9897
  async hydrateWorkflow(runId) {
9756
- await this.serialize(runId, () => this.rebuild(runId));
9898
+ await this.serialize(runId, () => this.rebuild(runId), false);
9757
9899
  }
9758
- async hydrateResumableWorkflows() {
9759
- const runs = await execute(invoke(() => this.journal.listRuns()));
9760
- for (const runId of new Set([...this.sequences.keys(), ...runs.map((run) => run.runId)]))
9761
- await this.hydrateWorkflow(runId);
9900
+ hydrateResumableWorkflows() {
9901
+ return this.serialize(this.catalogQueue, () => invoke(async () => {
9902
+ const runs = await this.journal.listRuns();
9903
+ for (const runId of new Set([...this.sequences.keys(), ...runs.map((run) => run.runId)]))
9904
+ await this.hydrateWorkflow(runId);
9905
+ }));
9762
9906
  }
9763
9907
  async prepareWorkflowCatalog() {
9764
9908
  await this.hydrateResumableWorkflows();
@@ -9767,13 +9911,7 @@ class JournalDurableBackend {
9767
9911
  *deleteOwned(runId, expectSeq) {
9768
9912
  try {
9769
9913
  const lease = yield* this.ownership(runId);
9770
- if (expectSeq !== undefined) {
9771
- const entries = yield* this.entries(runId);
9772
- const actualSeq = entries.at(-1)?.seq ?? 0;
9773
- if (actualSeq !== expectSeq)
9774
- throw new JournalCasConflictError(runId, expectSeq, actualSeq);
9775
- }
9776
- yield* invoke(() => this.journal.deleteOwnedRun(lease));
9914
+ yield* invoke(() => this.journal.deleteOwnedRun(lease, expectSeq));
9777
9915
  } catch (error) {
9778
9916
  if (!(error instanceof RunNotFoundError)) {
9779
9917
  if (error instanceof Error)
@@ -9814,27 +9952,33 @@ class JournalDurableBackend {
9814
9952
  }
9815
9953
  }
9816
9954
  }
9817
- reset() {
9818
- return execute(this.resetJournal());
9955
+ commitReset() {
9956
+ return this.serialize(this.catalogQueue, () => this.resetJournal());
9819
9957
  }
9820
9958
  *resetJournal() {
9821
- const runs = yield* invoke(() => this.synchronous?.listRunsSync() ?? this.journal.listRuns(), this.synchronous !== undefined);
9959
+ const runIds = new Set(this.sequences.keys());
9960
+ const runs = yield* invoke(() => this.journal.listRuns());
9822
9961
  for (const run of runs)
9823
- yield* invoke(() => {
9824
- if (this.synchronous !== undefined)
9825
- return this.synchronous.deleteRunSync(run.runId);
9826
- return this.journal.deleteRun(run.runId);
9827
- }, this.synchronous !== undefined);
9828
- this.projection.reset();
9829
- this.sequences.clear();
9830
- this.leases.clear();
9831
- this.lost.clear();
9832
- this.prompts.clear();
9833
- }
9834
- async renewLeases() {
9962
+ runIds.add(run.runId);
9963
+ for (const runId of runIds)
9964
+ yield this.enqueue(runId, () => this.deleteOwned(runId));
9965
+ }
9966
+ renewLeases() {
9967
+ if (this.renewing !== undefined)
9968
+ return this.renewing;
9969
+ if (this.state !== "open")
9970
+ return Promise.resolve();
9971
+ this.renewing = this.renewOwnedLeases().finally(() => {
9972
+ this.renewing = undefined;
9973
+ });
9974
+ return this.renewing;
9975
+ }
9976
+ async renewOwnedLeases() {
9835
9977
  for (const [runId, lease] of this.leases) {
9978
+ if (this.state !== "open")
9979
+ return;
9836
9980
  try {
9837
- await this.serialize(runId, () => this.renewLease(runId, lease));
9981
+ await this.serialize(runId, () => this.renewLease(runId, lease), false);
9838
9982
  } catch (error) {
9839
9983
  if (error instanceof Error)
9840
9984
  this.lost.set(runId, error);
@@ -9846,11 +9990,7 @@ class JournalDurableBackend {
9846
9990
  if (this.leases.get(runId) !== lease || this.lost.has(runId))
9847
9991
  return;
9848
9992
  try {
9849
- yield* invoke(() => {
9850
- if (this.synchronous !== undefined)
9851
- return this.synchronous.renewSync(lease);
9852
- return this.journal.renew(lease);
9853
- }, this.synchronous !== undefined);
9993
+ yield* invoke(() => this.journal.renew(lease));
9854
9994
  } catch (error) {
9855
9995
  if (this.leases.get(runId) === lease) {
9856
9996
  if (error instanceof Error)
@@ -9903,23 +10043,20 @@ class JournalDurableBackend {
9903
10043
  execution.retired = true;
9904
10044
  if (this.executions.get(runId) === execution)
9905
10045
  this.executions.delete(runId);
9906
- if (execution.lease !== undefined && this.leases.get(runId) === execution.lease)
9907
- return this.serialize(runId, () => this.release(runId));
10046
+ if (this.state !== "open")
10047
+ return this.closing;
10048
+ return this.serialize(runId, () => this.release(runId, execution), false);
9908
10049
  }
9909
10050
  releaseWorkflow(runId) {
9910
10051
  this.assertExecutionActive(runId);
9911
10052
  return this.serialize(runId, () => this.release(runId));
9912
10053
  }
9913
- *release(runId) {
10054
+ *release(runId, execution) {
9914
10055
  const lease = this.leases.get(runId);
9915
- if (lease === undefined)
10056
+ if (lease === undefined || execution !== undefined && execution.lease !== lease)
9916
10057
  return;
9917
10058
  try {
9918
- yield* invoke(() => {
9919
- if (this.synchronous !== undefined)
9920
- return this.synchronous.releaseSync(lease);
9921
- return this.journal.release(lease);
9922
- }, this.synchronous !== undefined);
10059
+ yield* invoke(() => this.journal.release(lease));
9923
10060
  } catch (error) {
9924
10061
  if (!(error instanceof StaleLeaseError))
9925
10062
  throw error;
@@ -9930,31 +10067,38 @@ class JournalDurableBackend {
9930
10067
  dropLease(runId) {
9931
10068
  this.leases.delete(runId);
9932
10069
  if (this.leases.size === 0) {
9933
- clearInterval(this.timer);
10070
+ if (this.timer !== undefined)
10071
+ clearInterval(this.timer);
9934
10072
  this.timer = undefined;
9935
10073
  }
9936
10074
  }
9937
- *releaseAll() {
9938
- for (const runId of this.leases.keys())
9939
- yield* this.release(runId);
9940
- }
9941
- async close() {
10075
+ close() {
10076
+ if (this.closing !== undefined)
10077
+ return this.closing;
10078
+ this.state = "closing";
9942
10079
  if (this.processExitCleanup !== undefined) {
9943
10080
  process.off("exit", this.processExitCleanup);
9944
10081
  this.processExitCleanup = undefined;
9945
10082
  }
9946
- if (this.closed)
9947
- return;
9948
10083
  if (this.timer !== undefined)
9949
10084
  clearInterval(this.timer);
9950
- if (this.pending.size > 0)
9951
- await Promise.all(this.pending.values());
10085
+ this.timer = undefined;
10086
+ this.closing = this.drainAndClose();
10087
+ return this.closing;
10088
+ }
10089
+ async drainAndClose() {
9952
10090
  try {
9953
- const released = execute(this.releaseAll());
9954
- if (isPromise(released))
9955
- await released;
10091
+ await this.renewing;
10092
+ while (this.pending.size > 0)
10093
+ await Promise.all(this.pending.values());
10094
+ for (const runId of this.leases.keys())
10095
+ await execute(this.release(runId));
9956
10096
  } finally {
9957
- this.closed = true;
10097
+ if (this.timer !== undefined)
10098
+ clearInterval(this.timer);
10099
+ this.timer = undefined;
10100
+ this.state = "closed";
10101
+ this.unregisterExecutionStorages();
9958
10102
  if (this.ownsJournal)
9959
10103
  await execute(invoke(() => this.journal.close()));
9960
10104
  }
@@ -9962,24 +10106,25 @@ class JournalDurableBackend {
9962
10106
  }
9963
10107
 
9964
10108
  // dist/builtin/workflows/src/durable/factory.ts
9965
- var DEFAULT_MEMORY_JOURNAL = "memory";
9966
10109
  async function initializeDurableBackend(options = {}) {
9967
10110
  const owner = getDurableBackendProcessOwner();
9968
10111
  const choice = options.journal;
9969
10112
  const selection = selectRunJournal({
9970
10113
  journal: choice,
9971
- settings: choice === undefined ? options.settings ?? SettingsManager.create(options.cwd ?? process.cwd()).getSettings() : undefined
10114
+ settings: choice === undefined ? options.settings ?? SettingsManager.create(options.cwd ?? process.cwd(), getAgentDir3(), {
10115
+ projectTrusted: options.projectTrusted
10116
+ }).getSettings() : undefined
9972
10117
  });
9973
- const key = "createRun" in selection ? selection : ("path" in selection) ? resolve(selection.path) : ("database" in selection) ? selection.database : choice === undefined ? DEFAULT_MEMORY_JOURNAL : choice;
10118
+ const key = "createRun" in selection ? selection : selection.kind === "memory" && choice !== undefined ? choice : storageSelectionKey(selection, getAgentDir3());
9974
10119
  const ownsJournal = choice === undefined || !("createRun" in choice);
9975
10120
  owner.selectedBackends ??= new Map;
9976
10121
  const selected = owner.selectedBackends;
9977
10122
  const existing = selected.get(key);
9978
- let backend;
10123
+ let ready;
9979
10124
  if (existing !== undefined) {
9980
- backend = await existing.ready;
10125
+ ready = existing.ready;
9981
10126
  } else {
9982
- const ready = resolveRunJournal({ journal: selection }).then((journal) => JournalDurableBackend.open(journal, { ownsJournal })).then((opened) => {
10127
+ ready = openSelectedRunJournal(selection).then((journal) => JournalDurableBackend.open(journal, { ownsJournal })).then((opened) => {
9983
10128
  if (ownsJournal)
9984
10129
  opened.closeOnProcessExit();
9985
10130
  entry.close = () => opened.close();
@@ -9990,9 +10135,8 @@ async function initializeDurableBackend(options = {}) {
9990
10135
  });
9991
10136
  const entry = { ready };
9992
10137
  selected.set(key, entry);
9993
- backend = await ready;
9994
10138
  }
9995
- return backend;
10139
+ return withRunJournalConfigSource(selection, () => ready);
9996
10140
  }
9997
10141
 
9998
10142
  // dist/builtin/workflows/src/shared/persistence-restore-helpers.ts
@@ -10656,7 +10800,7 @@ async function recordRunTimingCheckpointAsync(backend, run, options) {
10656
10800
  return false;
10657
10801
  for (const checkpoint of checkpoints)
10658
10802
  if (checkpoint !== undefined)
10659
- await backend.recordCheckpointAsync(checkpoint);
10803
+ await backend.commitCheckpoint(checkpoint);
10660
10804
  return true;
10661
10805
  }
10662
10806
  function runTimingCheckpoint(backend, run, options) {
@@ -10709,17 +10853,17 @@ function inheritedRunElapsedMs(input) {
10709
10853
 
10710
10854
  // dist/builtin/workflows/src/durable/workflow-status-transition.ts
10711
10855
  async function transitionDurableWorkflowStatus(backend, workflowId, expectedStatuses, status, pendingPrompts, resumable) {
10712
- return await backend.transitionWorkflowStatus(workflowId, expectedStatuses, status, pendingPrompts, resumable);
10856
+ return await backend.commitWorkflowStatusTransition(workflowId, expectedStatuses, status, pendingPrompts, resumable);
10713
10857
  }
10714
10858
 
10715
10859
  // dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts
10716
- import { isAbsolute as isAbsolute8, join as join11, resolve as resolve9 } from "node:path";
10860
+ import { isAbsolute as isAbsolute8, join as join11, resolve as resolve8 } from "node:path";
10717
10861
  import { CONFIG_DIR_NAME } from "@bastani/atomic";
10718
10862
 
10719
10863
  // dist/builtin/workflows/src/shared/workflow-artifacts.ts
10720
10864
  import { mkdir, readdir, rm, stat } from "node:fs/promises";
10721
10865
  import { dirname as dirname3, join as join4 } from "node:path";
10722
- import { getAgentDir as getAgentDir3, getEnvValue } from "@bastani/atomic";
10866
+ import { getAgentDir as getAgentDir4, getEnvValue } from "@bastani/atomic";
10723
10867
  // dist/builtin/workflows/src/shared/workflow-artifact-env.ts
10724
10868
  var WORKFLOW_ARTIFACT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
10725
10869
  var ENV_WORKFLOW_ARTIFACT_DIR = "ATOMIC_WORKFLOW_ARTIFACT_DIR";
@@ -10732,7 +10876,7 @@ function workflowArtifactRoot() {
10732
10876
  const override = getEnvValue(ENV_WORKFLOW_ARTIFACT_DIR);
10733
10877
  if (override !== undefined && override.length > 0)
10734
10878
  return override;
10735
- return join4(dirname3(getAgentDir3()), "workflows");
10879
+ return join4(dirname3(getAgentDir4()), "workflows");
10736
10880
  }
10737
10881
  function workflowArtifactRunsRoot() {
10738
10882
  return join4(workflowArtifactRoot(), "runs");
@@ -11996,7 +12140,7 @@ function cleanupWorktrees(setup) {
11996
12140
  }
11997
12141
  // dist/builtin/workflows/src/runs/shared/worktree-cwd.ts
11998
12142
  import { lstatSync as lstatSync4, realpathSync as realpathSync4 } from "node:fs";
11999
- import { dirname as dirname8, isAbsolute as isAbsolute6, relative as relative4, resolve as resolve7, sep as sep5 } from "node:path";
12143
+ import { dirname as dirname8, isAbsolute as isAbsolute6, relative as relative4, resolve as resolve6, sep as sep5 } from "node:path";
12000
12144
  function relativePathWithin(root, candidate) {
12001
12145
  const path = relative4(root, candidate);
12002
12146
  return path === ".." || path.startsWith(`..${sep5}`) || isAbsolute6(path) ? undefined : path;
@@ -12015,14 +12159,14 @@ function resolveWorktreeStageCwd(cwd, setup) {
12015
12159
  if (cwd === undefined || cwd.length === 0)
12016
12160
  return;
12017
12161
  const absoluteInput = isAbsolute6(cwd);
12018
- const candidate = absoluteInput ? cwd : resolve7(setup.cwd, cwd);
12162
+ const candidate = absoluteInput ? cwd : resolve6(setup.cwd, cwd);
12019
12163
  if (!absoluteInput && relativePathWithin(setup.worktreeRoot, candidate) === undefined) {
12020
12164
  throw new Error(`atomic-workflows: relative cwd ${cwd} escapes gitWorktreeDir ${setup.worktreeRoot}; choose a cwd inside the worktree.`);
12021
12165
  }
12022
12166
  const candidateRealPath = existingRealPath(candidate, "cwd");
12023
12167
  const worktreeRelative = relativePathWithin(worktreeRoot, candidateRealPath);
12024
12168
  if (worktreeRelative !== undefined)
12025
- return resolve7(setup.worktreeRoot, worktreeRelative);
12169
+ return resolve6(setup.worktreeRoot, worktreeRelative);
12026
12170
  if (!isAbsolute6(cwd)) {
12027
12171
  throw new Error(`atomic-workflows: relative cwd ${cwd} escapes gitWorktreeDir ${setup.worktreeRoot}; choose a path that remains inside the selected worktree.`);
12028
12172
  }
@@ -12033,7 +12177,7 @@ function resolveWorktreeStageCwd(cwd, setup) {
12033
12177
  if (repositoryRelative === undefined) {
12034
12178
  throw new Error(`atomic-workflows: cwd ${cwd} is outside gitWorktreeDir ${setup.worktreeRoot}; use a cwd inside the invoking repository so Atomic can remap it, or omit cwd.`);
12035
12179
  }
12036
- const mappedCwd = resolve7(setup.worktreeRoot, repositoryRelative);
12180
+ const mappedCwd = resolve6(setup.worktreeRoot, repositoryRelative);
12037
12181
  const mappedRealPath = existingRealPath(mappedCwd, "remapped worktree cwd");
12038
12182
  if (relativePathWithin(worktreeRoot, mappedRealPath) === undefined) {
12039
12183
  throw new Error(`atomic-workflows: cwd ${cwd} remaps through a path that resolves outside gitWorktreeDir ${setup.worktreeRoot}; remove the escaping symlink or omit cwd.`);
@@ -12043,7 +12187,7 @@ function resolveWorktreeStageCwd(cwd, setup) {
12043
12187
 
12044
12188
  // dist/builtin/workflows/src/runs/foreground/executor-task-prompts.ts
12045
12189
  import { existsSync as existsSync3 } from "node:fs";
12046
- import { isAbsolute as isAbsolute7, resolve as resolve8 } from "node:path";
12190
+ import { isAbsolute as isAbsolute7, resolve as resolve7 } from "node:path";
12047
12191
  function normalizeTaskContexts(previous) {
12048
12192
  if (previous === undefined)
12049
12193
  return [];
@@ -12096,7 +12240,7 @@ function taskPrevious(options) {
12096
12240
  function resolveWorkflowPath(filePath, baseDir) {
12097
12241
  if (isAbsolute7(filePath))
12098
12242
  return filePath;
12099
- return resolve8(baseDir ?? process.cwd(), filePath);
12243
+ return resolve7(baseDir ?? process.cwd(), filePath);
12100
12244
  }
12101
12245
  function taskBaseDir(options) {
12102
12246
  if (typeof options.chainDir === "string" && options.chainDir.trim().length > 0) {
@@ -12396,7 +12540,7 @@ function workflowInvocationMetadata(inputDefaults, workflowInvocationCwd, cache,
12396
12540
  function resolvedTaskCwd(cwd, workflowInvocationCwd) {
12397
12541
  if (cwd === undefined)
12398
12542
  return;
12399
- return isAbsolute8(cwd) ? cwd : resolve9(workflowInvocationCwd, cwd);
12543
+ return isAbsolute8(cwd) ? cwd : resolve8(workflowInvocationCwd, cwd);
12400
12544
  }
12401
12545
  function taskWorktreeOutputsRoot(runId) {
12402
12546
  return join11(workflowArtifactRunPath(runId), "task-outputs");
@@ -12409,7 +12553,7 @@ function prepareTaskWorktrees(tasks, options, runId, scope, workflowInvocationCw
12409
12553
  throw new Error("atomic-workflows: worktree and gitWorktreeDir are mutually exclusive; use gitWorktreeDir for a reusable worktree or worktree:true for temporary isolated worktrees.");
12410
12554
  }
12411
12555
  const explicitCwd = tasks.find((task) => typeof task.cwd === "string")?.cwd;
12412
- const sharedCwd = explicitCwd === undefined ? workflowInvocationCwd : isAbsolute8(explicitCwd) ? explicitCwd : resolve9(workflowInvocationCwd, explicitCwd);
12556
+ const sharedCwd = explicitCwd === undefined ? workflowInvocationCwd : isAbsolute8(explicitCwd) ? explicitCwd : resolve8(workflowInvocationCwd, explicitCwd);
12413
12557
  const conflict = findWorktreeTaskCwdConflict(tasks.map((task) => ({ agent: task.name, cwd: resolvedTaskCwd(task.cwd, workflowInvocationCwd) })), sharedCwd);
12414
12558
  if (conflict !== undefined)
12415
12559
  throw new Error(formatWorktreeTaskCwdConflict(conflict, sharedCwd));
@@ -13793,6 +13937,19 @@ function createStageScheduler(input) {
13793
13937
  function createStageControlRegistry() {
13794
13938
  const _byRun = new Map;
13795
13939
  const pendingDisposals = new Set;
13940
+ const sessionStores = new Map;
13941
+ let generation = 0;
13942
+ function rememberSessionStore(handle) {
13943
+ const store = handle.sessionStore;
13944
+ if (store === undefined)
13945
+ return;
13946
+ let stores = sessionStores.get(handle.runId);
13947
+ if (stores === undefined) {
13948
+ stores = new Map;
13949
+ sessionStores.set(handle.runId, stores);
13950
+ }
13951
+ stores.set(handle.stageId, store);
13952
+ }
13796
13953
  function ensureRun(runId) {
13797
13954
  let runMap = _byRun.get(runId);
13798
13955
  if (!runMap) {
@@ -13880,7 +14037,11 @@ function createStageControlRegistry() {
13880
14037
  };
13881
14038
  }
13882
14039
  return {
14040
+ get generation() {
14041
+ return generation;
14042
+ },
13883
14043
  register(handle) {
14044
+ rememberSessionStore(handle);
13884
14045
  const runMap = ensureRun(handle.runId);
13885
14046
  const displaced = runMap.get(handle.stageId);
13886
14047
  runMap.set(handle.stageId, {
@@ -13897,6 +14058,7 @@ function createStageControlRegistry() {
13897
14058
  if (!existing)
13898
14059
  return;
13899
14060
  if (existing.get(handle.stageId)?.handle === handle) {
14061
+ rememberSessionStore(handle);
13900
14062
  existing.delete(handle.stageId);
13901
14063
  }
13902
14064
  if (existing.size === 0)
@@ -13982,6 +14144,7 @@ function createStageControlRegistry() {
13982
14144
  return false;
13983
14145
  if (handle !== undefined && entry.handle !== handle)
13984
14146
  return false;
14147
+ rememberSessionStore(entry.handle);
13985
14148
  if (!entry.controlsDependencies)
13986
14149
  return false;
13987
14150
  entry.controlsDependencies = false;
@@ -13999,6 +14162,9 @@ function createStageControlRegistry() {
13999
14162
  get(runId, stageId) {
14000
14163
  return _byRun.get(runId)?.get(stageId)?.handle;
14001
14164
  },
14165
+ getSessionStore(runId, stageId) {
14166
+ return _byRun.get(runId)?.get(stageId)?.handle.sessionStore ?? sessionStores.get(runId)?.get(stageId);
14167
+ },
14002
14168
  forRun(runId) {
14003
14169
  const runMap = _byRun.get(runId);
14004
14170
  if (!runMap)
@@ -14011,17 +14177,28 @@ function createStageControlRegistry() {
14011
14177
  run(runId) {
14012
14178
  return makeRunHandle(runId);
14013
14179
  },
14014
- async clear() {
14015
- const entries = [..._byRun.values()].flatMap((runMap) => [...runMap.values()]);
14016
- _byRun.clear();
14180
+ async clear(runId) {
14181
+ if (runId === undefined)
14182
+ generation += 1;
14183
+ const entries = runId === undefined ? [..._byRun.values()].flatMap((runMap) => [...runMap.values()]) : [..._byRun.get(runId)?.values() ?? []];
14184
+ if (runId === undefined) {
14185
+ _byRun.clear();
14186
+ sessionStores.clear();
14187
+ } else {
14188
+ _byRun.get(runId)?.clear();
14189
+ _byRun.delete(runId);
14190
+ sessionStores.delete(runId);
14191
+ }
14017
14192
  await disposeEntries(entries);
14018
14193
  },
14019
14194
  async clearDetached() {
14020
14195
  const entries = [];
14196
+ generation += 1;
14021
14197
  for (const [runId, runMap] of [..._byRun]) {
14022
14198
  for (const [stageId, entry] of [...runMap]) {
14023
14199
  if (entry.controlsDependencies)
14024
14200
  continue;
14201
+ rememberSessionStore(entry.handle);
14025
14202
  runMap.delete(stageId);
14026
14203
  entries.push(entry);
14027
14204
  }
@@ -14648,7 +14825,7 @@ function createTaskPrimitive(runtime) {
14648
14825
  }
14649
14826
  });
14650
14827
  const stage = stageHandle.context;
14651
- const promptText = resolvedTaskOptions.resumeFromSessionFile !== undefined ? RESUME_CONTINUATION_PROMPT : applyTaskContext(`${taskReadInstruction(resolvedTaskOptions)}${taskPrompt(resolvedTaskOptions)}`, taskPrevious(resolvedTaskOptions));
14828
+ const promptText = resolvedTaskOptions.resumeFromSessionId !== undefined ? RESUME_CONTINUATION_PROMPT : applyTaskContext(`${taskReadInstruction(resolvedTaskOptions)}${taskPrompt(resolvedTaskOptions)}`, taskPrevious(resolvedTaskOptions));
14652
14829
  const rawOutput = await stage.prompt(promptText, taskPromptOptions(resolvedTaskOptions));
14653
14830
  const structured = typeof rawOutput === "string" ? undefined : rawOutput;
14654
14831
  const text = truncateTaskOutput(structuredTaskOutputText(rawOutput), resolvedTaskOptions.maxOutput);
@@ -14738,6 +14915,7 @@ function wrapUiWithDurable(base, deps) {
14738
14915
  response,
14739
14916
  completedAt: Date.now()
14740
14917
  };
14918
+ await deps.beforeCheckpoint?.();
14741
14919
  await recordCheckpointDurably(deps.backend, checkpoint);
14742
14920
  };
14743
14921
  const cached = (identity) => deps.backend.getUiResponse(deps.workflowId, identity.hash);
@@ -15154,7 +15332,7 @@ async function finalizeDurableTerminalStatus(input) {
15154
15332
  ...input.runSnapshot.failureDisposition !== undefined ? { failureDisposition: input.runSnapshot.failureDisposition } : {},
15155
15333
  ...input.runSnapshot.failedToolNodeId !== undefined ? { failedToolNodeId: input.runSnapshot.failedToolNodeId } : {}
15156
15334
  } : undefined;
15157
- await input.durableBackend.setWorkflowStatus(input.runId, durableStatus, undefined, input.runSnapshot.resumable, failure);
15335
+ await input.durableBackend.commitWorkflowStatus(input.runId, durableStatus, undefined, input.runSnapshot.resumable, failure);
15158
15336
  }
15159
15337
  }
15160
15338
  function toDurableStatus(status) {
@@ -15259,7 +15437,7 @@ async function recordWorkflowHeartbeatAnchor(backend, record) {
15259
15437
  output: { anchorAt: record.anchorAt, intervalMinutes: record.intervalMinutes },
15260
15438
  completedAt: record.now
15261
15439
  };
15262
- const stored = await backend.recordAdditiveCheckpointBestEffort(checkpoint);
15440
+ const stored = await backend.commitAdditiveCheckpointBestEffort(checkpoint);
15263
15441
  if (!stored)
15264
15442
  return false;
15265
15443
  return readWorkflowHeartbeatAnchor(backend, record.runId) !== undefined;
@@ -15289,6 +15467,60 @@ function createDurableStageSessionRecorder(input) {
15289
15467
  };
15290
15468
  }
15291
15469
 
15470
+ // dist/builtin/workflows/src/shared/stage-session-store.ts
15471
+ import { randomUUID as randomUUID6 } from "node:crypto";
15472
+ import { dirname as dirname9, resolve as resolve9 } from "node:path";
15473
+ import {
15474
+ JsonlSessionStore,
15475
+ resolveSessionStore,
15476
+ SessionManager
15477
+ } from "@bastani/atomic";
15478
+ async function stageSessionStore(options, defaultSessionDir) {
15479
+ if (options.sessionStore !== undefined)
15480
+ return options.sessionStore;
15481
+ if (options.sessionManager !== undefined)
15482
+ return options.sessionManager.getSessionStore();
15483
+ const directory = options.sessionDir ?? defaultSessionDir;
15484
+ if (directory !== undefined)
15485
+ return JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false });
15486
+ return resolveSessionStore(options.cwd ?? process.cwd(), {
15487
+ agentDir: options.agentDir,
15488
+ settings: options.settingsManager?.getSettings()
15489
+ });
15490
+ }
15491
+ async function forkStageSession(store, sessionId, cwd, options, destination = store) {
15492
+ const source = await store.load(sessionId);
15493
+ const id = randomUUID6();
15494
+ await destination.create({
15495
+ id,
15496
+ version: 4,
15497
+ createdAt: new Date().toISOString(),
15498
+ cwd,
15499
+ parentSessionId: sessionId,
15500
+ ...options.internal === true ? { internal: true } : {},
15501
+ ...options.workflow === undefined ? {} : { workflow: options.workflow }
15502
+ }, source.entries);
15503
+ return SessionManager.open(destination, id, cwd);
15504
+ }
15505
+ async function migrateLegacyStageSession(store, sessionId, sessionFile) {
15506
+ if (sessionFile === undefined || await store.readHeader(sessionId) !== undefined)
15507
+ return;
15508
+ const location = resolve9(sessionFile);
15509
+ const legacy = await JsonlSessionStore.open(dirname9(location), { exactDirectory: true, scanExisting: false });
15510
+ try {
15511
+ for await (const file of legacy.scanFiles()) {
15512
+ if (resolve9(file.location) !== location || file.header.id !== sessionId)
15513
+ continue;
15514
+ const snapshot = await file.read();
15515
+ if (await store.readHeader(sessionId) === undefined)
15516
+ await store.create(snapshot.header, snapshot.entries);
15517
+ return;
15518
+ }
15519
+ } finally {
15520
+ await legacy.close();
15521
+ }
15522
+ }
15523
+
15292
15524
  // dist/builtin/workflows/src/durable/completed-catalog-stage-groups.ts
15293
15525
  function validBoundaryRecordSet(checkpoints, strict) {
15294
15526
  const stages = checkpoints.filter((item) => item.kind === "stage");
@@ -15665,9 +15897,6 @@ var SESSION_KEY6 = "workflows:job-tracker:v1";
15665
15897
  var singleton6 = createSessionScopedSingleton(SESSION_KEY6, createJobTracker);
15666
15898
  var jobTracker = singleton6.facade;
15667
15899
 
15668
- // dist/builtin/workflows/src/durable/fork-workflow.ts
15669
- import { SessionManager as SessionManager2 } from "@bastani/atomic";
15670
-
15671
15900
  // dist/builtin/workflows/src/shared/workflow-stage-target.ts
15672
15901
  var WORKFLOW_RUN_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
15673
15902
  var WORKFLOW_TARGET_PREFIX = "workflow:";
@@ -16060,6 +16289,7 @@ function createDurableStageDeps(input) {
16060
16289
  backend: input.backend,
16061
16290
  nextCheckpointId: input.nextCheckpointId,
16062
16291
  nextReplayKey: input.nextReplayKey,
16292
+ beforeCheckpoint: input.beforeCheckpoint,
16063
16293
  replayKeyForCompletedStage: (stage) => input.completedReplayKeys.get(stage.id),
16064
16294
  runTopology: durableRunTopology(input.run),
16065
16295
  sourceOrderForStage: (stage) => {
@@ -16110,7 +16340,8 @@ function createDurableStageTopologyResolver(backend, workflowId) {
16110
16340
  async function recordDurableActiveStage(deps, stage) {
16111
16341
  if (stage.replayKey === undefined || stage.status === "completed" || stage.status === "failed" || stage.status === "skipped")
16112
16342
  return false;
16113
- await deps.backend.recordCheckpointAsync({
16343
+ await deps.beforeCheckpoint?.();
16344
+ await deps.backend.commitCheckpoint({
16114
16345
  kind: "stage",
16115
16346
  workflowId: deps.workflowId,
16116
16347
  checkpointId: `stage-active-meta:${durableHash({ replayKey: stage.replayKey, stageId: stage.id })}`,
@@ -16143,7 +16374,7 @@ function createDurableCachedStageRecorder(input) {
16143
16374
  input.run.stages.sort((left, right) => (replaySourceOrders.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (replaySourceOrders.get(right.id) ?? Number.MAX_SAFE_INTEGER));
16144
16375
  }
16145
16376
  const stage = input.store.runs().find((run) => run.id === input.run.id)?.stages.find((candidate) => candidate.replayKey === replayKey);
16146
- const persistence = stage === undefined ? undefined : input.backend.recordCheckpoint({
16377
+ const persistence = stage === undefined ? undefined : input.backend.commitCheckpoint({
16147
16378
  kind: "stage",
16148
16379
  workflowId: input.run.id,
16149
16380
  checkpointId: `stage-replay-meta:${durableHash({ replayKey, stageId: stage.id, parentIds: stage.parentIds })}`,
@@ -16458,6 +16689,9 @@ function createAdmittedToolExecutionTracker(options = {}) {
16458
16689
  await drainRecordedFailures();
16459
16690
  };
16460
16691
  return {
16692
+ get closed() {
16693
+ return state === "CLOSED" || options.signal?.aborted === true;
16694
+ },
16461
16695
  track(execution) {
16462
16696
  if (state === "CLOSED" || options.signal?.aborted) {
16463
16697
  const error = new Error("atomic-workflows: ctx.tool admission is closed for this run");
@@ -16633,6 +16867,13 @@ function createTrackedToolPrimitive(input) {
16633
16867
  });
16634
16868
  const lifecycle = createToolNodeLifecycle(input);
16635
16869
  const budgetBoundary = input.budget.enabled ? () => input.budget.stopAtBoundaryAsync(input.run.stages.at(-1)?.name) : undefined;
16870
+ const assertToolAdmissionOpen = () => {
16871
+ const quit = input.toolAdmission.quitReason;
16872
+ if (quit !== undefined) {
16873
+ observedQuit ??= quit;
16874
+ throw quit;
16875
+ }
16876
+ };
16636
16877
  const tool = createToolPrimitive({
16637
16878
  workflowId: input.workflowId,
16638
16879
  ...input.checkpointSourceWorkflowId === undefined ? {} : { checkpointSourceWorkflowId: input.checkpointSourceWorkflowId },
@@ -16666,7 +16907,16 @@ function createTrackedToolPrimitive(input) {
16666
16907
  observedQuit ??= admission.error;
16667
16908
  return admission;
16668
16909
  },
16669
- ...budgetBoundary !== undefined ? { beforeToolCall: budgetBoundary, afterToolCall: budgetBoundary } : {},
16910
+ beforeToolCall: () => {
16911
+ const afterDrain = () => {
16912
+ const budget = budgetBoundary?.();
16913
+ return budget === undefined ? assertToolAdmissionOpen() : budget.then(assertToolAdmissionOpen);
16914
+ };
16915
+ const pending = input.beforeToolCall?.();
16916
+ return pending === undefined ? afterDrain() : pending.then(afterDrain);
16917
+ },
16918
+ beforeCheckpoint: input.beforeCheckpoint,
16919
+ ...budgetBoundary !== undefined ? { afterToolCall: budgetBoundary } : {},
16670
16920
  ...lifecycle
16671
16921
  });
16672
16922
  const abandonInFlightAsCancelled = (reason) => {
@@ -17572,12 +17822,12 @@ class StageToolExecutionBuffer {
17572
17822
  function createStageControlHandle(runtime) {
17573
17823
  const messagePreparation = () => {
17574
17824
  const meta = runtime.innerCtx.__sessionMeta();
17575
- if (meta.sessionId !== undefined || meta.sessionFile !== undefined) {
17825
+ if (meta.sessionId !== undefined) {
17576
17826
  return { beforePreparation: runtime.throwIfStageMutationBlocked };
17577
17827
  }
17578
- if (runtime.stageSnapshot.sessionFile !== undefined) {
17828
+ if (runtime.stageSnapshot.sessionId !== undefined) {
17579
17829
  return {
17580
- sessionFile: runtime.stageSnapshot.sessionFile,
17830
+ sessionId: runtime.stageSnapshot.sessionId,
17581
17831
  beforePreparation: runtime.throwIfStageMutationBlocked
17582
17832
  };
17583
17833
  }
@@ -17587,10 +17837,10 @@ function createStageControlHandle(runtime) {
17587
17837
  return { beforePreparation: runtime.throwIfStageMutationBlocked };
17588
17838
  };
17589
17839
  const ensureMessagingSession = async () => {
17590
- const sessionFile = messagePreparation().sessionFile;
17591
- if (sessionFile === undefined)
17840
+ const sessionId = messagePreparation().sessionId;
17841
+ if (sessionId === undefined)
17592
17842
  return;
17593
- await runtime.innerCtx.__ensureSessionFromFile(sessionFile);
17843
+ await runtime.innerCtx.__ensureSessionFromId(sessionId);
17594
17844
  await runtime.captureStageSessionMeta({ awaitDurable: true });
17595
17845
  };
17596
17846
  const toolExecutions = new StageToolExecutionBuffer;
@@ -17606,6 +17856,9 @@ function createStageControlHandle(runtime) {
17606
17856
  get status() {
17607
17857
  return runtime.stageSnapshot.status;
17608
17858
  },
17859
+ get sessionStore() {
17860
+ return runtime.innerCtx.__agentSession()?.sessionManager.getSessionStore();
17861
+ },
17609
17862
  get sessionId() {
17610
17863
  return runtime.innerCtx.__sessionMeta().sessionId ?? runtime.stageSnapshot.sessionId;
17611
17864
  },
@@ -17894,7 +18147,7 @@ function createReplayStageContext(input) {
17894
18147
  __getLastAssistantText: () => replayResult,
17895
18148
  getLastAssistantText: () => replayResult,
17896
18149
  __ensureSession: async () => {},
17897
- __ensureSessionFromFile: async () => {},
18150
+ __ensureSessionFromId: async () => {},
17898
18151
  __sealGeneration: () => {},
17899
18152
  __closeGeneration: async () => {},
17900
18153
  __sessionMeta: () => ({ sessionId: replaySource.sessionId, sessionFile: replaySource.sessionFile }),
@@ -17917,7 +18170,7 @@ function createReplayStageContext(input) {
17917
18170
  }
17918
18171
 
17919
18172
  // dist/builtin/workflows/src/shared/pending-stage-route-capability.ts
17920
- import { randomUUID as randomUUID6 } from "node:crypto";
18173
+ import { randomUUID as randomUUID7 } from "node:crypto";
17921
18174
  var routeCapabilitiesKey = Symbol.for("atomic-workflows/pending-stage-route-capabilities@1");
17922
18175
  var processState = globalThis;
17923
18176
  var routeCapabilities = processState[routeCapabilitiesKey] ?? new WeakMap;
@@ -17930,7 +18183,7 @@ function workflowPendingStageRouteCapability(store, runId) {
17930
18183
  }
17931
18184
  let capability = capabilities.get(runId);
17932
18185
  if (capability === undefined) {
17933
- capability = randomUUID6();
18186
+ capability = randomUUID7();
17934
18187
  capabilities.set(runId, capability);
17935
18188
  }
17936
18189
  return capability;
@@ -18987,7 +19240,7 @@ function assistantMessage(text) {
18987
19240
  }
18988
19241
 
18989
19242
  // dist/builtin/workflows/src/runs/foreground/stage-runner-options.ts
18990
- import { SessionManager as SessionManager3 } from "@bastani/atomic";
19243
+ import { SessionManager as SessionManager2 } from "@bastani/atomic";
18991
19244
  function workflowSessionOptions(meta) {
18992
19245
  return {
18993
19246
  internal: true,
@@ -19012,7 +19265,7 @@ async function stripWorkflowOnlyOptions2(options, defaultSessionDir, meta, pendi
19012
19265
  if (!options) {
19013
19266
  return defaultSessionDir === undefined ? { orchestrationContext } : {
19014
19267
  orchestrationContext,
19015
- sessionManager: await SessionManager3.create(process.cwd(), defaultSessionDir, classification)
19268
+ sessionManager: await SessionManager2.create(process.cwd(), defaultSessionDir, classification)
19016
19269
  };
19017
19270
  }
19018
19271
  const {
@@ -19024,8 +19277,10 @@ async function stripWorkflowOnlyOptions2(options, defaultSessionDir, meta, pendi
19024
19277
  inheritedModelConstraints: _inheritedModelConstraints,
19025
19278
  routerSelection: _routerSelection,
19026
19279
  context,
19027
- forkFromSessionFile,
19028
- resumeFromSessionFile,
19280
+ forkFromSessionId,
19281
+ resumeFromSessionId,
19282
+ resumeFromLegacySessionFile,
19283
+ sessionStore,
19029
19284
  durableReplayKey: _durableReplayKey,
19030
19285
  durableAccumulatedDurationMs: _durableAccumulatedDurationMs,
19031
19286
  durableStageId: _durableStageId,
@@ -19037,15 +19292,18 @@ async function stripWorkflowOnlyOptions2(options, defaultSessionDir, meta, pendi
19037
19292
  group: _group,
19038
19293
  ...sessionOptions
19039
19294
  } = options;
19040
- if (sessionOptions.sessionManager === undefined) {
19041
- const cwd = sessionOptions.cwd ?? process.cwd();
19042
- const effectiveSessionDir = sessionDir ?? defaultSessionDir;
19043
- if (resumeFromSessionFile !== undefined) {
19044
- sessionOptions.sessionManager = await SessionManager3.open(resumeFromSessionFile, effectiveSessionDir, cwd);
19045
- } else if (context === "fork" && forkFromSessionFile !== undefined) {
19046
- sessionOptions.sessionManager = await SessionManager3.forkFrom(forkFromSessionFile, cwd, effectiveSessionDir, classification);
19047
- } else if (effectiveSessionDir !== undefined) {
19048
- sessionOptions.sessionManager = await SessionManager3.create(cwd, effectiveSessionDir, classification);
19295
+ const cwd = sessionOptions.cwd ?? process.cwd();
19296
+ if (resumeFromSessionId !== undefined) {
19297
+ const store = await stageSessionStore(options, defaultSessionDir);
19298
+ await migrateLegacyStageSession(store, resumeFromSessionId, resumeFromLegacySessionFile);
19299
+ sessionOptions.sessionManager = await SessionManager2.open(store, resumeFromSessionId, cwd);
19300
+ } else if (context === "fork" && forkFromSessionId !== undefined) {
19301
+ sessionOptions.sessionManager = await forkStageSession(await stageSessionStore(options, defaultSessionDir), forkFromSessionId, cwd, classification);
19302
+ } else if (sessionOptions.sessionManager === undefined) {
19303
+ if (sessionStore !== undefined) {
19304
+ sessionOptions.sessionManager = await SessionManager2.create(sessionStore, cwd, classification);
19305
+ } else if ((sessionDir ?? defaultSessionDir) !== undefined) {
19306
+ sessionOptions.sessionManager = await SessionManager2.create(cwd, sessionDir ?? defaultSessionDir, classification);
19049
19307
  }
19050
19308
  }
19051
19309
  return {
@@ -19612,7 +19870,7 @@ class StageSessionController {
19612
19870
  sessionPromise;
19613
19871
  sessionShutdownPromise;
19614
19872
  bindingCleanupFailure;
19615
- reattachSessionFile;
19873
+ reattachSessionId;
19616
19874
  lastPromptStartIndex;
19617
19875
  attemptUsageStartIndex;
19618
19876
  discardedAttemptUsage = {
@@ -19868,9 +20126,9 @@ class StageSessionController {
19868
20126
  const ready = waitForStageStartup(this.sessionPromise, this.startupWait.signal);
19869
20127
  return this.modelRoute ? this.checkedSession(await ready) : ready;
19870
20128
  }
19871
- async ensureSessionFromFile(sessionFile, consumer = "prompt") {
20129
+ async ensureSessionFromId(sessionId, consumer = "prompt") {
19872
20130
  if (!this.sessionShutdownPromise && !this.sessionPromise && !this.session)
19873
- this.reattachSessionFile = sessionFile;
20131
+ this.reattachSessionId = sessionId;
19874
20132
  const session = await this.ensureSession(consumer);
19875
20133
  await session.closeWorkflowStageGeneration?.();
19876
20134
  return session;
@@ -19883,12 +20141,12 @@ class StageSessionController {
19883
20141
  return pausedDelivery;
19884
20142
  }
19885
20143
  preparation?.beforePreparation?.();
19886
- const sessionFile = preparation?.sessionFile;
20144
+ const sessionId = preparation?.sessionId;
19887
20145
  const deliver = async (activity) => {
19888
20146
  if (this.effectiveStageOptions?.model === "auto")
19889
20147
  await this.preparePrompt(typeof content === "string" ? content : content.filter((part) => part.type === "text").map((part) => part.text).join(`
19890
20148
  `));
19891
- const activeSession = sessionFile === undefined ? await this.ensureSession("prompt") : await this.ensureSessionFromFile(sessionFile, "prompt");
20149
+ const activeSession = sessionId === undefined ? await this.ensureSession("prompt") : await this.ensureSessionFromId(sessionId, "prompt");
19892
20150
  const pausedDelivery = this.pauseControl.deferRunnerOwnedDelivery(() => sendStageUserMessage(activeSession, content, options, beforeDelivery, release, this.messageAdmission, activity));
19893
20151
  if (pausedDelivery !== undefined) {
19894
20152
  release();
@@ -19896,7 +20154,7 @@ class StageSessionController {
19896
20154
  }
19897
20155
  return sendStageUserMessage(activeSession, content, options, beforeDelivery, release, this.messageAdmission, activity);
19898
20156
  };
19899
- if (this.session === undefined || sessionFile !== undefined)
20157
+ if (this.session === undefined || sessionId !== undefined)
19900
20158
  return this.deliveryActivity.runWithLease(() => deliver());
19901
20159
  return deliver(this.deliveryActivity);
19902
20160
  });
@@ -20436,7 +20694,7 @@ class StageSessionController {
20436
20694
  if (first === undefined) {
20437
20695
  return this.createSessionObservingPause(undefined, consumer).catch((error) => this.createInitialSessionWithRetry(undefined, consumer, { error }));
20438
20696
  }
20439
- if (this.reattachSessionFile !== undefined) {
20697
+ if (this.reattachSessionId !== undefined) {
20440
20698
  const resumed = await this.createSession(undefined, consumer, { restoreSavedModel: true });
20441
20699
  const restoredId = workflowModelId(resumed.model);
20442
20700
  const exactRestoredIndex = restoredId === undefined ? -1 : candidates.findIndex((entry) => entry.id === restoredId && entry.reasoningLevel === resumed.thinkingLevel);
@@ -20659,7 +20917,7 @@ class StageSessionController {
20659
20917
  ownsFallbackChain: this.hasExplicitModelFallbackConfig,
20660
20918
  scopedModels,
20661
20919
  restoreSavedModel: resumeOptions?.restoreSavedModel,
20662
- reattachSessionFile: this.reattachSessionFile,
20920
+ reattachSessionId: this.reattachSessionId,
20663
20921
  sharedModelRuntime: this.sharedModelRuntime,
20664
20922
  defaultCwd: this.opts.defaultCwd
20665
20923
  });
@@ -21008,7 +21266,7 @@ class StageSessionController {
21008
21266
  // dist/builtin/workflows/src/runs/foreground/stage-runner-output.ts
21009
21267
  import { createHash as createHash3 } from "node:crypto";
21010
21268
  import { mkdir as mkdir2, writeFile } from "node:fs/promises";
21011
- import { basename as basename5, dirname as dirname9, isAbsolute as isAbsolute9, join as join12, resolve as resolve10 } from "node:path";
21269
+ import { basename as basename5, dirname as dirname10, isAbsolute as isAbsolute9, join as join12, resolve as resolve10 } from "node:path";
21012
21270
  var DEFAULT_MAX_OUTPUT_BYTES = 200 * 1024;
21013
21271
  var DEFAULT_MAX_OUTPUT_LINES = 5000;
21014
21272
  function normalizeMaxOutput2(maxOutput) {
@@ -21193,7 +21451,7 @@ async function finalizePromptOutput(fullOutput, outputOptions, runtimeCwd, runId
21193
21451
  const transcriptFile = transcriptPath(runId, outputPath);
21194
21452
  const transcript = renderTranscript(messages, fullOutput);
21195
21453
  try {
21196
- await mkdir2(dirname9(outputPath), { recursive: true });
21454
+ await mkdir2(dirname10(outputPath), { recursive: true });
21197
21455
  await writeFile(outputPath, fullOutput, "utf8");
21198
21456
  } catch (err) {
21199
21457
  return `${displayOutput}
@@ -21205,7 +21463,7 @@ ${err instanceof Error ? err.message : String(err)}`;
21205
21463
  let transcriptError;
21206
21464
  try {
21207
21465
  await ensureWorkflowArtifactRunDirectory(runId);
21208
- await mkdir2(dirname9(transcriptFile), { recursive: true });
21466
+ await mkdir2(dirname10(transcriptFile), { recursive: true });
21209
21467
  await writeFile(transcriptFile, transcript, "utf8");
21210
21468
  transcriptAvailable = true;
21211
21469
  } catch (err) {
@@ -21228,7 +21486,7 @@ function createStageContext2(opts) {
21228
21486
  const stageCwd = stageOptions?.cwd ?? stageOptions?.sessionManager?.getCwd() ?? agentSessionAdapterDefaultCwd(adapters.agentSession) ?? opts.defaultCwd ?? process.cwd();
21229
21487
  const structuredOutputCapture = stageOptions?.schema ? createStructuredOutputCapture() : undefined;
21230
21488
  const structuredOutputExecutionCapture = stageOptions?.schema ? {} : undefined;
21231
- const effectiveStageOptions = stageOptionsWithStructuredOutput(stageOptions, structuredOutputCapture, structuredOutputExecutionCapture);
21489
+ const effectiveStageOptions = stageOptionsWithStructuredOutput(adapters.sessionStore === undefined || stageOptions?.sessionStore !== undefined || stageOptions?.sessionDir !== undefined || stageOptions?.sessionManager !== undefined ? stageOptions : { ...stageOptions, sessionStore: adapters.sessionStore }, structuredOutputCapture, structuredOutputExecutionCapture);
21232
21490
  const meta = {
21233
21491
  runId,
21234
21492
  stageId,
@@ -21467,8 +21725,8 @@ ${nextPrompt}`;
21467
21725
  return;
21468
21726
  await controller.ensureSession();
21469
21727
  },
21470
- async __ensureSessionFromFile(sessionFile) {
21471
- await controller.ensureSessionFromFile(sessionFile);
21728
+ async __ensureSessionFromId(sessionId) {
21729
+ await controller.ensureSessionFromId(sessionId);
21472
21730
  },
21473
21731
  __sealGeneration() {
21474
21732
  controller.sealGeneration();
@@ -21537,11 +21795,11 @@ function createWorkflowStageFactory(input) {
21537
21795
  input.assertLiveWorkAllowed?.();
21538
21796
  options = stageOptionsWithGitWorktree(prepareLiveOptions?.() ?? options, input.workflowInvocationCwd, input.gitWorktreeSetupCache);
21539
21797
  }
21540
- const replayStageOptions = executeReplaySource?.sessionFile === undefined ? options : {
21798
+ const replayStageOptions = executeReplaySource?.sessionId === undefined ? options : {
21541
21799
  ...options ?? {},
21542
21800
  routerSelection: executeReplaySource.routerSelection,
21543
21801
  context: options?.context ?? "fork",
21544
- forkFromSessionFile: options?.forkFromSessionFile ?? executeReplaySource.sessionFile
21802
+ forkFromSessionId: options?.forkFromSessionId ?? executeReplaySource.sessionId
21545
21803
  };
21546
21804
  const intercomGroup = options?.durableIntercomGroup ?? resolveStageGroup(replayStageOptions, input.workflowIntercomGroup);
21547
21805
  const stageOptionsForContext = replayStageOptions?.group === undefined || intercomGroup === undefined ? replayStageOptions : { ...replayStageOptions, group: intercomGroup };
@@ -21716,8 +21974,8 @@ function createWorkflowStageFactory(input) {
21716
21974
  stageSnapshot.sessionId = meta.sessionId;
21717
21975
  if (meta.sessionFile !== undefined)
21718
21976
  stageSnapshot.sessionFile = meta.sessionFile;
21719
- if (meta.sessionId !== undefined || meta.sessionFile !== undefined)
21720
- input.activeStore.recordStageSession(input.runId, stageId, meta);
21977
+ if (meta.sessionId !== undefined)
21978
+ input.activeStore.recordStageSession(input.runId, stageId, { sessionId: meta.sessionId });
21721
21979
  const pending = input.opts.onStageSession?.(input.runId, stageSnapshot, checkpointOptions);
21722
21980
  if (checkpointOptions?.forceDurable === true || checkpointOptions?.awaitDurable === true) {
21723
21981
  await pending;
@@ -22249,11 +22507,45 @@ async function executeRun(def, resolvedInputs, opts) {
22249
22507
  return waitForRunRelease().then(() => whenRunning(call));
22250
22508
  if (ownController.signal.aborted)
22251
22509
  return Promise.reject(ownController.signal.reason);
22252
- return call();
22510
+ const persistence = drainCachedStagePersistence();
22511
+ return persistence === undefined ? call() : persistence.then(() => whenRunning(call));
22253
22512
  };
22254
22513
  ownController.signal.addEventListener("abort", () => scheduler.rejectReleaseBarriers(ownController.signal.reason ?? new Error("atomic-workflows: run aborted")), { once: true });
22255
22514
  const cachedStagePersistence = [];
22256
22515
  let cachedStageFailure;
22516
+ let cachedStageDrain;
22517
+ const drainCachedStagePersistence = () => {
22518
+ if (cachedStageDrain !== undefined)
22519
+ return cachedStageDrain;
22520
+ if (cachedStagePersistence.length === 0) {
22521
+ if (cachedStageFailure !== undefined)
22522
+ throw cachedStageFailure;
22523
+ return;
22524
+ }
22525
+ cachedStageDrain = (async () => {
22526
+ try {
22527
+ while (cachedStagePersistence.length > 0)
22528
+ await Promise.all(cachedStagePersistence.splice(0));
22529
+ if (cachedStageFailure !== undefined)
22530
+ throw cachedStageFailure;
22531
+ } finally {
22532
+ cachedStageDrain = undefined;
22533
+ }
22534
+ })();
22535
+ return cachedStageDrain;
22536
+ };
22537
+ const drainBeforeCheckpoint = () => {
22538
+ const persistence = drainCachedStagePersistence();
22539
+ return persistence?.then(() => ownController.signal.throwIfAborted());
22540
+ };
22541
+ const beforeLiveCall = () => {
22542
+ ownController.signal.throwIfAborted();
22543
+ const persistence = drainCachedStagePersistence();
22544
+ if (persistence !== undefined)
22545
+ return persistence.then(beforeLiveCall);
22546
+ if (scheduler.isRunPaused())
22547
+ return waitForRunRelease().then(beforeLiveCall);
22548
+ };
22257
22549
  const finalizers = createRunFinalizers({
22258
22550
  def,
22259
22551
  runId,
@@ -22262,8 +22554,14 @@ async function executeRun(def, resolvedInputs, opts) {
22262
22554
  opts,
22263
22555
  classifyExecutorFailure,
22264
22556
  drainWorkflowExitCleanups: async (reason) => {
22265
- await Promise.all(cachedStagePersistence);
22266
- await exit.drainWorkflowExitCleanups(reason);
22557
+ try {
22558
+ await drainCachedStagePersistence();
22559
+ } catch (error) {
22560
+ if (error !== cachedStageFailure)
22561
+ throw error;
22562
+ } finally {
22563
+ await exit.drainWorkflowExitCleanups(reason);
22564
+ }
22267
22565
  },
22268
22566
  assertSuccessfulCompletion: () => {
22269
22567
  if (cachedStageFailure !== undefined)
@@ -22279,7 +22577,8 @@ async function executeRun(def, resolvedInputs, opts) {
22279
22577
  run: runSnapshot,
22280
22578
  nextCheckpointId: checkpointIdGenerator,
22281
22579
  nextReplayKey: stageReplayKeyGenerator,
22282
- completedReplayKeys: completedStageReplayKeys
22580
+ completedReplayKeys: completedStageReplayKeys,
22581
+ beforeCheckpoint: drainBeforeCheckpoint
22283
22582
  });
22284
22583
  const durableOnStageEnd = createDurableStageEndRecorder({
22285
22584
  rootRunId: runId,
@@ -22428,7 +22727,9 @@ async function executeRun(def, resolvedInputs, opts) {
22428
22727
  retryToolNodes: opts.continuation?.retryToolNodes,
22429
22728
  toolControls,
22430
22729
  toolAdmission,
22431
- budget
22730
+ budget,
22731
+ beforeToolCall: drainCachedStagePersistence,
22732
+ beforeCheckpoint: drainBeforeCheckpoint
22432
22733
  });
22433
22734
  let selectedAdmittedToolFailure;
22434
22735
  const suspendForGracefulQuit = (reason) => {
@@ -22469,9 +22770,11 @@ async function executeRun(def, resolvedInputs, opts) {
22469
22770
  workflowId: runId,
22470
22771
  backend: durableBackend,
22471
22772
  nextCheckpointId: checkpointIdGenerator,
22773
+ beforeCheckpoint: drainBeforeCheckpoint,
22472
22774
  beforeCall: () => {
22473
22775
  ownController.signal.throwIfAborted();
22474
- return scheduler.isRunPaused() ? waitForRunRelease() : undefined;
22776
+ const persistence = drainCachedStagePersistence();
22777
+ return persistence ?? (scheduler.isRunPaused() ? waitForRunRelease() : undefined);
22475
22778
  },
22476
22779
  ...opts.usePromptNodesForUi === true ? {
22477
22780
  onReplay: async (request) => getPromptNodeUi().replayDurable(request)
@@ -22508,6 +22811,7 @@ async function executeRun(def, resolvedInputs, opts) {
22508
22811
  durableIntercomGroup,
22509
22812
  task: taskRunners.task,
22510
22813
  recordCachedTask: recordCachedStage,
22814
+ beforeCheckpoint: drainBeforeCheckpoint,
22511
22815
  signal: ownController.signal,
22512
22816
  registerTailControl: (registration) => {
22513
22817
  registration.controller.signal.addEventListener("abort", () => {
@@ -22544,6 +22848,8 @@ async function executeRun(def, resolvedInputs, opts) {
22544
22848
  backend: durableBackend,
22545
22849
  nextReplayKey: (stageName) => stageReplayKeyGenerator(stageName),
22546
22850
  durableIntercomGroup,
22851
+ beforeCall: beforeLiveCall,
22852
+ beforeCheckpoint: drainBeforeCheckpoint,
22547
22853
  recordCachedStage,
22548
22854
  stage: (name, options, replayKey) => {
22549
22855
  const stage = runtime.stage(name, options);
@@ -22604,7 +22910,7 @@ async function executeRun(def, resolvedInputs, opts) {
22604
22910
  return pending;
22605
22911
  }),
22606
22912
  tool: (...args) => {
22607
- if (!scheduler.isRunPaused())
22913
+ if (admittedTools.closed)
22608
22914
  return tool(...args);
22609
22915
  const pending = whenRunning(() => tool(...args));
22610
22916
  pending.catch(() => {});
@@ -22732,13 +23038,13 @@ async function executeRun(def, resolvedInputs, opts) {
22732
23038
  ownController.signal.throwIfAborted();
22733
23039
  if (opts.parentRun === undefined) {
22734
23040
  if (durableRootRegistration !== undefined) {
22735
- await durableBackend.registerWorkflow({
23041
+ await durableBackend.commitWorkflowRegistration({
22736
23042
  ...durableRootRegistration,
22737
23043
  modelOwner: runSnapshot.modelOwner,
22738
23044
  ...workflowInvocationMetadata(inputRuntimeDefaults, workflowInvocationCwd, gitWorktreeSetupCache, runSnapshot.origin)
22739
23045
  });
22740
23046
  } else {
22741
- await durableBackend.setWorkflowStatus(runId, "running");
23047
+ await durableBackend.commitWorkflowStatus(runId, "running");
22742
23048
  }
22743
23049
  }
22744
23050
  durableRootAdmitted = true;
@@ -22760,9 +23066,7 @@ async function executeRun(def, resolvedInputs, opts) {
22760
23066
  await waitForRunRelease();
22761
23067
  ownController.signal.throwIfAborted();
22762
23068
  const rawResult = await raceAbort2(runWorkflowDefinitionCallback(def.name, runId, () => def.run(ctx)), ownController.signal);
22763
- await Promise.all(cachedStagePersistence);
22764
- if (cachedStageFailure !== undefined)
22765
- throw cachedStageFailure;
23069
+ await drainCachedStagePersistence();
22766
23070
  while (scheduler.isRunPaused())
22767
23071
  await waitForRunRelease();
22768
23072
  await admittedTools.closeAndDrain();
@@ -22802,7 +23106,7 @@ async function executeRun(def, resolvedInputs, opts) {
22802
23106
  const recorded = activeStore.recordRunEnd(runId, returned.status, result, returned.error, returned.metadata);
22803
23107
  if (opts.parentRun === undefined)
22804
23108
  await recordRunTimingCheckpointAsync(durableBackend, runSnapshot);
22805
- await durableBackend.setWorkflowStatus(runId, returned.status, undefined, returned.metadata?.resumable);
23109
+ await durableBackend.commitWorkflowStatus(runId, returned.status, undefined, returned.metadata?.resumable);
22806
23110
  await appendRunEndWhenRecorded(opts.persistence, recorded, {
22807
23111
  runId,
22808
23112
  status: returned.status,
@@ -22932,6 +23236,9 @@ async function executeRun(def, resolvedInputs, opts) {
22932
23236
  unregisterToolAdmission();
22933
23237
  } finally {
22934
23238
  terminalEvents.dispose();
23239
+ if (opts.stageControlRegistry === undefined && opts.executionMode !== "interactive" && isTerminalRunStatus(runSnapshot.status) && runSnapshot.resumable !== true) {
23240
+ await stageRegistry.clear(runId);
23241
+ }
22935
23242
  }
22936
23243
  }
22937
23244
  }
@@ -23026,7 +23333,6 @@ export {
23026
23333
  JOURNAL_TABLES,
23027
23334
  JournalCasConflictError,
23028
23335
  JournalClosedError,
23029
- JournalConfigurationError,
23030
23336
  JournalCounterRangeError,
23031
23337
  JournalError,
23032
23338
  JournalInvalidTextError,