@hexabot-ai/agentic 3.5.0-beta.0 → 3.6.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 (145) hide show
  1. package/README.md +12 -3
  2. package/dist/cjs/action/abstract-action.js +51 -35
  3. package/dist/cjs/bindings/base-binding.js +229 -211
  4. package/dist/cjs/checkpoint.js +1 -1
  5. package/dist/cjs/context.js +2 -3
  6. package/dist/cjs/dsl.types.js +44 -90
  7. package/dist/cjs/errors.js +13 -1
  8. package/dist/cjs/index.js +3 -1
  9. package/dist/cjs/resume-payload.js +11 -1
  10. package/dist/cjs/runner-runtime-control.js +39 -27
  11. package/dist/cjs/step-executors/conditional-executor.js +2 -7
  12. package/dist/cjs/step-executors/loop-executor.js +14 -28
  13. package/dist/cjs/step-executors/parallel-executor.js +14 -25
  14. package/dist/cjs/step-executors/scope.js +25 -0
  15. package/dist/cjs/step-executors/skip-helpers.js +26 -34
  16. package/dist/cjs/step-executors/task-executor.js +58 -69
  17. package/dist/cjs/utils/flow-steps.js +41 -0
  18. package/dist/cjs/utils/naming.js +10 -10
  19. package/dist/cjs/utils/object-path.js +51 -0
  20. package/dist/cjs/utils/timeout.js +16 -39
  21. package/dist/cjs/validation-issue.js +14 -1
  22. package/dist/cjs/workflow-compiler.js +52 -96
  23. package/dist/cjs/workflow-fingerprint.js +22 -11
  24. package/dist/cjs/workflow-runner.js +19 -25
  25. package/dist/cjs/workflow-values.js +9 -7
  26. package/dist/cjs/workflow.js +44 -103
  27. package/dist/esm/action/abstract-action.js +51 -35
  28. package/dist/esm/bindings/base-binding.js +229 -211
  29. package/dist/esm/checkpoint.js +2 -2
  30. package/dist/esm/context.js +2 -3
  31. package/dist/esm/dsl.types.js +42 -88
  32. package/dist/esm/errors.js +11 -0
  33. package/dist/esm/index.js +2 -2
  34. package/dist/esm/resume-payload.js +10 -1
  35. package/dist/esm/runner-runtime-control.js +39 -27
  36. package/dist/esm/step-executors/conditional-executor.js +2 -7
  37. package/dist/esm/step-executors/loop-executor.js +14 -28
  38. package/dist/esm/step-executors/parallel-executor.js +14 -25
  39. package/dist/esm/step-executors/scope.js +21 -0
  40. package/dist/esm/step-executors/skip-helpers.js +27 -35
  41. package/dist/esm/step-executors/task-executor.js +58 -69
  42. package/dist/esm/utils/flow-steps.js +37 -0
  43. package/dist/esm/utils/naming.js +9 -9
  44. package/dist/esm/utils/object-path.js +46 -0
  45. package/dist/esm/utils/timeout.js +16 -39
  46. package/dist/esm/validation-issue.js +11 -0
  47. package/dist/esm/workflow-compiler.js +50 -95
  48. package/dist/esm/workflow-fingerprint.js +22 -11
  49. package/dist/esm/workflow-runner.js +21 -27
  50. package/dist/esm/workflow-values.js +7 -6
  51. package/dist/esm/workflow.js +43 -103
  52. package/dist/types/action/abstract-action.d.ts +7 -1
  53. package/dist/types/action/abstract-action.d.ts.map +1 -1
  54. package/dist/types/bindings/base-binding.d.ts +10 -0
  55. package/dist/types/bindings/base-binding.d.ts.map +1 -1
  56. package/dist/types/context.d.ts +2 -3
  57. package/dist/types/context.d.ts.map +1 -1
  58. package/dist/types/dsl.types.d.ts +7 -12
  59. package/dist/types/dsl.types.d.ts.map +1 -1
  60. package/dist/types/errors.d.ts +9 -0
  61. package/dist/types/errors.d.ts.map +1 -1
  62. package/dist/types/index.d.ts +2 -2
  63. package/dist/types/index.d.ts.map +1 -1
  64. package/dist/types/resume-payload.d.ts +7 -0
  65. package/dist/types/resume-payload.d.ts.map +1 -1
  66. package/dist/types/runner-runtime-control.d.ts.map +1 -1
  67. package/dist/types/step-executors/conditional-executor.d.ts.map +1 -1
  68. package/dist/types/step-executors/loop-executor.d.ts +2 -4
  69. package/dist/types/step-executors/loop-executor.d.ts.map +1 -1
  70. package/dist/types/step-executors/parallel-executor.d.ts.map +1 -1
  71. package/dist/types/step-executors/scope.d.ts +12 -0
  72. package/dist/types/step-executors/scope.d.ts.map +1 -0
  73. package/dist/types/step-executors/skip-helpers.d.ts +2 -8
  74. package/dist/types/step-executors/skip-helpers.d.ts.map +1 -1
  75. package/dist/types/step-executors/task-executor.d.ts.map +1 -1
  76. package/dist/types/utils/flow-steps.d.ts +16 -0
  77. package/dist/types/utils/flow-steps.d.ts.map +1 -0
  78. package/dist/types/utils/naming.d.ts +7 -7
  79. package/dist/types/utils/naming.d.ts.map +1 -1
  80. package/dist/types/utils/object-path.d.ts +11 -0
  81. package/dist/types/utils/object-path.d.ts.map +1 -0
  82. package/dist/types/utils/timeout.d.ts.map +1 -1
  83. package/dist/types/validation-issue.d.ts +13 -0
  84. package/dist/types/validation-issue.d.ts.map +1 -1
  85. package/dist/types/workflow-compiler.d.ts +15 -1
  86. package/dist/types/workflow-compiler.d.ts.map +1 -1
  87. package/dist/types/workflow-fingerprint.d.ts.map +1 -1
  88. package/dist/types/workflow-runner.d.ts +2 -0
  89. package/dist/types/workflow-runner.d.ts.map +1 -1
  90. package/dist/types/workflow-values.d.ts +2 -0
  91. package/dist/types/workflow-values.d.ts.map +1 -1
  92. package/dist/types/workflow.d.ts +2 -1
  93. package/dist/types/workflow.d.ts.map +1 -1
  94. package/examples/defs-bindings-agent/actions/ai-agent.ts +5 -3
  95. package/examples/defs-bindings-agent/actions/{caculate-score.ts → calculate-score.ts} +8 -8
  96. package/examples/defs-bindings-agent/actions/index.ts +2 -2
  97. package/examples/defs-bindings-agent/workflow.yml +2 -2
  98. package/examples/full/workflow.yml +20 -15
  99. package/examples/suspend-resume/workflow.yml +6 -3
  100. package/package.json +8 -5
  101. package/src/__tests__/checkpoint.test.ts +6 -1
  102. package/src/__tests__/resume-payload.test.ts +29 -0
  103. package/src/__tests__/test-helpers.ts +1 -1
  104. package/src/__tests__/validation.test.ts +330 -0
  105. package/src/__tests__/workflow-compiler.test.ts +278 -3
  106. package/src/__tests__/workflow-definition-path.test.ts +2 -0
  107. package/src/__tests__/workflow-fingerprint.test.ts +65 -0
  108. package/src/__tests__/workflow-runner.test.ts +280 -5
  109. package/src/__tests__/workflow-values.test.ts +13 -0
  110. package/src/__tests__/workflow.test.ts +4 -2
  111. package/src/action/__tests__/abstract-action-timing.test.ts +92 -0
  112. package/src/action/abstract-action.ts +67 -40
  113. package/src/bindings/base-binding.test.ts +470 -0
  114. package/src/bindings/base-binding.ts +344 -267
  115. package/src/checkpoint.ts +2 -4
  116. package/src/context.ts +2 -3
  117. package/src/dsl.types.ts +75 -154
  118. package/src/errors.ts +15 -0
  119. package/src/index.ts +2 -0
  120. package/src/resume-payload.ts +13 -3
  121. package/src/runner-runtime-control.ts +52 -29
  122. package/src/step-executors/conditional-executor.ts +3 -7
  123. package/src/step-executors/loop-executor.test.ts +55 -0
  124. package/src/step-executors/loop-executor.ts +16 -50
  125. package/src/step-executors/parallel-executor.ts +14 -37
  126. package/src/step-executors/scope.ts +30 -0
  127. package/src/step-executors/skip-helpers.test.ts +133 -0
  128. package/src/step-executors/skip-helpers.ts +43 -76
  129. package/src/step-executors/task-executor.test.ts +130 -1
  130. package/src/step-executors/task-executor.ts +109 -79
  131. package/src/utils/flow-steps.test.ts +121 -0
  132. package/src/utils/flow-steps.ts +62 -0
  133. package/src/utils/naming.test.ts +50 -0
  134. package/src/utils/naming.ts +11 -11
  135. package/src/utils/object-path.test.ts +70 -0
  136. package/src/utils/object-path.ts +67 -0
  137. package/src/utils/timeout.test.ts +152 -0
  138. package/src/utils/timeout.ts +26 -44
  139. package/src/validation-issue.test.ts +70 -0
  140. package/src/validation-issue.ts +27 -0
  141. package/src/workflow-compiler.ts +118 -180
  142. package/src/workflow-fingerprint.ts +23 -12
  143. package/src/workflow-runner.ts +28 -27
  144. package/src/workflow-values.ts +9 -7
  145. package/src/workflow.ts +58 -140
@@ -7,8 +7,12 @@ import jsonata from 'jsonata';
7
7
  import { parse as parseYaml } from 'yaml';
8
8
  import { z } from 'zod';
9
9
  import { validateAndResolveBindings } from './bindings/base-binding';
10
+ import { isRecord } from './utils/clone';
11
+ import { collectTaskReferences } from './utils/flow-steps';
10
12
  import { SNAKE_CASE_REGEX } from './utils/naming';
11
- import { mergeSettings } from './workflow-values';
13
+ import { getValueAtPath } from './utils/object-path';
14
+ import { toIssuePath, toValidationIssues, } from './validation-issue';
15
+ import { isExpressionString, mergeSettings } from './workflow-values';
12
16
  export const ExpressionStringSchema = z
13
17
  .string()
14
18
  .regex(/^=/, 'Expression strings must start with "="')
@@ -43,44 +47,52 @@ export const JsonValueSchema = z.lazy(() => z.union([
43
47
  z.array(JsonValueSchema),
44
48
  z.record(z.string(), JsonValueSchema),
45
49
  ]));
46
- const InputFieldSchema = z.lazy(() => z
47
- .strictObject({
48
- type: z.enum([
49
- 'string',
50
- 'number',
51
- 'integer',
52
- 'boolean',
53
- 'array',
54
- 'object',
55
- ]),
56
- description: z.string().optional(),
57
- enum: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),
58
- items: InputFieldSchema.optional(),
59
- properties: z.record(z.string(), InputFieldSchema).optional(),
60
- })
61
- .superRefine((value, ctx) => {
62
- if (value.type === 'array' && !value.items) {
50
+ const isJsonObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
51
+ /**
52
+ * Tell whether `inputs.schema` is written as the field map this DSL used
53
+ * before JSON Schema (`{ question: { type: string } }`). A JSON Schema has a
54
+ * string `type` at its root, which a field map never has: each of its values
55
+ * is a field, an object with its own `type`.
56
+ */
57
+ const isInputFieldMap = (schema) => {
58
+ const fields = Object.values(schema);
59
+ return (typeof schema.type !== 'string' &&
60
+ fields.length > 0 &&
61
+ fields.every((field) => isJsonObject(field) && 'type' in field));
62
+ };
63
+ const WorkflowInputSchemaSchema = z
64
+ .record(z.string(), JsonValueSchema)
65
+ .superRefine((schema, ctx) => {
66
+ if (isInputFieldMap(schema)) {
63
67
  ctx.addIssue({
64
68
  code: 'custom',
65
- message: 'Array inputs must declare "items"',
66
- path: ['items'],
69
+ message: 'Workflow inputs must be described by a JSON Schema, e.g. ' +
70
+ '{ type: object, properties: { question: { type: string } }, ' +
71
+ 'required: [question] }; a map of fields ' +
72
+ '({ question: { type: string } }) is no longer supported',
67
73
  });
74
+ return;
68
75
  }
69
- if (value.type !== 'array' && value.items) {
76
+ if (schema.type !== 'object') {
70
77
  ctx.addIssue({
71
78
  code: 'custom',
72
- message: '"items" is only valid when type is "array"',
73
- path: ['items'],
79
+ message: 'Workflow inputs must be described by a JSON Schema of type ' +
80
+ '"object"; declare the input fields under "properties"',
81
+ path: ['type'],
74
82
  });
83
+ return;
84
+ }
85
+ try {
86
+ z.fromJSONSchema(schema);
75
87
  }
76
- if (value.type !== 'object' && value.properties) {
88
+ catch (error) {
89
+ const reason = error instanceof Error ? error.message : String(error);
77
90
  ctx.addIssue({
78
91
  code: 'custom',
79
- message: '"properties" is only valid when type is "object"',
80
- path: ['properties'],
92
+ message: `Not a valid JSON Schema (${reason})`,
81
93
  });
82
94
  }
83
- }));
95
+ });
84
96
  // Retry policy: exponential backoff per attempt, capped by max_delay_ms, with optional jitter multiplier.
85
97
  const RetriesSchema = z.strictObject({
86
98
  enabled: z.boolean().optional().meta({
@@ -223,7 +235,7 @@ export const WorkflowMetadataSchema = z.strictObject({
223
235
  description: z.string().optional(),
224
236
  });
225
237
  const InputsSchema = z.strictObject({
226
- schema: z.record(z.string(), InputFieldSchema).optional(),
238
+ schema: WorkflowInputSchemaSchema.optional(),
227
239
  });
228
240
  const DefaultsSchema = z.strictObject({
229
241
  settings: SettingsSchema.optional(),
@@ -236,44 +248,6 @@ export const WorkflowDefinitionSchema = z.strictObject({
236
248
  flow: z.array(FlowStepSchema),
237
249
  outputs: z.record(z.string(), ExpressionStringSchema),
238
250
  });
239
- const collectTaskReferences = (steps, basePath = ['flow']) => {
240
- const refs = [];
241
- steps.forEach((step, index) => {
242
- const stepPath = [...basePath, index];
243
- if ('do' in step) {
244
- refs.push({ taskId: step.do, path: [...stepPath, 'do'] });
245
- return;
246
- }
247
- if ('parallel' in step) {
248
- refs.push(...collectTaskReferences(step.parallel.steps, [
249
- ...stepPath,
250
- 'parallel',
251
- 'steps',
252
- ]));
253
- return;
254
- }
255
- if ('conditional' in step) {
256
- step.conditional.when.forEach((branch, branchIndex) => {
257
- refs.push(...collectTaskReferences(branch.steps, [
258
- ...stepPath,
259
- 'conditional',
260
- 'when',
261
- branchIndex,
262
- 'steps',
263
- ]));
264
- });
265
- return;
266
- }
267
- if ('loop' in step) {
268
- refs.push(...collectTaskReferences(step.loop.steps, [
269
- ...stepPath,
270
- 'loop',
271
- 'steps',
272
- ]));
273
- }
274
- });
275
- return refs;
276
- };
277
251
  export const isTaskDefinition = (definition) => definition.kind === TASK_KIND;
278
252
  export const extractTaskDefinitions = (defs) => Object.entries(defs).reduce((tasks, [defName, def]) => {
279
253
  if (isTaskDefinition(def)) {
@@ -282,20 +256,8 @@ export const extractTaskDefinitions = (defs) => Object.entries(defs).reduce((tas
282
256
  return tasks;
283
257
  }, {});
284
258
  const EXECUTION_SETTING_KEYS = new Set(Object.keys(BaseSettingsSchema.shape));
285
- const isExpressionString = (value) => typeof value === 'string' && value.startsWith('=');
286
- const toIssuePath = (path) => path.filter((segment) => typeof segment === 'string' || typeof segment === 'number');
287
- const getValueAtPath = (value, path) => {
288
- let current = value;
289
- for (const segment of path) {
290
- if (current === null || typeof current !== 'object') {
291
- return undefined;
292
- }
293
- current = current[segment];
294
- }
295
- return current;
296
- };
297
259
  const extractActionSettings = (settings) => {
298
- if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
260
+ if (!isRecord(settings)) {
299
261
  return {};
300
262
  }
301
263
  return Object.fromEntries(Object.entries(settings).filter(([key]) => !EXECUTION_SETTING_KEYS.has(key)));
@@ -361,14 +323,6 @@ const validateTaskActionSchemas = (definition, actions) => {
361
323
  }
362
324
  return issues;
363
325
  };
364
- const toSchemaIssues = (zodIssues) => zodIssues.map((issue) => {
365
- const path = issue.path.join('.') || '<root>';
366
- return {
367
- code: 'schema',
368
- message: `${path}: ${issue.message}`,
369
- path: issue.path.filter((segment) => typeof segment === 'string' || typeof segment === 'number'),
370
- };
371
- });
372
326
  const invalidWorkflow = (issues) => ({
373
327
  success: false,
374
328
  issues,
@@ -389,7 +343,7 @@ export function validateWorkflow(input, options) {
389
343
  }
390
344
  const parsed = WorkflowDefinitionSchema.safeParse(candidate);
391
345
  if (!parsed.success) {
392
- return invalidWorkflow(toSchemaIssues(parsed.error.issues));
346
+ return invalidWorkflow(toValidationIssues('schema', parsed.error.issues));
393
347
  }
394
348
  const issues = [];
395
349
  const taskDefinitions = extractTaskDefinitions(parsed.data.defs);
@@ -9,6 +9,17 @@ export class WorkflowCancellationError extends Error {
9
9
  this.name = 'WorkflowCancellationError';
10
10
  }
11
11
  }
12
+ /**
13
+ * The input payload passed to `start()` does not match the workflow's
14
+ * `inputs.schema`. Nothing ran: the runner is left as it was before the call.
15
+ */
16
+ export class WorkflowInputRejectedError extends Error {
17
+ constructor(issues) {
18
+ super(`Workflow input was rejected: ${issues.join('; ')}`);
19
+ this.name = 'WorkflowInputRejectedError';
20
+ this.issues = issues;
21
+ }
22
+ }
12
23
  /** Base class for every reason a suspended run cannot be resumed. */
13
24
  export class WorkflowResumeError extends Error {
14
25
  }
package/dist/esm/index.js CHANGED
@@ -8,11 +8,11 @@ export { defineAction } from './action/action';
8
8
  export { BaseWorkflowContext, EWorkflowRunStatus, WORKFLOW_RUN_STATUSES, } from './context';
9
9
  export * from './dsl.types';
10
10
  export { issueMessages, } from './validation-issue';
11
- export { compileWorkflow, Workflow, WorkflowEventEmitter, WorkflowRunner, } from './workflow';
11
+ export { buildWorkflowInputParser, compileWorkflow, Workflow, WorkflowEventEmitter, WorkflowRunner, } from './workflow';
12
12
  export { StepType } from './workflow-event-emitter';
13
13
  export { CHECKPOINT_VERSION, collectWaits, validateCheckpoint, workflowCheckpointSchema, } from './checkpoint';
14
14
  export { fingerprintWorkflow } from './workflow-fingerprint';
15
- export { NonDeterministicWorkflowError, WorkflowCancellationError, WorkflowCheckpointInvalidError, WorkflowDefinitionDriftError, WorkflowResumeError, WorkflowResumeRejectedError, WorkflowWaitAmbiguousError, WorkflowWaitNotFoundError, } from './errors';
15
+ export { NonDeterministicWorkflowError, WorkflowCancellationError, WorkflowCheckpointInvalidError, WorkflowDefinitionDriftError, WorkflowInputRejectedError, WorkflowResumeError, WorkflowResumeRejectedError, WorkflowWaitAmbiguousError, WorkflowWaitNotFoundError, } from './errors';
16
16
  export { compileValue, evaluateMapping, evaluateValue, mergeSettings, } from './workflow-values';
17
17
  export { assertSnakeCaseName, isSnakeCaseName, toSnakeCase, } from './utils/naming';
18
18
  export { sleep, withTimeout } from './utils/timeout';
@@ -209,6 +209,15 @@ export function checkResumePayload(wait, resumeData) {
209
209
  error: rejectResumePayload(`wait "${wait.waitId}"`, result.error.issues),
210
210
  };
211
211
  }
212
+ /**
213
+ * Describe schema issues as `<path>: <message>` lines.
214
+ *
215
+ * @param issues The schema issues.
216
+ * @returns One line per issue.
217
+ */
218
+ export function describeSchemaIssues(issues) {
219
+ return issues.map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`);
220
+ }
212
221
  /**
213
222
  * Build the error refusing a payload that failed a schema.
214
223
  *
@@ -217,7 +226,7 @@ export function checkResumePayload(wait, resumeData) {
217
226
  * @returns The rejection error.
218
227
  */
219
228
  export function rejectResumePayload(subject, issues) {
220
- const messages = issues.map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`);
229
+ const messages = describeSchemaIssues(issues);
221
230
  return new WorkflowResumeRejectedError(`Resume payload for ${subject} was rejected: ${messages.join('; ')}`, { issues: messages });
222
231
  }
223
232
  const relaxNode = (def, jsonSchema) => {
@@ -84,13 +84,7 @@ export class RunnerRuntimeControl {
84
84
  assertJsonPayloadSchema(active, options.accepts);
85
85
  }
86
86
  if (options?.key) {
87
- // A reused key would resolve from the first call's answer on resume,
88
- // so the second call could never suspend.
89
- if (active.usedKeys.has(options.key)) {
90
- throw new Error(`workflow.suspend() key "${options.key}" is used more than once ` +
91
- `in step "${active.step.id}"; keys must be unique within an action body.`);
92
- }
93
- active.usedKeys.add(options.key);
87
+ claimSuspendKey(active, options.key);
94
88
  }
95
89
  active.cursor += 1;
96
90
  const suspendKey = buildSuspendKey(active.cursor, options?.key);
@@ -98,26 +92,7 @@ export class RunnerRuntimeControl {
98
92
  if (active.awaitResults.has(suspendKey)) {
99
93
  return resolveRecordedResult(active, suspendKey, options?.accepts);
100
94
  }
101
- const request = {
102
- suspendKey,
103
- reason: options?.reason,
104
- data: options?.data,
105
- awaitResults: Object.fromEntries(active.awaitResults),
106
- };
107
- if (options?.accepts) {
108
- request.accepts = describeResumePayload(options.accepts);
109
- if (isPayloadOptional(options.accepts)) {
110
- request.payloadOptional = true;
111
- }
112
- }
113
- const waiter = active.waiter;
114
- if (waiter) {
115
- active.waiter = undefined;
116
- waiter(request);
117
- }
118
- else {
119
- active.pending.push(request);
120
- }
95
+ deliverSuspension(active, buildSuspensionRequest(active, suspendKey, options));
121
96
  // Never settles: the step executor aborts this body, and resuming re-runs
122
97
  // it so that this call resolves from `awaitResults` instead.
123
98
  return new Promise(() => undefined);
@@ -174,6 +149,43 @@ export class RunnerRuntimeControl {
174
149
  `"${suspendKey}" before expected "${expected.suspendKey}".`);
175
150
  }
176
151
  }
152
+ /**
153
+ * Reserve a user key for the running attempt. A reused key would resolve from
154
+ * the first call's answer on resume, so the second call could never suspend.
155
+ */
156
+ const claimSuspendKey = (active, key) => {
157
+ if (active.usedKeys.has(key)) {
158
+ throw new Error(`workflow.suspend() key "${key}" is used more than once ` +
159
+ `in step "${active.step.id}"; keys must be unique within an action body.`);
160
+ }
161
+ active.usedKeys.add(key);
162
+ };
163
+ const buildSuspensionRequest = (active, suspendKey, options) => {
164
+ const request = {
165
+ suspendKey,
166
+ reason: options?.reason,
167
+ data: options?.data,
168
+ awaitResults: Object.fromEntries(active.awaitResults),
169
+ };
170
+ if (options?.accepts) {
171
+ request.accepts = describeResumePayload(options.accepts);
172
+ if (isPayloadOptional(options.accepts)) {
173
+ request.payloadOptional = true;
174
+ }
175
+ }
176
+ return request;
177
+ };
178
+ /** Hand a request to the executor waiting for one, or queue it until it waits. */
179
+ const deliverSuspension = (active, request) => {
180
+ const waiter = active.waiter;
181
+ if (waiter) {
182
+ active.waiter = undefined;
183
+ waiter(request);
184
+ }
185
+ else {
186
+ active.pending.push(request);
187
+ }
188
+ };
177
189
  /**
178
190
  * Refuse an `accepts` schema that no JSON payload can match: the wait it
179
191
  * opens could never be resumed, since payloads are read back as JSON.
@@ -4,6 +4,7 @@
4
4
  * Full terms: see LICENSE.md.
5
5
  */
6
6
  import { evaluateValue } from '../workflow-values';
7
+ import { buildEvaluationScope } from './scope';
7
8
  import { markStepsSkipped } from './skip-helpers';
8
9
  /**
9
10
  * Evaluate a conditional step by checking branches in order and executing the first match.
@@ -38,15 +39,9 @@ export async function executeConditional(env, step, state, path, frame) {
38
39
  return undefined;
39
40
  }
40
41
  const chooseBranch = async (env, step, state) => {
42
+ const scope = buildEvaluationScope(env, state);
41
43
  for (let index = 0; index < step.branches.length; index += 1) {
42
44
  const branch = step.branches[index];
43
- const scope = {
44
- input: state.input,
45
- context: env.context.state,
46
- output: state.output,
47
- iteration: state.iteration,
48
- accumulator: state.accumulator,
49
- };
50
45
  const conditionResult = branch.condition !== undefined
51
46
  ? await evaluateValue(branch.condition, scope)
52
47
  : true;
@@ -4,6 +4,7 @@
4
4
  * Full terms: see LICENSE.md.
5
5
  */
6
6
  import { evaluateValue } from '../workflow-values';
7
+ import { buildEvaluationScope } from './scope';
7
8
  /**
8
9
  * Execute a loop step by iterating over input items and executing child steps.
9
10
  *
@@ -49,7 +50,10 @@ async function executeForEachLoop(env, step, state, path, frame) {
49
50
  child,
50
51
  };
51
52
  }
52
- const postScope = buildScope(env, iterationState, { item, index }, accumulator);
53
+ const postScope = buildEvaluationScope(env, iterationState, {
54
+ iteration: { item, index },
55
+ accumulator,
56
+ });
53
57
  accumulator = await updateAccumulator(step, postScope, accumulator);
54
58
  const shouldStop = await shouldStopLoop(step, postScope);
55
59
  if (shouldStop) {
@@ -68,7 +72,10 @@ async function executeWhileLoop(env, step, state, path, frame) {
68
72
  const resumedChild = frame && index === frame.index ? frame.child : undefined;
69
73
  // The guard of a resumed iteration already passed before it suspended.
70
74
  if (!resumedChild) {
71
- const conditionScope = buildScope(env, state, { item: undefined, index }, accumulator);
75
+ const conditionScope = buildEvaluationScope(env, state, {
76
+ iteration: { item: undefined, index },
77
+ accumulator,
78
+ });
72
79
  const shouldContinue = await evaluateValue(step.while, conditionScope);
73
80
  if (!Boolean(shouldContinue)) {
74
81
  break;
@@ -84,7 +91,10 @@ async function executeWhileLoop(env, step, state, path, frame) {
84
91
  if (child) {
85
92
  return { kind: 'loop', stepId: step.id, index, accumulator, child };
86
93
  }
87
- const postScope = buildScope(env, iterationState, { item: undefined, index }, accumulator);
94
+ const postScope = buildEvaluationScope(env, iterationState, {
95
+ iteration: { item: undefined, index },
96
+ accumulator,
97
+ });
88
98
  accumulator = await updateAccumulator(step, postScope, accumulator);
89
99
  state.output = iterationState.output;
90
100
  }
@@ -92,13 +102,7 @@ async function executeWhileLoop(env, step, state, path, frame) {
92
102
  return undefined;
93
103
  }
94
104
  async function resolveItems(env, step, state) {
95
- const items = await evaluateValue(step.forEach.in, {
96
- input: state.input,
97
- context: env.context.state,
98
- output: state.output,
99
- iteration: state.iteration,
100
- accumulator: state.accumulator,
101
- });
105
+ const items = await evaluateValue(step.forEach.in, buildEvaluationScope(env, state));
102
106
  return Array.isArray(items) ? items : [];
103
107
  }
104
108
  function finalizeAccumulatorState(step, state, accumulator) {
@@ -140,21 +144,3 @@ export async function shouldStopLoop(step, scope) {
140
144
  const result = await evaluateValue(step.until, scope);
141
145
  return Boolean(result);
142
146
  }
143
- /**
144
- * Build the evaluation scope for loop iteration and accumulator updates.
145
- *
146
- * @param env Executor environment with workflow context.
147
- * @param state Execution state for the current iteration.
148
- * @param iteration The current iteration item and index.
149
- * @param accumulator Accumulator value to expose to expressions.
150
- * @returns An evaluation scope object.
151
- */
152
- function buildScope(env, state, iteration, accumulator) {
153
- return {
154
- input: state.input,
155
- context: env.context.state,
156
- output: state.output,
157
- iteration,
158
- accumulator,
159
- };
160
- }
@@ -52,10 +52,7 @@ export async function executeParallel(env, step, state, path, frame) {
52
52
  baseContextState,
53
53
  recorded,
54
54
  }));
55
- if (step.strategy === 'wait_any') {
56
- return executeWaitAny(env, step, branches, outcomes, state);
57
- }
58
- return executeWaitAll(env, step, branches, outcomes, state);
55
+ return settleBlock(env, step, branches, outcomes, state);
59
56
  }
60
57
  /**
61
58
  * Settle a recorded branch that has nothing to run in this pass: a fulfilled
@@ -78,7 +75,13 @@ function keepRecordedBranch(env, index, recorded) {
78
75
  frame: recorded.child,
79
76
  };
80
77
  }
81
- async function executeWaitAll(env, step, branches, outcomes, state) {
78
+ /**
79
+ * Collect branch results as they settle. A failed or cancelled branch fails
80
+ * the block; under `wait_any` the first fulfilled branch wins it. Otherwise
81
+ * the block suspends once every branch settled with at least one suspended,
82
+ * and completes when all of them fulfilled.
83
+ */
84
+ async function settleBlock(env, step, branches, outcomes, state) {
82
85
  const pending = new Set(branches);
83
86
  while (pending.size > 0) {
84
87
  const { branch, result } = await raceNext(pending);
@@ -88,32 +91,18 @@ async function executeWaitAll(env, step, branches, outcomes, state) {
88
91
  await abandonBranches(env, branches, pending, outcomes, result.error);
89
92
  throw result.error;
90
93
  }
91
- }
92
- if (hasSuspendedBranch(outcomes)) {
93
- return buildParallelFrame(step, outcomes);
94
- }
95
- mergeBranchOutputs(state, outcomes);
96
- }
97
- async function executeWaitAny(env, step, branches, outcomes, state) {
98
- const pending = new Set(branches);
99
- while (pending.size > 0) {
100
- const { branch, result } = await raceNext(pending);
101
- pending.delete(branch);
102
- outcomes.set(result.index, result);
103
- if (result.status === 'suspended') {
104
- continue;
105
- }
106
- if (result.status === 'fulfilled') {
94
+ if (result.status === 'fulfilled' && step.strategy === 'wait_any') {
107
95
  // Parked losers will never be resumed; drop their waits with the race.
108
96
  await abandonBranches(env, branches, pending, outcomes, new WorkflowCancellationError('Parallel wait_any winner selected.'), 'Parallel wait_any branch lost the race.');
109
97
  mergeBranchOutputs(state, new Map([[result.index, result]]));
110
98
  return undefined;
111
99
  }
112
- await abandonBranches(env, branches, pending, outcomes, result.error);
113
- throw result.error;
114
100
  }
115
- // Every branch settled without a winner, so all of them are suspended.
116
- return buildParallelFrame(step, outcomes);
101
+ // Without a winner, every branch of a wait_any block is suspended.
102
+ if (hasSuspendedBranch(outcomes)) {
103
+ return buildParallelFrame(step, outcomes);
104
+ }
105
+ mergeBranchOutputs(state, outcomes);
117
106
  }
118
107
  /**
119
108
  * Give up on the block: cancel the branches still running, let every branch
@@ -0,0 +1,21 @@
1
+ /*
2
+ * Hexabot — Fair Core License (FCL-1.0-ALv2)
3
+ * Copyright (c) 2026 Hexastack.
4
+ * Full terms: see LICENSE.md.
5
+ */
6
+ /**
7
+ * Expose the live state of a step to its expressions.
8
+ *
9
+ * @param env Executor environment, for the context state.
10
+ * @param state Execution state of the step.
11
+ * @param overrides The iteration and accumulator a loop evaluates with.
12
+ * @returns The scope expressions are evaluated against.
13
+ */
14
+ export const buildEvaluationScope = (env, state, overrides = {}) => ({
15
+ input: state.input,
16
+ context: env.context.state,
17
+ output: state.output,
18
+ iteration: state.iteration,
19
+ accumulator: state.accumulator,
20
+ ...overrides,
21
+ });
@@ -3,46 +3,38 @@
3
3
  * Copyright (c) 2025 Hexastack.
4
4
  * Full terms: see LICENSE.md.
5
5
  */
6
- import { StepType, } from '../workflow-event-emitter';
7
- const markStepSkipped = (env, step, iterationStack, reason) => {
8
- const stepInfo = env.buildInstanceStepInfo(step, iterationStack);
9
- env.markSnapshot(stepInfo, 'skipped', reason);
10
- env.emit('hook:step:skipped', { runId: env.runId, step: stepInfo, reason });
11
- switch (step.type) {
12
- case StepType.Parallel:
13
- step.steps.forEach((child) => markStepSkipped(env, child, iterationStack, reason));
14
- break;
15
- case StepType.Conditional:
16
- step.branches.forEach((branch) => branch.steps.forEach((child) => markStepSkipped(env, child, iterationStack, reason)));
17
- break;
18
- case StepType.Loop:
19
- case StepType.Task:
20
- break;
6
+ import { StepType } from '../workflow-event-emitter';
7
+ /**
8
+ * Visit steps depth first, entering parallel and conditional children. Loop
9
+ * bodies are not entered: their step instances depend on iterations that
10
+ * never ran.
11
+ */
12
+ const forEachStepInTree = (steps, visit) => {
13
+ for (const step of steps) {
14
+ visit(step);
15
+ if (step.type === StepType.Parallel) {
16
+ forEachStepInTree(step.steps, visit);
17
+ }
18
+ else if (step.type === StepType.Conditional) {
19
+ step.branches.forEach((branch) => forEachStepInTree(branch.steps, visit));
20
+ }
21
21
  }
22
22
  };
23
- const markStepCancelled = (env, step, iterationStack, reason) => {
24
- const stepInfo = env.buildInstanceStepInfo(step, iterationStack);
25
- env.markSnapshot(stepInfo, 'cancelled', reason);
26
- env.emit('hook:step:cancelled', {
27
- runId: env.runId,
28
- step: stepInfo,
29
- error: new Error(reason ?? 'Step execution was cancelled.'),
23
+ /** Mark every step of the tree with `status`, then announce it. */
24
+ const markStepTree = (env, steps, iterationStack, status, reason, announce) => {
25
+ forEachStepInTree(steps, (step) => {
26
+ const stepInfo = env.buildInstanceStepInfo(step, iterationStack);
27
+ env.markSnapshot(stepInfo, status, reason);
28
+ announce(stepInfo);
30
29
  });
31
- switch (step.type) {
32
- case StepType.Parallel:
33
- step.steps.forEach((child) => markStepCancelled(env, child, iterationStack, reason));
34
- break;
35
- case StepType.Conditional:
36
- step.branches.forEach((branch) => branch.steps.forEach((child) => markStepCancelled(env, child, iterationStack, reason)));
37
- break;
38
- case StepType.Loop:
39
- case StepType.Task:
40
- break;
41
- }
42
30
  };
43
31
  export const markStepsSkipped = (env, steps, iterationStack, reason) => {
44
- steps.forEach((step) => markStepSkipped(env, step, iterationStack, reason));
32
+ markStepTree(env, steps, iterationStack, 'skipped', reason, (stepInfo) => env.emit('hook:step:skipped', { runId: env.runId, step: stepInfo, reason }));
45
33
  };
46
34
  export const markStepsCancelled = (env, steps, iterationStack, reason) => {
47
- steps.forEach((step) => markStepCancelled(env, step, iterationStack, reason));
35
+ markStepTree(env, steps, iterationStack, 'cancelled', reason, (stepInfo) => env.emit('hook:step:cancelled', {
36
+ runId: env.runId,
37
+ step: stepInfo,
38
+ error: new Error(reason ?? 'Step execution was cancelled.'),
39
+ }));
48
40
  };