@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
@@ -9,6 +9,39 @@ import { isNonDeterministicWorkflowError, isWorkflowResumeRejectedError, throwIf
9
9
  import { assertSnakeCaseName } from '../utils/naming';
10
10
  import { sleep, withTimeout } from '../utils/timeout';
11
11
  const BASE_SETTINGS_KEYS = Object.keys(BaseSettingsSchema.shape);
12
+ /**
13
+ * Read the retry settings of a run. Without a `retries` block an action runs
14
+ * once; a block that leaves `enabled` out turns retries on.
15
+ */
16
+ const resolveRetryPolicy = (retries) => {
17
+ if (!retries) {
18
+ return {
19
+ maxAttempts: 1,
20
+ backoffMs: 0,
21
+ maxDelayMs: 0,
22
+ jitter: 0,
23
+ multiplier: 1,
24
+ };
25
+ }
26
+ return {
27
+ maxAttempts: (retries.enabled ?? true) ? retries.max_attempts : 1,
28
+ backoffMs: retries.backoff_ms ?? 0,
29
+ maxDelayMs: retries.max_delay_ms,
30
+ jitter: retries.jitter,
31
+ multiplier: retries.multiplier,
32
+ };
33
+ };
34
+ /** Cap a retry delay at the policy's `max_delay_ms`, when one is set. */
35
+ const capDelay = (delay, { maxDelayMs }) => maxDelayMs > 0 ? Math.min(delay, maxDelayMs) : delay;
36
+ /** Pause before the next attempt: the delay, capped, then spread by the jitter. */
37
+ const retryPause = (delay, policy) => {
38
+ const cappedDelay = capDelay(delay, policy);
39
+ if (cappedDelay <= 0) {
40
+ return 0;
41
+ }
42
+ const jitterFactor = policy.jitter > 0 ? 1 + (Math.random() * 2 - 1) * policy.jitter : 1;
43
+ return Math.max(0, Math.round(cappedDelay * jitterFactor));
44
+ };
12
45
  /**
13
46
  * Base implementation that enforces schema-validated input/output.
14
47
  */
@@ -53,11 +86,10 @@ export class AbstractAction {
53
86
  return this.outputSchema.parse(payload);
54
87
  }
55
88
  /**
56
- * Executes the action with retry, timeout, and schema safety.
89
+ * Parses settings over the base execution settings (timeout, retries).
57
90
  *
58
- * @param payload - Raw input being provided to the action.
59
- * @returns Validated output produced by the action.
60
- * @throws Error when retries are exhausted or validation fails.
91
+ * @param payload - Raw settings of the task.
92
+ * @returns Settings typed as `RuntimeSettings<S>` after schema validation.
61
93
  */
62
94
  parseSettings(payload) {
63
95
  const settings = z
@@ -65,27 +97,21 @@ export class AbstractAction {
65
97
  .parse(payload ?? {});
66
98
  return (settings ?? {});
67
99
  }
100
+ /**
101
+ * Executes the action with retry, timeout, and schema safety.
102
+ *
103
+ * @param payload - Raw input being provided to the action.
104
+ * @returns Validated output produced by the action.
105
+ * @throws Error when retries are exhausted or validation fails.
106
+ */
68
107
  async run(payload, context, settings, bindings, signal) {
69
108
  const input = this.parseInput(payload);
70
109
  const parsedSettings = this.parseSettings(settings);
71
110
  const parsedBindings = (bindings ?? {});
72
111
  this.assertSupportedBindings(parsedBindings);
73
112
  const timeoutMs = parsedSettings.timeout_ms ?? 0;
74
- const retrySettings = parsedSettings.retries ?? {
75
- enabled: false,
76
- max_attempts: 1,
77
- backoff_ms: 0,
78
- max_delay_ms: 0,
79
- jitter: 0,
80
- multiplier: 1,
81
- };
82
- const retriesEnabled = retrySettings.enabled ?? true;
83
- const maxAttempts = retriesEnabled ? retrySettings.max_attempts : 1;
84
- let attempt = 0;
85
- let currentDelay = retrySettings.backoff_ms ?? 0;
86
- const maxDelayMs = retrySettings.max_delay_ms;
87
- const jitter = retrySettings.jitter;
88
- const multiplier = retrySettings.multiplier;
113
+ const retryPolicy = resolveRetryPolicy(parsedSettings.retries);
114
+ let delay = retryPolicy.backoffMs;
89
115
  // Suspend keys are positional within the body, so every attempt has to
90
116
  // start from where this run did: otherwise a retry asks for `index:2`
91
117
  // where the first attempt resolved `index:1`, and the step suspends on a
@@ -93,7 +119,7 @@ export class AbstractAction {
93
119
  const rewindSuspendCursor = context
94
120
  ?.getWorkflowRuntime?.()
95
121
  ?.markSuspendCursor?.();
96
- while (attempt < maxAttempts) {
122
+ for (let attempt = 1; attempt <= retryPolicy.maxAttempts; attempt += 1) {
97
123
  if (signal) {
98
124
  throwIfAborted(signal);
99
125
  }
@@ -109,28 +135,18 @@ export class AbstractAction {
109
135
  return this.parseOutput(result);
110
136
  }
111
137
  catch (error) {
112
- attempt += 1;
113
138
  // A retry would read the same refused resume payload again, or replay
114
139
  // the same body into the same mismatch with what it recorded.
115
- if (attempt >= maxAttempts ||
140
+ if (attempt >= retryPolicy.maxAttempts ||
116
141
  isWorkflowResumeRejectedError(error) ||
117
142
  isNonDeterministicWorkflowError(error)) {
118
143
  throw error;
119
144
  }
120
- let delay = currentDelay;
121
- if (maxDelayMs > 0) {
122
- delay = Math.min(delay, maxDelayMs);
123
- }
124
- if (delay > 0) {
125
- const jitterFactor = jitter > 0 ? 1 + (Math.random() * 2 - 1) * jitter : 1;
126
- const jitteredDelay = Math.max(0, Math.round(delay * jitterFactor));
127
- if (jitteredDelay > 0) {
128
- await sleep(jitteredDelay, signal);
129
- }
145
+ const pause = retryPause(delay, retryPolicy);
146
+ if (pause > 0) {
147
+ await sleep(pause, signal);
130
148
  }
131
- const nextDelay = currentDelay * multiplier;
132
- currentDelay =
133
- maxDelayMs > 0 ? Math.min(nextDelay, maxDelayMs) : nextDelay;
149
+ delay = capDelay(delay * retryPolicy.multiplier, retryPolicy);
134
150
  }
135
151
  }
136
152
  throw new Error('Action failed after exhausting retry attempts.');
@@ -3,6 +3,7 @@
3
3
  * Copyright (c) 2025 Hexastack.
4
4
  * Full terms: see LICENSE.md.
5
5
  */
6
+ import { toValidationIssues, } from '../validation-issue';
6
7
  const TASK_KIND = 'task';
7
8
  const resolveValidationOptions = (options) => {
8
9
  if (!options) {
@@ -19,19 +20,11 @@ const hasBindingsConfigured = (workflow) => {
19
20
  const hasNestedBindings = Object.values(defs).some((definition) => definition.bindings && Object.keys(definition.bindings).length > 0);
20
21
  return hasNonTaskDefs || hasNestedBindings;
21
22
  };
22
- const toBindingSettingsIssues = (zodIssues, defName) => zodIssues.map((issue) => {
23
- const path = issue.path.join('.') || '<root>';
24
- return {
25
- code: 'binding_settings',
26
- message: `defs.${defName}.settings.${path}: ${issue.message}`,
27
- path: [
28
- 'defs',
29
- defName,
30
- 'settings',
31
- ...issue.path.filter((segment) => typeof segment === 'string' || typeof segment === 'number'),
32
- ],
33
- };
34
- });
23
+ const toBindingSettingsIssues = (schemaIssues, defName) => toValidationIssues('binding_settings', schemaIssues, [
24
+ 'defs',
25
+ defName,
26
+ 'settings',
27
+ ]);
35
28
  const collectDuplicateReferences = (refs) => {
36
29
  const seen = new Set();
37
30
  const duplicates = new Set();
@@ -108,245 +101,270 @@ const missingActionIssue = (defName, actionName) => ({
108
101
  path: ['defs', defName, 'action'],
109
102
  actionName,
110
103
  });
111
- const resolveSupportedBindingKinds = (definition, defName, kinds, actions, issues) => {
104
+ /** Look an action up in the catalog; inherited object members are not actions. */
105
+ const findAction = (actions, actionName) => actions && Object.prototype.hasOwnProperty.call(actions, actionName)
106
+ ? actions[actionName]
107
+ : undefined;
108
+ /**
109
+ * Whether a def names an action the catalog does not hold. A task always runs
110
+ * its action, so an empty name is missing as well; other defs may leave it
111
+ * empty.
112
+ */
113
+ const isMissingAction = (definition, actions) => {
114
+ if (!actions || typeof definition.action !== 'string') {
115
+ return false;
116
+ }
117
+ if (definition.action === '' && definition.kind !== TASK_KIND) {
118
+ return false;
119
+ }
120
+ return !findAction(actions, definition.action);
121
+ };
122
+ const actionPolicyIssues = (defName, definition, { actionPolicy = 'optional' }) => {
123
+ const issue = (code, message) => [
124
+ {
125
+ code,
126
+ message: `defs.${defName}.action: Binding kind "${definition.kind}" ${message}`,
127
+ path: ['defs', defName, 'action'],
128
+ bindingKind: definition.kind,
129
+ },
130
+ ];
131
+ if (actionPolicy === 'required' && !definition.action) {
132
+ return issue('action_required', 'requires an action.');
133
+ }
134
+ if (actionPolicy === 'forbidden' && definition.action) {
135
+ return issue('action_forbidden', 'does not allow action declarations.');
136
+ }
137
+ return [];
138
+ };
139
+ /**
140
+ * Check the kind, action and settings of one def. Settings that match the
141
+ * kind's schema are recorded in `parsedSettings`, for mounting.
142
+ */
143
+ const validateDef = (defName, definition, kinds, actions, parsedSettings) => {
144
+ const missingAction = isMissingAction(definition, actions)
145
+ ? [missingActionIssue(defName, definition.action)]
146
+ : [];
147
+ if (definition.kind === TASK_KIND) {
148
+ return missingAction;
149
+ }
150
+ const kindDefinition = kinds[definition.kind];
151
+ if (!kindDefinition) {
152
+ return [
153
+ {
154
+ code: 'unknown_binding_kind',
155
+ message: `defs.${defName}.kind: Unknown binding kind "${definition.kind}".`,
156
+ path: ['defs', defName, 'kind'],
157
+ bindingKind: definition.kind,
158
+ },
159
+ ...missingAction,
160
+ ];
161
+ }
162
+ const issues = [
163
+ ...actionPolicyIssues(defName, definition, kindDefinition),
164
+ ...missingAction,
165
+ ];
166
+ const parsed = kindDefinition.schema.safeParse(definition.settings);
167
+ if (!parsed.success) {
168
+ return [
169
+ ...issues,
170
+ ...toBindingSettingsIssues(parsed.error.issues, defName),
171
+ ];
172
+ }
173
+ parsedSettings.set(defName, parsed.data);
174
+ // `?.` on `safeParse` too: hosts may pass serialized schemas.
175
+ const actionParsed = definition.action
176
+ ? findAction(actions, definition.action)?.settingSchema?.safeParse?.(definition.settings)
177
+ : undefined;
178
+ if (actionParsed && !actionParsed.success) {
179
+ issues.push(...toBindingSettingsIssues(actionParsed.error.issues, defName));
180
+ }
181
+ return issues;
182
+ };
183
+ /**
184
+ * List the binding kinds a def may mount, or null when they cannot be known:
185
+ * no action catalog was given, or the def's action is missing from it.
186
+ */
187
+ const resolveSupportedBindingKinds = (definition, kinds, actions) => {
112
188
  if (definition.action) {
113
- if (!actions) {
114
- return null;
115
- }
116
- const action = actions[definition.action];
117
- if (!action) {
118
- issues.push(missingActionIssue(defName, definition.action));
119
- return [];
120
- }
121
- return action.supportedBindings ?? [];
189
+ const action = findAction(actions, definition.action);
190
+ return action ? (action.supportedBindings ?? []) : null;
122
191
  }
123
192
  if (definition.kind === TASK_KIND) {
124
193
  return [];
125
194
  }
126
195
  return kinds[definition.kind]?.supportedBindings ?? [];
127
196
  };
128
- export const validateAndResolveBindings = (workflow, options) => {
197
+ /**
198
+ * Check one `bindings.<kind>` entry of a def: the kind exists, the reference
199
+ * cardinality matches it, the def may mount it, and every reference names a
200
+ * def of that kind.
201
+ */
202
+ const validateBindingEntry = (defName, definition, bindingKind, bindingRefs, context) => {
203
+ const issue = (code, message) => ({
204
+ code,
205
+ message: `defs.${defName}.bindings.${bindingKind}: ${message}`,
206
+ path: ['defs', defName, 'bindings', bindingKind],
207
+ bindingKind,
208
+ });
209
+ const kindDefinition = context.kinds[bindingKind];
210
+ if (!kindDefinition) {
211
+ return [
212
+ issue('unknown_binding_kind', `Unknown binding kind "${bindingKind}".`),
213
+ ];
214
+ }
215
+ const { multiple } = kindDefinition;
216
+ if (multiple ? !Array.isArray(bindingRefs) : typeof bindingRefs !== 'string') {
217
+ const expected = multiple
218
+ ? 'an array of def references'
219
+ : 'a single def reference string';
220
+ return [
221
+ issue('binding_ref', `Expected ${expected} for binding kind "${bindingKind}".`),
222
+ ];
223
+ }
129
224
  const issues = [];
130
- const resolvedDefs = {};
131
- const defs = workflow.defs ?? {};
132
- const resolvedOptions = resolveValidationOptions(options);
133
- const kinds = resolvedOptions.bindingKinds ?? {};
134
- const actions = resolvedOptions.actions;
135
- const kindNames = Object.keys(kinds);
136
- const hasBindingUsage = hasBindingsConfigured(workflow);
137
- const parsedSettingsByDefName = new Map();
138
- if (hasBindingUsage && kindNames.length === 0) {
139
- issues.push({
140
- code: 'binding_registry_required',
141
- message: 'Workflows that declare non-task defs or nested bindings require a non-empty "bindingKinds" registry.',
142
- });
225
+ const { supportedKinds } = context;
226
+ if (supportedKinds && !supportedKinds.includes(bindingKind)) {
227
+ const supportedKindsLabel = supportedKinds.length > 0 ? supportedKinds.join(', ') : '<none>';
228
+ issues.push(issue('binding_unsupported', `"${definition.action ?? definition.kind}" does not support binding kind "${bindingKind}". Supported binding kinds: ${supportedKindsLabel}.`));
143
229
  }
144
- for (const [defName, defDefinition] of Object.entries(defs)) {
145
- if (defDefinition.kind === TASK_KIND) {
146
- if (defDefinition.action && actions && !actions[defDefinition.action]) {
147
- issues.push(missingActionIssue(defName, defDefinition.action));
148
- }
149
- continue;
150
- }
151
- const kindDefinition = kinds[defDefinition.kind];
152
- if (!kindDefinition) {
153
- issues.push({
154
- code: 'unknown_binding_kind',
155
- message: `defs.${defName}.kind: Unknown binding kind "${defDefinition.kind}".`,
156
- path: ['defs', defName, 'kind'],
157
- bindingKind: defDefinition.kind,
158
- });
159
- continue;
160
- }
161
- const actionPolicy = kindDefinition.actionPolicy ?? 'optional';
162
- if (actionPolicy === 'required' && !defDefinition.action) {
163
- issues.push({
164
- code: 'action_required',
165
- message: `defs.${defName}.action: Binding kind "${defDefinition.kind}" requires an action.`,
166
- path: ['defs', defName, 'action'],
167
- bindingKind: defDefinition.kind,
168
- });
169
- }
170
- if (actionPolicy === 'forbidden' && defDefinition.action) {
171
- issues.push({
172
- code: 'action_forbidden',
173
- message: `defs.${defName}.action: Binding kind "${defDefinition.kind}" does not allow action declarations.`,
174
- path: ['defs', defName, 'action'],
175
- bindingKind: defDefinition.kind,
176
- });
177
- }
178
- if (defDefinition.action && actions && !actions[defDefinition.action]) {
179
- issues.push(missingActionIssue(defName, defDefinition.action));
180
- }
181
- const { schema } = kindDefinition;
182
- const parsedPayload = schema.safeParse(defDefinition.settings);
183
- if (!parsedPayload.success) {
184
- issues.push(...toBindingSettingsIssues(parsedPayload.error.issues, defName));
185
- continue;
186
- }
187
- parsedSettingsByDefName.set(defName, parsedPayload.data);
188
- const actionSchema = defDefinition.action
189
- ? actions?.[defDefinition.action]?.settingSchema
190
- : undefined;
191
- const actionParsed = actionSchema?.safeParse?.(defDefinition.settings);
192
- if (actionParsed && !actionParsed.success) {
193
- issues.push(...toBindingSettingsIssues(actionParsed.error.issues, defName));
194
- }
230
+ const refProblems = describeReferenceProblems(toBindingRefs(bindingRefs), bindingKind, context.defs);
231
+ return [
232
+ ...issues,
233
+ ...refProblems.map((message) => issue('binding_ref', message)),
234
+ ];
235
+ };
236
+ /** Duplicate references, and references that do not name a def of `bindingKind`. */
237
+ const describeReferenceProblems = (refs, bindingKind, defs) => {
238
+ const problems = [];
239
+ const duplicateRefs = collectDuplicateReferences(refs);
240
+ if (duplicateRefs.length > 0) {
241
+ problems.push(`Duplicate def reference(s): ${duplicateRefs.join(', ')}`);
195
242
  }
196
- for (const [defName, defDefinition] of Object.entries(defs)) {
197
- const defBindings = defDefinition.bindings;
198
- if (!defBindings) {
199
- continue;
243
+ for (const ref of refs) {
244
+ const target = defs[ref];
245
+ if (!target) {
246
+ problems.push(`Unknown def reference "${ref}".`);
200
247
  }
201
- const supportedKinds = resolveSupportedBindingKinds(defDefinition, defName, kinds, actions, issues);
202
- const shouldValidateSupportedKinds = Array.isArray(supportedKinds);
203
- for (const [bindingKind, bindingRefs] of Object.entries(defBindings)) {
204
- const bindingPath = ['defs', defName, 'bindings', bindingKind];
205
- const kindDefinition = kinds[bindingKind];
206
- if (!kindDefinition) {
207
- issues.push({
208
- code: 'unknown_binding_kind',
209
- message: `defs.${defName}.bindings.${bindingKind}: Unknown binding kind "${bindingKind}".`,
210
- path: bindingPath,
211
- bindingKind,
212
- });
213
- continue;
214
- }
215
- const { multiple } = kindDefinition;
216
- if (multiple && !Array.isArray(bindingRefs)) {
217
- issues.push({
218
- code: 'binding_ref',
219
- message: `defs.${defName}.bindings.${bindingKind}: Expected an array of def references for binding kind "${bindingKind}".`,
220
- path: bindingPath,
221
- bindingKind,
222
- });
223
- continue;
224
- }
225
- if (!multiple && typeof bindingRefs !== 'string') {
226
- issues.push({
227
- code: 'binding_ref',
228
- message: `defs.${defName}.bindings.${bindingKind}: Expected a single def reference string for binding kind "${bindingKind}".`,
229
- path: bindingPath,
230
- bindingKind,
231
- });
232
- continue;
233
- }
234
- if (shouldValidateSupportedKinds &&
235
- supportedKinds &&
236
- !supportedKinds.includes(bindingKind)) {
237
- const supportedKindsLabel = supportedKinds.length > 0 ? supportedKinds.join(', ') : '<none>';
238
- issues.push({
239
- code: 'binding_unsupported',
240
- message: `defs.${defName}.bindings.${bindingKind}: "${defDefinition.action ?? defDefinition.kind}" does not support binding kind "${bindingKind}". Supported binding kinds: ${supportedKindsLabel}.`,
241
- path: bindingPath,
242
- bindingKind,
243
- });
244
- }
245
- const refs = toBindingRefs(bindingRefs);
246
- const duplicateRefs = collectDuplicateReferences(refs);
247
- if (duplicateRefs.length > 0) {
248
- issues.push({
249
- code: 'binding_ref',
250
- message: `defs.${defName}.bindings.${bindingKind}: Duplicate def reference(s): ${duplicateRefs.join(', ')}`,
251
- path: bindingPath,
252
- bindingKind,
253
- });
254
- }
255
- for (const ref of refs) {
256
- const definition = defs[ref];
257
- if (!definition) {
258
- issues.push({
259
- code: 'binding_ref',
260
- message: `defs.${defName}.bindings.${bindingKind}: Unknown def reference "${ref}".`,
261
- path: bindingPath,
262
- bindingKind,
263
- });
264
- continue;
265
- }
266
- if (definition.kind !== bindingKind) {
267
- issues.push({
268
- code: 'binding_ref',
269
- message: `defs.${defName}.bindings.${bindingKind}: Def "${ref}" has kind "${definition.kind}" and cannot be mounted as "${bindingKind}".`,
270
- path: bindingPath,
271
- bindingKind,
272
- });
273
- }
274
- }
248
+ else if (target.kind !== bindingKind) {
249
+ problems.push(`Def "${ref}" has kind "${target.kind}" and cannot be mounted as "${bindingKind}".`);
275
250
  }
276
251
  }
277
- issues.push(...detectBindingCycles(defs));
252
+ return problems;
253
+ };
254
+ const validateDefBindings = (defName, definition, defs, kinds, actions) => {
255
+ if (!definition.bindings) {
256
+ return [];
257
+ }
258
+ const context = {
259
+ defs,
260
+ kinds,
261
+ supportedKinds: resolveSupportedBindingKinds(definition, kinds, actions),
262
+ };
263
+ return Object.entries(definition.bindings).flatMap(([bindingKind, bindingRefs]) => validateBindingEntry(defName, definition, bindingKind, bindingRefs, context));
264
+ };
265
+ /**
266
+ * Mount every non-task def whose settings parsed, with its nested bindings.
267
+ * A def reached again while it is being mounted, through a cycle, is left
268
+ * out of the def that reached it.
269
+ */
270
+ const resolveBindingDefs = (defs, kinds, parsedSettings) => {
271
+ const resolvedDefs = {};
278
272
  const inProgress = new Set();
279
- const mountResolvedDef = (defName) => {
273
+ const mountDef = (defName) => {
280
274
  const existing = resolvedDefs[defName];
281
275
  if (existing) {
282
276
  return existing.payload;
283
277
  }
284
278
  const definition = defs[defName];
285
- if (!definition || definition.kind === TASK_KIND) {
286
- return undefined;
287
- }
288
- const parsedSettings = parsedSettingsByDefName.get(defName);
289
- if (parsedSettings === undefined) {
290
- return undefined;
291
- }
292
- if (inProgress.has(defName)) {
279
+ const settings = parsedSettings.get(defName);
280
+ if (!definition ||
281
+ definition.kind === TASK_KIND ||
282
+ settings === undefined ||
283
+ inProgress.has(defName)) {
293
284
  return undefined;
294
285
  }
295
286
  inProgress.add(defName);
296
- const nestedBindings = mountTaskBindings(definition.bindings, resolvedDefs, kinds, mountResolvedDef);
287
+ const nestedBindings = mountTaskBindings(definition.bindings, resolvedDefs, kinds, mountDef);
297
288
  const payload = {
298
- settings: parsedSettings,
289
+ settings,
299
290
  ...(definition.action ? { action: definition.action } : {}),
291
+ ...(definition.description
292
+ ? { description: definition.description }
293
+ : {}),
300
294
  ...(Object.keys(nestedBindings).length > 0
301
295
  ? { bindings: nestedBindings }
302
296
  : {}),
303
297
  };
304
- resolvedDefs[defName] = {
305
- kind: definition.kind,
306
- payload,
307
- };
298
+ resolvedDefs[defName] = { kind: definition.kind, payload };
308
299
  inProgress.delete(defName);
309
300
  return payload;
310
301
  };
311
302
  for (const [defName, definition] of Object.entries(defs)) {
312
- if (definition.kind === TASK_KIND) {
313
- continue;
303
+ if (definition.kind !== TASK_KIND) {
304
+ mountDef(defName);
314
305
  }
315
- mountResolvedDef(defName);
316
306
  }
317
- return { issues, resolvedDefs };
307
+ return resolvedDefs;
318
308
  };
319
- export const mountTaskBindings = (taskBindings, resolvedDefs, bindingKinds, resolveDef) => {
309
+ /**
310
+ * Validate the defs and bindings of a workflow, and mount every valid
311
+ * non-task def so tasks can be handed their bindings.
312
+ */
313
+ export const validateAndResolveBindings = (workflow, options) => {
314
+ const defs = workflow.defs ?? {};
315
+ const { bindingKinds: kinds = {}, actions } = resolveValidationOptions(options);
316
+ const issues = [];
317
+ const parsedSettings = new Map();
318
+ if (hasBindingsConfigured(workflow) && Object.keys(kinds).length === 0) {
319
+ issues.push({
320
+ code: 'binding_registry_required',
321
+ message: 'Workflows that declare non-task defs or nested bindings require a non-empty "bindingKinds" registry.',
322
+ });
323
+ }
324
+ for (const [defName, definition] of Object.entries(defs)) {
325
+ issues.push(...validateDef(defName, definition, kinds, actions, parsedSettings));
326
+ }
327
+ for (const [defName, definition] of Object.entries(defs)) {
328
+ issues.push(...validateDefBindings(defName, definition, defs, kinds, actions));
329
+ }
330
+ issues.push(...detectBindingCycles(defs));
331
+ return {
332
+ issues,
333
+ resolvedDefs: resolveBindingDefs(defs, kinds, parsedSettings),
334
+ };
335
+ };
336
+ /** Payloads of the references that resolve, keyed by def name; none gives undefined. */
337
+ const resolveEach = (refs, resolve) => {
338
+ const payloads = {};
339
+ for (const ref of refs) {
340
+ const payload = resolve(ref);
341
+ if (payload) {
342
+ payloads[ref] = payload;
343
+ }
344
+ }
345
+ return Object.keys(payloads).length > 0 ? payloads : undefined;
346
+ };
347
+ /**
348
+ * Mount the defs a task (or def) references in `bindings`, by binding kind:
349
+ * one payload for a single-ref kind, payloads keyed by def name otherwise.
350
+ * References that resolve to nothing are left out.
351
+ */
352
+ export const mountTaskBindings = (taskBindings, resolvedDefs, bindingKinds = {}, resolveDef) => {
320
353
  if (!taskBindings) {
321
354
  return {};
322
355
  }
356
+ const resolve = (ref) => resolvedDefs[ref]?.payload ?? resolveDef?.(ref);
323
357
  const mounted = {};
324
- const kinds = bindingKinds ?? {};
325
358
  for (const [bindingKind, bindingRefs] of Object.entries(taskBindings)) {
326
359
  const refs = toBindingRefs(bindingRefs);
327
- const isMultiple = kinds[bindingKind]?.multiple ?? Array.isArray(bindingRefs);
328
- if (!isMultiple) {
329
- const ref = refs[0];
330
- if (!ref) {
331
- continue;
332
- }
333
- const resolvedDefPayload = resolvedDefs[ref]?.payload ?? resolveDef?.(ref) ?? undefined;
334
- if (!resolvedDefPayload) {
335
- continue;
336
- }
337
- mounted[bindingKind] = resolvedDefPayload;
338
- continue;
339
- }
340
- const mountedKindDefs = {};
341
- for (const ref of refs) {
342
- const resolvedDefPayload = resolvedDefs[ref]?.payload ?? resolveDef?.(ref) ?? undefined;
343
- if (!resolvedDefPayload) {
344
- continue;
345
- }
346
- mountedKindDefs[ref] = resolvedDefPayload;
347
- }
348
- if (Object.keys(mountedKindDefs).length > 0) {
349
- mounted[bindingKind] = mountedKindDefs;
360
+ const isMultiple = bindingKinds[bindingKind]?.multiple ?? Array.isArray(bindingRefs);
361
+ const payload = isMultiple
362
+ ? resolveEach(refs, resolve)
363
+ : refs[0]
364
+ ? resolve(refs[0])
365
+ : undefined;
366
+ if (payload) {
367
+ mounted[bindingKind] = payload;
350
368
  }
351
369
  }
352
370
  return mounted;
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { z } from 'zod';
7
7
  import { WorkflowCheckpointInvalidError, WorkflowDefinitionDriftError, WorkflowResumeError, WorkflowWaitAmbiguousError, WorkflowWaitNotFoundError, } from './errors';
8
- import { checkResumePayload } from './resume-payload';
8
+ import { checkResumePayload, describeSchemaIssues } from './resume-payload';
9
9
  import { isRecord } from './utils/clone';
10
10
  import { StepType } from './workflow-event-emitter';
11
11
  import { fingerprintWorkflow } from './workflow-fingerprint';
@@ -206,7 +206,7 @@ const parseCheckpoint = (checkpoint) => {
206
206
  }
207
207
  const result = workflowCheckpointSchema.safeParse(checkpoint);
208
208
  if (!result.success) {
209
- const issues = result.error.issues.map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`);
209
+ const issues = describeSchemaIssues(result.error.issues);
210
210
  throw new WorkflowCheckpointInvalidError('malformed', `Checkpoint does not match the expected shape: ${issues.join('; ')}`, { issues });
211
211
  }
212
212
  return result.data;
@@ -35,10 +35,9 @@ export const WORKFLOW_RUN_STATUSES = [
35
35
  */
36
36
  export class BaseWorkflowContext {
37
37
  /**
38
- * Sets up the context and copies any initial state onto the instance.
38
+ * Sets up the context with its initial state.
39
39
  *
40
- * @param initialState - Optional properties to assign to the context instance.
41
- * @param eventEmitter - Optional workflow event emitter to expose to actions.
40
+ * @param initialState - State exposed to expressions as `$context`.
42
41
  */
43
42
  constructor(initialState) {
44
43
  this.state = (initialState ?? {});