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