@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
package/README.md CHANGED
@@ -5,9 +5,9 @@ Typed runtime and YAML DSL for orchestrating multi-step AI/automation workflows.
5
5
  ## Highlights
6
6
  - Declarative workflow DSL in YAML or JS objects with JSONata expressions (prefixed by `=`) and clear scopes (`$input`, `$context`, `$output`, `$iteration`, `$accumulator`).
7
7
  - Type-safe actions built with `defineAction`, Zod-validated IO, and merged settings (timeouts, retries, plus action-specific options) inherited from workflow defaults.
8
- - Resumable execution via `WorkflowRunner` and `context.workflow.suspend`, plus snapshots for persistence and replay.
8
+ - Durable, resumable execution via `WorkflowRunner` and `context.workflow.suspend`: a suspended run yields a JSON checkpoint that any process can resume, including suspensions inside `parallel` blocks.
9
9
  - Flow primitives: sequential `do`, truly concurrent `parallel` blocks (`wait_all`/`wait_any`), `conditional` branches, and two loop variants: `loop.type: for_each` (iterables) and `loop.type: while` (pre-check condition).
10
- - Event emitter hooks for observability (`hook:workflow:start|finish|failure|suspended`, `hook:step:start|success|error|cancelled|suspended|skipped`).
10
+ - Event emitter hooks for observability (`hook:workflow:start|finish|failure|suspended|resume_rejected`, `hook:step:start|resumed|resume_rejected|success|error|cancelled|suspended|skipped`).
11
11
 
12
12
  ## Installation
13
13
 
@@ -17,7 +17,7 @@ pnpm add @hexabot-ai/agentic
17
17
  npm install @hexabot-ai/agentic
18
18
  ```
19
19
 
20
- Requires Node.js >= 24.17.0.
20
+ Requires Node.js >= 24.22.1.
21
21
 
22
22
  The package ships both ESM (`import`) and CommonJS (`require`) entrypoints plus browser-safe internals, so you can run workflows in Node.js or bundle them for the client.
23
23
 
@@ -104,9 +104,9 @@ export const call_api = defineAction<
104
104
  });
105
105
  ```
106
106
 
107
- Settings are parsed and merged with workflow defaults before `execute` runs; retries and timeout wrappers are applied automatically. Each action receives an `AbortSignal` as `signal`; long-running actions should stop promptly when it is aborted. Awaiting `context.workflow.suspend(...)` pauses the workflow until `resume` is called, except inside `parallel` branches where suspension fails with `ParallelSuspensionError`.
107
+ Settings are parsed and merged with workflow defaults before `execute` runs; retries and timeout wrappers are applied automatically. Each action receives an `AbortSignal` as `signal`; long-running actions should stop promptly when it is aborted. Awaiting `context.workflow.suspend(...)` pauses the workflow until `resume` is called; see [Suspension and human-in-the-loop](#suspension-and-human-in-the-loop).
108
108
 
109
- Parallel branches start concurrently with isolated `$output`, `$iteration`, `$accumulator`, and context state from the parallel entry point. `wait_all` merges successful branch output deltas in child order. `wait_any` advances with the first successful branch, aborts losing branches, and discards loser outputs.
109
+ Parallel branches start concurrently with isolated `$output`, `$iteration`, `$accumulator`, and context state from the parallel entry point. `wait_all` merges successful branch output deltas in child order. `wait_any` advances with the first successful branch, aborts losing branches, and discards loser outputs. Branches may suspend: the block waits for every branch to finish or suspend, then suspends with one open wait per suspended branch.
110
110
 
111
111
  ## Running a workflow from YAML
112
112
 
@@ -137,9 +137,17 @@ const startResult = await runner.start({
137
137
  if (startResult.status === 'finished') {
138
138
  console.log('output', startResult.output);
139
139
  } else if (startResult.status === 'suspended') {
140
- // persist startResult.snapshot and prompt the user; resume later:
141
- const resumeResult = await runner.resume({ resumeData: { reply: 'go' } });
142
- console.log(resumeResult.status, resumeResult.output);
140
+ // Persist startResult.checkpoint (plain JSON) and prompt the user; later:
141
+ const restored = workflow.buildRunnerFromCheckpoint({
142
+ checkpoint: startResult.checkpoint,
143
+ snapshot: startResult.snapshot,
144
+ context,
145
+ });
146
+ const resumeResult = await restored.resume({
147
+ waitId: startResult.waits[0].waitId,
148
+ resumeData: { reply: 'go' },
149
+ });
150
+ console.log(resumeResult.status);
143
151
  }
144
152
  ```
145
153
 
@@ -195,28 +203,72 @@ These helpers are registered on every expression and can be referenced from YAML
195
203
  Inside an action you can pause execution and surface metadata to the caller:
196
204
 
197
205
  ```ts
198
- export const await_user = defineAction<unknown, { reply?: string }, AppContext, Settings>({
206
+ export const await_user = defineAction<unknown, { reply: string }, AppContext, Settings>({
199
207
  name: 'await_user',
200
208
  execute: async ({ context }) => {
201
- const resumeData = await context.workflow.suspend({
209
+ const { reply } = await context.workflow.suspend({
202
210
  reason: 'awaiting_user',
203
211
  data: { prompt: 'Please confirm' },
212
+ accepts: z.object({ reply: z.string() }),
204
213
  });
205
- return { reply: (resumeData as { reply?: string })?.reply };
214
+ return { reply };
206
215
  },
207
216
  });
208
217
  ```
209
218
 
210
- `Workflow.run` throws an error with suspension details (`stepId`, `reason`, `data`) when this happens; `WorkflowRunner.start` instead returns `{ status: 'suspended', ... }` so hosts can persist state and resume later with `runner.resume`.
219
+ `accepts` declares the payload the wait accepts and types what `suspend()` resolves with. A payload that does not match it is refused without failing the run: the run stays suspended on the same wait, with the same `waitId`. An action can also refuse a payload it has read by throwing `WorkflowResumeRejectedError`.
211
220
 
212
- Suspending actions must not be placed inside `parallel` blocks.
221
+ Payloads are stored as JSON, so `accepts` sees a payload in its JSON form: a `Date` arrives as its ISO string, and a resume without payload arrives as `undefined` (make the schema `.optional()` to allow it). Declare the JSON form, e.g. `z.coerce.date()` or `z.iso.datetime()` rather than `z.date()`; `suspend()` throws when part of the schema is a type JSON cannot carry, since no payload could ever resume that wait.
222
+
223
+ `WorkflowRunner.start` and `resume` return `{ status: 'suspended', waits, checkpoint, snapshot }` when a run pauses. `Workflow.run` throws an error carrying the same `waits`.
224
+
225
+ - **`waits`** lists every open wait (`waitId`, `step`, `suspendKey`, `reason`, `data`, and `accepts`, a JSON Schema of the payload when the action declared one, with `payloadOptional` when it may be left out). A run can hold several when branches of a `parallel` block suspend. `waitId` is opaque; do not parse it.
226
+ - **`checkpoint`** is plain JSON holding everything needed to resume: the frames of the suspended control flow (sequence positions, chosen branches, loop items and accumulators, parallel branch outcomes), the outputs so far, and the suspended tasks' inputs and earlier resume payloads. Persist it as-is. It is built through JSON, so a resumed run sees the same values in process and after a restore (a `Date` becomes its ISO string); a run whose state JSON cannot encode, such as a `BigInt`, fails instead of suspending.
227
+
228
+ To resume, possibly in another process:
229
+
230
+ ```ts
231
+ const resumeData = { reply: 'go' };
232
+ const validation = workflow.validateCheckpoint(stored.checkpoint, { waitId, resumeData });
233
+ if (!validation.ok) {
234
+ // WorkflowCheckpointInvalidError | WorkflowDefinitionDriftError | WorkflowWaitNotFoundError
235
+ // | WorkflowWaitAmbiguousError (several waits are open and no waitId was given)
236
+ // | WorkflowResumeRejectedError (the payload does not match what the wait accepts)
237
+ throw validation.error;
238
+ }
239
+
240
+ const runner = workflow.buildRunnerFromCheckpoint({
241
+ checkpoint: stored.checkpoint,
242
+ snapshot: stored.snapshot,
243
+ context,
244
+ });
245
+ const result = await runner.resume({ waitId, resumeData });
246
+ if (result.status === 'suspended' && result.rejection) {
247
+ // Refused payload: the checkpoint, snapshot and step log are unchanged, the wait is still open.
248
+ }
249
+ ```
250
+
251
+ `validateCheckpoint` runs no action and needs no context, so hosts can call it before claiming a wait. It checks a payload against the same wait `resume` would resolve: `waitId` may be omitted from both only when exactly one wait is open.
252
+
253
+ Resuming skips every step that already completed. The suspended action's body **runs again from the top**: `suspend()` calls it already made resolve immediately with their recorded results, including the one being resumed. Guard side effects that happen before a `suspend()` with `context.workflow.hasRecordedResult()`:
254
+
255
+ ```ts
256
+ if (!context.workflow.hasRecordedResult()) {
257
+ await sendPrompt(); // runs once, not once per resume
258
+ }
259
+ const reply = await context.workflow.suspend({ reason: 'awaiting_user' });
260
+ ```
261
+
262
+ When an action suspends, its `signal` is aborted and its timeout stops counting; suspended time does not count toward `timeout_ms`. An action that implements its own retry loop instead of relying on `AbstractAction` should call `context.workflow.markSuspendCursor?.()` before its first attempt and the returned rewind function before each attempt, so a retry resolves the same `suspend()` calls again. See [SUSPENSION.md](./SUSPENSION.md) for the full design.
213
263
 
214
264
  ## Events and observability
215
265
 
216
266
  `WorkflowRunner` can publish lifecycle hooks to any emitter-like object with `emit`/`on` (`WorkflowEventEmitterLike`); `WorkflowEventEmitter` is the built-in helper and mirrors these events:
217
267
 
218
- - `hook:workflow:start | finish | failure | suspended`
219
- - `hook:step:start | success | error | cancelled | suspended | skipped`
268
+ - `hook:workflow:start | finish | failure | suspended | resume_rejected`
269
+ - `hook:step:start | resumed | resume_rejected | success | error | cancelled | suspended | skipped`
270
+
271
+ Events about a wait (`hook:step:suspended`, `resumed`, `resume_rejected`, and `cancelled` when it drops a parked wait, plus `hook:workflow:resume_rejected`) carry its `wait` (`WaitInfo`), so hosts can match them by `waitId`. `resumed` and `hook:workflow:resume_rejected` also carry `resumeData`.
220
272
 
221
273
  Attach listeners to stream logs, emit metrics, or capture snapshots for debugging.
222
274
 
@@ -89,10 +89,18 @@ class AbstractAction {
89
89
  const maxDelayMs = retrySettings.max_delay_ms;
90
90
  const jitter = retrySettings.jitter;
91
91
  const multiplier = retrySettings.multiplier;
92
+ // Suspend keys are positional within the body, so every attempt has to
93
+ // start from where this run did: otherwise a retry asks for `index:2`
94
+ // where the first attempt resolved `index:1`, and the step suspends on a
95
+ // wait whose payload was already delivered.
96
+ const rewindSuspendCursor = context
97
+ ?.getWorkflowRuntime?.()
98
+ ?.markSuspendCursor?.();
92
99
  while (attempt < maxAttempts) {
93
100
  if (signal) {
94
101
  (0, errors_1.throwIfAborted)(signal);
95
102
  }
103
+ rewindSuspendCursor?.();
96
104
  try {
97
105
  const result = await (0, timeout_1.withTimeout)(this.execute({
98
106
  input,
@@ -105,7 +113,11 @@ class AbstractAction {
105
113
  }
106
114
  catch (error) {
107
115
  attempt += 1;
108
- if (attempt >= maxAttempts) {
116
+ // A retry would read the same refused resume payload again, or replay
117
+ // the same body into the same mismatch with what it recorded.
118
+ if (attempt >= maxAttempts ||
119
+ (0, errors_1.isWorkflowResumeRejectedError)(error) ||
120
+ (0, errors_1.isNonDeterministicWorkflowError)(error)) {
109
121
  throw error;
110
122
  }
111
123
  let delay = currentDelay;
@@ -0,0 +1,301 @@
1
+ "use strict";
2
+ /*
3
+ * Hexabot — Fair Core License (FCL-1.0-ALv2)
4
+ * Copyright (c) 2025 Hexastack.
5
+ * Full terms: see LICENSE.md.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.buildWaitId = exports.workflowCheckpointSchema = exports.CHECKPOINT_VERSION = void 0;
9
+ exports.collectWaits = collectWaits;
10
+ exports.selectWait = selectWait;
11
+ exports.assertFrameMatchesStep = assertFrameMatchesStep;
12
+ exports.validateCheckpoint = validateCheckpoint;
13
+ const zod_1 = require("zod");
14
+ const errors_1 = require("./errors");
15
+ const resume_payload_1 = require("./resume-payload");
16
+ const clone_1 = require("./utils/clone");
17
+ const workflow_event_emitter_1 = require("./workflow-event-emitter");
18
+ const workflow_fingerprint_1 = require("./workflow-fingerprint");
19
+ /** Current format version of {@link WorkflowCheckpoint}. */
20
+ exports.CHECKPOINT_VERSION = 1;
21
+ const recordSchema = zod_1.z.record(zod_1.z.string(), zod_1.z.unknown());
22
+ const stepIdSchema = zod_1.z.string().min(1);
23
+ const stepInfoSchema = zod_1.z.object({
24
+ id: stepIdSchema,
25
+ name: zod_1.z.string(),
26
+ type: zod_1.z.enum(workflow_event_emitter_1.StepType),
27
+ });
28
+ const waitInfoSchema = zod_1.z.object({
29
+ waitId: zod_1.z.string().min(1),
30
+ step: stepInfoSchema,
31
+ suspendKey: zod_1.z.string().min(1),
32
+ reason: zod_1.z.string().optional(),
33
+ data: zod_1.z.unknown().optional(),
34
+ accepts: recordSchema.optional(),
35
+ payloadOptional: zod_1.z.boolean().optional(),
36
+ });
37
+ const taskFrameSchema = zod_1.z.object({
38
+ kind: zod_1.z.literal('task'),
39
+ stepId: stepIdSchema,
40
+ inputs: recordSchema,
41
+ awaitResults: zod_1.z.record(zod_1.z.string(), zod_1.z.object({ value: zod_1.z.unknown().optional() })),
42
+ wait: waitInfoSchema,
43
+ });
44
+ const conditionalFrameSchema = zod_1.z.lazy(() => zod_1.z.object({
45
+ kind: zod_1.z.literal('conditional'),
46
+ stepId: stepIdSchema,
47
+ branchIndex: zod_1.z.int().nonnegative(),
48
+ child: sequenceFrameSchema,
49
+ }));
50
+ const loopFrameSchema = zod_1.z.lazy(() => zod_1.z.object({
51
+ kind: zod_1.z.literal('loop'),
52
+ stepId: stepIdSchema,
53
+ index: zod_1.z.int().nonnegative(),
54
+ items: zod_1.z.array(zod_1.z.unknown()).optional(),
55
+ accumulator: zod_1.z.unknown().optional(),
56
+ child: sequenceFrameSchema,
57
+ }));
58
+ const parallelFrameSchema = zod_1.z.lazy(() => zod_1.z.object({
59
+ kind: zod_1.z.literal('parallel'),
60
+ stepId: stepIdSchema,
61
+ branches: zod_1.z.array(zod_1.z.union([
62
+ zod_1.z.object({ status: zod_1.z.literal('fulfilled'), outputDelta: recordSchema }),
63
+ zod_1.z.object({
64
+ status: zod_1.z.literal('suspended'),
65
+ outputDelta: recordSchema,
66
+ child: stepFrameSchema,
67
+ }),
68
+ ])),
69
+ }));
70
+ const stepFrameSchema = zod_1.z.lazy(() => zod_1.z.union([
71
+ taskFrameSchema,
72
+ conditionalFrameSchema,
73
+ loopFrameSchema,
74
+ parallelFrameSchema,
75
+ ]));
76
+ const sequenceFrameSchema = zod_1.z.lazy(() => zod_1.z.object({
77
+ kind: zod_1.z.literal('sequence'),
78
+ index: zod_1.z.int().nonnegative(),
79
+ accumulator: zod_1.z.unknown().optional(),
80
+ child: stepFrameSchema,
81
+ }));
82
+ /** Schema of a persisted {@link WorkflowCheckpoint}, for hosts to type storage. */
83
+ exports.workflowCheckpointSchema = zod_1.z.object({
84
+ version: zod_1.z.literal(exports.CHECKPOINT_VERSION),
85
+ fingerprint: zod_1.z.string().min(1),
86
+ input: recordSchema,
87
+ output: recordSchema,
88
+ root: sequenceFrameSchema,
89
+ waits: zod_1.z.array(waitInfoSchema).min(1),
90
+ });
91
+ /**
92
+ * Build the handle of a wait from the instance step that suspended and its
93
+ * suspend key.
94
+ *
95
+ * @param stepInstanceId Instance step id, including any loop iteration suffix.
96
+ * @param suspendKey Normalized suspend key within the step body.
97
+ * @returns The wait id.
98
+ */
99
+ const buildWaitId = (stepInstanceId, suspendKey) => `${stepInstanceId}@${suspendKey}`;
100
+ exports.buildWaitId = buildWaitId;
101
+ /**
102
+ * List the open waits held by a frame tree, in flow order.
103
+ *
104
+ * @param frame Root or subtree of a checkpoint.
105
+ * @returns The waits of every suspended task under the frame.
106
+ */
107
+ function collectWaits(frame) {
108
+ switch (frame.kind) {
109
+ case 'task':
110
+ return [frame.wait];
111
+ case 'sequence':
112
+ case 'conditional':
113
+ case 'loop':
114
+ return collectWaits(frame.child);
115
+ case 'parallel':
116
+ return frame.branches.flatMap((branch) => branch.status === 'suspended' ? collectWaits(branch.child) : []);
117
+ }
118
+ }
119
+ /**
120
+ * Pick the wait a resume targets. `resume()` and `validateCheckpoint` both
121
+ * use it, so a payload is always checked against the wait it would resolve.
122
+ *
123
+ * @param waits Open waits of the suspended run.
124
+ * @param waitId Requested wait, optional when exactly one wait is open.
125
+ * @returns The targeted wait.
126
+ * @throws {WorkflowWaitNotFoundError} When `waitId` is not an open wait.
127
+ * @throws {WorkflowWaitAmbiguousError} When several waits are open and no
128
+ * `waitId` is given.
129
+ */
130
+ function selectWait(waits, waitId) {
131
+ const openWaitIds = waits.map((candidate) => candidate.waitId);
132
+ if (waitId === undefined) {
133
+ if (waits.length === 1) {
134
+ return waits[0];
135
+ }
136
+ throw new errors_1.WorkflowWaitAmbiguousError(openWaitIds);
137
+ }
138
+ const wait = waits.find((candidate) => candidate.waitId === waitId);
139
+ if (!wait) {
140
+ throw new errors_1.WorkflowWaitNotFoundError(waitId, openWaitIds);
141
+ }
142
+ return wait;
143
+ }
144
+ /**
145
+ * Check that a frame was taken for the given compiled step.
146
+ *
147
+ * @param frame The frame about to be resumed, if any.
148
+ * @param step The compiled step it is being handed to.
149
+ * @param path Location used in the error message.
150
+ * @throws {WorkflowCheckpointInvalidError} When the frame belongs elsewhere.
151
+ */
152
+ function assertFrameMatchesStep(frame, step, path = []) {
153
+ if (!frame) {
154
+ return;
155
+ }
156
+ if (frame.kind !== step.type || frame.stepId !== step.id) {
157
+ throw new errors_1.WorkflowCheckpointInvalidError('structure', `Checkpoint expects ${frame.kind} step "${frame.stepId}" but the flow ` +
158
+ `has ${step.type} step "${step.id}".`, { path });
159
+ }
160
+ }
161
+ /**
162
+ * Decide whether a checkpoint can resume against a compiled workflow, without
163
+ * running anything.
164
+ *
165
+ * Checks, in order: presence and shape, format version, definition
166
+ * fingerprint, that every frame lines up with the compiled step it names, that
167
+ * the `waits` index matches the frame tree, and (optionally) that a given wait
168
+ * is open and accepts a given payload.
169
+ *
170
+ * @param compiled The compiled workflow the run will resume against.
171
+ * @param checkpoint The persisted checkpoint, as stored.
172
+ * @param options.waitId Wait the caller is about to resume.
173
+ * @param options.resumeData Payload the caller is about to resume with. When
174
+ * the key is present, it is checked against the wait `resume()` would pick:
175
+ * the one named by `waitId`, or the only open wait.
176
+ * @returns The parsed checkpoint, or the typed reason it cannot resume.
177
+ */
178
+ function validateCheckpoint(compiled, checkpoint, options = {}) {
179
+ try {
180
+ const parsed = parseCheckpoint(checkpoint);
181
+ const actual = (0, workflow_fingerprint_1.fingerprintWorkflow)(compiled);
182
+ if (parsed.fingerprint !== actual) {
183
+ throw new errors_1.WorkflowDefinitionDriftError(parsed.fingerprint, actual);
184
+ }
185
+ assertSequenceMatches(compiled.flow, parsed.root, ['root']);
186
+ assertWaitIndex(parsed);
187
+ if (options.waitId !== undefined || 'resumeData' in options) {
188
+ const wait = selectWait(parsed.waits, options.waitId);
189
+ if ('resumeData' in options) {
190
+ const payload = (0, resume_payload_1.checkResumePayload)(wait, options.resumeData);
191
+ if (!payload.ok) {
192
+ throw payload.error;
193
+ }
194
+ }
195
+ }
196
+ return { ok: true, checkpoint: parsed };
197
+ }
198
+ catch (error) {
199
+ if (error instanceof errors_1.WorkflowResumeError) {
200
+ return { ok: false, error };
201
+ }
202
+ throw error;
203
+ }
204
+ }
205
+ const parseCheckpoint = (checkpoint) => {
206
+ if (checkpoint === null || checkpoint === undefined) {
207
+ throw new errors_1.WorkflowCheckpointInvalidError('missing', 'No checkpoint was persisted for this run.');
208
+ }
209
+ if ((0, clone_1.isRecord)(checkpoint) &&
210
+ checkpoint.version !== undefined &&
211
+ checkpoint.version !== exports.CHECKPOINT_VERSION) {
212
+ throw new errors_1.WorkflowCheckpointInvalidError('unsupported_version', `Unsupported checkpoint version ${String(checkpoint.version)}; ` +
213
+ `expected ${exports.CHECKPOINT_VERSION}.`);
214
+ }
215
+ const result = exports.workflowCheckpointSchema.safeParse(checkpoint);
216
+ if (!result.success) {
217
+ const issues = result.error.issues.map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`);
218
+ throw new errors_1.WorkflowCheckpointInvalidError('malformed', `Checkpoint does not match the expected shape: ${issues.join('; ')}`, { issues });
219
+ }
220
+ return result.data;
221
+ };
222
+ const structureError = (message, path) => new errors_1.WorkflowCheckpointInvalidError('structure', message, { path });
223
+ const assertSequenceMatches = (steps, frame, path) => {
224
+ const step = steps[frame.index];
225
+ if (!step) {
226
+ throw structureError(`Sequence position ${frame.index} is out of range (${steps.length} steps).`, path);
227
+ }
228
+ assertStepMatches(step, frame.child, [...path, frame.index]);
229
+ };
230
+ const assertStepMatches = (step, frame, path) => {
231
+ assertFrameMatchesStep(frame, step, path);
232
+ switch (step.type) {
233
+ case workflow_event_emitter_1.StepType.Task:
234
+ return;
235
+ case workflow_event_emitter_1.StepType.Conditional:
236
+ return assertConditionalMatches(step, frame, path);
237
+ case workflow_event_emitter_1.StepType.Loop:
238
+ return assertLoopMatches(step, frame, path);
239
+ case workflow_event_emitter_1.StepType.Parallel:
240
+ return assertParallelMatches(step, frame, path);
241
+ }
242
+ };
243
+ const assertConditionalMatches = (step, frame, path) => {
244
+ const branch = step.branches[frame.branchIndex];
245
+ if (!branch) {
246
+ throw structureError(`Branch ${frame.branchIndex} does not exist on conditional "${step.id}".`, path);
247
+ }
248
+ assertSequenceMatches(branch.steps, frame.child, [
249
+ ...path,
250
+ 'branch',
251
+ frame.branchIndex,
252
+ ]);
253
+ };
254
+ const assertLoopMatches = (step, frame, path) => {
255
+ if (step.loopType === 'for_each') {
256
+ if (!frame.items || frame.index >= frame.items.length) {
257
+ throw structureError(`for_each loop "${step.id}" is suspended at iteration ${frame.index} ` +
258
+ `of ${frame.items?.length ?? 0} recorded items.`, path);
259
+ }
260
+ }
261
+ else if (frame.items !== undefined) {
262
+ throw structureError(`while loop "${step.id}" cannot carry for_each items.`, path);
263
+ }
264
+ assertSequenceMatches(step.steps, frame.child, [...path, frame.index]);
265
+ };
266
+ const assertParallelMatches = (step, frame, path) => {
267
+ if (frame.branches.length !== step.steps.length) {
268
+ throw structureError(`Parallel "${step.id}" has ${step.steps.length} branches but the ` +
269
+ `checkpoint records ${frame.branches.length}.`, path);
270
+ }
271
+ let suspended = 0;
272
+ frame.branches.forEach((branch, index) => {
273
+ if (branch.status === 'suspended') {
274
+ suspended += 1;
275
+ assertStepMatches(step.steps[index], branch.child, [
276
+ ...path,
277
+ 'parallel',
278
+ index,
279
+ ]);
280
+ }
281
+ else if (step.strategy === 'wait_any') {
282
+ // A fulfilled branch wins a wait_any race, so it can never be parked.
283
+ throw structureError(`wait_any parallel "${step.id}" cannot record a fulfilled branch.`, path);
284
+ }
285
+ });
286
+ if (suspended === 0) {
287
+ throw structureError(`Parallel "${step.id}" is recorded as suspended without a suspended branch.`, path);
288
+ }
289
+ };
290
+ const assertWaitIndex = (checkpoint) => {
291
+ const expected = collectWaits(checkpoint.root).map((wait) => wait.waitId);
292
+ const actual = checkpoint.waits.map((wait) => wait.waitId);
293
+ if (expected.length !== actual.length ||
294
+ expected.some((waitId, index) => waitId !== actual[index])) {
295
+ throw structureError(`Checkpoint waits [${actual.join(', ')}] do not match the suspended ` +
296
+ `steps [${expected.join(', ')}].`, ['waits']);
297
+ }
298
+ if (new Set(expected).size !== expected.length) {
299
+ throw structureError(`Checkpoint holds duplicate waits [${expected.join(', ')}].`, ['waits']);
300
+ }
301
+ };
@@ -6,13 +6,14 @@
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.BaseWorkflowContext = exports.WORKFLOW_RUN_STATUSES = exports.EWorkflowRunStatus = void 0;
9
+ const clone_1 = require("./utils/clone");
9
10
  /**
10
11
  * Lifecycle of a workflow run:
11
12
  * - idle: runner constructed but `start` not invoked.
12
13
  * - running: set when `start` or `resume` begins executing steps.
13
14
  * - suspended: an action awaited `workflow.suspend`; `resume` moves back to running.
14
15
  * - finished: all steps completed and outputs were evaluated successfully.
15
- * - failed: an uncaught error bubbled out of a step or continuation.
16
+ * - failed: an uncaught error bubbled out of a step or the output mapping.
16
17
  */
17
18
  var EWorkflowRunStatus;
18
19
  (function (EWorkflowRunStatus) {
@@ -50,7 +51,7 @@ class BaseWorkflowContext {
50
51
  * Override to filter or reshape the exposed state.
51
52
  */
52
53
  snapshot() {
53
- return safeCloneRecord(this.state);
54
+ return (0, clone_1.cloneRecord)(this.state ?? {});
54
55
  }
55
56
  /**
56
57
  * Provides access to the workflow runtime API for the current execution.
@@ -64,6 +65,14 @@ class BaseWorkflowContext {
64
65
  }
65
66
  return this._workflowControl;
66
67
  }
68
+ /**
69
+ * Reads the runtime control without throwing when none is attached.
70
+ *
71
+ * @returns The attached runtime control, or `undefined` outside a run.
72
+ */
73
+ getWorkflowRuntime() {
74
+ return this._workflowControl;
75
+ }
67
76
  /**
68
77
  * Attaches or detaches the runtime control object.
69
78
  *
@@ -75,28 +84,3 @@ class BaseWorkflowContext {
75
84
  }
76
85
  }
77
86
  exports.BaseWorkflowContext = BaseWorkflowContext;
78
- const safeCloneRecord = (value) => {
79
- if (!value) {
80
- return {};
81
- }
82
- if (typeof structuredClone === 'function') {
83
- try {
84
- return structuredClone(value);
85
- }
86
- catch {
87
- // Fall through to JSON clone below.
88
- }
89
- }
90
- try {
91
- return JSON.parse(JSON.stringify(value));
92
- }
93
- catch {
94
- const shallow = {};
95
- for (const [key, entry] of Object.entries(value)) {
96
- if (typeof entry !== 'function') {
97
- shallow[key] = entry;
98
- }
99
- }
100
- return shallow;
101
- }
102
- };
@@ -168,6 +168,9 @@ const ConditionalWhenSchema = zod_1.z.lazy(() => zod_1.z.strictObject({
168
168
  steps: zod_1.z.array(exports.FlowStepSchema),
169
169
  }));
170
170
  const ConditionalElseSchema = zod_1.z.lazy(() => zod_1.z.strictObject({
171
+ // Refusing `condition` here keeps a `when` branch with a bad condition
172
+ // from also matching as an `else` branch, so its own issue is reported.
173
+ condition: zod_1.z.never().optional(),
171
174
  else: zod_1.z.unknown().optional(),
172
175
  steps: zod_1.z.array(exports.FlowStepSchema),
173
176
  }));