@hexabot-ai/agentic 3.4.0 → 3.5.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 (134) hide show
  1. package/README.md +67 -15
  2. package/dist/cjs/action/abstract-action.js +13 -1
  3. package/dist/cjs/checkpoint.js +301 -0
  4. package/dist/cjs/context.js +11 -27
  5. package/dist/cjs/dsl.types.js +3 -0
  6. package/dist/cjs/errors.js +116 -9
  7. package/dist/cjs/index.js +15 -6
  8. package/dist/cjs/resume-payload.js +257 -0
  9. package/dist/cjs/runner-runtime-control.js +181 -306
  10. package/dist/cjs/step-executors/conditional-executor.js +27 -29
  11. package/dist/cjs/step-executors/loop-executor.js +53 -62
  12. package/dist/cjs/step-executors/parallel-executor.js +169 -102
  13. package/dist/cjs/step-executors/task-executor.js +180 -96
  14. package/dist/cjs/utils/clone.js +73 -0
  15. package/dist/cjs/workflow-fingerprint.js +138 -0
  16. package/dist/cjs/workflow-runner.js +220 -155
  17. package/dist/cjs/workflow.js +24 -12
  18. package/dist/esm/action/abstract-action.js +14 -2
  19. package/dist/esm/checkpoint.js +293 -0
  20. package/dist/esm/context.js +11 -27
  21. package/dist/esm/dsl.types.js +3 -0
  22. package/dist/esm/errors.js +105 -6
  23. package/dist/esm/index.js +3 -3
  24. package/dist/esm/resume-payload.js +250 -0
  25. package/dist/esm/runner-runtime-control.js +179 -303
  26. package/dist/esm/step-executors/conditional-executor.js +27 -29
  27. package/dist/esm/step-executors/loop-executor.js +53 -62
  28. package/dist/esm/step-executors/parallel-executor.js +165 -98
  29. package/dist/esm/step-executors/task-executor.js +181 -97
  30. package/dist/esm/utils/clone.js +67 -0
  31. package/dist/esm/workflow-fingerprint.js +134 -0
  32. package/dist/esm/workflow-runner.js +220 -155
  33. package/dist/esm/workflow.js +24 -12
  34. package/dist/types/action/abstract-action.d.ts.map +1 -1
  35. package/dist/types/action/action.types.d.ts +0 -14
  36. package/dist/types/action/action.types.d.ts.map +1 -1
  37. package/dist/types/checkpoint.d.ts +188 -0
  38. package/dist/types/checkpoint.d.ts.map +1 -0
  39. package/dist/types/context.d.ts +45 -11
  40. package/dist/types/context.d.ts.map +1 -1
  41. package/dist/types/dsl.types.d.ts.map +1 -1
  42. package/dist/types/errors.d.ts +77 -3
  43. package/dist/types/errors.d.ts.map +1 -1
  44. package/dist/types/index.d.ts +6 -7
  45. package/dist/types/index.d.ts.map +1 -1
  46. package/dist/types/resume-payload.d.ts +69 -0
  47. package/dist/types/resume-payload.d.ts.map +1 -0
  48. package/dist/types/runner-runtime-control.d.ts +63 -51
  49. package/dist/types/runner-runtime-control.d.ts.map +1 -1
  50. package/dist/types/step-executors/conditional-executor.d.ts +6 -3
  51. package/dist/types/step-executors/conditional-executor.d.ts.map +1 -1
  52. package/dist/types/step-executors/loop-executor.d.ts +6 -4
  53. package/dist/types/step-executors/loop-executor.d.ts.map +1 -1
  54. package/dist/types/step-executors/parallel-executor.d.ts +11 -3
  55. package/dist/types/step-executors/parallel-executor.d.ts.map +1 -1
  56. package/dist/types/step-executors/task-executor.d.ts +11 -4
  57. package/dist/types/step-executors/task-executor.d.ts.map +1 -1
  58. package/dist/types/step-executors/types.d.ts +21 -13
  59. package/dist/types/step-executors/types.d.ts.map +1 -1
  60. package/dist/types/utils/clone.d.ts +33 -0
  61. package/dist/types/utils/clone.d.ts.map +1 -0
  62. package/dist/types/workflow-event-emitter.d.ts +29 -5
  63. package/dist/types/workflow-event-emitter.d.ts.map +1 -1
  64. package/dist/types/workflow-fingerprint.d.ts +14 -0
  65. package/dist/types/workflow-fingerprint.d.ts.map +1 -0
  66. package/dist/types/workflow-runner.d.ts +83 -41
  67. package/dist/types/workflow-runner.d.ts.map +1 -1
  68. package/dist/types/workflow-types.d.ts +25 -54
  69. package/dist/types/workflow-types.d.ts.map +1 -1
  70. package/dist/types/workflow.d.ts +24 -9
  71. package/dist/types/workflow.d.ts.map +1 -1
  72. package/examples/defs-bindings-agent/bindings.ts +1 -1
  73. package/examples/defs-bindings-agent/workflow.ts +3 -2
  74. package/examples/full/actions/await-user-input.ts +3 -2
  75. package/examples/full/actions/call-llm.ts +18 -18
  76. package/examples/full/actions/create-ticket.ts +1 -2
  77. package/examples/full/actions/decision-router.ts +6 -2
  78. package/examples/full/actions/get-calendar-events.ts +1 -2
  79. package/examples/full/actions/get-user-profile.ts +1 -2
  80. package/examples/full/actions/query-memory.ts +1 -2
  81. package/examples/full/actions/search-web.ts +1 -2
  82. package/examples/full/actions/send-email.ts +3 -2
  83. package/examples/full/workflow.ts +3 -2
  84. package/examples/loop/actions/await-reply.ts +2 -7
  85. package/examples/loop/workflow.ts +4 -2
  86. package/examples/suspend-resume/actions/wait-for-user.ts +11 -9
  87. package/examples/suspend-resume/workflow.ts +51 -11
  88. package/package.json +3 -3
  89. package/src/__tests__/checkpoint.test.ts +2568 -0
  90. package/src/__tests__/resume-payload.test.ts +245 -0
  91. package/src/__tests__/runner-runtime-control.test.ts +265 -0
  92. package/src/__tests__/workflow-fingerprint.test.ts +165 -0
  93. package/src/__tests__/workflow-runner.test.ts +167 -144
  94. package/src/__tests__/workflow.test.ts +97 -6
  95. package/src/action/abstract-action.ts +21 -2
  96. package/src/action/action.types.ts +0 -12
  97. package/src/checkpoint.ts +561 -0
  98. package/src/context.ts +51 -41
  99. package/src/dsl.types.ts +3 -0
  100. package/src/errors.ts +161 -8
  101. package/src/index.ts +33 -14
  102. package/src/resume-payload.ts +326 -0
  103. package/src/runner-runtime-control.ts +222 -456
  104. package/src/step-executors/conditional-executor.test.ts +77 -46
  105. package/src/step-executors/conditional-executor.ts +47 -40
  106. package/src/step-executors/loop-executor.test.ts +106 -92
  107. package/src/step-executors/loop-executor.ts +84 -101
  108. package/src/step-executors/parallel-executor.test.ts +300 -89
  109. package/src/step-executors/parallel-executor.ts +243 -125
  110. package/src/step-executors/task-executor.test.ts +321 -51
  111. package/src/step-executors/task-executor.ts +232 -145
  112. package/src/step-executors/types.ts +23 -22
  113. package/src/utils/clone.ts +75 -0
  114. package/src/workflow-event-emitter.ts +32 -6
  115. package/src/workflow-fingerprint.ts +159 -0
  116. package/src/workflow-runner.ts +325 -209
  117. package/src/workflow-types.ts +25 -56
  118. package/src/workflow.ts +41 -34
  119. package/dist/cjs/step-executors/suspension-continuation.js +0 -27
  120. package/dist/cjs/suspension-rebuilder.js +0 -265
  121. package/dist/cjs/utils/deferred.js +0 -17
  122. package/dist/esm/step-executors/suspension-continuation.js +0 -24
  123. package/dist/esm/suspension-rebuilder.js +0 -260
  124. package/dist/esm/utils/deferred.js +0 -14
  125. package/dist/types/step-executors/suspension-continuation.d.ts +0 -10
  126. package/dist/types/step-executors/suspension-continuation.d.ts.map +0 -1
  127. package/dist/types/suspension-rebuilder.d.ts +0 -67
  128. package/dist/types/suspension-rebuilder.d.ts.map +0 -1
  129. package/dist/types/utils/deferred.d.ts +0 -7
  130. package/dist/types/utils/deferred.d.ts.map +0 -1
  131. package/src/__tests__/suspension-rebuilder.test.ts +0 -404
  132. package/src/step-executors/suspension-continuation.ts +0 -31
  133. package/src/suspension-rebuilder.ts +0 -446
  134. package/src/utils/deferred.ts +0 -23
@@ -3,348 +3,224 @@
3
3
  * Copyright (c) 2025 Hexastack.
4
4
  * Full terms: see LICENSE.md.
5
5
  */
6
- import { createDeferred } from './utils/deferred';
6
+ import { NonDeterministicWorkflowError } from './errors';
7
+ import { describeResumePayload, findNonJsonTypes, isPayloadOptional, rejectResumePayload, } from './resume-payload';
8
+ import { cloneValue } from './utils/clone';
7
9
  const INDEX_KEY_PREFIX = 'index:';
8
10
  const USER_KEY_PREFIX = 'key:';
9
- export class NonDeterministicWorkflowError extends Error {
10
- constructor(message) {
11
- super(message);
12
- this.name = 'NonDeterministicWorkflowError';
13
- }
14
- }
15
- /** Minimal wrapper that exposes runner controls to actions via the context. */
11
+ /**
12
+ * Suspension control for one concurrency scope of a run.
13
+ *
14
+ * Steps inside a scope run one at a time, so the scope tracks a single active
15
+ * step. The root flow owns one scope and every parallel branch forks its own,
16
+ * which is what lets concurrent branches suspend independently.
17
+ */
16
18
  export class RunnerRuntimeControl {
17
- constructor(runner) {
18
- this.pendingSuspensions = new Map();
19
- this.suspensionWaiters = new Map();
20
- this.primedResumeData = new Map();
21
- this.stepAttempts = new Map();
22
- this.activeStepExecutions = new Map();
23
- this.replaySeeds = new Map();
24
- this.runner = runner;
25
- }
26
- get status() {
27
- return this.runner.getStatus();
28
- }
29
- get resumeData() {
30
- return this.runner.getLastResumeData();
31
- }
32
- suspend(options) {
33
- const currentStep = this.runner.getCurrentStep();
34
- if (!currentStep) {
35
- throw new Error('workflow.suspend() can only be called while a workflow step is running.');
36
- }
37
- const execution = this.ensureStepExecution(currentStep.id);
38
- execution.suspendCursor += 1;
39
- const suspendIndex = execution.suspendCursor;
40
- const suspendKey = buildSuspendKey(suspendIndex, options?.key);
41
- this.assertReplayExpectation(execution, {
42
- suspendIndex,
43
- suspendKey,
44
- reason: options?.reason,
45
- });
46
- if (execution.awaitResults.has(suspendKey)) {
47
- return Promise.resolve(execution.awaitResults.get(suspendKey));
48
- }
49
- const primed = this.dequeuePrimedResumeData(currentStep.id);
50
- if (primed.found) {
51
- return Promise.resolve(primed.value);
52
- }
53
- const request = {
54
- stepId: currentStep.id,
55
- stepExecId: execution.stepExecId,
56
- suspendIndex,
57
- suspendKey,
58
- reason: options?.reason,
59
- data: options?.data,
60
- awaitResults: this.serializeAwaitResults(execution.awaitResults),
61
- resume: createDeferred(),
19
+ /**
20
+ * Create the scope of a concurrent region such as a parallel branch.
21
+ *
22
+ * @returns A new, independent scope.
23
+ */
24
+ fork() {
25
+ return new RunnerRuntimeControl();
26
+ }
27
+ /**
28
+ * Mark a task step as running in this scope.
29
+ *
30
+ * @param step Instance step that is about to run its action.
31
+ * @param options.seed Previously resolved suspend results when the body re-runs.
32
+ */
33
+ beginStep(step, options = {}) {
34
+ this.active = {
35
+ step,
36
+ cursor: 0,
37
+ usedKeys: new Set(),
38
+ awaitResults: new Map(Object.entries(options.seed?.awaitResults ?? {})),
39
+ expected: options.seed
40
+ ? { ...options.seed.expected, matched: false }
41
+ : undefined,
42
+ pending: [],
62
43
  };
63
- this.enqueueSuspension(request);
64
- return request.resume.promise;
65
44
  }
66
- hasRecordedResult(key) {
67
- const currentStep = this.runner.getCurrentStep();
68
- if (!currentStep) {
69
- return false;
70
- }
71
- const execution = this.ensureStepExecution(currentStep.id);
72
- const suspendKey = buildSuspendKey(execution.suspendCursor + 1, key);
73
- if (execution.awaitResults.has(suspendKey)) {
74
- return true;
75
- }
76
- return (this.primedResumeData.get(currentStep.id)?.length ?? 0) > 0;
77
- }
78
- resume(data) {
79
- void this.runner.resume({ resumeData: data });
80
- }
81
- waitForStepSuspension(stepId) {
82
- const queued = this.dequeueStepSuspension(stepId);
45
+ /**
46
+ * Release the active step.
47
+ *
48
+ * @param options.completed True when the action body returned successfully.
49
+ * @throws {NonDeterministicWorkflowError} When a re-run body completed
50
+ * without reaching the suspension it was resumed from.
51
+ */
52
+ endStep(options = {}) {
53
+ const active = this.active;
54
+ this.active = undefined;
55
+ if (options.completed && active?.expected && !active.expected.matched) {
56
+ throw new NonDeterministicWorkflowError(`Resumed step "${active.step.id}" completed without reaching ` +
57
+ `suspension "${active.expected.suspendKey}".`);
58
+ }
59
+ }
60
+ /**
61
+ * Wait for the active step's next `suspend()` call.
62
+ *
63
+ * @returns The next suspension request.
64
+ */
65
+ waitForSuspension() {
66
+ const active = this.active;
67
+ if (!active) {
68
+ throw new Error('No workflow step is running in this scope.');
69
+ }
70
+ const queued = active.pending.shift();
83
71
  if (queued) {
84
72
  return Promise.resolve(queued);
85
73
  }
86
74
  return new Promise((resolve) => {
87
- const waiters = this.suspensionWaiters.get(stepId) ?? [];
88
- waiters.push(resolve);
89
- this.suspensionWaiters.set(stepId, waiters);
75
+ active.waiter = resolve;
90
76
  });
91
77
  }
92
- beginStepExecution(stepId) {
93
- const existing = this.activeStepExecutions.get(stepId);
94
- if (existing) {
95
- return existing.stepExecId;
96
- }
97
- const seeded = this.replaySeeds.get(stepId);
98
- if (seeded) {
99
- const execution = {
100
- stepId,
101
- stepExecId: seeded.stepExecId,
102
- suspendCursor: 0,
103
- awaitResults: this.normalizeAwaitResults(seeded.awaitResults),
104
- replayExpectation: seeded.activeSuspension
105
- ? {
106
- suspendIndex: seeded.activeSuspension.suspendIndex,
107
- suspendKey: normalizeSuspendKey(seeded.activeSuspension.suspendIndex, seeded.activeSuspension.suspendKey) ?? buildSuspendKey(seeded.activeSuspension.suspendIndex ?? 1),
108
- reason: seeded.activeSuspension.reason,
109
- matched: false,
110
- }
111
- : undefined,
112
- };
113
- this.activeStepExecutions.set(stepId, execution);
114
- this.replaySeeds.delete(stepId);
115
- this.bumpStepAttemptCounter(stepId, execution.stepExecId);
116
- return execution.stepExecId;
117
- }
118
- const attempt = (this.stepAttempts.get(stepId) ?? 0) + 1;
119
- const stepExecId = `${stepId}#${attempt}`;
120
- this.stepAttempts.set(stepId, attempt);
121
- this.activeStepExecutions.set(stepId, {
122
- stepId,
123
- stepExecId,
124
- suspendCursor: 0,
125
- awaitResults: new Map(),
126
- });
127
- return stepExecId;
128
- }
129
- prepareStepReplay(seed) {
130
- const normalizedAwaitResults = this.serializeAwaitResults(this.normalizeAwaitResults(seed.awaitResults ?? {}));
131
- this.replaySeeds.set(seed.stepId, {
132
- stepExecId: seed.stepExecId,
133
- awaitResults: normalizedAwaitResults,
134
- activeSuspension: seed.activeSuspension
135
- ? {
136
- suspendIndex: seed.activeSuspension.suspendIndex,
137
- suspendKey: normalizeSuspendKey(seed.activeSuspension.suspendIndex, seed.activeSuspension.suspendKey),
138
- reason: seed.activeSuspension.reason,
139
- }
140
- : undefined,
141
- });
142
- this.bumpStepAttemptCounter(seed.stepId, seed.stepExecId);
143
- }
144
- recordStepSuspendResult(params) {
145
- const suspendKey = normalizeSuspendKey(params.suspendIndex, params.suspendKey);
146
- if (!suspendKey) {
147
- this.primeStepResumeData(params.stepId, params.resumeData);
148
- return;
149
- }
150
- const activeExecution = this.activeStepExecutions.get(params.stepId);
151
- if (activeExecution &&
152
- (!params.stepExecId || params.stepExecId === activeExecution.stepExecId)) {
153
- if (!activeExecution.awaitResults.has(suspendKey)) {
154
- activeExecution.awaitResults.set(suspendKey, params.resumeData);
155
- }
156
- return;
78
+ suspend(options) {
79
+ const active = this.active;
80
+ if (!active) {
81
+ throw new Error('workflow.suspend() can only be called while a workflow step is running.');
157
82
  }
158
- const replaySeed = this.replaySeeds.get(params.stepId);
159
- if (replaySeed) {
160
- if (params.stepExecId && replaySeed.stepExecId !== params.stepExecId) {
161
- return;
162
- }
163
- replaySeed.awaitResults[suspendKey] =
164
- replaySeed.awaitResults[suspendKey] ?? params.resumeData;
165
- this.replaySeeds.set(params.stepId, replaySeed);
166
- return;
83
+ if (options?.accepts) {
84
+ assertJsonPayloadSchema(active, options.accepts);
167
85
  }
168
- const fallbackExecId = params.stepExecId ?? `${params.stepId}#1`;
169
- this.replaySeeds.set(params.stepId, {
170
- stepExecId: fallbackExecId,
171
- awaitResults: { [suspendKey]: params.resumeData },
172
- });
173
- this.bumpStepAttemptCounter(params.stepId, fallbackExecId);
174
- }
175
- clearStepSuspensions(stepId, error) {
176
- const queued = this.pendingSuspensions.get(stepId);
177
- if (queued) {
178
- for (const request of queued) {
179
- request.resume.reject(error ?? new Error(`Suspension for step "${stepId}" was cancelled.`));
86
+ if (options?.key) {
87
+ // A reused key would resolve from the first call's answer on resume,
88
+ // so the second call could never suspend.
89
+ if (active.usedKeys.has(options.key)) {
90
+ throw new Error(`workflow.suspend() key "${options.key}" is used more than once ` +
91
+ `in step "${active.step.id}"; keys must be unique within an action body.`);
180
92
  }
93
+ active.usedKeys.add(options.key);
181
94
  }
182
- const execution = this.activeStepExecutions.get(stepId);
183
- this.pendingSuspensions.delete(stepId);
184
- this.suspensionWaiters.delete(stepId);
185
- this.primedResumeData.delete(stepId);
186
- this.activeStepExecutions.delete(stepId);
187
- if (!error &&
188
- execution?.replayExpectation &&
189
- !execution.replayExpectation.matched) {
190
- throw new NonDeterministicWorkflowError(`Replay for step "${stepId}" did not reach expected suspension ` +
191
- `"${execution.replayExpectation.suspendKey}".`);
95
+ active.cursor += 1;
96
+ const suspendKey = buildSuspendKey(active.cursor, options?.key);
97
+ this.assertReplayExpectation(active, suspendKey, options?.reason);
98
+ if (active.awaitResults.has(suspendKey)) {
99
+ return resolveRecordedResult(active, suspendKey, options?.accepts);
192
100
  }
193
- }
194
- primeStepResumeData(stepId, resumeData) {
195
- const queued = this.primedResumeData.get(stepId) ?? [];
196
- queued.push(resumeData);
197
- this.primedResumeData.set(stepId, queued);
198
- }
199
- getSnapshot() {
200
- return this.runner.getSnapshot();
201
- }
202
- enqueueSuspension(request) {
203
- const waiters = this.suspensionWaiters.get(request.stepId);
204
- if (waiters && waiters.length > 0) {
205
- const resolve = waiters.shift();
206
- if (!resolve) {
207
- return;
208
- }
209
- if (waiters.length === 0) {
210
- this.suspensionWaiters.delete(request.stepId);
211
- }
212
- else {
213
- this.suspensionWaiters.set(request.stepId, waiters);
101
+ const request = {
102
+ suspendKey,
103
+ reason: options?.reason,
104
+ data: options?.data,
105
+ awaitResults: Object.fromEntries(active.awaitResults),
106
+ };
107
+ if (options?.accepts) {
108
+ request.accepts = describeResumePayload(options.accepts);
109
+ if (isPayloadOptional(options.accepts)) {
110
+ request.payloadOptional = true;
214
111
  }
215
- resolve(request);
216
- return;
217
112
  }
218
- const queued = this.pendingSuspensions.get(request.stepId) ?? [];
219
- queued.push(request);
220
- this.pendingSuspensions.set(request.stepId, queued);
221
- }
222
- dequeueStepSuspension(stepId) {
223
- const queued = this.pendingSuspensions.get(stepId);
224
- if (!queued || queued.length === 0) {
225
- return undefined;
226
- }
227
- const request = queued.shift();
228
- if (queued.length === 0) {
229
- this.pendingSuspensions.delete(stepId);
113
+ const waiter = active.waiter;
114
+ if (waiter) {
115
+ active.waiter = undefined;
116
+ waiter(request);
230
117
  }
231
118
  else {
232
- this.pendingSuspensions.set(stepId, queued);
233
- }
234
- return request;
119
+ active.pending.push(request);
120
+ }
121
+ // Never settles: the step executor aborts this body, and resuming re-runs
122
+ // it so that this call resolves from `awaitResults` instead.
123
+ return new Promise(() => undefined);
124
+ }
125
+ /**
126
+ * Report whether the active step, re-run to resolve a wait, has reached
127
+ * that wait's `suspend()` call. Only from then on has it read the payload,
128
+ * and can it refuse it.
129
+ *
130
+ * @returns True once the resolved suspension was reached.
131
+ */
132
+ hasReachedResolvedSuspension() {
133
+ return this.active?.expected?.matched ?? false;
235
134
  }
236
- dequeuePrimedResumeData(stepId) {
237
- const queued = this.primedResumeData.get(stepId);
238
- if (!queued || queued.length === 0) {
239
- return { found: false };
240
- }
241
- const value = queued.shift();
242
- if (queued.length === 0) {
243
- this.primedResumeData.delete(stepId);
244
- }
245
- else {
246
- this.primedResumeData.set(stepId, queued);
135
+ hasRecordedResult(key) {
136
+ const active = this.active;
137
+ if (!active) {
138
+ return false;
247
139
  }
248
- return { found: true, value };
140
+ return active.awaitResults.has(buildSuspendKey(active.cursor + 1, key));
249
141
  }
250
- ensureStepExecution(stepId) {
251
- const existing = this.activeStepExecutions.get(stepId);
252
- if (existing) {
253
- return existing;
254
- }
255
- this.beginStepExecution(stepId);
256
- const created = this.activeStepExecutions.get(stepId);
257
- if (!created) {
258
- throw new Error(`Unable to create runtime state for step "${stepId}".`);
142
+ markSuspendCursor() {
143
+ const active = this.active;
144
+ if (!active) {
145
+ return () => undefined;
259
146
  }
260
- return created;
147
+ const cursor = active.cursor;
148
+ const usedKeys = new Set(active.usedKeys);
149
+ return () => {
150
+ // A rewind taken in a step that has ended must not touch the next one.
151
+ if (this.active === active) {
152
+ active.cursor = cursor;
153
+ active.usedKeys = new Set(usedKeys);
154
+ }
155
+ };
261
156
  }
262
- assertReplayExpectation(execution, encountered) {
263
- const expectation = execution.replayExpectation;
264
- if (!expectation || expectation.matched) {
157
+ assertReplayExpectation(active, suspendKey, reason) {
158
+ const expected = active.expected;
159
+ if (!expected || expected.matched) {
265
160
  return;
266
161
  }
267
- if (encountered.suspendKey === expectation.suspendKey) {
268
- if (expectation.reason !== undefined &&
269
- encountered.reason !== expectation.reason) {
270
- throw new NonDeterministicWorkflowError(`Replay for step "${execution.stepId}" reached suspend ` +
271
- `"${encountered.suspendKey}" with reason "${encountered.reason ?? ''}", ` +
272
- `expected reason "${expectation.reason}".`);
162
+ if (suspendKey === expected.suspendKey) {
163
+ if (expected.reason !== undefined && reason !== expected.reason) {
164
+ throw new NonDeterministicWorkflowError(`Resumed step "${active.step.id}" reached suspend "${suspendKey}" ` +
165
+ `with reason "${reason ?? ''}", expected reason "${expected.reason}".`);
273
166
  }
274
- expectation.matched = true;
167
+ expected.matched = true;
275
168
  return;
276
169
  }
277
- if (execution.awaitResults.has(encountered.suspendKey)) {
170
+ if (active.awaitResults.has(suspendKey)) {
278
171
  return;
279
172
  }
280
- throw new NonDeterministicWorkflowError(`Replay for step "${execution.stepId}" reached unexpected suspend ` +
281
- `"${encountered.suspendKey}" before expected ` +
282
- `"${expectation.suspendKey}".`);
173
+ throw new NonDeterministicWorkflowError(`Resumed step "${active.step.id}" reached unexpected suspend ` +
174
+ `"${suspendKey}" before expected "${expected.suspendKey}".`);
283
175
  }
284
- normalizeAwaitResults(awaitResults) {
285
- const normalized = new Map();
286
- for (const [rawKey, value] of Object.entries(awaitResults)) {
287
- const normalizedKey = normalizeStoredSuspendKey(rawKey);
288
- normalized.set(normalizedKey, value);
289
- }
290
- return normalized;
176
+ }
177
+ /**
178
+ * Refuse an `accepts` schema that no JSON payload can match: the wait it
179
+ * opens could never be resumed, since payloads are read back as JSON.
180
+ *
181
+ * @throws {TypeError} Naming the parts of the schema JSON cannot carry.
182
+ */
183
+ const assertJsonPayloadSchema = (active, accepts) => {
184
+ const found = findNonJsonTypes(accepts);
185
+ if (found.length === 0) {
186
+ return;
187
+ }
188
+ throw new TypeError(`The accepts schema of workflow.suspend() in step "${active.step.id}" ` +
189
+ `can never match a JSON payload: ${found.join(', ')}. Resume payloads ` +
190
+ 'are stored as JSON, so accept their JSON form instead, e.g. ' +
191
+ 'z.coerce.date() or z.iso.datetime() for a date.');
192
+ };
193
+ /**
194
+ * Resolve a `suspend()` call from its recorded result, parsed through the
195
+ * call's `accepts` schema when it has one.
196
+ *
197
+ * The body gets its own copy: the recorded result is saved again with the
198
+ * step's next suspension and replayed on every later pass, so a body that
199
+ * changed it would see its own change applied twice.
200
+ *
201
+ * @returns The recorded (or parsed) result. It rejects with a
202
+ * `WorkflowResumeRejectedError` when the payload this pass resolved fails the
203
+ * schema, and with a {@link NonDeterministicWorkflowError} when a result
204
+ * accepted by an earlier pass no longer does.
205
+ */
206
+ const resolveRecordedResult = async (active, suspendKey, accepts) => {
207
+ const recorded = cloneValue(active.awaitResults.get(suspendKey));
208
+ if (!accepts) {
209
+ return recorded;
291
210
  }
292
- serializeAwaitResults(awaitResults) {
293
- return Object.fromEntries(awaitResults.entries());
211
+ const parsed = await accepts.safeParseAsync(recorded);
212
+ if (parsed.success) {
213
+ return parsed.data;
294
214
  }
295
- bumpStepAttemptCounter(stepId, stepExecId) {
296
- const parsedAttempt = parseStepExecAttempt(stepId, stepExecId);
297
- if (parsedAttempt === null) {
298
- return;
299
- }
300
- const previous = this.stepAttempts.get(stepId) ?? 0;
301
- if (parsedAttempt > previous) {
302
- this.stepAttempts.set(stepId, parsedAttempt);
303
- }
215
+ if (suspendKey === active.expected?.suspendKey) {
216
+ throw rejectResumePayload(`step "${active.step.id}"`, parsed.error.issues);
304
217
  }
305
- }
218
+ throw new NonDeterministicWorkflowError(`Resumed step "${active.step.id}" recorded a result for suspend ` +
219
+ `"${suspendKey}" that no longer matches its accepts schema.`);
220
+ };
306
221
  const buildSuspendKey = (suspendIndex, key) => {
307
222
  if (key) {
308
223
  return `${USER_KEY_PREFIX}${key}`;
309
224
  }
310
225
  return `${INDEX_KEY_PREFIX}${suspendIndex}`;
311
226
  };
312
- const normalizeSuspendKey = (suspendIndex, suspendKey) => {
313
- if (typeof suspendKey === 'string' && suspendKey.length > 0) {
314
- if (suspendKey.startsWith(INDEX_KEY_PREFIX) ||
315
- suspendKey.startsWith(USER_KEY_PREFIX)) {
316
- return suspendKey;
317
- }
318
- if (/^\d+$/.test(suspendKey)) {
319
- return `${INDEX_KEY_PREFIX}${suspendKey}`;
320
- }
321
- return `${USER_KEY_PREFIX}${suspendKey}`;
322
- }
323
- if (typeof suspendIndex === 'number' &&
324
- Number.isInteger(suspendIndex) &&
325
- suspendIndex > 0) {
326
- return `${INDEX_KEY_PREFIX}${suspendIndex}`;
327
- }
328
- return undefined;
329
- };
330
- const normalizeStoredSuspendKey = (rawKey) => {
331
- if (rawKey.startsWith(INDEX_KEY_PREFIX) ||
332
- rawKey.startsWith(USER_KEY_PREFIX)) {
333
- return rawKey;
334
- }
335
- if (/^\d+$/.test(rawKey)) {
336
- return `${INDEX_KEY_PREFIX}${rawKey}`;
337
- }
338
- return `${USER_KEY_PREFIX}${rawKey}`;
339
- };
340
- const parseStepExecAttempt = (stepId, stepExecId) => {
341
- const prefix = `${stepId}#`;
342
- if (!stepExecId.startsWith(prefix)) {
343
- return null;
344
- }
345
- const numeric = Number.parseInt(stepExecId.slice(prefix.length), 10);
346
- if (Number.isNaN(numeric) || numeric < 1) {
347
- return null;
348
- }
349
- return numeric;
350
- };
@@ -12,9 +12,32 @@ import { markStepsSkipped } from './skip-helpers';
12
12
  * @param step The conditional step definition.
13
13
  * @param state Mutable workflow execution state.
14
14
  * @param path Path tokens locating this step within the workflow tree.
15
- * @returns A suspension if a branch pauses execution, otherwise void.
15
+ * @param frame Frame returned when the chosen branch previously suspended; its
16
+ * branch is re-entered without evaluating conditions again.
17
+ * @returns A frame if the chosen branch suspends, otherwise void.
16
18
  */
17
- export async function executeConditional(env, step, state, path) {
19
+ export async function executeConditional(env, step, state, path, frame) {
20
+ const branchIndex = frame
21
+ ? frame.branchIndex
22
+ : await chooseBranch(env, step, state);
23
+ if (branchIndex === undefined) {
24
+ step.branches.forEach((branch) => markStepsSkipped(env, branch.steps, state.iterationStack));
25
+ return undefined;
26
+ }
27
+ if (!frame) {
28
+ step.branches.forEach((candidate, candidateIndex) => {
29
+ if (candidateIndex !== branchIndex) {
30
+ markStepsSkipped(env, candidate.steps, state.iterationStack);
31
+ }
32
+ });
33
+ }
34
+ const child = await env.executeFlow(step.branches[branchIndex].steps, state, [...path, 'branch', branchIndex], frame?.child);
35
+ if (child) {
36
+ return { kind: 'conditional', stepId: step.id, branchIndex, child };
37
+ }
38
+ return undefined;
39
+ }
40
+ const chooseBranch = async (env, step, state) => {
18
41
  for (let index = 0; index < step.branches.length; index += 1) {
19
42
  const branch = step.branches[index];
20
43
  const scope = {
@@ -28,33 +51,8 @@ export async function executeConditional(env, step, state, path) {
28
51
  ? await evaluateValue(branch.condition, scope)
29
52
  : true;
30
53
  if (conditionResult) {
31
- step.branches.forEach((candidate, candidateIndex) => {
32
- if (candidateIndex !== index) {
33
- markStepsSkipped(env, candidate.steps, state.iterationStack);
34
- }
35
- });
36
- const suspension = await env.executeFlow(branch.steps, state, [
37
- ...path,
38
- 'branch',
39
- index,
40
- ]);
41
- if (suspension) {
42
- return {
43
- ...suspension,
44
- continue: async (resumeData) => {
45
- const next = await suspension.continue(resumeData);
46
- if (next) {
47
- return next;
48
- }
49
- return undefined;
50
- },
51
- };
52
- }
53
- return undefined;
54
+ return index;
54
55
  }
55
56
  }
56
- if (step.branches.length > 0) {
57
- step.branches.forEach((branch) => markStepsSkipped(env, branch.steps, state.iterationStack));
58
- }
59
57
  return undefined;
60
- }
58
+ };