@hexabot-ai/agentic 3.4.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +67 -15
  2. package/dist/cjs/action/abstract-action.js +13 -1
  3. package/dist/cjs/checkpoint.js +301 -0
  4. package/dist/cjs/context.js +11 -27
  5. package/dist/cjs/dsl.types.js +3 -0
  6. package/dist/cjs/errors.js +116 -9
  7. package/dist/cjs/index.js +15 -6
  8. package/dist/cjs/resume-payload.js +257 -0
  9. package/dist/cjs/runner-runtime-control.js +181 -306
  10. package/dist/cjs/step-executors/conditional-executor.js +27 -29
  11. package/dist/cjs/step-executors/loop-executor.js +53 -62
  12. package/dist/cjs/step-executors/parallel-executor.js +169 -102
  13. package/dist/cjs/step-executors/task-executor.js +180 -96
  14. package/dist/cjs/utils/clone.js +73 -0
  15. package/dist/cjs/workflow-fingerprint.js +138 -0
  16. package/dist/cjs/workflow-runner.js +220 -155
  17. package/dist/cjs/workflow.js +24 -12
  18. package/dist/esm/action/abstract-action.js +14 -2
  19. package/dist/esm/checkpoint.js +293 -0
  20. package/dist/esm/context.js +11 -27
  21. package/dist/esm/dsl.types.js +3 -0
  22. package/dist/esm/errors.js +105 -6
  23. package/dist/esm/index.js +3 -3
  24. package/dist/esm/resume-payload.js +250 -0
  25. package/dist/esm/runner-runtime-control.js +179 -303
  26. package/dist/esm/step-executors/conditional-executor.js +27 -29
  27. package/dist/esm/step-executors/loop-executor.js +53 -62
  28. package/dist/esm/step-executors/parallel-executor.js +165 -98
  29. package/dist/esm/step-executors/task-executor.js +181 -97
  30. package/dist/esm/utils/clone.js +67 -0
  31. package/dist/esm/workflow-fingerprint.js +134 -0
  32. package/dist/esm/workflow-runner.js +220 -155
  33. package/dist/esm/workflow.js +24 -12
  34. package/dist/types/action/abstract-action.d.ts.map +1 -1
  35. package/dist/types/action/action.types.d.ts +0 -14
  36. package/dist/types/action/action.types.d.ts.map +1 -1
  37. package/dist/types/checkpoint.d.ts +188 -0
  38. package/dist/types/checkpoint.d.ts.map +1 -0
  39. package/dist/types/context.d.ts +45 -11
  40. package/dist/types/context.d.ts.map +1 -1
  41. package/dist/types/dsl.types.d.ts.map +1 -1
  42. package/dist/types/errors.d.ts +77 -3
  43. package/dist/types/errors.d.ts.map +1 -1
  44. package/dist/types/index.d.ts +6 -7
  45. package/dist/types/index.d.ts.map +1 -1
  46. package/dist/types/resume-payload.d.ts +69 -0
  47. package/dist/types/resume-payload.d.ts.map +1 -0
  48. package/dist/types/runner-runtime-control.d.ts +63 -51
  49. package/dist/types/runner-runtime-control.d.ts.map +1 -1
  50. package/dist/types/step-executors/conditional-executor.d.ts +6 -3
  51. package/dist/types/step-executors/conditional-executor.d.ts.map +1 -1
  52. package/dist/types/step-executors/loop-executor.d.ts +6 -4
  53. package/dist/types/step-executors/loop-executor.d.ts.map +1 -1
  54. package/dist/types/step-executors/parallel-executor.d.ts +11 -3
  55. package/dist/types/step-executors/parallel-executor.d.ts.map +1 -1
  56. package/dist/types/step-executors/task-executor.d.ts +11 -4
  57. package/dist/types/step-executors/task-executor.d.ts.map +1 -1
  58. package/dist/types/step-executors/types.d.ts +21 -13
  59. package/dist/types/step-executors/types.d.ts.map +1 -1
  60. package/dist/types/utils/clone.d.ts +33 -0
  61. package/dist/types/utils/clone.d.ts.map +1 -0
  62. package/dist/types/workflow-event-emitter.d.ts +29 -5
  63. package/dist/types/workflow-event-emitter.d.ts.map +1 -1
  64. package/dist/types/workflow-fingerprint.d.ts +14 -0
  65. package/dist/types/workflow-fingerprint.d.ts.map +1 -0
  66. package/dist/types/workflow-runner.d.ts +83 -41
  67. package/dist/types/workflow-runner.d.ts.map +1 -1
  68. package/dist/types/workflow-types.d.ts +25 -54
  69. package/dist/types/workflow-types.d.ts.map +1 -1
  70. package/dist/types/workflow.d.ts +24 -9
  71. package/dist/types/workflow.d.ts.map +1 -1
  72. package/examples/defs-bindings-agent/bindings.ts +1 -1
  73. package/examples/defs-bindings-agent/workflow.ts +3 -2
  74. package/examples/full/actions/await-user-input.ts +3 -2
  75. package/examples/full/actions/call-llm.ts +18 -18
  76. package/examples/full/actions/create-ticket.ts +1 -2
  77. package/examples/full/actions/decision-router.ts +6 -2
  78. package/examples/full/actions/get-calendar-events.ts +1 -2
  79. package/examples/full/actions/get-user-profile.ts +1 -2
  80. package/examples/full/actions/query-memory.ts +1 -2
  81. package/examples/full/actions/search-web.ts +1 -2
  82. package/examples/full/actions/send-email.ts +3 -2
  83. package/examples/full/workflow.ts +3 -2
  84. package/examples/loop/actions/await-reply.ts +2 -7
  85. package/examples/loop/workflow.ts +4 -2
  86. package/examples/suspend-resume/actions/wait-for-user.ts +11 -9
  87. package/examples/suspend-resume/workflow.ts +51 -11
  88. package/package.json +3 -3
  89. package/src/__tests__/checkpoint.test.ts +2568 -0
  90. package/src/__tests__/resume-payload.test.ts +245 -0
  91. package/src/__tests__/runner-runtime-control.test.ts +265 -0
  92. package/src/__tests__/workflow-fingerprint.test.ts +165 -0
  93. package/src/__tests__/workflow-runner.test.ts +167 -144
  94. package/src/__tests__/workflow.test.ts +97 -6
  95. package/src/action/abstract-action.ts +21 -2
  96. package/src/action/action.types.ts +0 -12
  97. package/src/checkpoint.ts +561 -0
  98. package/src/context.ts +51 -41
  99. package/src/dsl.types.ts +3 -0
  100. package/src/errors.ts +161 -8
  101. package/src/index.ts +33 -14
  102. package/src/resume-payload.ts +326 -0
  103. package/src/runner-runtime-control.ts +222 -456
  104. package/src/step-executors/conditional-executor.test.ts +77 -46
  105. package/src/step-executors/conditional-executor.ts +47 -40
  106. package/src/step-executors/loop-executor.test.ts +106 -92
  107. package/src/step-executors/loop-executor.ts +84 -101
  108. package/src/step-executors/parallel-executor.test.ts +300 -89
  109. package/src/step-executors/parallel-executor.ts +243 -125
  110. package/src/step-executors/task-executor.test.ts +321 -51
  111. package/src/step-executors/task-executor.ts +232 -145
  112. package/src/step-executors/types.ts +23 -22
  113. package/src/utils/clone.ts +75 -0
  114. package/src/workflow-event-emitter.ts +32 -6
  115. package/src/workflow-fingerprint.ts +159 -0
  116. package/src/workflow-runner.ts +325 -209
  117. package/src/workflow-types.ts +25 -56
  118. package/src/workflow.ts +41 -34
  119. package/dist/cjs/step-executors/suspension-continuation.js +0 -27
  120. package/dist/cjs/suspension-rebuilder.js +0 -265
  121. package/dist/cjs/utils/deferred.js +0 -17
  122. package/dist/esm/step-executors/suspension-continuation.js +0 -24
  123. package/dist/esm/suspension-rebuilder.js +0 -260
  124. package/dist/esm/utils/deferred.js +0 -14
  125. package/dist/types/step-executors/suspension-continuation.d.ts +0 -10
  126. package/dist/types/step-executors/suspension-continuation.d.ts.map +0 -1
  127. package/dist/types/suspension-rebuilder.d.ts +0 -67
  128. package/dist/types/suspension-rebuilder.d.ts.map +0 -1
  129. package/dist/types/utils/deferred.d.ts +0 -7
  130. package/dist/types/utils/deferred.d.ts.map +0 -1
  131. package/src/__tests__/suspension-rebuilder.test.ts +0 -404
  132. package/src/step-executors/suspension-continuation.ts +0 -31
  133. package/src/suspension-rebuilder.ts +0 -446
  134. package/src/utils/deferred.ts +0 -23
@@ -0,0 +1,245 @@
1
+ /*
2
+ * Hexabot — Fair Core License (FCL-1.0-ALv2)
3
+ * Copyright (c) 2025 Hexastack.
4
+ * Full terms: see LICENSE.md.
5
+ */
6
+
7
+ import { z, type ZodType } from 'zod';
8
+
9
+ import type { WaitInfo } from '../checkpoint';
10
+ import { WorkflowResumeRejectedError } from '../errors';
11
+ import {
12
+ checkResumePayload,
13
+ describeResumePayload,
14
+ findNonJsonTypes,
15
+ isPayloadOptional,
16
+ } from '../resume-payload';
17
+ import { StepType } from '../workflow-event-emitter';
18
+
19
+ const waitFor = (accepts?: ZodType | Record<string, unknown>): WaitInfo => ({
20
+ waitId: '0:ask@index:1',
21
+ step: { id: '0:ask', name: 'ask', type: StepType.Task },
22
+ suspendKey: 'index:1',
23
+ accepts:
24
+ accepts instanceof z.ZodType ? describeResumePayload(accepts) : accepts,
25
+ });
26
+ const precheck = (schema: ZodType, value: unknown) =>
27
+ checkResumePayload(waitFor(schema), value).ok;
28
+
29
+ describe('describeResumePayload', () => {
30
+ it('describes the input side of the schema as JSON Schema', () => {
31
+ expect(
32
+ describeResumePayload(
33
+ z.object({
34
+ reply: z.string().min(1).describe('The answer'),
35
+ count: z.number().default(1),
36
+ }),
37
+ ),
38
+ ).toEqual({
39
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
40
+ type: 'object',
41
+ properties: {
42
+ reply: { type: 'string', minLength: 1, description: 'The answer' },
43
+ count: { type: 'number' },
44
+ },
45
+ required: ['reply'],
46
+ });
47
+ });
48
+
49
+ // Each value is accepted by the Zod schema but would be refused by the
50
+ // JSON Schema zod generates for it; the relaxed description must accept it.
51
+ it.each<[string, ZodType, unknown]>([
52
+ ['coerced primitive', z.object({ n: z.coerce.number() }), { n: '5' }],
53
+ ['preprocess', z.preprocess((v) => String(v), z.string()), 5],
54
+ ['catch', z.string().catch('fallback'), 5],
55
+ ['custom', z.custom<string>((v) => typeof v === 'string'), 'x'],
56
+ ['trim before max', z.string().trim().max(3), ' ab '],
57
+ ['overwrite before max', z.number().overwrite(Math.round).max(5), 5.4],
58
+ ['regex flags', z.string().regex(/^abc$/i), 'ABC'],
59
+ ['custom email pattern', z.email({ pattern: /^.+@.+$/ }), 'a@b'],
60
+ [
61
+ 'partial record of enum keys',
62
+ z.partialRecord(z.enum(['a', 'b']), z.number()),
63
+ { a: 1 },
64
+ ],
65
+ [
66
+ 'coerce inside optional, arrays and unions',
67
+ z.object({
68
+ a: z.coerce.number().optional(),
69
+ b: z.array(z.coerce.number()),
70
+ c: z.union([z.coerce.number(), z.boolean()]),
71
+ }),
72
+ { a: '1', b: ['2'], c: '3' },
73
+ ],
74
+ ])('never refuses what the schema accepts: %s', (_name, schema, value) => {
75
+ expect(schema.safeParse(value).success).toBe(true);
76
+ expect(precheck(schema, value)).toBe(true);
77
+ });
78
+
79
+ it.each<[string, ZodType, unknown]>([
80
+ ['wrong type', z.object({ reply: z.string() }), { reply: 1 }],
81
+ ['missing key', z.object({ reply: z.string() }), {}],
82
+ ['not an object', z.object({ reply: z.string() }), null],
83
+ [
84
+ 'strict object extras',
85
+ z.strictObject({ a: z.string() }),
86
+ { a: 'x', b: 1 },
87
+ ],
88
+ ['enum', z.enum(['yes', 'no']), 'maybe'],
89
+ ['integer', z.int(), 1.5],
90
+ ['length', z.string().max(2), 'abc'],
91
+ [
92
+ 'discriminated union',
93
+ z.discriminatedUnion('kind', [
94
+ z.object({ kind: z.literal('a'), x: z.string() }),
95
+ z.object({ kind: z.literal('b') }),
96
+ ]),
97
+ { kind: 'a' },
98
+ ],
99
+ [
100
+ 'recursive schema',
101
+ (() => {
102
+ const node = z.object({
103
+ value: z.number(),
104
+ get next() {
105
+ return node.optional();
106
+ },
107
+ });
108
+
109
+ return node;
110
+ })(),
111
+ { value: 1, next: { value: 'two' } },
112
+ ],
113
+ ])('still refuses what JSON Schema can check: %s', (_name, schema, value) => {
114
+ expect(schema.safeParse(value).success).toBe(false);
115
+ expect(precheck(schema, value)).toBe(false);
116
+ });
117
+ });
118
+
119
+ describe('isPayloadOptional', () => {
120
+ it.each<[string, ZodType, boolean]>([
121
+ ['optional', z.object({ note: z.string() }).optional(), true],
122
+ ['default', z.object({ note: z.string() }).default({ note: '' }), true],
123
+ ['nullish', z.string().nullish(), true],
124
+ ['undefined', z.undefined(), true],
125
+ ['void', z.void(), true],
126
+ ['object', z.object({ note: z.string() }), false],
127
+ ['nullable', z.string().nullable(), false],
128
+ ])(
129
+ 'reports whether %s accepts a missing payload',
130
+ (_name, schema, optional) => {
131
+ expect(isPayloadOptional(schema)).toBe(optional);
132
+ expect(schema.safeParse(undefined).success).toBe(optional);
133
+ },
134
+ );
135
+ });
136
+
137
+ describe('findNonJsonTypes', () => {
138
+ it.each<[string, ZodType, string[]]>([
139
+ ['date', z.date(), ['(root) (date)']],
140
+ [
141
+ 'nested types JSON cannot carry',
142
+ z.object({
143
+ at: z.date().optional(),
144
+ items: z.array(z.object({ id: z.bigint() })),
145
+ tags: z.set(z.string()),
146
+ pair: z.tuple([z.string(), z.map(z.string(), z.number())]),
147
+ }),
148
+ ['at (date)', 'items[].id (bigint)', 'tags (set)', 'pair[1] (map)'],
149
+ ],
150
+ ['a dead union option', z.union([z.date(), z.string()]), ['(root) (date)']],
151
+ ['plain JSON', z.object({ a: z.string(), b: z.array(z.number()) }), []],
152
+ ['coerced', z.object({ at: z.coerce.date(), n: z.coerce.bigint() }), []],
153
+ ['preprocessed', z.preprocess((v) => new Date(String(v)), z.date()), []],
154
+ ['caught', z.date().catch(new Date(0)), []],
155
+ [
156
+ 'codec from JSON',
157
+ z.codec(z.iso.datetime(), z.date(), {
158
+ decode: (value) => new Date(value),
159
+ encode: (value) => value.toISOString(),
160
+ }),
161
+ [],
162
+ ],
163
+ ['transformed output', z.string().transform((v) => new Date(v)), []],
164
+ [
165
+ 'recursive schema',
166
+ (() => {
167
+ const node = z.object({
168
+ value: z.number(),
169
+ get next() {
170
+ return node.optional();
171
+ },
172
+ });
173
+
174
+ return node;
175
+ })(),
176
+ [],
177
+ ],
178
+ ])('%s', (_name, schema, found) => {
179
+ expect(findNonJsonTypes(schema)).toEqual(found);
180
+ });
181
+ });
182
+
183
+ describe('checkResumePayload', () => {
184
+ it('normalizes the payload the way the checkpoint stores it', () => {
185
+ const wait = waitFor();
186
+
187
+ expect(checkResumePayload(wait, undefined)).toEqual({
188
+ ok: true,
189
+ value: undefined,
190
+ });
191
+ expect(
192
+ checkResumePayload(wait, { at: new Date(0), gone: undefined }),
193
+ ).toEqual({ ok: true, value: { at: '1970-01-01T00:00:00.000Z' } });
194
+ });
195
+
196
+ it('accepts a missing payload only when the schema lets it be left out', () => {
197
+ const schema = z.object({ note: z.string() });
198
+ const optional = {
199
+ ...waitFor(schema.optional()),
200
+ payloadOptional: true,
201
+ };
202
+
203
+ expect(checkResumePayload(optional, undefined).ok).toBe(true);
204
+ expect(checkResumePayload(optional, { note: 1 }).ok).toBe(false);
205
+ // `null` is a payload, which the optional schema still refuses.
206
+ expect(checkResumePayload(optional, null).ok).toBe(false);
207
+ expect(checkResumePayload(waitFor(schema), undefined).ok).toBe(false);
208
+ });
209
+
210
+ it('refuses a payload JSON cannot store', () => {
211
+ const result = checkResumePayload(waitFor(), { n: BigInt(1) });
212
+
213
+ expect(result.ok).toBe(false);
214
+ if (!result.ok) {
215
+ expect(result.error).toBeInstanceOf(WorkflowResumeRejectedError);
216
+ expect(result.error.message).toMatch(
217
+ /Resume payload for wait "0:ask@index:1" cannot be stored as JSON/,
218
+ );
219
+ }
220
+ });
221
+
222
+ it('checks the normalized payload and reports the issues', () => {
223
+ const wait = waitFor(z.object({ at: z.string(), reply: z.string() }));
224
+
225
+ expect(checkResumePayload(wait, { at: new Date(0), reply: 'ok' }).ok).toBe(
226
+ true,
227
+ );
228
+
229
+ const result = checkResumePayload(wait, { at: 'now', reply: 1 });
230
+ expect(result.ok).toBe(false);
231
+ if (!result.ok) {
232
+ expect(result.error.message).toMatch(
233
+ /^Resume payload for wait "0:ask@index:1" was rejected: reply: /,
234
+ );
235
+ expect(result.error.issues).toEqual([expect.stringMatching(/^reply: /)]);
236
+ }
237
+ });
238
+
239
+ it('accepts anything when the wait has no usable schema', () => {
240
+ expect(checkResumePayload(waitFor(), 'anything').ok).toBe(true);
241
+ expect(
242
+ checkResumePayload(waitFor({ type: 'not-a-json-type' }), 'anything').ok,
243
+ ).toBe(true);
244
+ });
245
+ });
@@ -0,0 +1,265 @@
1
+ /*
2
+ * Hexabot — Fair Core License (FCL-1.0-ALv2)
3
+ * Copyright (c) 2025 Hexastack.
4
+ * Full terms: see LICENSE.md.
5
+ */
6
+
7
+ import { z, type ZodType } from 'zod';
8
+
9
+ import {
10
+ NonDeterministicWorkflowError,
11
+ WorkflowResumeRejectedError,
12
+ } from '../errors';
13
+ import { RunnerRuntimeControl } from '../runner-runtime-control';
14
+ import { StepType, type StepInfo } from '../workflow-event-emitter';
15
+
16
+ const step: StepInfo = { id: '0:ask', name: 'ask', type: StepType.Task };
17
+
18
+ describe('RunnerRuntimeControl', () => {
19
+ it('refuses to suspend outside a running step', () => {
20
+ const runtime = new RunnerRuntimeControl();
21
+
22
+ expect(() => runtime.suspend()).toThrow(
23
+ 'workflow.suspend() can only be called while a workflow step is running.',
24
+ );
25
+ expect(() => runtime.waitForSuspension()).toThrow(
26
+ 'No workflow step is running in this scope.',
27
+ );
28
+ expect(runtime.hasRecordedResult()).toBe(false);
29
+ });
30
+
31
+ it('queues a suspension requested before the executor waits for it', async () => {
32
+ const runtime = new RunnerRuntimeControl();
33
+
34
+ runtime.beginStep(step);
35
+ void runtime.suspend({ reason: 'first', data: { n: 1 } });
36
+
37
+ await expect(runtime.waitForSuspension()).resolves.toEqual({
38
+ suspendKey: 'index:1',
39
+ reason: 'first',
40
+ data: { n: 1 },
41
+ awaitResults: {},
42
+ });
43
+ });
44
+
45
+ it('resolves recorded suspensions immediately and reports them ahead of time', async () => {
46
+ const runtime = new RunnerRuntimeControl();
47
+
48
+ runtime.beginStep(step, {
49
+ seed: {
50
+ awaitResults: { 'index:1': 'a', 'key:confirm': 'b' },
51
+ expected: { suspendKey: 'key:confirm' },
52
+ },
53
+ });
54
+
55
+ expect(runtime.hasRecordedResult()).toBe(true);
56
+ await expect(runtime.suspend()).resolves.toBe('a');
57
+ expect(runtime.hasRecordedResult('confirm')).toBe(true);
58
+ await expect(runtime.suspend({ key: 'confirm' })).resolves.toBe('b');
59
+ expect(runtime.hasRecordedResult()).toBe(false);
60
+ expect(() => runtime.endStep({ completed: true })).not.toThrow();
61
+ });
62
+
63
+ it.each<[string, ZodType | undefined]>([
64
+ ['without accepts', undefined],
65
+ ['with z.any()', z.any()],
66
+ ['with a nested z.unknown()', z.object({ meta: z.unknown() })],
67
+ ])(
68
+ 'records a result again unchanged by a body that changed it, %s',
69
+ async (_label, accepts) => {
70
+ const runtime = new RunnerRuntimeControl();
71
+
72
+ runtime.beginStep(step, {
73
+ seed: {
74
+ awaitResults: { 'index:1': { meta: { n: 1 } } },
75
+ expected: { suspendKey: 'index:1' },
76
+ },
77
+ });
78
+
79
+ const answer = (await runtime.suspend({ accepts })) as {
80
+ meta: { n: number };
81
+ };
82
+ answer.meta.n += 1;
83
+ void runtime.suspend();
84
+
85
+ await expect(runtime.waitForSuspension()).resolves.toMatchObject({
86
+ suspendKey: 'index:2',
87
+ awaitResults: { 'index:1': { meta: { n: 1 } } },
88
+ });
89
+ },
90
+ );
91
+
92
+ it('rejects a user key reused within one attempt, but not across attempts', async () => {
93
+ const runtime = new RunnerRuntimeControl();
94
+
95
+ runtime.beginStep(step);
96
+ const rewind = runtime.markSuspendCursor();
97
+ void runtime.suspend({ key: 'confirm' });
98
+ expect(() => runtime.suspend({ key: 'confirm' })).toThrow(
99
+ /key "confirm" is used more than once in step "0:ask"/,
100
+ );
101
+
102
+ rewind();
103
+ expect(() => runtime.suspend({ key: 'confirm' })).not.toThrow();
104
+ });
105
+
106
+ it('rewinds the cursor to where an action run started, at any depth', async () => {
107
+ const runtime = new RunnerRuntimeControl();
108
+ const keys: string[] = [];
109
+ const next = async () => {
110
+ keys.push((await runtime.waitForSuspension()).suspendKey);
111
+ };
112
+
113
+ runtime.beginStep(step);
114
+ const rewindStep = runtime.markSuspendCursor();
115
+ void runtime.suspend();
116
+ await next();
117
+
118
+ // An action run nested in the body starts after the body's first suspend,
119
+ const rewindNested = runtime.markSuspendCursor();
120
+ void runtime.suspend();
121
+ await next();
122
+ // so its retry reproduces its own keys and leaves the body's alone.
123
+ rewindNested();
124
+ void runtime.suspend();
125
+ await next();
126
+
127
+ rewindStep();
128
+ void runtime.suspend();
129
+ await next();
130
+
131
+ expect(keys).toEqual(['index:1', 'index:2', 'index:2', 'index:1']);
132
+ });
133
+
134
+ it('ignores a rewind taken in a step that has ended', async () => {
135
+ const runtime = new RunnerRuntimeControl();
136
+
137
+ runtime.beginStep(step);
138
+ const stale = runtime.markSuspendCursor();
139
+ runtime.endStep();
140
+ runtime.beginStep(step);
141
+ void runtime.suspend({ key: 'confirm' });
142
+
143
+ stale();
144
+ expect(() => runtime.suspend({ key: 'confirm' })).toThrow(
145
+ /used more than once/,
146
+ );
147
+ // Outside a running step there is nothing to rewind.
148
+ runtime.endStep();
149
+ expect(() => runtime.markSuspendCursor()()).not.toThrow();
150
+ });
151
+
152
+ describe('determinism', () => {
153
+ const seed = {
154
+ awaitResults: { 'index:1': 'a' },
155
+ expected: { suspendKey: 'index:2', reason: 'second' },
156
+ };
157
+
158
+ it('fails a resumed body that completes without reaching its suspension', () => {
159
+ const runtime = new RunnerRuntimeControl();
160
+
161
+ runtime.beginStep(step, { seed });
162
+
163
+ expect(() => runtime.endStep({ completed: true })).toThrow(
164
+ NonDeterministicWorkflowError,
165
+ );
166
+ });
167
+
168
+ it('does not check a body that stopped without completing', () => {
169
+ const runtime = new RunnerRuntimeControl();
170
+
171
+ runtime.beginStep(step, { seed });
172
+
173
+ expect(() => runtime.endStep()).not.toThrow();
174
+ });
175
+
176
+ it('fails a resumed body that reaches an unrecorded suspension first', () => {
177
+ const runtime = new RunnerRuntimeControl();
178
+
179
+ runtime.beginStep(step, { seed });
180
+
181
+ expect(() => runtime.suspend({ key: 'new' })).toThrow(
182
+ /reached unexpected suspend "key:new" before expected "index:2"/,
183
+ );
184
+ });
185
+
186
+ it('fails a resumed body that reaches its suspension with another reason', async () => {
187
+ const runtime = new RunnerRuntimeControl();
188
+
189
+ runtime.beginStep(step, { seed });
190
+ await expect(runtime.suspend()).resolves.toBe('a');
191
+
192
+ expect(() => runtime.suspend({ reason: 'other' })).toThrow(
193
+ /with reason "other", expected reason "second"/,
194
+ );
195
+ });
196
+ });
197
+
198
+ describe('accepts', () => {
199
+ const accepts = z.object({ n: z.coerce.number() });
200
+
201
+ it('stores what the suspension accepts on its request', async () => {
202
+ const runtime = new RunnerRuntimeControl();
203
+
204
+ runtime.beginStep(step);
205
+ void runtime.suspend({ accepts: z.object({ reply: z.string() }) });
206
+
207
+ await expect(runtime.waitForSuspension()).resolves.toMatchObject({
208
+ suspendKey: 'index:1',
209
+ accepts: {
210
+ type: 'object',
211
+ properties: { reply: { type: 'string' } },
212
+ required: ['reply'],
213
+ },
214
+ });
215
+ });
216
+
217
+ it('resolves a recorded result parsed through the schema', async () => {
218
+ const runtime = new RunnerRuntimeControl();
219
+
220
+ runtime.beginStep(step, {
221
+ seed: {
222
+ awaitResults: { 'index:1': { n: '5' } },
223
+ expected: { suspendKey: 'index:1' },
224
+ },
225
+ });
226
+
227
+ expect(runtime.hasReachedResolvedSuspension()).toBe(false);
228
+ await expect(runtime.suspend({ accepts })).resolves.toEqual({ n: 5 });
229
+ expect(runtime.hasReachedResolvedSuspension()).toBe(true);
230
+ });
231
+
232
+ it('refuses the resolved payload when it fails the schema', async () => {
233
+ const runtime = new RunnerRuntimeControl();
234
+
235
+ runtime.beginStep(step, {
236
+ seed: {
237
+ awaitResults: { 'index:1': { n: 'five' } },
238
+ expected: { suspendKey: 'index:1' },
239
+ },
240
+ });
241
+
242
+ const refused = runtime.suspend({ accepts });
243
+ await expect(refused).rejects.toThrow(WorkflowResumeRejectedError);
244
+ await expect(refused).rejects.toThrow(
245
+ /^Resume payload for step "0:ask" was rejected: n: /,
246
+ );
247
+ expect(runtime.hasReachedResolvedSuspension()).toBe(true);
248
+ });
249
+
250
+ it('fails when a result accepted by an earlier pass no longer matches', async () => {
251
+ const runtime = new RunnerRuntimeControl();
252
+
253
+ runtime.beginStep(step, {
254
+ seed: {
255
+ awaitResults: { 'index:1': { n: 'five' }, 'index:2': 'b' },
256
+ expected: { suspendKey: 'index:2' },
257
+ },
258
+ });
259
+
260
+ await expect(runtime.suspend({ accepts })).rejects.toThrow(
261
+ NonDeterministicWorkflowError,
262
+ );
263
+ });
264
+ });
265
+ });
@@ -0,0 +1,165 @@
1
+ /*
2
+ * Hexabot — Fair Core License (FCL-1.0-ALv2)
3
+ * Copyright (c) 2025 Hexastack.
4
+ * Full terms: see LICENSE.md.
5
+ */
6
+
7
+ import { z } from 'zod';
8
+
9
+ import { defineAction } from '../action/action';
10
+ import { BaseWorkflowContext } from '../context';
11
+ import type { Settings, WorkflowDefinition } from '../dsl.types';
12
+ import { compileWorkflow } from '../workflow-compiler';
13
+ import type { EventEmitterLike } from '../workflow-event-emitter';
14
+ import { fingerprintWorkflow } from '../workflow-fingerprint';
15
+
16
+ import { createTaskDefs } from './test-helpers';
17
+
18
+ class TestContext extends BaseWorkflowContext {
19
+ public eventEmitter: EventEmitterLike = { emit: jest.fn(), on: jest.fn() };
20
+ }
21
+
22
+ const noop = (name: string) =>
23
+ defineAction<unknown, unknown, TestContext, Settings>({
24
+ name,
25
+ inputSchema: z.any(),
26
+ outputSchema: z.any(),
27
+ execute: async () => undefined,
28
+ });
29
+ const actions = { first: noop('first'), second: noop('second') };
30
+ const fingerprint = (definition: WorkflowDefinition) =>
31
+ fingerprintWorkflow(compileWorkflow(definition, { actions }));
32
+ const createDefinition = (): WorkflowDefinition => ({
33
+ defs: createTaskDefs({
34
+ ask: { action: 'first', inputs: { label: 'x', count: '=1' } },
35
+ note: { action: 'first' },
36
+ }),
37
+ flow: [
38
+ {
39
+ conditional: {
40
+ when: [
41
+ { condition: '=$input.ok', steps: [{ do: 'note' }] },
42
+ { else: true, steps: [{ do: 'ask' }] },
43
+ ],
44
+ },
45
+ },
46
+ {
47
+ loop: {
48
+ type: 'for_each',
49
+ name: 'items',
50
+ for_each: { item: 'item', in: '=["a", "b"]' },
51
+ until: '=false',
52
+ accumulate: {
53
+ as: 'acc',
54
+ initial: [],
55
+ merge: '=$append($accumulator, [1])',
56
+ },
57
+ steps: [{ do: 'ask' }],
58
+ },
59
+ },
60
+ {
61
+ loop: {
62
+ type: 'while',
63
+ name: 'retry',
64
+ while: '=$count($accumulator) < 1',
65
+ accumulate: {
66
+ as: 'n',
67
+ initial: [],
68
+ merge: '=$append($accumulator, 1)',
69
+ },
70
+ steps: [{ do: 'note' }],
71
+ },
72
+ },
73
+ {
74
+ parallel: {
75
+ strategy: 'wait_all',
76
+ steps: [{ do: 'note' }, { do: 'ask' }],
77
+ },
78
+ },
79
+ ],
80
+ outputs: { acc: '=$output.items.acc' },
81
+ });
82
+
83
+ type Mutation = (definition: any) => void;
84
+
85
+ describe('fingerprintWorkflow', () => {
86
+ it('is stable across compilations of the same definition', () => {
87
+ expect(fingerprint(createDefinition())).toBe(
88
+ fingerprint(createDefinition()),
89
+ );
90
+ });
91
+
92
+ it.each<[string, Mutation]>([
93
+ [
94
+ 'task settings',
95
+ (definition) => {
96
+ definition.defs.ask.settings = { timeout_ms: 5 };
97
+ },
98
+ ],
99
+ [
100
+ 'the key order of task inputs',
101
+ (definition) => {
102
+ definition.defs.ask.inputs = { count: '=1', label: 'x' };
103
+ },
104
+ ],
105
+ ])('ignores %s', (_label, mutate) => {
106
+ const next = createDefinition();
107
+ mutate(next);
108
+
109
+ expect(fingerprint(next)).toBe(fingerprint(createDefinition()));
110
+ });
111
+
112
+ it.each<[string, Mutation]>([
113
+ [
114
+ 'a renamed task',
115
+ (definition) => {
116
+ definition.defs.prompt = definition.defs.ask;
117
+ delete definition.defs.ask;
118
+ definition.flow[1].loop.steps = [{ do: 'prompt' }];
119
+ },
120
+ ],
121
+ [
122
+ 'an inserted step',
123
+ (definition) => definition.flow.unshift({ do: 'note' }),
124
+ ],
125
+ ['task inputs', (definition) => (definition.defs.ask.inputs.label = 'y')],
126
+ ['a task action', (definition) => (definition.defs.note.action = 'second')],
127
+ [
128
+ 'a branch condition',
129
+ (definition) => (definition.flow[0].conditional.when[0].condition = '=1'),
130
+ ],
131
+ [
132
+ 'the for_each items',
133
+ (definition) => (definition.flow[1].loop.for_each.in = '=["a"]'),
134
+ ],
135
+ [
136
+ 'an until expression',
137
+ (definition) => (definition.flow[1].loop.until = '=true'),
138
+ ],
139
+ [
140
+ 'an accumulator initial value',
141
+ (definition) => (definition.flow[1].loop.accumulate.initial = [0]),
142
+ ],
143
+ [
144
+ 'an accumulator merge',
145
+ (definition) =>
146
+ (definition.flow[1].loop.accumulate.merge = '=$accumulator'),
147
+ ],
148
+ ['a loop name', (definition) => (definition.flow[1].loop.name = 'entries')],
149
+ [
150
+ 'a while guard',
151
+ (definition) =>
152
+ (definition.flow[2].loop.while = '=$count($accumulator) < 2'),
153
+ ],
154
+ [
155
+ 'a parallel strategy',
156
+ (definition) => (definition.flow[3].parallel.strategy = 'wait_any'),
157
+ ],
158
+ ['an output mapping', (definition) => (definition.outputs.acc = '=1')],
159
+ ])('changes with %s', (_label, mutate) => {
160
+ const next = createDefinition();
161
+ mutate(next);
162
+
163
+ expect(fingerprint(next)).not.toBe(fingerprint(createDefinition()));
164
+ });
165
+ });