@proofoftech/flowsafe 0.34.0 → 0.36.0

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 (177) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/README.md +15 -3
  3. package/dist/answer-schema.d.ts +30 -0
  4. package/dist/answer-schema.d.ts.map +1 -0
  5. package/dist/answer-schema.js +311 -0
  6. package/dist/answer-schema.js.map +1 -0
  7. package/dist/approval-api/answer-schema.d.ts +2 -0
  8. package/dist/approval-api/answer-schema.d.ts.map +1 -0
  9. package/dist/approval-api/answer-schema.js +3 -0
  10. package/dist/approval-api/answer-schema.js.map +1 -0
  11. package/dist/approval-api/d1-store.d.ts +3 -16
  12. package/dist/approval-api/d1-store.d.ts.map +1 -1
  13. package/dist/approval-api/d1-store.js +117 -33
  14. package/dist/approval-api/d1-store.js.map +1 -1
  15. package/dist/approval-api/grants.d.ts +2 -3
  16. package/dist/approval-api/grants.d.ts.map +1 -1
  17. package/dist/approval-api/grants.js +5 -3
  18. package/dist/approval-api/grants.js.map +1 -1
  19. package/dist/approval-api/human-notifications.d.ts +34 -0
  20. package/dist/approval-api/human-notifications.d.ts.map +1 -0
  21. package/dist/approval-api/human-notifications.js +160 -0
  22. package/dist/approval-api/human-notifications.js.map +1 -0
  23. package/dist/approval-api/index.d.ts +3 -1
  24. package/dist/approval-api/index.d.ts.map +1 -1
  25. package/dist/approval-api/index.js +1 -0
  26. package/dist/approval-api/index.js.map +1 -1
  27. package/dist/approval-api/retention.d.ts +3 -1
  28. package/dist/approval-api/retention.d.ts.map +1 -1
  29. package/dist/approval-api/retention.js +21 -1
  30. package/dist/approval-api/retention.js.map +1 -1
  31. package/dist/approval-api/router.d.ts +1 -1
  32. package/dist/approval-api/router.d.ts.map +1 -1
  33. package/dist/approval-api/router.js +7 -0
  34. package/dist/approval-api/router.js.map +1 -1
  35. package/dist/approval-api/service.d.ts +6 -1
  36. package/dist/approval-api/service.d.ts.map +1 -1
  37. package/dist/approval-api/service.js +55 -10
  38. package/dist/approval-api/service.js.map +1 -1
  39. package/dist/approval-api/store-factory.d.ts +2 -0
  40. package/dist/approval-api/store-factory.d.ts.map +1 -1
  41. package/dist/approval-api/store-factory.js.map +1 -1
  42. package/dist/approval-api/store.d.ts +3 -0
  43. package/dist/approval-api/store.d.ts.map +1 -1
  44. package/dist/approval-api/store.js +2 -1
  45. package/dist/approval-api/store.js.map +1 -1
  46. package/dist/approval-api/types.d.ts +78 -4
  47. package/dist/approval-api/types.d.ts.map +1 -1
  48. package/dist/approval-api/types.js +1 -0
  49. package/dist/approval-api/types.js.map +1 -1
  50. package/dist/do-runner/constants.d.ts +3 -0
  51. package/dist/do-runner/constants.d.ts.map +1 -1
  52. package/dist/do-runner/constants.js +3 -0
  53. package/dist/do-runner/constants.js.map +1 -1
  54. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  55. package/dist/do-runner/d1-storage.js +34 -1
  56. package/dist/do-runner/d1-storage.js.map +1 -1
  57. package/dist/do-runner/durable-object.d.ts +10 -3
  58. package/dist/do-runner/durable-object.d.ts.map +1 -1
  59. package/dist/do-runner/durable-object.js +590 -65
  60. package/dist/do-runner/durable-object.js.map +1 -1
  61. package/dist/do-runner/execution-context.d.ts +6 -0
  62. package/dist/do-runner/execution-context.d.ts.map +1 -1
  63. package/dist/do-runner/execution-context.js +8 -0
  64. package/dist/do-runner/execution-context.js.map +1 -1
  65. package/dist/do-runner/fenced-workflow-capability.d.ts +12 -1
  66. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
  67. package/dist/do-runner/fenced-workflow-capability.js +17 -0
  68. package/dist/do-runner/fenced-workflow-capability.js.map +1 -1
  69. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  70. package/dist/do-runner/fenced-workflows-d1.js +165 -21
  71. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  72. package/dist/do-runner/index.d.ts +6 -4
  73. package/dist/do-runner/index.d.ts.map +1 -1
  74. package/dist/do-runner/index.js +4 -2
  75. package/dist/do-runner/index.js.map +1 -1
  76. package/dist/do-runner/init.d.ts +2 -2
  77. package/dist/do-runner/inventory.d.ts +1 -1
  78. package/dist/do-runner/inventory.d.ts.map +1 -1
  79. package/dist/do-runner/inventory.js +57 -1
  80. package/dist/do-runner/inventory.js.map +1 -1
  81. package/dist/do-runner/questions.d.ts +70 -0
  82. package/dist/do-runner/questions.d.ts.map +1 -0
  83. package/dist/do-runner/questions.js +440 -0
  84. package/dist/do-runner/questions.js.map +1 -0
  85. package/dist/do-runner/run-lifecycle.d.ts +25 -7
  86. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  87. package/dist/do-runner/run-lifecycle.js +54 -1
  88. package/dist/do-runner/run-lifecycle.js.map +1 -1
  89. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  90. package/dist/do-runner/run-storage-tables.d.ts.map +1 -1
  91. package/dist/do-runner/run-storage-tables.js +2 -0
  92. package/dist/do-runner/run-storage-tables.js.map +1 -1
  93. package/dist/do-runner/run-terminal-state.d.ts +1 -1
  94. package/dist/do-runner/run-terminal-state.d.ts.map +1 -1
  95. package/dist/do-runner/run-terminal-state.js +2 -2
  96. package/dist/do-runner/run-terminal-state.js.map +1 -1
  97. package/dist/do-runner/runtime.d.ts +92 -17
  98. package/dist/do-runner/runtime.d.ts.map +1 -1
  99. package/dist/do-runner/runtime.js +468 -42
  100. package/dist/do-runner/runtime.js.map +1 -1
  101. package/dist/do-runner/schedule-source.d.ts +4 -3
  102. package/dist/do-runner/schedule-source.d.ts.map +1 -1
  103. package/dist/do-runner/schedule-source.js.map +1 -1
  104. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  105. package/dist/do-runner/suspension-deadline.js +9 -4
  106. package/dist/do-runner/suspension-deadline.js.map +1 -1
  107. package/dist/do-runner/suspension-kinds.d.ts +6 -0
  108. package/dist/do-runner/suspension-kinds.d.ts.map +1 -0
  109. package/dist/do-runner/suspension-kinds.js +33 -0
  110. package/dist/do-runner/suspension-kinds.js.map +1 -0
  111. package/dist/host-kit/approval-bridge.d.ts +12 -14
  112. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  113. package/dist/host-kit/approval-bridge.js +40 -18
  114. package/dist/host-kit/approval-bridge.js.map +1 -1
  115. package/dist/host-kit/do-response.d.ts.map +1 -1
  116. package/dist/host-kit/do-response.js +30 -1
  117. package/dist/host-kit/do-response.js.map +1 -1
  118. package/dist/host-kit/do-run-topology.d.ts +8 -3
  119. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  120. package/dist/host-kit/do-run-topology.js +64 -1
  121. package/dist/host-kit/do-run-topology.js.map +1 -1
  122. package/dist/host-kit/flowsafe-worker.d.ts +23 -6
  123. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  124. package/dist/host-kit/flowsafe-worker.js +121 -16
  125. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  126. package/dist/host-kit/host-approval-service.d.ts +1 -1
  127. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  128. package/dist/host-kit/host-approval-service.js +10 -4
  129. package/dist/host-kit/host-approval-service.js.map +1 -1
  130. package/dist/host-kit/index.d.ts +3 -1
  131. package/dist/host-kit/index.d.ts.map +1 -1
  132. package/dist/host-kit/index.js +1 -0
  133. package/dist/host-kit/index.js.map +1 -1
  134. package/dist/host-kit/run-router.d.ts +35 -3
  135. package/dist/host-kit/run-router.d.ts.map +1 -1
  136. package/dist/host-kit/run-router.js +119 -6
  137. package/dist/host-kit/run-router.js.map +1 -1
  138. package/dist/human-notification-storage.d.ts +5 -0
  139. package/dist/human-notification-storage.d.ts.map +1 -0
  140. package/dist/human-notification-storage.js +57 -0
  141. package/dist/human-notification-storage.js.map +1 -0
  142. package/dist/notification-retry.d.ts +3 -0
  143. package/dist/notification-retry.d.ts.map +1 -0
  144. package/dist/notification-retry.js +6 -0
  145. package/dist/notification-retry.js.map +1 -0
  146. package/dist/schedules/fire-plan.d.ts +30 -0
  147. package/dist/schedules/fire-plan.d.ts.map +1 -0
  148. package/dist/schedules/fire-plan.js +111 -0
  149. package/dist/schedules/fire-plan.js.map +1 -0
  150. package/dist/schedules/index.d.ts +4 -2
  151. package/dist/schedules/index.d.ts.map +1 -1
  152. package/dist/schedules/index.js +2 -0
  153. package/dist/schedules/index.js.map +1 -1
  154. package/dist/schedules/mutation-contract.d.ts +8 -6
  155. package/dist/schedules/mutation-contract.d.ts.map +1 -1
  156. package/dist/schedules/mutation-contract.js.map +1 -1
  157. package/dist/schedules/router.d.ts +9 -6
  158. package/dist/schedules/router.d.ts.map +1 -1
  159. package/dist/schedules/router.js +362 -94
  160. package/dist/schedules/router.js.map +1 -1
  161. package/dist/schedules/schedule-extensions.d.ts +46 -0
  162. package/dist/schedules/schedule-extensions.d.ts.map +1 -0
  163. package/dist/schedules/schedule-extensions.js +7 -0
  164. package/dist/schedules/schedule-extensions.js.map +1 -0
  165. package/dist/schedules/schedules-d1.d.ts +44 -10
  166. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  167. package/dist/schedules/schedules-d1.js +437 -68
  168. package/dist/schedules/schedules-d1.js.map +1 -1
  169. package/dist/schedules/tick.d.ts +81 -18
  170. package/dist/schedules/tick.d.ts.map +1 -1
  171. package/dist/schedules/tick.js +701 -168
  172. package/dist/schedules/tick.js.map +1 -1
  173. package/dist/signals/notification-dispatch.d.ts +1 -1
  174. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  175. package/dist/signals/notification-dispatch.js +3 -4
  176. package/dist/signals/notification-dispatch.js.map +1 -1
  177. package/package.json +1 -1
@@ -23,18 +23,18 @@ import { RequestContext } from '@mastra/core/request-context';
23
23
  import { createEmptyWorkflowSnapshot, } from '@mastra/core/storage';
24
24
  import { cleanStepResult, } from '@mastra/core/workflows';
25
25
  import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
26
- import { BREAKWATER_ACTOR_KEY, BREAKWATER_CONNECTOR_EXECUTION_KEY, BREAKWATER_ISOLATION_SCOPE_KEY, BREAKWATER_WORKFLOW_SCOPE_KEY, } from './breakwater-keys.js';
26
+ import { BREAKWATER_ACTOR_KEY, BREAKWATER_CONNECTOR_EXECUTION_KEY, BREAKWATER_CONNECTOR_GRANTS_KEY, BREAKWATER_ISOLATION_SCOPE_KEY, BREAKWATER_WORKFLOW_SCOPE_KEY, } from './breakwater-keys.js';
27
27
  import { errorMessageOf, findInCauseChain } from './cause-chain.js';
28
28
  import { DoStatusError } from './do-status-error.js';
29
29
  import { assertMutationEpoch, ExecutionFenceUnreadableError, normalizeD1RunExecutionIdentity, normalizeMutationEpoch, normalizeStartIdentity, RunStartPendingError, } from './execution-admission.js';
30
- import { isReservedExecutionContextKey, RUN_PROVENANCE_CONTEXT_KEY, stripReservedExecutionContext, } from './execution-context.js';
30
+ import { isReservedExecutionContextKey, LEG_OUTCOME_CONTEXT_KEY, RUN_PROVENANCE_CONTEXT_KEY, stripReservedExecutionContext, } from './execution-context.js';
31
31
  import { admitsExistingRun, admitsRunStart, ExecutionFencedError, } from './execution-fence.js';
32
- import { FENCED_WORKFLOW_STORAGE, } from './fenced-workflow-capability.js';
32
+ import { FENCED_WORKFLOW_STORAGE, isEntryBoundarySnapshot, } from './fenced-workflow-capability.js';
33
33
  import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
34
34
  import { mastraRegistryEntries } from './mastra-registry.js';
35
35
  import { isPathSafeId } from './path-safe-id.js';
36
36
  import { exceedsRunInputDepth, runInputDepthMessage, } from './run-input-depth.js';
37
- import { advanceLifecycle, canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, failureEnvelope, hasDisputedSettlement, isSettledLegAbort, legAbortReason, lifecycleFromRequestContext, projectTerminalLifecycle, RUN_FAILURE_MARKERS, RUN_LIFECYCLE_CONTEXT_KEY, RUN_SETTLING_MARKERS, RunLifecycleBlockedError, RunSettledConflictError, RunStateNotStorableError, runTerminalError, terminalCleanupFor, terminalLegAbortReason, } from './run-lifecycle.js';
37
+ import { advanceLifecycle, canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, failureEnvelope, hasDisputedSettlement, isPauseLegAbort, isPauseReason, isSettledLegAbort, legAbortReason, lifecycleFromRequestContext, nextLifecycleRevision, pauseLegAbortReason, projectTerminalLifecycle, RUN_FAILURE_MARKERS, RUN_LIFECYCLE_CONTEXT_KEY, RUN_SETTLING_MARKERS, RunLifecycleBlockedError, RunSettledConflictError, RunStateNotStorableError, runTerminalError, terminalCleanupFor, terminalLegAbortReason, } from './run-lifecycle.js';
38
38
  import { decodeProgressRunProvenance, decodeResumeCounts, nextResumeCount, runExecutionIdentityFor, } from './run-provenance.js';
39
39
  import { captureRunRequester } from './run-requester.js';
40
40
  import { errorText, isDurableRunStatus, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
@@ -145,6 +145,84 @@ export class InvalidRunRequestError extends Error {
145
145
  this.name = 'InvalidRunRequestError';
146
146
  }
147
147
  }
148
+ export class PauseConflictError extends DoStatusError {
149
+ status = 409;
150
+ reason = { code: 'PAUSE_CONFLICT' };
151
+ constructor() {
152
+ super('a different pause request is already recorded for this run');
153
+ this.name = 'PauseConflictError';
154
+ }
155
+ }
156
+ export class PauseUnsupportedError extends DoStatusError {
157
+ status = 409;
158
+ reason = { code: 'PAUSE_UNSUPPORTED' };
159
+ constructor(message) {
160
+ super(message);
161
+ this.name = 'PauseUnsupportedError';
162
+ }
163
+ }
164
+ export class PauseHoldsScheduleError extends DoStatusError {
165
+ status = 409;
166
+ reason = { code: 'PAUSE_HOLDS_SCHEDULE' };
167
+ constructor() {
168
+ super('the schedule overlap policy skip or queue_one will skip or hold fires while the run is paused');
169
+ this.name = 'PauseHoldsScheduleError';
170
+ }
171
+ }
172
+ export class RunNotPausedError extends DoStatusError {
173
+ status = 409;
174
+ reason = { code: 'RUN_NOT_PAUSED' };
175
+ constructor() {
176
+ super('the run has no resumable pause');
177
+ this.name = 'RunNotPausedError';
178
+ }
179
+ }
180
+ export class PauseGenerationStaleError extends DoStatusError {
181
+ status = 409;
182
+ reason = { code: 'PAUSE_GENERATION_STALE' };
183
+ constructor() {
184
+ super('the run has a different pause generation');
185
+ this.name = 'PauseGenerationStaleError';
186
+ }
187
+ }
188
+ export class PauseInProgressError extends DoStatusError {
189
+ status = 409;
190
+ reason = { code: 'PAUSE_IN_PROGRESS' };
191
+ constructor() {
192
+ super('the run is honoring a pause');
193
+ this.name = 'PauseInProgressError';
194
+ }
195
+ }
196
+ /** @internal Validate the pause request before passing it across a host boundary. */
197
+ export function parsePauseRunOptions(value) {
198
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
199
+ throw new InvalidRunRequestError('pause body must be an object');
200
+ const { reason, holdsSchedule } = value;
201
+ if (!isPauseReason(reason))
202
+ throw new InvalidRunRequestError('pause requires a reason of 1 to 500 characters');
203
+ if (holdsSchedule !== undefined && typeof holdsSchedule !== 'boolean')
204
+ throw new InvalidRunRequestError('holdsSchedule must be a boolean');
205
+ return { reason, ...(holdsSchedule === undefined ? {} : { holdsSchedule }) };
206
+ }
207
+ /** @internal Validate the generation before forwarding or resuming a pause. */
208
+ export function parsePauseGeneration(value) {
209
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1)
210
+ throw new InvalidRunRequestError('expectedGeneration must be a positive safe integer');
211
+ return value;
212
+ }
213
+ function pauseForResume(state, expectedGeneration) {
214
+ const lifecycle = lifecycleFromRequestContext(state.requestContext);
215
+ const pause = lifecycle?.pause;
216
+ if (!lifecycle ||
217
+ !pause ||
218
+ (state.status === 'paused') !== (pause.pausedAt !== undefined))
219
+ throw new RunNotPausedError();
220
+ if (pause.honoringAt !== undefined)
221
+ throw new PauseInProgressError();
222
+ if (pause.generation !== expectedGeneration)
223
+ throw new PauseGenerationStaleError();
224
+ return { lifecycle, pause };
225
+ }
148
226
  // Only core's own shapes of a caller-fixable refusal answer 400: anchored
149
227
  // leading text, never a substring a foreign error can carry. The schema
150
228
  // violation is read by id and category because `instanceof` fails across
@@ -180,6 +258,7 @@ const RUN_STATE_FIELDS = [
180
258
  const RESUME_STATE_FIELDS = [
181
259
  ...RUN_STATE_FIELDS,
182
260
  'payload',
261
+ 'serializedStepGraph',
183
262
  ];
184
263
  function runProvenance(state) {
185
264
  const value = state.requestContext?.[RUN_PROVENANCE_CONTEXT_KEY];
@@ -290,6 +369,14 @@ function resolveResumeStep(step, state) {
290
369
  const suspended = Object.keys(state.suspendedPaths ?? {});
291
370
  return suspended.length === 1 ? suspended[0]?.split('.') : undefined;
292
371
  }
372
+ function suspendedInsideForeach(state, step) {
373
+ const paths = state.suspendedPaths ?? {};
374
+ const candidates = step
375
+ ? [paths[step.join('.')] ?? paths[step[0] ?? '']]
376
+ : Object.values(paths);
377
+ return candidates.some(([entry] = []) => entry !== undefined &&
378
+ state.serializedStepGraph?.[entry]?.type === 'foreach');
379
+ }
293
380
  // The live attempt for a step. Repeated steps (foreach) store an array of
294
381
  // attempts, so the current suspension/resume is the latest; a single-run step
295
382
  // stores one entry.
@@ -347,6 +434,17 @@ function summarizeState(runId, state, provenance) {
347
434
  return summaryWithRequester(summary, provenance);
348
435
  }
349
436
  summaryWithRequester(summary, provenance);
437
+ const pause = lifecycle?.pause;
438
+ if (pause &&
439
+ pause.restartAttemptToken === undefined &&
440
+ !isTerminalRunStatus(state.status)) {
441
+ summary.pauseRequestedAt = pause.requestedAt;
442
+ summary.pausedBy = pause.requestedBy;
443
+ summary.pauseReason = pause.reason;
444
+ summary.pauseGeneration = pause.generation;
445
+ if (pause.pausedAt !== undefined)
446
+ summary.pausedAt = pause.pausedAt;
447
+ }
350
448
  if (state.status === 'success') {
351
449
  summary.result = state.result;
352
450
  }
@@ -507,26 +605,23 @@ export function assertRunInputDepth(field, value) {
507
605
  if (exceedsRunInputDepth(value))
508
606
  throw new InvalidRunRequestError(runInputDepthMessage(field));
509
607
  }
510
- /**
511
- * `resumeCount` is absent on a first suspension and 1, 2, … after it, so 0 is
512
- * malformed rather than a suspension the step can be at.
513
- */
514
608
  function captureExpectedSuspension(value) {
515
609
  if (value === undefined)
516
610
  return undefined;
517
611
  if (value === null || typeof value !== 'object' || Array.isArray(value))
518
612
  throw new InvalidRunRequestError('expectedSuspension is malformed');
519
613
  const { suspendedAt, resumeCount } = value;
520
- if (!Number.isSafeInteger(suspendedAt) ||
614
+ if (typeof suspendedAt !== 'number' ||
615
+ !Number.isSafeInteger(suspendedAt) ||
521
616
  suspendedAt < 0 ||
522
617
  (resumeCount !== undefined &&
523
- (!Number.isSafeInteger(resumeCount) || resumeCount < 1)))
618
+ (typeof resumeCount !== 'number' ||
619
+ !Number.isSafeInteger(resumeCount) ||
620
+ resumeCount < 0)))
524
621
  throw new InvalidRunRequestError('expectedSuspension is malformed');
525
622
  return Object.freeze({
526
- suspendedAt: suspendedAt,
527
- ...(resumeCount === undefined
528
- ? {}
529
- : { resumeCount: resumeCount }),
623
+ suspendedAt,
624
+ ...(resumeCount === undefined ? {} : { resumeCount }),
530
625
  });
531
626
  }
532
627
  function isRunStateNotStorable(error) {
@@ -1044,6 +1139,7 @@ export class RunnerRuntime {
1044
1139
  preflight = false;
1045
1140
  const requestContext = await this.#requestContextFor(workflowId, runId, { kind: 'start' }, provenance, options.storedRequestContext, lifecycle);
1046
1141
  active.requestContext = requestContext;
1142
+ this.#enablePauseBoundary(active);
1047
1143
  if (options.onPreparedStartIdentity)
1048
1144
  await Reflect.apply(options.onPreparedStartIdentity, undefined, [
1049
1145
  execution,
@@ -1120,6 +1216,7 @@ export class RunnerRuntime {
1120
1216
  }
1121
1217
  active.run = run;
1122
1218
  engineEntered = true;
1219
+ // Mastra's WorkflowResult omits the engine's 'canceled' status.
1123
1220
  const startPromise = run.start({
1124
1221
  inputData: options.inputData,
1125
1222
  initialState: options.initialState,
@@ -1138,6 +1235,10 @@ export class RunnerRuntime {
1138
1235
  });
1139
1236
  const result = await executionPromise;
1140
1237
  this.#throwIfSettledLeg(active, workflowId, runId);
1238
+ if (result.status === 'canceled' &&
1239
+ isPauseLegAbort(active.run?.abortController.signal.reason) &&
1240
+ (await this.#commitPause(workflowId, runId, active)))
1241
+ return;
1141
1242
  await this.#reconcileTerminalState(workflowId, runId, result, requestContext, source,
1142
1243
  // A fenced start's admission witnessed the row it stored.
1143
1244
  admissionEntered || active.storedRunScope?.rowStored === true);
@@ -1184,6 +1285,65 @@ export class RunnerRuntime {
1184
1285
  * loads it and re-enters the engine at the suspended step.
1185
1286
  */
1186
1287
  async resume(workflowId, runId, options = {}) {
1288
+ return this.#resume(workflowId, runId, options);
1289
+ }
1290
+ async resumePaused(workflowId, runId, principal, options) {
1291
+ const { expectedGeneration, legAbort } = options;
1292
+ assertLegAbort(legAbort);
1293
+ if (!isExecutionPrincipalKind(principal?.kind) ||
1294
+ !isExecutionPrincipalId(principal?.id))
1295
+ throw new InvalidRunRequestError('resume principal is malformed');
1296
+ const restartPrincipal = { id: principal.id, kind: principal.kind };
1297
+ const cleared = await this.clearPendingPause(workflowId, runId, expectedGeneration);
1298
+ if (cleared)
1299
+ return cleared;
1300
+ return this.restartPaused(workflowId, runId, restartPrincipal, {
1301
+ expectedGeneration,
1302
+ legAbort,
1303
+ });
1304
+ }
1305
+ /** @internal Clear a pending pause without waiting for the active leg. */
1306
+ async clearPendingPause(workflowId, runId, generation) {
1307
+ const expectedGeneration = parsePauseGeneration(generation);
1308
+ this.#getWorkflow(workflowId);
1309
+ const proof = await this.#assertResumeFence(workflowId, runId);
1310
+ return this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
1311
+ const active = this.#activeRuns.get(this.#runKey(workflowId, runId));
1312
+ const source = active?.source ?? (await this.#captureWorkflowStorage(workflowId));
1313
+ const { state, row } = await this.#readForTransition(source, workflowId, runId);
1314
+ const { lifecycle, pause } = pauseForResume(state, expectedGeneration);
1315
+ if (pause.pausedAt !== undefined)
1316
+ return;
1317
+ if (!row)
1318
+ throw new RunStateUnreadableError(workflowId, runId);
1319
+ if (lifecycle.transitionIntent ||
1320
+ lifecycle.terminal ||
1321
+ !TERMINABLE_RUN_STATUSES.has(state.status))
1322
+ throw new RunTerminalConflictError(workflowId, runId, state.status, lifecycle.transitionIntent ? 'ending' : 'terminal');
1323
+ const provenance = runProvenance(state);
1324
+ await this.#assertRetainedResume(source, workflowId, runId, provenance, proof);
1325
+ const now = Date.now();
1326
+ const next = advanceLifecycle(lifecycle, {});
1327
+ delete next.pause;
1328
+ await this.#persistIntent(workflowId, runId, state, next, now, source, row);
1329
+ return summaryFromSelectedSnapshot(runId, {
1330
+ ...state,
1331
+ requestContext: {
1332
+ ...state.requestContext,
1333
+ [RUN_LIFECYCLE_CONTEXT_KEY]: next,
1334
+ },
1335
+ }, { ...row, updatedAt: new Date(now).toISOString() }, provenance);
1336
+ }));
1337
+ }
1338
+ /** @internal Start a leg for a committed pause after checking for a pending pause. */
1339
+ restartPaused(workflowId, runId, principal, options, onRestartState) {
1340
+ return this.#resume(workflowId, runId, {
1341
+ requestedBy: principal.id,
1342
+ requestedByKind: principal.kind,
1343
+ legAbort: options.legAbort,
1344
+ }, { generation: options.expectedGeneration, onRestartState });
1345
+ }
1346
+ async #resume(workflowId, runId, options, restart) {
1187
1347
  const { legAbort } = options;
1188
1348
  assertLegAbort(legAbort);
1189
1349
  assertRunInputDepth('resumeData', options.resumeData);
@@ -1199,6 +1359,7 @@ export class RunnerRuntime {
1199
1359
  let provenance;
1200
1360
  let engineEntered = false;
1201
1361
  let outcomeReadStarted = false;
1362
+ let restorePersistenceOverride;
1202
1363
  try {
1203
1364
  const source = await this.#captureWorkflowStorage(workflowId);
1204
1365
  active.source = source;
@@ -1215,13 +1376,21 @@ export class RunnerRuntime {
1215
1376
  prior.startToken !== proof.startToken ||
1216
1377
  source.tablePrefix !== proof.tablePrefix))
1217
1378
  throw new RunStateUnreadableError(workflowId, runId);
1218
- if (state.status !== 'suspended')
1379
+ if (restart) {
1380
+ pauseForResume(state, restart.generation);
1381
+ if (state.status !== 'paused')
1382
+ throw new RunNotPausedError();
1383
+ }
1384
+ else if (state.status !== 'suspended')
1219
1385
  throw new RunNotSuspendedError(workflowId, runId, state.status);
1220
- const prepared = await this.#trustedResumePreparation(workflowId, runId, state, { ...options, expectedSuspension });
1386
+ const prepared = await this.#trustedResumePreparation(workflowId, runId, state, { ...options, expectedSuspension }, restart !== undefined);
1221
1387
  provenance = prepared.provenance;
1222
1388
  const { requestContext, lifecycle, nextCounts } = prepared;
1223
1389
  active.requestContext = requestContext;
1224
1390
  active.lifecycle = lifecycle;
1391
+ if (restart ||
1392
+ !suspendedInsideForeach(state, resolveResumeStep(options.step, state)))
1393
+ this.#enablePauseBoundary(active);
1225
1394
  const check = async () => {
1226
1395
  const current = await this.#assertRetainedResume(source, workflowId, runId, prior, proof);
1227
1396
  const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
@@ -1250,18 +1419,53 @@ export class RunnerRuntime {
1250
1419
  const run = await this.#createRun(workflowId, runId);
1251
1420
  const { executionPromise } = await this.#withLifecycleLock(workflowId, runId, async () => {
1252
1421
  await check();
1422
+ if (restart) {
1423
+ const { storedRunScope } = active;
1424
+ if (!storedRunScope)
1425
+ throw new PauseUnsupportedError('storage cannot restart a pause');
1426
+ const claimedLifecycle = await this.#claimPausedRun(source, workflowId, runId, restart.generation, prior?.startToken, prepared.provenance.attemptToken, restart.onRestartState);
1427
+ active.lifecycle = claimedLifecycle;
1428
+ requestContext.set(RUN_LIFECYCLE_CONTEXT_KEY, claimedLifecycle);
1429
+ // The restart must record step entry before the step runs,
1430
+ // even when the workflow normally filters running snapshots.
1431
+ const engine = run.executionEngine;
1432
+ const override = engine.getRunPersistenceOverride(runId);
1433
+ const persistFirstWrite = () => true;
1434
+ const restore = () => {
1435
+ const currentOverride = engine.getRunPersistenceOverride(runId);
1436
+ if (currentOverride !== persistFirstWrite)
1437
+ return;
1438
+ if (override) {
1439
+ engine.setRunPersistenceOverride(runId, override);
1440
+ }
1441
+ else {
1442
+ engine.clearRunPersistenceOverride(runId);
1443
+ }
1444
+ };
1445
+ storedRunScope.restart = {
1446
+ attemptToken: prepared.provenance.attemptToken,
1447
+ onFirstWrite: restore,
1448
+ };
1449
+ restorePersistenceOverride = restore;
1450
+ engine.setRunPersistenceOverride(runId, persistFirstWrite);
1451
+ }
1253
1452
  active.run = run;
1254
1453
  engineEntered = true;
1255
- return {
1256
- executionPromise: run.resume({
1454
+ const legPromise = restart === undefined
1455
+ ? run.resume({
1257
1456
  step: options.step,
1258
1457
  resumeData: options.resumeData,
1259
1458
  requestContext,
1260
- }),
1261
- };
1459
+ })
1460
+ : run.restart({ requestContext });
1461
+ return { executionPromise: legPromise };
1262
1462
  });
1263
1463
  const resumed = await executionPromise;
1264
1464
  this.#throwIfSettledLeg(active, workflowId, runId);
1465
+ if (resumed.status === 'canceled' &&
1466
+ isPauseLegAbort(active.run?.abortController.signal.reason) &&
1467
+ (await this.#commitPause(workflowId, runId, active)))
1468
+ return resumed;
1265
1469
  await this.#reconcileTerminalState(workflowId, runId, resumed, requestContext, source,
1266
1470
  // A resume begins from the row it read.
1267
1471
  true, proof);
@@ -1274,10 +1478,35 @@ export class RunnerRuntime {
1274
1478
  await this.#settleStartReservation(selected);
1275
1479
  return selected.summary;
1276
1480
  }
1481
+ if (source.storage === 'd1' &&
1482
+ source.capability.supportsPause &&
1483
+ (result.status === 'suspended' ||
1484
+ isPauseLegAbort(active.run?.abortController.signal.reason))) {
1485
+ const summary = await this.#summaryAfterPersist(workflowId, runId, source, provenance);
1486
+ if (summary.pauseGeneration !== undefined)
1487
+ return summary;
1488
+ }
1277
1489
  return summarize(runId, result, nextCounts, provenance.requestedBy, provenance.requestedByKind, lifecycle?.deadlineAt);
1278
1490
  }
1279
1491
  catch (error) {
1280
- if (engineEntered && provenance && !outcomeReadStarted) {
1492
+ const claim = active.storedRunScope?.restart;
1493
+ const source = active.source;
1494
+ if (claim?.onFirstWrite && source) {
1495
+ try {
1496
+ const restored = await this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
1497
+ const { state, row } = await this.#readForTransition(source, workflowId, runId);
1498
+ return row
1499
+ ? this.#restorePausedRestart(source, state, row, Date.now(), claim.attemptToken)
1500
+ : undefined;
1501
+ }));
1502
+ if (restored)
1503
+ restart?.onRestartState?.(restored);
1504
+ }
1505
+ catch (restoreError) {
1506
+ console.error('restart pause recovery failed', restoreError);
1507
+ }
1508
+ }
1509
+ else if (engineEntered && provenance && !outcomeReadStarted) {
1281
1510
  await this.#failUnstorableLeg(workflowId, runId, active, error);
1282
1511
  const recovered = await this.#summaryForAttempt(workflowId, runId, provenance);
1283
1512
  if (recovered)
@@ -1286,10 +1515,110 @@ export class RunnerRuntime {
1286
1515
  throw asClientError(error) ?? error;
1287
1516
  }
1288
1517
  finally {
1518
+ restorePersistenceOverride?.();
1289
1519
  await leaveLeg();
1290
1520
  }
1291
1521
  });
1292
1522
  }
1523
+ #claimPausedRun(source, workflowId, runId, expectedGeneration, startToken, attemptToken, onRestartState) {
1524
+ return this.#retryOnRowChange(workflowId, runId, async () => {
1525
+ const { state, row } = await this.#readForTransition(source, workflowId, runId);
1526
+ const provenance = runProvenance(state);
1527
+ if (!row || provenance?.startToken !== startToken)
1528
+ throw new RunStateUnreadableError(workflowId, runId);
1529
+ const { lifecycle, pause } = pauseForResume(state, expectedGeneration);
1530
+ if (state.status !== 'paused')
1531
+ throw new RunNotPausedError();
1532
+ const now = Date.now();
1533
+ const ending = lifecycle.terminal?.status ??
1534
+ lifecycle.transitionIntent?.status ??
1535
+ (lifecycle.deadlineAt !== undefined && lifecycle.deadlineAt <= now
1536
+ ? 'timed_out'
1537
+ : undefined);
1538
+ if (ending)
1539
+ throw new RunTerminalConflictError(workflowId, runId, ending, lifecycle.terminal ? 'terminal' : 'ending');
1540
+ const next = advanceLifecycle(lifecycle, {});
1541
+ delete next.pause;
1542
+ const running = await this.#persistLifecycle(workflowId, runId, { ...state, status: 'running' }, { ...next, pause: { ...pause, restartAttemptToken: attemptToken } }, now, source, row);
1543
+ onRestartState?.(summaryFromSelectedSnapshot(runId, running, { ...row, updatedAt: new Date(now).toISOString() }, provenance));
1544
+ return next;
1545
+ });
1546
+ }
1547
+ async #restorePausedRestart(source, state, row, now, attemptToken) {
1548
+ const lifecycle = lifecycleFromRequestContext(state.requestContext);
1549
+ if (!lifecycle?.pause ||
1550
+ lifecycle.pause.restartAttemptToken !== attemptToken ||
1551
+ lifecycle.transitionIntent ||
1552
+ RUN_SETTLING_MARKERS.some((marker) => lifecycle[marker] !== undefined) ||
1553
+ !isEntryBoundarySnapshot(state))
1554
+ return;
1555
+ const pause = { ...lifecycle.pause };
1556
+ delete pause.restartAttemptToken;
1557
+ const paused = await this.#persistLifecycle(row.workflowId, row.runId, { ...state, status: 'paused' }, advanceLifecycle(lifecycle, { pause }), now, source, row);
1558
+ return summaryFromSelectedSnapshot(row.runId, paused, { ...row, updatedAt: new Date(now).toISOString() }, runProvenance(state));
1559
+ }
1560
+ /** Request a cooperative pause without waiting for the executing leg. */
1561
+ async requestPause(workflowId, runId, principal, options) {
1562
+ const { reason, holdsSchedule } = parsePauseRunOptions(options);
1563
+ if (!isExecutionPrincipalKind(principal?.kind) ||
1564
+ !isExecutionPrincipalId(principal?.id))
1565
+ throw new InvalidRunRequestError('pause principal is malformed');
1566
+ const requestedBy = { kind: principal.kind, id: principal.id };
1567
+ this.#getWorkflow(workflowId);
1568
+ return this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
1569
+ const active = this.#activeRuns.get(this.#runKey(workflowId, runId));
1570
+ const source = active?.source ?? (await this.#captureWorkflowStorage(workflowId));
1571
+ if (source.storage !== 'd1' ||
1572
+ !source.capability.supportsPause ||
1573
+ !source.enterStoredRun ||
1574
+ !source.replace ||
1575
+ !source.touch)
1576
+ throw new PauseUnsupportedError('storage cannot honor a pause');
1577
+ const { state, row } = await this.#readForTransition(source, workflowId, runId);
1578
+ if (!row)
1579
+ throw new RunStateUnreadableError(workflowId, runId);
1580
+ const lifecycle = lifecycleFromRequestContext(state.requestContext);
1581
+ const provenance = runProvenance(state);
1582
+ if (lifecycle?.terminal || !TERMINABLE_RUN_STATUSES.has(state.status))
1583
+ throw new RunTerminalConflictError(workflowId, runId, state.status);
1584
+ if (lifecycle?.transitionIntent)
1585
+ throw new RunTerminalConflictError(workflowId, runId, state.status, 'ending');
1586
+ if (provenance?.version === 2 &&
1587
+ provenance.startIdentity?.target.kind === 'agent')
1588
+ throw new PauseUnsupportedError('agent runs cannot be paused');
1589
+ if (state.status === 'suspended' && suspendedInsideForeach(state))
1590
+ throw new PauseUnsupportedError('suspended inside foreach');
1591
+ if (lifecycle?.scheduleDispatch && holdsSchedule !== true)
1592
+ throw new PauseHoldsScheduleError();
1593
+ if (lifecycle?.pause) {
1594
+ const pause = lifecycle.pause;
1595
+ if (pause.reason !== reason ||
1596
+ pause.requestedBy.kind !== requestedBy.kind ||
1597
+ pause.requestedBy.id !== requestedBy.id)
1598
+ throw new PauseConflictError();
1599
+ return summaryFromSelectedSnapshot(runId, state, row, provenance);
1600
+ }
1601
+ if (state.status === 'paused')
1602
+ throw new PauseUnsupportedError('this paused run has no pause record');
1603
+ const now = Date.now();
1604
+ const next = advanceLifecycle(lifecycle, {
1605
+ pause: {
1606
+ requestedAt: now,
1607
+ requestedBy,
1608
+ reason,
1609
+ generation: nextLifecycleRevision(lifecycle?.revision ?? 0),
1610
+ },
1611
+ });
1612
+ await this.#persistIntent(workflowId, runId, state, next, now, source, row);
1613
+ return summaryFromSelectedSnapshot(runId, {
1614
+ ...state,
1615
+ requestContext: {
1616
+ ...state.requestContext,
1617
+ [RUN_LIFECYCLE_CONTEXT_KEY]: next,
1618
+ },
1619
+ }, { ...row, updatedAt: new Date(now).toISOString() }, provenance);
1620
+ }));
1621
+ }
1293
1622
  /** Idempotently cancel a live run from its persisted snapshot. */
1294
1623
  terminate(workflowId, runId, now = Date.now()) {
1295
1624
  return this.#transitionTerminal(workflowId, runId, 'cancelled', now);
@@ -2021,6 +2350,56 @@ export class RunnerRuntime {
2021
2350
  ? source.enterStoredRun?.bind(source.capability)
2022
2351
  : undefined;
2023
2352
  }
2353
+ #enablePauseBoundary(active) {
2354
+ const { storedRunScope, requestContext } = active;
2355
+ if (!storedRunScope || !requestContext)
2356
+ return;
2357
+ storedRunScope.onPauseCommitted = () => {
2358
+ requestContext.set(LEG_OUTCOME_CONTEXT_KEY, 'paused');
2359
+ };
2360
+ storedRunScope.onPauseBoundary = (lifecycle) => {
2361
+ const controller = active.run?.abortController;
2362
+ if (!controller || controller.signal.aborted)
2363
+ return;
2364
+ if (!active.lifecycle || active.lifecycle.revision < lifecycle.revision)
2365
+ active.lifecycle = lifecycle;
2366
+ storedRunScope.pauseAbortRevision = lifecycle.revision;
2367
+ controller.abort(pauseLegAbortReason());
2368
+ };
2369
+ }
2370
+ async #commitPause(workflowId, runId, active) {
2371
+ const { source, storedRunScope } = active;
2372
+ const revision = storedRunScope?.pauseAbortRevision;
2373
+ if (!source || revision === undefined)
2374
+ return false;
2375
+ return this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
2376
+ const { state, row } = await this.#readForTransition(source, workflowId, runId);
2377
+ if (state.status === 'paused')
2378
+ return true;
2379
+ return row
2380
+ ? this.#persistPausedBoundary(source, state, row, Date.now(), revision)
2381
+ : false;
2382
+ }));
2383
+ }
2384
+ async #persistPausedBoundary(source, state, row, now, expectedRevision) {
2385
+ const lifecycle = lifecycleFromRequestContext(state.requestContext);
2386
+ if (lifecycle?.pause?.honoringAt === undefined ||
2387
+ lifecycle.pause.pausedAt !== undefined ||
2388
+ (expectedRevision !== undefined &&
2389
+ lifecycle.revision !== expectedRevision) ||
2390
+ lifecycle.transitionIntent ||
2391
+ RUN_SETTLING_MARKERS.some((marker) => lifecycle[marker] !== undefined) ||
2392
+ !isEntryBoundarySnapshot(state))
2393
+ return false;
2394
+ const pause = {
2395
+ ...lifecycle.pause,
2396
+ pausedAt: now,
2397
+ generation: nextLifecycleRevision(lifecycle.revision),
2398
+ };
2399
+ delete pause.honoringAt;
2400
+ await this.#persistLifecycle(row.workflowId, row.runId, { ...state, status: 'paused' }, advanceLifecycle(lifecycle, { pause }), now, source, row);
2401
+ return true;
2402
+ }
2024
2403
  /** Run a leg's writes of its own run inside the storage's stored-run scope. */
2025
2404
  #inStoredRunScope(active, operation) {
2026
2405
  const withStoredRun = this.#withStoredRunOf(active.source);
@@ -2038,12 +2417,11 @@ export class RunnerRuntime {
2038
2417
  * on the outgoing instance, so a run is written only after its row has gone
2039
2418
  * untouched for RUN_LEG_SILENT_MS (`live` otherwise).
2040
2419
  *
2041
- * `durable` (suspended, or terminal with its cleanup done) and `absent` leave
2042
- * the snapshot untouched. A recorded cancellation or timeout owns the
2043
- * outcome: `transition` completes it, or replays a terminal one whose cleanup
2044
- * is unfinished, and leaves the cleanup to the caller as the terminate and
2045
- * deadline routes do. The pending initial row stays with start recovery,
2046
- * which repairs it as an unknown outcome.
2420
+ * `durable` and `absent` leave the snapshot untouched. A recorded
2421
+ * cancellation or timeout owns the outcome: `transition` completes it or
2422
+ * replays it if cleanup is unfinished. The caller handles cleanup as it does
2423
+ * on the terminate and deadline routes. Start recovery handles the pending
2424
+ * initial row as an unknown outcome.
2047
2425
  *
2048
2426
  * Any other run becomes `failed` (`interrupted`), never re-executed: the step
2049
2427
  * that was in flight may already have had effects.
@@ -2101,6 +2479,17 @@ export class RunnerRuntime {
2101
2479
  currentLifecycle?.terminal ||
2102
2480
  currentLifecycle?.transitionIntent)
2103
2481
  return { kind: 'live' };
2482
+ const restartAttempt = currentLifecycle?.pause?.restartAttemptToken;
2483
+ if (restartAttempt !== undefined) {
2484
+ const summary = await this.#restorePausedRestart(source, current, silent, now, restartAttempt);
2485
+ if (summary)
2486
+ return { kind: 'paused', summary };
2487
+ }
2488
+ if (await this.#persistPausedBoundary(source, current, silent, now))
2489
+ return {
2490
+ kind: 'paused',
2491
+ summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(current)),
2492
+ };
2104
2493
  await this.#persistLifecycle(workflowId, runId, { ...current, ...failedByMarker('interruptedAt', now) }, advanceLifecycle(currentLifecycle, { interruptedAt: now }), now, source, silent);
2105
2494
  }
2106
2495
  catch (error) {
@@ -2114,6 +2503,39 @@ export class RunnerRuntime {
2114
2503
  };
2115
2504
  }));
2116
2505
  }
2506
+ /** @internal Fail a question resume after exhausting its retry budget. */
2507
+ async failQuestionResume(workflowId, runId, { stepKey, suspendedAt, resumeCount, }) {
2508
+ const proof = await this.#assertResumeFence(workflowId, runId);
2509
+ return this.#withRunLock(workflowId, runId, () => this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
2510
+ const source = await this.#captureWorkflowStorage(workflowId);
2511
+ const { state, row } = await this.#readForTransition(source, workflowId, runId);
2512
+ const provenance = runProvenance(state);
2513
+ if (proof &&
2514
+ (provenance?.version !== 2 ||
2515
+ provenance.startToken !== proof.startToken ||
2516
+ source.tablePrefix !== proof.tablePrefix))
2517
+ throw new RunStateUnreadableError(workflowId, runId);
2518
+ const lifecycle = lifecycleFromRequestContext(state.requestContext);
2519
+ const result = state.context?.[stepKey];
2520
+ const attempt = Array.isArray(result)
2521
+ ? result.at(-1)
2522
+ : result;
2523
+ const counts = new Map(provenance?.resumeCounts);
2524
+ if (state.status !== 'suspended' ||
2525
+ lifecycle?.terminal ||
2526
+ lifecycle?.transitionIntent ||
2527
+ !Object.hasOwn(state.suspendedPaths ?? {}, stepKey) ||
2528
+ attempt === null ||
2529
+ typeof attempt !== 'object' ||
2530
+ !('suspendedAt' in attempt) ||
2531
+ attempt.suspendedAt !== suspendedAt ||
2532
+ (counts.get(stepKey) ?? 0) !== resumeCount)
2533
+ return undefined;
2534
+ const now = Date.now();
2535
+ await this.#persistLifecycle(workflowId, runId, { ...state, ...failedByMarker('questionResumeFailedAt', now) }, advanceLifecycle(lifecycle, { questionResumeFailedAt: now }), now, source, row);
2536
+ return this.#summaryAfterPersist(workflowId, runId, source, provenance);
2537
+ })));
2538
+ }
2117
2539
  /**
2118
2540
  * The run's row, when no leg has marked it live within RUN_LEG_SILENT_MS and
2119
2541
  * the storage can compare-and-set it; `undefined` otherwise.
@@ -2214,17 +2636,23 @@ export class RunnerRuntime {
2214
2636
  if (lifecycle !== undefined) {
2215
2637
  base[RUN_LIFECYCLE_CONTEXT_KEY] = lifecycle;
2216
2638
  }
2639
+ if (leg.kind === 'restart') {
2640
+ // Mastra fills missing keys from the prior snapshot.
2641
+ base[BREAKWATER_CONNECTOR_GRANTS_KEY] = [];
2642
+ }
2217
2643
  // No isolation scope is minted here: a deployment serves exactly one
2218
2644
  // organization. The isolation-scope context key is RESERVED, so a provider
2219
2645
  // can never mint a scope that desyncs from the execution identity below.
2220
- if (leg.kind === 'start') {
2646
+ if (leg.kind === 'start' || leg.kind === 'restart') {
2221
2647
  base[BREAKWATER_CONNECTOR_EXECUTION_KEY] = {
2222
2648
  kind: 'start',
2223
2649
  workflowId,
2224
2650
  runId,
2225
2651
  };
2226
2652
  }
2227
- else if (leg.step !== undefined && leg.suspendedAt !== undefined) {
2653
+ else if (leg.kind === 'resume' &&
2654
+ leg.step !== undefined &&
2655
+ leg.suspendedAt !== undefined) {
2228
2656
  base[BREAKWATER_CONNECTOR_EXECUTION_KEY] = {
2229
2657
  kind: 'resume',
2230
2658
  workflowId,
@@ -2246,7 +2674,7 @@ export class RunnerRuntime {
2246
2674
  : undefined;
2247
2675
  return orderedRequestContext(base, values, storedRequestContext);
2248
2676
  }
2249
- async #trustedResumePreparation(workflowId, runId, state, options) {
2677
+ async #trustedResumePreparation(workflowId, runId, state, options, restart) {
2250
2678
  const { step: selectedStep, requestedBy, requestedByKind, deadlineMs, economicOperations, expectedSuspension, } = options;
2251
2679
  if (requestedBy !== undefined && !isExecutionPrincipalId(requestedBy)) {
2252
2680
  throw new InvalidRunRequestError('requestedBy is malformed');
@@ -2258,7 +2686,7 @@ export class RunnerRuntime {
2258
2686
  if ((requestedBy === undefined) !== (requestedByKind === undefined)) {
2259
2687
  throw new InvalidRunRequestError('requestedBy and requestedByKind must be provided together');
2260
2688
  }
2261
- const step = resolveResumeStep(selectedStep, state);
2689
+ const step = restart ? undefined : resolveResumeStep(selectedStep, state);
2262
2690
  const stepKey = step?.join('.');
2263
2691
  // resumeCount is read BEFORE this resume increments it: it is the count
2264
2692
  // of prior resumes = the ordinal of the CURRENT suspension being resumed
@@ -2274,19 +2702,16 @@ export class RunnerRuntime {
2274
2702
  ? storedProvenance?.requestedByKind
2275
2703
  : requestedByKind;
2276
2704
  const priorCounts = new Map(storedProvenance?.resumeCounts ?? []);
2277
- const leg = {
2278
- kind: 'resume',
2279
- step,
2280
- suspendedAt: stepKey !== undefined ? suspendedAtOf(state.steps, stepKey) : undefined,
2281
- resumeCount: stepKey !== undefined ? priorCounts.get(stepKey) : undefined,
2282
- };
2283
- // The pair the leg's grant minting reads, compared as
2284
- // boundToCurrentSuspension compares it.
2705
+ const suspendedAt = stepKey === undefined ? undefined : suspendedAtOf(state.steps, stepKey);
2706
+ const resumeCount = stepKey === undefined ? undefined : priorCounts.get(stepKey);
2707
+ const leg = restart
2708
+ ? { kind: 'restart' }
2709
+ : { kind: 'resume', step, suspendedAt, resumeCount };
2285
2710
  if (expectedSuspension !== undefined) {
2286
2711
  if (stepKey === undefined)
2287
2712
  throw new InvalidRunRequestError('expectedSuspension requires a resolvable resumed step');
2288
- if (leg.suspendedAt !== expectedSuspension.suspendedAt ||
2289
- leg.resumeCount !== expectedSuspension.resumeCount)
2713
+ if (suspendedAt !== expectedSuspension.suspendedAt ||
2714
+ (resumeCount ?? 0) !== (expectedSuspension.resumeCount ?? 0))
2290
2715
  throw new SuspensionChangedError(workflowId, runId, stepKey);
2291
2716
  }
2292
2717
  const nextCounts = new Map(priorCounts);
@@ -2449,7 +2874,8 @@ export class RunnerRuntime {
2449
2874
  * writes. Never throws: the caller's summary read follows.
2450
2875
  */
2451
2876
  async #failUnstorableLeg(workflowId, runId, active, error) {
2452
- if (!isRunStateNotStorable(error))
2877
+ if (!isRunStateNotStorable(error) ||
2878
+ isPauseLegAbort(active.run?.abortController.signal.reason))
2453
2879
  return;
2454
2880
  const { source, requestContext } = active;
2455
2881
  if (source?.storage === 'd1' && source.replace && requestContext) {