@proofoftech/flowsafe 0.14.0 → 0.16.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 (108) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +40 -6
  3. package/dist/agent-host/router.d.ts.map +1 -1
  4. package/dist/agent-host/router.js +44 -2
  5. package/dist/agent-host/router.js.map +1 -1
  6. package/dist/agent-host/thread-host.d.ts +7 -0
  7. package/dist/agent-host/thread-host.d.ts.map +1 -1
  8. package/dist/agent-host/thread-host.js +329 -213
  9. package/dist/agent-host/thread-host.js.map +1 -1
  10. package/dist/agent-host/thread-topology.d.ts +1 -0
  11. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  12. package/dist/agent-host/thread-topology.js +14 -1
  13. package/dist/agent-host/thread-topology.js.map +1 -1
  14. package/dist/agent-runner/durable-agent-runner.d.ts +4 -1
  15. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  16. package/dist/agent-runner/durable-agent-runner.js +8 -1
  17. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  18. package/dist/approval-api/d1-store.d.ts +4 -2
  19. package/dist/approval-api/d1-store.d.ts.map +1 -1
  20. package/dist/approval-api/d1-store.js +113 -13
  21. package/dist/approval-api/d1-store.js.map +1 -1
  22. package/dist/approval-api/index.d.ts +2 -2
  23. package/dist/approval-api/index.d.ts.map +1 -1
  24. package/dist/approval-api/index.js.map +1 -1
  25. package/dist/approval-api/service.d.ts.map +1 -1
  26. package/dist/approval-api/service.js +4 -1
  27. package/dist/approval-api/service.js.map +1 -1
  28. package/dist/approval-api/store-factory.d.ts +5 -1
  29. package/dist/approval-api/store-factory.d.ts.map +1 -1
  30. package/dist/approval-api/store-factory.js +7 -2
  31. package/dist/approval-api/store-factory.js.map +1 -1
  32. package/dist/approval-api/store.d.ts +6 -2
  33. package/dist/approval-api/store.d.ts.map +1 -1
  34. package/dist/approval-api/store.js +1 -1
  35. package/dist/approval-api/store.js.map +1 -1
  36. package/dist/do-runner/cf-types.d.ts +1 -0
  37. package/dist/do-runner/cf-types.d.ts.map +1 -1
  38. package/dist/do-runner/d1-storage.d.ts +32 -1
  39. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  40. package/dist/do-runner/d1-storage.js +160 -8
  41. package/dist/do-runner/d1-storage.js.map +1 -1
  42. package/dist/do-runner/deployment-identity.d.ts.map +1 -1
  43. package/dist/do-runner/deployment-identity.js +19 -3
  44. package/dist/do-runner/deployment-identity.js.map +1 -1
  45. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  46. package/dist/do-runner/do-error-response.js +15 -8
  47. package/dist/do-runner/do-error-response.js.map +1 -1
  48. package/dist/do-runner/durable-object.d.ts +7 -0
  49. package/dist/do-runner/durable-object.d.ts.map +1 -1
  50. package/dist/do-runner/durable-object.js +107 -6
  51. package/dist/do-runner/durable-object.js.map +1 -1
  52. package/dist/do-runner/execution-context.d.ts.map +1 -1
  53. package/dist/do-runner/execution-context.js +2 -0
  54. package/dist/do-runner/execution-context.js.map +1 -1
  55. package/dist/do-runner/index.d.ts +6 -5
  56. package/dist/do-runner/index.d.ts.map +1 -1
  57. package/dist/do-runner/index.js +2 -2
  58. package/dist/do-runner/index.js.map +1 -1
  59. package/dist/do-runner/run-lifecycle.d.ts +56 -0
  60. package/dist/do-runner/run-lifecycle.d.ts.map +1 -0
  61. package/dist/do-runner/run-lifecycle.js +179 -0
  62. package/dist/do-runner/run-lifecycle.js.map +1 -0
  63. package/dist/do-runner/runtime.d.ts +60 -2
  64. package/dist/do-runner/runtime.d.ts.map +1 -1
  65. package/dist/do-runner/runtime.js +545 -75
  66. package/dist/do-runner/runtime.js.map +1 -1
  67. package/dist/host-kit/approval-bridge.d.ts +7 -0
  68. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  69. package/dist/host-kit/approval-bridge.js +21 -0
  70. package/dist/host-kit/approval-bridge.js.map +1 -1
  71. package/dist/host-kit/do-response.d.ts.map +1 -1
  72. package/dist/host-kit/do-response.js +4 -1
  73. package/dist/host-kit/do-response.js.map +1 -1
  74. package/dist/host-kit/do-run-topology.d.ts +8 -3
  75. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  76. package/dist/host-kit/do-run-topology.js +20 -6
  77. package/dist/host-kit/do-run-topology.js.map +1 -1
  78. package/dist/host-kit/flowsafe-worker.d.ts +38 -23
  79. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  80. package/dist/host-kit/flowsafe-worker.js +137 -23
  81. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  82. package/dist/host-kit/host-approval-service.d.ts +1 -1
  83. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  84. package/dist/host-kit/host-approval-service.js +13 -4
  85. package/dist/host-kit/host-approval-service.js.map +1 -1
  86. package/dist/host-kit/index.d.ts +4 -4
  87. package/dist/host-kit/index.d.ts.map +1 -1
  88. package/dist/host-kit/index.js +2 -2
  89. package/dist/host-kit/index.js.map +1 -1
  90. package/dist/host-kit/run-route-error.d.ts +3 -2
  91. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  92. package/dist/host-kit/run-route-error.js +4 -2
  93. package/dist/host-kit/run-route-error.js.map +1 -1
  94. package/dist/host-kit/run-router.d.ts +4 -0
  95. package/dist/host-kit/run-router.d.ts.map +1 -1
  96. package/dist/host-kit/run-router.js +42 -9
  97. package/dist/host-kit/run-router.js.map +1 -1
  98. package/dist/host-kit/workflow-meta.d.ts +3 -3
  99. package/dist/schedules/schedules-d1.d.ts +8 -0
  100. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  101. package/dist/schedules/schedules-d1.js +59 -0
  102. package/dist/schedules/schedules-d1.js.map +1 -1
  103. package/dist/signals/thread-do-routes.d.ts +3 -1
  104. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  105. package/dist/signals/thread-do-routes.js +8 -0
  106. package/dist/signals/thread-do-routes.js.map +1 -1
  107. package/package.json +3 -7
  108. package/scripts/seed-deployment-identity.mjs +11 -3
@@ -10,11 +10,12 @@
10
10
  // silently skips it otherwise), which is why this class owns the Mastra
11
11
  // instance instead of running standalone workflows.
12
12
  //
13
- // Concurrency: start/resume are serialized per run — keyed by the run's
14
- // full identity (workflowId + runId) — via an in-instance FIFO lock.
15
- // Without it, two concurrent resumes both pass the 'suspended' pre-check
16
- // and the gated step's side effects execute twice — the exact failure an
17
- // approval product must not have. The lock is per runtime instance;
13
+ // Concurrency: start/resume and terminal transitions are serialized per run —
14
+ // keyed by the run's full identity (workflowId + runId) — via distinct
15
+ // execution and lifecycle FIFO locks.
16
+ // Without the execution lock, two concurrent resumes both pass the
17
+ // 'suspended' pre-check and the gated step's side effects execute twice — the
18
+ // exact failure an approval product must not have. Both locks are per runtime instance;
18
19
  // cross-instance serialization comes from routing one DO instance per run
19
20
  // (see durable-object.ts).
20
21
  import { Mastra } from '@mastra/core/mastra';
@@ -24,6 +25,7 @@ import { BREAKWATER_ACTOR_KEY, BREAKWATER_CONNECTOR_EXECUTION_KEY, BREAKWATER_IS
24
25
  import { isReservedExecutionContextKey, RUN_PROVENANCE_CONTEXT_KEY, stripReservedExecutionContext, } from './execution-context.js';
25
26
  import { mastraRegistryEntries } from './mastra-registry.js';
26
27
  import { isPathSafeId } from './path-safe-id.js';
28
+ import { canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext, RUN_LIFECYCLE_CONTEXT_KEY, } from './run-lifecycle.js';
27
29
  export class UnknownWorkflowError extends Error {
28
30
  constructor(workflowId) {
29
31
  super(`unknown workflow '${workflowId}'`);
@@ -48,6 +50,20 @@ export class RunAlreadyExistsError extends Error {
48
50
  this.name = 'RunAlreadyExistsError';
49
51
  }
50
52
  }
53
+ export class RunTerminalConflictError extends Error {
54
+ constructor(workflowId, runId, status) {
55
+ super(`run '${runId}' of workflow '${workflowId}' is already terminal with status '${status}'`);
56
+ this.name = 'RunTerminalConflictError';
57
+ }
58
+ }
59
+ export class RunLifecycleBlockedError extends Error {
60
+ reason;
61
+ constructor(reason) {
62
+ super(reason.message);
63
+ this.name = 'RunLifecycleBlockedError';
64
+ this.reason = reason;
65
+ }
66
+ }
51
67
  /** A request the caller can fix: bad input/resume data or step selection. */
52
68
  export class InvalidRunRequestError extends Error {
53
69
  constructor(message) {
@@ -200,7 +216,7 @@ function errorText(error) {
200
216
  }
201
217
  return String(error);
202
218
  }
203
- function summarize(runId, result, counts, requestedBy, requestedByKind) {
219
+ function summarize(runId, result, counts, requestedBy, requestedByKind, deadlineAt) {
204
220
  let summary;
205
221
  switch (result.status) {
206
222
  case 'success':
@@ -248,6 +264,8 @@ function summarize(runId, result, counts, requestedBy, requestedByKind) {
248
264
  if (requestedByKind !== undefined) {
249
265
  summary.requestedByKind = requestedByKind;
250
266
  }
267
+ if (deadlineAt !== undefined)
268
+ summary.deadlineAt = deadlineAt;
251
269
  return summary;
252
270
  }
253
271
  // Storage may hand timestamps back as Date or as a serialized string
@@ -323,17 +341,21 @@ function byStep(suspendedKeys, lookup) {
323
341
  // projection truthfully degrades to status-only rather than fabricating
324
342
  // detail.
325
343
  function summarizeState(runId, state, counts, requestedBy, requestedByKind) {
344
+ const lifecycle = lifecycleFromRequestContext(state.requestContext);
326
345
  const summary = {
327
346
  runId,
328
- status: state.status,
347
+ status: lifecycle?.terminal?.status ?? state.status,
329
348
  createdAt: toIso(state.createdAt),
330
349
  updatedAt: toIso(state.updatedAt),
331
350
  };
332
- if (requestedBy !== undefined)
333
- summary.requestedBy = requestedBy;
334
- if (requestedByKind !== undefined) {
335
- summary.requestedByKind = requestedByKind;
351
+ if (lifecycle?.deadlineAt !== undefined) {
352
+ summary.deadlineAt = lifecycle.deadlineAt;
336
353
  }
354
+ if (lifecycle?.terminal) {
355
+ summary.errorEnvelope = lifecycle.terminal.error;
356
+ return summaryWithRequester(summary, requestedBy, requestedByKind);
357
+ }
358
+ summaryWithRequester(summary, requestedBy, requestedByKind);
337
359
  if (state.status === 'success') {
338
360
  summary.result = state.result;
339
361
  }
@@ -359,6 +381,13 @@ function summarizeState(runId, state, counts, requestedBy, requestedByKind) {
359
381
  }
360
382
  return summary;
361
383
  }
384
+ function summaryWithRequester(summary, requestedBy, requestedByKind) {
385
+ if (requestedBy !== undefined)
386
+ summary.requestedBy = requestedBy;
387
+ if (requestedByKind !== undefined)
388
+ summary.requestedByKind = requestedByKind;
389
+ return summary;
390
+ }
362
391
  const TRUSTED_IDENTITY_CONTEXT_KEYS = new Set([
363
392
  BREAKWATER_ACTOR_KEY,
364
393
  'breakwater.auditContext',
@@ -375,6 +404,7 @@ function orderedRequestContext(runtimeContext, provided, scheduled) {
375
404
  key === BREAKWATER_ISOLATION_SCOPE_KEY ||
376
405
  key === BREAKWATER_CONNECTOR_EXECUTION_KEY ||
377
406
  key === RUN_PROVENANCE_CONTEXT_KEY ||
407
+ key === RUN_LIFECYCLE_CONTEXT_KEY ||
378
408
  key === 'runId') {
379
409
  continue;
380
410
  }
@@ -396,6 +426,67 @@ function orderedRequestContext(runtimeContext, provided, scheduled) {
396
426
  ...identity,
397
427
  ]);
398
428
  }
429
+ const TERMINABLE_RUN_STATUSES = new Set([
430
+ 'running',
431
+ 'waiting',
432
+ 'pending',
433
+ 'paused',
434
+ 'waiting_callback',
435
+ 'waiting_signal',
436
+ 'retry_wait',
437
+ 'suspended',
438
+ ]);
439
+ function relativeDeadline(deadlineMs, now = Date.now()) {
440
+ if (deadlineMs === undefined)
441
+ return undefined;
442
+ if (!Number.isSafeInteger(deadlineMs) || deadlineMs < 0) {
443
+ throw new InvalidRunRequestError('deadlineMs must be a nonnegative safe integer');
444
+ }
445
+ const deadlineAt = now + deadlineMs;
446
+ if (!Number.isSafeInteger(deadlineAt)) {
447
+ throw new InvalidRunRequestError('deadlineMs exceeds the supported range');
448
+ }
449
+ return deadlineAt;
450
+ }
451
+ function lifecycleForStart(options) {
452
+ const deadlineAt = relativeDeadline(options.deadlineMs);
453
+ const economicOperations = canonicalEconomicOperations(options.economicOperations);
454
+ const scheduleDispatch = canonicalScheduleDispatch(options.scheduleDispatch);
455
+ if (deadlineAt === undefined &&
456
+ economicOperations === undefined &&
457
+ scheduleDispatch === undefined) {
458
+ return undefined;
459
+ }
460
+ return {
461
+ version: 1,
462
+ revision: 1,
463
+ ...(deadlineAt === undefined ? {} : { deadlineAt }),
464
+ ...(economicOperations === undefined ? {} : { economicOperations }),
465
+ ...(scheduleDispatch === undefined ? {} : { scheduleDispatch }),
466
+ };
467
+ }
468
+ function effectiveLifecycle(persisted, active) {
469
+ if (!persisted)
470
+ return active;
471
+ if (!active)
472
+ return persisted;
473
+ if (persisted.revision > active.revision)
474
+ return persisted;
475
+ if (active.revision > persisted.revision)
476
+ return active;
477
+ return {
478
+ ...persisted,
479
+ ...active,
480
+ ...((persisted.transitionIntent ?? active.transitionIntent)
481
+ ? {
482
+ transitionIntent: persisted.transitionIntent ?? active.transitionIntent,
483
+ }
484
+ : {}),
485
+ ...((persisted.terminal ?? active.terminal)
486
+ ? { terminal: persisted.terminal ?? active.terminal }
487
+ : {}),
488
+ };
489
+ }
399
490
  export class RunnerRuntime {
400
491
  #storage;
401
492
  #logger;
@@ -403,6 +494,9 @@ export class RunnerRuntime {
403
494
  #agents = new Map();
404
495
  #workflows = new Map();
405
496
  #runLocks = new Map();
497
+ #activeRuns = new Map();
498
+ #terminalAbortIntents = new Map();
499
+ #lifecycleLocks = new Map();
406
500
  // The host DO's pubsub identity (RunnerRuntimeOptions.pubsub), threaded into
407
501
  // both createRun sites below (CI-M-002-002) so a configured host publishes and
408
502
  // replays on ONE shared feed. Undefined ⇒ core defaults a fresh emitter per
@@ -511,7 +605,8 @@ export class RunnerRuntime {
511
605
  attemptToken: startAttemptToken,
512
606
  resumeCounts: [],
513
607
  };
514
- const requestContext = await this.#requestContextFor(workflowId, runId, { kind: 'start' }, provenance, options.storedRequestContext);
608
+ const lifecycle = lifecycleForStart(options);
609
+ const requestContext = await this.#requestContextFor(workflowId, runId, { kind: 'start' }, provenance, options.storedRequestContext, lifecycle);
515
610
  // Thread the host DO's pubsub identity into the run (CI-M-002-002). Core
516
611
  // accepts `createRun({ runId, pubsub })` at every one of its OWN call
517
612
  // sites (agent/durable index.js:5224/5541) and stamps it straight onto
@@ -523,6 +618,9 @@ export class RunnerRuntime {
523
618
  // and observe()/replay agree (do-runner/pubsub.ts).
524
619
  const run = await workflow.createRun({ runId, pubsub: this.#pubsub });
525
620
  let result;
621
+ const activeKey = this.#runKey(workflowId, runId);
622
+ const active = { run, lifecycle, requestContext };
623
+ this.#activeRuns.set(activeKey, active);
526
624
  try {
527
625
  result = await run.start({
528
626
  inputData: options.inputData,
@@ -536,6 +634,11 @@ export class RunnerRuntime {
536
634
  return recovered;
537
635
  throw asClientError(error) ?? error;
538
636
  }
637
+ finally {
638
+ if (this.#activeRuns.get(activeKey) === active) {
639
+ this.#activeRuns.delete(activeKey);
640
+ }
641
+ }
539
642
  try {
540
643
  await this.#reconcileTerminalState(workflowId, run.runId, result, requestContext);
541
644
  }
@@ -545,7 +648,7 @@ export class RunnerRuntime {
545
648
  return recovered;
546
649
  throw error;
547
650
  }
548
- return summarize(run.runId, result, undefined, provenance.requestedBy, provenance.requestedByKind);
651
+ return summarize(run.runId, result, undefined, provenance.requestedBy, provenance.requestedByKind, lifecycle?.deadlineAt);
549
652
  });
550
653
  }
551
654
  /**
@@ -565,16 +668,43 @@ export class RunnerRuntime {
565
668
  // Provider before createRun for symmetry with start(): a resume-time
566
669
  // createRun only reattaches (no snapshot write), but failing before it
567
670
  // still does the least work and keeps the ordering invariant uniform.
568
- const { nextCounts, provenance, requestContext } = await this.#trustedResumePreparation(workflowId, runId, state, options.step, options.requestedBy, options.requestedByKind);
569
- if (options.prepareExecution) {
570
- const preparationValues = structuredClone(Object.fromEntries(requestContext.entries()));
571
- await options.prepareExecution(new RequestContext(Object.entries(preparationValues)));
572
- }
573
- // Same host pubsub identity as start() (CI-M-002-002) — see the note
574
- // there; undefined stays byte-identical to `createRun({ runId })`.
575
- const run = await workflow.createRun({ runId, pubsub: this.#pubsub });
671
+ const { nextCounts, provenance, requestContext, lifecycle } = await this.#trustedResumePreparation(workflowId, runId, state, options.step, options.requestedBy, options.requestedByKind, options.deadlineMs, options.economicOperations);
672
+ const activeKey = this.#runKey(workflowId, runId);
673
+ const active = { lifecycle, requestContext };
674
+ await this.#withLifecycleLock(workflowId, runId, async () => {
675
+ const current = await this.#loadSnapshot(workflowId, runId);
676
+ if (!current)
677
+ throw new UnknownRunError(workflowId, runId);
678
+ const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
679
+ if (currentLifecycle?.terminal || currentLifecycle?.transitionIntent) {
680
+ throw new RunTerminalConflictError(workflowId, runId, current.status);
681
+ }
682
+ active.lifecycle = effectiveLifecycle(currentLifecycle, lifecycle);
683
+ this.#activeRuns.set(activeKey, active);
684
+ });
685
+ let run;
576
686
  let result;
577
687
  try {
688
+ if (options.prepareExecution) {
689
+ const preparationValues = structuredClone(Object.fromEntries(requestContext.entries()));
690
+ await options.prepareExecution(new RequestContext(Object.entries(preparationValues)));
691
+ }
692
+ // Same host pubsub identity as start() (CI-M-002-002) — see the note
693
+ // there; undefined stays byte-identical to `createRun({ runId })`.
694
+ run = await workflow.createRun({ runId, pubsub: this.#pubsub });
695
+ await this.#withLifecycleLock(workflowId, runId, async () => {
696
+ const current = await this.#loadSnapshot(workflowId, runId);
697
+ if (!current)
698
+ throw new UnknownRunError(workflowId, runId);
699
+ const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
700
+ if (currentLifecycle?.terminal ||
701
+ currentLifecycle?.transitionIntent ||
702
+ this.#activeRuns.get(activeKey) !== active) {
703
+ throw new RunTerminalConflictError(workflowId, runId, current.status);
704
+ }
705
+ active.lifecycle = effectiveLifecycle(currentLifecycle, active.lifecycle);
706
+ active.run = run;
707
+ });
578
708
  result = await run.resume({
579
709
  step: options.step,
580
710
  resumeData: options.resumeData,
@@ -589,9 +719,14 @@ export class RunnerRuntime {
589
719
  // on its prior suspension, so neither requester nor ordinal advances.
590
720
  throw asClientError(error) ?? error;
591
721
  }
722
+ finally {
723
+ if (this.#activeRuns.get(activeKey) === active) {
724
+ this.#activeRuns.delete(activeKey);
725
+ }
726
+ }
592
727
  // A re-suspension produced by this resume carries the incremented ordinal
593
728
  // in the same authoritative snapshot as the new workflow state.
594
- const summary = summarize(run.runId, result, nextCounts, provenance.requestedBy, provenance.requestedByKind);
729
+ const summary = summarize(run.runId, result, nextCounts, provenance.requestedBy, provenance.requestedByKind, lifecycle?.deadlineAt);
595
730
  try {
596
731
  await this.#reconcileTerminalState(workflowId, run.runId, result, requestContext);
597
732
  }
@@ -604,16 +739,276 @@ export class RunnerRuntime {
604
739
  return summary;
605
740
  });
606
741
  }
742
+ /** Idempotently cancel a live run from its persisted snapshot. */
743
+ terminate(workflowId, runId, now = Date.now()) {
744
+ return this.#transitionTerminal(workflowId, runId, 'cancelled', now);
745
+ }
746
+ /**
747
+ * Interrupt the in-isolate Mastra execution before waiting on the run lock.
748
+ * A deadline CAS is checked from persisted state first, so a stale sweep can
749
+ * never cancel a live run whose deadline was extended.
750
+ */
751
+ async cancelActiveExecution(workflowId, runId, intendedStatus, replayPrincipals, cas, now = Date.now()) {
752
+ this.#getWorkflow(workflowId);
753
+ const prepared = await this.#withLifecycleLock(workflowId, runId, async () => {
754
+ const state = await this.#loadSnapshot(workflowId, runId);
755
+ if (!state)
756
+ throw new UnknownRunError(workflowId, runId);
757
+ const key = this.#runKey(workflowId, runId);
758
+ const active = this.#activeRuns.get(key);
759
+ const lifecycle = effectiveLifecycle(lifecycleFromRequestContext(state.requestContext), active?.lifecycle);
760
+ if (lifecycle?.terminal)
761
+ return undefined;
762
+ if (hasDisputedSettlement(lifecycle)) {
763
+ throw new RunLifecycleBlockedError({
764
+ code: 'DISPUTED_SETTLEMENT',
765
+ message: 'run termination is blocked while an economic operation is disputed',
766
+ });
767
+ }
768
+ const existingIntent = lifecycle?.transitionIntent;
769
+ if (existingIntent?.status === intendedStatus &&
770
+ (cas === undefined ||
771
+ (existingIntent.expectedRevision === cas.expectedRevision &&
772
+ existingIntent.expectedDeadlineAt === cas.expectedDeadlineAt))) {
773
+ if (!active?.run)
774
+ return undefined;
775
+ this.#terminalAbortIntents.set(key, intendedStatus);
776
+ return { run: active.run, key };
777
+ }
778
+ if (cas &&
779
+ (lifecycle?.revision !== cas.expectedRevision ||
780
+ lifecycle.deadlineAt !== cas.expectedDeadlineAt ||
781
+ lifecycle.deadlineAt === undefined ||
782
+ lifecycle.deadlineAt > now)) {
783
+ return undefined;
784
+ }
785
+ if (!TERMINABLE_RUN_STATUSES.has(state.status)) {
786
+ throw new RunTerminalConflictError(workflowId, runId, state.status);
787
+ }
788
+ if (cas &&
789
+ active &&
790
+ (active.lifecycle?.revision !== cas.expectedRevision ||
791
+ active.lifecycle.deadlineAt !== cas.expectedDeadlineAt)) {
792
+ return undefined;
793
+ }
794
+ const principals = canonicalReplayPrincipals(replayPrincipals);
795
+ const intent = {
796
+ ...(lifecycle ?? { version: 1, revision: 0 }),
797
+ revision: (lifecycle?.revision ?? 0) + 1,
798
+ transitionIntent: {
799
+ status: intendedStatus,
800
+ requestedAt: now,
801
+ replayPrincipals: principals,
802
+ ...(cas
803
+ ? {
804
+ expectedRevision: cas.expectedRevision,
805
+ expectedDeadlineAt: cas.expectedDeadlineAt,
806
+ }
807
+ : {}),
808
+ },
809
+ };
810
+ await this.#persistLifecycle(workflowId, runId, state, intent, now);
811
+ if (active) {
812
+ active.lifecycle = intent;
813
+ active.requestContext?.set(RUN_LIFECYCLE_CONTEXT_KEY, intent);
814
+ }
815
+ if (!active?.run)
816
+ return undefined;
817
+ this.#terminalAbortIntents.set(key, intendedStatus);
818
+ return { run: active.run, key };
819
+ });
820
+ if (!prepared)
821
+ return false;
822
+ try {
823
+ await prepared.run.cancel();
824
+ }
825
+ catch (error) {
826
+ this.#terminalAbortIntents.delete(prepared.key);
827
+ throw error;
828
+ }
829
+ return true;
830
+ }
831
+ /** Trusted host variant that persists the exact identities allowed to retry. */
832
+ terminateAsPrincipal(workflowId, runId, principal, owner, now = Date.now()) {
833
+ return this.#transitionTerminal(workflowId, runId, 'cancelled', now, undefined, [principal, owner], principal);
834
+ }
835
+ /** CAS-guarded deadline transition driven through the owner Durable Object. */
836
+ timeOut(workflowId, runId, cas, now = Date.now()) {
837
+ if (!Number.isSafeInteger(cas.expectedRevision) ||
838
+ cas.expectedRevision < 1 ||
839
+ (cas.expectedDeadlineAt !== undefined &&
840
+ (!Number.isSafeInteger(cas.expectedDeadlineAt) ||
841
+ cas.expectedDeadlineAt < 0)) ||
842
+ !Number.isSafeInteger(now) ||
843
+ now < 0) {
844
+ throw new InvalidRunRequestError('deadline transition CAS is malformed');
845
+ }
846
+ return this.#transitionTerminal(workflowId, runId, 'timed_out', now, cas);
847
+ }
848
+ /** Trusted host deadline transition with retry principals persisted atomically. */
849
+ timeOutAsPrincipal(workflowId, runId, cas, principal, owner, now = Date.now()) {
850
+ return this.#transitionTerminal(workflowId, runId, 'timed_out', now, cas, [principal, owner], principal);
851
+ }
852
+ async #transitionTerminal(workflowId, runId, status, now, cas, replayPrincipals, replayingPrincipal) {
853
+ this.#getWorkflow(workflowId);
854
+ return this.#withRunLock(workflowId, runId, async () => {
855
+ const state = await this.#loadSnapshot(workflowId, runId);
856
+ if (!state)
857
+ throw new UnknownRunError(workflowId, runId);
858
+ const lifecycle = lifecycleFromRequestContext(state.requestContext);
859
+ if (lifecycle?.terminal) {
860
+ if (replayingPrincipal &&
861
+ !lifecycle.terminal.replayPrincipals.some((principal) => principal.kind === replayingPrincipal.kind &&
862
+ principal.id === replayingPrincipal.id)) {
863
+ throw new UnknownRunError(workflowId, runId);
864
+ }
865
+ return {
866
+ summary: await this.#summaryAfterPersist(workflowId, runId),
867
+ transitioned: false,
868
+ casMatched: cas === undefined ||
869
+ (lifecycle.terminal.status === 'timed_out' &&
870
+ lifecycle.deadlineAt === cas.expectedDeadlineAt),
871
+ cleanup: {
872
+ revision: lifecycle.revision,
873
+ status: lifecycle.terminal.status,
874
+ cleanupCompleted: lifecycle.terminal.cleanupCompletedAt !== undefined,
875
+ ...(lifecycle.scheduleDispatch
876
+ ? { scheduleDispatch: lifecycle.scheduleDispatch }
877
+ : {}),
878
+ },
879
+ };
880
+ }
881
+ const transitionIntent = lifecycle?.transitionIntent;
882
+ const intentMatchesTransition = transitionIntent?.status === status &&
883
+ (cas === undefined ||
884
+ (transitionIntent.expectedRevision === cas.expectedRevision &&
885
+ transitionIntent.expectedDeadlineAt === cas.expectedDeadlineAt));
886
+ const intentMatchesCas = cas !== undefined && intentMatchesTransition;
887
+ if (cas !== undefined &&
888
+ !intentMatchesCas &&
889
+ (lifecycle?.revision !== cas.expectedRevision ||
890
+ lifecycle.deadlineAt !== cas.expectedDeadlineAt ||
891
+ lifecycle.deadlineAt === undefined ||
892
+ lifecycle.deadlineAt > now)) {
893
+ return {
894
+ summary: await this.#summaryAfterPersist(workflowId, runId),
895
+ transitioned: false,
896
+ casMatched: false,
897
+ cleanup: {
898
+ revision: lifecycle?.revision ?? 0,
899
+ status,
900
+ cleanupCompleted: false,
901
+ ...(lifecycle?.scheduleDispatch
902
+ ? { scheduleDispatch: lifecycle.scheduleDispatch }
903
+ : {}),
904
+ },
905
+ };
906
+ }
907
+ if (hasDisputedSettlement(lifecycle)) {
908
+ throw new RunLifecycleBlockedError({
909
+ code: 'DISPUTED_SETTLEMENT',
910
+ message: 'run termination is blocked while an economic operation is disputed',
911
+ });
912
+ }
913
+ const currentStatus = state.status;
914
+ const abortIntent = this.#terminalAbortIntents.get(this.#runKey(workflowId, runId));
915
+ if (!TERMINABLE_RUN_STATUSES.has(currentStatus) &&
916
+ !intentMatchesTransition &&
917
+ !(currentStatus === 'canceled' && abortIntent === status)) {
918
+ throw new RunTerminalConflictError(workflowId, runId, currentStatus);
919
+ }
920
+ const error = status === 'cancelled'
921
+ ? { code: 'CANCELLED', message: 'run was cancelled' }
922
+ : { code: 'TIMED_OUT', message: 'run deadline expired' };
923
+ const provenance = runProvenance(state);
924
+ const fallbackPrincipal = provenance?.requestedBy && provenance.requestedByKind
925
+ ? {
926
+ kind: provenance.requestedByKind,
927
+ id: provenance.requestedBy,
928
+ }
929
+ : { kind: 'system', id: 'flowsafe-system' };
930
+ const principals = canonicalReplayPrincipals(replayPrincipals ??
931
+ transitionIntent?.replayPrincipals ?? [fallbackPrincipal]);
932
+ const lifecycleBase = lifecycle
933
+ ? Object.fromEntries(Object.entries(lifecycle).filter(([key]) => key !== 'transitionIntent'))
934
+ : { version: 1, revision: 0 };
935
+ const next = {
936
+ ...lifecycleBase,
937
+ version: 1,
938
+ revision: (lifecycle?.revision ?? 0) + 1,
939
+ terminal: {
940
+ status,
941
+ error,
942
+ transitionedAt: now,
943
+ replayPrincipals: principals,
944
+ },
945
+ };
946
+ await this.#persistLifecycle(workflowId, runId, {
947
+ ...state,
948
+ status: status,
949
+ result: undefined,
950
+ error: {
951
+ name: status === 'cancelled' ? 'RunCancelledError' : 'RunTimedOutError',
952
+ message: error.message,
953
+ },
954
+ suspendedPaths: {},
955
+ waitingPaths: {},
956
+ resumeLabels: {},
957
+ activePaths: [],
958
+ activeStepsPath: {},
959
+ timestamp: now,
960
+ }, next, now);
961
+ this.#terminalAbortIntents.delete(this.#runKey(workflowId, runId));
962
+ return {
963
+ summary: await this.#summaryAfterPersist(workflowId, runId),
964
+ transitioned: true,
965
+ casMatched: true,
966
+ cleanup: {
967
+ revision: next.revision,
968
+ status,
969
+ cleanupCompleted: false,
970
+ ...(next.scheduleDispatch
971
+ ? { scheduleDispatch: next.scheduleDispatch }
972
+ : {}),
973
+ },
974
+ };
975
+ });
976
+ }
977
+ /** Marks idempotent terminal side-effect cleanup after every hook succeeds. */
978
+ async completeTerminalCleanup(workflowId, runId, expectedRevision, now = Date.now()) {
979
+ this.#getWorkflow(workflowId);
980
+ return this.#withRunLock(workflowId, runId, async () => {
981
+ const state = await this.#loadSnapshot(workflowId, runId);
982
+ if (!state)
983
+ throw new UnknownRunError(workflowId, runId);
984
+ const lifecycle = lifecycleFromRequestContext(state.requestContext);
985
+ if (!lifecycle?.terminal) {
986
+ throw new RunTerminalConflictError(workflowId, runId, state.status);
987
+ }
988
+ if (lifecycle.terminal.cleanupCompletedAt !== undefined) {
989
+ return this.#summaryAfterPersist(workflowId, runId);
990
+ }
991
+ if (lifecycle.revision !== expectedRevision) {
992
+ throw new Error('run terminal cleanup CAS no longer matches');
993
+ }
994
+ const next = {
995
+ ...lifecycle,
996
+ revision: lifecycle.revision + 1,
997
+ terminal: {
998
+ ...lifecycle.terminal,
999
+ cleanupCompletedAt: now,
1000
+ },
1001
+ };
1002
+ await this.#persistLifecycle(workflowId, runId, state, next, now);
1003
+ return this.#summaryAfterPersist(workflowId, runId);
1004
+ });
1005
+ }
607
1006
  async status(workflowId, runId) {
608
1007
  const workflow = this.#getWorkflow(workflowId);
609
1008
  const state = await this.#workflowState(workflow, runId);
610
1009
  if (!state)
611
1010
  return null;
612
- const provenance = runProvenance(state);
613
- // Snapshot provenance projects requester and resume ordinal alongside the
614
- // authoritative workflow state, including after isolate eviction.
615
- const counts = provenance ? new Map(provenance.resumeCounts) : undefined;
616
- return summarizeState(runId, state, counts, provenance?.requestedBy, provenance?.requestedByKind);
1011
+ return this.#summaryFromState(runId, state);
617
1012
  }
618
1013
  /**
619
1014
  * Reconcile an interrupted start against the token stored in the
@@ -651,7 +1046,7 @@ export class RunnerRuntime {
651
1046
  // the scope is never client-suppliable. Provider values are partitioned into
652
1047
  // stored application context, capabilities, and trusted identity so every
653
1048
  // layer has an explicit order and a provider cannot replace runtime scope.
654
- async #requestContextFor(workflowId, runId, leg, provenance, storedRequestContext) {
1049
+ async #requestContextFor(workflowId, runId, leg, provenance, storedRequestContext, lifecycle) {
655
1050
  const base = {
656
1051
  [BREAKWATER_WORKFLOW_SCOPE_KEY]: workflowId,
657
1052
  runId,
@@ -659,6 +1054,9 @@ export class RunnerRuntime {
659
1054
  if (provenance !== undefined) {
660
1055
  base[RUN_PROVENANCE_CONTEXT_KEY] = provenance;
661
1056
  }
1057
+ if (lifecycle !== undefined) {
1058
+ base[RUN_LIFECYCLE_CONTEXT_KEY] = lifecycle;
1059
+ }
662
1060
  // No isolation scope is minted here: a deployment serves exactly one
663
1061
  // organization, so breakwater's connector idempotency and rate-limit keys
664
1062
  // are deployment-wide by construction. Budget partitioning within a
@@ -696,7 +1094,7 @@ export class RunnerRuntime {
696
1094
  : undefined;
697
1095
  return orderedRequestContext(base, values, storedRequestContext);
698
1096
  }
699
- async #trustedResumePreparation(workflowId, runId, state, selectedStep, requestedBy, requestedByKind) {
1097
+ async #trustedResumePreparation(workflowId, runId, state, selectedStep, requestedBy, requestedByKind, deadlineMs, economicOperations) {
700
1098
  if (requestedBy !== undefined && !isExecutionPrincipalId(requestedBy)) {
701
1099
  throw new InvalidRunRequestError('requestedBy is malformed');
702
1100
  }
@@ -736,6 +1134,21 @@ export class RunnerRuntime {
736
1134
  attemptToken: crypto.randomUUID(),
737
1135
  resumeCounts: [...nextCounts],
738
1136
  };
1137
+ const storedLifecycle = lifecycleFromRequestContext(state.requestContext);
1138
+ const replacementDeadline = relativeDeadline(deadlineMs);
1139
+ const replacementOperations = canonicalEconomicOperations(economicOperations);
1140
+ const lifecycle = replacementDeadline === undefined && replacementOperations === undefined
1141
+ ? storedLifecycle
1142
+ : {
1143
+ ...(storedLifecycle ?? { version: 1, revision: 0 }),
1144
+ revision: (storedLifecycle?.revision ?? 0) + 1,
1145
+ ...(replacementDeadline === undefined
1146
+ ? {}
1147
+ : { deadlineAt: replacementDeadline }),
1148
+ ...(replacementOperations === undefined
1149
+ ? {}
1150
+ : { economicOperations: replacementOperations }),
1151
+ };
739
1152
  const requestContext = await this.#requestContextFor(workflowId, runId, {
740
1153
  kind: 'resume',
741
1154
  step,
@@ -743,16 +1156,55 @@ export class RunnerRuntime {
743
1156
  ? suspendedAtOf(state.steps, stepKey)
744
1157
  : undefined,
745
1158
  resumeCount: stepKey !== undefined ? priorCounts?.get(stepKey) : undefined,
746
- }, provenance);
1159
+ }, provenance, undefined, lifecycle);
747
1160
  return {
748
1161
  nextCounts,
749
1162
  provenance,
750
1163
  requestContext,
1164
+ lifecycle,
751
1165
  };
752
1166
  }
753
1167
  #workflowState(workflow, runId) {
754
1168
  return workflow.getWorkflowRunById(runId, { fields: RUN_STATE_FIELDS });
755
1169
  }
1170
+ async #loadSnapshot(workflowId, runId) {
1171
+ const workflows = await this.#storage.getStore('workflows');
1172
+ if (!workflows) {
1173
+ throw new Error('RunnerRuntime: workflows storage is unavailable');
1174
+ }
1175
+ return workflows.loadWorkflowSnapshot({ workflowName: workflowId, runId });
1176
+ }
1177
+ async #persistLifecycle(workflowId, runId, state, lifecycle, now) {
1178
+ const workflows = await this.#storage.getStore('workflows');
1179
+ if (!workflows) {
1180
+ throw new Error('RunnerRuntime: workflows storage is unavailable');
1181
+ }
1182
+ const persisted = {
1183
+ ...state,
1184
+ requestContext: {
1185
+ ...(state.requestContext ?? {}),
1186
+ [RUN_LIFECYCLE_CONTEXT_KEY]: lifecycle,
1187
+ },
1188
+ timestamp: now,
1189
+ };
1190
+ await workflows.persistWorkflowSnapshot({
1191
+ workflowName: workflowId,
1192
+ runId,
1193
+ snapshot: persisted,
1194
+ updatedAt: new Date(now),
1195
+ });
1196
+ return persisted;
1197
+ }
1198
+ async #summaryAfterPersist(workflowId, runId) {
1199
+ const state = await this.#workflowState(this.#getWorkflow(workflowId), runId);
1200
+ if (!state)
1201
+ throw new UnknownRunError(workflowId, runId);
1202
+ return this.#summaryFromState(runId, state);
1203
+ }
1204
+ #summaryFromState(runId, state) {
1205
+ const provenance = runProvenance(state);
1206
+ return summarizeState(runId, state, provenance ? new Map(provenance.resumeCounts) : undefined, provenance?.requestedBy, provenance?.requestedByKind);
1207
+ }
756
1208
  async #summaryForAttempt(workflow, runId, attemptToken) {
757
1209
  const persisted = await this.#workflowState(workflow, runId);
758
1210
  if (!persisted)
@@ -766,47 +1218,60 @@ export class RunnerRuntime {
766
1218
  const opts = terminalStateUpdate(result);
767
1219
  if (!opts)
768
1220
  return;
769
- const workflows = await this.#storage.getStore('workflows');
770
- if (!workflows) {
771
- throw new Error('RunnerRuntime: workflows storage is unavailable while persisting terminal state');
772
- }
773
- const snapshot = await workflows.loadWorkflowSnapshot({
774
- workflowName: workflowId,
775
- runId,
776
- });
777
- if (!snapshot) {
778
- throw new Error(`RunnerRuntime: run '${runId}' of workflow '${workflowId}' completed without a durable snapshot`);
779
- }
780
- const persistedContext = snapshot.requestContext !== null &&
781
- typeof snapshot.requestContext === 'object' &&
782
- !Array.isArray(snapshot.requestContext)
783
- ? snapshot.requestContext
784
- : {};
785
- // Core merges resume context over the prior snapshot. Terminal-only repair
786
- // must persist that same effective context, including application keys the
787
- // current provider intentionally omitted.
788
- const authoritativeContext = {
789
- ...persistedContext,
790
- ...Object.fromEntries(requestContext.entries()),
791
- };
792
- const persistedToken = runProvenance(snapshot)?.attemptToken;
793
- const authoritativeToken = runProvenance({
794
- ...snapshot,
795
- requestContext: authoritativeContext,
796
- })?.attemptToken;
797
- if (snapshot.status === result.status &&
798
- persistedToken === authoritativeToken) {
799
- return;
800
- }
801
- await workflows.persistWorkflowSnapshot({
802
- workflowName: workflowId,
803
- runId,
804
- snapshot: {
1221
+ await this.#withLifecycleLock(workflowId, runId, async () => {
1222
+ const workflows = await this.#storage.getStore('workflows');
1223
+ if (!workflows) {
1224
+ throw new Error('RunnerRuntime: workflows storage is unavailable while persisting terminal state');
1225
+ }
1226
+ const snapshot = await workflows.loadWorkflowSnapshot({
1227
+ workflowName: workflowId,
1228
+ runId,
1229
+ });
1230
+ if (!snapshot) {
1231
+ throw new Error(`RunnerRuntime: run '${runId}' of workflow '${workflowId}' completed without a durable snapshot`);
1232
+ }
1233
+ const persistedContext = snapshot.requestContext !== null &&
1234
+ typeof snapshot.requestContext === 'object' &&
1235
+ !Array.isArray(snapshot.requestContext)
1236
+ ? snapshot.requestContext
1237
+ : {};
1238
+ // Core merges resume context over the prior snapshot. Terminal-only
1239
+ // repair must persist that same effective context, including application
1240
+ // keys the current provider intentionally omitted.
1241
+ const authoritativeContext = {
1242
+ ...persistedContext,
1243
+ ...Object.fromEntries(requestContext.entries()),
1244
+ };
1245
+ const persistedLifecycle = lifecycleFromRequestContext(persistedContext);
1246
+ const authoritativeLifecycle = lifecycleFromRequestContext(authoritativeContext);
1247
+ const reconciledLifecycle = effectiveLifecycle(persistedLifecycle, authoritativeLifecycle);
1248
+ if (reconciledLifecycle) {
1249
+ authoritativeContext[RUN_LIFECYCLE_CONTEXT_KEY] = reconciledLifecycle;
1250
+ }
1251
+ const persistedCoversLifecycle = reconciledLifecycle === undefined ||
1252
+ (persistedLifecycle !== undefined &&
1253
+ JSON.stringify(persistedLifecycle) ===
1254
+ JSON.stringify(reconciledLifecycle));
1255
+ const persistedToken = runProvenance(snapshot)?.attemptToken;
1256
+ const authoritativeToken = runProvenance({
805
1257
  ...snapshot,
806
- ...opts,
807
1258
  requestContext: authoritativeContext,
808
- timestamp: Date.now(),
809
- },
1259
+ })?.attemptToken;
1260
+ if (snapshot.status === result.status &&
1261
+ persistedToken === authoritativeToken &&
1262
+ persistedCoversLifecycle) {
1263
+ return;
1264
+ }
1265
+ await workflows.persistWorkflowSnapshot({
1266
+ workflowName: workflowId,
1267
+ runId,
1268
+ snapshot: {
1269
+ ...snapshot,
1270
+ ...opts,
1271
+ requestContext: authoritativeContext,
1272
+ timestamp: Date.now(),
1273
+ },
1274
+ });
810
1275
  });
811
1276
  }
812
1277
  #getWorkflow(workflowId) {
@@ -843,20 +1308,25 @@ export class RunnerRuntime {
843
1308
  #runKey(workflowId, runId) {
844
1309
  return `${workflowId}:${runId}`;
845
1310
  }
1311
+ async #withLifecycleLock(workflowId, runId, fn) {
1312
+ return this.#withLock(this.#lifecycleLocks, this.#runKey(workflowId, runId), fn);
1313
+ }
846
1314
  // FIFO per-run lock: callers for the same run execute strictly in arrival
847
1315
  // order; distinct runs do not contend. The map entry is removed when the last
848
1316
  // waiter settles, so idle runs hold no memory. Keyed by the run's full identity
849
1317
  // via #runKey (workflowId + runId), not runId alone — the in-process lock
850
1318
  // granularity thus matches the cross-instance DO routing granularity.
851
1319
  async #withRunLock(workflowId, runId, fn) {
852
- const key = this.#runKey(workflowId, runId);
853
- const prev = this.#runLocks.get(key) ?? Promise.resolve();
854
- const task = prev.then(fn);
1320
+ return this.#withLock(this.#runLocks, this.#runKey(workflowId, runId), fn);
1321
+ }
1322
+ async #withLock(locks, key, fn) {
1323
+ const previous = locks.get(key) ?? Promise.resolve();
1324
+ const task = previous.then(fn);
855
1325
  const tail = task.then(() => undefined, () => undefined);
856
- this.#runLocks.set(key, tail);
1326
+ locks.set(key, tail);
857
1327
  void tail.then(() => {
858
- if (this.#runLocks.get(key) === tail)
859
- this.#runLocks.delete(key);
1328
+ if (locks.get(key) === tail)
1329
+ locks.delete(key);
860
1330
  });
861
1331
  return task;
862
1332
  }