@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
@@ -41097,6 +41097,19 @@ function createSessionScopedSingleton(key, createLocal) {
41097
41097
  function createStageControlRegistry() {
41098
41098
  const _byRun = new Map;
41099
41099
  const pendingDisposals = new Set;
41100
+ const sessionStores = new Map;
41101
+ let generation = 0;
41102
+ function rememberSessionStore(handle) {
41103
+ const store = handle.sessionStore;
41104
+ if (store === undefined)
41105
+ return;
41106
+ let stores = sessionStores.get(handle.runId);
41107
+ if (stores === undefined) {
41108
+ stores = new Map;
41109
+ sessionStores.set(handle.runId, stores);
41110
+ }
41111
+ stores.set(handle.stageId, store);
41112
+ }
41100
41113
  function ensureRun(runId) {
41101
41114
  let runMap = _byRun.get(runId);
41102
41115
  if (!runMap) {
@@ -41184,7 +41197,11 @@ function createStageControlRegistry() {
41184
41197
  };
41185
41198
  }
41186
41199
  return {
41200
+ get generation() {
41201
+ return generation;
41202
+ },
41187
41203
  register(handle) {
41204
+ rememberSessionStore(handle);
41188
41205
  const runMap = ensureRun(handle.runId);
41189
41206
  const displaced = runMap.get(handle.stageId);
41190
41207
  runMap.set(handle.stageId, {
@@ -41201,6 +41218,7 @@ function createStageControlRegistry() {
41201
41218
  if (!existing)
41202
41219
  return;
41203
41220
  if (existing.get(handle.stageId)?.handle === handle) {
41221
+ rememberSessionStore(handle);
41204
41222
  existing.delete(handle.stageId);
41205
41223
  }
41206
41224
  if (existing.size === 0)
@@ -41286,6 +41304,7 @@ function createStageControlRegistry() {
41286
41304
  return false;
41287
41305
  if (handle !== undefined && entry.handle !== handle)
41288
41306
  return false;
41307
+ rememberSessionStore(entry.handle);
41289
41308
  if (!entry.controlsDependencies)
41290
41309
  return false;
41291
41310
  entry.controlsDependencies = false;
@@ -41303,6 +41322,9 @@ function createStageControlRegistry() {
41303
41322
  get(runId, stageId) {
41304
41323
  return _byRun.get(runId)?.get(stageId)?.handle;
41305
41324
  },
41325
+ getSessionStore(runId, stageId) {
41326
+ return _byRun.get(runId)?.get(stageId)?.handle.sessionStore ?? sessionStores.get(runId)?.get(stageId);
41327
+ },
41306
41328
  forRun(runId) {
41307
41329
  const runMap = _byRun.get(runId);
41308
41330
  if (!runMap)
@@ -41315,17 +41337,28 @@ function createStageControlRegistry() {
41315
41337
  run(runId) {
41316
41338
  return makeRunHandle(runId);
41317
41339
  },
41318
- async clear() {
41319
- const entries = [..._byRun.values()].flatMap((runMap) => [...runMap.values()]);
41320
- _byRun.clear();
41340
+ async clear(runId) {
41341
+ if (runId === undefined)
41342
+ generation += 1;
41343
+ const entries = runId === undefined ? [..._byRun.values()].flatMap((runMap) => [...runMap.values()]) : [..._byRun.get(runId)?.values() ?? []];
41344
+ if (runId === undefined) {
41345
+ _byRun.clear();
41346
+ sessionStores.clear();
41347
+ } else {
41348
+ _byRun.get(runId)?.clear();
41349
+ _byRun.delete(runId);
41350
+ sessionStores.delete(runId);
41351
+ }
41321
41352
  await disposeEntries(entries);
41322
41353
  },
41323
41354
  async clearDetached() {
41324
41355
  const entries = [];
41356
+ generation += 1;
41325
41357
  for (const [runId, runMap] of [..._byRun]) {
41326
41358
  for (const [stageId, entry] of [...runMap]) {
41327
41359
  if (entry.controlsDependencies)
41328
41360
  continue;
41361
+ rememberSessionStore(entry.handle);
41329
41362
  runMap.delete(stageId);
41330
41363
  entries.push(entry);
41331
41364
  }
@@ -45031,6 +45064,7 @@ function getDurableBackendProcessOwner() {
45031
45064
  // dist/builtin/workflows/src/durable/journal/types.ts
45032
45065
  import { StorageSchemaVersionError } from "@bastani/atomic/storage";
45033
45066
  import { StorageUnavailableError } from "@bastani/atomic/storage";
45067
+ import { RUN_EVENT_TYPES } from "@bastani/atomic/storage";
45034
45068
  var JOURNAL_SCHEMA_VERSION = 1;
45035
45069
  var JOURNAL_PAYLOAD_ENCODING = "json-text";
45036
45070
  var JOURNAL_TABLES = { meta: "meta", runs: "runs", events: "events", leases: "leases" };
@@ -45052,20 +45086,6 @@ var JOURNAL_COLUMNS = {
45052
45086
  renewedAt: "renewed_at"
45053
45087
  };
45054
45088
  var JOURNAL_LEASE = { initialEpoch: 1, epochIncrement: 1, unheld: null, absentEpoch: 0 };
45055
- var RUN_EVENT_TYPES = {
45056
- runStarted: "RunStarted",
45057
- runFinished: "RunFinished",
45058
- statusChanged: "StatusChanged",
45059
- checkpointRecorded: "CheckpointRecorded",
45060
- promptAsked: "PromptAsked",
45061
- promptReleased: "PromptReleased",
45062
- controlRequested: "ControlRequested",
45063
- messageQueued: "MessageQueued",
45064
- messageDelivered: "MessageDelivered",
45065
- messageSettled: "MessageSettled",
45066
- timerScheduled: "TimerScheduled",
45067
- summaryRecorded: "SummaryRecorded"
45068
- };
45069
45089
 
45070
45090
  class JournalError extends Error {
45071
45091
  }
@@ -45077,19 +45097,6 @@ class JournalClosedError extends JournalError {
45077
45097
  }
45078
45098
  }
45079
45099
 
45080
- class JournalConfigurationError extends JournalError {
45081
- source;
45082
- setting;
45083
- reason;
45084
- constructor(source, setting, reason) {
45085
- super(`Invalid journal configuration at ${source}.${setting}: ${reason}`);
45086
- this.name = "JournalConfigurationError";
45087
- this.source = source;
45088
- this.setting = setting;
45089
- this.reason = reason;
45090
- }
45091
- }
45092
-
45093
45100
  class JournalInvalidTextError extends JournalError {
45094
45101
  field;
45095
45102
  reason;
@@ -45251,18 +45258,15 @@ class ScopedDurableBackend {
45251
45258
  async hasPendingStageDeliveryReceipt(workflowId, messageId, delivery, logicalRunId = workflowId) {
45252
45259
  return await this.inner.hasPendingStageDeliveryReceipt?.(this.scope.rootWorkflowId, messageId, delivery, logicalRunId) ?? false;
45253
45260
  }
45254
- registerWorkflow(_handle) {}
45261
+ async commitWorkflowRegistration(_handle) {}
45255
45262
  persistPendingStageMessages(workflowId, messages, logicalRunId = workflowId) {
45256
45263
  return this.inner.persistPendingStageMessages(this.scope.rootWorkflowId, messages, logicalRunId);
45257
45264
  }
45258
- recordCheckpoint(checkpoint) {
45259
- return this.inner.recordCheckpoint(this.remap(checkpoint));
45260
- }
45261
- async recordCheckpointAsync(checkpoint, options) {
45262
- await this.inner.recordCheckpointAsync(this.remap(checkpoint), options);
45265
+ async commitCheckpoint(checkpoint, options) {
45266
+ await this.inner.commitCheckpoint(this.remap(checkpoint), options);
45263
45267
  }
45264
- async recordAdditiveCheckpointBestEffort(checkpoint) {
45265
- return await this.inner.recordAdditiveCheckpointBestEffort(this.remap(checkpoint));
45268
+ async commitAdditiveCheckpointBestEffort(checkpoint) {
45269
+ return await this.inner.commitAdditiveCheckpointBestEffort(this.remap(checkpoint));
45266
45270
  }
45267
45271
  workflowOwnership(_workflowId) {
45268
45272
  return this.inner.workflowOwnership(this.scope.rootWorkflowId);
@@ -45292,12 +45296,12 @@ class ScopedDurableBackend {
45292
45296
  getLoadableWorkflow(_workflowId) {
45293
45297
  return;
45294
45298
  }
45295
- setWorkflowStatus(_workflowId, _status, _pendingPrompts, _resumable) {}
45296
- async transitionWorkflowStatus(_workflowId, _expectedStatuses, _status, _pendingPrompts, _resumable) {
45299
+ async commitWorkflowStatus(_workflowId, _status, _pendingPrompts, _resumable) {}
45300
+ async commitWorkflowStatusTransition(_workflowId, _expectedStatuses, _status, _pendingPrompts, _resumable) {
45297
45301
  return false;
45298
45302
  }
45299
- adjustPendingPrompts(_workflowId, delta) {
45300
- return this.inner.adjustPendingPrompts(this.scope.rootWorkflowId, delta);
45303
+ commitPendingPromptAdjustment(_workflowId, delta) {
45304
+ return this.inner.commitPendingPromptAdjustment(this.scope.rootWorkflowId, delta);
45301
45305
  }
45302
45306
  promptReservationScope(_workflowId) {
45303
45307
  return this.effectivePromptScope();
@@ -45330,7 +45334,7 @@ class ScopedDurableBackend {
45330
45334
  isWorkflowLoadable(_workflowId) {
45331
45335
  return false;
45332
45336
  }
45333
- reset() {}
45337
+ async commitReset() {}
45334
45338
  hydrateWorkflow(_workflowId) {
45335
45339
  return Promise.resolve();
45336
45340
  }
@@ -46724,19 +46728,9 @@ function createStageStoreMethods(context) {
46724
46728
  if (!run)
46725
46729
  return false;
46726
46730
  const stage = context.findStage(run, stageId);
46727
- if (!stage)
46728
- return false;
46729
- let changed = false;
46730
- if (session.sessionId !== undefined && stage.sessionId !== session.sessionId) {
46731
- stage.sessionId = session.sessionId;
46732
- changed = true;
46733
- }
46734
- if (session.sessionFile !== undefined && stage.sessionFile !== session.sessionFile) {
46735
- stage.sessionFile = session.sessionFile;
46736
- changed = true;
46737
- }
46738
- if (!changed)
46731
+ if (!stage || stage.sessionId === session.sessionId)
46739
46732
  return false;
46733
+ stage.sessionId = session.sessionId;
46740
46734
  context.bumpAndNotify();
46741
46735
  return true;
46742
46736
  },
@@ -48077,6 +48071,7 @@ function isReadOnlyArchiveStatus(status) {
48077
48071
  // dist/builtin/workflows/src/tui/stage-chat-view-state.ts
48078
48072
  function initializeStageChatView(ctx, opts) {
48079
48073
  ctx.store = opts.store;
48074
+ ctx.sessionStore = opts.sessionStore;
48080
48075
  ctx.theme = opts.graphTheme;
48081
48076
  ctx.runId = opts.runId;
48082
48077
  ctx.stageId = opts.stageId;
@@ -48136,7 +48131,7 @@ function initializeStageChatView(ctx, opts) {
48136
48131
  const initialStage = initialRun?.stages.find((s) => s.id === ctx.stageId);
48137
48132
  ctx.lastObservedRunStatus = initialRun?.status;
48138
48133
  ctx.lastObservedStageStatus = initialStage?.status;
48139
- snapshotMessagesFromSessionFile(ctx, initialStage);
48134
+ snapshotMessagesFromSession(ctx, initialStage);
48140
48135
  absorbStageNotices(ctx, initialStage);
48141
48136
  syncPromptState(ctx, initialStage?.pendingPrompt);
48142
48137
  const initialChatIsTerminal = isTerminalStageChatState(initialRun?.status) || isTerminalStageChatState(initialStage?.status);
@@ -48332,11 +48327,22 @@ function snapshotMessagesFromHandle(ctx) {
48332
48327
  ctx.chatHost.appendMessages(handle.messages);
48333
48328
  ctx.chatHost.hydrateStreamingAssistantMessage(handle.agentSession?.agent?.state.streamingMessage);
48334
48329
  }
48335
- function snapshotMessagesFromSessionFile(ctx, stage) {
48330
+ function snapshotMessagesFromSession(ctx, stage) {
48336
48331
  const handle = liveHandle(ctx);
48337
- if (!ctx.chatHost.loadSessionFile(handle?.sessionFile ?? stage?.sessionFile) && !handle) {
48338
- ctx.postMortemUnavailableReason ??= "invalid_session";
48332
+ const sessionId = handle?.sessionId ?? stage?.sessionId;
48333
+ if (sessionId === undefined)
48334
+ return;
48335
+ const sessionStore = handle?.sessionStore ?? handle?.agentSession?.sessionManager.getSessionStore() ?? ctx.sessionStore;
48336
+ if (sessionStore === undefined) {
48337
+ if (!handle)
48338
+ ctx.postMortemUnavailableReason ??= "invalid_session";
48339
+ return;
48339
48340
  }
48341
+ ctx.chatHost.loadSession(sessionStore, sessionId).then((loaded) => {
48342
+ if (!loaded && !liveHandle(ctx))
48343
+ ctx.postMortemUnavailableReason ??= "invalid_session";
48344
+ ctx.requestRender?.();
48345
+ });
48340
48346
  }
48341
48347
  function absorbStageNotices(ctx, stage) {
48342
48348
  const notices = stage?.notices;
@@ -48504,7 +48510,7 @@ function isReadOnlyArchive(ctx, stage = currentStage(ctx)) {
48504
48510
  return false;
48505
48511
  if (!stage)
48506
48512
  return true;
48507
- return isReadOnlyArchiveStatus(stage.status) || Boolean(stage.sessionFile);
48513
+ return isReadOnlyArchiveStatus(stage.status) || stage.sessionId !== undefined;
48508
48514
  }
48509
48515
  async function handleSlashCommand(ctx, text) {
48510
48516
  const [command, ...rest] = text.trim().split(/\s+/);
@@ -48566,6 +48572,8 @@ function promptPageSize(ctx) {
48566
48572
  // dist/builtin/workflows/src/tui/stage-chat-view-archive-history.ts
48567
48573
  function postMortemUnavailableMessage(reason) {
48568
48574
  switch (reason) {
48575
+ case "closed":
48576
+ return "Post-mortem chat is unavailable because its owning session has closed.";
48569
48577
  case "no_adapter":
48570
48578
  return "Post-mortem chat is unavailable because no agent session adapter is configured.";
48571
48579
  case "not_terminal":
@@ -48573,7 +48581,7 @@ function postMortemUnavailableMessage(reason) {
48573
48581
  case "no_session":
48574
48582
  return "No retained agent session is available for this stage.";
48575
48583
  case "invalid_session":
48576
- return "The retained session is missing, unreadable, or invalid. Check that the session file still exists and is readable.";
48584
+ return "The retained session is missing, unreadable, or invalid in the selected session store.";
48577
48585
  case undefined:
48578
48586
  return;
48579
48587
  }
@@ -48586,7 +48594,7 @@ function renderReadOnlyArchiveBody(ctx, width, budget, stage, indicatorLines = [
48586
48594
  const unavailableMessage = postMortemUnavailableMessage(ctx.postMortemUnavailableReason);
48587
48595
  const callout = [];
48588
48596
  callout.push(blankLine(width));
48589
- callout.push(...bannerLines(ctx, width, unavailableMessage === undefined ? "info" : "warning", unavailableMessage === undefined ? "◌" : "!", unavailableMessage === undefined ? "READ-ONLY SESSION" : "SESSION UNAVAILABLE", unavailableMessage === undefined ? stage?.sessionFile ? "archived transcript" : "no live chat session" : "post-mortem chat cannot be reopened"));
48597
+ callout.push(...bannerLines(ctx, width, unavailableMessage === undefined ? "info" : "warning", unavailableMessage === undefined ? "◌" : "!", unavailableMessage === undefined ? "READ-ONLY SESSION" : "SESSION UNAVAILABLE", unavailableMessage === undefined ? stage?.sessionId !== undefined ? "archived transcript" : "no live chat session" : "post-mortem chat cannot be reopened"));
48590
48598
  callout.push(...new Text3(paint2(unavailableMessage ?? "This node is no longer attached to a live chat session.", t.textMuted), 2, 0).render(width));
48591
48599
  const transcriptBudget = Math.max(0, budget - callout.length);
48592
48600
  const reservedIndicatorRows = indicatorLines.length > 0 && transcriptBudget > indicatorLines.length ? indicatorLines.length : 0;
@@ -49275,6 +49283,9 @@ function resolveAttachedStageHandle(registry, resolvePostMortemHandle, runId, st
49275
49283
  if (liveHandle !== undefined)
49276
49284
  return { handle: liveHandle };
49277
49285
  const postMortem = resolvePostMortemHandle?.(runId, stageId);
49286
+ return postMortem instanceof Promise ? postMortem.then(attachedResolution, () => ({ postMortemUnavailableReason: "invalid_session" })) : attachedResolution(postMortem);
49287
+ }
49288
+ function attachedResolution(postMortem) {
49278
49289
  if (postMortem?.ok === true)
49279
49290
  return { handle: postMortem.handle };
49280
49291
  return postMortem?.ok === false ? { postMortemUnavailableReason: postMortem.reason } : {};
@@ -49285,6 +49296,7 @@ var ENTER_TRANSITION_QUARANTINE_MS = 200;
49285
49296
 
49286
49297
  class WorkflowAttachPane {
49287
49298
  store;
49299
+ sessionStore;
49288
49300
  theme;
49289
49301
  runId;
49290
49302
  registry;
@@ -49305,6 +49317,7 @@ class WorkflowAttachPane {
49305
49317
  now;
49306
49318
  mode = "graph";
49307
49319
  visible = true;
49320
+ attachmentGeneration = 0;
49308
49321
  graphView;
49309
49322
  chatView = null;
49310
49323
  unsubscribeStore = null;
@@ -49317,6 +49330,7 @@ class WorkflowAttachPane {
49317
49330
  lastStageAwaitingInputKey = null;
49318
49331
  constructor(opts) {
49319
49332
  this.store = opts.store;
49333
+ this.sessionStore = opts.sessionStore;
49320
49334
  this.theme = opts.graphTheme;
49321
49335
  this.runId = opts.runId;
49322
49336
  this.registry = opts.stageControlRegistry;
@@ -49391,7 +49405,8 @@ class WorkflowAttachPane {
49391
49405
  const run = snap.runs.find((r) => r.id === runId);
49392
49406
  return run?.name ?? "workflow";
49393
49407
  }
49394
- _attachToStage(runId, stageId, options = { suppressInitialPromptSubmit: true }) {
49408
+ async _attachToStage(runId, stageId, options = { suppressInitialPromptSubmit: true }) {
49409
+ const generation = ++this.attachmentGeneration;
49395
49410
  this.graphEnterQuarantineUntil = 0;
49396
49411
  const snapshot = readGraphStoreSnapshot(this.store);
49397
49412
  const graphRunId = this._resolveRunId();
@@ -49400,11 +49415,15 @@ class WorkflowAttachPane {
49400
49415
  this.stagePromptEnterQuarantineUntil = options.suppressInitialPromptSubmit === true && this.lastStageAwaitingInputKey !== null ? this.now() + ENTER_TRANSITION_QUARANTINE_MS : 0;
49401
49416
  this.attachedRunId = runId;
49402
49417
  this.lastAttachedStageId = stageId;
49403
- const { handle, postMortemUnavailableReason } = resolveAttachedStageHandle(this.registry, this.resolvePostMortemHandle, runId, stageId);
49418
+ const resolution = resolveAttachedStageHandle(this.registry, this.resolvePostMortemHandle, runId, stageId);
49419
+ const { handle, postMortemUnavailableReason } = resolution instanceof Promise ? await resolution : resolution;
49420
+ if (generation !== this.attachmentGeneration || !this.visible)
49421
+ return;
49404
49422
  this.chatView?.dispose();
49405
49423
  let chatView;
49406
49424
  chatView = new StageChatView({
49407
49425
  store: this.store,
49426
+ sessionStore: this.sessionStore,
49408
49427
  graphTheme: this.theme,
49409
49428
  runId,
49410
49429
  stageId,
@@ -49430,8 +49449,10 @@ class WorkflowAttachPane {
49430
49449
  this.chatView = chatView;
49431
49450
  this.mode = "stage-chat";
49432
49451
  this.store.recordStageAttached(runId, stageId, this.visible);
49452
+ this.hostRequestRender?.();
49433
49453
  }
49434
49454
  _detachFromStage(reason = "user", metadata = {}) {
49455
+ this.attachmentGeneration += 1;
49435
49456
  this.composerDrafts.capture(this.attachedRunId, this.lastAttachedStageId, this.chatView?._inputBuffer);
49436
49457
  if (this.chatView && this.attachedRunId && this.lastAttachedStageId) {
49437
49458
  this.store.recordStageAttached(this.attachedRunId, this.lastAttachedStageId, false);
@@ -49448,6 +49469,7 @@ class WorkflowAttachPane {
49448
49469
  this.graphEnterQuarantineUntil = reason === "prompt-resolved" && metadata.suppressNextGraphSubmit === true ? this.now() + ENTER_TRANSITION_QUARANTINE_MS : 0;
49449
49470
  }
49450
49471
  retarget(runId, stageId, stageRunId) {
49472
+ this.attachmentGeneration += 1;
49451
49473
  if (this.chatView && this.attachedRunId && this.lastAttachedStageId) {
49452
49474
  this.store.recordStageAttached(this.attachedRunId, this.lastAttachedStageId, false);
49453
49475
  }
@@ -49521,6 +49543,8 @@ class WorkflowAttachPane {
49521
49543
  }
49522
49544
  setVisible(visible) {
49523
49545
  this.visible = visible;
49546
+ if (!visible)
49547
+ this.attachmentGeneration += 1;
49524
49548
  if (this.mode === "stage-chat" && this.attachedRunId && this.lastAttachedStageId) {
49525
49549
  this.store.recordStageAttached(this.attachedRunId, this.lastAttachedStageId, visible);
49526
49550
  }
@@ -49667,6 +49691,7 @@ class WorkflowAttachPane {
49667
49691
  this.graphView.invalidate();
49668
49692
  }
49669
49693
  dispose() {
49694
+ this.attachmentGeneration += 1;
49670
49695
  this.unsubscribeStore?.();
49671
49696
  this.unsubscribeStore = null;
49672
49697
  if (this.chatView && this.attachedRunId && this.lastAttachedStageId) {
@@ -49843,8 +49868,8 @@ function buildGraphOverlayAdapter(pi, store, buildOpts = {}) {
49843
49868
  const ui = surface?.ui ?? pi.ui;
49844
49869
  observeHostCustomUi(ui);
49845
49870
  if (mounted && currentHandle?.isHidden()) {
49846
- currentView?.retarget(runId, stageId, stageRunId);
49847
49871
  currentView?.setVisible(true);
49872
+ currentView?.retarget(runId, stageId, stageRunId);
49848
49873
  updateTerminalAutowrap(true);
49849
49874
  currentHandle.setHidden(false);
49850
49875
  currentHandle.focus();
@@ -49889,6 +49914,7 @@ function buildGraphOverlayAdapter(pi, store, buildOpts = {}) {
49889
49914
  graphTheme: deriveGraphThemeFromPiTheme(theme),
49890
49915
  runId,
49891
49916
  stageControlRegistry: registry,
49917
+ sessionStore: buildOpts.resolveSessionStore?.(),
49892
49918
  resolvePostMortemHandle,
49893
49919
  stageUiBroker,
49894
49920
  onClose: finish,
@@ -51232,11 +51258,15 @@ var POST_MORTEM_ATTACH_TIMEOUT_MS = 1e4;
51232
51258
  function registerCompletedStageIntercomAskRouter(pi, resolveHandle) {
51233
51259
  const queues = new Map;
51234
51260
  let disposed = false;
51261
+ const assertActive = () => {
51262
+ if (disposed)
51263
+ throw new Error("Intercom ask target is unavailable: its owning session has closed.");
51264
+ };
51235
51265
  const subscription = pi.events?.on?.(LATE_STAGE_MESSAGE_EVENT, (payload) => {
51236
51266
  if (disposed || !isCompletedStageAskEvent(payload) || payload.handled === true)
51237
51267
  return;
51238
51268
  payload.handled = true;
51239
- payload.completion = enqueueTargetTurn(queues, `${payload.workflowRunId}:${payload.workflowStageId}`, () => deliverAsPostMortemTurn(payload, resolveHandle));
51269
+ payload.completion = enqueueTargetTurn(queues, `${payload.workflowRunId}:${payload.workflowStageId}`, () => deliverAsPostMortemTurn(payload, resolveHandle, assertActive));
51240
51270
  });
51241
51271
  const dispose = () => {
51242
51272
  disposed = true;
@@ -51263,8 +51293,10 @@ function enqueueTargetTurn(queues, key, deliver) {
51263
51293
  }).catch(() => {});
51264
51294
  return current;
51265
51295
  }
51266
- async function deliverAsPostMortemTurn(event, resolveHandle) {
51267
- const resolution = resolveHandle(event.workflowRunId, event.workflowStageId);
51296
+ async function deliverAsPostMortemTurn(event, resolveHandle, assertActive) {
51297
+ assertActive();
51298
+ const resolution = await resolveHandle(event.workflowRunId, event.workflowStageId);
51299
+ assertActive();
51268
51300
  if (resolution === undefined) {
51269
51301
  throw new Error(`Intercom ask target is unavailable: completed workflow stage ${event.workflowRunId}/${event.workflowStageId} was deleted or is no longer retained.`);
51270
51302
  }
@@ -51277,6 +51309,7 @@ async function deliverAsPostMortemTurn(event, resolveHandle) {
51277
51309
  }
51278
51310
  await attachWithTimeout(handle);
51279
51311
  for (const message of event.messages) {
51312
+ assertActive();
51280
51313
  if (handle.isStreaming)
51281
51314
  await handle.followUp(message.content);
51282
51315
  else
@@ -51298,6 +51331,8 @@ async function attachWithTimeout(handle) {
51298
51331
  function unavailableReason(runId, stageId, reason) {
51299
51332
  const target = `${runId}/${stageId}`;
51300
51333
  switch (reason) {
51334
+ case "closed":
51335
+ return `Intercom ask target is unavailable: the owning session for workflow stage ${target} has closed.`;
51301
51336
  case "not_terminal":
51302
51337
  return `Intercom ask target is not resumable: workflow stage ${target} is not a completed stage with a retained conversation.`;
51303
51338
  case "no_session":
@@ -51316,7 +51351,7 @@ import { registerExtensionContextRetirementEffect, sessionScopedExtensionState a
51316
51351
  var releasedRuns = new WeakMap;
51317
51352
  async function releasePausedRunsOwnedBy(backend, modelOwner) {
51318
51353
  const settled = await Promise.allSettled(backend.listResumableWorkflows().filter((entry) => entry.status === "paused" && entry.modelOwner === modelOwner).map(async (entry) => {
51319
- const released = await backend.transitionWorkflowStatus(entry.workflowId, ["paused"], "paused", undefined, undefined, undefined, undefined, modelOwner);
51354
+ const released = await backend.commitWorkflowStatusTransition(entry.workflowId, ["paused"], "paused", undefined, undefined, undefined, undefined, modelOwner);
51320
51355
  return released ? entry.workflowId : undefined;
51321
51356
  }));
51322
51357
  const failures = settled.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
@@ -51337,7 +51372,7 @@ async function reclaimReleasedRunsOwnedBy(backend, modelOwner) {
51337
51372
  const handle = backend.getWorkflow(entry.workflowId);
51338
51373
  return handle?.releasedModelOwner === modelOwner ? [handle] : [];
51339
51374
  }).map(async (handle) => {
51340
- const reclaimed = await backend.transitionWorkflowStatus(handle.workflowId, ["paused"], "paused", undefined, undefined, handle.updatedAt);
51375
+ const reclaimed = await backend.commitWorkflowStatusTransition(handle.workflowId, ["paused"], "paused", undefined, undefined, handle.updatedAt);
51341
51376
  if (reclaimed)
51342
51377
  releasedRuns.get(backend)?.delete(handle.workflowId);
51343
51378
  }));
@@ -52407,7 +52442,7 @@ async function recordRunTimingCheckpointAsync(backend, run, options) {
52407
52442
  return false;
52408
52443
  for (const checkpoint of checkpoints)
52409
52444
  if (checkpoint !== undefined)
52410
- await backend.recordCheckpointAsync(checkpoint);
52445
+ await backend.commitCheckpoint(checkpoint);
52411
52446
  return true;
52412
52447
  }
52413
52448
  function runTimingCheckpoint(backend, run, options) {
@@ -52627,7 +52662,7 @@ class JournalProjection {
52627
52662
  } else {
52628
52663
  if ("output" in currentCheckpoint)
52629
52664
  rec.stageOutputByReplayKey.set(currentCheckpoint.replayKey, currentCheckpoint);
52630
- if (currentCheckpoint.sessionId !== undefined || currentCheckpoint.sessionFile !== undefined) {
52665
+ if (currentCheckpoint.sessionId !== undefined) {
52631
52666
  const existing = rec.stageSessionByReplayKey.get(currentCheckpoint.replayKey);
52632
52667
  if (existing === undefined || currentCheckpoint.completedAt >= existing.completedAt) {
52633
52668
  rec.stageSessionByReplayKey.set(currentCheckpoint.replayKey, currentCheckpoint);
@@ -52655,7 +52690,7 @@ class JournalProjection {
52655
52690
  }
52656
52691
  getStageSession(workflowId, replayKey) {
52657
52692
  const checkpoint = this.workflows.get(workflowId)?.stageSessionByReplayKey.get(replayKey);
52658
- if (checkpoint?.sessionId === undefined && checkpoint?.sessionFile === undefined)
52693
+ if (checkpoint?.sessionId === undefined)
52659
52694
  return;
52660
52695
  return {
52661
52696
  ...checkpoint.sessionId !== undefined ? { sessionId: checkpoint.sessionId } : {},
@@ -53005,9 +53040,10 @@ function replayedWorkflowToolOutcome(outcome) {
53005
53040
 
53006
53041
  // dist/builtin/workflows/src/durable/tool-failure-checkpoint.ts
53007
53042
  async function recordThrowingToolFailure(input, node, identity, error, attempts, cancelled = false) {
53043
+ await input.beforeCheckpoint?.();
53008
53044
  const message = workflowToolFailure(error, attempts, false).error.message;
53009
53045
  const failedAt = Date.now();
53010
- await input.backend.recordAdditiveCheckpointBestEffort({
53046
+ await input.backend.commitAdditiveCheckpointBestEffort({
53011
53047
  kind: "tool",
53012
53048
  workflowId: input.workflowId,
53013
53049
  checkpointId: `tool-failure:${identity.argsHash}:${input.nextCheckpointId()}`,
@@ -53335,6 +53371,21 @@ async function executeLiveToolInvocation(live) {
53335
53371
  const startedAt = Date.now();
53336
53372
  let attempts = 0;
53337
53373
  let callbackCompleted = false;
53374
+ const cancelInvocation = async (cancellation) => {
53375
+ control.noteCancelled();
53376
+ if (returnFailure || isWorkflowToolAbortError(cancellation) && cancellation.scope === "node" || input.runFailing?.() === true) {
53377
+ await recordCancelledToolInspection(live, startedAt, cancellation, attempts);
53378
+ }
53379
+ const endedAt = Date.now();
53380
+ input.onNodeEnd?.(node.id, {
53381
+ status: "cancelled",
53382
+ endedAt,
53383
+ durationMs: Math.max(0, endedAt - startedAt),
53384
+ error: cancellation.message
53385
+ });
53386
+ input.onNodeSettle?.(node.id);
53387
+ throw cancellation;
53388
+ };
53338
53389
  input.onNodeRunning?.(node.id, startedAt);
53339
53390
  try {
53340
53391
  const result = await executeWithRetries(() => {
@@ -53371,6 +53422,8 @@ async function executeLiveToolInvocation(live) {
53371
53422
  ...input.runTopology !== undefined ? { run: { ...input.runTopology } } : {}
53372
53423
  }
53373
53424
  };
53425
+ await input.beforeCheckpoint?.();
53426
+ throwIfInvocationCancelled(input, toolSignal);
53374
53427
  await recordCheckpointDurably(input.backend, checkpoint);
53375
53428
  input.onNodeEnd?.(node.id, {
53376
53429
  status: "completed",
@@ -53384,21 +53437,8 @@ async function executeLiveToolInvocation(live) {
53384
53437
  } catch (error) {
53385
53438
  const timeoutFailure = error instanceof WorkflowToolTimeoutError;
53386
53439
  const cancellation = timeoutFailure ? undefined : invocationCancellation(input, toolSignal);
53387
- if (cancellation !== undefined) {
53388
- control.noteCancelled();
53389
- if (returnFailure || isWorkflowToolAbortError(cancellation) && cancellation.scope === "node" || input.runFailing?.() === true) {
53390
- await recordCancelledToolInspection(live, startedAt, cancellation, attempts);
53391
- }
53392
- const endedAt = Date.now();
53393
- input.onNodeEnd?.(node.id, {
53394
- status: "cancelled",
53395
- endedAt,
53396
- durationMs: Math.max(0, endedAt - startedAt),
53397
- error: cancellation.message
53398
- });
53399
- input.onNodeSettle?.(node.id);
53400
- throw cancellation;
53401
- }
53440
+ if (cancellation !== undefined)
53441
+ return await cancelInvocation(cancellation);
53402
53442
  const callbackFailure = callbackError ?? error;
53403
53443
  if (returnFailure && !callbackCompleted && isExplicitCallbackCancellation(callbackFailure)) {
53404
53444
  input.onFailureObserved?.(callbackFailure, node.id);
@@ -53438,8 +53478,14 @@ async function executeLiveToolInvocation(live) {
53438
53478
  }
53439
53479
  };
53440
53480
  try {
53481
+ await input.beforeCheckpoint?.();
53482
+ if (!timeoutFailure)
53483
+ throwIfInvocationCancelled(input, toolSignal);
53441
53484
  await recordCheckpointDurably(input.backend, checkpoint);
53442
53485
  } catch (persistenceError) {
53486
+ const cancellation = timeoutFailure ? undefined : invocationCancellation(input, toolSignal);
53487
+ if (cancellation !== undefined)
53488
+ return await cancelInvocation(cancellation);
53443
53489
  input.onFailureObserved?.(persistenceError, node.id);
53444
53490
  const endedAt = Date.now();
53445
53491
  input.onNodeEnd?.(node.id, {
@@ -53590,7 +53636,7 @@ async function recordReplayedToolTopology(input, node, cached, argsHash, endedAt
53590
53636
  const unchanged = JSON.stringify(cached.topology.parentIds) === JSON.stringify(topology.parentIds) && JSON.stringify(cached.topology.run) === JSON.stringify(topology.run) && cached.topology.endedAt === topology.endedAt;
53591
53637
  if (unchanged)
53592
53638
  return;
53593
- await input.backend.recordAdditiveCheckpointBestEffort({
53639
+ await input.backend.commitAdditiveCheckpointBestEffort({
53594
53640
  kind: "tool",
53595
53641
  workflowId: input.workflowId,
53596
53642
  checkpointId: `tool-replay-meta:${durableHash({ argsHash, topology })}`,
@@ -53612,7 +53658,7 @@ function summarizeToolResult(value2) {
53612
53658
  return serialized.length <= 240 ? serialized : `${flattenTruncatedString(serialized.slice(0, 237))}...`;
53613
53659
  }
53614
53660
  async function recordCheckpointDurably(backend, checkpoint, signal) {
53615
- await backend.recordCheckpointAsync(checkpoint, signal === undefined ? undefined : { signal });
53661
+ await backend.commitCheckpoint(checkpoint, signal === undefined ? undefined : { signal });
53616
53662
  }
53617
53663
  async function executeWithRetries(fn, options, throwIfCancelled, signal) {
53618
53664
  throwIfCancelled();
@@ -53705,6 +53751,7 @@ async function recordStageCheckpoint(deps, stage, options) {
53705
53751
  completedAt: stage.endedAt ?? Date.now(),
53706
53752
  ...metadata
53707
53753
  };
53754
+ await deps.beforeCheckpoint?.();
53708
53755
  await recordCheckpointDurably(deps.backend, checkpoint);
53709
53756
  return true;
53710
53757
  }
@@ -53714,12 +53761,12 @@ function stageSessionDurationBucket(durationMs) {
53714
53761
  }
53715
53762
  async function recordStageSessionCheckpoint(deps, stage, options) {
53716
53763
  const replayKey = deps.replayKeyForCompletedStage?.(stage) ?? stage.replayKey ?? deps.nextReplayKey(stage.name);
53717
- if (stage.sessionFile === undefined)
53764
+ if (stage.sessionId === undefined)
53718
53765
  return false;
53719
53766
  const checkpointNow = deps.now?.() ?? Date.now();
53720
53767
  const durationMs = elapsedStageMs(stage, checkpointNow) ?? 0;
53721
53768
  const current = deps.backend.getStageSession(deps.workflowId, replayKey);
53722
- if (options?.force !== true && current !== undefined && current.sessionId === stage.sessionId && current.sessionFile === stage.sessionFile && current.startedAt === stage.startedAt && stageSessionDurationBucket(current.durationMs) === stageSessionDurationBucket(durationMs))
53769
+ if (options?.force !== true && current !== undefined && current.sessionId === stage.sessionId && current.startedAt === stage.startedAt && stageSessionDurationBucket(current.durationMs) === stageSessionDurationBucket(durationMs))
53723
53770
  return false;
53724
53771
  const checkpoint = {
53725
53772
  kind: "stage",
@@ -53734,6 +53781,7 @@ async function recordStageSessionCheckpoint(deps, stage, options) {
53734
53781
  durationMs,
53735
53782
  completedAt: checkpointNow
53736
53783
  };
53784
+ await deps.beforeCheckpoint?.();
53737
53785
  await recordCheckpointDurably(deps.backend, checkpoint);
53738
53786
  return true;
53739
53787
  }
@@ -53760,10 +53808,10 @@ function createDurableStagePrimitive(input) {
53760
53808
  const cached = stageCheckpointWithOutput(input.backend, input.workflowId, replayKey);
53761
53809
  if (cached !== undefined) {
53762
53810
  const recorded = input.recordCachedStage?.(name, replayKey, cached);
53763
- return createCachedStageContext(name, cached.output, cached.result, recorded);
53811
+ return withStageWriteBarrier(createCachedStageContext(name, cached.output, cached.result, recorded), input.beforeCall);
53764
53812
  }
53765
53813
  const session = input.backend.getStageSession(input.workflowId, replayKey);
53766
- const isMidSessionResume = session?.sessionFile !== undefined;
53814
+ const isMidSessionResume = session?.sessionId !== undefined;
53767
53815
  const topology = activeStageTopology(input.backend, input.workflowId, replayKey);
53768
53816
  const durableStageId = topology?.stageId ?? pendingStageIdForReplay(input.backend, input.workflowId, replayKey, name);
53769
53817
  const durableIntercomGroup = topology?.intercomGroup ?? input.durableIntercomGroup?.(replayKey, durableStageId);
@@ -53774,12 +53822,12 @@ function createDurableStagePrimitive(input) {
53774
53822
  ...topology !== undefined ? { durableParentIds: [...topology.parentIds] } : {},
53775
53823
  ...durableIntercomGroup !== undefined ? { durableIntercomGroup } : {},
53776
53824
  ...isMidSessionResume ? {
53777
- resumeFromSessionFile: session.sessionFile,
53825
+ resumeFromSessionId: session.sessionId,
53778
53826
  routerSelection: session.routerSelection,
53779
53827
  durableAccumulatedDurationMs: session.durationMs ?? 0
53780
53828
  } : {}
53781
53829
  };
53782
- const live = withMidSessionResumePrompt(input.stage(name, liveOptions, replayKey), isMidSessionResume);
53830
+ const live = withStageWriteBarrier(withMidSessionResumePrompt(input.stage(name, liveOptions, replayKey), isMidSessionResume), input.beforeCall);
53783
53831
  if (options?.schema === undefined)
53784
53832
  return live;
53785
53833
  return wrapSchemaStageForDurability({
@@ -53787,10 +53835,31 @@ function createDurableStagePrimitive(input) {
53787
53835
  workflowId: input.workflowId,
53788
53836
  backend: input.backend,
53789
53837
  replayKey,
53838
+ beforeCheckpoint: input.beforeCheckpoint,
53790
53839
  name
53791
53840
  });
53792
53841
  };
53793
53842
  }
53843
+ function withStageWriteBarrier(stage, beforeCall) {
53844
+ if (beforeCall === undefined)
53845
+ return stage;
53846
+ const wrapped = Object.create(stage);
53847
+ Object.defineProperties(wrapped, {
53848
+ prompt: {
53849
+ value: async (...args) => {
53850
+ await beforeCall();
53851
+ return stage.prompt(...args);
53852
+ }
53853
+ },
53854
+ complete: {
53855
+ value: async (...args) => {
53856
+ await beforeCall();
53857
+ return stage.complete(...args);
53858
+ }
53859
+ }
53860
+ });
53861
+ return wrapped;
53862
+ }
53794
53863
  var TASK_RESULT_CHECKPOINT_CONTROL_PREFIX = "task-checkpoint:";
53795
53864
  function createDurableTaskPrimitive(input) {
53796
53865
  return async (name, options, stageFailFastScope) => {
@@ -53811,8 +53880,8 @@ function createDurableTaskPrimitive(input) {
53811
53880
  durableParentIds: [...topology.parentIds]
53812
53881
  } : {},
53813
53882
  ...durableIntercomGroup !== undefined ? { durableIntercomGroup } : {},
53814
- ...session?.sessionFile !== undefined ? {
53815
- resumeFromSessionFile: session.sessionFile,
53883
+ ...session?.sessionId !== undefined ? {
53884
+ resumeFromSessionId: session.sessionId,
53816
53885
  routerSelection: session.routerSelection,
53817
53886
  durableAccumulatedDurationMs: session.durationMs ?? 0
53818
53887
  } : {}
@@ -53829,6 +53898,9 @@ function createDurableTaskPrimitive(input) {
53829
53898
  });
53830
53899
  const signal = mergeAbortSignals(input.signal, tailController.signal);
53831
53900
  try {
53901
+ await input.beforeCheckpoint?.();
53902
+ if (signal?.aborted)
53903
+ throw abortReasonError(signal);
53832
53904
  await awaitAbortable(signal, recordCheckpointDurably(input.backend, {
53833
53905
  kind: "stage",
53834
53906
  workflowId: input.workflowId,
@@ -53960,6 +54032,7 @@ function wrapSchemaStageForDurability(input) {
53960
54032
  value: async (text, options) => {
53961
54033
  const result = await stage.prompt(text, options);
53962
54034
  if (typeof result !== "string" || result.length === 0) {
54035
+ await input.beforeCheckpoint?.();
53963
54036
  await recordCheckpointDurably(input.backend, {
53964
54037
  kind: "stage",
53965
54038
  workflowId: input.workflowId,
@@ -54104,7 +54177,6 @@ function stableCheckpointId(kind, replayKey) {
54104
54177
  function stageSessionCheckpointId(replayKey, stage, durationMs) {
54105
54178
  return `${stableCheckpointId("stage-session", replayKey)}:${durableHash({
54106
54179
  sessionId: stage.sessionId ?? "",
54107
- sessionFile: stage.sessionFile ?? "",
54108
54180
  startedAt: stage.startedAt ?? 0,
54109
54181
  durationMs
54110
54182
  })}`;
@@ -54199,7 +54271,7 @@ function getLoadableDurableWorkflow(backend, workflowId) {
54199
54271
  return backend.getLoadableWorkflow(workflowId);
54200
54272
  }
54201
54273
  async function transitionDurableWorkflowStatus(backend, workflowId, expectedStatuses, status, pendingPrompts, resumable) {
54202
- return await backend.transitionWorkflowStatus(workflowId, expectedStatuses, status, pendingPrompts, resumable);
54274
+ return await backend.commitWorkflowStatusTransition(workflowId, expectedStatuses, status, pendingPrompts, resumable);
54203
54275
  }
54204
54276
  // dist/builtin/workflows/src/runs/background/workflow-lifecycle-aggregate.ts
54205
54277
  function expandedControlRunIds(store, runId) {
@@ -56804,25 +56876,10 @@ function formatStartupDiagnostics(configResult, discoveryResult) {
56804
56876
  }
56805
56877
 
56806
56878
  // dist/builtin/workflows/src/shared/session-transcript.ts
56807
- import { readFileSync, statSync } from "node:fs";
56808
- function isReopenableSessionTranscript(path) {
56879
+ async function isReopenableSession(store, sessionId) {
56809
56880
  try {
56810
- const stats = statSync(path);
56811
- if (!stats.isFile() || stats.size === 0)
56812
- return false;
56813
- const lines = readFileSync(path, "utf8").split(`
56814
- `).filter((line) => line.trim().length > 0);
56815
- if (lines.length < 2)
56816
- return false;
56817
- const entries = [];
56818
- for (const line of lines) {
56819
- const parsed = JSON.parse(line);
56820
- if (typeof parsed !== "object" || parsed === null)
56821
- return false;
56822
- entries.push(parsed);
56823
- }
56824
- const header = entries[0];
56825
- return header?.type === "session" && typeof header.id === "string" && entries.some(isUsableContextMessage);
56881
+ const snapshot = await store.load(sessionId);
56882
+ return snapshot.header.id === sessionId && snapshot.entries.some(isUsableContextMessage);
56826
56883
  } catch {
56827
56884
  return false;
56828
56885
  }
@@ -56842,6 +56899,41 @@ function hasUsableContentBlock(block) {
56842
56899
  return [contentBlock.text, contentBlock.thinking, contentBlock.data, contentBlock.name].some((value2) => typeof value2 === "string" && value2.trim().length > 0);
56843
56900
  }
56844
56901
 
56902
+ // dist/builtin/workflows/src/shared/stage-session-store.ts
56903
+ import { randomUUID as randomUUID3 } from "node:crypto";
56904
+ import {
56905
+ JsonlSessionStore,
56906
+ resolveSessionStore,
56907
+ SessionManager
56908
+ } from "@bastani/atomic";
56909
+ async function stageSessionStore(options, defaultSessionDir) {
56910
+ if (options.sessionStore !== undefined)
56911
+ return options.sessionStore;
56912
+ if (options.sessionManager !== undefined)
56913
+ return options.sessionManager.getSessionStore();
56914
+ const directory = options.sessionDir ?? defaultSessionDir;
56915
+ if (directory !== undefined)
56916
+ return JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false });
56917
+ return resolveSessionStore(options.cwd ?? process.cwd(), {
56918
+ agentDir: options.agentDir,
56919
+ settings: options.settingsManager?.getSettings()
56920
+ });
56921
+ }
56922
+ async function forkStageSession(store, sessionId, cwd, options, destination = store) {
56923
+ const source = await store.load(sessionId);
56924
+ const id = randomUUID3();
56925
+ await destination.create({
56926
+ id,
56927
+ version: 4,
56928
+ createdAt: new Date().toISOString(),
56929
+ cwd,
56930
+ parentSessionId: sessionId,
56931
+ ...options.internal === true ? { internal: true } : {},
56932
+ ...options.workflow === undefined ? {} : { workflow: options.workflow }
56933
+ }, source.entries);
56934
+ return SessionManager.open(destination, id, cwd);
56935
+ }
56936
+
56845
56937
  // dist/builtin/workflows/src/durable/stage-topology-validation.ts
56846
56938
  function immutableStageGroupError(stages) {
56847
56939
  const occurrenceError = promptOccurrenceIdentityError(stages);
@@ -57337,12 +57429,12 @@ function raceAbort(operation, signal) {
57337
57429
  }
57338
57430
 
57339
57431
  // dist/builtin/workflows/src/durable/factory.ts
57340
- import { resolve as resolve2 } from "node:path";
57341
- import { SettingsManager } from "@bastani/atomic";
57432
+ import { getAgentDir as getAgentDir3, SettingsManager } from "@bastani/atomic";
57433
+ import { storageSelectionKey } from "@bastani/atomic/storage";
57342
57434
 
57343
57435
  // dist/builtin/workflows/src/durable/journal/journal-backend.ts
57344
57436
  import { AsyncLocalStorage } from "node:async_hooks";
57345
- import { randomUUID as randomUUID3 } from "node:crypto";
57437
+ import { randomUUID as randomUUID4 } from "node:crypto";
57346
57438
  import { StorageError } from "@bastani/atomic/storage";
57347
57439
 
57348
57440
  // dist/builtin/workflows/src/runs/foreground/stage-session-heartbeat.ts
@@ -57482,7 +57574,7 @@ function prepareDurableChildInvocation(input) {
57482
57574
  return;
57483
57575
  }
57484
57576
  topology = makeTopology(input, boundaryId, childRunId, parentIds, sourceOrder, "start", "running");
57485
- await input.backend.recordCheckpointAsync({
57577
+ await input.backend.commitCheckpoint({
57486
57578
  kind: "stage",
57487
57579
  workflowId: input.workflowId,
57488
57580
  checkpointId: `boundary-start:${input.replayKey}`,
@@ -57509,7 +57601,7 @@ function prepareDurableChildInvocation(input) {
57509
57601
  const terminalTopology = makeTopology(input, boundaryId, childRunId, topology.parentIds, topology.sourceOrder, "terminal", status);
57510
57602
  const priorTerminalAt = stages.filter((stage) => stage.replayKey === input.replayKey && stage.topology?.boundary?.event === "terminal").reduce((latest, stage) => Math.max(latest, stage.completedAt), 0);
57511
57603
  const now = Math.max(Date.now(), priorTerminalAt + 1);
57512
- await input.backend.recordCheckpointAsync({
57604
+ await input.backend.commitCheckpoint({
57513
57605
  kind: "stage",
57514
57606
  workflowId: input.workflowId,
57515
57607
  checkpointId: `boundary-terminal:${input.replayKey}:${status}`,
@@ -57692,6 +57784,25 @@ function validatedInvocationRecords(input) {
57692
57784
  return { stages, start };
57693
57785
  }
57694
57786
 
57787
+ // dist/builtin/workflows/src/durable/execution-context-boundary.ts
57788
+ var executionStorages = new Set;
57789
+ function registerExecutionStorages(...storages) {
57790
+ for (const storage of storages)
57791
+ executionStorages.add(storage);
57792
+ return () => {
57793
+ for (const storage of storages)
57794
+ executionStorages.delete(storage);
57795
+ };
57796
+ }
57797
+ function outsideWorkflowExecutions(callback) {
57798
+ let run = callback;
57799
+ for (const storage of executionStorages) {
57800
+ const inner = run;
57801
+ run = () => storage.exit(inner);
57802
+ }
57803
+ return run();
57804
+ }
57805
+
57695
57806
  // dist/builtin/workflows/src/durable/prompt-reservation-state.ts
57696
57807
  function promptReservationToken(entry) {
57697
57808
  return entry;
@@ -57818,13 +57929,6 @@ class PromptReservationState {
57818
57929
 
57819
57930
  // dist/builtin/workflows/src/durable/journal/internal.ts
57820
57931
  var JOURNAL_READ_PAGE_SIZE = 256;
57821
- var synchronousJournals = new WeakMap;
57822
- function registerSynchronousJournal(journal, synchronous) {
57823
- synchronousJournals.set(journal, synchronous);
57824
- }
57825
- function synchronousJournal(journal) {
57826
- return synchronousJournals.get(journal);
57827
- }
57828
57932
 
57829
57933
  // dist/builtin/workflows/src/durable/journal/values.ts
57830
57934
  function validateText(field, value2) {
@@ -57860,33 +57964,22 @@ class MemoryRunJournal {
57860
57964
  runs = new Map;
57861
57965
  leases = new Map;
57862
57966
  closed = false;
57863
- constructor() {
57864
- registerSynchronousJournal(this, {
57865
- createRunSync: this.createRunSync.bind(this),
57866
- listRunsSync: this.listRunsSync.bind(this),
57867
- takeoverExpiredSync: this.takeoverExpiredSync.bind(this),
57868
- leaseStateSync: this.leaseStateSync.bind(this),
57869
- renewSync: this.renewSync.bind(this),
57870
- releaseSync: this.releaseSync.bind(this),
57871
- appendSync: this.appendSync.bind(this),
57872
- readEntries: this.readEntries.bind(this),
57873
- deleteRunSync: this.deleteRunSync.bind(this)
57874
- });
57967
+ storage;
57968
+ constructor(storage) {
57969
+ this.storage = storage === undefined ? undefined : { ...storage };
57875
57970
  }
57876
57971
  ensureOpen() {
57877
57972
  if (this.closed)
57878
57973
  throw new StorageUnavailableError({ adapter: "memory", location: ":memory:" }, new JournalClosedError);
57879
57974
  }
57880
57975
  async createRun(header) {
57881
- return this.createRunSync(header);
57882
- }
57883
- createRunSync(header) {
57884
57976
  this.ensureOpen();
57885
57977
  validateText("runId", header.runId);
57886
57978
  validateText("name", header.name);
57887
57979
  validateText("cwd", header.cwd);
57888
57980
  validateText("status", header.status);
57889
- const stored = storageBoundary(":memory:", () => JSON.parse(serializeJson(header)));
57981
+ const record = this.storage === undefined ? header : { ...header, storage: this.storage };
57982
+ const stored = storageBoundary(":memory:", () => JSON.parse(serializeJson(record)));
57890
57983
  if (this.runs.has(header.runId))
57891
57984
  return "exists";
57892
57985
  this.runs.set(header.runId, { header: stored, entries: [] });
@@ -57899,9 +57992,6 @@ class MemoryRunJournal {
57899
57992
  return run ? JSON.parse(serializeJson(run.header)) : undefined;
57900
57993
  }
57901
57994
  async listRuns(filter) {
57902
- return this.listRunsSync(filter);
57903
- }
57904
- listRunsSync(filter) {
57905
57995
  this.ensureOpen();
57906
57996
  if (filter?.cwd !== undefined)
57907
57997
  validateText("cwd", filter.cwd);
@@ -57921,9 +58011,6 @@ class MemoryRunJournal {
57921
58011
  return { status: "acquired", lease: { runId, holderId, epoch } };
57922
58012
  }
57923
58013
  async acquire(runId, holderId) {
57924
- return this.acquireSync(runId, holderId);
57925
- }
57926
- acquireSync(runId, holderId) {
57927
58014
  this.ensureOpen();
57928
58015
  validateText("runId", runId);
57929
58016
  validateText("holderId", holderId);
@@ -57951,24 +58038,18 @@ class MemoryRunJournal {
57951
58038
  return this.grant(runId, holderId);
57952
58039
  }
57953
58040
  async takeoverExpired(runId, holderId, staleAfterMs) {
57954
- return this.takeoverExpiredSync(runId, holderId, staleAfterMs);
57955
- }
57956
- takeoverExpiredSync(runId, holderId, staleAfterMs) {
57957
58041
  this.ensureOpen();
57958
58042
  validateText("runId", runId);
57959
58043
  validateText("holderId", holderId);
57960
58044
  this.requireRun(runId);
57961
- const current = this.leaseStateSync(runId);
58045
+ const current = this.leases.get(runId);
57962
58046
  if (current?.holderId === holderId)
57963
- return this.acquireSync(runId, holderId);
57964
- if (current !== undefined && !isWorkflowLeaseExpired(0, staleAfterMs, current.ageMs))
58047
+ return { status: "acquired", lease: { runId, holderId, epoch: current.epoch } };
58048
+ if (current?.holderId !== undefined && current.holderId !== null && !isWorkflowLeaseExpired(0, staleAfterMs, Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Date.now() - current.renewedAt))))
57965
58049
  return { status: "held", holderId: current.holderId, epoch: current.epoch };
57966
58050
  return this.grant(runId, holderId);
57967
58051
  }
57968
58052
  async leaseState(runId) {
57969
- return this.leaseStateSync(runId);
57970
- }
57971
- leaseStateSync(runId) {
57972
58053
  this.ensureOpen();
57973
58054
  validateText("runId", runId);
57974
58055
  const current = this.leases.get(runId);
@@ -57987,9 +58068,6 @@ class MemoryRunJournal {
57987
58068
  throw new StaleLeaseError(lease.runId, lease.epoch, current?.epoch ?? JOURNAL_LEASE.absentEpoch);
57988
58069
  }
57989
58070
  async renew(lease) {
57990
- this.renewSync(lease);
57991
- }
57992
- renewSync(lease) {
57993
58071
  this.ensureOpen();
57994
58072
  validateText("runId", lease.runId);
57995
58073
  validateText("holderId", lease.holderId);
@@ -57997,9 +58075,6 @@ class MemoryRunJournal {
57997
58075
  this.leases.set(lease.runId, { holderId: lease.holderId, epoch: lease.epoch, renewedAt: Date.now() });
57998
58076
  }
57999
58077
  async release(lease) {
58000
- this.releaseSync(lease);
58001
- }
58002
- releaseSync(lease) {
58003
58078
  this.ensureOpen();
58004
58079
  validateText("runId", lease.runId);
58005
58080
  validateText("holderId", lease.holderId);
@@ -58007,9 +58082,6 @@ class MemoryRunJournal {
58007
58082
  this.leases.set(lease.runId, { holderId: JOURNAL_LEASE.unheld, epoch: lease.epoch, renewedAt: Date.now() });
58008
58083
  }
58009
58084
  async append(lease, event, options) {
58010
- return this.appendSync(lease, event, options);
58011
- }
58012
- appendSync(lease, event, options) {
58013
58085
  this.ensureOpen();
58014
58086
  validateText("runId", lease.runId);
58015
58087
  validateText("holderId", lease.holderId);
@@ -58071,11 +58143,6 @@ class MemoryRunJournal {
58071
58143
  const start = Math.max(0, Math.ceil(fromSeq) - 1);
58072
58144
  return fromSeq <= entries.length ? entries.slice(start, start + JOURNAL_READ_PAGE_SIZE).map((entry) => this.copyEntry(entry)) : [];
58073
58145
  }
58074
- readEntries(runId, fromSeq = 1) {
58075
- this.ensureOpen();
58076
- validateText("runId", runId);
58077
- return (this.runs.get(runId)?.entries ?? []).filter((entry) => entry.seq >= fromSeq).map((entry) => this.copyEntry(entry));
58078
- }
58079
58146
  async readKey(runId, key) {
58080
58147
  this.ensureOpen();
58081
58148
  validateText("runId", runId);
@@ -58084,9 +58151,6 @@ class MemoryRunJournal {
58084
58151
  return entry ? this.copyEntry(entry) : undefined;
58085
58152
  }
58086
58153
  async deleteRun(runId) {
58087
- this.deleteRunSync(runId);
58088
- }
58089
- deleteRunSync(runId) {
58090
58154
  this.ensureOpen();
58091
58155
  validateText("runId", runId);
58092
58156
  const current = this.leases.get(runId);
@@ -58102,7 +58166,7 @@ class MemoryRunJournal {
58102
58166
  const actual = this.runs.get(lease.runId)?.entries.at(-1)?.seq ?? 0;
58103
58167
  if (expectSeq !== undefined && expectSeq !== actual)
58104
58168
  throw new JournalCasConflictError(lease.runId, expectSeq, actual);
58105
- this.deleteRunSync(lease.runId);
58169
+ await this.deleteRun(lease.runId);
58106
58170
  }
58107
58171
  async close() {
58108
58172
  this.closed = true;
@@ -58110,18 +58174,12 @@ class MemoryRunJournal {
58110
58174
  }
58111
58175
 
58112
58176
  // dist/builtin/workflows/src/durable/journal/journal-backend.ts
58113
- var PROCESS_HOLDER_ID = randomUUID3();
58114
- var DEFER_REBUILD = Symbol("defer-rebuild");
58115
- function isPromise(value2) {
58116
- return typeof value2?.then === "function";
58117
- }
58118
- function* invoke(action, synchronous = false) {
58177
+ var PROCESS_HOLDER_ID = randomUUID4();
58178
+ function* invoke(action) {
58119
58179
  try {
58120
58180
  const result = action();
58121
- if (synchronous)
58122
- return result;
58123
58181
  let value2;
58124
- yield Promise.resolve(result).then((resolved) => {
58182
+ yield result.then((resolved) => {
58125
58183
  value2 = resolved;
58126
58184
  });
58127
58185
  return value2;
@@ -58131,10 +58189,17 @@ function* invoke(action, synchronous = false) {
58131
58189
  throw new StorageUnavailableError({ adapter: "custom", location: "custom journal" }, error instanceof Error ? error : new Error(String(error)));
58132
58190
  }
58133
58191
  }
58134
- function execute(operation, step = operation.next()) {
58135
- if (step.done)
58136
- return step.value;
58137
- return step.value.then(() => execute(operation), (error) => execute(operation, operation.throw(error)));
58192
+ async function execute(operation) {
58193
+ let step = operation.next();
58194
+ while (!step.done) {
58195
+ try {
58196
+ await step.value;
58197
+ step = operation.next();
58198
+ } catch (error) {
58199
+ step = operation.throw(error);
58200
+ }
58201
+ }
58202
+ return step.value;
58138
58203
  }
58139
58204
 
58140
58205
  class JournalOwnershipError extends WorkflowInstanceOwnershipError {
@@ -58194,31 +58259,31 @@ class JournalDurableBackend {
58194
58259
  ownsJournal;
58195
58260
  persistent;
58196
58261
  projection = createJournalProjection();
58197
- synchronous;
58198
58262
  sequences = new Map;
58199
58263
  leases = new Map;
58200
58264
  executions = new Map;
58201
58265
  executionContext = new AsyncLocalStorage;
58202
58266
  pending = new Map;
58267
+ catalogQueue = Symbol("catalog");
58203
58268
  lost = new Map;
58204
58269
  prompts = new Map;
58205
58270
  timer;
58206
- closed = false;
58271
+ state = "open";
58272
+ closing;
58273
+ renewing;
58274
+ mutationContext = new AsyncLocalStorage;
58207
58275
  processExitCleanup;
58208
- constructor(journal, holderId = `${PROCESS_HOLDER_ID}:${randomUUID3()}`, rebuild, ownsJournal = true) {
58276
+ unregisterExecutionStorages = registerExecutionStorages(this.executionContext, this.mutationContext);
58277
+ constructor(journal, holderId = `${PROCESS_HOLDER_ID}:${randomUUID4()}`, ownsJournal = true) {
58209
58278
  this.journal = journal;
58210
58279
  this.holderId = holderId;
58211
58280
  this.ownsJournal = ownsJournal;
58212
- this.synchronous = synchronousJournal(journal);
58213
58281
  this.persistent = !(journal instanceof MemoryRunJournal);
58214
- if (rebuild !== DEFER_REBUILD && this.synchronous !== undefined)
58215
- for (const run of this.synchronous.listRunsSync())
58216
- execute(this.refresh(run.runId));
58217
58282
  }
58218
58283
  static async open(journal, options = {}) {
58219
58284
  let backend;
58220
58285
  try {
58221
- backend = new JournalDurableBackend(journal, undefined, DEFER_REBUILD, options.ownsJournal ?? true);
58286
+ backend = new JournalDurableBackend(journal, undefined, options.ownsJournal ?? true);
58222
58287
  for (const run of await journal.listRuns())
58223
58288
  for await (const entry of journal.read(run.runId))
58224
58289
  backend.fold(entry);
@@ -58234,21 +58299,31 @@ class JournalDurableBackend {
58234
58299
  throw new StorageUnavailableError({ adapter: "custom", location: "custom journal" }, error instanceof Error ? error : new Error(String(error)));
58235
58300
  }
58236
58301
  }
58237
- serialize(runId, action) {
58238
- const prior = this.pending.get(runId);
58239
- if (prior !== undefined)
58240
- return prior.then(() => this.serialize(runId, action));
58241
- const result = execute(action());
58242
- if (!isPromise(result))
58243
- return result;
58302
+ serialize(runId, action, requiresActiveExecution = true) {
58303
+ try {
58304
+ this.ensureOpen();
58305
+ if (requiresActiveExecution)
58306
+ this.assertExecutionActive(runId);
58307
+ } catch (error) {
58308
+ return Promise.reject(error);
58309
+ }
58310
+ const admitted = new Set([...this.executionContext.getStore()?.values() ?? []].filter((execution) => !execution.retired));
58311
+ return this.enqueue(runId, action, admitted);
58312
+ }
58313
+ enqueue(runId, action, admitted = this.mutationContext.getStore() ?? new Set) {
58314
+ const prior = this.pending.get(runId) ?? Promise.resolve();
58315
+ const result = prior.then(() => this.mutationContext.run(admitted, () => execute(action())));
58244
58316
  const settled = result.then(() => {}, () => {});
58245
58317
  this.pending.set(runId, settled);
58246
- return result.finally(() => {
58318
+ settled.then(() => {
58247
58319
  if (this.pending.get(runId) === settled)
58248
58320
  this.pending.delete(runId);
58249
58321
  });
58322
+ return result;
58250
58323
  }
58251
58324
  fold(entry) {
58325
+ if (entry.seq <= (this.sequences.get(entry.runId) ?? 0))
58326
+ return;
58252
58327
  const event = entry.event;
58253
58328
  if (event.type === RUN_EVENT_TYPES.checkpointRecorded) {
58254
58329
  const checkpoint = event.payload;
@@ -58283,8 +58358,6 @@ class JournalDurableBackend {
58283
58358
  this.sequences.set(entry.runId, entry.seq);
58284
58359
  }
58285
58360
  *entries(runId, fromSeq) {
58286
- if (this.synchronous !== undefined)
58287
- return this.synchronous.readEntries(runId, fromSeq);
58288
58361
  return yield* invoke(async () => {
58289
58362
  const entries = [];
58290
58363
  for await (const entry of this.journal.read(runId, fromSeq))
@@ -58308,7 +58381,7 @@ class JournalDurableBackend {
58308
58381
  }
58309
58382
  *current(runId) {
58310
58383
  this.ensureOpen();
58311
- this.assertExecutionActive(runId);
58384
+ this.assertExecutionActive(runId, true);
58312
58385
  yield* this.refresh(runId);
58313
58386
  if (this.projection.getWorkflow(runId) === undefined)
58314
58387
  return;
@@ -58324,24 +58397,24 @@ class JournalDurableBackend {
58324
58397
  return this.projection.getWorkflow(runId);
58325
58398
  }
58326
58399
  ensureOpen() {
58327
- if (this.closed)
58400
+ if (this.state === "closed" || this.state === "closing" && !this.mutationContext.getStore())
58328
58401
  throw new JournalBackendClosedError;
58329
58402
  }
58330
- assertExecutionActive(runId) {
58331
- for (const execution of this.executionContext.getStore()?.values() ?? [])
58332
- if (execution.retired)
58333
- throw new JournalExecutionRetiredError(runId);
58403
+ assertExecutionActive(runId, admitted = false) {
58404
+ for (const [executionRunId, execution] of this.executionContext.getStore() ?? [])
58405
+ if (execution.retired && !(admitted && this.mutationContext.getStore()?.has(execution)))
58406
+ throw new JournalExecutionRetiredError(typeof runId === "string" ? runId : executionRunId);
58334
58407
  }
58335
58408
  *ownership(runId) {
58336
58409
  this.ensureOpen();
58337
- this.assertExecutionActive(runId);
58410
+ this.assertExecutionActive(runId, true);
58338
58411
  const lost = this.lost.get(runId);
58339
58412
  if (lost)
58340
58413
  throw lost;
58341
58414
  const existing = this.leases.get(runId);
58342
58415
  if (existing)
58343
58416
  return existing;
58344
- const result = yield* invoke(() => this.synchronous !== undefined ? this.synchronous.takeoverExpiredSync(runId, this.holderId, FOREIGN_LIVE_WORKFLOW_WINDOW_MS) : this.journal.takeoverExpired(runId, this.holderId, FOREIGN_LIVE_WORKFLOW_WINDOW_MS), this.synchronous !== undefined);
58417
+ const result = yield* invoke(() => this.journal.takeoverExpired(runId, this.holderId, FOREIGN_LIVE_WORKFLOW_WINDOW_MS));
58345
58418
  if (result.status === "held")
58346
58419
  throw new JournalOwnershipError(runId, result.holderId);
58347
58420
  this.leases.set(runId, result.lease);
@@ -58351,7 +58424,7 @@ class JournalDurableBackend {
58351
58424
  }, STAGE_SESSION_HEARTBEAT_INTERVAL_MS);
58352
58425
  this.timer.unref();
58353
58426
  }
58354
- const execution = this.executions.get(runId);
58427
+ const execution = this.executionContext.getStore()?.get(runId) ?? this.executions.get(runId);
58355
58428
  if (execution !== undefined)
58356
58429
  execution.lease = result.lease;
58357
58430
  yield* this.rebuild(runId);
@@ -58363,7 +58436,7 @@ class JournalDurableBackend {
58363
58436
  let failure = new JournalOwnershipError(runId, null, error);
58364
58437
  this.lost.set(runId, failure);
58365
58438
  try {
58366
- const current = yield* invoke(() => this.synchronous !== undefined ? this.synchronous.leaseStateSync(runId) : this.journal.leaseState(runId), this.synchronous !== undefined);
58439
+ const current = yield* invoke(() => this.journal.leaseState(runId));
58367
58440
  failure = new JournalOwnershipError(runId, current?.holderId ?? null, error);
58368
58441
  this.lost.set(runId, failure);
58369
58442
  } catch {}
@@ -58372,8 +58445,8 @@ class JournalDurableBackend {
58372
58445
  *append(runId, event, options) {
58373
58446
  const lease = yield* this.ownership(runId);
58374
58447
  try {
58375
- yield* invoke(() => this.synchronous !== undefined ? this.synchronous.appendSync(lease, event, options) : this.journal.append(lease, event, options), this.synchronous !== undefined);
58376
- yield* this.refresh(runId);
58448
+ const outcome = yield* invoke(() => this.journal.append(lease, event, options));
58449
+ this.fold(outcome.entry);
58377
58450
  } catch (error) {
58378
58451
  if (error instanceof Error)
58379
58452
  throw yield* this.mapOwnership(error, runId);
@@ -58390,11 +58463,11 @@ class JournalDurableBackend {
58390
58463
  draft.registerWorkflow(handle, true);
58391
58464
  return draft;
58392
58465
  }
58393
- registerWorkflow(input) {
58466
+ commitWorkflowRegistration(input) {
58394
58467
  return this.serialize(input.workflowId, () => this.register(input));
58395
58468
  }
58396
58469
  *register(input) {
58397
- this.assertExecutionActive(input.workflowId);
58470
+ this.assertExecutionActive(input.workflowId, true);
58398
58471
  this.ensureOpen();
58399
58472
  const header = {
58400
58473
  runId: input.workflowId,
@@ -58404,7 +58477,7 @@ class JournalDurableBackend {
58404
58477
  status: input.status,
58405
58478
  inputs: input.inputs
58406
58479
  };
58407
- yield* invoke(() => this.synchronous?.createRunSync(header) ?? this.journal.createRun(header), this.synchronous !== undefined);
58480
+ yield* invoke(() => this.journal.createRun(header));
58408
58481
  yield* this.ownership(input.workflowId);
58409
58482
  yield* this.refresh(input.workflowId);
58410
58483
  const draft = yield* this.draft(input.workflowId);
@@ -58415,7 +58488,9 @@ class JournalDurableBackend {
58415
58488
  if (checkpoint.kind === "stage" && checkpoint.topology?.boundary !== undefined && typeof checkpoint.topology.boundary.invocationFingerprint !== "string")
58416
58489
  throw new DurableNestedTopologyError(`missing invocation fingerprint at ${checkpoint.checkpointId}`);
58417
58490
  }
58418
- recordCheckpoint(checkpoint) {
58491
+ commitCheckpoint(checkpoint, options) {
58492
+ if (options?.signal?.aborted)
58493
+ return Promise.reject(new JournalOperationAbortedError(checkpoint.workflowId, options.signal.reason instanceof Error ? options.signal.reason : undefined));
58419
58494
  return this.serialize(checkpoint.workflowId, () => this.checkpoint(checkpoint));
58420
58495
  }
58421
58496
  *checkpoint(checkpoint) {
@@ -58426,14 +58501,9 @@ class JournalDurableBackend {
58426
58501
  key: JSON.stringify([RUN_EVENT_TYPES.checkpointRecorded, checkpoint.kind, checkpoint.checkpointId])
58427
58502
  });
58428
58503
  }
58429
- async recordCheckpointAsync(checkpoint, options) {
58430
- if (options?.signal?.aborted)
58431
- throw new JournalOperationAbortedError(checkpoint.workflowId, options.signal.reason instanceof Error ? options.signal.reason : undefined);
58432
- await this.recordCheckpoint(checkpoint);
58433
- }
58434
- async recordAdditiveCheckpointBestEffort(checkpoint) {
58504
+ async commitAdditiveCheckpointBestEffort(checkpoint) {
58435
58505
  try {
58436
- await this.recordCheckpointAsync(checkpoint);
58506
+ await this.commitCheckpoint(checkpoint);
58437
58507
  return true;
58438
58508
  } catch (error) {
58439
58509
  if (!(error instanceof StorageUnavailableError))
@@ -58442,13 +58512,7 @@ class JournalDurableBackend {
58442
58512
  }
58443
58513
  }
58444
58514
  workflowOwnership(runId) {
58445
- if (this.synchronous !== undefined) {
58446
- const lease = this.synchronous.leaseStateSync(runId);
58447
- if (lease === undefined || isWorkflowLeaseExpired(0, FOREIGN_LIVE_WORKFLOW_WINDOW_MS, lease.ageMs))
58448
- return "available";
58449
- return lease.holderId === this.holderId ? "local" : "foreign";
58450
- }
58451
- return this.serialize(runId, () => this.probeOwnership(runId));
58515
+ return this.serialize(runId, () => this.probeOwnership(runId), false);
58452
58516
  }
58453
58517
  *probeOwnership(runId) {
58454
58518
  this.ensureOpen();
@@ -58457,7 +58521,7 @@ class JournalDurableBackend {
58457
58521
  return "available";
58458
58522
  return lease.holderId === this.holderId ? "local" : "foreign";
58459
58523
  }
58460
- setWorkflowStatus(runId, status, pendingPrompts, resumable, failure) {
58524
+ commitWorkflowStatus(runId, status, pendingPrompts, resumable, failure) {
58461
58525
  return this.serialize(runId, () => this.setStatus(runId, status, pendingPrompts, resumable, failure));
58462
58526
  }
58463
58527
  *setStatus(runId, status, pendingPrompts, resumable, failure) {
@@ -58467,7 +58531,7 @@ class JournalDurableBackend {
58467
58531
  if (handle)
58468
58532
  yield* this.snapshot(handle);
58469
58533
  }
58470
- async transitionWorkflowStatus(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
58534
+ async commitWorkflowStatusTransition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
58471
58535
  return await this.serialize(runId, () => this.transition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner));
58472
58536
  }
58473
58537
  *transition(runId, expected, status, pendingPrompts, resumable, expectedUpdatedAt, modelOwner, releasedModelOwner) {
@@ -58517,7 +58581,7 @@ class JournalDurableBackend {
58517
58581
  });
58518
58582
  return result;
58519
58583
  }
58520
- adjustPendingPrompts(runId, delta) {
58584
+ commitPendingPromptAdjustment(runId, delta) {
58521
58585
  return this.serialize(runId, () => this.promptChange(runId, delta >= 0 ? RUN_EVENT_TYPES.promptAsked : RUN_EVENT_TYPES.promptReleased, (state) => state.adjust(delta)));
58522
58586
  }
58523
58587
  promptReservationScope(runId) {
@@ -58623,12 +58687,14 @@ class JournalDurableBackend {
58623
58687
  return this.getPendingStageMessageDeliveryCount(runId, messageId, logicalRunId);
58624
58688
  }
58625
58689
  async hydrateWorkflow(runId) {
58626
- await this.serialize(runId, () => this.rebuild(runId));
58690
+ await this.serialize(runId, () => this.rebuild(runId), false);
58627
58691
  }
58628
- async hydrateResumableWorkflows() {
58629
- const runs = await execute(invoke(() => this.journal.listRuns()));
58630
- for (const runId of new Set([...this.sequences.keys(), ...runs.map((run) => run.runId)]))
58631
- await this.hydrateWorkflow(runId);
58692
+ hydrateResumableWorkflows() {
58693
+ return this.serialize(this.catalogQueue, () => invoke(async () => {
58694
+ const runs = await this.journal.listRuns();
58695
+ for (const runId of new Set([...this.sequences.keys(), ...runs.map((run) => run.runId)]))
58696
+ await this.hydrateWorkflow(runId);
58697
+ }));
58632
58698
  }
58633
58699
  async prepareWorkflowCatalog() {
58634
58700
  await this.hydrateResumableWorkflows();
@@ -58637,13 +58703,7 @@ class JournalDurableBackend {
58637
58703
  *deleteOwned(runId, expectSeq) {
58638
58704
  try {
58639
58705
  const lease = yield* this.ownership(runId);
58640
- if (expectSeq !== undefined) {
58641
- const entries = yield* this.entries(runId);
58642
- const actualSeq = entries.at(-1)?.seq ?? 0;
58643
- if (actualSeq !== expectSeq)
58644
- throw new JournalCasConflictError(runId, expectSeq, actualSeq);
58645
- }
58646
- yield* invoke(() => this.journal.deleteOwnedRun(lease));
58706
+ yield* invoke(() => this.journal.deleteOwnedRun(lease, expectSeq));
58647
58707
  } catch (error) {
58648
58708
  if (!(error instanceof RunNotFoundError)) {
58649
58709
  if (error instanceof Error)
@@ -58684,27 +58744,33 @@ class JournalDurableBackend {
58684
58744
  }
58685
58745
  }
58686
58746
  }
58687
- reset() {
58688
- return execute(this.resetJournal());
58747
+ commitReset() {
58748
+ return this.serialize(this.catalogQueue, () => this.resetJournal());
58689
58749
  }
58690
58750
  *resetJournal() {
58691
- const runs = yield* invoke(() => this.synchronous?.listRunsSync() ?? this.journal.listRuns(), this.synchronous !== undefined);
58751
+ const runIds = new Set(this.sequences.keys());
58752
+ const runs = yield* invoke(() => this.journal.listRuns());
58692
58753
  for (const run of runs)
58693
- yield* invoke(() => {
58694
- if (this.synchronous !== undefined)
58695
- return this.synchronous.deleteRunSync(run.runId);
58696
- return this.journal.deleteRun(run.runId);
58697
- }, this.synchronous !== undefined);
58698
- this.projection.reset();
58699
- this.sequences.clear();
58700
- this.leases.clear();
58701
- this.lost.clear();
58702
- this.prompts.clear();
58703
- }
58704
- async renewLeases() {
58754
+ runIds.add(run.runId);
58755
+ for (const runId of runIds)
58756
+ yield this.enqueue(runId, () => this.deleteOwned(runId));
58757
+ }
58758
+ renewLeases() {
58759
+ if (this.renewing !== undefined)
58760
+ return this.renewing;
58761
+ if (this.state !== "open")
58762
+ return Promise.resolve();
58763
+ this.renewing = this.renewOwnedLeases().finally(() => {
58764
+ this.renewing = undefined;
58765
+ });
58766
+ return this.renewing;
58767
+ }
58768
+ async renewOwnedLeases() {
58705
58769
  for (const [runId, lease] of this.leases) {
58770
+ if (this.state !== "open")
58771
+ return;
58706
58772
  try {
58707
- await this.serialize(runId, () => this.renewLease(runId, lease));
58773
+ await this.serialize(runId, () => this.renewLease(runId, lease), false);
58708
58774
  } catch (error) {
58709
58775
  if (error instanceof Error)
58710
58776
  this.lost.set(runId, error);
@@ -58716,11 +58782,7 @@ class JournalDurableBackend {
58716
58782
  if (this.leases.get(runId) !== lease || this.lost.has(runId))
58717
58783
  return;
58718
58784
  try {
58719
- yield* invoke(() => {
58720
- if (this.synchronous !== undefined)
58721
- return this.synchronous.renewSync(lease);
58722
- return this.journal.renew(lease);
58723
- }, this.synchronous !== undefined);
58785
+ yield* invoke(() => this.journal.renew(lease));
58724
58786
  } catch (error) {
58725
58787
  if (this.leases.get(runId) === lease) {
58726
58788
  if (error instanceof Error)
@@ -58773,23 +58835,20 @@ class JournalDurableBackend {
58773
58835
  execution.retired = true;
58774
58836
  if (this.executions.get(runId) === execution)
58775
58837
  this.executions.delete(runId);
58776
- if (execution.lease !== undefined && this.leases.get(runId) === execution.lease)
58777
- return this.serialize(runId, () => this.release(runId));
58838
+ if (this.state !== "open")
58839
+ return this.closing;
58840
+ return this.serialize(runId, () => this.release(runId, execution), false);
58778
58841
  }
58779
58842
  releaseWorkflow(runId) {
58780
58843
  this.assertExecutionActive(runId);
58781
58844
  return this.serialize(runId, () => this.release(runId));
58782
58845
  }
58783
- *release(runId) {
58846
+ *release(runId, execution) {
58784
58847
  const lease = this.leases.get(runId);
58785
- if (lease === undefined)
58848
+ if (lease === undefined || execution !== undefined && execution.lease !== lease)
58786
58849
  return;
58787
58850
  try {
58788
- yield* invoke(() => {
58789
- if (this.synchronous !== undefined)
58790
- return this.synchronous.releaseSync(lease);
58791
- return this.journal.release(lease);
58792
- }, this.synchronous !== undefined);
58851
+ yield* invoke(() => this.journal.release(lease));
58793
58852
  } catch (error) {
58794
58853
  if (!(error instanceof StaleLeaseError))
58795
58854
  throw error;
@@ -58800,31 +58859,38 @@ class JournalDurableBackend {
58800
58859
  dropLease(runId) {
58801
58860
  this.leases.delete(runId);
58802
58861
  if (this.leases.size === 0) {
58803
- clearInterval(this.timer);
58862
+ if (this.timer !== undefined)
58863
+ clearInterval(this.timer);
58804
58864
  this.timer = undefined;
58805
58865
  }
58806
58866
  }
58807
- *releaseAll() {
58808
- for (const runId of this.leases.keys())
58809
- yield* this.release(runId);
58810
- }
58811
- async close() {
58867
+ close() {
58868
+ if (this.closing !== undefined)
58869
+ return this.closing;
58870
+ this.state = "closing";
58812
58871
  if (this.processExitCleanup !== undefined) {
58813
58872
  process.off("exit", this.processExitCleanup);
58814
58873
  this.processExitCleanup = undefined;
58815
58874
  }
58816
- if (this.closed)
58817
- return;
58818
58875
  if (this.timer !== undefined)
58819
58876
  clearInterval(this.timer);
58820
- if (this.pending.size > 0)
58821
- await Promise.all(this.pending.values());
58877
+ this.timer = undefined;
58878
+ this.closing = this.drainAndClose();
58879
+ return this.closing;
58880
+ }
58881
+ async drainAndClose() {
58822
58882
  try {
58823
- const released = execute(this.releaseAll());
58824
- if (isPromise(released))
58825
- await released;
58883
+ await this.renewing;
58884
+ while (this.pending.size > 0)
58885
+ await Promise.all(this.pending.values());
58886
+ for (const runId of this.leases.keys())
58887
+ await execute(this.release(runId));
58826
58888
  } finally {
58827
- this.closed = true;
58889
+ if (this.timer !== undefined)
58890
+ clearInterval(this.timer);
58891
+ this.timer = undefined;
58892
+ this.state = "closed";
58893
+ this.unregisterExecutionStorages();
58828
58894
  if (this.ownsJournal)
58829
58895
  await execute(invoke(() => this.journal.close()));
58830
58896
  }
@@ -58832,12 +58898,13 @@ class JournalDurableBackend {
58832
58898
  }
58833
58899
 
58834
58900
  // dist/builtin/workflows/src/durable/journal/resolution.ts
58835
- import { dirname as dirname2, isAbsolute as isAbsolute2, join as join3 } from "node:path";
58836
- import { getAgentDir as getAgentDir3 } from "@bastani/atomic";
58837
-
58838
- // dist/builtin/workflows/src/durable/journal/sqlite-run-journal.ts
58839
- import { dirname, join as join2 } from "node:path";
58840
- import { getAgentDir as getAgentDir2, openNodeSqliteDatabase, validateStoragePrefix, wrapNodeSqliteDatabase } from "@bastani/atomic";
58901
+ import { dirname, isAbsolute as isAbsolute2, join as join2 } from "node:path";
58902
+ import { getAgentDir as getAgentDir2 } from "@bastani/atomic";
58903
+ import {
58904
+ StorageConfigError,
58905
+ StorageProvider,
58906
+ selectStorage
58907
+ } from "@bastani/atomic/storage";
58841
58908
 
58842
58909
  // dist/builtin/workflows/src/durable/journal/sql-run-journal.ts
58843
58910
  import {
@@ -59164,78 +59231,97 @@ class SqlRunJournal {
59164
59231
  }
59165
59232
  }
59166
59233
 
59167
- // dist/builtin/workflows/src/durable/journal/sqlite-run-journal.ts
59168
- function workflowJournalPath() {
59169
- const override = process.env.ATOMIC_WORKFLOW_JOURNAL_PATH;
59170
- return override !== undefined && override.length > 0 ? override : join2(dirname(getAgentDir2()), "workflows", "journal.sqlite");
59171
- }
59172
- async function openSqlRunJournal(source = workflowJournalPath(), options = {}) {
59173
- validateStoragePrefix(options.prefix);
59174
- const database = typeof source === "string" ? await openNodeSqliteDatabase(source) : wrapNodeSqliteDatabase(source);
59175
- try {
59176
- const journal = await SqlRunJournal.open(database, options);
59177
- const close = journal.close.bind(journal);
59178
- let closing;
59179
- journal.close = () => {
59180
- closing ??= close().then(() => database.close());
59181
- return closing;
59182
- };
59183
- return journal;
59184
- } catch (error) {
59185
- await database.close();
59186
- throw error;
59187
- }
59188
- }
59189
-
59190
59234
  // dist/builtin/workflows/src/durable/journal/resolution.ts
59235
+ var provider = new StorageProvider({
59236
+ memory: (descriptor) => new MemoryRunJournal(descriptor),
59237
+ sql: SqlRunJournal.open
59238
+ });
59239
+ var settingsSelections = new WeakSet;
59191
59240
  function selectRunJournal(options = {}) {
59192
- if (options.journal !== undefined)
59193
- return options.journal;
59241
+ const agentDir = getAgentDir2();
59242
+ const defaultPath = join2(dirname(agentDir), "workflows", "journal.sqlite");
59243
+ if (options.journal !== undefined) {
59244
+ if (options.journal !== null && typeof options.journal === "object" && "createRun" in options.journal) {
59245
+ const journal = options.journal;
59246
+ if ([
59247
+ journal.createRun,
59248
+ journal.getRun,
59249
+ journal.listRuns,
59250
+ journal.acquire,
59251
+ journal.takeover,
59252
+ journal.takeoverExpired,
59253
+ journal.leaseState,
59254
+ journal.renew,
59255
+ journal.release,
59256
+ journal.append,
59257
+ journal.read,
59258
+ journal.readKey,
59259
+ journal.deleteOwnedRun,
59260
+ journal.deleteRun,
59261
+ journal.close
59262
+ ].some((hook) => typeof hook !== "function")) {
59263
+ throw new StorageConfigError("sdk", "journal", "invalid-journal");
59264
+ }
59265
+ return journal;
59266
+ }
59267
+ return selectStorage(options.journal, "sdk", "journal", defaultPath);
59268
+ }
59194
59269
  const environment = process.env.ATOMIC_WORKFLOW_JOURNAL_PATH;
59195
59270
  if (environment !== undefined && environment.length > 0)
59196
- return { path: environment };
59271
+ return { kind: "sqlite", path: environment };
59197
59272
  const workflows = options.settings?.workflows;
59198
- const settings = Array.isArray(workflows) ? undefined : workflows?.journal;
59199
- const path = settings?.path;
59200
- if (path !== undefined && path.length > 0) {
59201
- if (settings?.memory === true)
59202
- throw new JournalConfigurationError("settings", "workflows.journal", "path-and-memory");
59203
- return { path: isAbsolute2(path) ? path : join3(dirname2(getAgentDir3()), path) };
59204
- }
59205
- if (settings?.memory === true)
59206
- return { memory: true };
59207
- return { path: workflowJournalPath() };
59273
+ const journal = Array.isArray(workflows) ? undefined : workflows?.journal;
59274
+ const value2 = journal !== undefined ? journal : options.settings?.storage;
59275
+ if (value2 === undefined)
59276
+ return { kind: "sqlite", path: defaultPath };
59277
+ const selection = selectStorage(value2, "settings", journal !== undefined ? "workflows.journal" : "storage", journal !== undefined ? defaultPath : join2(dirname(agentDir), "storage.sqlite"));
59278
+ const resolved = selection.kind === "sqlite" && !isAbsolute2(selection.path) ? { ...selection, path: join2(dirname(agentDir), selection.path) } : selection;
59279
+ settingsSelections.add(resolved);
59280
+ return resolved;
59208
59281
  }
59209
59282
  async function resolveRunJournal(options = {}) {
59210
- const selected = selectRunJournal(options);
59211
- if ("createRun" in selected)
59212
- return selected;
59213
- if ("path" in selected)
59214
- return await openSqlRunJournal(selected.path);
59215
- if ("database" in selected)
59216
- return await openSqlRunJournal(selected.database);
59217
- return new MemoryRunJournal;
59283
+ return openSelectedRunJournal(selectRunJournal(options));
59284
+ }
59285
+ async function openSelectedRunJournal(selection) {
59286
+ if ("createRun" in selection)
59287
+ return selection;
59288
+ return withRunJournalConfigSource(selection, () => provider.openRunJournal(selection, { agentDir: getAgentDir2(), domain: "journal" }));
59289
+ }
59290
+ async function withRunJournalConfigSource(selection, open) {
59291
+ if ("createRun" in selection)
59292
+ return open();
59293
+ try {
59294
+ return await open();
59295
+ } catch (error) {
59296
+ if (error instanceof StorageConfigError) {
59297
+ const source = settingsSelections.has(selection) ? "settings" : "sdk";
59298
+ if (error.source !== source)
59299
+ throw new StorageConfigError(source, error.field, error.reason);
59300
+ }
59301
+ throw error;
59302
+ }
59218
59303
  }
59219
59304
 
59220
59305
  // dist/builtin/workflows/src/durable/factory.ts
59221
- var DEFAULT_MEMORY_JOURNAL = "memory";
59222
59306
  async function initializeDurableBackend(options = {}) {
59223
59307
  const owner = getDurableBackendProcessOwner();
59224
59308
  const choice = options.journal;
59225
59309
  const selection = selectRunJournal({
59226
59310
  journal: choice,
59227
- settings: choice === undefined ? options.settings ?? SettingsManager.create(options.cwd ?? process.cwd()).getSettings() : undefined
59311
+ settings: choice === undefined ? options.settings ?? SettingsManager.create(options.cwd ?? process.cwd(), getAgentDir3(), {
59312
+ projectTrusted: options.projectTrusted
59313
+ }).getSettings() : undefined
59228
59314
  });
59229
- const key = "createRun" in selection ? selection : ("path" in selection) ? resolve2(selection.path) : ("database" in selection) ? selection.database : choice === undefined ? DEFAULT_MEMORY_JOURNAL : choice;
59315
+ const key = "createRun" in selection ? selection : selection.kind === "memory" && choice !== undefined ? choice : storageSelectionKey(selection, getAgentDir3());
59230
59316
  const ownsJournal = choice === undefined || !("createRun" in choice);
59231
59317
  owner.selectedBackends ??= new Map;
59232
59318
  const selected = owner.selectedBackends;
59233
59319
  const existing = selected.get(key);
59234
- let backend;
59320
+ let ready;
59235
59321
  if (existing !== undefined) {
59236
- backend = await existing.ready;
59322
+ ready = existing.ready;
59237
59323
  } else {
59238
- const ready = resolveRunJournal({ journal: selection }).then((journal) => JournalDurableBackend.open(journal, { ownsJournal })).then((opened) => {
59324
+ ready = openSelectedRunJournal(selection).then((journal) => JournalDurableBackend.open(journal, { ownsJournal })).then((opened) => {
59239
59325
  if (ownsJournal)
59240
59326
  opened.closeOnProcessExit();
59241
59327
  entry.close = () => opened.close();
@@ -59246,9 +59332,8 @@ async function initializeDurableBackend(options = {}) {
59246
59332
  });
59247
59333
  const entry = { ready };
59248
59334
  selected.set(key, entry);
59249
- backend = await ready;
59250
59335
  }
59251
- return backend;
59336
+ return withRunJournalConfigSource(selection, () => ready);
59252
59337
  }
59253
59338
 
59254
59339
  // dist/builtin/workflows/src/shared/workflow-request-timeout.ts
@@ -60596,14 +60681,14 @@ function createDurableChildWorkflowPrimitive(input) {
60596
60681
  }
60597
60682
 
60598
60683
  // dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts
60599
- import { isAbsolute as isAbsolute9, join as join11, resolve as resolve10 } from "node:path";
60684
+ import { isAbsolute as isAbsolute9, join as join10, resolve as resolve9 } from "node:path";
60600
60685
  import { CONFIG_DIR_NAME as CONFIG_DIR_NAME2 } from "@bastani/atomic";
60601
60686
 
60602
60687
  // dist/builtin/workflows/src/shared/workflow-artifacts.ts
60603
- import { randomUUID as randomUUID4 } from "node:crypto";
60688
+ import { randomUUID as randomUUID5 } from "node:crypto";
60604
60689
  import { existsSync } from "node:fs";
60605
60690
  import { mkdir, readdir, rm, stat } from "node:fs/promises";
60606
- import { dirname as dirname3, join as join4 } from "node:path";
60691
+ import { dirname as dirname2, join as join3 } from "node:path";
60607
60692
  import { getAgentDir as getAgentDir4, getEnvValue as getEnvValue2 } from "@bastani/atomic";
60608
60693
 
60609
60694
  // dist/builtin/workflows/src/shared/workflow-artifact-env.ts
@@ -60618,17 +60703,17 @@ function workflowArtifactRoot() {
60618
60703
  const override = getEnvValue2(ENV_WORKFLOW_ARTIFACT_DIR);
60619
60704
  if (override !== undefined && override.length > 0)
60620
60705
  return override;
60621
- return join4(dirname3(getAgentDir4()), "workflows");
60706
+ return join3(dirname2(getAgentDir4()), "workflows");
60622
60707
  }
60623
60708
  function workflowArtifactRunsRoot() {
60624
- return join4(workflowArtifactRoot(), "runs");
60709
+ return join3(workflowArtifactRoot(), "runs");
60625
60710
  }
60626
60711
  function safeRunId(runId) {
60627
60712
  const safe = runId.replace(/[^A-Za-z0-9._-]/g, "_");
60628
60713
  return safe.length > 0 ? safe : "run";
60629
60714
  }
60630
60715
  function workflowArtifactRunPath(runId) {
60631
- return join4(workflowArtifactRunsRoot(), safeRunId(runId));
60716
+ return join3(workflowArtifactRunsRoot(), safeRunId(runId));
60632
60717
  }
60633
60718
  function normalizeSerializedPath(value2) {
60634
60719
  return value2.replaceAll("\\", "/").replace(/\/{2,}/g, "/");
@@ -60764,7 +60849,7 @@ async function pruneWorkflowArtifactRuns(root = workflowArtifactRunsRoot(), now
60764
60849
  for (const entry of entries) {
60765
60850
  if (!entry.isDirectory())
60766
60851
  continue;
60767
- const entryPath = join4(root, entry.name);
60852
+ const entryPath = join3(root, entry.name);
60768
60853
  let metadata;
60769
60854
  try {
60770
60855
  metadata = await stat(entryPath);
@@ -60818,8 +60903,8 @@ async function ensureWorkflowArtifactRunDirectory(runId) {
60818
60903
  return directory;
60819
60904
  }
60820
60905
  function workflowArtifactDirectoryPath(runId) {
60821
- const effectiveRunId = runId ?? randomUUID4();
60822
- return join4(workflowArtifactRunPath(effectiveRunId), `artifact-${randomUUID4()}`);
60906
+ const effectiveRunId = runId ?? randomUUID5();
60907
+ return join3(workflowArtifactRunPath(effectiveRunId), `artifact-${randomUUID5()}`);
60823
60908
  }
60824
60909
  async function ensureWorkflowArtifactDirectory(directory) {
60825
60910
  await pruneArtifactRootIfDue(workflowArtifactRunsRoot(), Date.now());
@@ -61942,7 +62027,7 @@ function cleanupWorktrees(setup) {
61942
62027
  }
61943
62028
  // dist/builtin/workflows/src/runs/shared/worktree-cwd.ts
61944
62029
  import { lstatSync as lstatSync4, realpathSync as realpathSync5 } from "node:fs";
61945
- import { dirname as dirname8, isAbsolute as isAbsolute7, relative as relative4, resolve as resolve8, sep as sep5 } from "node:path";
62030
+ import { dirname as dirname7, isAbsolute as isAbsolute7, relative as relative4, resolve as resolve7, sep as sep5 } from "node:path";
61946
62031
  function relativePathWithin(root, candidate) {
61947
62032
  const path = relative4(root, candidate);
61948
62033
  return path === ".." || path.startsWith(`..${sep5}`) || isAbsolute7(path) ? undefined : path;
@@ -61961,14 +62046,14 @@ function resolveWorktreeStageCwd(cwd, setup) {
61961
62046
  if (cwd === undefined || cwd.length === 0)
61962
62047
  return;
61963
62048
  const absoluteInput = isAbsolute7(cwd);
61964
- const candidate = absoluteInput ? cwd : resolve8(setup.cwd, cwd);
62049
+ const candidate = absoluteInput ? cwd : resolve7(setup.cwd, cwd);
61965
62050
  if (!absoluteInput && relativePathWithin(setup.worktreeRoot, candidate) === undefined) {
61966
62051
  throw new Error(`atomic-workflows: relative cwd ${cwd} escapes gitWorktreeDir ${setup.worktreeRoot}; choose a cwd inside the worktree.`);
61967
62052
  }
61968
62053
  const candidateRealPath = existingRealPath(candidate, "cwd");
61969
62054
  const worktreeRelative = relativePathWithin(worktreeRoot, candidateRealPath);
61970
62055
  if (worktreeRelative !== undefined)
61971
- return resolve8(setup.worktreeRoot, worktreeRelative);
62056
+ return resolve7(setup.worktreeRoot, worktreeRelative);
61972
62057
  if (!isAbsolute7(cwd)) {
61973
62058
  throw new Error(`atomic-workflows: relative cwd ${cwd} escapes gitWorktreeDir ${setup.worktreeRoot}; choose a path that remains inside the selected worktree.`);
61974
62059
  }
@@ -61979,7 +62064,7 @@ function resolveWorktreeStageCwd(cwd, setup) {
61979
62064
  if (repositoryRelative === undefined) {
61980
62065
  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.`);
61981
62066
  }
61982
- const mappedCwd = resolve8(setup.worktreeRoot, repositoryRelative);
62067
+ const mappedCwd = resolve7(setup.worktreeRoot, repositoryRelative);
61983
62068
  const mappedRealPath = existingRealPath(mappedCwd, "remapped worktree cwd");
61984
62069
  if (relativePathWithin(worktreeRoot, mappedRealPath) === undefined) {
61985
62070
  throw new Error(`atomic-workflows: cwd ${cwd} remaps through a path that resolves outside gitWorktreeDir ${setup.worktreeRoot}; remove the escaping symlink or omit cwd.`);
@@ -61989,7 +62074,7 @@ function resolveWorktreeStageCwd(cwd, setup) {
61989
62074
 
61990
62075
  // dist/builtin/workflows/src/runs/foreground/executor-task-prompts.ts
61991
62076
  import { existsSync as existsSync4 } from "node:fs";
61992
- import { isAbsolute as isAbsolute8, resolve as resolve9 } from "node:path";
62077
+ import { isAbsolute as isAbsolute8, resolve as resolve8 } from "node:path";
61993
62078
  function normalizeTaskContexts(previous) {
61994
62079
  if (previous === undefined)
61995
62080
  return [];
@@ -62042,7 +62127,7 @@ function taskPrevious(options) {
62042
62127
  function resolveWorkflowPath(filePath, baseDir) {
62043
62128
  if (isAbsolute8(filePath))
62044
62129
  return filePath;
62045
- return resolve9(baseDir ?? process.cwd(), filePath);
62130
+ return resolve8(baseDir ?? process.cwd(), filePath);
62046
62131
  }
62047
62132
  function taskBaseDir(options) {
62048
62133
  if (typeof options.chainDir === "string" && options.chainDir.trim().length > 0) {
@@ -62342,10 +62427,10 @@ function workflowInvocationMetadata(inputDefaults, workflowInvocationCwd, cache,
62342
62427
  function resolvedTaskCwd(cwd, workflowInvocationCwd) {
62343
62428
  if (cwd === undefined)
62344
62429
  return;
62345
- return isAbsolute9(cwd) ? cwd : resolve10(workflowInvocationCwd, cwd);
62430
+ return isAbsolute9(cwd) ? cwd : resolve9(workflowInvocationCwd, cwd);
62346
62431
  }
62347
62432
  function taskWorktreeOutputsRoot(runId) {
62348
- return join11(workflowArtifactRunPath(runId), "task-outputs");
62433
+ return join10(workflowArtifactRunPath(runId), "task-outputs");
62349
62434
  }
62350
62435
  function prepareTaskWorktrees(tasks, options, runId, scope, workflowInvocationCwd = process.cwd(), symlinkDirectories) {
62351
62436
  if (options.worktree !== true && !tasks.some((task) => task.worktree === true)) {
@@ -62355,7 +62440,7 @@ function prepareTaskWorktrees(tasks, options, runId, scope, workflowInvocationCw
62355
62440
  throw new Error("atomic-workflows: worktree and gitWorktreeDir are mutually exclusive; use gitWorktreeDir for a reusable worktree or worktree:true for temporary isolated worktrees.");
62356
62441
  }
62357
62442
  const explicitCwd = tasks.find((task) => typeof task.cwd === "string")?.cwd;
62358
- const sharedCwd = explicitCwd === undefined ? workflowInvocationCwd : isAbsolute9(explicitCwd) ? explicitCwd : resolve10(workflowInvocationCwd, explicitCwd);
62443
+ const sharedCwd = explicitCwd === undefined ? workflowInvocationCwd : isAbsolute9(explicitCwd) ? explicitCwd : resolve9(workflowInvocationCwd, explicitCwd);
62359
62444
  const conflict = findWorktreeTaskCwdConflict(tasks.map((task) => ({ agent: task.name, cwd: resolvedTaskCwd(task.cwd, workflowInvocationCwd) })), sharedCwd);
62360
62445
  if (conflict !== undefined)
62361
62446
  throw new Error(formatWorktreeTaskCwdConflict(conflict, sharedCwd));
@@ -62370,9 +62455,9 @@ function prepareTaskWorktrees(tasks, options, runId, scope, workflowInvocationCw
62370
62455
  tasks: tasks.map((task, index) => ({ ...task, cwd: setup.worktrees[index].agentCwd })),
62371
62456
  setup,
62372
62457
  agents,
62373
- diffsDir: join11(setup.cwd, CONFIG_DIR_NAME2, "workflows", "worktree-diffs", runId, scope),
62458
+ diffsDir: join10(setup.cwd, CONFIG_DIR_NAME2, "workflows", "worktree-diffs", runId, scope),
62374
62459
  outputIsolations: tasks.map((_, index) => ({
62375
- baseDir: join11(trustedRoot, runId, scope, String(index)),
62460
+ baseDir: join10(trustedRoot, runId, scope, String(index)),
62376
62461
  trustedRoot
62377
62462
  }))
62378
62463
  };
@@ -63655,8 +63740,8 @@ function createRunLimiter(defaultConcurrency) {
63655
63740
  }
63656
63741
 
63657
63742
  // dist/builtin/workflows/src/shared/possible-stages.ts
63658
- import { existsSync as existsSync5, readFileSync as readFileSync3 } from "node:fs";
63659
- import { dirname as dirname9, join as join12, resolve as resolve11 } from "node:path";
63743
+ import { existsSync as existsSync5, readFileSync as readFileSync2 } from "node:fs";
63744
+ import { dirname as dirname8, join as join11, resolve as resolve10 } from "node:path";
63660
63745
  import { fileURLToPath as fileURLToPath3 } from "node:url";
63661
63746
  var DEFAULT_MAX_DEPTH = 4;
63662
63747
  var BUILTIN_BARREL_SPECIFIERS = new Set(["@bastani/atomic/workflows/builtin"]);
@@ -63665,7 +63750,7 @@ var TRACKED_NODE_METHODS = new Set(["stage", "task", "chain", "parallel", "workf
63665
63750
  function scanPossibleStagesFromSource(entrySourcePath, options = {}) {
63666
63751
  const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
63667
63752
  const scanner = new PossibleStagesScanner(maxDepth);
63668
- scanner.scanSubtree(resolve11(entrySourcePath), "", 0, [resolve11(entrySourcePath)]);
63753
+ scanner.scanSubtree(resolve10(entrySourcePath), "", 0, [resolve10(entrySourcePath)]);
63669
63754
  return {
63670
63755
  hasTrackedNodes: scanner.hasTrackedNodes,
63671
63756
  stages: [...scanner.stages].sort(),
@@ -63676,7 +63761,7 @@ function resolveBuiltinDefinitionSource(name) {
63676
63761
  const builtinDir = fileURLToPath3(new URL("../../builtin/", import.meta.url));
63677
63762
  for (const stem of [name, kebabCase(name)]) {
63678
63763
  for (const extension of [".ts", ".js"]) {
63679
- const candidate = join12(builtinDir, `${stem}${extension}`);
63764
+ const candidate = join11(builtinDir, `${stem}${extension}`);
63680
63765
  if (isFileSync(candidate))
63681
63766
  return candidate;
63682
63767
  }
@@ -63915,7 +64000,7 @@ function templateToPattern(raw) {
63915
64000
  function buildFileUnit(path, warnings) {
63916
64001
  let source;
63917
64002
  try {
63918
- source = readFileSync3(path, "utf-8");
64003
+ source = readFileSync2(path, "utf-8");
63919
64004
  } catch (error) {
63920
64005
  warnings.push(`possible-stages: failed to read ${path}: ${errorMessage2(error)}`);
63921
64006
  return;
@@ -65119,16 +65204,16 @@ function resolveRelativeSpecifier(specifier, importingFile) {
65119
65204
  return;
65120
65205
  const candidates = [];
65121
65206
  if (specifier.endsWith(".js")) {
65122
- candidates.push(join12(dirname9(importingFile), `${specifier.slice(0, -3)}.ts`));
65207
+ candidates.push(join11(dirname8(importingFile), `${specifier.slice(0, -3)}.ts`));
65123
65208
  }
65124
- candidates.push(join12(dirname9(importingFile), specifier), join12(dirname9(importingFile), `${specifier}.ts`), join12(dirname9(importingFile), `${specifier}.js`), join12(dirname9(importingFile), specifier, "index.ts"), join12(dirname9(importingFile), specifier, "index.js"));
65209
+ candidates.push(join11(dirname8(importingFile), specifier), join11(dirname8(importingFile), `${specifier}.ts`), join11(dirname8(importingFile), `${specifier}.js`), join11(dirname8(importingFile), specifier, "index.ts"), join11(dirname8(importingFile), specifier, "index.js"));
65125
65210
  return candidates.find((candidate) => isFileSync(candidate));
65126
65211
  }
65127
65212
  function isFileSync(path) {
65128
65213
  if (!existsSync5(path))
65129
65214
  return false;
65130
65215
  try {
65131
- readFileSync3(path, { flag: "r" });
65216
+ readFileSync2(path, { flag: "r" });
65132
65217
  return true;
65133
65218
  } catch {
65134
65219
  return false;
@@ -65386,10 +65471,10 @@ function createWorkflowExitManager(input) {
65386
65471
  };
65387
65472
  }
65388
65473
  // dist/builtin/workflows/src/engine/primitives/parallel.ts
65389
- import { randomUUID as randomUUID6 } from "node:crypto";
65474
+ import { randomUUID as randomUUID7 } from "node:crypto";
65390
65475
 
65391
65476
  // dist/builtin/workflows/src/shared/intercom-group.ts
65392
- import { randomUUID as randomUUID5 } from "node:crypto";
65477
+ import { randomUUID as randomUUID6 } from "node:crypto";
65393
65478
  var DEFAULT_INTERCOM_GROUP = "default";
65394
65479
  function workflowInvocationIntercomGroup(rootRunId) {
65395
65480
  return `workflow:${rootRunId}`;
@@ -65412,7 +65497,7 @@ function resolveStageGroup(stageOptions, workflowGroup) {
65412
65497
  const group = stageOptions.group;
65413
65498
  if (group === undefined)
65414
65499
  return workflowGroup;
65415
- const authored = group === true ? randomUUID5() : group.trim();
65500
+ const authored = group === true ? randomUUID6() : group.trim();
65416
65501
  if (authored.length === 0)
65417
65502
  return;
65418
65503
  if (workflowGroup === undefined || authored === DEFAULT_INTERCOM_GROUP)
@@ -65724,7 +65809,7 @@ function createParallelPrimitive(input) {
65724
65809
  const normalizedOptions = normalizeGroup(options);
65725
65810
  const normalizedSteps = steps.map(normalizeGroup);
65726
65811
  const needsAutoGroup = normalizedOptions.group === true || normalizedSteps.some((step) => step.group === true);
65727
- const autoGroup = needsAutoGroup ? randomUUID6() : undefined;
65812
+ const autoGroup = needsAutoGroup ? randomUUID7() : undefined;
65728
65813
  const resolveAutoGroup = (value2) => value2.group === true && autoGroup ? { ...value2, group: autoGroup } : value2;
65729
65814
  const resolvedOptions = resolveAutoGroup(normalizedOptions);
65730
65815
  const resolvedSteps = normalizedSteps.map(resolveAutoGroup);
@@ -65792,7 +65877,7 @@ function createTaskPrimitive(runtime) {
65792
65877
  }
65793
65878
  });
65794
65879
  const stage = stageHandle.context;
65795
- const promptText = resolvedTaskOptions.resumeFromSessionFile !== undefined ? RESUME_CONTINUATION_PROMPT : applyTaskContext(`${taskReadInstruction(resolvedTaskOptions)}${taskPrompt(resolvedTaskOptions)}`, taskPrevious(resolvedTaskOptions));
65880
+ const promptText = resolvedTaskOptions.resumeFromSessionId !== undefined ? RESUME_CONTINUATION_PROMPT : applyTaskContext(`${taskReadInstruction(resolvedTaskOptions)}${taskPrompt(resolvedTaskOptions)}`, taskPrevious(resolvedTaskOptions));
65796
65881
  const rawOutput = await stage.prompt(promptText, taskPromptOptions(resolvedTaskOptions));
65797
65882
  const structured = typeof rawOutput === "string" ? undefined : rawOutput;
65798
65883
  const text = truncateTaskOutput(structuredTaskOutputText(rawOutput), resolvedTaskOptions.maxOutput);
@@ -65882,6 +65967,7 @@ function wrapUiWithDurable(base, deps) {
65882
65967
  response,
65883
65968
  completedAt: Date.now()
65884
65969
  };
65970
+ await deps.beforeCheckpoint?.();
65885
65971
  await recordCheckpointDurably(deps.backend, checkpoint);
65886
65972
  };
65887
65973
  const cached = (identity) => deps.backend.getUiResponse(deps.workflowId, identity.hash);
@@ -66203,7 +66289,7 @@ async function finalizeDurableTerminalStatus(input) {
66203
66289
  ...input.runSnapshot.failureDisposition !== undefined ? { failureDisposition: input.runSnapshot.failureDisposition } : {},
66204
66290
  ...input.runSnapshot.failedToolNodeId !== undefined ? { failedToolNodeId: input.runSnapshot.failedToolNodeId } : {}
66205
66291
  } : undefined;
66206
- await input.durableBackend.setWorkflowStatus(input.runId, durableStatus, undefined, input.runSnapshot.resumable, failure);
66292
+ await input.durableBackend.commitWorkflowStatus(input.runId, durableStatus, undefined, input.runSnapshot.resumable, failure);
66207
66293
  }
66208
66294
  }
66209
66295
  function toDurableStatus(status) {
@@ -66308,7 +66394,7 @@ async function recordWorkflowHeartbeatAnchor(backend, record) {
66308
66394
  output: { anchorAt: record.anchorAt, intervalMinutes: record.intervalMinutes },
66309
66395
  completedAt: record.now
66310
66396
  };
66311
- const stored = await backend.recordAdditiveCheckpointBestEffort(checkpoint);
66397
+ const stored = await backend.commitAdditiveCheckpointBestEffort(checkpoint);
66312
66398
  if (!stored)
66313
66399
  return false;
66314
66400
  return readWorkflowHeartbeatAnchor(backend, record.runId) !== undefined;
@@ -66392,6 +66478,7 @@ function createDurableStageDeps(input) {
66392
66478
  backend: input.backend,
66393
66479
  nextCheckpointId: input.nextCheckpointId,
66394
66480
  nextReplayKey: input.nextReplayKey,
66481
+ beforeCheckpoint: input.beforeCheckpoint,
66395
66482
  replayKeyForCompletedStage: (stage) => input.completedReplayKeys.get(stage.id),
66396
66483
  runTopology: durableRunTopology(input.run),
66397
66484
  sourceOrderForStage: (stage) => {
@@ -66442,7 +66529,8 @@ function createDurableStageTopologyResolver(backend, workflowId) {
66442
66529
  async function recordDurableActiveStage(deps, stage) {
66443
66530
  if (stage.replayKey === undefined || stage.status === "completed" || stage.status === "failed" || stage.status === "skipped")
66444
66531
  return false;
66445
- await deps.backend.recordCheckpointAsync({
66532
+ await deps.beforeCheckpoint?.();
66533
+ await deps.backend.commitCheckpoint({
66446
66534
  kind: "stage",
66447
66535
  workflowId: deps.workflowId,
66448
66536
  checkpointId: `stage-active-meta:${durableHash({ replayKey: stage.replayKey, stageId: stage.id })}`,
@@ -66475,7 +66563,7 @@ function createDurableCachedStageRecorder(input) {
66475
66563
  input.run.stages.sort((left, right) => (replaySourceOrders.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (replaySourceOrders.get(right.id) ?? Number.MAX_SAFE_INTEGER));
66476
66564
  }
66477
66565
  const stage = input.store.runs().find((run) => run.id === input.run.id)?.stages.find((candidate) => candidate.replayKey === replayKey);
66478
- const persistence = stage === undefined ? undefined : input.backend.recordCheckpoint({
66566
+ const persistence = stage === undefined ? undefined : input.backend.commitCheckpoint({
66479
66567
  kind: "stage",
66480
66568
  workflowId: input.run.id,
66481
66569
  checkpointId: `stage-replay-meta:${durableHash({ replayKey, stageId: stage.id, parentIds: stage.parentIds })}`,
@@ -66767,6 +66855,9 @@ function createAdmittedToolExecutionTracker(options = {}) {
66767
66855
  await drainRecordedFailures();
66768
66856
  };
66769
66857
  return {
66858
+ get closed() {
66859
+ return state === "CLOSED" || options.signal?.aborted === true;
66860
+ },
66770
66861
  track(execution) {
66771
66862
  if (state === "CLOSED" || options.signal?.aborted) {
66772
66863
  const error = new Error("atomic-workflows: ctx.tool admission is closed for this run");
@@ -66942,6 +67033,13 @@ function createTrackedToolPrimitive(input) {
66942
67033
  });
66943
67034
  const lifecycle = createToolNodeLifecycle(input);
66944
67035
  const budgetBoundary = input.budget.enabled ? () => input.budget.stopAtBoundaryAsync(input.run.stages.at(-1)?.name) : undefined;
67036
+ const assertToolAdmissionOpen = () => {
67037
+ const quit = input.toolAdmission.quitReason;
67038
+ if (quit !== undefined) {
67039
+ observedQuit ??= quit;
67040
+ throw quit;
67041
+ }
67042
+ };
66945
67043
  const tool = createToolPrimitive({
66946
67044
  workflowId: input.workflowId,
66947
67045
  ...input.checkpointSourceWorkflowId === undefined ? {} : { checkpointSourceWorkflowId: input.checkpointSourceWorkflowId },
@@ -66975,7 +67073,16 @@ function createTrackedToolPrimitive(input) {
66975
67073
  observedQuit ??= admission.error;
66976
67074
  return admission;
66977
67075
  },
66978
- ...budgetBoundary !== undefined ? { beforeToolCall: budgetBoundary, afterToolCall: budgetBoundary } : {},
67076
+ beforeToolCall: () => {
67077
+ const afterDrain = () => {
67078
+ const budget = budgetBoundary?.();
67079
+ return budget === undefined ? assertToolAdmissionOpen() : budget.then(assertToolAdmissionOpen);
67080
+ };
67081
+ const pending = input.beforeToolCall?.();
67082
+ return pending === undefined ? afterDrain() : pending.then(afterDrain);
67083
+ },
67084
+ beforeCheckpoint: input.beforeCheckpoint,
67085
+ ...budgetBoundary !== undefined ? { afterToolCall: budgetBoundary } : {},
66979
67086
  ...lifecycle
66980
67087
  });
66981
67088
  const abandonInFlightAsCancelled = (reason) => {
@@ -67863,12 +67970,12 @@ class StageToolExecutionBuffer {
67863
67970
  function createStageControlHandle(runtime) {
67864
67971
  const messagePreparation = () => {
67865
67972
  const meta = runtime.innerCtx.__sessionMeta();
67866
- if (meta.sessionId !== undefined || meta.sessionFile !== undefined) {
67973
+ if (meta.sessionId !== undefined) {
67867
67974
  return { beforePreparation: runtime.throwIfStageMutationBlocked };
67868
67975
  }
67869
- if (runtime.stageSnapshot.sessionFile !== undefined) {
67976
+ if (runtime.stageSnapshot.sessionId !== undefined) {
67870
67977
  return {
67871
- sessionFile: runtime.stageSnapshot.sessionFile,
67978
+ sessionId: runtime.stageSnapshot.sessionId,
67872
67979
  beforePreparation: runtime.throwIfStageMutationBlocked
67873
67980
  };
67874
67981
  }
@@ -67878,10 +67985,10 @@ function createStageControlHandle(runtime) {
67878
67985
  return { beforePreparation: runtime.throwIfStageMutationBlocked };
67879
67986
  };
67880
67987
  const ensureMessagingSession = async () => {
67881
- const sessionFile = messagePreparation().sessionFile;
67882
- if (sessionFile === undefined)
67988
+ const sessionId = messagePreparation().sessionId;
67989
+ if (sessionId === undefined)
67883
67990
  return;
67884
- await runtime.innerCtx.__ensureSessionFromFile(sessionFile);
67991
+ await runtime.innerCtx.__ensureSessionFromId(sessionId);
67885
67992
  await runtime.captureStageSessionMeta({ awaitDurable: true });
67886
67993
  };
67887
67994
  const toolExecutions = new StageToolExecutionBuffer;
@@ -67897,6 +68004,9 @@ function createStageControlHandle(runtime) {
67897
68004
  get status() {
67898
68005
  return runtime.stageSnapshot.status;
67899
68006
  },
68007
+ get sessionStore() {
68008
+ return runtime.innerCtx.__agentSession()?.sessionManager.getSessionStore();
68009
+ },
67900
68010
  get sessionId() {
67901
68011
  return runtime.innerCtx.__sessionMeta().sessionId ?? runtime.stageSnapshot.sessionId;
67902
68012
  },
@@ -68185,7 +68295,7 @@ function createReplayStageContext(input) {
68185
68295
  __getLastAssistantText: () => replayResult,
68186
68296
  getLastAssistantText: () => replayResult,
68187
68297
  __ensureSession: async () => {},
68188
- __ensureSessionFromFile: async () => {},
68298
+ __ensureSessionFromId: async () => {},
68189
68299
  __sealGeneration: () => {},
68190
68300
  __closeGeneration: async () => {},
68191
68301
  __sessionMeta: () => ({ sessionId: replaySource.sessionId, sessionFile: replaySource.sessionFile }),
@@ -68208,7 +68318,7 @@ function createReplayStageContext(input) {
68208
68318
  }
68209
68319
 
68210
68320
  // dist/builtin/workflows/src/shared/pending-stage-route-capability.ts
68211
- import { randomUUID as randomUUID7 } from "node:crypto";
68321
+ import { randomUUID as randomUUID8 } from "node:crypto";
68212
68322
  var routeCapabilitiesKey = Symbol.for("atomic-workflows/pending-stage-route-capabilities@1");
68213
68323
  var processState = globalThis;
68214
68324
  var routeCapabilities = processState[routeCapabilitiesKey] ?? new WeakMap;
@@ -68221,7 +68331,7 @@ function workflowPendingStageRouteCapability(store, runId) {
68221
68331
  }
68222
68332
  let capability = capabilities.get(runId);
68223
68333
  if (capability === undefined) {
68224
- capability = randomUUID7();
68334
+ capability = randomUUID8();
68225
68335
  capabilities.set(runId, capability);
68226
68336
  }
68227
68337
  return capability;
@@ -69192,7 +69302,7 @@ function assistantMessage(text) {
69192
69302
  }
69193
69303
 
69194
69304
  // dist/builtin/workflows/src/runs/foreground/stage-runner-options.ts
69195
- import { SessionManager } from "@bastani/atomic";
69305
+ import { SessionManager as SessionManager2 } from "@bastani/atomic";
69196
69306
  function workflowSessionOptions(meta) {
69197
69307
  return {
69198
69308
  internal: true,
@@ -69217,7 +69327,7 @@ async function stripWorkflowOnlyOptions(options, defaultSessionDir, meta, pendin
69217
69327
  if (!options) {
69218
69328
  return defaultSessionDir === undefined ? { orchestrationContext } : {
69219
69329
  orchestrationContext,
69220
- sessionManager: await SessionManager.create(process.cwd(), defaultSessionDir, classification)
69330
+ sessionManager: await SessionManager2.create(process.cwd(), defaultSessionDir, classification)
69221
69331
  };
69222
69332
  }
69223
69333
  const {
@@ -69229,8 +69339,9 @@ async function stripWorkflowOnlyOptions(options, defaultSessionDir, meta, pendin
69229
69339
  inheritedModelConstraints: _inheritedModelConstraints,
69230
69340
  routerSelection: _routerSelection,
69231
69341
  context,
69232
- forkFromSessionFile,
69233
- resumeFromSessionFile,
69342
+ forkFromSessionId,
69343
+ resumeFromSessionId,
69344
+ sessionStore,
69234
69345
  durableReplayKey: _durableReplayKey,
69235
69346
  durableAccumulatedDurationMs: _durableAccumulatedDurationMs,
69236
69347
  durableStageId: _durableStageId,
@@ -69242,15 +69353,16 @@ async function stripWorkflowOnlyOptions(options, defaultSessionDir, meta, pendin
69242
69353
  group: _group,
69243
69354
  ...sessionOptions
69244
69355
  } = options;
69245
- if (sessionOptions.sessionManager === undefined) {
69246
- const cwd = sessionOptions.cwd ?? process.cwd();
69247
- const effectiveSessionDir = sessionDir ?? defaultSessionDir;
69248
- if (resumeFromSessionFile !== undefined) {
69249
- sessionOptions.sessionManager = await SessionManager.open(resumeFromSessionFile, effectiveSessionDir, cwd);
69250
- } else if (context === "fork" && forkFromSessionFile !== undefined) {
69251
- sessionOptions.sessionManager = await SessionManager.forkFrom(forkFromSessionFile, cwd, effectiveSessionDir, classification);
69252
- } else if (effectiveSessionDir !== undefined) {
69253
- sessionOptions.sessionManager = await SessionManager.create(cwd, effectiveSessionDir, classification);
69356
+ const cwd = sessionOptions.cwd ?? process.cwd();
69357
+ if (resumeFromSessionId !== undefined) {
69358
+ sessionOptions.sessionManager = await SessionManager2.open(await stageSessionStore(options, defaultSessionDir), resumeFromSessionId, cwd);
69359
+ } else if (context === "fork" && forkFromSessionId !== undefined) {
69360
+ sessionOptions.sessionManager = await forkStageSession(await stageSessionStore(options, defaultSessionDir), forkFromSessionId, cwd, classification);
69361
+ } else if (sessionOptions.sessionManager === undefined) {
69362
+ if (sessionStore !== undefined) {
69363
+ sessionOptions.sessionManager = await SessionManager2.create(sessionStore, cwd, classification);
69364
+ } else if ((sessionDir ?? defaultSessionDir) !== undefined) {
69365
+ sessionOptions.sessionManager = await SessionManager2.create(cwd, sessionDir ?? defaultSessionDir, classification);
69254
69366
  }
69255
69367
  }
69256
69368
  return {
@@ -69660,7 +69772,6 @@ async function sendStageUserMessage(activeSession, content, options, beforeDeliv
69660
69772
  }
69661
69773
 
69662
69774
  // dist/builtin/workflows/src/runs/foreground/stage-runner-session-options.ts
69663
- import { SessionManager as SessionManager2 } from "@bastani/atomic";
69664
69775
  var adapterDefaultCwds = new WeakMap;
69665
69776
  function setAgentSessionAdapterDefaultCwd(adapter, cwd) {
69666
69777
  adapterDefaultCwds.set(adapter, cwd);
@@ -69683,11 +69794,10 @@ async function buildStageSessionOptions(input) {
69683
69794
  }
69684
69795
  if (input.restoreSavedModel === true)
69685
69796
  delete options.model;
69686
- if (input.reattachSessionFile !== undefined && options.sessionManager === undefined) {
69687
- const cwd = options.cwd ?? process.cwd();
69688
- options.sessionManager = await SessionManager2.open(input.reattachSessionFile, options.sessionDir, cwd);
69797
+ if (input.reattachSessionId !== undefined) {
69798
+ options.resumeFromSessionId = input.reattachSessionId;
69689
69799
  options.context = undefined;
69690
- options.forkFromSessionFile = undefined;
69800
+ options.forkFromSessionId = undefined;
69691
69801
  }
69692
69802
  if (input.sharedModelRuntime !== undefined && options.modelRuntime === undefined) {
69693
69803
  options.modelRuntime = input.sharedModelRuntime;
@@ -69938,7 +70048,7 @@ class StageSessionController {
69938
70048
  sessionPromise;
69939
70049
  sessionShutdownPromise;
69940
70050
  bindingCleanupFailure;
69941
- reattachSessionFile;
70051
+ reattachSessionId;
69942
70052
  lastPromptStartIndex;
69943
70053
  attemptUsageStartIndex;
69944
70054
  discardedAttemptUsage = {
@@ -70194,9 +70304,9 @@ class StageSessionController {
70194
70304
  const ready = waitForStageStartup(this.sessionPromise, this.startupWait.signal);
70195
70305
  return this.modelRoute ? this.checkedSession(await ready) : ready;
70196
70306
  }
70197
- async ensureSessionFromFile(sessionFile, consumer = "prompt") {
70307
+ async ensureSessionFromId(sessionId, consumer = "prompt") {
70198
70308
  if (!this.sessionShutdownPromise && !this.sessionPromise && !this.session)
70199
- this.reattachSessionFile = sessionFile;
70309
+ this.reattachSessionId = sessionId;
70200
70310
  const session = await this.ensureSession(consumer);
70201
70311
  await session.closeWorkflowStageGeneration?.();
70202
70312
  return session;
@@ -70209,12 +70319,12 @@ class StageSessionController {
70209
70319
  return pausedDelivery;
70210
70320
  }
70211
70321
  preparation?.beforePreparation?.();
70212
- const sessionFile = preparation?.sessionFile;
70322
+ const sessionId = preparation?.sessionId;
70213
70323
  const deliver = async (activity) => {
70214
70324
  if (this.effectiveStageOptions?.model === "auto")
70215
70325
  await this.preparePrompt(typeof content === "string" ? content : content.filter((part) => part.type === "text").map((part) => part.text).join(`
70216
70326
  `));
70217
- const activeSession = sessionFile === undefined ? await this.ensureSession("prompt") : await this.ensureSessionFromFile(sessionFile, "prompt");
70327
+ const activeSession = sessionId === undefined ? await this.ensureSession("prompt") : await this.ensureSessionFromId(sessionId, "prompt");
70218
70328
  const pausedDelivery = this.pauseControl.deferRunnerOwnedDelivery(() => sendStageUserMessage(activeSession, content, options, beforeDelivery, release, this.messageAdmission, activity));
70219
70329
  if (pausedDelivery !== undefined) {
70220
70330
  release();
@@ -70222,7 +70332,7 @@ class StageSessionController {
70222
70332
  }
70223
70333
  return sendStageUserMessage(activeSession, content, options, beforeDelivery, release, this.messageAdmission, activity);
70224
70334
  };
70225
- if (this.session === undefined || sessionFile !== undefined)
70335
+ if (this.session === undefined || sessionId !== undefined)
70226
70336
  return this.deliveryActivity.runWithLease(() => deliver());
70227
70337
  return deliver(this.deliveryActivity);
70228
70338
  });
@@ -70762,7 +70872,7 @@ class StageSessionController {
70762
70872
  if (first === undefined) {
70763
70873
  return this.createSessionObservingPause(undefined, consumer).catch((error) => this.createInitialSessionWithRetry(undefined, consumer, { error }));
70764
70874
  }
70765
- if (this.reattachSessionFile !== undefined) {
70875
+ if (this.reattachSessionId !== undefined) {
70766
70876
  const resumed = await this.createSession(undefined, consumer, { restoreSavedModel: true });
70767
70877
  const restoredId = workflowModelId(resumed.model);
70768
70878
  const exactRestoredIndex = restoredId === undefined ? -1 : candidates.findIndex((entry) => entry.id === restoredId && entry.reasoningLevel === resumed.thinkingLevel);
@@ -70985,7 +71095,7 @@ class StageSessionController {
70985
71095
  ownsFallbackChain: this.hasExplicitModelFallbackConfig,
70986
71096
  scopedModels,
70987
71097
  restoreSavedModel: resumeOptions?.restoreSavedModel,
70988
- reattachSessionFile: this.reattachSessionFile,
71098
+ reattachSessionId: this.reattachSessionId,
70989
71099
  sharedModelRuntime: this.sharedModelRuntime,
70990
71100
  defaultCwd: this.opts.defaultCwd
70991
71101
  });
@@ -71334,7 +71444,7 @@ class StageSessionController {
71334
71444
  // dist/builtin/workflows/src/runs/foreground/stage-runner-output.ts
71335
71445
  import { createHash as createHash3 } from "node:crypto";
71336
71446
  import { mkdir as mkdir2, writeFile } from "node:fs/promises";
71337
- import { basename as basename4, dirname as dirname10, isAbsolute as isAbsolute10, join as join13, resolve as resolve12 } from "node:path";
71447
+ import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute10, join as join12, resolve as resolve11 } from "node:path";
71338
71448
  var DEFAULT_MAX_OUTPUT_BYTES = 200 * 1024;
71339
71449
  var DEFAULT_MAX_OUTPUT_LINES = 5000;
71340
71450
  function normalizeMaxOutput2(maxOutput) {
@@ -71399,7 +71509,7 @@ function formatByteSize(bytes) {
71399
71509
  }
71400
71510
  function transcriptPath(runId, outputPath) {
71401
71511
  const digest = createHash3("sha256").update(outputPath).digest("hex").slice(0, 16);
71402
- return join13(workflowArtifactRunPath(runId), "transcripts", `${digest}-${basename4(outputPath)}.transcript.md`);
71512
+ return join12(workflowArtifactRunPath(runId), "transcripts", `${digest}-${basename4(outputPath)}.transcript.md`);
71403
71513
  }
71404
71514
  function appendContent(lines, content) {
71405
71515
  if (typeof content === "string") {
@@ -71444,7 +71554,7 @@ function renderTranscript(messages, fallbackOutput) {
71444
71554
  `);
71445
71555
  }
71446
71556
  function savedOutputReference(outputPath, fullOutput, transcriptPathValue, transcriptText, transcriptAvailable, warning) {
71447
- const absolutePath = resolve12(outputPath);
71557
+ const absolutePath = resolve11(outputPath);
71448
71558
  const bytes = Buffer.byteLength(fullOutput, "utf8");
71449
71559
  const lines = countLines(fullOutput);
71450
71560
  const transcriptBytes = Buffer.byteLength(transcriptText, "utf8");
@@ -71459,8 +71569,8 @@ function resolveOutputPath(output, runtimeCwd, requestedCwd) {
71459
71569
  return;
71460
71570
  if (isAbsolute10(output))
71461
71571
  return output;
71462
- const baseCwd = requestedCwd === undefined ? runtimeCwd : isAbsolute10(requestedCwd) ? requestedCwd : resolve12(runtimeCwd, requestedCwd);
71463
- return resolve12(baseCwd, output);
71572
+ const baseCwd = requestedCwd === undefined ? runtimeCwd : isAbsolute10(requestedCwd) ? requestedCwd : resolve11(runtimeCwd, requestedCwd);
71573
+ return resolve11(baseCwd, output);
71464
71574
  }
71465
71575
  function degenerateWarning(fullOutput) {
71466
71576
  return fullOutput.trim().length === 0 ? "WARNING: the stage artifact is empty; search the companion transcript for this stage's work." : undefined;
@@ -71519,7 +71629,7 @@ async function finalizePromptOutput(fullOutput, outputOptions, runtimeCwd, runId
71519
71629
  const transcriptFile = transcriptPath(runId, outputPath);
71520
71630
  const transcript = renderTranscript(messages, fullOutput);
71521
71631
  try {
71522
- await mkdir2(dirname10(outputPath), { recursive: true });
71632
+ await mkdir2(dirname9(outputPath), { recursive: true });
71523
71633
  await writeFile(outputPath, fullOutput, "utf8");
71524
71634
  } catch (err) {
71525
71635
  return `${displayOutput}
@@ -71531,7 +71641,7 @@ ${err instanceof Error ? err.message : String(err)}`;
71531
71641
  let transcriptError;
71532
71642
  try {
71533
71643
  await ensureWorkflowArtifactRunDirectory(runId);
71534
- await mkdir2(dirname10(transcriptFile), { recursive: true });
71644
+ await mkdir2(dirname9(transcriptFile), { recursive: true });
71535
71645
  await writeFile(transcriptFile, transcript, "utf8");
71536
71646
  transcriptAvailable = true;
71537
71647
  } catch (err) {
@@ -71554,7 +71664,7 @@ function createStageContext2(opts) {
71554
71664
  const stageCwd = stageOptions?.cwd ?? stageOptions?.sessionManager?.getCwd() ?? agentSessionAdapterDefaultCwd(adapters.agentSession) ?? opts.defaultCwd ?? process.cwd();
71555
71665
  const structuredOutputCapture = stageOptions?.schema ? createStructuredOutputCapture() : undefined;
71556
71666
  const structuredOutputExecutionCapture = stageOptions?.schema ? {} : undefined;
71557
- const effectiveStageOptions = stageOptionsWithStructuredOutput(stageOptions, structuredOutputCapture, structuredOutputExecutionCapture);
71667
+ const effectiveStageOptions = stageOptionsWithStructuredOutput(adapters.sessionStore === undefined || stageOptions?.sessionStore !== undefined || stageOptions?.sessionDir !== undefined || stageOptions?.sessionManager !== undefined ? stageOptions : { ...stageOptions, sessionStore: adapters.sessionStore }, structuredOutputCapture, structuredOutputExecutionCapture);
71558
71668
  const meta = {
71559
71669
  runId,
71560
71670
  stageId,
@@ -71793,8 +71903,8 @@ ${nextPrompt}`;
71793
71903
  return;
71794
71904
  await controller.ensureSession();
71795
71905
  },
71796
- async __ensureSessionFromFile(sessionFile) {
71797
- await controller.ensureSessionFromFile(sessionFile);
71906
+ async __ensureSessionFromId(sessionId) {
71907
+ await controller.ensureSessionFromId(sessionId);
71798
71908
  },
71799
71909
  __sealGeneration() {
71800
71910
  controller.sealGeneration();
@@ -71863,11 +71973,11 @@ function createWorkflowStageFactory(input) {
71863
71973
  input.assertLiveWorkAllowed?.();
71864
71974
  options = stageOptionsWithGitWorktree(prepareLiveOptions?.() ?? options, input.workflowInvocationCwd, input.gitWorktreeSetupCache);
71865
71975
  }
71866
- const replayStageOptions = executeReplaySource?.sessionFile === undefined ? options : {
71976
+ const replayStageOptions = executeReplaySource?.sessionId === undefined ? options : {
71867
71977
  ...options ?? {},
71868
71978
  routerSelection: executeReplaySource.routerSelection,
71869
71979
  context: options?.context ?? "fork",
71870
- forkFromSessionFile: options?.forkFromSessionFile ?? executeReplaySource.sessionFile
71980
+ forkFromSessionId: options?.forkFromSessionId ?? executeReplaySource.sessionId
71871
71981
  };
71872
71982
  const intercomGroup = options?.durableIntercomGroup ?? resolveStageGroup(replayStageOptions, input.workflowIntercomGroup);
71873
71983
  const stageOptionsForContext = replayStageOptions?.group === undefined || intercomGroup === undefined ? replayStageOptions : { ...replayStageOptions, group: intercomGroup };
@@ -72042,8 +72152,8 @@ function createWorkflowStageFactory(input) {
72042
72152
  stageSnapshot.sessionId = meta.sessionId;
72043
72153
  if (meta.sessionFile !== undefined)
72044
72154
  stageSnapshot.sessionFile = meta.sessionFile;
72045
- if (meta.sessionId !== undefined || meta.sessionFile !== undefined)
72046
- input.activeStore.recordStageSession(input.runId, stageId, meta);
72155
+ if (meta.sessionId !== undefined)
72156
+ input.activeStore.recordStageSession(input.runId, stageId, { sessionId: meta.sessionId });
72047
72157
  const pending = input.opts.onStageSession?.(input.runId, stageSnapshot, checkpointOptions);
72048
72158
  if (checkpointOptions?.forceDurable === true || checkpointOptions?.awaitDurable === true) {
72049
72159
  await pending;
@@ -72575,11 +72685,45 @@ async function executeRun(def, resolvedInputs, opts) {
72575
72685
  return waitForRunRelease().then(() => whenRunning(call));
72576
72686
  if (ownController.signal.aborted)
72577
72687
  return Promise.reject(ownController.signal.reason);
72578
- return call();
72688
+ const persistence = drainCachedStagePersistence();
72689
+ return persistence === undefined ? call() : persistence.then(() => whenRunning(call));
72579
72690
  };
72580
72691
  ownController.signal.addEventListener("abort", () => scheduler.rejectReleaseBarriers(ownController.signal.reason ?? new Error("atomic-workflows: run aborted")), { once: true });
72581
72692
  const cachedStagePersistence = [];
72582
72693
  let cachedStageFailure;
72694
+ let cachedStageDrain;
72695
+ const drainCachedStagePersistence = () => {
72696
+ if (cachedStageDrain !== undefined)
72697
+ return cachedStageDrain;
72698
+ if (cachedStagePersistence.length === 0) {
72699
+ if (cachedStageFailure !== undefined)
72700
+ throw cachedStageFailure;
72701
+ return;
72702
+ }
72703
+ cachedStageDrain = (async () => {
72704
+ try {
72705
+ while (cachedStagePersistence.length > 0)
72706
+ await Promise.all(cachedStagePersistence.splice(0));
72707
+ if (cachedStageFailure !== undefined)
72708
+ throw cachedStageFailure;
72709
+ } finally {
72710
+ cachedStageDrain = undefined;
72711
+ }
72712
+ })();
72713
+ return cachedStageDrain;
72714
+ };
72715
+ const drainBeforeCheckpoint = () => {
72716
+ const persistence = drainCachedStagePersistence();
72717
+ return persistence?.then(() => ownController.signal.throwIfAborted());
72718
+ };
72719
+ const beforeLiveCall = () => {
72720
+ ownController.signal.throwIfAborted();
72721
+ const persistence = drainCachedStagePersistence();
72722
+ if (persistence !== undefined)
72723
+ return persistence.then(beforeLiveCall);
72724
+ if (scheduler.isRunPaused())
72725
+ return waitForRunRelease().then(beforeLiveCall);
72726
+ };
72583
72727
  const finalizers = createRunFinalizers({
72584
72728
  def,
72585
72729
  runId,
@@ -72588,8 +72732,14 @@ async function executeRun(def, resolvedInputs, opts) {
72588
72732
  opts,
72589
72733
  classifyExecutorFailure,
72590
72734
  drainWorkflowExitCleanups: async (reason) => {
72591
- await Promise.all(cachedStagePersistence);
72592
- await exit.drainWorkflowExitCleanups(reason);
72735
+ try {
72736
+ await drainCachedStagePersistence();
72737
+ } catch (error) {
72738
+ if (error !== cachedStageFailure)
72739
+ throw error;
72740
+ } finally {
72741
+ await exit.drainWorkflowExitCleanups(reason);
72742
+ }
72593
72743
  },
72594
72744
  assertSuccessfulCompletion: () => {
72595
72745
  if (cachedStageFailure !== undefined)
@@ -72605,7 +72755,8 @@ async function executeRun(def, resolvedInputs, opts) {
72605
72755
  run: runSnapshot,
72606
72756
  nextCheckpointId: checkpointIdGenerator,
72607
72757
  nextReplayKey: stageReplayKeyGenerator,
72608
- completedReplayKeys: completedStageReplayKeys
72758
+ completedReplayKeys: completedStageReplayKeys,
72759
+ beforeCheckpoint: drainBeforeCheckpoint
72609
72760
  });
72610
72761
  const durableOnStageEnd = createDurableStageEndRecorder({
72611
72762
  rootRunId: runId,
@@ -72754,7 +72905,9 @@ async function executeRun(def, resolvedInputs, opts) {
72754
72905
  retryToolNodes: opts.continuation?.retryToolNodes,
72755
72906
  toolControls,
72756
72907
  toolAdmission,
72757
- budget
72908
+ budget,
72909
+ beforeToolCall: drainCachedStagePersistence,
72910
+ beforeCheckpoint: drainBeforeCheckpoint
72758
72911
  });
72759
72912
  let selectedAdmittedToolFailure;
72760
72913
  const suspendForGracefulQuit = (reason) => {
@@ -72795,9 +72948,11 @@ async function executeRun(def, resolvedInputs, opts) {
72795
72948
  workflowId: runId,
72796
72949
  backend: durableBackend,
72797
72950
  nextCheckpointId: checkpointIdGenerator,
72951
+ beforeCheckpoint: drainBeforeCheckpoint,
72798
72952
  beforeCall: () => {
72799
72953
  ownController.signal.throwIfAborted();
72800
- return scheduler.isRunPaused() ? waitForRunRelease() : undefined;
72954
+ const persistence = drainCachedStagePersistence();
72955
+ return persistence ?? (scheduler.isRunPaused() ? waitForRunRelease() : undefined);
72801
72956
  },
72802
72957
  ...opts.usePromptNodesForUi === true ? {
72803
72958
  onReplay: async (request) => getPromptNodeUi().replayDurable(request)
@@ -72834,6 +72989,7 @@ async function executeRun(def, resolvedInputs, opts) {
72834
72989
  durableIntercomGroup,
72835
72990
  task: taskRunners.task,
72836
72991
  recordCachedTask: recordCachedStage,
72992
+ beforeCheckpoint: drainBeforeCheckpoint,
72837
72993
  signal: ownController.signal,
72838
72994
  registerTailControl: (registration) => {
72839
72995
  registration.controller.signal.addEventListener("abort", () => {
@@ -72870,6 +73026,8 @@ async function executeRun(def, resolvedInputs, opts) {
72870
73026
  backend: durableBackend,
72871
73027
  nextReplayKey: (stageName) => stageReplayKeyGenerator(stageName),
72872
73028
  durableIntercomGroup,
73029
+ beforeCall: beforeLiveCall,
73030
+ beforeCheckpoint: drainBeforeCheckpoint,
72873
73031
  recordCachedStage,
72874
73032
  stage: (name, options, replayKey) => {
72875
73033
  const stage = runtime.stage(name, options);
@@ -72930,7 +73088,7 @@ async function executeRun(def, resolvedInputs, opts) {
72930
73088
  return pending;
72931
73089
  }),
72932
73090
  tool: (...args) => {
72933
- if (!scheduler.isRunPaused())
73091
+ if (admittedTools.closed)
72934
73092
  return tool(...args);
72935
73093
  const pending = whenRunning(() => tool(...args));
72936
73094
  pending.catch(() => {});
@@ -73058,13 +73216,13 @@ async function executeRun(def, resolvedInputs, opts) {
73058
73216
  ownController.signal.throwIfAborted();
73059
73217
  if (opts.parentRun === undefined) {
73060
73218
  if (durableRootRegistration !== undefined) {
73061
- await durableBackend.registerWorkflow({
73219
+ await durableBackend.commitWorkflowRegistration({
73062
73220
  ...durableRootRegistration,
73063
73221
  modelOwner: runSnapshot.modelOwner,
73064
73222
  ...workflowInvocationMetadata(inputRuntimeDefaults, workflowInvocationCwd, gitWorktreeSetupCache, runSnapshot.origin)
73065
73223
  });
73066
73224
  } else {
73067
- await durableBackend.setWorkflowStatus(runId, "running");
73225
+ await durableBackend.commitWorkflowStatus(runId, "running");
73068
73226
  }
73069
73227
  }
73070
73228
  durableRootAdmitted = true;
@@ -73086,9 +73244,7 @@ async function executeRun(def, resolvedInputs, opts) {
73086
73244
  await waitForRunRelease();
73087
73245
  ownController.signal.throwIfAborted();
73088
73246
  const rawResult = await raceAbort(runWorkflowDefinitionCallback(def.name, runId, () => def.run(ctx)), ownController.signal);
73089
- await Promise.all(cachedStagePersistence);
73090
- if (cachedStageFailure !== undefined)
73091
- throw cachedStageFailure;
73247
+ await drainCachedStagePersistence();
73092
73248
  while (scheduler.isRunPaused())
73093
73249
  await waitForRunRelease();
73094
73250
  await admittedTools.closeAndDrain();
@@ -73128,7 +73284,7 @@ async function executeRun(def, resolvedInputs, opts) {
73128
73284
  const recorded = activeStore.recordRunEnd(runId, returned.status, result, returned.error, returned.metadata);
73129
73285
  if (opts.parentRun === undefined)
73130
73286
  await recordRunTimingCheckpointAsync(durableBackend, runSnapshot);
73131
- await durableBackend.setWorkflowStatus(runId, returned.status, undefined, returned.metadata?.resumable);
73287
+ await durableBackend.commitWorkflowStatus(runId, returned.status, undefined, returned.metadata?.resumable);
73132
73288
  await appendRunEndWhenRecorded(opts.persistence, recorded, {
73133
73289
  runId,
73134
73290
  status: returned.status,
@@ -73258,6 +73414,9 @@ async function executeRun(def, resolvedInputs, opts) {
73258
73414
  unregisterToolAdmission();
73259
73415
  } finally {
73260
73416
  terminalEvents.dispose();
73417
+ if (opts.stageControlRegistry === undefined && opts.executionMode !== "interactive" && isTerminalRunStatus(runSnapshot.status) && runSnapshot.resumable !== true) {
73418
+ await stageRegistry.clear(runId);
73419
+ }
73261
73420
  }
73262
73421
  }
73263
73422
  }
@@ -73424,127 +73583,141 @@ function workflowStartupFailureMessage(admission, snapshotError, fallback) {
73424
73583
  }
73425
73584
 
73426
73585
  // dist/builtin/workflows/src/durable/fork-workflow.ts
73427
- import { randomUUID as randomUUID8 } from "node:crypto";
73428
- import { SessionManager as SessionManager3 } from "@bastani/atomic";
73429
- async function forkDurableWorkflow(backend, source, cwd, modelOwner) {
73586
+ import { randomUUID as randomUUID9 } from "node:crypto";
73587
+ async function forkDurableWorkflow(backend, source, cwd, modelOwner, sessionStore) {
73430
73588
  source = structuredClone(source);
73431
- const workflowId = randomUUID8();
73432
- const ids = new Map([[source.workflowId, workflowId]]);
73433
- const mapId = (id) => {
73434
- let mapped = ids.get(id);
73435
- if (mapped === undefined) {
73436
- mapped = randomUUID8();
73437
- ids.set(id, mapped);
73438
- }
73439
- return mapped;
73440
- };
73441
- const mapTarget = (target) => {
73442
- const parsed = parseWorkflowStageTarget(target);
73443
- if (parsed === undefined || parsed.rootRunId !== source.workflowId)
73444
- return target;
73445
- return formatWorkflowStageTarget(workflowId, ...parsed.segments.map((segment) => ids.get(segment) ?? segment));
73446
- };
73447
- const mapRun = (run) => ({
73448
- ...run,
73449
- runId: mapId(run.runId),
73450
- ...run.parentRunId === undefined ? {} : { parentRunId: mapId(run.parentRunId) },
73451
- ...run.rootRunId === undefined ? {} : { rootRunId: workflowId }
73452
- });
73453
- const sessions = new Map;
73454
- const checkpoints = [];
73455
- for (const checkpoint of backend.listCheckpoints(source.workflowId)) {
73456
- const copy = structuredClone(checkpoint);
73457
- if (copy.kind === "ui") {
73458
- checkpoints.push({ ...copy, workflowId });
73459
- continue;
73460
- }
73461
- const topology = copy.topology;
73462
- if (copy.kind === "tool") {
73589
+ const sourceStore = await stageSessionStore({ cwd: source.workflowCwd ?? source.invocationCwd ?? cwd });
73590
+ let destinationStore;
73591
+ try {
73592
+ destinationStore = sessionStore ?? await stageSessionStore({ cwd });
73593
+ const workflowId = randomUUID9();
73594
+ const ids = new Map([[source.workflowId, workflowId]]);
73595
+ const mapId = (id) => {
73596
+ let mapped = ids.get(id);
73597
+ if (mapped === undefined) {
73598
+ mapped = randomUUID9();
73599
+ ids.set(id, mapped);
73600
+ }
73601
+ return mapped;
73602
+ };
73603
+ const mapTarget = (target) => {
73604
+ const parsed = parseWorkflowStageTarget(target);
73605
+ if (parsed === undefined || parsed.rootRunId !== source.workflowId)
73606
+ return target;
73607
+ return formatWorkflowStageTarget(workflowId, ...parsed.segments.map((segment) => ids.get(segment) ?? segment));
73608
+ };
73609
+ const mapRun = (run) => ({
73610
+ ...run,
73611
+ runId: mapId(run.runId),
73612
+ ...run.parentRunId === undefined ? {} : { parentRunId: mapId(run.parentRunId) },
73613
+ ...run.rootRunId === undefined ? {} : { rootRunId: workflowId }
73614
+ });
73615
+ const sessions = new Map;
73616
+ const checkpoints = [];
73617
+ for (const checkpoint of backend.listCheckpoints(source.workflowId)) {
73618
+ const copy = structuredClone(checkpoint);
73619
+ if (copy.kind === "ui") {
73620
+ checkpoints.push({ ...copy, workflowId });
73621
+ continue;
73622
+ }
73623
+ const topology = copy.topology;
73624
+ if (copy.kind === "tool") {
73625
+ checkpoints.push({
73626
+ ...copy,
73627
+ workflowId,
73628
+ ...topology === undefined ? {} : {
73629
+ topology: {
73630
+ ...copy.topology,
73631
+ ...copy.topology?.run === undefined ? {} : { run: mapRun(copy.topology.run) }
73632
+ }
73633
+ }
73634
+ });
73635
+ continue;
73636
+ }
73637
+ const stageTopology = copy.topology;
73638
+ const boundary = stageTopology?.boundary;
73639
+ const taskOutput = isToolPayloadObject(copy.output) && typeof copy.output.text === "string" ? copy.output : undefined;
73640
+ const sessionId = copy.sessionId ?? (typeof taskOutput?.sessionId === "string" ? taskOutput.sessionId : undefined);
73641
+ let session = sessionId === undefined ? undefined : sessions.get(sessionId);
73642
+ if (session === undefined && sessionId !== undefined) {
73643
+ session = await forkStageSession(sourceStore, sessionId, cwd, {
73644
+ internal: true,
73645
+ workflow: {
73646
+ runId: workflowId,
73647
+ stageId: stageTopology?.stageId ?? copy.checkpointId,
73648
+ stageName: copy.name
73649
+ }
73650
+ }, destinationStore);
73651
+ sessions.set(sessionId, session);
73652
+ }
73653
+ const childOutput = boundary === undefined ? undefined : parseWorkflowChildResult(copy.output);
73463
73654
  checkpoints.push({
73464
73655
  ...copy,
73465
73656
  workflowId,
73466
- ...topology === undefined ? {} : {
73657
+ ...childOutput === undefined ? {} : { output: { ...childOutput, runId: mapId(childOutput.runId) } },
73658
+ ...taskOutput === undefined ? {} : {
73659
+ output: {
73660
+ ...taskOutput,
73661
+ sessionId: session?.getSessionId(),
73662
+ sessionFile: session?.getSessionFile()
73663
+ }
73664
+ },
73665
+ sessionId: session?.getSessionId(),
73666
+ sessionFile: session?.getSessionFile(),
73667
+ ...stageTopology === undefined ? {} : {
73467
73668
  topology: {
73468
- ...copy.topology,
73469
- ...copy.topology?.run === undefined ? {} : { run: mapRun(copy.topology.run) }
73669
+ ...stageTopology,
73670
+ intercomGroup: undefined,
73671
+ ...stageTopology.run === undefined ? {} : { run: mapRun(stageTopology.run) },
73672
+ ...boundary === undefined ? {} : {
73673
+ boundary: {
73674
+ ...boundary,
73675
+ child: {
73676
+ ...boundary.child,
73677
+ runId: mapId(boundary.child.runId),
73678
+ parentRunId: mapId(boundary.child.parentRunId),
73679
+ rootRunId: workflowId
73680
+ }
73681
+ }
73682
+ }
73470
73683
  }
73471
73684
  }
73472
73685
  });
73473
- continue;
73474
73686
  }
73475
- const stageTopology = copy.topology;
73476
- const boundary = stageTopology?.boundary;
73477
- const taskOutput = isToolPayloadObject(copy.output) && typeof copy.output.text === "string" ? copy.output : undefined;
73478
- const sessionFile = copy.sessionFile ?? (typeof taskOutput?.sessionFile === "string" ? taskOutput.sessionFile : undefined);
73479
- let session = sessionFile === undefined ? undefined : sessions.get(sessionFile);
73480
- if (session === undefined && sessionFile !== undefined) {
73481
- session = await SessionManager3.forkFrom(sessionFile, cwd, undefined, {
73482
- internal: true,
73483
- workflow: { runId: workflowId, stageId: stageTopology?.stageId ?? copy.checkpointId, stageName: copy.name }
73484
- });
73485
- sessions.set(sessionFile, session);
73486
- }
73487
- const childOutput = boundary === undefined ? undefined : parseWorkflowChildResult(copy.output);
73488
- checkpoints.push({
73489
- ...copy,
73687
+ const fork = {
73688
+ ...source,
73490
73689
  workflowId,
73491
- ...childOutput === undefined ? {} : { output: { ...childOutput, runId: mapId(childOutput.runId) } },
73492
- ...taskOutput === undefined ? {} : {
73493
- output: { ...taskOutput, sessionId: session?.getSessionId(), sessionFile: session?.getSessionFile() }
73494
- },
73495
- sessionId: session?.getSessionId(),
73496
- sessionFile: session?.getSessionFile(),
73497
- ...stageTopology === undefined ? {} : {
73498
- topology: {
73499
- ...stageTopology,
73500
- intercomGroup: undefined,
73501
- ...stageTopology.run === undefined ? {} : { run: mapRun(stageTopology.run) },
73502
- ...boundary === undefined ? {} : {
73503
- boundary: {
73504
- ...boundary,
73505
- child: {
73506
- ...boundary.child,
73507
- runId: mapId(boundary.child.runId),
73508
- parentRunId: mapId(boundary.child.parentRunId),
73509
- rootRunId: workflowId
73510
- }
73511
- }
73512
- }
73513
- }
73514
- }
73690
+ rootWorkflowId: undefined,
73691
+ invocationCwd: cwd,
73692
+ workflowCwd: undefined,
73693
+ repositoryRoot: undefined,
73694
+ gitWorktreeRoot: undefined,
73695
+ sessionFile: undefined,
73696
+ modelOwner,
73697
+ releasedModelOwner: undefined,
73698
+ ownerExecutorId: undefined,
73699
+ createdAt: Date.now(),
73700
+ updatedAt: Date.now(),
73701
+ completedCheckpoints: 0,
73702
+ pendingStageMessages: source.pendingStageMessages?.map((message) => ({
73703
+ ...message,
73704
+ runId: mapId(message.runId),
73705
+ stageKey: mapTarget(message.stageKey),
73706
+ ...message.targetPath === undefined ? {} : { targetPath: mapTarget(message.targetPath) }
73707
+ }))
73708
+ };
73709
+ await backend.commitWorkflowRegistration({ ...fork, status: "running", resumable: false });
73710
+ for (const checkpoint of checkpoints)
73711
+ await backend.commitCheckpoint(checkpoint);
73712
+ await backend.commitWorkflowRegistration({
73713
+ ...fork,
73714
+ resumable: source.resumable ?? true,
73715
+ completedCheckpoints: backend.getWorkflow(workflowId).completedCheckpoints
73515
73716
  });
73717
+ return workflowId;
73718
+ } finally {
73719
+ await Promise.all([sourceStore.close(), sessionStore === undefined ? destinationStore?.close() : undefined]);
73516
73720
  }
73517
- const fork = {
73518
- ...source,
73519
- workflowId,
73520
- rootWorkflowId: undefined,
73521
- invocationCwd: cwd,
73522
- workflowCwd: undefined,
73523
- repositoryRoot: undefined,
73524
- gitWorktreeRoot: undefined,
73525
- sessionFile: undefined,
73526
- modelOwner,
73527
- releasedModelOwner: undefined,
73528
- ownerExecutorId: undefined,
73529
- createdAt: Date.now(),
73530
- updatedAt: Date.now(),
73531
- completedCheckpoints: 0,
73532
- pendingStageMessages: source.pendingStageMessages?.map((message) => ({
73533
- ...message,
73534
- runId: mapId(message.runId),
73535
- stageKey: mapTarget(message.stageKey),
73536
- ...message.targetPath === undefined ? {} : { targetPath: mapTarget(message.targetPath) }
73537
- }))
73538
- };
73539
- await backend.registerWorkflow({ ...fork, status: "running", resumable: false });
73540
- for (const checkpoint of checkpoints)
73541
- await backend.recordCheckpointAsync(checkpoint);
73542
- await backend.registerWorkflow({
73543
- ...fork,
73544
- resumable: source.resumable ?? true,
73545
- completedCheckpoints: backend.getWorkflow(workflowId).completedCheckpoints
73546
- });
73547
- return workflowId;
73548
73721
  }
73549
73722
 
73550
73723
  // dist/builtin/workflows/src/durable/tool-resume-frontier.ts
@@ -73780,7 +73953,7 @@ async function resumeDurableWorkflowClaimed(workflowId, deps, catalog) {
73780
73953
  }
73781
73954
  if (crossProject) {
73782
73955
  deps.signal?.throwIfAborted();
73783
- const forkId = await forkDurableWorkflow(backend, handle, currentCwd, deps.forkModelOwner ?? requestedOwner);
73956
+ const forkId = await forkDurableWorkflow(backend, handle, currentCwd, deps.forkModelOwner ?? requestedOwner, deps.baseRunOpts.adapters?.sessionStore);
73784
73957
  const fork = backend.getWorkflow(forkId);
73785
73958
  const result = await resumeDurableWorkflow(forkId, {
73786
73959
  ...deps,
@@ -73824,12 +73997,12 @@ async function resumeDurableWorkflowClaimed(workflowId, deps, catalog) {
73824
73997
  const current = backend.getWorkflow(resolved.workflowId);
73825
73998
  if (adoptedClaimUpdatedAt === undefined || current?.modelOwner !== requestedOwner)
73826
73999
  return false;
73827
- const restored = await backend.transitionWorkflowStatus(resolved.workflowId, ["running"], handle.status, handle.pendingPrompts, handle.resumable, adoptedClaimUpdatedAt);
74000
+ const restored = await backend.commitWorkflowStatusTransition(resolved.workflowId, ["running"], handle.status, handle.pendingPrompts, handle.resumable, adoptedClaimUpdatedAt);
73828
74001
  if (restored)
73829
74002
  onRestored?.();
73830
74003
  return restored;
73831
74004
  }
73832
- await backend.setWorkflowStatus(resolved.workflowId, handle.status, handle.pendingPrompts, handle.resumable, sourceFailure);
74005
+ await backend.commitWorkflowStatus(resolved.workflowId, handle.status, handle.pendingPrompts, handle.resumable, sourceFailure);
73833
74006
  onRestored?.();
73834
74007
  return true;
73835
74008
  };
@@ -73844,7 +74017,7 @@ async function resumeDurableWorkflowClaimed(workflowId, deps, catalog) {
73844
74017
  }
73845
74018
  unsettled.add(resolved.workflowId);
73846
74019
  try {
73847
- claimed = await backend.transitionWorkflowStatus(resolved.workflowId, [handle.status], "running", undefined, undefined, resolved.updatedAt, adopting ? requestedOwner : undefined);
74020
+ claimed = await backend.commitWorkflowStatusTransition(resolved.workflowId, [handle.status], "running", undefined, undefined, resolved.updatedAt, adopting ? requestedOwner : undefined);
73848
74021
  if (claimed && adopting)
73849
74022
  adoptedClaimUpdatedAt = backend.getWorkflow(resolved.workflowId)?.updatedAt;
73850
74023
  if (claimed && !adopting && deps.signal?.aborted)
@@ -73889,7 +74062,7 @@ async function resumeDurableWorkflowClaimed(workflowId, deps, catalog) {
73889
74062
  if (toolContinuation !== undefined && (message.includes("insufficient_state: replay topology mismatch") || message.includes("insufficient_state: replay topology ambiguous"))) {
73890
74063
  const current = deps.baseRunOpts.store?.runs().find((run) => run.id === resolved.workflowId);
73891
74064
  if (current?.status === "failed" && current.error === message) {
73892
- await backend.setWorkflowStatus(resolved.workflowId, handle.status, handle.pendingPrompts, handle.resumable, sourceFailure);
74065
+ await backend.commitWorkflowStatus(resolved.workflowId, handle.status, handle.pendingPrompts, handle.resumable, sourceFailure);
73893
74066
  if (deps.baseRunOpts.store?.runs().find((run) => run.id === resolved.workflowId) === current && current.status === "failed" && current.error === message) {
73894
74067
  deps.baseRunOpts.store.recordRunStart({ ...toolContinuation.source, error: message });
73895
74068
  }
@@ -74001,15 +74174,17 @@ function isReservedRunCheckpointHash(argsHash) {
74001
74174
  function listCompletedFromBackend(backend) {
74002
74175
  return backend.listCompletedWorkflows();
74003
74176
  }
74004
- function listOpenableCompletedWorkflows(backend) {
74005
- return listCompletedFromBackend(backend).filter((entry) => completedWorkflowSnapshot(backend, entry) !== undefined).sort((a, b) => b.updatedAt - a.updatedAt);
74177
+ async function listOpenableCompletedWorkflows(backend, sessionStore) {
74178
+ const entries = listCompletedFromBackend(backend);
74179
+ const snapshots = await Promise.all(entries.map((entry) => completedWorkflowSnapshot(backend, entry, sessionStore)));
74180
+ return entries.filter((_entry, index) => snapshots[index] !== undefined).sort((a, b) => b.updatedAt - a.updatedAt);
74006
74181
  }
74007
- function resolveCompletedWorkflow(workflowId, backend, openableCatalog = listOpenableCompletedWorkflows(backend)) {
74008
- const resolved = resolveDurableEntry(workflowId, openableCatalog);
74182
+ async function resolveCompletedWorkflow(workflowId, backend, openableCatalog, sessionStore) {
74183
+ const resolved = resolveDurableEntry(workflowId, openableCatalog ?? await listOpenableCompletedWorkflows(backend, sessionStore));
74009
74184
  if (resolved !== undefined) {
74010
74185
  if ("kind" in resolved)
74011
74186
  return { kind: "malformed", message: resolved.message };
74012
- const snapshot = completedWorkflowSnapshot(backend, resolved);
74187
+ const snapshot = await completedWorkflowSnapshot(backend, resolved, sessionStore);
74013
74188
  if (snapshot === undefined) {
74014
74189
  return { kind: "stale", entry: resolved };
74015
74190
  }
@@ -74022,40 +74197,49 @@ function resolveCompletedWorkflow(workflowId, backend, openableCatalog = listOpe
74022
74197
  return { kind: "malformed", message: authoritative.message };
74023
74198
  return { kind: "stale", entry: authoritative };
74024
74199
  }
74025
- function completedWorkflowSnapshot(backend, entry) {
74026
- const runs = completedWorkflowRunSnapshots(backend, entry);
74200
+ async function completedWorkflowSnapshot(backend, entry, sessionStore) {
74201
+ const runs = await completedWorkflowRunSnapshots(backend, entry, sessionStore);
74027
74202
  return runs.find((run) => run.id === entry.workflowId);
74028
74203
  }
74029
- function completedWorkflowRunSnapshots(backend, entry) {
74204
+ async function completedWorkflowRunSnapshots(backend, entry, sessionStore) {
74030
74205
  const handle = backend.getWorkflow(entry.workflowId);
74031
74206
  if (handle === undefined || handle.status !== "completed" && handle.status !== "failed")
74032
74207
  return [];
74033
74208
  const checkpoints = backend.listCheckpoints(entry.workflowId);
74034
74209
  if (checkpoints.length === 0)
74035
74210
  return [];
74036
- const runs = runSnapshotsFromCheckpoints(checkpoints, handle.workflowId, handle.name, handle.updatedAt, COMPLETED_RECONSTRUCTION).map((run) => ({ ...run, stages: run.stages.map(validatedStageTranscript) }));
74037
- const rootIndex = runs.findIndex((run) => run.id === handle.workflowId);
74038
- if (rootIndex < 0)
74039
- return [];
74040
- const rootDuration = priorRunElapsedMs(backend, handle.workflowId) ?? Math.max(0, handle.updatedAt - handle.createdAt);
74041
- const root = {
74042
- ...runs[rootIndex],
74043
- inputs: { ...handle.inputs },
74044
- status: handle.status,
74045
- startedAt: handle.createdAt,
74046
- endedAt: handle.updatedAt,
74047
- durationMs: rootDuration,
74048
- ...handle.error !== undefined ? { error: handle.error } : {},
74049
- ...handle.exited !== undefined ? { exited: handle.exited } : {},
74050
- ...handle.exitReason !== undefined ? { exitReason: handle.exitReason } : {},
74051
- ...handle.failureKind !== undefined ? { failureKind: handle.failureKind } : {},
74052
- ...handle.failureCode !== undefined ? { failureCode: handle.failureCode } : {},
74053
- ...handle.failureRecoverability !== undefined ? { failureRecoverability: handle.failureRecoverability } : {},
74054
- ...handle.failureDisposition !== undefined ? { failureDisposition: handle.failureDisposition } : {},
74055
- ...handle.failedToolNodeId !== undefined ? { failedToolNodeId: handle.failedToolNodeId } : {},
74056
- resumable: handle.resumable ?? false
74057
- };
74058
- return [root, ...runs.filter((_, index) => index !== rootIndex)];
74211
+ const selectedStore = sessionStore ?? await stageSessionStore({ cwd: handle.workflowCwd ?? handle.invocationCwd });
74212
+ try {
74213
+ const runs = await Promise.all(runSnapshotsFromCheckpoints(checkpoints, handle.workflowId, handle.name, handle.updatedAt, COMPLETED_RECONSTRUCTION).map(async (run) => ({
74214
+ ...run,
74215
+ stages: await Promise.all(run.stages.map((stage) => validatedStageTranscript(stage, selectedStore)))
74216
+ })));
74217
+ const rootIndex = runs.findIndex((run) => run.id === handle.workflowId);
74218
+ if (rootIndex < 0)
74219
+ return [];
74220
+ const rootDuration = priorRunElapsedMs(backend, handle.workflowId) ?? Math.max(0, handle.updatedAt - handle.createdAt);
74221
+ const root = {
74222
+ ...runs[rootIndex],
74223
+ inputs: { ...handle.inputs },
74224
+ status: handle.status,
74225
+ startedAt: handle.createdAt,
74226
+ endedAt: handle.updatedAt,
74227
+ durationMs: rootDuration,
74228
+ ...handle.error !== undefined ? { error: handle.error } : {},
74229
+ ...handle.exited !== undefined ? { exited: handle.exited } : {},
74230
+ ...handle.exitReason !== undefined ? { exitReason: handle.exitReason } : {},
74231
+ ...handle.failureKind !== undefined ? { failureKind: handle.failureKind } : {},
74232
+ ...handle.failureCode !== undefined ? { failureCode: handle.failureCode } : {},
74233
+ ...handle.failureRecoverability !== undefined ? { failureRecoverability: handle.failureRecoverability } : {},
74234
+ ...handle.failureDisposition !== undefined ? { failureDisposition: handle.failureDisposition } : {},
74235
+ ...handle.failedToolNodeId !== undefined ? { failedToolNodeId: handle.failedToolNodeId } : {},
74236
+ resumable: handle.resumable ?? false
74237
+ };
74238
+ return [root, ...runs.filter((_, index) => index !== rootIndex)];
74239
+ } finally {
74240
+ if (sessionStore === undefined)
74241
+ await selectedStore.close();
74242
+ }
74059
74243
  }
74060
74244
  function durableWorkflowRunSnapshots(backend, handle) {
74061
74245
  const checkpoints = backend.listCheckpoints(handle.workflowId);
@@ -74100,11 +74284,11 @@ function durableNestedRunSnapshots(backend, rootWorkflowId) {
74100
74284
  return [];
74101
74285
  return runSnapshotsFromCheckpoints(backend.listCheckpoints(rootWorkflowId), rootWorkflowId, handle.name, handle.updatedAt, ACTIVE_INSPECTION_RECONSTRUCTION).filter((run) => run.id !== rootWorkflowId);
74102
74286
  }
74103
- function validatedStageTranscript(stage) {
74104
- if (stage.sessionFile === undefined || isReopenableSessionTranscript(stage.sessionFile))
74287
+ async function validatedStageTranscript(stage, store) {
74288
+ if (stage.sessionId !== undefined && await isReopenableSession(store, stage.sessionId))
74105
74289
  return stage;
74106
- const { sessionFile, ...withoutSessionFile } = stage;
74107
- return withoutSessionFile;
74290
+ const { sessionId: _sessionId, sessionFile: _sessionFile, ...withoutSession } = stage;
74291
+ return withoutSession;
74108
74292
  }
74109
74293
  function checkpointDrafts(checkpoints) {
74110
74294
  const stageByReplayKey = new Map;
@@ -74410,7 +74594,8 @@ function emptyGraphRun(runId, runName, completedAt) {
74410
74594
 
74411
74595
  // dist/builtin/workflows/src/runs/foreground/postmortem-stage-chat.ts
74412
74596
  var TERMINAL_POSTMORTEM_STATUSES = new Set(["completed"]);
74413
- function ensurePostMortemStageHandle(runId, stage, deps) {
74597
+ async function ensurePostMortemStageHandle(runId, stage, deps) {
74598
+ const generation = deps.registry.generation;
74414
74599
  if (!TERMINAL_POSTMORTEM_STATUSES.has(stage.status))
74415
74600
  return { ok: false, reason: "not_terminal" };
74416
74601
  const existing = deps.registry.claim(runId, stage.id);
@@ -74419,23 +74604,30 @@ function ensurePostMortemStageHandle(runId, stage, deps) {
74419
74604
  }
74420
74605
  if (deps.adapters?.agentSession === undefined)
74421
74606
  return { ok: false, reason: "no_adapter" };
74422
- const sessionFile = stage.sessionFile;
74423
- if (typeof sessionFile !== "string" || sessionFile.length === 0)
74607
+ const sessionId = stage.sessionId;
74608
+ if (sessionId === undefined)
74424
74609
  return { ok: false, reason: "no_session" };
74425
- if (!isReopenableSessionTranscript(sessionFile))
74610
+ const sessionStore = await stageSessionStore({
74611
+ sessionStore: deps.registry.getSessionStore(runId, stage.id) ?? deps.sessionStore ?? deps.adapters.sessionStore,
74612
+ cwd: deps.cwd
74613
+ }, deps.defaultSessionDir);
74614
+ if (!await isReopenableSession(sessionStore, sessionId))
74426
74615
  return { ok: false, reason: "invalid_session" };
74616
+ if (deps.registry.generation !== generation)
74617
+ return { ok: false, reason: "closed" };
74427
74618
  const adapters = deps.adapters;
74428
- const handle = deps.registry.getOrCreateDetached(runId, stage.id, () => createPostMortemStageHandle(runId, stage, sessionFile, adapters, deps.cwd, deps.defaultSessionDir));
74619
+ const handle = deps.registry.getOrCreateDetached(runId, stage.id, () => createPostMortemStageHandle(runId, stage, sessionId, adapters, deps.cwd, deps.defaultSessionDir, sessionStore));
74429
74620
  return { ok: true, handle };
74430
74621
  }
74431
- function createPostMortemStageHandle(runId, stage, sessionFile, adapters, cwd, defaultSessionDir) {
74622
+ function createPostMortemStageHandle(runId, stage, sessionId, adapters, cwd, defaultSessionDir, sessionStore) {
74432
74623
  const context = createStageContext2({
74433
74624
  runId,
74434
74625
  stageId: stage.id,
74435
74626
  stageName: stage.name,
74436
74627
  adapters,
74437
74628
  stageOptions: {
74438
- resumeFromSessionFile: sessionFile,
74629
+ resumeFromSessionId: sessionId,
74630
+ sessionStore,
74439
74631
  ...cwd !== undefined ? { cwd } : {}
74440
74632
  },
74441
74633
  ...defaultSessionDir !== undefined ? { defaultSessionDir } : {}
@@ -74446,14 +74638,14 @@ function createPostMortemStageHandle(runId, stage, sessionFile, adapters, cwd, d
74446
74638
  throw new Error(`Post-mortem stage chat "${stage.name}" is closed.`);
74447
74639
  };
74448
74640
  const messagePreparation = () => ({
74449
- ...context.__sessionMeta().sessionFile === undefined ? { sessionFile } : {},
74641
+ ...context.__sessionMeta().sessionId === undefined ? { sessionId } : {},
74450
74642
  beforePreparation: throwIfClosed
74451
74643
  });
74452
74644
  const ensureAttached = async () => {
74453
74645
  throwIfClosed();
74454
- const sessionFileToRestore = messagePreparation().sessionFile;
74455
- if (sessionFileToRestore !== undefined) {
74456
- await context.__ensureSessionFromFile(sessionFileToRestore);
74646
+ const sessionIdToRestore = messagePreparation().sessionId;
74647
+ if (sessionIdToRestore !== undefined) {
74648
+ await context.__ensureSessionFromId(sessionIdToRestore);
74457
74649
  }
74458
74650
  };
74459
74651
  const queuedUserMessages = new StageQueuedUserMessageBuffer;
@@ -74463,11 +74655,12 @@ function createPostMortemStageHandle(runId, stage, sessionFile, adapters, cwd, d
74463
74655
  stageId: stage.id,
74464
74656
  stageName: stage.name,
74465
74657
  status: "completed",
74658
+ sessionStore,
74466
74659
  get sessionId() {
74467
- return context.__sessionMeta().sessionId ?? stage.sessionId;
74660
+ return context.__sessionMeta().sessionId ?? sessionId;
74468
74661
  },
74469
74662
  get sessionFile() {
74470
- return context.__sessionMeta().sessionFile ?? sessionFile;
74663
+ return context.__sessionMeta().sessionFile ?? stage.sessionFile;
74471
74664
  },
74472
74665
  get isStreaming() {
74473
74666
  return context.isStreaming;
@@ -74533,8 +74726,9 @@ function createPostMortemStageHandle(runId, stage, sessionFile, adapters, cwd, d
74533
74726
 
74534
74727
  // dist/builtin/workflows/src/durable/completed-inspection.ts
74535
74728
  var completedChatRegistrations = new WeakMap;
74536
- function openCompletedDurableWorkflow(workflowId, deps, catalog = listOpenableCompletedWorkflows(deps.durableBackend)) {
74537
- const resolved = resolveCompletedWorkflow(workflowId, deps.durableBackend, catalog);
74729
+ async function openCompletedDurableWorkflow(workflowId, deps, catalog) {
74730
+ const selectedStore = await stageSessionStore({ sessionStore: deps.sessionStore ?? deps.adapters?.sessionStore, cwd: deps.cwd }, deps.defaultSessionDir);
74731
+ const resolved = await resolveCompletedWorkflow(workflowId, deps.durableBackend, catalog, selectedStore);
74538
74732
  if (resolved.kind === "not_found") {
74539
74733
  return failure2("not_found", `No completed durable workflow found for id: ${workflowId}`);
74540
74734
  }
@@ -74548,7 +74742,7 @@ function openCompletedDurableWorkflow(workflowId, deps, catalog = listOpenableCo
74548
74742
  if (existing !== undefined && existing.status !== "completed") {
74549
74743
  return failure2("active", `Workflow ${resolved.snapshot.id} is already active in this session; attach with /workflow connect ${resolved.snapshot.id} instead.`);
74550
74744
  }
74551
- const snapshots = completedWorkflowRunSnapshots(deps.durableBackend, resolved.entry);
74745
+ const snapshots = await completedWorkflowRunSnapshots(deps.durableBackend, resolved.entry, selectedStore);
74552
74746
  const snapshot = snapshots.find((run) => run.id === resolved.snapshot.id) ?? resolved.snapshot;
74553
74747
  deps.beforeRestore?.(snapshots);
74554
74748
  for (const restored of snapshots) {
@@ -74556,9 +74750,9 @@ function openCompletedDurableWorkflow(workflowId, deps, catalog = listOpenableCo
74556
74750
  if (previous !== undefined)
74557
74751
  deps.store.removeRun(previous.id);
74558
74752
  deps.store.recordRunStart(restored);
74559
- registerCompletedChatHandles(restored, deps);
74753
+ registerCompletedChatHandles(restored, deps, selectedStore);
74560
74754
  }
74561
- const hasReopenableStage = snapshots.some((run) => run.stages.some((stage) => stage.sessionFile !== undefined));
74755
+ const hasReopenableStage = snapshots.some((run) => run.stages.some((stage) => stage.sessionId !== undefined));
74562
74756
  return {
74563
74757
  ok: true,
74564
74758
  runId: snapshot.id,
@@ -74570,32 +74764,32 @@ function openCompletedDurableWorkflow(workflowId, deps, catalog = listOpenableCo
74570
74764
  function failure2(reason, message) {
74571
74765
  return { ok: false, reason, message };
74572
74766
  }
74573
- function registerCompletedChatHandles(snapshot, deps) {
74767
+ function registerCompletedChatHandles(snapshot, deps, sessionStore) {
74574
74768
  if (deps.adapters?.agentSession === undefined)
74575
74769
  return;
74576
74770
  const registry = deps.stageControlRegistry ?? stageControlRegistry;
74577
74771
  const registrations = completedChatRegistrations.get(registry) ?? new Map;
74578
74772
  completedChatRegistrations.set(registry, registrations);
74579
- const desiredKeys = new Set(snapshot.stages.filter((stage) => stage.sessionFile !== undefined).map((stage) => completedChatKey(snapshot.id, stage.id)));
74773
+ const desiredKeys = new Set(snapshot.stages.filter((stage) => stage.sessionId !== undefined).map((stage) => completedChatKey(snapshot.id, stage.id)));
74580
74774
  for (const [key, registration] of registrations) {
74581
74775
  if (!key.startsWith(`${snapshot.id}:`) || desiredKeys.has(key))
74582
74776
  continue;
74583
74777
  removeCompletedChatRegistration(registrations, key, registration);
74584
74778
  }
74585
74779
  for (const stage of snapshot.stages) {
74586
- if (stage.sessionFile === undefined)
74780
+ if (stage.sessionId === undefined)
74587
74781
  continue;
74588
74782
  const key = completedChatKey(snapshot.id, stage.id);
74589
74783
  const registration = registrations.get(key);
74590
74784
  const existing = registry.claim(snapshot.id, stage.id);
74591
- if (existing?.sessionFile === stage.sessionFile && !existing.isDisposed)
74785
+ if (existing?.sessionId === stage.sessionId && existing.sessionStore === sessionStore && !existing.isDisposed)
74592
74786
  continue;
74593
74787
  if (registration !== undefined) {
74594
74788
  removeCompletedChatRegistration(registrations, key, registration);
74595
74789
  } else if (existing !== undefined) {
74596
74790
  disposeCompletedChatHandle(existing);
74597
74791
  }
74598
- const handle = createPostMortemStageHandle(snapshot.id, stage, stage.sessionFile, deps.adapters, deps.cwd, deps.defaultSessionDir);
74792
+ const handle = createPostMortemStageHandle(snapshot.id, stage, stage.sessionId, deps.adapters, deps.cwd, deps.defaultSessionDir, sessionStore);
74599
74793
  const unregister = registry.register(handle);
74600
74794
  registrations.set(key, { handle, unregister });
74601
74795
  registry.detachControl(snapshot.id, stage.id, handle);
@@ -74995,7 +75189,7 @@ async function prepareWorkflowResumeCatalog(runtime, suppressedLiveIds, target)
74995
75189
  const fallbackBackend = shared === undefined ? runtime.durableBackend() : undefined;
74996
75190
  const isDisplayLoadable = (entry) => fallbackBackend === undefined || fallbackBackend.isWorkflowLoadable(entry.workflowId);
74997
75191
  const resumable = filterSelectorDurableEntries(runtime, prepared).filter((entry) => !suppressedLiveIds.has(entry.workflowId) && isDisplayLoadable(entry));
74998
- const completed = shared?.completed ?? (runtime.prepareCompletedDurable !== undefined ? await runtime.prepareCompletedDurable() : listOpenableCompletedWorkflows(fallbackBackend ?? runtime.durableBackend()));
75192
+ const completed = shared?.completed ?? (runtime.prepareCompletedDurable !== undefined ? await runtime.prepareCompletedDurable() : await listOpenableCompletedWorkflows(fallbackBackend ?? runtime.durableBackend()));
74999
75193
  return {
75000
75194
  resumable,
75001
75195
  completed: completed.filter((entry) => isDisplayLoadable(entry))
@@ -75033,7 +75227,7 @@ async function handleDurableResume(target, ctx, reporter, deps, preparedCatalog)
75033
75227
  if (resolved.kind === "durable") {
75034
75228
  return await resumeDurableTarget(resolved.workflowId, ctx, reporter, deps, runtime);
75035
75229
  }
75036
- const completedAttempt = openCompleted(runtime, target, catalog.completed, deps.beforeRestoreCompleted, owner.store);
75230
+ const completedAttempt = await openCompleted(runtime, target, catalog.completed, deps.beforeRestoreCompleted, owner.store);
75037
75231
  if (!completedAttempt.ok && completedAttempt.reason !== "not_found") {
75038
75232
  fail(completedAttempt.message);
75039
75233
  return true;
@@ -75148,8 +75342,8 @@ async function resumeDurableTarget(workflowId, ctx, reporter, deps, runtime) {
75148
75342
  }
75149
75343
  return true;
75150
75344
  }
75151
- function openCompletedTarget(workflowId, catalog, ctx, reporter, deps, runtime) {
75152
- const result = openCompleted(runtime, workflowId, catalog, deps.beforeRestoreCompleted, deps.owner?.store);
75345
+ async function openCompletedTarget(workflowId, catalog, ctx, reporter, deps, runtime) {
75346
+ const result = await openCompleted(runtime, workflowId, catalog, deps.beforeRestoreCompleted, deps.owner?.store);
75153
75347
  if (!result.ok)
75154
75348
  reporter.error(result.message);
75155
75349
  else {
@@ -75484,7 +75678,7 @@ import { registerExtensionContextRetirementEffect as registerExtensionContextRet
75484
75678
 
75485
75679
  // dist/builtin/workflows/src/extension/discovery.ts
75486
75680
  import { join as join30 } from "node:path";
75487
- import { CONFIG_DIR_NAME as CONFIG_DIR_NAME3, getAgentDir as getAgentDir5 } from "@bastani/atomic";
75681
+ import { CONFIG_DIR_NAME as CONFIG_DIR_NAME3, getAgentDir as getAgentDir6 } from "@bastani/atomic";
75488
75682
 
75489
75683
  // dist/builtin/workflows/builtin/index.ts
75490
75684
  var exports_builtin = {};
@@ -75739,7 +75933,7 @@ function withBuiltinContext(ctx) {
75739
75933
 
75740
75934
  // dist/builtin/workflows/builtin/adversarial-verification-runner.ts
75741
75935
  import { readFile, writeFile as writeFile2 } from "node:fs/promises";
75742
- import { join as join15 } from "node:path";
75936
+ import { join as join14 } from "node:path";
75743
75937
  import { Type as Type4 } from "typebox";
75744
75938
 
75745
75939
  // dist/builtin/workflows/builtin/adversarial-verification-prompts.ts
@@ -76149,12 +76343,12 @@ async function warm_first_fan_out(ctx, steps, prefixKeyOf, options = {}) {
76149
76343
  }
76150
76344
 
76151
76345
  // dist/builtin/workflows/builtin/pattern-artifact-root.ts
76152
- import { randomUUID as randomUUID9 } from "node:crypto";
76346
+ import { randomUUID as randomUUID10 } from "node:crypto";
76153
76347
  import { mkdir as mkdir3 } from "node:fs/promises";
76154
- import { join as join14 } from "node:path";
76348
+ import { join as join13 } from "node:path";
76155
76349
  async function stableArtifactRoot(ctx, workflowName) {
76156
76350
  const cwd = ctx.cwd ?? process.cwd();
76157
- const artifactDir = await ctx.tool("artifact-root", { workflow: workflowName }, async () => join14(cwd, ".atomic", "workflows", "runs", `${workflowName}-${randomUUID9()}`));
76351
+ const artifactDir = await ctx.tool("artifact-root", { workflow: workflowName }, async () => join13(cwd, ".atomic", "workflows", "runs", `${workflowName}-${randomUUID10()}`));
76158
76352
  await mkdir3(artifactDir, { recursive: true });
76159
76353
  return artifactDir;
76160
76354
  }
@@ -76272,8 +76466,8 @@ async function writeInvalid(path, stage) {
76272
76466
  }
76273
76467
  async function runAdversarialVerification(ctx) {
76274
76468
  const root = await stableArtifactRoot(ctx, "adversarial-verification");
76275
- const criteriaPath = join15(root, "criteria.md");
76276
- const candidatePath = join15(root, "candidate.md");
76469
+ const criteriaPath = join14(root, "criteria.md");
76470
+ const candidatePath = join14(root, "candidate.md");
76277
76471
  const resolvedCriteria = resolveCriteria(ctx.inputs.criteria);
76278
76472
  await writeFile2(criteriaPath, renderCriteriaMarkdown(resolvedCriteria));
76279
76473
  await ctx.task("worker", { prompt: renderWorkerPrompt(ctx.inputs.task), context: "fresh", output: candidatePath, outputMode: "file-only" });
@@ -76305,7 +76499,7 @@ async function runAdversarialVerification(ctx) {
76305
76499
  criterion,
76306
76500
  verifierIndex: index + 1,
76307
76501
  name,
76308
- artifactPath: join15(root, `verification-${round}-${criterion.id}-${index + 1}.json`)
76502
+ artifactPath: join14(root, `verification-${round}-${criterion.id}-${index + 1}.json`)
76309
76503
  });
76310
76504
  }
76311
76505
  }
@@ -76358,8 +76552,8 @@ async function runAdversarialVerification(ctx) {
76358
76552
  const decision = decide_verification(roundResult, { acceptMean, quorumFraction: QUORUM_FRACTION });
76359
76553
  finalDecision = decision;
76360
76554
  finalMean = meanScore(scoreReports);
76361
- scoreTablePath = join15(root, `verification-summary-${round}.json`);
76362
- reviewReportPath = join15(root, `review-${round}.json`);
76555
+ scoreTablePath = join14(root, `verification-summary-${round}.json`);
76556
+ reviewReportPath = join14(root, `review-${round}.json`);
76363
76557
  const summary = {
76364
76558
  scores: scoreReports,
76365
76559
  mean: finalMean,
@@ -76456,7 +76650,7 @@ import { Type as Type7 } from "typebox";
76456
76650
 
76457
76651
  // dist/builtin/workflows/builtin/classify-and-act-runner.ts
76458
76652
  import { writeFile as writeFile3 } from "node:fs/promises";
76459
- import { join as join16 } from "node:path";
76653
+ import { join as join15 } from "node:path";
76460
76654
  import { Type as Type6 } from "typebox";
76461
76655
 
76462
76656
  // dist/builtin/workflows/builtin/classify-and-act-prompts.ts
@@ -76559,7 +76753,7 @@ async function runClassifyAndAct(ctx) {
76559
76753
  const needsFallback = exactCategory === undefined || confidence < ctx.inputs.confidence_threshold;
76560
76754
  const fallback = needsFallback ? await resolveFallbackCategory(ctx, exactCategory) : undefined;
76561
76755
  const category = fallback?.category ?? exactCategory;
76562
- const classificationPath = join16(artifactDir, "classification.json");
76756
+ const classificationPath = join15(artifactDir, "classification.json");
76563
76757
  await writeFile3(classificationPath, JSON.stringify({
76564
76758
  proposed_category: proposedCategory,
76565
76759
  selected_category: category,
@@ -76569,7 +76763,7 @@ async function runClassifyAndAct(ctx) {
76569
76763
  fallback_used: needsFallback,
76570
76764
  fallback_mode: fallback?.fallbackMode ?? "none"
76571
76765
  }, null, 2));
76572
- const actionPath = join16(artifactDir, `action-${safeName(category)}.md`);
76766
+ const actionPath = join15(artifactDir, `action-${safeName(category)}.md`);
76573
76767
  const action = await ctx.task(`action-${safeName(category)}`, {
76574
76768
  tools: actionTools(category),
76575
76769
  prompt: actionPrompt({ prompt: ctx.inputs.prompt, category, classificationPath }),
@@ -76619,7 +76813,7 @@ import { Type as Type9 } from "typebox";
76619
76813
 
76620
76814
  // dist/builtin/workflows/builtin/fan-out-and-synthesize-runner.ts
76621
76815
  import { writeFile as writeFile4 } from "node:fs/promises";
76622
- import { join as join17 } from "node:path";
76816
+ import { join as join16 } from "node:path";
76623
76817
  import { Type as Type8 } from "typebox";
76624
76818
 
76625
76819
  // dist/builtin/workflows/builtin/fan-out-and-synthesize-prompts.ts
@@ -76735,9 +76929,9 @@ async function runFanOutAndSynthesize(ctx) {
76735
76929
  context: "fresh"
76736
76930
  });
76737
76931
  const partitions = parsedPartitions(plan.structured, ctx.inputs.max_branches, ctx.inputs.prompt);
76738
- const partitionPath = join17(artifactDir, "partition-plan.json");
76932
+ const partitionPath = join16(artifactDir, "partition-plan.json");
76739
76933
  await writeFile4(partitionPath, JSON.stringify({ task: ctx.inputs.prompt, partitions }, null, 2));
76740
- const branchPaths = partitions.map((partition, index) => join17(artifactDir, `branch-${safeName2(partition.label, index)}.md`));
76934
+ const branchPaths = partitions.map((partition, index) => join16(artifactDir, `branch-${safeName2(partition.label, index)}.md`));
76741
76935
  const steps = partitions.map((partition, index) => ({
76742
76936
  name: `branch-${safeName2(partition.label, index)}`,
76743
76937
  prompt: branchPrompt({ prompt: ctx.inputs.prompt, ...partition }),
@@ -76747,13 +76941,13 @@ async function runFanOutAndSynthesize(ctx) {
76747
76941
  outputMode: "file-only"
76748
76942
  }));
76749
76943
  await ctx.parallel(steps, { concurrency: Math.min(ctx.inputs.max_concurrency, partitions.length), failFast: false });
76750
- const manifestPath = join17(artifactDir, "manifest.json");
76944
+ const manifestPath = join16(artifactDir, "manifest.json");
76751
76945
  await writeFile4(manifestPath, JSON.stringify({
76752
76946
  task: ctx.inputs.prompt,
76753
76947
  partition_plan: partitionPath,
76754
76948
  branches: partitions.map((partition, index) => ({ ...partition, artifact_path: branchPaths[index] }))
76755
76949
  }, null, 2));
76756
- const synthesisPath = join17(artifactDir, "synthesis.md");
76950
+ const synthesisPath = join16(artifactDir, "synthesis.md");
76757
76951
  const synthesis = await ctx.task("synthesize", {
76758
76952
  prompt: synthesisPrompt(ctx.inputs.prompt, manifestPath),
76759
76953
  context: "fresh",
@@ -76806,7 +77000,7 @@ import { Type as Type11 } from "typebox";
76806
77000
 
76807
77001
  // dist/builtin/workflows/builtin/generate-and-filter-runner.ts
76808
77002
  import { readFile as readFile2, writeFile as writeFile5 } from "node:fs/promises";
76809
- import { join as join18 } from "node:path";
77003
+ import { join as join17 } from "node:path";
76810
77004
  import { Type as Type10 } from "typebox";
76811
77005
 
76812
77006
  // dist/builtin/workflows/builtin/generate-and-filter-prompts.ts
@@ -76927,7 +77121,7 @@ function judgeDecision(value2) {
76927
77121
  }
76928
77122
  async function runGenerateAndFilter(ctx) {
76929
77123
  const root = await stableArtifactRoot(ctx, "generate-and-filter");
76930
- const candidatePaths = Array.from({ length: ctx.inputs.num_candidates }, (_, index) => join18(root, `candidate-${index + 1}.md`));
77124
+ const candidatePaths = Array.from({ length: ctx.inputs.num_candidates }, (_, index) => join17(root, `candidate-${index + 1}.md`));
76931
77125
  const shortlistLimit = Math.min(ctx.inputs.shortlist_size, ctx.inputs.num_candidates);
76932
77126
  await ctx.parallel(candidatePaths.map((path, index) => ({
76933
77127
  name: `generate-${index + 1}`,
@@ -76936,9 +77130,9 @@ async function runGenerateAndFilter(ctx) {
76936
77130
  output: path,
76937
77131
  outputMode: "file-only"
76938
77132
  })), { concurrency: ctx.inputs.max_concurrency, failFast: false });
76939
- const manifestPath = join18(root, "manifest.json");
77133
+ const manifestPath = join17(root, "manifest.json");
76940
77134
  await writeFile5(manifestPath, JSON.stringify({ task: ctx.inputs.prompt, candidate_artifact_paths: candidatePaths }, null, 2));
76941
- const filterPath = join18(root, "filter.json");
77135
+ const filterPath = join17(root, "filter.json");
76942
77136
  const filtered = await ctx.task("dedupe-and-filter", {
76943
77137
  prompt: renderFilterPrompt(ctx.inputs.prompt, candidatePaths, shortlistLimit),
76944
77138
  context: "fresh",
@@ -76955,7 +77149,7 @@ async function runGenerateAndFilter(ctx) {
76955
77149
  let judgePath = null;
76956
77150
  let decisionPath = filterPath;
76957
77151
  if (ctx.inputs.use_judge) {
76958
- judgePath = join18(root, "judge.json");
77152
+ judgePath = join17(root, "judge.json");
76959
77153
  const judgeCandidates = await Promise.all(shortlist.map(async (path) => ({ path, body: await readFile2(path, "utf8") })));
76960
77154
  const judgePrompt = renderJudgePrompt(ctx.inputs.prompt, filterPath, shortlistLimit, judgeCandidates);
76961
77155
  const judged = await ctx.task("judge", {
@@ -76971,7 +77165,7 @@ async function runGenerateAndFilter(ctx) {
76971
77165
  shortlist = judgedShortlist.length > 0 ? judgedShortlist : shortlist;
76972
77166
  decisionPath = judgePath;
76973
77167
  }
76974
- const finalPath = join18(root, "shortlist.md");
77168
+ const finalPath = join17(root, "shortlist.md");
76975
77169
  const finalShortlist = await ctx.task("final-shortlist", {
76976
77170
  prompt: renderFinalShortlistPrompt(ctx.inputs.prompt, decisionPath),
76977
77171
  context: "fresh",
@@ -77010,7 +77204,7 @@ var generate_and_filter_default = workflow({
77010
77204
  import { Type as Type15 } from "typebox";
77011
77205
 
77012
77206
  // dist/builtin/workflows/builtin/goal-runner.ts
77013
- import { join as join21 } from "node:path";
77207
+ import { join as join20 } from "node:path";
77014
77208
 
77015
77209
  // dist/builtin/workflows/builtin/progress-scoring.ts
77016
77210
  import { Type as Type12 } from "typebox";
@@ -77279,7 +77473,7 @@ var LEDGER_FILENAME = "goal-ledger.json";
77279
77473
 
77280
77474
  // dist/builtin/workflows/builtin/goal-artifacts.ts
77281
77475
  import { writeFile as writeFile6 } from "node:fs/promises";
77282
- import { join as join19 } from "node:path";
77476
+ import { join as join18 } from "node:path";
77283
77477
 
77284
77478
  // dist/builtin/workflows/builtin/review-convergence.ts
77285
77479
  var FINAL_ACTION_PATTERN = /\b(?:pr|pull[- ]request|merge[- ]request|review request|github pr|create pr)\b/iu;
@@ -77396,7 +77590,7 @@ function withoutTurn(value2) {
77396
77590
  return copy;
77397
77591
  }
77398
77592
  async function writeReviewArtifact(artifactDir, reviewer, decision, rawText, convergenceDecision) {
77399
- const artifactPath = join19(artifactDir, `review-${artifactSafeName(reviewer)}.json`);
77593
+ const artifactPath = join18(artifactDir, `review-${artifactSafeName(reviewer)}.json`);
77400
77594
  await writeFile6(artifactPath, `${JSON.stringify({ reviewer, decision, convergence_decision: convergenceDecision, raw_text: rawText }, null, 2)}
77401
77595
  `, { encoding: "utf8" });
77402
77596
  return artifactPath;
@@ -77405,7 +77599,7 @@ async function writeReviewRoundArtifact(artifactDir, reviews, consolidatedFindin
77405
77599
  reviewer: review.reviewer,
77406
77600
  findings: review.findings
77407
77601
  }))), reverification = []) {
77408
- const artifactPath = join19(artifactDir, "review-round-latest.json");
77602
+ const artifactPath = join18(artifactDir, "review-round-latest.json");
77409
77603
  const visibleReviews = reviews.map(withoutTurn);
77410
77604
  await writeFile6(artifactPath, `${JSON.stringify({ reviews: visibleReviews, consolidated_findings: consolidatedFindings, reverification }, null, 2)}
77411
77605
  `, { encoding: "utf8" });
@@ -77413,9 +77607,9 @@ async function writeReviewRoundArtifact(artifactDir, reviews, consolidatedFindin
77413
77607
  }
77414
77608
 
77415
77609
  // dist/builtin/workflows/builtin/goal-ledger.ts
77416
- import { randomUUID as randomUUID10 } from "node:crypto";
77610
+ import { randomUUID as randomUUID11 } from "node:crypto";
77417
77611
  import { readFile as readFile3, rename, rm as rm2, writeFile as writeFile7 } from "node:fs/promises";
77418
- import { dirname as dirname11, join as join20 } from "node:path";
77612
+ import { dirname as dirname10, join as join19 } from "node:path";
77419
77613
  import { isDeepStrictEqual } from "node:util";
77420
77614
 
77421
77615
  // dist/builtin/workflows/builtin/goal-reducer.ts
@@ -77653,7 +77847,7 @@ function modelVisibleLedger(ledger) {
77653
77847
  };
77654
77848
  }
77655
77849
  function goalLedgerStatePath(ledgerPath) {
77656
- return join20(dirname11(ledgerPath), LEDGER_STATE_FILENAME);
77850
+ return join19(dirname10(ledgerPath), LEDGER_STATE_FILENAME);
77657
77851
  }
77658
77852
  function appendLifecycleEvent(ledger, event, summary, turn = ledger.turns) {
77659
77853
  ledger.lifecycle.push({
@@ -77729,14 +77923,14 @@ function recoverLegacyExecutionInterruption(ledger) {
77729
77923
  return true;
77730
77924
  }
77731
77925
  async function createGoalLedger(objective, acceptanceCriteria, artifactDir) {
77732
- const ledgerPath = join20(artifactDir, LEDGER_FILENAME);
77926
+ const ledgerPath = join19(artifactDir, LEDGER_FILENAME);
77733
77927
  const existing = await readExistingGoalLedger(ledgerPath);
77734
77928
  if (existing !== undefined) {
77735
77929
  if (recoverLegacyExecutionInterruption(existing))
77736
77930
  await writeGoalLedger(ledgerPath, existing);
77737
77931
  return { ledger: existing, ledgerPath, artifactDir };
77738
77932
  }
77739
- const goalId = randomUUID10();
77933
+ const goalId = randomUUID11();
77740
77934
  const now = new Date().toISOString();
77741
77935
  const ledger = {
77742
77936
  goal_id: goalId,
@@ -77765,7 +77959,7 @@ async function writeGoalLedger(ledgerPath, ledger) {
77765
77959
  const stateContents = `${JSON.stringify(ledger, null, 2)}
77766
77960
  `;
77767
77961
  const statePath = goalLedgerStatePath(ledgerPath);
77768
- const pendingStatePath = `${statePath}.${randomUUID10()}.tmp`;
77962
+ const pendingStatePath = `${statePath}.${randomUUID11()}.tmp`;
77769
77963
  await writeFile7(pendingStatePath, stateContents, { encoding: "utf8" });
77770
77964
  try {
77771
77965
  await rename(pendingStatePath, statePath);
@@ -78228,8 +78422,8 @@ function positiveInteger(value2, fallback) {
78228
78422
  const floored = Math.floor(value2);
78229
78423
  return floored >= 1 ? floored : fallback;
78230
78424
  }
78231
- function forkContinuationOptions(sessionFile) {
78232
- return sessionFile === undefined || sessionFile.length === 0 ? {} : { context: "fork", forkFromSessionFile: sessionFile };
78425
+ function forkContinuationOptions(sessionId) {
78426
+ return sessionId === undefined ? {} : { context: "fork", forkFromSessionId: sessionId };
78233
78427
  }
78234
78428
  function normalizeBranchInput(value2, fallback) {
78235
78429
  const trimmed = value2?.trim();
@@ -78261,7 +78455,7 @@ async function runGoalWorkflow(ctx, options) {
78261
78455
  let latestReviews = [];
78262
78456
  let latestReviewArtifactPaths = [];
78263
78457
  let latestReviewReportPath;
78264
- let previousOrchestratorSessionFile;
78458
+ let previousOrchestratorSessionId;
78265
78459
  const recordedTurns = new Set(ledger.decisions.map((decision) => decision.turn));
78266
78460
  const lastRecordedTurn = Math.max(0, ...recordedTurns);
78267
78461
  for (let turn = 1;turn <= maxTurns && (ledger.status === "active" || turn <= lastRecordedTurn); turn += 1) {
@@ -78271,9 +78465,9 @@ async function runGoalWorkflow(ctx, options) {
78271
78465
  appendLifecycleEvent(ledger, "work_turn_started", "Orchestrator started.", turn);
78272
78466
  await writeGoalLedger(ledgerPath, ledger);
78273
78467
  }
78274
- const orchestratorReceiptPath = join21(artifactDir, "orchestrator-receipt.md");
78275
- const orchestratorForkOptions = forkContinuationOptions(previousOrchestratorSessionFile);
78276
- const orchestratorPrompt = orchestratorForkOptions.forkFromSessionFile === undefined ? renderGoalOrchestratorPrompt({
78468
+ const orchestratorReceiptPath = join20(artifactDir, "orchestrator-receipt.md");
78469
+ const orchestratorForkOptions = forkContinuationOptions(previousOrchestratorSessionId);
78470
+ const orchestratorPrompt = orchestratorForkOptions.forkFromSessionId === undefined ? renderGoalOrchestratorPrompt({
78277
78471
  ledger,
78278
78472
  ledgerPath,
78279
78473
  blockerThreshold,
@@ -78288,7 +78482,7 @@ async function runGoalWorkflow(ctx, options) {
78288
78482
  ...orchestratorModelConfig,
78289
78483
  ...orchestratorForkOptions
78290
78484
  });
78291
- previousOrchestratorSessionFile = orchestrator.sessionFile;
78485
+ previousOrchestratorSessionId = orchestrator.sessionId;
78292
78486
  if (!replayingRecordedTurn) {
78293
78487
  ledger.turns = turn;
78294
78488
  const receiptAlreadyRecorded = ledger.receipts.some((receipt) => receipt.turn === turn && receipt.artifact_path === orchestratorReceiptPath);
@@ -78342,7 +78536,7 @@ async function runGoalWorkflow(ctx, options) {
78342
78536
  const reviewerName = result.name ?? result.stageName;
78343
78537
  const normalizedReviewerName = reviewerName.replace(/-\d+$/u, "");
78344
78538
  const parsed = reviewerContractError === undefined ? parsedReviewDecisionFromResult(result, reviewerName) : { decision: reviewerErrorDecision(reviewerContractError.message), parsed: false, diagnostics: [reviewerContractError.message] };
78345
- const reviewArtifactPath = join21(artifactDir, `review-${artifactSafeName(normalizedReviewerName)}.json`);
78539
+ const reviewArtifactPath = join20(artifactDir, `review-${artifactSafeName(normalizedReviewerName)}.json`);
78346
78540
  const record = reviewDecisionToRecord({
78347
78541
  turn,
78348
78542
  reviewer: normalizedReviewerName,
@@ -78570,7 +78764,7 @@ import { Type as Type17 } from "typebox";
78570
78764
  import { spawnSync as spawnSync3 } from "node:child_process";
78571
78765
  import { mkdirSync as mkdirSync5 } from "node:fs";
78572
78766
  import { tmpdir, userInfo } from "node:os";
78573
- import { join as join22 } from "node:path";
78767
+ import { join as join21 } from "node:path";
78574
78768
  import { Type as Type16 } from "typebox";
78575
78769
  import { createChildProcessEnvironment as createChildProcessEnvironment3 } from "@bastani/atomic";
78576
78770
  var OUTPUT_TYPES = [
@@ -78627,32 +78821,32 @@ function tmpArtifactBase() {
78627
78821
  try {
78628
78822
  user = userInfo().username.replace(/[^A-Za-z0-9._-]/g, "_") || "default";
78629
78823
  } catch {}
78630
- return join22(tmpdir(), `open-claude-design-${user}`);
78824
+ return join21(tmpdir(), `open-claude-design-${user}`);
78631
78825
  }
78632
78826
  function prepareArtifactDir(cwd = process.cwd()) {
78633
78827
  const runId = `${new Date().toISOString().replace(/[:.]/g, "-")}-${Math.random().toString(36).slice(2, 8)}`;
78634
78828
  const tmpCandidates = [
78635
- join22(tmpArtifactBase(), runId),
78636
- join22(tmpdir(), "open-claude-design", runId)
78829
+ join21(tmpArtifactBase(), runId),
78830
+ join21(tmpdir(), "open-claude-design", runId)
78637
78831
  ];
78638
- const candidates = process.env.NODE_ENV === "test" ? tmpCandidates : [join22(cwd, "specs", "design", runId), ...tmpCandidates];
78832
+ const candidates = process.env.NODE_ENV === "test" ? tmpCandidates : [join21(cwd, "specs", "design", runId), ...tmpCandidates];
78639
78833
  for (const candidate of candidates) {
78640
78834
  try {
78641
78835
  mkdirSync5(candidate, { recursive: true });
78642
78836
  return {
78643
78837
  runId,
78644
78838
  artifactDir: candidate,
78645
- previewPath: join22(candidate, "preview.html"),
78646
- specPath: join22(candidate, "spec.html")
78839
+ previewPath: join21(candidate, "preview.html"),
78840
+ specPath: join21(candidate, "spec.html")
78647
78841
  };
78648
78842
  } catch {}
78649
78843
  }
78650
- const fallback = join22(tmpArtifactBase(), runId);
78844
+ const fallback = join21(tmpArtifactBase(), runId);
78651
78845
  return {
78652
78846
  runId,
78653
78847
  artifactDir: fallback,
78654
- previewPath: join22(fallback, "preview.html"),
78655
- specPath: join22(fallback, "spec.html")
78848
+ previewPath: join21(fallback, "preview.html"),
78849
+ specPath: join21(fallback, "spec.html")
78656
78850
  };
78657
78851
  }
78658
78852
  var HTML_PREVIEW_RULES = [
@@ -78970,7 +79164,7 @@ function buildLiveSessionStartPrompt(input) {
78970
79164
 
78971
79165
  // dist/builtin/workflows/builtin/open-claude-design-setup.ts
78972
79166
  import { mkdirSync as mkdirSync6, writeFileSync as writeFileSync3 } from "node:fs";
78973
- import { join as join23 } from "node:path";
79167
+ import { join as join22 } from "node:path";
78974
79168
  var GROUNDED_REPORTING5 = "Before reporting progress, audit each claim against a tool result from this session. Report only work you can point to evidence for; say so explicitly when something is unverified.";
78975
79169
  function renderDiscoveryContext(discovery) {
78976
79170
  return [
@@ -79046,10 +79240,10 @@ var NO_REFERENCES_BRIEF = "Reference discovery was skipped. Generate from the pr
79046
79240
  var DESIGN_CONTEXT_FILENAME = "design-context.md";
79047
79241
  var REFERENCES_BRIEF_FILENAME = "references.md";
79048
79242
  function designContextPath(artifactDir) {
79049
- return join23(artifactDir, DESIGN_CONTEXT_FILENAME);
79243
+ return join22(artifactDir, DESIGN_CONTEXT_FILENAME);
79050
79244
  }
79051
79245
  function referencesBriefPath(artifactDir) {
79052
- return join23(artifactDir, REFERENCES_BRIEF_FILENAME);
79246
+ return join22(artifactDir, REFERENCES_BRIEF_FILENAME);
79053
79247
  }
79054
79248
  function buildReferenceDiscoveryPrompt(args) {
79055
79249
  const siteList = REFERENCE_DESIGN_SITES.map((site, index) => `${index + 1}. ${site.name} — ${site.url}`).join(`
@@ -79075,8 +79269,8 @@ function buildReferenceDiscoveryPrompt(args) {
79075
79269
  [
79076
79270
  "Use the agent-browser skill to open each gallery; if `agent-browser` reports a missing browser executable, follow the bootstrap rules and retry once.",
79077
79271
  "From each gallery, choose 1-3 fitting designs and CLICK INTO each actual live or project-detail page; do not capture only the grid or thumbnail.",
79078
- `Capture motion across the entire page: start \`agent-browser record start ${join23(args.artifactDir, "ref-<site>-<n>.webm")}\`, scroll smoothly in small increments with waits (using repeated \`agent-browser scroll down 600\` or \`agent-browser mouse wheel 600\`) so animations fire and lazy content loads, then run \`agent-browser record stop\`.`,
79079
- `Also run \`agent-browser screenshot ${join23(args.artifactDir, "ref-<site>-<n>.png")} --full\`; this still is the minimum when video is unavailable.`,
79272
+ `Capture motion across the entire page: start \`agent-browser record start ${join22(args.artifactDir, "ref-<site>-<n>.webm")}\`, scroll smoothly in small increments with waits (using repeated \`agent-browser scroll down 600\` or \`agent-browser mouse wheel 600\`) so animations fire and lazy content loads, then run \`agent-browser record stop\`.`,
79273
+ `Also run \`agent-browser screenshot ${join22(args.artifactDir, "ref-<site>-<n>.png")} --full\`; this still is the minimum when video is unavailable.`,
79080
79274
  "Record the actual destination URL, title, and author. For each reference, cite observed layout, typography, color, spacing, and motion traits rather than inferred traits.",
79081
79275
  "Assess fit against DESIGN.md, PRODUCT.md, and the ds-* discovery evidence in the design-context file; prefer on-brand references and flag departures.",
79082
79276
  "Use ask_user_question to ask which reference direction they prefer, offering 2-4 strongest options plus `None of these fit`. If none fit, ask them to provide a reference image, screenshot, URL, or local file path and record the answer.",
@@ -79142,8 +79336,8 @@ function isUiUnavailableRejection(error) {
79142
79336
 
79143
79337
  // dist/builtin/workflows/builtin/open-claude-design-phases.ts
79144
79338
  var GROUNDED_REPORTING6 = "Before reporting progress, audit each claim against a tool result from this session. Report only work you can point to evidence for; say so explicitly when something is unverified.";
79145
- function forkContinuationOptions2(sessionFile) {
79146
- return sessionFile === undefined || sessionFile.length === 0 ? {} : { context: "fork", forkFromSessionFile: sessionFile };
79339
+ function forkContinuationOptions2(sessionId) {
79340
+ return sessionId === undefined ? {} : { context: "fork", forkFromSessionId: sessionId };
79147
79341
  }
79148
79342
  async function refineOpenClaudeDesign(options) {
79149
79343
  const { designContext, prompt, outputType, previewPath, previewFileUrl, browserBootstrapRules, designContextFile, referencesFile, designModelConfig, workflowCwd } = options;
@@ -79181,12 +79375,12 @@ async function refineOpenClaudeDesign(options) {
79181
79375
  }
79182
79376
  async function runLiveReviewSession(options) {
79183
79377
  const { designContext, round, reviewStageName, previewPath, previewFileUrl, browserBootstrapRules, designModelConfig, workflowCwd } = options;
79184
- let sessionFile;
79378
+ let sessionId;
79185
79379
  const start = await designContext.task(`${reviewStageName}-start`, {
79186
79380
  prompt: buildLiveSessionStartPrompt({ previewPath, previewFileUrl, browserBootstrapRules, round }),
79187
79381
  ...designModelConfig
79188
79382
  });
79189
- sessionFile = start.sessionFile;
79383
+ sessionId = start.sessionId;
79190
79384
  for (let index = 1;; index += 1) {
79191
79385
  const event = await designContext.tool(`live-poll-${round}-${index}`, { round, index }, async ({ signal }) => pollLiveEvent({ workflowCwd, signal }));
79192
79386
  if (event.type === "exit")
@@ -79199,9 +79393,9 @@ async function runLiveReviewSession(options) {
79199
79393
  const response = await designContext.task(`live-${event.type}-${round}-${index}`, {
79200
79394
  prompt: buildLiveEventPrompt({ event, previewPath }),
79201
79395
  ...designModelConfig,
79202
- ...forkContinuationOptions2(sessionFile)
79396
+ ...forkContinuationOptions2(sessionId)
79203
79397
  });
79204
- sessionFile = response.sessionFile ?? sessionFile;
79398
+ sessionId = response.sessionId ?? sessionId;
79205
79399
  const status = replyTokenFor(event);
79206
79400
  await designContext.tool(`live-reply-${round}-${index}`, { round, index, eventId: event.id, status }, async ({ signal }) => replyLiveEvent({ workflowCwd, event, status, signal }));
79207
79401
  }
@@ -79619,7 +79813,7 @@ import { Type as Type19 } from "typebox";
79619
79813
 
79620
79814
  // dist/builtin/workflows/builtin/loop-until-done-runner.ts
79621
79815
  import { mkdir as mkdir4, writeFile as writeFile8 } from "node:fs/promises";
79622
- import { join as join24 } from "node:path";
79816
+ import { join as join23 } from "node:path";
79623
79817
  import { Type as Type18 } from "typebox";
79624
79818
 
79625
79819
  // dist/builtin/workflows/builtin/loop-until-done-prompts.ts
@@ -79789,18 +79983,18 @@ async function writeLedger(path, task, maxIterations, status, entries) {
79789
79983
  }
79790
79984
  async function runLoopUntilDone(ctx) {
79791
79985
  const artifactDir = await stableArtifactRoot(ctx, "loop-until-done");
79792
- const iterationsDir = join24(artifactDir, "iterations");
79793
- const evaluationsDir = join24(artifactDir, "evaluations");
79986
+ const iterationsDir = join23(artifactDir, "iterations");
79987
+ const evaluationsDir = join23(artifactDir, "evaluations");
79794
79988
  await mkdir4(iterationsDir, { recursive: true });
79795
79989
  await mkdir4(evaluationsDir, { recursive: true });
79796
- const ledgerPath = join24(artifactDir, "progress-ledger.json");
79990
+ const ledgerPath = join23(artifactDir, "progress-ledger.json");
79797
79991
  const entries = [];
79798
79992
  const iterationArtifactPaths = [];
79799
79993
  const evaluationArtifactPaths = [];
79800
79994
  await writeLedger(ledgerPath, ctx.inputs.prompt, ctx.inputs.max_iterations, "active", entries);
79801
79995
  for (let iteration = 1;iteration <= ctx.inputs.max_iterations; iteration += 1) {
79802
- const iterationPath = join24(iterationsDir, `iteration-${iteration}.md`);
79803
- const evaluationPath = join24(evaluationsDir, `evaluation-${iteration}.json`);
79996
+ const iterationPath = join23(iterationsDir, `iteration-${iteration}.md`);
79997
+ const evaluationPath = join23(evaluationsDir, `evaluation-${iteration}.json`);
79804
79998
  iterationArtifactPaths.push(iterationPath);
79805
79999
  evaluationArtifactPaths.push(evaluationPath);
79806
80000
  await ctx.task(`iteration-${iteration}`, {
@@ -79849,7 +80043,7 @@ async function runLoopUntilDone(ctx) {
79849
80043
  await writeLedger(ledgerPath, ctx.inputs.prompt, ctx.inputs.max_iterations, decision.done ? "complete" : "active", entries);
79850
80044
  if (decision.done) {
79851
80045
  const report = progressReport(entries);
79852
- const resultPath = join24(artifactDir, "result.md");
80046
+ const resultPath = join23(artifactDir, "result.md");
79853
80047
  const final = await ctx.task("completion-summary", {
79854
80048
  prompt: renderCompletionPrompt({ task: ctx.inputs.prompt, ledgerPath, iterationPath }),
79855
80049
  context: "fresh",
@@ -79948,7 +80142,7 @@ import { Type as Type21 } from "typebox";
79948
80142
 
79949
80143
  // dist/builtin/workflows/builtin/ralph-core.ts
79950
80144
  import { mkdir as mkdir5, writeFile as writeFile9 } from "node:fs/promises";
79951
- import { dirname as dirname12, join as join25 } from "node:path";
80145
+ import { dirname as dirname11, join as join24 } from "node:path";
79952
80146
  import { Type as Type20 } from "typebox";
79953
80147
  // dist/builtin/workflows/builtin/ralph-review-gate.ts
79954
80148
  function reviewDecisionApproved(decision) {
@@ -80055,11 +80249,11 @@ function slugifyResearchTopic(prompt) {
80055
80249
  }
80056
80250
  function defaultResearchPath(prompt, now = new Date) {
80057
80251
  const date = now.toISOString().slice(0, 10);
80058
- return join25(DEFAULT_RESEARCH_DIR, `${date}-${slugifyResearchTopic(prompt)}.md`);
80252
+ return join24(DEFAULT_RESEARCH_DIR, `${date}-${slugifyResearchTopic(prompt)}.md`);
80059
80253
  }
80060
80254
  async function createImplementationNotesFile(prompt, runId) {
80061
80255
  const notesDir = await createWorkflowArtifactDirectory(runId);
80062
- const notesPath = join25(notesDir, IMPLEMENTATION_NOTES_FILENAME);
80256
+ const notesPath = join24(notesDir, IMPLEMENTATION_NOTES_FILENAME);
80063
80257
  const initialNotes = [
80064
80258
  "# Implementation Notes",
80065
80259
  "",
@@ -80080,7 +80274,7 @@ async function createImplementationNotesFile(prompt, runId) {
80080
80274
  }
80081
80275
  async function createQaEvidenceVideoPath(runId) {
80082
80276
  const qaDir = await createWorkflowArtifactDirectory(runId);
80083
- return join25(qaDir, QA_E2E_VIDEO_FILENAME);
80277
+ return join24(qaDir, QA_E2E_VIDEO_FILENAME);
80084
80278
  }
80085
80279
  function renderQaE2eVideoGuidance(qaVideoPath) {
80086
80280
  return [
@@ -80146,7 +80340,7 @@ function artifactSafeName2(value2) {
80146
80340
  return safe.length > 0 ? safe : "artifact";
80147
80341
  }
80148
80342
  async function writeJsonArtifact(path, content) {
80149
- await mkdir5(dirname12(path), { recursive: true });
80343
+ await mkdir5(dirname11(path), { recursive: true });
80150
80344
  await writeFile9(path, `${JSON.stringify(content, null, 2)}
80151
80345
  `, {
80152
80346
  encoding: "utf8"
@@ -80156,8 +80350,8 @@ async function writeJsonArtifact(path, content) {
80156
80350
  function compactReviewReport(path) {
80157
80351
  return path === undefined ? "No reviewer artifact was produced." : `Latest review round artifact: ${path}`;
80158
80352
  }
80159
- function forkContinuationOptions3(sessionFile) {
80160
- return sessionFile === undefined || sessionFile.length === 0 ? {} : { context: "fork", forkFromSessionFile: sessionFile };
80353
+ function forkContinuationOptions3(sessionId) {
80354
+ return sessionId === undefined ? {} : { context: "fork", forkFromSessionId: sessionId };
80161
80355
  }
80162
80356
  function renderResearchPromptRefinementPrompt(args) {
80163
80357
  return taggedPrompt4([
@@ -80216,7 +80410,7 @@ function renderResearchPrompt(args) {
80216
80410
 
80217
80411
  // dist/builtin/workflows/builtin/ralph-runner.ts
80218
80412
  import { existsSync as existsSync6 } from "node:fs";
80219
- import { join as join26, resolve as resolve13 } from "node:path";
80413
+ import { join as join25, resolve as resolve12 } from "node:path";
80220
80414
 
80221
80415
  // dist/builtin/workflows/builtin/ralph-reviewer-prompt.ts
80222
80416
  function renderRalphReviewerPrompt(args) {
@@ -80423,21 +80617,21 @@ async function runRalphWorkflow(ctx, options) {
80423
80617
  let finalPrReport;
80424
80618
  const workflowCwdContext = workflowCwdContextSection(workflowStartCwd);
80425
80619
  const workflowPrompt = prompt;
80426
- const workflowResearchPath = resolve13(workflowStartCwd, defaultResearchPath(workflowPrompt));
80620
+ const workflowResearchPath = resolve12(workflowStartCwd, defaultResearchPath(workflowPrompt));
80427
80621
  const implementationNotesPath = await createImplementationNotesFile(workflowPrompt, runId);
80428
80622
  const qaVideoPath = await createQaEvidenceVideoPath(runId);
80429
80623
  const artifactDir = await createWorkflowArtifactDirectory(runId);
80430
80624
  let approved = false;
80431
80625
  let iterationsCompleted = 0;
80432
- let previousResearchPromptRefinementSessionFile;
80626
+ let previousResearchPromptRefinementSessionId;
80433
80627
  const convergenceEntries = [];
80434
- let previousResearchSessionFile;
80435
- let previousOrchestratorSessionFile;
80628
+ let previousResearchSessionId;
80629
+ let previousOrchestratorSessionId;
80436
80630
  for (let iteration = 1;iteration <= maxLoops; iteration += 1) {
80437
80631
  iterationsCompleted = iteration;
80438
- const researchPromptRefinementForkOptions = forkContinuationOptions3(previousResearchPromptRefinementSessionFile);
80632
+ const researchPromptRefinementForkOptions = forkContinuationOptions3(previousResearchPromptRefinementSessionId);
80439
80633
  const researchPromptRefinement = await ctx.task(`research-prompt-refinement-${iteration}`, {
80440
- prompt: researchPromptRefinementForkOptions.forkFromSessionFile === undefined ? renderResearchPromptRefinementPrompt({
80634
+ prompt: researchPromptRefinementForkOptions.forkFromSessionId === undefined ? renderResearchPromptRefinementPrompt({
80441
80635
  request: workflowPrompt,
80442
80636
  acceptanceCriteria,
80443
80637
  workflowCwdContext,
@@ -80447,11 +80641,11 @@ async function runRalphWorkflow(ctx, options) {
80447
80641
  ...promptEngineerModelConfig,
80448
80642
  ...researchPromptRefinementForkOptions
80449
80643
  });
80450
- previousResearchPromptRefinementSessionFile = researchPromptRefinement.sessionFile;
80644
+ previousResearchPromptRefinementSessionId = researchPromptRefinement.sessionId;
80451
80645
  finalPlan = researchPromptRefinement.text;
80452
- const researchForkOptions = forkContinuationOptions3(previousResearchSessionFile);
80646
+ const researchForkOptions = forkContinuationOptions3(previousResearchSessionId);
80453
80647
  const research = await ctx.task(`research-${iteration}`, {
80454
- prompt: researchForkOptions.forkFromSessionFile === undefined ? renderResearchPrompt({
80648
+ prompt: researchForkOptions.forkFromSessionId === undefined ? renderResearchPrompt({
80455
80649
  transformedResearchQuestion: researchPromptRefinement.text,
80456
80650
  prompt: workflowPrompt,
80457
80651
  acceptanceCriteria,
@@ -80467,14 +80661,14 @@ async function runRalphWorkflow(ctx, options) {
80467
80661
  ...researchModelConfig,
80468
80662
  ...researchForkOptions
80469
80663
  });
80470
- previousResearchSessionFile = research.sessionFile;
80664
+ previousResearchSessionId = research.sessionId;
80471
80665
  finalResearch = research.text || `Research artifact: ${workflowResearchPath}`;
80472
80666
  const researchPath = workflowResearchPath;
80473
80667
  finalResearchPath = researchPath;
80474
80668
  finalPlanPath = researchPath;
80475
- const orchestratorReportPath = join26(artifactDir, "orchestrator-report.md");
80476
- const orchestratorForkOptions = forkContinuationOptions3(previousOrchestratorSessionFile);
80477
- const orchestratorPrompt = orchestratorForkOptions.forkFromSessionFile === undefined ? taggedPrompt4([
80669
+ const orchestratorReportPath = join25(artifactDir, "orchestrator-report.md");
80670
+ const orchestratorForkOptions = forkContinuationOptions3(previousOrchestratorSessionId);
80671
+ const orchestratorPrompt = orchestratorForkOptions.forkFromSessionId === undefined ? taggedPrompt4([
80478
80672
  ["acceptance_criteria", keepContext(acceptanceCriteria)],
80479
80673
  ["literal_contract", LITERAL_OBJECTIVE_CONTRACT],
80480
80674
  ["acceptance_matrix", ACCEPTANCE_MATRIX_CONTRACT],
@@ -80553,7 +80747,7 @@ Read it before implementation or delegation because it is the primary current im
80553
80747
  ...orchestratorModelConfig2,
80554
80748
  ...orchestratorForkOptions
80555
80749
  });
80556
- previousOrchestratorSessionFile = orchestrator.sessionFile;
80750
+ previousOrchestratorSessionId = orchestrator.sessionId;
80557
80751
  finalResult = orchestrator.text || `Orchestrator report artifact: ${orchestratorReportPath}`;
80558
80752
  const reviewPrompt = renderRalphReviewerPrompt({
80559
80753
  workflowPrompt,
@@ -80608,7 +80802,7 @@ Read it before implementation or delegation because it is the primary current im
80608
80802
  diagnostics: parsed.diagnostics,
80609
80803
  allowFinalActionRemaining: createPr
80610
80804
  });
80611
- const artifactPath = join26(artifactDir, `review-${artifactSafeName2(reviewer)}.json`);
80805
+ const artifactPath = join25(artifactDir, `review-${artifactSafeName2(reviewer)}.json`);
80612
80806
  await writeJsonArtifact(artifactPath, {
80613
80807
  reviewer,
80614
80808
  decision: parsed.decision,
@@ -80664,7 +80858,7 @@ Read it before implementation or delegation because it is the primary current im
80664
80858
  usage: fold_usage([orchestrator, ...reviews, ...reverifyResults])
80665
80859
  }));
80666
80860
  }
80667
- latestReviewReportPath = await writeJsonArtifact(join26(artifactDir, "review-round-latest.json"), {
80861
+ latestReviewReportPath = await writeJsonArtifact(join25(artifactDir, "review-round-latest.json"), {
80668
80862
  convergence_decision: roundConvergenceDecision,
80669
80863
  convergence: convergenceEntries,
80670
80864
  consolidated_findings: reverified.batch,
@@ -80845,7 +81039,7 @@ import { Type as Type23 } from "typebox";
80845
81039
 
80846
81040
  // dist/builtin/workflows/builtin/tournament-runner.ts
80847
81041
  import { mkdir as mkdir6, readFile as readFile4, writeFile as writeFile10 } from "node:fs/promises";
80848
- import { join as join27, isAbsolute as isAbsolute11, relative as relative5, resolve as resolve14 } from "node:path";
81042
+ import { join as join26, isAbsolute as isAbsolute11, relative as relative5, resolve as resolve13 } from "node:path";
80849
81043
  import { Type as Type22 } from "typebox";
80850
81044
 
80851
81045
  // dist/builtin/workflows/builtin/selection-math.ts
@@ -81060,8 +81254,8 @@ function criterionSlug(id) {
81060
81254
  }
81061
81255
  function judgeArtifactPath(judgesDir, job, criterionIndex) {
81062
81256
  const filename = `judge-${job.a}-${job.b}-c${criterionIndex}-${criterionSlug(job.criterionId)}-r${job.rep}.json`;
81063
- const root = resolve14(judgesDir);
81064
- const path = resolve14(judgesDir, filename);
81257
+ const root = resolve13(judgesDir);
81258
+ const path = resolve13(judgesDir, filename);
81065
81259
  const fromRoot = relative5(root, path);
81066
81260
  if (fromRoot.startsWith("..") || isAbsolute11(fromRoot)) {
81067
81261
  throw new Error(`tournament: judge artifact escaped its directory: ${path}`);
@@ -81112,16 +81306,16 @@ function combineUsage(totals) {
81112
81306
  }
81113
81307
  async function runTournament(ctx) {
81114
81308
  const artifactDir = await stableArtifactRoot(ctx, "tournament");
81115
- const attemptsDir = join27(artifactDir, "attempts");
81309
+ const attemptsDir = join26(artifactDir, "attempts");
81116
81310
  const numAttempts = ctx.inputs.num_attempts ?? 4;
81117
81311
  const maxConcurrency = ctx.inputs.max_concurrency ?? 4;
81118
81312
  const nEvaluations = ctx.inputs.n_evaluations ?? 2;
81119
81313
  const pivotCount = ctx.inputs.pivots ?? 1;
81120
81314
  const seed = ctx.inputs.seed ?? 0;
81121
- const judgesDir = join27(artifactDir, "judges");
81315
+ const judgesDir = join26(artifactDir, "judges");
81122
81316
  await mkdir6(attemptsDir, { recursive: true });
81123
81317
  await mkdir6(judgesDir, { recursive: true });
81124
- const attemptArtifactPaths = Array.from({ length: numAttempts }, (_, index) => join27(attemptsDir, `attempt-${index + 1}.md`));
81318
+ const attemptArtifactPaths = Array.from({ length: numAttempts }, (_, index) => join26(attemptsDir, `attempt-${index + 1}.md`));
81125
81319
  const models = ctx.inputs.models;
81126
81320
  const attemptResults = await ctx.parallel(attemptArtifactPaths.map((path, index) => ({
81127
81321
  name: `attempt-${index + 1}`,
@@ -81286,7 +81480,7 @@ The previous report was invalid. Return the required JSON schema exactly once.`,
81286
81480
  const outputRanking = ranking.map(({ label, meanPreference }) => ({ label, meanPreference }));
81287
81481
  const budgetPivots = Math.min(pivotCount, entrants.length);
81288
81482
  const comparisonBudget = (entrants.length + budgetPivots * (entrants.length - budgetPivots) + budgetPivots * (budgetPivots - 1) / 2) * criteria.length * nEvaluations;
81289
- const comparisonPath = join27(artifactDir, "comparisons.json");
81483
+ const comparisonPath = join26(artifactDir, "comparisons.json");
81290
81484
  const assignment = modelAssignment(entrants, models);
81291
81485
  const phaseUsage = {
81292
81486
  attempts: fold_usage(attemptResults),
@@ -81322,7 +81516,7 @@ The previous report was invalid. Return the required JSON schema exactly once.`,
81322
81516
  await writeLedger(fold_usage([]));
81323
81517
  const winner = ranking[0];
81324
81518
  const winnerEntrant = entrants[winner.index];
81325
- const resultPath = join27(artifactDir, "winner.md");
81519
+ const resultPath = join26(artifactDir, "winner.md");
81326
81520
  const reducer = await ctx.task("comparisons-reducer", {
81327
81521
  prompt: renderComparisonsReducerPrompt({
81328
81522
  task: ctx.inputs.prompt,
@@ -81461,7 +81655,7 @@ function createRegistry(initial = []) {
81461
81655
 
81462
81656
  // dist/builtin/workflows/src/extension/discovery-loaders.ts
81463
81657
  import { readdir as readdir2, stat as stat2 } from "node:fs/promises";
81464
- import { extname, isAbsolute as isAbsolute12, join as join29, resolve as resolve15 } from "node:path";
81658
+ import { extname, isAbsolute as isAbsolute12, join as join29, resolve as resolve14 } from "node:path";
81465
81659
 
81466
81660
  // ../../node_modules/jiti/lib/jiti-static.mjs
81467
81661
  var import_jiti = __toESM(require_jiti(), 1);
@@ -81500,7 +81694,6 @@ __export(exports_sdk_surface, {
81500
81694
  JOURNAL_TABLES: () => JOURNAL_TABLES,
81501
81695
  JournalCasConflictError: () => JournalCasConflictError,
81502
81696
  JournalClosedError: () => JournalClosedError,
81503
- JournalConfigurationError: () => JournalConfigurationError,
81504
81697
  JournalCounterRangeError: () => JournalCounterRangeError,
81505
81698
  JournalError: () => JournalError,
81506
81699
  JournalInvalidTextError: () => JournalInvalidTextError,
@@ -82026,6 +82219,30 @@ function registerRunJournalConformance(runner, name, open, observeRead) {
82026
82219
  });
82027
82220
  });
82028
82221
  }
82222
+ // dist/builtin/workflows/src/durable/journal/sqlite-run-journal.ts
82223
+ import { dirname as dirname12, join as join27 } from "node:path";
82224
+ import { getAgentDir as getAgentDir5, openNodeSqliteDatabase, validateStoragePrefix, wrapNodeSqliteDatabase } from "@bastani/atomic";
82225
+ function workflowJournalPath() {
82226
+ const override = process.env.ATOMIC_WORKFLOW_JOURNAL_PATH;
82227
+ return override !== undefined && override.length > 0 ? override : join27(dirname12(getAgentDir5()), "workflows", "journal.sqlite");
82228
+ }
82229
+ async function openSqlRunJournal(source = workflowJournalPath(), options = {}) {
82230
+ validateStoragePrefix(options.prefix);
82231
+ const database = typeof source === "string" ? await openNodeSqliteDatabase(source) : wrapNodeSqliteDatabase(source);
82232
+ try {
82233
+ const journal = await SqlRunJournal.open(database, options);
82234
+ const close = journal.close.bind(journal);
82235
+ let closing;
82236
+ journal.close = () => {
82237
+ closing ??= close().then(() => database.close());
82238
+ return closing;
82239
+ };
82240
+ return journal;
82241
+ } catch (error) {
82242
+ await database.close();
82243
+ throw error;
82244
+ }
82245
+ }
82029
82246
  // dist/builtin/workflows/src/extension/wiring.ts
82030
82247
  import { join as join28 } from "node:path";
82031
82248
  import {
@@ -82409,7 +82626,7 @@ function makeWorkflowStageOrchestrationContext(meta, pi) {
82409
82626
  const sendMessage = pi.sendMessage;
82410
82627
  if (!sendMessage)
82411
82628
  throw new Error("atomic-workflows: main-chat late-message route is unavailable");
82412
- return routeThroughStaleContextGuard(() => sendMessage(message, options));
82629
+ return routeThroughStaleContextGuard(() => outsideWorkflowExecutions(() => sendMessage(message, options)));
82413
82630
  },
82414
82631
  routeMessages(messages, options) {
82415
82632
  const intercomRoute = emitLateIntercomRoute(pi, meta, messages, options, true);
@@ -82417,15 +82634,15 @@ function makeWorkflowStageOrchestrationContext(meta, pi) {
82417
82634
  return intercomRoute;
82418
82635
  const sendMessages = pi.sendMessages;
82419
82636
  if (sendMessages)
82420
- return routeThroughStaleContextGuard(() => sendMessages(messages, options));
82637
+ return routeThroughStaleContextGuard(() => outsideWorkflowExecutions(() => sendMessages(messages, options)));
82421
82638
  const sendMessage = pi.sendMessage;
82422
82639
  if (!sendMessage)
82423
82640
  throw new Error("atomic-workflows: main-chat late-message route is unavailable");
82424
- return (async () => {
82641
+ return outsideWorkflowExecutions(async () => {
82425
82642
  for (const [index, message] of messages.entries()) {
82426
82643
  await sendMessage(message, index === 0 ? options : { deliverAs: "followUp" });
82427
82644
  }
82428
- })();
82645
+ });
82429
82646
  }
82430
82647
  }
82431
82648
  };
@@ -82860,7 +83077,7 @@ async function loadFromPaths(pathsOrMap, kind, baseCwd, diagnostics, getWorkflow
82860
83077
  const all = [];
82861
83078
  const entries = Array.isArray(pathsOrMap) ? pathsOrMap.map((p) => ({ rawPath: p })) : Object.entries(pathsOrMap).map(([name, p]) => ({ rawPath: p, configuredName: name }));
82862
83079
  for (const { rawPath, configuredName } of entries) {
82863
- const absPath = isAbsolute12(rawPath) ? rawPath : resolve15(baseCwd, rawPath);
83080
+ const absPath = isAbsolute12(rawPath) ? rawPath : resolve14(baseCwd, rawPath);
82864
83081
  let pathStats;
82865
83082
  try {
82866
83083
  pathStats = await stat2(absPath);
@@ -82892,7 +83109,7 @@ function workflowAgentDirs2(options) {
82892
83109
  const homeDir = options.homeDir;
82893
83110
  return [join30(homeDir, CONFIG_DIR_NAME3, "agent")];
82894
83111
  }
82895
- return [getAgentDir5()];
83112
+ return [getAgentDir6()];
82896
83113
  }
82897
83114
  function validateConfig2(config) {
82898
83115
  if (config === null || typeof config !== "object") {
@@ -83239,7 +83456,7 @@ async function discardUnadmittedRun(runId, activeStore) {
83239
83456
  activeStore.removeRun(runId);
83240
83457
  const handle = backend.getWorkflow(runId);
83241
83458
  if (handle?.status === "running") {
83242
- await backend.setWorkflowStatus(runId, "failed", handle.pendingPrompts, false);
83459
+ await backend.commitWorkflowStatus(runId, "failed", handle.pendingPrompts, false);
83243
83460
  }
83244
83461
  const deleted = await backend.deleteWorkflowIfInactive(runId);
83245
83462
  if (!deleted.ok && deleted.reason !== "not_found") {
@@ -83612,23 +83829,24 @@ function createDurableResumeRuntime(deps) {
83612
83829
  try {
83613
83830
  await backend.hydrateResumableWorkflows();
83614
83831
  await hydrateStoredWorkflowCandidates(backend);
83615
- return listOpenableCompletedWorkflows(backend);
83832
+ return await listOpenableCompletedWorkflows(backend, deps.adapters?.sessionStore);
83616
83833
  } finally {
83617
83834
  purgeSuppressedWorkflowRuns(backend, deps.store, deps.toolControlRegistry);
83618
83835
  }
83619
83836
  });
83620
83837
  },
83621
- openCompletedDurableWorkflow(workflowId, catalog) {
83838
+ async openCompletedDurableWorkflow(workflowId, catalog) {
83622
83839
  const finish = workflowObservationRuntime(deps.store).beginRecovery();
83623
83840
  try {
83624
83841
  const backend = selectedBackend(workflowId);
83625
83842
  const entry = resolveCatalogEntry(workflowId, catalog ?? []);
83626
83843
  const handle = backend.getWorkflow(entry?.workflowId ?? workflowId);
83627
- return openCompletedDurableWorkflow(workflowId, {
83844
+ return await openCompletedDurableWorkflow(workflowId, {
83628
83845
  durableBackend: backend,
83629
83846
  store: deps.store,
83630
83847
  stageControlRegistry: deps.stageControlRegistry,
83631
83848
  adapters: deps.adapters,
83849
+ sessionStore: deps.adapters?.sessionStore,
83632
83850
  cwd: handle?.workflowCwd ?? handle?.invocationCwd ?? deps.runtimeCwd,
83633
83851
  defaultSessionDir: deps.resolveDefaultStageSessionDir?.(),
83634
83852
  beforeRestore: deps.beforeRestoreCompleted
@@ -83669,7 +83887,11 @@ function createExtensionRuntime(opts = {}) {
83669
83887
  const presetBackend = opts.journal === undefined ? availableStoreDurableBackendOverride(activeStore) : undefined;
83670
83888
  const backendRef = { current: presetBackend };
83671
83889
  let ready;
83672
- const ensureReady = () => ready ??= (presetBackend === undefined ? initializeDurableBackend({ cwd: runtimeCwd, journal: opts.journal }) : Promise.resolve(presetBackend)).then((backend) => {
83890
+ const ensureReady = () => ready ??= (presetBackend === undefined ? initializeDurableBackend({
83891
+ cwd: runtimeCwd,
83892
+ journal: opts.journal,
83893
+ projectTrusted: opts.isProjectTrusted?.()
83894
+ }) : Promise.resolve(presetBackend)).then((backend) => {
83673
83895
  backendRef.current = backend;
83674
83896
  bindStoreDurableBackend(activeStore, backend);
83675
83897
  return backend;
@@ -84861,12 +85083,21 @@ function durableWorkflowHeartbeatAnchorStore(store) {
84861
85083
  function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
84862
85084
  const { resolveHostCwd, resolveLiveModelContext } = options;
84863
85085
  const { store, stageUiBroker, cancellationRegistry, jobs, stageControlRegistry, toolControlRegistry } = options.runState ?? currentWorkflowSessionRunState();
84864
- const scopedRunOptions = { store, jobs, stageControlRegistry, toolControlRegistry, stageUiBroker };
85086
+ let projectTrusted;
85087
+ const scopedRunOptions = {
85088
+ store,
85089
+ jobs,
85090
+ stageControlRegistry,
85091
+ toolControlRegistry,
85092
+ stageUiBroker,
85093
+ isProjectTrusted: () => projectTrusted ?? pi.getResourceLoaderInheritanceSnapshot?.()?.projectTrusted ?? true
85094
+ };
84865
85095
  let contextCwd;
84866
85096
  const resolveCwd = () => resolveHostCwd?.() ?? contextCwd ?? pi.sessionManager?.getCwd?.() ?? process.cwd();
84867
85097
  let detachHumanInput;
84868
85098
  pi.on?.("session_start", (_event, ctx) => {
84869
85099
  contextCwd = ctx?.cwd ?? ctx?.sessionManager?.getCwd?.();
85100
+ projectTrusted = ctx?.isProjectTrusted?.();
84870
85101
  detachHumanInput?.();
84871
85102
  detachHumanInput = ctx === undefined ? undefined : bindWorkflowHumanInput(store, ctx, stageUiBroker);
84872
85103
  if (ctx)
@@ -84922,7 +85153,7 @@ function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
84922
85153
  registerLifecycleNoticeRenderer({ rendererHost: pi, registerMessageRenderer });
84923
85154
  registerHilAnswerNoticeRenderer({ rendererHost: pi, registerMessageRenderer });
84924
85155
  registerWorkflowHeartbeatRenderer({ rendererHost: pi, registerMessageRenderer });
84925
- const sendWorkflowNotificationMessage = typeof pi.sendMessage === "function" ? (message, options) => pi.sendMessage(message, options) : undefined;
85156
+ const sendWorkflowNotificationMessage = typeof pi.sendMessage === "function" ? (message, options) => outsideWorkflowExecutions(() => pi.sendMessage(message, options)) : undefined;
84926
85157
  const reinstallLifecycleNotifications = () => {
84927
85158
  lifecycleNotificationsUnsubscribe?.();
84928
85159
  lifecycleNotificationsUnsubscribe = null;
@@ -85035,7 +85266,7 @@ function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
85035
85266
  prepareCompletedDurable() {
85036
85267
  return runtimeRef.current.prepareCompletedDurable?.() ?? Promise.resolve([]);
85037
85268
  },
85038
- openCompletedDurableWorkflow(workflowId, catalog) {
85269
+ async openCompletedDurableWorkflow(workflowId, catalog) {
85039
85270
  const open = runtimeRef.current.openCompletedDurableWorkflow;
85040
85271
  if (open === undefined) {
85041
85272
  return {
@@ -85048,8 +85279,9 @@ function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
85048
85279
  }
85049
85280
  };
85050
85281
  function runtimeForContext(ctx) {
85282
+ const contextTrusted = ctx?.isProjectTrusted?.();
85051
85283
  const models = workflowModelCatalogFromContext(ctx, resolveLiveModelContext);
85052
- if (models === undefined && !ctx?.generateWorkflowSummary)
85284
+ if (models === undefined && !ctx?.generateWorkflowSummary && contextTrusted === undefined)
85053
85285
  return runtimeProxy;
85054
85286
  return createExtensionRuntime({
85055
85287
  registry: runtimeRef.current.registry,
@@ -85058,6 +85290,7 @@ function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
85058
85290
  adapters,
85059
85291
  cancellation: cancellationRegistry,
85060
85292
  ...scopedRunOptions,
85293
+ isProjectTrusted: () => contextTrusted ?? scopedRunOptions.isProjectTrusted(),
85061
85294
  persistence: persistenceRef.current,
85062
85295
  mcp: mcpPort,
85063
85296
  config: runtimeConfigRef.current,
@@ -85306,6 +85539,7 @@ function createWorkflowExtensionRuntimeState(pi, adapters, options = {}) {
85306
85539
  reinstallWorkflowHeartbeatScheduler();
85307
85540
  },
85308
85541
  updateHostStageSessionDir(sessionManager) {
85542
+ adapters.sessionStore = sessionManager?.getSessionStore?.();
85309
85543
  try {
85310
85544
  hostStageSessionDir.current = sessionManager?.usesDefaultSessionDir?.() === false ? sessionManager.getSessionDir?.() : undefined;
85311
85545
  } catch {
@@ -86036,12 +86270,13 @@ function postMortemDepsForRun(runId, deps) {
86036
86270
  return {
86037
86271
  registry: deps.stageControlRegistry ?? stageControlRegistry,
86038
86272
  adapters: deps.adapters,
86273
+ sessionStore: deps.adapters.sessionStore,
86039
86274
  cwd: resolveStageCwd(runId, deps.store ?? store),
86040
86275
  defaultSessionDir: deps.resolveDefaultStageSessionDir()
86041
86276
  };
86042
86277
  }
86043
86278
  function createPostMortemHandleResolver(deps) {
86044
- return (runId, stageId) => {
86279
+ return async (runId, stageId) => {
86045
86280
  const run = readGraphStoreSnapshot(deps.store ?? store).runs.find((candidate) => candidate.id === runId);
86046
86281
  const stage = run?.stages.find((candidate) => candidate.id === stageId);
86047
86282
  if (stage === undefined)
@@ -90155,9 +90390,10 @@ function registerWorkflowMessageRenderers(pi) {
90155
90390
  registerInlineFormRenderer(pi, deriveGraphTheme({}));
90156
90391
  registerChatSurfaceRenderer(pi, deriveGraphTheme({}));
90157
90392
  }
90158
- function buildWorkflowOverlay(pi, owner, resolvePostMortemHandle) {
90393
+ function buildWorkflowOverlay(pi, owner, resolvePostMortemHandle, resolveSessionStore) {
90159
90394
  return buildGraphOverlayAdapter(pi, owner.store, {
90160
90395
  resolvePostMortemHandle,
90396
+ resolveSessionStore,
90161
90397
  stageControlRegistry: owner.stageControlRegistry,
90162
90398
  stageUiBroker: owner.stageUiBroker
90163
90399
  });
@@ -90236,7 +90472,7 @@ function factory(pi) {
90236
90472
  registerExtensionContextRetirementEffect3(ctx, disposeCompletedRoutes);
90237
90473
  registerExtensionContextRetirementEffect3(ctx, disposePendingRoutes);
90238
90474
  });
90239
- const overlay = buildWorkflowOverlay(pi, owner, postMortemHandleResolver);
90475
+ const overlay = buildWorkflowOverlay(pi, owner, postMortemHandleResolver, () => adapters.sessionStore);
90240
90476
  const workflowCommands = new Map;
90241
90477
  const storeWidgetRef = { current: null };
90242
90478
  const intercomControlRef = { current: null };