@hexabot-ai/agentic 3.5.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,6 +7,7 @@ import { buildWaitId, } from '../checkpoint';
7
7
  import { createLinkedAbortController, getAbortReason, isWorkflowResumeRejectedError, throwIfAborted, WorkflowCancellationError, } from '../errors';
8
8
  import { cloneAsJson, cloneValue } from '../utils/clone';
9
9
  import { evaluateMapping } from '../workflow-values';
10
+ import { buildEvaluationScope } from './scope';
10
11
  /**
11
12
  * Execute a task step, returning a frame when its action suspends.
12
13
  *
@@ -33,37 +34,17 @@ export async function executeTaskStep(env, step, state, _path, frame) {
33
34
  return frame;
34
35
  }
35
36
  const stepInfo = env.buildInstanceStepInfo(step, state.iterationStack);
36
- if (env.signal.aborted) {
37
- const error = getAbortReason(env.signal);
38
- recordTaskCancellation(env, stepInfo, error, frame?.wait);
39
- throw error;
40
- }
37
+ throwIfCancelled(env, stepInfo, frame);
41
38
  // Resumed bodies reuse the inputs they first ran with: re-evaluating could
42
39
  // differ, e.g. when an expression depends on the event that woke the run.
43
40
  const inputs = frame
44
41
  ? cloneValue(frame.inputs)
45
- : await evaluateMapping(task.inputs, buildScope(env, state));
46
- if (env.signal.aborted) {
47
- const error = getAbortReason(env.signal);
48
- recordTaskCancellation(env, stepInfo, error, frame?.wait);
49
- throw error;
50
- }
42
+ : await evaluateMapping(task.inputs, buildEvaluationScope(env, state));
43
+ throwIfCancelled(env, stepInfo, frame);
51
44
  // Kept apart from the object the body gets, so that a body changing its
52
45
  // inputs cannot change the inputs every later pass replays.
53
46
  const recordedInputs = frame ? frame.inputs : copyInputs(inputs);
54
47
  const resumeData = frame ? env.resolutions.get(frame.wait.waitId) : undefined;
55
- const seed = frame
56
- ? {
57
- awaitResults: {
58
- ...readRecordedResults(frame.awaitResults),
59
- [frame.wait.suspendKey]: resumeData,
60
- },
61
- expected: {
62
- suspendKey: frame.wait.suspendKey,
63
- reason: frame.wait.reason,
64
- },
65
- }
66
- : undefined;
67
48
  const stepExecution = env.recordStepExecution(stepInfo, {
68
49
  action: task.actionName,
69
50
  status: 'running',
@@ -73,7 +54,9 @@ export async function executeTaskStep(env, step, state, _path, frame) {
73
54
  input: inputs,
74
55
  context: { before: env.context.snapshot() },
75
56
  });
76
- env.runtime.beginStep(stepInfo, { seed });
57
+ env.runtime.beginStep(stepInfo, {
58
+ seed: frame ? buildReplaySeed(frame, resumeData) : undefined,
59
+ });
77
60
  env.markSnapshot(stepInfo, 'running');
78
61
  if (frame) {
79
62
  env.emit('hook:step:resumed', {
@@ -156,12 +139,31 @@ const copyInputs = (inputs) => {
156
139
  return inputs;
157
140
  }
158
141
  };
159
- const buildScope = (env, state) => ({
160
- input: state.input,
161
- context: env.context.state,
162
- output: state.output,
163
- iteration: state.iteration,
164
- accumulator: state.accumulator,
142
+ /**
143
+ * Record the task cancelled and throw when the run was aborted before its
144
+ * body started.
145
+ */
146
+ const throwIfCancelled = (env, stepInfo, frame) => {
147
+ if (!env.signal.aborted) {
148
+ return;
149
+ }
150
+ const error = getAbortReason(env.signal);
151
+ recordTaskCancellation(env, stepInfo, error, frame?.wait);
152
+ throw error;
153
+ };
154
+ /**
155
+ * Seed a resumed body with every answer it already got, including the one
156
+ * this pass resolved, and the suspension it is expected to reach again.
157
+ */
158
+ const buildReplaySeed = (frame, resumeData) => ({
159
+ awaitResults: {
160
+ ...readRecordedResults(frame.awaitResults),
161
+ [frame.wait.suspendKey]: resumeData,
162
+ },
163
+ expected: {
164
+ suspendKey: frame.wait.suspendKey,
165
+ reason: frame.wait.reason,
166
+ },
165
167
  });
166
168
  const waitForTaskProgress = async (signal, runtime, actionPromise) => {
167
169
  const completion = actionPromise.then((value) => ({ type: 'completed', value }), (error) => ({ type: 'failed', error }));
@@ -191,13 +193,9 @@ const waitForTaskProgress = async (signal, runtime, actionPromise) => {
191
193
  };
192
194
  const completeTask = async (env, stepInfo, task, state, result) => {
193
195
  await env.captureTaskOutput(task, state, result);
194
- const stepExecution = env.recordStepExecution(stepInfo, {
195
- status: 'completed',
196
- endedAt: Date.now(),
196
+ const stepExecution = endStepExecution(env, stepInfo, 'completed', {
197
197
  output: result,
198
- context: { after: env.context.snapshot() },
199
198
  });
200
- env.markSnapshot(stepInfo, 'completed');
201
199
  env.emit('hook:step:success', {
202
200
  runId: env.runId,
203
201
  step: stepInfo,
@@ -214,13 +212,7 @@ const suspendTask = (env, step, stepInfo, inputs, request) => {
214
212
  ...(request.accepts ? { accepts: request.accepts } : {}),
215
213
  ...(request.payloadOptional ? { payloadOptional: true } : {}),
216
214
  };
217
- const stepExecution = env.recordStepExecution(stepInfo, {
218
- status: 'suspended',
219
- endedAt: Date.now(),
220
- reason: request.reason,
221
- context: { after: env.context.snapshot() },
222
- });
223
- env.markSnapshot(stepInfo, 'suspended', request.reason);
215
+ const stepExecution = endStepExecution(env, stepInfo, 'suspended', { reason: request.reason }, request.reason);
224
216
  env.emit('hook:step:suspended', {
225
217
  runId: env.runId,
226
218
  step: stepInfo,
@@ -243,13 +235,7 @@ const readRecordedResults = (recorded) => Object.fromEntries(Object.entries(reco
243
235
  * resume payload, and hand back the frame it resumed from.
244
236
  */
245
237
  const keepWaiting = (env, stepInfo, frame, error) => {
246
- const stepExecution = env.recordStepExecution(stepInfo, {
247
- status: 'suspended',
248
- endedAt: Date.now(),
249
- reason: frame.wait.reason,
250
- context: { after: env.context.snapshot() },
251
- });
252
- env.markSnapshot(stepInfo, 'suspended', frame.wait.reason);
238
+ const stepExecution = endStepExecution(env, stepInfo, 'suspended', { reason: frame.wait.reason }, frame.wait.reason);
253
239
  env.emit('hook:step:resume_rejected', {
254
240
  runId: env.runId,
255
241
  step: stepInfo,
@@ -261,14 +247,7 @@ const keepWaiting = (env, stepInfo, frame, error) => {
261
247
  return frame;
262
248
  };
263
249
  const recordTaskFailure = (env, stepInfo, error) => {
264
- const normalizedError = normalizeError(error);
265
- const stepExecution = env.recordStepExecution(stepInfo, {
266
- status: 'failed',
267
- endedAt: Date.now(),
268
- error: normalizedError,
269
- context: { after: env.context.snapshot() },
270
- });
271
- env.markSnapshot(stepInfo, 'failed', normalizeErrorMessage(error));
250
+ const stepExecution = endStepExecutionWithError(env, stepInfo, 'failed', error);
272
251
  env.emit('hook:step:error', {
273
252
  runId: env.runId,
274
253
  step: stepInfo,
@@ -281,14 +260,7 @@ const recordTaskFailure = (env, stepInfo, error) => {
281
260
  * wait, so the event carries it.
282
261
  */
283
262
  const recordTaskCancellation = (env, stepInfo, error, wait) => {
284
- const normalizedError = normalizeError(error);
285
- const stepExecution = env.recordStepExecution(stepInfo, {
286
- status: 'cancelled',
287
- endedAt: Date.now(),
288
- error: normalizedError,
289
- context: { after: env.context.snapshot() },
290
- });
291
- env.markSnapshot(stepInfo, 'cancelled', normalizeErrorMessage(error));
263
+ const stepExecution = endStepExecutionWithError(env, stepInfo, 'cancelled', error);
292
264
  env.emit('hook:step:cancelled', {
293
265
  runId: env.runId,
294
266
  step: stepInfo,
@@ -297,7 +269,24 @@ const recordTaskCancellation = (env, stepInfo, error, wait) => {
297
269
  ...(wait ? { wait } : {}),
298
270
  });
299
271
  };
300
- const normalizeError = (error) => error instanceof Error
301
- ? { message: error.message, stack: error.stack }
302
- : { message: String(error) };
303
- const normalizeErrorMessage = (error) => error instanceof Error ? error.message : String(error);
272
+ /**
273
+ * Close the step's execution record with the status the step ended (or
274
+ * paused) with, and mirror that status on its snapshot.
275
+ *
276
+ * @returns The updated execution record, for the event announcing it.
277
+ */
278
+ const endStepExecution = (env, stepInfo, status, details, snapshotReason) => {
279
+ const stepExecution = env.recordStepExecution(stepInfo, {
280
+ status,
281
+ endedAt: Date.now(),
282
+ ...details,
283
+ context: { after: env.context.snapshot() },
284
+ });
285
+ env.markSnapshot(stepInfo, status, snapshotReason);
286
+ return stepExecution;
287
+ };
288
+ const endStepExecutionWithError = (env, stepInfo, status, error) => endStepExecution(env, stepInfo, status, {
289
+ error: error instanceof Error
290
+ ? { message: error.message, stack: error.stack }
291
+ : { message: String(error) },
292
+ }, error instanceof Error ? error.message : String(error));
@@ -0,0 +1,37 @@
1
+ /*
2
+ * Hexabot — Fair Core License (FCL-1.0-ALv2)
3
+ * Copyright (c) 2026 Hexastack.
4
+ * Full terms: see LICENSE.md.
5
+ */
6
+ /**
7
+ * The step lists nested in a flow step, each with its path relative to the
8
+ * step: one for `parallel` and `loop`, one per branch for `conditional`.
9
+ */
10
+ const nestedStepLists = (step) => {
11
+ if ('parallel' in step) {
12
+ return [{ steps: step.parallel.steps, path: ['parallel', 'steps'] }];
13
+ }
14
+ if ('conditional' in step) {
15
+ return step.conditional.when.map((branch, branchIndex) => ({
16
+ steps: branch.steps,
17
+ path: ['conditional', 'when', branchIndex, 'steps'],
18
+ }));
19
+ }
20
+ if ('loop' in step) {
21
+ return [{ steps: step.loop.steps, path: ['loop', 'steps'] }];
22
+ }
23
+ return [];
24
+ };
25
+ /**
26
+ * List every task reference of a flow, depth first, in flow order.
27
+ *
28
+ * @param steps The flow, or a nested step list.
29
+ * @param basePath Path of `steps` inside the workflow definition.
30
+ */
31
+ export const collectTaskReferences = (steps, basePath = ['flow']) => steps.flatMap((step, index) => {
32
+ const stepPath = [...basePath, index];
33
+ if ('do' in step) {
34
+ return [{ taskId: step.do, path: [...stepPath, 'do'] }];
35
+ }
36
+ return nestedStepLists(step).flatMap(({ steps: nested, path }) => collectTaskReferences(nested, [...stepPath, ...path]));
37
+ });
@@ -4,6 +4,13 @@
4
4
  * Full terms: see LICENSE.md.
5
5
  */
6
6
  export const SNAKE_CASE_REGEX = /^[a-z0-9]+(?:_[a-z0-9]+)*$/;
7
+ /**
8
+ * Checks whether the provided string is snake_case compliant.
9
+ *
10
+ * @param value - Text to evaluate.
11
+ * @returns `true` when the value is snake_case; otherwise `false`.
12
+ */
13
+ export const isSnakeCaseName = (value) => SNAKE_CASE_REGEX.test(value);
7
14
  /**
8
15
  * Verifies that names follow the snake_case convention required by the system.
9
16
  *
@@ -12,17 +19,10 @@ export const SNAKE_CASE_REGEX = /^[a-z0-9]+(?:_[a-z0-9]+)*$/;
12
19
  * @throws Error when the name is not snake_case.
13
20
  */
14
21
  export function assertSnakeCaseName(name, entity) {
15
- if (!SNAKE_CASE_REGEX.test(name)) {
16
- throw new Error(`${entity} name must be snake_case with at least one underscore. Received: "${name}"`);
22
+ if (!isSnakeCaseName(name)) {
23
+ throw new Error(`${entity} name must be snake_case (lowercase letters and digits separated by single underscores). Received: "${name}"`);
17
24
  }
18
25
  }
19
- /**
20
- * Checks whether the provided string is snake_case compliant.
21
- *
22
- * @param value - Text to evaluate.
23
- * @returns `true` when the value is snake_case; otherwise `false`.
24
- */
25
- export const isSnakeCaseName = (value) => SNAKE_CASE_REGEX.test(value);
26
26
  /**
27
27
  * Converts arbitrary text into snake_case for use in workflow entities.
28
28
  *
@@ -0,0 +1,46 @@
1
+ /*
2
+ * Hexabot — Fair Core License (FCL-1.0-ALv2)
3
+ * Copyright (c) 2026 Hexastack.
4
+ * Full terms: see LICENSE.md.
5
+ */
6
+ /**
7
+ * Read a nested value. Array segments must be numbers; a path that leaves
8
+ * the value resolves to `undefined`.
9
+ */
10
+ export const getValueAtPath = (value, path) => path.reduce((acc, key) => {
11
+ if (acc === null || acc === undefined) {
12
+ return undefined;
13
+ }
14
+ if (Array.isArray(acc)) {
15
+ return typeof key === 'number' ? acc[key] : undefined;
16
+ }
17
+ if (typeof acc === 'object') {
18
+ return acc[String(key)];
19
+ }
20
+ return undefined;
21
+ }, value);
22
+ /**
23
+ * Copy a value with one nested value replaced; the input is left untouched.
24
+ * A path that does not fit the value returns it as is.
25
+ */
26
+ export const setValueAtPath = (value, path, nextValue) => {
27
+ if (path.length === 0) {
28
+ return nextValue;
29
+ }
30
+ const [key, ...rest] = path;
31
+ if (Array.isArray(value)) {
32
+ if (typeof key !== 'number') {
33
+ return value;
34
+ }
35
+ const nextArray = [...value];
36
+ nextArray[key] = setValueAtPath(value[key], rest, nextValue);
37
+ return nextArray;
38
+ }
39
+ if (value && typeof value === 'object') {
40
+ return {
41
+ ...value,
42
+ [String(key)]: setValueAtPath(value[String(key)], rest, nextValue),
43
+ };
44
+ }
45
+ return value;
46
+ };
@@ -43,50 +43,27 @@ export async function withTimeout(promise, timeoutMs, signal) {
43
43
  }
44
44
  return new Promise((resolve, reject) => {
45
45
  let settled = false;
46
- const timer = timeoutMs
47
- ? setTimeout(() => {
48
- settled = true;
49
- signal?.removeEventListener('abort', onAbort);
50
- reject(new Error(`Step execution exceeded timeout of ${timeoutMs}ms`));
51
- }, timeoutMs)
52
- : undefined;
53
- const onAbort = () => {
46
+ let timer;
47
+ // The first of the promise, the timeout and the abort settles the
48
+ // result; the other two are detached.
49
+ const settle = (finish) => {
54
50
  if (settled) {
55
51
  return;
56
52
  }
57
53
  settled = true;
58
- if (timer) {
59
- clearTimeout(timer);
60
- }
61
- reject(getAbortReason(signal));
54
+ clearTimeout(timer);
55
+ signal?.removeEventListener('abort', onAbort);
56
+ finish();
62
57
  };
63
- if (signal) {
64
- if (signal.aborted) {
65
- onAbort();
66
- return;
67
- }
68
- signal.addEventListener('abort', onAbort, { once: true });
58
+ const onAbort = () => settle(() => reject(getAbortReason(signal)));
59
+ if (timeoutMs) {
60
+ timer = setTimeout(() => settle(() => reject(new Error(`Step execution exceeded timeout of ${timeoutMs}ms`))), timeoutMs);
69
61
  }
70
- promise.then((value) => {
71
- if (settled) {
72
- return;
73
- }
74
- settled = true;
75
- if (timer) {
76
- clearTimeout(timer);
77
- }
78
- signal?.removeEventListener('abort', onAbort);
79
- resolve(value);
80
- }, (error) => {
81
- if (settled) {
82
- return;
83
- }
84
- settled = true;
85
- if (timer) {
86
- clearTimeout(timer);
87
- }
88
- signal?.removeEventListener('abort', onAbort);
89
- reject(error);
90
- });
62
+ if (signal?.aborted) {
63
+ onAbort();
64
+ return;
65
+ }
66
+ signal?.addEventListener('abort', onAbort, { once: true });
67
+ promise.then((value) => settle(() => resolve(value)), (error) => settle(() => reject(error)));
91
68
  });
92
69
  }
@@ -4,3 +4,14 @@
4
4
  * Full terms: see LICENSE.md.
5
5
  */
6
6
  export const issueMessages = (issues) => issues.map((issue) => issue.message);
7
+ /** Keep the segments of a schema issue path that can locate a YAML node. */
8
+ export const toIssuePath = (path) => path.filter((segment) => typeof segment === 'string' || typeof segment === 'number');
9
+ /**
10
+ * Turn schema issues into validation issues located under `basePath`, the
11
+ * path of the value the schema checked.
12
+ */
13
+ export const toValidationIssues = (code, schemaIssues, basePath = []) => schemaIssues.map((issue) => ({
14
+ code,
15
+ message: `${[...basePath, issue.path.join('.') || '<root>'].join('.')}: ${issue.message}`,
16
+ path: [...basePath, ...toIssuePath(issue.path)],
17
+ }));
@@ -14,59 +14,21 @@ const buildStepId = (path, label) => {
14
14
  const pathPart = path.length > 0 ? path.join('.') : 'root';
15
15
  return `${pathPart}:${label}`;
16
16
  };
17
- /** Convert workflow input field metadata to a zod schema. */
18
- const inputFieldToZod = (field) => {
19
- let schema;
20
- switch (field.type) {
21
- case 'string':
22
- schema = z.string();
23
- break;
24
- case 'number':
25
- schema = z.number();
26
- break;
27
- case 'integer':
28
- schema = z.int();
29
- break;
30
- case 'boolean':
31
- schema = z.boolean();
32
- break;
33
- case 'array':
34
- schema = z.array(field.items ? inputFieldToZod(field.items) : z.any());
35
- break;
36
- case 'object': {
37
- const properties = {};
38
- if (field.properties) {
39
- for (const [name, child] of Object.entries(field.properties)) {
40
- properties[name] = inputFieldToZod(child).optional();
41
- }
42
- }
43
- schema =
44
- Object.keys(properties).length > 0
45
- ? z.strictObject(properties).partial()
46
- : z.record(z.string(), z.any());
47
- break;
48
- }
49
- default:
50
- schema = z.any();
51
- }
52
- if (field.enum) {
53
- schema = schema.refine((value) => field.enum?.some((allowed) => allowed === value), {
54
- message: `Value must be one of: ${field.enum.join(', ')}`,
55
- });
56
- }
57
- return schema;
58
- };
59
- /** Assemble a parser for the workflow top-level input payload. */
60
- const buildInputParser = (schema) => {
61
- if (!schema || Object.keys(schema).length === 0) {
62
- return z.looseObject({});
63
- }
64
- const shape = {};
65
- for (const [name, field] of Object.entries(schema)) {
66
- shape[name] = inputFieldToZod(field).optional();
67
- }
68
- return z.strictObject(shape).partial();
69
- };
17
+ /**
18
+ * Build the parser of a workflow's input payload from its `inputs.schema`.
19
+ *
20
+ * This is the one conversion from that JSON Schema to a parser: the runner
21
+ * uses it when a run starts, and a host that checks an input before creating
22
+ * a run should use it too, so both accept and refuse the same payloads. The
23
+ * parser applies the schema's `default` values.
24
+ *
25
+ * @param schema The JSON Schema under `inputs.schema`, when one is declared.
26
+ * @returns A parser of the input payload; it accepts any object without a schema.
27
+ * @throws When the schema is not a JSON Schema zod can read.
28
+ */
29
+ export const buildWorkflowInputParser = (schema) => schema
30
+ ? z.fromJSONSchema(schema)
31
+ : z.looseObject({});
70
32
  /** Compile a raw mapping object into expression-aware value mappings. */
71
33
  const compileMapping = (values, options) => {
72
34
  if (!values) {
@@ -77,15 +39,6 @@ const compileMapping = (values, options) => {
77
39
  compileValue(value, options),
78
40
  ]));
79
41
  };
80
- /** Ensure every task references a provided action implementation. */
81
- const assertActionsBound = (tasks, actions) => {
82
- const missing = Object.values(tasks)
83
- .map((task) => task.action)
84
- .filter((actionName) => !Object.prototype.hasOwnProperty.call(actions, actionName));
85
- if (missing.length > 0) {
86
- throw new Error(`No action implementations provided for: ${missing.join(', ')}`);
87
- }
88
- };
89
42
  /** Parse settings, compile inputs, and bind actions for each task. */
90
43
  const compileTasks = (definition, options) => {
91
44
  const compiled = {};
@@ -98,7 +51,6 @@ const compileTasks = (definition, options) => {
98
51
  if (bindingValidation.issues.length > 0) {
99
52
  throw new Error(`Workflow bindings validation failed: ${issueMessages(bindingValidation.issues).join('; ')}`);
100
53
  }
101
- assertActionsBound(taskDefinitions, options.actions);
102
54
  for (const [taskName, task] of Object.entries(taskDefinitions)) {
103
55
  const action = options.actions[task.action];
104
56
  const settingsPayload = mergeSettings(defaultSettings, task.settings);
@@ -116,48 +68,51 @@ const compileTasks = (definition, options) => {
116
68
  return compiled;
117
69
  };
118
70
  /** Recursively compile flow steps into executable nodes with generated ids. */
119
- const compileFlowSteps = (steps, path = [], options) => steps.map((step, index) => {
120
- const stepPath = [...path, index];
71
+ const compileFlowSteps = (steps, path = [], options) => steps.map((step, index) => compileFlowStep(step, [...path, index], options));
72
+ const compileFlowStep = (step, stepPath, options) => {
121
73
  if ('do' in step) {
122
- const label = step.do;
123
74
  return {
124
75
  type: StepType.Task,
125
76
  id: buildStepId(stepPath, step.do),
126
- label,
77
+ label: step.do,
127
78
  taskName: step.do,
128
79
  };
129
80
  }
130
81
  if ('parallel' in step) {
131
- const label = step.parallel.description ?? 'parallel';
132
- return {
133
- type: StepType.Parallel,
134
- id: buildStepId(stepPath, 'parallel'),
135
- label,
136
- description: step.parallel.description,
137
- strategy: step.parallel.strategy ?? 'wait_all',
138
- steps: compileFlowSteps(step.parallel.steps, [...stepPath, 'parallel'], options),
139
- };
82
+ return compileParallelStep(step.parallel, stepPath, options);
140
83
  }
141
84
  if ('conditional' in step) {
142
- const label = step.conditional.description ?? 'conditional';
143
- const branches = step.conditional.when.map((branch, branchIdx) => ({
144
- id: buildStepId([...stepPath, 'branch', branchIdx], 'conditional'),
85
+ return compileConditionalStep(step.conditional, stepPath, options);
86
+ }
87
+ return compileLoopStep(step.loop, stepPath, options);
88
+ };
89
+ const compileParallelStep = (parallel, stepPath, options) => ({
90
+ type: StepType.Parallel,
91
+ id: buildStepId(stepPath, 'parallel'),
92
+ label: parallel.description ?? 'parallel',
93
+ description: parallel.description,
94
+ strategy: parallel.strategy ?? 'wait_all',
95
+ steps: compileFlowSteps(parallel.steps, [...stepPath, 'parallel'], options),
96
+ });
97
+ const compileConditionalStep = (conditional, stepPath, options) => ({
98
+ type: StepType.Conditional,
99
+ id: buildStepId(stepPath, 'conditional'),
100
+ label: conditional.description ?? 'conditional',
101
+ description: conditional.description,
102
+ branches: conditional.when.map((branch, branchIndex) => {
103
+ const branchPath = [...stepPath, 'branch', branchIndex];
104
+ return {
105
+ id: buildStepId(branchPath, 'conditional'),
145
106
  condition: 'condition' in branch
146
107
  ? compileValue(branch.condition, options)
147
108
  : undefined,
148
- steps: compileFlowSteps(branch.steps, [...stepPath, 'branch', branchIdx], options),
149
- }));
150
- return {
151
- type: StepType.Conditional,
152
- id: buildStepId(stepPath, 'conditional'),
153
- label,
154
- description: step.conditional.description,
155
- branches,
109
+ steps: compileFlowSteps(branch.steps, branchPath, options),
156
110
  };
157
- }
158
- const loop = step.loop;
111
+ }),
112
+ });
113
+ const compileLoopStep = (loop, stepPath, options) => {
159
114
  const label = loop.name ?? 'loop';
160
- const commonLoop = {
115
+ const common = {
161
116
  type: StepType.Loop,
162
117
  id: buildStepId(stepPath, label),
163
118
  label,
@@ -170,11 +125,11 @@ const compileFlowSteps = (steps, path = [], options) => steps.map((step, index)
170
125
  merge: compileValue(loop.accumulate.merge, options),
171
126
  }
172
127
  : undefined,
173
- steps: compileFlowSteps(loop.steps, [...stepPath, loop.name ?? 'loop'], options),
128
+ steps: compileFlowSteps(loop.steps, [...stepPath, label], options),
174
129
  };
175
130
  if (loop.type === 'for_each') {
176
131
  return {
177
- ...commonLoop,
132
+ ...common,
178
133
  loopType: 'for_each',
179
134
  forEach: {
180
135
  item: loop.for_each.item,
@@ -185,14 +140,14 @@ const compileFlowSteps = (steps, path = [], options) => steps.map((step, index)
185
140
  };
186
141
  }
187
142
  return {
188
- ...commonLoop,
143
+ ...common,
189
144
  loopType: 'while',
190
145
  while: compileValue(loop.while, options),
191
146
  };
192
- });
147
+ };
193
148
  /** Compile a workflow definition into structures consumable by the runtime. */
194
149
  export const compileWorkflow = (definition, options) => {
195
- const inputParser = buildInputParser(definition.inputs?.schema);
150
+ const inputParser = buildWorkflowInputParser(definition.inputs?.schema);
196
151
  const tasks = compileTasks(definition, options);
197
152
  const flow = compileFlowSteps(definition.flow, [], options);
198
153
  const outputMapping = compileMapping(definition.outputs, options) ?? {};
@@ -59,22 +59,33 @@ const collectSteps = (compiled, steps, parts) => {
59
59
  }
60
60
  break;
61
61
  case StepType.Loop:
62
- parts.push(step.loopType, step.name ?? '');
63
- parts.push(step.accumulate
64
- ? `${step.accumulate.as}=${stringify(step.accumulate.initial)}:${describeValue(step.accumulate.merge)}`
65
- : '');
66
- if (step.loopType === 'for_each') {
67
- parts.push(step.forEach.item, describeValue(step.forEach.in));
68
- parts.push(describeValue(step.until));
69
- }
70
- else {
71
- parts.push(describeValue(step.while));
72
- }
62
+ parts.push(...describeLoop(step));
73
63
  collectSteps(compiled, step.steps, parts);
74
64
  break;
75
65
  }
76
66
  }
77
67
  };
68
+ /**
69
+ * Describe what drives a loop: its kind, name, accumulator, and items or
70
+ * condition.
71
+ *
72
+ * @param step The loop step.
73
+ * @returns The description fragments, in a fixed order.
74
+ */
75
+ const describeLoop = (step) => [
76
+ step.loopType,
77
+ step.name ?? '',
78
+ step.accumulate
79
+ ? `${step.accumulate.as}=${stringify(step.accumulate.initial)}:${describeValue(step.accumulate.merge)}`
80
+ : '',
81
+ ...(step.loopType === 'for_each'
82
+ ? [
83
+ step.forEach.item,
84
+ describeValue(step.forEach.in),
85
+ describeValue(step.until),
86
+ ]
87
+ : [describeValue(step.while)]),
88
+ ];
78
89
  /**
79
90
  * Describe a compiled mapping in a key-stable order.
80
91
  *