@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
package/src/checkpoint.ts CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  WorkflowWaitAmbiguousError,
14
14
  WorkflowWaitNotFoundError,
15
15
  } from './errors';
16
- import { checkResumePayload } from './resume-payload';
16
+ import { checkResumePayload, describeSchemaIssues } from './resume-payload';
17
17
  import { isRecord } from './utils/clone';
18
18
  import { StepType, type StepInfo } from './workflow-event-emitter';
19
19
  import { fingerprintWorkflow } from './workflow-fingerprint';
@@ -410,9 +410,7 @@ const parseCheckpoint = (checkpoint: unknown): WorkflowCheckpoint => {
410
410
 
411
411
  const result = workflowCheckpointSchema.safeParse(checkpoint);
412
412
  if (!result.success) {
413
- const issues = result.error.issues.map(
414
- (issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`,
415
- );
413
+ const issues = describeSchemaIssues(result.error.issues);
416
414
 
417
415
  throw new WorkflowCheckpointInvalidError(
418
416
  'malformed',
package/src/context.ts CHANGED
@@ -162,10 +162,9 @@ export abstract class BaseWorkflowContext<
162
162
  public abstract eventEmitter: WorkflowEventEmitterLike<E>;
163
163
 
164
164
  /**
165
- * Sets up the context and copies any initial state onto the instance.
165
+ * Sets up the context with its initial state.
166
166
  *
167
- * @param initialState - Optional properties to assign to the context instance.
168
- * @param eventEmitter - Optional workflow event emitter to expose to actions.
167
+ * @param initialState - State exposed to expressions as `$context`.
169
168
  */
170
169
  constructor(initialState: S) {
171
170
  this.state = (initialState ?? {}) as S;
package/src/dsl.types.ts CHANGED
@@ -10,9 +10,16 @@ import { z } from 'zod';
10
10
 
11
11
  import type { BindingKindSchemas } from './bindings/base-binding';
12
12
  import { validateAndResolveBindings } from './bindings/base-binding';
13
+ import { isRecord } from './utils/clone';
14
+ import { collectTaskReferences } from './utils/flow-steps';
13
15
  import { SNAKE_CASE_REGEX } from './utils/naming';
14
- import { type WorkflowValidationIssue } from './validation-issue';
15
- import { mergeSettings } from './workflow-values';
16
+ import { getValueAtPath } from './utils/object-path';
17
+ import {
18
+ toIssuePath,
19
+ toValidationIssues,
20
+ type WorkflowValidationIssue,
21
+ } from './validation-issue';
22
+ import { isExpressionString, mergeSettings } from './workflow-values';
16
23
 
17
24
  export const ExpressionStringSchema = z
18
25
  .string()
@@ -51,13 +58,11 @@ export const DEFAULT_RETRY_SETTINGS = {
51
58
  multiplier: 1,
52
59
  } as const;
53
60
 
54
- export type InputField = {
55
- type: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object';
56
- description?: string;
57
- enum?: Array<string | number | boolean>;
58
- items?: InputField;
59
- properties?: Record<string, InputField>;
60
- };
61
+ /**
62
+ * JSON Schema of the input payload of a workflow, as written under
63
+ * `inputs.schema`. Its root `type` is `object`.
64
+ */
65
+ export type WorkflowInputSchema = Record<string, JsonValue>;
61
66
 
62
67
  export type ConditionalBranch =
63
68
  | { condition: string; steps: FlowStep[] }
@@ -118,46 +123,63 @@ export const JsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>
118
123
  ]),
119
124
  );
120
125
 
121
- const InputFieldSchema: z.ZodType<InputField> = z.lazy(() =>
122
- z
123
- .strictObject({
124
- type: z.enum([
125
- 'string',
126
- 'number',
127
- 'integer',
128
- 'boolean',
129
- 'array',
130
- 'object',
131
- ]),
132
- description: z.string().optional(),
133
- enum: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),
134
- items: InputFieldSchema.optional(),
135
- properties: z.record(z.string(), InputFieldSchema).optional(),
136
- })
137
- .superRefine((value, ctx) => {
138
- if (value.type === 'array' && !value.items) {
139
- ctx.addIssue({
140
- code: 'custom',
141
- message: 'Array inputs must declare "items"',
142
- path: ['items'],
143
- });
144
- }
145
- if (value.type !== 'array' && value.items) {
146
- ctx.addIssue({
147
- code: 'custom',
148
- message: '"items" is only valid when type is "array"',
149
- path: ['items'],
150
- });
151
- }
152
- if (value.type !== 'object' && value.properties) {
153
- ctx.addIssue({
154
- code: 'custom',
155
- message: '"properties" is only valid when type is "object"',
156
- path: ['properties'],
157
- });
158
- }
159
- }),
160
- );
126
+ const isJsonObject = (
127
+ value: JsonValue,
128
+ ): value is { [key: string]: JsonValue } =>
129
+ typeof value === 'object' && value !== null && !Array.isArray(value);
130
+ /**
131
+ * Tell whether `inputs.schema` is written as the field map this DSL used
132
+ * before JSON Schema (`{ question: { type: string } }`). A JSON Schema has a
133
+ * string `type` at its root, which a field map never has: each of its values
134
+ * is a field, an object with its own `type`.
135
+ */
136
+ const isInputFieldMap = (schema: WorkflowInputSchema): boolean => {
137
+ const fields = Object.values(schema);
138
+
139
+ return (
140
+ typeof schema.type !== 'string' &&
141
+ fields.length > 0 &&
142
+ fields.every((field) => isJsonObject(field) && 'type' in field)
143
+ );
144
+ };
145
+ const WorkflowInputSchemaSchema: z.ZodType<WorkflowInputSchema> = z
146
+ .record(z.string(), JsonValueSchema)
147
+ .superRefine((schema, ctx) => {
148
+ if (isInputFieldMap(schema)) {
149
+ ctx.addIssue({
150
+ code: 'custom',
151
+ message:
152
+ 'Workflow inputs must be described by a JSON Schema, e.g. ' +
153
+ '{ type: object, properties: { question: { type: string } }, ' +
154
+ 'required: [question] }; a map of fields ' +
155
+ '({ question: { type: string } }) is no longer supported',
156
+ });
157
+
158
+ return;
159
+ }
160
+
161
+ if (schema.type !== 'object') {
162
+ ctx.addIssue({
163
+ code: 'custom',
164
+ message:
165
+ 'Workflow inputs must be described by a JSON Schema of type ' +
166
+ '"object"; declare the input fields under "properties"',
167
+ path: ['type'],
168
+ });
169
+
170
+ return;
171
+ }
172
+
173
+ try {
174
+ z.fromJSONSchema(schema);
175
+ } catch (error) {
176
+ const reason = error instanceof Error ? error.message : String(error);
177
+ ctx.addIssue({
178
+ code: 'custom',
179
+ message: `Not a valid JSON Schema (${reason})`,
180
+ });
181
+ }
182
+ });
161
183
  // Retry policy: exponential backoff per attempt, capped by max_delay_ms, with optional jitter multiplier.
162
184
  const RetriesSchema = z.strictObject({
163
185
  enabled: z.boolean().optional().meta({
@@ -260,10 +282,7 @@ const ConditionalElseSchema: z.ZodType<ConditionalBranch> = z.lazy(() =>
260
282
  steps: z.array(FlowStepSchema),
261
283
  }),
262
284
  );
263
- const ConditionalSchema: z.ZodType<{
264
- description?: string;
265
- when: ConditionalBranch[];
266
- }> = z.strictObject({
285
+ const ConditionalSchema: z.ZodType<ConditionalBlock> = z.strictObject({
267
286
  description: z.string().optional(),
268
287
  when: z.array(z.union([ConditionalWhenSchema, ConditionalElseSchema])).min(1),
269
288
  });
@@ -326,7 +345,7 @@ export const WorkflowMetadataSchema = z.strictObject({
326
345
  });
327
346
 
328
347
  const InputsSchema = z.strictObject({
329
- schema: z.record(z.string(), InputFieldSchema).optional(),
348
+ schema: WorkflowInputSchemaSchema.optional(),
330
349
  });
331
350
  const DefaultsSchema = z.strictObject({
332
351
  settings: SettingsSchema.optional(),
@@ -375,68 +394,6 @@ export type WorkflowValidationResult =
375
394
  | { success: true; data: WorkflowDefinition }
376
395
  | { success: false; issues: WorkflowValidationIssue[] };
377
396
 
378
- type TaskReference = {
379
- taskId: string;
380
- path: Array<string | number>;
381
- };
382
-
383
- const collectTaskReferences = (
384
- steps: FlowStep[],
385
- basePath: Array<string | number> = ['flow'],
386
- ): TaskReference[] => {
387
- const refs: TaskReference[] = [];
388
-
389
- steps.forEach((step, index) => {
390
- const stepPath = [...basePath, index];
391
-
392
- if ('do' in step) {
393
- refs.push({ taskId: step.do, path: [...stepPath, 'do'] });
394
-
395
- return;
396
- }
397
-
398
- if ('parallel' in step) {
399
- refs.push(
400
- ...collectTaskReferences(step.parallel.steps, [
401
- ...stepPath,
402
- 'parallel',
403
- 'steps',
404
- ]),
405
- );
406
-
407
- return;
408
- }
409
-
410
- if ('conditional' in step) {
411
- step.conditional.when.forEach((branch, branchIndex) => {
412
- refs.push(
413
- ...collectTaskReferences(branch.steps, [
414
- ...stepPath,
415
- 'conditional',
416
- 'when',
417
- branchIndex,
418
- 'steps',
419
- ]),
420
- );
421
- });
422
-
423
- return;
424
- }
425
-
426
- if ('loop' in step) {
427
- refs.push(
428
- ...collectTaskReferences(step.loop.steps, [
429
- ...stepPath,
430
- 'loop',
431
- 'steps',
432
- ]),
433
- );
434
- }
435
- });
436
-
437
- return refs;
438
- };
439
-
440
397
  export const isTaskDefinition = (
441
398
  definition: DefDefinition,
442
399
  ): definition is TaskDefinition => definition.kind === TASK_KIND;
@@ -451,31 +408,8 @@ export const extractTaskDefinitions = (defs: DefDefinitions): TaskDefinitions =>
451
408
  }, {});
452
409
 
453
410
  const EXECUTION_SETTING_KEYS = new Set(Object.keys(BaseSettingsSchema.shape));
454
- const isExpressionString = (value: unknown): boolean =>
455
- typeof value === 'string' && value.startsWith('=');
456
- const toIssuePath = (path: readonly PropertyKey[]): Array<string | number> =>
457
- path.filter(
458
- (segment): segment is string | number =>
459
- typeof segment === 'string' || typeof segment === 'number',
460
- );
461
- const getValueAtPath = (
462
- value: unknown,
463
- path: Array<string | number>,
464
- ): unknown => {
465
- let current = value;
466
-
467
- for (const segment of path) {
468
- if (current === null || typeof current !== 'object') {
469
- return undefined;
470
- }
471
-
472
- current = (current as Record<string | number, unknown>)[segment];
473
- }
474
-
475
- return current;
476
- };
477
411
  const extractActionSettings = (settings: unknown): Record<string, unknown> => {
478
- if (!settings || typeof settings !== 'object' || Array.isArray(settings)) {
412
+ if (!isRecord(settings)) {
479
413
  return {};
480
414
  }
481
415
 
@@ -582,19 +516,6 @@ const validateTaskActionSchemas = (
582
516
 
583
517
  return issues;
584
518
  };
585
- const toSchemaIssues = (zodIssues: z.ZodIssue[]): WorkflowValidationIssue[] =>
586
- zodIssues.map((issue) => {
587
- const path = issue.path.join('.') || '<root>';
588
-
589
- return {
590
- code: 'schema',
591
- message: `${path}: ${issue.message}`,
592
- path: issue.path.filter(
593
- (segment): segment is string | number =>
594
- typeof segment === 'string' || typeof segment === 'number',
595
- ),
596
- };
597
- });
598
519
  const invalidWorkflow = (
599
520
  issues: WorkflowValidationIssue[],
600
521
  ): WorkflowValidationResult => ({
@@ -625,7 +546,7 @@ export function validateWorkflow(
625
546
  const parsed = WorkflowDefinitionSchema.safeParse(candidate);
626
547
 
627
548
  if (!parsed.success) {
628
- return invalidWorkflow(toSchemaIssues(parsed.error.issues));
549
+ return invalidWorkflow(toValidationIssues('schema', parsed.error.issues));
629
550
  }
630
551
 
631
552
  const issues: WorkflowValidationIssue[] = [];
package/src/errors.ts CHANGED
@@ -11,6 +11,21 @@ export class WorkflowCancellationError extends Error {
11
11
  }
12
12
  }
13
13
 
14
+ /**
15
+ * The input payload passed to `start()` does not match the workflow's
16
+ * `inputs.schema`. Nothing ran: the runner is left as it was before the call.
17
+ */
18
+ export class WorkflowInputRejectedError extends Error {
19
+ /** One `<path>: <message>` line per schema issue. */
20
+ public readonly issues: string[];
21
+
22
+ constructor(issues: string[]) {
23
+ super(`Workflow input was rejected: ${issues.join('; ')}`);
24
+ this.name = 'WorkflowInputRejectedError';
25
+ this.issues = issues;
26
+ }
27
+ }
28
+
14
29
  /** Base class for every reason a suspended run cannot be resumed. */
15
30
  export abstract class WorkflowResumeError extends Error {}
16
31
 
package/src/index.ts CHANGED
@@ -52,6 +52,7 @@ export type {
52
52
  } from './bindings/base-binding';
53
53
 
54
54
  export {
55
+ buildWorkflowInputParser,
55
56
  compileWorkflow,
56
57
  Workflow,
57
58
  WorkflowEventEmitter,
@@ -116,6 +117,7 @@ export {
116
117
  WorkflowCancellationError,
117
118
  WorkflowCheckpointInvalidError,
118
119
  WorkflowDefinitionDriftError,
120
+ WorkflowInputRejectedError,
119
121
  WorkflowResumeError,
120
122
  WorkflowResumeRejectedError,
121
123
  WorkflowWaitAmbiguousError,
@@ -270,6 +270,18 @@ export function checkResumePayload(
270
270
  };
271
271
  }
272
272
 
273
+ /**
274
+ * Describe schema issues as `<path>: <message>` lines.
275
+ *
276
+ * @param issues The schema issues.
277
+ * @returns One line per issue.
278
+ */
279
+ export function describeSchemaIssues(issues: z.core.$ZodIssue[]): string[] {
280
+ return issues.map(
281
+ (issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`,
282
+ );
283
+ }
284
+
273
285
  /**
274
286
  * Build the error refusing a payload that failed a schema.
275
287
  *
@@ -281,9 +293,7 @@ export function rejectResumePayload(
281
293
  subject: string,
282
294
  issues: z.core.$ZodIssue[],
283
295
  ): WorkflowResumeRejectedError {
284
- const messages = issues.map(
285
- (issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`,
286
- );
296
+ const messages = describeSchemaIssues(issues);
287
297
 
288
298
  return new WorkflowResumeRejectedError(
289
299
  `Resume payload for ${subject} was rejected: ${messages.join('; ')}`,
@@ -142,16 +142,7 @@ export class RunnerRuntimeControl implements WorkflowRuntimeControl {
142
142
  }
143
143
 
144
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.`,
151
- );
152
- }
153
-
154
- active.usedKeys.add(options.key);
145
+ claimSuspendKey(active, options.key);
155
146
  }
156
147
 
157
148
  active.cursor += 1;
@@ -163,25 +154,10 @@ export class RunnerRuntimeControl implements WorkflowRuntimeControl {
163
154
  return resolveRecordedResult(active, suspendKey, options?.accepts);
164
155
  }
165
156
 
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
- }
177
- }
178
- const waiter = active.waiter;
179
- if (waiter) {
180
- active.waiter = undefined;
181
- waiter(request);
182
- } else {
183
- active.pending.push(request);
184
- }
157
+ deliverSuspension(
158
+ active,
159
+ buildSuspensionRequest(active, suspendKey, options),
160
+ );
185
161
 
186
162
  // Never settles: the step executor aborts this body, and resuming re-runs
187
163
  // it so that this call resolves from `awaitResults` instead.
@@ -260,6 +236,53 @@ export class RunnerRuntimeControl implements WorkflowRuntimeControl {
260
236
  }
261
237
  }
262
238
 
239
+ /**
240
+ * Reserve a user key for the running attempt. A reused key would resolve from
241
+ * the first call's answer on resume, so the second call could never suspend.
242
+ */
243
+ const claimSuspendKey = (active: ActiveStep, key: string): void => {
244
+ if (active.usedKeys.has(key)) {
245
+ throw new Error(
246
+ `workflow.suspend() key "${key}" is used more than once ` +
247
+ `in step "${active.step.id}"; keys must be unique within an action body.`,
248
+ );
249
+ }
250
+
251
+ active.usedKeys.add(key);
252
+ };
253
+ const buildSuspensionRequest = <T>(
254
+ active: ActiveStep,
255
+ suspendKey: string,
256
+ options?: SuspensionOptions<T>,
257
+ ): RuntimeSuspensionRequest => {
258
+ const request: RuntimeSuspensionRequest = {
259
+ suspendKey,
260
+ reason: options?.reason,
261
+ data: options?.data,
262
+ awaitResults: Object.fromEntries(active.awaitResults),
263
+ };
264
+ if (options?.accepts) {
265
+ request.accepts = describeResumePayload(options.accepts);
266
+ if (isPayloadOptional(options.accepts)) {
267
+ request.payloadOptional = true;
268
+ }
269
+ }
270
+
271
+ return request;
272
+ };
273
+ /** Hand a request to the executor waiting for one, or queue it until it waits. */
274
+ const deliverSuspension = (
275
+ active: ActiveStep,
276
+ request: RuntimeSuspensionRequest,
277
+ ): void => {
278
+ const waiter = active.waiter;
279
+ if (waiter) {
280
+ active.waiter = undefined;
281
+ waiter(request);
282
+ } else {
283
+ active.pending.push(request);
284
+ }
285
+ };
263
286
  /**
264
287
  * Refuse an `accepts` schema that no JSON payload can match: the wait it
265
288
  * opens could never be resumed, since payloads are read back as JSON.
@@ -8,6 +8,7 @@ import type { ConditionalFrame } from '../checkpoint';
8
8
  import type { ConditionalStep, ExecutionState } from '../workflow-types';
9
9
  import { evaluateValue } from '../workflow-values';
10
10
 
11
+ import { buildEvaluationScope } from './scope';
11
12
  import { markStepsSkipped } from './skip-helpers';
12
13
  import type { StepExecutorEnv } from './types';
13
14
 
@@ -67,15 +68,10 @@ const chooseBranch = async (
67
68
  step: ConditionalStep,
68
69
  state: ExecutionState,
69
70
  ): Promise<number | undefined> => {
71
+ const scope = buildEvaluationScope(env, state);
72
+
70
73
  for (let index = 0; index < step.branches.length; index += 1) {
71
74
  const branch = step.branches[index];
72
- const scope = {
73
- input: state.input,
74
- context: env.context.state,
75
- output: state.output,
76
- iteration: state.iteration,
77
- accumulator: state.accumulator,
78
- };
79
75
  const conditionResult =
80
76
  branch.condition !== undefined
81
77
  ? await evaluateValue(branch.condition, scope)
@@ -135,6 +135,34 @@ describe('executeLoop', () => {
135
135
  expect(state.output).toMatchObject({ item_0: 2, item_1: 4, item_2: 6 });
136
136
  });
137
137
 
138
+ it('stops before the last item once until holds, seeing the accumulator before the merge', async () => {
139
+ const executeFlow = jest.fn(recordItem);
140
+ const state = createState();
141
+ const step: LoopStep = {
142
+ id: 'loop',
143
+ type: StepType.Loop,
144
+ loopType: 'for_each',
145
+ label: 'loop',
146
+ name: 'collector',
147
+ forEach: { item: 'entry', in: { kind: 'literal', value: [1, 2, 3, 4] } },
148
+ // At index 2 the accumulator is still 1 + 2, before this item is merged.
149
+ until: compileValue('=$accumulator >= 3'),
150
+ accumulate: {
151
+ as: 'sum',
152
+ initial: 0,
153
+ merge: compileValue('=$accumulator + $iteration.item'),
154
+ },
155
+ steps: [createTaskStep('child')],
156
+ };
157
+
158
+ await expect(
159
+ executeLoop(createEnv(executeFlow), step, state, []),
160
+ ).resolves.toBeUndefined();
161
+ expect(executeFlow).toHaveBeenCalledTimes(3);
162
+ expect(state.output.collector).toEqual({ sum: 6 });
163
+ expect(state.output).not.toHaveProperty('item_3');
164
+ });
165
+
138
166
  it('records the suspended iteration and resumes it with the recorded items and accumulator', async () => {
139
167
  const step: LoopStep = {
140
168
  id: 'loop',
@@ -300,6 +328,33 @@ describe('loop helpers', () => {
300
328
  await expect(shouldStopLoop(step, scope)).resolves.toBe(false);
301
329
  });
302
330
 
331
+ it('treats a for_each frame without recorded items as an empty item list', async () => {
332
+ const step: LoopStep = {
333
+ id: 'loop',
334
+ type: StepType.Loop,
335
+ loopType: 'for_each',
336
+ label: 'loop',
337
+ name: 'collector',
338
+ forEach: { item: 'entry', in: { kind: 'literal', value: [1, 2] } },
339
+ accumulate: { as: 'sum', initial: 0, merge: compileValue('=0') },
340
+ steps: [createTaskStep('child')],
341
+ };
342
+ const flow = jest.fn(recordItem);
343
+ const state = createState();
344
+
345
+ await expect(
346
+ executeLoop(createEnv(flow), step, state, [], {
347
+ kind: 'loop',
348
+ stepId: 'loop',
349
+ index: 0,
350
+ accumulator: 7,
351
+ child: childFrame,
352
+ }),
353
+ ).resolves.toBeUndefined();
354
+ expect(flow).not.toHaveBeenCalled();
355
+ expect(state.output.collector).toEqual({ sum: 7 });
356
+ });
357
+
303
358
  it('does not stop while loops through until semantics', async () => {
304
359
  const step: LoopStep = {
305
360
  id: 'loop',