@hexabot-ai/agentic 3.4.0-beta.2 → 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
@@ -4,556 +4,322 @@
4
4
  * Full terms: see LICENSE.md.
5
5
  */
6
6
 
7
- import type {
8
- SuspensionOptions,
9
- WorkflowRunStatus,
10
- WorkflowRuntimeControl,
11
- } from './context';
12
- import type { Deferred } from './utils/deferred';
13
- import { createDeferred } from './utils/deferred';
14
- import type { WorkflowRunner } from './workflow-runner';
7
+ import type { ZodType } from 'zod';
8
+
9
+ import type { SuspensionOptions, WorkflowRuntimeControl } from './context';
10
+ import { NonDeterministicWorkflowError } from './errors';
11
+ import {
12
+ describeResumePayload,
13
+ findNonJsonTypes,
14
+ isPayloadOptional,
15
+ rejectResumePayload,
16
+ } from './resume-payload';
17
+ import { cloneValue } from './utils/clone';
18
+ import type { StepInfo } from './workflow-event-emitter';
15
19
 
16
20
  const INDEX_KEY_PREFIX = 'index:';
17
21
  const USER_KEY_PREFIX = 'key:';
18
22
 
19
- type ReplayExpectation = {
20
- suspendIndex?: number;
21
- suspendKey: string;
22
- reason?: string;
23
- matched: boolean;
24
- };
25
-
26
- type StepExecutionState = {
27
- stepId: string;
28
- stepExecId: string;
29
- suspendCursor: number;
30
- awaitResults: Map<string, unknown>;
31
- replayExpectation?: ReplayExpectation;
32
- };
33
-
34
- type StoredReplaySeed = {
35
- stepExecId: string;
36
- awaitResults: Record<string, unknown>;
37
- activeSuspension?: {
38
- suspendIndex?: number;
39
- suspendKey?: string;
40
- reason?: string;
41
- };
42
- };
43
-
23
+ /** A `suspend()` call the step executor has to turn into a wait. */
44
24
  export type RuntimeSuspensionRequest = {
45
- stepId: string;
46
- stepExecId: string;
47
- suspendIndex: number;
48
25
  suspendKey: string;
49
26
  reason?: string;
50
27
  data?: unknown;
28
+ /** Relaxed JSON Schema of the payload the wait accepts. */
29
+ accepts?: Record<string, unknown>;
30
+ /** Set when the `accepts` schema also accepts a resume without payload. */
31
+ payloadOptional?: boolean;
32
+ /** Suspend results already resolved for this step, keyed by suspend key. */
51
33
  awaitResults: Record<string, unknown>;
52
- resume: Deferred<unknown>;
53
34
  };
54
35
 
55
- export type RuntimeStepReplaySeed = {
56
- stepId: string;
57
- stepExecId: string;
58
- awaitResults?: Record<string, unknown>;
59
- activeSuspension?: {
60
- suspendIndex?: number;
61
- suspendKey?: string;
62
- reason?: string;
63
- };
36
+ /** Seed for a task body that re-runs after its wait was resolved. */
37
+ export type StepReplaySeed = {
38
+ awaitResults: Record<string, unknown>;
39
+ /** Suspension the re-run body is expected to reach again. */
40
+ expected: { suspendKey: string; reason?: string };
64
41
  };
65
42
 
66
- export type RuntimeResolvedSuspension = {
67
- stepId: string;
68
- resumeData: unknown;
69
- stepExecId?: string;
70
- suspendIndex?: number;
71
- suspendKey?: string;
43
+ type ActiveStep = {
44
+ step: StepInfo;
45
+ cursor: number;
46
+ /** User keys already passed to `suspend()` by the current attempt. */
47
+ usedKeys: Set<string>;
48
+ awaitResults: Map<string, unknown>;
49
+ expected?: { suspendKey: string; reason?: string; matched: boolean };
50
+ pending: RuntimeSuspensionRequest[];
51
+ waiter?: (request: RuntimeSuspensionRequest) => void;
72
52
  };
73
53
 
74
- export class NonDeterministicWorkflowError extends Error {
75
- constructor(message: string) {
76
- super(message);
77
- this.name = 'NonDeterministicWorkflowError';
78
- }
79
- }
80
-
81
- /** Minimal wrapper that exposes runner controls to actions via the context. */
54
+ /**
55
+ * Suspension control for one concurrency scope of a run.
56
+ *
57
+ * Steps inside a scope run one at a time, so the scope tracks a single active
58
+ * step. The root flow owns one scope and every parallel branch forks its own,
59
+ * which is what lets concurrent branches suspend independently.
60
+ */
82
61
  export class RunnerRuntimeControl implements WorkflowRuntimeControl {
83
- private readonly runner: WorkflowRunner;
84
-
85
- private readonly pendingSuspensions = new Map<
86
- string,
87
- RuntimeSuspensionRequest[]
88
- >();
89
-
90
- private readonly suspensionWaiters = new Map<
91
- string,
92
- Array<(request: RuntimeSuspensionRequest) => void>
93
- >();
94
-
95
- private readonly primedResumeData = new Map<string, unknown[]>();
96
-
97
- private readonly stepAttempts = new Map<string, number>();
98
-
99
- private readonly activeStepExecutions = new Map<string, StepExecutionState>();
100
-
101
- private readonly replaySeeds = new Map<string, StoredReplaySeed>();
102
-
103
- constructor(runner: WorkflowRunner) {
104
- this.runner = runner;
105
- }
106
-
107
- get status(): WorkflowRunStatus {
108
- return this.runner.getStatus();
62
+ private active?: ActiveStep;
63
+
64
+ /**
65
+ * Create the scope of a concurrent region such as a parallel branch.
66
+ *
67
+ * @returns A new, independent scope.
68
+ */
69
+ fork(): RunnerRuntimeControl {
70
+ return new RunnerRuntimeControl();
109
71
  }
110
72
 
111
- get resumeData(): unknown {
112
- return this.runner.getLastResumeData();
73
+ /**
74
+ * Mark a task step as running in this scope.
75
+ *
76
+ * @param step Instance step that is about to run its action.
77
+ * @param options.seed Previously resolved suspend results when the body re-runs.
78
+ */
79
+ beginStep(step: StepInfo, options: { seed?: StepReplaySeed } = {}): void {
80
+ this.active = {
81
+ step,
82
+ cursor: 0,
83
+ usedKeys: new Set(),
84
+ awaitResults: new Map(Object.entries(options.seed?.awaitResults ?? {})),
85
+ expected: options.seed
86
+ ? { ...options.seed.expected, matched: false }
87
+ : undefined,
88
+ pending: [],
89
+ };
113
90
  }
114
91
 
115
- suspend<T = unknown>(options?: SuspensionOptions): Promise<T> {
116
- const currentStep = this.runner.getCurrentStep();
117
- if (!currentStep) {
118
- throw new Error(
119
- 'workflow.suspend() can only be called while a workflow step is running.',
92
+ /**
93
+ * Release the active step.
94
+ *
95
+ * @param options.completed True when the action body returned successfully.
96
+ * @throws {NonDeterministicWorkflowError} When a re-run body completed
97
+ * without reaching the suspension it was resumed from.
98
+ */
99
+ endStep(options: { completed?: boolean } = {}): void {
100
+ const active = this.active;
101
+ this.active = undefined;
102
+
103
+ if (options.completed && active?.expected && !active.expected.matched) {
104
+ throw new NonDeterministicWorkflowError(
105
+ `Resumed step "${active.step.id}" completed without reaching ` +
106
+ `suspension "${active.expected.suspendKey}".`,
120
107
  );
121
108
  }
122
-
123
- const execution = this.ensureStepExecution(currentStep.id);
124
-
125
- execution.suspendCursor += 1;
126
- const suspendIndex = execution.suspendCursor;
127
- const suspendKey = buildSuspendKey(suspendIndex, options?.key);
128
-
129
- this.assertReplayExpectation(execution, {
130
- suspendIndex,
131
- suspendKey,
132
- reason: options?.reason,
133
- });
134
-
135
- if (execution.awaitResults.has(suspendKey)) {
136
- return Promise.resolve(execution.awaitResults.get(suspendKey) as T);
137
- }
138
-
139
- const primed = this.dequeuePrimedResumeData(currentStep.id);
140
- if (primed.found) {
141
- return Promise.resolve(primed.value as T);
142
- }
143
-
144
- const request: RuntimeSuspensionRequest = {
145
- stepId: currentStep.id,
146
- stepExecId: execution.stepExecId,
147
- suspendIndex,
148
- suspendKey,
149
- reason: options?.reason,
150
- data: options?.data,
151
- awaitResults: this.serializeAwaitResults(execution.awaitResults),
152
- resume: createDeferred<unknown>(),
153
- };
154
-
155
- this.enqueueSuspension(request);
156
-
157
- return request.resume.promise as Promise<T>;
158
109
  }
159
110
 
160
- hasRecordedResult(key?: string): boolean {
161
- const currentStep = this.runner.getCurrentStep();
162
- if (!currentStep) {
163
- return false;
164
- }
165
-
166
- const execution = this.ensureStepExecution(currentStep.id);
167
- const suspendKey = buildSuspendKey(execution.suspendCursor + 1, key);
168
- if (execution.awaitResults.has(suspendKey)) {
169
- return true;
111
+ /**
112
+ * Wait for the active step's next `suspend()` call.
113
+ *
114
+ * @returns The next suspension request.
115
+ */
116
+ waitForSuspension(): Promise<RuntimeSuspensionRequest> {
117
+ const active = this.active;
118
+ if (!active) {
119
+ throw new Error('No workflow step is running in this scope.');
170
120
  }
171
121
 
172
- return (this.primedResumeData.get(currentStep.id)?.length ?? 0) > 0;
173
- }
174
-
175
- resume(data?: unknown): void {
176
- void this.runner.resume({ resumeData: data });
177
- }
178
-
179
- waitForStepSuspension(stepId: string): Promise<RuntimeSuspensionRequest> {
180
- const queued = this.dequeueStepSuspension(stepId);
122
+ const queued = active.pending.shift();
181
123
  if (queued) {
182
124
  return Promise.resolve(queued);
183
125
  }
184
126
 
185
127
  return new Promise((resolve) => {
186
- const waiters = this.suspensionWaiters.get(stepId) ?? [];
187
-
188
- waiters.push(resolve);
189
- this.suspensionWaiters.set(stepId, waiters);
128
+ active.waiter = resolve;
190
129
  });
191
130
  }
192
131
 
193
- beginStepExecution(stepId: string): string {
194
- const existing = this.activeStepExecutions.get(stepId);
195
- if (existing) {
196
- return existing.stepExecId;
197
- }
198
-
199
- const seeded = this.replaySeeds.get(stepId);
200
- if (seeded) {
201
- const execution: StepExecutionState = {
202
- stepId,
203
- stepExecId: seeded.stepExecId,
204
- suspendCursor: 0,
205
- awaitResults: this.normalizeAwaitResults(seeded.awaitResults),
206
- replayExpectation: seeded.activeSuspension
207
- ? {
208
- suspendIndex: seeded.activeSuspension.suspendIndex,
209
- suspendKey:
210
- normalizeSuspendKey(
211
- seeded.activeSuspension.suspendIndex,
212
- seeded.activeSuspension.suspendKey,
213
- ) ?? buildSuspendKey(seeded.activeSuspension.suspendIndex ?? 1),
214
- reason: seeded.activeSuspension.reason,
215
- matched: false,
216
- }
217
- : undefined,
218
- };
219
-
220
- this.activeStepExecutions.set(stepId, execution);
221
- this.replaySeeds.delete(stepId);
222
- this.bumpStepAttemptCounter(stepId, execution.stepExecId);
223
-
224
- return execution.stepExecId;
225
- }
226
-
227
- const attempt = (this.stepAttempts.get(stepId) ?? 0) + 1;
228
- const stepExecId = `${stepId}#${attempt}`;
229
- this.stepAttempts.set(stepId, attempt);
230
- this.activeStepExecutions.set(stepId, {
231
- stepId,
232
- stepExecId,
233
- suspendCursor: 0,
234
- awaitResults: new Map<string, unknown>(),
235
- });
236
-
237
- return stepExecId;
238
- }
239
-
240
- prepareStepReplay(seed: RuntimeStepReplaySeed): void {
241
- const normalizedAwaitResults = this.serializeAwaitResults(
242
- this.normalizeAwaitResults(seed.awaitResults ?? {}),
243
- );
244
-
245
- this.replaySeeds.set(seed.stepId, {
246
- stepExecId: seed.stepExecId,
247
- awaitResults: normalizedAwaitResults,
248
- activeSuspension: seed.activeSuspension
249
- ? {
250
- suspendIndex: seed.activeSuspension.suspendIndex,
251
- suspendKey: normalizeSuspendKey(
252
- seed.activeSuspension.suspendIndex,
253
- seed.activeSuspension.suspendKey,
254
- ),
255
- reason: seed.activeSuspension.reason,
256
- }
257
- : undefined,
258
- });
259
- this.bumpStepAttemptCounter(seed.stepId, seed.stepExecId);
260
- }
261
-
262
- recordStepSuspendResult(params: RuntimeResolvedSuspension): void {
263
- const suspendKey = normalizeSuspendKey(
264
- params.suspendIndex,
265
- params.suspendKey,
266
- );
267
-
268
- if (!suspendKey) {
269
- this.primeStepResumeData(params.stepId, params.resumeData);
270
-
271
- return;
272
- }
273
-
274
- const activeExecution = this.activeStepExecutions.get(params.stepId);
275
- if (
276
- activeExecution &&
277
- (!params.stepExecId || params.stepExecId === activeExecution.stepExecId)
278
- ) {
279
- if (!activeExecution.awaitResults.has(suspendKey)) {
280
- activeExecution.awaitResults.set(suspendKey, params.resumeData);
281
- }
282
-
283
- return;
132
+ suspend<T = unknown>(options?: SuspensionOptions<T>): Promise<T> {
133
+ const active = this.active;
134
+ if (!active) {
135
+ throw new Error(
136
+ 'workflow.suspend() can only be called while a workflow step is running.',
137
+ );
284
138
  }
285
139
 
286
- const replaySeed = this.replaySeeds.get(params.stepId);
287
- if (replaySeed) {
288
- if (params.stepExecId && replaySeed.stepExecId !== params.stepExecId) {
289
- return;
290
- }
291
-
292
- replaySeed.awaitResults[suspendKey] =
293
- replaySeed.awaitResults[suspendKey] ?? params.resumeData;
294
- this.replaySeeds.set(params.stepId, replaySeed);
295
-
296
- return;
140
+ if (options?.accepts) {
141
+ assertJsonPayloadSchema(active, options.accepts);
297
142
  }
298
143
 
299
- const fallbackExecId = params.stepExecId ?? `${params.stepId}#1`;
300
- this.replaySeeds.set(params.stepId, {
301
- stepExecId: fallbackExecId,
302
- awaitResults: { [suspendKey]: params.resumeData },
303
- });
304
- this.bumpStepAttemptCounter(params.stepId, fallbackExecId);
305
- }
306
-
307
- clearStepSuspensions(stepId: string, error?: unknown): void {
308
- const queued = this.pendingSuspensions.get(stepId);
309
- if (queued) {
310
- for (const request of queued) {
311
- request.resume.reject(
312
- error ?? new Error(`Suspension for step "${stepId}" was cancelled.`),
144
+ if (options?.key) {
145
+ // A reused key would resolve from the first call's answer on resume,
146
+ // so the second call could never suspend.
147
+ if (active.usedKeys.has(options.key)) {
148
+ throw new Error(
149
+ `workflow.suspend() key "${options.key}" is used more than once ` +
150
+ `in step "${active.step.id}"; keys must be unique within an action body.`,
313
151
  );
314
152
  }
315
- }
316
-
317
- const execution = this.activeStepExecutions.get(stepId);
318
-
319
- this.pendingSuspensions.delete(stepId);
320
- this.suspensionWaiters.delete(stepId);
321
- this.primedResumeData.delete(stepId);
322
- this.activeStepExecutions.delete(stepId);
323
153
 
324
- if (
325
- !error &&
326
- execution?.replayExpectation &&
327
- !execution.replayExpectation.matched
328
- ) {
329
- throw new NonDeterministicWorkflowError(
330
- `Replay for step "${stepId}" did not reach expected suspension ` +
331
- `"${execution.replayExpectation.suspendKey}".`,
332
- );
154
+ active.usedKeys.add(options.key);
333
155
  }
334
- }
335
156
 
336
- primeStepResumeData(stepId: string, resumeData: unknown): void {
337
- const queued = this.primedResumeData.get(stepId) ?? [];
157
+ active.cursor += 1;
158
+ const suspendKey = buildSuspendKey(active.cursor, options?.key);
338
159
 
339
- queued.push(resumeData);
340
- this.primedResumeData.set(stepId, queued);
341
- }
160
+ this.assertReplayExpectation(active, suspendKey, options?.reason);
342
161
 
343
- getSnapshot() {
344
- return this.runner.getSnapshot();
345
- }
346
-
347
- private enqueueSuspension(request: RuntimeSuspensionRequest): void {
348
- const waiters = this.suspensionWaiters.get(request.stepId);
349
- if (waiters && waiters.length > 0) {
350
- const resolve = waiters.shift();
351
- if (!resolve) {
352
- return;
353
- }
354
-
355
- if (waiters.length === 0) {
356
- this.suspensionWaiters.delete(request.stepId);
357
- } else {
358
- this.suspensionWaiters.set(request.stepId, waiters);
359
- }
360
-
361
- resolve(request);
362
-
363
- return;
162
+ if (active.awaitResults.has(suspendKey)) {
163
+ return resolveRecordedResult(active, suspendKey, options?.accepts);
364
164
  }
365
165
 
366
- const queued = this.pendingSuspensions.get(request.stepId) ?? [];
367
-
368
- queued.push(request);
369
- this.pendingSuspensions.set(request.stepId, queued);
370
- }
371
-
372
- private dequeueStepSuspension(
373
- stepId: string,
374
- ): RuntimeSuspensionRequest | undefined {
375
- const queued = this.pendingSuspensions.get(stepId);
376
- if (!queued || queued.length === 0) {
377
- return undefined;
166
+ const request: RuntimeSuspensionRequest = {
167
+ suspendKey,
168
+ reason: options?.reason,
169
+ data: options?.data,
170
+ awaitResults: Object.fromEntries(active.awaitResults),
171
+ };
172
+ if (options?.accepts) {
173
+ request.accepts = describeResumePayload(options.accepts);
174
+ if (isPayloadOptional(options.accepts)) {
175
+ request.payloadOptional = true;
176
+ }
378
177
  }
379
-
380
- const request = queued.shift();
381
- if (queued.length === 0) {
382
- this.pendingSuspensions.delete(stepId);
178
+ const waiter = active.waiter;
179
+ if (waiter) {
180
+ active.waiter = undefined;
181
+ waiter(request);
383
182
  } else {
384
- this.pendingSuspensions.set(stepId, queued);
183
+ active.pending.push(request);
385
184
  }
386
185
 
387
- return request;
186
+ // Never settles: the step executor aborts this body, and resuming re-runs
187
+ // it so that this call resolves from `awaitResults` instead.
188
+ return new Promise<T>(() => undefined);
388
189
  }
389
190
 
390
- private dequeuePrimedResumeData(stepId: string): {
391
- found: boolean;
392
- value?: unknown;
393
- } {
394
- const queued = this.primedResumeData.get(stepId);
395
- if (!queued || queued.length === 0) {
396
- return { found: false };
397
- }
191
+ /**
192
+ * Report whether the active step, re-run to resolve a wait, has reached
193
+ * that wait's `suspend()` call. Only from then on has it read the payload,
194
+ * and can it refuse it.
195
+ *
196
+ * @returns True once the resolved suspension was reached.
197
+ */
198
+ hasReachedResolvedSuspension(): boolean {
199
+ return this.active?.expected?.matched ?? false;
200
+ }
398
201
 
399
- const value = queued.shift();
400
- if (queued.length === 0) {
401
- this.primedResumeData.delete(stepId);
402
- } else {
403
- this.primedResumeData.set(stepId, queued);
202
+ hasRecordedResult(key?: string): boolean {
203
+ const active = this.active;
204
+ if (!active) {
205
+ return false;
404
206
  }
405
207
 
406
- return { found: true, value };
208
+ return active.awaitResults.has(buildSuspendKey(active.cursor + 1, key));
407
209
  }
408
210
 
409
- private ensureStepExecution(stepId: string): StepExecutionState {
410
- const existing = this.activeStepExecutions.get(stepId);
411
- if (existing) {
412
- return existing;
211
+ markSuspendCursor(): () => void {
212
+ const active = this.active;
213
+ if (!active) {
214
+ return () => undefined;
413
215
  }
414
216
 
415
- this.beginStepExecution(stepId);
416
-
417
- const created = this.activeStepExecutions.get(stepId);
418
- if (!created) {
419
- throw new Error(`Unable to create runtime state for step "${stepId}".`);
420
- }
217
+ const cursor = active.cursor;
218
+ const usedKeys = new Set(active.usedKeys);
421
219
 
422
- return created;
220
+ return () => {
221
+ // A rewind taken in a step that has ended must not touch the next one.
222
+ if (this.active === active) {
223
+ active.cursor = cursor;
224
+ active.usedKeys = new Set(usedKeys);
225
+ }
226
+ };
423
227
  }
424
228
 
425
229
  private assertReplayExpectation(
426
- execution: StepExecutionState,
427
- encountered: { suspendIndex: number; suspendKey: string; reason?: string },
230
+ active: ActiveStep,
231
+ suspendKey: string,
232
+ reason?: string,
428
233
  ): void {
429
- const expectation = execution.replayExpectation;
430
- if (!expectation || expectation.matched) {
234
+ const expected = active.expected;
235
+ if (!expected || expected.matched) {
431
236
  return;
432
237
  }
433
238
 
434
- if (encountered.suspendKey === expectation.suspendKey) {
435
- if (
436
- expectation.reason !== undefined &&
437
- encountered.reason !== expectation.reason
438
- ) {
239
+ if (suspendKey === expected.suspendKey) {
240
+ if (expected.reason !== undefined && reason !== expected.reason) {
439
241
  throw new NonDeterministicWorkflowError(
440
- `Replay for step "${execution.stepId}" reached suspend ` +
441
- `"${encountered.suspendKey}" with reason "${encountered.reason ?? ''}", ` +
442
- `expected reason "${expectation.reason}".`,
242
+ `Resumed step "${active.step.id}" reached suspend "${suspendKey}" ` +
243
+ `with reason "${reason ?? ''}", expected reason "${expected.reason}".`,
443
244
  );
444
245
  }
445
246
 
446
- expectation.matched = true;
247
+ expected.matched = true;
447
248
 
448
249
  return;
449
250
  }
450
251
 
451
- if (execution.awaitResults.has(encountered.suspendKey)) {
252
+ if (active.awaitResults.has(suspendKey)) {
452
253
  return;
453
254
  }
454
255
 
455
256
  throw new NonDeterministicWorkflowError(
456
- `Replay for step "${execution.stepId}" reached unexpected suspend ` +
457
- `"${encountered.suspendKey}" before expected ` +
458
- `"${expectation.suspendKey}".`,
257
+ `Resumed step "${active.step.id}" reached unexpected suspend ` +
258
+ `"${suspendKey}" before expected "${expected.suspendKey}".`,
459
259
  );
460
260
  }
461
-
462
- private normalizeAwaitResults(
463
- awaitResults: Record<string, unknown>,
464
- ): Map<string, unknown> {
465
- const normalized = new Map<string, unknown>();
466
-
467
- for (const [rawKey, value] of Object.entries(awaitResults)) {
468
- const normalizedKey = normalizeStoredSuspendKey(rawKey);
469
- normalized.set(normalizedKey, value);
470
- }
471
-
472
- return normalized;
473
- }
474
-
475
- private serializeAwaitResults(
476
- awaitResults: Map<string, unknown>,
477
- ): Record<string, unknown> {
478
- return Object.fromEntries(awaitResults.entries());
479
- }
480
-
481
- private bumpStepAttemptCounter(stepId: string, stepExecId: string): void {
482
- const parsedAttempt = parseStepExecAttempt(stepId, stepExecId);
483
- if (parsedAttempt === null) {
484
- return;
485
- }
486
-
487
- const previous = this.stepAttempts.get(stepId) ?? 0;
488
- if (parsedAttempt > previous) {
489
- this.stepAttempts.set(stepId, parsedAttempt);
490
- }
491
- }
492
261
  }
493
262
 
494
- const buildSuspendKey = (suspendIndex: number, key?: string): string => {
495
- if (key) {
496
- return `${USER_KEY_PREFIX}${key}`;
263
+ /**
264
+ * Refuse an `accepts` schema that no JSON payload can match: the wait it
265
+ * opens could never be resumed, since payloads are read back as JSON.
266
+ *
267
+ * @throws {TypeError} Naming the parts of the schema JSON cannot carry.
268
+ */
269
+ const assertJsonPayloadSchema = (active: ActiveStep, accepts: ZodType) => {
270
+ const found = findNonJsonTypes(accepts);
271
+ if (found.length === 0) {
272
+ return;
497
273
  }
498
274
 
499
- return `${INDEX_KEY_PREFIX}${suspendIndex}`;
275
+ throw new TypeError(
276
+ `The accepts schema of workflow.suspend() in step "${active.step.id}" ` +
277
+ `can never match a JSON payload: ${found.join(', ')}. Resume payloads ` +
278
+ 'are stored as JSON, so accept their JSON form instead, e.g. ' +
279
+ 'z.coerce.date() or z.iso.datetime() for a date.',
280
+ );
500
281
  };
501
- const normalizeSuspendKey = (
502
- suspendIndex?: number,
503
- suspendKey?: string,
504
- ): string | undefined => {
505
- if (typeof suspendKey === 'string' && suspendKey.length > 0) {
506
- if (
507
- suspendKey.startsWith(INDEX_KEY_PREFIX) ||
508
- suspendKey.startsWith(USER_KEY_PREFIX)
509
- ) {
510
- return suspendKey;
511
- }
512
-
513
- if (/^\d+$/.test(suspendKey)) {
514
- return `${INDEX_KEY_PREFIX}${suspendKey}`;
515
- }
516
-
517
- return `${USER_KEY_PREFIX}${suspendKey}`;
518
- }
519
-
520
- if (
521
- typeof suspendIndex === 'number' &&
522
- Number.isInteger(suspendIndex) &&
523
- suspendIndex > 0
524
- ) {
525
- return `${INDEX_KEY_PREFIX}${suspendIndex}`;
282
+ /**
283
+ * Resolve a `suspend()` call from its recorded result, parsed through the
284
+ * call's `accepts` schema when it has one.
285
+ *
286
+ * The body gets its own copy: the recorded result is saved again with the
287
+ * step's next suspension and replayed on every later pass, so a body that
288
+ * changed it would see its own change applied twice.
289
+ *
290
+ * @returns The recorded (or parsed) result. It rejects with a
291
+ * `WorkflowResumeRejectedError` when the payload this pass resolved fails the
292
+ * schema, and with a {@link NonDeterministicWorkflowError} when a result
293
+ * accepted by an earlier pass no longer does.
294
+ */
295
+ const resolveRecordedResult = async <T>(
296
+ active: ActiveStep,
297
+ suspendKey: string,
298
+ accepts?: ZodType<T>,
299
+ ): Promise<T> => {
300
+ const recorded = cloneValue(active.awaitResults.get(suspendKey));
301
+ if (!accepts) {
302
+ return recorded as T;
526
303
  }
527
304
 
528
- return undefined;
529
- };
530
- const normalizeStoredSuspendKey = (rawKey: string): string => {
531
- if (
532
- rawKey.startsWith(INDEX_KEY_PREFIX) ||
533
- rawKey.startsWith(USER_KEY_PREFIX)
534
- ) {
535
- return rawKey;
305
+ const parsed = await accepts.safeParseAsync(recorded);
306
+ if (parsed.success) {
307
+ return parsed.data;
536
308
  }
537
309
 
538
- if (/^\d+$/.test(rawKey)) {
539
- return `${INDEX_KEY_PREFIX}${rawKey}`;
310
+ if (suspendKey === active.expected?.suspendKey) {
311
+ throw rejectResumePayload(`step "${active.step.id}"`, parsed.error.issues);
540
312
  }
541
313
 
542
- return `${USER_KEY_PREFIX}${rawKey}`;
314
+ throw new NonDeterministicWorkflowError(
315
+ `Resumed step "${active.step.id}" recorded a result for suspend ` +
316
+ `"${suspendKey}" that no longer matches its accepts schema.`,
317
+ );
543
318
  };
544
- const parseStepExecAttempt = (
545
- stepId: string,
546
- stepExecId: string,
547
- ): number | null => {
548
- const prefix = `${stepId}#`;
549
- if (!stepExecId.startsWith(prefix)) {
550
- return null;
551
- }
552
-
553
- const numeric = Number.parseInt(stepExecId.slice(prefix.length), 10);
554
- if (Number.isNaN(numeric) || numeric < 1) {
555
- return null;
319
+ const buildSuspendKey = (suspendIndex: number, key?: string): string => {
320
+ if (key) {
321
+ return `${USER_KEY_PREFIX}${key}`;
556
322
  }
557
323
 
558
- return numeric;
324
+ return `${INDEX_KEY_PREFIX}${suspendIndex}`;
559
325
  };