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

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 (248) hide show
  1. package/CHANGELOG.md +31 -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 +6 -0
  5. package/dist/builtin/subagents/package.json +3 -3
  6. package/dist/builtin/subagents/src/extension/index.bundle.mjs +120 -121
  7. package/dist/builtin/web-access/package.json +2 -2
  8. package/dist/builtin/workflows/CHANGELOG.md +19 -0
  9. package/dist/builtin/workflows/builtin/{chunk-q7dx7kh7.js → chunk-85mx6wcf.js} +6 -6
  10. package/dist/builtin/workflows/builtin/{chunk-neszcj53.js → chunk-8kkv04hz.js} +15 -15
  11. package/dist/builtin/workflows/builtin/{chunk-g1a4hw0s.js → chunk-8x61e0s7.js} +13 -25
  12. package/dist/builtin/workflows/builtin/{chunk-2qgfyvzs.js → chunk-y45tkftg.js} +7 -7
  13. package/dist/builtin/workflows/builtin/goal.js +2 -2
  14. package/dist/builtin/workflows/builtin/index.js +4 -4
  15. package/dist/builtin/workflows/builtin/open-claude-design.js +1 -1
  16. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  17. package/dist/builtin/workflows/package.json +2 -2
  18. package/dist/builtin/workflows/src/durable/journal/internal.d.ts +0 -19
  19. package/dist/builtin/workflows/src/durable/journal/memory-run-journal.d.ts +3 -11
  20. package/dist/builtin/workflows/src/durable/journal/resolution.d.ts +15 -9
  21. package/dist/builtin/workflows/src/durable/journal/types.d.ts +3 -93
  22. package/dist/builtin/workflows/src/extension/index.bundle.mjs +992 -756
  23. package/dist/builtin/workflows/src/index.js +547 -394
  24. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +1 -1
  25. package/dist/cli/args.d.ts +2 -0
  26. package/dist/cli/args.d.ts.map +1 -1
  27. package/dist/cli/args.js +29 -3
  28. package/dist/cli/args.js.map +1 -1
  29. package/dist/cli/session-picker.d.ts +1 -1
  30. package/dist/cli/session-picker.d.ts.map +1 -1
  31. package/dist/cli/session-picker.js +2 -2
  32. package/dist/cli/session-picker.js.map +1 -1
  33. package/dist/core/agent-session-events.d.ts.map +1 -1
  34. package/dist/core/agent-session-events.js +6 -1
  35. package/dist/core/agent-session-events.js.map +1 -1
  36. package/dist/core/agent-session-runtime.d.ts +4 -0
  37. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  38. package/dist/core/agent-session-runtime.js +44 -4
  39. package/dist/core/agent-session-runtime.js.map +1 -1
  40. package/dist/core/agent-session-services.d.ts +1 -1
  41. package/dist/core/agent-session-services.d.ts.map +1 -1
  42. package/dist/core/agent-session-services.js +2 -2
  43. package/dist/core/agent-session-services.js.map +1 -1
  44. package/dist/core/compaction/branch-summarization.d.ts +1 -4
  45. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  46. package/dist/core/compaction/branch-summarization.js +0 -4
  47. package/dist/core/compaction/branch-summarization.js.map +1 -1
  48. package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -1
  49. package/dist/core/compaction/pi-summary-fallback.js +1 -3
  50. package/dist/core/compaction/pi-summary-fallback.js.map +1 -1
  51. package/dist/core/extensions/loader-api.js +1 -1
  52. package/dist/core/extensions/loader-api.js.map +1 -1
  53. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  54. package/dist/core/extensions/runner-context.js +7 -1
  55. package/dist/core/extensions/runner-context.js.map +1 -1
  56. package/dist/core/fast-model-routing.js +1 -1
  57. package/dist/core/fast-model-routing.js.map +1 -1
  58. package/dist/core/model-config.d.ts +765 -0
  59. package/dist/core/model-config.d.ts.map +1 -1
  60. package/dist/core/model-config.js +46 -24
  61. package/dist/core/model-config.js.map +1 -1
  62. package/dist/core/model-resolver-defaults.js +1 -1
  63. package/dist/core/model-resolver-defaults.js.map +1 -1
  64. package/dist/core/resource-loader-reload.js +1 -1
  65. package/dist/core/resource-loader-reload.js.map +1 -1
  66. package/dist/core/resource-loader-types.d.ts +1 -1
  67. package/dist/core/resource-loader-types.d.ts.map +1 -1
  68. package/dist/core/resource-loader-types.js.map +1 -1
  69. package/dist/core/sdk-types.d.ts +4 -0
  70. package/dist/core/sdk-types.d.ts.map +1 -1
  71. package/dist/core/sdk-types.js.map +1 -1
  72. package/dist/core/sdk.d.ts +1 -1
  73. package/dist/core/sdk.d.ts.map +1 -1
  74. package/dist/core/sdk.js +48 -19
  75. package/dist/core/sdk.js.map +1 -1
  76. package/dist/core/session-lifecycle-work.d.ts +3 -0
  77. package/dist/core/session-lifecycle-work.d.ts.map +1 -1
  78. package/dist/core/session-lifecycle-work.js +2 -0
  79. package/dist/core/session-lifecycle-work.js.map +1 -1
  80. package/dist/core/session-manager-core.d.ts +7 -4
  81. package/dist/core/session-manager-core.d.ts.map +1 -1
  82. package/dist/core/session-manager-core.js +149 -41
  83. package/dist/core/session-manager-core.js.map +1 -1
  84. package/dist/core/session-manager-list.d.ts.map +1 -1
  85. package/dist/core/session-manager-list.js +7 -7
  86. package/dist/core/session-manager-list.js.map +1 -1
  87. package/dist/core/session-manager-storage.d.ts +3 -2
  88. package/dist/core/session-manager-storage.d.ts.map +1 -1
  89. package/dist/core/session-manager-storage.js +25 -9
  90. package/dist/core/session-manager-storage.js.map +1 -1
  91. package/dist/core/session-manager-types.d.ts +1 -1
  92. package/dist/core/session-manager-types.d.ts.map +1 -1
  93. package/dist/core/session-manager-types.js.map +1 -1
  94. package/dist/core/session-manager.d.ts +1 -1
  95. package/dist/core/session-manager.d.ts.map +1 -1
  96. package/dist/core/session-manager.js +1 -1
  97. package/dist/core/session-manager.js.map +1 -1
  98. package/dist/core/session-resume-args.d.ts +4 -0
  99. package/dist/core/session-resume-args.d.ts.map +1 -0
  100. package/dist/core/session-resume-args.js +9 -0
  101. package/dist/core/session-resume-args.js.map +1 -0
  102. package/dist/core/session-storage.d.ts +26 -0
  103. package/dist/core/session-storage.d.ts.map +1 -0
  104. package/dist/core/session-storage.js +155 -0
  105. package/dist/core/session-storage.js.map +1 -0
  106. package/dist/core/session-store-list.d.ts +4 -0
  107. package/dist/core/session-store-list.d.ts.map +1 -0
  108. package/dist/core/session-store-list.js +28 -0
  109. package/dist/core/session-store-list.js.map +1 -0
  110. package/dist/core/settings-manager-basic-accessors.d.ts +0 -1
  111. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  112. package/dist/core/settings-manager-basic-accessors.js +0 -5
  113. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  114. package/dist/core/settings-merge.d.ts.map +1 -1
  115. package/dist/core/settings-merge.js +5 -0
  116. package/dist/core/settings-merge.js.map +1 -1
  117. package/dist/core/settings-schema.d.ts +74 -3
  118. package/dist/core/settings-schema.d.ts.map +1 -1
  119. package/dist/core/settings-schema.js +28 -14
  120. package/dist/core/settings-schema.js.map +1 -1
  121. package/dist/core/storage/errors.d.ts +1 -0
  122. package/dist/core/storage/errors.d.ts.map +1 -1
  123. package/dist/core/storage/errors.js.map +1 -1
  124. package/dist/core/storage/index.d.ts +4 -0
  125. package/dist/core/storage/index.d.ts.map +1 -1
  126. package/dist/core/storage/index.js +3 -0
  127. package/dist/core/storage/index.js.map +1 -1
  128. package/dist/core/storage/provider.d.ts +58 -0
  129. package/dist/core/storage/provider.d.ts.map +1 -0
  130. package/dist/core/storage/provider.js +243 -0
  131. package/dist/core/storage/provider.js.map +1 -0
  132. package/dist/core/storage/run-journal.d.ts +93 -0
  133. package/dist/core/storage/run-journal.d.ts.map +1 -0
  134. package/dist/core/storage/run-journal.js +15 -0
  135. package/dist/core/storage/run-journal.js.map +1 -0
  136. package/dist/core/storage/selection.d.ts +16 -0
  137. package/dist/core/storage/selection.d.ts.map +1 -0
  138. package/dist/core/storage/selection.js +87 -0
  139. package/dist/core/storage/selection.js.map +1 -0
  140. package/dist/core/storage/session/jsonl-session-store.d.ts +2 -0
  141. package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
  142. package/dist/core/storage/session/jsonl-session-store.js +58 -29
  143. package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
  144. package/dist/core/storage/session/legacy-format.d.ts +18 -0
  145. package/dist/core/storage/session/legacy-format.d.ts.map +1 -0
  146. package/dist/core/storage/session/legacy-format.js +63 -0
  147. package/dist/core/storage/session/legacy-format.js.map +1 -0
  148. package/dist/core/storage/session/memory-session-store.d.ts +3 -1
  149. package/dist/core/storage/session/memory-session-store.d.ts.map +1 -1
  150. package/dist/core/storage/session/memory-session-store.js +9 -2
  151. package/dist/core/storage/session/memory-session-store.js.map +1 -1
  152. package/dist/core/storage/session/sql-session-store.d.ts +4 -1
  153. package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
  154. package/dist/core/storage/session/sql-session-store.js +25 -6
  155. package/dist/core/storage/session/sql-session-store.js.map +1 -1
  156. package/dist/core/storage/session/types.d.ts +4 -0
  157. package/dist/core/storage/session/types.d.ts.map +1 -1
  158. package/dist/core/storage/session/types.js.map +1 -1
  159. package/dist/core/tools/read-url.d.ts.map +1 -1
  160. package/dist/core/tools/read-url.js +6 -1
  161. package/dist/core/tools/read-url.js.map +1 -1
  162. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  163. package/dist/extensions/codemode/execute.js +13 -0
  164. package/dist/extensions/codemode/execute.js.map +1 -1
  165. package/dist/extensions/herdr/index.d.ts.map +1 -1
  166. package/dist/extensions/herdr/index.js +5 -3
  167. package/dist/extensions/herdr/index.js.map +1 -1
  168. package/dist/index.d.ts +3 -1
  169. package/dist/index.d.ts.map +1 -1
  170. package/dist/index.js +3 -1
  171. package/dist/index.js.map +1 -1
  172. package/dist/main-session.d.ts +5 -1
  173. package/dist/main-session.d.ts.map +1 -1
  174. package/dist/main-session.js +106 -45
  175. package/dist/main-session.js.map +1 -1
  176. package/dist/main.d.ts.map +1 -1
  177. package/dist/main.js +49 -15
  178. package/dist/main.js.map +1 -1
  179. package/dist/modes/interactive/components/chat-session-host.d.ts +3 -1
  180. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  181. package/dist/modes/interactive/components/chat-session-host.js +15 -7
  182. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  183. package/dist/modes/interactive/components/session-selector-delete.d.ts +1 -1
  184. package/dist/modes/interactive/components/session-selector-delete.d.ts.map +1 -1
  185. package/dist/modes/interactive/components/session-selector-delete.js.map +1 -1
  186. package/dist/modes/interactive/components/session-selector-list.d.ts +4 -4
  187. package/dist/modes/interactive/components/session-selector-list.d.ts.map +1 -1
  188. package/dist/modes/interactive/components/session-selector-list.js +13 -12
  189. package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
  190. package/dist/modes/interactive/components/session-selector.d.ts +1 -0
  191. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  192. package/dist/modes/interactive/components/session-selector.js +16 -5
  193. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  194. package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
  195. package/dist/modes/interactive/interactive-mode-helpers.js +6 -2
  196. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  197. package/dist/modes/interactive/interactive-session-routing.js +19 -7
  198. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  199. package/dist/modes/interactive/interactive-slash-commands.js +3 -1
  200. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  201. package/dist/modes/interactive-engine/create-isolated-runtime.d.ts.map +1 -1
  202. package/dist/modes/interactive-engine/create-isolated-runtime.js +8 -1
  203. package/dist/modes/interactive-engine/create-isolated-runtime.js.map +1 -1
  204. package/dist/modes/interactive-engine/engine-args.d.ts.map +1 -1
  205. package/dist/modes/interactive-engine/engine-args.js +5 -1
  206. package/dist/modes/interactive-engine/engine-args.js.map +1 -1
  207. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  208. package/dist/modes/interactive-engine/isolated-runtime.js +21 -15
  209. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  210. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  211. package/dist/modes/rpc/rpc-client-process.js +3 -1
  212. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  213. package/dist/modes/rpc/rpc-command-handler.js +1 -1
  214. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  215. package/dist/modes/rpc/rpc-terminal-drain.d.ts.map +1 -1
  216. package/dist/modes/rpc/rpc-terminal-drain.js +11 -2
  217. package/dist/modes/rpc/rpc-terminal-drain.js.map +1 -1
  218. package/dist/utils/canonical-path.d.ts +5 -0
  219. package/dist/utils/canonical-path.d.ts.map +1 -0
  220. package/dist/utils/canonical-path.js +26 -0
  221. package/dist/utils/canonical-path.js.map +1 -0
  222. package/dist/utils/paths.d.ts +1 -7
  223. package/dist/utils/paths.d.ts.map +1 -1
  224. package/dist/utils/paths.js +1 -15
  225. package/dist/utils/paths.js.map +1 -1
  226. package/docs/codemode.md +2 -0
  227. package/docs/compaction.md +2 -2
  228. package/docs/docs.json +1 -0
  229. package/docs/environment-variables.md +6 -2
  230. package/docs/getting-started/installation.md +1 -1
  231. package/docs/models/reference.md +2 -0
  232. package/docs/models-configuration.md +206 -0
  233. package/docs/models.md +11 -1
  234. package/docs/providers.md +2 -2
  235. package/docs/reference/cli.md +4 -0
  236. package/docs/sdk/web-server.md +3 -3
  237. package/docs/sdk.md +40 -3
  238. package/docs/session-format.md +30 -25
  239. package/docs/sessions.md +41 -17
  240. package/docs/settings.md +31 -9
  241. package/docs/storage.md +85 -2
  242. package/docs/workflows/api-reference.md +23 -15
  243. package/docs/workflows/operations.md +3 -3
  244. package/docs/workflows/reliable-design.md +16 -16
  245. package/npm-shrinkwrap.json +53 -53
  246. package/package.json +7 -6
  247. package/schemas/models.schema.json +62 -29
  248. 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,19 +1065,20 @@ 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 {
@@ -1477,10 +1405,82 @@ class SqlRunJournal {
1477
1405
  }
1478
1406
  }
1479
1407
 
1408
+ // dist/builtin/workflows/src/durable/journal/resolution.ts
1409
+ var provider = new StorageProvider({
1410
+ memory: (descriptor) => new MemoryRunJournal(descriptor),
1411
+ sql: SqlRunJournal.open
1412
+ });
1413
+ var settingsSelections = new WeakSet;
1414
+ function selectRunJournal(options = {}) {
1415
+ const agentDir = getAgentDir();
1416
+ const defaultPath = join(dirname(agentDir), "workflows", "journal.sqlite");
1417
+ if (options.journal !== undefined) {
1418
+ if (options.journal !== null && typeof options.journal === "object" && "createRun" in options.journal) {
1419
+ const journal = options.journal;
1420
+ if ([
1421
+ journal.createRun,
1422
+ journal.getRun,
1423
+ journal.listRuns,
1424
+ journal.acquire,
1425
+ journal.takeover,
1426
+ journal.takeoverExpired,
1427
+ journal.leaseState,
1428
+ journal.renew,
1429
+ journal.release,
1430
+ journal.append,
1431
+ journal.read,
1432
+ journal.readKey,
1433
+ journal.deleteOwnedRun,
1434
+ journal.deleteRun,
1435
+ journal.close
1436
+ ].some((hook) => typeof hook !== "function")) {
1437
+ throw new StorageConfigError("sdk", "journal", "invalid-journal");
1438
+ }
1439
+ return journal;
1440
+ }
1441
+ return selectStorage(options.journal, "sdk", "journal", defaultPath);
1442
+ }
1443
+ const environment = process.env.ATOMIC_WORKFLOW_JOURNAL_PATH;
1444
+ if (environment !== undefined && environment.length > 0)
1445
+ return { kind: "sqlite", path: environment };
1446
+ const workflows = options.settings?.workflows;
1447
+ const journal = Array.isArray(workflows) ? undefined : workflows?.journal;
1448
+ const value = journal !== undefined ? journal : options.settings?.storage;
1449
+ if (value === undefined)
1450
+ return { kind: "sqlite", path: defaultPath };
1451
+ const selection = selectStorage(value, "settings", journal !== undefined ? "workflows.journal" : "storage", journal !== undefined ? defaultPath : join(dirname(agentDir), "storage.sqlite"));
1452
+ const resolved = selection.kind === "sqlite" && !isAbsolute(selection.path) ? { ...selection, path: join(dirname(agentDir), selection.path) } : selection;
1453
+ settingsSelections.add(resolved);
1454
+ return resolved;
1455
+ }
1456
+ async function resolveRunJournal(options = {}) {
1457
+ return openSelectedRunJournal(selectRunJournal(options));
1458
+ }
1459
+ async function openSelectedRunJournal(selection) {
1460
+ if ("createRun" in selection)
1461
+ return selection;
1462
+ return withRunJournalConfigSource(selection, () => provider.openRunJournal(selection, { agentDir: getAgentDir(), domain: "journal" }));
1463
+ }
1464
+ async function withRunJournalConfigSource(selection, open) {
1465
+ if ("createRun" in selection)
1466
+ return open();
1467
+ try {
1468
+ return await open();
1469
+ } catch (error) {
1470
+ if (error instanceof StorageConfigError) {
1471
+ const source = settingsSelections.has(selection) ? "settings" : "sdk";
1472
+ if (error.source !== source)
1473
+ throw new StorageConfigError(source, error.field, error.reason);
1474
+ }
1475
+ throw error;
1476
+ }
1477
+ }
1480
1478
  // dist/builtin/workflows/src/durable/journal/sqlite-run-journal.ts
1479
+ import { dirname as dirname2, join as join2 } from "node:path";
1480
+ import { getAgentDir as getAgentDir2, openNodeSqliteDatabase, validateStoragePrefix, wrapNodeSqliteDatabase } from "@bastani/atomic";
1481
1481
  function workflowJournalPath() {
1482
1482
  const override = process.env.ATOMIC_WORKFLOW_JOURNAL_PATH;
1483
- return override !== undefined && override.length > 0 ? override : join(dirname(getAgentDir()), "workflows", "journal.sqlite");
1483
+ return override !== undefined && override.length > 0 ? override : join2(dirname2(getAgentDir2()), "workflows", "journal.sqlite");
1484
1484
  }
1485
1485
  async function openSqlRunJournal(source = workflowJournalPath(), options = {}) {
1486
1486
  validateStoragePrefix(options.prefix);
@@ -1499,36 +1499,6 @@ async function openSqlRunJournal(source = workflowJournalPath(), options = {}) {
1499
1499
  throw error;
1500
1500
  }
1501
1501
  }
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
1502
  // dist/builtin/workflows/src/engine/graph-inference.ts
1533
1503
  class GraphFrontierTracker {
1534
1504
  frontier = new Set;
@@ -1600,6 +1570,25 @@ import {
1600
1570
  resolveRestoredModelReference
1601
1571
  } from "@bastani/atomic";
1602
1572
 
1573
+ // dist/builtin/workflows/src/durable/execution-context-boundary.ts
1574
+ var executionStorages = new Set;
1575
+ function registerExecutionStorages(...storages) {
1576
+ for (const storage of storages)
1577
+ executionStorages.add(storage);
1578
+ return () => {
1579
+ for (const storage of storages)
1580
+ executionStorages.delete(storage);
1581
+ };
1582
+ }
1583
+ function outsideWorkflowExecutions(callback) {
1584
+ let run = callback;
1585
+ for (const storage of executionStorages) {
1586
+ const inner = run;
1587
+ run = () => storage.exit(inner);
1588
+ }
1589
+ return run();
1590
+ }
1591
+
1603
1592
  // dist/builtin/workflows/src/runs/foreground/stage-runner-session.ts
1604
1593
  function stageSessionExtensionRunner(current) {
1605
1594
  const runner = current.extensionRunner;
@@ -1683,7 +1672,6 @@ async function rejectDisposedCreatedSession(result, stageName) {
1683
1672
  }
1684
1673
 
1685
1674
  // dist/builtin/workflows/src/runs/foreground/stage-runner-session-options.ts
1686
- import { SessionManager } from "@bastani/atomic";
1687
1675
  var adapterDefaultCwds = new WeakMap;
1688
1676
  function setAgentSessionAdapterDefaultCwd(adapter, cwd) {
1689
1677
  adapterDefaultCwds.set(adapter, cwd);
@@ -1706,11 +1694,10 @@ async function buildStageSessionOptions(input) {
1706
1694
  }
1707
1695
  if (input.restoreSavedModel === true)
1708
1696
  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);
1697
+ if (input.reattachSessionId !== undefined) {
1698
+ options.resumeFromSessionId = input.reattachSessionId;
1712
1699
  options.context = undefined;
1713
- options.forkFromSessionFile = undefined;
1700
+ options.forkFromSessionId = undefined;
1714
1701
  }
1715
1702
  if (input.sharedModelRuntime !== undefined && options.modelRuntime === undefined) {
1716
1703
  options.modelRuntime = input.sharedModelRuntime;
@@ -1967,18 +1954,15 @@ class ScopedDurableBackend {
1967
1954
  async hasPendingStageDeliveryReceipt(workflowId, messageId, delivery, logicalRunId = workflowId) {
1968
1955
  return await this.inner.hasPendingStageDeliveryReceipt?.(this.scope.rootWorkflowId, messageId, delivery, logicalRunId) ?? false;
1969
1956
  }
1970
- registerWorkflow(_handle) {}
1957
+ async commitWorkflowRegistration(_handle) {}
1971
1958
  persistPendingStageMessages(workflowId, messages, logicalRunId = workflowId) {
1972
1959
  return this.inner.persistPendingStageMessages(this.scope.rootWorkflowId, messages, logicalRunId);
1973
1960
  }
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);
1961
+ async commitCheckpoint(checkpoint, options) {
1962
+ await this.inner.commitCheckpoint(this.remap(checkpoint), options);
1979
1963
  }
1980
- async recordAdditiveCheckpointBestEffort(checkpoint) {
1981
- return await this.inner.recordAdditiveCheckpointBestEffort(this.remap(checkpoint));
1964
+ async commitAdditiveCheckpointBestEffort(checkpoint) {
1965
+ return await this.inner.commitAdditiveCheckpointBestEffort(this.remap(checkpoint));
1982
1966
  }
1983
1967
  workflowOwnership(_workflowId) {
1984
1968
  return this.inner.workflowOwnership(this.scope.rootWorkflowId);
@@ -2008,12 +1992,12 @@ class ScopedDurableBackend {
2008
1992
  getLoadableWorkflow(_workflowId) {
2009
1993
  return;
2010
1994
  }
2011
- setWorkflowStatus(_workflowId, _status, _pendingPrompts, _resumable) {}
2012
- async transitionWorkflowStatus(_workflowId, _expectedStatuses, _status, _pendingPrompts, _resumable) {
1995
+ async commitWorkflowStatus(_workflowId, _status, _pendingPrompts, _resumable) {}
1996
+ async commitWorkflowStatusTransition(_workflowId, _expectedStatuses, _status, _pendingPrompts, _resumable) {
2013
1997
  return false;
2014
1998
  }
2015
- adjustPendingPrompts(_workflowId, delta) {
2016
- return this.inner.adjustPendingPrompts(this.scope.rootWorkflowId, delta);
1999
+ commitPendingPromptAdjustment(_workflowId, delta) {
2000
+ return this.inner.commitPendingPromptAdjustment(this.scope.rootWorkflowId, delta);
2017
2001
  }
2018
2002
  promptReservationScope(_workflowId) {
2019
2003
  return this.effectivePromptScope();
@@ -2046,7 +2030,7 @@ class ScopedDurableBackend {
2046
2030
  isWorkflowLoadable(_workflowId) {
2047
2031
  return false;
2048
2032
  }
2049
- reset() {}
2033
+ async commitReset() {}
2050
2034
  hydrateWorkflow(_workflowId) {
2051
2035
  return Promise.resolve();
2052
2036
  }
@@ -4217,19 +4201,9 @@ function createStageStoreMethods(context) {
4217
4201
  if (!run)
4218
4202
  return false;
4219
4203
  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)
4204
+ if (!stage || stage.sessionId === session.sessionId)
4232
4205
  return false;
4206
+ stage.sessionId = session.sessionId;
4233
4207
  context.bumpAndNotify();
4234
4208
  return true;
4235
4209
  },
@@ -4950,7 +4924,7 @@ function makeWorkflowStageOrchestrationContext(meta, pi) {
4950
4924
  const sendMessage = pi.sendMessage;
4951
4925
  if (!sendMessage)
4952
4926
  throw new Error("atomic-workflows: main-chat late-message route is unavailable");
4953
- return routeThroughStaleContextGuard(() => sendMessage(message, options));
4927
+ return routeThroughStaleContextGuard(() => outsideWorkflowExecutions(() => sendMessage(message, options)));
4954
4928
  },
4955
4929
  routeMessages(messages, options) {
4956
4930
  const intercomRoute = emitLateIntercomRoute(pi, meta, messages, options, true);
@@ -4958,15 +4932,15 @@ function makeWorkflowStageOrchestrationContext(meta, pi) {
4958
4932
  return intercomRoute;
4959
4933
  const sendMessages = pi.sendMessages;
4960
4934
  if (sendMessages)
4961
- return routeThroughStaleContextGuard(() => sendMessages(messages, options));
4935
+ return routeThroughStaleContextGuard(() => outsideWorkflowExecutions(() => sendMessages(messages, options)));
4962
4936
  const sendMessage = pi.sendMessage;
4963
4937
  if (!sendMessage)
4964
4938
  throw new Error("atomic-workflows: main-chat late-message route is unavailable");
4965
- return (async () => {
4939
+ return outsideWorkflowExecutions(async () => {
4966
4940
  for (const [index, message] of messages.entries()) {
4967
4941
  await sendMessage(message, index === 0 ? options : { deliverAs: "followUp" });
4968
4942
  }
4969
- })();
4943
+ });
4970
4944
  }
4971
4945
  }
4972
4946
  };
@@ -6570,7 +6544,7 @@ class JournalProjection {
6570
6544
  } else {
6571
6545
  if ("output" in currentCheckpoint)
6572
6546
  rec.stageOutputByReplayKey.set(currentCheckpoint.replayKey, currentCheckpoint);
6573
- if (currentCheckpoint.sessionId !== undefined || currentCheckpoint.sessionFile !== undefined) {
6547
+ if (currentCheckpoint.sessionId !== undefined) {
6574
6548
  const existing = rec.stageSessionByReplayKey.get(currentCheckpoint.replayKey);
6575
6549
  if (existing === undefined || currentCheckpoint.completedAt >= existing.completedAt) {
6576
6550
  rec.stageSessionByReplayKey.set(currentCheckpoint.replayKey, currentCheckpoint);
@@ -6598,7 +6572,7 @@ class JournalProjection {
6598
6572
  }
6599
6573
  getStageSession(workflowId, replayKey) {
6600
6574
  const checkpoint = this.workflows.get(workflowId)?.stageSessionByReplayKey.get(replayKey);
6601
- if (checkpoint?.sessionId === undefined && checkpoint?.sessionFile === undefined)
6575
+ if (checkpoint?.sessionId === undefined)
6602
6576
  return;
6603
6577
  return {
6604
6578
  ...checkpoint.sessionId !== undefined ? { sessionId: checkpoint.sessionId } : {},
@@ -7129,7 +7103,7 @@ function prepareDurableChildInvocation(input) {
7129
7103
  return;
7130
7104
  }
7131
7105
  topology = makeTopology(input, boundaryId, childRunId, parentIds, sourceOrder, "start", "running");
7132
- await input.backend.recordCheckpointAsync({
7106
+ await input.backend.commitCheckpoint({
7133
7107
  kind: "stage",
7134
7108
  workflowId: input.workflowId,
7135
7109
  checkpointId: `boundary-start:${input.replayKey}`,
@@ -7156,7 +7130,7 @@ function prepareDurableChildInvocation(input) {
7156
7130
  const terminalTopology = makeTopology(input, boundaryId, childRunId, topology.parentIds, topology.sourceOrder, "terminal", status);
7157
7131
  const priorTerminalAt = stages.filter((stage) => stage.replayKey === input.replayKey && stage.topology?.boundary?.event === "terminal").reduce((latest, stage) => Math.max(latest, stage.completedAt), 0);
7158
7132
  const now = Math.max(Date.now(), priorTerminalAt + 1);
7159
- await input.backend.recordCheckpointAsync({
7133
+ await input.backend.commitCheckpoint({
7160
7134
  kind: "stage",
7161
7135
  workflowId: input.workflowId,
7162
7136
  checkpointId: `boundary-terminal:${input.replayKey}:${status}`,
@@ -7829,9 +7803,10 @@ function replayedWorkflowToolOutcome(outcome) {
7829
7803
 
7830
7804
  // dist/builtin/workflows/src/durable/tool-failure-checkpoint.ts
7831
7805
  async function recordThrowingToolFailure(input, node, identity, error, attempts, cancelled = false) {
7806
+ await input.beforeCheckpoint?.();
7832
7807
  const message = workflowToolFailure(error, attempts, false).error.message;
7833
7808
  const failedAt = Date.now();
7834
- await input.backend.recordAdditiveCheckpointBestEffort({
7809
+ await input.backend.commitAdditiveCheckpointBestEffort({
7835
7810
  kind: "tool",
7836
7811
  workflowId: input.workflowId,
7837
7812
  checkpointId: `tool-failure:${identity.argsHash}:${input.nextCheckpointId()}`,
@@ -8159,6 +8134,21 @@ async function executeLiveToolInvocation(live) {
8159
8134
  const startedAt = Date.now();
8160
8135
  let attempts = 0;
8161
8136
  let callbackCompleted = false;
8137
+ const cancelInvocation = async (cancellation) => {
8138
+ control.noteCancelled();
8139
+ if (returnFailure || isWorkflowToolAbortError(cancellation) && cancellation.scope === "node" || input.runFailing?.() === true) {
8140
+ await recordCancelledToolInspection(live, startedAt, cancellation, attempts);
8141
+ }
8142
+ const endedAt = Date.now();
8143
+ input.onNodeEnd?.(node.id, {
8144
+ status: "cancelled",
8145
+ endedAt,
8146
+ durationMs: Math.max(0, endedAt - startedAt),
8147
+ error: cancellation.message
8148
+ });
8149
+ input.onNodeSettle?.(node.id);
8150
+ throw cancellation;
8151
+ };
8162
8152
  input.onNodeRunning?.(node.id, startedAt);
8163
8153
  try {
8164
8154
  const result = await executeWithRetries(() => {
@@ -8195,6 +8185,8 @@ async function executeLiveToolInvocation(live) {
8195
8185
  ...input.runTopology !== undefined ? { run: { ...input.runTopology } } : {}
8196
8186
  }
8197
8187
  };
8188
+ await input.beforeCheckpoint?.();
8189
+ throwIfInvocationCancelled(input, toolSignal);
8198
8190
  await recordCheckpointDurably(input.backend, checkpoint);
8199
8191
  input.onNodeEnd?.(node.id, {
8200
8192
  status: "completed",
@@ -8208,21 +8200,8 @@ async function executeLiveToolInvocation(live) {
8208
8200
  } catch (error) {
8209
8201
  const timeoutFailure = error instanceof WorkflowToolTimeoutError;
8210
8202
  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
- }
8203
+ if (cancellation !== undefined)
8204
+ return await cancelInvocation(cancellation);
8226
8205
  const callbackFailure = callbackError ?? error;
8227
8206
  if (returnFailure && !callbackCompleted && isExplicitCallbackCancellation(callbackFailure)) {
8228
8207
  input.onFailureObserved?.(callbackFailure, node.id);
@@ -8262,8 +8241,14 @@ async function executeLiveToolInvocation(live) {
8262
8241
  }
8263
8242
  };
8264
8243
  try {
8244
+ await input.beforeCheckpoint?.();
8245
+ if (!timeoutFailure)
8246
+ throwIfInvocationCancelled(input, toolSignal);
8265
8247
  await recordCheckpointDurably(input.backend, checkpoint);
8266
8248
  } catch (persistenceError) {
8249
+ const cancellation = timeoutFailure ? undefined : invocationCancellation(input, toolSignal);
8250
+ if (cancellation !== undefined)
8251
+ return await cancelInvocation(cancellation);
8267
8252
  input.onFailureObserved?.(persistenceError, node.id);
8268
8253
  const endedAt = Date.now();
8269
8254
  input.onNodeEnd?.(node.id, {
@@ -8414,7 +8399,7 @@ async function recordReplayedToolTopology(input, node, cached, argsHash, endedAt
8414
8399
  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
8400
  if (unchanged)
8416
8401
  return;
8417
- await input.backend.recordAdditiveCheckpointBestEffort({
8402
+ await input.backend.commitAdditiveCheckpointBestEffort({
8418
8403
  kind: "tool",
8419
8404
  workflowId: input.workflowId,
8420
8405
  checkpointId: `tool-replay-meta:${durableHash({ argsHash, topology })}`,
@@ -8436,7 +8421,7 @@ function summarizeToolResult(value) {
8436
8421
  return serialized.length <= 240 ? serialized : `${flattenTruncatedString(serialized.slice(0, 237))}...`;
8437
8422
  }
8438
8423
  async function recordCheckpointDurably(backend, checkpoint, signal) {
8439
- await backend.recordCheckpointAsync(checkpoint, signal === undefined ? undefined : { signal });
8424
+ await backend.commitCheckpoint(checkpoint, signal === undefined ? undefined : { signal });
8440
8425
  }
8441
8426
  async function executeWithRetries(fn, options, throwIfCancelled, signal) {
8442
8427
  throwIfCancelled();
@@ -8495,6 +8480,7 @@ async function recordStageCheckpoint(deps, stage, options) {
8495
8480
  completedAt: stage.endedAt ?? Date.now(),
8496
8481
  ...metadata
8497
8482
  };
8483
+ await deps.beforeCheckpoint?.();
8498
8484
  await recordCheckpointDurably(deps.backend, checkpoint);
8499
8485
  return true;
8500
8486
  }
@@ -8504,12 +8490,12 @@ function stageSessionDurationBucket(durationMs) {
8504
8490
  }
8505
8491
  async function recordStageSessionCheckpoint(deps, stage, options) {
8506
8492
  const replayKey = deps.replayKeyForCompletedStage?.(stage) ?? stage.replayKey ?? deps.nextReplayKey(stage.name);
8507
- if (stage.sessionFile === undefined)
8493
+ if (stage.sessionId === undefined)
8508
8494
  return false;
8509
8495
  const checkpointNow = deps.now?.() ?? Date.now();
8510
8496
  const durationMs = elapsedStageMs(stage, checkpointNow) ?? 0;
8511
8497
  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))
8498
+ if (options?.force !== true && current !== undefined && current.sessionId === stage.sessionId && current.startedAt === stage.startedAt && stageSessionDurationBucket(current.durationMs) === stageSessionDurationBucket(durationMs))
8513
8499
  return false;
8514
8500
  const checkpoint = {
8515
8501
  kind: "stage",
@@ -8524,6 +8510,7 @@ async function recordStageSessionCheckpoint(deps, stage, options) {
8524
8510
  durationMs,
8525
8511
  completedAt: checkpointNow
8526
8512
  };
8513
+ await deps.beforeCheckpoint?.();
8527
8514
  await recordCheckpointDurably(deps.backend, checkpoint);
8528
8515
  return true;
8529
8516
  }
@@ -8550,10 +8537,10 @@ function createDurableStagePrimitive(input) {
8550
8537
  const cached = stageCheckpointWithOutput(input.backend, input.workflowId, replayKey);
8551
8538
  if (cached !== undefined) {
8552
8539
  const recorded = input.recordCachedStage?.(name, replayKey, cached);
8553
- return createCachedStageContext(name, cached.output, cached.result, recorded);
8540
+ return withStageWriteBarrier(createCachedStageContext(name, cached.output, cached.result, recorded), input.beforeCall);
8554
8541
  }
8555
8542
  const session = input.backend.getStageSession(input.workflowId, replayKey);
8556
- const isMidSessionResume = session?.sessionFile !== undefined;
8543
+ const isMidSessionResume = session?.sessionId !== undefined;
8557
8544
  const topology = activeStageTopology(input.backend, input.workflowId, replayKey);
8558
8545
  const durableStageId = topology?.stageId ?? pendingStageIdForReplay(input.backend, input.workflowId, replayKey, name);
8559
8546
  const durableIntercomGroup = topology?.intercomGroup ?? input.durableIntercomGroup?.(replayKey, durableStageId);
@@ -8564,12 +8551,12 @@ function createDurableStagePrimitive(input) {
8564
8551
  ...topology !== undefined ? { durableParentIds: [...topology.parentIds] } : {},
8565
8552
  ...durableIntercomGroup !== undefined ? { durableIntercomGroup } : {},
8566
8553
  ...isMidSessionResume ? {
8567
- resumeFromSessionFile: session.sessionFile,
8554
+ resumeFromSessionId: session.sessionId,
8568
8555
  routerSelection: session.routerSelection,
8569
8556
  durableAccumulatedDurationMs: session.durationMs ?? 0
8570
8557
  } : {}
8571
8558
  };
8572
- const live = withMidSessionResumePrompt(input.stage(name, liveOptions, replayKey), isMidSessionResume);
8559
+ const live = withStageWriteBarrier(withMidSessionResumePrompt(input.stage(name, liveOptions, replayKey), isMidSessionResume), input.beforeCall);
8573
8560
  if (options?.schema === undefined)
8574
8561
  return live;
8575
8562
  return wrapSchemaStageForDurability({
@@ -8577,10 +8564,31 @@ function createDurableStagePrimitive(input) {
8577
8564
  workflowId: input.workflowId,
8578
8565
  backend: input.backend,
8579
8566
  replayKey,
8567
+ beforeCheckpoint: input.beforeCheckpoint,
8580
8568
  name
8581
8569
  });
8582
8570
  };
8583
8571
  }
8572
+ function withStageWriteBarrier(stage, beforeCall) {
8573
+ if (beforeCall === undefined)
8574
+ return stage;
8575
+ const wrapped = Object.create(stage);
8576
+ Object.defineProperties(wrapped, {
8577
+ prompt: {
8578
+ value: async (...args) => {
8579
+ await beforeCall();
8580
+ return stage.prompt(...args);
8581
+ }
8582
+ },
8583
+ complete: {
8584
+ value: async (...args) => {
8585
+ await beforeCall();
8586
+ return stage.complete(...args);
8587
+ }
8588
+ }
8589
+ });
8590
+ return wrapped;
8591
+ }
8584
8592
  var TASK_RESULT_CHECKPOINT_CONTROL_PREFIX = "task-checkpoint:";
8585
8593
  function createDurableTaskPrimitive(input) {
8586
8594
  return async (name, options, stageFailFastScope) => {
@@ -8601,8 +8609,8 @@ function createDurableTaskPrimitive(input) {
8601
8609
  durableParentIds: [...topology.parentIds]
8602
8610
  } : {},
8603
8611
  ...durableIntercomGroup !== undefined ? { durableIntercomGroup } : {},
8604
- ...session?.sessionFile !== undefined ? {
8605
- resumeFromSessionFile: session.sessionFile,
8612
+ ...session?.sessionId !== undefined ? {
8613
+ resumeFromSessionId: session.sessionId,
8606
8614
  routerSelection: session.routerSelection,
8607
8615
  durableAccumulatedDurationMs: session.durationMs ?? 0
8608
8616
  } : {}
@@ -8619,6 +8627,9 @@ function createDurableTaskPrimitive(input) {
8619
8627
  });
8620
8628
  const signal = mergeAbortSignals(input.signal, tailController.signal);
8621
8629
  try {
8630
+ await input.beforeCheckpoint?.();
8631
+ if (signal?.aborted)
8632
+ throw abortReasonError(signal);
8622
8633
  await awaitAbortable(signal, recordCheckpointDurably(input.backend, {
8623
8634
  kind: "stage",
8624
8635
  workflowId: input.workflowId,
@@ -8750,6 +8761,7 @@ function wrapSchemaStageForDurability(input) {
8750
8761
  value: async (text, options) => {
8751
8762
  const result = await stage.prompt(text, options);
8752
8763
  if (typeof result !== "string" || result.length === 0) {
8764
+ await input.beforeCheckpoint?.();
8753
8765
  await recordCheckpointDurably(input.backend, {
8754
8766
  kind: "stage",
8755
8767
  workflowId: input.workflowId,
@@ -8894,7 +8906,6 @@ function stableCheckpointId(kind, replayKey) {
8894
8906
  function stageSessionCheckpointId(replayKey, stage, durationMs) {
8895
8907
  return `${stableCheckpointId("stage-session", replayKey)}:${durableHash({
8896
8908
  sessionId: stage.sessionId ?? "",
8897
- sessionFile: stage.sessionFile ?? "",
8898
8909
  startedAt: stage.startedAt ?? 0,
8899
8910
  durationMs
8900
8911
  })}`;
@@ -9024,8 +9035,8 @@ function createDurableChildWorkflowPrimitive(input) {
9024
9035
  }
9025
9036
 
9026
9037
  // dist/builtin/workflows/src/durable/factory.ts
9027
- import { resolve } from "node:path";
9028
- import { SettingsManager } from "@bastani/atomic";
9038
+ import { getAgentDir as getAgentDir3, SettingsManager } from "@bastani/atomic";
9039
+ import { storageSelectionKey } from "@bastani/atomic/storage";
9029
9040
 
9030
9041
  // dist/builtin/workflows/src/durable/journal/journal-backend.ts
9031
9042
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
@@ -9241,17 +9252,11 @@ class PromptReservationState {
9241
9252
 
9242
9253
  // dist/builtin/workflows/src/durable/journal/journal-backend.ts
9243
9254
  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) {
9255
+ function* invoke(action) {
9249
9256
  try {
9250
9257
  const result = action();
9251
- if (synchronous)
9252
- return result;
9253
9258
  let value;
9254
- yield Promise.resolve(result).then((resolved) => {
9259
+ yield result.then((resolved) => {
9255
9260
  value = resolved;
9256
9261
  });
9257
9262
  return value;
@@ -9261,10 +9266,17 @@ function* invoke(action, synchronous = false) {
9261
9266
  throw new StorageUnavailableError({ adapter: "custom", location: "custom journal" }, error instanceof Error ? error : new Error(String(error)));
9262
9267
  }
9263
9268
  }
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)));
9269
+ async function execute(operation) {
9270
+ let step = operation.next();
9271
+ while (!step.done) {
9272
+ try {
9273
+ await step.value;
9274
+ step = operation.next();
9275
+ } catch (error) {
9276
+ step = operation.throw(error);
9277
+ }
9278
+ }
9279
+ return step.value;
9268
9280
  }
9269
9281
 
9270
9282
  class JournalOwnershipError extends WorkflowInstanceOwnershipError {
@@ -9324,31 +9336,31 @@ class JournalDurableBackend {
9324
9336
  ownsJournal;
9325
9337
  persistent;
9326
9338
  projection = createJournalProjection();
9327
- synchronous;
9328
9339
  sequences = new Map;
9329
9340
  leases = new Map;
9330
9341
  executions = new Map;
9331
9342
  executionContext = new AsyncLocalStorage2;
9332
9343
  pending = new Map;
9344
+ catalogQueue = Symbol("catalog");
9333
9345
  lost = new Map;
9334
9346
  prompts = new Map;
9335
9347
  timer;
9336
- closed = false;
9348
+ state = "open";
9349
+ closing;
9350
+ renewing;
9351
+ mutationContext = new AsyncLocalStorage2;
9337
9352
  processExitCleanup;
9338
- constructor(journal, holderId = `${PROCESS_HOLDER_ID}:${randomUUID4()}`, rebuild, ownsJournal = true) {
9353
+ unregisterExecutionStorages = registerExecutionStorages(this.executionContext, this.mutationContext);
9354
+ constructor(journal, holderId = `${PROCESS_HOLDER_ID}:${randomUUID4()}`, ownsJournal = true) {
9339
9355
  this.journal = journal;
9340
9356
  this.holderId = holderId;
9341
9357
  this.ownsJournal = ownsJournal;
9342
- this.synchronous = synchronousJournal(journal);
9343
9358
  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
9359
  }
9348
9360
  static async open(journal, options = {}) {
9349
9361
  let backend;
9350
9362
  try {
9351
- backend = new JournalDurableBackend(journal, undefined, DEFER_REBUILD, options.ownsJournal ?? true);
9363
+ backend = new JournalDurableBackend(journal, undefined, options.ownsJournal ?? true);
9352
9364
  for (const run of await journal.listRuns())
9353
9365
  for await (const entry of journal.read(run.runId))
9354
9366
  backend.fold(entry);
@@ -9364,21 +9376,31 @@ class JournalDurableBackend {
9364
9376
  throw new StorageUnavailableError({ adapter: "custom", location: "custom journal" }, error instanceof Error ? error : new Error(String(error)));
9365
9377
  }
9366
9378
  }
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;
9379
+ serialize(runId, action, requiresActiveExecution = true) {
9380
+ try {
9381
+ this.ensureOpen();
9382
+ if (requiresActiveExecution)
9383
+ this.assertExecutionActive(runId);
9384
+ } catch (error) {
9385
+ return Promise.reject(error);
9386
+ }
9387
+ const admitted = new Set([...this.executionContext.getStore()?.values() ?? []].filter((execution) => !execution.retired));
9388
+ return this.enqueue(runId, action, admitted);
9389
+ }
9390
+ enqueue(runId, action, admitted = this.mutationContext.getStore() ?? new Set) {
9391
+ const prior = this.pending.get(runId) ?? Promise.resolve();
9392
+ const result = prior.then(() => this.mutationContext.run(admitted, () => execute(action())));
9374
9393
  const settled = result.then(() => {}, () => {});
9375
9394
  this.pending.set(runId, settled);
9376
- return result.finally(() => {
9395
+ settled.then(() => {
9377
9396
  if (this.pending.get(runId) === settled)
9378
9397
  this.pending.delete(runId);
9379
9398
  });
9399
+ return result;
9380
9400
  }
9381
9401
  fold(entry) {
9402
+ if (entry.seq <= (this.sequences.get(entry.runId) ?? 0))
9403
+ return;
9382
9404
  const event = entry.event;
9383
9405
  if (event.type === RUN_EVENT_TYPES.checkpointRecorded) {
9384
9406
  const checkpoint = event.payload;
@@ -9413,8 +9435,6 @@ class JournalDurableBackend {
9413
9435
  this.sequences.set(entry.runId, entry.seq);
9414
9436
  }
9415
9437
  *entries(runId, fromSeq) {
9416
- if (this.synchronous !== undefined)
9417
- return this.synchronous.readEntries(runId, fromSeq);
9418
9438
  return yield* invoke(async () => {
9419
9439
  const entries = [];
9420
9440
  for await (const entry of this.journal.read(runId, fromSeq))
@@ -9438,7 +9458,7 @@ class JournalDurableBackend {
9438
9458
  }
9439
9459
  *current(runId) {
9440
9460
  this.ensureOpen();
9441
- this.assertExecutionActive(runId);
9461
+ this.assertExecutionActive(runId, true);
9442
9462
  yield* this.refresh(runId);
9443
9463
  if (this.projection.getWorkflow(runId) === undefined)
9444
9464
  return;
@@ -9454,24 +9474,24 @@ class JournalDurableBackend {
9454
9474
  return this.projection.getWorkflow(runId);
9455
9475
  }
9456
9476
  ensureOpen() {
9457
- if (this.closed)
9477
+ if (this.state === "closed" || this.state === "closing" && !this.mutationContext.getStore())
9458
9478
  throw new JournalBackendClosedError;
9459
9479
  }
9460
- assertExecutionActive(runId) {
9461
- for (const execution of this.executionContext.getStore()?.values() ?? [])
9462
- if (execution.retired)
9463
- throw new JournalExecutionRetiredError(runId);
9480
+ assertExecutionActive(runId, admitted = false) {
9481
+ for (const [executionRunId, execution] of this.executionContext.getStore() ?? [])
9482
+ if (execution.retired && !(admitted && this.mutationContext.getStore()?.has(execution)))
9483
+ throw new JournalExecutionRetiredError(typeof runId === "string" ? runId : executionRunId);
9464
9484
  }
9465
9485
  *ownership(runId) {
9466
9486
  this.ensureOpen();
9467
- this.assertExecutionActive(runId);
9487
+ this.assertExecutionActive(runId, true);
9468
9488
  const lost = this.lost.get(runId);
9469
9489
  if (lost)
9470
9490
  throw lost;
9471
9491
  const existing = this.leases.get(runId);
9472
9492
  if (existing)
9473
9493
  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);
9494
+ const result = yield* invoke(() => this.journal.takeoverExpired(runId, this.holderId, FOREIGN_LIVE_WORKFLOW_WINDOW_MS));
9475
9495
  if (result.status === "held")
9476
9496
  throw new JournalOwnershipError(runId, result.holderId);
9477
9497
  this.leases.set(runId, result.lease);
@@ -9481,7 +9501,7 @@ class JournalDurableBackend {
9481
9501
  }, STAGE_SESSION_HEARTBEAT_INTERVAL_MS);
9482
9502
  this.timer.unref();
9483
9503
  }
9484
- const execution = this.executions.get(runId);
9504
+ const execution = this.executionContext.getStore()?.get(runId) ?? this.executions.get(runId);
9485
9505
  if (execution !== undefined)
9486
9506
  execution.lease = result.lease;
9487
9507
  yield* this.rebuild(runId);
@@ -9493,7 +9513,7 @@ class JournalDurableBackend {
9493
9513
  let failure = new JournalOwnershipError(runId, null, error);
9494
9514
  this.lost.set(runId, failure);
9495
9515
  try {
9496
- const current = yield* invoke(() => this.synchronous !== undefined ? this.synchronous.leaseStateSync(runId) : this.journal.leaseState(runId), this.synchronous !== undefined);
9516
+ const current = yield* invoke(() => this.journal.leaseState(runId));
9497
9517
  failure = new JournalOwnershipError(runId, current?.holderId ?? null, error);
9498
9518
  this.lost.set(runId, failure);
9499
9519
  } catch {}
@@ -9502,8 +9522,8 @@ class JournalDurableBackend {
9502
9522
  *append(runId, event, options) {
9503
9523
  const lease = yield* this.ownership(runId);
9504
9524
  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);
9525
+ const outcome = yield* invoke(() => this.journal.append(lease, event, options));
9526
+ this.fold(outcome.entry);
9507
9527
  } catch (error) {
9508
9528
  if (error instanceof Error)
9509
9529
  throw yield* this.mapOwnership(error, runId);
@@ -9520,11 +9540,11 @@ class JournalDurableBackend {
9520
9540
  draft.registerWorkflow(handle, true);
9521
9541
  return draft;
9522
9542
  }
9523
- registerWorkflow(input) {
9543
+ commitWorkflowRegistration(input) {
9524
9544
  return this.serialize(input.workflowId, () => this.register(input));
9525
9545
  }
9526
9546
  *register(input) {
9527
- this.assertExecutionActive(input.workflowId);
9547
+ this.assertExecutionActive(input.workflowId, true);
9528
9548
  this.ensureOpen();
9529
9549
  const header = {
9530
9550
  runId: input.workflowId,
@@ -9534,7 +9554,7 @@ class JournalDurableBackend {
9534
9554
  status: input.status,
9535
9555
  inputs: input.inputs
9536
9556
  };
9537
- yield* invoke(() => this.synchronous?.createRunSync(header) ?? this.journal.createRun(header), this.synchronous !== undefined);
9557
+ yield* invoke(() => this.journal.createRun(header));
9538
9558
  yield* this.ownership(input.workflowId);
9539
9559
  yield* this.refresh(input.workflowId);
9540
9560
  const draft = yield* this.draft(input.workflowId);
@@ -9545,7 +9565,9 @@ class JournalDurableBackend {
9545
9565
  if (checkpoint.kind === "stage" && checkpoint.topology?.boundary !== undefined && typeof checkpoint.topology.boundary.invocationFingerprint !== "string")
9546
9566
  throw new DurableNestedTopologyError(`missing invocation fingerprint at ${checkpoint.checkpointId}`);
9547
9567
  }
9548
- recordCheckpoint(checkpoint) {
9568
+ commitCheckpoint(checkpoint, options) {
9569
+ if (options?.signal?.aborted)
9570
+ return Promise.reject(new JournalOperationAbortedError(checkpoint.workflowId, options.signal.reason instanceof Error ? options.signal.reason : undefined));
9549
9571
  return this.serialize(checkpoint.workflowId, () => this.checkpoint(checkpoint));
9550
9572
  }
9551
9573
  *checkpoint(checkpoint) {
@@ -9556,14 +9578,9 @@ class JournalDurableBackend {
9556
9578
  key: JSON.stringify([RUN_EVENT_TYPES.checkpointRecorded, checkpoint.kind, checkpoint.checkpointId])
9557
9579
  });
9558
9580
  }
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) {
9581
+ async commitAdditiveCheckpointBestEffort(checkpoint) {
9565
9582
  try {
9566
- await this.recordCheckpointAsync(checkpoint);
9583
+ await this.commitCheckpoint(checkpoint);
9567
9584
  return true;
9568
9585
  } catch (error) {
9569
9586
  if (!(error instanceof StorageUnavailableError))
@@ -9572,13 +9589,7 @@ class JournalDurableBackend {
9572
9589
  }
9573
9590
  }
9574
9591
  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));
9592
+ return this.serialize(runId, () => this.probeOwnership(runId), false);
9582
9593
  }
9583
9594
  *probeOwnership(runId) {
9584
9595
  this.ensureOpen();
@@ -9587,7 +9598,7 @@ class JournalDurableBackend {
9587
9598
  return "available";
9588
9599
  return lease.holderId === this.holderId ? "local" : "foreign";
9589
9600
  }
9590
- setWorkflowStatus(runId, status, pendingPrompts, resumable, failure) {
9601
+ commitWorkflowStatus(runId, status, pendingPrompts, resumable, failure) {
9591
9602
  return this.serialize(runId, () => this.setStatus(runId, status, pendingPrompts, resumable, failure));
9592
9603
  }
9593
9604
  *setStatus(runId, status, pendingPrompts, resumable, failure) {
@@ -9597,7 +9608,7 @@ class JournalDurableBackend {
9597
9608
  if (handle)
9598
9609
  yield* this.snapshot(handle);
9599
9610
  }
9600
- async transitionWorkflowStatus(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
9611
+ async commitWorkflowStatusTransition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
9601
9612
  return await this.serialize(runId, () => this.transition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner));
9602
9613
  }
9603
9614
  *transition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
@@ -9647,7 +9658,7 @@ class JournalDurableBackend {
9647
9658
  });
9648
9659
  return result;
9649
9660
  }
9650
- adjustPendingPrompts(runId, delta) {
9661
+ commitPendingPromptAdjustment(runId, delta) {
9651
9662
  return this.serialize(runId, () => this.promptChange(runId, delta >= 0 ? RUN_EVENT_TYPES.promptAsked : RUN_EVENT_TYPES.promptReleased, (state) => state.adjust(delta)));
9652
9663
  }
9653
9664
  promptReservationScope(runId) {
@@ -9753,12 +9764,14 @@ class JournalDurableBackend {
9753
9764
  return this.getPendingStageMessageDeliveryCount(runId, messageId, logicalRunId);
9754
9765
  }
9755
9766
  async hydrateWorkflow(runId) {
9756
- await this.serialize(runId, () => this.rebuild(runId));
9767
+ await this.serialize(runId, () => this.rebuild(runId), false);
9757
9768
  }
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);
9769
+ hydrateResumableWorkflows() {
9770
+ return this.serialize(this.catalogQueue, () => invoke(async () => {
9771
+ const runs = await this.journal.listRuns();
9772
+ for (const runId of new Set([...this.sequences.keys(), ...runs.map((run) => run.runId)]))
9773
+ await this.hydrateWorkflow(runId);
9774
+ }));
9762
9775
  }
9763
9776
  async prepareWorkflowCatalog() {
9764
9777
  await this.hydrateResumableWorkflows();
@@ -9767,13 +9780,7 @@ class JournalDurableBackend {
9767
9780
  *deleteOwned(runId, expectSeq) {
9768
9781
  try {
9769
9782
  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));
9783
+ yield* invoke(() => this.journal.deleteOwnedRun(lease, expectSeq));
9777
9784
  } catch (error) {
9778
9785
  if (!(error instanceof RunNotFoundError)) {
9779
9786
  if (error instanceof Error)
@@ -9814,27 +9821,33 @@ class JournalDurableBackend {
9814
9821
  }
9815
9822
  }
9816
9823
  }
9817
- reset() {
9818
- return execute(this.resetJournal());
9824
+ commitReset() {
9825
+ return this.serialize(this.catalogQueue, () => this.resetJournal());
9819
9826
  }
9820
9827
  *resetJournal() {
9821
- const runs = yield* invoke(() => this.synchronous?.listRunsSync() ?? this.journal.listRuns(), this.synchronous !== undefined);
9828
+ const runIds = new Set(this.sequences.keys());
9829
+ const runs = yield* invoke(() => this.journal.listRuns());
9822
9830
  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() {
9831
+ runIds.add(run.runId);
9832
+ for (const runId of runIds)
9833
+ yield this.enqueue(runId, () => this.deleteOwned(runId));
9834
+ }
9835
+ renewLeases() {
9836
+ if (this.renewing !== undefined)
9837
+ return this.renewing;
9838
+ if (this.state !== "open")
9839
+ return Promise.resolve();
9840
+ this.renewing = this.renewOwnedLeases().finally(() => {
9841
+ this.renewing = undefined;
9842
+ });
9843
+ return this.renewing;
9844
+ }
9845
+ async renewOwnedLeases() {
9835
9846
  for (const [runId, lease] of this.leases) {
9847
+ if (this.state !== "open")
9848
+ return;
9836
9849
  try {
9837
- await this.serialize(runId, () => this.renewLease(runId, lease));
9850
+ await this.serialize(runId, () => this.renewLease(runId, lease), false);
9838
9851
  } catch (error) {
9839
9852
  if (error instanceof Error)
9840
9853
  this.lost.set(runId, error);
@@ -9846,11 +9859,7 @@ class JournalDurableBackend {
9846
9859
  if (this.leases.get(runId) !== lease || this.lost.has(runId))
9847
9860
  return;
9848
9861
  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);
9862
+ yield* invoke(() => this.journal.renew(lease));
9854
9863
  } catch (error) {
9855
9864
  if (this.leases.get(runId) === lease) {
9856
9865
  if (error instanceof Error)
@@ -9903,23 +9912,20 @@ class JournalDurableBackend {
9903
9912
  execution.retired = true;
9904
9913
  if (this.executions.get(runId) === execution)
9905
9914
  this.executions.delete(runId);
9906
- if (execution.lease !== undefined && this.leases.get(runId) === execution.lease)
9907
- return this.serialize(runId, () => this.release(runId));
9915
+ if (this.state !== "open")
9916
+ return this.closing;
9917
+ return this.serialize(runId, () => this.release(runId, execution), false);
9908
9918
  }
9909
9919
  releaseWorkflow(runId) {
9910
9920
  this.assertExecutionActive(runId);
9911
9921
  return this.serialize(runId, () => this.release(runId));
9912
9922
  }
9913
- *release(runId) {
9923
+ *release(runId, execution) {
9914
9924
  const lease = this.leases.get(runId);
9915
- if (lease === undefined)
9925
+ if (lease === undefined || execution !== undefined && execution.lease !== lease)
9916
9926
  return;
9917
9927
  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);
9928
+ yield* invoke(() => this.journal.release(lease));
9923
9929
  } catch (error) {
9924
9930
  if (!(error instanceof StaleLeaseError))
9925
9931
  throw error;
@@ -9930,31 +9936,38 @@ class JournalDurableBackend {
9930
9936
  dropLease(runId) {
9931
9937
  this.leases.delete(runId);
9932
9938
  if (this.leases.size === 0) {
9933
- clearInterval(this.timer);
9939
+ if (this.timer !== undefined)
9940
+ clearInterval(this.timer);
9934
9941
  this.timer = undefined;
9935
9942
  }
9936
9943
  }
9937
- *releaseAll() {
9938
- for (const runId of this.leases.keys())
9939
- yield* this.release(runId);
9940
- }
9941
- async close() {
9944
+ close() {
9945
+ if (this.closing !== undefined)
9946
+ return this.closing;
9947
+ this.state = "closing";
9942
9948
  if (this.processExitCleanup !== undefined) {
9943
9949
  process.off("exit", this.processExitCleanup);
9944
9950
  this.processExitCleanup = undefined;
9945
9951
  }
9946
- if (this.closed)
9947
- return;
9948
9952
  if (this.timer !== undefined)
9949
9953
  clearInterval(this.timer);
9950
- if (this.pending.size > 0)
9951
- await Promise.all(this.pending.values());
9954
+ this.timer = undefined;
9955
+ this.closing = this.drainAndClose();
9956
+ return this.closing;
9957
+ }
9958
+ async drainAndClose() {
9952
9959
  try {
9953
- const released = execute(this.releaseAll());
9954
- if (isPromise(released))
9955
- await released;
9960
+ await this.renewing;
9961
+ while (this.pending.size > 0)
9962
+ await Promise.all(this.pending.values());
9963
+ for (const runId of this.leases.keys())
9964
+ await execute(this.release(runId));
9956
9965
  } finally {
9957
- this.closed = true;
9966
+ if (this.timer !== undefined)
9967
+ clearInterval(this.timer);
9968
+ this.timer = undefined;
9969
+ this.state = "closed";
9970
+ this.unregisterExecutionStorages();
9958
9971
  if (this.ownsJournal)
9959
9972
  await execute(invoke(() => this.journal.close()));
9960
9973
  }
@@ -9962,24 +9975,25 @@ class JournalDurableBackend {
9962
9975
  }
9963
9976
 
9964
9977
  // dist/builtin/workflows/src/durable/factory.ts
9965
- var DEFAULT_MEMORY_JOURNAL = "memory";
9966
9978
  async function initializeDurableBackend(options = {}) {
9967
9979
  const owner = getDurableBackendProcessOwner();
9968
9980
  const choice = options.journal;
9969
9981
  const selection = selectRunJournal({
9970
9982
  journal: choice,
9971
- settings: choice === undefined ? options.settings ?? SettingsManager.create(options.cwd ?? process.cwd()).getSettings() : undefined
9983
+ settings: choice === undefined ? options.settings ?? SettingsManager.create(options.cwd ?? process.cwd(), getAgentDir3(), {
9984
+ projectTrusted: options.projectTrusted
9985
+ }).getSettings() : undefined
9972
9986
  });
9973
- const key = "createRun" in selection ? selection : ("path" in selection) ? resolve(selection.path) : ("database" in selection) ? selection.database : choice === undefined ? DEFAULT_MEMORY_JOURNAL : choice;
9987
+ const key = "createRun" in selection ? selection : selection.kind === "memory" && choice !== undefined ? choice : storageSelectionKey(selection, getAgentDir3());
9974
9988
  const ownsJournal = choice === undefined || !("createRun" in choice);
9975
9989
  owner.selectedBackends ??= new Map;
9976
9990
  const selected = owner.selectedBackends;
9977
9991
  const existing = selected.get(key);
9978
- let backend;
9992
+ let ready;
9979
9993
  if (existing !== undefined) {
9980
- backend = await existing.ready;
9994
+ ready = existing.ready;
9981
9995
  } else {
9982
- const ready = resolveRunJournal({ journal: selection }).then((journal) => JournalDurableBackend.open(journal, { ownsJournal })).then((opened) => {
9996
+ ready = openSelectedRunJournal(selection).then((journal) => JournalDurableBackend.open(journal, { ownsJournal })).then((opened) => {
9983
9997
  if (ownsJournal)
9984
9998
  opened.closeOnProcessExit();
9985
9999
  entry.close = () => opened.close();
@@ -9990,9 +10004,8 @@ async function initializeDurableBackend(options = {}) {
9990
10004
  });
9991
10005
  const entry = { ready };
9992
10006
  selected.set(key, entry);
9993
- backend = await ready;
9994
10007
  }
9995
- return backend;
10008
+ return withRunJournalConfigSource(selection, () => ready);
9996
10009
  }
9997
10010
 
9998
10011
  // dist/builtin/workflows/src/shared/persistence-restore-helpers.ts
@@ -10656,7 +10669,7 @@ async function recordRunTimingCheckpointAsync(backend, run, options) {
10656
10669
  return false;
10657
10670
  for (const checkpoint of checkpoints)
10658
10671
  if (checkpoint !== undefined)
10659
- await backend.recordCheckpointAsync(checkpoint);
10672
+ await backend.commitCheckpoint(checkpoint);
10660
10673
  return true;
10661
10674
  }
10662
10675
  function runTimingCheckpoint(backend, run, options) {
@@ -10709,17 +10722,17 @@ function inheritedRunElapsedMs(input) {
10709
10722
 
10710
10723
  // dist/builtin/workflows/src/durable/workflow-status-transition.ts
10711
10724
  async function transitionDurableWorkflowStatus(backend, workflowId, expectedStatuses, status, pendingPrompts, resumable) {
10712
- return await backend.transitionWorkflowStatus(workflowId, expectedStatuses, status, pendingPrompts, resumable);
10725
+ return await backend.commitWorkflowStatusTransition(workflowId, expectedStatuses, status, pendingPrompts, resumable);
10713
10726
  }
10714
10727
 
10715
10728
  // dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts
10716
- import { isAbsolute as isAbsolute8, join as join11, resolve as resolve9 } from "node:path";
10729
+ import { isAbsolute as isAbsolute8, join as join11, resolve as resolve8 } from "node:path";
10717
10730
  import { CONFIG_DIR_NAME } from "@bastani/atomic";
10718
10731
 
10719
10732
  // dist/builtin/workflows/src/shared/workflow-artifacts.ts
10720
10733
  import { mkdir, readdir, rm, stat } from "node:fs/promises";
10721
10734
  import { dirname as dirname3, join as join4 } from "node:path";
10722
- import { getAgentDir as getAgentDir3, getEnvValue } from "@bastani/atomic";
10735
+ import { getAgentDir as getAgentDir4, getEnvValue } from "@bastani/atomic";
10723
10736
  // dist/builtin/workflows/src/shared/workflow-artifact-env.ts
10724
10737
  var WORKFLOW_ARTIFACT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
10725
10738
  var ENV_WORKFLOW_ARTIFACT_DIR = "ATOMIC_WORKFLOW_ARTIFACT_DIR";
@@ -10732,7 +10745,7 @@ function workflowArtifactRoot() {
10732
10745
  const override = getEnvValue(ENV_WORKFLOW_ARTIFACT_DIR);
10733
10746
  if (override !== undefined && override.length > 0)
10734
10747
  return override;
10735
- return join4(dirname3(getAgentDir3()), "workflows");
10748
+ return join4(dirname3(getAgentDir4()), "workflows");
10736
10749
  }
10737
10750
  function workflowArtifactRunsRoot() {
10738
10751
  return join4(workflowArtifactRoot(), "runs");
@@ -11996,7 +12009,7 @@ function cleanupWorktrees(setup) {
11996
12009
  }
11997
12010
  // dist/builtin/workflows/src/runs/shared/worktree-cwd.ts
11998
12011
  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";
12012
+ import { dirname as dirname8, isAbsolute as isAbsolute6, relative as relative4, resolve as resolve6, sep as sep5 } from "node:path";
12000
12013
  function relativePathWithin(root, candidate) {
12001
12014
  const path = relative4(root, candidate);
12002
12015
  return path === ".." || path.startsWith(`..${sep5}`) || isAbsolute6(path) ? undefined : path;
@@ -12015,14 +12028,14 @@ function resolveWorktreeStageCwd(cwd, setup) {
12015
12028
  if (cwd === undefined || cwd.length === 0)
12016
12029
  return;
12017
12030
  const absoluteInput = isAbsolute6(cwd);
12018
- const candidate = absoluteInput ? cwd : resolve7(setup.cwd, cwd);
12031
+ const candidate = absoluteInput ? cwd : resolve6(setup.cwd, cwd);
12019
12032
  if (!absoluteInput && relativePathWithin(setup.worktreeRoot, candidate) === undefined) {
12020
12033
  throw new Error(`atomic-workflows: relative cwd ${cwd} escapes gitWorktreeDir ${setup.worktreeRoot}; choose a cwd inside the worktree.`);
12021
12034
  }
12022
12035
  const candidateRealPath = existingRealPath(candidate, "cwd");
12023
12036
  const worktreeRelative = relativePathWithin(worktreeRoot, candidateRealPath);
12024
12037
  if (worktreeRelative !== undefined)
12025
- return resolve7(setup.worktreeRoot, worktreeRelative);
12038
+ return resolve6(setup.worktreeRoot, worktreeRelative);
12026
12039
  if (!isAbsolute6(cwd)) {
12027
12040
  throw new Error(`atomic-workflows: relative cwd ${cwd} escapes gitWorktreeDir ${setup.worktreeRoot}; choose a path that remains inside the selected worktree.`);
12028
12041
  }
@@ -12033,7 +12046,7 @@ function resolveWorktreeStageCwd(cwd, setup) {
12033
12046
  if (repositoryRelative === undefined) {
12034
12047
  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
12048
  }
12036
- const mappedCwd = resolve7(setup.worktreeRoot, repositoryRelative);
12049
+ const mappedCwd = resolve6(setup.worktreeRoot, repositoryRelative);
12037
12050
  const mappedRealPath = existingRealPath(mappedCwd, "remapped worktree cwd");
12038
12051
  if (relativePathWithin(worktreeRoot, mappedRealPath) === undefined) {
12039
12052
  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 +12056,7 @@ function resolveWorktreeStageCwd(cwd, setup) {
12043
12056
 
12044
12057
  // dist/builtin/workflows/src/runs/foreground/executor-task-prompts.ts
12045
12058
  import { existsSync as existsSync3 } from "node:fs";
12046
- import { isAbsolute as isAbsolute7, resolve as resolve8 } from "node:path";
12059
+ import { isAbsolute as isAbsolute7, resolve as resolve7 } from "node:path";
12047
12060
  function normalizeTaskContexts(previous) {
12048
12061
  if (previous === undefined)
12049
12062
  return [];
@@ -12096,7 +12109,7 @@ function taskPrevious(options) {
12096
12109
  function resolveWorkflowPath(filePath, baseDir) {
12097
12110
  if (isAbsolute7(filePath))
12098
12111
  return filePath;
12099
- return resolve8(baseDir ?? process.cwd(), filePath);
12112
+ return resolve7(baseDir ?? process.cwd(), filePath);
12100
12113
  }
12101
12114
  function taskBaseDir(options) {
12102
12115
  if (typeof options.chainDir === "string" && options.chainDir.trim().length > 0) {
@@ -12396,7 +12409,7 @@ function workflowInvocationMetadata(inputDefaults, workflowInvocationCwd, cache,
12396
12409
  function resolvedTaskCwd(cwd, workflowInvocationCwd) {
12397
12410
  if (cwd === undefined)
12398
12411
  return;
12399
- return isAbsolute8(cwd) ? cwd : resolve9(workflowInvocationCwd, cwd);
12412
+ return isAbsolute8(cwd) ? cwd : resolve8(workflowInvocationCwd, cwd);
12400
12413
  }
12401
12414
  function taskWorktreeOutputsRoot(runId) {
12402
12415
  return join11(workflowArtifactRunPath(runId), "task-outputs");
@@ -12409,7 +12422,7 @@ function prepareTaskWorktrees(tasks, options, runId, scope, workflowInvocationCw
12409
12422
  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
12423
  }
12411
12424
  const explicitCwd = tasks.find((task) => typeof task.cwd === "string")?.cwd;
12412
- const sharedCwd = explicitCwd === undefined ? workflowInvocationCwd : isAbsolute8(explicitCwd) ? explicitCwd : resolve9(workflowInvocationCwd, explicitCwd);
12425
+ const sharedCwd = explicitCwd === undefined ? workflowInvocationCwd : isAbsolute8(explicitCwd) ? explicitCwd : resolve8(workflowInvocationCwd, explicitCwd);
12413
12426
  const conflict = findWorktreeTaskCwdConflict(tasks.map((task) => ({ agent: task.name, cwd: resolvedTaskCwd(task.cwd, workflowInvocationCwd) })), sharedCwd);
12414
12427
  if (conflict !== undefined)
12415
12428
  throw new Error(formatWorktreeTaskCwdConflict(conflict, sharedCwd));
@@ -13793,6 +13806,19 @@ function createStageScheduler(input) {
13793
13806
  function createStageControlRegistry() {
13794
13807
  const _byRun = new Map;
13795
13808
  const pendingDisposals = new Set;
13809
+ const sessionStores = new Map;
13810
+ let generation = 0;
13811
+ function rememberSessionStore(handle) {
13812
+ const store = handle.sessionStore;
13813
+ if (store === undefined)
13814
+ return;
13815
+ let stores = sessionStores.get(handle.runId);
13816
+ if (stores === undefined) {
13817
+ stores = new Map;
13818
+ sessionStores.set(handle.runId, stores);
13819
+ }
13820
+ stores.set(handle.stageId, store);
13821
+ }
13796
13822
  function ensureRun(runId) {
13797
13823
  let runMap = _byRun.get(runId);
13798
13824
  if (!runMap) {
@@ -13880,7 +13906,11 @@ function createStageControlRegistry() {
13880
13906
  };
13881
13907
  }
13882
13908
  return {
13909
+ get generation() {
13910
+ return generation;
13911
+ },
13883
13912
  register(handle) {
13913
+ rememberSessionStore(handle);
13884
13914
  const runMap = ensureRun(handle.runId);
13885
13915
  const displaced = runMap.get(handle.stageId);
13886
13916
  runMap.set(handle.stageId, {
@@ -13897,6 +13927,7 @@ function createStageControlRegistry() {
13897
13927
  if (!existing)
13898
13928
  return;
13899
13929
  if (existing.get(handle.stageId)?.handle === handle) {
13930
+ rememberSessionStore(handle);
13900
13931
  existing.delete(handle.stageId);
13901
13932
  }
13902
13933
  if (existing.size === 0)
@@ -13982,6 +14013,7 @@ function createStageControlRegistry() {
13982
14013
  return false;
13983
14014
  if (handle !== undefined && entry.handle !== handle)
13984
14015
  return false;
14016
+ rememberSessionStore(entry.handle);
13985
14017
  if (!entry.controlsDependencies)
13986
14018
  return false;
13987
14019
  entry.controlsDependencies = false;
@@ -13999,6 +14031,9 @@ function createStageControlRegistry() {
13999
14031
  get(runId, stageId) {
14000
14032
  return _byRun.get(runId)?.get(stageId)?.handle;
14001
14033
  },
14034
+ getSessionStore(runId, stageId) {
14035
+ return _byRun.get(runId)?.get(stageId)?.handle.sessionStore ?? sessionStores.get(runId)?.get(stageId);
14036
+ },
14002
14037
  forRun(runId) {
14003
14038
  const runMap = _byRun.get(runId);
14004
14039
  if (!runMap)
@@ -14011,17 +14046,28 @@ function createStageControlRegistry() {
14011
14046
  run(runId) {
14012
14047
  return makeRunHandle(runId);
14013
14048
  },
14014
- async clear() {
14015
- const entries = [..._byRun.values()].flatMap((runMap) => [...runMap.values()]);
14016
- _byRun.clear();
14049
+ async clear(runId) {
14050
+ if (runId === undefined)
14051
+ generation += 1;
14052
+ const entries = runId === undefined ? [..._byRun.values()].flatMap((runMap) => [...runMap.values()]) : [..._byRun.get(runId)?.values() ?? []];
14053
+ if (runId === undefined) {
14054
+ _byRun.clear();
14055
+ sessionStores.clear();
14056
+ } else {
14057
+ _byRun.get(runId)?.clear();
14058
+ _byRun.delete(runId);
14059
+ sessionStores.delete(runId);
14060
+ }
14017
14061
  await disposeEntries(entries);
14018
14062
  },
14019
14063
  async clearDetached() {
14020
14064
  const entries = [];
14065
+ generation += 1;
14021
14066
  for (const [runId, runMap] of [..._byRun]) {
14022
14067
  for (const [stageId, entry] of [...runMap]) {
14023
14068
  if (entry.controlsDependencies)
14024
14069
  continue;
14070
+ rememberSessionStore(entry.handle);
14025
14071
  runMap.delete(stageId);
14026
14072
  entries.push(entry);
14027
14073
  }
@@ -14648,7 +14694,7 @@ function createTaskPrimitive(runtime) {
14648
14694
  }
14649
14695
  });
14650
14696
  const stage = stageHandle.context;
14651
- const promptText = resolvedTaskOptions.resumeFromSessionFile !== undefined ? RESUME_CONTINUATION_PROMPT : applyTaskContext(`${taskReadInstruction(resolvedTaskOptions)}${taskPrompt(resolvedTaskOptions)}`, taskPrevious(resolvedTaskOptions));
14697
+ const promptText = resolvedTaskOptions.resumeFromSessionId !== undefined ? RESUME_CONTINUATION_PROMPT : applyTaskContext(`${taskReadInstruction(resolvedTaskOptions)}${taskPrompt(resolvedTaskOptions)}`, taskPrevious(resolvedTaskOptions));
14652
14698
  const rawOutput = await stage.prompt(promptText, taskPromptOptions(resolvedTaskOptions));
14653
14699
  const structured = typeof rawOutput === "string" ? undefined : rawOutput;
14654
14700
  const text = truncateTaskOutput(structuredTaskOutputText(rawOutput), resolvedTaskOptions.maxOutput);
@@ -14738,6 +14784,7 @@ function wrapUiWithDurable(base, deps) {
14738
14784
  response,
14739
14785
  completedAt: Date.now()
14740
14786
  };
14787
+ await deps.beforeCheckpoint?.();
14741
14788
  await recordCheckpointDurably(deps.backend, checkpoint);
14742
14789
  };
14743
14790
  const cached = (identity) => deps.backend.getUiResponse(deps.workflowId, identity.hash);
@@ -15154,7 +15201,7 @@ async function finalizeDurableTerminalStatus(input) {
15154
15201
  ...input.runSnapshot.failureDisposition !== undefined ? { failureDisposition: input.runSnapshot.failureDisposition } : {},
15155
15202
  ...input.runSnapshot.failedToolNodeId !== undefined ? { failedToolNodeId: input.runSnapshot.failedToolNodeId } : {}
15156
15203
  } : undefined;
15157
- await input.durableBackend.setWorkflowStatus(input.runId, durableStatus, undefined, input.runSnapshot.resumable, failure);
15204
+ await input.durableBackend.commitWorkflowStatus(input.runId, durableStatus, undefined, input.runSnapshot.resumable, failure);
15158
15205
  }
15159
15206
  }
15160
15207
  function toDurableStatus(status) {
@@ -15259,7 +15306,7 @@ async function recordWorkflowHeartbeatAnchor(backend, record) {
15259
15306
  output: { anchorAt: record.anchorAt, intervalMinutes: record.intervalMinutes },
15260
15307
  completedAt: record.now
15261
15308
  };
15262
- const stored = await backend.recordAdditiveCheckpointBestEffort(checkpoint);
15309
+ const stored = await backend.commitAdditiveCheckpointBestEffort(checkpoint);
15263
15310
  if (!stored)
15264
15311
  return false;
15265
15312
  return readWorkflowHeartbeatAnchor(backend, record.runId) !== undefined;
@@ -15289,6 +15336,41 @@ function createDurableStageSessionRecorder(input) {
15289
15336
  };
15290
15337
  }
15291
15338
 
15339
+ // dist/builtin/workflows/src/shared/stage-session-store.ts
15340
+ import { randomUUID as randomUUID6 } from "node:crypto";
15341
+ import {
15342
+ JsonlSessionStore,
15343
+ resolveSessionStore,
15344
+ SessionManager
15345
+ } from "@bastani/atomic";
15346
+ async function stageSessionStore(options, defaultSessionDir) {
15347
+ if (options.sessionStore !== undefined)
15348
+ return options.sessionStore;
15349
+ if (options.sessionManager !== undefined)
15350
+ return options.sessionManager.getSessionStore();
15351
+ const directory = options.sessionDir ?? defaultSessionDir;
15352
+ if (directory !== undefined)
15353
+ return JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false });
15354
+ return resolveSessionStore(options.cwd ?? process.cwd(), {
15355
+ agentDir: options.agentDir,
15356
+ settings: options.settingsManager?.getSettings()
15357
+ });
15358
+ }
15359
+ async function forkStageSession(store, sessionId, cwd, options, destination = store) {
15360
+ const source = await store.load(sessionId);
15361
+ const id = randomUUID6();
15362
+ await destination.create({
15363
+ id,
15364
+ version: 4,
15365
+ createdAt: new Date().toISOString(),
15366
+ cwd,
15367
+ parentSessionId: sessionId,
15368
+ ...options.internal === true ? { internal: true } : {},
15369
+ ...options.workflow === undefined ? {} : { workflow: options.workflow }
15370
+ }, source.entries);
15371
+ return SessionManager.open(destination, id, cwd);
15372
+ }
15373
+
15292
15374
  // dist/builtin/workflows/src/durable/completed-catalog-stage-groups.ts
15293
15375
  function validBoundaryRecordSet(checkpoints, strict) {
15294
15376
  const stages = checkpoints.filter((item) => item.kind === "stage");
@@ -15665,9 +15747,6 @@ var SESSION_KEY6 = "workflows:job-tracker:v1";
15665
15747
  var singleton6 = createSessionScopedSingleton(SESSION_KEY6, createJobTracker);
15666
15748
  var jobTracker = singleton6.facade;
15667
15749
 
15668
- // dist/builtin/workflows/src/durable/fork-workflow.ts
15669
- import { SessionManager as SessionManager2 } from "@bastani/atomic";
15670
-
15671
15750
  // dist/builtin/workflows/src/shared/workflow-stage-target.ts
15672
15751
  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
15752
  var WORKFLOW_TARGET_PREFIX = "workflow:";
@@ -16060,6 +16139,7 @@ function createDurableStageDeps(input) {
16060
16139
  backend: input.backend,
16061
16140
  nextCheckpointId: input.nextCheckpointId,
16062
16141
  nextReplayKey: input.nextReplayKey,
16142
+ beforeCheckpoint: input.beforeCheckpoint,
16063
16143
  replayKeyForCompletedStage: (stage) => input.completedReplayKeys.get(stage.id),
16064
16144
  runTopology: durableRunTopology(input.run),
16065
16145
  sourceOrderForStage: (stage) => {
@@ -16110,7 +16190,8 @@ function createDurableStageTopologyResolver(backend, workflowId) {
16110
16190
  async function recordDurableActiveStage(deps, stage) {
16111
16191
  if (stage.replayKey === undefined || stage.status === "completed" || stage.status === "failed" || stage.status === "skipped")
16112
16192
  return false;
16113
- await deps.backend.recordCheckpointAsync({
16193
+ await deps.beforeCheckpoint?.();
16194
+ await deps.backend.commitCheckpoint({
16114
16195
  kind: "stage",
16115
16196
  workflowId: deps.workflowId,
16116
16197
  checkpointId: `stage-active-meta:${durableHash({ replayKey: stage.replayKey, stageId: stage.id })}`,
@@ -16143,7 +16224,7 @@ function createDurableCachedStageRecorder(input) {
16143
16224
  input.run.stages.sort((left, right) => (replaySourceOrders.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (replaySourceOrders.get(right.id) ?? Number.MAX_SAFE_INTEGER));
16144
16225
  }
16145
16226
  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({
16227
+ const persistence = stage === undefined ? undefined : input.backend.commitCheckpoint({
16147
16228
  kind: "stage",
16148
16229
  workflowId: input.run.id,
16149
16230
  checkpointId: `stage-replay-meta:${durableHash({ replayKey, stageId: stage.id, parentIds: stage.parentIds })}`,
@@ -16458,6 +16539,9 @@ function createAdmittedToolExecutionTracker(options = {}) {
16458
16539
  await drainRecordedFailures();
16459
16540
  };
16460
16541
  return {
16542
+ get closed() {
16543
+ return state === "CLOSED" || options.signal?.aborted === true;
16544
+ },
16461
16545
  track(execution) {
16462
16546
  if (state === "CLOSED" || options.signal?.aborted) {
16463
16547
  const error = new Error("atomic-workflows: ctx.tool admission is closed for this run");
@@ -16633,6 +16717,13 @@ function createTrackedToolPrimitive(input) {
16633
16717
  });
16634
16718
  const lifecycle = createToolNodeLifecycle(input);
16635
16719
  const budgetBoundary = input.budget.enabled ? () => input.budget.stopAtBoundaryAsync(input.run.stages.at(-1)?.name) : undefined;
16720
+ const assertToolAdmissionOpen = () => {
16721
+ const quit = input.toolAdmission.quitReason;
16722
+ if (quit !== undefined) {
16723
+ observedQuit ??= quit;
16724
+ throw quit;
16725
+ }
16726
+ };
16636
16727
  const tool = createToolPrimitive({
16637
16728
  workflowId: input.workflowId,
16638
16729
  ...input.checkpointSourceWorkflowId === undefined ? {} : { checkpointSourceWorkflowId: input.checkpointSourceWorkflowId },
@@ -16666,7 +16757,16 @@ function createTrackedToolPrimitive(input) {
16666
16757
  observedQuit ??= admission.error;
16667
16758
  return admission;
16668
16759
  },
16669
- ...budgetBoundary !== undefined ? { beforeToolCall: budgetBoundary, afterToolCall: budgetBoundary } : {},
16760
+ beforeToolCall: () => {
16761
+ const afterDrain = () => {
16762
+ const budget = budgetBoundary?.();
16763
+ return budget === undefined ? assertToolAdmissionOpen() : budget.then(assertToolAdmissionOpen);
16764
+ };
16765
+ const pending = input.beforeToolCall?.();
16766
+ return pending === undefined ? afterDrain() : pending.then(afterDrain);
16767
+ },
16768
+ beforeCheckpoint: input.beforeCheckpoint,
16769
+ ...budgetBoundary !== undefined ? { afterToolCall: budgetBoundary } : {},
16670
16770
  ...lifecycle
16671
16771
  });
16672
16772
  const abandonInFlightAsCancelled = (reason) => {
@@ -17572,12 +17672,12 @@ class StageToolExecutionBuffer {
17572
17672
  function createStageControlHandle(runtime) {
17573
17673
  const messagePreparation = () => {
17574
17674
  const meta = runtime.innerCtx.__sessionMeta();
17575
- if (meta.sessionId !== undefined || meta.sessionFile !== undefined) {
17675
+ if (meta.sessionId !== undefined) {
17576
17676
  return { beforePreparation: runtime.throwIfStageMutationBlocked };
17577
17677
  }
17578
- if (runtime.stageSnapshot.sessionFile !== undefined) {
17678
+ if (runtime.stageSnapshot.sessionId !== undefined) {
17579
17679
  return {
17580
- sessionFile: runtime.stageSnapshot.sessionFile,
17680
+ sessionId: runtime.stageSnapshot.sessionId,
17581
17681
  beforePreparation: runtime.throwIfStageMutationBlocked
17582
17682
  };
17583
17683
  }
@@ -17587,10 +17687,10 @@ function createStageControlHandle(runtime) {
17587
17687
  return { beforePreparation: runtime.throwIfStageMutationBlocked };
17588
17688
  };
17589
17689
  const ensureMessagingSession = async () => {
17590
- const sessionFile = messagePreparation().sessionFile;
17591
- if (sessionFile === undefined)
17690
+ const sessionId = messagePreparation().sessionId;
17691
+ if (sessionId === undefined)
17592
17692
  return;
17593
- await runtime.innerCtx.__ensureSessionFromFile(sessionFile);
17693
+ await runtime.innerCtx.__ensureSessionFromId(sessionId);
17594
17694
  await runtime.captureStageSessionMeta({ awaitDurable: true });
17595
17695
  };
17596
17696
  const toolExecutions = new StageToolExecutionBuffer;
@@ -17606,6 +17706,9 @@ function createStageControlHandle(runtime) {
17606
17706
  get status() {
17607
17707
  return runtime.stageSnapshot.status;
17608
17708
  },
17709
+ get sessionStore() {
17710
+ return runtime.innerCtx.__agentSession()?.sessionManager.getSessionStore();
17711
+ },
17609
17712
  get sessionId() {
17610
17713
  return runtime.innerCtx.__sessionMeta().sessionId ?? runtime.stageSnapshot.sessionId;
17611
17714
  },
@@ -17894,7 +17997,7 @@ function createReplayStageContext(input) {
17894
17997
  __getLastAssistantText: () => replayResult,
17895
17998
  getLastAssistantText: () => replayResult,
17896
17999
  __ensureSession: async () => {},
17897
- __ensureSessionFromFile: async () => {},
18000
+ __ensureSessionFromId: async () => {},
17898
18001
  __sealGeneration: () => {},
17899
18002
  __closeGeneration: async () => {},
17900
18003
  __sessionMeta: () => ({ sessionId: replaySource.sessionId, sessionFile: replaySource.sessionFile }),
@@ -17917,7 +18020,7 @@ function createReplayStageContext(input) {
17917
18020
  }
17918
18021
 
17919
18022
  // dist/builtin/workflows/src/shared/pending-stage-route-capability.ts
17920
- import { randomUUID as randomUUID6 } from "node:crypto";
18023
+ import { randomUUID as randomUUID7 } from "node:crypto";
17921
18024
  var routeCapabilitiesKey = Symbol.for("atomic-workflows/pending-stage-route-capabilities@1");
17922
18025
  var processState = globalThis;
17923
18026
  var routeCapabilities = processState[routeCapabilitiesKey] ?? new WeakMap;
@@ -17930,7 +18033,7 @@ function workflowPendingStageRouteCapability(store, runId) {
17930
18033
  }
17931
18034
  let capability = capabilities.get(runId);
17932
18035
  if (capability === undefined) {
17933
- capability = randomUUID6();
18036
+ capability = randomUUID7();
17934
18037
  capabilities.set(runId, capability);
17935
18038
  }
17936
18039
  return capability;
@@ -18987,7 +19090,7 @@ function assistantMessage(text) {
18987
19090
  }
18988
19091
 
18989
19092
  // dist/builtin/workflows/src/runs/foreground/stage-runner-options.ts
18990
- import { SessionManager as SessionManager3 } from "@bastani/atomic";
19093
+ import { SessionManager as SessionManager2 } from "@bastani/atomic";
18991
19094
  function workflowSessionOptions(meta) {
18992
19095
  return {
18993
19096
  internal: true,
@@ -19012,7 +19115,7 @@ async function stripWorkflowOnlyOptions2(options, defaultSessionDir, meta, pendi
19012
19115
  if (!options) {
19013
19116
  return defaultSessionDir === undefined ? { orchestrationContext } : {
19014
19117
  orchestrationContext,
19015
- sessionManager: await SessionManager3.create(process.cwd(), defaultSessionDir, classification)
19118
+ sessionManager: await SessionManager2.create(process.cwd(), defaultSessionDir, classification)
19016
19119
  };
19017
19120
  }
19018
19121
  const {
@@ -19024,8 +19127,9 @@ async function stripWorkflowOnlyOptions2(options, defaultSessionDir, meta, pendi
19024
19127
  inheritedModelConstraints: _inheritedModelConstraints,
19025
19128
  routerSelection: _routerSelection,
19026
19129
  context,
19027
- forkFromSessionFile,
19028
- resumeFromSessionFile,
19130
+ forkFromSessionId,
19131
+ resumeFromSessionId,
19132
+ sessionStore,
19029
19133
  durableReplayKey: _durableReplayKey,
19030
19134
  durableAccumulatedDurationMs: _durableAccumulatedDurationMs,
19031
19135
  durableStageId: _durableStageId,
@@ -19037,15 +19141,16 @@ async function stripWorkflowOnlyOptions2(options, defaultSessionDir, meta, pendi
19037
19141
  group: _group,
19038
19142
  ...sessionOptions
19039
19143
  } = 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);
19144
+ const cwd = sessionOptions.cwd ?? process.cwd();
19145
+ if (resumeFromSessionId !== undefined) {
19146
+ sessionOptions.sessionManager = await SessionManager2.open(await stageSessionStore(options, defaultSessionDir), resumeFromSessionId, cwd);
19147
+ } else if (context === "fork" && forkFromSessionId !== undefined) {
19148
+ sessionOptions.sessionManager = await forkStageSession(await stageSessionStore(options, defaultSessionDir), forkFromSessionId, cwd, classification);
19149
+ } else if (sessionOptions.sessionManager === undefined) {
19150
+ if (sessionStore !== undefined) {
19151
+ sessionOptions.sessionManager = await SessionManager2.create(sessionStore, cwd, classification);
19152
+ } else if ((sessionDir ?? defaultSessionDir) !== undefined) {
19153
+ sessionOptions.sessionManager = await SessionManager2.create(cwd, sessionDir ?? defaultSessionDir, classification);
19049
19154
  }
19050
19155
  }
19051
19156
  return {
@@ -19612,7 +19717,7 @@ class StageSessionController {
19612
19717
  sessionPromise;
19613
19718
  sessionShutdownPromise;
19614
19719
  bindingCleanupFailure;
19615
- reattachSessionFile;
19720
+ reattachSessionId;
19616
19721
  lastPromptStartIndex;
19617
19722
  attemptUsageStartIndex;
19618
19723
  discardedAttemptUsage = {
@@ -19868,9 +19973,9 @@ class StageSessionController {
19868
19973
  const ready = waitForStageStartup(this.sessionPromise, this.startupWait.signal);
19869
19974
  return this.modelRoute ? this.checkedSession(await ready) : ready;
19870
19975
  }
19871
- async ensureSessionFromFile(sessionFile, consumer = "prompt") {
19976
+ async ensureSessionFromId(sessionId, consumer = "prompt") {
19872
19977
  if (!this.sessionShutdownPromise && !this.sessionPromise && !this.session)
19873
- this.reattachSessionFile = sessionFile;
19978
+ this.reattachSessionId = sessionId;
19874
19979
  const session = await this.ensureSession(consumer);
19875
19980
  await session.closeWorkflowStageGeneration?.();
19876
19981
  return session;
@@ -19883,12 +19988,12 @@ class StageSessionController {
19883
19988
  return pausedDelivery;
19884
19989
  }
19885
19990
  preparation?.beforePreparation?.();
19886
- const sessionFile = preparation?.sessionFile;
19991
+ const sessionId = preparation?.sessionId;
19887
19992
  const deliver = async (activity) => {
19888
19993
  if (this.effectiveStageOptions?.model === "auto")
19889
19994
  await this.preparePrompt(typeof content === "string" ? content : content.filter((part) => part.type === "text").map((part) => part.text).join(`
19890
19995
  `));
19891
- const activeSession = sessionFile === undefined ? await this.ensureSession("prompt") : await this.ensureSessionFromFile(sessionFile, "prompt");
19996
+ const activeSession = sessionId === undefined ? await this.ensureSession("prompt") : await this.ensureSessionFromId(sessionId, "prompt");
19892
19997
  const pausedDelivery = this.pauseControl.deferRunnerOwnedDelivery(() => sendStageUserMessage(activeSession, content, options, beforeDelivery, release, this.messageAdmission, activity));
19893
19998
  if (pausedDelivery !== undefined) {
19894
19999
  release();
@@ -19896,7 +20001,7 @@ class StageSessionController {
19896
20001
  }
19897
20002
  return sendStageUserMessage(activeSession, content, options, beforeDelivery, release, this.messageAdmission, activity);
19898
20003
  };
19899
- if (this.session === undefined || sessionFile !== undefined)
20004
+ if (this.session === undefined || sessionId !== undefined)
19900
20005
  return this.deliveryActivity.runWithLease(() => deliver());
19901
20006
  return deliver(this.deliveryActivity);
19902
20007
  });
@@ -20436,7 +20541,7 @@ class StageSessionController {
20436
20541
  if (first === undefined) {
20437
20542
  return this.createSessionObservingPause(undefined, consumer).catch((error) => this.createInitialSessionWithRetry(undefined, consumer, { error }));
20438
20543
  }
20439
- if (this.reattachSessionFile !== undefined) {
20544
+ if (this.reattachSessionId !== undefined) {
20440
20545
  const resumed = await this.createSession(undefined, consumer, { restoreSavedModel: true });
20441
20546
  const restoredId = workflowModelId(resumed.model);
20442
20547
  const exactRestoredIndex = restoredId === undefined ? -1 : candidates.findIndex((entry) => entry.id === restoredId && entry.reasoningLevel === resumed.thinkingLevel);
@@ -20659,7 +20764,7 @@ class StageSessionController {
20659
20764
  ownsFallbackChain: this.hasExplicitModelFallbackConfig,
20660
20765
  scopedModels,
20661
20766
  restoreSavedModel: resumeOptions?.restoreSavedModel,
20662
- reattachSessionFile: this.reattachSessionFile,
20767
+ reattachSessionId: this.reattachSessionId,
20663
20768
  sharedModelRuntime: this.sharedModelRuntime,
20664
20769
  defaultCwd: this.opts.defaultCwd
20665
20770
  });
@@ -21008,7 +21113,7 @@ class StageSessionController {
21008
21113
  // dist/builtin/workflows/src/runs/foreground/stage-runner-output.ts
21009
21114
  import { createHash as createHash3 } from "node:crypto";
21010
21115
  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";
21116
+ import { basename as basename5, dirname as dirname9, isAbsolute as isAbsolute9, join as join12, resolve as resolve9 } from "node:path";
21012
21117
  var DEFAULT_MAX_OUTPUT_BYTES = 200 * 1024;
21013
21118
  var DEFAULT_MAX_OUTPUT_LINES = 5000;
21014
21119
  function normalizeMaxOutput2(maxOutput) {
@@ -21118,7 +21223,7 @@ function renderTranscript(messages, fallbackOutput) {
21118
21223
  `);
21119
21224
  }
21120
21225
  function savedOutputReference(outputPath, fullOutput, transcriptPathValue, transcriptText, transcriptAvailable, warning) {
21121
- const absolutePath = resolve10(outputPath);
21226
+ const absolutePath = resolve9(outputPath);
21122
21227
  const bytes = Buffer.byteLength(fullOutput, "utf8");
21123
21228
  const lines = countLines(fullOutput);
21124
21229
  const transcriptBytes = Buffer.byteLength(transcriptText, "utf8");
@@ -21133,8 +21238,8 @@ function resolveOutputPath(output, runtimeCwd, requestedCwd) {
21133
21238
  return;
21134
21239
  if (isAbsolute9(output))
21135
21240
  return output;
21136
- const baseCwd = requestedCwd === undefined ? runtimeCwd : isAbsolute9(requestedCwd) ? requestedCwd : resolve10(runtimeCwd, requestedCwd);
21137
- return resolve10(baseCwd, output);
21241
+ const baseCwd = requestedCwd === undefined ? runtimeCwd : isAbsolute9(requestedCwd) ? requestedCwd : resolve9(runtimeCwd, requestedCwd);
21242
+ return resolve9(baseCwd, output);
21138
21243
  }
21139
21244
  function degenerateWarning(fullOutput) {
21140
21245
  return fullOutput.trim().length === 0 ? "WARNING: the stage artifact is empty; search the companion transcript for this stage's work." : undefined;
@@ -21228,7 +21333,7 @@ function createStageContext2(opts) {
21228
21333
  const stageCwd = stageOptions?.cwd ?? stageOptions?.sessionManager?.getCwd() ?? agentSessionAdapterDefaultCwd(adapters.agentSession) ?? opts.defaultCwd ?? process.cwd();
21229
21334
  const structuredOutputCapture = stageOptions?.schema ? createStructuredOutputCapture() : undefined;
21230
21335
  const structuredOutputExecutionCapture = stageOptions?.schema ? {} : undefined;
21231
- const effectiveStageOptions = stageOptionsWithStructuredOutput(stageOptions, structuredOutputCapture, structuredOutputExecutionCapture);
21336
+ const effectiveStageOptions = stageOptionsWithStructuredOutput(adapters.sessionStore === undefined || stageOptions?.sessionStore !== undefined || stageOptions?.sessionDir !== undefined || stageOptions?.sessionManager !== undefined ? stageOptions : { ...stageOptions, sessionStore: adapters.sessionStore }, structuredOutputCapture, structuredOutputExecutionCapture);
21232
21337
  const meta = {
21233
21338
  runId,
21234
21339
  stageId,
@@ -21467,8 +21572,8 @@ ${nextPrompt}`;
21467
21572
  return;
21468
21573
  await controller.ensureSession();
21469
21574
  },
21470
- async __ensureSessionFromFile(sessionFile) {
21471
- await controller.ensureSessionFromFile(sessionFile);
21575
+ async __ensureSessionFromId(sessionId) {
21576
+ await controller.ensureSessionFromId(sessionId);
21472
21577
  },
21473
21578
  __sealGeneration() {
21474
21579
  controller.sealGeneration();
@@ -21537,11 +21642,11 @@ function createWorkflowStageFactory(input) {
21537
21642
  input.assertLiveWorkAllowed?.();
21538
21643
  options = stageOptionsWithGitWorktree(prepareLiveOptions?.() ?? options, input.workflowInvocationCwd, input.gitWorktreeSetupCache);
21539
21644
  }
21540
- const replayStageOptions = executeReplaySource?.sessionFile === undefined ? options : {
21645
+ const replayStageOptions = executeReplaySource?.sessionId === undefined ? options : {
21541
21646
  ...options ?? {},
21542
21647
  routerSelection: executeReplaySource.routerSelection,
21543
21648
  context: options?.context ?? "fork",
21544
- forkFromSessionFile: options?.forkFromSessionFile ?? executeReplaySource.sessionFile
21649
+ forkFromSessionId: options?.forkFromSessionId ?? executeReplaySource.sessionId
21545
21650
  };
21546
21651
  const intercomGroup = options?.durableIntercomGroup ?? resolveStageGroup(replayStageOptions, input.workflowIntercomGroup);
21547
21652
  const stageOptionsForContext = replayStageOptions?.group === undefined || intercomGroup === undefined ? replayStageOptions : { ...replayStageOptions, group: intercomGroup };
@@ -21716,8 +21821,8 @@ function createWorkflowStageFactory(input) {
21716
21821
  stageSnapshot.sessionId = meta.sessionId;
21717
21822
  if (meta.sessionFile !== undefined)
21718
21823
  stageSnapshot.sessionFile = meta.sessionFile;
21719
- if (meta.sessionId !== undefined || meta.sessionFile !== undefined)
21720
- input.activeStore.recordStageSession(input.runId, stageId, meta);
21824
+ if (meta.sessionId !== undefined)
21825
+ input.activeStore.recordStageSession(input.runId, stageId, { sessionId: meta.sessionId });
21721
21826
  const pending = input.opts.onStageSession?.(input.runId, stageSnapshot, checkpointOptions);
21722
21827
  if (checkpointOptions?.forceDurable === true || checkpointOptions?.awaitDurable === true) {
21723
21828
  await pending;
@@ -22249,11 +22354,45 @@ async function executeRun(def, resolvedInputs, opts) {
22249
22354
  return waitForRunRelease().then(() => whenRunning(call));
22250
22355
  if (ownController.signal.aborted)
22251
22356
  return Promise.reject(ownController.signal.reason);
22252
- return call();
22357
+ const persistence = drainCachedStagePersistence();
22358
+ return persistence === undefined ? call() : persistence.then(() => whenRunning(call));
22253
22359
  };
22254
22360
  ownController.signal.addEventListener("abort", () => scheduler.rejectReleaseBarriers(ownController.signal.reason ?? new Error("atomic-workflows: run aborted")), { once: true });
22255
22361
  const cachedStagePersistence = [];
22256
22362
  let cachedStageFailure;
22363
+ let cachedStageDrain;
22364
+ const drainCachedStagePersistence = () => {
22365
+ if (cachedStageDrain !== undefined)
22366
+ return cachedStageDrain;
22367
+ if (cachedStagePersistence.length === 0) {
22368
+ if (cachedStageFailure !== undefined)
22369
+ throw cachedStageFailure;
22370
+ return;
22371
+ }
22372
+ cachedStageDrain = (async () => {
22373
+ try {
22374
+ while (cachedStagePersistence.length > 0)
22375
+ await Promise.all(cachedStagePersistence.splice(0));
22376
+ if (cachedStageFailure !== undefined)
22377
+ throw cachedStageFailure;
22378
+ } finally {
22379
+ cachedStageDrain = undefined;
22380
+ }
22381
+ })();
22382
+ return cachedStageDrain;
22383
+ };
22384
+ const drainBeforeCheckpoint = () => {
22385
+ const persistence = drainCachedStagePersistence();
22386
+ return persistence?.then(() => ownController.signal.throwIfAborted());
22387
+ };
22388
+ const beforeLiveCall = () => {
22389
+ ownController.signal.throwIfAborted();
22390
+ const persistence = drainCachedStagePersistence();
22391
+ if (persistence !== undefined)
22392
+ return persistence.then(beforeLiveCall);
22393
+ if (scheduler.isRunPaused())
22394
+ return waitForRunRelease().then(beforeLiveCall);
22395
+ };
22257
22396
  const finalizers = createRunFinalizers({
22258
22397
  def,
22259
22398
  runId,
@@ -22262,8 +22401,14 @@ async function executeRun(def, resolvedInputs, opts) {
22262
22401
  opts,
22263
22402
  classifyExecutorFailure,
22264
22403
  drainWorkflowExitCleanups: async (reason) => {
22265
- await Promise.all(cachedStagePersistence);
22266
- await exit.drainWorkflowExitCleanups(reason);
22404
+ try {
22405
+ await drainCachedStagePersistence();
22406
+ } catch (error) {
22407
+ if (error !== cachedStageFailure)
22408
+ throw error;
22409
+ } finally {
22410
+ await exit.drainWorkflowExitCleanups(reason);
22411
+ }
22267
22412
  },
22268
22413
  assertSuccessfulCompletion: () => {
22269
22414
  if (cachedStageFailure !== undefined)
@@ -22279,7 +22424,8 @@ async function executeRun(def, resolvedInputs, opts) {
22279
22424
  run: runSnapshot,
22280
22425
  nextCheckpointId: checkpointIdGenerator,
22281
22426
  nextReplayKey: stageReplayKeyGenerator,
22282
- completedReplayKeys: completedStageReplayKeys
22427
+ completedReplayKeys: completedStageReplayKeys,
22428
+ beforeCheckpoint: drainBeforeCheckpoint
22283
22429
  });
22284
22430
  const durableOnStageEnd = createDurableStageEndRecorder({
22285
22431
  rootRunId: runId,
@@ -22428,7 +22574,9 @@ async function executeRun(def, resolvedInputs, opts) {
22428
22574
  retryToolNodes: opts.continuation?.retryToolNodes,
22429
22575
  toolControls,
22430
22576
  toolAdmission,
22431
- budget
22577
+ budget,
22578
+ beforeToolCall: drainCachedStagePersistence,
22579
+ beforeCheckpoint: drainBeforeCheckpoint
22432
22580
  });
22433
22581
  let selectedAdmittedToolFailure;
22434
22582
  const suspendForGracefulQuit = (reason) => {
@@ -22469,9 +22617,11 @@ async function executeRun(def, resolvedInputs, opts) {
22469
22617
  workflowId: runId,
22470
22618
  backend: durableBackend,
22471
22619
  nextCheckpointId: checkpointIdGenerator,
22620
+ beforeCheckpoint: drainBeforeCheckpoint,
22472
22621
  beforeCall: () => {
22473
22622
  ownController.signal.throwIfAborted();
22474
- return scheduler.isRunPaused() ? waitForRunRelease() : undefined;
22623
+ const persistence = drainCachedStagePersistence();
22624
+ return persistence ?? (scheduler.isRunPaused() ? waitForRunRelease() : undefined);
22475
22625
  },
22476
22626
  ...opts.usePromptNodesForUi === true ? {
22477
22627
  onReplay: async (request) => getPromptNodeUi().replayDurable(request)
@@ -22508,6 +22658,7 @@ async function executeRun(def, resolvedInputs, opts) {
22508
22658
  durableIntercomGroup,
22509
22659
  task: taskRunners.task,
22510
22660
  recordCachedTask: recordCachedStage,
22661
+ beforeCheckpoint: drainBeforeCheckpoint,
22511
22662
  signal: ownController.signal,
22512
22663
  registerTailControl: (registration) => {
22513
22664
  registration.controller.signal.addEventListener("abort", () => {
@@ -22544,6 +22695,8 @@ async function executeRun(def, resolvedInputs, opts) {
22544
22695
  backend: durableBackend,
22545
22696
  nextReplayKey: (stageName) => stageReplayKeyGenerator(stageName),
22546
22697
  durableIntercomGroup,
22698
+ beforeCall: beforeLiveCall,
22699
+ beforeCheckpoint: drainBeforeCheckpoint,
22547
22700
  recordCachedStage,
22548
22701
  stage: (name, options, replayKey) => {
22549
22702
  const stage = runtime.stage(name, options);
@@ -22604,7 +22757,7 @@ async function executeRun(def, resolvedInputs, opts) {
22604
22757
  return pending;
22605
22758
  }),
22606
22759
  tool: (...args) => {
22607
- if (!scheduler.isRunPaused())
22760
+ if (admittedTools.closed)
22608
22761
  return tool(...args);
22609
22762
  const pending = whenRunning(() => tool(...args));
22610
22763
  pending.catch(() => {});
@@ -22732,13 +22885,13 @@ async function executeRun(def, resolvedInputs, opts) {
22732
22885
  ownController.signal.throwIfAborted();
22733
22886
  if (opts.parentRun === undefined) {
22734
22887
  if (durableRootRegistration !== undefined) {
22735
- await durableBackend.registerWorkflow({
22888
+ await durableBackend.commitWorkflowRegistration({
22736
22889
  ...durableRootRegistration,
22737
22890
  modelOwner: runSnapshot.modelOwner,
22738
22891
  ...workflowInvocationMetadata(inputRuntimeDefaults, workflowInvocationCwd, gitWorktreeSetupCache, runSnapshot.origin)
22739
22892
  });
22740
22893
  } else {
22741
- await durableBackend.setWorkflowStatus(runId, "running");
22894
+ await durableBackend.commitWorkflowStatus(runId, "running");
22742
22895
  }
22743
22896
  }
22744
22897
  durableRootAdmitted = true;
@@ -22760,9 +22913,7 @@ async function executeRun(def, resolvedInputs, opts) {
22760
22913
  await waitForRunRelease();
22761
22914
  ownController.signal.throwIfAborted();
22762
22915
  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;
22916
+ await drainCachedStagePersistence();
22766
22917
  while (scheduler.isRunPaused())
22767
22918
  await waitForRunRelease();
22768
22919
  await admittedTools.closeAndDrain();
@@ -22802,7 +22953,7 @@ async function executeRun(def, resolvedInputs, opts) {
22802
22953
  const recorded = activeStore.recordRunEnd(runId, returned.status, result, returned.error, returned.metadata);
22803
22954
  if (opts.parentRun === undefined)
22804
22955
  await recordRunTimingCheckpointAsync(durableBackend, runSnapshot);
22805
- await durableBackend.setWorkflowStatus(runId, returned.status, undefined, returned.metadata?.resumable);
22956
+ await durableBackend.commitWorkflowStatus(runId, returned.status, undefined, returned.metadata?.resumable);
22806
22957
  await appendRunEndWhenRecorded(opts.persistence, recorded, {
22807
22958
  runId,
22808
22959
  status: returned.status,
@@ -22932,6 +23083,9 @@ async function executeRun(def, resolvedInputs, opts) {
22932
23083
  unregisterToolAdmission();
22933
23084
  } finally {
22934
23085
  terminalEvents.dispose();
23086
+ if (opts.stageControlRegistry === undefined && opts.executionMode !== "interactive" && isTerminalRunStatus(runSnapshot.status) && runSnapshot.resumable !== true) {
23087
+ await stageRegistry.clear(runId);
23088
+ }
22935
23089
  }
22936
23090
  }
22937
23091
  }
@@ -23026,7 +23180,6 @@ export {
23026
23180
  JOURNAL_TABLES,
23027
23181
  JournalCasConflictError,
23028
23182
  JournalClosedError,
23029
- JournalConfigurationError,
23030
23183
  JournalCounterRangeError,
23031
23184
  JournalError,
23032
23185
  JournalInvalidTextError,